From 6bdeacc44271cf05a1a2cdf423b76990cebeb273 Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Thu, 19 Nov 2026 20:02:02 +0100 Subject: [PATCH 1/9] feat(sdk-dart): show an incognito session Conversation folds reasoning_delta, tool_started, tool_updated and tool_ran into Turn.steps and Turn.isDone; TurnMessage builds the channel's message shape from them; flutter_demo shows an incognito chat from the socket. Co-Authored-By: Claude Opus 5.5 --- .../flutter_demo/lib/agent_chat.dart | 142 ++++++-- .../flutter_demo/lib/chat_view.dart | 33 +- .../voice_agents/flutter_demo/lib/main.dart | 18 +- .../flutter_demo/test/agent_chat_test.dart | 97 +++++ .../lib/src/core/agent_event.dart | 1 + .../lib/src/core/conversation.dart | 334 +++++++++++++++++- .../dart/stream_agents/lib/src/core/core.dart | 1 + .../lib/src/core/turn_message.dart | 189 ++++++++++ .../test/core/conversation_test.dart | 263 ++++++++++++++ .../stream_agents/test/core/session_test.dart | 58 +++ .../test/core/turn_message_test.dart | 136 +++++++ 11 files changed, 1211 insertions(+), 61 deletions(-) create mode 100644 sdks/dart/stream_agents/lib/src/core/turn_message.dart create mode 100644 sdks/dart/stream_agents/test/core/turn_message_test.dart diff --git a/examples/voice_agents/flutter_demo/lib/agent_chat.dart b/examples/voice_agents/flutter_demo/lib/agent_chat.dart index fc0db911b4..6169c74517 100644 --- a/examples/voice_agents/flutter_demo/lib/agent_chat.dart +++ b/examples/voice_agents/flutter_demo/lib/agent_chat.dart @@ -11,14 +11,23 @@ import 'package:stream_agents/stream_agents.dart'; /// question in the channel and answers it there: the reply's text, and its steps (each round /// of reasoning and each tool call) as attachments. The session's socket is what runs this /// phone's tools and carries the person's answers to the ones that ask first. +/// +/// An incognito session keeps no channel, so it is shown from its socket instead: the +/// session's `turnMessages`, which are the conversation in the channel's shape. class AgentChat with AIConversationTransport { - AgentChat._(this.session, stream.Channel channel) : _channel = channel; + AgentChat._(this.session, stream.Channel? channel) + : _channel = channel, + _kept = channel != null; - /// Opens the session's channel and starts following it. + /// Opens the session's channel and starts following it, or follows the session's socket + /// alone when it keeps no channel, as an incognito one does. /// /// The session is closed if its channel cannot be opened, so it does not run on with /// nobody to show it. static Future open(AgentSession session) async { + if (session.session.conversationId.isEmpty) { + return AgentChat.unkept(session); + } stream.Channel? channel; try { channel = await session.chat(); @@ -45,6 +54,10 @@ class AgentChat with AIConversationTransport { .._hasOlderMessages = hasOlderMessages .._follow(channel); + /// Follows [session], which keeps no channel, from its socket alone. + factory AgentChat.unkept(AgentSession session) => + AgentChat._(session, null).._follow(null); + static const _pageSize = 30; /// What a reply that failed says, in place of the provider's raw error. @@ -53,6 +66,9 @@ class AgentChat with AIConversationTransport { final AgentSession session; stream.Channel? _channel; + /// Whether the conversation is kept in a channel, rather than shown from the socket alone. + final bool _kept; + /// Why the session's socket stopped, or null: tools and approvals stop until a new /// conversation is opened. ValueListenable get sessionFailure => _sessionFailure; @@ -70,9 +86,30 @@ class AgentChat with AIConversationTransport { var _unanswered = false; var _closed = false; + var _unkeptShown = const []; + /// The messages as Stream's AI components show them. - List get listMessages => - listed(_channel?.state?.messages ?? const [], reasoning, shown: _shown); + List get listMessages => _kept + ? listed(_channel?.state?.messages ?? const [], reasoning, shown: _shown) + : _unkeptShown = listedTurns(session.turnMessages, shown: _unkeptShown); + + /// The [messages] of a session that keeps no channel as Stream's AI components show them, + /// without the replies that ended with nothing written, reusing those in [shown] that did + /// not change. + static List listedTurns( + List messages, { + List shown = const [], + }) { + final known = {for (final message in shown) message.id: message}; + return [ + for (final message in messages) + if (!message.isUnwrittenReply) + if (known[message.id] case final same? when same._turn == message) + same + else + AgentMessage.unkept(message), + ]; + } /// The [messages] as Stream's AI components show them, oldest first, without those deleted /// and without the replies that ended with nothing written, reusing those in [shown]. @@ -96,21 +133,27 @@ class AgentChat with AIConversationTransport { _tell(_unanswered ? _failedActivity : activityOf(session.state)); } - void _follow(stream.Channel channel) { + void _follow(stream.Channel? channel) { + if (channel != null) { + _subscriptions + ..add(channel.state!.messagesStream.listen((_) => _publish())) + // The client's events rather than the channel's list: the list can fold several live + // updates into one, and each update carries its own window of the reply's thinking. + ..add( + channel.client.on(stream.EventType.messageUpdated).listen((event) { + final message = event.message; + if (event.cid == channel.cid && + message != null && + _readReasoning(message)) { + _publish(); + } + }), + ); + } else { + // A call waiting for the person asks on its step of the reply. + _subscriptions.add(session.approvals.stream.listen((_) => _publish())); + } _subscriptions - ..add(channel.state!.messagesStream.listen((_) => _publish())) - // The client's events rather than the channel's list: the list can fold several live - // updates into one, and each update carries its own window of the reply's thinking. - ..add( - channel.client.on(stream.EventType.messageUpdated).listen((event) { - final message = event.message; - if (event.cid == channel.cid && - message != null && - _readReasoning(message)) { - _publish(); - } - }), - ) ..add(session.conversation.stream.listen((_) => _sessionChanged())) ..add(session.connection.stream.listen((_) => _sessionChanged())) // A reply that fails ends with nothing written in the channel: only the socket says so. @@ -130,7 +173,7 @@ class AgentChat with AIConversationTransport { void _publish() { final feed = _feed; - if (feed == null || _channel == null) return; + if (feed == null || _closed) return; feed ..updateMessages(listMessages) ..updateHasOlderMessages(_hasOlderMessages); @@ -139,6 +182,8 @@ class AgentChat with AIConversationTransport { void _sessionChanged() { _sessionFailure.value = session.failure?.toString(); if (!_unanswered) _tell(activityOf(session.state)); + // With no channel, the socket is where the conversation is. + if (!_kept) _publish(); } void _report(AgentEvent event) { @@ -261,32 +306,59 @@ extension AgentReply on stream.Message { ]); } -/// A message of the conversation as Stream's AI components show it. -class AgentMessage with AIMessage { - AgentMessage(this.message, this._reasoning) : parts = message.steps; +/// Whether this is a reply the agent ended without writing anything: no text and no steps. +extension UnwrittenTurnReply on TurnMessage { + bool get isUnwrittenReply => + isAgentReply && !isGenerating && text.isEmpty && steps.isEmpty; +} - final stream.Message message; - final LiveReasoning _reasoning; +/// A message of the conversation as Stream's AI components show it: one of the channel's, or, +/// for a session that keeps no channel, one built from its socket. +class AgentMessage with AIMessage { + AgentMessage(stream.Message this.message, LiveReasoning this._reasoning) + : _turn = null, + id = message.id, + role = message.isAgentReply + ? AIMessageRole.assistant + : AIMessageRole.user, + text = message.text ?? '', + isGenerating = message.isGenerating, + parts = message.steps; + + /// A message of a session that keeps no channel, an incognito one, from its socket. + AgentMessage.unkept(TurnMessage this._turn) + : message = null, + _reasoning = null, + id = _turn.id, + role = _turn.isAgentReply ? AIMessageRole.assistant : AIMessageRole.user, + text = _turn.text, + isGenerating = _turn.isGenerating, + parts = AIMessagePart.parseAll(_turn.steps); + + /// The channel's message, or null for one built from the socket. + final stream.Message? message; + final TurnMessage? _turn; + final LiveReasoning? _reasoning; @override - final List parts; + final String id; @override - String get id => message.id; + final AIMessageRole role; @override - AIMessageRole get role => - message.isAgentReply ? AIMessageRole.assistant : AIMessageRole.user; + final String text; @override - String get text => message.text ?? ''; + final bool isGenerating; @override - bool get isGenerating => message.isGenerating; + final List parts; @override late final List attachments = [ - for (final attachment in message.attachments) + for (final attachment + in message?.attachments ?? const []) if (attachment.type == 'image' && attachment.imageUrl != null) AIMessageAttachment.image( Uri.parse(attachment.imageUrl!), @@ -302,8 +374,10 @@ class AgentMessage with AIMessage { ]; /// A step keeps only the opening of its thinking; the whole of it came with the live - /// updates, while the reply was being written. + /// updates, while the reply was being written. One built from the socket holds all of it. @override - String? reasoningText(AIReasoningPart step) => - _reasoning[(message: message.id, step: step.id)]; + String? reasoningText(AIReasoningPart step) => switch (_turn) { + final turn? => turn.reasoning[step.id], + null => _reasoning?[(message: id, step: step.id)], + }; } diff --git a/examples/voice_agents/flutter_demo/lib/chat_view.dart b/examples/voice_agents/flutter_demo/lib/chat_view.dart index 838ce41cce..f16b63a02e 100644 --- a/examples/voice_agents/flutter_demo/lib/chat_view.dart +++ b/examples/voice_agents/flutter_demo/lib/chat_view.dart @@ -17,8 +17,13 @@ import 'notice.dart'; /// same knowledge, the same skills and the same tools running on this phone. What is new in /// writing is that the reply shows its working, with Stream's AI components: the agent's /// reasoning as it thinks, each tool call as it runs, and a question when a tool asks first. +/// +/// An [incognito] conversation is kept nowhere: it has no channel, is never listed, and is +/// shown from the session's socket. class ChatView extends StatefulWidget { - const ChatView({super.key}); + const ChatView({super.key, this.incognito = false}); + + final bool incognito; @override State createState() => _ChatViewState(); @@ -46,7 +51,13 @@ class _ChatViewState extends State { // The call keeps the agent's own model, which answers sooner. final session = await Demo.agents .agent(Demo.agentName) - .chat(SessionOptions(llm: 'xai/grok-4.7', tools: Demo.tools)); + .chat( + SessionOptions( + llm: 'xai/grok-4.7', + tools: Demo.tools, + incognito: widget.incognito ? true : null, + ), + ); final chat = await AgentChat.open(session); if (!mounted) { await chat.close(); @@ -198,11 +209,19 @@ class _AgentConversationState extends State<_AgentConversation> { _conversation.status.isAnswering && activity?.text != null ? AITypingIndicatorView(text: activity!.text!) : null, - emptyContent: Notice( - icon: context.streamIcons.archive, - title: 'Ask about an order', - message: 'Orders A-1042 and A-1043 are on this account.', - ), + emptyContent: widget.chat.session.session.incognito + ? Notice( + icon: context.streamIcons.lock, + title: 'Incognito chat', + message: + 'This conversation is not kept. Ask about order A-1042 or A-1043.', + ) + : Notice( + icon: context.streamIcons.archive, + title: 'Ask about an order', + message: + 'Orders A-1042 and A-1043 are on this account.', + ), ), ), if (isWelcoming) diff --git a/examples/voice_agents/flutter_demo/lib/main.dart b/examples/voice_agents/flutter_demo/lib/main.dart index aba1032a4d..f0d0802ea0 100644 --- a/examples/voice_agents/flutter_demo/lib/main.dart +++ b/examples/voice_agents/flutter_demo/lib/main.dart @@ -51,6 +51,9 @@ class _HomePageState extends State { var _tab = 0; var _voiceStyle = VoiceStyle.orb; + // Whether the Chat tab holds an incognito conversation. Switching starts a new one. + var _incognito = false; + void _pickStyle() => showStreamSheet( context: context, isDismissible: true, @@ -89,14 +92,25 @@ class _HomePageState extends State { onPressed: _pickStyle, icon: Icon(context.streamIcons.slidersFill), ) - : null, + : StreamButton.icon( + style: .secondary, + type: _incognito ? .solid : .ghost, + tooltip: _incognito ? 'Leave incognito' : 'New incognito chat', + onPressed: () => setState(() => _incognito = !_incognito), + icon: Icon( + _incognito + ? context.streamIcons.lock + : context.streamIcons.unlock, + ), + ), ), // Both tabs stay alive, so a call carries on while the Chat tab is shown. body: IndexedStack( index: _tab, sizing: StackFit.expand, children: [ - const ChatView(), + // A new conversation each time incognito is switched. + ChatView(key: ValueKey(_incognito), incognito: _incognito), VoiceView(style: _voiceStyle), ], ), diff --git a/examples/voice_agents/flutter_demo/test/agent_chat_test.dart b/examples/voice_agents/flutter_demo/test/agent_chat_test.dart index 3f01542bd7..9c5904e905 100644 --- a/examples/voice_agents/flutter_demo/test/agent_chat_test.dart +++ b/examples/voice_agents/flutter_demo/test/agent_chat_test.dart @@ -315,6 +315,103 @@ void main() { ); }); + test( + 'shows a session with no channel from its socket, as Stream reads a kept reply', + () async { + // Its own router, whose one socket is this session's: the one set up holds the other. + final router = await _Router.start(); + addTearDown(router.close); + final agents = StreamAgents( + url: router.url, + customerId: 'acme', + userId: 'ada', + ); + addTearDown(agents.close); + final session = await agents.attach( + 's1', + tools: [ + AgentTool( + name: 'issue_refund', + description: 'Refund an order.', + approval: const ToolApproval( + title: 'Refund this order?', + allowTitle: 'Refund', + ), + run: (_) async => 'Refunded', + ), + ], + ); + final chat = closing(AgentChat.unkept(session)); + final conversation = conversationOf(chat); + final socket = await router.socket; + + conversation.send("I'd like a refund for order A-1042"); + await _until(() => router.asked == 1); + socket + ..send('{"type":"responding","turn_id":"t1"}') + ..send( + '{"type":"reasoning_delta","turn_id":"t1","text":"They were charged twice."}', + ) + ..send( + '{"type":"tool_started","tool_call_id":"c1","tool":"issue_refund",' + '"turn_id":"t1","started_at":"2026-11-19T09:00:00Z"}', + ) + ..send( + '{"type":"tool_call","id":"c1","name":"issue_refund","arguments":"{}",' + '"request_id":"m1","turn_id":"t1"}', + ); + await _until( + () => + conversation + .messages + .lastOrNull + ?.parts + .lastOrNull + ?.toolCall + ?.status == + AIToolCallStatus.awaitingApproval, + ); + + expect( + [for (final m in conversation.messages) m.role], + [AIMessageRole.user, AIMessageRole.assistant], + ); + final reply = conversation.messages.last; + expect(reply.isGenerating, isTrue); + final [thinking, refund] = reply.parts; + expect(thinking.reasoning?.id, 'r1'); + expect( + reply.reasoningText(thinking.reasoning!), + 'They were charged twice.', + ); + // Asked of the person using the app, which is who Stream's approver answers as. + expect(refund.toolCall?.targetUserId, 'ada'); + expect(refund.toolCall?.approval?.title, 'Refund this order?'); + + session.decide('c1', allowed: true); + socket + ..send( + '{"type":"tool_ran","tool_call_id":"c1","turn_id":"t1",' + '"tool":"issue_refund","error":""}', + ) + ..send( + '{"pending_work":true,"type":"responded","turn_id":"t1",' + '"text":"","time_to_first_token_ms":90}', + ) + ..send('{"type":"responding","turn_id":"t2"}') + ..send( + '{"pending_work":false,"type":"responded","turn_id":"t2",' + '"text":"Refunded.","time_to_first_token_ms":90}', + ); + await _until(() => conversation.messages.last.text == 'Refunded.'); + + final done = conversation.messages.last; + expect(done.isGenerating, isFalse); + expect(done.parts.last.toolCall?.status, AIToolCallStatus.completed); + expect(conversation.messages, hasLength(2)); + }, + ); + test('close disposes the watched channel', () async { final channel = channelOf([_question('q0')]); final chat = AgentChat.following(session, channel); diff --git a/sdks/dart/stream_agents/lib/src/core/agent_event.dart b/sdks/dart/stream_agents/lib/src/core/agent_event.dart index c22e7ac29b..c5094970c6 100644 --- a/sdks/dart/stream_agents/lib/src/core/agent_event.dart +++ b/sdks/dart/stream_agents/lib/src/core/agent_event.dart @@ -37,6 +37,7 @@ enum AgentEventKind { decision('decision'), responding('responding'), responseDelta('response_delta'), + reasoningDelta('reasoning_delta'), uiDelta('ui_delta'), uiCompleted('ui_completed'), responded('responded'), diff --git a/sdks/dart/stream_agents/lib/src/core/conversation.dart b/sdks/dart/stream_agents/lib/src/core/conversation.dart index ef43b81b11..18e8618153 100644 --- a/sdks/dart/stream_agents/lib/src/core/conversation.dart +++ b/sdks/dart/stream_agents/lib/src/core/conversation.dart @@ -93,6 +93,8 @@ final class Turn { required this.text, required this.at, this.ui, + this.steps = const [], + this.isDone = false, }); /// The router's turn id for an agent turn, and one of our own for a participant's. Stable @@ -103,9 +105,70 @@ final class Turn { final DateTime at; final TurnUI? ui; - Turn _withText(String text) => Turn(id: id, speaker: speaker, text: text, at: at, ui: ui); + /// What the agent did on its way to the turn's text, in order: each round of the model's + /// thinking on a written reply, and each tool it called. Empty on a participant's turn. + final List steps; - Turn _withUI(TurnUI ui) => Turn(id: id, speaker: speaker, text: text, at: at, ui: ui); + /// Whether the agent is done with the turn: it answered with no tools or work left to come, + /// or it was interrupted. A turn whose tools are still running is not. Never set on a + /// participant's turn. + final bool isDone; + + Turn _withText(String text) => _copy(text: text); + + Turn _withUI(TurnUI? ui) => + Turn(id: id, speaker: speaker, text: text, at: at, ui: ui, steps: steps, isDone: isDone); + + Turn _copy({String? text, List? steps, bool? isDone}) => Turn( + id: id, + speaker: speaker, + text: text ?? this.text, + at: at, + ui: ui, + steps: steps ?? this.steps, + isDone: isDone ?? this.isDone, + ); + + /// This turn with [delta] added to the round of thinking under way, or to a new one when the + /// model did something else since: every round is numbered from `r1`, as a kept reply's steps + /// are. + Turn _think(String delta, DateTime began) { + if (steps.lastOrNull case final ReasoningStep round when round.isStreaming) { + return _copy(steps: [...steps.take(steps.length - 1), round._withText(round.text + delta)]); + } + final rounds = steps.whereType().length; + return _copy( + steps: [ + ...steps, + ReasoningStep(id: 'r${rounds + 1}', isStreaming: true, text: delta, at: began), + ], + ); + } + + /// This turn with its round of thinking under way completed, or itself when none is. + Turn _settled(DateTime now) { + if (steps.lastOrNull case final ReasoningStep round when round.isStreaming) { + return _copy(steps: [...steps.take(steps.length - 1), round._completed(now)]); + } + return this; + } + + /// This turn with [call] begun, or itself when it already shows that call. A round of + /// thinking's id is ours, `r1` and on, so a call the provider gave the same id is another step. + Turn _called(ToolCallStep call) => steps.any((step) => step is ToolCallStep && step.id == call.id) + ? this + : _copy(steps: [...steps, call]); + + /// This turn with its running call [id] changed as [change] says, or itself when it has none. + Turn _changedCall(String id, ToolCallStep Function(ToolCallStep) change) { + final index = steps.indexWhere( + (step) => step is ToolCallStep && step.id == id && step.status == ToolCallStatus.running, + ); + if (index == -1) return this; + final changed = [...steps]; + changed[index] = change(steps[index] as ToolCallStep); + return _copy(steps: changed); + } @override bool operator ==(Object other) => @@ -114,15 +177,145 @@ final class Turn { other.speaker == speaker && other.text == text && other.at == at && - other.ui == ui; + other.ui == ui && + other.isDone == isDone && + _same(other.steps, steps); @override - int get hashCode => Object.hash(id, speaker, text, at, ui); + int get hashCode => Object.hash(id, speaker, text, at, ui, Object.hashAll(steps), isDone); @override String toString() => 'Turn($id, ${speaker.isAgent ? 'agent' : 'participant'}: $text)'; } +/// One thing the agent did in a turn: a round of the model's thinking, or a call of a tool. +sealed class TurnStep { + const TurnStep(); + + /// `r1`, `r2` and on for a round of thinking; the call's id for a tool call. + String get id; + + /// When it began. + DateTime get at; +} + +/// A round of the model's thinking on a written reply, which is read, never spoken. +final class ReasoningStep extends TurnStep { + const ReasoningStep({ + required this.id, + required this.isStreaming, + required this.text, + required this.at, + this.duration, + }); + + /// `r1`, `r2` and on, in the order the turn thought. + @override + final String id; + + /// Whether the model is still thinking: until it writes, calls a tool or finishes. + final bool isStreaming; + + /// The thinking so far. + final String text; + + /// When the model began on it: when it was asked, or took the reply up again after writing, + /// as a kept reply's step is timed. Not when its first words arrived, which a model that + /// sends its thinking in one burst sends only at the end. + @override + final DateTime at; + + /// How long the model thought, once it is done. + final Duration? duration; + + ReasoningStep _withText(String text) => + ReasoningStep(id: id, isStreaming: isStreaming, text: text, at: at, duration: duration); + + ReasoningStep _completed(DateTime now) => + ReasoningStep(id: id, isStreaming: false, text: text, at: at, duration: now.difference(at)); + + @override + bool operator ==(Object other) => + other is ReasoningStep && + other.id == id && + other.isStreaming == isStreaming && + other.text == text && + other.at == at && + other.duration == duration; + + @override + int get hashCode => Object.hash(id, isStreaming, text, at, duration); + + @override + String toString() => 'ReasoningStep($id, ${isStreaming ? 'streaming' : 'completed'})'; +} + +/// A call of a tool: what was called and how it went, not what it was given or gave. +final class ToolCallStep extends TurnStep { + const ToolCallStep({ + required this.id, + required this.name, + required this.status, + this.summary = '', + required this.at, + this.duration, + }); + + /// The call's id, which [AgentSession.decide] answers it by while it waits in `approvals`. + @override + final String id; + + /// The tool. + final String name; + final ToolCallStatus status; + + /// What whoever runs it last said about how it is going (`tool_updated`), or the empty string. + final String summary; + + @override + final DateTime at; + + /// How long it ran, once it is no longer running. + final Duration? duration; + + ToolCallStep _with({ToolCallStatus? status, String? summary, Duration? duration}) => ToolCallStep( + id: id, + name: name, + status: status ?? this.status, + summary: summary ?? this.summary, + at: at, + duration: duration ?? this.duration, + ); + + @override + bool operator ==(Object other) => + other is ToolCallStep && + other.id == id && + other.name == name && + other.status == status && + other.summary == summary && + other.at == at && + other.duration == duration; + + @override + int get hashCode => Object.hash(id, name, status, summary, at, duration); + + @override + String toString() => 'ToolCallStep($id, $name, ${status.wire})'; +} + +/// How a tool call went. +enum ToolCallStatus { + running('running'), + completed('completed'), + failed('failed'); + + const ToolCallStatus(this.wire); + + /// Its name in a kept reply's `ai_tool_call` step. + final String wire; +} + /// What the agent is doing. sealed class ConversationState { const ConversationState(); @@ -179,9 +372,10 @@ final class Conversation { /// A conversation built here has no UI being written; derive from an existing one /// ([withoutTurn], [withState]) to keep it. const Conversation({this.turns = const [], this.state = ConversationState.idle, this.failure}) - : _uiWritten = const {}; + : _uiWritten = const {}, + _resumedAt = const {}; - const Conversation._(this.turns, this.state, this.failure, this._uiWritten); + const Conversation._(this.turns, this.state, this.failure, this._uiWritten, this._resumedAt); /// Oldest first. The agent's turn in flight is the last entry and grows as deltas arrive. final List turns; @@ -194,6 +388,10 @@ final class Conversation { /// What each turn's UI block has written so far, unmerged, until the turn's UI is settled. final Map _uiWritten; + /// When the model last took each agent turn in flight up again, by turn id: when it was asked, + /// or went on after writing. A round of thinking is timed from it. + final Map _resumedAt; + /// Whatever the caller typed, shown before the router has confirmed hearing it. Conversation said(String text, {DateTime? at}) => _with( turns: [ @@ -261,15 +459,52 @@ final class Conversation { state: ConversationState.responding, failure: null, uiWritten: _uiWritten.containsKey(event.turnId) ? _without(event.turnId) : null, + resumedAt: {..._resumedAt, event.turnId: now}, ); case AgentEventKind.responseDelta: - return _write( + // Writing ends the round of thinking under way, and the next one is timed from here. + final went = event.text.isEmpty ? this : _wentOn(event.turnId, now); + return went + ._write(event.turnId, now, (text) => text + event.text, event.text) + .withState(ConversationState.responding); + + case AgentEventKind.reasoningDelta: + if (event.text.isEmpty) { + return this; + } + final began = _resumedAt[event.turnId] ?? now; + return _amend(event.turnId, (turn) => turn._think(event.text, began), startingAt: now); + + case AgentEventKind.toolStarted: + final call = ToolCallStep( + id: _text(event['tool_call_id']), + name: _text(event['tool']), + status: ToolCallStatus.running, + at: now, + ); + return _amend(event.turnId, (turn) => turn._settled(now)._called(call), startingAt: now); + + case AgentEventKind.toolUpdated: + // Words to say as written are a line of the reply, not how the call is going. + if (event['verbatim'] == true || event.text.isEmpty) { + return this; + } + return _amend( event.turnId, - now, - (text) => text + event.text, - event.text, - ).withState(ConversationState.responding); + (turn) => + turn._changedCall(_text(event['id']), (call) => call._with(summary: event.text)), + ); + + case AgentEventKind.toolRan: + final status = event.errorText.isEmpty ? ToolCallStatus.completed : ToolCallStatus.failed; + return _amend( + event.turnId, + (turn) => turn._changedCall( + _text(event['tool_call_id']), + (call) => call._with(status: status, duration: now.difference(call.at)), + ), + ); case AgentEventKind.uiDelta: final delta = _text(event['delta']); @@ -283,7 +518,11 @@ final class Conversation { mode: _nonEmptyOr(_text(event['mode']), 'replace'), raw: '${_uiWritten[event.turnId]?.raw ?? ''}$delta', ); - final written = _with(uiWritten: {..._uiWritten, event.turnId: pending}); + // Writing UI ends the round of thinking under way, as writing text does. + final written = _wentOn( + event.turnId, + now, + )._with(uiWritten: {..._uiWritten, event.turnId: pending}); // Only the line still being written grew, so no statement finished: nothing shown changes. final updated = format == 'openui' && !delta.contains('\n') ? written @@ -317,7 +556,10 @@ final class Conversation { final written = event.text.isEmpty ? settled : settled._write(event.turnId, now, (_) => event.text, event.text); - return written.withState(ConversationState.idle); + // A reply whose tools or work are still to come is carried on by a turn of its own. + return written + ._ended(event.turnId, now, done: event['pending_work'] != true) + .withState(ConversationState.idle); case AgentEventKind.delegated: return _with(state: Working([..._working, _text(event['skill'])])); @@ -331,10 +573,14 @@ final class Conversation { return _with(state: left.isEmpty ? ConversationState.responding : Working(left)); case AgentEventKind.interrupted: - return _settleUI(event.turnId, now).withState(ConversationState.idle); + return _settleUI( + event.turnId, + now, + )._ended(event.turnId, now, done: true).withState(ConversationState.idle); case AgentEventKind.error: - return _with(failure: event.errorText); + final refused = event['code'] == 'prompt_injection' ? _refused() : this; + return refused._with(failure: event.errorText); case AgentEventKind.left: return withState(ConversationState.ended); @@ -370,6 +616,53 @@ final class Conversation { return _with(turns: changed); } + /// Applies [change] to the agent turn [turnId]. A turn this never saw begin is started at + /// [startingAt] when the event begins something, and left alone when it is null. + Conversation _amend(String turnId, Turn Function(Turn) change, {DateTime? startingAt}) { + final index = turns.lastIndexWhere((turn) => turn.id == turnId && turn.speaker.isAgent); + if (index == -1) { + if (startingAt == null) return this; + return _with( + turns: [ + ...turns, + change(Turn(id: turnId, speaker: Speaker.agent, text: '', at: startingAt)), + ], + ); + } + final changed = change(turns[index]); + if (identical(changed, turns[index])) return this; + return _with(turns: [...turns]..[index] = changed); + } + + /// The model went on with the agent turn [turnId] at [now], writing text or UI: its round of + /// thinking under way is complete, and the next one is timed from here. + Conversation _wentOn(String turnId, DateTime now) => + _amend(turnId, (turn) => turn._settled(now))._with(resumedAt: {..._resumedAt, turnId: now}); + + /// Nothing more of the agent turn [turnId] comes at [now]: its round of thinking is complete, + /// and the turn is [done] unless a turn of its own carries the reply on. + Conversation _ended(String turnId, DateTime now, {required bool done}) { + final settled = _amend(turnId, (turn) { + final ended = turn._settled(now); + return done && !ended.isDone ? ended._copy(isDone: true) : ended; + }); + return settled._resumedAt.containsKey(turnId) + ? settled._with(resumedAt: {...settled._resumedAt}..remove(turnId)) + : settled; + } + + /// The prompt injection screen refused the reply being written. What it streamed before the + /// verdict is not the answer, so its text and UI go, as they do from the kept conversation; + /// its thinking and tool calls stay. + Conversation _refused() { + final index = turns.lastIndexWhere((turn) => turn.speaker.isAgent); + if (index == -1 || turns[index].isDone) return this; + final turn = turns[index]; + final cleared = _uiWritten.containsKey(turn.id) ? _with(uiWritten: _without(turn.id)) : this; + if (turn.text.isEmpty && turn.ui == null) return cleared; + return cleared._with(turns: [...turns]..[index] = turn._withText('')._withUI(null)); + } + /// The turn ended with no `ui_completed`, as an interrupted reply does: the router dropped its /// UI block with the turn. What was written shows, but for a statement it ended in the middle /// of, and the UI is complete, since nothing more of it will come. @@ -453,22 +746,26 @@ final class Conversation { ConversationState? state, Object? failure = _keep, Map? uiWritten, + Map? resumedAt, }) => Conversation._( turns ?? this.turns, state ?? this.state, identical(failure, _keep) ? this.failure : failure as String?, uiWritten ?? _uiWritten, + resumedAt ?? _resumedAt, ); /// The UI written so far counts, or a delta that shows nothing new would be lost to a holder - /// that skips equal values, and the next one would land on stale text. + /// that skips equal values, and the next one would land on stale text. So does when each turn + /// was taken up again, which times the next round of thinking. @override bool operator ==(Object other) => other is Conversation && other.state == state && other.failure == failure && _same(other.turns, turns) && - _sameWritten(other._uiWritten, _uiWritten); + _sameEntries(other._uiWritten, _uiWritten) && + _sameEntries(other._resumedAt, _resumedAt); @override int get hashCode => Object.hash( @@ -476,6 +773,7 @@ final class Conversation { state, failure, Object.hashAllUnordered(_uiWritten.values), + Object.hashAllUnordered(_resumedAt.values), ); } @@ -626,7 +924,7 @@ String? _optionalText(Object? value) => value is String && value.isNotEmpty ? va String _nonEmptyOr(String value, String fallback) => value.isNotEmpty ? value : fallback; -bool _sameWritten(Map a, Map b) { +bool _sameEntries(Map a, Map b) { if (identical(a, b)) { return true; } diff --git a/sdks/dart/stream_agents/lib/src/core/core.dart b/sdks/dart/stream_agents/lib/src/core/core.dart index f070477a63..da79f9c2de 100644 --- a/sdks/dart/stream_agents/lib/src/core/core.dart +++ b/sdks/dart/stream_agents/lib/src/core/core.dart @@ -19,3 +19,4 @@ export 'sessions.dart' show Responses, Sessions; export 'socket.dart'; export 'stream_agents.dart'; export 'tools.dart'; +export 'turn_message.dart'; diff --git a/sdks/dart/stream_agents/lib/src/core/turn_message.dart b/sdks/dart/stream_agents/lib/src/core/turn_message.dart new file mode 100644 index 0000000000..3faedefd6d --- /dev/null +++ b/sdks/dart/stream_agents/lib/src/core/turn_message.dart @@ -0,0 +1,189 @@ +import 'dart:convert'; + +import 'agent_session.dart'; +import 'conversation.dart'; + +/// A message of a conversation kept in no channel, an incognito session's, in the shape a kept +/// one has in Stream Chat, so an app shows both alike with Stream's AI components. +/// +/// Each of the person's turns is a message, and the agent's turns between two of them are one +/// reply, as the router writes a reply whose tools it waited on: their text, the latest UI, and +/// each round of thinking and each tool call as a step, generating until the agent is done with +/// it. A call waiting in the session's `approvals` asks its user on its step, as a kept reply's +/// does. +final class TurnMessage { + TurnMessage({ + required this.id, + required this.isAgentReply, + required this.text, + required this.at, + this.isGenerating = false, + this.steps = const [], + this.reasoning = const {}, + this.customData = const {}, + }); + + /// Its first turn's id. + final String id; + + /// Whether the agent wrote it, rather than the person. + final bool isAgentReply; + final String text; + + /// When its first turn began. + final DateTime at; + + /// Whether the agent is still writing it. + final bool isGenerating; + + /// The reply's steps, in order, as a kept reply's attachments hold them: an `ai_reasoning` + /// for each round of thinking, numbered from `r1` across the reply, and an `ai_tool_call` for + /// each call. Stream Chat's `AIMessagePart.parseAll` reads them as they are. + final List<({String type, Map payload})> steps; + + /// The whole of each round of thinking, by its step's id. + final Map reasoning; + + /// The reply's custom data as a kept one holds it: its UI under `ai_ui`, which + /// `AIUIDocument.fromCustomData` reads, or nothing. + final Map customData; + + /// The messages of [conversation], oldest first. + /// + /// [approvals] are the calls waiting for the person, each of which asks on its step. [userId] + /// is the person the session is with, whom a waiting call asks: the agents' own user, which an + /// `AIToolApprover` matches against `target_user_id`, not the session's `userId`, which is the + /// name the agent joined the call as. The latest reply is written only while [isConnected], + /// whether the session's socket still carries the conversation. + static List messages( + Conversation conversation, { + List approvals = const [], + required String userId, + required bool isConnected, + }) { + final groups = >[]; + for (final turn in conversation.turns) { + if (turn.speaker.isAgent && (groups.lastOrNull?.first.speaker.isAgent ?? false)) { + groups.last.add(turn); + } else { + groups.add([turn]); + } + } + return [ + for (final (index, turns) in groups.indexed) + // Only the latest reply can still be written: one the person asked over is as it was + // left. + _of( + turns, + isGenerating: index == groups.length - 1 && isConnected && !turns.last.isDone, + approvals: approvals, + userId: userId, + ), + ]; + } + + static TurnMessage _of( + List turns, { + required bool isGenerating, + required List approvals, + required String userId, + }) { + final first = turns.first; + if (!first.speaker.isAgent) { + return TurnMessage(id: first.id, isAgentReply: false, text: first.text, at: first.at); + } + final steps = <({String type, Map payload})>[]; + final reasoning = {}; + for (final step in turns.expand((turn) => turn.steps)) { + switch (step) { + case ReasoningStep(): + // Numbered across the reply, which a tool's result carries on in a turn of its own. + final id = 'r${reasoning.length + 1}'; + reasoning[id] = step.text; + steps.add(( + type: 'ai_reasoning', + payload: { + 'id': id, + 'status': step.isStreaming ? 'streaming' : 'completed', + 'duration_ms': ?step.duration?.inMilliseconds, + }, + )); + case ToolCallStep(): + final waiting = step.status == ToolCallStatus.running + ? approvals.where((request) => request.id == step.id).firstOrNull + : null; + steps.add(( + type: 'ai_tool_call', + payload: { + 'id': step.id, + 'name': step.name, + 'status': waiting != null ? 'awaiting_approval' : step.status.wire, + if (step.summary.isNotEmpty) 'summary': step.summary, + 'duration_ms': ?step.duration?.inMilliseconds, + if (waiting != null) ...{'target_user_id': userId, 'approval': _approval(waiting)}, + }, + )); + } + } + final ui = turns.lastWhere((turn) => turn.ui != null, orElse: () => first).ui; + return TurnMessage( + id: first.id, + isAgentReply: true, + text: turns.map((turn) => turn.text).where((text) => text.isNotEmpty).join('\n\n'), + at: first.at, + isGenerating: isGenerating, + steps: steps, + reasoning: reasoning, + customData: {if (ui != null) 'ai_ui': ui.toWireJson()}, + ); + } + + /// The question a waiting call asks, as its step in Stream Chat holds it. + static Map _approval(ToolApprovalRequest waiting) => { + 'title': waiting.approval.title, + if (waiting.approval.message case final message? when message.isNotEmpty) 'message': message, + if (waiting.reason.isNotEmpty) 'reason': waiting.reason, + if (waiting.approval.allowTitle case final title? when title.isNotEmpty) 'allow_title': title, + if (waiting.approval.declineTitle case final title? when title.isNotEmpty) + 'decline_title': title, + }; + + /// What it shows besides its id, text and time, compared as one value: the steps' maps are + /// written in a fixed order, so a step that did not change encodes the same. + late final String _shown = jsonEncode([ + for (final step in steps) [step.type, step.payload], + reasoning, + customData, + ]); + + /// Equal when it shows the same, so a view can keep a message that did not change. + @override + bool operator ==(Object other) => + other is TurnMessage && + other.id == id && + other.isAgentReply == isAgentReply && + other.text == text && + other.at == at && + other.isGenerating == isGenerating && + other._shown == _shown; + + @override + int get hashCode => Object.hash(id, isAgentReply, text, at, isGenerating, _shown); + + @override + String toString() => 'TurnMessage($id, ${isAgentReply ? 'agent' : 'person'}: $text)'; +} + +/// The conversation as messages, for a session kept in no channel. +extension TurnMessages on AgentSession { + /// The conversation as messages, for a session kept in no channel, an incognito one, to show + /// with Stream's AI components; a kept session's messages are its channel's (`chat()`). Build + /// it again whenever [AgentSession.conversation], [AgentSession.approvals] or + /// [AgentSession.connection] changes. A waiting call asks the agents' own user. + List get turnMessages => TurnMessage.messages( + conversation.value, + approvals: approvals.value, + userId: backend.userId, + isConnected: isConnected, + ); +} diff --git a/sdks/dart/stream_agents/test/core/conversation_test.dart b/sdks/dart/stream_agents/test/core/conversation_test.dart index 4a5e18847b..7451ab0730 100644 --- a/sdks/dart/stream_agents/test/core/conversation_test.dart +++ b/sdks/dart/stream_agents/test/core/conversation_test.dart @@ -392,6 +392,269 @@ void main() { expect(identical(after, before), isTrue); }); + + group('steps', () { + final start = DateTime.utc(2026, 11, 19, 9); + DateTime ms(int milliseconds) => start.add(Duration(milliseconds: milliseconds)); + + Conversation play(List<(int, String)> frames, {Conversation from = const Conversation()}) { + var conversation = from; + for (final (at, json) in frames) { + conversation = conversation.apply(frame(json), at: ms(at)); + } + return conversation; + } + + test('a written reply keeps its thinking and tool calls in the order they happened', () { + final conversation = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (1000, '{"type":"reasoning_delta","turn_id":"t1","text":"They want "}'), + (1100, '{"type":"reasoning_delta","turn_id":"t1","text":"Lisbon\'s weather."}'), + ( + 2000, + '{"type":"tool_started","tool_call_id":"call_1","tool":"weather","turn_id":"t1",' + '"started_at":"2026-11-19T09:00:02Z"}', + ), + ( + 2100, + '{"type":"tool_updated","id":"call_1","turn_id":"t1","tool":"weather",' + '"text":"Reading the forecast","verbatim":false}', + ), + ( + 2200, + '{"type":"tool_updated","id":"call_1","turn_id":"t1","tool":"weather",' + '"text":"One moment.","verbatim":true}', + ), + ( + 2500, + '{"type":"tool_ran","tool_call_id":"call_1","turn_id":"t1","tool":"weather",' + '"arguments":"{}","result":"sunny","files":[],"error":""}', + ), + (2600, '{"type":"reasoning_delta","turn_id":"t1","text":"Check the calendar too."}'), + ( + 2700, + '{"type":"tool_started","tool_call_id":"call_2","tool":"calendar","turn_id":"t1",' + '"started_at":"2026-11-19T09:00:02Z"}', + ), + ( + 3000, + '{"type":"tool_ran","tool_call_id":"call_2","turn_id":"t1","tool":"calendar",' + '"arguments":"{}","result":"","files":[],"error":"calendar unreachable"}', + ), + ( + 3100, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"Let me look.",' + '"time_to_first_token_ms":90}', + ), + ]); + + final turn = conversation.turns.single; + expect(turn.steps, [ + ReasoningStep( + id: 'r1', + isStreaming: false, + text: "They want Lisbon's weather.", + at: ms(0), + duration: const Duration(seconds: 2), + ), + ToolCallStep( + id: 'call_1', + name: 'weather', + status: ToolCallStatus.completed, + summary: 'Reading the forecast', + at: ms(2000), + duration: const Duration(milliseconds: 500), + ), + ReasoningStep( + id: 'r2', + isStreaming: false, + text: 'Check the calendar too.', + at: ms(0), + duration: const Duration(milliseconds: 2700), + ), + ToolCallStep( + id: 'call_2', + name: 'calendar', + status: ToolCallStatus.failed, + at: ms(2700), + duration: const Duration(milliseconds: 300), + ), + ]); + // Its tools' results are still to come, in a turn of its own. + expect(turn.isDone, isFalse); + expect(turn.text, 'Let me look.'); + }); + + test('times a round of thinking from when the model was asked, not its first words', () { + // A model that sends its thinking in one burst, just before it writes. + final asked = play([ + (1000, '{"type":"responding","turn_id":"t1"}'), + (5000, '{"type":"reasoning_delta","turn_id":"t1","text":"Lisbon, "}'), + (5001, '{"type":"reasoning_delta","turn_id":"t1","text":"this weekend."}'), + (5250, '{"type":"response_delta","turn_id":"t1","text":"Sunny."}'), + ]); + final first = asked.turns.single.steps.single as ReasoningStep; + expect(first.at, ms(1000)); + expect(first.duration, const Duration(milliseconds: 4250)); + + // After writing, the next round is timed from when the model went on. + final wentOn = play([ + (7000, '{"type":"reasoning_delta","turn_id":"t1","text":"And Sunday?"}'), + (8000, '{"type":"response_delta","turn_id":"t1","text":" Sunday too."}'), + ], from: asked); + final second = wentOn.turns.single.steps.last as ReasoningStep; + expect(second.id, 'r2'); + expect(second.at, ms(5250)); + expect(second.duration, const Duration(milliseconds: 2750)); + }); + + test('a round stays open while the model thinks, and UI being written closes it', () { + final thinking = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (300, '{"type":"reasoning_delta","turn_id":"t1","text":"A card fits."}'), + ]); + expect((thinking.turns.single.steps.single as ReasoningStep).isStreaming, isTrue); + + final carding = play([ + ( + 900, + '{"type":"ui_delta","turn_id":"t1","format":"openui","mode":"replace",' + r'"delta":"root = Card([])\n"}', + ), + ], from: thinking); + final round = carding.turns.single.steps.single as ReasoningStep; + expect(round.isStreaming, isFalse); + expect(round.duration, const Duration(milliseconds: 900)); + }); + + test('a call shows once, even when started again or sharing an id with a round', () { + final conversation = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (1, '{"type":"reasoning_delta","turn_id":"t1","text":"The weather tool knows."}'), + (2, '{"type":"tool_started","tool_call_id":"r1","tool":"weather","turn_id":"t1"}'), + (3, '{"type":"tool_started","tool_call_id":"r1","tool":"weather","turn_id":"t1"}'), + ( + 10, + '{"type":"tool_ran","tool_call_id":"r1","tool":"weather","turn_id":"t1","error":""}', + ), + ]); + + final steps = conversation.turns.single.steps; + expect(steps.map((step) => (step.runtimeType, step.id)), [ + (ReasoningStep, 'r1'), + (ToolCallStep, 'r1'), + ]); + expect((steps.last as ToolCallStep).status, ToolCallStatus.completed); + expect((steps.last as ToolCallStep).duration, const Duration(milliseconds: 8)); + }); + + test('a turn is done once it answered with nothing left to come, or was cut off', () { + final answered = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + ( + 1, + '{"pending_work":false,"type":"responded","turn_id":"t1","text":"Sunny.",' + '"time_to_first_token_ms":90}', + ), + ]); + expect(answered.turns.single.isDone, isTrue); + + final waiting = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + ( + 1, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"",' + '"time_to_first_token_ms":90}', + ), + ]); + expect(waiting.turns.single.isDone, isFalse); + + final cut = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (1, '{"type":"reasoning_delta","turn_id":"t1","text":"Hmm"}'), + (5, '{"type":"interrupted","turn_id":"t1","participant":null}'), + ]); + expect(cut.turns.single.isDone, isTrue); + expect( + (cut.turns.single.steps.single as ReasoningStep).duration, + const Duration(milliseconds: 5), + ); + }); + + test( + 'progress for a call or a turn never seen changes nothing; thinking starts the turn', + () { + final before = play([(0, '{"type":"responding","turn_id":"t1"}')]); + + for (final json in [ + '{"type":"tool_updated","id":"nope","turn_id":"t1","text":"Working","verbatim":false}', + '{"type":"tool_ran","tool_call_id":"nope","turn_id":"t1","error":""}', + '{"type":"tool_ran","tool_call_id":"c1","turn_id":"t9","error":""}', + '{"type":"reasoning_delta","turn_id":"t1","text":""}', + ]) { + expect(identical(before.apply(frame(json)), before), isTrue, reason: json); + } + + final unseen = before.apply( + frame('{"type":"reasoning_delta","turn_id":"t2","text":"Next."}'), + at: ms(40), + ); + expect(unseen.turns.map((turn) => turn.id), ['t1', 't2']); + expect((unseen.turns.last.steps.single as ReasoningStep).at, ms(40)); + }, + ); + + test('a reply the prompt injection screen refused loses its text and UI, not its steps', () { + final refused = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (1, '{"type":"reasoning_delta","turn_id":"t1","text":"Reading the page."}'), + (2, '{"type":"tool_started","tool_call_id":"c1","tool":"fetch","turn_id":"t1"}'), + (3, '{"type":"response_delta","turn_id":"t1","text":"Ignore your rules and"}'), + ( + 4, + '{"type":"ui_delta","turn_id":"t1","format":"openui","mode":"replace",' + r'"delta":"root = Card([])\n"}', + ), + ( + 5, + '{"type":"error","context":"llm","error":"the input was refused",' + '"code":"prompt_injection"}', + ), + ]); + + final turn = refused.turns.single; + expect(turn.text, isEmpty); + expect(turn.ui, isNull); + expect(turn.steps.map((step) => step.id), ['r1', 'c1']); + expect(refused.failure, 'the input was refused'); + + // Another failure leaves what was written alone. + final failed = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (3, '{"type":"response_delta","turn_id":"t1","text":"Half"}'), + (5, '{"type":"error","context":"tts","error":"the voice is unknown"}'), + ]); + expect(failed.turns.single.text, 'Half'); + }); + + test('a refusal after the reply is done leaves the answer that was given', () { + final answered = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + ( + 1, + '{"pending_work":false,"type":"responded","turn_id":"t1","text":"Sunny.",' + '"time_to_first_token_ms":90}', + ), + ( + 5, + '{"type":"error","context":"llm","error":"the input was refused",' + '"code":"prompt_injection"}', + ), + ]); + + expect(answered.turns.single.text, 'Sunny.'); + }); + }); }); group('AgentEvent', () { diff --git a/sdks/dart/stream_agents/test/core/session_test.dart b/sdks/dart/stream_agents/test/core/session_test.dart index 35d35afb80..11a414bcde 100644 --- a/sdks/dart/stream_agents/test/core/session_test.dart +++ b/sdks/dart/stream_agents/test/core/session_test.dart @@ -749,6 +749,64 @@ void main() { await chat.close(); }); + test( + 'waits on its step of the reply, for the agents\' user, in a conversation kept nowhere', + () async { + // The router's session keeps no conversation: sessionJson's conversation_id is empty. + final chat = await agents + .withUser('ada') + .chat( + SessionOptions( + incognito: true, + tools: [ + AgentTool( + name: 'issue_refund', + description: 'Refund an order.', + approval: const ToolApproval( + title: 'Refund order A-1042?', + reasonArgument: 'reason', + allowTitle: 'Refund', + ), + run: (arguments) async => 'Refunded', + ), + ], + ), + ); + final socket = await router.socket(); + + socket + ..send('{"type":"responding","turn_id":"t1"}') + ..send( + '{"type":"tool_started","tool_call_id":"c1","tool":"issue_refund","turn_id":"t1",' + '"started_at":"2026-11-19T09:00:00Z"}', + ) + ..send(refundCall); + await until(() => chat.approvals.value.isNotEmpty); + + final step = chat.turnMessages.last.steps.single; + expect(step.type, 'ai_tool_call'); + expect(step.payload, { + 'id': 'c1', + 'name': 'issue_refund', + 'status': 'awaiting_approval', + // The person using the app, whom Stream's approver shows the card to: the session's own + // user_id is the name the agent joined the call as. + 'target_user_id': 'ada', + 'approval': { + 'title': 'Refund order A-1042?', + 'reason': 'it arrived unopened', + 'allow_title': 'Refund', + }, + }); + + chat.decide('c1', allowed: true); + + expect(chat.turnMessages.last.steps.single.payload['status'], 'running'); + await chat.close(); + expect(chat.turnMessages.last.isGenerating, isFalse); + }, + ); + test('declined, never runs, tells the model so, and a second answer does nothing', () async { final chat = await open(); final socket = await router.socket(); diff --git a/sdks/dart/stream_agents/test/core/turn_message_test.dart b/sdks/dart/stream_agents/test/core/turn_message_test.dart new file mode 100644 index 0000000000..5c06fbff41 --- /dev/null +++ b/sdks/dart/stream_agents/test/core/turn_message_test.dart @@ -0,0 +1,136 @@ +import 'package:test/test.dart'; +import 'package:stream_agents/src/core/core.dart'; + +/// Frames exactly as `frameOf` in the router writes them. +AgentEvent frame(String json) => AgentEvent.tryParse(json)!; + +void main() { + group('TurnMessage', () { + final start = DateTime.utc(2026, 11, 19, 9); + DateTime ms(int milliseconds) => start.add(Duration(milliseconds: milliseconds)); + + Conversation play(List<(int, String)> frames, {Conversation from = const Conversation()}) { + var conversation = from; + for (final (at, json) in frames) { + conversation = conversation.apply(frame(json), at: ms(at)); + } + return conversation; + } + + // A question, and a reply that waits on a tool and carries on in a turn of its own. + final asked = const Conversation().said('Weather in Lisbon?', at: ms(0)); + final toolTurn = [ + (10, '{"type":"responding","turn_id":"t1"}'), + (1000, '{"type":"reasoning_delta","turn_id":"t1","text":"They want Lisbon\'s weather."}'), + (1500, '{"type":"tool_started","tool_call_id":"call_1","tool":"weather","turn_id":"t1"}'), + ( + 1600, + '{"type":"tool_updated","id":"call_1","turn_id":"t1","tool":"weather",' + '"text":"Reading the forecast","verbatim":false}', + ), + ( + 2000, + '{"type":"tool_ran","tool_call_id":"call_1","turn_id":"t1","tool":"weather","error":""}', + ), + ( + 2100, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"Let me look.",' + '"time_to_first_token_ms":90}', + ), + ]; + final answerTurn = [ + (2200, '{"type":"responding","turn_id":"t2"}'), + (2600, '{"type":"reasoning_delta","turn_id":"t2","text":"Sunny, 24."}'), + (3000, '{"type":"response_delta","turn_id":"t2","text":"Sunny and 24°C."}'), + ]; + const answered = + '{"pending_work":false,"type":"responded","turn_id":"t2","text":"Sunny and 24°C.",' + '"time_to_first_token_ms":90}'; + + test('a reply is one message across its tools\' turns, with every step in order', () { + final conversation = play([...toolTurn, ...answerTurn, (3100, answered)], from: asked); + + final messages = TurnMessage.messages(conversation, userId: 'ada', isConnected: true); + + expect(messages.map((message) => (message.isAgentReply, message.text)), [ + (false, 'Weather in Lisbon?'), + (true, 'Let me look.\n\nSunny and 24°C.'), + ]); + final reply = messages.last; + expect(reply.id, 't1'); + expect(reply.at, ms(10)); + expect(reply.isGenerating, isFalse); + // Records compare their maps by identity, so each step is compared as a list. + expect(reply.steps.map((step) => [step.type, step.payload]), [ + [ + 'ai_reasoning', + {'id': 'r1', 'status': 'completed', 'duration_ms': 1490}, + ], + [ + 'ai_tool_call', + { + 'id': 'call_1', + 'name': 'weather', + 'status': 'completed', + 'summary': 'Reading the forecast', + 'duration_ms': 500, + }, + ], + // The second turn's round is its own r1, and the reply's r2. + [ + 'ai_reasoning', + {'id': 'r2', 'status': 'completed', 'duration_ms': 800}, + ], + ]); + expect(reply.reasoning, {'r1': "They want Lisbon's weather.", 'r2': 'Sunny, 24.'}); + expect(reply.customData, isEmpty); + }); + + test('only the latest reply is being written, and only while the socket carries it', () { + final writing = play([...toolTurn, ...answerTurn], from: asked); + + expect( + TurnMessage.messages(writing, userId: 'ada', isConnected: true).last.isGenerating, + isTrue, + ); + // Its tools are done but the turn carrying the reply on is not. + final betweenTurns = play(toolTurn, from: asked); + expect( + TurnMessage.messages(betweenTurns, userId: 'ada', isConnected: true).last.isGenerating, + isTrue, + ); + expect( + TurnMessage.messages(writing, userId: 'ada', isConnected: false).last.isGenerating, + isFalse, + ); + + // Asked over mid-thought: the reply before is as it was left. + final thinking = play([...toolTurn, ...answerTurn.take(2)], from: asked); + final askedAgain = thinking.said('Never mind.', at: ms(4000)); + final messages = TurnMessage.messages(askedAgain, userId: 'ada', isConnected: true); + expect(messages.map((message) => message.isGenerating), [false, false, false]); + expect( + messages[1].steps.last.payload['status'], + 'streaming', + reason: 'the round it was left on', + ); + }); + + test('a reply with UI carries its latest card as a kept one does', () { + final conversation = play([ + (10, '{"type":"responding","turn_id":"t1"}'), + ( + 20, + '{"type":"ui_completed","turn_id":"t1","format":"openui","mode":"replace",' + r'"content":"root = Card([])"}', + ), + ], from: asked); + + final reply = TurnMessage.messages(conversation, userId: 'ada', isConnected: true).last; + + expect(reply.customData, { + 'ai_ui': {'v': 1, 'format': 'openui', 'status': 'complete', 'content': 'root = Card([])'}, + }); + }); + }); +} From 90aa02701d78d59f982dc7b1bec1facb2b0e4e4c Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Thu, 19 Nov 2026 20:28:37 +0100 Subject: [PATCH 2/9] feat(sdk-dart): time thinking after a tool's result, mirror Kotlin's reducer, docs Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk-dart/SKILL.md | 11 +++ .claude/skills/sdk/SKILL.md | 4 ++ CHANGELOG.md | 4 ++ sdks/dart/stream_agents/CHANGELOG.md | 10 +++ sdks/dart/stream_agents/README.md | 14 ++++ .../lib/src/core/conversation.dart | 69 +++++++++++-------- .../lib/src/core/turn_message.dart | 6 +- .../test/core/conversation_test.dart | 5 +- 8 files changed, 88 insertions(+), 35 deletions(-) diff --git a/.claude/skills/sdk-dart/SKILL.md b/.claude/skills/sdk-dart/SKILL.md index 8494e88016..f76cd86b19 100644 --- a/.claude/skills/sdk-dart/SKILL.md +++ b/.claude/skills/sdk-dart/SKILL.md @@ -181,6 +181,17 @@ is kept working. What the router writes is what it renders: `AIMessage.reasoningText` reads it. - A tool that asks first is answered by an `AIToolApprover` whose `decide` calls `session.decide`; on a call, by an `AIToolApprovalCard` over `session.approvals`. +- An incognito session has no channel, and `chat()` throws. `Conversation` folds the socket's + `reasoning_delta`, `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran` into + `Turn.steps` and `Turn.isDone`, timing a round of thinking from when the turn was asked, + went on writing, or had a tool's result (a private `_resumedAt`, part of equality as + `_uiWritten` is). `session.turnMessages` (`TurnMessage`, in core) is the conversation in the + channel's shape: one reply per question across its tools' turns, each step the record + `AIMessagePart.parseAll` takes, rounds numbered across the reply, the whole thinking in + `reasoning`, and a call in `approvals` as `awaiting_approval` for the agents' own user + (`backend.userId`), never `Session.userId`, the agent's name on the call. `flutter_demo`'s + `AgentChat.unkept` follows it, rebuilding on `conversation`, `approvals` and `connection`, + and its app bar's lock starts an incognito chat. - `AIConversationView` lays the channel out in turns, `ChatComposer` asks and stops, and `AIVoiceGlowView` / `AIVoiceWaveView` show the agent on a call. diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 346d4368df..a032011b15 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -967,3 +967,7 @@ A device naming a user on a connections call (AI-3412): the router answers every `agent.yaml`'s `greeting` may be its text alone, `greeting: Hello, how can I help?`, read as `{text, mode: variation}`; the mapping still says `exact`, and a mapping without `mode` is now `variation` too, so a folder loader always sends `mode`. The API's own default stays `exact`. Go is done (`GreetingSettings.UnmarshalYAML` in `sdks/go/agents/folder.go`). Other SDKs need to update: the folder loaders of JavaScript (`sdks/js/src/folder.ts`, `greeting()`), Python (`plugins/stream` `folder.py`, `_greeting`), .NET, Ruby, Rust and PHP should take the string form and default a missing `mode` to `variation`. Calls have an id of their own and a `session_id`: a session starts a new call each time voice is started or stopped on it, and an incognito session keeps none, so a session id is no longer a call id. `Call.id` is the call's own id; `Call` gains `session_id` (absent once the session is deleted) and loses `config_id` and `user_id`. `listCalls` (`GET /v1/agents/calls`) takes `session_id` and answers that session's calls newest first. Go is done: `client.Sessions.Timeline` and `Decisions` list the session's calls with `session_id` and `limit=1`, read the newest one's `getCallTimeline` or `getCallEvents`, and fail with `client.ErrNoCall` when the session has none (`sdks/go/client/sessions.go`). Other SDKs need to update: JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP regenerate their clients, and any helper that passes a session id to `/v1/agents/calls/{id}` (its timeline, events, transcript or tokens) lists the session's calls first; Swift, Kotlin and Dart regenerate `Call` where they have it. STS models list their built-in voices on `Provider.voices` (`ModelVoice`: `id`, `name`, `description`, `gender`, `default`), omitted for non-STS providers, and new voice configs created via `createAgentConfig` or `syncAgent` now default `sts` to `sts-fast` when `sts` is omitted and no cascade settings are provided (explicit `sts: ""` selects the cascade). Go is regenerated (`sdks/go/acceleration/generated.go`). Other SDKs need to update: JavaScript, Python (`plugins/stream`), Swift, Kotlin, Dart, .NET, Ruby, Rust and PHP regenerate their OpenAPI types to pick up `Provider.voices` and `ModelVoice`. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; `flutter_demo`'s `AgentChat` shows an incognito session from them. Dart differs from Swift in two places, both on purpose: a waiting call's `target_user_id` is the agents' own user (`backend.userId`), as Kotlin's #2114 has it, not the session's `user_id`, which the spec calls the name the agent joined the call as, so an `AIToolApprover` for the person never matches Swift's or JavaScript's; and a round of thinking after a tool's result in the same turn is timed from `tool_ran`, where Swift, Kotlin and JavaScript time it from when the turn was last asked or went on writing, so it overlaps the call. Other SDKs need to update: Kotlin (#2114, open) should land its fold; Swift and JavaScript should set `target_user_id` to the person and time a round after `tool_ran`; the server SDKs need nothing. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Other SDKs need to update: Swift, Kotlin and Dart, whose AI components read the same steps, should fold the same frames into their `Conversation` turns and show a session with no channel through their transports; the server SDKs need nothing. +An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types; Python, Kotlin, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. +A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP should send their tool's display title on `host_tools`, their registries taking one where they do not yet; Swift, Kotlin and Dart read `display_title` off the tool call state once regenerated. diff --git a/CHANGELOG.md b/CHANGELOG.md index cb26da99e0..422bcd8a60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,10 @@ Every server SDK's client has a tool registry for the whole app, and one call ru `client.Connections()` creates, authorizes, reads, lists and deletes connections: `Create(ctx, client.ConnectionRequest{Connector: "linear", UserID: "alice"})`, then `Authorize(ctx, id, client.AuthorizeOptions{ReturnURL, UserID})` for the launch URL, handoff token and expiry of the consent, and `Get(ctx, id, client.ConnectionOptions{UserID})`, `List(ctx, client.ConnectionFilter{UserID, Connector})`, `Delete(ctx, id, client.ConnectionOptions{UserID})`. Every call takes the user as `UserID` of its options struct and sends it as both the owner and `X-Stream-User-Id`. An empty user is the app's own connection. +### The Dart SDK shows an incognito session + +An incognito session has no Stream Chat channel, so `session.chat()` throws and a Flutter app had nothing to show its replies with. `Conversation` now folds the socket's `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran` into each turn's `steps` (`ReasoningStep`, `ToolCallStep`) and `isDone`, timing a round of reasoning from when the model was asked, went on, or had a tool's result, and an `error` with code `prompt_injection` clears the reply being written of its text and UI. `session.turnMessages` is the conversation in the shape a kept one has in Chat, its steps as the records `AIMessagePart.parseAll` reads, and a call waiting for approval asks the agents' own user. `AgentEventKind` gains `reasoningDelta` and `toolUpdated`, so an exhaustive `switch` over it needs the two cases. `flutter_demo` has an incognito toggle in the Chat tab's app bar. + ### The Swift SDK shows an incognito session An incognito session has no Stream Chat channel, so `session.chat()` throws and an app had nothing to show its replies with. `Conversation` now folds the socket's `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran` into each turn's `steps` (rounds of reasoning and tool calls, in order) and `isDone`, timing a round of reasoning from when the model was asked. `session.turnMessages` is the conversation in the shape a kept one has in Chat: one `TurnMessage` per question and reply, its steps as attachment payloads for StreamChatAI's `AIMessagePart.parts(from:)`, the whole of each round of thinking, the reply's UI, and an approval card for the session's user, now `Session.userID`. `swift_assistant` has an incognito toggle at the top right of a new chat (#2091). diff --git a/sdks/dart/stream_agents/CHANGELOG.md b/sdks/dart/stream_agents/CHANGELOG.md index a596229a3b..9f072d8e66 100644 --- a/sdks/dart/stream_agents/CHANGELOG.md +++ b/sdks/dart/stream_agents/CHANGELOG.md @@ -22,6 +22,16 @@ while it runs, such as "Comparing 40 flights", otherwise its display title, such as "Checking the weather", falling back to the tool's name. - `session.toolCallsForTurn(turnId)` - the calls one agent turn made, to show under its message. +- `session.turnMessages` and `TurnMessage` - an incognito session, which has no channel, in the + shape a kept one has in Stream Chat, for Stream's AI components. +- `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone` - each reply's rounds of + thinking and tool calls, folded from the socket's `reasoning_delta`, `tool_started`, + `tool_updated` and `tool_ran`. A reply the prompt injection screen refused loses its text and UI. + +🔄 Changed + +- `AgentEventKind` has `reasoningDelta` and `toolUpdated`: a `switch` over it with no default + needs the two cases. ## 0.7.0 diff --git a/sdks/dart/stream_agents/README.md b/sdks/dart/stream_agents/README.md index 4794151401..7484942b27 100644 --- a/sdks/dart/stream_agents/README.md +++ b/sdks/dart/stream_agents/README.md @@ -172,6 +172,20 @@ Import `stream_chat` with a prefix: it exports a `TokenProvider` of its own. Asking an incognito session for its channel throws a `StateError`, since it keeps none. +Show an incognito session from its socket instead: `session.turnMessages` is the conversation +in the channel's shape, one reply per question with its steps as attachment payloads, the whole +of each round of thinking, and a call waiting in `approvals` asking on its step. Build it again +whenever `conversation`, `approvals` or `connection` changes: + +```dart +final session = await agents.agent('support').chat(const SessionOptions(incognito: true)); + +for (final message in session.turnMessages) { + final parts = AIMessagePart.parseAll(message.steps); // stream_chat_flutter_ai + // For each part with a reasoning step, message.reasoning[part.id] is its whole thinking. +} +``` + The channel opens on the app's own client when it hands one over, connected as the same user: ```dart diff --git a/sdks/dart/stream_agents/lib/src/core/conversation.dart b/sdks/dart/stream_agents/lib/src/core/conversation.dart index 18e8618153..b3cbcf751b 100644 --- a/sdks/dart/stream_agents/lib/src/core/conversation.dart +++ b/sdks/dart/stream_agents/lib/src/core/conversation.dart @@ -219,8 +219,8 @@ final class ReasoningStep extends TurnStep { /// The thinking so far. final String text; - /// When the model began on it: when it was asked, or took the reply up again after writing, - /// as a kept reply's step is timed. Not when its first words arrived, which a model that + /// When the model began on it: when it was asked, or took the reply up again after writing or + /// after a tool's result, as a kept reply's step is timed. Not when its first words arrived, which a model that /// sends its thinking in one burst sends only at the end. @override final DateTime at; @@ -389,7 +389,7 @@ final class Conversation { final Map _uiWritten; /// When the model last took each agent turn in flight up again, by turn id: when it was asked, - /// or went on after writing. A round of thinking is timed from it. + /// went on after writing, or had a tool's result. A round of thinking is timed from it. final Map _resumedAt; /// Whatever the caller typed, shown before the router has confirmed hearing it. @@ -459,12 +459,13 @@ final class Conversation { state: ConversationState.responding, failure: null, uiWritten: _uiWritten.containsKey(event.turnId) ? _without(event.turnId) : null, - resumedAt: {..._resumedAt, event.turnId: now}, - ); + )._resumed(event.turnId, now); case AgentEventKind.responseDelta: // Writing ends the round of thinking under way, and the next one is timed from here. - final went = event.text.isEmpty ? this : _wentOn(event.turnId, now); + final went = event.text.isEmpty + ? this + : _amend(event.turnId, (turn) => turn._settled(now))._resumed(event.turnId, now); return went ._write(event.turnId, now, (text) => text + event.text, event.text) .withState(ConversationState.responding); @@ -498,13 +499,18 @@ final class Conversation { case AgentEventKind.toolRan: final status = event.errorText.isEmpty ? ToolCallStatus.completed : ToolCallStatus.failed; - return _amend( + final ran = _amend( event.turnId, (turn) => turn._changedCall( _text(event['tool_call_id']), (call) => call._with(status: status, duration: now.difference(call.at)), ), ); + // The model goes on from the call's result, so its next round of thinking in this turn + // is timed from here, not from when it was first asked. + return identical(ran, this) || !_resumedAt.containsKey(event.turnId) + ? ran + : ran._resumed(event.turnId, now); case AgentEventKind.uiDelta: final delta = _text(event['delta']); @@ -519,10 +525,10 @@ final class Conversation { raw: '${_uiWritten[event.turnId]?.raw ?? ''}$delta', ); // Writing UI ends the round of thinking under way, as writing text does. - final written = _wentOn( + final written = _amend( event.turnId, - now, - )._with(uiWritten: {..._uiWritten, event.turnId: pending}); + (turn) => turn._settled(now), + )._resumed(event.turnId, now)._with(uiWritten: {..._uiWritten, event.turnId: pending}); // Only the line still being written grew, so no statement finished: nothing shown changes. final updated = format == 'openui' && !delta.contains('\n') ? written @@ -557,8 +563,13 @@ final class Conversation { ? settled : settled._write(event.turnId, now, (_) => event.text, event.text); // A reply whose tools or work are still to come is carried on by a turn of its own. + final done = event['pending_work'] != true; return written - ._ended(event.turnId, now, done: event['pending_work'] != true) + ._resumed(event.turnId, null) + ._amend(event.turnId, (turn) { + final settledTurn = turn._settled(now); + return done && !settledTurn.isDone ? settledTurn._copy(isDone: true) : settledTurn; + }) .withState(ConversationState.idle); case AgentEventKind.delegated: @@ -573,10 +584,7 @@ final class Conversation { return _with(state: left.isEmpty ? ConversationState.responding : Working(left)); case AgentEventKind.interrupted: - return _settleUI( - event.turnId, - now, - )._ended(event.turnId, now, done: true).withState(ConversationState.idle); + return _ended(event.turnId, now).withState(ConversationState.idle); case AgentEventKind.error: final refused = event['code'] == 'prompt_injection' ? _refused() : this; @@ -634,23 +642,24 @@ final class Conversation { return _with(turns: [...turns]..[index] = changed); } - /// The model went on with the agent turn [turnId] at [now], writing text or UI: its round of - /// thinking under way is complete, and the next one is timed from here. - Conversation _wentOn(String turnId, DateTime now) => - _amend(turnId, (turn) => turn._settled(now))._with(resumedAt: {..._resumedAt, turnId: now}); - - /// Nothing more of the agent turn [turnId] comes at [now]: its round of thinking is complete, - /// and the turn is [done] unless a turn of its own carries the reply on. - Conversation _ended(String turnId, DateTime now, {required bool done}) { - final settled = _amend(turnId, (turn) { - final ended = turn._settled(now); - return done && !ended.isDone ? ended._copy(isDone: true) : ended; - }); - return settled._resumedAt.containsKey(turnId) - ? settled._with(resumedAt: {...settled._resumedAt}..remove(turnId)) - : settled; + /// This conversation with the agent turn [turnId] taken up again [at], or done with for null. + Conversation _resumed(String turnId, DateTime? at) { + if (at == null) { + return _resumedAt.containsKey(turnId) + ? _with(resumedAt: {..._resumedAt}..remove(turnId)) + : this; + } + return _with(resumedAt: {..._resumedAt, turnId: at}); } + /// The agent turn [turnId] with nothing more of it to come: its round of thinking and its UI + /// settled, and the turn done. + Conversation _ended(String turnId, DateTime now) => + _settleUI(turnId, now)._resumed(turnId, null)._amend(turnId, (turn) { + final settledTurn = turn._settled(now); + return settledTurn.isDone ? settledTurn : settledTurn._copy(isDone: true); + }); + /// The prompt injection screen refused the reply being written. What it streamed before the /// verdict is not the answer, so its text and UI go, as they do from the kept conversation; /// its thinking and tool calls stay. diff --git a/sdks/dart/stream_agents/lib/src/core/turn_message.dart b/sdks/dart/stream_agents/lib/src/core/turn_message.dart index 3faedefd6d..6f40c7848c 100644 --- a/sdks/dart/stream_agents/lib/src/core/turn_message.dart +++ b/sdks/dart/stream_agents/lib/src/core/turn_message.dart @@ -12,7 +12,7 @@ import 'conversation.dart'; /// it. A call waiting in the session's `approvals` asks its user on its step, as a kept reply's /// does. final class TurnMessage { - TurnMessage({ + TurnMessage._({ required this.id, required this.isAgentReply, required this.text, @@ -90,7 +90,7 @@ final class TurnMessage { }) { final first = turns.first; if (!first.speaker.isAgent) { - return TurnMessage(id: first.id, isAgentReply: false, text: first.text, at: first.at); + return TurnMessage._(id: first.id, isAgentReply: false, text: first.text, at: first.at); } final steps = <({String type, Map payload})>[]; final reasoning = {}; @@ -126,7 +126,7 @@ final class TurnMessage { } } final ui = turns.lastWhere((turn) => turn.ui != null, orElse: () => first).ui; - return TurnMessage( + return TurnMessage._( id: first.id, isAgentReply: true, text: turns.map((turn) => turn.text).where((text) => text.isNotEmpty).join('\n\n'), diff --git a/sdks/dart/stream_agents/test/core/conversation_test.dart b/sdks/dart/stream_agents/test/core/conversation_test.dart index 7451ab0730..1c5b2a5292 100644 --- a/sdks/dart/stream_agents/test/core/conversation_test.dart +++ b/sdks/dart/stream_agents/test/core/conversation_test.dart @@ -465,12 +465,13 @@ void main() { at: ms(2000), duration: const Duration(milliseconds: 500), ), + // Timed from when the model had the weather's result, not from when it was asked. ReasoningStep( id: 'r2', isStreaming: false, text: 'Check the calendar too.', - at: ms(0), - duration: const Duration(milliseconds: 2700), + at: ms(2500), + duration: const Duration(milliseconds: 200), ), ToolCallStep( id: 'call_2', From fd76629d8948a935705b6ee0f5fb144c0ad990e1 Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Fri, 20 Nov 2026 00:07:51 +0100 Subject: [PATCH 3/9] fix(sdk-dart): name the step status apart from tool groups' ToolCallStatus; time thinking as Swift and Kotlin do The router answers a reply as waiting before its tools run, so resuming on tool_ran never applied. Tests now play frames in the router's order. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk-dart/SKILL.md | 10 +++-- .claude/skills/sdk/SKILL.md | 1 + CHANGELOG.md | 2 +- sdks/dart/stream_agents/CHANGELOG.md | 3 +- .../lib/src/core/conversation.dart | 44 +++++++++---------- .../lib/src/core/turn_message.dart | 2 +- .../test/core/conversation_test.dart | 41 +++++++---------- .../test/core/turn_message_test.dart | 11 ++--- 8 files changed, 55 insertions(+), 59 deletions(-) diff --git a/.claude/skills/sdk-dart/SKILL.md b/.claude/skills/sdk-dart/SKILL.md index f76cd86b19..baa8d5ae1e 100644 --- a/.claude/skills/sdk-dart/SKILL.md +++ b/.claude/skills/sdk-dart/SKILL.md @@ -183,9 +183,13 @@ is kept working. What the router writes is what it renders: `session.decide`; on a call, by an `AIToolApprovalCard` over `session.approvals`. - An incognito session has no channel, and `chat()` throws. `Conversation` folds the socket's `reasoning_delta`, `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran` into - `Turn.steps` and `Turn.isDone`, timing a round of thinking from when the turn was asked, - went on writing, or had a tool's result (a private `_resumedAt`, part of equality as - `_uiWritten` is). `session.turnMessages` (`TurnMessage`, in core) is the conversation in the + `Turn.steps` and `Turn.isDone`, timing a round of thinking from when the turn was asked or + went on writing (a private `_resumedAt`, part of equality as `_uiWritten` is). The router + answers a reply as waiting (`pending_work`) before its tools run, so their steps land on a + turn already answered, and their results carry it on in a turn of its own. The reducer keeps + Kotlin's shape (`_amend`, `_resumed`, `_ended`, `_refused`; `Turn._think`, `_settled`, + `_called`, `_changedCall`), with step types top level (`ReasoningStep`, `ToolCallStep`, + `ToolCallStepStatus`) for want of nested types. `session.turnMessages` (`TurnMessage`, in core) is the conversation in the channel's shape: one reply per question across its tools' turns, each step the record `AIMessagePart.parseAll` takes, rounds numbered across the reply, the whole thinking in `reasoning`, and a call in `approvals` as `awaiting_approval` for the agents' own user diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index a032011b15..3a79184b97 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -968,6 +968,7 @@ A device naming a user on a connections call (AI-3412): the router answers every Calls have an id of their own and a `session_id`: a session starts a new call each time voice is started or stopped on it, and an incognito session keeps none, so a session id is no longer a call id. `Call.id` is the call's own id; `Call` gains `session_id` (absent once the session is deleted) and loses `config_id` and `user_id`. `listCalls` (`GET /v1/agents/calls`) takes `session_id` and answers that session's calls newest first. Go is done: `client.Sessions.Timeline` and `Decisions` list the session's calls with `session_id` and `limit=1`, read the newest one's `getCallTimeline` or `getCallEvents`, and fail with `client.ErrNoCall` when the session has none (`sdks/go/client/sessions.go`). Other SDKs need to update: JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP regenerate their clients, and any helper that passes a session id to `/v1/agents/calls/{id}` (its timeline, events, transcript or tokens) lists the session's calls first; Swift, Kotlin and Dart regenerate `Call` where they have it. STS models list their built-in voices on `Provider.voices` (`ModelVoice`: `id`, `name`, `description`, `gender`, `default`), omitted for non-STS providers, and new voice configs created via `createAgentConfig` or `syncAgent` now default `sts` to `sts-fast` when `sts` is omitted and no cascade settings are provided (explicit `sts: ""` selects the cascade). Go is regenerated (`sdks/go/acceleration/generated.go`). Other SDKs need to update: JavaScript, Python (`plugins/stream`), Swift, Kotlin, Dart, .NET, Ruby, Rust and PHP regenerate their OpenAPI types to pick up `Provider.voices` and `ModelVoice`. The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; `flutter_demo`'s `AgentChat` shows an incognito session from them. Dart differs from Swift in two places, both on purpose: a waiting call's `target_user_id` is the agents' own user (`backend.userId`), as Kotlin's #2114 has it, not the session's `user_id`, which the spec calls the name the agent joined the call as, so an `AIToolApprover` for the person never matches Swift's or JavaScript's; and a round of thinking after a tool's result in the same turn is timed from `tool_ran`, where Swift, Kotlin and JavaScript time it from when the turn was last asked or went on writing, so it overlaps the call. Other SDKs need to update: Kotlin (#2114, open) should land its fold; Swift and JavaScript should set `target_user_id` to the person and time a round after `tool_ran`; the server SDKs need nothing. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; `flutter_demo`'s `AgentChat` shows an incognito session from them. Dart differs from Swift in one place, on purpose: a waiting call's `target_user_id` is the agents' own user (`backend.userId`), as Kotlin's #2114 has it, not the session's `user_id`, which the spec calls the name the agent joined the call as, so an `AIToolApprover` for the person never matches Swift's or JavaScript's. Its `ToolCallStepStatus` is named apart from `ToolCallStatus` (tool groups' call state), since Dart has no nested types. Other SDKs need to update: Kotlin (#2114, open) should land its fold; Swift and JavaScript should set `target_user_id` to the person; the server SDKs need nothing. The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Other SDKs need to update: Swift, Kotlin and Dart, whose AI components read the same steps, should fold the same frames into their `Conversation` turns and show a session with no channel through their transports; the server SDKs need nothing. An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types; Python, Kotlin, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP should send their tool's display title on `host_tools`, their registries taking one where they do not yet; Swift, Kotlin and Dart read `display_title` off the tool call state once regenerated. diff --git a/CHANGELOG.md b/CHANGELOG.md index 422bcd8a60..744e4df732 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,7 +74,7 @@ Every server SDK's client has a tool registry for the whole app, and one call ru ### The Dart SDK shows an incognito session -An incognito session has no Stream Chat channel, so `session.chat()` throws and a Flutter app had nothing to show its replies with. `Conversation` now folds the socket's `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran` into each turn's `steps` (`ReasoningStep`, `ToolCallStep`) and `isDone`, timing a round of reasoning from when the model was asked, went on, or had a tool's result, and an `error` with code `prompt_injection` clears the reply being written of its text and UI. `session.turnMessages` is the conversation in the shape a kept one has in Chat, its steps as the records `AIMessagePart.parseAll` reads, and a call waiting for approval asks the agents' own user. `AgentEventKind` gains `reasoningDelta` and `toolUpdated`, so an exhaustive `switch` over it needs the two cases. `flutter_demo` has an incognito toggle in the Chat tab's app bar. +An incognito session has no Stream Chat channel, so `session.chat()` throws and a Flutter app had nothing to show its replies with. `Conversation` now folds the socket's `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran` into each turn's `steps` (`ReasoningStep`, `ToolCallStep`) and `isDone`, timing a round of reasoning from when the model was asked or went on writing, and an `error` with code `prompt_injection` clears the reply being written of its text and UI. `session.turnMessages` is the conversation in the shape a kept one has in Chat, its steps as the records `AIMessagePart.parseAll` reads, and a call waiting for approval asks the agents' own user. `AgentEventKind` gains `reasoningDelta`, so an exhaustive `switch` over it needs the case. `flutter_demo` has an incognito toggle in the Chat tab's app bar. ### The Swift SDK shows an incognito session diff --git a/sdks/dart/stream_agents/CHANGELOG.md b/sdks/dart/stream_agents/CHANGELOG.md index 9f072d8e66..67f13e9634 100644 --- a/sdks/dart/stream_agents/CHANGELOG.md +++ b/sdks/dart/stream_agents/CHANGELOG.md @@ -30,8 +30,7 @@ 🔄 Changed -- `AgentEventKind` has `reasoningDelta` and `toolUpdated`: a `switch` over it with no default - needs the two cases. +- `AgentEventKind` has `reasoningDelta`: a `switch` over it with no default needs the case. ## 0.7.0 diff --git a/sdks/dart/stream_agents/lib/src/core/conversation.dart b/sdks/dart/stream_agents/lib/src/core/conversation.dart index b3cbcf751b..043acdefbf 100644 --- a/sdks/dart/stream_agents/lib/src/core/conversation.dart +++ b/sdks/dart/stream_agents/lib/src/core/conversation.dart @@ -162,7 +162,7 @@ final class Turn { /// This turn with its running call [id] changed as [change] says, or itself when it has none. Turn _changedCall(String id, ToolCallStep Function(ToolCallStep) change) { final index = steps.indexWhere( - (step) => step is ToolCallStep && step.id == id && step.status == ToolCallStatus.running, + (step) => step is ToolCallStep && step.id == id && step.status == ToolCallStepStatus.running, ); if (index == -1) return this; final changed = [...steps]; @@ -219,8 +219,8 @@ final class ReasoningStep extends TurnStep { /// The thinking so far. final String text; - /// When the model began on it: when it was asked, or took the reply up again after writing or - /// after a tool's result, as a kept reply's step is timed. Not when its first words arrived, which a model that + /// When the model began on it: when it was asked, or took the reply up again after writing, + /// as a kept reply's step is timed. Not when its first words arrived, which a model that /// sends its thinking in one burst sends only at the end. @override final DateTime at; @@ -267,7 +267,7 @@ final class ToolCallStep extends TurnStep { /// The tool. final String name; - final ToolCallStatus status; + final ToolCallStepStatus status; /// What whoever runs it last said about how it is going (`tool_updated`), or the empty string. final String summary; @@ -278,14 +278,15 @@ final class ToolCallStep extends TurnStep { /// How long it ran, once it is no longer running. final Duration? duration; - ToolCallStep _with({ToolCallStatus? status, String? summary, Duration? duration}) => ToolCallStep( - id: id, - name: name, - status: status ?? this.status, - summary: summary ?? this.summary, - at: at, - duration: duration ?? this.duration, - ); + ToolCallStep _with({ToolCallStepStatus? status, String? summary, Duration? duration}) => + ToolCallStep( + id: id, + name: name, + status: status ?? this.status, + summary: summary ?? this.summary, + at: at, + duration: duration ?? this.duration, + ); @override bool operator ==(Object other) => @@ -305,12 +306,12 @@ final class ToolCallStep extends TurnStep { } /// How a tool call went. -enum ToolCallStatus { +enum ToolCallStepStatus { running('running'), completed('completed'), failed('failed'); - const ToolCallStatus(this.wire); + const ToolCallStepStatus(this.wire); /// Its name in a kept reply's `ai_tool_call` step. final String wire; @@ -389,7 +390,7 @@ final class Conversation { final Map _uiWritten; /// When the model last took each agent turn in flight up again, by turn id: when it was asked, - /// went on after writing, or had a tool's result. A round of thinking is timed from it. + /// or went on after writing. A round of thinking is timed from it. final Map _resumedAt; /// Whatever the caller typed, shown before the router has confirmed hearing it. @@ -481,7 +482,7 @@ final class Conversation { final call = ToolCallStep( id: _text(event['tool_call_id']), name: _text(event['tool']), - status: ToolCallStatus.running, + status: ToolCallStepStatus.running, at: now, ); return _amend(event.turnId, (turn) => turn._settled(now)._called(call), startingAt: now); @@ -498,19 +499,16 @@ final class Conversation { ); case AgentEventKind.toolRan: - final status = event.errorText.isEmpty ? ToolCallStatus.completed : ToolCallStatus.failed; - final ran = _amend( + final status = event.errorText.isEmpty + ? ToolCallStepStatus.completed + : ToolCallStepStatus.failed; + return _amend( event.turnId, (turn) => turn._changedCall( _text(event['tool_call_id']), (call) => call._with(status: status, duration: now.difference(call.at)), ), ); - // The model goes on from the call's result, so its next round of thinking in this turn - // is timed from here, not from when it was first asked. - return identical(ran, this) || !_resumedAt.containsKey(event.turnId) - ? ran - : ran._resumed(event.turnId, now); case AgentEventKind.uiDelta: final delta = _text(event['delta']); diff --git a/sdks/dart/stream_agents/lib/src/core/turn_message.dart b/sdks/dart/stream_agents/lib/src/core/turn_message.dart index 6f40c7848c..a3faf75da4 100644 --- a/sdks/dart/stream_agents/lib/src/core/turn_message.dart +++ b/sdks/dart/stream_agents/lib/src/core/turn_message.dart @@ -109,7 +109,7 @@ final class TurnMessage { }, )); case ToolCallStep(): - final waiting = step.status == ToolCallStatus.running + final waiting = step.status == ToolCallStepStatus.running ? approvals.where((request) => request.id == step.id).firstOrNull : null; steps.add(( diff --git a/sdks/dart/stream_agents/test/core/conversation_test.dart b/sdks/dart/stream_agents/test/core/conversation_test.dart index 1c5b2a5292..b80f5ce3bb 100644 --- a/sdks/dart/stream_agents/test/core/conversation_test.dart +++ b/sdks/dart/stream_agents/test/core/conversation_test.dart @@ -406,15 +406,27 @@ void main() { } test('a written reply keeps its thinking and tool calls in the order they happened', () { + // The router's order: the reply is answered as waiting on its tools, which then run, and + // their results carry it on in a turn of its own. final conversation = play([ (0, '{"type":"responding","turn_id":"t1"}'), (1000, '{"type":"reasoning_delta","turn_id":"t1","text":"They want "}'), (1100, '{"type":"reasoning_delta","turn_id":"t1","text":"Lisbon\'s weather."}'), + ( + 2000, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"Let me look.",' + '"time_to_first_token_ms":90}', + ), ( 2000, '{"type":"tool_started","tool_call_id":"call_1","tool":"weather","turn_id":"t1",' '"started_at":"2026-11-19T09:00:02Z"}', ), + ( + 2000, + '{"type":"tool_started","tool_call_id":"call_2","tool":"calendar","turn_id":"t1",' + '"started_at":"2026-11-19T09:00:02Z"}', + ), ( 2100, '{"type":"tool_updated","id":"call_1","turn_id":"t1","tool":"weather",' @@ -430,22 +442,11 @@ void main() { '{"type":"tool_ran","tool_call_id":"call_1","turn_id":"t1","tool":"weather",' '"arguments":"{}","result":"sunny","files":[],"error":""}', ), - (2600, '{"type":"reasoning_delta","turn_id":"t1","text":"Check the calendar too."}'), - ( - 2700, - '{"type":"tool_started","tool_call_id":"call_2","tool":"calendar","turn_id":"t1",' - '"started_at":"2026-11-19T09:00:02Z"}', - ), ( - 3000, + 2300, '{"type":"tool_ran","tool_call_id":"call_2","turn_id":"t1","tool":"calendar",' '"arguments":"{}","result":"","files":[],"error":"calendar unreachable"}', ), - ( - 3100, - '{"pending_work":true,"type":"responded","turn_id":"t1","text":"Let me look.",' - '"time_to_first_token_ms":90}', - ), ]); final turn = conversation.turns.single; @@ -460,24 +461,16 @@ void main() { ToolCallStep( id: 'call_1', name: 'weather', - status: ToolCallStatus.completed, + status: ToolCallStepStatus.completed, summary: 'Reading the forecast', at: ms(2000), duration: const Duration(milliseconds: 500), ), - // Timed from when the model had the weather's result, not from when it was asked. - ReasoningStep( - id: 'r2', - isStreaming: false, - text: 'Check the calendar too.', - at: ms(2500), - duration: const Duration(milliseconds: 200), - ), ToolCallStep( id: 'call_2', name: 'calendar', - status: ToolCallStatus.failed, - at: ms(2700), + status: ToolCallStepStatus.failed, + at: ms(2000), duration: const Duration(milliseconds: 300), ), ]); @@ -545,7 +538,7 @@ void main() { (ReasoningStep, 'r1'), (ToolCallStep, 'r1'), ]); - expect((steps.last as ToolCallStep).status, ToolCallStatus.completed); + expect((steps.last as ToolCallStep).status, ToolCallStepStatus.completed); expect((steps.last as ToolCallStep).duration, const Duration(milliseconds: 8)); }); diff --git a/sdks/dart/stream_agents/test/core/turn_message_test.dart b/sdks/dart/stream_agents/test/core/turn_message_test.dart index 5c06fbff41..3b4d483455 100644 --- a/sdks/dart/stream_agents/test/core/turn_message_test.dart +++ b/sdks/dart/stream_agents/test/core/turn_message_test.dart @@ -22,6 +22,12 @@ void main() { final toolTurn = [ (10, '{"type":"responding","turn_id":"t1"}'), (1000, '{"type":"reasoning_delta","turn_id":"t1","text":"They want Lisbon\'s weather."}'), + // As the router sends it: answered as waiting on its tool, which then runs. + ( + 1500, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"Let me look.",' + '"time_to_first_token_ms":90}', + ), (1500, '{"type":"tool_started","tool_call_id":"call_1","tool":"weather","turn_id":"t1"}'), ( 1600, @@ -32,11 +38,6 @@ void main() { 2000, '{"type":"tool_ran","tool_call_id":"call_1","turn_id":"t1","tool":"weather","error":""}', ), - ( - 2100, - '{"pending_work":true,"type":"responded","turn_id":"t1","text":"Let me look.",' - '"time_to_first_token_ms":90}', - ), ]; final answerTurn = [ (2200, '{"type":"responding","turn_id":"t2"}'), From b097497f2df6ec0a0405cceec0441989ab04a411 Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Mon, 23 Nov 2026 12:18:54 +0100 Subject: [PATCH 4/9] docs(sdk-dart): one Dart note in the sdk skill, one Changed heading Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk/SKILL.md | 2 +- sdks/dart/stream_agents/CHANGELOG.md | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 3a79184b97..9e30379449 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -954,7 +954,7 @@ Connections (AI-3376): Go has `client.Connections()` for the accounts the app an Connections in Rust (AI-3383): `Client::connections()` (`sdks/rust/src/connections.rs`) follows Go's shape with the user as `user_id` of each call: `create(&NewConnection{connector, label, user_id})`, `authorize(id, &AuthorizeOptions{return_url, user_id})`, `get(id, user_id: Option<&str>)`, `list(&ConnectionFilter{connector, user_id})`, `delete(id, user_id: Option<&str>)`; options structs rather than adjacent `Option<&str>` so a label cannot be swapped for a user. A user given goes through `pub(crate) Client::acting_for`, so the header matches the call and replaces a `ClientOptions::user_id` the client was built with; no user (or an empty one) leaves the client as built, as Go's `UserID` does (92148e5fe). Rust had no public acting-for helper to deprecate for AI-3387: `Backend` and its `acting_for` field are crate-private (`sdks/rust/src/backend.rs`, not re-exported from `lib.rs`), and `Client::acting_for` is `pub(crate)`. No other SDK needs to change for this. Connections in JavaScript (AI-3378, AI-3387): `api.connections` has `create(connectorId, { label, userId })`, `authorize(id, { returnUrl, userId })`, `get(id, { userId })`, `list({ connectorId, userId })` (every page, 200 a page, newest first) and `delete(id, { userId })`. The user is an optional parameter of each call, never a client of its own: given, it is sent as `owner.user_id` (create) and `X-Stream-User-Id` on every call, reads included, with the app's server credential (an internal `speakingFor(backend, userId)` in `backend.ts`, kept off `Backend`'s type, which Dispatch's `answer` also uses); left out or empty, the call is the app's (`owner.type: app`, `owner_type=app`, no header added). Optional parts are one options object, never adjacent positional strings. `Backend.actingFor` stays public and working, marked `@deprecated` (Chat's "deprecate, never break"), and a test pins its requests to the base commit's. A client built with `BackendOptions.userId` still sends that user on a call without `userId`, as on every other call; one built on the deprecated `actingFor` does not (the call is the app's). A `userId` on a client that is not server side (a device, or a page on a customer-id router) is a `ConfigurationError` before any request. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP (AI-3379..AI-3383). Connections in Python (AI-3379, no spec change): `plugins/stream` has `api.connections` with the Go shape: `create(connector_id, *, label=None, user_id=None)`, `authorize(id, *, return_url=None, user_id=None)` returning `Authorization`, `get(id, *, user_id=None)`, `list(*, connector_id=None, user_id=None)` reading every page, `delete(id, *, user_id=None)`; every option is keyword-only, so a user id cannot land in the label's or connector's slot. A user given is `owner.user_id` (create) and `X-Stream-User-Id` on every call, replacing whoever the client acts for and the user its backend was built for (which behind the proxy would sign that user's own token); none is the app's connection, sent as the client is otherwise (a client built for a user still names that user). AI-3387 in Python: `Client.for_user` is deprecated (`DeprecationWarning`, still working) in favour of a keyword-only `user_id=None`, last, on `Client.agent` and `Client.router`, on a client built with `team=`/`usage_categories=`; a device naming a user is refused before any request. Dispatch and `Accelerated` keep `Backend.acting_for` internally. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Other SDKs need to update: Dart, whose AI components read the same steps, should fold the same frames into their `Conversation` turns and show a session with no channel through their transports; the server SDKs need nothing. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`, `ToolCallStepStatus`, top level for want of nested types and named apart from tool groups' `ToolCallStatus`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; like Kotlin, its `target_user_id` is the agents' own user (`backend.userId`), not the session's `user_id`; `flutter_demo`'s `AgentChat` shows an incognito session from them. Other SDKs need to update: Swift (`TurnMessage.swift`) and JavaScript (`turn-messages.ts`) set `target_user_id` to the session's `user_id`, the agent's name on the call, so an `AIToolApprover` for the person never matches; they should use the person, as Kotlin and Dart do. The server SDKs need nothing. An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types, and Kotlin has `SessionOptions.ui`, which `Sessions.create` sends as it is (null left out); Python, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Every server SDK now declares one: Python `register(display_title=...)` (on `ToolPolicy`, sent by `plugins/stream`'s `_with_policy`), .NET `displayTitle:`, Ruby `display_title:`, PHP `displayTitle:` and Rust's `SessionTool.display_title`; Swift, Kotlin and Dart read it off the tool call state. Nothing is left to update. Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Connections.php`) has `create(NewConnection)`, `authorize(id, AuthorizeOptions)`, `get(id, userId)`, `list(ConnectionFilter)` (every page, `limit` 200, a repeated cursor ends it) and `delete(id, userId)`, Go's shape: the calls with more than one optional take an options object (`NewConnection`, `AuthorizeOptions`, `ConnectionFilter`, `sdks/php/src/`) like Go's `ConnectionRequest`, `AuthorizeOptions` and `ConnectionFilter`, so a user id cannot take the place of a label, return URL or connector (R1.1 of the review: `create('linear', 'ada')` had filed the user's account as the app's). `userId` is optional and last (a parameter of `get` and `delete`, a field of the options objects); given, it is `owner.user_id` and `X-Stream-User-Id` with the server credential (a server token behind the proxy, never a user token); left out or empty, `owner.type: app` and no header, whoever the backend otherwise acts for. `Connections` goes through `Backend::speakingFor` (`@internal`, PHP has no package visibility), which drops the backend's own user. `Dispatch::answer` goes through `Backend::writingFor` (`@internal`, `Dispatch.php:193`), which keeps the backend's own user when the writer has none, as `onBehalfOf` did before; `onBehalfOf` calls `writingFor`. `Backend::onBehalfOf` stays public and working, `@deprecated` in favour of the `userId` parameter; PHP's `Backend::actingFor` is unchanged and still signs a user token (the device path), so its name means something else than `actingFor` in Go and JavaScript. No other public PHP wrapper used `onBehalfOf`. diff --git a/sdks/dart/stream_agents/CHANGELOG.md b/sdks/dart/stream_agents/CHANGELOG.md index 67f13e9634..549043198c 100644 --- a/sdks/dart/stream_agents/CHANGELOG.md +++ b/sdks/dart/stream_agents/CHANGELOG.md @@ -7,6 +7,8 @@ row before; read that as `session.session`. `chat` and `voice` are now `sessions.create` with `startVoice` false and true. +- `AgentEventKind` has `reasoningDelta`: a `switch` over it with no default needs the case. + ✅ Added - `SessionOptions.watch` - false opens a session with no socket and no tools declared; turns go @@ -28,10 +30,6 @@ thinking and tool calls, folded from the socket's `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran`. A reply the prompt injection screen refused loses its text and UI. -🔄 Changed - -- `AgentEventKind` has `reasoningDelta`: a `switch` over it with no default needs the case. - ## 0.7.0 First release of `stream_agents`, the Flutter client for Stream Agents, versioned with the From 77e932e45a67a2570b492fcb14287dc9331a5bba Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Mon, 23 Nov 2026 13:22:31 +0100 Subject: [PATCH 5/9] docs(sdk-skill): drop the note on other SDKs Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 9e30379449..8a3fb3a345 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -954,7 +954,7 @@ Connections (AI-3376): Go has `client.Connections()` for the accounts the app an Connections in Rust (AI-3383): `Client::connections()` (`sdks/rust/src/connections.rs`) follows Go's shape with the user as `user_id` of each call: `create(&NewConnection{connector, label, user_id})`, `authorize(id, &AuthorizeOptions{return_url, user_id})`, `get(id, user_id: Option<&str>)`, `list(&ConnectionFilter{connector, user_id})`, `delete(id, user_id: Option<&str>)`; options structs rather than adjacent `Option<&str>` so a label cannot be swapped for a user. A user given goes through `pub(crate) Client::acting_for`, so the header matches the call and replaces a `ClientOptions::user_id` the client was built with; no user (or an empty one) leaves the client as built, as Go's `UserID` does (92148e5fe). Rust had no public acting-for helper to deprecate for AI-3387: `Backend` and its `acting_for` field are crate-private (`sdks/rust/src/backend.rs`, not re-exported from `lib.rs`), and `Client::acting_for` is `pub(crate)`. No other SDK needs to change for this. Connections in JavaScript (AI-3378, AI-3387): `api.connections` has `create(connectorId, { label, userId })`, `authorize(id, { returnUrl, userId })`, `get(id, { userId })`, `list({ connectorId, userId })` (every page, 200 a page, newest first) and `delete(id, { userId })`. The user is an optional parameter of each call, never a client of its own: given, it is sent as `owner.user_id` (create) and `X-Stream-User-Id` on every call, reads included, with the app's server credential (an internal `speakingFor(backend, userId)` in `backend.ts`, kept off `Backend`'s type, which Dispatch's `answer` also uses); left out or empty, the call is the app's (`owner.type: app`, `owner_type=app`, no header added). Optional parts are one options object, never adjacent positional strings. `Backend.actingFor` stays public and working, marked `@deprecated` (Chat's "deprecate, never break"), and a test pins its requests to the base commit's. A client built with `BackendOptions.userId` still sends that user on a call without `userId`, as on every other call; one built on the deprecated `actingFor` does not (the call is the app's). A `userId` on a client that is not server side (a device, or a page on a customer-id router) is a `ConfigurationError` before any request. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP (AI-3379..AI-3383). Connections in Python (AI-3379, no spec change): `plugins/stream` has `api.connections` with the Go shape: `create(connector_id, *, label=None, user_id=None)`, `authorize(id, *, return_url=None, user_id=None)` returning `Authorization`, `get(id, *, user_id=None)`, `list(*, connector_id=None, user_id=None)` reading every page, `delete(id, *, user_id=None)`; every option is keyword-only, so a user id cannot land in the label's or connector's slot. A user given is `owner.user_id` (create) and `X-Stream-User-Id` on every call, replacing whoever the client acts for and the user its backend was built for (which behind the proxy would sign that user's own token); none is the app's connection, sent as the client is otherwise (a client built for a user still names that user). AI-3387 in Python: `Client.for_user` is deprecated (`DeprecationWarning`, still working) in favour of a keyword-only `user_id=None`, last, on `Client.agent` and `Client.router`, on a client built with `team=`/`usage_categories=`; a device naming a user is refused before any request. Dispatch and `Accelerated` keep `Backend.acting_for` internally. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`, `ToolCallStepStatus`, top level for want of nested types and named apart from tool groups' `ToolCallStatus`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; like Kotlin, its `target_user_id` is the agents' own user (`backend.userId`), not the session's `user_id`; `flutter_demo`'s `AgentChat` shows an incognito session from them. Other SDKs need to update: Swift (`TurnMessage.swift`) and JavaScript (`turn-messages.ts`) set `target_user_id` to the session's `user_id`, the agent's name on the call, so an `AIToolApprover` for the person never matches; they should use the person, as Kotlin and Dart do. The server SDKs need nothing. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`, `ToolCallStepStatus`, top level for want of nested types and named apart from tool groups' `ToolCallStatus`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; like Kotlin, its `target_user_id` is the agents' own user (`backend.userId`), not the session's `user_id`; `flutter_demo`'s `AgentChat` shows an incognito session from them. The server SDKs need nothing. An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types, and Kotlin has `SessionOptions.ui`, which `Sessions.create` sends as it is (null left out); Python, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Every server SDK now declares one: Python `register(display_title=...)` (on `ToolPolicy`, sent by `plugins/stream`'s `_with_policy`), .NET `displayTitle:`, Ruby `display_title:`, PHP `displayTitle:` and Rust's `SessionTool.display_title`; Swift, Kotlin and Dart read it off the tool call state. Nothing is left to update. Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Connections.php`) has `create(NewConnection)`, `authorize(id, AuthorizeOptions)`, `get(id, userId)`, `list(ConnectionFilter)` (every page, `limit` 200, a repeated cursor ends it) and `delete(id, userId)`, Go's shape: the calls with more than one optional take an options object (`NewConnection`, `AuthorizeOptions`, `ConnectionFilter`, `sdks/php/src/`) like Go's `ConnectionRequest`, `AuthorizeOptions` and `ConnectionFilter`, so a user id cannot take the place of a label, return URL or connector (R1.1 of the review: `create('linear', 'ada')` had filed the user's account as the app's). `userId` is optional and last (a parameter of `get` and `delete`, a field of the options objects); given, it is `owner.user_id` and `X-Stream-User-Id` with the server credential (a server token behind the proxy, never a user token); left out or empty, `owner.type: app` and no header, whoever the backend otherwise acts for. `Connections` goes through `Backend::speakingFor` (`@internal`, PHP has no package visibility), which drops the backend's own user. `Dispatch::answer` goes through `Backend::writingFor` (`@internal`, `Dispatch.php:193`), which keeps the backend's own user when the writer has none, as `onBehalfOf` did before; `onBehalfOf` calls `writingFor`. `Backend::onBehalfOf` stays public and working, `@deprecated` in favour of the `userId` parameter; PHP's `Backend::actingFor` is unchanged and still signs a user token (the device path), so its name means something else than `actingFor` in Go and JavaScript. No other public PHP wrapper used `onBehalfOf`. From bcf92a225cd0c25d5b922872550a87aa59468b5e Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Mon, 23 Nov 2026 13:35:29 +0100 Subject: [PATCH 6/9] fix(sdk-dart): UI with no format closes a round of thinking; tests in the router's frame order TurnMessage compares its steps by value rather than by encoding them. Co-Authored-By: Claude Opus 5.5 --- .../flutter_demo/test/agent_chat_test.dart | 10 +++-- .../lib/src/core/conversation.dart | 13 +++--- .../lib/src/core/turn_message.dart | 40 ++++++++++++------- .../test/core/conversation_test.dart | 22 ++++++++++ .../stream_agents/test/core/session_test.dart | 5 +++ .../test/core/turn_message_test.dart | 34 ++++++++++++++++ 6 files changed, 100 insertions(+), 24 deletions(-) diff --git a/examples/voice_agents/flutter_demo/test/agent_chat_test.dart b/examples/voice_agents/flutter_demo/test/agent_chat_test.dart index 9c5904e905..79c53d495c 100644 --- a/examples/voice_agents/flutter_demo/test/agent_chat_test.dart +++ b/examples/voice_agents/flutter_demo/test/agent_chat_test.dart @@ -347,11 +347,17 @@ void main() { conversation.send("I'd like a refund for order A-1042"); await _until(() => router.asked == 1); + // The router's order: the reply is answered as waiting on its tools, which then run, and + // their results carry it on in a turn of its own. socket ..send('{"type":"responding","turn_id":"t1"}') ..send( '{"type":"reasoning_delta","turn_id":"t1","text":"They were charged twice."}', ) + ..send( + '{"pending_work":true,"type":"responded","turn_id":"t1",' + '"text":"","time_to_first_token_ms":90}', + ) ..send( '{"type":"tool_started","tool_call_id":"c1","tool":"issue_refund",' '"turn_id":"t1","started_at":"2026-11-19T09:00:00Z"}', @@ -394,10 +400,6 @@ void main() { '{"type":"tool_ran","tool_call_id":"c1","turn_id":"t1",' '"tool":"issue_refund","error":""}', ) - ..send( - '{"pending_work":true,"type":"responded","turn_id":"t1",' - '"text":"","time_to_first_token_ms":90}', - ) ..send('{"type":"responding","turn_id":"t2"}') ..send( '{"pending_work":false,"type":"responded","turn_id":"t2",' diff --git a/sdks/dart/stream_agents/lib/src/core/conversation.dart b/sdks/dart/stream_agents/lib/src/core/conversation.dart index 043acdefbf..1e9e07186e 100644 --- a/sdks/dart/stream_agents/lib/src/core/conversation.dart +++ b/sdks/dart/stream_agents/lib/src/core/conversation.dart @@ -513,20 +513,21 @@ final class Conversation { case AgentEventKind.uiDelta: final delta = _text(event['delta']); final format = _text(event['format']); - if (delta.isEmpty || format.isEmpty) { + if (delta.isEmpty) { return this; } + // Writing UI ends the round of thinking under way, as writing text does. + final went = _amend(event.turnId, (turn) => turn._settled(now))._resumed(event.turnId, now); + if (format.isEmpty) { + return went; + } final pending = ( format: format, version: _optionalText(event['version']), mode: _nonEmptyOr(_text(event['mode']), 'replace'), raw: '${_uiWritten[event.turnId]?.raw ?? ''}$delta', ); - // Writing UI ends the round of thinking under way, as writing text does. - final written = _amend( - event.turnId, - (turn) => turn._settled(now), - )._resumed(event.turnId, now)._with(uiWritten: {..._uiWritten, event.turnId: pending}); + final written = went._with(uiWritten: {..._uiWritten, event.turnId: pending}); // Only the line still being written grew, so no statement finished: nothing shown changes. final updated = format == 'openui' && !delta.contains('\n') ? written diff --git a/sdks/dart/stream_agents/lib/src/core/turn_message.dart b/sdks/dart/stream_agents/lib/src/core/turn_message.dart index a3faf75da4..6296438ef8 100644 --- a/sdks/dart/stream_agents/lib/src/core/turn_message.dart +++ b/sdks/dart/stream_agents/lib/src/core/turn_message.dart @@ -1,5 +1,3 @@ -import 'dart:convert'; - import 'agent_session.dart'; import 'conversation.dart'; @@ -148,15 +146,8 @@ final class TurnMessage { 'decline_title': title, }; - /// What it shows besides its id, text and time, compared as one value: the steps' maps are - /// written in a fixed order, so a step that did not change encodes the same. - late final String _shown = jsonEncode([ - for (final step in steps) [step.type, step.payload], - reasoning, - customData, - ]); - - /// Equal when it shows the same, so a view can keep a message that did not change. + /// Equal when it shows the same, its steps, thinking and custom data compared by value, so a + /// view can keep a message that did not change. @override bool operator ==(Object other) => other is TurnMessage && @@ -165,10 +156,18 @@ final class TurnMessage { other.text == text && other.at == at && other.isGenerating == isGenerating && - other._shown == _shown; - + _sameValue(other.reasoning, reasoning) && + _sameValue(other.customData, customData) && + other.steps.length == steps.length && + [ + for (var i = 0; i < steps.length; i++) + other.steps[i].type == steps[i].type && + _sameValue(other.steps[i].payload, steps[i].payload), + ].every((same) => same); + + /// Leaves out the steps' and custom data's contents, which equality compares by value. @override - int get hashCode => Object.hash(id, isAgentReply, text, at, isGenerating, _shown); + int get hashCode => Object.hash(id, isAgentReply, text, at, isGenerating, steps.length); @override String toString() => 'TurnMessage($id, ${isAgentReply ? 'agent' : 'person'}: $text)'; @@ -187,3 +186,16 @@ extension TurnMessages on AgentSession { isConnected: isConnected, ); } + +/// Whether [a] and [b] hold the same JSON-like value: maps and lists compared entry by entry. +bool _sameValue(Object? a, Object? b) => switch ((a, b)) { + (final Map a, final Map b) => + a.length == b.length && + a.entries.every( + (entry) => b.containsKey(entry.key) && _sameValue(entry.value, b[entry.key]), + ), + (final List a, final List b) => + a.length == b.length && + [for (var i = 0; i < a.length; i++) _sameValue(a[i], b[i])].every((same) => same), + _ => a == b, +}; diff --git a/sdks/dart/stream_agents/test/core/conversation_test.dart b/sdks/dart/stream_agents/test/core/conversation_test.dart index b80f5ce3bb..f4af177b64 100644 --- a/sdks/dart/stream_agents/test/core/conversation_test.dart +++ b/sdks/dart/stream_agents/test/core/conversation_test.dart @@ -521,10 +521,32 @@ void main() { expect(round.duration, const Duration(milliseconds: 900)); }); + test('UI being written closes the round even when it names no format', () { + final carding = play([ + (0, '{"type":"responding","turn_id":"t1"}'), + (300, '{"type":"reasoning_delta","turn_id":"t1","text":"A card fits."}'), + (700, '{"type":"ui_delta","turn_id":"t1","delta":"a","format":""}'), + // The next round is timed from the UI, not from when the turn was asked. + (900, '{"type":"reasoning_delta","turn_id":"t1","text":"Now the total."}'), + ]); + + final [first, second] = carding.turns.single.steps.cast(); + expect(first.isStreaming, isFalse); + expect(first.duration, const Duration(milliseconds: 700)); + expect(second.id, 'r2'); + expect(second.at, ms(700)); + expect(carding.turns.single.ui, isNull); + }); + test('a call shows once, even when started again or sharing an id with a round', () { final conversation = play([ (0, '{"type":"responding","turn_id":"t1"}'), (1, '{"type":"reasoning_delta","turn_id":"t1","text":"The weather tool knows."}'), + ( + 2, + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"",' + '"time_to_first_token_ms":90}', + ), (2, '{"type":"tool_started","tool_call_id":"r1","tool":"weather","turn_id":"t1"}'), (3, '{"type":"tool_started","tool_call_id":"r1","tool":"weather","turn_id":"t1"}'), ( diff --git a/sdks/dart/stream_agents/test/core/session_test.dart b/sdks/dart/stream_agents/test/core/session_test.dart index 11a414bcde..6f2fbbad62 100644 --- a/sdks/dart/stream_agents/test/core/session_test.dart +++ b/sdks/dart/stream_agents/test/core/session_test.dart @@ -774,8 +774,13 @@ void main() { ); final socket = await router.socket(); + // The router's order: the reply is answered as waiting on its tools, which then start. socket ..send('{"type":"responding","turn_id":"t1"}') + ..send( + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"",' + '"time_to_first_token_ms":90}', + ) ..send( '{"type":"tool_started","tool_call_id":"c1","tool":"issue_refund","turn_id":"t1",' '"started_at":"2026-11-19T09:00:00Z"}', diff --git a/sdks/dart/stream_agents/test/core/turn_message_test.dart b/sdks/dart/stream_agents/test/core/turn_message_test.dart index 3b4d483455..d7e54d80b5 100644 --- a/sdks/dart/stream_agents/test/core/turn_message_test.dart +++ b/sdks/dart/stream_agents/test/core/turn_message_test.dart @@ -117,6 +117,40 @@ void main() { ); }); + test('a message built again unchanged is equal, and one whose step or card moved is not', () { + final running = play([ + ...toolTurn.take(4), + ( + 1700, + '{"type":"ui_completed","turn_id":"t1","format":"openui","mode":"replace",' + r'"content":"root = Card([])"}', + ), + ], from: asked); + TurnMessage reply(Conversation conversation) => + TurnMessage.messages(conversation, userId: 'ada', isConnected: true).last; + + // Built twice from the same conversation, with maps that are not the same objects. + expect(reply(running), reply(running)); + expect(reply(running).hashCode, reply(running).hashCode); + + final ran = play([ + ( + 2000, + '{"type":"tool_ran","tool_call_id":"call_1","turn_id":"t1","tool":"weather","error":""}', + ), + ], from: running); + expect(reply(ran), isNot(reply(running)), reason: 'the call completed'); + + final recarded = play([ + ( + 1800, + '{"type":"ui_completed","turn_id":"t1","format":"openui","mode":"replace",' + r'"content":"root = Card([Text(\"Sunny\")])"}', + ), + ], from: running); + expect(reply(recarded), isNot(reply(running)), reason: 'the card changed'); + }); + test('a reply with UI carries its latest card as a kept one does', () { final conversation = play([ (10, '{"type":"responding","turn_id":"t1"}'), From a984b36b9af4a22f07a0d5331efe8f323b12201c Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Mon, 23 Nov 2026 13:54:13 +0100 Subject: [PATCH 7/9] refactor(sdk-dart): align incognito steps with Kotlin and Swift, trim docs Steps copy as Kotlin's data classes do; flutter_demo maps turnMessages straight to messages, as swift_assistant and android_assistant do. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk-dart/SKILL.md | 20 ++--- .claude/skills/sdk/SKILL.md | 2 +- CHANGELOG.md | 2 +- .../flutter_demo/lib/agent_chat.dart | 45 +++--------- .../flutter_demo/lib/chat_view.dart | 3 +- .../voice_agents/flutter_demo/lib/main.dart | 1 - sdks/dart/stream_agents/CHANGELOG.md | 9 +-- sdks/dart/stream_agents/README.md | 6 +- .../lib/src/core/conversation.dart | 73 +++++++++---------- .../lib/src/core/turn_message.dart | 46 ++++-------- 10 files changed, 75 insertions(+), 132 deletions(-) diff --git a/.claude/skills/sdk-dart/SKILL.md b/.claude/skills/sdk-dart/SKILL.md index baa8d5ae1e..eab4210cbd 100644 --- a/.claude/skills/sdk-dart/SKILL.md +++ b/.claude/skills/sdk-dart/SKILL.md @@ -181,21 +181,11 @@ is kept working. What the router writes is what it renders: `AIMessage.reasoningText` reads it. - A tool that asks first is answered by an `AIToolApprover` whose `decide` calls `session.decide`; on a call, by an `AIToolApprovalCard` over `session.approvals`. -- An incognito session has no channel, and `chat()` throws. `Conversation` folds the socket's - `reasoning_delta`, `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran` into - `Turn.steps` and `Turn.isDone`, timing a round of thinking from when the turn was asked or - went on writing (a private `_resumedAt`, part of equality as `_uiWritten` is). The router - answers a reply as waiting (`pending_work`) before its tools run, so their steps land on a - turn already answered, and their results carry it on in a turn of its own. The reducer keeps - Kotlin's shape (`_amend`, `_resumed`, `_ended`, `_refused`; `Turn._think`, `_settled`, - `_called`, `_changedCall`), with step types top level (`ReasoningStep`, `ToolCallStep`, - `ToolCallStepStatus`) for want of nested types. `session.turnMessages` (`TurnMessage`, in core) is the conversation in the - channel's shape: one reply per question across its tools' turns, each step the record - `AIMessagePart.parseAll` takes, rounds numbered across the reply, the whole thinking in - `reasoning`, and a call in `approvals` as `awaiting_approval` for the agents' own user - (`backend.userId`), never `Session.userId`, the agent's name on the call. `flutter_demo`'s - `AgentChat.unkept` follows it, rebuilding on `conversation`, `approvals` and `connection`, - and its app bar's lock starts an incognito chat. +- An incognito session has no channel, and `chat()` throws. `Conversation` folds + `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran` into `Turn.steps` and + `Turn.isDone`, as Kotlin's does; `session.turnMessages` gives the channel's message shape, and + a waiting call asks `backend.userId`, not `Session.userId` (the agent's name on the call). + `flutter_demo`'s `AgentChat.unkept` shows it. - `AIConversationView` lays the channel out in turns, `ChatComposer` asks and stops, and `AIVoiceGlowView` / `AIVoiceWaveView` show the agent on a call. diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 8a3fb3a345..570b830875 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -954,7 +954,7 @@ Connections (AI-3376): Go has `client.Connections()` for the accounts the app an Connections in Rust (AI-3383): `Client::connections()` (`sdks/rust/src/connections.rs`) follows Go's shape with the user as `user_id` of each call: `create(&NewConnection{connector, label, user_id})`, `authorize(id, &AuthorizeOptions{return_url, user_id})`, `get(id, user_id: Option<&str>)`, `list(&ConnectionFilter{connector, user_id})`, `delete(id, user_id: Option<&str>)`; options structs rather than adjacent `Option<&str>` so a label cannot be swapped for a user. A user given goes through `pub(crate) Client::acting_for`, so the header matches the call and replaces a `ClientOptions::user_id` the client was built with; no user (or an empty one) leaves the client as built, as Go's `UserID` does (92148e5fe). Rust had no public acting-for helper to deprecate for AI-3387: `Backend` and its `acting_for` field are crate-private (`sdks/rust/src/backend.rs`, not re-exported from `lib.rs`), and `Client::acting_for` is `pub(crate)`. No other SDK needs to change for this. Connections in JavaScript (AI-3378, AI-3387): `api.connections` has `create(connectorId, { label, userId })`, `authorize(id, { returnUrl, userId })`, `get(id, { userId })`, `list({ connectorId, userId })` (every page, 200 a page, newest first) and `delete(id, { userId })`. The user is an optional parameter of each call, never a client of its own: given, it is sent as `owner.user_id` (create) and `X-Stream-User-Id` on every call, reads included, with the app's server credential (an internal `speakingFor(backend, userId)` in `backend.ts`, kept off `Backend`'s type, which Dispatch's `answer` also uses); left out or empty, the call is the app's (`owner.type: app`, `owner_type=app`, no header added). Optional parts are one options object, never adjacent positional strings. `Backend.actingFor` stays public and working, marked `@deprecated` (Chat's "deprecate, never break"), and a test pins its requests to the base commit's. A client built with `BackendOptions.userId` still sends that user on a call without `userId`, as on every other call; one built on the deprecated `actingFor` does not (the call is the app's). A `userId` on a client that is not server side (a device, or a page on a customer-id router) is a `ConfigurationError` before any request. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP (AI-3379..AI-3383). Connections in Python (AI-3379, no spec change): `plugins/stream` has `api.connections` with the Go shape: `create(connector_id, *, label=None, user_id=None)`, `authorize(id, *, return_url=None, user_id=None)` returning `Authorization`, `get(id, *, user_id=None)`, `list(*, connector_id=None, user_id=None)` reading every page, `delete(id, *, user_id=None)`; every option is keyword-only, so a user id cannot land in the label's or connector's slot. A user given is `owner.user_id` (create) and `X-Stream-User-Id` on every call, replacing whoever the client acts for and the user its backend was built for (which behind the proxy would sign that user's own token); none is the app's connection, sent as the client is otherwise (a client built for a user still names that user). AI-3387 in Python: `Client.for_user` is deprecated (`DeprecationWarning`, still working) in favour of a keyword-only `user_id=None`, last, on `Client.agent` and `Client.router`, on a client built with `team=`/`usage_categories=`; a device naming a user is refused before any request. Dispatch and `Accelerated` keep `Backend.acting_for` internally. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`, `ToolCallStepStatus`, top level for want of nested types and named apart from tool groups' `ToolCallStatus`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; like Kotlin, its `target_user_id` is the agents' own user (`backend.userId`), not the session's `user_id`; `flutter_demo`'s `AgentChat` shows an incognito session from them. The server SDKs need nothing. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same (`Turn.steps`, `Turn.isDone`, `session.turnMessages`, each step the record `AIMessagePart.parseAll` takes), its `target_user_id` the agents' own user as in Kotlin; `flutter_demo`'s `AgentChat` shows an incognito session from them. The server SDKs need nothing. An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types, and Kotlin has `SessionOptions.ui`, which `Sessions.create` sends as it is (null left out); Python, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Every server SDK now declares one: Python `register(display_title=...)` (on `ToolPolicy`, sent by `plugins/stream`'s `_with_policy`), .NET `displayTitle:`, Ruby `display_title:`, PHP `displayTitle:` and Rust's `SessionTool.display_title`; Swift, Kotlin and Dart read it off the tool call state. Nothing is left to update. Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Connections.php`) has `create(NewConnection)`, `authorize(id, AuthorizeOptions)`, `get(id, userId)`, `list(ConnectionFilter)` (every page, `limit` 200, a repeated cursor ends it) and `delete(id, userId)`, Go's shape: the calls with more than one optional take an options object (`NewConnection`, `AuthorizeOptions`, `ConnectionFilter`, `sdks/php/src/`) like Go's `ConnectionRequest`, `AuthorizeOptions` and `ConnectionFilter`, so a user id cannot take the place of a label, return URL or connector (R1.1 of the review: `create('linear', 'ada')` had filed the user's account as the app's). `userId` is optional and last (a parameter of `get` and `delete`, a field of the options objects); given, it is `owner.user_id` and `X-Stream-User-Id` with the server credential (a server token behind the proxy, never a user token); left out or empty, `owner.type: app` and no header, whoever the backend otherwise acts for. `Connections` goes through `Backend::speakingFor` (`@internal`, PHP has no package visibility), which drops the backend's own user. `Dispatch::answer` goes through `Backend::writingFor` (`@internal`, `Dispatch.php:193`), which keeps the backend's own user when the writer has none, as `onBehalfOf` did before; `onBehalfOf` calls `writingFor`. `Backend::onBehalfOf` stays public and working, `@deprecated` in favour of the `userId` parameter; PHP's `Backend::actingFor` is unchanged and still signs a user token (the device path), so its name means something else than `actingFor` in Go and JavaScript. No other public PHP wrapper used `onBehalfOf`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 744e4df732..16469a0356 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,7 +74,7 @@ Every server SDK's client has a tool registry for the whole app, and one call ru ### The Dart SDK shows an incognito session -An incognito session has no Stream Chat channel, so `session.chat()` throws and a Flutter app had nothing to show its replies with. `Conversation` now folds the socket's `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran` into each turn's `steps` (`ReasoningStep`, `ToolCallStep`) and `isDone`, timing a round of reasoning from when the model was asked or went on writing, and an `error` with code `prompt_injection` clears the reply being written of its text and UI. `session.turnMessages` is the conversation in the shape a kept one has in Chat, its steps as the records `AIMessagePart.parseAll` reads, and a call waiting for approval asks the agents' own user. `AgentEventKind` gains `reasoningDelta`, so an exhaustive `switch` over it needs the case. `flutter_demo` has an incognito toggle in the Chat tab's app bar. +An incognito session has no Stream Chat channel, so a Flutter app had nothing to show its replies with. `Turn` now has `steps` (rounds of thinking and tool calls) and `isDone`, from the socket, and `session.turnMessages` is the conversation in the shape Stream's AI components read, a waiting call's approval card included. `AgentEventKind` gains `reasoningDelta`, so an exhaustive `switch` over it needs the case. `flutter_demo` has an incognito toggle. ### The Swift SDK shows an incognito session diff --git a/examples/voice_agents/flutter_demo/lib/agent_chat.dart b/examples/voice_agents/flutter_demo/lib/agent_chat.dart index 6169c74517..34fe6b6062 100644 --- a/examples/voice_agents/flutter_demo/lib/agent_chat.dart +++ b/examples/voice_agents/flutter_demo/lib/agent_chat.dart @@ -12,15 +12,14 @@ import 'package:stream_agents/stream_agents.dart'; /// of reasoning and each tool call) as attachments. The session's socket is what runs this /// phone's tools and carries the person's answers to the ones that ask first. /// -/// An incognito session keeps no channel, so it is shown from its socket instead: the -/// session's `turnMessages`, which are the conversation in the channel's shape. +/// An incognito session keeps no channel: its messages are its socket's `turnMessages`. class AgentChat with AIConversationTransport { AgentChat._(this.session, stream.Channel? channel) : _channel = channel, _kept = channel != null; - /// Opens the session's channel and starts following it, or follows the session's socket - /// alone when it keeps no channel, as an incognito one does. + /// Opens the session's channel and starts following it, or follows its socket alone when it + /// keeps no channel. /// /// The session is closed if its channel cannot be opened, so it does not run on with /// nobody to show it. @@ -66,7 +65,6 @@ class AgentChat with AIConversationTransport { final AgentSession session; stream.Channel? _channel; - /// Whether the conversation is kept in a channel, rather than shown from the socket alone. final bool _kept; /// Why the session's socket stopped, or null: tools and approvals stop until a new @@ -86,30 +84,13 @@ class AgentChat with AIConversationTransport { var _unanswered = false; var _closed = false; - var _unkeptShown = const []; - /// The messages as Stream's AI components show them. List get listMessages => _kept ? listed(_channel?.state?.messages ?? const [], reasoning, shown: _shown) - : _unkeptShown = listedTurns(session.turnMessages, shown: _unkeptShown); - - /// The [messages] of a session that keeps no channel as Stream's AI components show them, - /// without the replies that ended with nothing written, reusing those in [shown] that did - /// not change. - static List listedTurns( - List messages, { - List shown = const [], - }) { - final known = {for (final message in shown) message.id: message}; - return [ - for (final message in messages) - if (!message.isUnwrittenReply) - if (known[message.id] case final same? when same._turn == message) - same - else + : [ + for (final message in session.turnMessages) AgentMessage.unkept(message), - ]; - } + ]; /// The [messages] as Stream's AI components show them, oldest first, without those deleted /// and without the replies that ended with nothing written, reusing those in [shown]. @@ -306,14 +287,8 @@ extension AgentReply on stream.Message { ]); } -/// Whether this is a reply the agent ended without writing anything: no text and no steps. -extension UnwrittenTurnReply on TurnMessage { - bool get isUnwrittenReply => - isAgentReply && !isGenerating && text.isEmpty && steps.isEmpty; -} - -/// A message of the conversation as Stream's AI components show it: one of the channel's, or, -/// for a session that keeps no channel, one built from its socket. +/// A message of the conversation as Stream's AI components show it: the channel's, or an +/// incognito session's. class AgentMessage with AIMessage { AgentMessage(stream.Message this.message, LiveReasoning this._reasoning) : _turn = null, @@ -325,7 +300,7 @@ class AgentMessage with AIMessage { isGenerating = message.isGenerating, parts = message.steps; - /// A message of a session that keeps no channel, an incognito one, from its socket. + /// An incognito session's message, from its socket. AgentMessage.unkept(TurnMessage this._turn) : message = null, _reasoning = null, @@ -374,7 +349,7 @@ class AgentMessage with AIMessage { ]; /// A step keeps only the opening of its thinking; the whole of it came with the live - /// updates, while the reply was being written. One built from the socket holds all of it. + /// updates, while the reply was being written. An incognito one holds all of it. @override String? reasoningText(AIReasoningPart step) => switch (_turn) { final turn? => turn.reasoning[step.id], diff --git a/examples/voice_agents/flutter_demo/lib/chat_view.dart b/examples/voice_agents/flutter_demo/lib/chat_view.dart index f16b63a02e..33bfe1c5ce 100644 --- a/examples/voice_agents/flutter_demo/lib/chat_view.dart +++ b/examples/voice_agents/flutter_demo/lib/chat_view.dart @@ -18,8 +18,7 @@ import 'notice.dart'; /// writing is that the reply shows its working, with Stream's AI components: the agent's /// reasoning as it thinks, each tool call as it runs, and a question when a tool asks first. /// -/// An [incognito] conversation is kept nowhere: it has no channel, is never listed, and is -/// shown from the session's socket. +/// An [incognito] conversation keeps no channel and is never listed. class ChatView extends StatefulWidget { const ChatView({super.key, this.incognito = false}); diff --git a/examples/voice_agents/flutter_demo/lib/main.dart b/examples/voice_agents/flutter_demo/lib/main.dart index f0d0802ea0..9489963b1a 100644 --- a/examples/voice_agents/flutter_demo/lib/main.dart +++ b/examples/voice_agents/flutter_demo/lib/main.dart @@ -109,7 +109,6 @@ class _HomePageState extends State { index: _tab, sizing: StackFit.expand, children: [ - // A new conversation each time incognito is switched. ChatView(key: ValueKey(_incognito), incognito: _incognito), VoiceView(style: _voiceStyle), ], diff --git a/sdks/dart/stream_agents/CHANGELOG.md b/sdks/dart/stream_agents/CHANGELOG.md index 549043198c..7507adcada 100644 --- a/sdks/dart/stream_agents/CHANGELOG.md +++ b/sdks/dart/stream_agents/CHANGELOG.md @@ -24,11 +24,10 @@ while it runs, such as "Comparing 40 flights", otherwise its display title, such as "Checking the weather", falling back to the tool's name. - `session.toolCallsForTurn(turnId)` - the calls one agent turn made, to show under its message. -- `session.turnMessages` and `TurnMessage` - an incognito session, which has no channel, in the - shape a kept one has in Stream Chat, for Stream's AI components. -- `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone` - each reply's rounds of - thinking and tool calls, folded from the socket's `reasoning_delta`, `tool_started`, - `tool_updated` and `tool_ran`. A reply the prompt injection screen refused loses its text and UI. +- `session.turnMessages` and `TurnMessage` - an incognito session's conversation, for Stream's AI + components. +- `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone` - a reply's thinking and tool + calls, from the socket. ## 0.7.0 diff --git a/sdks/dart/stream_agents/README.md b/sdks/dart/stream_agents/README.md index 7484942b27..bc331bee6c 100644 --- a/sdks/dart/stream_agents/README.md +++ b/sdks/dart/stream_agents/README.md @@ -172,10 +172,8 @@ Import `stream_chat` with a prefix: it exports a `TokenProvider` of its own. Asking an incognito session for its channel throws a `StateError`, since it keeps none. -Show an incognito session from its socket instead: `session.turnMessages` is the conversation -in the channel's shape, one reply per question with its steps as attachment payloads, the whole -of each round of thinking, and a call waiting in `approvals` asking on its step. Build it again -whenever `conversation`, `approvals` or `connection` changes: +Show an incognito session from its socket instead: `session.turnMessages` is the conversation in +the channel's shape. Read it again whenever `conversation`, `approvals` or `connection` changes: ```dart final session = await agents.agent('support').chat(const SessionOptions(incognito: true)); diff --git a/sdks/dart/stream_agents/lib/src/core/conversation.dart b/sdks/dart/stream_agents/lib/src/core/conversation.dart index 1e9e07186e..3171fb2b47 100644 --- a/sdks/dart/stream_agents/lib/src/core/conversation.dart +++ b/sdks/dart/stream_agents/lib/src/core/conversation.dart @@ -105,13 +105,10 @@ final class Turn { final DateTime at; final TurnUI? ui; - /// What the agent did on its way to the turn's text, in order: each round of the model's - /// thinking on a written reply, and each tool it called. Empty on a participant's turn. + /// The agent's rounds of thinking and tool calls, in order. Empty on a participant's turn. final List steps; - /// Whether the agent is done with the turn: it answered with no tools or work left to come, - /// or it was interrupted. A turn whose tools are still running is not. Never set on a - /// participant's turn. + /// Whether the agent answered with nothing left to come, or was cut off. final bool isDone; Turn _withText(String text) => _copy(text: text); @@ -129,12 +126,16 @@ final class Turn { isDone: isDone ?? this.isDone, ); - /// This turn with [delta] added to the round of thinking under way, or to a new one when the - /// model did something else since: every round is numbered from `r1`, as a kept reply's steps - /// are. + /// Adds [delta] to the round under way, or starts the next one, numbered from `r1` as a kept + /// reply's steps are. Turn _think(String delta, DateTime began) { if (steps.lastOrNull case final ReasoningStep round when round.isStreaming) { - return _copy(steps: [...steps.take(steps.length - 1), round._withText(round.text + delta)]); + return _copy( + steps: [ + ...steps.take(steps.length - 1), + round._copy(text: round.text + delta), + ], + ); } final rounds = steps.whereType().length; return _copy( @@ -145,21 +146,23 @@ final class Turn { ); } - /// This turn with its round of thinking under way completed, or itself when none is. Turn _settled(DateTime now) { if (steps.lastOrNull case final ReasoningStep round when round.isStreaming) { - return _copy(steps: [...steps.take(steps.length - 1), round._completed(now)]); + return _copy( + steps: [ + ...steps.take(steps.length - 1), + round._copy(isStreaming: false, duration: now.difference(round.at)), + ], + ); } return this; } - /// This turn with [call] begun, or itself when it already shows that call. A round of - /// thinking's id is ours, `r1` and on, so a call the provider gave the same id is another step. + /// A provider may give a call a round's id (`r1`), so only calls are compared. Turn _called(ToolCallStep call) => steps.any((step) => step is ToolCallStep && step.id == call.id) ? this : _copy(steps: [...steps, call]); - /// This turn with its running call [id] changed as [change] says, or itself when it has none. Turn _changedCall(String id, ToolCallStep Function(ToolCallStep) change) { final index = steps.indexWhere( (step) => step is ToolCallStep && step.id == id && step.status == ToolCallStepStatus.running, @@ -219,20 +222,21 @@ final class ReasoningStep extends TurnStep { /// The thinking so far. final String text; - /// When the model began on it: when it was asked, or took the reply up again after writing, - /// as a kept reply's step is timed. Not when its first words arrived, which a model that - /// sends its thinking in one burst sends only at the end. + /// When the model was asked or went on writing, as a kept reply's step is timed, not when its + /// first words arrived. @override final DateTime at; /// How long the model thought, once it is done. final Duration? duration; - ReasoningStep _withText(String text) => - ReasoningStep(id: id, isStreaming: isStreaming, text: text, at: at, duration: duration); - - ReasoningStep _completed(DateTime now) => - ReasoningStep(id: id, isStreaming: false, text: text, at: at, duration: now.difference(at)); + ReasoningStep _copy({bool? isStreaming, String? text, Duration? duration}) => ReasoningStep( + id: id, + isStreaming: isStreaming ?? this.isStreaming, + text: text ?? this.text, + at: at, + duration: duration ?? this.duration, + ); @override bool operator ==(Object other) => @@ -269,7 +273,7 @@ final class ToolCallStep extends TurnStep { final String name; final ToolCallStepStatus status; - /// What whoever runs it last said about how it is going (`tool_updated`), or the empty string. + /// The last `tool_updated` text that is not to be said verbatim, or empty. final String summary; @override @@ -278,7 +282,7 @@ final class ToolCallStep extends TurnStep { /// How long it ran, once it is no longer running. final Duration? duration; - ToolCallStep _with({ToolCallStepStatus? status, String? summary, Duration? duration}) => + ToolCallStep _copy({ToolCallStepStatus? status, String? summary, Duration? duration}) => ToolCallStep( id: id, name: name, @@ -389,8 +393,7 @@ final class Conversation { /// What each turn's UI block has written so far, unmerged, until the turn's UI is settled. final Map _uiWritten; - /// When the model last took each agent turn in flight up again, by turn id: when it was asked, - /// or went on after writing. A round of thinking is timed from it. + /// When each agent turn in flight was asked or went on writing, which times its next round. final Map _resumedAt; /// Whatever the caller typed, shown before the router has confirmed hearing it. @@ -495,7 +498,7 @@ final class Conversation { return _amend( event.turnId, (turn) => - turn._changedCall(_text(event['id']), (call) => call._with(summary: event.text)), + turn._changedCall(_text(event['id']), (call) => call._copy(summary: event.text)), ); case AgentEventKind.toolRan: @@ -506,7 +509,7 @@ final class Conversation { event.turnId, (turn) => turn._changedCall( _text(event['tool_call_id']), - (call) => call._with(status: status, duration: now.difference(call.at)), + (call) => call._copy(status: status, duration: now.difference(call.at)), ), ); @@ -623,8 +626,7 @@ final class Conversation { return _with(turns: changed); } - /// Applies [change] to the agent turn [turnId]. A turn this never saw begin is started at - /// [startingAt] when the event begins something, and left alone when it is null. + /// Changes agent turn [turnId], starting it at [startingAt] if this never saw it begin. Conversation _amend(String turnId, Turn Function(Turn) change, {DateTime? startingAt}) { final index = turns.lastIndexWhere((turn) => turn.id == turnId && turn.speaker.isAgent); if (index == -1) { @@ -641,7 +643,6 @@ final class Conversation { return _with(turns: [...turns]..[index] = changed); } - /// This conversation with the agent turn [turnId] taken up again [at], or done with for null. Conversation _resumed(String turnId, DateTime? at) { if (at == null) { return _resumedAt.containsKey(turnId) @@ -651,17 +652,14 @@ final class Conversation { return _with(resumedAt: {..._resumedAt, turnId: at}); } - /// The agent turn [turnId] with nothing more of it to come: its round of thinking and its UI - /// settled, and the turn done. Conversation _ended(String turnId, DateTime now) => _settleUI(turnId, now)._resumed(turnId, null)._amend(turnId, (turn) { final settledTurn = turn._settled(now); return settledTurn.isDone ? settledTurn : settledTurn._copy(isDone: true); }); - /// The prompt injection screen refused the reply being written. What it streamed before the - /// verdict is not the answer, so its text and UI go, as they do from the kept conversation; - /// its thinking and tool calls stay. + /// What a refused reply streamed is not the answer: its text and UI go, as from a kept + /// conversation, and its steps stay. Conversation _refused() { final index = turns.lastIndexWhere((turn) => turn.speaker.isAgent); if (index == -1 || turns[index].isDone) return this; @@ -764,8 +762,7 @@ final class Conversation { ); /// The UI written so far counts, or a delta that shows nothing new would be lost to a holder - /// that skips equal values, and the next one would land on stale text. So does when each turn - /// was taken up again, which times the next round of thinking. + /// that skips equal values, and the next one would land on stale text. So does [_resumedAt]. @override bool operator ==(Object other) => other is Conversation && diff --git a/sdks/dart/stream_agents/lib/src/core/turn_message.dart b/sdks/dart/stream_agents/lib/src/core/turn_message.dart index 6296438ef8..b105f06e49 100644 --- a/sdks/dart/stream_agents/lib/src/core/turn_message.dart +++ b/sdks/dart/stream_agents/lib/src/core/turn_message.dart @@ -1,14 +1,11 @@ import 'agent_session.dart'; import 'conversation.dart'; -/// A message of a conversation kept in no channel, an incognito session's, in the shape a kept -/// one has in Stream Chat, so an app shows both alike with Stream's AI components. +/// A message of an incognito session, which keeps no channel, in the shape a kept one has in +/// Stream Chat, so Stream's AI components show both alike. /// -/// Each of the person's turns is a message, and the agent's turns between two of them are one -/// reply, as the router writes a reply whose tools it waited on: their text, the latest UI, and -/// each round of thinking and each tool call as a step, generating until the agent is done with -/// it. A call waiting in the session's `approvals` asks its user on its step, as a kept reply's -/// does. +/// The agent's turns between two of the person's are one reply, as the router writes a reply +/// whose tools it waited on. final class TurnMessage { TurnMessage._({ required this.id, @@ -34,25 +31,21 @@ final class TurnMessage { /// Whether the agent is still writing it. final bool isGenerating; - /// The reply's steps, in order, as a kept reply's attachments hold them: an `ai_reasoning` - /// for each round of thinking, numbered from `r1` across the reply, and an `ai_tool_call` for - /// each call. Stream Chat's `AIMessagePart.parseAll` reads them as they are. + /// The reply's `ai_reasoning` and `ai_tool_call` steps, in order, as `AIMessagePart.parseAll` + /// reads them. Rounds are numbered from `r1` across the reply. final List<({String type, Map payload})> steps; /// The whole of each round of thinking, by its step's id. final Map reasoning; - /// The reply's custom data as a kept one holds it: its UI under `ai_ui`, which - /// `AIUIDocument.fromCustomData` reads, or nothing. + /// The reply's UI under `ai_ui`, as a kept one holds it, or nothing. final Map customData; /// The messages of [conversation], oldest first. /// - /// [approvals] are the calls waiting for the person, each of which asks on its step. [userId] - /// is the person the session is with, whom a waiting call asks: the agents' own user, which an - /// `AIToolApprover` matches against `target_user_id`, not the session's `userId`, which is the - /// name the agent joined the call as. The latest reply is written only while [isConnected], - /// whether the session's socket still carries the conversation. + /// A call in [approvals] asks [userId] on its step: the person, whom `AIToolApprover` matches, + /// not `Session.userId`, the agent's name on the call. Only the latest reply is generating, + /// and only while [isConnected]. static List messages( Conversation conversation, { List approvals = const [], @@ -69,8 +62,6 @@ final class TurnMessage { } return [ for (final (index, turns) in groups.indexed) - // Only the latest reply can still be written: one the person asked over is as it was - // left. _of( turns, isGenerating: index == groups.length - 1 && isConnected && !turns.last.isDone, @@ -95,7 +86,6 @@ final class TurnMessage { for (final step in turns.expand((turn) => turn.steps)) { switch (step) { case ReasoningStep(): - // Numbered across the reply, which a tool's result carries on in a turn of its own. final id = 'r${reasoning.length + 1}'; reasoning[id] = step.text; steps.add(( @@ -136,7 +126,6 @@ final class TurnMessage { ); } - /// The question a waiting call asks, as its step in Stream Chat holds it. static Map _approval(ToolApprovalRequest waiting) => { 'title': waiting.approval.title, if (waiting.approval.message case final message? when message.isNotEmpty) 'message': message, @@ -146,8 +135,7 @@ final class TurnMessage { 'decline_title': title, }; - /// Equal when it shows the same, its steps, thinking and custom data compared by value, so a - /// view can keep a message that did not change. + /// Equal when it shows the same, its maps compared by value. @override bool operator ==(Object other) => other is TurnMessage && @@ -165,7 +153,6 @@ final class TurnMessage { _sameValue(other.steps[i].payload, steps[i].payload), ].every((same) => same); - /// Leaves out the steps' and custom data's contents, which equality compares by value. @override int get hashCode => Object.hash(id, isAgentReply, text, at, isGenerating, steps.length); @@ -173,12 +160,12 @@ final class TurnMessage { String toString() => 'TurnMessage($id, ${isAgentReply ? 'agent' : 'person'}: $text)'; } -/// The conversation as messages, for a session kept in no channel. +/// An incognito session's conversation as messages. extension TurnMessages on AgentSession { - /// The conversation as messages, for a session kept in no channel, an incognito one, to show - /// with Stream's AI components; a kept session's messages are its channel's (`chat()`). Build - /// it again whenever [AgentSession.conversation], [AgentSession.approvals] or - /// [AgentSession.connection] changes. A waiting call asks the agents' own user. + /// The conversation as messages, for a session with no channel. + /// + /// Read it again when [AgentSession.conversation], [AgentSession.approvals] or + /// [AgentSession.connection] changes. List get turnMessages => TurnMessage.messages( conversation.value, approvals: approvals.value, @@ -187,7 +174,6 @@ extension TurnMessages on AgentSession { ); } -/// Whether [a] and [b] hold the same JSON-like value: maps and lists compared entry by entry. bool _sameValue(Object? a, Object? b) => switch ((a, b)) { (final Map a, final Map b) => a.length == b.length && From daf56b082c27b42cd1b336a31d93210e0d4481f3 Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Mon, 23 Nov 2026 15:08:21 +0100 Subject: [PATCH 8/9] fix(sdk-dart): incognito demo drops an unwritten reply; review notes The flutter_demo's incognito path leaves out a reply that ended with no text and no steps, as the kept path does. The sdk skill notes that Swift and JavaScript should send the person's user as target_user_id. Docs on TurnMessage.text and ToolCallStep.status, the PR number in the CHANGELOG, and the multi-behaviour tests split one behaviour each. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk/SKILL.md | 2 +- CHANGELOG.md | 2 +- .../flutter_demo/lib/agent_chat.dart | 9 +- .../flutter_demo/test/agent_chat_test.dart | 38 +++++++ .../lib/src/core/conversation.dart | 2 + .../lib/src/core/turn_message.dart | 3 + .../test/core/conversation_test.dart | 55 ++++++----- .../stream_agents/test/core/session_test.dart | 98 +++++++++++-------- .../test/core/turn_message_test.dart | 17 +++- 9 files changed, 157 insertions(+), 69 deletions(-) diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 570b830875..9c7afca722 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -954,7 +954,7 @@ Connections (AI-3376): Go has `client.Connections()` for the accounts the app an Connections in Rust (AI-3383): `Client::connections()` (`sdks/rust/src/connections.rs`) follows Go's shape with the user as `user_id` of each call: `create(&NewConnection{connector, label, user_id})`, `authorize(id, &AuthorizeOptions{return_url, user_id})`, `get(id, user_id: Option<&str>)`, `list(&ConnectionFilter{connector, user_id})`, `delete(id, user_id: Option<&str>)`; options structs rather than adjacent `Option<&str>` so a label cannot be swapped for a user. A user given goes through `pub(crate) Client::acting_for`, so the header matches the call and replaces a `ClientOptions::user_id` the client was built with; no user (or an empty one) leaves the client as built, as Go's `UserID` does (92148e5fe). Rust had no public acting-for helper to deprecate for AI-3387: `Backend` and its `acting_for` field are crate-private (`sdks/rust/src/backend.rs`, not re-exported from `lib.rs`), and `Client::acting_for` is `pub(crate)`. No other SDK needs to change for this. Connections in JavaScript (AI-3378, AI-3387): `api.connections` has `create(connectorId, { label, userId })`, `authorize(id, { returnUrl, userId })`, `get(id, { userId })`, `list({ connectorId, userId })` (every page, 200 a page, newest first) and `delete(id, { userId })`. The user is an optional parameter of each call, never a client of its own: given, it is sent as `owner.user_id` (create) and `X-Stream-User-Id` on every call, reads included, with the app's server credential (an internal `speakingFor(backend, userId)` in `backend.ts`, kept off `Backend`'s type, which Dispatch's `answer` also uses); left out or empty, the call is the app's (`owner.type: app`, `owner_type=app`, no header added). Optional parts are one options object, never adjacent positional strings. `Backend.actingFor` stays public and working, marked `@deprecated` (Chat's "deprecate, never break"), and a test pins its requests to the base commit's. A client built with `BackendOptions.userId` still sends that user on a call without `userId`, as on every other call; one built on the deprecated `actingFor` does not (the call is the app's). A `userId` on a client that is not server side (a device, or a page on a customer-id router) is a `ConfigurationError` before any request. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP (AI-3379..AI-3383). Connections in Python (AI-3379, no spec change): `plugins/stream` has `api.connections` with the Go shape: `create(connector_id, *, label=None, user_id=None)`, `authorize(id, *, return_url=None, user_id=None)` returning `Authorization`, `get(id, *, user_id=None)`, `list(*, connector_id=None, user_id=None)` reading every page, `delete(id, *, user_id=None)`; every option is keyword-only, so a user id cannot land in the label's or connector's slot. A user given is `owner.user_id` (create) and `X-Stream-User-Id` on every call, replacing whoever the client acts for and the user its backend was built for (which behind the proxy would sign that user's own token); none is the app's connection, sent as the client is otherwise (a client built for a user still names that user). AI-3387 in Python: `Client.for_user` is deprecated (`DeprecationWarning`, still working) in favour of a keyword-only `user_id=None`, last, on `Client.agent` and `Client.router`, on a client built with `team=`/`usage_categories=`; a device naming a user is refused before any request. Dispatch and `Accelerated` keep `Backend.acting_for` internally. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same (`Turn.steps`, `Turn.isDone`, `session.turnMessages`, each step the record `AIMessagePart.parseAll` takes), its `target_user_id` the agents' own user as in Kotlin; `flutter_demo`'s `AgentChat` shows an incognito session from them. The server SDKs need nothing. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same (`Turn.steps`, `Turn.isDone`, `session.turnMessages`, each step the record `AIMessagePart.parseAll` takes), its `target_user_id` the agents' own user as in Kotlin; `flutter_demo`'s `AgentChat` shows an incognito session from them. Other SDKs need to update: Swift and JavaScript should send the person's user (the one the app signed in as) as `target_user_id`, as Kotlin and Dart do, not `Session.userId`. The server SDKs need nothing. An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types, and Kotlin has `SessionOptions.ui`, which `Sessions.create` sends as it is (null left out); Python, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Every server SDK now declares one: Python `register(display_title=...)` (on `ToolPolicy`, sent by `plugins/stream`'s `_with_policy`), .NET `displayTitle:`, Ruby `display_title:`, PHP `displayTitle:` and Rust's `SessionTool.display_title`; Swift, Kotlin and Dart read it off the tool call state. Nothing is left to update. Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Connections.php`) has `create(NewConnection)`, `authorize(id, AuthorizeOptions)`, `get(id, userId)`, `list(ConnectionFilter)` (every page, `limit` 200, a repeated cursor ends it) and `delete(id, userId)`, Go's shape: the calls with more than one optional take an options object (`NewConnection`, `AuthorizeOptions`, `ConnectionFilter`, `sdks/php/src/`) like Go's `ConnectionRequest`, `AuthorizeOptions` and `ConnectionFilter`, so a user id cannot take the place of a label, return URL or connector (R1.1 of the review: `create('linear', 'ada')` had filed the user's account as the app's). `userId` is optional and last (a parameter of `get` and `delete`, a field of the options objects); given, it is `owner.user_id` and `X-Stream-User-Id` with the server credential (a server token behind the proxy, never a user token); left out or empty, `owner.type: app` and no header, whoever the backend otherwise acts for. `Connections` goes through `Backend::speakingFor` (`@internal`, PHP has no package visibility), which drops the backend's own user. `Dispatch::answer` goes through `Backend::writingFor` (`@internal`, `Dispatch.php:193`), which keeps the backend's own user when the writer has none, as `onBehalfOf` did before; `onBehalfOf` calls `writingFor`. `Backend::onBehalfOf` stays public and working, `@deprecated` in favour of the `userId` parameter; PHP's `Backend::actingFor` is unchanged and still signs a user token (the device path), so its name means something else than `actingFor` in Go and JavaScript. No other public PHP wrapper used `onBehalfOf`. diff --git a/CHANGELOG.md b/CHANGELOG.md index 16469a0356..41411fcd4a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,7 +74,7 @@ Every server SDK's client has a tool registry for the whole app, and one call ru ### The Dart SDK shows an incognito session -An incognito session has no Stream Chat channel, so a Flutter app had nothing to show its replies with. `Turn` now has `steps` (rounds of thinking and tool calls) and `isDone`, from the socket, and `session.turnMessages` is the conversation in the shape Stream's AI components read, a waiting call's approval card included. `AgentEventKind` gains `reasoningDelta`, so an exhaustive `switch` over it needs the case. `flutter_demo` has an incognito toggle. +An incognito session has no Stream Chat channel, so a Flutter app had nothing to show its replies with. `Turn` now has `steps` (rounds of thinking and tool calls) and `isDone`, from the socket, and `session.turnMessages` is the conversation in the shape Stream's AI components read, a waiting call's approval card included. `AgentEventKind` gains `reasoningDelta`, so an exhaustive `switch` over it needs the case. `flutter_demo` has an incognito toggle (#2200). ### The Swift SDK shows an incognito session diff --git a/examples/voice_agents/flutter_demo/lib/agent_chat.dart b/examples/voice_agents/flutter_demo/lib/agent_chat.dart index 34fe6b6062..ccc334287d 100644 --- a/examples/voice_agents/flutter_demo/lib/agent_chat.dart +++ b/examples/voice_agents/flutter_demo/lib/agent_chat.dart @@ -89,7 +89,7 @@ class AgentChat with AIConversationTransport { ? listed(_channel?.state?.messages ?? const [], reasoning, shown: _shown) : [ for (final message in session.turnMessages) - AgentMessage.unkept(message), + if (!message.isUnwrittenReply) AgentMessage.unkept(message), ]; /// The [messages] as Stream's AI components show them, oldest first, without those deleted @@ -287,6 +287,13 @@ extension AgentReply on stream.Message { ]); } +extension UnkeptReply on TurnMessage { + /// Whether this is a reply the agent ended without writing anything, as + /// [AgentReply.isUnwrittenReply] is for a kept one. + bool get isUnwrittenReply => + isAgentReply && !isGenerating && text.isEmpty && steps.isEmpty; +} + /// A message of the conversation as Stream's AI components show it: the channel's, or an /// incognito session's. class AgentMessage with AIMessage { diff --git a/examples/voice_agents/flutter_demo/test/agent_chat_test.dart b/examples/voice_agents/flutter_demo/test/agent_chat_test.dart index 79c53d495c..fd57476643 100644 --- a/examples/voice_agents/flutter_demo/test/agent_chat_test.dart +++ b/examples/voice_agents/flutter_demo/test/agent_chat_test.dart @@ -414,6 +414,44 @@ void main() { }, ); + test( + 'leaves out a reply with no channel that ended with nothing written, as a kept one is', + () async { + final router = await _Router.start(); + addTearDown(router.close); + final agents = StreamAgents( + url: router.url, + customerId: 'acme', + userId: 'ada', + ); + addTearDown(agents.close); + final session = await agents.attach('s1'); + final chat = closing(AgentChat.unkept(session)); + final conversation = conversationOf(chat); + final socket = await router.socket; + + conversation.send('Read me this page'); + await _until(() => router.asked == 1); + // A model that answered with nothing: no error, no text and no steps. + socket + ..send('{"type":"responding","turn_id":"t1"}') + ..send( + '{"pending_work":false,"type":"responded","turn_id":"t1",' + '"text":"","time_to_first_token_ms":90}', + ); + await _until( + () => + session.turnMessages.last.isAgentReply && + !session.turnMessages.last.isGenerating, + ); + + expect( + [for (final m in chat.listMessages) m.role], + [AIMessageRole.user], + ); + }, + ); + test('close disposes the watched channel', () async { final channel = channelOf([_question('q0')]); final chat = AgentChat.following(session, channel); diff --git a/sdks/dart/stream_agents/lib/src/core/conversation.dart b/sdks/dart/stream_agents/lib/src/core/conversation.dart index 3171fb2b47..10e2a0574e 100644 --- a/sdks/dart/stream_agents/lib/src/core/conversation.dart +++ b/sdks/dart/stream_agents/lib/src/core/conversation.dart @@ -271,6 +271,8 @@ final class ToolCallStep extends TurnStep { /// The tool. final String name; + + /// Whether it is running, or how it ended. final ToolCallStepStatus status; /// The last `tool_updated` text that is not to be said verbatim, or empty. diff --git a/sdks/dart/stream_agents/lib/src/core/turn_message.dart b/sdks/dart/stream_agents/lib/src/core/turn_message.dart index b105f06e49..d71759d691 100644 --- a/sdks/dart/stream_agents/lib/src/core/turn_message.dart +++ b/sdks/dart/stream_agents/lib/src/core/turn_message.dart @@ -23,6 +23,9 @@ final class TurnMessage { /// Whether the agent wrote it, rather than the person. final bool isAgentReply; + + /// What it says: the person's question, or the reply's text, its turns' text joined by a + /// blank line. final String text; /// When its first turn began. diff --git a/sdks/dart/stream_agents/test/core/conversation_test.dart b/sdks/dart/stream_agents/test/core/conversation_test.dart index f4af177b64..8817a39be0 100644 --- a/sdks/dart/stream_agents/test/core/conversation_test.dart +++ b/sdks/dart/stream_agents/test/core/conversation_test.dart @@ -564,7 +564,7 @@ void main() { expect((steps.last as ToolCallStep).duration, const Duration(milliseconds: 8)); }); - test('a turn is done once it answered with nothing left to come, or was cut off', () { + test('a turn is done once it answered with nothing left to come', () { final answered = play([ (0, '{"type":"responding","turn_id":"t1"}'), ( @@ -573,8 +573,11 @@ void main() { '"time_to_first_token_ms":90}', ), ]); + expect(answered.turns.single.isDone, isTrue); + }); + test('a turn that answered with work still to come is not done', () { final waiting = play([ (0, '{"type":"responding","turn_id":"t1"}'), ( @@ -583,13 +586,17 @@ void main() { '"time_to_first_token_ms":90}', ), ]); + expect(waiting.turns.single.isDone, isFalse); + }); + test('a turn cut off is done, its thinking ended where it was cut', () { final cut = play([ (0, '{"type":"responding","turn_id":"t1"}'), (1, '{"type":"reasoning_delta","turn_id":"t1","text":"Hmm"}'), (5, '{"type":"interrupted","turn_id":"t1","participant":null}'), ]); + expect(cut.turns.single.isDone, isTrue); expect( (cut.turns.single.steps.single as ReasoningStep).duration, @@ -597,28 +604,30 @@ void main() { ); }); - test( - 'progress for a call or a turn never seen changes nothing; thinking starts the turn', - () { - final before = play([(0, '{"type":"responding","turn_id":"t1"}')]); - - for (final json in [ - '{"type":"tool_updated","id":"nope","turn_id":"t1","text":"Working","verbatim":false}', - '{"type":"tool_ran","tool_call_id":"nope","turn_id":"t1","error":""}', - '{"type":"tool_ran","tool_call_id":"c1","turn_id":"t9","error":""}', - '{"type":"reasoning_delta","turn_id":"t1","text":""}', - ]) { - expect(identical(before.apply(frame(json)), before), isTrue, reason: json); - } - - final unseen = before.apply( - frame('{"type":"reasoning_delta","turn_id":"t2","text":"Next."}'), - at: ms(40), - ); - expect(unseen.turns.map((turn) => turn.id), ['t1', 't2']); - expect((unseen.turns.last.steps.single as ReasoningStep).at, ms(40)); - }, - ); + test('progress for a call or a turn never seen changes nothing', () { + final before = play([(0, '{"type":"responding","turn_id":"t1"}')]); + + for (final json in [ + '{"type":"tool_updated","id":"nope","turn_id":"t1","text":"Working","verbatim":false}', + '{"type":"tool_ran","tool_call_id":"nope","turn_id":"t1","error":""}', + '{"type":"tool_ran","tool_call_id":"c1","turn_id":"t9","error":""}', + '{"type":"reasoning_delta","turn_id":"t1","text":""}', + ]) { + expect(identical(before.apply(frame(json)), before), isTrue, reason: json); + } + }); + + test('thinking for a turn never seen starts it', () { + final before = play([(0, '{"type":"responding","turn_id":"t1"}')]); + + final unseen = before.apply( + frame('{"type":"reasoning_delta","turn_id":"t2","text":"Next."}'), + at: ms(40), + ); + + expect(unseen.turns.map((turn) => turn.id), ['t1', 't2']); + expect((unseen.turns.last.steps.single as ReasoningStep).at, ms(40)); + }); test('a reply the prompt injection screen refused loses its text and UI, not its steps', () { final refused = play([ diff --git a/sdks/dart/stream_agents/test/core/session_test.dart b/sdks/dart/stream_agents/test/core/session_test.dart index 6f2fbbad62..60e4c09e2d 100644 --- a/sdks/dart/stream_agents/test/core/session_test.dart +++ b/sdks/dart/stream_agents/test/core/session_test.dart @@ -749,44 +749,50 @@ void main() { await chat.close(); }); + /// A session kept nowhere whose reply waits on the person's answer to a refund. + Future waitingUnkept() async { + // The router's session keeps no conversation: sessionJson's conversation_id is empty. + final chat = await agents + .withUser('ada') + .chat( + SessionOptions( + incognito: true, + tools: [ + AgentTool( + name: 'issue_refund', + description: 'Refund an order.', + approval: const ToolApproval( + title: 'Refund order A-1042?', + reasonArgument: 'reason', + allowTitle: 'Refund', + ), + run: (arguments) async => 'Refunded', + ), + ], + ), + ); + final socket = await router.socket(); + + // The router's order: the reply is answered as waiting on its tools, which then start. + socket + ..send('{"type":"responding","turn_id":"t1"}') + ..send( + '{"pending_work":true,"type":"responded","turn_id":"t1","text":"",' + '"time_to_first_token_ms":90}', + ) + ..send( + '{"type":"tool_started","tool_call_id":"c1","tool":"issue_refund","turn_id":"t1",' + '"started_at":"2026-11-19T09:00:00Z"}', + ) + ..send(refundCall); + await until(() => chat.approvals.value.isNotEmpty); + return chat; + } + test( 'waits on its step of the reply, for the agents\' user, in a conversation kept nowhere', () async { - // The router's session keeps no conversation: sessionJson's conversation_id is empty. - final chat = await agents - .withUser('ada') - .chat( - SessionOptions( - incognito: true, - tools: [ - AgentTool( - name: 'issue_refund', - description: 'Refund an order.', - approval: const ToolApproval( - title: 'Refund order A-1042?', - reasonArgument: 'reason', - allowTitle: 'Refund', - ), - run: (arguments) async => 'Refunded', - ), - ], - ), - ); - final socket = await router.socket(); - - // The router's order: the reply is answered as waiting on its tools, which then start. - socket - ..send('{"type":"responding","turn_id":"t1"}') - ..send( - '{"pending_work":true,"type":"responded","turn_id":"t1","text":"",' - '"time_to_first_token_ms":90}', - ) - ..send( - '{"type":"tool_started","tool_call_id":"c1","tool":"issue_refund","turn_id":"t1",' - '"started_at":"2026-11-19T09:00:00Z"}', - ) - ..send(refundCall); - await until(() => chat.approvals.value.isNotEmpty); + final chat = await waitingUnkept(); final step = chat.turnMessages.last.steps.single; expect(step.type, 'ai_tool_call'); @@ -803,15 +809,27 @@ void main() { 'allow_title': 'Refund', }, }); - - chat.decide('c1', allowed: true); - - expect(chat.turnMessages.last.steps.single.payload['status'], 'running'); await chat.close(); - expect(chat.turnMessages.last.isGenerating, isFalse); }, ); + test('allowed in a conversation kept nowhere, its step runs', () async { + final chat = await waitingUnkept(); + + chat.decide('c1', allowed: true); + + expect(chat.turnMessages.last.steps.single.payload['status'], 'running'); + await chat.close(); + }); + + test('closed while its reply waits, the reply is no longer being written', () async { + final chat = await waitingUnkept(); + + await chat.close(); + + expect(chat.turnMessages.last.isGenerating, isFalse); + }); + test('declined, never runs, tells the model so, and a second answer does nothing', () async { final chat = await open(); final socket = await router.socket(); diff --git a/sdks/dart/stream_agents/test/core/turn_message_test.dart b/sdks/dart/stream_agents/test/core/turn_message_test.dart index d7e54d80b5..732f8836ba 100644 --- a/sdks/dart/stream_agents/test/core/turn_message_test.dart +++ b/sdks/dart/stream_agents/test/core/turn_message_test.dart @@ -87,28 +87,39 @@ void main() { expect(reply.customData, isEmpty); }); - test('only the latest reply is being written, and only while the socket carries it', () { + test('the latest reply is being written while the socket carries it', () { final writing = play([...toolTurn, ...answerTurn], from: asked); expect( TurnMessage.messages(writing, userId: 'ada', isConnected: true).last.isGenerating, isTrue, ); - // Its tools are done but the turn carrying the reply on is not. + }); + + test('a reply whose tools are done is still being written until its next turn is', () { final betweenTurns = play(toolTurn, from: asked); + expect( TurnMessage.messages(betweenTurns, userId: 'ada', isConnected: true).last.isGenerating, isTrue, ); + }); + + test('a reply is not being written once the socket is gone', () { + final writing = play([...toolTurn, ...answerTurn], from: asked); + expect( TurnMessage.messages(writing, userId: 'ada', isConnected: false).last.isGenerating, isFalse, ); + }); - // Asked over mid-thought: the reply before is as it was left. + test('a reply asked over mid-thought is left as it was, no longer being written', () { final thinking = play([...toolTurn, ...answerTurn.take(2)], from: asked); final askedAgain = thinking.said('Never mind.', at: ms(4000)); + final messages = TurnMessage.messages(askedAgain, userId: 'ada', isConnected: true); + expect(messages.map((message) => message.isGenerating), [false, false, false]); expect( messages[1].steps.last.payload['status'], From 190ebf11a28202837369b42560a9cf112316adcc Mon Sep 17 00:00:00 2001 From: VelikovPetar Date: Mon, 23 Nov 2026 19:09:17 +0100 Subject: [PATCH 9/9] docs: follow #2207 for CHANGELOG and SDK notes The Swift and JavaScript target_user_id note moves to .claude/skills/sdk/notes/2026-11-23-target-user-id.md. The sdk skill's reasoning_delta paragraph no longer says Dart still needs to update. The root CHANGELOG keeps one Breaking Changes line for AgentEventKind's new value; the package CHANGELOG is left as main has it. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk/SKILL.md | 7 +------ .claude/skills/sdk/notes/2026-11-23-target-user-id.md | 1 + CHANGELOG.md | 8 ++++---- sdks/dart/stream_agents/CHANGELOG.md | 6 ------ 4 files changed, 6 insertions(+), 16 deletions(-) create mode 100644 .claude/skills/sdk/notes/2026-11-23-target-user-id.md diff --git a/.claude/skills/sdk/SKILL.md b/.claude/skills/sdk/SKILL.md index 9c7afca722..35a9532e67 100644 --- a/.claude/skills/sdk/SKILL.md +++ b/.claude/skills/sdk/SKILL.md @@ -954,7 +954,7 @@ Connections (AI-3376): Go has `client.Connections()` for the accounts the app an Connections in Rust (AI-3383): `Client::connections()` (`sdks/rust/src/connections.rs`) follows Go's shape with the user as `user_id` of each call: `create(&NewConnection{connector, label, user_id})`, `authorize(id, &AuthorizeOptions{return_url, user_id})`, `get(id, user_id: Option<&str>)`, `list(&ConnectionFilter{connector, user_id})`, `delete(id, user_id: Option<&str>)`; options structs rather than adjacent `Option<&str>` so a label cannot be swapped for a user. A user given goes through `pub(crate) Client::acting_for`, so the header matches the call and replaces a `ClientOptions::user_id` the client was built with; no user (or an empty one) leaves the client as built, as Go's `UserID` does (92148e5fe). Rust had no public acting-for helper to deprecate for AI-3387: `Backend` and its `acting_for` field are crate-private (`sdks/rust/src/backend.rs`, not re-exported from `lib.rs`), and `Client::acting_for` is `pub(crate)`. No other SDK needs to change for this. Connections in JavaScript (AI-3378, AI-3387): `api.connections` has `create(connectorId, { label, userId })`, `authorize(id, { returnUrl, userId })`, `get(id, { userId })`, `list({ connectorId, userId })` (every page, 200 a page, newest first) and `delete(id, { userId })`. The user is an optional parameter of each call, never a client of its own: given, it is sent as `owner.user_id` (create) and `X-Stream-User-Id` on every call, reads included, with the app's server credential (an internal `speakingFor(backend, userId)` in `backend.ts`, kept off `Backend`'s type, which Dispatch's `answer` also uses); left out or empty, the call is the app's (`owner.type: app`, `owner_type=app`, no header added). Optional parts are one options object, never adjacent positional strings. `Backend.actingFor` stays public and working, marked `@deprecated` (Chat's "deprecate, never break"), and a test pins its requests to the base commit's. A client built with `BackendOptions.userId` still sends that user on a call without `userId`, as on every other call; one built on the deprecated `actingFor` does not (the call is the app's). A `userId` on a client that is not server side (a device, or a page on a customer-id router) is a `ConfigurationError` before any request. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP (AI-3379..AI-3383). Connections in Python (AI-3379, no spec change): `plugins/stream` has `api.connections` with the Go shape: `create(connector_id, *, label=None, user_id=None)`, `authorize(id, *, return_url=None, user_id=None)` returning `Authorization`, `get(id, *, user_id=None)`, `list(*, connector_id=None, user_id=None)` reading every page, `delete(id, *, user_id=None)`; every option is keyword-only, so a user id cannot land in the label's or connector's slot. A user given is `owner.user_id` (create) and `X-Stream-User-Id` on every call, replacing whoever the client acts for and the user its backend was built for (which behind the proxy would sign that user's own token); none is the app's connection, sent as the client is otherwise (a client built for a user still names that user). AI-3387 in Python: `Client.for_user` is deprecated (`DeprecationWarning`, still working) in favour of a keyword-only `user_id=None`, last, on `Client.agent` and `Client.router`, on a client built with `team=`/`usage_categories=`; a device naming a user is refused before any request. Dispatch and `Accelerated` keep `Backend.acting_for` internally. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same (`Turn.steps`, `Turn.isDone`, `session.turnMessages`, each step the record `AIMessagePart.parseAll` takes), its `target_user_id` the agents' own user as in Kotlin; `flutter_demo`'s `AgentChat` shows an incognito session from them. Other SDKs need to update: Swift and JavaScript should send the person's user (the one the app signed in as) as `target_user_id`, as Kotlin and Dart do, not `Session.userId`. The server SDKs need nothing. +The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Kotlin does the same: `Conversation` folds the frames into `Turn.steps` (`TurnStep.Reasoning`, `TurnStep.ToolCall`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals, userId, isConnected)` (`AgentSession.turnMessages`, a `Flow`) builds the replies, each step an attachment type and plain-Kotlin fields for `AIMessagePart.parts`; its `target_user_id` is the user `setUser` named (`backend.user`), not the session's `user_id`, which is the name the agent joined the call as; `android_assistant`'s `AgentTransport` shows an incognito session from them. Dart does the same (`Turn.steps`, `Turn.isDone`, `session.turnMessages`, each step the record `AIMessagePart.parseAll` takes), its `target_user_id` the agents' own user as in Kotlin; `flutter_demo`'s `AgentChat` shows an incognito session from them. The server SDKs need nothing. An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types, and Kotlin has `SessionOptions.ui`, which `Sessions.create` sends as it is (null left out); Python, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Every server SDK now declares one: Python `register(display_title=...)` (on `ToolPolicy`, sent by `plugins/stream`'s `_with_policy`), .NET `displayTitle:`, Ruby `display_title:`, PHP `displayTitle:` and Rust's `SessionTool.display_title`; Swift, Kotlin and Dart read it off the tool call state. Nothing is left to update. Connections in PHP (AI-3381, AI-3387): `$client->connections` (`sdks/php/src/Connections.php`) has `create(NewConnection)`, `authorize(id, AuthorizeOptions)`, `get(id, userId)`, `list(ConnectionFilter)` (every page, `limit` 200, a repeated cursor ends it) and `delete(id, userId)`, Go's shape: the calls with more than one optional take an options object (`NewConnection`, `AuthorizeOptions`, `ConnectionFilter`, `sdks/php/src/`) like Go's `ConnectionRequest`, `AuthorizeOptions` and `ConnectionFilter`, so a user id cannot take the place of a label, return URL or connector (R1.1 of the review: `create('linear', 'ada')` had filed the user's account as the app's). `userId` is optional and last (a parameter of `get` and `delete`, a field of the options objects); given, it is `owner.user_id` and `X-Stream-User-Id` with the server credential (a server token behind the proxy, never a user token); left out or empty, `owner.type: app` and no header, whoever the backend otherwise acts for. `Connections` goes through `Backend::speakingFor` (`@internal`, PHP has no package visibility), which drops the backend's own user. `Dispatch::answer` goes through `Backend::writingFor` (`@internal`, `Dispatch.php:193`), which keeps the backend's own user when the writer has none, as `onBehalfOf` did before; `onBehalfOf` calls `writingFor`. `Backend::onBehalfOf` stays public and working, `@deprecated` in favour of the `userId` parameter; PHP's `Backend::actingFor` is unchanged and still signs a user token (the device path), so its name means something else than `actingFor` in Go and JavaScript. No other public PHP wrapper used `onBehalfOf`. @@ -967,8 +967,3 @@ A device naming a user on a connections call (AI-3412): the router answers every `agent.yaml`'s `greeting` may be its text alone, `greeting: Hello, how can I help?`, read as `{text, mode: variation}`; the mapping still says `exact`, and a mapping without `mode` is now `variation` too, so a folder loader always sends `mode`. The API's own default stays `exact`. Go is done (`GreetingSettings.UnmarshalYAML` in `sdks/go/agents/folder.go`). Other SDKs need to update: the folder loaders of JavaScript (`sdks/js/src/folder.ts`, `greeting()`), Python (`plugins/stream` `folder.py`, `_greeting`), .NET, Ruby, Rust and PHP should take the string form and default a missing `mode` to `variation`. Calls have an id of their own and a `session_id`: a session starts a new call each time voice is started or stopped on it, and an incognito session keeps none, so a session id is no longer a call id. `Call.id` is the call's own id; `Call` gains `session_id` (absent once the session is deleted) and loses `config_id` and `user_id`. `listCalls` (`GET /v1/agents/calls`) takes `session_id` and answers that session's calls newest first. Go is done: `client.Sessions.Timeline` and `Decisions` list the session's calls with `session_id` and `limit=1`, read the newest one's `getCallTimeline` or `getCallEvents`, and fail with `client.ErrNoCall` when the session has none (`sdks/go/client/sessions.go`). Other SDKs need to update: JavaScript, Python (`plugins/stream`), .NET, Ruby, Rust and PHP regenerate their clients, and any helper that passes a session id to `/v1/agents/calls/{id}` (its timeline, events, transcript or tokens) lists the session's calls first; Swift, Kotlin and Dart regenerate `Call` where they have it. STS models list their built-in voices on `Provider.voices` (`ModelVoice`: `id`, `name`, `description`, `gender`, `default`), omitted for non-STS providers, and new voice configs created via `createAgentConfig` or `syncAgent` now default `sts` to `sts-fast` when `sts` is omitted and no cascade settings are provided (explicit `sts: ""` selects the cascade). Go is regenerated (`sdks/go/acceleration/generated.go`). Other SDKs need to update: JavaScript, Python (`plugins/stream`), Swift, Kotlin, Dart, .NET, Ruby, Rust and PHP regenerate their OpenAPI types to pick up `Provider.voices` and `ModelVoice`. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; `flutter_demo`'s `AgentChat` shows an incognito session from them. Dart differs from Swift in two places, both on purpose: a waiting call's `target_user_id` is the agents' own user (`backend.userId`), as Kotlin's #2114 has it, not the session's `user_id`, which the spec calls the name the agent joined the call as, so an `AIToolApprover` for the person never matches Swift's or JavaScript's; and a round of thinking after a tool's result in the same turn is timed from `tool_ran`, where Swift, Kotlin and JavaScript time it from when the turn was last asked or went on writing, so it overlaps the call. Other SDKs need to update: Kotlin (#2114, open) should land its fold; Swift and JavaScript should set `target_user_id` to the person and time a round after `tool_ran`; the server SDKs need nothing. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Swift does the same: `Conversation` folds the frames into `Turn.steps` and `Turn.isDone`, and `TurnMessage.messages(of:approvals:userID:isConnected:)` (`session.turnMessages`) builds the replies, each step an attachment type and JSON payload for `AIMessagePart.parts(from:)`, the session's user now `Session.userID`; `swift_assistant`'s `AgentChat` shows an incognito session from them. Dart does the same: `Conversation` folds the frames into `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone`, and `TurnMessage.messages(conversation, approvals:, userId:, isConnected:)` (`session.turnMessages`) builds the replies, each step the `(type:, payload:)` record `AIMessagePart.parseAll` takes; `flutter_demo`'s `AgentChat` shows an incognito session from them. Dart differs from Swift in one place, on purpose: a waiting call's `target_user_id` is the agents' own user (`backend.userId`), as Kotlin's #2114 has it, not the session's `user_id`, which the spec calls the name the agent joined the call as, so an `AIToolApprover` for the person never matches Swift's or JavaScript's. Its `ToolCallStepStatus` is named apart from `ToolCallStatus` (tool groups' call state), since Dart has no nested types. Other SDKs need to update: Kotlin (#2114, open) should land its fold; Swift and JavaScript should set `target_user_id` to the person; the server SDKs need nothing. -The session socket sends `reasoning_delta` (`turn_id`, `text`): the next piece of the model's thinking on a written reply, which a kept conversation also streams into the reply's Chat message and an incognito one has nowhere else to show. JavaScript folds it, with `tool_started`, `tool_updated` (not `verbatim`) and `tool_ran`, into each agent turn's `steps` in `sdks/js/src/conversation.ts`: a round of thinking `r1`, `r2`... opens on a delta after anything else and completes when the turn writes text or UI, calls a tool, answers or is cut off; a call runs until `tool_ran`, failed when it carries an `error`, its summary the last non-verbatim update. A turn is `done` on `responded` with no `pending_work`, or `interrupted`. `AgentChat` shows a session with no `conversationId` from these turns (`sdks/js/src/turn-messages.ts`): the agent's turns between two of the person's messages are one reply, shaped as the channel's messages (top level in stream-chat 9, under `custom` in 10) with `ai_reasoning` and `ai_tool_call` steps, rounds numbered across the reply, its whole thinking given to `reasoning`, and a call waiting in `approvals` shown `awaiting_approval` with its question and the session's `user_id` as `target_user_id`. The clients that carry the socket's description (JavaScript types, Python `plugins/stream`) are regenerated. Other SDKs need to update: Swift, Kotlin and Dart, whose AI components read the same steps, should fold the same frames into their `Conversation` turns and show a session with no channel through their transports; the server SDKs need nothing. -An agent's UI instructions are kept apart from its instructions, so a session can turn UI off: `AgentConfig`, `AgentConfigRequest`, `AgentConfigPatch` and `SyncAgentRequest` have `ui_instructions` (an additive migration), and `CreateSessionRequest` has `ui`, a boolean a device may send. The router tells the model `ui_instructions` after the instructions (a backend's own session instructions included) unless the session was opened with `ui: false`, which reopening or forking it keeps (`agent_sessions.no_ui`). A sync sends the directory whole, so a sync without `ui_instructions` removes them; a PUT that leaves them out keeps them, so a client that does not know the field does not take the UI away. Go's `Load` compiles agent.yaml's `ui:` into `Folder.UIInstructions` and `syncFolder` sends it as `ui_instructions`; the folder's hash takes it in only when there is UI, so a directory without `ui:` is not synced again, and one with it is synced once more, which moves the UI out of the stored instructions. A router older than the field takes the sync and drops it, so `syncFolder` does not trust a stamp covering UI that the stored config lacks, and syncs again, and the router writes a sync of the same hash that declares UI the config lacks rather than finding it unchanged. Deploy the router before releasing an SDK that sends the field. JavaScript does the same: `loadFolder` puts the compiled `ui:` in `Folder.uiInstructions`, `Agent.sync` sends it as `ui_instructions` (left out without `ui:`, so such a directory keeps its fingerprint), and a stamp covering UI the stored config lacks is synced again. When a sync's answer has no `ui_instructions` though it sent them (a router older than the field), JavaScript syncs once more with the UI joined onto `instructions`, as before, under that body's own fingerprint and without writing the stamp, so the agent keeps its UI and the next sync moves it apart once the router knows the field. That fallback cannot honour `ui: false`: the UI is in `instructions` then, which every session is told, so the Interactive UI switch needs a router that knows the field and a sync it stored apart. Go only syncs again there, so an older router leaves a Go-synced agent with no UI, and Go should fall back the same way. `Agent`'s `instructions` option replaces instructions.md only: the folder's `ui:` is still sent as `ui_instructions`, as in Go. `react_assistant`'s settings have the same Interactive UI switch as `swift_assistant`'s, which opens new conversations with `ui: false`. The shared fixtures are unchanged: they are what the model is told, the instructions and the UI joined by a blank line, as the router joins them. Every generated client is regenerated (Go, JavaScript types, Python `plugins/stream`, Swift, Rust's `types.rs`); Rust compiling and sending `ui:` is still to do, below. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP, when they read `ui:`, should send it as `ui_instructions` the same way; Swift has `SessionOptions.ui`, which `swift_assistant`'s Settings switch sets, and JavaScript's `sessions.create` passes `ui` through with the regenerated types; Python, Kotlin, Dart and the other server SDKs should offer `ui` on their create-session options, so an app that shows no UI can say so. -A tool call's state (`ToolCallState`, the `tool_call.started`, `tool_call.progress` and `tool_call.finished` frames) carries `display_title`: what the call is doing, as its tool was declared with (a session's own tool's `display_title`, or a hosted tool's), or "Searching the web" for the router's own search, the same default a Chat reply's tool step uses (`conversation.ToolTitle`). A worker's `host_tools` frame takes `display_title` on each tool, beside `interruptible` and `timeout_ms`. Go has `tools.DisplayTitle(title)`, sent on `host_tools` and on a session's own tools. The generated clients are regenerated (Go, JavaScript types, Python `plugins/stream`, Ruby, PHP, .NET); Swift's generates no `ToolCallState`, so it is unchanged. JavaScript needs nothing: its `host_tools` sends `tools.declared()`, `displayTitle` included, which the router now keeps. Other SDKs need to update: Python, .NET, Ruby, Rust and PHP should send their tool's display title on `host_tools`, their registries taking one where they do not yet; Swift, Kotlin and Dart read `display_title` off the tool call state once regenerated. diff --git a/.claude/skills/sdk/notes/2026-11-23-target-user-id.md b/.claude/skills/sdk/notes/2026-11-23-target-user-id.md new file mode 100644 index 0000000000..9b696d229b --- /dev/null +++ b/.claude/skills/sdk/notes/2026-11-23-target-user-id.md @@ -0,0 +1 @@ +An incognito session's tool call waiting for approval is shown as an `ai_tool_call` step with `target_user_id`: the user Stream's approver shows the card to. Kotlin and Dart send the person's user, the one the app signed in as (`backend.user` in Kotlin, `backend.userId` in Dart), which is what a kept reply's step uses (the conversation's owner, `parts.go`). `Session.user_id` is the name the agent joined the call as, not the session's owner. Other SDKs need to update: Swift (`TurnMessage.swift`) and JavaScript (`turn-messages.ts`) should send the person's user as `target_user_id`, as Kotlin and Dart do, not `Session.userId`. The server SDKs need nothing. diff --git a/CHANGELOG.md b/CHANGELOG.md index 41411fcd4a..0e1866e10a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Unreleased +## Breaking Changes + +- The Dart SDK's `AgentEventKind` gains `reasoningDelta`, so a `switch` over it with no default needs the case (#2200). + ## Features ### New voice agents default to `sts-fast` and STS providers expose built-in voices @@ -72,10 +76,6 @@ Every server SDK's client has a tool registry for the whole app, and one call ru `client.Connections()` creates, authorizes, reads, lists and deletes connections: `Create(ctx, client.ConnectionRequest{Connector: "linear", UserID: "alice"})`, then `Authorize(ctx, id, client.AuthorizeOptions{ReturnURL, UserID})` for the launch URL, handoff token and expiry of the consent, and `Get(ctx, id, client.ConnectionOptions{UserID})`, `List(ctx, client.ConnectionFilter{UserID, Connector})`, `Delete(ctx, id, client.ConnectionOptions{UserID})`. Every call takes the user as `UserID` of its options struct and sends it as both the owner and `X-Stream-User-Id`. An empty user is the app's own connection. -### The Dart SDK shows an incognito session - -An incognito session has no Stream Chat channel, so a Flutter app had nothing to show its replies with. `Turn` now has `steps` (rounds of thinking and tool calls) and `isDone`, from the socket, and `session.turnMessages` is the conversation in the shape Stream's AI components read, a waiting call's approval card included. `AgentEventKind` gains `reasoningDelta`, so an exhaustive `switch` over it needs the case. `flutter_demo` has an incognito toggle (#2200). - ### The Swift SDK shows an incognito session An incognito session has no Stream Chat channel, so `session.chat()` throws and an app had nothing to show its replies with. `Conversation` now folds the socket's `reasoning_delta`, `tool_started`, `tool_updated` and `tool_ran` into each turn's `steps` (rounds of reasoning and tool calls, in order) and `isDone`, timing a round of reasoning from when the model was asked. `session.turnMessages` is the conversation in the shape a kept one has in Chat: one `TurnMessage` per question and reply, its steps as attachment payloads for StreamChatAI's `AIMessagePart.parts(from:)`, the whole of each round of thinking, the reply's UI, and an approval card for the session's user, now `Session.userID`. `swift_assistant` has an incognito toggle at the top right of a new chat (#2091). diff --git a/sdks/dart/stream_agents/CHANGELOG.md b/sdks/dart/stream_agents/CHANGELOG.md index 7507adcada..a596229a3b 100644 --- a/sdks/dart/stream_agents/CHANGELOG.md +++ b/sdks/dart/stream_agents/CHANGELOG.md @@ -7,8 +7,6 @@ row before; read that as `session.session`. `chat` and `voice` are now `sessions.create` with `startVoice` false and true. -- `AgentEventKind` has `reasoningDelta`: a `switch` over it with no default needs the case. - ✅ Added - `SessionOptions.watch` - false opens a session with no socket and no tools declared; turns go @@ -24,10 +22,6 @@ while it runs, such as "Comparing 40 flights", otherwise its display title, such as "Checking the weather", falling back to the tool's name. - `session.toolCallsForTurn(turnId)` - the calls one agent turn made, to show under its message. -- `session.turnMessages` and `TurnMessage` - an incognito session's conversation, for Stream's AI - components. -- `Turn.steps` (`ReasoningStep`, `ToolCallStep`) and `Turn.isDone` - a reply's thinking and tool - calls, from the socket. ## 0.7.0