All files tool-executor.ts

100% Statements 24/24
83.33% Branches 10/12
100% Functions 2/2
100% Lines 24/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61  1x 1x   1x         27x 27x           27x   27x     26x   26x 25x 25x   1x             25x 1x       24x 2x     22x 1x     21x 21x 14x     7x 6x     1x        
import { Vault, TFile, Notice, App } from 'obsidian';
import { ToolCall, ToolResult, ToolExecutionError, PathValidationError } from './types';
import { validatePath, safeParseJson } from './utils';
 
export class ToolExecutor {
  private vault: Vault;
  private app: App;
 
  constructor(vault: Vault, app: App) {
    this.vault = vault;
    this.app = app;
  }
 
  async handleToolCall(call: ToolCall): Promise<ToolResult> {
    const {
      function: { name, arguments: args },
    } = call;
 
    switch (name) {
      case 'create_file': {
        let filePath: string, content: string;
        try {
          // Handle both string (JSON) and object arguments, since some Ollama versions return args as an object
          const parsedArgs = typeof args === 'string' ? safeParseJson(args) : args;
          filePath = parsedArgs.path;
          content = parsedArgs.content;
        } catch (e) {
          throw new ToolExecutionError(
            `Invalid arguments provided for create_file: ${e instanceof Error ? e.message : 'Unknown parsing error'}`,
            'create_file'
          );
        }
 
        // Validate content is a string
        if (typeof content !== 'string') {
          throw new ToolExecutionError('Content must be a string', 'create_file');
        }
 
        // Validate path using shared utility
        if (typeof filePath !== 'string') {
          throw new ToolExecutionError('Path must be a string', 'create_file');
        }
 
        if (!filePath) {
          throw new ToolExecutionError('Path is required', 'create_file');
        }
 
        const pathValidation = validatePath(filePath);
        if (!pathValidation.valid) {
          throw new PathValidationError(pathValidation.error || 'Path validation failed', filePath);
        }
 
        await this.vault.create(filePath, content);
        return { success: true, message: 'File created successfully' };
      }
      default:
        return { success: false, message: `Unknown tool: ${name}` };
    }
  }
}