formatCommandsWithinBudget function

String formatCommandsWithinBudget(
  1. List<SkillCommand> commands, {
  2. int? contextWindowTokens,
})

Format commands within the character budget, preserving bundled skill descriptions while truncating others as needed.

Implementation

String formatCommandsWithinBudget(
  List<SkillCommand> commands, {
  int? contextWindowTokens,
}) {
  if (commands.isEmpty) return '';

  final budget = getCharBudget(contextWindowTokens: contextWindowTokens);

  // Try full descriptions first.
  final fullEntries = commands.map((cmd) {
    return _formatCommandDescription(cmd);
  }).toList();

  final fullTotal =
      fullEntries.fold<int>(0, (sum, e) => sum + e.length) +
      (fullEntries.length - 1); // newlines

  if (fullTotal <= budget) {
    return fullEntries.join('\n');
  }

  // Partition into bundled (never truncated) and rest.
  final bundledIndices = <int>{};
  final restCommands = <SkillCommand>[];
  for (var i = 0; i < commands.length; i++) {
    final cmd = commands[i];
    if (cmd.type == 'prompt' && cmd.source == 'bundled') {
      bundledIndices.add(i);
    } else {
      restCommands.add(cmd);
    }
  }

  // Compute space used by bundled skills.
  var bundledChars = 0;
  for (var i = 0; i < fullEntries.length; i++) {
    if (bundledIndices.contains(i)) {
      bundledChars += fullEntries[i].length + 1;
    }
  }
  final remainingBudget = budget - bundledChars;

  if (restCommands.isEmpty) {
    return fullEntries.join('\n');
  }

  // Calculate max description length for non-bundled commands.
  final restNameOverhead =
      restCommands.fold<int>(0, (sum, cmd) => sum + cmd.name.length + 4) +
      (restCommands.length - 1);
  final availableForDescs = remainingBudget - restNameOverhead;
  final maxDescLen = (availableForDescs / restCommands.length).floor();

  if (maxDescLen < minDescLength) {
    // Non-bundled go names-only, bundled keep descriptions.
    return commands
        .asMap()
        .entries
        .map((entry) {
          if (bundledIndices.contains(entry.key)) {
            return fullEntries[entry.key];
          }
          return '- ${entry.value.name}';
        })
        .join('\n');
  }

  // Truncate non-bundled descriptions to fit within budget.
  return commands
      .asMap()
      .entries
      .map((entry) {
        if (bundledIndices.contains(entry.key)) {
          return fullEntries[entry.key];
        }
        final description = _getCommandDescription(entry.value);
        return '- ${entry.value.name}: ${_truncate(description, maxDescLen)}';
      })
      .join('\n');
}