|
| 1 | +/*--------------------------------------------------------------------------------------------- |
| 2 | + * Atom++ — AI (M2, feature 2: inline tab-completion) |
| 3 | + * |
| 4 | + * Ghost-text completions as you type, accepted with Tab. Uses VS Code's stable |
| 5 | + * InlineCompletionItemProvider API (no core patches). Requests go directly to the |
| 6 | + * provider (Claude / Ollama) — debounced, and cancelled the moment you keep typing. |
| 7 | + *--------------------------------------------------------------------------------------------*/ |
| 8 | +// @ts-check |
| 9 | +'use strict'; |
| 10 | + |
| 11 | +const vscode = require('vscode'); |
| 12 | + |
| 13 | +const PREFIX_MAX = 2500; // chars of context before the cursor (smaller = faster first token) |
| 14 | +const SUFFIX_MAX = 1000; // chars of context after the cursor |
| 15 | +const MAX_TOKENS = 160; // keep completions short & snappy |
| 16 | + |
| 17 | +const SYSTEM_PROMPT = |
| 18 | + 'You are a code completion engine inside the Atom++ editor. You are given the code ' + |
| 19 | + 'before the cursor and the code after it, with the insertion point marked <CURSOR>. ' + |
| 20 | + 'Reply with ONLY the raw code that should be inserted at <CURSOR> to continue the code ' + |
| 21 | + 'naturally. Do NOT repeat code that already exists before or after the cursor. Do NOT ' + |
| 22 | + 'wrap your answer in markdown fences. Do NOT add explanations. If no completion is ' + |
| 23 | + 'appropriate, reply with an empty string.'; |
| 24 | + |
| 25 | +/** @param {vscode.CancellationToken} token */ |
| 26 | +function sleep(ms, token) { |
| 27 | + return new Promise((resolve) => { |
| 28 | + const t = setTimeout(resolve, ms); |
| 29 | + token.onCancellationRequested(() => { clearTimeout(t); resolve(undefined); }); |
| 30 | + }); |
| 31 | +} |
| 32 | + |
| 33 | +/** Build prefix/suffix context windows around the cursor. */ |
| 34 | +function buildContext(document, position) { |
| 35 | + const start = new vscode.Position(0, 0); |
| 36 | + const lastLine = document.lineAt(document.lineCount - 1); |
| 37 | + const end = lastLine.range.end; |
| 38 | + const pre = document.getText(new vscode.Range(start, position)); |
| 39 | + const suf = document.getText(new vscode.Range(position, end)); |
| 40 | + return { prefix: pre.slice(-PREFIX_MAX), suffix: suf.slice(0, SUFFIX_MAX) }; |
| 41 | +} |
| 42 | + |
| 43 | +/** Strip accidental markdown fences / leading language tags the model may add. */ |
| 44 | +function clean(text) { |
| 45 | + if (!text) { return ''; } |
| 46 | + let t = text; |
| 47 | + const fence = String.fromCharCode(96, 96, 96); |
| 48 | + if (t.indexOf(fence) >= 0) { |
| 49 | + // Take the content of the first fenced block if the whole thing got wrapped. |
| 50 | + const m = t.match(new RegExp(fence + '[a-zA-Z0-9_+-]*\\n?([\\s\\S]*?)' + fence)); |
| 51 | + if (m) { t = m[1]; } |
| 52 | + else { t = t.split(fence).join(''); } |
| 53 | + } |
| 54 | + return t; |
| 55 | +} |
| 56 | + |
| 57 | +/** |
| 58 | + * @param {vscode.ExtensionContext} context |
| 59 | + * @param {{ aiConfig: () => vscode.WorkspaceConfiguration, |
| 60 | + * getKeySilent: () => Thenable<string|undefined>, |
| 61 | + * completeClaude: Function, completeOllama: Function }} deps |
| 62 | + */ |
| 63 | +function registerInlineComplete(context, deps) { |
| 64 | + const { aiConfig, getKeySilent, completeClaude, completeOllama } = deps; |
| 65 | + |
| 66 | + // --- status bar toggle --------------------------------------------------- |
| 67 | + const status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 50); |
| 68 | + status.command = 'atompp.ai.toggleCompletions'; |
| 69 | + function refreshStatus() { |
| 70 | + const on = aiConfig().get('completions.enabled', true); |
| 71 | + status.text = on ? '$(sparkle) AI' : '$(circle-slash) AI'; |
| 72 | + status.tooltip = on |
| 73 | + ? 'Atom++ AI inline completions: ON (click to disable)' |
| 74 | + : 'Atom++ AI inline completions: OFF (click to enable)'; |
| 75 | + status.show(); |
| 76 | + } |
| 77 | + refreshStatus(); |
| 78 | + |
| 79 | + context.subscriptions.push( |
| 80 | + status, |
| 81 | + vscode.commands.registerCommand('atompp.ai.toggleCompletions', async () => { |
| 82 | + const cfg = aiConfig(); |
| 83 | + const next = !cfg.get('completions.enabled', true); |
| 84 | + await cfg.update('completions.enabled', next, vscode.ConfigurationTarget.Global); |
| 85 | + refreshStatus(); |
| 86 | + vscode.window.setStatusBarMessage('Atom++ AI completions ' + (next ? 'enabled' : 'disabled'), 2000); |
| 87 | + }), |
| 88 | + vscode.workspace.onDidChangeConfiguration((e) => { |
| 89 | + if (e.affectsConfiguration('atompp.ai.completions')) { refreshStatus(); } |
| 90 | + }) |
| 91 | + ); |
| 92 | + |
| 93 | + // --- the provider -------------------------------------------------------- |
| 94 | + /** @type {vscode.InlineCompletionItemProvider} */ |
| 95 | + const provider = { |
| 96 | + async provideInlineCompletionItems(document, position, ctx, token) { |
| 97 | + const cfg = aiConfig(); |
| 98 | + if (!cfg.get('completions.enabled', true)) { return null; } |
| 99 | + if (document.uri.scheme !== 'file' && document.uri.scheme !== 'untitled') { return null; } |
| 100 | + |
| 101 | + // Debounce: if the user keeps typing, this token is cancelled and we bail. |
| 102 | + const debounce = Math.max(0, cfg.get('completions.debounce', 150)); |
| 103 | + await sleep(debounce, token); |
| 104 | + if (token.isCancellationRequested) { return null; } |
| 105 | + |
| 106 | + const provider2 = cfg.get('provider', 'claude'); |
| 107 | + const { prefix, suffix } = buildContext(document, position); |
| 108 | + if (!prefix.trim() && !suffix.trim()) { return null; } |
| 109 | + |
| 110 | + const userContent = |
| 111 | + 'Language: ' + (document.languageId || 'plaintext') + '\n' + |
| 112 | + 'Insert code at <CURSOR>. Reply with ONLY the text to insert.\n\n' + |
| 113 | + prefix + '<CURSOR>' + suffix; |
| 114 | + |
| 115 | + const ac = new AbortController(); |
| 116 | + const sub = token.onCancellationRequested(() => ac.abort()); |
| 117 | + |
| 118 | + let text = ''; |
| 119 | + try { |
| 120 | + if (provider2 === 'claude') { |
| 121 | + const key = await getKeySilent(); |
| 122 | + if (!key || token.isCancellationRequested) { return null; } |
| 123 | + text = await completeClaude({ |
| 124 | + apiKey: key, |
| 125 | + model: cfg.get('completions.model', 'claude-haiku-4-5-20251001'), |
| 126 | + maxTokens: MAX_TOKENS, |
| 127 | + system: SYSTEM_PROMPT, |
| 128 | + messages: [{ role: 'user', content: userContent }], |
| 129 | + signal: ac.signal |
| 130 | + }); |
| 131 | + } else { |
| 132 | + text = await completeOllama({ |
| 133 | + url: cfg.get('ollama.url', 'http://localhost:11434'), |
| 134 | + model: cfg.get('ollama.model', 'llama3.1'), |
| 135 | + system: SYSTEM_PROMPT, |
| 136 | + messages: [{ role: 'user', content: userContent }], |
| 137 | + signal: ac.signal |
| 138 | + }); |
| 139 | + } |
| 140 | + } catch (e) { |
| 141 | + // Network/abort/key errors are silent — inline completion must never nag. |
| 142 | + return null; |
| 143 | + } finally { |
| 144 | + sub.dispose(); |
| 145 | + } |
| 146 | + |
| 147 | + if (token.isCancellationRequested) { return null; } |
| 148 | + const insert = clean(text); |
| 149 | + if (!insert.trim()) { return null; } |
| 150 | + // Avoid suggesting text that just duplicates what's already after the cursor. |
| 151 | + if (suffix.startsWith(insert)) { return null; } |
| 152 | + |
| 153 | + const item = new vscode.InlineCompletionItem(insert, new vscode.Range(position, position)); |
| 154 | + return [item]; |
| 155 | + } |
| 156 | + }; |
| 157 | + |
| 158 | + context.subscriptions.push( |
| 159 | + vscode.languages.registerInlineCompletionItemProvider({ pattern: '**' }, provider) |
| 160 | + ); |
| 161 | +} |
| 162 | + |
| 163 | +module.exports = { registerInlineComplete }; |
0 commit comments