-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.ts
More file actions
383 lines (334 loc) · 11.6 KB
/
main.ts
File metadata and controls
383 lines (334 loc) · 11.6 KB
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
380
381
382
383
import { Editor, MarkdownView, Notice, Plugin, WorkspaceLeaf } from "obsidian";
import type { LLMPluginSettings, LLMProvider } from "./src/types";
import { DEFAULT_SETTINGS } from "./src/types";
import { LLMSettingTab } from "./src/settings/SettingsTab";
import { QuickPromptModal } from "./src/modals";
import { ChatView, CHAT_VIEW_TYPE } from "./src/views";
import { LLMExecutor, detectAvailableProviders } from "./src/executor/LLMExecutor";
export default class LLMPlugin extends Plugin {
settings: LLMPluginSettings;
private executor: LLMExecutor | null = null;
private statusBarEl: HTMLElement | null = null;
async onload() {
await this.loadSettings();
// Initialize executor
this.executor = new LLMExecutor(this.settings);
// Register the chat view
this.registerView(CHAT_VIEW_TYPE, (leaf) => new ChatView(leaf, this));
// Add ribbon icon for quick chat
this.addRibbonIcon("message-square", "Open LLM Chat", () => {
this.activateChatView();
});
// Add status bar item
this.statusBarEl = this.addStatusBarItem();
this.statusBarEl.addClass("llm-status-bar-item");
this.updateStatusBar();
// Command: Open LLM Chat
this.addCommand({
id: "open-llm-chat",
name: "Open Chat",
callback: () => {
this.activateChatView();
},
});
// Command: Quick Prompt
this.addCommand({
id: "quick-llm-prompt",
name: "Quick Prompt",
callback: () => {
new QuickPromptModal(this.app, this).open();
},
});
// Command: Send Selection to LLM
this.addCommand({
id: "send-selection-to-llm",
name: "Send Selection to LLM",
editorCallback: (editor: Editor, view: MarkdownView) => {
const selection = editor.getSelection();
if (!selection) {
new Notice("No text selected");
return;
}
new QuickPromptModal(this.app, this, {
initialText: selection,
onResponse: (response) => {
this.insertResponse(editor, response);
},
}).open();
},
});
// Command: Summarize Selection
this.addCommand({
id: "summarize-selection",
name: "Summarize Selection",
editorCallback: (editor: Editor, view: MarkdownView) => {
const selection = editor.getSelection();
if (!selection) {
new Notice("No text selected");
return;
}
new QuickPromptModal(this.app, this, {
initialText: selection,
promptPrefix: "Please summarize the following text concisely:",
onResponse: (response) => {
this.insertResponse(editor, response);
},
}).open();
},
});
// Command: Explain Selection
this.addCommand({
id: "explain-selection",
name: "Explain Selection",
editorCallback: (editor: Editor, view: MarkdownView) => {
const selection = editor.getSelection();
if (!selection) {
new Notice("No text selected");
return;
}
new QuickPromptModal(this.app, this, {
initialText: selection,
promptPrefix: "Please explain the following in simple terms:",
onResponse: (response) => {
this.insertResponse(editor, response);
},
}).open();
},
});
// Command: Improve Writing
this.addCommand({
id: "improve-writing",
name: "Improve Writing",
editorCallback: (editor: Editor, view: MarkdownView) => {
const selection = editor.getSelection();
if (!selection) {
new Notice("No text selected");
return;
}
new QuickPromptModal(this.app, this, {
initialText: selection,
promptPrefix:
"Please improve the following text for clarity and readability while preserving the meaning:",
onResponse: (response) => {
this.insertResponse(editor, response);
},
}).open();
},
});
// Command: Generate from Context
this.addCommand({
id: "generate-from-context",
name: "Generate from Current Note Context",
editorCallback: async (editor: Editor, view: MarkdownView) => {
const content = editor.getValue();
const cursor = editor.getCursor();
new QuickPromptModal(this.app, this, {
promptPrefix: `Given the following note content, please continue writing or answer questions about it:\n\n---\n${content.slice(0, 2000)}${content.length > 2000 ? "..." : ""}\n---\n\nYour request:`,
onResponse: (response) => {
this.insertResponse(editor, response);
},
}).open();
},
});
// Command: Detect Available Providers
this.addCommand({
id: "detect-providers",
name: "Detect Available Providers",
callback: async () => {
new Notice("Detecting available LLM providers...");
const available = await detectAvailableProviders();
if (available.length === 0) {
new Notice("No LLM CLI tools detected. Please install claude, opencode, codex, or gemini CLI.");
} else {
new Notice(`Available providers: ${available.join(", ")}`);
}
},
});
// Add settings tab
this.addSettingTab(new LLMSettingTab(this.app, this));
}
onunload() {
this.executor?.cancel();
// Detach all chat view leaves
this.app.workspace.detachLeavesOfType(CHAT_VIEW_TYPE);
}
/**
* Activate or reveal the chat view panel
*/
async activateChatView() {
const { workspace } = this.app;
let leaf: WorkspaceLeaf | null = null;
const leaves = workspace.getLeavesOfType(CHAT_VIEW_TYPE);
if (leaves.length > 0) {
// View already exists, reveal it
leaf = leaves[0];
} else {
// Create a new leaf in the right sidebar
leaf = workspace.getRightLeaf(false);
if (leaf) {
await leaf.setViewState({ type: CHAT_VIEW_TYPE, active: true });
}
}
if (leaf) {
workspace.revealLeaf(leaf);
}
return leaf;
}
/**
* Get the ChatView instance if it exists
*/
getChatView(): ChatView | null {
const leaves = this.app.workspace.getLeavesOfType(CHAT_VIEW_TYPE);
if (leaves.length > 0) {
return leaves[0].view as ChatView;
}
return null;
}
/**
* Add a message exchange to the chat view
*/
addToChatView(userMessage: string, assistantMessage: string, provider: LLMProvider) {
const chatView = this.getChatView();
if (chatView) {
chatView.addMessageExchange(userMessage, assistantMessage, provider);
}
}
async loadSettings() {
const loadedData = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, loadedData ?? {});
// Migration: handle old systemPrompt string setting
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const oldData = loadedData as any;
if (oldData?.systemPrompt && typeof oldData.systemPrompt === "string" && oldData.systemPrompt.trim()) {
// Old inline system prompt exists - show migration notice
new Notice(
"System prompt settings have changed. Please create a note with your system prompt and select it in settings.",
10000
);
}
// Migration: handle old per-provider timeout (ensure defaultTimeout exists)
if (this.settings.defaultTimeout === undefined) {
this.settings.defaultTimeout = 120;
}
}
async saveSettings() {
await this.saveData(this.settings);
// Update executor with new settings
this.executor?.updateSettings(this.settings);
this.updateStatusBar();
}
/**
* Insert LLM response into the editor based on settings
*/
private insertResponse(editor: Editor, response: string) {
const position = this.settings.insertPosition;
switch (position) {
case "cursor":
editor.replaceRange(response, editor.getCursor());
break;
case "end":
const lastLine = editor.lastLine();
const lastLineContent = editor.getLine(lastLine);
editor.replaceRange(
"\n\n" + response,
{ line: lastLine, ch: lastLineContent.length }
);
break;
case "replace-selection":
editor.replaceSelection(response);
break;
}
new Notice("LLM response inserted");
}
/**
* Update the status bar with current provider and model info
* @param provider Optional provider to display (uses default if not specified)
* @param actualModelName Optional actual model name from ACP session (overrides configured model display)
* @param status Optional status: "idle" (default), "connecting", "connected"
*/
updateStatusBar(provider?: LLMProvider, actualModelName?: string, status?: "idle" | "connecting" | "connected") {
if (!this.statusBarEl) return;
const displayProvider = provider ?? this.settings.defaultProvider;
const providerConfig = this.settings.providers[displayProvider];
const providerNames: Record<string, string> = {
claude: "Claude",
opencode: "OpenCode",
codex: "Codex",
gemini: "Gemini",
};
this.statusBarEl.empty();
this.statusBarEl.addClass("llm-status-bar");
const indicator = this.statusBarEl.createSpan({ cls: "llm-status-indicator" });
// Build status text with provider and model
let statusText = providerNames[displayProvider] || displayProvider;
if (status === "connecting") {
statusText += " (connecting...)";
} else if (actualModelName) {
// Use actual model name from ACP session
statusText += ` (${this.formatModelName(actualModelName)})`;
} else if (providerConfig?.model) {
// Show configured model name
statusText += ` (${this.formatModelName(providerConfig.model)})`;
} else {
// Indicate CLI default is being used
statusText += " (default)";
}
this.statusBarEl.createSpan({
text: ` LLM: ${statusText}`,
cls: "llm-status-text",
});
// Set indicator state based on status
if (status === "connecting") {
indicator.addClass("connecting");
} else if (providerConfig?.enabled) {
indicator.addClass("active");
}
}
/**
* Format model name for display (abbreviate long names)
*/
private formatModelName(model: string): string {
// Common abbreviations for model IDs
const abbreviations: Record<string, string> = {
"claude-3-5-haiku-latest": "haiku",
"claude-3-5-sonnet-latest": "sonnet-3.5",
"claude-sonnet-4-20250514": "sonnet-4",
"claude-opus-4-20250514": "opus-4",
"gemini-3.0-flash": "flash-3.0",
"gemini-2.0-flash-lite": "flash-lite",
"gemini-2.0-flash": "flash-2.0",
"gemini-2.5-flash": "flash-2.5",
"gemini-2.5-pro": "pro-2.5",
"gpt-4o-mini": "4o-mini",
"gpt-4o": "4o",
"gpt-5-nano": "5-nano",
"gpt-5-mini": "5-mini",
"gpt-5": "5",
"claude-sonnet": "sonnet",
"claude-haiku": "haiku",
// ACP display names (from Claude ACP adapter)
"default": "opus",
"Default (recommended)": "opus",
"Sonnet": "sonnet",
"Haiku": "haiku",
};
// Check for exact match first
if (abbreviations[model]) {
return abbreviations[model];
}
// Try case-insensitive match
const lowerModel = model.toLowerCase();
for (const [key, value] of Object.entries(abbreviations)) {
if (key.toLowerCase() === lowerModel) {
return value;
}
}
// If model name is long, try to extract a shorter name
// Remove text in parentheses and trim
const simplified = model.replace(/\s*\([^)]*\)\s*/g, "").trim();
if (simplified !== model && simplified.length > 0) {
return this.formatModelName(simplified);
}
return model;
}
}