getToolkits method

Future<List<Toolkit>> getToolkits(
  1. ToolContext context,
  2. List<RequiredToolkit> remoteToolkits
)

Implementation

Future<List<Toolkit>> getToolkits(
  ToolContext context,
  List<RequiredToolkit> remoteToolkits,
) async {
  final Participant? caller = context.caller;
  final Participant? onBehalfOf = context.onBehalfOf;

  Participant? toolTarget = caller;
  if (onBehalfOf != null) {
    toolTarget = onBehalfOf;
  }

  final room = this.room;

  final Map<String, ToolkitDescription> toolkitsByName = {};
  final List<Toolkit> resolvedToolkits = [];

  final visibleToolkits = await room.agents.listToolkits(
    participantId: toolTarget?.id,
  );
  for (final tk in visibleToolkits) {
    toolkitsByName[tk.name] = tk;
  }

  for (final requiredToolkit in remoteToolkits) {
    final tk = toolkitsByName[requiredToolkit.name];
    if (tk == null) {
      if (onBehalfOf != null) {
        throw RoomServerException(
          'unable to get toolkit ${requiredToolkit.name} '
          'on behalf of $onBehalfOf',
        );
      } else {
        throw RoomServerException(
          'unable to get toolkit ${requiredToolkit.name} '
          'for caller ${caller?.id}',
        );
      }
    }

    final List<ToolDescription> selectedTools;
    if (requiredToolkit.tools == null) {
      selectedTools = tk.tools;
    } else {
      final toolsByName = <String, ToolDescription>{
        for (final td in tk.tools) td.name: td,
      };
      selectedTools = <ToolDescription>[];
      for (final requiredToolName in requiredToolkit.tools!) {
        final td = toolsByName[requiredToolName];
        if (td == null) {
          throw RoomServerException(
            'unable to locate required tool $requiredToolName '
            'in toolkit ${requiredToolkit.name}',
          );
        }
        selectedTools.add(td);
      }
    }

    final List<BaseTool> roomTools = selectedTools
        .map(
          (td) => _buildRoomProxyTool(
            toolkitName: tk.name,
            toolDescription: td,
            participantId: toolTarget?.id,
            onBehalfOfId: toolTarget?.id,
          ),
        )
        .toList(growable: false);

    resolvedToolkits.add(
      RoomToolkit(
        name: tk.name,
        title: tk.title,
        description: tk.description,
        thumbnailUrl: tk.thumbnailUrl,
        tools: roomTools,
      ),
    );
  }

  return resolvedToolkits;
}