Adds a plugin to clean up freewriting text using the Anthropic API. This initial commit introduces core functionality, including: - API client for interacting with Anthropic's Claude models. - Service for orchestrating cleanup operations and managing API calls. - Command for executing the cleanup process on selected text within Obsidian editor. - Settings tab for configuring the API key, model, prompts, and commentary preferences. - Type definitions for settings, API requests/responses, and cleanup results. The plugin provides a command to clean up selected text, apply custom prompts, and optionally generate commentary on the freewriting session.
162 lines
5.1 KiB
TypeScript
162 lines
5.1 KiB
TypeScript
// ABOUTME: Service class for orchestrating freewriting text cleanup operations
|
|
// ABOUTME: Handles validation, API coordination, and result formatting
|
|
|
|
import { Notice } from 'obsidian';
|
|
import { AnthropicClient } from '../api/anthropicClient';
|
|
import { FreewritingCleanupSettings, CleanupResult, ANTHROPIC_LIMITS } from '../types';
|
|
|
|
export class CleanupService {
|
|
private anthropicClient: AnthropicClient;
|
|
|
|
constructor(apiKey: string) {
|
|
this.anthropicClient = new AnthropicClient(apiKey);
|
|
}
|
|
|
|
// MARK: - Public Methods
|
|
|
|
async cleanupText(text: string, settings: FreewritingCleanupSettings): Promise<CleanupResult> {
|
|
// Validate input
|
|
if (!text || text.trim().length === 0) {
|
|
throw new Error('No text selected for cleanup');
|
|
}
|
|
|
|
if (!this.anthropicClient.validateApiKey()) {
|
|
throw new Error('API key is not configured. Please check your plugin settings.');
|
|
}
|
|
|
|
// Check text length limits
|
|
if (text.length > ANTHROPIC_LIMITS.MAX_CHARACTERS) {
|
|
throw new Error(`Selected text is too long (${text.length} characters). Maximum allowed: ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters.`);
|
|
}
|
|
|
|
const startTime = Date.now();
|
|
|
|
try {
|
|
const { cleanedText, commentary } = await this.anthropicClient.cleanupText(
|
|
text,
|
|
settings.model,
|
|
settings.cleanupPrompt,
|
|
settings.enableCommentary,
|
|
settings.commentaryStyle,
|
|
settings.customCommentaryPrompt
|
|
);
|
|
|
|
const result: CleanupResult = {
|
|
originalText: text,
|
|
cleanedText,
|
|
commentary,
|
|
timestamp: new Date(),
|
|
model: settings.model,
|
|
tokensUsed: {
|
|
input: 0, // We don't have access to this from the response
|
|
output: 0 // We don't have access to this from the response
|
|
}
|
|
};
|
|
|
|
const duration = Date.now() - startTime;
|
|
new Notice(`Text cleanup completed in ${(duration / 1000).toFixed(1)}s`);
|
|
|
|
return result;
|
|
} catch (error) {
|
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
|
new Notice(`Text cleanup failed: ${errorMessage}`);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async testConnection(settings: FreewritingCleanupSettings): Promise<{
|
|
success: boolean;
|
|
message: string;
|
|
details?: {
|
|
model: string;
|
|
responseTime: number;
|
|
inputTokens?: number;
|
|
outputTokens?: number;
|
|
};
|
|
}> {
|
|
if (!this.anthropicClient.validateApiKey()) {
|
|
return {
|
|
success: false,
|
|
message: 'API key is not configured'
|
|
};
|
|
}
|
|
|
|
try {
|
|
const result = await this.anthropicClient.testConnection(settings.model);
|
|
return result;
|
|
} catch (error) {
|
|
return {
|
|
success: false,
|
|
message: error instanceof Error ? error.message : 'Unknown error'
|
|
};
|
|
}
|
|
}
|
|
|
|
formatCleanupResult(result: CleanupResult): string {
|
|
let formatted = `\n\n---\n\nAI Cleanup:\n\n${result.cleanedText}`;
|
|
|
|
if (result.commentary) {
|
|
formatted += `\n\n---\n\nAI Commentary:\n\n${result.commentary}`;
|
|
}
|
|
|
|
return formatted;
|
|
}
|
|
|
|
// MARK: - Configuration Methods
|
|
|
|
updateApiKey(apiKey: string): void {
|
|
this.anthropicClient.updateApiKey(apiKey);
|
|
}
|
|
|
|
validateSettings(settings: FreewritingCleanupSettings): {
|
|
isValid: boolean;
|
|
errors: string[];
|
|
} {
|
|
const errors: string[] = [];
|
|
|
|
if (!settings.apiKey || settings.apiKey.trim().length === 0) {
|
|
errors.push('API key is required');
|
|
}
|
|
|
|
if (!settings.model) {
|
|
errors.push('Model selection is required');
|
|
}
|
|
|
|
if (!settings.cleanupPrompt || settings.cleanupPrompt.trim().length === 0) {
|
|
errors.push('Cleanup prompt is required');
|
|
}
|
|
|
|
return {
|
|
isValid: errors.length === 0,
|
|
errors
|
|
};
|
|
}
|
|
|
|
// MARK: - Utility Methods
|
|
|
|
static getCharacterCount(text: string): number {
|
|
return text.length;
|
|
}
|
|
|
|
static estimateTokenCount(text: string): number {
|
|
// Rough estimation: 1 token ≈ 4 characters for English text
|
|
return Math.ceil(text.length / 4);
|
|
}
|
|
|
|
static isWithinLimits(text: string): {
|
|
withinCharacterLimit: boolean;
|
|
withinTokenLimit: boolean;
|
|
characterCount: number;
|
|
estimatedTokenCount: number;
|
|
} {
|
|
const characterCount = this.getCharacterCount(text);
|
|
const estimatedTokenCount = this.estimateTokenCount(text);
|
|
|
|
return {
|
|
withinCharacterLimit: characterCount <= ANTHROPIC_LIMITS.MAX_CHARACTERS,
|
|
withinTokenLimit: estimatedTokenCount <= ANTHROPIC_LIMITS.MAX_TOKENS,
|
|
characterCount,
|
|
estimatedTokenCount
|
|
};
|
|
}
|
|
} |