invokeAgentWebSocket function

Future<AgentResult> invokeAgentWebSocket({
  1. required Uri uri,
  2. required IntentCallInvocationEnvelope envelope,
  3. 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();
  }
}