Files
LLeMbas-IDE/vscode/extension.js
T
HomerandClaude Fable 5.2 d095de0458 VS Code: sign in and out, the server's minimum version, an accessible page; docs and changelog
LLeMbas: Sign In / Sign Out run the CLI's own sign-in and say whose it replaces. The chat page tells
a screen reader what happens and is operable with the keyboard. New tests: the vscode API used
against engines.vscode, signing in against a stand-in lembas, and the LLeMbas CLI itself when its
source is at hand. The READMEs, the Neovim help (helptags in the install recipe) and the changelog
say what changed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:45:58 +00:00

1552 lines
67 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
// LLeMbas in VS Code and VSCodium. The agent is the LLeMbas CLI, unchanged: this extension
// starts `lembas serve --stdio` and is its client (Agent Client Protocol, version 1). The
// sign-in, the models, the tools and the permissions are the CLI's; the only thing set here is
// which command starts it.
//
// This file is the glue to the editor. Everything that can be tested without an editor lives
// in src/ and never imports `vscode`.
const vscode = require('vscode');
const crypto = require('node:crypto');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { Agent } = require('./src/agent');
const { Chat } = require('./src/chat');
const { Completer, windowAround } = require('./src/completion');
const { editorContext, selectionLabel, sliceLines } = require('./src/context');
const hunksOf = require('./src/hunks');
const markdown = require('./src/markdown');
const media = require('./src/media');
const { chatHtml } = require('./src/webview');
const words = require('./src/words');
const login = require('./src/login');
const { resolveCommand } = require('./src/agent');
const DIFF_SCHEME = 'llembas-diff';
const VIEW_ID = 'llembas.chat';
function config() {
return vscode.workspace.getConfiguration('llembas');
}
/** The folder the agent works in: the active editor's workspace folder, else the first folder of the window, else the open file's, else home. */
function workingDirectory() {
const active = vscode.window.activeTextEditor;
if (active && active.document.uri.scheme === 'file' && typeof vscode.workspace.getWorkspaceFolder === 'function') {
const folder = vscode.workspace.getWorkspaceFolder(active.document.uri);
if (folder && folder.uri.scheme === 'file') return folder.uri.fsPath;
}
for (const f of vscode.workspace.workspaceFolders || []) if (f.uri.scheme === 'file') return f.uri.fsPath;
if (active && active.document.uri.scheme === 'file') return path.dirname(active.document.uri.fsPath);
return os.homedir();
}
/** `rel` under `dir` or one of the folders above it, when that file's content is exactly `text`; else ''. */
function fileWithText(dir, rel, text) {
if (typeof rel !== 'string' || !rel || path.isAbsolute(rel) || rel.split(/[\\/]/).includes('..')) return '';
let at = dir;
for (let i = 0; i < 12; i++) {
const file = path.join(at, rel);
try {
if (fs.statSync(file).isFile() && fs.readFileSync(file, 'utf8') === text) return file;
} catch {
// not there
}
const up = path.dirname(at);
if (up === at) break;
at = up;
}
return '';
}
function samePath(a, b) {
const x = path.normalize(a);
const y = path.normalize(b);
return process.platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y;
}
/** A failure as a message of the editor's: the CLI's refusals in the words both editors use. */
function say(e) {
const text = (chat ? chat.words(e) : words.say(e)).trim();
return 'LLeMbas: ' + text + (/[.!?…`]$/.test(text) ? '' : '.');
}
// ---- texts shown in a diff view ----------------------------------------------------------
class DiffTexts {
constructor() {
this.texts = new Map(); // uri path -> string | () => string
this.changed = new vscode.EventEmitter();
this.onDidChange = this.changed.event;
}
uri(key, name) {
const safe = media.safeName(name) || 'text';
return vscode.Uri.from({ scheme: DIFF_SCHEME, path: `/${key}/${safe}` });
}
set(uri, text) {
this.texts.set(uri.path, text);
this.changed.fire(uri);
}
dropUnder(prefix) {
for (const key of [...this.texts.keys()]) if (key.startsWith(prefix)) this.texts.delete(key);
}
provideTextDocumentContent(uri) {
const t = this.texts.get(uri.path);
return typeof t === 'function' ? t() : t || '';
}
}
async function closeDiffTabs(prefix) {
const tabs = [];
for (const group of vscode.window.tabGroups.all) {
for (const tab of group.tabs) {
const input = tab.input;
if (input instanceof vscode.TabInputTextDiff && input.modified.scheme === DIFF_SCHEME && input.modified.path.startsWith(prefix)) tabs.push(tab);
}
}
if (tabs.length) await vscode.window.tabGroups.close(tabs, true);
}
// ---- a rewrite, shown before it is made --------------------------------------------------
class Proposals {
constructor(texts) {
this.texts = texts;
this.byDoc = new Map(); // document uri string -> { uri, hunks, n }
this.applying = new Set(); // documents this extension is changing right now
this.count = 0;
this.lensChanged = new vscode.EventEmitter();
this.onDidChangeCodeLenses = this.lensChanged.event;
this.removed = vscode.window.createTextEditorDecorationType({
isWholeLine: true,
backgroundColor: new vscode.ThemeColor('diffEditor.removedLineBackground'),
borderWidth: '0 0 0 3px',
borderStyle: 'solid',
borderColor: new vscode.ThemeColor('editorOverviewRuler.deletedForeground'),
overviewRulerColor: new vscode.ThemeColor('editorOverviewRuler.modifiedForeground'),
overviewRulerLane: vscode.OverviewRulerLane.Left,
});
this.added = vscode.window.createTextEditorDecorationType({
overviewRulerColor: new vscode.ThemeColor('editorOverviewRuler.addedForeground'),
overviewRulerLane: vscode.OverviewRulerLane.Left,
});
}
entry(doc) {
return this.byDoc.get(doc.uri.toString());
}
pending(doc) {
const e = doc && this.entry(doc);
return e ? e.hunks.length : 0;
}
set(doc, hunks) {
this.clear(doc); // an older proposal for this file, and its texts and diff tab
const n = ++this.count;
const entry = { uri: doc.uri, hunks, n, proposal: null };
entry.proposal = this.texts.uri(`proposal/${n}`, path.basename(doc.uri.path) || 'untitled');
this.texts.set(entry.proposal, () => {
const lines = [];
for (let i = 0; i < doc.lineCount; i++) lines.push(doc.lineAt(i).text);
return hunksOf.withAll(lines, entry.hunks).join(doc.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n');
});
this.byDoc.set(doc.uri.toString(), entry);
this.refresh(doc);
return entry;
}
clear(doc) {
const entry = this.entry(doc);
if (!entry) return;
this.byDoc.delete(doc.uri.toString());
this.texts.dropUnder(`/proposal/${entry.n}/`);
closeDiffTabs(`/proposal/${entry.n}/`).then(undefined, () => {});
this.refresh(doc);
}
refresh(doc) {
const entry = this.entry(doc);
if (entry && entry.hunks.length === 0) return this.clear(doc);
if (entry) this.texts.changed.fire(entry.proposal);
this.lensChanged.fire();
for (const editor of vscode.window.visibleTextEditors) if (editor.document === doc) this.decorate(editor);
const active = vscode.window.activeTextEditor;
vscode.commands.executeCommand('setContext', 'llembas.hasProposal', !!(active && this.pending(active.document)));
}
decorate(editor) {
const entry = this.entry(editor.document);
const removed = [];
const added = [];
const doc = editor.document;
for (const h of entry ? entry.hunks : []) {
const anchor = Math.min(Math.max(0, h.old.length ? h.line + h.old.length - 1 : h.line), doc.lineCount - 1);
const hover = new vscode.MarkdownString();
hover.appendText(h.new.length ? 'LLeMbas proposes here:\n' : 'LLeMbas proposes to take these lines away.');
if (h.new.length) hover.appendCodeblock(h.new.join('\n').replace(/```/g, '`​``'), doc.languageId);
if (h.old.length) {
removed.push({ range: new vscode.Range(h.line, 0, h.line + h.old.length - 1, 0), hoverMessage: hover });
}
const first = h.new.length ? h.new[0].replace(/[\u0000-\u001f\u007f]/g, ' ').trim().slice(0, 100) : '';
const more = h.new.length > 1 ? ` (+${h.new.length - 1} more line${h.new.length > 2 ? 's' : ''})` : '';
const what = h.new.length === 0 ? 'taken away' : (h.old.length ? '→ ' : h.line >= doc.lineCount ? 'added below: ' : 'added above: ') + first + more;
added.push({
range: new vscode.Range(anchor, 0, anchor, 0),
hoverMessage: hover,
renderOptions: {
after: {
contentText: what,
margin: '0 0 0 2em',
color: new vscode.ThemeColor('editorGhostText.foreground'),
backgroundColor: new vscode.ThemeColor('diffEditor.insertedTextBackground'),
},
},
});
}
editor.setDecorations(this.removed, removed);
editor.setDecorations(this.added, added);
}
provideCodeLenses(doc) {
const entry = this.entry(doc);
if (!entry) return [];
const out = [];
const uri = doc.uri.toString();
const ordered = entry.hunks.slice().sort((a, b) => a.line - b.line);
ordered.forEach((h, i) => {
const line = Math.min(h.line, doc.lineCount - 1);
const range = new vscode.Range(line, 0, line, 0);
out.push(new vscode.CodeLens(range, { title: 'Accept', command: 'llembas.acceptChange', arguments: [uri, h.id] }));
out.push(new vscode.CodeLens(range, { title: 'Reject', command: 'llembas.rejectChange', arguments: [uri, h.id] }));
if (i === 0) {
if (ordered.length > 1) {
out.push(new vscode.CodeLens(range, { title: `Accept all ${ordered.length}`, command: 'llembas.acceptAllChanges', arguments: [uri] }));
out.push(new vscode.CodeLens(range, { title: 'Reject all', command: 'llembas.rejectAllChanges', arguments: [uri] }));
}
out.push(new vscode.CodeLens(range, { title: 'Show as a diff', command: 'llembas.showChanges', arguments: [uri] }));
}
});
return out;
}
/** The document a command means: the one a code lens named, else the one in front. */
docFor(uri) {
if (typeof uri === 'string') return vscode.workspace.textDocuments.find((d) => d.uri.toString() === uri);
const active = vscode.window.activeTextEditor;
return active && active.document;
}
/** The hunk a command means: the one a code lens named, else the one at or below the cursor. */
hunkFor(doc, id) {
const entry = this.entry(doc);
if (!entry) return undefined;
if (id !== undefined) return entry.hunks.find((h) => h.id === id);
const active = vscode.window.activeTextEditor;
const cur = active && active.document === doc ? active.selection.active.line : 0;
const ordered = entry.hunks.slice().sort((a, b) => a.line - b.line);
return ordered.find((h) => cur <= h.line + Math.max(h.old.length, 1) - 1) || ordered[ordered.length - 1];
}
async accept(doc, wanted) {
const entry = this.entry(doc);
if (!entry) return;
const lineAt = (i) => doc.lineAt(i).text;
const fits = wanted.filter((h) => hunksOf.stillFits(h, lineAt, doc.lineCount));
const stale = wanted.filter((h) => !fits.includes(h));
const eol = doc.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n';
const at = (p) => (p.end ? doc.lineAt(p.line).range.end : new vscode.Position(p.line, 0));
const edit = new vscode.WorkspaceEdit();
for (const h of fits) {
const e = hunksOf.editFor(h, doc.lineCount);
edit.replace(doc.uri, new vscode.Range(at(e.start), at(e.stop)), e.text.replace(/\n/g, eol));
}
let ok = true;
if (fits.length) {
const key = doc.uri.toString();
this.applying.add(key);
try {
ok = await vscode.workspace.applyEdit(edit);
} finally {
this.applying.delete(key);
}
}
if (ok) {
// From the bottom up, so every hunk still waiting keeps a true line number.
for (const h of fits.slice().sort((a, b) => b.line - a.line)) entry.hunks = hunksOf.afterAccept(entry.hunks, h);
}
entry.hunks = entry.hunks.filter((h) => !stale.some((s) => s.id === h.id));
this.refresh(doc);
if (!ok) vscode.window.showWarningMessage('LLeMbas: the editor did not take the change.');
else if (stale.length) {
vscode.window.showWarningMessage(
`LLeMbas: the text changed where ${stale.length === 1 ? 'a change was' : stale.length + ' changes were'} proposed; ${stale.length === 1 ? 'it was' : 'they were'} dropped.`,
);
}
}
reject(doc, wanted) {
const entry = this.entry(doc);
if (!entry) return;
entry.hunks = entry.hunks.filter((h) => !wanted.includes(h));
this.refresh(doc);
}
/** Somebody typed in a document that has proposals. */
documentChanged(ev) {
if (this.applying.has(ev.document.uri.toString())) return;
const entry = this.entry(ev.document);
if (!entry) return;
const changes = ev.contentChanges.slice().sort((a, b) => b.range.start.line - a.range.start.line);
for (const c of changes) {
entry.hunks = hunksOf.afterChange(entry.hunks, {
startLine: c.range.start.line,
endLine: c.range.end.line,
newLineCount: c.text.split('\n').length,
});
}
this.refresh(ev.document);
}
async showDiff(doc) {
const entry = this.entry(doc);
if (!entry) return;
await vscode.commands.executeCommand('vscode.diff', doc.uri, entry.proposal, `LLeMbas: ${path.basename(doc.uri.path)} (proposed)`, {
preview: true,
preserveFocus: true,
viewColumn: vscode.ViewColumn.Beside,
});
}
}
// ---- the chat view -----------------------------------------------------------------------
class ChatView {
constructor(context, chat, shown, actions) {
this.context = context;
this.chat = chat;
this.shown = shown; // key -> a file the agent showed
this.actions = actions;
this.view = undefined;
this.attached = null; // { editor, label }
this.dirty = new Map();
this.timer = null;
this.reading = new Map(); // item id -> the reply's Markdown, read as it grows
chat.on('item', (item) => this.queue(item));
chat.on('reset', () => this.reset());
chat.on('state', () => {
this.flush(); // what was written reaches the page before the news that the turn is over
this.post({ type: 'state', state: chat.state() });
});
}
resolveWebviewView(view) {
this.view = view;
const webview = view.webview;
webview.options = {
enableScripts: true,
enableCommandUris: false,
localResourceRoots: [vscode.Uri.joinPath(this.context.extensionUri, 'media'), vscode.Uri.file(this.actions.mediaDir)],
};
webview.html = chatHtml({
cspSource: webview.cspSource,
nonce: crypto.randomBytes(18).toString('base64url'),
scriptUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'chat.js')).toString(),
styleUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'chat.css')).toString(),
logoUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'logo.png')).toString(),
});
webview.onDidReceiveMessage((m) => this.receive(m));
view.onDidDispose(() => {
if (this.view === view) this.view = undefined;
});
}
post(message) {
if (this.view) this.view.webview.postMessage(message).then(undefined, () => {});
}
/** An item as the page is given it: a model's text as a tree, a picture as an address the page may load. */
present(item) {
if (item.kind === 'agent') {
let growing = this.reading.get(item.id);
if (!growing) this.reading.set(item.id, (growing = new markdown.Growing()));
return { id: item.id, kind: 'agent', ast: growing.update(item.text) };
}
if (item.kind === 'plancard') {
const { text, ...rest } = item;
return { ...rest, ast: text ? markdown.parse(text) : [] };
}
if (item.kind === 'media') {
const entry = this.shown.get(item.key);
const src = item.picture && entry && entry.file && this.view ? this.view.webview.asWebviewUri(vscode.Uri.file(entry.file)).toString() : '';
return { ...item, src, sizeWords: item.size ? media.sizeInWords(item.size) : '' };
}
return item;
}
queue(item) {
// A reply arrives in many small pieces; the page is told at most twenty times a second, and
// less often the longer the reply is, since the page draws the whole of it each time.
this.dirty.set(item.id, item);
if (this.timer) return;
const length = typeof item.text === 'string' ? item.text.length : 0;
const pause = length > 200000 ? 1000 : length > 50000 ? 400 : length > 10000 ? 150 : 50;
this.timer = setTimeout(() => this.flush(), pause);
}
flush() {
if (this.timer) clearTimeout(this.timer);
this.timer = null;
const items = [...this.dirty.values()];
this.dirty.clear();
for (const it of items) this.post({ type: 'item', item: this.present(it) });
}
reset() {
this.dirty.clear();
this.reading.clear();
this.post({
type: 'reset',
items: this.chat.items.map((i) => this.present(i)),
state: this.chat.state(),
settings: this.actions.uiSettings ? this.actions.uiSettings() : undefined,
attached: this.attached ? this.attached.label : '',
});
}
attach(attached) {
this.attached = attached;
this.post({ type: 'attached', label: attached ? attached.label : '' });
}
/** Bring the view forward. `keepFocus`: without taking the keyboard from the editor. */
async reveal(focusPrompt, keepFocus) {
if (keepFocus && this.view) return this.view.show(true);
await vscode.commands.executeCommand(VIEW_ID + '.focus');
if (focusPrompt) this.post({ type: 'focus' });
return undefined;
}
receive(m) {
if (!m || typeof m !== 'object' || typeof m.type !== 'string') return;
const a = this.actions;
switch (m.type) {
case 'ready':
return this.reset();
case 'send':
if (typeof m.text === 'string' && m.text.trim() && m.text.length <= 1000000) a.sendTyped(m.text);
return undefined;
case 'steer':
if (typeof m.text === 'string' && m.text.trim() && m.text.length <= 1000000) a.guard(this.chat.steer(m.text));
return undefined;
case 'stop':
return this.chat.stop();
case 'new':
return a.newSession();
case 'signIn':
return a.guard(a.signIn());
case 'compact':
return a.guard(a.compact());
case 'sessions':
return a.guard(a.resumeSession());
case 'explain':
return a.guard(a.explain());
case 'fix':
return a.guard(a.fixProblems());
case 'addFile':
return a.guard(a.addFile());
case 'copyCode':
if (typeof m.text === 'string' && vscode.env && vscode.env.clipboard && typeof vscode.env.clipboard.writeText === 'function') {
vscode.env.clipboard.writeText(m.text).then(undefined, () => {});
}
return undefined;
case 'insertCode':
if (typeof m.text === 'string') a.guard(a.insertCode(m.text));
return undefined;
case 'updateSettings':
if (m.settings && typeof m.settings === 'object') a.guard(a.updateSettings(m.settings));
return undefined;
case 'searchFiles':
if (typeof m.query === 'string') {
const seq = m.seq;
a.searchFiles(m.query)
.then((files) => this.post({ type: 'files', seq, files }))
.catch(() => this.post({ type: 'files', seq, files: [] }));
}
return undefined;
case 'detach':
return this.attach(null);
case 'setMode':
if (typeof m.id === 'string') a.guard(this.chat.setMode(m.id));
return undefined;
case 'setModel':
if (typeof m.id === 'string') a.guard(this.chat.setModel(m.id));
return undefined;
case 'answer':
if (typeof m.card === 'string' && typeof m.option === 'string') this.chat.answer(m.card, m.option);
return undefined;
case 'answerQuestion':
if (typeof m.card === 'string' && Array.isArray(m.answers)) this.chat.answerQuestion(m.card, m.answers);
return undefined;
case 'dismissQuestion':
if (typeof m.card === 'string') this.chat.dismissQuestion(m.card);
return undefined;
case 'answerPlan':
if (typeof m.card === 'string' && typeof m.outcome === 'string') this.chat.answerPlan(m.card, m.outcome, m.value);
return undefined;
case 'showDiff':
if (typeof m.card === 'string') this.chat.reshow(m.card);
return undefined;
case 'openLink': {
// The page is not trusted with the decision: the address is checked again here.
const href = markdown.safeHref(m.href);
if (href) vscode.env.openExternal(vscode.Uri.parse(href, true));
return undefined;
}
case 'openFile':
if (typeof m.path === 'string' && m.path.trim()) {
a.openFileAt(m.path.trim(), m.line, !!m.soft);
}
return undefined;
case 'openMedia':
if (typeof m.key === 'string') a.openShown(m.key);
return undefined;
default:
return undefined;
}
}
}
// ---- activation --------------------------------------------------------------------------
let chat = null;
let mediaDir = null;
let cancelSignIn = null; // ends a sign-in that still waits when the window closes
function activate(context) {
const output = vscode.window.createOutputChannel('LLeMbas');
context.subscriptions.push(output);
mediaDir = fs.mkdtempSync(path.join(os.tmpdir(), 'llembas-vscode-'));
const version = String((context.extension && context.extension.packageJSON && context.extension.packageJSON.version) || '0');
const windowModel = { autocomplete: undefined, main: undefined }; // the quick switch: this window only, saved nowhere
const shown = new Map();
let shownCount = 0;
let rewrites = 0;
const rewriting = new Set(); // documents a rewrite is being written for
const texts = new DiffTexts();
const proposals = new Proposals(texts);
context.subscriptions.push(vscode.workspace.registerTextDocumentContentProvider(DIFF_SCHEME, texts));
// ---- the agent's questions to the editor ----
const written = new Map(); // document uri -> { version, content }: what the agent wrote last, while the document is still that
const hooks = {
/** ACP `fs/read_text_file`: a file open here is answered from the editor, saved or not. */
readTextFile(p) {
if (!p || typeof p.path !== 'string' || !path.isAbsolute(p.path)) throw { code: -32602, message: 'an absolute path is needed' };
const doc = vscode.workspace.textDocuments.find((d) => d.uri.scheme === 'file' && !d.isClosed && samePath(d.uri.fsPath, p.path));
if (doc) {
// While the document is as the agent's last write left it, the agent is given back exactly
// the text it wrote: it compares texts to know whether a file changed behind it, and a
// document never holds a text quite as it was written (its line ends are the document's).
const w = written.get(doc.uri.toString());
const text = w && w.version === doc.version ? w.content : doc.getText();
return { content: sliceLines(text, p.line, p.limit) };
}
// Not open: the disk's text, byte for byte. A file that is not text is the agent's own to read.
let bytes;
try {
bytes = fs.readFileSync(p.path);
} catch (e) {
throw { code: -32002, message: 'cannot read ' + p.path + ': ' + e.code };
}
let text;
try {
if (bytes.includes(0)) throw new Error('not text');
text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
} catch {
throw { code: -32002, message: 'not a text file: ' + p.path };
}
return { content: sliceLines(text, p.line, p.limit) };
},
/**
* ACP `fs/write_text_file`: the text becomes the file's content before the answer. A file
* that is open here gets it in its document, which is then saved (only that one document is
* touched); one that is not open is written to the disk. An editor that answers reads must
* take writes too, or the agent could never change a file it has read here.
*/
async writeTextFile(p) {
if (!p || typeof p.path !== 'string' || !path.isAbsolute(p.path) || typeof p.content !== 'string') {
throw { code: -32602, message: 'an absolute path and the content are needed' };
}
const doc = vscode.workspace.textDocuments.find((d) => d.uri.scheme === 'file' && !d.isClosed && samePath(d.uri.fsPath, p.path));
if (!doc) {
try {
fs.mkdirSync(path.dirname(p.path), { recursive: true });
fs.writeFileSync(p.path, p.content);
} catch (e) {
throw { code: -32002, message: 'the editor could not write ' + p.path + ': ' + e.code };
}
return {};
}
const key = doc.uri.toString();
written.delete(key);
// The document's own line ends: a file with CRLF stays one, whatever the model wrote.
const eol = doc.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n';
const wanted = p.content.replace(/\r\n/g, '\n').replace(/\n/g, eol);
if (doc.getText() !== wanted) {
const last = doc.lineAt(doc.lineCount - 1);
const edit = new vscode.WorkspaceEdit();
edit.replace(doc.uri, new vscode.Range(new vscode.Position(0, 0), last.range.end), wanted);
if (!(await vscode.workspace.applyEdit(edit))) throw { code: -32603, message: 'the editor did not take the text' };
}
if (doc.isDirty && !(await doc.save())) throw { code: -32603, message: 'the editor could not save ' + p.path };
// Saving may change the text again (format on save, a final line break): only a document
// that is still what was written is answered for with the agent's own text.
if (doc.getText() === wanted) written.set(key, { version: doc.version, content: p.content });
return {};
},
/** An approval card that carries diffs: each opens in the editor's own diff view before the answer. */
showDiffs(cardId, diffs) {
diffs.slice(0, 8).forEach((d, i) => {
const name = path.basename(d.path) || 'file';
const left = texts.uri(`card/${cardId}/${i}/now`, name);
const right = texts.uri(`card/${cardId}/${i}/proposed`, name);
texts.set(left, d.oldText === null ? '' : d.oldText);
texts.set(right, d.newText);
const what = d.deleted ? 'would be deleted' : d.oldText === null ? 'would be created' : 'proposed change';
vscode.commands
.executeCommand('vscode.diff', left, right, `LLeMbas: ${name} (${what})`, { preview: false, preserveFocus: true })
.then(undefined, (e) => output.appendLine('diff: ' + e));
});
},
closeDiffs(cardId) {
texts.dropUnder(`/card/${cardId}/`);
closeDiffTabs(`/card/${cardId}/`).then(undefined, () => {});
},
/** `_lembas/show` with a handle: fetch the file, find out what it is, keep it for the chat. */
async showMedia(p, read) {
const megabytes = Math.max(1, Math.min(64, Number(config().get('media.maxMegabytes')) || 64));
const got = await media.receiveShown(p, read, { dir: mediaDir, maxBytes: megabytes * 1024 * 1024 });
if (!got.ok) return got;
const key = 'm' + ++shownCount;
shown.set(key, got);
return { ...got, key };
},
/** `_lembas/show` with text: opened as a read-only document. HTML is opened as its text, never drawn. */
async showText(p) {
// The file itself when the one on this machine holds exactly the text that was sent (the
// agent names it from its project's root, which may be above the session's folder);
// otherwise the text as sent.
const file = fileWithText(chat.sessionCwd || workingDirectory(), p.path, String(p.text));
const line = Number.isInteger(p.line) && p.line > 0 ? p.line - 1 : 0;
try {
let uri;
if (file) uri = vscode.Uri.file(file);
else {
// Not a file here: a document of the extension's own, which cannot be edited and so
// never asks to be saved.
uri = texts.uri(`shown/${++shownCount}`, path.basename(String(p.path || 'text')));
texts.set(uri, String(p.text));
}
const doc = await vscode.workspace.openTextDocument(uri);
const startLine = Math.min(line, Math.max(0, doc.lineCount - 1));
const endLine = Number.isInteger(p.endLine) && p.endLine > 0 ? Math.min(p.endLine - 1, Math.max(0, doc.lineCount - 1)) : startLine;
const startPos = new vscode.Position(startLine, 0);
const endPos = endLine > startLine ? doc.lineAt(endLine).range.end : startPos;
await vscode.window.showTextDocument(doc, { preview: true, preserveFocus: true, selection: new vscode.Range(startPos, endPos) });
return { shown: true };
} catch (e) {
return { shown: false, reason: 'The editor could not open it: ' + e.message };
}
},
};
chat = new Chat({
makeAgent: (o) =>
new Agent({
command: String(config().get('command') || 'lembas'),
args: ['serve', '--stdio'],
cwd: o.cwd,
onRequest: o.onRequest,
writeTextFile: true,
clientInfo: { name: 'llembas-vscode', version },
home: os.homedir(),
}),
cwd: workingDirectory,
version,
options: () => ({
mode: String(config().get('chat.startMode') || '') || undefined,
model: windowModel.main,
showThoughts: !!config().get('chat.showThinking'),
}),
hooks,
});
chat.on('stderr', (text) => output.append(text));
context.subscriptions.push({ dispose: () => chat.dispose() });
/** A failure as a message; one that says the CLI is not signed in offers to sign in. */
const failed = (e) => {
if (!words.notSignedIn(e)) return vscode.window.showErrorMessage(say(e));
return vscode.window.showErrorMessage(say(e), 'Sign in').then((pick) => (pick ? guard(signIn()) : undefined));
};
const guard = (promise) => Promise.resolve(promise).then(undefined, failed);
// ---- signing in and out ----
let signingIn = null; // the sign-in under way: { cancel }
/** The program the agent is started as: the same one signs in and out. */
const cliCommand = () => resolveCommand(String(config().get('command') || 'lembas'), process.env, os.homedir());
async function signIn(address) {
if (signingIn) return vscode.window.showWarningMessage('LLeMbas: a sign-in is under way. Cancel it in its notification first.');
let server = typeof address === 'string' ? address.trim() : '';
if (!server) {
const typed = await vscode.window.showInputBox({
title: 'LLeMbas: sign in',
prompt: "Your LLeMbas server's address",
placeHolder: 'the address you open LLeMbas at in the browser',
ignoreFocusOut: true,
});
if (typed === undefined || !typed.trim()) return undefined;
server = typed.trim();
}
const command = cliCommand();
const ca = String(config().get('login.caFile') || '').trim();
const now = await login.current(command);
// The same server again, without a certificate: the CLI reads its login anew and replaces nothing.
if (now && !(login.sameServer(now, server) && !ca)) {
const go = `Sign in to ${server}`;
const pick = await vscode.window.showWarningMessage(
`LLeMbas: this computer is signed in to ${now}. The LLeMbas CLI keeps one sign-in: the terminal and the linked service use it too. Signing in to ${server} replaces it.`,
{ modal: true },
go,
);
if (pick !== go) return undefined;
}
const r = await vscode.window
.withProgress({ location: vscode.ProgressLocation.Notification, title: `LLeMbas: signing in to ${server}`, cancellable: true }, (progress, token) => {
const run = login.signIn({
command,
address: server,
ca: ca || undefined,
onCode(ev) {
const where = (ev.instance && (ev.instance.name || ev.instance.base_url)) || server;
progress.report({ message: `approve the code ${String(ev.user_code)} at ${String(ev.verification_uri)}` });
chat.note(`To sign in to ${where}, approve the code ${String(ev.user_code)} at ${String(ev.verification_uri)}. The page is being opened in your browser.`);
// Only a web address is handed to the browser, whatever the program printed.
const url = login.webAddress(ev.verification_uri_complete) || login.webAddress(ev.verification_uri);
if (url) Promise.resolve(vscode.env.openExternal(vscode.Uri.parse(url, true))).then(undefined, () => {});
},
});
signingIn = run;
cancelSignIn = () => run.cancel();
token.onCancellationRequested(() => run.cancel());
return run.result;
})
.then(
(v) => v,
(e) => ({ ok: false, error: { message: String((e && e.message) || e) } }),
);
signingIn = null;
cancelSignIn = null;
if (r.ok) {
// A new agent, so the open chat works at once with the new sign-in.
chat.stopAgent(true);
completer.unblock();
const models = Number.isFinite(r.done.models) ? ` (${r.done.models} models)` : '';
chat.note(`Signed in to ${String(r.done.base_url || server)}${models}. The next message starts a session.`);
showStatus();
return vscode.window.showInformationMessage(`LLeMbas: signed in to ${String(r.done.base_url || server)}.`);
}
if (r.cancelled) return chat.note('Signing in was cancelled.');
const why = r.error.code === 'not_found' ? words.WORDS.not_found(String(config().get('command') || 'lembas')) : words.say(r.error);
chat.note('Not signed in: ' + why, 'error');
return vscode.window.showErrorMessage('LLeMbas: not signed in: ' + why);
}
async function signOut() {
const command = cliCommand();
const now = await login.current(command);
if (!now) return vscode.window.showInformationMessage('LLeMbas: this computer is not signed in to a server.');
const go = `Sign out of ${now}`;
const pick = await vscode.window.showWarningMessage(`LLeMbas: sign this computer out of ${now}? The terminal and the linked service use the same sign-in.`, { modal: true }, go);
if (pick !== go) return undefined;
const r = await login.signOut(command);
if (!r.ok) return vscode.window.showErrorMessage('LLeMbas: not signed out: ' + r.message);
chat.stopAgent(true);
chat.note(r.message || `Signed out of ${now}.`);
showStatus();
return undefined;
}
// ---- what the editor shows, told to the agent ----
function seen(editor, needSelection) {
if (!editor) return null;
const doc = editor.document;
const file = doc.uri.scheme === 'file' ? doc.uri.fsPath : undefined;
const sel = editor.selection;
const out = { path: file, cursorLine: sel.active.line + 1, open: [] };
let first = sel.active.line;
let last = sel.active.line;
if (!sel.isEmpty) {
const lines = hunksOf.wholeLines({ startLine: sel.start.line, endLine: sel.end.line, endCharacter: sel.end.character });
first = lines.first;
last = lines.last;
out.selection = { start: first + 1, end: last + 1, text: doc.getText(sel) };
} else if (needSelection) {
return null;
}
const severity = ['error', 'warning', 'info', 'hint'];
out.diagnostics = vscode.languages
.getDiagnostics(doc.uri)
.filter((d) => (sel.isEmpty ? d.severity <= vscode.DiagnosticSeverity.Warning : d.range.end.line >= first && d.range.start.line <= last))
.sort((a, b) => a.severity - b.severity || a.range.start.line - b.range.start.line)
.map((d) => ({ line: d.range.start.line + 1, severity: severity[d.severity] || 'info', message: d.message, source: d.source }));
for (const group of vscode.window.tabGroups.all) {
for (const tab of group.tabs) {
if (tab.input instanceof vscode.TabInputText && tab.input.uri.scheme === 'file') out.open.push(tab.input.uri.fsPath);
}
}
const name = file ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
return { editor: editorContext(out), label: out.selection ? selectionLabel(name, first + 1, last + 1) : '' };
}
// ---- the chat ----
function openFileAt(rawPath, line, soft) {
const resolved = path.isAbsolute(rawPath) ? rawPath : path.resolve((chat && chat.sessionCwd) || workingDirectory(), rawPath);
if (soft && !fs.existsSync(resolved)) return undefined;
const uri = vscode.Uri.file(resolved);
const opts = { preview: true };
if (Number.isInteger(line) && line > 0) {
const pos = new vscode.Position(line - 1, 0);
opts.selection = new vscode.Range(pos, pos);
}
return vscode.window.showTextDocument(uri, opts).then(undefined, (e) => {
if (!soft) vscode.window.showWarningMessage(say(e));
});
}
async function searchProjectFiles(query) {
const fromAgent = await chat.searchFiles(query, 40).catch(() => []);
if (fromAgent.length) return fromAgent;
const root = workingDirectory();
const seenPaths = new Set();
const openRel = [];
for (const d of vscode.workspace.textDocuments) {
if (d.uri.scheme !== 'file') continue;
const rel = path.relative(root, d.uri.fsPath).replace(/\\/g, '/');
if (rel && !rel.startsWith('..') && !seenPaths.has(rel) && (!query || rel.toLowerCase().includes(query.toLowerCase()))) {
seenPaths.add(rel);
openRel.push({ path: rel, kind: 'file' });
}
}
return openRel;
}
async function pickProjectFile(title, allowDirs) {
// The index answers a name, or part of one: with nothing typed it has only the files used lately.
const query = await vscode.window.showInputBox({ title, placeHolder: 'Part of the file\'s name' });
if (query === undefined || !query.trim()) return undefined;
const files = (await searchProjectFiles(query.trim())).filter((f) => allowDirs || f.kind !== 'dir');
if (!files.length) {
vscode.window.showInformationMessage(`LLeMbas: no file in this project matches "${query.trim()}".`);
return undefined;
}
if (files.length === 1) return files[0];
const picked = await vscode.window.showQuickPick(
files.map((f) => ({
label: (f.kind === 'dir' ? '$(folder) ' : '$(file) ') + f.path + (f.kind === 'dir' ? '/' : ''),
entry: f,
})),
{ title, placeHolder: 'Choose a file' },
);
return picked ? picked.entry : undefined;
}
async function openIndexedFile() {
const entry = await pickProjectFile('LLeMbas: open file from project index', false);
if (entry) await openFileAt(entry.path);
}
async function addFileToChat() {
const entry = await pickProjectFile('LLeMbas: add file to chat', true);
if (!entry) return;
await view.reveal(true);
const escaped = entry.path.replace(/([ #])/g, '\\$1') + (entry.kind === 'dir' ? '/' : '');
view.post({ type: 'insertText', text: `@${escaped} ` });
}
async function resumeSession() {
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is working. Stop it first.');
let list;
try {
list = await chat.listSessions(40);
} catch (e) {
return vscode.window.showErrorMessage(say(e));
}
if (!list.length) return vscode.window.showInformationMessage('LLeMbas: no previous sessions in this folder.');
const picked = await vscode.window.showQuickPick(
list.map((s) => ({
label: String(s.title || s.id),
description: [s.model || '', s.updated ? new Date(s.updated).toISOString().slice(0, 16).replace('T', ' ') : ''].filter(Boolean).join(' · '),
id: s.id,
})),
{ title: 'LLeMbas: resume a previous session', placeHolder: 'Choose a session' },
);
if (!picked) return undefined;
await view.reveal(true);
await chat.resumeSession(picked.id);
return undefined;
}
function uiSettings() {
const c = config();
return {
auto: !!c.get('complete.auto'),
maxTokens: Number(c.get('complete.maxTokens')) || 0,
length: String(c.get('complete.length') || 'auto'),
instructions: String(c.get('complete.instructions') || ''),
showThinking: !!c.get('chat.showThinking'),
};
}
async function updateSettings(patch) {
const c = config();
if (typeof c.update !== 'function') return;
const target = vscode.ConfigurationTarget ? vscode.ConfigurationTarget.Global : true;
const tasks = [];
if (typeof patch.auto === 'boolean') tasks.push(c.update('complete.auto', patch.auto, target));
if (typeof patch.maxTokens === 'number' && Number.isFinite(patch.maxTokens)) {
const clamped = Math.max(0, Math.min(4096, Math.round(patch.maxTokens)));
tasks.push(c.update('complete.maxTokens', clamped, target));
}
if (typeof patch.length === 'string' && ['auto', 'words', 'line', 'block', 'file'].includes(patch.length)) {
tasks.push(c.update('complete.length', patch.length, target));
}
if (typeof patch.instructions === 'string') {
tasks.push(c.update('complete.instructions', patch.instructions.slice(0, 2000), target));
}
if (typeof patch.showThinking === 'boolean') tasks.push(c.update('chat.showThinking', patch.showThinking, target));
await Promise.all(tasks);
view.post({ type: 'settings', settings: uiSettings() });
showStatus();
}
async function insertCode(text) {
const editor = vscode.window.activeTextEditor;
if (!editor) return vscode.window.showInformationMessage('LLeMbas: open an editor to insert code.');
const doc = editor.document;
const eol = doc.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n';
const edit = new vscode.WorkspaceEdit();
edit.replace(doc.uri, editor.selection, String(text).replace(/\r\n/g, '\n').replace(/\n/g, eol));
await vscode.workspace.applyEdit(edit);
return undefined;
}
async function compactSession() {
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is working. Stop it first.');
if (!chat.session) return vscode.window.showInformationMessage('LLeMbas: start a session first.');
await chat.compact();
return undefined;
}
async function toggleAutocomplete() {
const c = config();
const next = !c.get('complete.auto');
if (typeof c.update === 'function') {
const target = vscode.ConfigurationTarget ? vscode.ConfigurationTarget.Global : true;
await c.update('complete.auto', next, target);
}
view.post({ type: 'settings', settings: uiSettings() });
showStatus();
vscode.window.showInformationMessage(`LLeMbas: autocomplete as you type is ${next ? 'on' : 'off'}.`);
}
const actions = {
mediaDir,
guard,
openFileAt,
searchFiles: searchProjectFiles,
resumeSession,
addFile: addFileToChat,
compact: compactSession,
explain: () => explain(),
fixProblems: () => fixProblems(),
insertCode,
uiSettings,
updateSettings,
async sendTyped(text) {
if (chat.busy) {
if (chat.has('steer')) return chat.steer(text);
return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.');
}
let w = view.attached;
if (!w && config().get('chat.sendEditorContext') && !text.startsWith('/')) w = seen(vscode.window.activeTextEditor, false);
view.attach(null);
return chat.send(text, w ? { editor: w.editor, label: w.label } : undefined);
},
signIn: () => signIn(),
async newSession() {
if (!(await chat.newSession())) vscode.window.showWarningMessage('LLeMbas is working. Stop it first.');
},
async openShown(key) {
const entry = shown.get(key);
if (!entry) return undefined;
const target = entry.file || entry.original;
if (!target) return undefined;
const uri = vscode.Uri.file(target);
// Only kinds that are merely displayed are opened, and only when the bytes are that kind.
if (entry.open && entry.open.how === 'editor') return vscode.commands.executeCommand('vscode.open', uri);
if (entry.open && entry.open.how === 'system') return vscode.env.openExternal(uri);
return vscode.commands.executeCommand('revealFileInOS', uri);
},
};
const view = new ChatView(context, chat, shown, actions);
context.subscriptions.push(vscode.window.registerWebviewViewProvider(VIEW_ID, view, { webviewOptions: { retainContextWhenHidden: true } }));
// The files the agent showed belong to the transcript: when it is cleared they go too.
chat.on('reset', () => {
for (const entry of shown.values()) if (entry.file) fs.rm(entry.file, { force: true }, () => {});
shown.clear();
texts.dropUnder('/shown/');
});
// A card must be seen to be answered: the view is brought forward when one arrives.
chat.on('item', (item) => {
if ((item.kind === 'card' || item.kind === 'question' || item.kind === 'plancard') && item.state === 'open') {
view.reveal(false, true).then(undefined, () => {});
}
});
async function ask() {
const editor = vscode.window.activeTextEditor;
const w = seen(editor, true);
if (!w) return vscode.window.showInformationMessage('LLeMbas: select the text you want to ask about first.');
const question = await vscode.window.showInputBox({
title: `Ask LLeMbas about ${w.label}`,
placeHolder: 'Your question (leave empty to send the selection with your next message)',
});
if (question === undefined) return undefined;
await view.reveal(!question.trim());
if (!question.trim()) return view.attach(w);
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.');
return chat.send(question, { editor: w.editor, label: w.label });
}
async function explain() {
const editor = vscode.window.activeTextEditor;
const w = seen(editor, true);
if (!w) return vscode.window.showInformationMessage('LLeMbas: select the code you want explained first.');
await view.reveal(false);
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.');
return chat.send('Explain the selected code concisely, including any subtle behavior or edge cases.', { editor: w.editor, label: w.label });
}
async function fixProblems() {
const editor = vscode.window.activeTextEditor;
if (!editor) return vscode.window.showInformationMessage('LLeMbas: open a file with problems first.');
const w = seen(editor, false);
if (!w || !w.editor || !w.editor.diagnostics || !w.editor.diagnostics.length) {
return vscode.window.showInformationMessage('LLeMbas: no warnings or errors reported in this file.');
}
await view.reveal(false);
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is still working on the last message. Stop it first.');
return chat.send('Fix the reported diagnostics in this file.', { editor: w.editor, label: w.label });
}
async function generateAtCursor() {
const editor = vscode.window.activeTextEditor;
if (!editor) return vscode.window.showInformationMessage('LLeMbas: open an editor first.');
const doc = editor.document;
const key = doc.uri.toString();
if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.');
if (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.');
rewriting.add(key);
try {
const line = editor.selection.active.line;
const instruction = await vscode.window.showInputBox({
title: 'Generate code at cursor',
placeHolder: 'Describe the code to write here',
});
if (!instruction || !instruction.trim()) return undefined;
if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start'));
if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite/generate yet. Update the CLI.');
const lines = (from, to) => {
const out = [];
for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text);
return out;
};
const old = [doc.lineAt(line).text];
const versionThen = doc.version;
const id = 'e' + ++rewrites;
const params = {
id,
cwd: workingDirectory(),
text: old.join('\n') || ' ',
before: lines(line - 40, line - 1).join('\n'),
after: lines(line + 1, line + 40).join('\n'),
language: doc.languageId,
instruction: `At this line, ${instruction.trim()}`,
};
if (doc.uri.scheme === 'file') params.path = doc.uri.fsPath;
if (chat.session) params.sessionId = chat.session;
if (windowModel.main) params.model = windowModel.main;
let r;
try {
r = await vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification, title: 'LLeMbas is generating…', cancellable: true },
async (progress, token) => {
let written = 0;
const onDelta = (p) => {
if (!p || p.id !== id || typeof p.delta !== 'string') return;
written += p.delta.length;
progress.report({ message: `${written} characters` });
};
chat.on('editDelta', onDelta);
token.onCancellationRequested(() => chat.notify('_lembas/edit/cancel', { id }));
try {
return await chat.request('_lembas/edit', params);
} finally {
chat.off('editDelta', onDelta);
}
},
);
} catch (e) {
return vscode.window.showErrorMessage(say(e));
}
if (!r || r.cancelled || typeof r.text !== 'string' || doc.isClosed) return undefined;
if (doc.version !== versionThen) {
return vscode.window.showWarningMessage('LLeMbas: the file changed while the code was generated, so nothing is shown. Ask again.');
}
const fresh = hunksOf.splitLines(r.text);
if (fresh.length > 1 && fresh[fresh.length - 1] === '') fresh.pop();
const hunks = hunksOf.propose(line, old, fresh);
if (!hunks.length) return vscode.window.showInformationMessage('LLeMbas: nothing to insert.');
proposals.set(doc, hunks);
if (config().get('rewrite.openDiff')) proposals.showDiff(doc).then(undefined, () => {});
return undefined;
} finally {
rewriting.delete(key);
}
}
// ---- rewrite a selection ----
async function rewrite() {
const editor = vscode.window.activeTextEditor;
if (!editor || editor.selection.isEmpty) return vscode.window.showInformationMessage('LLeMbas: select the lines to rewrite first.');
const doc = editor.document;
const key = doc.uri.toString();
if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.');
if (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.');
rewriting.add(key);
try {
return await rewriteIn(editor);
} finally {
rewriting.delete(key);
}
}
async function rewriteIn(editor) {
const doc = editor.document;
const sel = editor.selection;
const { first, last } = hunksOf.wholeLines({ startLine: sel.start.line, endLine: sel.end.line, endCharacter: sel.end.character });
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
const instruction = await vscode.window.showInputBox({
title: `Rewrite ${selectionLabel(name, first + 1, last + 1)}`,
placeHolder: 'What should change?',
});
if (!instruction || !instruction.trim()) return undefined;
if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start'));
if (!chat.has('editor')) {
return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite a selection yet. Update the CLI.');
}
const lines = (from, to) => {
const out = [];
for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text);
return out;
};
const old = lines(first, last);
const versionThen = doc.version;
const id = 'e' + ++rewrites;
const params = {
id,
cwd: workingDirectory(),
text: old.join('\n'),
before: lines(first - 40, first - 1).join('\n'),
after: lines(last + 1, last + 40).join('\n'),
language: doc.languageId,
instruction: instruction.trim(),
};
if (doc.uri.scheme === 'file') params.path = doc.uri.fsPath;
if (chat.session) params.sessionId = chat.session;
if (windowModel.main) params.model = windowModel.main;
let r;
try {
r = await vscode.window.withProgress(
{ location: vscode.ProgressLocation.Notification, title: 'LLeMbas is rewriting…', cancellable: true },
async (progress, token) => {
let written = 0;
const onDelta = (p) => {
if (!p || p.id !== id || typeof p.delta !== 'string') return;
written += p.delta.length;
progress.report({ message: `${written} characters` });
};
chat.on('editDelta', onDelta);
token.onCancellationRequested(() => chat.notify('_lembas/edit/cancel', { id }));
try {
return await chat.request('_lembas/edit', params);
} finally {
chat.off('editDelta', onDelta);
}
},
);
} catch (e) {
return vscode.window.showErrorMessage(say(e));
}
if (!r || r.cancelled || typeof r.text !== 'string') return undefined;
if (doc.isClosed) return undefined;
if (doc.version !== versionThen) {
return vscode.window.showWarningMessage('LLeMbas: the file changed while the rewrite was written, so nothing is shown. Ask again.');
}
const fresh = hunksOf.splitLines(r.text);
if (fresh.length > 1 && fresh[fresh.length - 1] === '') fresh.pop();
const hunks = hunksOf.propose(first, old, fresh);
if (!hunks.length) return vscode.window.showInformationMessage('LLeMbas: the rewrite changes nothing.');
const made = proposals.set(doc, hunks);
rewriting.delete(doc.uri.toString()); // the proposal is up; what follows only waits for an answer
if (config().get('rewrite.openDiff')) proposals.showDiff(doc).then(undefined, () => {});
const n = hunks.length;
const pick = await vscode.window.showInformationMessage(
`LLeMbas proposes ${n} change${n === 1 ? '' : 's'}. Nothing is written until you accept.`,
'Accept all',
'Reject all',
);
const entry = proposals.entry(doc);
if (!pick || entry !== made) return undefined; // answered through the code lenses meanwhile
if (pick === 'Accept all') return proposals.accept(doc, entry.hunks.slice());
return proposals.reject(doc, entry.hunks.slice());
}
// ---- autocomplete ----
const completer = new Completer({
request: async (method, params) => {
const agent = await chat.connect(true);
if (!agent) throw new Error(chat.startError || 'the agent is not running');
if (!agent.has('editor')) {
throw Object.assign(new Error('this LLeMbas CLI has no autocomplete yet. Update the CLI.'), { data: { reason: 'unsupported' } });
}
return agent.request(method, params, 60000);
},
notify: (method, params) => chat.notify(method, params),
debounceMs: () => Number(config().get('complete.debounce')),
model: () => windowModel.autocomplete,
maxTokens: () => Number(config().get('complete.maxTokens')) || undefined,
length: () => String(config().get('complete.length') || 'auto'),
instructions: () => String(config().get('complete.instructions') || ''),
onRefusal(reason, message) {
if (reason === 'no_model' || reason === 'not_allowed' || reason === 'unknown_model') {
const text = message || (reason === 'no_model' ? 'No autocomplete model is chosen.' : 'That model cannot be used for autocomplete.');
vscode.window.showInformationMessage('LLeMbas: no suggestions: ' + text, 'Choose a model').then((pick) => {
if (pick) guard(pickModel('autocomplete'));
});
} else if (reason === 'not_logged_in') {
vscode.window.showWarningMessage('LLeMbas: no suggestions: ' + chat.words({ message, data: { reason } }), 'Sign in').then((pick) => {
if (pick) guard(signIn());
});
} else {
vscode.window.showInformationMessage('LLeMbas: no suggestions: ' + (message || 'autocomplete is not available here yet.'));
}
},
onError(message, manual) {
output.appendLine('autocomplete: ' + message);
if (manual) vscode.window.showWarningMessage('LLeMbas: no suggestion: ' + message);
},
});
function openSnippets(excludeDoc) {
const out = [];
for (const d of vscode.workspace.textDocuments) {
if (out.length >= 6) break;
if (d === excludeDoc || d.isClosed || d.uri.scheme !== 'file') continue;
const text = d.getText();
if (!text || text.length > 32768) continue;
out.push({ path: d.uri.fsPath, text });
}
return out;
}
function warmActiveEditor(editor) {
if (!editor || !editor.document || editor.document.uri.scheme !== 'file') return;
completer.warm({
cwd: workingDirectory(),
sessionId: chat.session || undefined,
path: editor.document.uri.fsPath,
text: editor.document.getText().slice(0, 32768),
});
}
chat.on('connected', () => {
completer.unblock();
warmActiveEditor(vscode.window.activeTextEditor);
});
const inline = {
async provideInlineCompletionItems(document, position, ctx, token) {
const manual = ctx.triggerKind === vscode.InlineCompletionTriggerKind.Invoke;
if (!manual && !config().get('complete.auto')) return undefined;
if (!manual && ctx.selectedCompletionInfo) return undefined; // the editor's own list is open
const offset = document.offsetAt(position);
const from = document.positionAt(Math.max(0, offset - 12000));
const to = document.positionAt(offset + 4000);
const around = document.getText(new vscode.Range(from, to));
const { prefix, suffix } = windowAround(around, offset - document.offsetAt(from));
if (!manual && !prefix.trim() && !suffix.trim()) return undefined;
const open = openSnippets(document);
const asked = completer.ask(
{
prefix,
suffix,
path: document.uri.scheme === 'file' ? document.uri.fsPath : undefined,
language: document.languageId,
cwd: workingDirectory(),
sessionId: chat.session || undefined,
open: open.length ? open : undefined,
},
{ manual },
);
const seq = completer.current;
const sub = token.onCancellationRequested(() => completer.cancel(seq));
const text = await asked;
sub.dispose();
if (!text || token.isCancellationRequested) return undefined;
return [new vscode.InlineCompletionItem(text, new vscode.Range(position, position))];
},
};
const editable = [{ scheme: 'file' }, { scheme: 'untitled' }, { scheme: 'vscode-notebook-cell' }];
context.subscriptions.push(vscode.languages.registerInlineCompletionItemProvider(editable, inline));
// ---- the two model settings ----
const status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 90);
status.command = 'llembas.modelSettings';
context.subscriptions.push(status);
function showStatus() {
const saved = chat.settings && chat.settings.autocomplete && chat.settings.autocomplete.model;
const model = windowModel.autocomplete || saved;
const autoOn = !!config().get('complete.auto');
const maxTok = Number(config().get('complete.maxTokens')) || 0;
const len = String(config().get('complete.length') || 'auto');
const icon = chat.busy ? '$(sync~spin) ' : '$(sparkle) ';
const suffix = model ? ': ' + String(model).split('/').pop() : '';
status.text = icon + 'LLeMbas' + suffix + (autoOn ? '' : ' (off)');
const lines = [
model
? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}`
: 'Autocomplete model: not chosen',
`Autocomplete: ${autoOn ? 'on' : 'off'} · scope: ${len}${maxTok ? ` · max ${maxTok} tokens` : ''}`,
];
if (chat.mode) lines.push(`Session mode: ${chat.mode}`);
if (chat.model) lines.push(`Session model: ${chat.model}`);
lines.push('Click to change models.');
status.tooltip = lines.join('\n');
status.show();
}
showStatus();
chat.on('state', showStatus);
/** Choose the autocomplete or the main model: saved in the account, or for this window only. */
async function pickModel(kind) {
const data = await chat.loadModels();
const setting = kind === 'autocomplete' ? data.autocomplete : data.main;
if (!setting) {
return vscode.window.showInformationMessage('LLeMbas: this LLeMbas CLI or its server does not keep the editor\'s model settings yet. Update them.');
}
const savedNow = setting.model || null;
const windowNow = windowModel[kind];
const items = data.models
.filter((m) => !Array.isArray(m.for) || m.for.includes(kind))
.map((m) => ({
label: String(m.name || m.id),
description: [m.id, m.id === savedNow ? (setting.source === 'instance' ? "the server's default" : 'saved') : '', m.id === windowNow ? 'this window' : '']
.filter(Boolean)
.join(' · '),
id: m.id,
}));
items.push({ label: "Use the server's default", description: 'forget my saved choice and the one of this window', id: null });
const title = kind === 'autocomplete' ? 'LLeMbas: autocomplete model' : 'LLeMbas: main model (chat, rewrite)';
const picked = await vscode.window.showQuickPick(items, { title, placeHolder: 'Any model your server offers', matchOnDescription: true });
if (!picked) return undefined;
const key = kind === 'autocomplete' ? 'autocomplete_model' : 'main_model';
if (picked.id === null) {
windowModel[kind] = undefined;
await chat.editorSettings({ [key]: null });
} else {
const where = await vscode.window.showQuickPick(
[
{ label: 'Save it', description: 'kept in your account: every editor you sign in from uses it', save: true },
{ label: 'Only this window', description: 'a quick switch, saved nowhere', save: false },
],
{ title: `${title}: ${picked.label}` },
);
if (!where) return undefined;
if (where.save) {
await chat.editorSettings({ [key]: picked.id });
windowModel[kind] = undefined;
} else {
windowModel[kind] = picked.id;
if (kind === 'main' && chat.session && !chat.busy) await chat.setModel(picked.id);
}
}
if (kind === 'autocomplete') completer.unblock();
showStatus();
return undefined;
}
async function modelSettings() {
let data;
try {
data = await chat.loadModels();
} catch (e) {
return vscode.window.showErrorMessage(say(e));
}
const name = (kind) => {
const s = kind === 'autocomplete' ? data.autocomplete : data.main;
if (windowModel[kind]) return `${windowModel[kind]} (this window only)`;
if (!s || !s.model) return 'not chosen';
return s.model + (s.source === 'instance' ? " (the server's default)" : '');
};
const picked = await vscode.window.showQuickPick(
[
{ label: 'Autocomplete model', description: name('autocomplete'), kind: 'autocomplete' },
{ label: 'Main model', description: name('main'), detail: 'chat and rewriting a selection', kind: 'main' },
],
{ title: 'LLeMbas: models' },
);
return picked ? pickModel(picked.kind) : undefined;
}
async function chooseSessionModel() {
const data = await chat.loadModels();
const picked = await vscode.window.showQuickPick(
data.models.map((m) => ({ label: String(m.name || m.id), description: m.id + (m.id === chat.model ? ' · now' : ''), id: m.id })),
{ title: "LLeMbas: this session's model" },
);
return picked ? chat.setModel(picked.id) : undefined;
}
async function chooseMode() {
if (!(await chat.ensureSession())) return undefined;
const picked = await vscode.window.showQuickPick(
chat.modes.map((m) => ({ label: String(m.name || m.id), description: m.id === chat.mode ? 'now' : '', id: m.id })),
{ title: 'LLeMbas: mode' },
);
return picked ? chat.setMode(picked.id) : undefined;
}
// ---- commands ----
const command = (name, fn) => context.subscriptions.push(vscode.commands.registerCommand(name, (...args) => guard(Promise.resolve().then(() => fn(...args)))));
command('llembas.open', () => view.reveal(true));
command('llembas.newSession', actions.newSession);
command('llembas.resumeSession', resumeSession);
command('llembas.compact', compactSession);
command('llembas.stop', () => chat.stop());
command('llembas.restart', () => chat.stopAgent());
command('llembas.signIn', signIn);
command('llembas.signOut', signOut);
command('llembas.ask', ask);
command('llembas.explain', explain);
command('llembas.fixProblems', fixProblems);
command('llembas.generate', generateAtCursor);
command('llembas.rewrite', rewrite);
command('llembas.complete', () => vscode.commands.executeCommand('editor.action.inlineSuggest.trigger'));
command('llembas.toggleAutocomplete', toggleAutocomplete);
command('llembas.openFile', openIndexedFile);
command('llembas.addFile', addFileToChat);
command('llembas.chooseMode', chooseMode);
command('llembas.chooseModel', chooseSessionModel);
command('llembas.modelSettings', modelSettings);
command('llembas.chooseAutocompleteModel', () => pickModel('autocomplete'));
command('llembas.chooseMainModel', () => pickModel('main'));
command('llembas.acceptChange', (uri, id) => {
const doc = proposals.docFor(uri);
const hunk = doc && proposals.hunkFor(doc, id);
return hunk ? proposals.accept(doc, [hunk]) : undefined;
});
command('llembas.rejectChange', (uri, id) => {
const doc = proposals.docFor(uri);
const hunk = doc && proposals.hunkFor(doc, id);
return hunk ? proposals.reject(doc, [hunk]) : undefined;
});
command('llembas.acceptAllChanges', (uri) => {
const doc = proposals.docFor(uri);
const entry = doc && proposals.entry(doc);
return entry ? proposals.accept(doc, entry.hunks.slice()) : undefined;
});
command('llembas.rejectAllChanges', (uri) => {
const doc = proposals.docFor(uri);
const entry = doc && proposals.entry(doc);
return entry ? proposals.reject(doc, entry.hunks.slice()) : undefined;
});
command('llembas.showChanges', (uri) => {
const doc = proposals.docFor(uri);
return doc ? proposals.showDiff(doc) : undefined;
});
context.subscriptions.push(
vscode.languages.registerCodeLensProvider([{ scheme: 'file' }, { scheme: 'untitled' }], proposals),
vscode.workspace.onDidChangeTextDocument((ev) => proposals.documentChanged(ev)),
vscode.workspace.onDidCloseTextDocument((doc) => {
proposals.clear(doc);
written.delete(doc.uri.toString());
}),
vscode.window.onDidChangeVisibleTextEditors((editors) => editors.forEach((e) => proposals.decorate(e))),
vscode.window.onDidChangeActiveTextEditor((e) => {
vscode.commands.executeCommand('setContext', 'llembas.hasProposal', !!(e && proposals.pending(e.document)));
warmActiveEditor(e);
}),
vscode.workspace.onDidChangeConfiguration((ev) => {
// Another command for the agent: the running one is stopped, and the next request starts the new one.
if (ev.affectsConfiguration('llembas.command')) chat.stopAgent();
if (ev.affectsConfiguration('llembas.complete') || ev.affectsConfiguration('llembas.chat.showThinking')) {
view.post({ type: 'settings', settings: uiSettings() });
showStatus();
}
}),
proposals.removed,
proposals.added,
);
}
function deactivate() {
if (chat) chat.dispose();
if (cancelSignIn) cancelSignIn();
if (mediaDir) {
try {
fs.rmSync(mediaDir, { recursive: true, force: true });
} catch {
// the system clears its temporary files in its own time
}
}
}
module.exports = { activate, deactivate };