invokeAgentWebSocket function
Future<AgentResult>
invokeAgentWebSocket({
- required Uri uri,
- required IntentCallInvocationEnvelope envelope,
- Duration timeout = const Duration(seconds: 5),
Sends one invoke frame and waits for the matching observed result.
Implementation
Future<AgentResult> invokeAgentWebSocket({
required final Uri uri,
required final IntentCallInvocationEnvelope envelope,
final Duration timeout = const Duration(seconds: 5),
}) async {
final socket = await WebSocket.connect(uri.toString());
final completer = Completer<AgentResult>();
late final StreamSubscription<dynamic> subscription;
subscription = socket.listen((final raw) {
final decoded = _decodeMap(raw);
if (decoded == null || decoded['op'] != 'observed') {
return;
}
final observation = AgentCallObservation.fromJson(decoded);
if (observation.envelope.id != envelope.id || completer.isCompleted) {
return;
}
completer.complete(observation.result);
});
socket.add(
jsonEncode(<String, Object?>{
'op': 'invoke',
'envelope': envelope.toJson(),
}),
);
try {
return await completer.future.timeout(timeout);
} finally {
await subscription.cancel();
await socket.close();
}
}