Privacy: the text of other open files with a suggestion, and the paths of other open tabs with a message, now come only from files inside the window's folders, never from a file that looks like it holds secrets (the table both editors share, tests/rules/private_files.json), and never from one the project's .gitignore leaves out. In a file that looks secret no suggestion is asked for; said once. The README (What is sent) and the settings' descriptions say exactly what is sent and what is not. - Signing in elsewhere, or out, drops the old account's models, this window's model choice and the listed sessions, and reads the models again. - A rewrite or generation holds the file only while it is written; asked again before the instruction was typed, the question that waits gets the keyboard. - The Mode and model lists are rebuilt only when what they offer changed. - Session times are local time. - _lembas/session/deleted is gone: the CLI sends it only on the LLeMbas link, never on serve --stdio. Deleting says why it could not (agent, too old, working) and reads the list again when the CLI no longer has the session. - Dead page messages (focus, insertText, keepBeside), data-line and hooks.filesChanged removed. - Sign-in lines and versions read as the Neovim plugin reads them (tests/rules/). - Texts: one sentence for "still working" and one for "this CLI is too old"; Open a File of This Project; Send now; Approve: edit without asking / ask before each edit; "You (sent while working)" as in Neovim; the Status rows named in words, no Harness row; the hero image has no "LLeMbas IDE" alt text; Choose the Main Model removed (Models does it); Stop the Agent. - README: "nothing is stored in the editor"; the VS Code 1.85 subgrid note names Electron 25 / Chromium 114 and 1.86's Electron 27 / Chromium 118 (read from each tag's cgmanifest.json). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1821 lines
77 KiB
JavaScript
1821 lines
77 KiB
JavaScript
'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, and nothing about them is
|
||
// stored here: the panel shows them and changes them through the CLI. The editor's own settings
|
||
// are which command starts it and how the panel and the suggestions behave.
|
||
//
|
||
// The side panel is the whole of it: the conversation, the sessions, the models, every setting,
|
||
// the sign-in and the agent's status are views of that one frame, and every command opens the
|
||
// panel where it belongs. Nothing here asks through a Quick Pick, an input box or a notification
|
||
// that wants an answer. What stays in the editor is what is about the text itself: the inline
|
||
// suggestion, a rewrite's changes with their Accept / Reject lines, and the diff views.
|
||
//
|
||
// 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 settings = require('./src/settings');
|
||
const { validate } = require('./src/messages');
|
||
const { Account } = require('./src/account');
|
||
const priv = require('./src/private');
|
||
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.onChange = null; // told whenever what is proposed changed
|
||
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)));
|
||
if (this.onChange) this.onChange();
|
||
}
|
||
|
||
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.ready = false; // the page has said it is there
|
||
this.later = new Map(); // what to tell the page once it is: the newest of each kind
|
||
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;
|
||
this.ready = false;
|
||
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(),
|
||
fields: this.actions.fields,
|
||
});
|
||
webview.onDidReceiveMessage((m) => this.receive(m));
|
||
view.onDidDispose(() => {
|
||
if (this.view === view) {
|
||
this.view = undefined;
|
||
this.ready = false;
|
||
}
|
||
});
|
||
}
|
||
|
||
/** Tell the page now, or as soon as there is one: what opens a view must not be lost to a panel that was closed. */
|
||
postLater(message) {
|
||
if (this.ready) return this.post(message);
|
||
this.later.set(message.type, message);
|
||
return undefined;
|
||
}
|
||
|
||
/**
|
||
* Bring the panel forward on one of its views. `beside`: next to the conversation, which stays.
|
||
* `focus`: the control that takes the keyboard (`false`: none). `quiet`: without taking the
|
||
* keyboard from the editor.
|
||
*/
|
||
async show(viewId, o) {
|
||
const how = o || {};
|
||
if (how.quiet && this.view) this.view.show(true);
|
||
else await vscode.commands.executeCommand(VIEW_ID + '.focus');
|
||
const message = { type: 'show', view: viewId, beside: !!how.beside, focus: how.focus === undefined ? true : how.focus };
|
||
if (typeof how.address === 'string') message.address = how.address;
|
||
this.postLater(message);
|
||
}
|
||
|
||
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(),
|
||
config: this.actions.configState(),
|
||
tasks: this.actions.taskList(),
|
||
attached: this.attached ? this.attached.label : '',
|
||
});
|
||
}
|
||
|
||
attach(attached) {
|
||
this.attached = attached;
|
||
this.post({ type: 'attached', label: attached ? attached.label : '' });
|
||
}
|
||
|
||
/** Bring the panel forward as it is, without taking the keyboard from the editor. */
|
||
async reveal() {
|
||
if (this.view) return this.view.show(true);
|
||
await vscode.commands.executeCommand(VIEW_ID + '.focus');
|
||
return undefined;
|
||
}
|
||
|
||
/** What the page says. It is checked against the schema first (src/messages.js): type, shapes, lengths, enumerations. */
|
||
receive(raw) {
|
||
const m = validate(raw);
|
||
if (!m) return undefined;
|
||
const a = this.actions;
|
||
switch (m.type) {
|
||
case 'ready': {
|
||
this.ready = true;
|
||
this.reset();
|
||
const waiting = [...this.later.values()];
|
||
this.later.clear();
|
||
for (const message of waiting) this.post(message);
|
||
return undefined;
|
||
}
|
||
case 'send':
|
||
return a.sendTyped(m.text);
|
||
case 'steer':
|
||
return a.guard(this.chat.steer(m.text));
|
||
case 'stop':
|
||
return this.chat.stop();
|
||
case 'new':
|
||
return a.newSession();
|
||
case 'compact':
|
||
return a.guard(a.compact());
|
||
case 'explain':
|
||
return a.guard(a.explain());
|
||
case 'fix':
|
||
return a.guard(a.fixProblems());
|
||
case 'copyCode':
|
||
if (vscode.env && vscode.env.clipboard && typeof vscode.env.clipboard.writeText === 'function') {
|
||
vscode.env.clipboard.writeText(m.text).then(undefined, () => {});
|
||
}
|
||
return undefined;
|
||
case 'insertCode':
|
||
return a.guard(a.insertCode(m.text));
|
||
case 'searchFiles': {
|
||
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);
|
||
// Only a mode the session has, only a model the server listed (or the one in force), whatever the page sends.
|
||
case 'setMode':
|
||
if (this.chat.modes.length && !this.chat.modes.some((x) => String(x.id) === m.id)) return undefined;
|
||
return a.guard(this.chat.setMode(m.id));
|
||
case 'setModel':
|
||
if (m.id !== this.chat.model && !this.chat.models.some((x) => x.id === m.id)) return undefined;
|
||
return a.guard(this.chat.setModel(m.id));
|
||
case 'answer':
|
||
return this.chat.answer(m.card, m.option);
|
||
case 'answerQuestion':
|
||
return this.chat.answerQuestion(m.card, m.answers);
|
||
case 'dismissQuestion':
|
||
return this.chat.dismissQuestion(m.card);
|
||
case 'answerPlan':
|
||
return this.chat.answerPlan(m.card, m.outcome, m.value);
|
||
case 'showDiff':
|
||
return this.chat.reshow(m.card);
|
||
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':
|
||
return a.openFileAt(m.path.trim(), m.line, !!m.soft);
|
||
case 'openMedia':
|
||
return a.openShown(m.key);
|
||
// ---- the other views ----
|
||
case 'load':
|
||
return a.guard(a.load(m.what));
|
||
case 'setSetting':
|
||
return a.guard(a.writeSetting({ key: m.key, value: m.value, target: m.target }));
|
||
case 'resetSetting':
|
||
return a.guard(a.writeSetting({ key: m.key, target: m.target, reset: true }));
|
||
case 'openSettingsUi':
|
||
return a.openSettingsUi();
|
||
case 'chooseModel':
|
||
return a.guard(a.chooseModel(m.kind, m.id, m.keep));
|
||
case 'resume':
|
||
return a.guard(a.resume(m.id));
|
||
case 'deleteSession':
|
||
return a.guard(a.deleteSession(m.id));
|
||
case 'signIn':
|
||
return a.guard(a.account.begin(m.address));
|
||
case 'signInConfirm':
|
||
return a.guard(a.account.confirm());
|
||
case 'signInCancel':
|
||
return a.account.cancel();
|
||
case 'openApproval':
|
||
return a.openApproval();
|
||
case 'signOut':
|
||
return a.guard(a.account.askSignOut());
|
||
case 'signOutConfirm':
|
||
return a.guard(a.account.confirmSignOut());
|
||
case 'accountDismiss':
|
||
return a.account.dismiss();
|
||
case 'restartAgent':
|
||
return a.guard(a.restartAgent());
|
||
case 'instruction':
|
||
return a.answerTask(m.id, m.text);
|
||
case 'cancelTask':
|
||
return a.cancelTask(m.id);
|
||
case 'proposal':
|
||
return a.guard(a.answerProposal(m.id, m.answer));
|
||
default:
|
||
return undefined;
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---- activation --------------------------------------------------------------------------
|
||
|
||
let chat = null;
|
||
let mediaDir = null;
|
||
let cancelSignIn = null; // ends a sign-in that still waits when the window closes
|
||
let autocompleteProblem = null; // why there are no suggestions: { text, command }
|
||
|
||
function activate(context) {
|
||
autocompleteProblem = null;
|
||
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
|
||
// The settings as the panel shows them: every one the manifest contributes (src/settings.js).
|
||
const manifest = (context.extension && context.extension.packageJSON) || {};
|
||
const contributed = (manifest.contributes && manifest.contributes.configuration && manifest.contributes.configuration.properties) || {};
|
||
const fields = settings.fields(contributed);
|
||
const problems = []; // what went wrong lately, for the Status view
|
||
const shown = new Map();
|
||
let shownCount = 0;
|
||
let rewrites = 0;
|
||
const rewriting = new Set(); // documents a rewrite is being written for
|
||
const asking = new Map(); // document uri -> the panel's task that waits for its instruction
|
||
const ignored = new priv.Ignored(); // what the project's .gitignore leaves out, as git says it
|
||
const saidPrivate = new Set(); // documents it was said of that no suggestion is asked for in them
|
||
|
||
/** The folders that are the project here: the window's own, on this computer. */
|
||
const projectFolders = () => (vscode.workspace.workspaceFolders || []).filter((f) => f.uri.scheme === 'file').map((f) => f.uri.fsPath);
|
||
/** Whether a file other than the one in front may go along by itself (src/private.js). */
|
||
const maySend = (file) => priv.maySend(file, projectFolders(), ignored);
|
||
|
||
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() });
|
||
|
||
/** What went wrong is kept for the Status view, the newest last. */
|
||
function problem(text) {
|
||
problems.push(String(text).slice(0, 600));
|
||
while (problems.length > 12) problems.shift();
|
||
postStatus();
|
||
}
|
||
|
||
/**
|
||
* A failure is said in the panel: a note in the conversation, which offers the Account view
|
||
* when the CLI is not signed in. Never a notification that waits for an answer.
|
||
*/
|
||
const failed = (e) => {
|
||
const signedOut = words.notSignedIn(e);
|
||
const text = chat.words(e).trim();
|
||
const whole = text + (/[.!?…`]$/.test(text) ? '' : '.');
|
||
chat.note(whole, 'error', signedOut ? 'signIn' : undefined);
|
||
problem(whole);
|
||
view.reveal().then(undefined, () => {});
|
||
};
|
||
const guard = (promise) => Promise.resolve(promise).then(undefined, failed);
|
||
/** Said beside the editor and expecting no answer: what a command could not do there. */
|
||
const tell = (text, level) => {
|
||
if (level === 'warning') return vscode.window.showWarningMessage('LLeMbas: ' + text);
|
||
if (level === 'error') return vscode.window.showErrorMessage('LLeMbas: ' + text);
|
||
return vscode.window.showInformationMessage('LLeMbas: ' + text);
|
||
};
|
||
|
||
// ---- signing in and out: the panel's Account view ----
|
||
|
||
/** 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());
|
||
|
||
const account = new Account({
|
||
command: cliCommand,
|
||
commandName: () => String(config().get('command') || 'lembas'),
|
||
ca: () => String(config().get('login.caFile') || ''),
|
||
});
|
||
cancelSignIn = () => account.dispose();
|
||
account.on('change', () => view.post({ type: 'account', account: account.state() }));
|
||
/** Another account, or none: nothing read from the old one is kept — not its models, not this window's choice among them, not its sessions. */
|
||
function forgetAccount() {
|
||
windowModel.main = undefined;
|
||
windowModel.autocomplete = undefined;
|
||
chat.forgetAccount();
|
||
listed.sessions = [];
|
||
listed.error = '';
|
||
modelsRead.loaded = false;
|
||
modelsRead.error = '';
|
||
postModels();
|
||
postSessions();
|
||
}
|
||
account.on('signedIn', (done) => {
|
||
// A new agent, so the open chat works at once with the new sign-in.
|
||
chat.stopAgent(true);
|
||
forgetAccount();
|
||
loadModels().then(undefined, () => {});
|
||
autocompleteProblem = null;
|
||
completer.unblock();
|
||
const models = Number.isFinite(done.models) ? ` (${done.models} models)` : '';
|
||
chat.note(`Signed in to ${account.server}${models}. The next message starts a session.`);
|
||
showStatus();
|
||
postStatus();
|
||
});
|
||
account.on('signedOut', (message) => {
|
||
chat.stopAgent(true);
|
||
forgetAccount();
|
||
chat.note(message);
|
||
showStatus();
|
||
postStatus();
|
||
});
|
||
|
||
/** "Sign In": the Account view, and with an address the sign-in itself (which asks there before it replaces one). */
|
||
async function signIn(address) {
|
||
const server = typeof address === 'string' ? address.trim() : '';
|
||
await view.show('account', { focus: 'account-address', address: server || undefined });
|
||
if (server) await account.begin(server);
|
||
else account.refresh().then(undefined, () => {});
|
||
}
|
||
|
||
/** "Sign Out": the Account view asks, saying whose sign-in goes. */
|
||
async function signOut() {
|
||
await view.show('account', { focus: 'confirm' });
|
||
await account.askSignOut();
|
||
}
|
||
|
||
function openApproval() {
|
||
const url = account.approvalUrl();
|
||
if (url) Promise.resolve(vscode.env.openExternal(vscode.Uri.parse(url, true))).then(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 }));
|
||
// The other open tabs, by name: only files of this project, never one that looks like it
|
||
// holds secrets or that the project's .gitignore leaves out (src/private.js).
|
||
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' && maySend(tab.input.uri.fsPath)) 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) : '' };
|
||
}
|
||
|
||
/**
|
||
* Git is asked of every open tab of this project whether the project's .gitignore leaves it
|
||
* out — when the window opens and whenever its tabs change — so that it is known by the time
|
||
* a message would name the tab. A tab git has not answered for yet is not named.
|
||
*/
|
||
function askAboutTabs() {
|
||
const folders = projectFolders();
|
||
let asked = 0;
|
||
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') continue;
|
||
const file = tab.input.uri.fsPath;
|
||
if (asked++ < 200 && priv.inside(file, folders) && !priv.looksSecret(file)) ignored.known(file);
|
||
}
|
||
}
|
||
}
|
||
|
||
// ---- 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;
|
||
}
|
||
|
||
/** "Open a File of This Project": a search of the project's files, beside the conversation. */
|
||
function openIndexedFile() {
|
||
return view.show('files', { beside: true, focus: 'files-query' });
|
||
}
|
||
|
||
/** "Add File to Chat": an `@` in the composer, where the files of the project are listed as it is typed. */
|
||
async function addFileToChat() {
|
||
await view.show('chat', { focus: false });
|
||
view.postLater({ type: 'addFile' });
|
||
}
|
||
|
||
// ---- sessions: the panel's Sessions view ----
|
||
|
||
const listed = { loading: false, error: '', sessions: [] };
|
||
const sessionsState = () => ({ ...listed, canDelete: chat.has('delete'), current: chat.session || '', busy: chat.busy });
|
||
const postSessions = () => view.post({ type: 'sessions', sessions: sessionsState() });
|
||
|
||
async function loadSessions() {
|
||
listed.loading = true;
|
||
listed.error = '';
|
||
postSessions();
|
||
try {
|
||
const list = await chat.listSessions(50);
|
||
listed.sessions = list
|
||
.filter((x) => x && typeof x.id === 'string' && x.id.length <= 200)
|
||
.map((x) => ({ id: x.id, title: String(x.title || '').slice(0, 300), model: String(x.model || '').slice(0, 200), updated: Number(x.updated) || 0 }));
|
||
} catch (e) {
|
||
listed.sessions = [];
|
||
listed.error = chat.words(e);
|
||
}
|
||
listed.loading = false;
|
||
postSessions();
|
||
}
|
||
|
||
/** Only a session the list showed is opened or deleted, whatever id the page sends. */
|
||
const isListed = (id) => listed.sessions.some((x) => x.id === id);
|
||
|
||
async function resume(id) {
|
||
if (!isListed(id)) return undefined;
|
||
if (chat.busy) {
|
||
listed.error = words.WORDS.working;
|
||
return postSessions();
|
||
}
|
||
if (await chat.resumeSession(id)) {
|
||
postSessions();
|
||
await view.show('chat', { focus: true });
|
||
}
|
||
return undefined;
|
||
}
|
||
|
||
async function deleteSession(id) {
|
||
if (!isListed(id)) return undefined;
|
||
const why = await chat.deleteSession(id);
|
||
if (why === 'agent') listed.error = chat.startError || 'The agent did not start.';
|
||
else if (why === 'too_old') listed.error = words.WORDS.too_old;
|
||
else if (why === 'working') listed.error = words.WORDS.working;
|
||
if (why && why !== 'gone') return postSessions();
|
||
// Deleted, or no longer there: either way the list is read again.
|
||
return loadSessions();
|
||
}
|
||
|
||
// ---- settings: read and written as the editor's own, at the level the person chose ----
|
||
|
||
const hasWorkspace = () => !!(vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length);
|
||
|
||
function configState() {
|
||
const c = config();
|
||
const values = {};
|
||
for (const f of fields) values[f.key] = settings.levelsOf(f, typeof c.inspect === 'function' ? c.inspect(f.key) : undefined, c.get(f.key));
|
||
return { workspace: hasWorkspace(), values };
|
||
}
|
||
const postConfig = () => view.post({ type: 'config', config: configState() });
|
||
|
||
/**
|
||
* A change the panel asks for. It is checked against the table first: only a setting of
|
||
* LLeMbas, only a value of its declared type and range, only at a level it has.
|
||
*/
|
||
async function writeSetting(wanted) {
|
||
const w = settings.checkWrite(fields, wanted);
|
||
const refuse = (why) => {
|
||
view.post({ type: 'refused', text: why });
|
||
postConfig();
|
||
};
|
||
if (!w.ok) return refuse(w.why);
|
||
if (w.target === 'workspace' && !hasWorkspace()) return refuse('Open a folder to keep a setting for it.');
|
||
try {
|
||
await config().update(w.key, w.value, w.target === 'workspace' ? vscode.ConfigurationTarget.Workspace : vscode.ConfigurationTarget.Global);
|
||
} catch (e) {
|
||
return refuse('The editor did not take the setting: ' + String((e && e.message) || e));
|
||
}
|
||
postConfig();
|
||
showStatus();
|
||
return undefined;
|
||
}
|
||
|
||
function openSettingsUi() {
|
||
const id = (context.extension && context.extension.id) || `${manifest.publisher || 'llembas'}.${manifest.name || 'llembas'}`;
|
||
return vscode.commands.executeCommand('workbench.action.openSettings', '@ext:' + id);
|
||
}
|
||
|
||
// ---- what an editor command leaves in the panel to be answered ----
|
||
|
||
const tasks = new Map(); // id -> { id, kind, title, detail, … }
|
||
let taskCount = 0;
|
||
const taskList = () => [...tasks.values()].map((t) => ({ id: t.id, kind: t.kind, title: t.title, detail: t.detail || '', placeholder: t.placeholder || '', action: t.action || '' }));
|
||
const postTasks = (focus) => view.postLater({ type: 'tasks', tasks: taskList(), focus: focus || '' });
|
||
|
||
/**
|
||
* Ask for an instruction in the panel (in place of an input box). Resolves the text, or
|
||
* `undefined` when it was put away. `key`: the document it is about, so that asking again
|
||
* for the same one goes to the question that already waits.
|
||
*/
|
||
function askInstruction(title, placeholder, action, key) {
|
||
const id = 't' + ++taskCount;
|
||
return new Promise((resolve) => {
|
||
if (key) asking.set(key, id);
|
||
const settle = (text) => {
|
||
if (key && asking.get(key) === id) asking.delete(key);
|
||
resolve(text);
|
||
};
|
||
tasks.set(id, { id, kind: 'instruction', title, placeholder, action, resolve: settle });
|
||
view.show('chat', { focus: false }).then(
|
||
() => postTasks(id),
|
||
() => postTasks(id),
|
||
);
|
||
});
|
||
}
|
||
|
||
function answerTask(id, text) {
|
||
const t = tasks.get(id);
|
||
if (!t || t.kind !== 'instruction') return;
|
||
tasks.delete(id);
|
||
postTasks();
|
||
// The keyboard goes back to the text the instruction is about.
|
||
vscode.commands.executeCommand('workbench.action.focusActiveEditorGroup').then(undefined, () => {});
|
||
t.resolve(text);
|
||
}
|
||
|
||
function cancelTask(id) {
|
||
const t = tasks.get(id);
|
||
if (!t) return;
|
||
if (t.kind === 'instruction') {
|
||
tasks.delete(id);
|
||
postTasks();
|
||
vscode.commands.executeCommand('workbench.action.focusActiveEditorGroup').then(undefined, () => {});
|
||
t.resolve(undefined);
|
||
} else if (t.kind === 'working' && t.cancel) t.cancel();
|
||
}
|
||
|
||
/** An instruction for this document is already asked for in the panel: the keyboard goes there. `true` when one is. */
|
||
async function waitingInstruction(key) {
|
||
const id = asking.get(key);
|
||
if (!id || !tasks.has(id)) return false;
|
||
await view.show('chat', { focus: false }).then(undefined, () => {});
|
||
postTasks(id);
|
||
return true;
|
||
}
|
||
|
||
/** A request to the model that is being written: shown in the panel with what came so far, and a way to stop it. */
|
||
async function working(title, id, run) {
|
||
const tid = 't' + ++taskCount;
|
||
const task = { id: tid, kind: 'working', title, detail: 'Waiting for the model…', cancel: () => chat.notify('_lembas/edit/cancel', { id }) };
|
||
tasks.set(tid, task);
|
||
postTasks();
|
||
let written = 0;
|
||
let told = 0;
|
||
const onDelta = (p) => {
|
||
if (!p || p.id !== id || typeof p.delta !== 'string') return;
|
||
written += p.delta.length;
|
||
task.detail = `${written} characters so far`;
|
||
// The page is told a few times a second, not at every piece.
|
||
if (Date.now() - told < 250) return;
|
||
told = Date.now();
|
||
postTasks();
|
||
};
|
||
chat.on('editDelta', onDelta);
|
||
try {
|
||
return await run();
|
||
} finally {
|
||
chat.off('editDelta', onDelta);
|
||
tasks.delete(tid);
|
||
postTasks();
|
||
}
|
||
}
|
||
|
||
/** Changes shown in a file: answered there change by change, or here all at once. */
|
||
function proposed(doc, entry) {
|
||
const tid = 't' + ++taskCount;
|
||
tasks.set(tid, { id: tid, kind: 'proposal', doc, entry, title: '', detail: 'Nothing is written until you accept. Each change can be answered in the file too.' });
|
||
syncProposals();
|
||
view.reveal().then(undefined, () => {});
|
||
}
|
||
|
||
function syncProposals() {
|
||
let changed = false;
|
||
for (const t of [...tasks.values()]) {
|
||
if (t.kind !== 'proposal') continue;
|
||
const n = proposals.entry(t.doc) === t.entry ? t.entry.hunks.length : 0;
|
||
const title = `${n} change${n === 1 ? '' : 's'} proposed in ${path.basename(t.doc.uri.path) || 'the file'}`;
|
||
if (n === 0) tasks.delete(t.id);
|
||
else if (title !== t.title) t.title = title;
|
||
else continue;
|
||
changed = true;
|
||
}
|
||
if (changed) postTasks();
|
||
}
|
||
proposals.onChange = syncProposals;
|
||
|
||
async function answerProposal(id, answer) {
|
||
const t = tasks.get(id);
|
||
if (!t || t.kind !== 'proposal' || proposals.entry(t.doc) !== t.entry) return undefined;
|
||
if (answer === 'show') return proposals.showDiff(t.doc);
|
||
if (answer === 'accept') return proposals.accept(t.doc, t.entry.hunks.slice());
|
||
return proposals.reject(t.doc, t.entry.hunks.slice());
|
||
}
|
||
|
||
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(words.WORDS.working);
|
||
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');
|
||
// Where the value in force is kept is where it is changed: a Workspace value is not left to outvote the new one.
|
||
const inspected = typeof c.inspect === 'function' ? c.inspect('complete.auto') : undefined;
|
||
const target = inspected && inspected.workspaceValue !== undefined ? vscode.ConfigurationTarget.Workspace : vscode.ConfigurationTarget.Global;
|
||
await c.update('complete.auto', next, target);
|
||
postConfig();
|
||
showStatus();
|
||
tell(`autocomplete as you type is ${next ? 'on' : 'off'}.`);
|
||
}
|
||
|
||
/** What a view of the panel asks for when it opens. */
|
||
function load(what) {
|
||
if (what === 'config') return postConfig();
|
||
if (what === 'models') return loadModels();
|
||
if (what === 'sessions') return loadSessions();
|
||
if (what === 'account') return account.refresh();
|
||
// Status says who is signed in too: looked up once, the first time it is asked for.
|
||
if (!account.checked) account.refresh().then(postStatus, postStatus);
|
||
return postStatus();
|
||
}
|
||
|
||
/** "Restart the agent" in the Status view: stopped, and started again at once. */
|
||
async function restartAgent() {
|
||
chat.stopAgent(true);
|
||
autocompleteProblem = null;
|
||
completer.unblock();
|
||
await chat.connect(true);
|
||
showStatus();
|
||
postStatus();
|
||
}
|
||
|
||
const actions = {
|
||
mediaDir,
|
||
fields,
|
||
guard,
|
||
account,
|
||
openFileAt,
|
||
searchFiles: searchProjectFiles,
|
||
compact: compactSession,
|
||
explain: () => explain(),
|
||
fixProblems: () => fixProblems(),
|
||
insertCode,
|
||
configState,
|
||
taskList,
|
||
load,
|
||
writeSetting,
|
||
openSettingsUi,
|
||
chooseModel: (kind, id, keep) => chooseModel(kind, id, keep),
|
||
resume,
|
||
deleteSession,
|
||
openApproval,
|
||
restartAgent,
|
||
answerTask,
|
||
cancelTask,
|
||
answerProposal,
|
||
async sendTyped(text) {
|
||
if (chat.busy) {
|
||
if (chat.has('steer')) return chat.steer(text);
|
||
return vscode.window.showWarningMessage(words.WORDS.working);
|
||
}
|
||
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);
|
||
},
|
||
async newSession() {
|
||
if (!(await chat.newSession())) vscode.window.showWarningMessage(words.WORDS.working);
|
||
},
|
||
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().then(undefined, () => {});
|
||
}
|
||
});
|
||
|
||
/** "Ask About the Selection": the selection goes with the next message, and the keyboard goes to the composer to type it. */
|
||
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.');
|
||
view.attach(w);
|
||
return view.show('chat', { focus: 'prompt' });
|
||
}
|
||
|
||
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.show('chat', { focus: false });
|
||
if (chat.busy) return vscode.window.showWarningMessage(words.WORDS.working);
|
||
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.show('chat', { focus: false });
|
||
if (chat.busy) return vscode.window.showWarningMessage(words.WORDS.working);
|
||
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.');
|
||
// Asked again before the instruction was typed: the question that waits is the one to answer.
|
||
if (await waitingInstruction(key)) return undefined;
|
||
const line = editor.selection.active.line;
|
||
const name = doc.uri.scheme === 'file' ? vscode.workspace.asRelativePath(doc.uri, false) : 'untitled';
|
||
const instruction = await askInstruction(`Generate code at ${name}:${line + 1}`, 'Describe the code to write there', 'Generate', key);
|
||
if (!instruction || !instruction.trim()) return undefined;
|
||
if (proposals.pending(doc) || rewriting.has(key)) return undefined;
|
||
// Only from here is something being written for this file.
|
||
rewriting.add(key);
|
||
try {
|
||
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: ' + words.WORDS.too_old);
|
||
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 working(`Generating code at ${name}:${line + 1}…`, id, () => chat.request('_lembas/edit', params));
|
||
} 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.');
|
||
const made = proposals.set(doc, hunks);
|
||
proposed(doc, made);
|
||
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.');
|
||
if (await waitingInstruction(key)) return undefined;
|
||
return rewriteIn(editor);
|
||
}
|
||
|
||
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 label = selectionLabel(name, first + 1, last + 1);
|
||
const key = doc.uri.toString();
|
||
const instruction = await askInstruction(`Rewrite ${label}`, 'What should change?', 'Rewrite', key);
|
||
if (!instruction || !instruction.trim()) return undefined;
|
||
if (proposals.pending(doc) || rewriting.has(key)) return undefined;
|
||
// Only from here is a rewrite being written for this file: an instruction that was asked
|
||
// for and never typed holds nothing.
|
||
rewriting.add(key);
|
||
try {
|
||
return await rewriteWith(editor, instruction, first, last, label);
|
||
} finally {
|
||
rewriting.delete(key);
|
||
}
|
||
}
|
||
|
||
async function rewriteWith(editor, instruction, first, last, label) {
|
||
const doc = editor.document;
|
||
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: ' + words.WORDS.too_old);
|
||
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 working(`Rewriting ${label}…`, id, () => chat.request('_lembas/edit', params));
|
||
} 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, () => {});
|
||
// Answered in the file change by change (the Accept / Reject lines), or in the panel all at once.
|
||
proposed(doc, made);
|
||
return undefined;
|
||
}
|
||
|
||
// ---- 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(words.WORDS.too_old), { 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) {
|
||
// Said once, expecting no answer: the status item marks it and opens the panel where it is put right.
|
||
let text;
|
||
let command = 'llembas.modelSettings';
|
||
if (reason === 'no_model' || reason === 'not_allowed' || reason === 'unknown_model') {
|
||
text = (message || (reason === 'no_model' ? 'No autocomplete model is chosen.' : 'That model cannot be used for autocomplete.')) + ' Choose one in the LLeMbas panel, under Models.';
|
||
command = 'llembas.chooseAutocompleteModel';
|
||
} else if (reason === 'not_logged_in') {
|
||
text = chat.words({ message, data: { reason } }) + ' The LLeMbas panel has it under Account.';
|
||
command = 'llembas.signIn';
|
||
} else text = message || 'autocomplete is not available here yet.';
|
||
autocompleteProblem = { text: 'No suggestions: ' + text, command };
|
||
problem(autocompleteProblem.text);
|
||
showStatus();
|
||
if (reason === 'not_logged_in') vscode.window.showWarningMessage('LLeMbas: no suggestions: ' + text);
|
||
else vscode.window.showInformationMessage('LLeMbas: no suggestions: ' + text);
|
||
},
|
||
onError(message, manual) {
|
||
output.appendLine('autocomplete: ' + message);
|
||
if (manual) vscode.window.showWarningMessage('LLeMbas: no suggestion: ' + message);
|
||
},
|
||
});
|
||
/**
|
||
* The text of up to six other open files (the first 400 lines of each, as the Neovim plugin
|
||
* sends), which the CLI may put pieces of beside the text around the cursor. Only files of
|
||
* this project, and never one that looks like it holds secrets or that the project's
|
||
* .gitignore leaves out (src/private.js).
|
||
*/
|
||
async function openSnippets(excludeDoc) {
|
||
const folders = projectFolders();
|
||
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 file = d.uri.fsPath;
|
||
if (!priv.inside(file, folders) || priv.looksSecret(file) || (await ignored.check(file))) continue;
|
||
if (d.isClosed) continue;
|
||
const last = Math.min(d.lineCount, 400);
|
||
const text = last > 0 ? d.getText(new vscode.Range(0, 0, last - 1, d.lineAt(last - 1).text.length)) : '';
|
||
if (!text || text.length > 32768) continue;
|
||
out.push({ path: file, text });
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/** A file that looks like it holds secrets: no suggestion is asked for in it, so nothing of it is sent. Said once a file. */
|
||
function privateDocument(document, manual) {
|
||
if (document.uri.scheme !== 'file' || !priv.looksSecret(document.uri.fsPath)) return false;
|
||
const key = document.uri.toString();
|
||
if (manual || !saidPrivate.has(key)) {
|
||
saidPrivate.add(key);
|
||
tell('no suggestions in this file: its name says it may hold secrets, so nothing of it is sent.');
|
||
}
|
||
return true;
|
||
}
|
||
|
||
function warmActiveEditor(editor) {
|
||
if (!editor || !editor.document || editor.document.uri.scheme !== 'file') return;
|
||
if (priv.looksSecret(editor.document.uri.fsPath)) return;
|
||
// Asked now, so that it is known by the time a message would name this tab.
|
||
if (priv.inside(editor.document.uri.fsPath, projectFolders())) ignored.known(editor.document.uri.fsPath);
|
||
completer.warm({
|
||
cwd: workingDirectory(),
|
||
sessionId: chat.session || undefined,
|
||
path: editor.document.uri.fsPath,
|
||
text: editor.document.getText().slice(0, 32768),
|
||
});
|
||
}
|
||
|
||
chat.on('connected', () => {
|
||
autocompleteProblem = null;
|
||
completer.unblock();
|
||
warmActiveEditor(vscode.window.activeTextEditor);
|
||
postStatus();
|
||
});
|
||
chat.on('stopped', () => postStatus());
|
||
|
||
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
|
||
if (privateDocument(document, manual)) return undefined;
|
||
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 = await openSnippets(document);
|
||
if (token.isCancellationRequested) return undefined;
|
||
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 ----
|
||
|
||
// Beside the panel, for when it is closed: what autocomplete uses and whether it is on. A press opens the panel.
|
||
const LENGTH_WORDS = { auto: 'as the server sets it', words: 'a few words', line: 'one line', block: 'a function or block', file: 'a long passage' };
|
||
const status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 90);
|
||
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) ' : autocompleteProblem ? '$(warning) ' : '$(sparkle) ';
|
||
const suffix = model ? ': ' + String(model).split('/').pop() : '';
|
||
status.text = icon + 'LLeMbas' + suffix + (autoOn ? '' : ' (off)');
|
||
status.command = autocompleteProblem ? autocompleteProblem.command : 'llembas.modelSettings';
|
||
const lines = [
|
||
model
|
||
? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}`
|
||
: 'Autocomplete model: not chosen',
|
||
`Autocomplete: ${autoOn ? 'on' : 'off'} · length: ${LENGTH_WORDS[len] || len}${maxTok ? ` · at most ${maxTok} tokens` : ''}`,
|
||
];
|
||
if (autocompleteProblem) lines.unshift(autocompleteProblem.text);
|
||
if (chat.mode) lines.push(`Session mode: ${chat.mode}`);
|
||
if (chat.model) lines.push(`Session model: ${chat.model}`);
|
||
lines.push('Click to open the LLeMbas panel.');
|
||
status.tooltip = lines.join('\n');
|
||
status.show();
|
||
}
|
||
showStatus();
|
||
chat.on('state', showStatus);
|
||
|
||
// ---- the agent's state: the panel's Status view ----
|
||
|
||
function postStatus() {
|
||
view.post({
|
||
type: 'status',
|
||
status: {
|
||
...chat.status(),
|
||
command: String(config().get('command') || 'lembas'),
|
||
resolved: cliCommand(),
|
||
extension: version,
|
||
cwd: chat.sessionCwd || workingDirectory(),
|
||
problems: problems.slice(),
|
||
checked: account.checked,
|
||
server: account.server,
|
||
},
|
||
});
|
||
}
|
||
|
||
// ---- the models: the panel's Models view ----
|
||
|
||
const modelsRead = { loading: false, loaded: false, error: '' };
|
||
const modelsState = () => ({
|
||
...modelsRead,
|
||
models: chat.models.map((m) => ({ id: String(m.id), name: String(m.name || m.id), for: Array.isArray(m.for) ? m.for.map(String) : undefined })),
|
||
main: (chat.settings && chat.settings.main) || null,
|
||
autocomplete: (chat.settings && chat.settings.autocomplete) || null,
|
||
window: { main: windowModel.main || '', autocomplete: windowModel.autocomplete || '' },
|
||
});
|
||
const postModels = () => view.post({ type: 'models', models: modelsState() });
|
||
|
||
async function loadModels() {
|
||
modelsRead.loading = true;
|
||
modelsRead.error = '';
|
||
postModels();
|
||
try {
|
||
await chat.loadModels();
|
||
modelsRead.loaded = true;
|
||
} catch (e) {
|
||
modelsRead.error = chat.words(e);
|
||
}
|
||
modelsRead.loading = false;
|
||
postModels();
|
||
showStatus();
|
||
}
|
||
// The list is read again by the chat when a session opens: the view follows.
|
||
let modelsSeen = null;
|
||
chat.on('state', () => {
|
||
if (chat.models === modelsSeen) return;
|
||
modelsSeen = chat.models;
|
||
if (chat.models.length) modelsRead.loaded = true;
|
||
postModels();
|
||
});
|
||
|
||
/**
|
||
* Choose the autocomplete or the main model: saved in the account (`keep: 'account'`), or for
|
||
* this window only. `id` `null`: the server's own again, and this window's choice forgotten.
|
||
* Only a model the server listed for that use is taken, whatever the page sends.
|
||
*/
|
||
async function chooseModel(kind, id, keep) {
|
||
const key = kind === 'autocomplete' ? 'autocomplete_model' : 'main_model';
|
||
if (id !== null && !chat.models.some((m) => m.id === id && (!Array.isArray(m.for) || m.for.includes(kind)))) {
|
||
modelsRead.error = `${id} is not a model your server offers for ${kind === 'autocomplete' ? 'autocomplete' : 'chat'}.`;
|
||
return postModels();
|
||
}
|
||
modelsRead.error = '';
|
||
try {
|
||
if (id === null) {
|
||
windowModel[kind] = undefined;
|
||
await chat.editorSettings({ [key]: null });
|
||
} else if (keep === 'account') {
|
||
await chat.editorSettings({ [key]: id });
|
||
windowModel[kind] = undefined;
|
||
} else {
|
||
windowModel[kind] = id;
|
||
if (kind === 'main' && chat.session && !chat.busy) await chat.setModel(id);
|
||
}
|
||
} catch (e) {
|
||
modelsRead.error = chat.words(e);
|
||
}
|
||
if (kind === 'autocomplete') {
|
||
autocompleteProblem = null;
|
||
completer.unblock();
|
||
}
|
||
showStatus();
|
||
return postModels();
|
||
}
|
||
|
||
// ---- commands ----
|
||
|
||
const command = (name, fn) => context.subscriptions.push(vscode.commands.registerCommand(name, (...args) => guard(Promise.resolve().then(() => fn(...args)))));
|
||
// A command opens the panel where it belongs. One that is about the conversation in progress
|
||
// opens its view beside the conversation; one that is about how LLeMbas is set up opens the view whole.
|
||
command('llembas.open', () => view.show('chat', { focus: 'prompt' }));
|
||
command('llembas.newSession', actions.newSession);
|
||
command('llembas.resumeSession', () => view.show('sessions', { beside: true, focus: 'sessions-filter' }));
|
||
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', async () => {
|
||
// The modes are the session's: one is opened first, so the list in the chat's header has them.
|
||
await chat.ensureSession();
|
||
return view.show('chat', { focus: 'mode' });
|
||
});
|
||
command('llembas.chooseModel', () => view.show('models', { beside: true, focus: 'm-session' }));
|
||
command('llembas.modelSettings', () => view.show('models', { focus: 'm-main' }));
|
||
command('llembas.chooseAutocompleteModel', () => view.show('models', { focus: 'm-autocomplete' }));
|
||
command('llembas.settings', () => view.show('settings', {}));
|
||
command('llembas.status', () => view.show('status', {}));
|
||
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());
|
||
saidPrivate.delete(doc.uri.toString());
|
||
}),
|
||
// A .gitignore that changed, or other folders: what git said before is asked again.
|
||
vscode.workspace.onDidSaveTextDocument((doc) => {
|
||
if (/(^|[\\/])\.gitignore$/.test(doc.uri.fsPath || '')) {
|
||
ignored.forget();
|
||
askAboutTabs();
|
||
}
|
||
}),
|
||
vscode.workspace.onDidChangeWorkspaceFolders(() => {
|
||
ignored.forget();
|
||
askAboutTabs();
|
||
}),
|
||
vscode.window.tabGroups.onDidChangeTabs(() => askAboutTabs()),
|
||
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();
|
||
// Changed anywhere — the editor's Settings, settings.json, another window: the panel shows it.
|
||
if (ev.affectsConfiguration('llembas')) {
|
||
postConfig();
|
||
showStatus();
|
||
postStatus();
|
||
}
|
||
}),
|
||
proposals.removed,
|
||
proposals.added,
|
||
);
|
||
askAboutTabs();
|
||
}
|
||
|
||
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 };
|