VS Code / VSCodium: the extension's first version

A client of `lembas serve --stdio`, in vscode/: plain JavaScript, no
dependencies, no build. scripts/package-vscode.sh writes the .vsix with
Node alone; the version comes from VERSION.

- Chat in a side bar view: transcript, mode, the session's model, Stop,
  new session. Approval cards are answered there; one that carries ACP
  diff content opens the editor's diff view before the answer.
- Ask about a selection, with the editor context as _meta.lembas.editor.
- Rewrite a selection through _lembas/edit: proposed changes with
  Accept / Reject per change and for all, and a diff beside the file.
  Nothing is written before it is accepted.
- Autocomplete as an inline completion provider on _lembas/complete:
  debounced, the request before cancelled by its own id, a cancelled or
  stale answer shown as nothing. No model chosen: said once, with a
  button that opens the picker.
- The two model settings through _lembas/editor/settings, and a quick
  switch for the window that is saved nowhere.
- Files the agent shows (_lembas/show, _lembas/show/read): pictures in
  the chat, anything else a line with Open, under a size limit.
- fs/read_text_file answered from the open document.

Model output is untrusted: the extension's own Markdown reader makes a
tree of plain objects and the page builds elements and text from it,
under a Content-Security-Policy with one nonce'd script.

Tests (scripts/test-vscode.sh, node --test): the modules in src/ against
a stand-in agent, the package's structure, and extension.js against an
in-memory stand-in for the editor's API. Nothing was run inside VS Code.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-24 11:42:58 +00:00
1 parent ea5dd1b1b3
commit 3d548bbd73
34 files changed
+6510 -2

No files matched your search

+21
View File
@@ -30,3 +30,24 @@
### Fixed (Neovim)
- Starting a new session could leave the plugin believing the new agent had stopped.
### VS Code / VSCodium extension
- First version, in `vscode/`: a client of `lembas serve --stdio`, like the Neovim plugin. Plain
JavaScript with no dependencies and no build; `scripts/package-vscode.sh` writes the `.vsix`.
- A chat in the side bar: the transcript, the session's mode and model, Stop, and a new session.
The CLI's approval cards are answered there; one that carries an edit opens the change in the
editor's diff view before you answer, and nothing is written until you allow it.
- Ask about a selection: the file, the lines, the selected text as the editor has it and the
problems shown there go with the question; a typed message carries the file in front.
- Rewrite a selection: the result is proposed in the file as changes to accept or reject, one by
one or all at once, and as a diff beside it. Nothing is written before you accept.
- Autocomplete as inline suggestions, as you type and on `Alt+\`. Without an autocomplete model
it says so once, with a button to choose one.
- The two model settings, autocomplete and main: saved in your account, or switched for one
window only.
- A picture the agent shows appears in the chat; any other file is a line with Open. Files of
more than 64 MB are refused.
- The agent reads a file you have open as the editor has it, saved or not.
- What a model writes is drawn as text through the extension's own small Markdown reader: HTML in
a reply stays text, and only `http`, `https` and `mailto` links open.
+18 -1
View File
@@ -1,6 +1,6 @@
# LLeMbas IDE
LLeMbas in your editor: a Neovim plugin, and a VS Code / VSCodium extension (not written yet).
LLeMbas in your editor: a Neovim plugin, and a VS Code / VSCodium extension.
Both are clients of the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI). The CLI is the agent:
it holds the sign-in to your LLeMbas server, the models, the tools and the permissions. The editor
@@ -55,10 +55,27 @@ approvals work, and a rewrite is done by the agent on the saved file.
Not there yet: picking an older session, and the agent's questions and plans as cards.
## VS Code and VSCodium
Needs VS Code or VSCodium 1.85 or newer. The extension lives in `vscode/`; it is plain JavaScript
with no dependencies, and is installed from a package you build with Node alone:
```sh
scripts/package-vscode.sh # writes dist/llembas-<version>.vsix
codium --install-extension dist/llembas-<version>.vsix # or: code --install-extension …
```
A chat in the side bar, questions about a selection, a selection rewritten as changes you accept or
reject, autocomplete as you type and on `Alt+\`, the two model settings, and pictures the agent
shows. Commands, keys, settings and what is not there yet: [`vscode/README.md`](vscode/README.md).
## Tests
`scripts/test-nvim.sh` runs the plugin headless against a stand-in agent (needs `nvim` and `python3`).
`scripts/test-vscode.sh` runs the extension's parts that need no editor against a stand-in agent of
its own, and checks the package (needs Node 18 or newer and `python3`). It does not start VS Code.
## Licence
MIT.
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# Builds the VS Code / VSCodium extension as dist/llembas-<version>.vsix. Needs only Node 18 or
# newer: no packaging tool, no npm install. The version is the repository's VERSION file.
set -eu
cd "$(dirname "$0")/.."
exec node vscode/tools/vsix.js "$@"
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# The extension's tests: the parts that need no editor, against a stand-in agent.
# Needs Node 18 or newer and python3. Nothing here starts VS Code.
set -eu
cd "$(dirname "$0")/.."
exec node --test vscode/tests/*.test.js
+156 -1
View File
@@ -1,3 +1,158 @@
# LLeMbas for VS Code and VSCodium
Not written yet. It will be a client of `lembas serve --stdio`, like the Neovim plugin beside it.
LLeMbas in the editor: a chat with the agent beside your files, questions about a selection, a
selection rewritten as a diff you accept or reject, and autocomplete.
The extension is a client of the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI). The CLI is
the agent: it holds the sign-in to your LLeMbas server, the models, the tools and the permissions.
The extension starts `lembas serve --stdio` and talks to it over the Agent Client Protocol. Nothing
about a server or a model is set in the editor, only which command starts the CLI.
This is a beta. It has been tested without an editor (see *Tests*); it has not yet been run inside
VS Code or VSCodium by its authors.
## What you need
- VS Code or VSCodium 1.85 or newer.
- The LLeMbas CLI, signed in (`lembas login <address>`). The chat works with LLeMbas CLI 2.0 betas;
autocomplete, rewriting a selection, the model settings and pictures in the chat need a CLI and a
server that have the editor methods (harness spec 3.11.0). With an older one the extension says so
where it matters and the rest keeps working.
## Install
Build the package (needs only Node 18 or newer — no `npm install`, no packaging tool):
```sh
scripts/package-vscode.sh # writes dist/llembas-<version>.vsix
```
Then install it:
```sh
codium --install-extension dist/llembas-<version>.vsix # VSCodium
code --install-extension dist/llembas-<version>.vsix # VS Code
```
or in the editor: Extensions → `…` → *Install from VSIX…*.
If the editor does not find `lembas` (an editor started from the desktop does not always have your
shell's `PATH`), set **LLeMbas: Command** to the program's full path.
The extension is off in a folder you have not trusted (Restricted Mode): it starts an agent that
works in that folder.
## What it does
**Chat.** The LLeMbas icon in the activity bar opens the chat. Above the transcript: the session's
mode, the session's model, and *New*. Enter sends, Shift+Enter starts a new line; while the agent
works the button is *Stop*. When the agent asks before doing something, the question appears as a
card with its answers as buttons. A question about an edit — in manual mode, every edit — opens
the change in the editor's own diff view first; nothing is written until you allow it. Files the
agent changed are named under the tool's line and open with a click.
What a model writes is shown as text. A small Markdown reader in the extension turns it into
paragraphs, lists, code and links; HTML in a reply stays text, pictures in a reply are not loaded,
and a link opens in your browser only when it is `http`, `https` or `mailto`.
**Ask about a selection.** Select text, then *LLeMbas: Ask About the Selection*. With a question it
is sent at once; with an empty one the selection goes with the next message you type. The agent is
told the file, the lines, the selected text as the editor has it (saved or not) and the problems
the editor shows there. A message typed in the chat carries the file in front and the cursor's line
the same way (setting *Send Editor Context*).
**Rewrite a selection.** Select lines, then *LLeMbas: Rewrite the Selection* and say what should
change. The result comes back as proposed changes in the file: each one is marked, with *Accept*
and *Reject* above it, *Accept all* / *Reject all* above the first, and the whole proposal in the
diff view beside the file. Nothing is written until you accept; rejecting leaves the file as it
was. A change whose lines you edited meanwhile is dropped instead of being applied to the wrong
text.
**Autocomplete.** Suggestions appear as you type, after a short pause, as the editor's own inline
suggestions: Tab accepts, Escape dismisses. `Alt+\` asks for one now. It needs an autocomplete
model: when none is chosen the extension says so once, with a button to choose one, and stays quiet
until one is set.
**Two model settings.** *LLeMbas: Models (Autocomplete and Main)* — also the *LLeMbas* item in the
status bar — shows both: the **autocomplete** model, and the **main** model (chat and rewriting).
Any model your server offers can be picked for either. *Save it* keeps the choice in your account,
so every editor you sign in from uses it; *Only this window* is a quick switch that is saved
nowhere. The picker in the chat changes the model of the session you are in.
**Files the agent shows.** A picture the agent shows (a screenshot, a chart) appears in the chat.
Any other file is a line with *Open*, which hands it to your system's program for that kind of
file. A file of a kind the system might run instead of show (a script, an installer, a web page)
is not opened; you are offered its folder. Files of more than 64 MB are refused, and the agent is
told why (setting *Media: Max Megabytes*).
**Unsaved text.** When the agent reads a file you have open, it gets the text as the editor has
it, saved or not.
## Commands and keys
| Command | Key | |
|---|---|---|
| LLeMbas: Open the Chat | `Ctrl+Alt+L` | |
| LLeMbas: Ask About the Selection | `Ctrl+Alt+K` | also in the editor's context menu |
| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in the editor's context menu |
| LLeMbas: Suggest a Completion Here | `Alt+\` | |
| LLeMbas: Accept All Proposed Changes in This File | `Ctrl+Alt+Enter` | while changes are proposed |
| LLeMbas: Reject All Proposed Changes in This File | `Ctrl+Alt+Backspace` | while changes are proposed |
| LLeMbas: Accept / Reject the Proposed Change at the Cursor | | or the lines above each change |
| LLeMbas: Show the Proposed Changes as a Diff | | |
| LLeMbas: New Session | | the old session stays in the CLI's own store |
| LLeMbas: Stop the Running Turn | | |
| LLeMbas: Choose the Mode | | |
| LLeMbas: Choose This Session's Model | | |
| LLeMbas: Models (Autocomplete and Main) | | |
| LLeMbas: Choose the Autocomplete Model / the Main Model | | |
| LLeMbas: Stop the Agent | | it starts again when needed |
On macOS the keys use `Cmd` in place of `Ctrl`.
## Settings
| Setting | Default | |
|---|---|---|
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path. Set for the machine, never by a folder |
| `llembas.chat.sendEditorContext` | on | tell the agent which file is in front, the cursor, the selection and its problems |
| `llembas.chat.showThinking` | off | show the model's thinking |
| `llembas.chat.startMode` | | the mode a new session starts in; empty: the CLI's own |
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` |
| `llembas.complete.debounce` | 250 | the pause, in milliseconds, before a suggestion is asked for |
| `llembas.complete.maxTokens` | 0 | the longest suggestion; 0: the server's own number |
| `llembas.rewrite.openDiff` | on | open the diff view beside the file when a rewrite is proposed |
| `llembas.media.maxMegabytes` | 64 | the largest file taken from the agent to show or open |
## Not there yet
- Picking up an older session: a window starts a new one.
- The agent's questions with choices (`ask_user`) and its plans for approval are not shown as
cards; the agent is told nobody can be asked.
- Sound, video, PDF and 3D files are not drawn in the chat: they are a line with *Open*.
- A table in a reply is shown as written, not drawn as a table.
- An edit the agent asks about in a chat is allowed or denied as a whole, not change by change.
- A window with several folders works in the first one.
- No marketplace listing: install from the `.vsix`.
## How it is made
Plain JavaScript, no bundler, no dependencies, nothing fetched from the network, no telemetry.
`extension.js` is the only file that talks to the editor; everything else is in `src/` and runs
without one: the protocol client (`rpc.js`, `agent.js`), the chat (`chat.js`), autocomplete's
waiting and cancelling (`completion.js`), the changes of a rewrite (`hunks.js`), the Markdown
reader (`markdown.js`), the editor context (`context.js`) and shown files (`media.js`). The chat's
page (`media/chat.js`) builds what it shows from elements and text only, under a
Content-Security-Policy that allows one script and nothing from elsewhere; every colour is one of
the editor's theme variables.
## Tests
```sh
scripts/test-vscode.sh # needs Node 18+ and python3
```
They run the modules in `src/` against a stand-in agent (`tests/fake_agent.py`), check the
package the script builds (its archive, its manifest, what is and is not in it), and load
`extension.js` against an in-memory stand-in for the editor's API (`tests/stub_vscode.js`). None of
them starts VS Code: how the extension looks and behaves in a real editor is not covered by them.
+940
View File
@@ -0,0 +1,940 @@
'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 DIFF_SCHEME = 'llembas-diff';
const VIEW_ID = 'llembas.chat';
function config() {
return vscode.workspace.getConfiguration('llembas');
}
/** The folder the agent works in: the first folder of the window, else the open file's, else home. */
function workingDirectory() {
for (const f of vscode.workspace.workspaceFolders || []) if (f.uri.scheme === 'file') return f.uri.fsPath;
const active = vscode.window.activeTextEditor;
if (active && active.document.uri.scheme === 'file') return path.dirname(active.document.uri.fsPath);
return os.homedir();
}
function samePath(a, b) {
const x = path.normalize(a);
const y = path.normalize(b);
return process.platform === 'win32' ? x.toLowerCase() === y.toLowerCase() : x === y;
}
function say(e) {
const text = String((e && e.message) || e || 'it failed').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 = false;
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'),
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) {
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) {
this.applying = true;
try {
ok = await vscode.workspace.applyEdit(edit);
} finally {
this.applying = false;
}
}
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) 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;
chat.on('item', (item) => this.queue(item));
chat.on('reset', () => this.reset());
chat.on('state', () => 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(),
});
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') return { id: item.id, kind: 'agent', ast: markdown.parse(item.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.
this.dirty.set(item.id, item);
if (this.timer) return;
this.timer = setTimeout(() => {
this.timer = null;
const items = [...this.dirty.values()];
this.dirty.clear();
for (const it of items) this.post({ type: 'item', item: this.present(it) });
}, 50);
}
reset() {
this.dirty.clear();
this.post({
type: 'reset',
items: this.chat.items.map((i) => this.present(i)),
state: this.chat.state(),
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 'stop':
return this.chat.stop();
case 'new':
return a.newSession();
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 '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' && path.isAbsolute(m.path)) {
vscode.window.showTextDocument(vscode.Uri.file(m.path), { preview: true }).then(undefined, (e) => vscode.window.showWarningMessage(say(e)));
}
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;
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 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 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' && samePath(d.uri.fsPath, p.path));
// A file that is not open is the agent's to read from the disk itself, under its own permissions.
if (!doc) throw { code: -32002, message: 'not open in the editor: ' + p.path };
return { content: sliceLines(doc.getText(), p.line, p.limit) };
},
/** 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 document. HTML is opened as its text, never drawn. */
async showText(p) {
const file = typeof p.path === 'string' && p.path ? path.resolve(workingDirectory(), p.path) : '';
const line = Number.isInteger(p.line) && p.line > 0 ? p.line - 1 : 0;
try {
let doc;
if (file && fs.existsSync(file)) doc = await vscode.workspace.openTextDocument(vscode.Uri.file(file));
else doc = await vscode.workspace.openTextDocument({ content: String(p.text) });
const at = new vscode.Position(Math.min(line, doc.lineCount - 1), 0);
await vscode.window.showTextDocument(doc, { preview: true, preserveFocus: true, selection: new vscode.Range(at, at) });
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,
clientInfo: { name: 'llembas-vscode', version },
}),
cwd: workingDirectory,
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() });
const guard = (promise) => Promise.resolve(promise).then(undefined, (e) => vscode.window.showErrorMessage(say(e)));
// ---- 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 ----
const actions = {
mediaDir,
guard,
async sendTyped(text) {
if (chat.busy) 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);
},
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;
if (entry.picture && entry.file) return vscode.commands.executeCommand('vscode.open', vscode.Uri.file(entry.file));
const target = entry.original || entry.file;
if (!target) return;
if (media.mayRun(path.basename(target))) {
const pick = await vscode.window.showWarningMessage(
`${path.basename(target)} is a kind of file your system may run rather than show, so LLeMbas does not open it.`,
'Show it in its folder',
);
if (pick) vscode.commands.executeCommand('revealFileInOS', vscode.Uri.file(target));
return;
}
vscode.env.openExternal(vscode.Uri.file(target));
},
};
const view = new ChatView(context, chat, shown, actions);
context.subscriptions.push(vscode.window.registerWebviewViewProvider(VIEW_ID, view, { webviewOptions: { retainContextWhenHidden: true } }));
// 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.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 });
}
// ---- 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;
if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.');
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);
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);
},
notify: (method, params) => chat.notify(method, params),
debounceMs: () => Number(config().get('complete.debounce')),
model: () => windowModel.autocomplete,
maxTokens: () => Number(config().get('complete.maxTokens')) || undefined,
onRefusal(reason, message) {
if (reason === 'no_model' || reason === 'not_allowed') {
const text = reason === 'no_model' ? message || 'No autocomplete model is chosen.' : message || 'That model is not allowed for autocomplete.';
vscode.window.showInformationMessage('LLeMbas: ' + text, 'Choose a model').then((pick) => {
if (pick) guard(pickModel('autocomplete'));
});
} else if (reason === 'not_logged_in') {
vscode.window.showWarningMessage('LLeMbas: ' + (message || 'The LLeMbas CLI is not signed in.') + ' Sign in with `lembas login` in a terminal.');
} else {
vscode.window.showInformationMessage('LLeMbas: ' + (message || 'Autocomplete is not available here yet.'));
}
},
onError(message, manual) {
output.appendLine('autocomplete: ' + message);
if (manual) vscode.window.showWarningMessage(say(message));
},
});
chat.on('connected', () => completer.unblock());
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 asked = completer.ask(
{ prefix, suffix, path: document.uri.scheme === 'file' ? document.uri.fsPath : undefined, language: document.languageId },
{ 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;
status.text = 'LLeMbas' + (model ? ': ' + String(model).split('/').pop() : '');
status.tooltip = model
? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}. Click to change the models.`
: 'LLeMbas: choose the models';
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.stop', () => chat.stop());
command('llembas.restart', () => {
if (chat.agent) chat.agent.stop();
});
command('llembas.ask', ask);
command('llembas.rewrite', rewrite);
command('llembas.complete', () => vscode.commands.executeCommand('editor.action.inlineSuggest.trigger'));
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)),
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))),
),
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.agent) chat.agent.stop();
}),
proposals.removed,
proposals.added,
);
}
function deactivate() {
if (chat) chat.dispose();
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 };
+204
View File
@@ -0,0 +1,204 @@
/* Every colour is one of the editor's theme variables. */
html, body { height: 100%; }
body {
margin: 0;
padding: 0;
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
color: var(--vscode-foreground);
background: var(--vscode-sideBar-background);
font-family: var(--vscode-font-family);
font-size: var(--vscode-font-size);
line-height: 1.45;
}
* { box-sizing: border-box; }
.bar {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;
gap: 6px;
padding: 6px 8px;
border-bottom: 1px solid var(--vscode-panel-border);
}
select, button, textarea { font: inherit; }
select {
width: 100%;
height: 26px;
color: var(--vscode-dropdown-foreground);
background: var(--vscode-dropdown-background);
border: 1px solid var(--vscode-dropdown-border);
border-radius: 2px;
}
button {
height: 26px;
padding: 0 10px;
color: var(--vscode-button-foreground);
background: var(--vscode-button-background);
border: 1px solid var(--vscode-button-border, transparent);
border-radius: 2px;
cursor: pointer;
white-space: nowrap;
}
button:hover { background: var(--vscode-button-hoverBackground); }
button.second {
color: var(--vscode-button-secondaryForeground);
background: var(--vscode-button-secondaryBackground);
}
button.second:hover { background: var(--vscode-button-secondaryHoverBackground); }
button.plain {
width: 22px;
height: 22px;
padding: 0;
color: var(--vscode-foreground);
background: transparent;
border-color: transparent;
}
button.plain:hover { background: var(--vscode-toolbar-hoverBackground); }
button:disabled, select:disabled { opacity: 0.6; cursor: default; }
select:focus, button:focus-visible, textarea:focus, .link:focus-visible {
outline: 1px solid var(--vscode-focusBorder);
outline-offset: -1px;
}
#log {
overflow-y: auto;
overflow-x: hidden;
padding: 8px;
}
.item { margin: 0 0 10px; overflow-wrap: anywhere; }
.who {
margin: 0 0 2px;
font-size: 0.85em;
font-weight: 600;
color: var(--vscode-descriptionForeground);
}
.user .text, .thought .text, .note { white-space: pre-wrap; }
.user .body {
padding: 6px 8px;
background: var(--vscode-input-background);
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
border-radius: 3px;
}
.label { font-size: 0.85em; color: var(--vscode-descriptionForeground); }
.thought .text { color: var(--vscode-descriptionForeground); font-style: italic; }
.note { color: var(--vscode-descriptionForeground); font-size: 0.92em; }
.tool, .plan {
display: grid;
grid-template-columns: 1.4em minmax(0, 1fr);
color: var(--vscode-descriptionForeground);
font-size: 0.92em;
}
.tool.failed .mark { color: var(--vscode-errorForeground); }
.tool .files { grid-column: 2; }
.md p, .md ul, .md ol, .md pre, .md blockquote, .md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 0 0 8px; }
.md > :last-child { margin-bottom: 0; }
.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { font-size: 1em; font-weight: 600; }
.md h1 { font-size: 1.2em; }
.md h2 { font-size: 1.1em; }
.md ul, .md ol { padding-left: 1.5em; }
.md li.depth-1 { margin-left: 1.2em; }
.md li.depth-2 { margin-left: 2.4em; }
.md li.depth-3 { margin-left: 3.6em; }
.md li.depth-4 { margin-left: 4.8em; }
.md li.depth-5 { margin-left: 6em; }
.md blockquote {
padding: 0 0 0 8px;
border-left: 3px solid var(--vscode-textBlockQuote-border);
background: var(--vscode-textBlockQuote-background);
}
.md hr { border: 0; border-top: 1px solid var(--vscode-panel-border); margin: 8px 0; }
code, pre {
font-family: var(--vscode-editor-font-family);
font-size: var(--vscode-editor-font-size);
}
.md code { background: var(--vscode-textCodeBlock-background); padding: 0 3px; border-radius: 2px; }
pre {
margin: 0;
padding: 6px 8px;
overflow-x: auto; /* a wide line scrolls here, never the view */
white-space: pre;
background: var(--vscode-textCodeBlock-background);
border-radius: 3px;
}
.md pre code { background: transparent; padding: 0; }
.link {
color: var(--vscode-textLink-foreground);
text-decoration: underline;
cursor: pointer;
}
.link:hover { color: var(--vscode-textLink-activeForeground); }
.card {
padding: 8px;
border: 1px solid var(--vscode-inputValidation-warningBorder, var(--vscode-panel-border));
background: var(--vscode-inputValidation-warningBackground, var(--vscode-input-background));
border-radius: 3px;
}
.card.closed {
border-color: var(--vscode-panel-border);
background: transparent;
color: var(--vscode-descriptionForeground);
}
.card .title { white-space: pre-wrap; font-family: var(--vscode-editor-font-family); margin: 2px 0 4px; }
.card .reason { font-size: 0.92em; margin: 0 0 6px; }
.card pre { margin: 0 0 6px; max-height: 16em; overflow: auto; }
.card .buttons { display: flex; flex-wrap: wrap; gap: 6px; }
.media img {
display: block;
max-width: 100%;
max-height: 60vh;
height: auto;
border: 1px solid var(--vscode-panel-border);
border-radius: 3px;
cursor: pointer;
}
.media .caption {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 6px;
align-items: center;
min-height: 26px;
margin-top: 4px;
font-size: 0.92em;
color: var(--vscode-descriptionForeground);
}
.media .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
footer { padding: 6px 8px 8px; border-top: 1px solid var(--vscode-panel-border); }
textarea {
display: block;
width: 100%;
height: 5.2em;
resize: none;
padding: 5px 6px;
color: var(--vscode-input-foreground);
background: var(--vscode-input-background);
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
border-radius: 2px;
}
textarea::placeholder { color: var(--vscode-input-placeholderForeground); }
.send {
display: grid;
grid-template-columns: minmax(0, 1fr) auto auto;
gap: 6px;
align-items: center;
height: 26px;
margin-top: 6px;
}
.attached {
grid-column: 1;
display: grid;
grid-template-columns: minmax(0, auto) 22px;
gap: 2px;
align-items: center;
justify-content: start;
height: 26px;
font-size: 0.92em;
color: var(--vscode-descriptionForeground);
}
.attached-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.working { grid-column: 2; font-size: 0.92em; color: var(--vscode-descriptionForeground); }
#send { grid-column: 3; }
[hidden] { display: none !important; }
+317
View File
@@ -0,0 +1,317 @@
// The chat view's one script. It draws what the extension sends: items of a transcript, and
// the Markdown of a model's text as a tree of plain objects (src/markdown.js). Everything is
// built with createElement and textContent; no markup is ever parsed from a string here.
(function () {
'use strict';
var MARKS = { pending: '…', in_progress: '…', completed: '✓', failed: '✗' };
var MAX_DEPTH = 8;
function el(doc, tag, cls, text) {
var e = doc.createElement(tag);
if (cls) e.className = cls;
if (text !== undefined && text !== null) e.textContent = String(text);
return e;
}
function buildInline(doc, nodes, parent, depth) {
if (!Array.isArray(nodes) || depth > MAX_DEPTH) return;
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if (!n || typeof n !== 'object') continue;
if (n.t === 'text') parent.appendChild(doc.createTextNode(String(n.v)));
else if (n.t === 'br') parent.appendChild(doc.createElement('br'));
else if (n.t === 'code') parent.appendChild(el(doc, 'code', '', n.v));
else if (n.t === 'b' || n.t === 'i') {
var e = doc.createElement(n.t === 'b' ? 'strong' : 'em');
buildInline(doc, n.c, e, depth + 1);
parent.appendChild(e);
} else if (n.t === 'a') {
// Not an anchor that navigates: the extension is asked to open the address, and checks it again.
var a = doc.createElement('span');
a.className = 'link';
a.setAttribute('role', 'link');
a.setAttribute('tabindex', '0');
a.setAttribute('title', String(n.href));
a.setAttribute('data-href', String(n.href));
buildInline(doc, n.c, a, depth + 1);
parent.appendChild(a);
}
}
}
function buildBlocks(doc, blocks, parent, depth) {
if (!Array.isArray(blocks) || depth > MAX_DEPTH) return;
for (var i = 0; i < blocks.length; i++) {
var b = blocks[i];
if (!b || typeof b !== 'object') continue;
var e;
if (b.t === 'p') {
e = doc.createElement('p');
buildInline(doc, b.c, e, 0);
} else if (b.t === 'h') {
var level = Math.max(1, Math.min(6, Number(b.l) || 1));
e = doc.createElement('h' + level);
buildInline(doc, b.c, e, 0);
} else if (b.t === 'pre') {
e = doc.createElement('pre');
e.appendChild(el(doc, 'code', '', b.v));
} else if (b.t === 'hr') {
e = doc.createElement('hr');
} else if (b.t === 'quote') {
e = doc.createElement('blockquote');
buildBlocks(doc, b.c, e, depth + 1);
} else if (b.t === 'ul' || b.t === 'ol') {
e = doc.createElement(b.t);
var items = Array.isArray(b.items) ? b.items : [];
for (var j = 0; j < items.length; j++) {
var d = Math.max(0, Math.min(5, Number(items[j] && items[j].d) || 0));
var li = el(doc, 'li', d ? 'depth-' + d : '');
buildInline(doc, items[j] && items[j].c, li, 0);
e.appendChild(li);
}
} else {
continue;
}
parent.appendChild(e);
}
}
function button(doc, text, cls, onClick) {
var b = el(doc, 'button', cls || '', text);
b.setAttribute('type', 'button');
b.addEventListener('click', onClick);
return b;
}
/** One item of the transcript as an element. `post` sends a message to the extension. */
function renderItem(doc, item, post) {
var root = el(doc, 'div', 'item ' + String(item.kind).replace(/[^a-z]/g, ''));
root.setAttribute('data-id', String(item.id));
if (item.kind === 'user') {
root.appendChild(el(doc, 'div', 'who', 'You'));
var body = el(doc, 'div', 'body');
if (item.label) body.appendChild(el(doc, 'div', 'label', '[' + item.label + ']'));
body.appendChild(el(doc, 'div', 'text', item.text));
root.appendChild(body);
} else if (item.kind === 'agent') {
root.appendChild(el(doc, 'div', 'who', 'LLeMbas'));
var md = el(doc, 'div', 'md');
if (Array.isArray(item.ast)) buildBlocks(doc, item.ast, md, 0);
else md.textContent = String(item.text || '');
root.appendChild(md);
} else if (item.kind === 'thought') {
root.appendChild(el(doc, 'div', 'who', 'Thinking'));
root.appendChild(el(doc, 'div', 'text', item.text));
} else if (item.kind === 'note') {
root.textContent = String(item.text);
} else if (item.kind === 'tool') {
if (item.status === 'failed') root.className += ' failed';
root.appendChild(el(doc, 'span', 'mark', MARKS[item.status] || '…'));
root.appendChild(el(doc, 'span', 'title', String(item.title) + (item.denied ? ' (not allowed)' : '')));
var files = Array.isArray(item.files) ? item.files : [];
if (files.length) {
var list = el(doc, 'div', 'files');
files.slice(0, 20).forEach(function (path, i) {
if (i) list.appendChild(doc.createTextNode(', '));
var f = el(doc, 'span', 'link', String(path).split(/[\\/]/).pop());
f.setAttribute('role', 'link');
f.setAttribute('tabindex', '0');
f.setAttribute('title', String(path));
f.setAttribute('data-file', String(path));
list.appendChild(f);
});
root.appendChild(list);
}
} else if (item.kind === 'plan') {
root.appendChild(el(doc, 'span', 'mark', item.done >= item.all ? '✓' : '…'));
root.appendChild(el(doc, 'span', 'title', 'Plan: ' + Number(item.done) + ' of ' + Number(item.all) + ' tasks done'));
} else if (item.kind === 'card') {
var open = item.state === 'open';
if (!open) root.className += ' closed';
root.appendChild(el(doc, 'div', 'who', open ? 'LLeMbas asks' + (item.tool ? ' (' + item.tool + ')' : '') : 'Asked'));
root.appendChild(el(doc, 'div', 'title', item.title));
if (open && item.reason) root.appendChild(el(doc, 'div', 'reason', item.reason));
if (open && item.detail) root.appendChild(el(doc, 'pre', '', item.detail));
if (open) {
var row = el(doc, 'div', 'buttons');
(Array.isArray(item.options) ? item.options : []).forEach(function (o) {
var deny = String(o.kind).indexOf('reject') === 0;
row.appendChild(button(doc, o.name, deny ? 'second' : '', function () {
post({ type: 'answer', card: item.id, option: o.optionId });
}));
});
if (Array.isArray(item.files) && item.files.length) {
row.appendChild(button(doc, 'Show the change', 'second', function () {
post({ type: 'showDiff', card: item.id });
}));
}
root.appendChild(row);
} else {
root.appendChild(el(doc, 'div', 'reason', item.answer));
}
} else if (item.kind === 'media') {
if (item.picture && item.src) {
var img = doc.createElement('img');
img.setAttribute('src', String(item.src));
img.setAttribute('alt', String(item.name));
img.addEventListener('click', function () {
post({ type: 'openMedia', key: item.key });
});
root.appendChild(img);
}
var cap = el(doc, 'div', 'caption');
cap.appendChild(el(doc, 'span', 'name', String(item.name) + (item.sizeWords ? ' (' + item.sizeWords + ')' : '')));
cap.appendChild(button(doc, 'Open', 'second', function () {
post({ type: 'openMedia', key: item.key });
}));
root.appendChild(cap);
}
return root;
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = { buildBlocks: buildBlocks, buildInline: buildInline, renderItem: renderItem };
return;
}
// ---- in the view ----------------------------------------------------------------------
var vscode = acquireVsCodeApi();
var doc = document;
var log = doc.getElementById('log');
var prompt = doc.getElementById('prompt');
var send = doc.getElementById('send');
var mode = doc.getElementById('mode');
var model = doc.getElementById('model');
var attached = doc.getElementById('attached');
var attachedLabel = doc.getElementById('attached-label');
var working = doc.getElementById('working');
var state = { busy: false, modes: [], models: [], mode: null, model: null };
var nodes = {};
function post(msg) {
vscode.postMessage(msg);
}
function atBottom() {
return log.scrollHeight - log.scrollTop - log.clientHeight < 40;
}
function upsert(item) {
var stick = atBottom();
var fresh = renderItem(doc, item, post);
var old = nodes[item.id];
if (old && old.parentNode === log) log.replaceChild(fresh, old);
else log.appendChild(fresh);
nodes[item.id] = fresh;
if (stick) log.scrollTop = log.scrollHeight;
}
function reset(items) {
while (log.firstChild) log.removeChild(log.firstChild);
nodes = {};
(items || []).forEach(upsert);
log.scrollTop = log.scrollHeight;
}
function fill(select, options, current, placeholder) {
while (select.firstChild) select.removeChild(select.firstChild);
var seen = false;
options.forEach(function (o) {
var opt = el(doc, 'option', '', o.name);
opt.value = o.id;
if (o.id === current) {
opt.selected = true;
seen = true;
}
select.appendChild(opt);
});
if (!seen) {
var opt = el(doc, 'option', '', current || placeholder);
opt.value = current || '';
opt.selected = true;
select.insertBefore(opt, select.firstChild);
}
select.disabled = options.length === 0;
}
function showState(s) {
state = s;
fill(mode, s.modes || [], s.mode, 'Mode');
fill(model, s.models || [], s.model, 'Model');
send.textContent = s.busy ? 'Stop' : 'Send';
working.hidden = !s.busy;
mode.disabled = mode.disabled || !!s.busy;
model.disabled = model.disabled || !!s.busy;
}
function submit() {
if (state.busy) return post({ type: 'stop' });
var text = prompt.value;
if (!text.trim()) return;
post({ type: 'send', text: text });
prompt.value = '';
vscode.setState({ draft: '' });
}
send.addEventListener('click', submit);
prompt.addEventListener('keydown', function (ev) {
if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing) {
ev.preventDefault();
if (!state.busy) submit();
}
});
prompt.addEventListener('input', function () {
vscode.setState({ draft: prompt.value });
});
doc.getElementById('new').addEventListener('click', function () {
post({ type: 'new' });
});
doc.getElementById('detach').addEventListener('click', function () {
post({ type: 'detach' });
});
mode.addEventListener('change', function () {
if (mode.value) post({ type: 'setMode', id: mode.value });
});
model.addEventListener('change', function () {
if (model.value) post({ type: 'setModel', id: model.value });
});
function follow(target) {
var t = target;
while (t && t !== log) {
if (t.getAttribute && t.getAttribute('data-href')) return post({ type: 'openLink', href: t.getAttribute('data-href') });
if (t.getAttribute && t.getAttribute('data-file')) return post({ type: 'openFile', path: t.getAttribute('data-file') });
t = t.parentNode;
}
}
log.addEventListener('click', function (ev) {
follow(ev.target);
});
log.addEventListener('keydown', function (ev) {
if (ev.key === 'Enter') follow(ev.target);
});
window.addEventListener('message', function (ev) {
var m = ev.data;
if (!m || typeof m !== 'object') return;
if (m.type === 'reset') {
reset(m.items);
showState(m.state);
showAttached(m.attached);
} else if (m.type === 'item') upsert(m.item);
else if (m.type === 'state') showState(m.state);
else if (m.type === 'attached') showAttached(m.label);
else if (m.type === 'focus') prompt.focus();
});
function showAttached(label) {
attached.hidden = !label;
attachedLabel.textContent = label ? 'With ' + label : '';
}
var saved = vscode.getState();
if (saved && typeof saved.draft === 'string') prompt.value = saved.draft;
post({ type: 'ready' });
})();
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" stroke-linecap="round"><path d="M12 3c4.4 0 8 2.9 8 6.6 0 3.6-3.6 6.5-8 6.5-.9 0-1.8-.1-2.6-.3L5 18.5l1-3.6C4.7 13.7 4 11.8 4 9.6 4 5.9 7.6 3 12 3z"/><path d="M8.5 8h7M8.5 11h4.5"/></svg>

After

Width:  |  Height:  |  Size: 348 B

+135
View File
@@ -0,0 +1,135 @@
{
"name": "llembas",
"displayName": "LLeMbas",
"description": "LLeMbas in your editor: chat with the agent, ask about a selection, have it rewritten as a diff, and autocomplete — a client of the LLeMbas CLI.",
"version": "0.0.0",
"publisher": "llembas",
"license": "MIT",
"repository": { "type": "git", "url": "https://github.com/LLeMbas/LLeMbas-IDE" },
"engines": { "vscode": "^1.85.0" },
"categories": ["Machine Learning", "Other"],
"keywords": ["llembas", "agent", "chat", "autocomplete", "acp"],
"main": "./extension.js",
"extensionKind": ["workspace"],
"activationEvents": ["onStartupFinished", "onView:llembas.chat"],
"capabilities": {
"untrustedWorkspaces": {
"supported": false,
"description": "LLeMbas starts an agent that works in the open folder; it stays off until you trust the folder."
},
"virtualWorkspaces": {
"supported": false,
"description": "The LLeMbas CLI works on files on this computer."
}
},
"contributes": {
"viewsContainers": {
"activitybar": [{ "id": "llembas", "title": "LLeMbas", "icon": "media/icon.svg" }]
},
"views": {
"llembas": [{ "type": "webview", "id": "llembas.chat", "name": "Chat" }]
},
"commands": [
{ "command": "llembas.open", "title": "Open the Chat", "category": "LLeMbas" },
{ "command": "llembas.newSession", "title": "New Session", "category": "LLeMbas" },
{ "command": "llembas.stop", "title": "Stop the Running Turn", "category": "LLeMbas" },
{ "command": "llembas.ask", "title": "Ask About the Selection", "category": "LLeMbas" },
{ "command": "llembas.rewrite", "title": "Rewrite the Selection", "category": "LLeMbas" },
{ "command": "llembas.complete", "title": "Suggest a Completion Here", "category": "LLeMbas" },
{ "command": "llembas.acceptChange", "title": "Accept the Proposed Change at the Cursor", "category": "LLeMbas" },
{ "command": "llembas.rejectChange", "title": "Reject the Proposed Change at the Cursor", "category": "LLeMbas" },
{ "command": "llembas.acceptAllChanges", "title": "Accept All Proposed Changes in This File", "category": "LLeMbas" },
{ "command": "llembas.rejectAllChanges", "title": "Reject All Proposed Changes in This File", "category": "LLeMbas" },
{ "command": "llembas.showChanges", "title": "Show the Proposed Changes as a Diff", "category": "LLeMbas" },
{ "command": "llembas.chooseMode", "title": "Choose the Mode", "category": "LLeMbas" },
{ "command": "llembas.chooseModel", "title": "Choose This Session's Model", "category": "LLeMbas" },
{ "command": "llembas.modelSettings", "title": "Models (Autocomplete and Main)", "category": "LLeMbas" },
{ "command": "llembas.chooseAutocompleteModel", "title": "Choose the Autocomplete Model", "category": "LLeMbas" },
{ "command": "llembas.chooseMainModel", "title": "Choose the Main Model", "category": "LLeMbas" },
{ "command": "llembas.restart", "title": "Stop the Agent (It Starts Again When Needed)", "category": "LLeMbas" }
],
"keybindings": [
{ "command": "llembas.open", "key": "ctrl+alt+l", "mac": "cmd+alt+l" },
{ "command": "llembas.ask", "key": "ctrl+alt+k", "mac": "cmd+alt+k", "when": "editorTextFocus && editorHasSelection" },
{ "command": "llembas.rewrite", "key": "ctrl+alt+e", "mac": "cmd+alt+e", "when": "editorTextFocus && editorHasSelection && !editorReadonly" },
{ "command": "llembas.complete", "key": "alt+\\", "when": "editorTextFocus && !editorReadonly" },
{ "command": "llembas.acceptAllChanges", "key": "ctrl+alt+enter", "mac": "cmd+alt+enter", "when": "editorTextFocus && llembas.hasProposal" },
{ "command": "llembas.rejectAllChanges", "key": "ctrl+alt+backspace", "mac": "cmd+alt+backspace", "when": "editorTextFocus && llembas.hasProposal" }
],
"menus": {
"editor/context": [
{ "command": "llembas.ask", "when": "editorHasSelection", "group": "llembas@1" },
{ "command": "llembas.rewrite", "when": "editorHasSelection && !editorReadonly", "group": "llembas@2" }
],
"view/title": [
{ "command": "llembas.newSession", "when": "view == llembas.chat", "group": "llembas@1" },
{ "command": "llembas.modelSettings", "when": "view == llembas.chat", "group": "llembas@2" },
{ "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@3" }
],
"commandPalette": [
{ "command": "llembas.acceptChange", "when": "llembas.hasProposal" },
{ "command": "llembas.rejectChange", "when": "llembas.hasProposal" },
{ "command": "llembas.acceptAllChanges", "when": "llembas.hasProposal" },
{ "command": "llembas.rejectAllChanges", "when": "llembas.hasProposal" },
{ "command": "llembas.showChanges", "when": "llembas.hasProposal" }
]
},
"configuration": {
"title": "LLeMbas",
"properties": {
"llembas.command": {
"type": "string",
"default": "lembas",
"scope": "machine",
"markdownDescription": "The LLeMbas CLI: `lembas` when it is on your `PATH`, or the full path of the program. It is started as `lembas serve --stdio`. This is the only thing set here: the server, the sign-in, the models and the permissions are the CLI's own."
},
"llembas.chat.sendEditorContext": {
"type": "boolean",
"default": true,
"description": "Tell the agent, with each message you type, which file is in front, where the cursor is, what is selected, and the problems the editor shows there."
},
"llembas.chat.showThinking": {
"type": "boolean",
"default": false,
"description": "Show the model's thinking in the chat."
},
"llembas.chat.startMode": {
"type": "string",
"default": "",
"description": "The mode a new session starts in (for example manual, in which every edit is shown as a diff to accept). Empty: the CLI's own."
},
"llembas.complete.auto": {
"type": "boolean",
"default": true,
"description": "Suggest a completion as you type. Off: only when you ask for one (Alt+\\). It needs an autocomplete model, chosen on the server or with \"LLeMbas: Choose the Autocomplete Model\"."
},
"llembas.complete.debounce": {
"type": "number",
"default": 250,
"minimum": 0,
"maximum": 5000,
"description": "How long you must pause, in milliseconds, before a completion is asked for."
},
"llembas.complete.maxTokens": {
"type": "number",
"default": 0,
"minimum": 0,
"maximum": 512,
"description": "The longest completion to ask for, in tokens. 0: the server's own number."
},
"llembas.rewrite.openDiff": {
"type": "boolean",
"default": true,
"description": "Open the diff view beside the file when a rewrite is proposed. Off: only the marks and the Accept / Reject lines in the file."
},
"llembas.media.maxMegabytes": {
"type": "number",
"default": 64,
"minimum": 1,
"maximum": 64,
"description": "The largest file, in megabytes, the chat takes from the agent to show (a picture) or to open. A larger one is refused, and the agent is told why."
}
}
}
}
}
+149
View File
@@ -0,0 +1,149 @@
'use strict';
// The agent: `lembas serve --stdio` as a child process, spoken to over the Agent Client Protocol
// (version 1). Everything about models, tools, permissions and the sign-in is the agent's own.
// No `vscode` here.
const { EventEmitter } = require('node:events');
const childProcess = require('node:child_process');
const { Rpc, RpcError } = require('./rpc');
const PROTOCOL_VERSION = 1;
class Agent extends EventEmitter {
/**
* @param {{ command: string, args?: string[], cwd?: string, env?: object,
* clientInfo?: { name: string, version: string },
* onRequest?: (method: string, params: any) => any }} options
* Events: `notify (method, params)`, `stderr (text)`, `exit ({ code, last })`.
*/
constructor(options) {
super();
this.options = options;
this.capabilities = new Set();
this.info = null;
this.ready = false;
this.stopped = false;
this.stderr = [];
this.proc = null;
this.rpc = null;
this.starting = null;
}
/** Start the process and say hello. The same promise for every caller. */
connect() {
if (!this.starting) this.starting = this._start();
return this.starting;
}
_start() {
const o = this.options;
return new Promise((resolve, reject) => {
let settled = false;
const fail = (message) => {
this.stopped = true;
if (this.rpc) this.rpc.close(message);
if (!settled) {
settled = true;
reject(new Error(message));
}
};
let proc;
try {
proc = childProcess.spawn(o.command, o.args || ['serve', '--stdio'], {
cwd: o.cwd,
env: o.env || process.env,
stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
windowsHide: true,
});
} catch (e) {
return fail(`could not start ${o.command}: ${e.message}`);
}
this.proc = proc;
this.rpc = new Rpc({
write: (line) => proc.stdin.write(line),
onRequest: (method, params) => {
if (!o.onRequest) throw { code: -32601, message: 'Method not found: ' + method };
return o.onRequest(method, params);
},
onNotify: (method, params) => this.emit('notify', method, params),
});
proc.stdin.on('error', () => {});
proc.stdout.on('data', (d) => this.rpc.feed(d));
proc.stderr.on('data', (d) => {
const text = d.toString('utf8');
for (const line of text.split(/\r?\n/)) if (line.trim()) this.stderr.push(line);
while (this.stderr.length > 40) this.stderr.shift();
this.emit('stderr', text);
});
proc.on('error', (e) => {
const why = e.code === 'ENOENT' ? 'the command was not found' : e.message;
fail(`could not start ${o.command}: ${why}`);
this.emit('exit', { code: null, last: why, started: false });
});
proc.on('exit', (code, signal) => {
const last = this.stderr.length ? this.stderr[this.stderr.length - 1] : '';
const was = this.ready;
this.ready = false;
fail(`the agent stopped (${signal || 'exit ' + code})${last ? ': ' + last : ''}`);
this.emit('exit', { code, signal, last, started: was });
});
this.rpc
.request('initialize', {
protocolVersion: PROTOCOL_VERSION,
clientCapabilities: {
fs: { readTextFile: true, writeTextFile: false },
// `show` with `media`: the spec offers the show tool to a client that says `show`,
// and hands over files that are not text to one that also says `media`.
_meta: { lembas: { editor: true, media: true, show: true } },
},
clientInfo: o.clientInfo || { name: 'llembas-vscode', version: '0' },
})
.then(
(r) => {
if (settled) return;
const lembas = (r && r._meta && r._meta.lembas) || {};
this.capabilities = new Set(Array.isArray(lembas.capabilities) ? lembas.capabilities : []);
this.info = r || {};
this.ready = true;
settled = true;
resolve(this);
},
(e) => {
if (settled) return;
this.stop();
fail('the agent refused to start: ' + e.message);
},
);
});
}
has(capability) {
return this.capabilities.has(capability);
}
request(method, params) {
if (!this.rpc || this.stopped) return Promise.reject(new RpcError({ code: -32000, message: 'the agent is not running' }));
return this.rpc.request(method, params);
}
notify(method, params) {
if (this.rpc && !this.stopped) this.rpc.notify(method, params);
}
stop() {
if (!this.proc || this.stopped) return;
this.stopped = true;
try {
this.proc.stdin.end();
} catch {
// already closed
}
try {
this.proc.kill('SIGTERM');
} catch {
// already gone
}
}
}
module.exports = { Agent, PROTOCOL_VERSION };
+468
View File
@@ -0,0 +1,468 @@
'use strict';
// The chat: one agent process, one session, and the transcript as a list of plain items the
// view draws. Everything the editor itself must do — show a diff, read an open document, take
// in a shown file — is a hook. No `vscode` here.
const { EventEmitter } = require('node:events');
const { promptParams } = require('./context');
const DETAIL_MAX = 20000;
function sentence(text) {
const s = String(text || '').trim();
return s ? s[0].toUpperCase() + s.slice(1) + (/[.!?…]$/.test(s) ? '' : '.') : '';
}
class Chat extends EventEmitter {
/**
* @param {{ makeAgent: (o: { cwd: string, onRequest: Function }) => import('./agent').Agent,
* cwd: () => string,
* options?: () => { mode?: string, model?: string, showThoughts?: boolean },
* hooks?: { readTextFile?: Function, showDiffs?: Function, closeDiffs?: Function,
* showMedia?: Function, showText?: Function, filesChanged?: Function },
* now?: () => number }} io
* Events: `item (item)`, `reset`, `state`, `connected (agent)`, `stopped`, `editDelta (params)`, `stderr (text)`.
*/
constructor(io) {
super();
this.io = io;
this.hooks = io.hooks || {};
this.now = io.now || Date.now;
this.agent = null;
this.failedAt = 0;
this.items = [];
this.nextItem = 1;
this._clearSession();
this.models = [];
this.settings = null;
}
_clearSession() {
this.session = null;
this.sessionStarting = null;
this.busy = false;
this.modes = [];
this.mode = null;
this.model = null;
this.said = null;
this.tools = new Map();
this.cards = new Map();
}
options() {
return (this.io.options && this.io.options()) || {};
}
// ---- the transcript -------------------------------------------------------------------
add(item) {
item.id = 'i' + this.nextItem++;
this.items.push(item);
this.emit('item', item);
return item;
}
changed(item) {
this.emit('item', item);
}
note(text) {
this.said = null;
return this.add({ kind: 'note', text: String(text) });
}
/** What the view needs besides the items. */
state() {
return {
busy: this.busy,
session: !!this.session,
mode: this.mode,
modes: this.modes.map((m) => ({ id: String(m.id), name: String(m.name || m.id) })),
model: this.model,
models: this.models.filter((m) => !Array.isArray(m.for) || m.for.includes('main')).map((m) => ({ id: String(m.id), name: String(m.name || m.id) })),
};
}
// ---- the agent ------------------------------------------------------------------------
/** A running agent that has answered `initialize`, or `null`. `quiet`: a failure is not written into the chat. */
async connect(quiet) {
if (this.agent && !this.agent.stopped) {
try {
return await this.agent.connect();
} catch {
return null;
}
}
// Completion asks at every pause in typing: a command that is not there is not tried each time.
if (quiet && this.failedAt && this.now() - this.failedAt < 60000) return null;
const agent = this.io.makeAgent({ cwd: this.io.cwd(), onRequest: (method, params) => this._onRequest(agent, method, params) });
this.agent = agent;
agent.on('notify', (method, params) => this._onNotify(agent, method, params));
agent.on('stderr', (text) => this.emit('stderr', text));
agent.on('exit', (e) => this._onExit(agent, e));
try {
await agent.connect();
this.failedAt = 0;
this.startError = null;
this.emit('connected', agent);
return agent;
} catch (e) {
if (this.agent === agent) this.agent = null;
this.failedAt = this.now();
this.startError = e.message;
if (!quiet) this.note(sentence(e.message));
return null;
}
}
_onExit(agent, e) {
if (this.agent !== agent) return;
const had = this.session !== null || this.sessionStarting !== null || this.busy;
this.agent = null;
for (const card of [...this.cards.values()]) this._settle(card, 'The agent stopped before this was answered.');
this._clearSession();
if (e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`);
this.emit('stopped');
this.emit('state');
}
/** A request of the editor's own (`_lembas/complete`, `_lembas/edit`, …). Rejects when the agent cannot be had. */
async request(method, params, quiet) {
const agent = await this.connect(quiet);
if (!agent) throw new Error(this.startError || 'the agent is not running');
return agent.request(method, params);
}
notify(method, params) {
if (this.agent && this.agent.ready) this.agent.notify(method, params);
}
has(capability) {
return !!(this.agent && this.agent.ready && this.agent.has(capability));
}
/** An open session, started when there is none. Resolves `false` when that failed (the chat says why). */
ensureSession() {
if (this.session) return Promise.resolve(true);
if (this.sessionStarting) return this.sessionStarting;
const starting = (async () => {
const agent = await this.connect(false);
if (!agent) return false;
const o = this.options();
const meta = {};
if (o.mode) meta.mode = o.mode;
if (o.model) meta.model = o.model;
let r;
try {
r = await agent.request('session/new', { cwd: this.io.cwd(), mcpServers: [], _meta: meta });
} catch (e) {
if (this.agent === agent) this.note('No session: ' + sentence(e.message));
return false;
}
if (this.agent !== agent || !r || typeof r.sessionId !== 'string') return false;
this.session = r.sessionId;
const lembas = (r._meta && r._meta.lembas) || {};
this.modes = (r.modes && Array.isArray(r.modes.availableModes) && r.modes.availableModes) || [];
this.mode = (r.modes && r.modes.currentModeId) || lembas.mode || null;
this.model = lembas.model || null;
this.emit('state');
if (agent.has('editor')) this.loadModels().catch(() => {});
return true;
})();
this.sessionStarting = starting;
const done = () => {
if (this.sessionStarting === starting) this.sessionStarting = null;
};
starting.then(done, done);
return starting;
}
/**
* Send a prompt. `editor` is what the editor shows (`editorContext`), `label` how the
* transcript names an attached selection. Resolves `false` when a turn already runs.
*/
async send(text, with_) {
if (this.busy) return false;
const w = with_ || {};
this.add({ kind: 'user', text, label: w.label || '' });
this.said = 'user';
this.busy = true;
this.emit('state');
try {
if (!(await this.ensureSession())) return true;
const agent = this.agent;
try {
const r = await agent.request('session/prompt', promptParams(this.session, text, w.editor, agent.has('editor')));
const lembas = (r && r._meta && r._meta.lembas) || {};
if (typeof lembas.message === 'string' && lembas.message) this.note(lembas.message);
if (r && r.stopReason && r.stopReason !== 'end_turn') {
this.note(r.stopReason === 'cancelled' ? 'Stopped.' : 'The turn ended: ' + String(r.stopReason).replace(/_/g, ' ') + '.');
}
} catch (e) {
if (this.agent === agent) this.note('The turn failed: ' + sentence(e.message));
}
return true;
} finally {
this.busy = false;
this.said = null;
this.emit('state');
}
}
/** Stop the running turn. Cards still open are answered as cancelled, as ACP asks. */
stop() {
if (!this.agent || !this.session || !this.busy) return;
this.agent.notify('session/cancel', { sessionId: this.session });
for (const card of [...this.cards.values()]) this._settle(card, 'Not answered: the turn was stopped.');
}
/** A new session; the old one stays in the agent's own store. Resolves `false` while a turn runs. */
async newSession() {
if (this.busy) return false;
for (const card of [...this.cards.values()]) this._settle(card, 'Not answered.');
const agent = this.agent;
const models = this.models;
this._clearSession();
this.agent = agent;
this.models = models;
this.items = [];
this.emit('reset');
this.emit('state');
return true;
}
async setMode(id) {
if (!(await this.ensureSession())) return false;
await this.agent.request('session/set_mode', { sessionId: this.session, modeId: id });
this.mode = id;
this.emit('state');
return true;
}
/** The session's model, for this session only. */
async setModel(id) {
if (!(await this.ensureSession())) return false;
const r = await this.agent.request('_lembas/configure', { sessionId: this.session, model: id });
this.model = (r && r.model) || id;
this.emit('state');
return true;
}
/** The models the sign-in offers, and the person's two settings (`_lembas/models`). */
async loadModels(quiet) {
const r = await this.request('_lembas/models', {}, quiet);
this.models = r && Array.isArray(r.models) ? r.models.filter((m) => m && typeof m.id === 'string') : [];
this.settings = { autocomplete: (r && r.autocomplete) || null, main: (r && r.main) || null };
this.emit('state');
return { models: this.models, ...this.settings };
}
/** Read the two saved model settings, or save `set` first (`_lembas/editor/settings`). */
async editorSettings(set) {
const r = await this.request('_lembas/editor/settings', set ? { set } : {});
this.settings = { autocomplete: (r && r.autocomplete) || null, main: (r && r.main) || null };
return this.settings;
}
// ---- what the agent sends -------------------------------------------------------------
_onNotify(agent, method, params) {
if (this.agent !== agent || !params) return;
if (method === 'session/update') {
if (params.sessionId === this.session && params.update) this._onUpdate(params.update);
} else if (method === '_lembas/edit/delta') {
this.emit('editDelta', params);
} else if (method === '_lembas/permission/settled') {
for (const card of [...this.cards.values()]) {
if (card.item.toolCallId === params.toolCallId) this._settle(card, 'Answered elsewhere, or no longer waited for.');
}
} else if (method === '_lembas/event') {
const ev = params.event;
if (params.sessionId !== this.session || !ev) return;
if (ev.type === 'model' && typeof ev.ref === 'string') {
this.model = ev.ref;
this.emit('state');
} else if (ev.type === 'mode' && typeof ev.mode === 'string') {
this.mode = ev.mode;
this.emit('state');
}
}
}
_onUpdate(u) {
const kind = u.sessionUpdate;
if (kind === 'agent_message_chunk' || kind === 'agent_thought_chunk') {
const thought = kind === 'agent_thought_chunk';
if (thought && !this.options().showThoughts) return;
if (!u.content || u.content.type !== 'text' || typeof u.content.text !== 'string') return;
const want = thought ? 'thought' : 'agent';
if (this.said !== want || !this.current) {
this.current = this.add({ kind: want, text: '' });
this.said = want;
}
this.current.text += u.content.text;
this.changed(this.current);
} else if (kind === 'tool_call' || kind === 'tool_call_update') {
const id = String(u.toolCallId);
let item = this.tools.get(id);
const fresh = !item;
if (!item) {
item = { kind: 'tool', toolCallId: id, title: 'tool', status: 'pending', files: [], denied: false };
this.tools.set(id, item);
}
if (typeof u.title === 'string' && u.title) item.title = u.title;
if (typeof u.status === 'string') item.status = u.status;
if (u._meta && u._meta.lembas && u._meta.lembas.denied) item.denied = true;
const files = diffItems(u.content).map((d) => d.path);
if (files.length) item.files = [...new Set(files)];
this.said = 'tool';
if (fresh) this.add(item);
else this.changed(item);
if (item.status === 'completed' && item.files.length && this.hooks.filesChanged) this.hooks.filesChanged(item.files);
} else if (kind === 'plan') {
const entries = Array.isArray(u.entries) ? u.entries : [];
if (!entries.length) return;
const done = entries.filter((e) => e && e.status === 'completed').length;
if (!this.planItem || !this.items.includes(this.planItem)) this.planItem = this.add({ kind: 'plan', done, all: entries.length });
else {
this.planItem.done = done;
this.planItem.all = entries.length;
this.changed(this.planItem);
}
this.said = 'tool';
} else if (kind === 'current_mode_update') {
if (typeof u.currentModeId === 'string') this.mode = u.currentModeId;
this.emit('state');
}
}
_onRequest(agent, method, params) {
if (this.agent !== agent) throw { code: -32000, message: 'this client has moved on' };
if (method === 'session/request_permission') return this._onPermission(params);
if (method === 'fs/read_text_file') {
if (!this.hooks.readTextFile) throw { code: -32601, message: 'Method not found: ' + method };
return this.hooks.readTextFile(params);
}
if (method === '_lembas/show') return this._onShow(agent, params);
throw { code: -32601, message: 'Method not found: ' + method };
}
_onPermission(p) {
const call = (p && p.toolCall) || {};
const lembas = (p && p._meta && p._meta.lembas) || {};
const options = (Array.isArray(p && p.options) ? p.options : [])
.filter((o) => o && typeof o.optionId === 'string')
.map((o) => ({ optionId: o.optionId, name: String(o.name || o.optionId), kind: String(o.kind || '') }));
const diffs = diffItems(call.content);
const text = (Array.isArray(call.content) ? call.content : [])
.map((c) => (c && c.type === 'content' && c.content && c.content.type === 'text' ? c.content.text : c && c.type === 'text' ? c.text : ''))
.filter((t) => typeof t === 'string' && t)
.join('\n');
const item = this.add({
kind: 'card',
toolCallId: String(call.toolCallId || ''),
title: String(call.title || lembas.tool || 'a tool'),
tool: typeof lembas.tool === 'string' ? lembas.tool : '',
reason: typeof lembas.reason === 'string' ? lembas.reason : '',
detail: text.length > DETAIL_MAX ? text.slice(0, DETAIL_MAX) + '\n…' : text,
files: diffs.map((d) => d.path),
options,
state: 'open',
answer: '',
});
this.said = 'tool';
return new Promise((resolve) => {
const card = { item, resolve, diffs };
this.cards.set(item.id, card);
if (diffs.length && this.hooks.showDiffs) {
try {
this.hooks.showDiffs(item.id, diffs, item.title);
} catch {
// the card itself still asks
}
}
});
}
/** The person's answer to a card. */
answer(cardId, optionId) {
const card = this.cards.get(cardId);
if (!card) return false;
const option = card.item.options.find((o) => o.optionId === optionId);
if (!option) return false;
this._close(card, 'answered', option.name);
card.resolve({ outcome: { outcome: 'selected', optionId } });
return true;
}
/** Show a card's diffs again. */
reshow(cardId) {
const card = this.cards.get(cardId);
if (card && card.diffs.length && this.hooks.showDiffs) this.hooks.showDiffs(cardId, card.diffs, card.item.title);
}
_settle(card, why) {
this._close(card, 'settled', why);
card.resolve({ outcome: { outcome: 'cancelled' } });
}
_close(card, state, answer) {
this.cards.delete(card.item.id);
card.item.state = state;
card.item.answer = answer;
this.changed(card.item);
if (card.diffs.length && this.hooks.closeDiffs) {
try {
this.hooks.closeDiffs(card.item.id);
} catch {
// a tab that is already closed
}
}
}
async _onShow(agent, p) {
if (!p || p.sessionId !== this.session) return { shown: false, reason: 'This is not the session the editor shows.' };
if (typeof p.handle === 'string') {
if (!this.hooks.showMedia) return { shown: false, reason: 'This editor cannot show files.' };
const got = await this.hooks.showMedia(p, (q) => agent.request('_lembas/show/read', q));
if (!got || !got.ok) {
const reason = (got && got.reason) || 'The file could not be shown.';
this.note(`${(got && got.name) || 'A file'} was not shown: ${reason}`);
return { shown: false, reason };
}
this.add({ kind: 'media', name: got.name, size: got.size, picture: !!got.picture, src: got.src || '', key: got.key || '' });
this.said = 'tool';
return { shown: true };
}
if (typeof p.text === 'string' && this.hooks.showText) {
const r = await this.hooks.showText(p);
if (r && r.shown) {
this.note(`Shown: ${String(p.path || 'a file')}`);
return { shown: true };
}
return { shown: false, reason: (r && r.reason) || 'The file could not be shown.' };
}
return { shown: false, reason: 'This editor cannot show that.' };
}
dispose() {
if (this.agent) this.agent.stop();
}
}
function diffItems(content) {
const out = [];
for (const c of Array.isArray(content) ? content : []) {
if (c && c.type === 'diff' && typeof c.path === 'string' && typeof c.newText === 'string') {
out.push({
path: c.path,
oldText: typeof c.oldText === 'string' ? c.oldText : null,
newText: c.newText,
deleted: !!(c._meta && c._meta.lembas && c._meta.lembas.deleted),
});
}
}
return out;
}
module.exports = { Chat, diffItems };
+138
View File
@@ -0,0 +1,138 @@
'use strict';
// Autocomplete on `_lembas/complete`: the waiting before a request is sent, the cancelling of
// the one before it, and what happens to an answer nobody waits for any more. No `vscode` here.
const REFUSALS = new Set(['no_model', 'not_allowed', 'not_logged_in', 'unsupported']);
/** The text around the cursor that is sent: a window, not the file. */
function windowAround(text, offset, limits) {
const prefixMax = (limits && limits.prefixMax) || 12000;
const suffixMax = (limits && limits.suffixMax) || 4000;
const at = Math.max(0, Math.min(offset, text.length));
let start = Math.max(0, at - prefixMax);
let end = Math.min(text.length, at + suffixMax);
// Never cut a surrogate pair in two.
if (start > 0 && isLow(text.charCodeAt(start))) start += 1;
if (end < text.length && isLow(text.charCodeAt(end))) end -= 1;
return { prefix: text.slice(start, at), suffix: text.slice(at, end) };
}
function isLow(code) {
return code >= 0xdc00 && code <= 0xdfff;
}
class Completer {
/**
* @param {{ request: (method: string, params: object) => Promise<any>,
* notify: (method: string, params: object) => void,
* debounceMs?: () => number,
* model?: () => string | undefined,
* maxTokens?: () => number | undefined,
* onRefusal?: (reason: string, message: string, manual: boolean) => void,
* onError?: (message: string, manual: boolean) => void,
* setTimeout?: Function, clearTimeout?: Function, now?: () => number }} io
*/
constructor(io) {
this.io = io;
this.seq = 0;
this.pending = null; // { seq, timer, id, sent, finish }
this.blocked = ''; // the refusal that stopped asking as you type
this.pausedUntil = 0;
this.setTimeout = io.setTimeout || setTimeout;
this.clearTimeout = io.clearTimeout || clearTimeout;
this.now = io.now || Date.now;
}
/**
* Ask for the text that belongs at the cursor. Resolves with the text, or with `null` when
* there is nothing to show: a newer request took its place, it was cancelled, the answer was
* empty, or asking is stopped. Never rejects.
* @param {{ prefix: string, suffix?: string, path?: string, language?: string }} what
* @param {{ manual?: boolean }} [how]
*/
ask(what, how) {
const manual = !!(how && how.manual);
this.cancel(); // the one before this, waiting or sent
if (!manual && (this.blocked || this.now() < this.pausedUntil)) return Promise.resolve(null);
const seq = ++this.seq;
return new Promise((resolve) => {
const entry = { seq, id: 'c' + seq, sent: false, timer: null, finish: null };
entry.finish = (value) => {
if (entry.timer !== null) this.clearTimeout(entry.timer);
entry.timer = null;
if (this.pending === entry) this.pending = null;
entry.finish = () => {};
resolve(value);
};
this.pending = entry;
const wait = manual ? 0 : Math.max(0, Number(this.io.debounceMs ? this.io.debounceMs() : 250) || 0);
const go = () => {
entry.timer = null;
this._send(entry, what, manual);
};
if (wait === 0) go();
else entry.timer = this.setTimeout(go, wait);
});
}
_send(entry, what, manual) {
entry.sent = true;
const params = { id: entry.id, prefix: what.prefix, suffix: what.suffix || '' };
if (what.path) params.path = what.path;
if (what.language) params.language = what.language;
const model = this.io.model ? this.io.model() : undefined;
if (model) params.model = model;
const maxTokens = this.io.maxTokens ? this.io.maxTokens() : undefined;
if (maxTokens) params.max_tokens = maxTokens;
let asked;
try {
asked = Promise.resolve(this.io.request('_lembas/complete', params));
} catch (e) {
asked = Promise.reject(e);
}
asked.then(
(r) => {
// An answer to a request that is no longer the newest is thrown away, whatever it says.
if (this.pending !== entry) return;
if (manual && this.blocked) this.blocked = '';
if (!r || r.cancelled || typeof r.text !== 'string' || r.text === '') return entry.finish(null);
entry.finish(r.text);
},
(e) => {
const reason = e && e.data && typeof e.data.reason === 'string' ? e.data.reason : '';
const message = (e && e.message) || 'the completion failed';
if (REFUSALS.has(reason)) {
// Said once; as-you-type then stays quiet until a model is set (or it is asked by hand).
const first = this.blocked !== reason;
this.blocked = reason;
if ((first || manual) && this.io.onRefusal) this.io.onRefusal(reason, message, manual);
} else {
this.pausedUntil = this.now() + 15000;
if (this.io.onError) this.io.onError(message, manual);
}
if (this.pending === entry) entry.finish(null);
},
);
}
/** Stop what is waited for: the editor moved on. `seq` limits it to that request. */
cancel(seq) {
const entry = this.pending;
if (!entry || (seq !== undefined && entry.seq !== seq)) return;
if (entry.sent) this.io.notify('_lembas/complete/cancel', { id: entry.id });
entry.finish(null);
}
/** The number of the request now waited for, for `cancel(seq)`. */
get current() {
return this.pending ? this.pending.seq : 0;
}
/** A model was chosen, or the agent started again: ask as you type again. */
unblock() {
this.blocked = '';
this.pausedUntil = 0;
}
}
module.exports = { Completer, windowAround, REFUSALS };
+106
View File
@@ -0,0 +1,106 @@
'use strict';
// What the editor knows and the agent is told with a prompt (`_meta.lembas.editor`), and the
// answer to the agent's question for a file's text. No `vscode` here.
const LIMITS = { diagnostics: 20, diagnosticChars: 300, open: 30, selectionChars: 20000 };
const SEVERITIES = ['error', 'warning', 'info', 'hint'];
function oneLine(text, max) {
const flat = String(text).replace(/\s+/g, ' ').trim();
return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
}
/**
* The `editor` object of a prompt, from plain data. Lines are 1-based, a selection's range
* inclusive. Returns `undefined` when there is nothing to say.
* @param {{ path?: string, cursorLine?: number,
* selection?: { path?: string, start: number, end: number, text?: string },
* diagnostics?: { path?: string, line?: number, severity?: string, message: string, source?: string }[],
* open?: string[] }} seen
*/
function editorContext(seen) {
if (!seen) return undefined;
const out = {};
if (seen.path) out.path = seen.path;
if (Number.isInteger(seen.cursorLine) && seen.cursorLine > 0) out.cursor = { line: seen.cursorLine };
if (seen.selection && Number.isInteger(seen.selection.start) && Number.isInteger(seen.selection.end)) {
const s = seen.selection;
out.selection = { start: Math.max(1, s.start), end: Math.max(s.start, s.end) };
if (s.path && s.path !== seen.path) out.selection.path = s.path;
if (typeof s.text === 'string') out.selection.text = s.text;
}
const diagnostics = [];
for (const d of seen.diagnostics || []) {
if (!d || typeof d.message !== 'string' || !d.message.trim()) continue;
if (diagnostics.length >= LIMITS.diagnostics) break;
const item = { message: oneLine(d.message, LIMITS.diagnosticChars) };
if (d.path) item.path = d.path;
if (Number.isInteger(d.line) && d.line > 0) item.line = d.line;
if (SEVERITIES.includes(d.severity)) item.severity = d.severity;
if (d.source) item.source = oneLine(d.source, 60);
diagnostics.push(item);
}
if (diagnostics.length) out.diagnostics = diagnostics;
const open = [];
for (const p of seen.open || []) {
if (typeof p !== 'string' || !p || p === seen.path || open.includes(p)) continue;
if (open.length >= LIMITS.open) break;
open.push(p);
}
if (open.length) out.open = open;
return Object.keys(out).length ? out : undefined;
}
/** How a selection is named in the transcript: `file.py:3-9`. */
function selectionLabel(name, start, end) {
return `${name || 'untitled'}:${start}${end !== start ? '-' + end : ''}`;
}
/**
* The params of `session/prompt` for a typed text and what the editor shows. An agent that
* lists the capability `editor` gets the context as `_meta.lembas.editor`; an older one gets a
* sentence and the selected text in front of the prompt, as the prompt's own blocks.
*/
function promptParams(sessionId, text, editor, agentReadsEditor) {
const params = { sessionId, prompt: [] };
if (editor && agentReadsEditor) {
params._meta = { lembas: { editor } };
} else if (editor) {
const sel = editor.selection;
const where = (sel && sel.path) || editor.path || 'an unsaved file';
if (sel) {
params.prompt.push({ type: 'text', text: `Selected in the editor: ${where}, lines ${sel.start}-${sel.end}.` });
if (typeof sel.text === 'string') {
params.prompt.push({
type: 'resource',
resource: { uri: `untitled:selection#L${sel.start}-${sel.end}`, mimeType: 'text/plain', text: sel.text },
});
}
} else if (editor.path) {
const at = editor.cursor ? `, cursor on line ${editor.cursor.line}` : '';
params.prompt.push({ type: 'text', text: `Open in the editor: ${editor.path}${at}.` });
}
if (editor.diagnostics && editor.diagnostics.length) {
const lines = editor.diagnostics.map(
(d) => `- ${d.line ? 'line ' + d.line + ', ' : ''}${d.severity || 'info'}${d.source ? ' (' + d.source + ')' : ''}: ${d.message}`,
);
params.prompt.push({ type: 'text', text: 'Diagnostics the editor shows there:\n' + lines.join('\n') });
}
}
params.prompt.push({ type: 'text', text });
return params;
}
/**
* The part of a text ACP's `fs/read_text_file` asks for: from `line` (1-based), at most `limit`
* lines. Without either, the whole text.
*/
function sliceLines(text, line, limit) {
const from = Number.isFinite(Number(line)) && Number(line) > 1 ? Math.floor(Number(line)) : 1;
const count = Number.isFinite(Number(limit)) && Number(limit) >= 0 && limit !== null && limit !== undefined ? Math.floor(Number(limit)) : null;
if (from === 1 && count === null) return text;
const lines = String(text).split('\n');
return lines.slice(from - 1, count === null ? undefined : from - 1 + count).join('\n');
}
module.exports = { editorContext, promptParams, selectionLabel, sliceLines, LIMITS };
+188
View File
@@ -0,0 +1,188 @@
'use strict';
// A rewrite shown before it is made: the proposed lines against the lines now, as hunks that are
// accepted or rejected one by one. Lines are 0-based here. No `vscode` here.
const MAX_EDIT_DISTANCE = 4000;
function splitLines(text) {
return String(text).replace(/\r\n/g, '\n').split('\n');
}
/**
* The differences between two lists of lines (Myers' algorithm), as
* `{ aStart, aCount, bStart, bCount }` in order. Lists too different to compare in reasonable
* time come back as one hunk that replaces everything between their common ends.
*/
function diffLines(a, b) {
let head = 0;
while (head < a.length && head < b.length && a[head] === b[head]) head++;
let tail = 0;
while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++;
const n = a.length - head - tail;
const m = b.length - head - tail;
if (n === 0 && m === 0) return [];
if (n === 0 || m === 0) return [{ aStart: head, aCount: n, bStart: head, bCount: m }];
const max = Math.min(n + m, MAX_EDIT_DISTANCE);
const offset = max + 1;
let v = new Int32Array(2 * max + 3);
const trace = [];
let found = -1;
for (let d = 0; d <= max && found < 0; d++) {
trace.push(v.slice());
for (let k = -d; k <= d; k += 2) {
let x;
if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])) x = v[offset + k + 1];
else x = v[offset + k - 1] + 1;
let y = x - k;
while (x < n && y < m && a[head + x] === b[head + y]) {
x++;
y++;
}
v[offset + k] = x;
if (x >= n && y >= m) {
found = d;
break;
}
}
}
if (found < 0) return [{ aStart: head, aCount: n, bStart: head, bCount: m }];
// Walk back from the end, collecting the single steps.
const steps = []; // { x, y, del } : a line of a deleted at x, or a line of b inserted at y
let x = n;
let y = m;
for (let d = found; d > 0; d--) {
const prev = trace[d];
const k = x - y;
let prevK;
if (k === -d || (k !== d && prev[offset + k - 1] < prev[offset + k + 1])) prevK = k + 1;
else prevK = k - 1;
const prevX = prev[offset + prevK];
const prevY = prevX - prevK;
while (x > prevX && y > prevY) {
x--;
y--;
}
if (x === prevX) steps.push({ x: prevX, y: prevY, del: false });
else steps.push({ x: prevX, y: prevY, del: true });
x = prevX;
y = prevY;
}
steps.reverse();
const hunks = [];
let cur = null;
for (const s of steps) {
const ax = head + s.x;
const by = head + s.y;
if (cur && cur.aStart + cur.aCount === ax && cur.bStart + cur.bCount === by) {
if (s.del) cur.aCount++;
else cur.bCount++;
} else {
cur = { aStart: ax, aCount: s.del ? 1 : 0, bStart: by, bCount: s.del ? 0 : 1 };
hunks.push(cur);
}
}
return hunks;
}
/**
* A rewrite of the document's lines `first .. first + oldLines.length - 1` as pending hunks.
* Each hunk: `{ id, line, old: string[], new: string[] }` — `line` is where its old lines start
* in the document now, or, when it only adds lines, the line they go in front of.
*/
function propose(first, oldLines, newLines) {
return diffLines(oldLines, newLines).map((h, i) => ({
id: i + 1,
line: first + h.aStart,
old: oldLines.slice(h.aStart, h.aStart + h.aCount),
new: newLines.slice(h.bStart, h.bStart + h.bCount),
}));
}
/** Whether the document still says, at the hunk, what the hunk was made against. */
function stillFits(hunk, lineAt, lineCount) {
if (hunk.line < 0 || hunk.line + hunk.old.length > lineCount) return false;
if (hunk.old.length === 0) return hunk.line <= lineCount;
for (let i = 0; i < hunk.old.length; i++) if (lineAt(hunk.line + i) !== hunk.old[i]) return false;
return true;
}
/**
* The one text edit that accepts a hunk in a document of `lineCount` lines:
* `{ start: { line, end }, stop: { line, end }, text }` — a position is the start of its line,
* or the line's end when `end` is true. Line breaks in `text` are "\n"; the caller puts the
* document's own in.
*/
function editFor(hunk, lineCount) {
const text = hunk.new.join('\n');
if (hunk.old.length === 0) {
if (hunk.line >= lineCount) {
// After the last line.
const last = Math.max(0, lineCount - 1);
return { start: { line: last, end: true }, stop: { line: last, end: true }, text: '\n' + text };
}
return { start: { line: hunk.line, end: false }, stop: { line: hunk.line, end: false }, text: text + '\n' };
}
const lastOld = hunk.line + hunk.old.length - 1;
if (hunk.new.length > 0) {
return { start: { line: hunk.line, end: false }, stop: { line: lastOld, end: true }, text };
}
// Lines taken away, with their line break.
if (lastOld + 1 < lineCount) {
return { start: { line: hunk.line, end: false }, stop: { line: lastOld + 1, end: false }, text: '' };
}
if (hunk.line > 0) {
return { start: { line: hunk.line - 1, end: true }, stop: { line: lastOld, end: true }, text: '' };
}
return { start: { line: 0, end: false }, stop: { line: lastOld, end: true }, text: '' };
}
/** The hunks left after one was accepted: those below it move by what it added or took away. */
function afterAccept(hunks, accepted) {
const delta = accepted.new.length - accepted.old.length;
return hunks
.filter((h) => h !== accepted)
.map((h) => (h.line > accepted.line || (h.line === accepted.line && h.id > accepted.id) ? { ...h, line: h.line + delta } : h));
}
/**
* The hunks left after the document changed by somebody else's hand: lines `startLine ..
* endLine` (inclusive) were replaced by `newLineCount` lines. A hunk above the change stays, one
* below it moves, and one the change reaches into is dropped — its text is no longer what was
* shown.
*/
function afterChange(hunks, change) {
const delta = change.newLineCount - (change.endLine - change.startLine + 1);
const out = [];
for (const h of hunks) {
if (h.old.length === 0) {
// Lines to add in front of `line`: a change at or below that line leaves the place alone.
if (change.startLine >= h.line) out.push(h);
else if (change.endLine < h.line) out.push({ ...h, line: h.line + delta });
continue;
}
const last = h.line + h.old.length - 1;
if (last < change.startLine) out.push(h);
else if (h.line > change.endLine) out.push({ ...h, line: h.line + delta });
}
return out;
}
/** The whole text as it would be with every pending hunk accepted (for the diff view). */
function withAll(lines, hunks) {
const out = lines.slice();
const ordered = hunks.slice().sort((p, q) => q.line - p.line || q.id - p.id);
for (const h of ordered) out.splice(h.line, h.old.length, ...h.new);
return out;
}
/** The lines a selection covers: whole lines, and not the line a selection merely ends in front of. */
function wholeLines(sel) {
let last = sel.endLine;
if (last > sel.startLine && sel.endCharacter === 0) last -= 1;
return { first: sel.startLine, last };
}
module.exports = { splitLines, diffLines, propose, stillFits, editFor, afterAccept, afterChange, withAll, wholeLines };
+273
View File
@@ -0,0 +1,273 @@
'use strict';
// A small Markdown reader for what a model writes. It makes a tree of plain objects and never
// a string of markup: the chat view builds elements from the tree with `createElement` and
// `textContent`, so nothing a model writes is ever parsed as HTML. Raw HTML in the text stays
// text. No `vscode` here.
//
// Blocks: { t: 'p', c } { t: 'h', l, c } { t: 'pre', lang, v } { t: 'hr' }
// { t: 'quote', c: blocks } { t: 'ul' | 'ol', items: [{ d, c }] }
// Inline: { t: 'text', v } { t: 'code', v } { t: 'b', c } { t: 'i', c }
// { t: 'a', href, c } { t: 'br' }
const MAX_DEPTH = 6;
/** A link the chat may offer to open: http, https or mailto, and nothing else. */
function safeHref(url) {
if (typeof url !== 'string' || url.length > 2000) return null;
// eslint-disable-next-line no-control-regex
if (/[\u0000- \u007f"<>`\\]/.test(url)) return null;
if (/^https?:\/\/[^/?#]+/i.test(url) || /^mailto:[^@\s]+@[^@\s]+$/i.test(url)) return url;
return null;
}
function pushText(out, v) {
if (!v) return;
const last = out[out.length - 1];
if (last && last.t === 'text') last.v += v;
else out.push({ t: 'text', v });
}
function isWord(ch) {
return ch !== undefined && /[\p{L}\p{N}]/u.test(ch);
}
function findClosing(s, from, marker) {
for (let i = from; i < s.length; i++) {
if (s[i] === '\\') {
i++;
continue;
}
if (s[i] === '`') {
// Skip a code span whole.
let n = 1;
while (s[i + n] === '`') n++;
const close = s.indexOf('`'.repeat(n), i + n);
if (close < 0) return -1;
i = close + n - 1;
continue;
}
if (s.startsWith(marker, i)) {
if (i === from) continue; // empty
if (/\s/.test(s[i - 1])) continue;
if (marker[0] === '_' && isWord(s[i + marker.length])) continue;
if (marker.length === 1 && s[i + 1] === marker) {
// A double marker inside single emphasis belongs to something else.
i++;
continue;
}
return i;
}
}
return -1;
}
function parseInline(s, depth) {
const out = [];
const deep = (depth || 0) >= MAX_DEPTH;
let i = 0;
while (i < s.length) {
const ch = s[i];
if (ch === '\n') {
out.push({ t: 'br' });
i++;
continue;
}
if (ch === '\\' && i + 1 < s.length && /[!-/:-@[-`{-~]/.test(s[i + 1])) {
pushText(out, s[i + 1]);
i += 2;
continue;
}
if (ch === '`') {
let n = 1;
while (s[i + n] === '`') n++;
const close = s.indexOf('`'.repeat(n), i + n);
if (close >= 0) {
let v = s.slice(i + n, close).replace(/\n/g, ' ');
if (v.length > 2 && v.startsWith(' ') && v.endsWith(' ')) v = v.slice(1, -1);
out.push({ t: 'code', v });
i = close + n;
continue;
}
pushText(out, '`'.repeat(n));
i += n;
continue;
}
if (!deep && (ch === '*' || ch === '_')) {
const double = s[i + 1] === ch;
const marker = double ? ch + ch : ch;
const next = s[i + marker.length];
const opens = next !== undefined && !/\s/.test(next) && !(ch === '_' && isWord(s[i - 1]));
if (opens) {
const close = findClosing(s, i + marker.length, marker);
if (close > 0) {
out.push({ t: double ? 'b' : 'i', c: parseInline(s.slice(i + marker.length, close), (depth || 0) + 1) });
i = close + marker.length;
continue;
}
}
pushText(out, marker);
i += marker.length;
continue;
}
if (!deep && (ch === '[' || (ch === '!' && s[i + 1] === '['))) {
const open = ch === '!' ? i + 1 : i;
let level = 0;
let close = -1;
for (let j = open; j < s.length; j++) {
if (s[j] === '\\') j++;
else if (s[j] === '[') level++;
else if (s[j] === ']' && --level === 0) {
close = j;
break;
}
}
if (close > 0 && s[close + 1] === '(') {
let end = -1;
let parens = 0;
for (let j = close + 1; j < s.length; j++) {
if (s[j] === '(') parens++;
else if (s[j] === ')' && --parens === 0) {
end = j;
break;
} else if (s[j] === '\n') break;
}
if (end > 0) {
const inside = s.slice(close + 2, end).trim();
const url = inside.split(/\s+/)[0].replace(/^<|>$/g, '');
const href = safeHref(url);
const label = s.slice(open + 1, close);
if (href) {
// A picture is never loaded: it is a link like any other.
const c = ch === '!' ? [{ t: 'text', v: label || href }] : parseInline(label, (depth || 0) + 1);
out.push({ t: 'a', href, c: c.length ? c : [{ t: 'text', v: href }] });
i = end + 1;
continue;
}
// Not a link the chat opens: shown as it was written.
pushText(out, s.slice(i, end + 1));
i = end + 1;
continue;
}
}
pushText(out, ch);
i++;
continue;
}
if (ch === 'h' && !isWord(s[i - 1])) {
const m = /^https?:\/\/[^\s<>()[\]"'`\\]+/i.exec(s.slice(i, i + 2000));
if (m) {
const raw = m[0].replace(/[.,;:!?*_]+$/, '');
const href = safeHref(raw);
if (href) {
out.push({ t: 'a', href, c: [{ t: 'text', v: raw }] });
i += raw.length;
continue;
}
}
}
pushText(out, ch);
i++;
}
return out;
}
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/;
const HEADING = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/;
const RULE = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/;
const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
const QUOTE = /^ {0,3}>\s?(.*)$/;
/** Markdown text to a list of blocks. */
function parse(src, depth) {
const level = depth || 0;
const lines = String(src === undefined || src === null ? '' : src).replace(/\r\n?/g, '\n').split('\n');
const blocks = [];
let para = [];
const flush = () => {
if (para.length) blocks.push({ t: 'p', c: parseInline(para.join('\n'), 0) });
para = [];
};
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
const fence = FENCE.exec(line);
if (fence) {
flush();
const mark = fence[1];
const body = [];
let j = i + 1;
for (; j < lines.length; j++) {
const t = lines[j].trim();
if (t.startsWith(mark[0].repeat(mark.length)) && /^(`+|~+)$/.test(t)) break;
body.push(lines[j]);
}
blocks.push({ t: 'pre', lang: fence[2].replace(/[^A-Za-z0-9_+#.-]/g, '').slice(0, 30), v: body.join('\n') });
i = j; // an unclosed fence runs to the end: the text is still being written
continue;
}
if (line.trim() === '') {
flush();
continue;
}
const heading = HEADING.exec(line);
if (heading) {
flush();
blocks.push({ t: 'h', l: heading[1].length, c: parseInline(heading[2], 0) });
continue;
}
if (RULE.test(line)) {
flush();
blocks.push({ t: 'hr' });
continue;
}
if (QUOTE.test(line) && level < MAX_DEPTH) {
flush();
const body = [];
let j = i;
for (; j < lines.length; j++) {
const q = QUOTE.exec(lines[j]);
if (!q) break;
body.push(q[1]);
}
blocks.push({ t: 'quote', c: parse(body.join('\n'), level + 1) });
i = j - 1;
continue;
}
if (/^\s*\|/.test(line)) {
// A table is kept as written, in the fixed-width face, so its columns still line up.
flush();
const body = [];
let j = i;
for (; j < lines.length && /^\s*\|/.test(lines[j]); j++) body.push(lines[j].trim());
blocks.push({ t: 'pre', lang: '', v: body.join('\n') });
i = j - 1;
continue;
}
const item = ITEM.exec(line);
if (item) {
flush();
const ordered = /\d/.test(item[2]);
const base = item[1].length;
const items = [];
let j = i;
for (; j < lines.length; j++) {
const m = ITEM.exec(lines[j]);
if (m) {
const d = Math.max(0, Math.min(MAX_DEPTH - 1, Math.floor((m[1].replace(/\t/g, ' ').length - base) / 2)));
items.push({ d, text: [m[3]] });
} else if (lines[j].trim() !== '' && /^\s+/.test(lines[j]) && items.length && !FENCE.test(lines[j])) {
items[items.length - 1].text.push(lines[j].trim());
} else {
break;
}
}
blocks.push({ t: ordered ? 'ol' : 'ul', items: items.map((it) => ({ d: it.d, c: parseInline(it.text.join('\n'), 0) })) });
i = j - 1;
continue;
}
para.push(line);
}
flush();
return blocks;
}
module.exports = { parse, parseInline, safeHref };
+135
View File
@@ -0,0 +1,135 @@
'use strict';
// Files the agent shows (`_lembas/show`): what a file is, read from its bytes, and the fetching
// of those bytes through `_lembas/show/read`. No `vscode` here.
const crypto = require('node:crypto');
const PART = 1024 * 1024; // the most one answer carries
/** What the bytes are, when they are a picture the chat can draw; otherwise `null`. */
function sniffPicture(buf) {
if (!buf || buf.length < 12) return null;
if (buf[0] === 0x89 && buf.toString('latin1', 1, 4) === 'PNG' && buf[4] === 0x0d && buf[5] === 0x0a) return { mime: 'image/png', ext: 'png' };
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return { mime: 'image/jpeg', ext: 'jpg' };
const head = buf.toString('latin1', 0, 12);
if (head.startsWith('GIF87a') || head.startsWith('GIF89a')) return { mime: 'image/gif', ext: 'gif' };
if (head.startsWith('RIFF') && head.slice(8, 12) === 'WEBP') return { mime: 'image/webp', ext: 'webp' };
if (head.slice(4, 8) === 'ftyp' && (head.slice(8, 12) === 'avif' || head.slice(8, 12) === 'avis')) return { mime: 'image/avif', ext: 'avif' };
return null;
}
/** A size in words: "640 bytes", "48 KB", "1.4 MB" (1 MB is 1024 KB). */
function sizeInWords(bytes) {
const n = Number(bytes) || 0;
if (n < 1024) return `${n} byte${n === 1 ? '' : 's'}`;
if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
const mb = n / (1024 * 1024);
if (mb < 1024) return `${Number.isInteger(mb) || mb >= 10 ? Math.round(mb) : mb.toFixed(1)} MB`;
return `${(mb / 1024).toFixed(1)} GB`;
}
/** A file name made only of harmless characters, from whatever path the agent gave. */
function safeName(path, fallbackExt) {
const base = String(path || '').split(/[\\/]/).pop() || '';
let name = base.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '').slice(-80);
if (!name) name = 'file';
if (fallbackExt && !/\.[A-Za-z0-9]{1,8}$/.test(name)) name += '.' + fallbackExt;
return name;
}
const RUNNABLE = new Set([
'exe', 'bat', 'cmd', 'com', 'scr', 'msi', 'msp', 'pif', 'lnk', 'ps1', 'vbs', 'vbe', 'js', 'jse', 'wsf', 'wsh', 'hta', 'cpl', 'reg',
'sh', 'bash', 'zsh', 'fish', 'command', 'desktop', 'appimage', 'run', 'bin', 'app', 'jar', 'py', 'pl', 'rb', 'php', 'scpt', 'workflow',
'action', 'url', 'html', 'htm', 'xhtml', 'svg', 'dmg', 'pkg', 'deb', 'rpm',
]);
/** Whether the system might run a file of this name instead of showing it. */
function mayRun(name) {
const m = /\.([A-Za-z0-9]+)$/.exec(String(name));
return !m || RUNNABLE.has(m[1].toLowerCase());
}
/**
* Read a shown file to its end through `_lembas/show/read`.
* @param {(params: object) => Promise<{ data: string, offset?: number, eof?: boolean }>} read
* @param {{ handle: string, size?: number, hash?: string }} file
* @param {{ maxBytes: number, length?: number }} limits
* @returns {Promise<Buffer>} rejects with an Error whose message is a sentence for the person
*/
async function fetchShown(read, file, limits) {
const max = limits.maxBytes;
if (typeof file.size === 'number' && file.size > max) throw tooLarge(file.size, max);
const parts = [];
let offset = 0;
for (let turn = 0; turn < 100000; turn++) {
const r = await read({ handle: file.handle, offset, length: limits.length || PART });
if (!r || typeof r.data !== 'string') throw new Error('The agent sent no data for the file.');
const bytes = Buffer.from(r.data, 'base64');
if (bytes.length > 0) {
parts.push(bytes);
offset += bytes.length;
}
if (offset > max) throw tooLarge(offset, max);
if (r.eof) break;
if (bytes.length === 0) throw new Error('The agent stopped sending the file before its end.');
}
const all = Buffer.concat(parts);
if (typeof file.size === 'number' && all.length !== file.size) {
throw new Error(`The file arrived as ${sizeInWords(all.length)}, not the ${sizeInWords(file.size)} the agent named.`);
}
if (typeof file.hash === 'string' && file.hash.startsWith('sha256:')) {
const got = crypto.createHash('sha256').update(all).digest('hex');
if (got !== file.hash.slice(7).toLowerCase()) throw new Error('The file did not arrive whole (its checksum differs).');
}
return all;
}
function tooLarge(size, max) {
return new Error(`The file is ${sizeInWords(size)}; this editor takes files of up to ${sizeInWords(max)}.`);
}
/**
* Take in a file the agent shows: find out what it is from its first bytes, and put it where
* the editor can show or open it. A picture is always fetched into `dir`; anything else is
* fetched only when the agent named no file on this machine (`uri`).
* @param {object} p the params of `_lembas/show` (with a `handle`)
* @param {(params: object) => Promise<object>} read `_lembas/show/read`
* @param {{ dir: string, maxBytes: number, length?: number, fs?: object }} where
* @returns {Promise<{ ok: boolean, reason?: string, name: string, size: number, picture: boolean,
* mime?: string, file?: string, original?: string }>}
*/
async function receiveShown(p, read, where) {
const fs = where.fs || require('node:fs/promises');
const path = require('node:path');
const size = typeof p.size === 'number' ? p.size : undefined;
const base = { ok: false, name: safeName(p.path), size: size || 0, picture: false };
if (typeof p.handle !== 'string' || !p.handle) return { ...base, reason: 'The agent named no file to fetch.' };
if (size !== undefined && size > where.maxBytes) return { ...base, reason: tooLarge(size, where.maxBytes).message };
let original;
if (typeof p.uri === 'string' && p.uri.startsWith('file:')) {
try {
original = require('node:url').fileURLToPath(p.uri);
} catch {
original = undefined;
}
}
try {
const head = await read({ handle: p.handle, offset: 0, length: 4096 });
const first = Buffer.from(head && typeof head.data === 'string' ? head.data : '', 'base64');
const picture = sniffPicture(first);
if (!picture && original) return { ...base, ok: true, original, size: size === undefined ? 0 : size };
const bytes = head && head.eof && (size === undefined || first.length === size) && !p.hash
? first
: await fetchShown(read, { handle: p.handle, size, hash: p.hash }, { maxBytes: where.maxBytes, length: where.length });
receiveShown.count = (receiveShown.count || 0) + 1;
let name = safeName(p.path, picture ? picture.ext : 'bin');
// A picture is served by its name's ending, so the ending is what the bytes are.
if (picture && !name.toLowerCase().endsWith('.' + picture.ext)) name = name.replace(/\.[A-Za-z0-9]{1,8}$/, '') + '.' + picture.ext;
const file = path.join(where.dir, `${receiveShown.count}-${name}`);
await fs.writeFile(file, bytes, { mode: 0o600, flag: 'wx' });
return { ok: true, name, size: bytes.length, picture: !!picture, mime: picture ? picture.mime : undefined, file, original };
} catch (e) {
return { ...base, reason: (e && e.message) || 'The file could not be fetched.' };
}
}
module.exports = { sniffPicture, sizeInWords, safeName, mayRun, fetchShown, receiveShown, PART };
+133
View File
@@ -0,0 +1,133 @@
'use strict';
// JSON-RPC 2.0 over lines: the framing the Agent Client Protocol uses on stdio. No `vscode` here.
const { StringDecoder } = require('node:string_decoder');
class RpcError extends Error {
constructor(error) {
super(error && typeof error.message === 'string' ? error.message : 'the request failed');
this.name = 'RpcError';
this.code = error && typeof error.code === 'number' ? error.code : -32603;
this.data = error ? error.data : undefined;
}
/** The `data.reason` word of a refusal, or ''. */
get reason() {
return this.data && typeof this.data.reason === 'string' ? this.data.reason : '';
}
}
class Rpc {
/**
* @param {{ write: (line: string) => void,
* onRequest?: (method: string, params: any) => any,
* onNotify?: (method: string, params: any) => void }} io
* `onRequest` returns the result (or a promise of it); to refuse it throws an object with
* `code` and `message`.
*/
constructor(io) {
this.io = io;
this.nextId = 1;
this.waiting = new Map();
this.buffer = '';
this.decoder = new StringDecoder('utf8');
this.closed = false;
}
/** Bytes (or text) from the other side. */
feed(chunk) {
this.buffer += typeof chunk === 'string' ? chunk : this.decoder.write(chunk);
for (;;) {
const nl = this.buffer.indexOf('\n');
if (nl < 0) break;
const line = this.buffer.slice(0, nl);
this.buffer = this.buffer.slice(nl + 1);
if (line.trim() === '') continue;
let msg;
try {
msg = JSON.parse(line);
} catch {
continue; // not ours: a stray line on stdout
}
if (msg && typeof msg === 'object' && !Array.isArray(msg)) this._message(msg);
}
}
_message(msg) {
if (typeof msg.method === 'string') {
const params = msg.params === undefined || msg.params === null ? {} : msg.params;
if (msg.id !== undefined && msg.id !== null) {
this._serve(msg.id, msg.method, params);
} else if (this.io.onNotify) {
try {
this.io.onNotify(msg.method, params);
} catch {
// a notification has nobody to tell
}
}
return;
}
if (msg.id === undefined || msg.id === null) return;
const entry = this.waiting.get(msg.id);
if (!entry) return;
this.waiting.delete(msg.id);
if (msg.error) entry.reject(new RpcError(msg.error));
else entry.resolve(msg.result === undefined ? null : msg.result);
}
_serve(id, method, params) {
let answered = false;
const reply = (result, error) => {
if (answered) return;
answered = true;
if (error) {
const out = { code: typeof error.code === 'number' ? error.code : -32603, message: String(error.message || error) };
if (error.data !== undefined) out.data = error.data;
this._write({ jsonrpc: '2.0', id, error: out });
} else {
this._write({ jsonrpc: '2.0', id, result: result === undefined ? null : result });
}
};
if (!this.io.onRequest) return reply(null, { code: -32601, message: 'Method not found: ' + method });
let out;
try {
out = this.io.onRequest(method, params);
} catch (e) {
return reply(null, e || { message: 'failed' });
}
Promise.resolve(out).then((r) => reply(r), (e) => reply(null, e || { message: 'failed' }));
}
_write(msg) {
if (this.closed) return;
try {
this.io.write(JSON.stringify(msg) + '\n');
} catch {
// the process is gone; its exit says so
}
}
/** A request; resolves with the result, rejects with an RpcError. */
request(method, params) {
if (this.closed) return Promise.reject(new RpcError({ code: -32000, message: 'the agent is not running' }));
const id = this.nextId++;
return new Promise((resolve, reject) => {
this.waiting.set(id, { resolve, reject });
this._write({ jsonrpc: '2.0', id, method, params: params === undefined ? {} : params });
});
}
notify(method, params) {
this._write({ jsonrpc: '2.0', method, params: params === undefined ? {} : params });
}
/** The other side is gone: everything still waited for fails. */
close(message) {
if (this.closed) return;
this.closed = true;
const waiting = [...this.waiting.values()];
this.waiting.clear();
for (const w of waiting) w.reject(new RpcError({ code: -32000, message: message || 'the agent stopped' }));
}
}
module.exports = { Rpc, RpcError };
+53
View File
@@ -0,0 +1,53 @@
'use strict';
// The chat view's page: a fixed skeleton with a strict Content-Security-Policy. Nothing a model
// or a server writes is ever part of this text; it reaches the page as messages and is drawn
// with `textContent`. No `vscode` here.
/**
* @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string }} o
*/
function chatHtml(o) {
for (const v of [o.cspSource, o.nonce, o.scriptUri, o.styleUri]) {
if (typeof v !== 'string' || /["<>\s]/.test(v)) throw new Error('unsafe value for the chat page');
}
const csp = [
"default-src 'none'",
`img-src ${o.cspSource}`,
`style-src ${o.cspSource}`,
`script-src 'nonce-${o.nonce}'`,
"base-uri 'none'",
"form-action 'none'",
].join('; ');
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="${csp}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="${o.styleUri}">
<title>LLeMbas</title>
</head>
<body>
<header class="bar">
<select id="mode" title="Mode" aria-label="Mode"></select>
<select id="model" title="This session's model" aria-label="Model"></select>
<button id="new" type="button" title="Start a new session">New</button>
</header>
<main id="log" aria-live="polite"></main>
<footer>
<textarea id="prompt" rows="3" placeholder="Ask LLeMbas (Enter sends, Shift+Enter starts a new line)" aria-label="Message"></textarea>
<div class="send">
<div id="attached" class="attached" hidden>
<span id="attached-label" class="attached-label"></span>
<button id="detach" type="button" class="plain" title="Do not send the selection" aria-label="Do not send the selection">×</button>
</div>
<span id="working" class="working" hidden>Working…</span>
<button id="send" type="button">Send</button>
</div>
</footer>
<script nonce="${o.nonce}" src="${o.scriptUri}"></script>
</body>
</html>`;
}
module.exports = { chatHtml };
+63
View File
@@ -0,0 +1,63 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { Agent } = require('../src/agent');
const { tempDir, fakeAgent, until } = require('./helpers');
test('the hello says what this client is: an editor that shows media and has unsaved text', async (t) => {
const agent = fakeAgent(t, tempDir(t));
await agent.connect();
const hello = agent.log().find((m) => m.method === 'initialize');
assert.equal(hello.params.protocolVersion, 1);
assert.deepEqual(hello.params.clientCapabilities._meta.lembas, { editor: true, media: true, show: true });
assert.deepEqual(hello.params.clientCapabilities.fs, { readTextFile: true, writeTextFile: false });
assert.ok(agent.ready && agent.has('editor') && agent.has('media') && !agent.has('fs'));
});
test('every caller of connect gets the same start', async (t) => {
const agent = fakeAgent(t, tempDir(t));
const [a, b] = await Promise.all([agent.connect(), agent.connect()]);
assert.equal(a, b);
assert.equal(agent.log().filter((m) => m.method === 'initialize').length, 1);
});
test('an agent from before the editor methods has no capabilities', async (t) => {
const agent = fakeAgent(t, tempDir(t), { FAKE_AGENT_PLAIN: '1' });
await agent.connect();
assert.ok(!agent.has('editor'));
await assert.rejects(agent.request('_lembas/models', {}), (e) => e.code === -32601);
});
test('a command that does not exist is said in words, once', async (t) => {
const agent = new Agent({ command: 'lembas-that-is-not-installed', cwd: tempDir(t) });
const exits = [];
agent.on('exit', (e) => exits.push(e));
await assert.rejects(agent.connect(), /could not start lembas-that-is-not-installed: the command was not found/);
await assert.rejects(agent.request('x', {}), /not running/);
assert.equal(exits.length, 1);
assert.equal(exits[0].started, false);
});
test('an agent that exits fails what was asked and says its last words', async (t) => {
const agent = fakeAgent(t, tempDir(t));
await agent.connect();
const exits = [];
agent.on('exit', (e) => exits.push(e));
const r = await agent.request('session/new', { cwd: '/', mcpServers: [] });
const turn = agent.request('session/prompt', { sessionId: r.sessionId, prompt: [{ type: 'text', text: 'CRASH' }] });
await assert.rejects(turn, /the agent stopped \(exit 3\): not signed in: run lembas login/);
await until(() => exits.length === 1);
assert.equal(exits[0].code, 3);
assert.equal(exits[0].started, true);
assert.match(exits[0].last, /not signed in/);
});
test('stop ends the process', async (t) => {
const agent = fakeAgent(t, tempDir(t));
await agent.connect();
let gone = false;
agent.on('exit', () => (gone = true));
agent.stop();
await until(() => gone);
await assert.rejects(agent.request('x', {}), /not running/);
});
+378
View File
@@ -0,0 +1,378 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { receiveShown } = require('../src/media');
const { editorContext } = require('../src/context');
const { fakeChat, tempDir, until, text } = require('./helpers');
const lastPrompt = (agent) => agent.log().filter((m) => m.method === 'session/prompt').pop();
test('a typed prompt is answered: what was typed, then the reply, in order', async (t) => {
const { chat, agents } = fakeChat(t);
const states = [];
chat.on('state', () => states.push(chat.state().busy));
assert.equal(await chat.send('hello'), true);
assert.equal(text(chat), 'You: hello\nLLeMbas: Hello there.\nSecond line');
assert.equal(chat.busy, false);
assert.ok(states.includes(true), 'the view heard that a turn runs');
assert.deepEqual(chat.state().modes, [{ id: 'ask', name: 'Ask' }, { id: 'edit', name: 'Edit' }]);
assert.equal(chat.state().mode, 'ask');
assert.equal(chat.state().model, 'example/model-a');
const sent = lastPrompt(agents[0]);
assert.deepEqual(sent.params.prompt, [{ type: 'text', text: 'hello' }]);
assert.equal(sent.params._meta, undefined);
});
test('thinking is hidden unless asked for', async (t) => {
const a = fakeChat(t);
await a.chat.send('hello');
assert.ok(!text(a.chat).includes('hidden thought'));
const b = fakeChat(t, { options: { showThoughts: true } });
await b.chat.send('hello');
assert.equal(text(b.chat), 'You: hello\nThinking: hidden thought\nLLeMbas: Hello there.\nSecond line');
});
test('a second prompt while one runs is refused, and Stop ends the turn', async (t) => {
const { chat, agents } = fakeChat(t);
const turn = chat.send('SLOW please');
await until(() => chat.items.some((i) => i.kind === 'agent'));
assert.equal(await chat.send('another'), false);
chat.stop();
await turn;
assert.match(text(chat), /> Stopped\.$/);
assert.ok(agents[0].log().some((m) => m.method === 'session/cancel' && m.params.sessionId === 'ses_test'));
assert.equal(agents[0].log().filter((m) => m.method === 'session/prompt').length, 1);
});
test('the editor context goes in _meta.lembas.editor, not into the prompt', async (t) => {
const { chat, agents } = fakeChat(t);
const editor = editorContext({
path: '/home/user/project/src/oven.py',
cursorLine: 12,
selection: { start: 10, end: 14, text: 'def bake():\n pass' },
diagnostics: [{ line: 12, severity: 'error', message: "name 'crumbs' is not defined", source: 'pyflakes' }],
open: ['/home/user/project/src/oven.py', '/home/user/project/src/flour.py'],
});
await chat.send('META what is this', { editor, label: 'src/oven.py:10-14' });
const sent = lastPrompt(agents[0]);
assert.deepEqual(sent.params.prompt, [{ type: 'text', text: 'META what is this' }]);
assert.deepEqual(sent.params._meta.lembas.editor, {
path: '/home/user/project/src/oven.py',
cursor: { line: 12 },
selection: { start: 10, end: 14, text: 'def bake():\n pass' },
diagnostics: [{ message: "name 'crumbs' is not defined", line: 12, severity: 'error', source: 'pyflakes' }],
open: ['/home/user/project/src/flour.py'],
});
assert.match(text(chat), /^You: \[src\/oven\.py:10-14\] META what is this/);
assert.match(text(chat), /editor=\{"cursor": \{"line": 12\}/);
});
test('an agent that does not read the editor context gets it as blocks in front of the prompt', async (t) => {
const { chat, agents } = fakeChat(t, { env: { FAKE_AGENT_PLAIN: '1' } });
const editor = editorContext({ path: '/p/a.py', selection: { start: 3, end: 4, text: 'x = 1\ny = 2' }, diagnostics: [{ line: 3, severity: 'warning', message: 'unused' }] });
await chat.send('why', { editor });
const sent = lastPrompt(agents[0]);
assert.equal(sent.params._meta, undefined);
assert.deepEqual(sent.params.prompt.map((b) => b.type), ['text', 'resource', 'text', 'text']);
assert.equal(sent.params.prompt[0].text, 'Selected in the editor: /p/a.py, lines 3-4.');
assert.equal(sent.params.prompt[1].resource.text, 'x = 1\ny = 2');
assert.match(sent.params.prompt[2].text, /- line 3, warning: unused/);
assert.equal(sent.params.prompt[3].text, 'why');
});
test('an approval card waits for the answer, and the answer reaches the agent', async (t) => {
const { chat } = fakeChat(t);
const turn = chat.send('PERM');
await until(() => chat.cards.size === 1);
const card = chat.items.find((i) => i.kind === 'card');
assert.equal(card.title, 'rm -r build');
assert.equal(card.tool, 'bash');
assert.equal(card.reason, 'deletes files');
assert.deepEqual(card.options.map((o) => o.optionId), ['once', 'deny']);
assert.equal(card.state, 'open');
assert.equal(chat.answer(card.id, 'no-such-option'), false);
assert.equal(chat.answer(card.id, 'deny'), true);
assert.equal(chat.answer(card.id, 'once'), false, 'a card is answered once');
await turn;
assert.equal(card.state, 'answered');
assert.equal(card.answer, 'Deny');
assert.match(text(chat), /answer=deny/);
});
test('a card with a diff is shown as a diff before the answer, and nothing is written until then', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'waybread.py');
fs.writeFileSync(file, 'old text\n');
const calls = [];
const { chat } = fakeChat(t, {
dir,
hooks: {
showDiffs: (cardId, diffs) => calls.push(['show', cardId, diffs, fs.readFileSync(file, 'utf8')]),
closeDiffs: (cardId) => calls.push(['close', cardId]),
filesChanged: (files) => calls.push(['changed', files]),
},
});
const turn = chat.send(`DIFFPERM ${file}`);
await until(() => chat.cards.size === 1);
const card = chat.items.find((i) => i.kind === 'card');
assert.equal(calls.length, 1);
assert.equal(calls[0][0], 'show');
assert.equal(calls[0][1], card.id);
assert.deepEqual(calls[0][2], [{ path: file, oldText: 'old text\n', newText: 'rewritten by the agent\n', deleted: false }]);
assert.equal(calls[0][3], 'old text\n', 'the file is as it was while the card is open');
assert.deepEqual(card.files, [file]);
chat.answer(card.id, 'once');
await turn;
assert.equal(fs.readFileSync(file, 'utf8'), 'rewritten by the agent\n');
assert.deepEqual(calls[1], ['close', card.id]);
assert.deepEqual(calls[2], ['changed', [file]]);
const tool = chat.items.find((i) => i.kind === 'tool');
assert.equal(tool.status, 'completed');
assert.deepEqual(tool.files, [file]);
});
test('a rejected diff leaves the file alone', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'a.txt');
fs.writeFileSync(file, 'keep me\n');
const { chat } = fakeChat(t, { dir });
const turn = chat.send(`DIFFPERM ${file}`);
await until(() => chat.cards.size === 1);
chat.answer(chat.items.find((i) => i.kind === 'card').id, 'deny');
await turn;
assert.equal(fs.readFileSync(file, 'utf8'), 'keep me\n');
assert.ok(!chat.items.some((i) => i.kind === 'tool'));
});
test('a card the agent withdraws is taken down', async (t) => {
const { chat } = fakeChat(t);
await chat.send('SETTLE');
const card = chat.items.find((i) => i.kind === 'card');
assert.equal(card.state, 'settled');
assert.equal(chat.cards.size, 0);
assert.match(text(chat), /answer=cancelled/);
});
test('Stop answers an open card as cancelled', async (t) => {
const { chat } = fakeChat(t);
const turn = chat.send('PERM');
await until(() => chat.cards.size === 1);
chat.stop();
await turn;
assert.equal(chat.items.find((i) => i.kind === 'card').state, 'settled');
assert.match(text(chat), /answer=cancelled/);
});
test('a tool call is one line that changes as the call goes on', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'b.txt');
const { chat } = fakeChat(t, { dir });
await chat.send(`WRITE ${file}`);
const tools = chat.items.filter((i) => i.kind === 'tool');
assert.equal(tools.length, 1);
assert.equal(tools[0].title, 'edit b.txt');
assert.equal(tools[0].status, 'completed');
});
test("the agent's question for a file's text is the hook's to answer", async (t) => {
const asked = [];
const { chat } = fakeChat(t, {
hooks: {
readTextFile: (p) => {
asked.push(p);
if (p.path.endsWith('open.py')) return { content: 'unsaved text' };
throw { code: -32002, message: 'not open in the editor' };
},
},
});
await chat.send('READ /p/open.py');
assert.match(text(chat), /read="unsaved text"/);
assert.deepEqual(asked[0], { sessionId: 'ses_test', path: '/p/open.py' });
await chat.send('READ /p/closed.py');
assert.match(text(chat), /read=null/, 'an error: the agent reads the disk itself');
});
test('the models, the session model and the mode', async (t) => {
const { chat, agents } = fakeChat(t);
await chat.ensureSession();
await until(() => chat.models.length === 3);
assert.deepEqual(chat.state().models.map((m) => m.id), ['example/model-a', 'example/model-b', 'example/model-c']);
assert.equal(await chat.setModel('example/model-b'), true);
assert.equal(chat.model, 'example/model-b');
const conf = agents[0].log().find((m) => m.method === '_lembas/configure');
assert.deepEqual(conf.params, { sessionId: 'ses_test', model: 'example/model-b' });
await chat.setMode('edit');
assert.equal(chat.mode, 'edit');
assert.deepEqual(agents[0].log().find((m) => m.method === 'session/set_mode').params, { sessionId: 'ses_test', modeId: 'edit' });
});
test('the two saved model settings are read and saved through the agent', async (t) => {
const { chat, agents } = fakeChat(t, { env: { FAKE_AGENT_AUTOCOMPLETE: 'none' } });
const data = await chat.loadModels();
assert.equal(data.autocomplete.model, null);
assert.deepEqual(data.autocomplete.allowed, ['example/model-a', 'example/model-b']);
assert.equal(data.main.model, null);
const saved = await chat.editorSettings({ autocomplete_model: 'example/model-b' });
assert.equal(saved.autocomplete.model, 'example/model-b');
assert.equal(saved.autocomplete.source, 'person');
assert.deepEqual(agents[0].log().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: 'example/model-b' } });
assert.equal((await chat.editorSettings({ main_model: 'example/model-c' })).main.model, 'example/model-c');
assert.equal((await chat.editorSettings()).autocomplete.model, 'example/model-b');
assert.equal(chat.session, null, 'settings need no session');
});
test("the window's own model and mode start a session", async (t) => {
const { chat, agents } = fakeChat(t, { options: { model: 'example/model-c', mode: 'manual' } });
await chat.ensureSession();
assert.deepEqual(agents[0].log().find((m) => m.method === 'session/new').params._meta, { mode: 'manual', model: 'example/model-c' });
assert.equal(chat.model, 'example/model-c');
});
test('an agent that dies is said in the chat, and the next message starts a new one', async (t) => {
const { chat, agents } = fakeChat(t);
await chat.send('CRASH');
assert.match(text(chat), /> The agent stopped \(exit 3\): not signed in: run lembas login$/);
assert.equal(chat.session, null);
assert.equal(chat.busy, false);
await chat.send('hello again');
assert.equal(agents.length, 2);
assert.match(text(chat), /You: hello again\nLLeMbas: Hello there\.\nSecond line$/);
});
test('a command that is not there is said once in the chat, and not tried at every keystroke', async (t) => {
const { Agent } = require('../src/agent');
const { Chat } = require('../src/chat');
let made = 0;
let now = 1000;
const chat = new Chat({
makeAgent: (o) => {
made++;
return new Agent({ command: 'lembas-that-is-not-installed', cwd: o.cwd, onRequest: o.onRequest });
},
cwd: () => tempDir(t),
now: () => now,
});
assert.equal(await chat.connect(true), null);
assert.equal(chat.items.length, 0, 'quietly');
assert.equal(await chat.connect(true), null);
assert.equal(made, 1, 'not started again within the minute');
now += 61000;
assert.equal(await chat.connect(true), null);
assert.equal(made, 2);
await chat.send('hello');
assert.equal(made, 3, 'a message always tries');
assert.match(text(chat), /> Could not start lembas-that-is-not-installed: the command was not found\.$/);
assert.equal(chat.busy, false);
});
test('a new session clears the transcript and keeps the agent', async (t) => {
const { chat, agents } = fakeChat(t);
await chat.send('hello');
let resets = 0;
chat.on('reset', () => resets++);
assert.equal(await chat.newSession(), true);
assert.equal(resets, 1);
assert.equal(chat.items.length, 0);
assert.equal(chat.session, null);
await chat.send('again');
assert.equal(agents.length, 1);
assert.equal(agents[0].log().filter((m) => m.method === 'session/new').length, 2);
});
// ---- files the agent shows ---------------------------------------------------------------
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), crypto.randomBytes(5000)]);
function mediaChat(t, maxBytes) {
const dir = tempDir(t);
const store = path.join(dir, 'store');
fs.mkdirSync(store);
const got = [];
const made = fakeChat(t, {
dir,
hooks: {
showMedia: async (p, read) => {
const r = await receiveShown(p, read, { dir: store, maxBytes: maxBytes || 1024 * 1024 });
got.push(r);
return r.ok ? { ...r, key: 'm' + got.length } : r;
},
},
});
return { ...made, got, store };
}
test('a picture the agent shows is fetched in parts, checked, and kept for the chat', async (t) => {
const { chat, agents, dir, got } = mediaChat(t);
const file = path.join(dir, 'chart.html'); // the name lies; the bytes are a picture
fs.writeFileSync(file, PNG);
await chat.send(`SHOW ${file}`);
assert.match(text(chat), /shown=\{"shown": true\}/);
const item = chat.items.find((i) => i.kind === 'media');
assert.equal(item.picture, true);
assert.equal(item.name, 'chart.png', 'named by what the bytes are');
assert.equal(item.size, PNG.length);
assert.ok(fs.readFileSync(got[0].file).equals(PNG));
assert.equal(got[0].mime, 'image/png');
const reads = agents[0].log().filter((m) => m.method === '_lembas/show/read');
assert.ok(reads.length >= 6, 'the stand-in gives a thousand bytes a time');
assert.ok(reads.every((m) => m.params.handle === reads[0].params.handle));
});
test('a file that is not a picture is a line with Open; one on this machine is not fetched', async (t) => {
const { chat, agents, dir, got } = mediaChat(t);
const file = path.join(dir, 'report.pdf');
fs.writeFileSync(file, Buffer.concat([Buffer.from('%PDF-1.7\n'), crypto.randomBytes(3000)]));
await chat.send(`SHOW ${file} WITHURI`);
const item = chat.items.find((i) => i.kind === 'media');
assert.equal(item.picture, false);
assert.equal(item.name, 'report.pdf');
assert.equal(got[0].original, file);
assert.equal(got[0].file, undefined);
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/show/read').length, 1, 'only its first bytes were read');
});
test('without a file on this machine, the bytes are fetched and written to the store', async (t) => {
const { chat, dir, got, store } = mediaChat(t);
const file = path.join(dir, 'notes.bin');
const bytes = crypto.randomBytes(2500);
fs.writeFileSync(file, bytes);
await chat.send(`SHOW ${file}`);
assert.equal(got[0].picture, false);
assert.ok(got[0].file.startsWith(store + path.sep));
assert.ok(fs.readFileSync(got[0].file).equals(bytes));
});
test('a file over the limit is refused in words, to the person and to the agent', async (t) => {
const { chat, agents, dir } = mediaChat(t, 2048);
const file = path.join(dir, 'big.png');
fs.writeFileSync(file, PNG);
await chat.send(`SHOW ${file}`);
assert.match(text(chat), /> big\.png was not shown: The file is 5 KB; this editor takes files of up to 2 KB\./);
assert.match(text(chat), /shown=\{"reason": "The file is 5 KB; this editor takes files of up to 2 KB\.", "shown": false\}/);
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/show/read').length, 0);
assert.ok(!chat.items.some((i) => i.kind === 'media'));
});
test('a file whose checksum differs is not shown', async (t) => {
const { chat, dir, store } = mediaChat(t);
const file = path.join(dir, 'pic.png');
fs.writeFileSync(file, PNG);
await chat.send(`SHOW ${file} BADHASH`);
assert.match(text(chat), /was not shown: The file did not arrive whole/);
assert.deepEqual(fs.readdirSync(store), []);
});
test('a text file the agent shows goes to the hook that opens it', async (t) => {
const dir = tempDir(t);
const file = path.join(dir, 'page.html');
fs.writeFileSync(file, '<script>alert(1)</script>');
const opened = [];
const { chat } = fakeChat(t, { dir, hooks: { showText: async (p) => (opened.push(p), { shown: true }) } });
await chat.send(`SHOWTEXT ${file}`);
assert.equal(opened[0].path, 'page.html');
assert.equal(opened[0].text, '<script>alert(1)</script>');
assert.match(text(chat), /> Shown: page\.html/);
});
+273
View File
@@ -0,0 +1,273 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { Completer, windowAround } = require('../src/completion');
const { fakeChat, until } = require('./helpers');
/** A Completer on a hand-wound clock and a hand-answered agent. */
function rig(options) {
const timers = [];
const sent = [];
const notes = [];
const refusals = [];
const errors = [];
let now = 0;
const completer = new Completer({
request: (method, params) => new Promise((resolve, reject) => sent.push({ method, params, resolve, reject })),
notify: (method, params) => notes.push({ method, params }),
debounceMs: () => 250,
model: () => (options && options.model) || undefined,
onRefusal: (reason, message, manual) => refusals.push({ reason, message, manual }),
onError: (message, manual) => errors.push({ message, manual }),
setTimeout: (fn, ms) => {
const timer = { fn, at: now + ms, dead: false };
timers.push(timer);
return timer;
},
clearTimeout: (timer) => {
timer.dead = true;
},
now: () => now,
});
const tick = (ms) => {
now += ms;
for (const timer of timers.splice(0)) {
if (timer.dead) continue;
if (timer.at <= now) timer.fn();
else timers.push(timer);
}
};
const settle = () => new Promise((r) => setImmediate(r));
return { completer, sent, notes, refusals, errors, tick, settle };
}
const refusal = (reason, message) => Object.assign(new Error(message), { code: -32602, data: { reason } });
test('nothing is sent until the pause is over', async () => {
const { completer, sent, tick } = rig();
const p = completer.ask({ prefix: 'def bake(', suffix: '):', path: '/p/oven.py', language: 'python' });
tick(249);
assert.equal(sent.length, 0);
tick(1);
assert.equal(sent.length, 1);
assert.deepEqual(sent[0], { method: '_lembas/complete', params: { id: 'c1', prefix: 'def bake(', suffix: '):', path: '/p/oven.py', language: 'python' }, resolve: sent[0].resolve, reject: sent[0].reject });
sent[0].resolve({ text: 'flour', model: 'm', finish: 'stop' });
assert.equal(await p, 'flour');
});
test('typing on before the pause is over: the earlier request is never sent', async () => {
const { completer, sent, notes, tick } = rig();
const first = completer.ask({ prefix: 'a' });
tick(100);
const second = completer.ask({ prefix: 'ab' });
assert.equal(await first, null);
tick(250);
assert.equal(sent.length, 1);
assert.equal(sent[0].params.prefix, 'ab');
assert.equal(notes.length, 0, 'nothing was under way, so nothing is cancelled');
sent[0].resolve({ text: 'c' });
assert.equal(await second, 'c');
});
test('a request under way is cancelled by its own id when the next keystroke comes', async () => {
const { completer, sent, notes, tick, settle } = rig();
const first = completer.ask({ prefix: 'a' });
tick(250);
const second = completer.ask({ prefix: 'ab' });
assert.deepEqual(notes, [{ method: '_lembas/complete/cancel', params: { id: 'c1' } }]);
assert.equal(await first, null, 'answered at once, without waiting for the agent');
// The agent's late answer to the first, whatever it says, is thrown away.
sent[0].resolve({ text: 'STALE', model: 'm', finish: 'stop' });
await settle();
tick(250);
assert.equal(sent[1].params.id, 'c2');
sent[1].resolve({ text: 'fresh' });
assert.equal(await second, 'fresh');
});
test('a late error of a request that was replaced does not stop the newer one', async () => {
const { completer, sent, errors, tick, settle } = rig();
completer.ask({ prefix: 'a' });
tick(250);
const second = completer.ask({ prefix: 'ab' }, { manual: true });
sent[0].reject(new Error('socket closed'));
await settle();
assert.equal(errors.length, 1);
sent[1].resolve({ text: 'ok' });
assert.equal(await second, 'ok');
});
test('a result that says cancelled, or carries no text, shows nothing', async () => {
const { completer, sent, tick } = rig();
let p = completer.ask({ prefix: 'a' });
tick(250);
sent[0].resolve({ text: '', cancelled: true });
assert.equal(await p, null);
p = completer.ask({ prefix: 'a' });
tick(250);
sent[1].resolve({ text: '', model: 'm', finish: 'stop' });
assert.equal(await p, null);
p = completer.ask({ prefix: 'a' });
tick(250);
sent[2].resolve(null);
assert.equal(await p, null);
});
test('the editor moving on cancels only the request it meant', async () => {
const { completer, sent, notes, tick } = rig();
const first = completer.ask({ prefix: 'a' });
const seq = completer.current;
tick(250);
completer.cancel(seq + 5);
assert.equal(notes.length, 0);
completer.cancel(seq);
assert.equal(await first, null);
assert.deepEqual(notes.map((n) => n.params.id), ['c1']);
assert.equal(completer.current, 0);
completer.cancel(seq); // again: nothing happens
assert.equal(notes.length, 1);
assert.equal(sent.length, 1);
});
test('asked by hand, it is sent at once', async () => {
const { completer, sent } = rig();
const p = completer.ask({ prefix: 'a' }, { manual: true });
assert.equal(sent.length, 1);
sent[0].resolve({ text: 'b' });
assert.equal(await p, 'b');
});
test('the quick switch of this window is the request\'s model', () => {
const { completer, sent } = rig({ model: 'example/model-b' });
completer.ask({ prefix: 'a' }, { manual: true });
assert.equal(sent[0].params.model, 'example/model-b');
});
test('no autocomplete model: said once, then quiet until one is set', async () => {
const { completer, sent, refusals, tick } = rig();
let p = completer.ask({ prefix: 'a' });
tick(250);
sent[0].reject(refusal('no_model', 'No autocomplete model is chosen. Choose one in your settings.'));
assert.equal(await p, null);
assert.deepEqual(refusals, [{ reason: 'no_model', message: 'No autocomplete model is chosen. Choose one in your settings.', manual: false }]);
for (let i = 0; i < 5; i++) {
p = completer.ask({ prefix: 'more' + i });
tick(250);
assert.equal(await p, null);
}
assert.equal(sent.length, 1, 'no further request while typing');
assert.equal(refusals.length, 1, 'and it is not said again');
completer.unblock(); // a model was chosen
p = completer.ask({ prefix: 'a' });
tick(250);
assert.equal(sent.length, 2);
sent[1].resolve({ text: 'x' });
assert.equal(await p, 'x');
});
test('asked by hand while it is quiet: the server is asked again, and its answer counts', async () => {
const { completer, sent, refusals, tick } = rig();
let p = completer.ask({ prefix: 'a' });
tick(250);
sent[0].reject(refusal('no_model', 'No autocomplete model is chosen.'));
await p;
p = completer.ask({ prefix: 'a' }, { manual: true });
sent[1].reject(refusal('no_model', 'No autocomplete model is chosen.'));
await p;
assert.equal(refusals.length, 2, 'asked on purpose, so it is said again');
assert.equal(refusals[1].manual, true);
// Meanwhile a model was chosen elsewhere: the next request by hand works, and typing asks again.
p = completer.ask({ prefix: 'a' }, { manual: true });
sent[2].resolve({ text: 'yes' });
assert.equal(await p, 'yes');
p = completer.ask({ prefix: 'ab' });
tick(250);
assert.equal(sent.length, 4);
});
test('another failure is not a refusal: typing pauses a while and then asks again', async () => {
const { completer, sent, refusals, errors, tick } = rig();
let p = completer.ask({ prefix: 'a' });
tick(250);
sent[0].reject(Object.assign(new Error('The server did not answer.'), { code: -32603 }));
assert.equal(await p, null);
assert.equal(refusals.length, 0);
assert.deepEqual(errors, [{ message: 'The server did not answer.', manual: false }]);
p = completer.ask({ prefix: 'ab' });
tick(250);
assert.equal(await p, null);
assert.equal(sent.length, 1);
tick(15000);
completer.ask({ prefix: 'abc' });
tick(250);
assert.equal(sent.length, 2);
});
test('the window around the cursor: the end of what is before, the start of what is after', () => {
const text = 'a'.repeat(50) + '|' + 'b'.repeat(50);
const w = windowAround(text, 51, { prefixMax: 10, suffixMax: 5 });
assert.equal(w.prefix, 'aaaaaaaaa|');
assert.equal(w.suffix, 'bbbbb');
assert.deepEqual(windowAround('short', 2), { prefix: 'sh', suffix: 'ort' });
assert.deepEqual(windowAround('x', 99), { prefix: 'x', suffix: '' });
// A character of two units is never cut in half.
const bread = 'ab🍞cd🍞ef';
const cut = windowAround(bread, 5, { prefixMax: 2, suffixMax: 2 });
assert.equal(cut.prefix, 'c');
assert.equal(cut.suffix, 'd');
});
// ---- against the stand-in agent, on the real clock ----------------------------------------
function onAgent(t, env, extra) {
const { chat, agents } = fakeChat(t, { env });
const refusals = [];
const completer = new Completer({
request: (m, p) => chat.request(m, p, true),
notify: (m, p) => chat.notify(m, p),
debounceMs: () => 20,
onRefusal: (reason, message) => refusals.push({ reason, message }),
...(extra || {}),
});
return { chat, agents, completer, refusals };
}
test('agent: a completion comes back as text to insert', async (t) => {
const { completer, agents } = onAgent(t);
assert.equal(await completer.ask({ prefix: 'def bake', suffix: '', language: 'python' }), '<bake|example/model-a>');
const sent = agents[0].log().find((m) => m.method === '_lembas/complete');
assert.deepEqual(sent.params, { id: 'c1', prefix: 'def bake', suffix: '', language: 'python' });
assert.ok(!agents[0].log().some((m) => m.method === 'session/new'), 'a completion needs no session');
});
test('agent: a slow completion is cancelled by the next one, and only the newest is shown', async (t) => {
const { completer, agents, chat } = onAgent(t);
await chat.connect(true);
const slow = completer.ask({ prefix: 'SLOWC one' }, { manual: true });
await until(() => agents[0].log().some((m) => m.method === '_lembas/complete'));
const fast = completer.ask({ prefix: 'two' }, { manual: true });
assert.equal(await slow, null);
assert.equal(await fast, '<two|example/model-a>');
assert.deepEqual(agents[0].log().find((m) => m.method === '_lembas/complete/cancel').params, { id: 'c1' });
});
test('agent: nobody has chosen a model — said once with the server\'s sentence, then a window choice works', async (t) => {
let model;
const { completer, agents, refusals } = onAgent(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' }, { model: () => model });
assert.equal(await completer.ask({ prefix: 'a' }), null);
assert.equal(await completer.ask({ prefix: 'ab' }), null);
assert.equal(await completer.ask({ prefix: 'abc' }), null);
assert.deepEqual(refusals, [{ reason: 'no_model', message: 'No autocomplete model is chosen. Choose one in your settings on the server.' }]);
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/complete').length, 1);
model = 'example/model-b';
completer.unblock();
assert.equal(await completer.ask({ prefix: 'abc' }), '<abc|example/model-b>');
});
test('agent: a model not allowed for autocomplete is a refusal of its own', async (t) => {
const { completer, refusals } = onAgent(t, {}, { model: () => 'example/model-c' });
assert.equal(await completer.ask({ prefix: 'a' }), null);
assert.equal(refusals[0].reason, 'not_allowed');
});
+64
View File
@@ -0,0 +1,64 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { editorContext, promptParams, selectionLabel, sliceLines, LIMITS } = require('../src/context');
test('nothing to say is no context at all', () => {
assert.equal(editorContext(null), undefined);
assert.equal(editorContext({}), undefined);
assert.equal(editorContext({ diagnostics: [], open: [] }), undefined);
});
test('lines are 1-based, a selection in another file names it, the open file is not listed twice', () => {
assert.deepEqual(editorContext({ path: '/p/a.py', cursorLine: 3, selection: { path: '/p/a.py', start: 2, end: 2, text: 'x' }, open: ['/p/a.py', '/p/b.py', '/p/b.py'] }), {
path: '/p/a.py',
cursor: { line: 3 },
selection: { start: 2, end: 2, text: 'x' },
open: ['/p/b.py'],
});
assert.deepEqual(editorContext({ path: '/p/a.py', selection: { path: '/p/c.py', start: 5, end: 3 } }).selection, { start: 5, end: 5, path: '/p/c.py' });
assert.equal(editorContext({ path: '/p/a.py', cursorLine: 0 }).cursor, undefined);
});
test('diagnostics and open files are kept to the limits, each message one line', () => {
const many = Array.from({ length: 50 }, (_, i) => ({ line: i + 1, severity: 'error', message: 'bad\n thing ' + i + ' ' + 'x'.repeat(400), source: 'lint' }));
const ctx = editorContext({ path: '/p/a.py', diagnostics: [...many, { message: ' ' }, null], open: Array.from({ length: 80 }, (_, i) => '/p/f' + i) });
assert.equal(ctx.diagnostics.length, LIMITS.diagnostics);
assert.ok(ctx.diagnostics.every((d) => !d.message.includes('\n') && d.message.length <= LIMITS.diagnosticChars));
assert.match(ctx.diagnostics[0].message, /^bad thing 0 x+…$/);
assert.equal(ctx.open.length, LIMITS.open);
assert.equal(editorContext({ diagnostics: [{ message: 'm', severity: 'fatal', line: -2 }] }).diagnostics[0].severity, undefined);
});
test('the prompt: context beside the text for an agent that reads it', () => {
const editor = editorContext({ path: '/p/a.py', cursorLine: 3 });
assert.deepEqual(promptParams('ses_1', 'hi', editor, true), {
sessionId: 'ses_1',
prompt: [{ type: 'text', text: 'hi' }],
_meta: { lembas: { editor: { path: '/p/a.py', cursor: { line: 3 } } } },
});
assert.deepEqual(promptParams('ses_1', 'hi', undefined, true), { sessionId: 'ses_1', prompt: [{ type: 'text', text: 'hi' }] });
assert.deepEqual(promptParams('ses_1', 'hi', editor, false).prompt, [
{ type: 'text', text: 'Open in the editor: /p/a.py, cursor on line 3.' },
{ type: 'text', text: 'hi' },
]);
});
test('how a selection is named', () => {
assert.equal(selectionLabel('src/a.py', 3, 9), 'src/a.py:3-9');
assert.equal(selectionLabel('src/a.py', 3, 3), 'src/a.py:3');
assert.equal(selectionLabel('', 1, 2), 'untitled:1-2');
});
test("the part of a text the agent asks for (ACP's line and limit)", () => {
const text = 'one\ntwo\nthree\nfour\n';
assert.equal(sliceLines(text), text);
assert.equal(sliceLines(text, null, null), text);
assert.equal(sliceLines(text, 1), text);
assert.equal(sliceLines(text, 2, 2), 'two\nthree');
assert.equal(sliceLines(text, 3), 'three\nfour\n');
assert.equal(sliceLines(text, 1, 1), 'one');
assert.equal(sliceLines(text, 99, 5), '');
assert.equal(sliceLines(text, 2, 0), '');
assert.equal(sliceLines(text, 'x', 'y'), text);
});
+485
View File
@@ -0,0 +1,485 @@
'use strict';
// extension.js, loaded against tests/stub_vscode.js and the stand-in agent. This is NOT a run
// inside VS Code: the editor here is a few hundred lines of memory. It shows that the glue
// loads, registers what the manifest names, and drives the tested modules the way it means to.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const Module = require('node:module');
const crypto = require('node:crypto');
const { make } = require('./stub_vscode');
const { FAKE, tempDir, until } = require('./helpers');
const ROOT = path.join(__dirname, '..');
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), crypto.randomBytes(3000)]);
/** Activate the extension in a fresh stand-in editor whose `lembas` is the stand-in agent. */
function host(t, env) {
const dir = tempDir(t);
const log = path.join(dir, 'agent.log');
const command = path.join(dir, 'lembas');
const vars = { FAKE_AGENT_LOG: log, PYTHONDONTWRITEBYTECODE: '1', ...(env || {}) };
const exports_ = Object.entries(vars).map(([k, v]) => `export ${k}='${v}'`).join('\n');
// The extension starts `<command> serve --stdio`; this one is the stand-in, whatever it is told.
fs.writeFileSync(command, `#!/bin/sh\n${exports_}\nexec python3 '${FAKE}'\n`, { mode: 0o755 });
const vscode = make(pkg);
vscode.__.config['llembas.command'] = command;
vscode.workspace.workspaceFolders = [{ uri: vscode.Uri.file(dir) }];
const load = Module._load;
Module._load = function (request, ...rest) {
return request === 'vscode' ? vscode : load.call(this, request, ...rest);
};
for (const key of Object.keys(require.cache)) if (key.startsWith(ROOT + path.sep) && !key.includes(`${path.sep}tests${path.sep}`)) delete require.cache[key];
const extension = require('../extension.js');
Module._load = load;
const context = { subscriptions: [], extensionUri: vscode.Uri.file(ROOT), extension: { packageJSON: { version: '0.0.0' } } };
extension.activate(context);
t.after(() => {
for (const s of context.subscriptions) s.dispose && s.dispose();
extension.deactivate();
});
const view = vscode.__.view();
vscode.__.viewProviders.get('llembas.chat').provider.resolveWebviewView(view);
view.say({ type: 'ready' });
const sent = () => (fs.existsSync(log) ? fs.readFileSync(log, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
const run = (name, ...args) => vscode.__.commands.get(name)(...args);
/** The newest version of every item the page was sent, in order. */
const items = () => {
const byId = new Map();
for (const m of view.posted) {
if (m.type === 'reset') {
byId.clear();
for (const i of m.items) byId.set(i.id, i);
} else if (m.type === 'item') byId.set(m.item.id, m.item);
}
return [...byId.values()];
};
const state = () => view.posted.filter((m) => m.type === 'state' || m.type === 'reset').pop().state;
const idle = () => until(() => state().busy === false && items().length > 0);
return { vscode, view, dir, sent, run, items, state, idle, s: vscode.__ };
}
const flat = (ast) => JSON.stringify(ast);
test('activation registers the view, every command of the manifest, the providers and a status item', (t) => {
const { s, view } = host(t);
assert.deepEqual([...s.commands.keys()].sort(), pkg.contributes.commands.map((c) => c.command).sort());
assert.ok(s.viewProviders.get('llembas.chat').options.webviewOptions.retainContextWhenHidden);
assert.equal(s.inlineProviders.length, 1);
assert.equal(s.lensProviders.length, 1);
assert.ok(s.contentProviders.has('llembas-diff'));
assert.equal(s.statusItems[0].text, 'LLeMbas');
assert.equal(s.statusItems[0].command, 'llembas.modelSettings');
assert.equal(view.webview.options.enableScripts, true);
assert.equal(view.webview.options.enableCommandUris, false);
assert.equal(view.webview.options.localResourceRoots.length, 2);
assert.match(view.webview.html, /Content-Security-Policy" content="default-src 'none'; img-src https:\/\/file\.example; style-src https:\/\/file\.example; script-src 'nonce-[A-Za-z0-9_-]{20,}'/);
assert.deepEqual(view.posted[0], { type: 'reset', items: [], state: { busy: false, session: false, mode: null, modes: [], model: null, models: [] }, attached: '' });
});
test('a message typed in the view is answered, and the reply reaches the page as a tree, not as markup', async (t) => {
const { vscode, view, sent, items, state, idle, dir } = host(t);
vscode.__.open(path.join(dir, 'oven.py'), 'def bake():\n pass\n', new vscode.Selection(1, 4, 1, 4), 'python');
view.say({ type: 'send', text: 'hello' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
const [user, agent] = items();
assert.deepEqual({ kind: user.kind, text: user.text }, { kind: 'user', text: 'hello' });
assert.equal(agent.text, undefined, "the model's text is not sent as a string to draw");
assert.equal(flat(agent.ast), flat([{ t: 'p', c: [{ t: 'text', v: 'Hello there.' }, { t: 'br' }, { t: 'text', v: 'Second line' }] }]));
assert.equal(state().mode, 'ask');
assert.equal(state().model, 'example/model-a');
await until(() => state().models.length === 3);
// The file in front and the cursor went with the prompt.
const prompt = sent().find((m) => m.method === 'session/prompt');
assert.deepEqual(prompt.params._meta.lembas.editor, { path: path.join(dir, 'oven.py'), cursor: { line: 2 } });
assert.equal(sent().find((m) => m.method === 'session/new').params.cwd, dir);
// The page's own controls.
view.say({ type: 'setModel', id: 'example/model-b' });
await until(() => state().model === 'example/model-b');
view.say({ type: 'setMode', id: 'edit' });
await until(() => state().mode === 'edit');
view.say({ type: 'new' });
await until(() => items().length === 0);
});
test('messages from the page are checked: a bad link is not opened, a wrong shape is ignored', async (t) => {
const { view, s } = host(t);
for (const m of [null, 'send', { type: 7 }, { type: 'send', text: 42 }, { type: 'send', text: ' ' }, { type: 'answer', card: 1, option: {} }, { type: 'openLink', href: 'javascript:alert(1)' },
{ type: 'openLink', href: 'command:workbench.action.terminal.new' }, { type: 'openLink', href: 'file:///etc/passwd' }, { type: 'openFile', path: 'relative/path' }, { type: 'openMedia', key: 'nope' }, { type: 'unknown' }]) {
view.say(m);
}
view.say({ type: 'openLink', href: 'https://example.org/docs' });
await new Promise((r) => setTimeout(r, 30));
assert.deepEqual(s.external, ['https://example.org/docs']);
assert.equal(view.posted.filter((m) => m.type === 'item').length, 0, 'nothing was sent to the agent');
});
test('ask about a selection: the answer in the chat, the selection as editor context', async (t) => {
const { vscode, view, sent, items, idle, run, dir, s } = host(t);
const file = path.join(dir, 'oven.py');
vscode.__.open(file, 'import flour\n\ndef bake():\n return crumbs\n\nprint(bake())\n', new vscode.Selection(2, 0, 4, 0), 'python');
s.diagnostics.set(vscode.Uri.file(file).toString(), [
{ range: new vscode.Range(3, 11, 3, 17), severity: 0, message: "name 'crumbs' is not defined", source: 'lint' },
{ range: new vscode.Range(0, 0, 0, 12), severity: 1, message: 'unused import', source: 'lint' },
]);
s.inputs.push('META why does this fail?');
await run('llembas.ask');
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
const prompt = sent().find((m) => m.method === 'session/prompt');
assert.deepEqual(prompt.params.prompt, [{ type: 'text', text: 'META why does this fail?' }]);
assert.deepEqual(prompt.params._meta.lembas.editor, {
path: file,
cursor: { line: 5 },
selection: { start: 3, end: 4, text: 'def bake():\n return crumbs\n' },
diagnostics: [{ message: "name 'crumbs' is not defined", line: 4, severity: 'error', source: 'lint' }],
});
assert.equal(items()[0].label, 'oven.py:3-4');
assert.ok(s.executed.some((e) => e[0] === 'llembas.chat.focus'), 'the chat is brought forward');
// Without a question the selection waits for the next message typed.
s.inputs.push('');
await run('llembas.ask');
assert.deepEqual(view.posted.filter((m) => m.type === 'attached').pop(), { type: 'attached', label: 'oven.py:3-4' });
view.say({ type: 'send', text: 'and this?' });
await until(() => sent().filter((m) => m.method === 'session/prompt').length === 2);
assert.equal(sent().filter((m) => m.method === 'session/prompt')[1].params._meta.lembas.editor.selection.start, 3);
assert.deepEqual(view.posted.filter((m) => m.type === 'attached').pop(), { type: 'attached', label: '' });
await idle();
// Nothing selected: said, and nothing sent.
vscode.window.activeTextEditor.selection = new vscode.Selection(1, 0, 1, 0);
await run('llembas.ask');
assert.match(s.messages.pop().text, /select the text/);
});
test('rewrite a selection: shown as changes to accept or reject, nothing written before', async (t) => {
const { vscode, sent, run, dir, s } = host(t);
const before = ['top', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'bottom'].join('\n');
const editor = vscode.__.open(path.join(dir, 'list.txt'), before, new vscode.Selection(1, 0, 10, 0));
const doc = editor.document;
s.inputs.push('REPLACE A1\\na2\\na3\\na5\\na6\\nnew\\na7\\na8\\nA9\\ntail');
await run('llembas.rewrite');
const asked = sent().find((m) => m.method === '_lembas/edit');
assert.equal(asked.params.text, 'a1\na2\na3\na4\na5\na6\na7\na8\na9', 'whole lines, and not the line the selection only ends in front of');
assert.equal(asked.params.before, 'top');
assert.equal(asked.params.after, 'bottom');
assert.equal(asked.params.path, path.join(dir, 'list.txt'));
assert.equal(asked.params.id, 'e1');
assert.ok(s.executed.some((e) => e[0] === 'progress'), 'the pieces written so far are shown');
assert.equal(doc.text, before, 'nothing is written before it is accepted');
assert.match(s.messages.pop().text, /proposes 4 changes\. Nothing is written until you accept\./);
const lenses = s.lensProviders[0].provideCodeLenses(doc);
assert.deepEqual(lenses.map((l) => `${l.range.start.line}:${l.command.title}`), [
'1:Accept', '1:Reject', '1:Accept all 4', '1:Reject all', '1:Show as a diff', '4:Accept', '4:Reject', '7:Accept', '7:Reject', '9:Accept', '9:Reject',
]);
const [removed, added] = [...editor.decorations.values()];
assert.deepEqual(removed.map((d) => d.range.start.line), [1, 4, 9]);
assert.deepEqual(added.map((d) => d.renderOptions.after.contentText), ['→ A1', 'taken away', 'added above: new', '→ A9 (+1 more line)']);
// The diff view: the file on the left, the whole proposal on the right.
const diff = s.executed.find((e) => e[0] === 'vscode.diff');
assert.equal(diff[1], doc.uri);
assert.equal(diff[2].scheme, 'llembas-diff');
const proposed = () => s.contentProviders.get('llembas-diff').provideTextDocumentContent(diff[2]);
assert.equal(proposed(), ['top', 'A1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
// A second rewrite waits until this one is settled.
s.inputs.push('anything');
await run('llembas.rewrite');
assert.match(s.messages.pop().text, /accept or reject the changes shown in this file first/);
// Accept the second change (a4 taken away) through its code lens.
const second = lenses.find((l) => l.range.start.line === 4 && l.command.title === 'Accept').command;
await run(second.command, ...second.arguments);
assert.equal(doc.text, ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'a7', 'a8', 'a9', 'bottom'].join('\n'));
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [1, 6, 8]);
// Reject the first (A1) at the cursor, by the command without arguments.
editor.selection = new vscode.Selection(1, 0, 1, 0);
await run('llembas.rejectChange');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [6, 8]);
assert.equal(proposed(), ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
// Typing above moves what is left; then accept all.
doc.text = 'typed\n' + doc.text;
doc.version += 1;
s.changed.fire({ document: doc, contentChanges: [{ range: new vscode.Range(0, 0, 0, 0), text: 'typed\n' }] });
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [7, 9]);
await run('llembas.acceptAllChanges');
assert.equal(doc.text, ['typed', 'top', 'a1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc), []);
assert.deepEqual([...editor.decorations.values()].map((d) => d.length), [0, 0]);
assert.ok(!s.tabs.some((tab) => tab.input.modified), 'the diff view is closed with the last change');
});
test('rewrite: a change typed over is dropped rather than applied to the wrong text; reject all leaves the file alone', async (t) => {
const { vscode, run, dir, s } = host(t);
const editor = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo\nthree', new vscode.Selection(0, 0, 2, 5));
const doc = editor.document;
s.inputs.push('REPLACE ONE\\ntwo\\nTHREE');
await run('llembas.rewrite');
assert.equal(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').length, 2);
// The person edits line 3 behind the extension's back (no change event reaches it).
doc.text = 'one\ntwo\nthree!';
await run('llembas.acceptAllChanges');
assert.equal(doc.text, 'ONE\ntwo\nthree!');
assert.match(s.messages.pop().text, /the text changed where a change was proposed; it was dropped/);
s.inputs.push('REPLACE x');
editor.selection = new vscode.Selection(0, 0, 2, 6);
await run('llembas.rewrite');
await run('llembas.rejectAllChanges');
assert.equal(doc.text, 'ONE\ntwo\nthree!');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc), []);
});
test('rewrite: the answer to the proposal\'s own message accepts all; a file that changed meanwhile shows nothing', async (t) => {
const { vscode, run, dir, s } = host(t);
const editor = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
s.inputs.push('shout');
s.answers.push('Accept all');
await run('llembas.rewrite');
assert.equal(editor.document.text, 'ONE\nTWO');
s.inputs.push('SLOWE shout');
const going = run('llembas.rewrite');
await until(() => typeof s.cancelProgress === 'function');
await new Promise((r) => setTimeout(r, 100));
s.cancelProgress();
await going;
assert.equal(editor.document.text, 'ONE\nTWO', 'a cancelled rewrite proposes nothing');
assert.deepEqual(s.lensProviders[0].provideCodeLenses(editor.document), []);
});
test('autocomplete: as you type and by hand, as an inline completion at the cursor', async (t) => {
const { vscode, sent, dir, s } = host(t);
s.config['llembas.complete.debounce'] = 10;
const editor = vscode.__.open(path.join(dir, 'oven.py'), 'def bake(flour):\n return \nprint(1)\n', new vscode.Selection(1, 11, 1, 11), 'python');
const provider = s.inlineProviders[0];
const token = () => ({ isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
const at = new vscode.Position(1, 11);
const got = await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1 }, token());
assert.equal(got.length, 1);
assert.equal(got[0].insertText, '<return|example/model-a>');
assert.deepEqual(got[0].range.start, at);
assert.deepEqual(sent().find((m) => m.method === '_lembas/complete').params, {
id: 'c1', prefix: 'def bake(flour):\n return ', suffix: '\nprint(1)\n', path: path.join(dir, 'oven.py'), language: 'python',
});
// The editor's own suggestion list is open: stay out of its way.
assert.equal(await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1, selectedCompletionInfo: {} }, token()), undefined);
// Switched off: nothing as you type, still there by hand.
s.config['llembas.complete.auto'] = false;
assert.equal(await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1 }, token()), undefined);
assert.equal((await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 0 }, token()))[0].insertText, '<return|example/model-a>');
s.config['llembas.complete.auto'] = true;
// The editor moved on before the answer: the request is cancelled by its id and nothing is shown.
editor.document.text = 'x = SLOWC \n';
let cancel;
const moving = provider.provideInlineCompletionItems(editor.document, new vscode.Position(0, 10), { triggerKind: 0 }, {
isCancellationRequested: false,
onCancellationRequested: (fn) => ((cancel = fn), { dispose() {} }),
});
await until(() => sent().filter((m) => m.method === '_lembas/complete').length === 3);
cancel();
assert.equal(await moving, undefined);
await until(() => sent().some((m) => m.method === '_lembas/complete/cancel'));
assert.deepEqual(sent().find((m) => m.method === '_lembas/complete/cancel').params, { id: 'c3' });
// The command asks the editor for an inline suggestion, which comes back to the provider as "by hand".
await s.commands.get('llembas.complete')();
assert.ok(s.executed.some((e) => e[0] === 'editor.action.inlineSuggest.trigger'));
});
test('autocomplete without a model: said once with a button, quiet until one is chosen; the quick switch is not saved', async (t) => {
const { vscode, sent, dir, s } = host(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' });
s.config['llembas.complete.debounce'] = 5;
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = 1\ny = ', new vscode.Selection(1, 4, 1, 4), 'python');
const provider = s.inlineProviders[0];
const ask = () => provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
// The person presses the button, picks Model B, for this window only.
s.answers.push('Choose a model');
s.picks.push((items) => {
assert.deepEqual(items.map((i) => i.label), ['Model A', 'Model B', "Use the server's default"], 'only models allowed for autocomplete');
return items[1];
});
s.picks.push((items) => items.find((i) => i.label === 'Only this window'));
assert.equal(await ask(), undefined);
assert.deepEqual(s.messages[0], { level: 'info', text: 'LLeMbas: No autocomplete model is chosen. Choose one in your settings on the server.', buttons: ['Choose a model'] });
await until(() => s.statusItems[0].text === 'LLeMbas: model-b');
assert.match(s.statusItems[0].tooltip, /example\/model-b \(this window only\)/);
assert.equal(s.messages.length, 1);
const got = await ask();
assert.equal(got[0].insertText, '<=|example/model-b>');
assert.equal(sent().filter((m) => m.method === '_lembas/complete').pop().params.model, 'example/model-b');
assert.ok(!sent().some((m) => m.method === '_lembas/editor/settings'), 'a quick switch is saved nowhere');
});
test('autocomplete without a model: asked again and again while typing, the server is asked once', async (t) => {
const { vscode, sent, dir, s } = host(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' });
s.config['llembas.complete.debounce'] = 5;
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = ', new vscode.Selection(0, 4, 0, 4), 'python');
const ask = () => s.inlineProviders[0].provideInlineCompletionItems(editor.document, new vscode.Position(0, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
for (let i = 0; i < 4; i++) assert.equal(await ask(), undefined);
assert.equal(sent().filter((m) => m.method === '_lembas/complete').length, 1);
assert.equal(s.messages.length, 1);
});
test('the two model settings: read, and saved in the account through the agent', async (t) => {
const { sent, run, s } = host(t);
s.picks.push((items) => {
assert.deepEqual(items.map((i) => [i.label, i.description]), [['Autocomplete model', 'example/model-a'], ['Main model', 'not chosen']]);
return items[1];
});
s.picks.push((items) => {
assert.deepEqual(items.map((i) => i.label), ['Model A', 'Model B', 'Model C', "Use the server's default"]);
return items[2];
});
s.picks.push((items) => items.find((i) => i.label === 'Save it'));
await run('llembas.modelSettings');
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { main_model: 'example/model-c' } });
s.picks.push((items) => items.find((i) => i.label === 'Model B'));
s.picks.push((items) => items.find((i) => i.label === 'Save it'));
await run('llembas.chooseAutocompleteModel');
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: 'example/model-b' } });
assert.equal(s.statusItems[0].text, 'LLeMbas: model-b');
s.picks.push((items) => items[items.length - 1]);
await run('llembas.chooseAutocompleteModel');
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: null } });
});
test("the window's main model starts sessions and rewrites, and is saved nowhere", async (t) => {
const { vscode, view, sent, run, items, idle, dir, s } = host(t);
s.picks.push((items_) => items_.find((i) => i.label === 'Model C'));
s.picks.push((items_) => items_.find((i) => i.label === 'Only this window'));
await run('llembas.chooseMainModel');
assert.ok(!sent().some((m) => m.method === '_lembas/editor/settings'));
view.say({ type: 'send', text: 'hello' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
assert.equal(sent().find((m) => m.method === 'session/new').params._meta.model, 'example/model-c');
vscode.__.open(path.join(dir, 'a.txt'), 'one', new vscode.Selection(0, 0, 0, 3));
s.inputs.push('shout');
await run('llembas.rewrite');
const edit = sent().find((m) => m.method === '_lembas/edit');
assert.equal(edit.params.model, 'example/model-c');
assert.equal(edit.params.sessionId, 'ses_test');
});
test("an approval that carries a diff opens the editor's diff view before the answer, and closes it after", async (t) => {
const { view, items, idle, dir, s } = host(t);
const file = path.join(dir, 'waybread.py');
fs.writeFileSync(file, 'old text\n');
view.say({ type: 'send', text: `DIFFPERM ${file}` });
await until(() => items().some((i) => i.kind === 'card'));
const card = items().find((i) => i.kind === 'card');
assert.equal(card.state, 'open');
assert.deepEqual(card.files, [file]);
const diff = s.executed.find((e) => e[0] === 'vscode.diff');
const provider = s.contentProviders.get('llembas-diff');
assert.equal(provider.provideTextDocumentContent(diff[1]), 'old text\n');
assert.equal(provider.provideTextDocumentContent(diff[2]), 'rewritten by the agent\n');
assert.equal(diff[3], 'LLeMbas: waybread.py (proposed change)');
assert.ok(diff[1].path.endsWith('/waybread.py'), 'named like the file, so the editor colours it as one');
assert.equal(fs.readFileSync(file, 'utf8'), 'old text\n');
assert.deepEqual(view.shows, [true], 'the chat is shown without taking the keyboard');
assert.equal(s.tabs.filter((tab) => tab.input.modified).length, 1);
view.say({ type: 'answer', card: card.id, option: 'once' });
await until(() => fs.readFileSync(file, 'utf8') === 'rewritten by the agent\n');
await idle();
await until(() => items().find((i) => i.kind === 'card').state === 'answered'); // items reach the page a moment after the state
await until(() => s.tabs.filter((tab) => tab.input.modified).length === 0);
assert.equal(provider.provideTextDocumentContent(diff[2]), '', 'the texts are let go');
assert.deepEqual(items().find((i) => i.kind === 'tool').files, [file]);
});
test('unsaved text: the agent reads an open file from the editor, and any other file itself', async (t) => {
const { vscode, view, items, idle, dir } = host(t);
const file = path.join(dir, 'draft.md');
fs.writeFileSync(file, 'saved text\n');
vscode.__.open(file, 'unsaved text\nline two\n');
view.say({ type: 'send', text: `READ ${file}` });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
assert.match(flat(items().find((i) => i.kind === 'agent').ast), /read=\\"unsaved text\\\\nline two\\\\n\\"/);
view.say({ type: 'send', text: `READ ${path.join(dir, 'not-open.md')}` });
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
await idle();
assert.match(flat(items().filter((i) => i.kind === 'agent')[1].ast), /read=null/);
});
test('media: a picture is shown in the chat from the extension\'s own folder; other files get Open, runnable ones do not open', async (t) => {
const { view, items, idle, dir, s } = host(t);
const picture = path.join(dir, 'chart.png');
fs.writeFileSync(picture, PNG);
view.say({ type: 'send', text: `SHOW ${picture}` });
await until(() => items().some((i) => i.kind === 'media'));
await idle();
const shown = items().find((i) => i.kind === 'media');
assert.equal(shown.picture, true);
assert.equal(shown.sizeWords, '3 KB');
const root = view.webview.options.localResourceRoots[1].path;
assert.ok(shown.src.startsWith('https://file.example' + root + '/') && shown.src.endsWith('-chart.png'), shown.src);
assert.ok(fs.readFileSync(shown.src.slice('https://file.example'.length)).equals(PNG));
view.say({ type: 'openMedia', key: shown.key });
await until(() => s.executed.some((e) => e[0] === 'vscode.open'));
view.say({ type: 'new' });
await until(() => items().length === 0);
const script = path.join(dir, 'setup.sh');
fs.writeFileSync(script, '#!/bin/sh\necho hello from a script that must not run\n');
view.say({ type: 'send', text: `SHOW ${script} WITHURI` });
await until(() => items().some((i) => i.kind === 'media'));
await idle();
const line = items().find((i) => i.kind === 'media');
assert.equal(line.picture, false);
assert.equal(line.src, '');
view.say({ type: 'openMedia', key: line.key });
await until(() => s.messages.some((m) => /may run rather than show/.test(m.text)));
assert.deepEqual(s.external, [], 'not handed to the system');
view.say({ type: 'new' });
await until(() => items().length === 0);
const pdf = path.join(dir, 'report.pdf');
fs.writeFileSync(pdf, '%PDF-1.7\n' + 'x'.repeat(2000));
view.say({ type: 'send', text: `SHOW ${pdf} WITHURI` });
await until(() => items().some((i) => i.kind === 'media'));
await idle();
view.say({ type: 'openMedia', key: items().find((i) => i.kind === 'media').key });
await until(() => s.external.length === 1);
assert.equal(s.external[0], 'file://' + pdf);
});
test('media over the limit is refused in words', async (t) => {
const { view, items, idle, dir, s } = host(t);
s.config['llembas.media.maxMegabytes'] = 1;
const big = path.join(dir, 'big.bin');
fs.writeFileSync(big, Buffer.alloc(1024 * 1024 + 10));
view.say({ type: 'send', text: `SHOW ${big}` });
await until(() => items().some((i) => i.kind === 'note'));
await idle();
assert.equal(items().find((i) => i.kind === 'note').text, 'big.bin was not shown: The file is 1.0 MB; this editor takes files of up to 1 MB.');
});
test('a command that is not installed is said in the chat, and autocomplete stays quiet about it', async (t) => {
const { vscode, view, items, dir, s } = host(t);
s.config['llembas.command'] = path.join(dir, 'no-such-lembas');
s.config['llembas.complete.debounce'] = 5;
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = ', new vscode.Selection(0, 4, 0, 4));
const got = await s.inlineProviders[0].provideInlineCompletionItems(editor.document, new vscode.Position(0, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
assert.equal(got, undefined);
assert.equal(s.messages.length, 0);
assert.equal(items().length, 0);
view.say({ type: 'send', text: 'hello' });
await until(() => items().some((i) => i.kind === 'note'));
assert.match(items().find((i) => i.kind === 'note').text, /^Could not start .*no-such-lembas: the command was not found\.$/);
});
+338
View File
@@ -0,0 +1,338 @@
#!/usr/bin/env python3
"""A stand-in for `lembas serve --stdio`, for the extension's tests: ACP version 1 over lines,
with the editor's methods of harness spec 3.11.0 (`_lembas/complete`, `_lembas/edit`,
`_lembas/models`, `_lembas/editor/settings`, `_lembas/show` with `_lembas/show/read`).
It started as a copy of the Neovim plugin's stand-in and is kept separately on purpose.
A turn is steered by words in the prompt's last text block:
PERM asks for an approval
DIFFPERM <path> asks for an approval that carries a diff, and writes the file when allowed
WRITE <path> rewrites that file
READ <path> asks the client for the file's text and says it back
SHOW <path> shows that file through a handle
SHOWTEXT <path> shows that file as text
META says back the editor context the prompt carried
SETTLE asks for an approval and then withdraws it
SLOW waits to be cancelled
CRASH exits
A completion is steered by words in its prefix (SLOWC waits to be cancelled, FAILC fails), a
rewrite by words in its instruction (SLOWE waits to be cancelled).
Environment: FAKE_AGENT_LOG (every message received is appended, one JSON object a line),
FAKE_AGENT_AUTOCOMPLETE (the saved autocomplete model; "none": nobody has chosen one),
FAKE_AGENT_PLAIN=1 (an agent from before the editor's methods: no capabilities, no methods).
"""
import base64
import hashlib
import json
import os
import sys
import threading
LOG = os.environ.get("FAKE_AGENT_LOG")
PLAIN = os.environ.get("FAKE_AGENT_PLAIN") == "1"
lock = threading.Lock()
waiting = {}
cancelled = threading.Event()
next_id = [1000]
MODELS = [
{"id": "example/model-a", "name": "Model A", "for": ["main", "autocomplete"], "default": True},
{"id": "example/model-b", "name": "Model B", "for": ["main", "autocomplete"]},
{"id": "example/model-c", "name": "Model C", "for": ["main"]},
]
saved = os.environ.get("FAKE_AGENT_AUTOCOMPLETE", "example/model-a")
settings = {"autocomplete_model": None if saved == "none" else saved, "main_model": None}
session_model = ["example/model-a"]
completions = {} # the client's id -> Event set when it is cancelled
complete_lock = threading.Lock()
running_completion = [None] # (client id, Event)
edits = {}
handles = {} # handle -> bytes
def out(msg):
with lock:
sys.stdout.write(json.dumps(msg) + "\n")
sys.stdout.flush()
def result(msg, value):
out({"jsonrpc": "2.0", "id": msg["id"], "result": value})
def refuse(msg, code, message, reason=None):
error = {"code": code, "message": message}
if reason:
error["data"] = {"reason": reason}
out({"jsonrpc": "2.0", "id": msg["id"], "error": error})
def update(session, body):
out({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": session, "update": body}})
def say(session, text):
update(session, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}})
def ask(method, params, wait=10):
with lock:
next_id[0] += 1
rid = next_id[0]
done = threading.Event()
waiting[rid] = [done, None]
out({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
done.wait(wait)
return waiting.pop(rid)[1]
def read(path, mode="r"):
with open(path, mode) as f:
return f.read()
def word_after(text, word):
return text.split(word + " ", 1)[1].split()[0]
def editor_settings():
return {"autocomplete": {"model": settings["autocomplete_model"],
"source": "person" if settings["autocomplete_model"] else None,
"allowed": ["example/model-a", "example/model-b"]},
"main": {"model": settings["main_model"]}}
def prompt(msg):
p = msg["params"]
session = p["sessionId"]
text = [b["text"] for b in p["prompt"] if b["type"] == "text"][-1]
update(session, {"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hidden thought"}})
say(session, "Hello ")
say(session, "there.\nSecond line")
options = [{"optionId": "once", "name": "Allow once", "kind": "allow_once"},
{"optionId": "deny", "name": "Deny", "kind": "reject_once"}]
if "META" in text:
say(session, "\neditor=" + json.dumps(((p.get("_meta") or {}).get("lembas") or {}).get("editor"), sort_keys=True))
if "DIFFPERM " in text:
path = word_after(text, "DIFFPERM")
old = read(path) if os.path.exists(path) else None
new = "rewritten by the agent\n"
diff = [{"type": "diff", "path": path, "oldText": old, "newText": new}]
answer = ask("session/request_permission", {
"sessionId": session,
"toolCall": {"toolCallId": "edit-" + str(msg["id"]), "title": "edit " + os.path.basename(path), "kind": "edit",
"status": "pending", "rawInput": {}, "content": diff},
"options": options,
"_meta": {"lembas": {"tool": "edit", "reason": "manual mode asks about every edit"}}})
got = (answer or {}).get("outcome", {})
if got.get("optionId") == "once":
update(session, {"sessionUpdate": "tool_call", "toolCallId": "d1", "title": "edit " + os.path.basename(path),
"kind": "edit", "status": "in_progress"})
with open(path, "w") as f:
f.write(new)
update(session, {"sessionUpdate": "tool_call_update", "toolCallId": "d1", "status": "completed",
"content": [{"type": "content", "content": {"type": "text", "text": "done"}}] + diff})
say(session, "\nanswer=" + str(got.get("optionId") or got.get("outcome")))
elif "SETTLE" in text:
call = "settle-" + str(msg["id"])
def withdraw():
out({"jsonrpc": "2.0", "method": "_lembas/permission/settled", "params": {"sessionId": session, "toolCallId": call}})
threading.Timer(0.2, withdraw).start()
answer = ask("session/request_permission", {
"sessionId": session,
"toolCall": {"toolCallId": call, "title": "make build", "kind": "execute", "status": "pending", "rawInput": {}},
"options": options, "_meta": {"lembas": {"tool": "bash"}}})
got = (answer or {}).get("outcome", {})
say(session, "\nanswer=" + str(got.get("optionId") or got.get("outcome")))
elif "PERM" in text:
answer = ask("session/request_permission", {
"sessionId": session,
"toolCall": {"toolCallId": "perm-" + str(msg["id"]), "title": "rm -r build", "kind": "execute", "status": "pending", "rawInput": {}},
"options": options,
"_meta": {"lembas": {"tool": "bash", "reason": "deletes files"}}})
got = (answer or {}).get("outcome", {})
say(session, "\nanswer=" + str(got.get("optionId") or got.get("outcome")))
if "WRITE " in text:
path = word_after(text, "WRITE")
update(session, {"sessionUpdate": "tool_call", "toolCallId": "c1", "title": "edit " + os.path.basename(path),
"kind": "edit", "status": "in_progress"})
with open(path, "w") as f:
f.write("rewritten by the agent\n")
update(session, {"sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "completed"})
if "READ " in text:
path = word_after(text, "READ")
answer = ask("fs/read_text_file", {"sessionId": session, "path": path})
say(session, "\nread=" + json.dumps((answer or {}).get("content")))
if "SHOWTEXT " in text:
path = word_after(text, "SHOWTEXT")
answer = ask("_lembas/show", {"sessionId": session, "toolCallId": "show-t", "path": os.path.basename(path),
"kind": "text", "text": read(path)})
say(session, "\nshown=" + json.dumps(answer, sort_keys=True))
elif "SHOW " in text:
path = word_after(text, "SHOW")
data = read(path, "rb")
handle = "h_" + str(msg["id"])
handles[handle] = data
params = {"sessionId": session, "toolCallId": "show-" + str(msg["id"]), "path": os.path.basename(path),
"kind": "binary", "mimeType": "application/octet-stream", "size": len(data),
"hash": "sha256:" + hashlib.sha256(data).hexdigest(), "handle": handle}
if "WITHURI" in text:
params["uri"] = "file://" + os.path.abspath(path)
if "BADHASH" in text:
params["hash"] = "sha256:" + "0" * 64
answer = ask("_lembas/show", params, 30)
handles.pop(handle, None)
say(session, "\nshown=" + json.dumps(answer, sort_keys=True))
if "CRASH" in text:
sys.stderr.write("not signed in: run lembas login\n")
sys.stderr.flush()
os._exit(3)
stop = "end_turn"
if "SLOW" in text.replace("SLOWC", "").replace("SLOWE", ""):
stop = "cancelled" if cancelled.wait(10) else "end_turn"
cancelled.clear()
result(msg, {"stopReason": stop})
def complete(msg):
p = msg["params"]
cid = p.get("id")
mine = threading.Event()
with complete_lock:
before = running_completion[0]
running_completion[0] = (cid, mine)
if cid:
completions[cid] = mine
if before:
before[1].set() # a newer request cancels the older
try:
model = p.get("model") or settings["autocomplete_model"]
if not model:
return refuse(msg, -32602, "No autocomplete model is chosen. Choose one in your settings on the server.", "no_model")
if model == "example/model-c":
return refuse(msg, -32602, "Model C is not allowed for autocomplete.", "not_allowed")
prefix = p.get("prefix", "")
if "FAILC" in prefix:
return refuse(msg, -32603, "The server did not answer.")
if "SLOWC" in prefix:
mine.wait(10)
elif mine.wait(0.05):
pass
if mine.is_set():
return result(msg, {"text": "", "cancelled": True})
last = prefix.split()[-1] if prefix.split() else ""
result(msg, {"text": "<" + last + "|" + model + ">", "model": model, "finish": "stop"})
finally:
with complete_lock:
if running_completion[0] and running_completion[0][1] is mine:
running_completion[0] = None
if cid:
completions.pop(cid, None)
def edit(msg):
p = msg["params"]
eid = p.get("id")
mine = threading.Event()
if eid:
edits[eid] = mine
try:
if not p.get("text") or not p.get("instruction"):
return refuse(msg, -32602, "text and instruction are needed")
if "SLOWE" in p["instruction"]:
mine.wait(10)
if mine.is_set():
return result(msg, {"text": "", "cancelled": True})
if p["instruction"].startswith("REPLACE "):
new = p["instruction"][len("REPLACE "):].replace("\\n", "\n")
else:
new = p["text"].upper()
if eid:
half = len(new) // 2
for piece in (new[:half], new[half:]):
out({"jsonrpc": "2.0", "method": "_lembas/edit/delta", "params": {"id": eid, "delta": piece}})
result(msg, {"text": new, "model": p.get("model") or session_model[0]})
finally:
if eid:
edits.pop(eid, None)
def show_read(msg):
p = msg["params"]
data = handles.get(p.get("handle"))
if data is None:
return refuse(msg, -32602, "This file is no longer offered.")
offset = int(p.get("offset") or 0)
length = min(int(p.get("length") or 1000), 1000) # small parts, so a client has to loop
part = data[offset:offset + length]
result(msg, {"data": base64.b64encode(part).decode(), "offset": offset, "eof": offset + len(part) >= len(data)})
def main():
for line in sys.stdin:
if not line.strip():
continue
msg = json.loads(line)
if LOG:
with open(LOG, "a") as f:
f.write(json.dumps(msg) + "\n")
method = msg.get("method")
if method is None:
entry = waiting.get(msg.get("id"))
if entry:
entry[1] = msg.get("result")
entry[0].set()
elif method == "initialize":
meta = {} if PLAIN else {"lembas": {"protocol": 3, "harness_spec": "3.11.0", "limits": None, "connection": "example",
"capabilities": ["configure", "show", "editor", "media"]}}
result(msg, {"protocolVersion": 1, "agentCapabilities": {}, "agentInfo": {"name": "stand-in", "version": "0"}, "_meta": meta})
elif method == "session/new":
wanted = (msg["params"].get("_meta") or {}).get("model")
if wanted:
session_model[0] = wanted
result(msg, {
"sessionId": "ses_test",
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]},
"_meta": {"lembas": {"model": session_model[0], "mode": "ask"}}})
elif method == "session/prompt":
threading.Thread(target=prompt, args=(msg,), daemon=True).start()
elif method == "session/cancel":
cancelled.set()
elif method == "session/set_mode":
result(msg, {})
update(msg["params"]["sessionId"], {"sessionUpdate": "current_mode_update", "currentModeId": msg["params"]["modeId"]})
elif method == "_lembas/configure":
session_model[0] = msg["params"].get("model") or session_model[0]
result(msg, {"model": session_model[0], "effort": "default"})
elif PLAIN and "id" in msg:
refuse(msg, -32601, "Method not found")
elif method == "_lembas/models":
result(msg, {"models": MODELS, **editor_settings()})
elif method == "_lembas/editor/settings":
for key, value in (msg["params"].get("set") or {}).items():
if key in settings:
settings[key] = value
result(msg, editor_settings())
elif method == "_lembas/complete":
threading.Thread(target=complete, args=(msg,), daemon=True).start()
elif method == "_lembas/complete/cancel":
event = completions.get(msg["params"].get("id"))
if event:
event.set()
elif method == "_lembas/edit":
threading.Thread(target=edit, args=(msg,), daemon=True).start()
elif method == "_lembas/edit/cancel":
event = edits.get(msg["params"].get("id"))
if event:
event.set()
elif method == "_lembas/show/read":
show_read(msg)
elif "id" in msg:
refuse(msg, -32601, "Method not found")
main()
+76
View File
@@ -0,0 +1,76 @@
'use strict';
// Shared by the tests: the stand-in agent, a place for files, and reading what the agent was sent.
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 FAKE = path.join(__dirname, 'fake_agent.py');
function tempDir(t) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'llembas-vscode-test-'));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
return dir;
}
/** An Agent on the stand-in. `env` adds to the environment; the log of what it received is `agent.log()`. */
function fakeAgent(t, dir, env, more) {
const logFile = path.join(dir, `agent-${Math.random().toString(36).slice(2)}.log`);
const agent = new Agent({
command: 'python3',
args: [FAKE],
cwd: dir,
env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', FAKE_AGENT_LOG: logFile, ...(env || {}) },
clientInfo: { name: 'test', version: '0' },
...(more || {}),
});
agent.log = () => (fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
t.after(() => agent.stop());
return agent;
}
/** A Chat on the stand-in. Returns `{ chat, agents, dir }`; `agents` fills as the chat starts them. */
function fakeChat(t, options) {
const o = options || {};
const dir = o.dir || tempDir(t);
const agents = [];
const chat = new Chat({
makeAgent: (m) => {
const a = fakeAgent(t, dir, o.env, { cwd: m.cwd, onRequest: m.onRequest, ...(o.agent || {}) });
agents.push(a);
return a;
},
cwd: () => dir,
options: () => o.options || {},
hooks: o.hooks || {},
});
t.after(() => chat.dispose());
return { chat, agents, dir };
}
/** Wait until `test()` is true (checked every few milliseconds). */
async function until(test, ms) {
const end = Date.now() + (ms || 8000);
for (;;) {
if (test()) return true;
if (Date.now() > end) throw new Error('waited too long for: ' + test);
await new Promise((r) => setTimeout(r, 10));
}
}
const text = (chat) =>
chat.items
.map((i) => {
if (i.kind === 'user') return `You: ${i.label ? '[' + i.label + '] ' : ''}${i.text}`;
if (i.kind === 'agent') return `LLeMbas: ${i.text}`;
if (i.kind === 'thought') return `Thinking: ${i.text}`;
if (i.kind === 'note') return `> ${i.text}`;
if (i.kind === 'tool') return `tool ${i.status}: ${i.title}`;
if (i.kind === 'card') return `card ${i.state}: ${i.title} (${i.answer})`;
if (i.kind === 'media') return `media: ${i.name}`;
return i.kind;
})
.join('\n');
module.exports = { FAKE, tempDir, fakeAgent, fakeChat, until, text };
+179
View File
@@ -0,0 +1,179 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const h = require('../src/hunks');
/** Apply an edit of `editFor` to a list of lines, as an editor would to its text. */
function applyEdit(lines, e) {
const text = lines.join('\n');
const starts = [0];
for (let i = 0; i < text.length; i++) if (text[i] === '\n') starts.push(i + 1);
const offset = (p) => (p.end ? (p.line + 1 < starts.length ? starts[p.line + 1] - 1 : text.length) : starts[p.line]);
return (text.slice(0, offset(e.start)) + e.text + text.slice(offset(e.stop))).split('\n');
}
const apply = (a, hunks) => {
const out = a.slice();
for (const k of hunks.slice().reverse()) out.splice(k.aStart, k.aCount, ...k.b);
return out;
};
test('the differences between two lists of lines', () => {
const a = ['one', 'two', 'three', 'four', 'five'];
assert.deepEqual(h.diffLines(a, a), []);
assert.deepEqual(h.diffLines(a, ['one', 'TWO', 'three', 'four', 'five']), [{ aStart: 1, aCount: 1, bStart: 1, bCount: 1 }]);
assert.deepEqual(h.diffLines(a, ['one', 'three', 'four', 'five']), [{ aStart: 1, aCount: 1, bStart: 1, bCount: 0 }]);
assert.deepEqual(h.diffLines(a, ['zero', 'one', 'two', 'three', 'four', 'five']), [{ aStart: 0, aCount: 0, bStart: 0, bCount: 1 }]);
assert.deepEqual(h.diffLines(a, [...a, 'six', 'seven']), [{ aStart: 5, aCount: 0, bStart: 5, bCount: 2 }]);
assert.deepEqual(h.diffLines(a, ['ONE', 'two', 'three', 'four', 'FIVE']), [
{ aStart: 0, aCount: 1, bStart: 0, bCount: 1 },
{ aStart: 4, aCount: 1, bStart: 4, bCount: 1 },
]);
assert.deepEqual(h.diffLines([], ['a']), [{ aStart: 0, aCount: 0, bStart: 0, bCount: 1 }]);
assert.deepEqual(h.diffLines(['a'], []), [{ aStart: 0, aCount: 1, bStart: 0, bCount: 0 }]);
});
test('whatever the two texts, the hunks turn the one into the other', () => {
let seed = 7;
const rnd = (n) => {
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
return seed % n;
};
for (let round = 0; round < 300; round++) {
const a = Array.from({ length: rnd(14) }, () => 'line ' + rnd(5));
const b = a.slice();
for (let edits = rnd(5); edits > 0; edits--) {
const at = rnd(b.length + 1);
if (rnd(2)) b.splice(at, rnd(3), 'new ' + rnd(4));
else b.splice(at, rnd(3));
}
const hunks = h.diffLines(a, b);
const withB = hunks.map((k) => ({ ...k, b: b.slice(k.bStart, k.bStart + k.bCount) }));
assert.deepEqual(apply(a, withB), b, `round ${round}`);
for (let i = 1; i < hunks.length; i++) {
assert.ok(hunks[i].aStart > hunks[i - 1].aStart + hunks[i - 1].aCount, 'an unchanged line lies between two hunks');
}
}
});
test('texts too different to compare come back as one hunk, still correct', () => {
const a = Array.from({ length: 5000 }, (_, i) => 'a' + i);
const b = Array.from({ length: 5000 }, (_, i) => 'b' + i);
const hunks = h.diffLines(['same', ...a, 'end'], ['same', ...b, 'end']);
assert.deepEqual(hunks, [{ aStart: 1, aCount: 5000, bStart: 1, bCount: 5000 }]);
});
const DOC = ['# bread', 'def a():', ' return 1', '', 'def b():', ' return 2', 'print(a())'];
test('a rewrite of lines 2-6 becomes hunks at the document\'s own lines', () => {
const old = DOC.slice(1, 6);
const fresh = ['def a():', ' return 10', '', 'def b():', ' """Two."""', ' return 2'];
const hunks = h.propose(1, old, fresh);
assert.deepEqual(hunks, [
{ id: 1, line: 2, old: [' return 1'], new: [' return 10'] },
{ id: 2, line: 5, old: [], new: [' """Two."""'] },
]);
assert.deepEqual(h.withAll(DOC, hunks), ['# bread', ...fresh, 'print(a())']);
});
const OLD = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'];
const FRESH = ['A1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail'];
const AROUND = ['top', ...OLD, 'bottom'];
test('accepting hunks one by one, in any order, gives the rewrite; rejecting leaves the text', () => {
const orders = [[0, 1, 2, 3], [3, 2, 1, 0], [1, 3, 0, 2], [2, 0, 3, 1]];
for (const order of orders) {
let lines = AROUND.slice();
let hunks = h.propose(1, OLD, FRESH);
assert.equal(hunks.length, 4); // a1 replaced, a4 taken away, "new" added, a9 replaced with two lines
const ids = order.map((i) => hunks[i].id);
for (const id of ids) {
const hunk = hunks.find((k) => k.id === id);
assert.ok(h.stillFits(hunk, (i) => lines[i], lines.length), `hunk ${id} fits in order ${order}`);
lines = applyEdit(lines, h.editFor(hunk, lines.length));
hunks = h.afterAccept(hunks, hunk);
}
assert.deepEqual(lines, ['top', ...FRESH, 'bottom'], `order ${order}`);
assert.equal(hunks.length, 0);
}
// Accept only the second and the fourth: where the others were proposed, the old text stays.
let lines = AROUND.slice();
let hunks = h.propose(1, OLD, FRESH);
for (const id of [2, 4]) {
const hunk = hunks.find((k) => k.id === id);
lines = applyEdit(lines, h.editFor(hunk, lines.length));
hunks = h.afterAccept(hunks, hunk);
}
assert.deepEqual(lines, ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'a7', 'a8', 'A9', 'tail', 'bottom']);
assert.deepEqual(hunks.map((k) => [k.id, k.line]), [[1, 1], [3, 6]]);
});
test('the edit for each kind of hunk, at the edges of a document', () => {
// Lines added after the last line.
let lines = ['a', 'b'];
lines = applyEdit(lines, h.editFor({ line: 2, old: [], new: ['c', 'd'] }, 2));
assert.deepEqual(lines, ['a', 'b', 'c', 'd']);
// Lines added in front of the first.
assert.deepEqual(applyEdit(['a', 'b'], h.editFor({ line: 0, old: [], new: ['z'] }, 2)), ['z', 'a', 'b']);
// The last line taken away: the line break before it goes too.
assert.deepEqual(applyEdit(['a', 'b', 'c'], h.editFor({ line: 2, old: ['c'], new: [] }, 3)), ['a', 'b']);
// A middle line taken away.
assert.deepEqual(applyEdit(['a', 'b', 'c'], h.editFor({ line: 1, old: ['b'], new: [] }, 3)), ['a', 'c']);
// Every line taken away leaves one empty line, which is what an empty document is.
assert.deepEqual(applyEdit(['a', 'b'], h.editFor({ line: 0, old: ['a', 'b'], new: [] }, 2)), ['']);
// Lines replaced by more lines.
assert.deepEqual(applyEdit(['a', 'b', 'c'], h.editFor({ line: 1, old: ['b'], new: ['x', 'y'] }, 3)), ['a', 'x', 'y', 'c']);
});
test('all hunks as one set of edits against the same text (accept all)', () => {
const hunks = h.propose(1, OLD, FRESH);
// An editor applies edits given against one state; from the bottom up is the same thing.
let lines = AROUND.slice();
for (const hunk of hunks.slice().sort((p, q) => q.line - p.line)) lines = applyEdit(lines, h.editFor(hunk, AROUND.length));
assert.deepEqual(lines, ['top', ...FRESH, 'bottom']);
});
test('a hunk whose text was changed by hand no longer fits', () => {
const [hunk] = h.propose(1, [' return 1'], [' return 10']);
const lines = ['x', ' return 1'];
assert.ok(h.stillFits(hunk, (i) => lines[i], lines.length));
lines[1] = ' return 1 # edited';
assert.ok(!h.stillFits(hunk, (i) => lines[i], lines.length));
assert.ok(!h.stillFits({ line: 5, old: ['a'], new: [] }, (i) => lines[i], lines.length), 'past the end');
assert.ok(h.stillFits({ line: 2, old: [], new: ['z'] }, (i) => lines[i], lines.length), 'adding after the last line');
assert.ok(!h.stillFits({ line: 3, old: [], new: ['z'] }, (i) => lines[i], lines.length));
});
test('typing elsewhere moves the hunks below it; typing inside one drops it', () => {
const hunks = [
{ id: 1, line: 2, old: ['b', 'c'], new: ['B'] },
{ id: 2, line: 8, old: [], new: ['added'] },
{ id: 3, line: 10, old: ['k'], new: [] },
];
// A new line typed at the end of line 0.
let out = h.afterChange(hunks, { startLine: 0, endLine: 0, newLineCount: 2 });
assert.deepEqual(out.map((k) => k.line), [3, 9, 11]);
// Two lines deleted between the first and the second hunk.
out = h.afterChange(hunks, { startLine: 5, endLine: 7, newLineCount: 1 });
assert.deepEqual(out.map((k) => [k.id, k.line]), [[1, 2], [2, 6], [3, 8]]);
// A character typed inside the first hunk's lines.
out = h.afterChange(hunks, { startLine: 3, endLine: 3, newLineCount: 1 });
assert.deepEqual(out.map((k) => k.id), [2, 3]);
// A change below everything.
out = h.afterChange(hunks, { startLine: 20, endLine: 20, newLineCount: 3 });
assert.deepEqual(out, hunks);
// A deletion that swallows the place an addition was meant for.
out = h.afterChange(hunks, { startLine: 7, endLine: 9, newLineCount: 1 });
assert.deepEqual(out.map((k) => [k.id, k.line]), [[1, 2], [3, 8]]);
});
test('the lines a selection covers', () => {
assert.deepEqual(h.wholeLines({ startLine: 3, endLine: 5, endCharacter: 4 }), { first: 3, last: 5 });
assert.deepEqual(h.wholeLines({ startLine: 3, endLine: 6, endCharacter: 0 }), { first: 3, last: 5 }, 'not the line it only ends in front of');
assert.deepEqual(h.wholeLines({ startLine: 3, endLine: 3, endCharacter: 0 }), { first: 3, last: 3 });
});
test('a text is split into lines whatever its line breaks', () => {
assert.deepEqual(h.splitLines('a\r\nb\nc'), ['a', 'b', 'c']);
assert.deepEqual(h.splitLines('a\n'), ['a', '']);
});
+218
View File
@@ -0,0 +1,218 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { parse, parseInline, safeHref } = require('../src/markdown');
const { chatHtml } = require('../src/webview');
const page = require('../media/chat.js');
// A document that can only do what the chat page is allowed to do: make elements and text.
// It has no way to parse markup, so a test that passes here cannot have used one.
class Node {
constructor(tag, text) {
this.tag = tag;
this.text = text;
this.children = [];
this.attrs = {};
this.className = '';
this.listeners = {};
}
appendChild(c) {
this.children.push(c);
return c;
}
setAttribute(k, v) {
this.attrs[k] = String(v);
}
addEventListener(name, fn) {
this.listeners[name] = fn;
}
set textContent(v) {
this.children = [new Node('#text', String(v))];
}
get textContent() {
return this.tag === '#text' ? this.text : this.children.map((c) => c.textContent).join('');
}
all(out) {
const list = out || [];
for (const c of this.children) {
list.push(c);
c.all(list);
}
return list;
}
/** A picture of the tree, for comparing: text in quotes, elements as tag(children). */
show() {
if (this.tag === '#text') return JSON.stringify(this.text);
return `${this.tag}(${this.children.map((c) => c.show()).join(' ')})`;
}
}
const doc = { createElement: (tag) => new Node(tag), createTextNode: (text) => new Node('#text', text) };
function render(src) {
const root = new Node('div');
page.buildBlocks(doc, parse(src), root, 0);
return root;
}
const ALLOWED = new Set(['#text', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code', 'hr', 'blockquote', 'ul', 'ol', 'li', 'strong', 'em', 'span', 'br']);
test('paragraphs, emphasis, code and line breaks', () => {
assert.equal(render('Hello **bold** and *it* and `x < y`.\nnext').show(), 'div(p("Hello " strong("bold") " and " em("it") " and " code("x < y") "." br() "next"))');
assert.equal(render('one\n\ntwo').show(), 'div(p("one") p("two"))');
assert.equal(render('snake_case_name and 2 * 3 * 4').show(), 'div(p("snake_case_name and 2 * 3 * 4"))');
assert.equal(render('__bold__ _it_ **a *b* c**').show(), 'div(p(strong("bold") " " em("it") " " strong("a " em("b") " c")))');
assert.equal(render('\\*not\\* \\`code\\`').show(), 'div(p("*not* `code`"))');
});
test('headings, rules, quotes and lists', () => {
assert.equal(render('# One\n## Two ##\n####### seven').show(), 'div(h1("One") h2("Two") p("####### seven"))');
assert.equal(render('a\n\n---\n\nb').show(), 'div(p("a") hr() p("b"))');
assert.equal(render('> quoted **text**\n> more\n\nafter').show(), 'div(blockquote(p("quoted " strong("text") br() "more")) p("after"))');
const list = render('- one\n- two\n - inner\n still inner\n- three\n\n1. first\n2) second');
assert.equal(list.show(), 'div(ul(li("one") li("two") li("inner" br() "still inner") li("three")) ol(li("first") li("second")))');
assert.equal(list.children[0].children[2].className, 'depth-1');
});
test('a fenced block is text as written, and one still being written is a block already', () => {
assert.equal(render('```python\nprint("<b>hi</b>")\n**not bold**\n```\nafter').show(), 'div(pre(code("print(\\"<b>hi</b>\\")\\n**not bold**")) p("after"))');
assert.equal(render('text\n```js\nconst a = 1;').show(), 'div(p("text") pre(code("const a = 1;")))');
assert.equal(parse('```js title="<x>"\n1\n```')[0].lang, 'js');
assert.equal(render('~~~\na\n~~~').show(), 'div(pre(code("a")))');
});
test('a table is kept as written, in a block that scrolls on its own', () => {
assert.equal(render('| a | b |\n|---|---|\n| 1 | 2 |').show(), 'div(pre(code("| a | b |\\n|---|---|\\n| 1 | 2 |")))');
});
test('markup a model writes is text, never elements', () => {
const hostile = [
'<script>alert(1)</script>',
'<img src=x onerror=alert(1)>',
'Click <a href="javascript:alert(1)">here</a>',
'**<iframe src="https://example.org"></iframe>**',
'# <style>body{display:none}</style>',
'- <svg onload=alert(1)>',
'> </div><script src="https://example.org/x.js"></script>',
'```\n</code></pre><script>alert(1)</script>\n```',
'`</code><script>alert(1)</script>`',
'&lt;script&gt; &#60;b&#62;',
].join('\n\n');
const root = render(hostile);
const nodes = root.all();
for (const n of nodes) assert.ok(ALLOWED.has(n.tag), `unexpected element: ${n.tag}`);
for (const n of nodes) for (const k of Object.keys(n.attrs)) assert.ok(['role', 'tabindex', 'title', 'data-href'].includes(k), `unexpected attribute: ${k}`);
// Every character the model wrote is still there, as text.
const text = root.textContent;
for (const piece of ['<script>alert(1)</script>', '<img src=x onerror=alert(1)>', 'javascript:alert(1)', '<iframe src="', '<svg onload=alert(1)>', '&lt;script&gt; &#60;b&#62;']) {
assert.ok(text.includes(piece), `kept as text: ${piece}`);
}
});
test('only http, https and mailto become links, and a link never navigates by itself', () => {
const root = render(
'[site](https://example.org/a?b=c) [mail](mailto:person@example.org) [bad](javascript:alert(1)) [data](data:text/html,<b>) [file](file:///etc/passwd) [vs](vscode://x) [cmd](command:workbench.action.terminal.new) bare https://example.org/path. and ![pic](https://example.org/p.png)',
);
const links = root.all().filter((n) => n.attrs['data-href']);
assert.deepEqual(links.map((n) => n.attrs['data-href']), ['https://example.org/a?b=c', 'mailto:person@example.org', 'https://example.org/path', 'https://example.org/p.png']);
for (const n of links) {
assert.equal(n.tag, 'span', 'not an anchor: the extension is asked to open it');
assert.equal(n.attrs.href, undefined);
assert.equal(n.attrs.title, n.attrs['data-href'], 'the address is shown before it is opened');
}
assert.ok(!root.all().some((n) => n.tag === 'img' || n.tag === 'a'), 'a picture in a reply is a link, never loaded');
const text = root.textContent;
assert.ok(text.includes('[bad](javascript:alert(1))') && text.includes('[cmd](command:workbench.action.terminal.new)'));
});
test('what counts as a safe address', () => {
for (const ok of ['https://example.org', 'http://192.0.2.7:8080/x?y#z', 'HTTPS://EXAMPLE.ORG/', 'mailto:a@example.org']) assert.equal(safeHref(ok), ok);
for (const bad of ['javascript:alert(1)', ' https://example.org', 'https://exa mple.org', 'https://example.org/"onmouseover="x', 'data:text/html,x', 'file:///etc/passwd', 'command:x', 'vscode://file/x', '//example.org', 'https://', 'mailto:nobody', 'https://example.org/\u0000', 'ftp://example.org', '', null, 42, 'https://example.org/' + 'a'.repeat(3000)]) {
assert.equal(safeHref(bad), null, String(bad));
}
});
test('deeply nested or enormous input does not hang or overflow', () => {
const deep = '*a '.repeat(2000) + ' b*'.repeat(2000);
assert.ok(parseInline(deep).length > 0);
assert.ok(parse('> '.repeat(500) + 'x').length > 0);
assert.ok(parse('['.repeat(5000) + 'x' + ']'.repeat(5000) + '(https://example.org)').length > 0);
const big = ('word '.repeat(20) + '\n').repeat(5000);
const started = Date.now();
parse(big);
assert.ok(Date.now() - started < 2000);
assert.deepEqual(parse(''), []);
assert.deepEqual(parse(null), []);
});
test('an item of the transcript is drawn from its fields as text', () => {
const posted = [];
const post = (m) => posted.push(m);
const card = page.renderItem(doc, {
id: 'i7', kind: 'card', state: 'open', title: 'rm -rf <b>build</b>', tool: 'bash', reason: '<i>deletes</i> files', detail: '--- a\n+++ b',
files: ['/p/a.py'], options: [{ optionId: 'once', name: 'Allow <once>', kind: 'allow_once' }, { optionId: 'deny', name: 'Deny', kind: 'reject_once' }],
}, post);
for (const n of card.all()) assert.ok(['#text', 'div', 'pre', 'button'].includes(n.tag), n.tag);
assert.ok(card.textContent.includes('rm -rf <b>build</b>') && card.textContent.includes('<i>deletes</i> files'));
const buttons = card.all().filter((n) => n.tag === 'button');
assert.deepEqual(buttons.map((b) => b.textContent), ['Allow <once>', 'Deny', 'Show the change']);
buttons[1].listeners.click();
buttons[2].listeners.click();
assert.deepEqual(posted, [{ type: 'answer', card: 'i7', option: 'deny' }, { type: 'showDiff', card: 'i7' }]);
const closed = page.renderItem(doc, { id: 'i7', kind: 'card', state: 'answered', title: 't', answer: 'Deny', options: [{ optionId: 'once', name: 'Allow' }] }, post);
assert.equal(closed.all().filter((n) => n.tag === 'button').length, 0, 'an answered card has no buttons');
const user = page.renderItem(doc, { id: 'i1', kind: 'user', text: '<script>x</script>', label: 'a.py:1-2' }, post);
assert.ok(user.textContent.includes('<script>x</script>') && user.textContent.includes('[a.py:1-2]'));
assert.ok(!user.all().some((n) => n.tag === 'script'));
const picture = page.renderItem(doc, { id: 'i2', kind: 'media', picture: true, src: 'https://file.example/1-chart.png', name: 'chart.png', sizeWords: '5 KB', key: 'm1' }, post);
const img = picture.all().find((n) => n.tag === 'img');
assert.equal(img.attrs.src, 'https://file.example/1-chart.png');
assert.ok(picture.textContent.includes('chart.png (5 KB)'));
const other = page.renderItem(doc, { id: 'i3', kind: 'media', picture: false, name: 'report.pdf', key: 'm2' }, post);
assert.ok(!other.all().some((n) => n.tag === 'img'));
other.all().find((n) => n.tag === 'button').listeners.click();
assert.deepEqual(posted.pop(), { type: 'openMedia', key: 'm2' });
const unknown = page.renderItem(doc, { id: 'i4', kind: 'surprise<script>', text: 'x' }, post);
assert.equal(unknown.children.length, 0);
assert.equal(unknown.className, 'item surprisescript');
});
test("the page's script never parses markup and never evaluates text", () => {
const src = fs.readFileSync(path.join(__dirname, '..', 'media', 'chat.js'), 'utf8');
for (const banned of ['innerHTML', 'outerHTML', 'insertAdjacentHTML', 'document.write', 'eval(', 'new Function', 'DOMParser', 'srcdoc', 'setTimeout("', "setTimeout('"]) {
assert.ok(!src.includes(banned), `chat.js must not use ${banned}`);
}
});
test('the page: a strict policy, one script with a nonce, nothing from elsewhere', () => {
const html = chatHtml({ cspSource: 'https://file.example', nonce: 'abc123', scriptUri: 'https://file.example/media/chat.js', styleUri: 'https://file.example/media/chat.css' });
const csp = /<meta http-equiv="Content-Security-Policy" content="([^"]+)">/.exec(html)[1];
const rules = Object.fromEntries(csp.split('; ').map((r) => [r.split(' ')[0], r.split(' ').slice(1)]));
assert.deepEqual(rules['default-src'], ["'none'"]);
assert.deepEqual(rules['script-src'], ["'nonce-abc123'"]);
assert.deepEqual(rules['style-src'], ['https://file.example']);
assert.deepEqual(rules['img-src'], ['https://file.example']);
assert.ok(!/unsafe-inline|unsafe-eval|\*|data:|blob:|http:/.test(csp));
assert.equal((html.match(/<script/g) || []).length, 1);
assert.match(html, /<script nonce="abc123" src="https:\/\/file\.example\/media\/chat\.js"><\/script>/);
assert.ok(!/\son[a-z]+=/.test(html), 'no inline handlers');
assert.ok(!/style=/.test(html), 'no inline styles');
assert.throws(() => chatHtml({ cspSource: 'x', nonce: 'a"b', scriptUri: 's', styleUri: 't' }));
});
test('the stylesheet takes every colour from the editor\'s theme', () => {
const css = fs.readFileSync(path.join(__dirname, '..', 'media', 'chat.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
assert.ok(!/#[0-9a-fA-F]{3,8}\b/.test(css), 'no hex colours');
assert.ok(!/\b(rgb|rgba|hsl|hsla)\(/.test(css), 'no colour functions');
assert.ok(!/url\(|@import/.test(css), 'nothing loaded from a stylesheet');
for (const m of css.matchAll(/(?:^|[;{\s])(color|background|background-color|border(?:-[a-z]+)*|outline)\s*:\s*([^;}]+)/g)) {
const value = m[2].trim();
if (/^(0|none|transparent|inherit)$/.test(value)) continue;
const colourless = value.replace(/var\(--vscode-[A-Za-z0-9-]+(?:,\s*(?:transparent|var\(--vscode-[A-Za-z0-9-]+\)))?\)/g, '').replace(/\b(\d+(\.\d+)?(px|em)?|solid|transparent)\b/g, '').trim();
assert.equal(colourless, '', `${m[1]}: ${value}`);
}
});
+76
View File
@@ -0,0 +1,76 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const crypto = require('node:crypto');
const { sniffPicture, sizeInWords, safeName, mayRun, fetchShown } = require('../src/media');
test('a picture is known by its bytes, not by its name or by what the agent calls it', () => {
const pad = Buffer.alloc(16);
assert.equal(sniffPicture(Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), pad])).mime, 'image/png');
assert.equal(sniffPicture(Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), pad])).ext, 'jpg');
assert.equal(sniffPicture(Buffer.concat([Buffer.from('GIF89a'), pad])).mime, 'image/gif');
assert.equal(sniffPicture(Buffer.concat([Buffer.from('RIFF\x10\x00\x00\x00WEBPVP8 '), pad])).mime, 'image/webp');
assert.equal(sniffPicture(Buffer.concat([Buffer.from('\x00\x00\x00\x1cftypavif', 'latin1'), pad])).mime, 'image/avif');
for (const not of ['<svg xmlns="http://www.w3.org/2000/svg"><script/></svg>', '<!DOCTYPE html><html>', '%PDF-1.7 and more bytes', 'RIFF\x10\x00\x00\x00WAVEfmt ', 'short', '']) {
assert.equal(sniffPicture(Buffer.from(not, 'latin1')), null, not);
}
assert.equal(sniffPicture(null), null);
});
test('sizes are said in words', () => {
assert.equal(sizeInWords(1), '1 byte');
assert.equal(sizeInWords(640), '640 bytes');
assert.equal(sizeInWords(48211), '47 KB');
assert.equal(sizeInWords(1.5 * 1024 * 1024), '1.5 MB');
assert.equal(sizeInWords(64 * 1024 * 1024), '64 MB');
assert.equal(sizeInWords(3 * 1024 * 1024 * 1024), '3.0 GB');
});
test('a file name is made harmless', () => {
assert.equal(safeName('out/chart.png'), 'chart.png');
assert.equal(safeName('C:\\Users\\person\\shot 1.PNG'), 'shot_1.PNG');
assert.equal(safeName('../../.bashrc'), 'bashrc');
assert.equal(safeName('a/b/"; rm -rf ~ #.txt'), '___rm_-rf____.txt');
assert.equal(safeName('', 'bin'), 'file.bin');
assert.equal(safeName('noext', 'png'), 'noext.png');
assert.ok(safeName('x'.repeat(500) + '.png').length <= 80);
});
test('files the system might run are never opened for the person', () => {
for (const name of ['run.sh', 'setup.EXE', 'a.desktop', 'page.html', 'pic.svg', 'x.jar', 'tool.py', 'noending', 'x.AppImage']) assert.equal(mayRun(name), true, name);
for (const name of ['report.pdf', 'sound.mp3', 'clip.mp4', 'data.csv', 'model.glb', 'archive.zip', 'notes.txt']) assert.equal(mayRun(name), false, name);
});
function reader(bytes, part) {
const calls = [];
const read = async (p) => {
calls.push(p);
const chunk = bytes.subarray(p.offset, p.offset + Math.min(p.length, part));
return { data: chunk.toString('base64'), offset: p.offset, eof: p.offset + chunk.length >= bytes.length };
};
return { read, calls };
}
test('a file is read part by part to its end and checked', async () => {
const bytes = crypto.randomBytes(10500);
const hash = 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
const { read, calls } = reader(bytes, 4000);
const got = await fetchShown(read, { handle: 'h_1', size: bytes.length, hash }, { maxBytes: 1e6 });
assert.ok(got.equals(bytes));
assert.deepEqual(calls.map((c) => c.offset), [0, 4000, 8000]);
assert.ok(calls.every((c) => c.handle === 'h_1' && c.length === 1024 * 1024));
});
test('too large, cut short, the wrong size or the wrong checksum are refused in words', async () => {
const bytes = crypto.randomBytes(5000);
const { read, calls } = reader(bytes, 1000);
await assert.rejects(fetchShown(read, { handle: 'h', size: 5000 }, { maxBytes: 4096 }), /The file is 5 KB; this editor takes files of up to 4 KB\./);
assert.equal(calls.length, 0, 'a size over the limit is refused before anything is read');
// The agent named no size, or a false one: the limit holds while reading.
await assert.rejects(fetchShown(read, { handle: 'h' }, { maxBytes: 2500 }), /this editor takes files of up to 2 KB/);
await assert.rejects(fetchShown(read, { handle: 'h', size: 100 }, { maxBytes: 1e6 }), /arrived as 5 KB, not the 100 bytes/);
await assert.rejects(fetchShown(read, { handle: 'h', hash: 'sha256:' + 'a'.repeat(64) }, { maxBytes: 1e6 }), /checksum differs/);
await assert.rejects(fetchShown(async () => ({ data: '', eof: false }), { handle: 'h' }, { maxBytes: 1e6 }), /stopped sending/);
await assert.rejects(fetchShown(async () => ({}), { handle: 'h' }, { maxBytes: 1e6 }), /sent no data/);
await assert.rejects(fetchShown(async () => { throw new Error('This file is no longer offered.'); }, { handle: 'h' }, { maxBytes: 1e6 }), /no longer offered/);
});
+92
View File
@@ -0,0 +1,92 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const { Rpc, RpcError } = require('../src/rpc');
function pair(handlers) {
const sent = [];
const rpc = new Rpc({ write: (line) => sent.push(line), ...(handlers || {}) });
return { rpc, sent, last: () => JSON.parse(sent[sent.length - 1]) };
}
test('a request is one line of JSON-RPC 2.0 and its answer resolves it', async () => {
const { rpc, sent, last } = pair();
const p = rpc.request('initialize', { protocolVersion: 1 });
assert.equal(sent.length, 1);
assert.ok(sent[0].endsWith('\n') && !sent[0].slice(0, -1).includes('\n'));
assert.deepEqual(last(), { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: 1 } });
rpc.feed('{"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n');
assert.deepEqual(await p, { ok: true });
});
test('messages split across chunks, several in one chunk, and a character split in two', async () => {
const got = [];
const { rpc } = pair({ onNotify: (m, p) => got.push([m, p]) });
const line = Buffer.from('{"jsonrpc":"2.0","method":"note","params":{"t":"žluťoučký 🍞"}}\n');
const cut = line.indexOf(0xf0) + 2; // inside the four bytes of the bread
rpc.feed(line.subarray(0, cut));
assert.equal(got.length, 0);
rpc.feed(Buffer.concat([line.subarray(cut), line, Buffer.from('\n \n')]));
assert.equal(got.length, 2);
assert.equal(got[0][1].t, 'žluťoučký 🍞');
});
test('a line that is not JSON, or not an object, is skipped', () => {
const got = [];
const { rpc } = pair({ onNotify: (m) => got.push(m) });
rpc.feed('warming up...\n[1,2]\n"text"\n{"jsonrpc":"2.0","method":"ok"}\n');
assert.deepEqual(got, ['ok']);
});
test('an error answer rejects with its code, message and reason', async () => {
const { rpc } = pair();
const p = rpc.request('_lembas/complete', {});
rpc.feed('{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"No autocomplete model is chosen.","data":{"reason":"no_model"}}}\n');
await assert.rejects(p, (e) => e instanceof RpcError && e.code === -32602 && e.reason === 'no_model' && /No autocomplete/.test(e.message));
});
test('a request from the other side is answered: a value, a promise, a refusal, a throw', async () => {
const { rpc, sent } = pair({
onRequest: (method, params) => {
if (method === 'value') return { echo: params.x };
if (method === 'later') return new Promise((r) => setTimeout(() => r('done'), 5));
if (method === 'refuse') throw { code: -32002, message: 'cannot read', data: { reason: 'missing' } };
if (method === 'nothing') return undefined;
throw new Error('boom');
},
});
rpc.feed('{"jsonrpc":"2.0","id":"a","method":"value","params":{"x":7}}\n');
rpc.feed('{"jsonrpc":"2.0","id":2,"method":"later"}\n');
rpc.feed('{"jsonrpc":"2.0","id":3,"method":"refuse"}\n');
rpc.feed('{"jsonrpc":"2.0","id":4,"method":"nothing"}\n');
rpc.feed('{"jsonrpc":"2.0","id":5,"method":"other"}\n');
await new Promise((r) => setTimeout(r, 30));
const byId = Object.fromEntries(sent.map((l) => JSON.parse(l)).map((m) => [m.id, m]));
assert.deepEqual(byId.a.result, { echo: 7 });
assert.equal(byId[2].result, 'done');
assert.deepEqual(byId[3].error, { code: -32002, message: 'cannot read', data: { reason: 'missing' } });
assert.equal(byId[4].result, null);
assert.equal(byId[5].error.code, -32603);
assert.match(byId[5].error.message, /boom/);
});
test('without a handler a request is method-not-found', () => {
const { rpc, last } = pair();
rpc.feed('{"jsonrpc":"2.0","id":9,"method":"_lembas/question"}\n');
assert.equal(last().error.code, -32601);
});
test('closing fails everything waited for, and later requests too', async () => {
const { rpc, sent } = pair();
const p = rpc.request('session/prompt', {});
rpc.close('the agent stopped (exit 3)');
await assert.rejects(p, /the agent stopped \(exit 3\)/);
await assert.rejects(rpc.request('x', {}), /not running/);
rpc.notify('y', {});
assert.equal(sent.length, 1);
});
test('an answer nobody waits for is ignored', () => {
const { rpc } = pair();
rpc.feed('{"jsonrpc":"2.0","id":77,"result":1}\n');
});
+385
View File
@@ -0,0 +1,385 @@
'use strict';
// A stand-in for the `vscode` module, for tests/extension.test.js: just enough of the editor's
// API, in memory, for extension.js to be loaded and driven. It is NOT VS Code — what passes
// here shows that the glue code runs and calls the API the way it means to, not that the
// editor behaves that way.
const path = require('node:path');
class Position {
constructor(line, character) {
this.line = line;
this.character = character;
}
}
class Range {
constructor(a, b, c, d) {
if (a instanceof Position) {
this.start = a;
this.end = b;
} else {
this.start = new Position(a, b);
this.end = new Position(c, d);
}
}
get isEmpty() {
return this.start.line === this.end.line && this.start.character === this.end.character;
}
}
class Selection extends Range {
constructor(a, b, c, d) {
super(a, b, c, d);
this.anchor = this.start;
this.active = this.end;
}
}
class Uri {
constructor(scheme, p) {
this.scheme = scheme;
this.path = p;
}
get fsPath() {
return this.path;
}
toString() {
return `${this.scheme}:${this.scheme === 'file' ? '//' : ''}${this.path}`;
}
static file(p) {
return new Uri('file', p);
}
static from(o) {
return new Uri(o.scheme, o.path);
}
static parse(text) {
const m = /^([a-z][a-z0-9+.-]*):(.*)$/i.exec(text);
return new Uri(m[1], m[2]);
}
static joinPath(base, ...parts) {
return new Uri(base.scheme, path.posix.join(base.path, ...parts));
}
}
class EventEmitter {
constructor() {
this.listeners = [];
this.event = (fn) => {
this.listeners.push(fn);
return { dispose: () => (this.listeners = this.listeners.filter((l) => l !== fn)) };
};
}
fire(value) {
for (const l of this.listeners.slice()) l(value);
}
}
class TextDocument {
constructor(uri, text, languageId) {
this.uri = uri;
this.languageId = languageId || 'plaintext';
this.version = 1;
this.eol = 1;
this.isClosed = false;
this.text = text;
}
get lines() {
return this.text.split('\n');
}
get lineCount() {
return this.lines.length;
}
lineAt(i) {
const text = this.lines[i];
if (text === undefined) throw new Error('no line ' + i);
return { text, range: new Range(i, 0, i, text.length) };
}
offsetAt(pos) {
const lines = this.lines;
let offset = 0;
for (let i = 0; i < Math.min(pos.line, lines.length); i++) offset += lines[i].length + 1;
return Math.min(this.text.length, offset + Math.min(pos.character, (lines[pos.line] || '').length));
}
positionAt(offset) {
const before = this.text.slice(0, Math.max(0, Math.min(offset, this.text.length))).split('\n');
return new Position(before.length - 1, before[before.length - 1].length);
}
getText(range) {
return range ? this.text.slice(this.offsetAt(range.start), this.offsetAt(range.end)) : this.text;
}
}
class TextEditor {
constructor(document, selection) {
this.document = document;
this.selection = selection || new Selection(0, 0, 0, 0);
this.decorations = new Map();
}
setDecorations(type, list) {
this.decorations.set(type, list);
}
}
class WorkspaceEdit {
constructor() {
this.edits = [];
}
replace(uri, range, text) {
this.edits.push({ uri, range, text });
}
}
class MarkdownString {
constructor() {
this.value = '';
}
appendText(t) {
this.value += t;
return this;
}
appendCodeblock(code, lang) {
this.value += '\n```' + (lang || '') + '\n' + code + '\n```\n';
return this;
}
}
class TabInputText {
constructor(uri) {
this.uri = uri;
}
}
class TabInputTextDiff {
constructor(original, modified) {
this.original = original;
this.modified = modified;
}
}
function make(pkg) {
const state = {
config: {}, // 'llembas.command' -> value
inputs: [], // answers to showInputBox, in order
picks: [], // functions (items) => item, answers to showQuickPick, in order
answers: [], // answers to show…Message, in order (undefined: dismissed)
messages: [], // { level, text, buttons }
executed: [], // commands of the editor's own that were run
external: [],
commands: new Map(),
contentProviders: new Map(),
viewProviders: new Map(),
inlineProviders: [],
lensProviders: [],
statusItems: [],
output: [],
diagnostics: new Map(),
tabs: [],
changed: new EventEmitter(),
closed: new EventEmitter(),
configured: new EventEmitter(),
visible: new EventEmitter(),
active: new EventEmitter(),
};
const defaults = {};
for (const [key, def] of Object.entries(pkg.contributes.configuration.properties)) defaults[key] = def.default;
const message = (level) => (text, ...buttons) => {
state.messages.push({ level, text, buttons: buttons.filter((b) => typeof b === 'string') });
return Promise.resolve(state.answers.length ? state.answers.shift() : undefined);
};
const api = {
__: state,
Position,
Range,
Selection,
Uri,
EventEmitter,
WorkspaceEdit,
MarkdownString,
TabInputText,
TabInputTextDiff,
TextDocument,
TextEditor,
ThemeColor: class {
constructor(id) {
this.id = id;
}
},
CodeLens: class {
constructor(range, command) {
this.range = range;
this.command = command;
}
},
InlineCompletionItem: class {
constructor(insertText, range) {
this.insertText = insertText;
this.range = range;
}
},
EndOfLine: { LF: 1, CRLF: 2 },
OverviewRulerLane: { Left: 1 },
StatusBarAlignment: { Left: 1, Right: 2 },
ProgressLocation: { Notification: 15 },
ViewColumn: { Beside: -2 },
InlineCompletionTriggerKind: { Invoke: 0, Automatic: 1 },
DiagnosticSeverity: { Error: 0, Warning: 1, Information: 2, Hint: 3 },
workspace: {
workspaceFolders: undefined,
textDocuments: [],
getConfiguration: (section) => ({
get: (key) => {
const full = `${section}.${key}`;
if (!(full in defaults)) throw new Error('a setting that is not declared: ' + full);
return full in state.config ? state.config[full] : defaults[full];
},
}),
registerTextDocumentContentProvider: (scheme, provider) => {
state.contentProviders.set(scheme, provider);
return { dispose() {} };
},
onDidChangeTextDocument: state.changed.event,
onDidCloseTextDocument: state.closed.event,
onDidChangeConfiguration: state.configured.event,
asRelativePath: (uri) => path.basename(uri.path),
openTextDocument: async (what) => {
const doc = what instanceof Uri ? new TextDocument(what, require('node:fs').readFileSync(what.fsPath, 'utf8')) : new TextDocument(new Uri('untitled', 'Untitled-1'), what.content);
api.workspace.textDocuments.push(doc);
return doc;
},
applyEdit: async (edit) => {
// Every range is against the text as it was; applied from the end of the text backwards.
const byDoc = new Map();
for (const e of edit.edits) {
const doc = api.workspace.textDocuments.find((d) => d.uri.toString() === e.uri.toString());
if (!doc) return false;
if (!byDoc.has(doc)) byDoc.set(doc, []);
byDoc.get(doc).push({ from: doc.offsetAt(e.range.start), to: doc.offsetAt(e.range.end), text: e.text, range: e.range });
}
for (const [doc, edits] of byDoc) {
edits.sort((a, b) => b.from - a.from);
for (let i = 1; i < edits.length; i++) if (edits[i].to > edits[i - 1].from) throw new Error('overlapping edits');
for (const e of edits) doc.text = doc.text.slice(0, e.from) + e.text + doc.text.slice(e.to);
doc.version += 1;
state.changed.fire({ document: doc, contentChanges: edits.map((e) => ({ range: e.range, text: e.text })) });
}
return true;
},
},
window: {
activeTextEditor: undefined,
visibleTextEditors: [],
tabGroups: {
get all() {
return [{ tabs: state.tabs }];
},
close: async (tabs) => {
state.tabs = state.tabs.filter((t) => !tabs.includes(t));
return true;
},
},
createOutputChannel: () => ({ append: (t) => state.output.push(t), appendLine: (t) => state.output.push(t + '\n'), dispose() {} }),
registerWebviewViewProvider: (id, provider, options) => {
state.viewProviders.set(id, { provider, options });
return { dispose() {} };
},
createTextEditorDecorationType: (options) => ({ options, dispose() {} }),
createStatusBarItem: () => {
const item = { text: '', tooltip: '', command: '', shown: false, show: () => (item.shown = true), dispose() {} };
state.statusItems.push(item);
return item;
},
showInputBox: async () => state.inputs.shift(),
showQuickPick: async (items, options) => {
const pick = state.picks.shift();
if (!pick) return undefined;
const chosen = pick(items, options);
if (chosen === undefined) throw new Error('the test picked nothing from: ' + items.map((i) => i.label).join(', '));
return chosen;
},
showInformationMessage: message('info'),
showWarningMessage: message('warning'),
showErrorMessage: message('error'),
showTextDocument: async (doc) => {
state.executed.push(['showTextDocument', doc]);
return new TextEditor(doc);
},
withProgress: (options, task) => {
const cancel = new EventEmitter();
state.cancelProgress = () => cancel.fire();
return task({ report: (r) => state.executed.push(['progress', r.message]) }, { onCancellationRequested: cancel.event, isCancellationRequested: false });
},
onDidChangeVisibleTextEditors: state.visible.event,
onDidChangeActiveTextEditor: state.active.event,
},
commands: {
registerCommand: (name, fn) => {
state.commands.set(name, fn);
return { dispose() {} };
},
executeCommand: async (name, ...args) => {
if (state.commands.has(name)) return state.commands.get(name)(...args);
state.executed.push([name, ...args]);
if (name === 'vscode.diff') state.tabs.push({ input: new TabInputTextDiff(args[0], args[1]), label: args[2] });
return undefined;
},
},
languages: {
registerInlineCompletionItemProvider: (selector, provider) => {
state.inlineProviders.push(provider);
return { dispose() {} };
},
registerCodeLensProvider: (selector, provider) => {
state.lensProviders.push(provider);
return { dispose() {} };
},
getDiagnostics: (uri) => state.diagnostics.get(uri.toString()) || [],
},
env: {
openExternal: async (uri) => {
state.external.push(uri.toString());
return true;
},
},
};
/** Open a document in an editor, in front. */
api.__.open = (file, text, selection, languageId) => {
const doc = new TextDocument(typeof file === 'string' ? Uri.file(file) : file, text, languageId);
const editor = new TextEditor(doc, selection);
api.workspace.textDocuments.push(doc);
api.window.visibleTextEditors.push(editor);
api.window.activeTextEditor = editor;
state.tabs.push({ input: new TabInputText(doc.uri) });
return editor;
};
/** A view of the chat: what the page was sent is `view.posted`; `view.say(m)` is the page speaking. */
api.__.view = () => {
const posted = [];
let listener = () => {};
const view = {
posted,
shows: [],
webview: {
options: null,
html: '',
cspSource: 'https://file.example',
asWebviewUri: (uri) => Uri.parse('https://file.example' + uri.path),
postMessage: async (m) => {
posted.push(JSON.parse(JSON.stringify(m)));
return true;
},
onDidReceiveMessage: (fn) => {
listener = fn;
},
},
show: (preserveFocus) => view.shows.push(preserveFocus),
onDidDispose: () => {},
say: (m) => listener(m),
};
return view;
};
return api;
}
module.exports = { make };
+177
View File
@@ -0,0 +1,177 @@
'use strict';
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { execFileSync, spawnSync } = require('node:child_process');
const { zip, unzip, crc32 } = require('../tools/zip');
const { tempDir } = require('./helpers');
const ROOT = path.join(__dirname, '..');
const REPO = path.join(ROOT, '..');
const VERSION = fs.readFileSync(path.join(REPO, 'VERSION'), 'utf8').trim();
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
/** Whether a text is well-formed XML as far as elements and attributes go; returns its elements. */
function elements(xml) {
const out = [];
const stack = [];
const body = xml.replace(/^<\?xml[^?]*\?>\s*/, '');
assert.ok(!/<\?|<!/.test(body), 'no processing instructions, doctypes or comments');
const re = /<(\/?)([A-Za-z_][\w:.-]*)((?:\s+[\w:.-]+="[^"<]*")*)\s*(\/?)>|([^<]+)/g;
let at = 0;
for (let m; (m = re.exec(body)); ) {
assert.equal(m.index, at, 'nothing unreadable at ' + at);
at = re.lastIndex;
if (m[5] !== undefined) {
assert.ok(!/&(?!(amp|lt|gt|quot|apos);)/.test(m[5]), 'text is escaped');
if (stack.length) stack[stack.length - 1].text += m[5];
else assert.equal(m[5].trim(), '');
continue;
}
if (m[1]) {
assert.equal(stack.pop().name, m[2], 'closing tag matches');
continue;
}
const attrs = {};
for (const a of m[3].matchAll(/([\w:.-]+)="([^"]*)"/g)) attrs[a[1]] = a[2].replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
const el = { name: m[2], attrs, text: '' };
out.push(el);
if (!m[4]) stack.push(el);
}
assert.equal(at, body.length);
assert.equal(stack.length, 0, 'every element is closed');
return out;
}
test('the archive writer and reader agree, and with the system\'s unzip', (t) => {
const files = [
{ name: 'a.txt', data: Buffer.from('hello\n'.repeat(100)) },
{ name: 'dir/ž 🍞.bin', data: Buffer.from([0, 1, 2, 3, 255]) },
{ name: 'empty', data: Buffer.alloc(0) },
];
const archive = zip(files);
assert.deepEqual(unzip(archive).map((f) => [f.name, f.data.toString('hex')]), files.map((f) => [f.name, f.data.toString('hex')]));
assert.ok(archive.equals(zip(files)), 'the same input gives the same archive');
assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926);
assert.throws(() => zip([{ name: '../x', data: Buffer.alloc(0) }]));
assert.throws(() => zip([{ name: 'a', data: Buffer.alloc(0) }, { name: 'a', data: Buffer.alloc(0) }]));
const damaged = Buffer.from(archive);
damaged[40] ^= 0xff;
assert.throws(() => unzip(damaged));
if (spawnSync('unzip', ['-v']).status === 0) {
const file = path.join(tempDir(t), 'x.zip');
fs.writeFileSync(file, archive);
assert.match(execFileSync('unzip', ['-t', file], { encoding: 'utf8' }), /No errors detected/);
}
});
test('the package script builds a .vsix that is what an editor expects', (t) => {
const out = tempDir(t);
const said = execFileSync('sh', [path.join(REPO, 'scripts', 'package-vscode.sh'), out], { encoding: 'utf8' });
const file = path.join(out, `llembas-${VERSION}.vsix`);
assert.ok(said.startsWith(file + '\n'), said);
const entries = unzip(fs.readFileSync(file));
const names = entries.map((e) => e.name);
const get = (name) => entries.find((e) => e.name === name).data.toString('utf8');
// The three things a .vsix is.
assert.ok(names.includes('[Content_Types].xml') && names.includes('extension.vsixmanifest') && names.includes('extension/package.json'));
assert.ok(names.every((n) => n === '[Content_Types].xml' || n === 'extension.vsixmanifest' || n.startsWith('extension/')), 'nothing outside extension/');
// The manifest: well-formed, and it says the repository's version and this extension's identity.
const manifest = elements(get('extension.vsixmanifest'));
assert.equal(manifest[0].name, 'PackageManifest');
assert.equal(manifest[0].attrs.xmlns, 'http://schemas.microsoft.com/developer/vsx-schema/2011');
const identity = manifest.find((e) => e.name === 'Identity');
assert.deepEqual(identity.attrs, { Language: 'en-US', Id: 'llembas', Version: VERSION, Publisher: 'llembas' });
assert.equal(manifest.find((e) => e.name === 'DisplayName').text, 'LLeMbas');
const prop = (id) => manifest.find((e) => e.name === 'Property' && e.attrs.Id === id).attrs.Value;
assert.equal(prop('Microsoft.VisualStudio.Code.Engine'), pkg.engines.vscode);
assert.equal(prop('Microsoft.VisualStudio.Code.ExtensionKind'), 'workspace');
assert.equal(manifest.find((e) => e.name === 'InstallationTarget').attrs.Id, 'Microsoft.VisualStudio.Code');
const assets = manifest.filter((e) => e.name === 'Asset');
assert.equal(assets.find((a) => a.attrs.Type === 'Microsoft.VisualStudio.Code.Manifest').attrs.Path, 'extension/package.json');
for (const a of assets) assert.ok(names.includes(a.attrs.Path), `the asset ${a.attrs.Path} is in the package`);
assert.ok(names.includes(manifest.find((e) => e.name === 'License').text));
// The content types name every kind of file in the package.
const types = elements(get('[Content_Types].xml'));
assert.equal(types[0].attrs.xmlns, 'http://schemas.openxmlformats.org/package/2006/content-types');
const known = new Set(types.filter((e) => e.name === 'Default').map((e) => e.attrs.Extension));
for (const n of names) if (n !== '[Content_Types].xml') assert.ok(known.has(path.extname(n)), `a content type for ${n}`);
// The packaged manifest of the extension: the version written in, everything it points at present.
const packed = JSON.parse(get('extension/package.json'));
assert.equal(packed.version, VERSION);
assert.deepEqual({ ...packed, version: pkg.version }, pkg, 'otherwise the source manifest, unchanged');
assert.ok(names.includes('extension/' + packed.main.replace(/^\.\//, '')));
assert.ok(names.includes('extension/' + packed.contributes.viewsContainers.activitybar[0].icon));
for (const need of ['extension/README.md', 'extension/LICENSE.txt', 'extension/media/chat.js', 'extension/media/chat.css', 'extension/src/rpc.js']) assert.ok(names.includes(need), need);
assert.equal(get('extension/LICENSE.txt'), fs.readFileSync(path.join(REPO, 'LICENSE'), 'utf8'));
// Every module the code asks for is in the package, or is Node's or the editor's own.
for (const e of entries.filter((x) => x.name.endsWith('.js') && !x.name.startsWith('extension/media/'))) {
for (const m of e.data.toString('utf8').matchAll(/require\('([^']+)'\)/g)) {
if (m[1] === 'vscode' || m[1].startsWith('node:')) continue;
assert.ok(m[1].startsWith('.'), `${e.name} asks for ${m[1]}: no outside packages`);
const target = path.posix.normalize(path.posix.join(path.posix.dirname(e.name), m[1])) + (m[1].endsWith('.js') ? '' : '.js');
assert.ok(names.includes(target), `${e.name} asks for ${target}`);
}
}
// What does not ship.
assert.ok(!names.some((n) => /\/(tests|tools|node_modules)\//.test(n)), 'no tests, tools or packages');
assert.ok(!names.some((n) => /fake_agent|\.test\.js$|\.vsix$/.test(n)));
if (spawnSync('unzip', ['-v']).status === 0) {
assert.match(execFileSync('unzip', ['-t', file], { encoding: 'utf8' }), /No errors detected/);
}
});
test('the manifest in the source tree: no dependencies, no build, the version only in VERSION', () => {
assert.equal(pkg.version, '0.0.0', 'a placeholder: the package script writes the real one');
assert.match(VERSION, /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/);
for (const key of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies', 'scripts', 'extensionDependencies']) {
assert.equal(pkg[key], undefined, `no ${key}`);
}
assert.match(pkg.engines.vscode, /^\^1\.\d+\.0$/);
assert.ok(pkg.activationEvents.length > 0);
assert.equal(pkg.contributes.configuration.properties['llembas.command'].scope, 'machine', 'a folder cannot say which program is started');
assert.equal(pkg.capabilities.untrustedWorkspaces.supported, false);
for (const file of fs.readdirSync(ROOT, { recursive: true })) {
if (!/\.(js|json|css|md|py)$/.test(file) || /node_modules/.test(file)) continue;
if (file === path.join('tests', 'vsix.test.js')) continue;
const text = fs.readFileSync(path.join(ROOT, file), 'utf8');
assert.ok(!text.includes(VERSION), `${file} repeats the version`);
}
});
test('every command, key and menu entry names a command the extension registers, and the other way round', () => {
const source = fs.readFileSync(path.join(ROOT, 'extension.js'), 'utf8');
const registered = new Set([...source.matchAll(/command\('(llembas\.[A-Za-z]+)'/g)].map((m) => m[1]));
const contributed = new Set(pkg.contributes.commands.map((c) => c.command));
assert.deepEqual([...registered].sort(), [...contributed].sort());
for (const k of pkg.contributes.keybindings) assert.ok(contributed.has(k.command), k.command);
for (const list of Object.values(pkg.contributes.menus)) for (const m of list) assert.ok(contributed.has(m.command), m.command);
// Every setting the code reads is declared, and every declared setting is read.
const read = new Set([...source.matchAll(/config\(\)\.get\('([A-Za-z.]+)'\)/g)].map((m) => 'llembas.' + m[1]));
assert.deepEqual([...read].sort(), Object.keys(pkg.contributes.configuration.properties).sort());
assert.ok(source.includes(`const VIEW_ID = '${pkg.contributes.views.llembas[0].id}'`));
});
test('the modules that are tested without an editor do not ask for one, and nothing reaches the network', () => {
for (const dir of ['src', 'tools', 'media']) {
for (const file of fs.readdirSync(path.join(ROOT, dir))) {
if (!file.endsWith('.js')) continue;
const text = fs.readFileSync(path.join(ROOT, dir, file), 'utf8');
assert.ok(!/require\(['"]vscode['"]\)/.test(text), `${dir}/${file} must not import vscode`);
}
}
for (const file of ['extension.js', ...fs.readdirSync(path.join(ROOT, 'src')).map((f) => 'src/' + f), 'media/chat.js']) {
const text = fs.readFileSync(path.join(ROOT, file), 'utf8');
for (const banned of ["require('node:http')", "require('node:https')", "require('node:net')", "require('http')", "require('https')", 'fetch(', 'XMLHttpRequest', 'WebSocket', 'telemetry', 'eval(', 'new Function']) {
assert.ok(!text.includes(banned), `${file} must not use ${banned}`);
}
}
});
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env node
'use strict';
// Builds the extension's .vsix without any packaging tool. A .vsix is a zip that holds
// `[Content_Types].xml`, `extension.vsixmanifest` and the extension itself under `extension/`.
// The version comes from the repository's VERSION file and is written into the packaged
// manifest; nothing in the source tree repeats it.
//
// node vscode/tools/vsix.js [output directory] (default: dist/)
const fs = require('node:fs');
const path = require('node:path');
const { zip } = require('./zip');
const ROOT = path.resolve(__dirname, '..');
const REPO = path.resolve(ROOT, '..');
// What ships: the code, the view's files and the read-me. Tests and tools stay behind.
const SHIPPED = ['extension.js', 'README.md', 'src', 'media'];
const SEMVER = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
function xml(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
function walk(dir, base, out) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
const full = path.join(dir, entry.name);
const rel = base ? base + '/' + entry.name : entry.name;
if (entry.isDirectory()) walk(full, rel, out);
else if (entry.isFile()) out.push({ name: rel, data: fs.readFileSync(full) });
}
return out;
}
function manifestXml(pkg) {
const kinds = Array.isArray(pkg.extensionKind) ? pkg.extensionKind.join(',') : 'workspace';
return `<?xml version="1.0" encoding="utf-8"?>
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
<Metadata>
<Identity Language="en-US" Id="${xml(pkg.name)}" Version="${xml(pkg.version)}" Publisher="${xml(pkg.publisher)}" />
<DisplayName>${xml(pkg.displayName || pkg.name)}</DisplayName>
<Description xml:space="preserve">${xml(pkg.description || '')}</Description>
<Tags>${xml((pkg.keywords || []).join(','))}</Tags>
<Categories>${xml((pkg.categories || []).join(','))}</Categories>
<GalleryFlags>Public</GalleryFlags>
<Properties>
<Property Id="Microsoft.VisualStudio.Code.Engine" Value="${xml(pkg.engines.vscode)}" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionDependencies" Value="" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionPack" Value="" />
<Property Id="Microsoft.VisualStudio.Code.ExtensionKind" Value="${xml(kinds)}" />
<Property Id="Microsoft.VisualStudio.Code.LocalizedLanguages" Value="" />
<Property Id="Microsoft.VisualStudio.Services.GitHubFlavoredMarkdown" Value="true" />
<Property Id="Microsoft.VisualStudio.Services.Content.Pricing" Value="Free" />
</Properties>
<License>extension/LICENSE.txt</License>
</Metadata>
<Installation>
<InstallationTarget Id="Microsoft.VisualStudio.Code" />
</Installation>
<Dependencies />
<Assets>
<Asset Type="Microsoft.VisualStudio.Code.Manifest" Path="extension/package.json" Addressable="true" />
<Asset Type="Microsoft.VisualStudio.Services.Content.Details" Path="extension/README.md" Addressable="true" />
<Asset Type="Microsoft.VisualStudio.Services.Content.License" Path="extension/LICENSE.txt" Addressable="true" />
</Assets>
</PackageManifest>
`;
}
const TYPES = {
'.json': 'application/json',
'.vsixmanifest': 'text/xml',
'.js': 'application/javascript',
'.css': 'text/css',
'.md': 'text/markdown',
'.txt': 'text/plain',
'.svg': 'image/svg+xml',
};
function contentTypesXml(names) {
const used = new Set(['.vsixmanifest']);
for (const n of names) used.add(path.extname(n).toLowerCase());
const lines = [];
for (const ext of [...used].sort()) {
if (!TYPES[ext]) throw new Error(`a file of a kind the package does not know: ${ext || '(no ending)'}`);
lines.push(`<Default Extension="${ext}" ContentType="${TYPES[ext]}" />`);
}
return `<?xml version="1.0" encoding="utf-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${lines.join('')}</Types>\n`;
}
/** The files of the archive, in order, and the manifest they were made from. */
function build(options) {
const root = (options && options.root) || ROOT;
const repo = (options && options.repo) || REPO;
const version = fs.readFileSync(path.join(repo, 'VERSION'), 'utf8').trim();
if (!SEMVER.test(version)) throw new Error(`VERSION is not a version: ${version}`);
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
pkg.version = version;
const files = [{ name: 'package.json', data: Buffer.from(JSON.stringify(pkg, null, 2) + '\n') }];
for (const item of SHIPPED) {
const full = path.join(root, item);
if (fs.statSync(full).isDirectory()) walk(full, item, files);
else files.push({ name: item, data: fs.readFileSync(full) });
}
files.push({ name: 'LICENSE.txt', data: fs.readFileSync(path.join(repo, 'LICENSE')) });
// Everything the manifest points at has to be in the package.
const have = new Set(files.map((f) => f.name));
const main = String(pkg.main || '').replace(/^\.\//, '');
for (const need of [main, 'README.md', 'LICENSE.txt']) if (!have.has(need)) throw new Error('missing from the package: ' + need);
const entries = [
{ name: 'extension.vsixmanifest', data: Buffer.from(manifestXml(pkg)) },
{ name: '[Content_Types].xml', data: Buffer.from(contentTypesXml(files.map((f) => f.name))) },
...files.map((f) => ({ name: 'extension/' + f.name, data: f.data })),
];
return { pkg, version, entries, fileName: `${pkg.name}-${version}.vsix` };
}
function main() {
const outDir = path.resolve(process.argv[2] || path.join(REPO, 'dist'));
const built = build();
fs.mkdirSync(outDir, { recursive: true });
const out = path.join(outDir, built.fileName);
const archive = zip(built.entries);
fs.writeFileSync(out, archive);
process.stdout.write(`${out}\n${built.entries.length} files, ${archive.length} bytes, version ${built.version}\n`);
}
if (require.main === module) {
try {
main();
} catch (e) {
process.stderr.write(`package-vscode: ${e.message}\n`);
process.exit(1);
}
}
module.exports = { build, manifestXml, contentTypesXml };
+124
View File
@@ -0,0 +1,124 @@
'use strict';
// A zip archive written and read with Node alone (deflate from node:zlib): enough for a .vsix,
// which is a zip, and for checking one. No dependencies.
const zlib = require('node:zlib');
const CRC = (() => {
const t = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
t[n] = c >>> 0;
}
return t;
})();
function crc32(buf) {
let c = 0xffffffff;
for (let i = 0; i < buf.length; i++) c = CRC[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
return (c ^ 0xffffffff) >>> 0;
}
function dosTime(date) {
const d = date || new Date(Date.UTC(2020, 0, 1));
const time = (d.getUTCHours() << 11) | (d.getUTCMinutes() << 5) | (d.getUTCSeconds() >> 1);
const day = ((Math.max(1980, d.getUTCFullYear()) - 1980) << 9) | ((d.getUTCMonth() + 1) << 5) | d.getUTCDate();
return { time, day };
}
/**
* @param {{ name: string, data: Buffer }[]} files names with forward slashes
* @param {{ date?: Date }} [options] one date for every entry, so the same input gives the same archive
* @returns {Buffer}
*/
function zip(files, options) {
const { time, day } = dosTime(options && options.date);
const parts = [];
const central = [];
let offset = 0;
const seen = new Set();
for (const f of files) {
if (!f.name || f.name.startsWith('/') || f.name.includes('\\') || f.name.split('/').includes('..')) throw new Error('bad name in archive: ' + f.name);
if (seen.has(f.name)) throw new Error('twice in archive: ' + f.name);
seen.add(f.name);
const name = Buffer.from(f.name, 'utf8');
const data = Buffer.isBuffer(f.data) ? f.data : Buffer.from(f.data);
const packed = zlib.deflateRawSync(data, { level: 9 });
const stored = packed.length >= data.length;
const body = stored ? data : packed;
const crc = crc32(data);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4); // version needed
local.writeUInt16LE(0x0800, 6); // names are UTF-8
local.writeUInt16LE(stored ? 0 : 8, 8);
local.writeUInt16LE(time, 10);
local.writeUInt16LE(day, 12);
local.writeUInt32LE(crc, 14);
local.writeUInt32LE(body.length, 18);
local.writeUInt32LE(data.length, 22);
local.writeUInt16LE(name.length, 26);
local.writeUInt16LE(0, 28);
parts.push(local, name, body);
const entry = Buffer.alloc(46);
entry.writeUInt32LE(0x02014b50, 0);
entry.writeUInt16LE(20, 4); // made by
entry.writeUInt16LE(20, 6);
entry.writeUInt16LE(0x0800, 8);
entry.writeUInt16LE(stored ? 0 : 8, 10);
entry.writeUInt16LE(time, 12);
entry.writeUInt16LE(day, 14);
entry.writeUInt32LE(crc, 16);
entry.writeUInt32LE(body.length, 20);
entry.writeUInt32LE(data.length, 24);
entry.writeUInt16LE(name.length, 28);
entry.writeUInt32LE(offset, 42);
central.push(entry, name);
offset += local.length + name.length + body.length;
}
const dir = Buffer.concat(central);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0);
end.writeUInt16LE(files.length, 8);
end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(dir.length, 12);
end.writeUInt32LE(offset, 16);
return Buffer.concat([...parts, dir, end]);
}
/** The entries of an archive, each checked against its checksum. */
function unzip(buf) {
let end = -1;
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) {
if (buf.readUInt32LE(i) === 0x06054b50) {
end = i;
break;
}
}
if (end < 0) throw new Error('not a zip archive');
const count = buf.readUInt16LE(end + 10);
let at = buf.readUInt32LE(end + 16);
const out = [];
for (let n = 0; n < count; n++) {
if (buf.readUInt32LE(at) !== 0x02014b50) throw new Error('damaged archive directory');
const method = buf.readUInt16LE(at + 10);
const crc = buf.readUInt32LE(at + 16);
const packedSize = buf.readUInt32LE(at + 20);
const size = buf.readUInt32LE(at + 24);
const nameLength = buf.readUInt16LE(at + 28);
const extra = buf.readUInt16LE(at + 30);
const comment = buf.readUInt16LE(at + 32);
const local = buf.readUInt32LE(at + 42);
const name = buf.toString('utf8', at + 46, at + 46 + nameLength);
if (buf.readUInt32LE(local) !== 0x04034b50) throw new Error('damaged entry: ' + name);
const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
const body = buf.subarray(start, start + packedSize);
const data = method === 0 ? Buffer.from(body) : zlib.inflateRawSync(body);
if (data.length !== size || crc32(data) !== crc) throw new Error('checksum of ' + name + ' differs');
out.push({ name, data });
at += 46 + nameLength + extra + comment;
}
return out;
}
module.exports = { zip, unzip, crc32 };