-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.ts
379 lines (328 loc) · 13.2 KB
/
main.ts
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import { Plugin, WorkspaceLeaf, TFile, TFolder, requestUrl, Notice, normalizePath, MarkdownView } from 'obsidian';
import { MeshView, MESH_VIEW_TYPE } from './views/MeshView';
import { SettingsView } from './views/SettingsView';
import { PluginSettings, DEFAULT_SETTINGS, ProviderName, Workflow, GitHubApiItem , SearchProviderName } from './types';
import { OpenAIProvider } from './providers/OpenAIProvider';
import { GoogleProvider } from './providers/GoogleProvider';
import { MicrosoftProvider } from './providers/MicrosoftProvider';
import { AnthropicProvider } from './providers/AnthropicProvider';
import { GrocqProvider } from './providers/GrocqProvider';
import { OllamaProvider } from './providers/OllamaProvider';
import { YoutubeProvider } from './providers/YoutubeProvider';
import { TavilyProvider } from './providers/TavilyProvider';
import { debugLog } from './utils/MeshUtils';
import { ProcessActiveNoteModal } from './modals/ProcessActiveNoteModal';
import { ProcessClipboardModal } from 'modals/ProcessClipboardModal';
import { TavilySearchModal } from 'modals/TavilySearchModal';
import { TavilySearchModalWF } from 'modals/TavilySearchModalWF';
import { processWorkflow } from './utils/WorkflowUtils';
import { createOutputFile } from './utils/FileUtils';
import { processPatterns, processStitchedPatterns, getInputContent } from './utils/MeshUtils';
import { PerplexityProvider } from 'providers/PerplexityProvider';
import { OpenRouterProvider } from './providers/OpenRouterProvider';
import { LMStudioProvider } from './providers/LMStudioProvider';
import { AnalyzePathwaysModal } from 'modals/AnalyzePathwaysModal';
export default class MeshAIPlugin extends Plugin {
settings: PluginSettings;
youtubeProvider: YoutubeProvider;
tavilyProvider: TavilyProvider;
perplexityProvider: PerplexityProvider;
async onload() {
await this.loadSettings();
this.fixFolderPaths();
this.youtubeProvider = new YoutubeProvider(this);
this.tavilyProvider = new TavilyProvider(this.settings.tavilyApiKey, this);
this.addSettingTab(new SettingsView(this.app, this));
this.registerView(
MESH_VIEW_TYPE,
(leaf) => new MeshView(leaf, this)
);
// Add the new commands
this.addCommand({
id: 'process-active-note',
name: 'Process Active Note',
callback: () => {
new ProcessActiveNoteModal(this.app, this).open();
}
});
this.addCommand({
id: 'process-clipboard',
name: 'Process Clipboard',
callback: () => {
new ProcessClipboardModal(this.app, this).open();
}
});
this.addCommand({
id: 'tavily-search',
name: 'Tavily Search',
callback: () => {
new TavilySearchModal(this.app, this).open();
}
});
this.addCommand({
id: 'analyze-pathways',
name: 'Analyze Pathways',
callback: () => {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (activeView) {
const content = activeView.getViewData();
new AnalyzePathwaysModal(this.app, this, content).open();
} else {
new Notice('Please open a markdown file to analyze pathways.');
}
}
});
// Add workflow commands
this.createWorkflowCommands();
this.addRibbonIcon('brain', 'Mesh AI Integration', () => {
this.activateView();
});
// Add process selection menu item
this.registerEvent(
this.app.workspace.on('editor-menu', (menu, editor) => {
// Only add the menu item if there's selected text
if (editor.getSelection()) {
menu.addItem((item) => {
item
.setTitle('Mesh AI: Process Selection')
.setIcon('brain')
.onClick(async () => {
// Copy the selected text to clipboard
const selectedText = editor.getSelection();
await navigator.clipboard.writeText(selectedText);
// Open the process clipboard modal
new ProcessClipboardModal(this.app, this).open();
});
});
}
})
);
}
createWorkflowCommands() {
// Remove existing workflow commands
this.removeWorkflowCommands();
// Add new workflow commands
this.settings.workflows.forEach((workflow, index) => {
this.addCommand({
id: `mesh-ai-workflow-${index + 1}-active-note`,
name: `Run Workflow: ${workflow.name} (Active Note)`,
callback: () => this.runWorkflow(workflow, 'active-note'),
});
this.addCommand({
id: `mesh-ai-workflow-${index + 1}-clipboard`,
name: `Run Workflow: ${workflow.name} (Clipboard)`,
callback: () => this.runWorkflow(workflow, 'clipboard'),
});
this.addCommand({
id: `mesh-ai-workflow-${index + 1}-tavily`,
name: `Run Workflow: ${workflow.name} (Tavily)`,
callback: () => new TavilySearchModalWF(this.app, this, workflow).open(),
});
});
}
private removeWorkflowCommands() {
// This method will be called when reloading commands
// It doesn't need to do anything as Obsidian handles command cleanup automatically
}
async runWorkflow(workflow: Workflow, inputType: 'active-note' | 'clipboard') {
let notice = new Notice(`Running workflow: ${workflow.name}...`, 0);
let input: string;
try {
let result: string;
if (workflow.usePatternStitching) {
input = await getInputContent(this.app, this, inputType)
result = await processStitchedPatterns(this, workflow.provider, workflow.patterns, input);
} else {
input = await getInputContent(this.app, this, inputType)
result = await processPatterns(this, workflow.provider, workflow.patterns, input);
}
const fileName = `Workflow Output ${new Date().toISOString().replace(/:/g, '-')}`;
await createOutputFile(this, result, fileName);
new Notice(`Workflow '${workflow.name}' processed successfully`);
} catch (error) {
console.error('Error processing workflow:', error);
new Notice(`Error in workflow '${workflow.name}': ${error instanceof Error ? error.message : String(error)}`);
} finally {
notice.hide();
}
}
async loadParticlesJS() {
return new Promise<void>((resolve) => {
if (typeof (window as any).particlesJS === 'function') {
console.log('particlesJS loaded successfully');
resolve();
} else {
console.error('particlesJS is not available');
resolve();
}
});
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
async activateView() {
const { workspace } = this.app;
let leaf = workspace.getLeavesOfType(MESH_VIEW_TYPE)[0];
if (!leaf) {
const rightLeaf = workspace.getRightLeaf(false);
if (rightLeaf) {
await rightLeaf.setViewState({ type: MESH_VIEW_TYPE, active: true });
leaf = rightLeaf;
} else {
leaf = workspace.getLeaf('split', 'vertical');
await leaf.setViewState({ type: MESH_VIEW_TYPE, active: true });
}
}
workspace.revealLeaf(leaf);
}
async loadAllPatterns(): Promise<string[]> {
const customPatterns = await this.loadCustomPatterns();
const fabricPatterns = await this.loadFabricPatterns();
return [...new Set([...customPatterns, ...fabricPatterns])].sort();
}
async loadCustomPatterns(): Promise<string[]> {
const folder = this.app.vault.getAbstractFileByPath(this.settings.customPatternsFolder);
const patterns: string[] = [];
if (folder instanceof TFolder) {
for (const file of folder.children) {
if (file instanceof TFile && file.extension === 'md') {
patterns.push(file.basename);
}
}
}
return patterns.sort();
}
async loadFabricPatterns(): Promise<string[]> {
const normalizedPath = normalizePath(this.settings.fabricPatternsFolder);
const folder = this.app.vault.getAbstractFileByPath(normalizedPath);
const patterns: string[] = [];
if (folder instanceof TFolder) {
for (const file of folder.children) {
if (file instanceof TFile && file.extension === 'md') {
patterns.push(file.basename);
}
}
}
return patterns.sort();
}
async downloadPatternsFromGitHub() {
const apiUrl = 'https://api.github.com/repos/danielmiessler/fabric/contents/patterns';
const baseRawUrl = 'https://raw.githubusercontent.com/danielmiessler/fabric/main/patterns';
try {
// Ensure the Fabric Patterns folder exists
const normalizedFolderPath = normalizePath(this.settings.fabricPatternsFolder);
const fabricPatternsFolder = this.app.vault.getAbstractFileByPath(normalizedFolderPath);
if (!(fabricPatternsFolder instanceof TFolder)) {
await this.app.vault.createFolder(normalizedFolderPath);
}
// Fetch the list of folders in the patterns directory
const response = await requestUrl({ url: apiUrl });
const items = response.json as GitHubApiItem[];
const folders = items.filter((item) => item.type === 'dir');
let successCount = 0;
let failCount = 0;
for (const folder of folders) {
try {
const fileName = `${folder.name}.md`;
const fileUrl = `${baseRawUrl}/${folder.name}/system.md`;
const filePath = normalizePath(`${this.settings.fabricPatternsFolder}/${fileName}`);
// Fetch the content of the system.md file
const fileContent = await requestUrl({ url: fileUrl });
// Check if the file already exists
const existingFile = this.app.vault.getAbstractFileByPath(filePath);
if (existingFile instanceof TFile) {
// If file exists, update its content
await this.app.vault.modify(existingFile, fileContent.text);
debugLog(this, `Updated existing file: ${fileName}`);
} else {
// If file doesn't exist, create it
await this.app.vault.create(filePath, fileContent.text);
debugLog(this, `Created new file: ${fileName}`);
}
successCount++;
} catch (error) {
debugLog(this, `Error processing ${folder.name}:`, error);
if (error instanceof Error) {
debugLog(this, `Error message: ${error.message}`);
debugLog(this, `Error stack: ${error.stack}`);
}
failCount++;
}
}
new Notice(`Successfully downloaded/updated ${successCount} patterns. ${failCount} failed.`);
await this.loadAllPatterns();
} catch (error) {
debugLog(this, 'Error in downloadPatternsFromGitHub:', error);
new Notice(`Failed to download patterns: ${error.message}`);
}
}
async clearFabricPatternsFolder() {
const fabricPatternsFolder = this.app.vault.getAbstractFileByPath(this.settings.fabricPatternsFolder);
if (fabricPatternsFolder instanceof TFolder) {
for (const file of fabricPatternsFolder.children) {
if (file instanceof TFile) {
await this.app.fileManager.trashFile(file);
}
}
} else {
// If the folder doesn't exist, create it
await this.app.vault.createFolder(this.settings.fabricPatternsFolder);
}
}
getProvider(providerName: ProviderName) {
switch (providerName) {
case 'openai':
return new OpenAIProvider(this.settings.openaiApiKey, this);
case 'google':
return new GoogleProvider(this.settings.googleApiKey, this);
case 'microsoft':
return new MicrosoftProvider(this.settings.microsoftApiKey, this);
case 'anthropic':
return new AnthropicProvider(this.settings.anthropicApiKey, this);
case 'grocq':
return new GrocqProvider(this.settings.grocqApiKey, this);
case 'ollama':
return new OllamaProvider(this.settings.ollamaServerUrl, this);
case 'openrouter':
return new OpenRouterProvider(this.settings.openrouterApiKey, this);
case 'lmstudio':
return new LMStudioProvider(this.settings.lmstudioServerUrl, this);
default:
throw new Error(`Unknown provider: ${providerName}`);
}
}
getSearchProvider(providerName: SearchProviderName) {
switch (providerName) {
case 'tavily':
return new TavilyProvider(this.settings.tavilyApiKey, this);
case 'perplexity':
return new PerplexityProvider(this.settings.perplexityApiKey, this);
default:
throw new Error(`Unsupported search provider: ${providerName}`);
}
}
reloadMeshView() {
const meshLeaves = this.app.workspace.getLeavesOfType(MESH_VIEW_TYPE);
meshLeaves.forEach((leaf) => {
if (leaf.view instanceof MeshView) {
(leaf.view as MeshView).onOpen();
}
});
}
fixFolderPaths() {
const pathsToFix = ['customPatternsFolder', 'fabricPatternsFolder', 'meshOutputFolder'];
let settingsChanged = false;
for (const path of pathsToFix) {
if (typeof this.settings[path] === 'string' && this.settings[path].includes('\\')) {
this.settings[path] = (this.settings[path] as string).replace(/\\/g, '/');
settingsChanged = true;
}
}
if (settingsChanged) {
this.saveSettings();
}
}
}