VS Code: sign in and out, the server's minimum version, an accessible page; docs and changelog

LLeMbas: Sign In / Sign Out run the CLI's own sign-in and say whose it replaces. The chat page tells
a screen reader what happens and is operable with the keyboard. New tests: the vscode API used
against engines.vscode, signing in against a stand-in lembas, and the LLeMbas CLI itself when its
source is at hand. The READMEs, the Neovim help (helptags in the install recipe) and the changelog
say what changed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-12-01 19:45:58 +00:00
1 parent f06acbb7b7
commit d095de0458
20 files changed
+1016 -45

No files matched your search

+1
View File
@@ -3,3 +3,4 @@ node_modules/
__pycache__/
*.pyc
dist/
nvim/doc/tags
+72
View File
@@ -1,5 +1,77 @@
# Changelog
## Unreleased
Both editors were checked method by method against the LLeMbas CLI (2.0.0-beta.17) and now run
their tests against one stand-in agent that answers only as the CLI does — and against the CLI
itself where its source is at hand.
### Added (VS Code / VSCodium & Neovim)
- **Sign in and out from the editor.** `:LLeMbasLogin [address] [--ca file]` / *LLeMbas: Sign In*
runs the CLI's own sign-in, shows the code to approve, opens the approval page and, once it is
approved, starts the agent anew so the open chat works at once; it can be cancelled
(`:LLeMbasLoginCancel`, the notification's Cancel). The CLI keeps one sign-in for the whole
computer: when it would be replaced, the editor says whose it is and asks first.
`:LLeMbasLogout` / *LLeMbas: Sign Out*. Every "not signed in" message offers it.
- **The CLI's version is checked.** One older than 2.0.0-beta.16 is said once, with both versions
and how to update (`lembas update`); versions are compared as numbers (`beta.10` is newer than
`beta.9`). A server that asks for a newer plugin or extension is said once too.
- **`lembas` is also looked for in `~/.local/bin`** when the editor's `PATH` does not have it, and a
CLI that is not found says how to set its path.
- Neovim: `:LLeMbasRestart` (stop the agent; it starts again when needed) and `:LLeMbasLog` (what
the agent wrote on stderr); `:LLeMbasStatus` says the CLI's version, the folder, and why no
suggestion came. The subagents at work are counted in the panel's header.
- VS Code: the chat page tells a screen reader that a turn began or ended and that something waits
for an answer, instead of reading every piece of a reply again; file references, links and
question options are reachable and operable with the keyboard, and inputs have labels.
### Fixed (VS Code / VSCodium & Neovim)
- **A turn that failed was silent.** The CLI ends it like any other and says why in an event (and,
from its next version, in the answer): the reason is now in the transcript, once.
- **Token usage and progress were never shown** with the real CLI: both were read from fields it
does not send. Usage is the session's own (a subagent's is not added); progress says what it is
about (the tool call, the model, why it retries).
- **The agent could not edit a file it had read through the editor unless the file was open** —
in Neovim any file that was not open, in VS Code any file whose tab was closed after the read:
every later edit was refused with "read it again". The editor now answers for files that are not
open from the disk, byte for byte, and writes them there.
- **An edit right after a write was refused as "changed since you last read it"** where the editor
holds the text differently from how it was written (a CRLF document, a last line break): the
agent is given back exactly what it wrote while the document has not changed since.
- **Not being signed in** is said the same way everywhere, with what to do; a session is asked for
once more with a new agent before it is said, so signing in and sending again works without
restarting anything.
- **The agent's life.** The start is given up after 10 seconds without an answer, and requests
that would leave the editor waiting have a limit; an agent that ignores a stop is killed after
5 seconds; a crash is said once, with the agent's last words, and the next message starts a new
one; nothing is left running when the editor closes.
- A file the agent shows as text is opened as the file itself only when the file here holds exactly
that text, and otherwise as the text that was sent, read-only (Neovim used to ignore the text;
both looked for the file in the wrong folder when the session's was not the editor's).
- A card the agent takes down (answered elsewhere, or no longer waited for) is not answered
afterwards; a closed approval is shown as refused.
- The hello says `protocol: 3` and the client's name (`llembas-nvim`, `llembas-vscode`).
- Finding a file for `@file` asks for part of its name: the CLI's index answers an empty question
with only the files used lately, which looked like "no files" in a new project. It needs no
session, and no sign-in.
- Session resume: attachments, harness turns and failed tool calls are drawn as they were.
### Fixed (Neovim)
- A server failure switched suggestions off for good, and every refusal pointed at the model
picker. Only refusals that stay true (no model, a model not allowed, not signed in, an older
server) stop the asking, each with its own way out; anything else pauses it. While you type the
reason is one short line, never a prompt to press a key.
- A rewrite used the model the first session started on, even after the session's model was changed.
- A long prefix was cut in the middle of a character.
- The install recipe makes the help tags, so `:help llembas` works.
### Fixed (VS Code / VSCodium)
- A line the agent never ended was kept for ever (now at most 64 MB, as in Neovim).
## [1.0.0-beta.5] — 2026-11-27
### Fixed (VS Code / VSCodium)
+32 -7
View File
@@ -7,8 +7,18 @@ it holds the sign-in to your LLeMbas server, the models, the tools and the permi
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.
This is a beta. It needs LLeMbas CLI 2.0.0-beta.14 or newer, signed in (`lembas login <address>`).
With an older CLI only the chat, asking about a selection and approvals work.
This is a beta. It needs LLeMbas CLI 2.0.0-beta.16 or newer on the same computer. With an older CLI
the editor says so once, with how to update it (`lembas update`), and what that CLI lacks is off.
The CLI has to be signed in to your LLeMbas server. You can do that from the editor —
`:LLeMbasLogin` in Neovim, *LLeMbas: Sign In* in VS Code — or in a terminal with
`lembas login <address>`. It is the same sign-in either way: **the CLI keeps one for the whole
computer**, which the terminal and the linked service use too, so signing in to another server from
the editor replaces it (the editor says whose it replaces and asks first).
If the editor does not find `lembas` (an editor started from the desktop does not always have your
shell's `PATH`) it also looks in `~/.local/bin`, where the CLI's installer puts it; anywhere else,
set the command to the program's full path (`cmd` in Neovim's `setup`, *LLeMbas: Command* in VS Code).
## Neovim
@@ -23,12 +33,14 @@ lazy.nvim:
config = function(plugin)
vim.opt.rtp:append(plugin.dir .. "/nvim")
vim.cmd("runtime plugin/llembas.lua")
vim.cmd("silent! helptags " .. plugin.dir .. "/nvim/doc") -- so that :help llembas works
require("llembas").setup({})
end,
}
```
vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }`
vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }` (it makes the help tags itself).
By hand: add the checkout's `nvim` folder to `runtimepath` and run `:helptags <checkout>/nvim/doc` once.
| Command | What it does |
|---|---|
@@ -46,7 +58,7 @@ vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }`
| `:LLeMbasAutocompleteInstructions [text\|-]` | set or clear custom instructions sent with autocomplete |
| `:LLeMbasAutocompleteModel[!] [model]` | the model that writes suggestions (`!`: this editor only; `-`: back to default) |
| `:LLeMbasMainModel [model]` | the model for chat and rewriting, saved in your account (`?` shows both) |
| `:LLeMbasFiles[!] [query]` | search project index and insert `@path` (`!`: open file in editor) |
| `:LLeMbasFiles[!] [name]` | find a project file by part of its name and insert `@path` (`!`: open it); asks for the name when none is given |
| `:LLeMbasOpenFile [query]` | open a file from the project index |
| `:LLeMbasCommands` | pick a session `/command` or skill |
| `:LLeMbasSessions` | list and resume a previous session with its history |
@@ -57,6 +69,10 @@ vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }`
| `:LLeMbasNew[!]` | start a new session (`!` ends a hung turn) |
| `:LLeMbasMode [mode]` | change the mode (works live mid-turn) |
| `:LLeMbasModel [model]` | pick or change the session's model |
| `:LLeMbasLogin [address] [--ca file]` | sign this computer in to a LLeMbas server: shows the code, opens the approval page (`:LLeMbasLoginCancel` stops waiting) |
| `:LLeMbasLogout` | sign this computer out (the terminal and the linked service with it) |
| `:LLeMbasRestart` | stop the agent; it starts again when it is needed |
| `:LLeMbasLog` | what the agent wrote on stderr (why it stopped, when it did) |
| `:LLeMbasStatus`, `:LLeMbasHelp` | floating status overview / commands & keys card |
In the prompt: `<CR>` (normal mode) or `<C-s>` sends (or steers mid-turn), `<C-c>` stops the turn, `<C-x><C-f>` inserts `@file`, `<C-x><C-o>` inserts `/command`, `q` closes, `g?` opens help.
@@ -83,10 +99,19 @@ media. Commands, keys, and settings: [`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-nvim.sh` runs the plugin headless (needs `nvim` 0.10+ and `python3`).
`scripts/test-vscode.sh` runs the extension's parts that need no editor, and checks the package and
the `vscode` API it uses against the version it says it needs (Node 18 or newer and `python3`). It
does not start VS Code.
`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.
Both run against the same stand-in agent, `tests/fake_agent.py`, which answers only in the shapes
the LLeMbas CLI answers in and checks what it is sent as the CLI does; `tests/fake_lembas.py` stands
in for `lembas login` and `lembas logout`. When the CLI's source is at hand — a `LLeMbas-CLI`
checkout beside this repository, or wherever `LEMBAS_CLI_SOURCE` points, with its dependencies
installed and `bun` on the `PATH` — both suites also start the CLI itself, with a home of its own
(`LEMBAS_HOME`), so that it is never signed in and never touches your sessions: the hello, what
needs no sign-in, and that "not signed in" ends in an instruction. Without it they say that they
skipped that part (`LEMBAS_SKIP_REAL_CLI=1` skips it on purpose).
## Licence
+60 -6
View File
@@ -3,6 +3,13 @@
The agent is the LLeMbas CLI. This plugin starts `lembas serve --stdio` and is its
client; the sign-in, the models, the tools and the permissions are the CLI's.
It needs LLeMbas CLI 2.0.0-beta.16 or newer; an older one is said once, with how
to update it. A `lembas` that is not on Neovim's PATH is also looked for in
~/.local/bin; anywhere else, set `cmd` (|llembas-setup|).
The CLI keeps ONE sign-in for the whole computer: the terminal and the linked
service use it too. |:LLeMbasLogin| is that same sign-in, made from here.
==============================================================================
COMMANDS *llembas-commands*
@@ -65,12 +72,13 @@ COMMANDS *llembas-commands*
The model for chat and rewriting, saved in your account. "?" shows both
settings.
:LLeMbasFiles[!] [query] *:LLeMbasFiles*
Search the project file index and insert @path into the prompt (! opens
the chosen file directly in the editing window).
:LLeMbasFiles[!] [name] *:LLeMbasFiles*
Find a file or folder of the project by part of its name and insert @path
into the prompt (! opens the chosen file in the editing window). Without
a name it asks for one. Needs no session and no sign-in.
:LLeMbasOpenFile [query] *:LLeMbasOpenFile*
Open a file from the project index.
:LLeMbasOpenFile [name] *:LLeMbasOpenFile*
Open a file of the project, found the same way.
:LLeMbasCommands *:LLeMbasCommands*
Pick an available /command or skill and insert it into the prompt.
@@ -100,7 +108,50 @@ COMMANDS *llembas-commands*
Pick or change the session's model.
:LLeMbasStatus :LLeMbasHelp *:LLeMbasStatus* *:LLeMbasHelp*
Open floating status overview or commands & keymaps reference.
Open floating status overview or commands & keymaps reference. The status
says the CLI's version, the folder the agent works in, and why no
suggestion came when none did.
:LLeMbasLogin [address] [--ca {file}] *:LLeMbasLogin*
Sign this computer in to a LLeMbas server (the address is asked for when
not given; nothing is predefined). The CLI's own sign-in is run
(`lembas login --json`): the code to approve is shown in the chat and the
approval page is opened in your browser. When it is approved the agent is
started anew, so the open panel works at once.
When the computer is signed in to another server already, the plugin says
which and asks first: the new sign-in replaces it, for the terminal and
the linked service too. --ca names the certificate authority of a server
that has a private one (also `login.ca` in |llembas-setup|); with it the
CLI always makes a new sign-in.
:LLeMbasLoginCancel *:LLeMbasLoginCancel*
Stop a sign-in that waits to be approved.
:LLeMbasLogout *:LLeMbasLogout*
Sign this computer out, after asking: the terminal and the linked service
are signed out with it.
:LLeMbasRestart *:LLeMbasRestart*
Stop the agent. The transcript stays; the next message, suggestion or
rewrite starts a new agent and a new session.
:LLeMbasLog *:LLeMbasLog*
Show what the agent wrote on stderr: the running one's, or the last
one's — where to look when it stopped.
==============================================================================
WHEN SOMETHING IS WRONG *llembas-trouble*
The CLI is not found the chat says so; install it or set `cmd`.
The CLI is too old said once, with both versions: `lembas update`.
Not signed in every way in says so: |:LLeMbasLogin|.
The agent stopped the chat says why (its last words); the next
message starts it again. |:LLeMbasLog| has more.
The agent does not answer the start is given up after 10 seconds and said;
a turn has no limit (<C-c> or |:LLeMbasStop| stops
it, |:LLeMbasNew|! ends the agent).
A turn failed the reason is in the transcript, in red.
The plugin is too old a server may ask for a newer plugin: said once.
==============================================================================
SETUP *llembas-setup*
@@ -115,6 +166,9 @@ SETUP *llembas-setup*
model = nil, -- the model a session starts on
show_thoughts = false, -- the model's thinking in the transcript
send_open_file = true, -- a typed message names the file you are in
login = {
ca = nil, -- the CA file of a server with a private one
},
complete = {
auto = true, -- suggest as you type
debounce_ms = 250, -- the pause before a suggestion is asked for
+2 -1
View File
@@ -1,5 +1,6 @@
#!/bin/sh
# The Neovim plugin's tests: headless, against a stand-in agent. Needs nvim 0.10+ and python3.
# The Neovim plugin's tests: headless, against the stand-in agent (tests/fake_agent.py) and, when its
# source is at hand, the LLeMbas CLI itself. Needs nvim 0.10+ and python3.
set -eu
cd "$(dirname "$0")/.."
exec nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua
+2 -1
View File
@@ -1,5 +1,6 @@
#!/bin/sh
# The extension's tests: the parts that need no editor, against a stand-in agent.
# The extension's tests: the parts that need no editor, against the stand-in agent
# (tests/fake_agent.py) and, when its source is at hand, the LLeMbas CLI itself.
# Needs Node 18 or newer and python3. Nothing here starts VS Code.
set -eu
cd "$(dirname "$0")/.."
+32 -8
View File
@@ -12,10 +12,11 @@ about a server or a model is set in the editor, only which command starts the CL
## 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.
- The LLeMbas CLI, 2.0.0-beta.16 or newer, on the same computer. An older one is said once, with how
to update it (`lembas update`), and what it lacks is off.
- The CLI signed in to your LLeMbas server: **LLeMbas: Sign In** in the editor, or
`lembas login <address>` in a terminal. It is the same sign-in — the CLI keeps **one for the whole
computer**, which the terminal and the linked service use too.
## Install
@@ -35,7 +36,8 @@ 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.
shell's `PATH`) it also looks in `~/.local/bin`, where the CLI's installer puts it; anywhere else,
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.
@@ -77,7 +79,21 @@ for display-only kinds whose bytes match their filename) or *Show in folder* for
over 64 MB are refused (`llembas.media.maxMegabytes`).
**Unsaved text.** The agent reads open files from your editor buffers (saved or not), and writes
open files back through the document so undo and disk stay in sync.
open files back through the document so undo and disk stay in sync. A document keeps its own line
ends (CRLF stays CRLF).
**Signing in.** *LLeMbas: Sign In* asks for your server's address (nothing is predefined), runs the
CLI's own sign-in, shows the code to approve and opens the approval page in your browser; the
notification's Cancel stops waiting. When it is approved the agent starts anew and the open chat
works at once. If the computer is signed in to another server already, the extension says which and
asks first: the new sign-in replaces it, for the terminal and the linked service too. For a server
with a private certificate authority set `llembas.login.caFile`; with it the CLI always makes a new
sign-in. *LLeMbas: Sign Out* signs the computer out, after asking.
**When something is wrong.** A CLI that is not found, is too old, is not signed in, stops or does
not answer is said in the chat in words, with what to do; a turn that failed says why. What the CLI
wrote on stderr is in the *LLeMbas* channel of the Output panel. *LLeMbas: Stop the Agent* ends a
stuck one; the next message starts it again.
## Commands and keys
@@ -95,7 +111,7 @@ open files back through the document so undo and disk stay in sync.
| 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 CodeLenses above each change |
| LLeMbas: Show the Proposed Changes as a Diff | | |
| LLeMbas: Open File from Project Index / Add File to Chat | | |
| LLeMbas: Open File from Project Index / Add File to Chat | | asks for part of the file's name |
| LLeMbas: New Session / Resume a Previous Session | | |
| LLeMbas: Compact Session Context | | |
| LLeMbas: Stop the Running Turn | | |
@@ -103,6 +119,7 @@ open files back through the document so undo and disk stay in sync.
| LLeMbas: Models (Autocomplete and Main) | | also status bar item |
| LLeMbas: Choose the Autocomplete Model / the Main Model | | |
| LLeMbas: Stop the Agent | | starts again when needed |
| LLeMbas: Sign In / Sign Out | | the CLI's one sign-in for this computer |
On macOS the keys use `Cmd` in place of `Ctrl`.
@@ -111,6 +128,7 @@ On macOS the keys use `Cmd` in place of `Ctrl`.
| Setting | Default | |
|---|---|---|
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path (machine-scoped) |
| `llembas.login.caFile` | | the CA file of a server with a private certificate authority, for *Sign In* (machine-scoped) |
| `llembas.chat.sendEditorContext` | on | send active file, cursor, selection, diagnostics and open files |
| `llembas.chat.showThinking` | off | show collapsible model thinking blocks |
| `llembas.chat.startMode` | | initial mode for a new session (machine-scoped) |
@@ -127,13 +145,19 @@ On macOS the keys use `Cmd` in place of `Ctrl`.
- Sound, video, PDF and 3D files are not rendered inline in the chat: they appear with *Open*.
- An edit the agent asks about in a chat is allowed or denied as a whole, not change by change.
- No marketplace listing: install from the `.vsix`.
- A question card has no "ask back" answer, and a plan card no editing of the plan in place.
- It has been tested against a stand-in for the editor and against the LLeMbas CLI itself, not yet
in a release of VS Code by these tests: tell us what you see.
## 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 chat page (`media/chat.js`) builds elements with `createElement` and `textContent`
only, under a strict Content-Security-Policy; every colour comes from VS Code's theme variables.
only, under a strict Content-Security-Policy (no remote resource, no inline script or style); every
colour comes from VS Code's theme variables. What the page sends back is checked again by the
extension before anything is opened. The page says what happens to a screen reader (a turn began or
ended, something waits for your answer) and everything in it can be reached with the keyboard.
## Tests
+108 -2
View File
@@ -21,6 +21,8 @@ const markdown = require('./src/markdown');
const media = require('./src/media');
const { chatHtml } = require('./src/webview');
const words = require('./src/words');
const login = require('./src/login');
const { resolveCommand } = require('./src/agent');
const DIFF_SCHEME = 'llembas-diff';
const VIEW_ID = 'llembas.chat';
@@ -447,6 +449,8 @@ class ChatView {
return this.chat.stop();
case 'new':
return a.newSession();
case 'signIn':
return a.guard(a.signIn());
case 'compact':
return a.guard(a.compact());
case 'sessions':
@@ -523,6 +527,7 @@ class ChatView {
let chat = null;
let mediaDir = null;
let cancelSignIn = null; // ends a sign-in that still waits when the window closes
function activate(context) {
const output = vscode.window.createOutputChannel('LLeMbas');
@@ -682,6 +687,7 @@ function activate(context) {
home: os.homedir(),
}),
cwd: workingDirectory,
version,
options: () => ({
mode: String(config().get('chat.startMode') || '') || undefined,
model: windowModel.main,
@@ -692,7 +698,101 @@ function activate(context) {
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)));
/** A failure as a message; one that says the CLI is not signed in offers to sign in. */
const failed = (e) => {
if (!words.notSignedIn(e)) return vscode.window.showErrorMessage(say(e));
return vscode.window.showErrorMessage(say(e), 'Sign in').then((pick) => (pick ? guard(signIn()) : undefined));
};
const guard = (promise) => Promise.resolve(promise).then(undefined, failed);
// ---- signing in and out ----
let signingIn = null; // the sign-in under way: { cancel }
/** The program the agent is started as: the same one signs in and out. */
const cliCommand = () => resolveCommand(String(config().get('command') || 'lembas'), process.env, os.homedir());
async function signIn(address) {
if (signingIn) return vscode.window.showWarningMessage('LLeMbas: a sign-in is under way. Cancel it in its notification first.');
let server = typeof address === 'string' ? address.trim() : '';
if (!server) {
const typed = await vscode.window.showInputBox({
title: 'LLeMbas: sign in',
prompt: "Your LLeMbas server's address",
placeHolder: 'the address you open LLeMbas at in the browser',
ignoreFocusOut: true,
});
if (typed === undefined || !typed.trim()) return undefined;
server = typed.trim();
}
const command = cliCommand();
const ca = String(config().get('login.caFile') || '').trim();
const now = await login.current(command);
// The same server again, without a certificate: the CLI reads its login anew and replaces nothing.
if (now && !(login.sameServer(now, server) && !ca)) {
const go = `Sign in to ${server}`;
const pick = await vscode.window.showWarningMessage(
`LLeMbas: this computer is signed in to ${now}. The LLeMbas CLI keeps one sign-in: the terminal and the linked service use it too. Signing in to ${server} replaces it.`,
{ modal: true },
go,
);
if (pick !== go) return undefined;
}
const r = await vscode.window
.withProgress({ location: vscode.ProgressLocation.Notification, title: `LLeMbas: signing in to ${server}`, cancellable: true }, (progress, token) => {
const run = login.signIn({
command,
address: server,
ca: ca || undefined,
onCode(ev) {
const where = (ev.instance && (ev.instance.name || ev.instance.base_url)) || server;
progress.report({ message: `approve the code ${String(ev.user_code)} at ${String(ev.verification_uri)}` });
chat.note(`To sign in to ${where}, approve the code ${String(ev.user_code)} at ${String(ev.verification_uri)}. The page is being opened in your browser.`);
// Only a web address is handed to the browser, whatever the program printed.
const url = login.webAddress(ev.verification_uri_complete) || login.webAddress(ev.verification_uri);
if (url) Promise.resolve(vscode.env.openExternal(vscode.Uri.parse(url, true))).then(undefined, () => {});
},
});
signingIn = run;
cancelSignIn = () => run.cancel();
token.onCancellationRequested(() => run.cancel());
return run.result;
})
.then(
(v) => v,
(e) => ({ ok: false, error: { message: String((e && e.message) || e) } }),
);
signingIn = null;
cancelSignIn = null;
if (r.ok) {
// A new agent, so the open chat works at once with the new sign-in.
chat.stopAgent(true);
completer.unblock();
const models = Number.isFinite(r.done.models) ? ` (${r.done.models} models)` : '';
chat.note(`Signed in to ${String(r.done.base_url || server)}${models}. The next message starts a session.`);
showStatus();
return vscode.window.showInformationMessage(`LLeMbas: signed in to ${String(r.done.base_url || server)}.`);
}
if (r.cancelled) return chat.note('Signing in was cancelled.');
const why = r.error.code === 'not_found' ? words.WORDS.not_found(String(config().get('command') || 'lembas')) : words.say(r.error);
chat.note('Not signed in: ' + why, 'error');
return vscode.window.showErrorMessage('LLeMbas: not signed in: ' + why);
}
async function signOut() {
const command = cliCommand();
const now = await login.current(command);
if (!now) return vscode.window.showInformationMessage('LLeMbas: this computer is not signed in to a server.');
const go = `Sign out of ${now}`;
const pick = await vscode.window.showWarningMessage(`LLeMbas: sign this computer out of ${now}? The terminal and the linked service use the same sign-in.`, { modal: true }, go);
if (pick !== go) return undefined;
const r = await login.signOut(command);
if (!r.ok) return vscode.window.showErrorMessage('LLeMbas: not signed out: ' + r.message);
chat.stopAgent(true);
chat.note(r.message || `Signed out of ${now}.`);
showStatus();
return undefined;
}
// ---- what the editor shows, told to the agent ----
@@ -902,6 +1002,7 @@ function activate(context) {
view.attach(null);
return chat.send(text, w ? { editor: w.editor, label: w.label } : undefined);
},
signIn: () => signIn(),
async newSession() {
if (!(await chat.newSession())) vscode.window.showWarningMessage('LLeMbas is working. Stop it first.');
},
@@ -1168,7 +1269,9 @@ function activate(context) {
if (pick) guard(pickModel('autocomplete'));
});
} else if (reason === 'not_logged_in') {
vscode.window.showWarningMessage('LLeMbas: no suggestions: ' + chat.words({ message, data: { reason } }));
vscode.window.showWarningMessage('LLeMbas: no suggestions: ' + chat.words({ message, data: { reason } }), 'Sign in').then((pick) => {
if (pick) guard(signIn());
});
} else {
vscode.window.showInformationMessage('LLeMbas: no suggestions: ' + (message || 'autocomplete is not available here yet.'));
}
@@ -1367,6 +1470,8 @@ function activate(context) {
command('llembas.compact', compactSession);
command('llembas.stop', () => chat.stop());
command('llembas.restart', () => chat.stopAgent());
command('llembas.signIn', signIn);
command('llembas.signOut', signOut);
command('llembas.ask', ask);
command('llembas.explain', explain);
command('llembas.fixProblems', fixProblems);
@@ -1433,6 +1538,7 @@ function activate(context) {
function deactivate() {
if (chat) chat.dispose();
if (cancelSignIn) cancelSignIn();
if (mediaDir) {
try {
fs.rmSync(mediaDir, { recursive: true, force: true });
+5
View File
@@ -844,3 +844,8 @@ textarea::placeholder { color: var(--vscode-input-placeholderForeground); }
}
.actions { display: flex; gap: 4px; }
[hidden] { display: none !important; }
/* Read by a screen reader, not drawn. */
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
.note .note-action { margin-left: 8px; }
.md code.file-ref:focus-visible, .file-chip:focus-visible, .link:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: 1px; }
+52 -5
View File
@@ -45,7 +45,11 @@
var raw = String(n.v || '');
var isRef = FILE_REF_RE.test(raw.trim());
var code = el(doc, 'code', isRef ? 'file-ref' : '', raw);
if (isRef) code.setAttribute('title', 'Open ' + raw.trim());
if (isRef) {
code.setAttribute('title', 'Open ' + raw.trim());
code.setAttribute('role', 'link');
code.setAttribute('tabindex', '0');
}
parent.appendChild(code);
} else if (n.t === 'b' || n.t === 'i' || n.t === 'del') {
var e = doc.createElement(n.t === 'b' ? 'strong' : n.t === 'i' ? 'em' : 'del');
@@ -204,7 +208,12 @@
root.appendChild(details);
} else if (item.kind === 'note') {
if (item.level === 'error' || item.level === 'warn') root.className += ' ' + item.level;
root.textContent = String(item.text);
root.appendChild(el(doc, 'span', 'note-text', String(item.text)));
if (item.action === 'signIn') {
root.appendChild(button(doc, 'Sign in', 'mini note-action', function () {
post({ type: 'signIn' });
}));
}
} else if (item.kind === 'tool') {
var stCls = item.denied ? 'denied' : item.status === 'failed' ? 'failed' : item.status === 'completed' ? 'completed' : 'running';
root.className += ' ' + stCls;
@@ -316,16 +325,23 @@
if (idx >= 0) {
chosen[qi].splice(idx, 1);
b.className = 'second q-opt';
b.setAttribute('aria-pressed', 'false');
} else {
chosen[qi].push(o.label);
b.className = 'q-opt selected';
b.setAttribute('aria-pressed', 'true');
}
} else {
chosen[qi] = [o.label];
btns.forEach(function (other) { other.className = 'second q-opt'; });
btns.forEach(function (other) {
other.className = 'second q-opt';
other.setAttribute('aria-pressed', 'false');
});
b.className = 'q-opt selected';
b.setAttribute('aria-pressed', 'true');
}
});
b.setAttribute('aria-pressed', 'false');
btns.push(b);
optWrap.appendChild(b);
});
@@ -334,6 +350,7 @@
var inp = el(doc, 'input', 'q-input');
inp.setAttribute('type', 'text');
inp.setAttribute('placeholder', opts.length ? 'Or write your own answer…' : 'Your answer…');
inp.setAttribute('aria-label', (opts.length ? 'Your own answer to: ' : 'Your answer to: ') + String(q.question || q.header || 'the question'));
inputs.push(inp);
blk.appendChild(inp);
root.appendChild(blk);
@@ -373,6 +390,7 @@
var fb = el(doc, 'input', 'q-input');
fb.setAttribute('type', 'text');
fb.setAttribute('placeholder', 'Optional feedback to revise the plan…');
fb.setAttribute('aria-label', 'Feedback to revise the plan');
root.appendChild(fb);
var pRow = el(doc, 'div', 'buttons');
pRow.appendChild(button(doc, 'Approve (Edit)', '', function () {
@@ -395,7 +413,7 @@
if (item.picture && item.src) {
var img = doc.createElement('img');
img.setAttribute('src', String(item.src));
img.setAttribute('alt', String(item.name));
img.setAttribute('alt', 'Shown by the agent: ' + String(item.name));
img.addEventListener('click', function () {
post({ type: 'openMedia', key: item.key });
});
@@ -472,6 +490,11 @@
function upsert(item) {
var stick = atBottom();
if ((item.kind === 'card' || item.kind === 'question' || item.kind === 'plancard') && item.state === 'open' && !nodes[item.id]) {
announce(item.kind === 'card' ? 'LLeMbas asks for your approval: ' + String(item.title || '') : item.kind === 'question' ? 'LLeMbas asks a question' : 'A plan waits for your approval');
} else if (item.kind === 'note' && (item.level === 'error' || item.level === 'warn') && !nodes[item.id]) {
announce(String(item.text));
}
var fresh = renderItem(doc, item, post, uiState);
var old = nodes[item.id];
if (old && old.parentNode === log) log.replaceChild(fresh, old);
@@ -540,6 +563,7 @@
}
function showState(s) {
if (s.busy !== state.busy) announce(s.busy ? 'LLeMbas is working' : 'LLeMbas has finished');
state = s;
fill(mode, s.modes || [], s.mode, 'Mode');
fill(model, s.models || [], s.model, 'Model');
@@ -550,6 +574,7 @@
if (connDot) {
connDot.className = 'dot' + (s.busy ? ' is-busy' : s.connected ? ' is-ok' : '');
connDot.setAttribute('title', s.busy ? 'Working' : s.connected ? 'Connected' : 'Ready');
connDot.setAttribute('aria-label', 'Agent: ' + (s.busy ? 'working' : s.connected ? 'connected' : 'starts when needed'));
}
if (modeDot) {
var mCls = String(s.mode || '').replace(/[^a-z]/g, '');
@@ -579,6 +604,20 @@
popup.hidden = true;
while (popup.firstChild) popup.removeChild(popup.firstChild);
}
if (prompt) {
prompt.setAttribute('aria-expanded', 'false');
prompt.removeAttribute('aria-activedescendant');
}
}
// What a screen reader is told: that a turn began or ended, and that something waits for an
// answer -- not every piece of a reply as it is drawn again.
var announceEl = doc.getElementById('announce');
var lastAnnounced = '';
function announce(text) {
if (!announceEl || text === lastAnnounced) return;
lastAnnounced = text;
announceEl.textContent = text;
}
function renderPopup() {
@@ -587,6 +626,8 @@
popupState.items.forEach(function (it, idx) {
var row = el(doc, 'div', 'popup-row' + (idx === popupState.index ? ' active' : ''));
row.setAttribute('role', 'option');
row.setAttribute('id', 'popup-option-' + idx);
row.setAttribute('aria-selected', idx === popupState.index ? 'true' : 'false');
var left = el(doc, 'span', 'popup-left');
if (it.badge) left.appendChild(el(doc, 'span', 'popup-badge', it.badge));
left.appendChild(el(doc, 'span', 'popup-label', it.label));
@@ -599,6 +640,8 @@
popup.appendChild(row);
});
popup.hidden = false;
prompt.setAttribute('aria-expanded', 'true');
prompt.setAttribute('aria-activedescendant', 'popup-option-' + popupState.index);
}
function applyPopup(idx) {
@@ -772,7 +815,11 @@
follow(ev.target);
});
log.addEventListener('keydown', function (ev) {
if (ev.key === 'Enter') follow(ev.target);
// What acts as a link is opened with Enter or Space, as a link is; a button has its own keys.
if ((ev.key === 'Enter' || ev.key === ' ') && ev.target && ev.target.getAttribute && ev.target.getAttribute('role') === 'link') {
ev.preventDefault();
follow(ev.target);
}
});
function formatTokenReadout(n) {
+11 -2
View File
@@ -55,7 +55,9 @@
{ "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" }
{ "command": "llembas.restart", "title": "Stop the Agent (It Starts Again When Needed)", "category": "LLeMbas" },
{ "command": "llembas.signIn", "title": "Sign In", "category": "LLeMbas" },
{ "command": "llembas.signOut", "title": "Sign Out", "category": "LLeMbas" }
],
"keybindings": [
{ "command": "llembas.open", "key": "ctrl+alt+l", "mac": "cmd+alt+l" },
@@ -78,7 +80,8 @@
{ "command": "llembas.resumeSession", "when": "view == llembas.chat", "group": "llembas@2" },
{ "command": "llembas.openFile", "when": "view == llembas.chat", "group": "llembas@3" },
{ "command": "llembas.modelSettings", "when": "view == llembas.chat", "group": "llembas@4" },
{ "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@5" }
{ "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@5" },
{ "command": "llembas.signIn", "when": "view == llembas.chat", "group": "llembas@6" }
],
"commandPalette": [
{ "command": "llembas.acceptChange", "when": "llembas.hasProposal" },
@@ -97,6 +100,12 @@
"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.login.caFile": {
"type": "string",
"default": "",
"scope": "machine",
"description": "A file with the certificate authority of a LLeMbas server that has a private one. Used by \"LLeMbas: Sign In\" only; with it, signing in is always a new sign-in. Empty: the system's own certificates."
},
"llembas.chat.sendEditorContext": {
"type": "boolean",
"default": true,
+12 -3
View File
@@ -4,7 +4,7 @@
// in a shown file — is a hook. No `vscode` here.
const { EventEmitter } = require('node:events');
const { promptParams } = require('./context');
const { notSignedIn, say } = require('./words');
const { WORDS, compareVersions, minClient, notSignedIn, say } = require('./words');
const DETAIL_MAX = 20000;
// How long a request may go unanswered. A turn has no limit (Stop ends it); what would leave
@@ -152,10 +152,12 @@ class Chat extends EventEmitter {
this.emit('item', item);
}
note(text, level) {
/** `action`: what the note offers to do about itself (`signIn`). */
note(text, level, action) {
this.said = null;
const item = { kind: 'note', text: String(text) };
if (level && level !== 'info') item.level = String(level);
if (action) item.action = action;
return this.add(item);
}
@@ -206,6 +208,13 @@ class Chat extends EventEmitter {
this.startError = null;
// An older CLI is said once per agent.
if (agent.tooOld) this.note(agent.tooOld, 'warn');
// The signed-in server's own minimum for this extension, when the CLI passes one on: said once.
const min = minClient(agent.info);
const mine = this.io.version || '';
if (min && mine && compareVersions(mine, min) === -1 && this.saidMin !== min) {
this.saidMin = min;
this.note(WORDS.client_too_old_for_server(mine, min), 'warn');
}
this.emit('connected', agent);
this.emit('state');
return agent;
@@ -301,7 +310,7 @@ class Chat extends EventEmitter {
// before anything is said.
this.stopAgent(true);
if (attempt === 0) continue;
this.note(say(e), 'error');
this.note(say(e), 'error', 'signIn');
} else this.note('No session: ' + sentence(say(e)), 'error');
return false;
}
+178
View File
@@ -0,0 +1,178 @@
'use strict';
// Signing in and out from the editor: `lembas login --json <address>` and `lembas logout`, run
// with the same program the extension starts as its agent. The command line is a list, never a
// shell's; the address is the person's own (nothing is predefined here); what the CLI prints is
// read as data. No `vscode` here.
const childProcess = require('node:child_process');
const KILL_AFTER_MS = 5000;
/** The events in a piece of `lembas login --json`'s output: one JSON object a line. */
function eventsOf(text) {
const out = [];
for (const line of String(text || '').split(/\r?\n/)) {
if (!line.trim()) continue;
try {
const ev = JSON.parse(line);
if (ev && typeof ev === 'object' && typeof ev.event === 'string') out.push(ev);
} catch {
// not an event
}
}
return out;
}
function lastLine(text) {
const lines = String(text || '').split(/\r?\n/).filter((l) => l.trim());
return lines.length ? lines[lines.length - 1] : '';
}
/** Whether two addresses name the same server (scheme and trailing slashes aside). */
function sameServer(a, b) {
const bare = (s) => String(s || '').replace(/^https?:\/\//i, '').replace(/\/+$/, '').toLowerCase();
return bare(a) !== '' && bare(a) === bare(b);
}
/** A web address and nothing else: what may be handed to the browser, whatever the program printed. */
function webAddress(url) {
return typeof url === 'string' && /^https?:\/\/[^\s]+$/.test(url) ? url : '';
}
function kill(proc, afterMs) {
try {
proc.kill('SIGTERM');
} catch {
// already gone
}
const t = setTimeout(() => {
try {
proc.kill('SIGKILL');
} catch {
// already gone
}
}, afterMs || KILL_AFTER_MS);
if (typeof t.unref === 'function') t.unref();
proc.once('exit', () => clearTimeout(t));
}
/**
* Run `lembas <args>` and read its events as they come.
* @param {{ command: string, args: string[], env?: object, onEvent?: (ev: object) => void, timeoutMs?: number, killAfterMs?: number }} o
* @returns {{ done: Promise<{ code: number | null, events: object[], stdout: string, stderr: string, failed?: string }>, cancel: () => void }}
*/
function run(o) {
let proc;
const events = [];
let stdout = '';
let stderr = '';
let buffer = '';
let timer = null;
const done = new Promise((resolve) => {
try {
proc = childProcess.spawn(o.command, o.args, { env: o.env || process.env, stdio: ['ignore', 'pipe', 'pipe'], shell: false, windowsHide: true });
} catch (e) {
return resolve({ code: null, events, stdout, stderr, failed: e.message });
}
proc.stdout.on('data', (d) => {
const text = d.toString('utf8');
stdout = (stdout + text).slice(-65536);
buffer += text;
const nl = buffer.lastIndexOf('\n');
if (nl < 0) return;
const whole = buffer.slice(0, nl);
buffer = buffer.slice(nl + 1);
for (const ev of eventsOf(whole)) {
events.push(ev);
if (o.onEvent) o.onEvent(ev);
}
});
proc.stderr.on('data', (d) => (stderr = (stderr + d.toString('utf8')).slice(-65536)));
proc.on('error', (e) => resolve({ code: null, events, stdout, stderr, failed: e.code === 'ENOENT' || e.code === 'EACCES' ? 'not_found' : e.message }));
proc.on('exit', (code) => {
if (timer) clearTimeout(timer);
resolve({ code, events, stdout, stderr });
});
if (o.timeoutMs) {
timer = setTimeout(() => kill(proc, o.killAfterMs), o.timeoutMs);
if (typeof timer.unref === 'function') timer.unref();
}
});
return { done, cancel: () => proc && kill(proc, o.killAfterMs) };
}
/**
* The server this computer is signed in to now, or '': `lembas login --json` with no address
* reads the one login there is anew, and says whose it is.
*/
async function current(command, env) {
let found = '';
const r = run({
command,
args: ['login', '--json'],
env,
timeoutMs: 15000,
onEvent(ev) {
if (ev.event === 'done' && typeof ev.base_url === 'string') found = ev.base_url;
// A sign-in the server no longer takes is begun anew by the CLI: that it asks for a code
// says there was one. It is not gone through with here.
if (ev.event === 'code' && ev.instance && typeof ev.instance.base_url === 'string') {
found = ev.instance.base_url;
r.cancel();
}
},
});
await r.done;
return found;
}
/**
* Sign in to `address`. Resolves `{ ok: true, done }`, `{ ok: false, cancelled: true }` or
* `{ ok: false, error: { message, code? } }`. `onCode(ev)` is the code to approve.
* @param {{ command: string, address: string, ca?: string, env?: object, onCode?: (ev: object) => void, killAfterMs?: number }} o
*/
function signIn(o) {
let cancelled = false;
let settled = null;
let expiry = null;
const args = ['login', '--json', o.address];
if (o.ca) args.push('--ca', o.ca);
const r = run({
command: o.command,
args,
env: o.env,
killAfterMs: o.killAfterMs,
onEvent(ev) {
if (ev.event === 'code') {
if (o.onCode) o.onCode(ev);
// The CLI says when the code has run out; should it not, nothing waits for ever.
const limit = (Number(ev.expires_in) > 0 ? Number(ev.expires_in) : 600) + 30;
expiry = setTimeout(() => r.cancel(), limit * 1000);
if (typeof expiry.unref === 'function') expiry.unref();
} else if (ev.event === 'done') settled = settled || { ok: true, done: ev };
else if (ev.event === 'error') settled = settled || { ok: false, error: { message: String(ev.message || 'the sign-in failed'), code: typeof ev.code === 'string' ? ev.code : undefined } };
},
});
const result = r.done.then((out) => {
if (expiry) clearTimeout(expiry);
if (settled) return settled;
if (cancelled) return { ok: false, cancelled: true };
if (out.failed === 'not_found') return { ok: false, error: { message: '', code: 'not_found' } };
return { ok: false, error: { message: lastLine(out.stderr) || out.failed || `the LLeMbas CLI ended (exit ${out.code})` } };
});
return {
result,
cancel() {
cancelled = true;
r.cancel();
},
};
}
/** Sign out of the one login there is. Resolves `{ ok, message }`: the CLI's own line. */
async function signOut(command, env) {
const out = await run({ command, args: ['logout'], env, timeoutMs: 30000 }).done;
if (out.code === 0) return { ok: true, message: lastLine(out.stdout) };
return { ok: false, message: lastLine(out.stderr) || out.failed || `exit ${out.code}` };
}
module.exports = { eventsOf, sameServer, webAddress, current, signIn, signOut };
+5 -4
View File
@@ -42,7 +42,7 @@ function chatHtml(o) {
<div class="bar-top">
<div class="brand">
${brandImg}
<span id="conn-dot" class="dot" title="Agent status" aria-hidden="true"></span>
<span id="conn-dot" class="dot" title="Agent status" role="img" aria-label="Agent status"></span>
<span id="session-title" class="brand-title">LLeMbas</span>
</div>
<div class="bar-btns">
@@ -94,7 +94,8 @@ function chatHtml(o) {
</section>
<div id="team-bar" class="team-bar" hidden aria-live="polite"></div>
</div>
<main id="log" aria-live="polite">
<div id="announce" class="sr-only" role="status" aria-live="polite"></div>
<main id="log" aria-label="Conversation" tabindex="-1">
<section id="empty" class="empty">
<div class="hero">
${heroImg}
@@ -115,13 +116,13 @@ function chatHtml(o) {
</section>
</main>
<footer>
<div id="popup" class="popup" hidden role="listbox" aria-label="Suggestions"></div>
<div id="popup" class="popup" hidden role="listbox" aria-label="Files and commands"></div>
<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>
<div class="composer">
<textarea id="prompt" rows="3" placeholder="Ask LLeMbas (@file, /command, Enter sends, Shift+Enter newline)" aria-label="Message"></textarea>
<textarea id="prompt" rows="3" placeholder="Ask LLeMbas (@file, /command, Enter sends, Shift+Enter newline)" aria-label="Message to LLeMbas" aria-controls="popup" aria-autocomplete="list"></textarea>
<div class="send">
<div class="left-controls">
<button id="add-file" type="button" class="second" title="Add a file from the project index (@file)">@ File</button>
+14 -3
View File
@@ -10,8 +10,10 @@ const WORDS = {
`The LLeMbas CLI was not found: \`${command}\` is not a program this editor can start. Install the CLI, or set "LLeMbas: Command" (llembas.command) to its full path.`,
cli_too_old: (has, needs) => `LLeMbas CLI ${has} is older than this needs (${needs} or newer), so parts of it will not work. Update the CLI: lembas update`,
no_answer: (seconds) => `The LLeMbas CLI did not answer within ${seconds} seconds.`,
not_logged_in: 'The LLeMbas CLI is not signed in to a server. Run `lembas login <server>` in a terminal, then try again.',
signed_out: "The server no longer accepts this computer's sign-in. Run `lembas login <server>` in a terminal, then try again.",
not_logged_in: 'The LLeMbas CLI is not signed in to a server. Sign in with the command "LLeMbas: Sign In" (or `lembas login <server>` in a terminal), then try again.',
signed_out: 'The server no longer accepts this computer\'s sign-in. Sign in with the command "LLeMbas: Sign In" (or `lembas login <server>` in a terminal), then try again.',
client_too_old_for_server: (has, needs) =>
`This extension (${has}) is older than your LLeMbas server asks for (${needs} or newer); the server may refuse parts of it. Update the extension.`,
// These begin the sentence; what the CLI said follows.
unreachable: 'The LLeMbas server cannot be reached',
timeout: 'The LLeMbas server did not answer in time',
@@ -47,6 +49,15 @@ function compareVersions(a, b) {
return 0;
}
/**
* The oldest version of this extension the signed-in server works with, as the CLI's hello
* passes it on, or ''. The one place that knows where the field is.
*/
function minClient(initResult) {
const lembas = initResult && initResult._meta && initResult._meta.lembas;
return lembas && typeof lembas.min_client === 'string' ? lembas.min_client : '';
}
/** The code of a failure, where the CLI gives one (`data.reason`, `data.code`, or `code` of a turn's error). */
function codeOf(e) {
if (!e || typeof e !== 'object') return '';
@@ -80,4 +91,4 @@ function say(e) {
return WORDS[code] + ': ' + said;
}
module.exports = { MIN_CLI, WORDS, compareVersions, codeOf, notSignedIn, say };
module.exports = { MIN_CLI, WORDS, compareVersions, codeOf, notSignedIn, say, minClient };
+108
View File
@@ -0,0 +1,108 @@
'use strict';
// The extension has never been run in a real VS Code by these tests. This is the next best check:
// every member of the `vscode` API that extension.js uses must be one this file knows, with the
// version of VS Code it came in, and none may be newer than what package.json says the extension
// needs (`engines.vscode`). The same for the editor's own commands and theme colours it names, and
// for what the manifest contributes. Using something new means adding it here, with its version.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const ROOT = path.join(__dirname, '..');
const source = fs.readFileSync(path.join(ROOT, 'extension.js'), 'utf8');
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
// Member -> the VS Code version it is in at the latest (the API's own "since" where it is later
// than 1.30; everything older is written as 1.30).
const API = {
'window.showWarningMessage': '1.30', 'window.showInformationMessage': '1.30', 'window.showErrorMessage': '1.30', 'window.activeTextEditor': '1.30',
'window.visibleTextEditors': '1.30', 'window.showQuickPick': '1.30', 'window.showInputBox': '1.30', 'window.withProgress': '1.30',
'window.showTextDocument': '1.30', 'window.createTextEditorDecorationType': '1.30', 'window.createStatusBarItem': '1.30',
'window.createOutputChannel': '1.30', 'window.onDidChangeVisibleTextEditors': '1.30', 'window.onDidChangeActiveTextEditor': '1.30',
'window.registerWebviewViewProvider': '1.50', 'window.tabGroups': '1.67',
'workspace.textDocuments': '1.30', 'workspace.applyEdit': '1.30', 'workspace.getWorkspaceFolder': '1.30', 'workspace.asRelativePath': '1.30',
'workspace.workspaceFolders': '1.30', 'workspace.registerTextDocumentContentProvider': '1.30', 'workspace.openTextDocument': '1.30',
'workspace.onDidCloseTextDocument': '1.30', 'workspace.onDidChangeTextDocument': '1.30', 'workspace.onDidChangeConfiguration': '1.30',
'workspace.getConfiguration': '1.30',
'commands.executeCommand': '1.30', 'commands.registerCommand': '1.30',
'languages.registerCodeLensProvider': '1.30', 'languages.getDiagnostics': '1.30', 'languages.registerInlineCompletionItemProvider': '1.68',
'env.openExternal': '1.31', 'env.clipboard': '1.30',
'Uri.file': '1.30', 'Uri.parse': '1.30', 'Uri.joinPath': '1.45', 'Uri.from': '1.45',
Range: '1.30', Position: '1.30', ThemeColor: '1.30', CodeLens: '1.30', WorkspaceEdit: '1.30', EventEmitter: '1.30', MarkdownString: '1.30',
'EndOfLine.CRLF': '1.30', 'ProgressLocation.Notification': '1.30', 'OverviewRulerLane.Left': '1.30', 'ConfigurationTarget.Global': '1.30',
'ViewColumn.Beside': '1.30', ConfigurationTarget: '1.30', 'StatusBarAlignment.Right': '1.30', 'DiagnosticSeverity.Warning': '1.30',
TabInputText: '1.67', TabInputTextDiff: '1.67', InlineCompletionItem: '1.68', 'InlineCompletionTriggerKind.Invoke': '1.68',
};
// Words after `vscode.` that are not the API: the names of the editor's own commands, in strings.
const NOT_API = new Set(['diff', 'open']);
const EDITOR_COMMANDS = { 'vscode.diff': '1.30', 'vscode.open': '1.30', setContext: '1.30', revealFileInOS: '1.30', 'editor.action.inlineSuggest.trigger': '1.58' };
const THEME_COLORS = {
'diffEditor.insertedTextBackground': '1.30', 'diffEditor.removedLineBackground': '1.65', 'editorGhostText.foreground': '1.59',
'editorOverviewRuler.addedForeground': '1.30', 'editorOverviewRuler.deletedForeground': '1.30', 'editorOverviewRuler.modifiedForeground': '1.30',
};
const needs = /^\^?(\d+)\.(\d+)/.exec(pkg.engines.vscode);
const atMost = (since) => {
const [major, minor] = since.split('.').map(Number);
return major < Number(needs[1]) || (major === Number(needs[1]) && minor <= Number(needs[2]));
};
test('every member of the vscode API that is used is known, and none is newer than engines.vscode', () => {
assert.ok(needs, 'engines.vscode is a version');
const used = new Set();
for (const m of source.matchAll(/\bvscode\.([A-Za-z]+)(?:\.([A-Za-z]+))?/g)) {
if (NOT_API.has(m[1])) continue;
const namespace = /^[a-z]/.test(m[1]);
// A namespace is used through its members; a class or an enum by itself or by one member.
if (namespace && !m[2]) continue;
used.add(namespace || (m[2] && API[`${m[1]}.${m[2]}`]) ? `${m[1]}.${m[2]}` : m[1]);
}
assert.ok(used.size > 40, 'the source was read');
for (const name of [...used].sort()) {
assert.ok(API[name], `vscode.${name} is used and not in this test's list: add it, with the VS Code version it came in`);
assert.ok(atMost(API[name]), `vscode.${name} came in ${API[name]}, after the ${pkg.engines.vscode} the extension says it needs`);
}
});
test("the editor's own commands and theme colours that are named exist in that version too", () => {
const commands = new Set([...source.matchAll(/executeCommand\('([^']+)'/g)].map((m) => m[1]));
for (const c of commands) {
assert.ok(EDITOR_COMMANDS[c], `the command ${c} is run and not in this test's list`);
assert.ok(atMost(EDITOR_COMMANDS[c]), c);
}
const colours = new Set([...source.matchAll(/ThemeColor\('([^']+)'\)/g)].map((m) => m[1]));
assert.ok(colours.size >= 5);
for (const c of colours) {
assert.ok(THEME_COLORS[c], `the theme colour ${c} is used and not in this test's list`);
assert.ok(atMost(THEME_COLORS[c]), c);
}
assert.ok(!/#[0-9a-fA-F]{3,8}\b|rgba?\(/.test(source.replace(/\/\/.*$/gm, '')), 'no colour of its own in the glue code');
});
test('the manifest contributes only what exists: commands, menus, keys, the view, the settings', () => {
const c = pkg.contributes;
const commands = new Set(c.commands.map((x) => x.command));
assert.equal(commands.size, c.commands.length, 'no command twice');
for (const x of c.commands) assert.ok(x.title && x.category === 'LLeMbas', x.command);
for (const [menu, entries] of Object.entries(c.menus)) for (const e of entries) assert.ok(commands.has(e.command), `${menu}: ${e.command}`);
for (const k of c.keybindings) assert.ok(commands.has(k.command) && k.key, k.command);
for (const name of commands) assert.ok(source.includes(`command('${name}'`), `${name} is registered in extension.js`);
// The view: its container, its id as the code uses it, and what wakes the extension.
assert.equal(c.viewsContainers.activitybar[0].id, 'llembas');
assert.deepEqual(c.views.llembas, [{ type: 'webview', id: 'llembas.chat', name: 'Chat' }]);
assert.ok(source.includes("const VIEW_ID = 'llembas.chat'"));
assert.ok(fs.existsSync(path.join(ROOT, c.viewsContainers.activitybar[0].icon)) && fs.existsSync(path.join(ROOT, pkg.icon)) && fs.existsSync(path.join(ROOT, pkg.main)));
assert.ok(pkg.activationEvents.includes('onStartupFinished'), 'inline suggestions and the status item are there before the view is opened');
for (const e of pkg.activationEvents) assert.match(e, /^(onStartupFinished|onView:llembas\.chat)$/);
assert.deepEqual(pkg.extensionKind, ['workspace'], 'it runs where the files and the CLI are');
assert.equal(pkg.capabilities.untrustedWorkspaces.supported, false, 'it starts a program: off in a folder that is not trusted');
// Settings: each is read by the code, and what starts or reaches a program cannot be set by a folder.
const settings = c.configuration.properties;
for (const key of Object.keys(settings)) {
assert.ok(source.includes(`'${key.replace(/^llembas\./, '')}'`), `${key} is read in extension.js`);
assert.ok(settings[key].description || settings[key].markdownDescription, key);
}
for (const key of ['llembas.command', 'llembas.login.caFile', 'llembas.chat.startMode']) assert.equal(settings[key].scope, 'machine', key);
assert.equal(settings['llembas.command'].default, 'lembas', 'nothing is predefined but the program\'s name');
});
+33 -2
View File
@@ -573,13 +573,44 @@ test('not signed in: said with what to do, the agent is not kept, and after the
const { chat, agents } = fakeChat(t, { env });
await chat.send('hello?');
const errors = () => chat.items.filter((i) => i.kind === 'note' && i.level === 'error').map((i) => i.text);
assert.deepEqual(errors(), ['The LLeMbas CLI is not signed in to a server. Run `lembas login <server>` in a terminal, then try again.']);
assert.deepEqual(errors(), ['The LLeMbas CLI is not signed in to a server. Sign in with the command "LLeMbas: Sign In" (or `lembas login <server>` in a terminal), then try again.']);
assert.equal(chat.items.find((i) => i.level === 'error').action, 'signIn', 'the note offers to sign in');
assert.equal(chat.busy, false);
assert.equal(chat.agent, null, 'an agent started before the sign-in is not kept');
assert.equal(agents.length, 2, 'a new agent was asked once before anything was said');
await assert.rejects(chat.loadModels(), (e) => chat.words(e) === 'The LLeMbas CLI is not signed in to a server. Run `lembas login <server>` in a terminal, then try again.');
await assert.rejects(chat.loadModels(), (e) => chat.words(e) === 'The LLeMbas CLI is not signed in to a server. Sign in with the command "LLeMbas: Sign In" (or `lembas login <server>` in a terminal), then try again.');
assert.deepEqual(await chat.searchFiles('nothing-of-that-name'), [], 'the file index needs no sign-in');
delete env.FAKE_AGENT_LOGIN;
await chat.send('signed in now');
assert.match(text(chat), /You: signed in now\nLLeMbas: Hello there\.\nSecond line$/);
});
test("a server that asks for a newer extension is said once, with both versions, and the chat goes on working", async (t) => {
const { Chat } = require('../src/chat');
const { fakeAgent } = require('./helpers');
const { minClient } = require('../src/words');
assert.equal(minClient({ _meta: { lembas: { min_client: '1.2.3' } } }), '1.2.3');
assert.equal(minClient({}), '');
const dir = tempDir(t);
const make = (version, min) => {
const chat = new Chat({
makeAgent: (m) => fakeAgent(t, dir, { FAKE_AGENT_MIN_CLIENT: min }, { cwd: m.cwd, onRequest: m.onRequest }),
cwd: () => dir,
version,
});
t.after(() => chat.dispose());
return chat;
};
const old = make('0.9.0-beta.5', '0.9.0-beta.10');
await old.send('hello');
const said = () => old.items.filter((i) => i.kind === 'note' && /older than your LLeMbas server asks for/.test(i.text));
assert.equal(said().length, 1);
assert.equal(said()[0].text, 'This extension (0.9.0-beta.5) is older than your LLeMbas server asks for (0.9.0-beta.10 or newer); the server may refuse parts of it. Update the extension.');
assert.match(text(old), /LLeMbas: Hello there\./);
old.stopAgent();
await old.send('again');
assert.equal(said().length, 1, 'not at every start of the agent');
const fine = make('0.9.0', '0.9.0-beta.10');
await fine.send('hello');
assert.ok(!fine.items.some((i) => /older than your LLeMbas server/.test(i.text)));
});
+67 -1
View File
@@ -23,7 +23,9 @@ function host(t, env) {
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 });
// With FAKE_LEMBAS_STATE it is the stand-in for the whole program, which also signs in and out.
const program = vars.FAKE_LEMBAS_STATE ? `'${path.join(path.dirname(FAKE), 'fake_lembas.py')}' "$@"` : `'${FAKE}'`;
fs.writeFileSync(command, `#!/bin/sh\n${exports_}\nexec python3 ${program}\n`, { mode: 0o755 });
const vscode = make(pkg);
vscode.__.config['llembas.command'] = command;
vscode.workspace.workspaceFolders = [{ uri: vscode.Uri.file(dir) }];
@@ -763,3 +765,67 @@ test('full agentic features: question & plan cards, session resume, @file search
view.say({ type: 'stop' });
await idle();
});
test('sign in and out from the editor: the code is shown, the page is opened, the open chat works at once; whose sign-in is replaced is asked', async (t) => {
const stateDir = tempDir(t);
const stateFile = path.join(stateDir, 'login.json');
const lembasLog = path.join(stateDir, 'lembas.log');
const { view, run, items, idle, s } = host(t, { FAKE_LEMBAS_STATE: stateFile, FAKE_LEMBAS_LOG: lembasLog });
const lines = () => (fs.existsSync(lembasLog) ? fs.readFileSync(lembasLog, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
const notes = () => items().filter((i) => i.kind === 'note').map((i) => i.text);
// Not signed in: the chat says so, and offers to sign in.
view.say({ type: 'send', text: 'hello?' });
await until(() => items().some((i) => i.kind === 'note' && i.action === 'signIn'));
await idle();
assert.match(notes()[0], /^The LLeMbas CLI is not signed in to a server\. Sign in with the command "LLeMbas: Sign In"/);
// The note's own button: the address is asked for (nothing is predefined), the code shown, the page opened.
s.inputs.push('ai.example.org');
view.say({ type: 'signIn' });
await until(() => notes().some((n) => /^Signed in to https:\/\/ai\.example\.org \(3 models\)/.test(n)));
assert.ok(notes().some((n) => n === 'To sign in to Example, approve the code WAYB-READ at https://ai.example.org/device. The page is being opened in your browser.'), notes().join('\n'));
assert.deepEqual(s.external, ['https://ai.example.org/device?code=WAYB-READ']);
assert.ok(s.executed.some((e) => e[0] === 'progress' && /approve the code WAYB-READ/.test(e[1])));
assert.deepEqual(lines().filter((l) => l[0] === 'login').pop(), ['login', '--json', 'ai.example.org']);
view.say({ type: 'send', text: 'signed in now' });
await until(() => items().some((i) => i.kind === 'agent'));
await idle();
// Another server, with a private certificate authority: asked first, saying whose sign-in goes.
s.config['llembas.login.caFile'] = '/etc/ssl/private-ca.pem';
const before = lines().length;
await run('llembas.signIn', 'other.example.org'); // dismissed: nothing happens
const asked = s.messages.filter((m) => m.level === 'warning').pop();
assert.equal(asked.text, 'LLeMbas: this computer is signed in to https://ai.example.org. The LLeMbas CLI keeps one sign-in: the terminal and the linked service use it too. Signing in to other.example.org replaces it.');
assert.deepEqual(asked.buttons, ['Sign in to other.example.org']);
assert.deepEqual(lines().slice(before), [['login', '--json']], 'only the question whose sign-in there is');
assert.equal(JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url, 'https://ai.example.org');
s.answers.push('Sign in to other.example.org');
await run('llembas.signIn', 'other.example.org');
assert.deepEqual(lines().pop(), ['login', '--json', 'other.example.org', '--ca', '/etc/ssl/private-ca.pem']);
assert.equal(JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url, 'https://other.example.org');
s.config['llembas.login.caFile'] = '';
// A failure in the shared words; a wait that is cancelled.
s.answers.push('Sign in to unreachable.example.org');
await run('llembas.signIn', 'unreachable.example.org');
await until(() => notes().some((n) => /^Not signed in: The LLeMbas server cannot be reached: https:\/\/unreachable\.example\.org could not be reached/.test(n)));
s.answers.push('Sign in to slow.example.org');
const waiting = run('llembas.signIn', 'slow.example.org');
await until(() => notes().some((n) => /slow\.example\.org\/device/.test(n)));
s.cancelProgress();
await waiting;
await until(() => notes().includes('Signing in was cancelled.'));
assert.equal(JSON.parse(fs.readFileSync(stateFile, 'utf8')).base_url, 'https://other.example.org', 'the sign-in there was stays');
// Signing out: asked first, then the CLI's own line.
await run('llembas.signOut');
assert.ok(fs.existsSync(stateFile), 'dismissed: still signed in');
s.answers.push('Sign out of https://other.example.org');
await run('llembas.signOut');
assert.ok(!fs.existsSync(stateFile));
await until(() => notes().includes('Signed out of example; its connection is removed.'));
await run('llembas.signOut');
assert.equal(s.messages.pop().text, 'LLeMbas: this computer is not signed in to a server.');
});
+88
View File
@@ -0,0 +1,88 @@
'use strict';
// Signing in and out, against tests/fake_lembas.py: a stand-in `lembas` that writes the events
// the LLeMbas CLI writes (`lembas login --json`).
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const login = require('../src/login');
const { say } = require('../src/words');
const { tempDir } = require('./helpers');
const LEMBAS = path.join(__dirname, '..', '..', 'tests', 'fake_lembas.py');
function rig(t) {
const dir = tempDir(t);
const state = path.join(dir, 'state.json');
const log = path.join(dir, 'lembas.log');
const env = { ...process.env, PYTHONDONTWRITEBYTECODE: '1', FAKE_LEMBAS_STATE: state, FAKE_LEMBAS_LOG: log };
const lines = () => (fs.existsSync(log) ? fs.readFileSync(log, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
return { dir, state, env, lines };
}
test('the events of a sign-in are read a line at a time; anything else is not an event', () => {
assert.deepEqual(login.eventsOf('{"event":"code","user_code":"A"}\nnoise\n{"no":"event"}\n{"event":"done"}\n'), [{ event: 'code', user_code: 'A' }, { event: 'done' }]);
assert.equal(login.sameServer('https://ai.example.org/', 'AI.example.org'), true);
assert.equal(login.sameServer('https://ai.example.org', 'https://other.example.org'), false);
assert.equal(login.sameServer('', ''), false);
assert.equal(login.webAddress('https://ai.example.org/device?code=A'), 'https://ai.example.org/device?code=A');
for (const bad of ['file:///etc/passwd', 'javascript:alert(1)', 'https://a b', undefined, 'command:x']) assert.equal(login.webAddress(bad), '', String(bad));
});
test('sign in: the code to approve, then done; the CLI is run as a command line of its own', async (t) => {
const { env, lines, state } = rig(t);
assert.equal(await login.current(LEMBAS, env), '', 'nobody is signed in yet');
const codes = [];
const r = await login.signIn({ command: LEMBAS, address: 'ai.example.org', env, onCode: (ev) => codes.push(ev) }).result;
assert.equal(r.ok, true);
assert.deepEqual([r.done.base_url, r.done.fresh, r.done.models], ['https://ai.example.org', true, 3]);
assert.deepEqual(codes.map((c) => [c.user_code, c.verification_uri, c.verification_uri_complete, c.instance.name]), [['WAYB-READ', 'https://ai.example.org/device', 'https://ai.example.org/device?code=WAYB-READ', 'Example']]);
assert.deepEqual(lines().pop(), ['login', '--json', 'ai.example.org']);
assert.equal(await login.current(LEMBAS, env), 'https://ai.example.org', 'whose sign-in the computer has now');
const again = await login.signIn({ command: LEMBAS, address: 'other.example.org', ca: '/etc/ssl/private-ca.pem', env }).result;
assert.equal(again.ok, true);
assert.deepEqual(lines().pop(), ['login', '--json', 'other.example.org', '--ca', '/etc/ssl/private-ca.pem']);
assert.equal(JSON.parse(fs.readFileSync(state, 'utf8')).ca, '/etc/ssl/private-ca.pem');
});
test('sign in: an error is the CLI\'s message, in the shared words where it gives a code', async (t) => {
const { env } = rig(t);
const coded = await login.signIn({ command: LEMBAS, address: 'unreachable.example.org', env }).result;
assert.equal(coded.ok, false);
assert.equal(coded.error.code, 'unreachable');
assert.equal(say(coded.error), 'The LLeMbas server cannot be reached: https://unreachable.example.org could not be reached (connection refused) — is the address right, and the server up?');
const plain = await login.signIn({ command: LEMBAS, address: 'plain-unreachable.example.org', env }).result;
assert.equal(plain.error.code, undefined);
assert.match(say(plain.error), /^https:\/\/plain-unreachable\.example\.org could not be reached/);
});
test('sign in: a code that runs out ends the wait', async (t) => {
const { env } = rig(t);
const r = await login.signIn({ command: LEMBAS, address: 'expires.example.org', env }).result;
assert.equal(r.ok, false);
assert.equal(say(r.error), 'The LLeMbas server did not answer in time: the code ran out before it was approved — sign in again for a new one');
});
test('sign in: cancelling ends the program, and the sign-in there was stays', async (t) => {
const { env, state } = rig(t);
await login.signIn({ command: LEMBAS, address: 'ai.example.org', env }).result;
let shown = false;
const run = login.signIn({ command: LEMBAS, address: 'slow.example.org', env, onCode: () => (shown = true), killAfterMs: 300 });
while (!shown) await new Promise((r) => setTimeout(r, 10));
run.cancel();
assert.deepEqual(await run.result, { ok: false, cancelled: true });
assert.equal(JSON.parse(fs.readFileSync(state, 'utf8')).base_url, 'https://ai.example.org');
});
test('sign in: a program that is not there is said as that', async (t) => {
const r = await login.signIn({ command: path.join(tempDir(t), 'no-lembas'), address: 'ai.example.org' }).result;
assert.deepEqual(r, { ok: false, error: { message: '', code: 'not_found' } });
});
test('sign out: the CLI\'s own line; with nobody signed in, its refusal', async (t) => {
const { env, state } = rig(t);
assert.deepEqual(await login.signOut(LEMBAS, env), { ok: false, message: 'not logged in to any instance' });
await login.signIn({ command: LEMBAS, address: 'ai.example.org', env }).result;
assert.deepEqual(await login.signOut(LEMBAS, env), { ok: true, message: 'Signed out of example; its connection is removed.' });
assert.ok(!fs.existsSync(state));
});
+134
View File
@@ -0,0 +1,134 @@
'use strict';
// Against the LLeMbas CLI itself, when its source is at hand (LEMBAS_CLI_SOURCE, or a LLeMbas-CLI
// checkout beside this repository) and bun is installed; skipped, saying why, when not.
// The CLI runs with a home of its own (LEMBAS_HOME), so it is never signed in and never touches a
// person's sessions: what is proved is the hello, the capabilities, what needs no sign-in, and
// that "not signed in" ends in words that say what to do.
const test = require('node:test');
const assert = require('node:assert/strict');
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 } = require('../src/completion');
const { MIN_CLI, compareVersions, say, notSignedIn } = require('../src/words');
const { tempDir, until, text } = require('./helpers');
function findCli() {
const dirs = [process.env.LEMBAS_CLI_SOURCE];
let up = path.resolve(__dirname, '..', '..');
for (let i = 0; i < 4; i++) {
up = path.dirname(up);
dirs.push(path.join(up, 'LLeMbas-CLI'));
}
return dirs.find((d) => d && fs.existsSync(path.join(d, 'src', 'cli.ts')) && fs.existsSync(path.join(d, 'node_modules')));
}
function findBun() {
const names = String(process.env.PATH || '').split(path.delimiter).map((d) => path.join(d, 'bun'));
names.push(path.join(os.homedir(), '.local', 'bin', 'bun'), path.join(os.homedir(), '.bun', 'bin', 'bun'));
return names.find((f) => {
try {
fs.accessSync(f, fs.constants.X_OK);
return true;
} catch {
return false;
}
});
}
const cli = findCli();
const bun = findBun();
const skip =
process.env.LEMBAS_SKIP_REAL_CLI === '1'
? 'LEMBAS_SKIP_REAL_CLI=1'
: !cli
? "the CLI's source was not found (set LEMBAS_CLI_SOURCE to a LLeMbas-CLI checkout with its dependencies installed)"
: !bun
? 'bun was not found on the PATH'
: false;
const SIGN_IN = 'The LLeMbas CLI is not signed in to a server. Sign in with the command "LLeMbas: Sign In" (or `lembas login <server>` in a terminal), then try again.';
test('the real LLeMbas CLI: the hello, what needs no sign-in, and "not signed in" in words', { skip, timeout: 120000 }, async (t) => {
const home = tempDir(t);
const project = tempDir(t);
fs.mkdirSync(path.join(project, 'src'));
fs.writeFileSync(path.join(project, 'src', 'oven.py'), "print('waybread')\n");
require('node:child_process').spawnSync('git', ['-C', project, 'init', '-q']);
const agents = [];
const chat = new Chat({
makeAgent: (m) => {
const a = new Agent({
command: bun,
args: ['run', path.join(cli, 'src', 'cli.ts'), 'serve', '--stdio'],
cwd: m.cwd,
env: { ...process.env, LEMBAS_HOME: home },
onRequest: m.onRequest,
writeTextFile: true,
clientInfo: { name: 'llembas-vscode', version: '0.0.0-test' },
startTimeoutMs: 60000,
});
agents.push(a);
return a;
},
cwd: () => project,
version: '0.0.0-test',
});
t.after(() => chat.dispose());
// The hello.
const agent = await chat.connect(false);
assert.ok(agent, text(chat));
assert.equal(agent.info.protocolVersion, 1);
assert.equal(agent.info.agentInfo.name, 'LLeMbas CLI');
assert.notEqual(compareVersions(agent.version, MIN_CLI), -1, `the CLI at hand (${agent.version}) is at least the oldest this works with (${MIN_CLI})`);
assert.equal(agent.tooOld, '');
assert.equal(agent.info._meta.lembas.protocol, 3);
assert.equal(agent.info._meta.lembas.limits, null, 'serve --stdio has no limits of a link');
for (const c of ['editor', 'media', 'show', 'files', 'commands', 'steer', 'sessions', 'compact', 'configure', 'ask', 'plan', 'model', 'turns']) {
assert.ok(agent.has(c), 'the capability the extension uses: ' + c);
}
assert.ok(!agent.has('fs'), 'device files are the link\'s, never an editor\'s');
// What needs no sign-in, in the shapes the extension reads.
assert.deepEqual(await chat.searchFiles('oven'), [{ path: 'src/oven.py', kind: 'file' }]);
assert.deepEqual(await chat.searchFiles(''), [], 'nothing was used lately in a new project');
const commands = await agent.request('_lembas/commands', { cwd: project });
assert.deepEqual([commands.commands[0].name, commands.commands[0]._meta.lembas.kind], ['compact', 'builtin']);
assert.deepEqual(await chat.listSessions(10), []);
await assert.rejects(agent.request('_lembas/sessions/resume', { sessionId: 'ses_nope' }), (e) => e.code === -32602 && /no such session/.test(e.message));
await assert.rejects(agent.request('session/set_mode', { sessionId: 'ses_nope', modeId: 'plan' }), (e) => e.code === -32602);
await assert.rejects(agent.request('no/such-method', {}), (e) => e.code === -32601);
assert.deepEqual(await agent.request('session/cancel', { sessionId: 'ses_nope' }), { cancelled: 'none' });
// Not signed in: every way in says the same, and none hangs or throws.
for (const [method, params] of [['_lembas/models', {}], ['_lembas/editor/settings', {}], ['_lembas/complete', { id: 'c1', prefix: 'def bake():', suffix: '' }], ['_lembas/edit', { id: 'e1', text: 'x = 1', instruction: 'make it 2', cwd: project }]]) {
await assert.rejects(agent.request(method, params, 30000), (e) => e.code === -32602 && notSignedIn(e) && say(e) === SIGN_IN, method);
}
const refusals = [];
const completer = new Completer({
request: (method, params) => agent.request(method, params, 30000),
notify: (method, params) => agent.notify(method, params),
debounceMs: () => 0,
onRefusal: (reason, message) => refusals.push([reason, say({ message, data: { reason } })]),
});
assert.equal(await completer.ask({ prefix: 'def bake():', suffix: '' }, { manual: true }), null);
assert.deepEqual(refusals, [['not_logged_in', SIGN_IN]]);
assert.equal(await completer.ask({ prefix: 'def bake():\n', suffix: '' }), null, 'and typing asks no more');
assert.equal(refusals.length, 1);
// A message: the chat says how to sign in, once, and is not left working.
assert.equal(await chat.send('hello, real CLI'), true);
const errors = chat.items.filter((i) => i.kind === 'note' && i.level === 'error');
assert.deepEqual(errors.map((i) => [i.text, i.action]), [[SIGN_IN, 'signIn']], text(chat));
assert.equal(chat.busy, false);
assert.equal(chat.session, null);
assert.equal(chat.agent, null, 'an agent started before the sign-in is not kept');
// Nothing is left running.
for (const a of agents) a.stop();
await until(() => agents.every((a) => a.gone), 15000);
for (const a of agents) assert.throws(() => process.kill(a.proc.pid, 0), 'the CLI process has ended');
});