From a63d184448c948f6baa734b91ec9cdabd72d31e9 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Sat, 20 Sep 2025 12:14:55 +0200 Subject: [PATCH] Implements freewriting cleanup plugin 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. --- api/anthropicClient.ts | 230 +++++++++++++++++++++++++++++ commands/cleanupCommand.ts | 147 ++++++++++++++++++ main.ts | 197 +++++++++---------------- package.json | 8 +- services/cleanupService.ts | 162 ++++++++++++++++++++ settings.ts | 295 +++++++++++++++++++++++++++++++++++++ types.ts | 89 +++++++++++ 7 files changed, 993 insertions(+), 135 deletions(-) create mode 100644 api/anthropicClient.ts create mode 100644 commands/cleanupCommand.ts create mode 100644 services/cleanupService.ts create mode 100644 settings.ts create mode 100644 types.ts diff --git a/api/anthropicClient.ts b/api/anthropicClient.ts new file mode 100644 index 0000000..e256415 --- /dev/null +++ b/api/anthropicClient.ts @@ -0,0 +1,230 @@ +// ABOUTME: Anthropic API client for text cleanup using Claude +// ABOUTME: Handles API requests, error handling, retry logic, and response parsing + +import { requestUrl } from 'obsidian'; +import { AnthropicRequest, AnthropicResponse, AnthropicModel, ANTHROPIC_LIMITS, CommentaryStyle, COMMENTARY_PRESETS } from '../types'; + +export class AnthropicClient { + private apiKey: string; + private baseUrl = 'https://api.anthropic.com/v1/messages'; + private readonly MAX_RETRIES = 3; + private readonly RETRY_DELAY_BASE = 1000; // 1 second base delay + + constructor(apiKey: string) { + this.apiKey = apiKey; + } + + // MARK: - Public Methods + + async cleanupText( + text: string, + model: AnthropicModel, + cleanupPrompt: string, + enableCommentary = false, + commentaryStyle: CommentaryStyle = 'constructive', + customCommentaryPrompt?: string + ): Promise<{ cleanedText: string; commentary?: string }> { + if (!this.apiKey) { + throw new Error('API key is required'); + } + + if (text.length > ANTHROPIC_LIMITS.MAX_CHARACTERS) { + throw new Error(`Text too long. Maximum ${ANTHROPIC_LIMITS.MAX_CHARACTERS} characters allowed.`); + } + + // Get commentary prompt if enabled + let commentaryPrompt = ''; + if (enableCommentary) { + if (commentaryStyle === 'custom' && customCommentaryPrompt) { + commentaryPrompt = customCommentaryPrompt; + } else { + commentaryPrompt = COMMENTARY_PRESETS[commentaryStyle as Exclude]; + } + } + + const systemPrompt = `${cleanupPrompt} + +${enableCommentary ? `After cleaning the text, also provide commentary based on this instruction: ${commentaryPrompt}` : ''} + +CRITICAL OUTPUT REQUIREMENTS - YOU MUST FOLLOW THIS EXACT FORMAT: + +===CLEANED TEXT=== +[Put the cleaned up text here] +- Fix spelling, grammar, and punctuation errors +- Add line breaks and paragraphs as appropriate for readability +- Preserve any existing markdown formatting (bold, italics, links, etc.) +- Do not add quotation marks or any wrapper text +===END CLEANED TEXT=== + +${enableCommentary ? ` +===COMMENTARY=== +[Put your commentary here based on the instruction above] +===END COMMENTARY=== +` : ''} + +You MUST use exactly these markers. Do not deviate from this format.`; + + const userMessage = `Please process this freewriting text according to the format requirements:\n\n${text}`; + + const request: AnthropicRequest = { + model, + max_tokens: ANTHROPIC_LIMITS.DEFAULT_MAX_OUTPUT_TOKENS, + messages: [{ role: 'user', content: userMessage }], + system: systemPrompt + }; + + const response = await this.makeRequestWithRetry(request); + return this.parseStructuredResponse(response, enableCommentary); + } + + async testConnection(model: AnthropicModel): Promise<{ + success: boolean; + message: string; + details?: { + model: string; + responseTime: number; + inputTokens?: number; + outputTokens?: number; + }; + error?: string; + }> { + if (!this.validateApiKey()) { + return { + success: false, + message: 'API key is empty or invalid format', + error: 'INVALID_KEY_FORMAT' + }; + } + + const startTime = Date.now(); + const testRequest: AnthropicRequest = { + model, + max_tokens: 50, + messages: [{ role: 'user', content: 'Hello! Please respond with just "Test successful."' }], + system: 'You are a test assistant. Respond only with "Test successful." and nothing else.' + }; + + try { + const response = await this.makeRequest(testRequest); + const responseTime = Date.now() - startTime; + + return { + success: true, + message: 'API connection successful', + details: { + model: response.model, + responseTime, + inputTokens: response.usage.input_tokens, + outputTokens: response.usage.output_tokens + } + }; + } catch (error) { + return { + success: false, + message: error instanceof Error ? error.message : 'Unknown error', + error: 'CONNECTION_FAILED' + }; + } + } + + // MARK: - Private Methods + + private async makeRequestWithRetry(request: AnthropicRequest): Promise { + let lastError: Error = new Error('No attempts made'); + + for (let attempt = 1; attempt <= this.MAX_RETRIES; attempt++) { + try { + const response = await this.makeRequest(request); + return this.extractTextFromResponse(response); + } catch (error) { + lastError = error instanceof Error ? error : new Error('Unknown error'); + + if (attempt < this.MAX_RETRIES) { + const delay = this.RETRY_DELAY_BASE * Math.pow(2, attempt - 1); // Exponential backoff + await this.sleep(delay); + continue; + } + } + } + + throw new Error(`Failed after ${this.MAX_RETRIES} attempts. Last error: ${lastError.message}`); + } + + private parseStructuredResponse(responseText: string, expectCommentary: boolean): { cleanedText: string; commentary?: string } { + // Extract cleaned text + const cleanedTextMatch = responseText.match(/===CLEANED TEXT===([\s\S]*?)===END CLEANED TEXT===/); + if (!cleanedTextMatch) { + throw new Error('Invalid response format: Could not find cleaned text section'); + } + + const cleanedText = cleanedTextMatch[1].trim(); + if (!cleanedText) { + throw new Error('Empty cleaned text received'); + } + + let commentary: string | undefined; + + if (expectCommentary) { + const commentaryMatch = responseText.match(/===COMMENTARY===([\s\S]*?)===END COMMENTARY===/); + if (commentaryMatch) { + commentary = commentaryMatch[1].trim(); + } + } + + return { cleanedText, commentary }; + } + + private async makeRequest(request: AnthropicRequest): Promise { + try { + const response = await requestUrl({ + url: this.baseUrl, + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-api-key': this.apiKey, + 'anthropic-version': '2023-06-01' + }, + body: JSON.stringify(request) + }); + + if (response.status < 200 || response.status >= 300) { + const errorBody = response.text || 'Unknown error'; + throw new Error(`API request failed (${response.status}): ${errorBody}`); + } + + return response.json as AnthropicResponse; + } catch (error) { + if (error instanceof Error) { + throw error; + } + throw new Error(`Network request failed: ${String(error)}`); + } + } + + private extractTextFromResponse(response: AnthropicResponse): string { + if (!response.content || response.content.length === 0) { + throw new Error('No content received from API'); + } + + const text = response.content[0].text; + if (!text || text.trim().length === 0) { + throw new Error('Empty response from API'); + } + + return text.trim(); + } + + private sleep(ms: number): Promise { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + // MARK: - Configuration Methods + + updateApiKey(apiKey: string): void { + this.apiKey = apiKey; + } + + validateApiKey(): boolean { + return !!(this.apiKey && this.apiKey.trim().length > 0); + } +} \ No newline at end of file diff --git a/commands/cleanupCommand.ts b/commands/cleanupCommand.ts new file mode 100644 index 0000000..e8e3c03 --- /dev/null +++ b/commands/cleanupCommand.ts @@ -0,0 +1,147 @@ +// ABOUTME: Command implementation for the freewriting cleanup functionality +// ABOUTME: Handles editor interaction, text selection, and result insertion + +import { Editor, MarkdownView, Notice } from 'obsidian'; +import { CleanupService } from '../services/cleanupService'; +import { FreewritingCleanupSettings } from '../types'; + +export class CleanupCommand { + private cleanupService: CleanupService; + + constructor(cleanupService: CleanupService) { + this.cleanupService = cleanupService; + } + + // MARK: - Public Methods + + async execute(editor: Editor, view: MarkdownView, settings: FreewritingCleanupSettings): Promise { + try { + // Get selected text + const selectedText = editor.getSelection(); + + if (!selectedText || selectedText.trim().length === 0) { + new Notice('Please select some text to clean up'); + return; + } + + // Validate text length before proceeding + const limits = CleanupService.isWithinLimits(selectedText); + if (!limits.withinCharacterLimit) { + new Notice(`Selected text is too long (${limits.characterCount} characters). Maximum: 680,000 characters.`); + return; + } + + // Show loading notice + const loadingNotice = new Notice('Cleaning up text...', 0); // 0 = persistent + + try { + // Process the text + const result = await this.cleanupService.cleanupText(selectedText, settings); + + // Format the result with separator + const formattedResult = this.cleanupService.formatCleanupResult(result); + + // Get cursor position and selection range + const selectionEnd = editor.getCursor('to'); + + // Insert the formatted result below the selected text + const insertPosition = { + line: selectionEnd.line, + ch: editor.getLine(selectionEnd.line).length + }; + + // Move to end of current line and insert new content + editor.setCursor(insertPosition); + editor.replaceRange(formattedResult, insertPosition); + + // Clear the loading notice + loadingNotice.hide(); + + } catch (error) { + // Clear loading notice + loadingNotice.hide(); + + // Handle specific error types + if (error instanceof Error) { + if (error.message.includes('API key')) { + new Notice('API key error. Please check your settings.'); + } else if (error.message.includes('too long')) { + new Notice('Text is too long for processing.'); + } else if (error.message.includes('Failed after')) { + new Notice('Service temporarily unavailable. Please try again.'); + } else { + new Notice(`Cleanup failed: ${error.message}`); + } + } else { + new Notice('An unexpected error occurred during cleanup.'); + } + + console.error('Cleanup command error:', error); + throw error; + } + + } catch (error) { + console.error('Error in cleanup command:', error); + } + } + + // MARK: - Helper Methods + + private getInsertionPosition(editor: Editor): { line: number; ch: number } { + const selection = editor.listSelections()[0]; + if (selection) { + // Insert after the selection + return { + line: selection.head.line, + ch: editor.getLine(selection.head.line).length + }; + } + + // Fallback to current cursor position + return editor.getCursor(); + } + + private formatSelectedTextInfo(text: string): string { + const characterCount = text.length; + const estimatedTokens = CleanupService.estimateTokenCount(text); + const lines = text.split('\n').length; + + return `Selected: ${characterCount} characters, ${lines} lines, ~${estimatedTokens} tokens`; + } + + // MARK: - Validation Methods + + validateSelection(selectedText: string): { + isValid: boolean; + error?: string; + info?: string; + } { + if (!selectedText || selectedText.trim().length === 0) { + return { + isValid: false, + error: 'No text selected' + }; + } + + const limits = CleanupService.isWithinLimits(selectedText); + + if (!limits.withinCharacterLimit) { + return { + isValid: false, + error: `Text too long: ${limits.characterCount} characters (max: 680,000)` + }; + } + + if (!limits.withinTokenLimit) { + return { + isValid: false, + error: `Text too long: ~${limits.estimatedTokenCount} tokens (max: 200,000)` + }; + } + + return { + isValid: true, + info: this.formatSelectedTextInfo(selectedText) + }; + } +} \ No newline at end of file diff --git a/main.ts b/main.ts index 471bc8e..30b4820 100644 --- a/main.ts +++ b/main.ts @@ -1,134 +1,69 @@ -import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian'; +// ABOUTME: Main plugin file for Freewriting Cleanup - cleans up freewriting text using AI +// ABOUTME: Coordinates between services, commands, and Obsidian's plugin lifecycle -// Remember to rename these classes and interfaces! +import { Editor, MarkdownView, Plugin } from 'obsidian'; +import { FreewritingCleanupSettings } from './types'; +import { DEFAULT_SETTINGS, FreewritingCleanupSettingTab } from './settings'; +import { CleanupService } from './services/cleanupService'; +import { CleanupCommand } from './commands/cleanupCommand'; -interface MyPluginSettings { - mySetting: string; -} - -const DEFAULT_SETTINGS: MyPluginSettings = { - mySetting: 'default' -} - -export default class MyPlugin extends Plugin { - settings: MyPluginSettings; - - async onload() { - await this.loadSettings(); - - // This creates an icon in the left ribbon. - const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (_evt: MouseEvent) => { - // Called when the user clicks the icon. - new Notice('This is a notice!'); - }); - // Perform additional things with the ribbon - ribbonIconEl.addClass('my-plugin-ribbon-class'); - - // This adds a status bar item to the bottom of the app. Does not work on mobile apps. - const statusBarItemEl = this.addStatusBarItem(); - statusBarItemEl.setText('Status Bar Text'); - - // This adds a simple command that can be triggered anywhere - this.addCommand({ - id: 'open-sample-modal-simple', - name: 'Open sample modal (simple)', - callback: () => { - new SampleModal(this.app).open(); - } - }); - // This adds an editor command that can perform some operation on the current editor instance - this.addCommand({ - id: 'sample-editor-command', - name: 'Sample editor command', - editorCallback: (editor: Editor, _view: MarkdownView) => { - console.log(editor.getSelection()); - editor.replaceSelection('Sample Editor Command'); - } - }); - // This adds a complex command that can check whether the current state of the app allows execution of the command - this.addCommand({ - id: 'open-sample-modal-complex', - name: 'Open sample modal (complex)', - checkCallback: (checking: boolean) => { - // Conditions to check - const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView); - if (markdownView) { - // If checking is true, we're simply "checking" if the command can be run. - // If checking is false, then we want to actually perform the operation. - if (!checking) { - new SampleModal(this.app).open(); - } - - // This command will only show up in Command Palette when the check function returns true - return true; - } - } - }); - - // This adds a settings tab so the user can configure various aspects of the plugin - this.addSettingTab(new SampleSettingTab(this.app, this)); - - // If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin) - // Using this function will automatically remove the event listener when this plugin is disabled. - this.registerDomEvent(document, 'click', (evt: MouseEvent) => { - console.log('click', evt); - }); - - // When registering intervals, this function will automatically clear the interval when the plugin is disabled. - this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000)); - } - - onunload() { - - } - - async loadSettings() { - this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); - } - - async saveSettings() { - await this.saveData(this.settings); - } -} - -class SampleModal extends Modal { - constructor(app: App) { - super(app); - } - - onOpen() { - const {contentEl} = this; - contentEl.setText('Woah!'); - } - - onClose() { - const {contentEl} = this; - contentEl.empty(); - } -} - -class SampleSettingTab extends PluginSettingTab { - plugin: MyPlugin; - - constructor(app: App, plugin: MyPlugin) { - super(app, plugin); - this.plugin = plugin; - } - - display(): void { - const {containerEl} = this; - - containerEl.empty(); - - new Setting(containerEl) - .setName('Setting #1') - .setDesc('It\'s a secret') - .addText(text => text - .setPlaceholder('Enter your secret') - .setValue(this.plugin.settings.mySetting) - .onChange(async (value) => { - this.plugin.settings.mySetting = value; - await this.plugin.saveSettings(); - })); - } +export default class FreewritingCleanupPlugin extends Plugin { + settings: FreewritingCleanupSettings; + cleanupService: CleanupService; + cleanupCommand: CleanupCommand; + + async onload() { + await this.loadSettings(); + + // Initialize services + this.cleanupService = new CleanupService(this.settings.apiKey); + this.cleanupCommand = new CleanupCommand(this.cleanupService); + + // Register command + this.registerCommand(); + + // Add settings tab + this.addSettingTab(new FreewritingCleanupSettingTab(this.app, this)); + } + + onunload() { + // Cleanup if needed + } + + // MARK: - Settings Management + + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + + async saveSettings() { + await this.saveData(this.settings); + + // Update the cleanup service with new settings + if (this.cleanupService) { + this.cleanupService.updateApiKey(this.settings.apiKey); + } + } + + // MARK: - Command Registration + + private registerCommand() { + this.addCommand({ + id: 'cleanup-freewriting', + name: 'Clean Up Freewriting', + editorCallback: async (editor: Editor, view: MarkdownView) => { + await this.executeCleanupCommand(editor, view); + } + }); + } + + // MARK: - Command Implementation + + private async executeCleanupCommand(editor: Editor, view: MarkdownView): Promise { + try { + await this.cleanupCommand.execute(editor, view, this.settings); + } catch (error) { + console.error('Error executing cleanup command:', error); + } + } } diff --git a/package.json b/package.json index 6a00766..2d20f7b 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,15 @@ { - "name": "obsidian-sample-plugin", + "name": "freewriting-cleanup", "version": "1.0.0", - "description": "This is a sample plugin for Obsidian (https://obsidian.md)", + "description": "Use AI to clean up your freewriting typos and create a proper paragraph.", "main": "main.js", "scripts": { "dev": "node esbuild.config.mjs", "build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production", "version": "node version-bump.mjs && git add manifest.json versions.json" }, - "keywords": [], - "author": "", + "keywords": ["obsidian", "plugin", "ai", "writing", "cleanup", "anthropic", "claude"], + "author": "Alexander Kucera", "license": "MIT", "devDependencies": { "@types/node": "^16.11.6", diff --git a/services/cleanupService.ts b/services/cleanupService.ts new file mode 100644 index 0000000..f569170 --- /dev/null +++ b/services/cleanupService.ts @@ -0,0 +1,162 @@ +// 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 { + // 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 + }; + } +} \ No newline at end of file diff --git a/settings.ts b/settings.ts new file mode 100644 index 0000000..f8e6cc4 --- /dev/null +++ b/settings.ts @@ -0,0 +1,295 @@ +// ABOUTME: Settings interface and SettingTab implementation for the Freewriting Cleanup plugin +// ABOUTME: Handles user configuration including API key, model selection, and prompt customization + +import { App, ButtonComponent, Notice, PluginSettingTab, Setting } from 'obsidian'; +import FreewritingCleanupPlugin from './main'; +import { FreewritingCleanupSettings, ANTHROPIC_MODELS, AnthropicModel, COMMENTARY_STYLES, CommentaryStyle, COMMENTARY_PRESETS } from './types'; + +export const DEFAULT_SETTINGS: FreewritingCleanupSettings = { + apiKey: '', + model: 'claude-3-5-haiku-latest' as const, + cleanupPrompt: 'I did some free writing. Please correct my jumbled typo mess. Only fix spelling, grammar, and punctuation. Add line breaks and paragraphs as appropriate. Do not make stylistic changes to the content or tone.', + enableCommentary: false, + commentaryStyle: 'constructive' as const, + customCommentaryPrompt: 'Provide thoughtful feedback on this freewriting session, considering the writer\'s flow of thoughts and ideas.' +}; + +export class FreewritingCleanupSettingTab extends PluginSettingTab { + plugin: FreewritingCleanupPlugin; + + constructor(app: App, plugin: FreewritingCleanupPlugin) { + super(app, plugin); + this.plugin = plugin; + } + + display(): void { + const { containerEl } = this; + containerEl.empty(); + + containerEl.createEl('h2', { text: 'Freewriting Cleanup Settings' }); + + // MARK: - API Configuration + + containerEl.createEl('h3', { text: 'API Configuration' }); + + new Setting(containerEl) + .setName('Anthropic API Key') + .setDesc('Your Anthropic API key for Claude. Get one at https://console.anthropic.com/') + .addText(text => text + .setPlaceholder('sk-ant-...') + .setValue(this.plugin.settings.apiKey) + .onChange(async (value) => { + this.plugin.settings.apiKey = value; + await this.plugin.saveSettings(); + this.plugin.cleanupService.updateApiKey(value); + })) + .then(setting => { + // Make it a password field + setting.controlEl.querySelector('input')?.setAttribute('type', 'password'); + }); + + new Setting(containerEl) + .setName('Test API Key') + .setDesc('Test your API key to verify it works correctly') + .addButton(button => button + .setButtonText('Test Connection') + .onClick(async () => { + await this.testApiKey(button); + })); + + new Setting(containerEl) + .setName('Claude Model') + .setDesc('Which Claude model to use for text cleanup') + .addDropdown(dropdown => { + ANTHROPIC_MODELS.forEach(model => { + dropdown.addOption(model, model); + }); + dropdown + .setValue(this.plugin.settings.model) + .onChange(async (value) => { + this.plugin.settings.model = value as AnthropicModel; + await this.plugin.saveSettings(); + }); + }); + + // MARK: - Cleanup Configuration + + containerEl.createEl('h3', { text: 'Cleanup Configuration' }); + + new Setting(containerEl) + .setName('Cleanup Prompt') + .setDesc('Instructions for how Claude should clean up your freewriting text') + .addTextArea(textArea => { + textArea + .setPlaceholder('Enter your cleanup instructions...') + .setValue(this.plugin.settings.cleanupPrompt) + .onChange(async (value) => { + this.plugin.settings.cleanupPrompt = value; + await this.plugin.saveSettings(); + }); + + // Style the textarea + textArea.inputEl.rows = 4; + textArea.inputEl.style.width = '100%'; + textArea.inputEl.style.minHeight = '100px'; + }); + + // MARK: - Commentary Configuration + + containerEl.createEl('h3', { text: 'AI Commentary' }); + + new Setting(containerEl) + .setName('AI should comment on text') + .setDesc('After cleaning up your text, AI will provide thoughtful commentary on your freewriting session') + .addToggle(toggle => toggle + .setValue(this.plugin.settings.enableCommentary) + .onChange(async (value) => { + this.plugin.settings.enableCommentary = value; + await this.plugin.saveSettings(); + this.display(); // Refresh to show/hide commentary options + })); + + if (this.plugin.settings.enableCommentary) { + new Setting(containerEl) + .setName('Commentary Style') + .setDesc('Choose the type of feedback AI should provide') + .addDropdown(dropdown => { + COMMENTARY_STYLES.forEach(style => { + const displayName = style.charAt(0).toUpperCase() + style.slice(1); + dropdown.addOption(style, displayName); + }); + dropdown + .setValue(this.plugin.settings.commentaryStyle) + .onChange(async (value) => { + this.plugin.settings.commentaryStyle = value as CommentaryStyle; + await this.plugin.saveSettings(); + this.display(); // Refresh to show/hide custom prompt + }); + }); + + if (this.plugin.settings.commentaryStyle === 'custom') { + new Setting(containerEl) + .setName('Custom Commentary Prompt') + .setDesc('Instructions for how AI should comment on your freewriting') + .addTextArea(textArea => { + textArea + .setPlaceholder('Enter your commentary instructions...') + .setValue(this.plugin.settings.customCommentaryPrompt) + .onChange(async (value) => { + this.plugin.settings.customCommentaryPrompt = value; + await this.plugin.saveSettings(); + }); + + // Style the textarea + textArea.inputEl.rows = 3; + textArea.inputEl.style.width = '100%'; + textArea.inputEl.style.minHeight = '80px'; + }); + } else { + // Show the current preset for reference + const presetText = COMMENTARY_PRESETS[this.plugin.settings.commentaryStyle as Exclude]; + const descDiv = containerEl.createDiv({ cls: 'setting-item-description' }); + descDiv.style.marginLeft = '0'; + descDiv.style.padding = '10px'; + descDiv.style.backgroundColor = 'var(--background-secondary)'; + descDiv.style.borderRadius = '5px'; + descDiv.style.fontSize = '0.9em'; + descDiv.innerHTML = `Selected style: ${presetText}`; + } + } + + // MARK: - Usage Information + + containerEl.createEl('h3', { text: 'Usage Information' }); + + const usageDiv = containerEl.createDiv(); + usageDiv.innerHTML = ` +

How to use:

+
    +
  1. Select the text you want to clean up in any note
  2. +
  3. Run the "Clean Up Freewriting" command (Ctrl/Cmd+P)
  4. +
  5. The cleaned text will appear below your original text
  6. +
+

Limits: Maximum 680,000 characters (~150,000 words) per cleanup

+

Format: Original text → separator → cleaned text

+ `; + + // MARK: - Reset Settings + + containerEl.createEl('h3', { text: 'Reset' }); + + new Setting(containerEl) + .setName('Reset to Defaults') + .setDesc('Reset all settings to their default values') + .addButton(button => button + .setButtonText('Reset Settings') + .setWarning() + .onClick(async () => { + await this.resetSettings(); + })); + } + + // MARK: - Private Methods + + private async testApiKey(button: ButtonComponent): Promise { + const originalText = button.buttonEl.textContent; + button.setButtonText('Testing...'); + button.setDisabled(true); + + try { + const result = await this.plugin.cleanupService.testConnection(this.plugin.settings); + + if (result.success) { + new Notice('✅ API connection successful!'); + if (result.details) { + const details = result.details; + new Notice(`Model: ${details.model}, Response time: ${details.responseTime}ms`); + } + } else { + new Notice(`❌ API test failed: ${result.message}`); + } + } catch (error) { + new Notice(`❌ API test failed: ${error instanceof Error ? error.message : 'Unknown error'}`); + } finally { + button.setButtonText(originalText || 'Test Connection'); + button.setDisabled(false); + } + } + + private async resetSettings(): Promise { + // Confirm the reset + const confirmed = await this.showConfirmDialog('Reset Settings', + 'Are you sure you want to reset all settings to their defaults? This cannot be undone.'); + + if (confirmed) { + // Keep the API key but reset everything else + const currentApiKey = this.plugin.settings.apiKey; + this.plugin.settings = { ...DEFAULT_SETTINGS, apiKey: currentApiKey }; + + await this.plugin.saveSettings(); + this.plugin.cleanupService.updateApiKey(currentApiKey); + + // Refresh the settings display + this.display(); + + new Notice('Settings reset to defaults'); + } + } + + private async showConfirmDialog(title: string, message: string): Promise { + return new Promise((resolve) => { + const modal = new ConfirmModal(this.app, title, message, (result) => { + resolve(result); + }); + modal.open(); + }); + } +} + +// Simple confirmation modal +class ConfirmModal { + private app: App; + private title: string; + private message: string; + private callback: (result: boolean) => void; + private modalEl: HTMLElement; + + constructor(app: App, title: string, message: string, callback: (result: boolean) => void) { + this.app = app; + this.title = title; + this.message = message; + this.callback = callback; + } + + open(): void { + // Create modal backdrop + this.modalEl = document.createElement('div'); + this.modalEl.className = 'modal-container mod-dim'; + + // Create modal content + const modal = this.modalEl.createDiv('modal'); + const header = modal.createDiv('modal-header'); + header.createEl('h3', { text: this.title }); + + const content = modal.createDiv('modal-content'); + content.createEl('p', { text: this.message }); + + const buttons = modal.createDiv('modal-button-container'); + + const cancelButton = buttons.createEl('button', { text: 'Cancel' }); + cancelButton.onclick = () => this.close(false); + + const confirmButton = buttons.createEl('button', { text: 'Confirm', cls: 'mod-warning' }); + confirmButton.onclick = () => this.close(true); + + document.body.appendChild(this.modalEl); + confirmButton.focus(); + } + + private close(result: boolean): void { + if (this.modalEl && this.modalEl.parentNode) { + this.modalEl.parentNode.removeChild(this.modalEl); + } + this.callback(result); + } +} \ No newline at end of file diff --git a/types.ts b/types.ts new file mode 100644 index 0000000..b5a8567 --- /dev/null +++ b/types.ts @@ -0,0 +1,89 @@ +// ABOUTME: Type definitions for the Freewriting Cleanup plugin +// ABOUTME: Defines interfaces for settings, API responses, and plugin configuration + +export interface FreewritingCleanupSettings { + apiKey: string; + model: AnthropicModel; + cleanupPrompt: string; + enableCommentary: boolean; + commentaryStyle: CommentaryStyle; + customCommentaryPrompt: string; +} + +export interface AnthropicMessage { + role: 'user' | 'assistant' | 'system'; + content: string; +} + +export interface AnthropicRequest { + model: string; + max_tokens: number; + messages: AnthropicMessage[]; + system?: string; +} + +export interface AnthropicResponse { + content: Array<{ + text: string; + type: 'text'; + }>; + id: string; + model: string; + role: 'assistant'; + stop_reason: string; + stop_sequence: null; + type: 'message'; + usage: { + input_tokens: number; + output_tokens: number; + }; +} + +export interface CleanupResult { + originalText: string; + cleanedText: string; + commentary?: string; + timestamp: Date; + model: string; + tokensUsed: { + input: number; + output: number; + }; +} + +export const ANTHROPIC_MODELS = [ + 'claude-opus-4-1-20250805', + 'claude-opus-4-20250514', + 'claude-sonnet-4-20250514', + 'claude-3-7-sonnet-latest', + 'claude-3-5-haiku-latest', + 'claude-3-haiku-20240307' +] as const; + +export type AnthropicModel = typeof ANTHROPIC_MODELS[number]; + +// Commentary style options +export const COMMENTARY_STYLES = [ + 'constructive', + 'encouraging', + 'analytical', + 'brief', + 'custom' +] as const; + +export type CommentaryStyle = typeof COMMENTARY_STYLES[number]; + +// Preset commentary prompts +export const COMMENTARY_PRESETS: Record, string> = { + constructive: 'Provide balanced feedback on this freewriting, noting strengths and areas for development. Consider the flow of ideas, creativity, and any interesting themes that emerged.', + encouraging: 'Offer positive, supportive observations about this freewriting session. Focus on what worked well, creative insights, and encouraging the writer to continue exploring these ideas.', + analytical: 'Analyze the writing structure, themes, and patterns in this freewriting. Look at the progression of thoughts, recurring concepts, and the overall coherence of ideas.', + brief: 'Give 2-3 concise observations about this freewriting session. Keep it short but insightful.' +}; + +// Constants for Anthropic API limits +export const ANTHROPIC_LIMITS = { + MAX_TOKENS: 200000, + MAX_CHARACTERS: 680000, + DEFAULT_MAX_OUTPUT_TOKENS: 4000 +} as const; \ No newline at end of file