execute method

  1. @override
Future<ToolResult> execute(
  1. Map<String, dynamic> input
)
override

Execute the tool with the given input.

Implementation

@override
Future<ToolResult> execute(Map<String, dynamic> input) async {
  final validation = validateInput(input);
  if (!validation.isValid) return ToolResult.error(validation.error!);

  final parsed = NotebookEditInput.fromJson(input);
  final file = File(parsed.notebookPath);

  if (!await file.exists()) {
    return ToolResult.error('Notebook not found: ${parsed.notebookPath}');
  }

  try {
    final raw = await file.readAsString();
    final notebook = jsonDecode(raw) as Map<String, dynamic>;
    final cells = (notebook['cells'] as List).cast<Map<String, dynamic>>();
    final cellType = parsed.cellType ?? 'code';

    switch (parsed.command) {
      case 'add':
        final newCell = _makeCell(cellType, parsed.content!);
        final idx = parsed.cellIndex.clamp(0, cells.length);
        cells.insert(idx, newCell);

      case 'edit':
        if (parsed.cellIndex < 0 || parsed.cellIndex >= cells.length) {
          return ToolResult.error(
            'cell_index ${parsed.cellIndex} out of range (0..${cells.length - 1})',
          );
        }
        cells[parsed.cellIndex]['source'] = _splitSource(parsed.content!);
        if (parsed.cellType != null) {
          cells[parsed.cellIndex]['cell_type'] = parsed.cellType;
        }

      case 'delete':
        if (parsed.cellIndex < 0 || parsed.cellIndex >= cells.length) {
          return ToolResult.error(
            'cell_index ${parsed.cellIndex} out of range (0..${cells.length - 1})',
          );
        }
        cells.removeAt(parsed.cellIndex);

      case 'move':
        if (parsed.cellIndex < 0 || parsed.cellIndex >= cells.length) {
          return ToolResult.error(
            'cell_index ${parsed.cellIndex} out of range',
          );
        }
        final target = parsed.targetIndex!.clamp(0, cells.length - 1);
        final cell = cells.removeAt(parsed.cellIndex);
        cells.insert(target, cell);
    }

    notebook['cells'] = cells;
    final encoder = const JsonEncoder.withIndent(' ');
    await file.writeAsString(encoder.convert(notebook));

    final out = NotebookEditOutput(
      success: true,
      message: '${parsed.command} cell at index ${parsed.cellIndex}',
      cellCount: cells.length,
    );
    return ToolResult.success(out.toString());
  } catch (e) {
    return ToolResult.error('Error editing notebook: $e');
  }
}