61 lines
1.9 KiB
TypeScript
61 lines
1.9 KiB
TypeScript
import { Vault, TFile, Notice, App } from 'obsidian';
|
|
import { ToolCall, ToolResult, ToolExecutionError, PathValidationError } from './types';
|
|
import { validatePath } 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' ? JSON.parse(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}` };
|
|
}
|
|
}
|
|
}
|