partitionToolCalls function

List<ToolBatch> partitionToolCalls(
  1. List<ToolUseBlock> toolUseMessages,
  2. ToolUseContext toolUseContext
)

Partition tool calls into batches for orchestration.

Implementation

List<ToolBatch> partitionToolCalls(
  List<ToolUseBlock> toolUseMessages,
  ToolUseContext toolUseContext,
) {
  final batches = <ToolBatch>[];

  for (final toolUse in toolUseMessages) {
    final tool = findToolByName(toolUseContext.tools, toolUse.name);
    bool isConcurrencySafe = false;
    if (tool != null) {
      try {
        isConcurrencySafe = tool.isConcurrencySafe(toolUse.input);
      } catch (_) {
        isConcurrencySafe = false;
      }
    }

    if (isConcurrencySafe &&
        batches.isNotEmpty &&
        batches.last.isConcurrencySafe) {
      // Mutable list — extend the last batch
      batches.last.blocks.add(toolUse);
    } else {
      batches.add(
        ToolBatch(isConcurrencySafe: isConcurrencySafe, blocks: [toolUse]),
      );
    }
  }

  return batches;
}