Compare commits
30
Commits
v1.0.0-beta.4
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
252bbfb621
|
||
|
|
1459e6162f
|
||
|
|
528eb14b29
|
||
|
|
5def58bffc
|
||
|
|
97d3f8bbba
|
||
|
|
eab47acb39
|
||
|
|
2b1d42b976
|
||
|
|
86cc9352dc
|
||
|
|
572d12e967
|
||
|
|
102d68349f
|
||
|
|
cb0fd41ba6
|
||
|
|
b87cfa15ce
|
||
|
|
5dd1a4384b
|
||
|
|
6be29f85e2
|
||
|
|
9de046c603
|
||
|
|
4b2187f4b6
|
||
|
|
777c4d8852
|
||
|
|
081f240c76
|
||
|
|
fa5b6499f8
|
||
|
|
c4ceb3b84e
|
||
|
|
736aba5c63
|
||
|
|
0675b42df8
|
||
|
|
16502c174e
|
||
|
|
31ede4d8d2
|
||
|
|
d095de0458
|
||
|
|
f06acbb7b7
|
||
|
|
2af200c03b
|
||
|
|
e4381217b4
|
||
|
|
dd2bc2dcae
|
||
|
|
63d705c76c
|
No files matched your search
@@ -0,0 +1,65 @@
|
||||
# The GitHub Release for a tag, made from the Gitea release of the same tag. LLeMbas IDE is developed
|
||||
# on Gitea (git.houmeres.sk/LLeMbas/LLeMbas-IDE), which mirrors its commits and tags here; a mirror carries no Releases,
|
||||
# and GitHub's are what ide/install.sh reads by default. So when a tag arrives this waits for Gitea's
|
||||
# release to have its files, checks them exactly as the installer would — SHA256SUMS signed by the
|
||||
# release key, every file matching — and publishes the same files and notes. Nothing is built here.
|
||||
name: release
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
# By hand, for a tag that arrived without starting this.
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: "The tag, e.g. v1.0.0"
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
GITEA: https://git.houmeres.sk
|
||||
# The repository on Gitea (the same name as on GitHub).
|
||||
REPO: LLeMbas/LLeMbas-IDE
|
||||
TAG: ${{ inputs.tag || github.ref_name }}
|
||||
PUBKEY: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSZO3Byow7R3ZpOH3MCvpPIga2pZBzhfX5wXfNP1cLa"
|
||||
steps:
|
||||
- name: Wait for the Gitea release and its files
|
||||
run: |
|
||||
# The tag is mirrored as soon as it is pushed; the release and its files come minutes later.
|
||||
for i in $(seq 1 50); do
|
||||
if curl -fsSL "$GITEA/api/v1/repos/$REPO/releases/tags/$TAG" -o release.json &&
|
||||
jq -e '[.assets[].name] | index("SHA256SUMS.sig") and index("SHA256SUMS") and index("install.sh")' release.json >/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 60
|
||||
done
|
||||
echo "no Gitea release for $TAG with its files after 50 minutes" >&2
|
||||
exit 1
|
||||
- name: Download and check the files
|
||||
run: |
|
||||
mkdir files
|
||||
jq -r '.assets[].name' release.json > names
|
||||
while IFS= read -r name; do
|
||||
case "$name" in */* | .* | "") echo "a file name that is not one: $name" >&2; exit 1 ;; esac
|
||||
curl -fsSL -o "files/$name" "$GITEA/$REPO/releases/download/$TAG/$name"
|
||||
done < names
|
||||
cd files
|
||||
# Signed in the namespace lembas-release.
|
||||
printf 'lembas-release %s\n' "$PUBKEY" > ../allowed
|
||||
ssh-keygen -Y verify -f ../allowed -I lembas-release -n lembas-release -s SHA256SUMS.sig < SHA256SUMS || { echo "SHA256SUMS is not signed by the release key" >&2; exit 1; }
|
||||
sha256sum -c --strict SHA256SUMS
|
||||
[ -f "llembas-ide-${TAG#v}.tar.gz" ] || { echo "no llembas-ide-${TAG#v}.tar.gz in the release" >&2; exit 1; }
|
||||
for f in *; do case "$f" in SHA256SUMS | SHA256SUMS.sig) continue ;; esac; grep -q " $f\$" SHA256SUMS || { echo "$f is not in SHA256SUMS" >&2; exit 1; }; done
|
||||
- name: Publish the GitHub Release
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
jq -r .body release.json > notes.md
|
||||
pre=""
|
||||
case "$TAG" in *-beta.*) pre="--prerelease" ;; esac
|
||||
gh release create "$TAG" --repo "$GITHUB_REPOSITORY" --verify-tag --title "$(jq -r .name release.json)" --notes-file notes.md $pre files/*
|
||||
@@ -3,3 +3,4 @@ node_modules/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
dist/
|
||||
nvim/doc/tags
|
||||
+318
@@ -1,5 +1,323 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
## [1.0.0-beta.9] — 2026-12-04
|
||||
|
||||
### Fixed (LLeMbas IDE)
|
||||
|
||||
- **A directory opened like a file no longer brings back the old explorer over the bars.**
|
||||
Since beta.8 the tree is the left bar, but mini.files was still Neovim's default explorer, so
|
||||
`llembas-ide .`, `llembas-ide src/` or `:e src/` opened its floating columns on top of the new
|
||||
layout. Now a directory given at the start becomes the working directory: the tree is rooted
|
||||
there and the start screen shows. A directory opened later opens in the tree, with the focus
|
||||
there, and the window keeps the file it showed. mini.files stays on `<Space>E`, and is what a
|
||||
directory outside the tree, or one opened with the bars off, opens in. netrw stays off.
|
||||
- The Neovim plugin's tree has `show_dir(path)`: a directory under its root opened and shown.
|
||||
|
||||
## [1.0.0-beta.8] — 2026-12-03
|
||||
|
||||
### Privacy: less is sent by itself (both editors)
|
||||
|
||||
- **Other open files go along only when they belong to the project and do not look secret.**
|
||||
Until now a suggestion sent your server pieces of up to six other open files, and a message
|
||||
the paths of every open tab, wherever those files were on the disk. Now, in both editors:
|
||||
- only files **inside the project** — the working directory in Neovim, the window's folders in
|
||||
VS Code (with no folder open, nothing of other files);
|
||||
- never a file that **looks like it holds secrets**: `.env` and `.env.*` (not `.env.example`,
|
||||
`.env.sample`, `.env.template`), `*.env`, `*.pem`, `*.key`, `*.p12`, `*.pfx`, `*.jks`,
|
||||
`*.keystore`, `*.ppk`, `*.kdbx`, `id_rsa*`, `id_ed25519*`, `id_ecdsa*`, `id_dsa*`, `.netrc`,
|
||||
`.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`, `.git-credentials`, `credentials*`, `secrets.*`,
|
||||
`secret.*`, and anything under `.ssh/`, `.gnupg/`, `.aws/`, `.kube/`, `.docker/`, `.azure/`;
|
||||
- never a file the project's **`.gitignore`** leaves out (git is asked once a file; until it
|
||||
has answered the file is left out).
|
||||
- **In a file that looks like it holds secrets no suggestion is asked for at all**, so nothing of
|
||||
it is sent. The editor says so once.
|
||||
- The READMEs, `:help llembas-privacy` and the settings' descriptions now say all of what is
|
||||
sent — the text around the cursor, pieces of other open project files, the paths of open
|
||||
project tabs — and what never is. Before, they named the text around the cursor only.
|
||||
- What you point at yourself is unchanged: a selection you ask about, a file you name with `@`,
|
||||
the file you are typing in.
|
||||
|
||||
### Fixed (LLeMbas IDE)
|
||||
|
||||
- **A LLeMbas CLI in `~/.local/bin` that is not on `PATH` is found** — the state right after a
|
||||
first install. The start screen said "not installed", the statusline "no CLI", suggestions
|
||||
were off and every LLeMbas key led to the sign-in page, while the plugin underneath would have
|
||||
worked; `llembas-ide doctor` said the same. There is one rule now, the plugin's
|
||||
(`require("llembas").cli()`), which the IDE, `doctor` and the installer all keep.
|
||||
- **The LLeMbas CLI's installer is checked before it is run.** When you say yes to installing
|
||||
the CLI, its installer is taken from the CLI's own release and run only once it matches that
|
||||
release's `SHA256SUMS`, signed with the LLeMbas release key. Before, it was run as downloaded.
|
||||
A beta of the IDE now takes the CLI's newest beta release itself, instead of the stable
|
||||
line's installer.
|
||||
- `curl … | bash -s -- --help` prints the help (it printed nothing and failed).
|
||||
- The start screen no longer says "LLeMbas needs a server and a sign-in" to somebody who is
|
||||
signed in.
|
||||
- `doctor` and an update notice a file **added** to a plugin's directory, not only one that was
|
||||
changed: Neovim loads both. `doctor` no longer fails a sound installation over a stray line
|
||||
of Neovim's own at start, says so when the list of pinned plugins is missing (it said "git is
|
||||
not installed"), and checks for `ssh-keygen`.
|
||||
- `ssh-keygen` (openssh-client) is named among what the installer needs: it checks the
|
||||
release's signature, and the installer stops without it.
|
||||
- A release archive that holds a link is refused.
|
||||
|
||||
### Fixed (VS Code / VSCodium)
|
||||
|
||||
- **Signing in to another server, or out, lets go of everything read from the old account**: its
|
||||
model list, this window's own choice of model, the sessions listed. Before, the next session
|
||||
could be started on a model the new server does not have, and the Models view offered the old
|
||||
server's list.
|
||||
- **A rewrite holds a file only while it is being written.** Asking for a rewrite and leaving
|
||||
the instruction untyped locked Rewrite and Generate in that file ("a rewrite of this file is
|
||||
still being written") until the window was closed. Asking again now goes to the question that
|
||||
waits.
|
||||
- The Mode and model lists are no longer rebuilt with every step of a turn, which could close a
|
||||
list that was open under the pointer.
|
||||
- The times in the Sessions view are this computer's, not UTC.
|
||||
- Deleting a session that the CLI no longer has reads the list again instead of saying nothing;
|
||||
an agent that did not start is said as that, not as "this CLI cannot delete a session".
|
||||
|
||||
### Fixed (Neovim plugin)
|
||||
|
||||
- An answer that arrives from an agent that was replaced meanwhile (`:LLeMbasNew!`,
|
||||
`:LLeMbasRestart`) no longer ends the new turn or says "the turn failed: the agent stopped".
|
||||
- `:LLeMbasOpen` judges a file by its first bytes and its name, as VS Code does, not by its
|
||||
name alone: a program named `picture.png` is not handed to the system. Plain text opens in
|
||||
the editor.
|
||||
- `:LLeMbasLogin` reads the sign-in there is by whole lines, so that a sign-in cut in two on
|
||||
its way can never be read as "not signed in" and replaced without the question; an address
|
||||
that the CLI would read as an option is refused.
|
||||
- A line of the protocol longer than the plugin keeps is dropped whole, without losing the
|
||||
message after it.
|
||||
- After `:cd`, what is remembered for the new directory holds: the mode and effort a session
|
||||
starts with, LLeMbas and suggestions on or off.
|
||||
- A version with something after its number ("1.2.3junk") is no version in Neovim either.
|
||||
|
||||
### Changed (texts, both editors)
|
||||
|
||||
- One wording for one thing: "LLeMbas is still working. Stop it first." and "This LLeMbas CLI is
|
||||
too old for that. Update it: lembas update" replace eleven different sentences.
|
||||
- Plain words for the CLI's own: *Open a File of This Project* (was "from Project Index"), **Send
|
||||
now** while LLeMbas works (was "Steer"), **Approve: edit without asking** / **Approve: ask
|
||||
before each edit** on a plan (were "Approve (Edit)" / "(Manual)"), "how much a suggestion
|
||||
writes" with the same five names everywhere (were three sets), "Thinking (1,234 characters)".
|
||||
- VS Code's Status view: "Oldest CLI that works", "CLI is too old", "Extension is too old", "Last
|
||||
stop", "Folder"; the "Harness" row is gone. The dot in the chat's header says "Not started:
|
||||
starts when needed" where it said "Ready". `:LLeMbasStatus` in Neovim says "Length", "Model
|
||||
here only", and no longer lists the CLI's capabilities.
|
||||
- VS Code: *Choose the Main Model* is gone (it did what *Models* does); the model is called
|
||||
"chat and rewrite" everywhere. *Stop the Agent* is the command's whole name.
|
||||
- The plugin's help card and the extension's panel no longer call themselves "LLeMbas IDE": that
|
||||
is the Neovim distribution's name.
|
||||
- A message typed while LLeMbas works reads "You (sent while working)" in both editors (VS Code
|
||||
said "[sent while working]", Neovim "You (while working)").
|
||||
- "Nothing about a server or a model is *stored* in the editor" where the READMEs said nothing
|
||||
is *set* there: the panel does set them, through the CLI.
|
||||
- The root README gives the install line that works while every release is a beta.
|
||||
- The IDE's key table says that a chord is mapped in normal, visual and insert mode.
|
||||
|
||||
### Added (Neovim plugin and LLeMbas IDE)
|
||||
|
||||
- **Four bars around the code.** LLeMbas IDE starts with them; in the plugin alone one option
|
||||
turns them on (`bars = true`), and each can be switched off.
|
||||
- **Top bar**: what LLeMbas is doing (idle, thinking, tools, writing, waiting for you, not signed
|
||||
in, no CLI, AI off), the conversation's title, model · mode · effort, how full the context is,
|
||||
suggestions on or off, and the git branch and the file's problems when there is room.
|
||||
- **Bottom bar**: the keys you need most for the bar that has the focus — the code, the tree,
|
||||
the prompt, the settings lines, the transcript, a proposed change — and Neovim's own state at
|
||||
its right end (mode, modified, macro, search count, line and column, pending operator).
|
||||
- **The tree** on the left, open by default: the file you are in is followed; `Enter` opens,
|
||||
`a` new (a `/` at the end makes a directory), `r` rename or move, `d` delete after asking (to
|
||||
the trash where there is one), `/` filter as you type, `.` hidden files; one git mark a row.
|
||||
- **The right bar**: the settings as they are now (model, mode, effort, autocomplete — `Enter`
|
||||
on a line opens its choices right under it), the chat, and the prompt.
|
||||
Every row is laid out from known widths: fixed cells, one cell that takes the rest and is cut
|
||||
with an ellipsis, nothing wrapped. On a narrow screen the right bar folds away, then the tree.
|
||||
- **The prompt says what Enter will do**: `ask ›`, `rewrite ›` or `add ›`. `Tab` in an empty
|
||||
prompt switches. *ask* sends the question to the chat; *rewrite* has the lines that came along
|
||||
rewritten and *add* has new code written at the point, both shown in the file as changes to
|
||||
accept or reject. `:LLeMbasPrompt [ask|rewrite|add]`.
|
||||
- **To the prompt with what you are on**: the selection, or else the cursor's line, comes along,
|
||||
and its name is shown above the prompt (`main.rs:12-18`).
|
||||
- **The LLeMbas terminal's chords**, beside keys that arrive in every terminal. One table
|
||||
(`require("llembas.keys")`) maps each action in both forms — `Ctrl+Shift+A` / `<Leader>la` to
|
||||
the prompt, `Ctrl+Tab` / `<Leader>lm` the mode, `Ctrl+Shift+M` the model, `Ctrl+Alt+M` the
|
||||
autocomplete model, `Ctrl+Alt+A` suggestions, `Ctrl+Shift+I` LLeMbas on and off, `Ctrl+Shift+G`
|
||||
stop, `Ctrl+Shift+Y` / `J` accept and reject (`Alt+Ctrl+Shift+Y` all), `Ctrl+Shift+E` the tree,
|
||||
`Ctrl+Shift+D` the chat, `Alt+←` / `Alt+→` between the bars, `Ctrl+Shift+P` the menu — and the
|
||||
bottom bar shows the form that reaches Neovim from your terminal. The IDE's cheat sheet and
|
||||
README are made from the same table.
|
||||
- **Effort**, in the settings lines, in the menu and as `:LLeMbasEffort`; a level the model does
|
||||
not offer is said, with the level it runs on.
|
||||
- **LLeMbas on and off** (`:LLeMbasAI`, `Ctrl+Shift+I`): off is a plain editor — the agent is
|
||||
stopped, no suggestion is asked for, nothing is sent.
|
||||
- **The menu** (`:LLeMbasMenu`, `Ctrl+Shift+P`): every command and every setting in one list.
|
||||
- **Remembered per working directory**, with a machine-wide default under it: the mode, the
|
||||
effort, suggestions and LLeMbas on or off, which bars are shown and how wide. The models stay
|
||||
where they were kept: the session's with the LLeMbas CLI, the autocomplete and main model in
|
||||
your account.
|
||||
- **Public API for anything that shows LLeMbas's state**: `settings()`, `setting_lines()`,
|
||||
`choices()`, `set()`, `prompt()`, `intent()`, and the event `User LLeMbasChanged`
|
||||
(`:help llembas-api`).
|
||||
- **Inside the LLeMbas terminal** the editor says that it is in front (the user var
|
||||
`llembas_ide`), so the terminal hands its own chords through; nothing is written elsewhere.
|
||||
|
||||
### Changed (LLeMbas IDE)
|
||||
|
||||
- `<Space>la`, `<Space>le` and `<Space>lg` go to the prompt (ask, rewrite, add) with the
|
||||
selection or the cursor's line, instead of asking on the command line. `<Space>lm` switches to
|
||||
the next mode; the list of modes is in the settings lines and the menu.
|
||||
- `<Space>e` shows and hides the tree; the side-by-side explorer is `<Space>E`.
|
||||
- The statusline and the line of open buffers stand in only when the bottom or the top bar is
|
||||
switched off. With the top bar shown the open buffers are reached with `<Space>,`, `<S-h>` and
|
||||
`<S-l>`.
|
||||
- In the right bar `Enter` sends from insert mode (`Ctrl+J` is a new line) and `Esc` goes back
|
||||
to the code. The chat panel on its own (`bars = false`) keeps its keys.
|
||||
- A session no longer saves the bars' windows; they are laid out anew around what it restores.
|
||||
|
||||
### Changed (Neovim plugin)
|
||||
|
||||
- A proposed change's hint, and the keys in a buffer with changes, are the key table's.
|
||||
- `<CR>`, `K` and `i` in the transcript and the prompt's keys are mapped from the key table.
|
||||
|
||||
## [1.0.0-beta.7] — 2026-12-02
|
||||
|
||||
### Changed (VS Code / VSCodium)
|
||||
|
||||
- **Everything is in the one panel.** The LLeMbas side panel has a strip of tabs — Chat, Sessions,
|
||||
Models, Autocomplete, Settings, Account, Status — over one frame, and nothing asks anywhere else:
|
||||
no Quick Pick, no input box, no notification that wants an answer, no trip to the editor's
|
||||
Settings page. Every command is still in the palette and on its key; each now opens the panel
|
||||
where it belongs or does its work in the file. The view that is open, and what you were typing,
|
||||
are there again after the panel is closed or the window reloaded.
|
||||
- **Whole, or beside the conversation.** A tab opens its view in the whole frame. Anything reached
|
||||
from the conversation — the model button, History, a note's button, *Resume a Previous Session*,
|
||||
*Choose This Session's Model*, *Open File from Project Index* — opens beside it (below it in a
|
||||
narrow panel, next to it from 640 px) and closes back with Esc, leaving the composer's text, the
|
||||
scroll and the keyboard where they were.
|
||||
- **Every setting has a field in the panel**, made from one table that follows the manifest. They
|
||||
stay the editor's own settings: each field shows where its value comes from, is written to the
|
||||
level you choose (User or Workspace) and can be reset there, and follows a change made elsewhere
|
||||
at once. The *Tune* drawer is gone: its settings are the Autocomplete view.
|
||||
- **Signing in and out is the Account view**: the address, the code to approve with a button for
|
||||
the approval page (the browser is no longer opened by itself), the question whose sign-in is
|
||||
replaced, and Cancel — all in the panel.
|
||||
- **Models are three lists in the Models view**: this conversation's, the chat and rewrite model,
|
||||
and the autocomplete model, each saved in the account or for this window only.
|
||||
- **Rewrite and Generate ask for their instruction above the composer**, show the rewrite being
|
||||
written with a way to stop it, and offer *Accept all* / *Reject all* there; the changes are still
|
||||
answered one by one in the file. *Ask About the Selection* attaches the selection and puts the
|
||||
keyboard in the composer.
|
||||
|
||||
### Added (VS Code / VSCodium)
|
||||
|
||||
- **Sessions view**: filter, resume, new, and delete (where the CLI can), asked again in the row.
|
||||
- **Status view**: the agent's state, the program and its version, what this and the server need,
|
||||
what went wrong lately, what the agent last wrote, and *Restart the agent*. Commands *LLeMbas:
|
||||
Status of the Agent* and *LLeMbas: Settings (in the Panel)*.
|
||||
- What the page sends is checked against a schema: a setting is written only when it is one of
|
||||
LLeMbas's, with a value of its type and range; a server's address the program would read as an
|
||||
option is refused.
|
||||
- Controls are 28 px high, fields keep their label, control, hint and level on shared rows, nothing
|
||||
scrolls sideways in a 240 px side bar, and high-contrast themes and reduced motion are respected.
|
||||
|
||||
## [1.0.0-beta.6] — 2026-12-01
|
||||
|
||||
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).
|
||||
### Added (LLeMbas IDE)
|
||||
|
||||
- **LLeMbas IDE: a complete Neovim editor with LLeMbas built in, installed by one script** (`ide/install.sh`, later `curl … | bash`). For one user, without root, under its own `NVIM_APPNAME` (`llembas-ide`): a Neovim configuration of your own is never read or written.
|
||||
- A **pinned Neovim** release (0.12.7), its SHA-256 checked before unpacking; or a Neovim of your own, 0.10 or newer, with `--nvim-bin`.
|
||||
- **Five third-party plugins, each at one pinned commit** (`ide/plugins.lock`; licences in `ide/THIRD_PARTY.md`, all MIT or Apache-2.0), placed as plain Neovim packages: no plugin manager, nothing fetched or updated when the editor starts. 19 Treesitter grammars are compiled at install when a C compiler is there (`ide/parsers.lock`); otherwise Neovim's bundled ones are used.
|
||||
- **The editor**: file explorer, fuzzy finder (files, text, buffers, symbols), Treesitter highlighting, language servers found on `PATH` through Neovim's own client (`:LLeMbasIdeLsp` says which are found and how to install the others; the IDE downloads none), a completion menu that leaves `<Tab>` to LLeMbas's suggestions, git signs and diffs, statusline and buffer line, key hints, comment, surround, autopairs, a terminal, problem lists, format on demand, one session per directory. One leader-key map: `:LLeMbasIdeKeys`.
|
||||
- **LLeMbas built in**: chat, ask, rewrite, explain, fix and generate under `<Space>l`, suggestions on and off, model, mode and state in the statusline, sign-in from the start screen. Nothing is predefined, and the editor works fully without a server.
|
||||
- **The LLeMbas look**: a start screen with the mark, and the colourscheme `llembas` (dark `moria`, light `shire`) generated from the design tokens by `scripts/gen-ide-theme.py`.
|
||||
- **A launcher**, `llembas-ide`, with `--version`, `doctor`, `update` and `uninstall`, and a menu entry.
|
||||
- Everything is built in a staging directory and started there once before it replaces what is installed; a failure leaves things exactly as they were. `--dry-run` prints every action.
|
||||
- `scripts/test-ide.sh` tests it; `scripts/package-ide.sh` writes the release files (`install.sh`, `llembas-ide-<version>.tar.gz`, `SHA256SUMS`).
|
||||
|
||||
### Fixed (LLeMbas IDE)
|
||||
|
||||
- Shell scripts and TSX files are coloured by their compiled grammars: a file type whose name is
|
||||
not its grammar's (`sh`, `typescriptreact`, `javascriptreact`, `jsonc`) had none started for it.
|
||||
- An install that is refused leaves nothing behind, not even the empty directories above its
|
||||
prefix, and a release address that is not `https://` is refused in words.
|
||||
|
||||
## [1.0.0-beta.5] — 2026-11-27
|
||||
|
||||
### Fixed (VS Code / VSCodium)
|
||||
|
||||
- **Chat input pinned to the bottom of the side panel.** Wrapped the header, collapsible Tune drawer, and subagent strip inside a single `.chrome` container and restored a 3-row `body` grid (`auto minmax(0, 1fr) auto`) with `height: 100vh`. Previously, `hidden` (`display: none`) siblings shifted `<main id="log">` and `<footer>` onto `auto` tracks above an empty `1fr` track, floating the chat composer near the top with empty space beneath it.
|
||||
|
||||
## [1.0.0-beta.4] — 2026-11-27
|
||||
|
||||
### Fixed (VS Code / VSCodium & Neovim)
|
||||
|
||||
@@ -5,10 +5,49 @@ 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
|
||||
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.
|
||||
or a model is stored in the editor: you can sign in and choose models from it, and it is the CLI
|
||||
and your account that keep them.
|
||||
|
||||
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).
|
||||
|
||||
## LLeMbas IDE: the whole editor, one script
|
||||
|
||||
<!-- ide:begin -->
|
||||
A complete Neovim IDE with LLeMbas built in, installed for one user by one script: a pinned
|
||||
Neovim, a ready configuration (four bars around the code — state, keys, file tree, and LLeMbas's
|
||||
settings, chat and prompt — fuzzy finder, Treesitter, language servers, completion, git, sessions,
|
||||
key hints), the LLeMbas theme and the plugin below. It keeps its own directories
|
||||
and never touches a Neovim configuration of your own.
|
||||
|
||||
```sh
|
||||
curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/latest/download/install.sh | bash
|
||||
llembas-ide
|
||||
```
|
||||
|
||||
That line installs the newest **stable** release, and finds nothing as long as every release is a
|
||||
beta. For a beta, take the installer of that release and ask for the beta channel (`<version>` is
|
||||
a release's version, such as the newest on the
|
||||
[releases page](https://github.com/LLeMbas/LLeMbas-IDE/releases)):
|
||||
|
||||
```sh
|
||||
curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/download/v<version>/install.sh | bash -s -- --channel beta
|
||||
```
|
||||
|
||||
What it installs and where, the keys, how to make it yours, updating, removing and what leaves
|
||||
the machine: [`ide/README.md`](ide/README.md). The installer is [`ide/install.sh`](ide/install.sh);
|
||||
`scripts/test-ide.sh` tests it and `scripts/package-ide.sh` writes its release files.
|
||||
<!-- ide:end -->
|
||||
|
||||
## Neovim
|
||||
|
||||
@@ -23,16 +62,18 @@ 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 |
|
||||
|---|---|
|
||||
| `:LLeMbas` | open or close the chat panel (`right`, `left`, `bottom`, or `float`) |
|
||||
| `:LLeMbas` | open or close the chat panel (where it opens: `position` in `setup`) |
|
||||
| `:'<,'>LLeMbasAsk [question]` | ask about the selected lines; without a question they go with the next message |
|
||||
| `:'<,'>LLeMbasExplain` | explain the selected lines |
|
||||
| `:'<,'>LLeMbasEdit [instruction]` | rewrite the selected lines as inline hunks (`ga`/`gr`, `gA`/`gR`, `]h`/`[h`) |
|
||||
@@ -42,22 +83,51 @@ vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }`
|
||||
| `:LLeMbasAccept[!]`, `:LLeMbasReject[!]` | accept or reject proposed changes (`!`: all) |
|
||||
| `:LLeMbasNextHunk`, `:LLeMbasPrevHunk` | jump between proposed changes (`]h`, `[h`) |
|
||||
| `:LLeMbasAutocomplete [on\|off]` | toggle suggestions as you type |
|
||||
| `:LLeMbasAutocompleteTokens [N\|auto\|words\|line\|block\|file]` | tune autocomplete max tokens and prediction length preset |
|
||||
| `:LLeMbasAutocompleteInstructions [text\|-]` | set or clear custom instructions sent with autocomplete |
|
||||
| `:LLeMbasAutocompleteTokens [N\|auto\|words\|line\|block\|file]` | how much a suggestion writes: a length, or at most N tokens |
|
||||
| `:LLeMbasAutocompleteInstructions [text\|-]` | your own instructions for suggestions (`-` clears them) |
|
||||
| `: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) |
|
||||
| `:LLeMbasOpenFile [query]` | open a file from the project index |
|
||||
| `: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 of this project, found by part of its name |
|
||||
| `:LLeMbasCommands` | pick a session `/command` or skill |
|
||||
| `:LLeMbasSessions` | list and resume a previous session with its history |
|
||||
| `:LLeMbasCompact` | compact the session context |
|
||||
| `:LLeMbasToggleThoughts` | show or hide model thinking |
|
||||
| `:LLeMbasOpen` | open the file the agent showed last |
|
||||
| `:LLeMbasOpen` | open the file the agent showed last (pictures, PDF, sound, video and plain text only, and only when the file is what its name says) |
|
||||
| `:LLeMbasStop` | stop the running turn |
|
||||
| `:LLeMbasNew[!]` | start a new session (`!` ends a hung turn) |
|
||||
| `:LLeMbasNew[!]` | start a new session (`!` also ends the agent when a turn hangs) |
|
||||
| `: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 |
|
||||
| `:[range]LLeMbasPrompt [ask\|rewrite\|add]` | to the prompt with the lines, or the cursor's line, as the attachment; the prompt says what Enter will do |
|
||||
| `:LLeMbasEffort [level]` | the effort of the conversation |
|
||||
| `:LLeMbasAI [on\|off]` | everything of LLeMbas on or off (off: a plain editor, nothing is sent) |
|
||||
| `:LLeMbasMenu` | every command and every setting, to pick from |
|
||||
| `:LLeMbasBars [on\|off\|top\|bottom\|tree\|chat [on\|off]]` | the four bars, or one of them |
|
||||
| `:LLeMbasTree` | the file tree, show and hide |
|
||||
|
||||
**The four bars.** One option lays the editor out as LLeMbas IDE does — a top bar (what the agent
|
||||
is doing, the conversation, model · mode · effort, context, suggestions), a bottom bar (the keys
|
||||
for where the focus is, and Neovim's own state), a file tree on the left, and on the right the
|
||||
settings lines over the chat over the prompt:
|
||||
|
||||
```lua
|
||||
require("llembas").setup({ bars = true }) -- or a table: { tree = false, chat_width = 46, top = false, … }
|
||||
```
|
||||
|
||||
With the bars (or with `keys = true` alone) LLeMbas's keys are mapped from one table, each action
|
||||
in two forms: the LLeMbas terminal's chords (`Ctrl+Shift+A` to the prompt with the selection,
|
||||
`Ctrl+Tab` the mode, `Ctrl+Shift+M` the model, `Ctrl+Shift+Y`/`J` accept/reject, `Ctrl+Shift+E`/`D`
|
||||
the tree and the chat, `Ctrl+Shift+P` the menu, …), which need a terminal with the kitty keyboard
|
||||
protocol, and a key after `<Leader>l` that always arrives. In an empty prompt `<Tab>` switches
|
||||
what Enter does: ask, rewrite, add. The mode, the effort, on/off and the bars are remembered per
|
||||
working directory. Everything the bars show is public API — `settings()`, `setting_lines()`,
|
||||
`choices()`, `set()`, `prompt()`, the `User LLeMbasChanged` event — see `:help llembas-bars`,
|
||||
`:help llembas-keys` and `:help llembas-api`.
|
||||
|
||||
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.
|
||||
In the transcript: `<CR>` / `gf` opens `file:line`, `K` inspects tool output in a float, `y` yanks the fenced code block under the cursor, `i` jumps to the prompt, `q` closes.
|
||||
@@ -65,6 +135,13 @@ In the transcript: `<CR>` / `gf` opens `file:line`, `K` inspects tool output in
|
||||
While typing, `<Tab>` accepts a suggestion, `<M-Right>` accepts the next word, and `<M-\>` triggers one manually; all keys and `LLeMbas*` highlight groups can be customized. `require("llembas").statusline()` provides a compact statusline component.
|
||||
Help: `:help llembas`.
|
||||
|
||||
**What is sent by itself.** A suggestion sends your server the text around the cursor and pieces
|
||||
of up to six other open files; a message names the other open files. Both only for files inside
|
||||
the working directory, and never a file that looks like it holds secrets (`.env`, keys,
|
||||
credentials) or that the project's `.gitignore` leaves out; in a file that looks secret no
|
||||
suggestion is asked for at all. The list, and what never goes: `:help llembas-privacy`. VS Code
|
||||
keeps the same rule ([`vscode/README.md`](vscode/README.md), *What is sent*).
|
||||
|
||||
## VS Code and VSCodium
|
||||
|
||||
Needs VS Code or VSCodium 1.85 or newer. The extension lives in `vscode/`; it is plain JavaScript
|
||||
@@ -75,18 +152,35 @@ scripts/package-vscode.sh # writes dist/llemba
|
||||
codium --install-extension dist/llembas-<version>.vsix # or: code --install-extension …
|
||||
```
|
||||
|
||||
Includes a redesigned sidebar chat with interactive approval, question and plan cards, real GFM
|
||||
tables, code-block Copy/Insert toolbars, collapsible thinking and tool output, session resume and
|
||||
compaction, `@file` and `/command` popups, inline diff rewrites and generation, inline autocomplete
|
||||
with a **Tune** drawer (max-tokens slider, length presets, and custom instructions), and shown
|
||||
media. Commands, keys, and settings: [`vscode/README.md`](vscode/README.md).
|
||||
Everything is in **one side panel**: a strip of tabs over one frame — Chat, Sessions, Models,
|
||||
Autocomplete, Settings, Account, Status. The chat has interactive approval, question and plan
|
||||
cards, real GFM tables, code-block Copy/Insert toolbars, collapsible thinking and tool output,
|
||||
session resume and compaction, `@file` and `/command` popups and shown media; rewrites and
|
||||
generation are inline diffs; autocomplete is inline. Every `llembas.*` setting has a field in the
|
||||
panel (written to your User or Workspace settings, as you choose), signing in happens in the
|
||||
Account view, and nothing asks through a Quick Pick, an input box or a notification that wants an
|
||||
answer. A view reached
|
||||
from the conversation opens beside it and closes back to it. 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`. The few rules the two editors each carry a copy of —
|
||||
comparing versions, which files are never sent along, reading the sign-in's output, an over-long
|
||||
line of the protocol, what may be opened — are checked in both against the same cases,
|
||||
[`tests/rules/`](tests/rules/), so that one cannot change without the other. 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
|
||||
|
||||
|
||||
+471
@@ -0,0 +1,471 @@
|
||||
# LLeMbas IDE
|
||||
|
||||
A complete Neovim editor with LLeMbas built in, installed by one script.
|
||||
|
||||
It is stock Neovim, a pinned release, with a ready configuration: four bars around the code (what
|
||||
LLeMbas is doing at the top, the keys for where you are at the bottom, the file tree on the left,
|
||||
LLeMbas's settings, chat and prompt on the right), a fuzzy finder, Treesitter highlighting,
|
||||
language servers, a completion menu, git signs and diffs, key hints, a terminal, sessions, and
|
||||
the LLeMbas plugin for chat, asking about code, rewriting and suggestions as you type. It keeps to itself: its own
|
||||
`NVIM_APPNAME`, its own directories. A Neovim configuration of your own in `~/.config/nvim` is
|
||||
never read and never written.
|
||||
|
||||
It works fully as an editor on its own. LLeMbas needs two more things: the
|
||||
[LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI), which the installer offers, and a sign-in
|
||||
to your LLeMbas server (`lembas login <address>`). No server, model or key is set anywhere in
|
||||
the IDE.
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/latest/download/install.sh | bash
|
||||
```
|
||||
|
||||
While LLeMbas IDE is in beta there is no stable release for that to find; take a beta's own
|
||||
installer and ask for the betas (`<version>` from the
|
||||
[releases page](https://github.com/LLeMbas/LLeMbas-IDE/releases)):
|
||||
|
||||
```sh
|
||||
curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/download/v<version>/install.sh | bash -s -- --channel beta
|
||||
```
|
||||
|
||||
From a clone of this repository: `ide/install.sh --from-checkout`.
|
||||
|
||||
Then start it with `llembas-ide` (any arguments go to Neovim: `llembas-ide src/main.c`).
|
||||
|
||||
Linux on x86-64 and arm64. macOS is written for and has not been tried. It needs `bash`, `git`,
|
||||
`curl`, `tar`, `sha256sum` and `ssh-keygen` (the `openssh-client` package: it checks the
|
||||
release's signature); nothing runs as root. `curl … | bash -s -- --help` prints every option. Good to have: a C compiler (`cc`) for the
|
||||
Treesitter grammars, `rg` (ripgrep) for searching in files, a Nerd Font is not needed.
|
||||
|
||||
| Option | What it does |
|
||||
|---|---|
|
||||
| `--version X` | install release X instead of the newest |
|
||||
| `--channel stable\|beta` | which releases "newest" looks at (default `stable`) |
|
||||
| `--prefix DIR` | where the IDE itself goes (default `~/.local/share/llembas-ide`) |
|
||||
| `--from-checkout` | install from the clone the script sits in |
|
||||
| `--nvim-bin PATH` | use a Neovim of your own (0.10 or newer) instead of the pinned release |
|
||||
| `--no-cli` | do not offer the LLeMbas CLI |
|
||||
| `--no-parsers` | do not compile the Treesitter grammars |
|
||||
| `--yes` | ask nothing |
|
||||
| `--dry-run` | print every action and do nothing |
|
||||
|
||||
### What gets installed, and where
|
||||
|
||||
| Where | What |
|
||||
|---|---|
|
||||
| `~/.local/share/llembas-ide/nvim/` | Neovim, the release pinned in [`neovim.version`](neovim.version); its SHA-256 is checked against [`neovim.sha256`](neovim.sha256) before it is unpacked |
|
||||
| `~/.local/share/llembas-ide/site/pack/llembas/` | the IDE's configuration, the third-party plugins, the compiled Treesitter grammars |
|
||||
| `~/.local/share/llembas-ide/lib/` | the LLeMbas plugin, the installer and the lock files (for `update`, `doctor` and `uninstall`) |
|
||||
| `~/.config/llembas-ide/init.lua` | starts the IDE; replaced by an update unless you edited it |
|
||||
| `~/.config/llembas-ide/lua/user/init.lua` | **yours**: created once with comments only, never overwritten |
|
||||
| `~/.local/bin/llembas-ide` | the launcher |
|
||||
| `~/.local/share/applications/llembas-ide.desktop`, `~/.local/share/icons/hicolor/256x256/apps/llembas-ide.png` | the menu entry (Linux) |
|
||||
|
||||
Neovim keeps the IDE's history, undo files and sessions in `~/.local/state/llembas-ide/` and its
|
||||
cache in `~/.cache/llembas-ide/`. Nothing else is written. `XDG_DATA_HOME`, `XDG_CONFIG_HOME`,
|
||||
`XDG_STATE_HOME` and `XDG_CACHE_HOME` are honoured.
|
||||
|
||||
Everything is built in a staging directory and started there once, headless, before it replaces
|
||||
what is installed. A failure at any point leaves the previous installation, or nothing, exactly
|
||||
as it was.
|
||||
|
||||
### What it is made of
|
||||
|
||||
The third-party plugins are five, each fetched with git at exactly the commit in
|
||||
[`plugins.lock`](plugins.lock) (the commit hash is the check), and the Treesitter grammars are
|
||||
compiled from the commits in [`parsers.lock`](parsers.lock). Names, sources, licences and pins:
|
||||
[`THIRD_PARTY.md`](THIRD_PARTY.md). All of it is MIT or Apache-2.0.
|
||||
|
||||
There is no plugin manager. The plugins are plain Neovim packages (`:help packages`) that the
|
||||
installer places; the editor only loads what is there. So nothing is installed, fetched or
|
||||
updated when the IDE starts or while it runs, no plugin ever moves off its pinned commit on its
|
||||
own, and the IDE starts the same with or without a network. Plugins change when LLeMbas IDE
|
||||
does: a new version of the IDE carries new pins.
|
||||
|
||||
- **Treesitter.** With a C compiler at install, 19 grammars are compiled (Bash, C, CSS, Go, HTML,
|
||||
JavaScript, JSON, Lua, Markdown, Python, Rust, TOML, TSX, TypeScript, Vimscript, help, YAML and
|
||||
two helpers). Without one, Neovim's own bundled grammars colour C, Lua, Markdown, Vimscript and
|
||||
help, and every other language uses Neovim's regular syntax files; install a compiler and run
|
||||
`llembas-ide update` to get them all.
|
||||
- **Language servers.** Neovim's built-in client starts the servers it finds on your `PATH`
|
||||
(`:LLeMbasIdeLsp` lists the ones the IDE knows, which are found, and how each project says to
|
||||
install its server). The IDE never downloads a language server or a formatter: there is no
|
||||
installer for third-party programs in it.
|
||||
- **Formatting** happens when you ask (`<Space>cf`), with a formatter that is installed, or the
|
||||
language server.
|
||||
|
||||
## The screen
|
||||
|
||||
```
|
||||
┌──────────────────────────────────────────────────────────────────────┐
|
||||
│ ● idle │ fix config loader │ flash · manual · high │ ctx 12% │ AC on │ top bar
|
||||
├────────────┬──────────────────────────────────┬──────────────────────┤
|
||||
│ ▾ src/ │ 1 fn main() { │ model flash │ the settings, live:
|
||||
│ ▸ api/ │ 2 let cfg = Config::load() │ mode manual │ Enter on a line opens
|
||||
│ main.rs│ 3 run(cfg) │ effort high │ its choices right there
|
||||
│ lib.rs │ 4 } │ autocomplete on │
|
||||
│ ▸ tests/ │ 5 ├──────────────────────┤
|
||||
│ Cargo.to…│ 6 fn run(cfg: Config) { │ ## You │ the chat
|
||||
│ README.md│ 7 ... │ why does load … │
|
||||
│ │ ├──────────────────────┤
|
||||
│ │ │ main.rs:2-3 │ what comes along
|
||||
│ │ │ ask › _ │ the prompt
|
||||
├────────────┴──────────────────────────────────┴──────────────────────┤
|
||||
│ ^⇧A ask · Tab accept suggestion · ^⇧P menu · Alt+←→ bars NOR 3:9 │ bottom bar
|
||||
└──────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
- **Top bar.** What LLeMbas is doing (idle, thinking, tools, writing, waiting for you, not signed
|
||||
in, no CLI, AI off), the conversation's title, model · mode · effort, how full the model's
|
||||
context is, suggestions on or off, and at the right end the git branch and the file's problems
|
||||
when there is room. Every cell has a fixed width; the title takes what is left and is cut with
|
||||
an ellipsis.
|
||||
- **Bottom bar.** The keys you need most *where the focus is*: it changes as you move between the
|
||||
code, the tree, the prompt, the settings lines, the transcript, and a proposed change. It is
|
||||
made from the same table that maps the keys, so it cannot show a key that is not bound, and it
|
||||
is cut from the end to fit, never wrapped. At its right end is Neovim's own state: the mode,
|
||||
`+` for unsaved changes, the macro being recorded, the line and column, and from 120 columns
|
||||
the search count and the pending operator (narrower, those two are where stock Neovim shows
|
||||
them, in the command line's row under the bar).
|
||||
- **The tree** (left). Open by default, 26 columns. The file you are in is followed and marked.
|
||||
`Enter` opens a file and opens or closes a directory (`→`/`←` too), `a` makes a file — or a
|
||||
directory when the name ends in `/` — `r` renames or moves, `d` deletes after asking (into the
|
||||
trash where the system has one), `/` filters as you type, `.` shows hidden files. One mark per
|
||||
row says its git state (`M` changed, `A` added, `?` new, `D` deleted, `!` conflict, `•` a
|
||||
directory with changes inside).
|
||||
- **The right bar.** At the top the settings as they are now; move there and press `Enter` on a
|
||||
line to open its choices under it, `Enter` again to take one. Under them the conversation, and
|
||||
at the bottom the prompt. The prompt's first line begins with what `Enter` will do: `ask ›`,
|
||||
`rewrite ›` or `add ›`.
|
||||
|
||||
**From the code to LLeMbas.** `Ctrl+Shift+A` (or `<Space>la`) goes to the prompt and takes along
|
||||
what you are on: the selection, or else the cursor's line. Its name is shown above the prompt
|
||||
(`main.rs:12-18`). In an empty prompt `Tab` switches what `Enter` does with it:
|
||||
|
||||
| The prompt says | Enter |
|
||||
|---|---|
|
||||
| `ask ›` | sends the question to the chat, with what came along as context |
|
||||
| `rewrite ›` | has those lines rewritten; the result is shown in the file as changes to accept or reject |
|
||||
| `add ›` | has new code written at that point, shown the same way |
|
||||
|
||||
Nothing is written into a file until you accept it (`Ctrl+Shift+Y`, or `ga`; `Ctrl+Shift+J` or
|
||||
`gr` rejects). With text in the prompt `Tab` is Neovim's own Tab. `Enter` sends, `Ctrl+J` makes a
|
||||
new line, `Esc` goes back to the code.
|
||||
|
||||
**Narrow and low screens.** When the code would be left with fewer than 60 columns the right bar
|
||||
folds away, then the tree; `Ctrl+Shift+D` and `Ctrl+Shift+E` (or `Alt+→` / `Alt+←`) bring them
|
||||
back at any width. The top and bottom bars drop their least needed cells. Under 18 rows the
|
||||
settings lines make room for the chat.
|
||||
|
||||
**What is remembered.** The mode, the effort, suggestions on or off, LLeMbas on or off, which
|
||||
bars are shown and how wide the side bars are: per working directory, in
|
||||
`~/.local/state/llembas-ide/llembas/settings.json`. A directory that has chosen nothing takes
|
||||
the machine-wide values, which *Make these settings the default for every directory* in the menu
|
||||
(`Ctrl+Shift+P`) sets from where you are. The models are not kept here: the LLeMbas CLI remembers
|
||||
the model last used in a directory, and your account the autocomplete model.
|
||||
|
||||
## Keys
|
||||
|
||||
The leader key is `<Space>`. Press it and wait: the next keys are shown. `:LLeMbasIdeKeys` (or
|
||||
`<Space>ik`) shows this list in the editor.
|
||||
|
||||
**LLeMbas's keys have two forms.** The chords — `Ctrl+Shift+A` and the rest, the same as in the
|
||||
LLeMbas terminal — reach Neovim only from a terminal that reports such keys distinctly (the kitty
|
||||
keyboard protocol: kitty, Ghostty, foot, WezTerm with it switched on, and the LLeMbas terminal,
|
||||
which hands its own chords through while the IDE is in front). The other form, a key after
|
||||
`<Space>l`, arrives everywhere. Both are always mapped. The bottom bar shows the chords once one
|
||||
has arrived from your terminal (that is remembered) or the terminal is one known to report them,
|
||||
and the `<Space>` keys otherwise; `keys = { chords = true }` or `false` in your own file settles
|
||||
it by hand.
|
||||
|
||||
The completion menu and LLeMbas's suggestions share insert mode and never want the same key:
|
||||
`<Tab>` accepts LLeMbas's grey suggestion when one is shown and is a plain Tab otherwise; the menu
|
||||
is moved in with `<C-n>`/`<C-p>` and taken with `<CR>` (the entry you moved to) or `<C-y>` (the
|
||||
first one). In an empty prompt `<Tab>` switches ask, rewrite, add; no menu opens over the prompt.
|
||||
|
||||
<!-- keys:begin -->
|
||||
**Typing**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<M-\>` | insert | Ask LLeMbas for a suggestion now (accepting one: under LLeMbas, below) |
|
||||
| `<C-n> <C-p>` | insert | Move in the completion menu (also <Down> <Up>) |
|
||||
| `<CR>` | insert | Take the menu entry you moved to; otherwise a new line |
|
||||
| `<C-y>` | insert | Take the menu's first entry |
|
||||
| `<C-e>` | insert | Close the menu |
|
||||
| `<C-Space>` | insert | Open the menu, or the entry's documentation |
|
||||
|
||||
**Editing**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `gcc` | normal | Comment the line, on and off (gc with a motion or a selection) |
|
||||
| `sa sd sr` | normal | Surround: add (saiw"), delete (sd"), replace (sr"') |
|
||||
| `K` | normal | Documentation of the symbol under the cursor |
|
||||
| `gd gD gI gy` | normal | Definition, declaration, implementation, type (with a language server) |
|
||||
|
||||
**Find**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space><Space>` | normal | Find a file |
|
||||
| `<Space>/` | normal | Search in files (needs rg) |
|
||||
| `<Space>,` | normal | Switch buffer |
|
||||
| `<Space>e` | normal | File tree (the left bar), show and hide |
|
||||
| `<Space>E` | normal | Directories side by side, at this file (edit them like text) |
|
||||
| `<Space>ff` | normal | Find a file |
|
||||
| `<Space>fg` | normal | Search in files (needs rg) |
|
||||
| `<Space>fw` | normal | Search the word under the cursor |
|
||||
| `<Space>fb` | normal | Open buffers |
|
||||
| `<Space>fr` | normal | Recent files |
|
||||
| `<Space>fs` | normal | Symbols in this file |
|
||||
| `<Space>fS` | normal | Symbols in the project |
|
||||
| `<Space>fR` | normal | References to the symbol under the cursor |
|
||||
| `<Space>fd` | normal | Problems in the project |
|
||||
| `<Space>fh` | normal | Help pages |
|
||||
| `<Space>fk` | normal | All key mappings |
|
||||
| `<Space>f.` | normal | The last search again |
|
||||
|
||||
**Buffers**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space>bd` | normal | Close the buffer, keep the window |
|
||||
| `<Space>bn` | normal | Next buffer |
|
||||
| `<Space>bp` | normal | Previous buffer |
|
||||
| `<S-l>` | normal | Next buffer |
|
||||
| `<S-h>` | normal | Previous buffer |
|
||||
| `<Space>w` | normal | Save |
|
||||
| `<Space>q` | normal | Close the window |
|
||||
| `<Esc>` | normal | Clear the search highlight |
|
||||
|
||||
**Code**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space>ca` | normal | Code action |
|
||||
| `<Space>cr` | normal | Rename the symbol |
|
||||
| `<Space>cf` | normal, visual | Format the file or the selection |
|
||||
| `<Space>cd` | normal | The problem on this line |
|
||||
| `<Space>cl` | normal | Language servers: found, missing, how to install |
|
||||
|
||||
**Problems**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space>xx` | normal | Problems in this file, as a list |
|
||||
| `<Space>xw` | normal | Problems in the project, as a list |
|
||||
| `<Space>xn` | normal | Next problem |
|
||||
| `<Space>xp` | normal | Previous problem |
|
||||
|
||||
**Git**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space>gs` | normal | Changed files |
|
||||
| `<Space>gh` | normal | Changes, hunk by hunk |
|
||||
| `<Space>gd` | normal | This file beside its committed version |
|
||||
| `<Space>go` | normal | Show changes inline, on and off |
|
||||
| `<Space>ga` | normal | Stage the change under the cursor |
|
||||
| `<Space>gr` | normal | Undo the change under the cursor |
|
||||
| `<Space>gb` | normal | Who changed this line, and the commit |
|
||||
| `]g [g` | normal | Next and previous git change (]G [G: last and first) |
|
||||
|
||||
**LLeMbas**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<C-S-A> or <Space>la` | normal, visual; the chord also in insert | To the chat prompt; the selection, or else the cursor's line, comes along |
|
||||
| `<Space>le` | normal, visual | To the prompt, to have the selection or the line rewritten (shown as changes) |
|
||||
| `<Space>lg` | normal, visual | To the prompt, to have new code written at the cursor (shown as changes) |
|
||||
| `<Space>lx` | normal, visual | Explain the line or the selection |
|
||||
| `<Space>lf` | normal | Fix this file's problems |
|
||||
| `<Tab>` | insert, with a suggestion | Accept the suggestion (the grey text); without one, Neovim's own Tab |
|
||||
| `<M-Right>` | insert, with a suggestion | Accept one word of the suggestion |
|
||||
| `<C-M-a> or <Space>lt` | normal; the chord also in visual, insert | Suggestions as you type, on and off |
|
||||
| `<C-M-m> or <Space>lC` | normal; the chord also in visual, insert | Choose the model that writes suggestions |
|
||||
| `<C-S-P> or <Space>lp` | normal; the chord also in visual, insert | The LLeMbas menu: every command and every setting |
|
||||
| `<C-Tab> or <Space>lm` | normal; the chord also in visual, insert | Switch the mode |
|
||||
| `<C-S-M> or <Space>lM` | normal; the chord also in visual, insert | Choose the model |
|
||||
| `<Space>lE` | normal | Choose the effort |
|
||||
| `<C-S-I> or <Space>lI` | normal; the chord also in visual, insert | LLeMbas on and off (off: a plain editor, nothing is sent) |
|
||||
| `<C-S-G> or <Space>l.` | normal; the chord also in visual, insert | Stop the running turn |
|
||||
| `<C-S-Y> or ga` | a proposed change | Accept the proposed change under the cursor |
|
||||
| `<C-S-J> or gr` | a proposed change | Reject the proposed change under the cursor |
|
||||
| `]h` | a proposed change | The next proposed change |
|
||||
| `[h` | a proposed change | The previous proposed change |
|
||||
| `<M-C-S-Y> or gA` | a proposed change | Accept every proposed change in the file |
|
||||
| `gR` | a proposed change | Reject every proposed change in the file |
|
||||
| `<C-S-E> or <Space>lb` | normal; the chord also in visual, insert | The file tree, show and hide |
|
||||
| `<C-S-D> or <Space>ll` | normal; the chord also in visual, insert | The chat (the right bar), show and hide |
|
||||
| `<M-Left>` | normal, insert | To the bar on the left: chat, code, tree |
|
||||
| `<M-Right>` | normal, insert | To the bar on the right: tree, code, chat |
|
||||
| `<Space>ls` | normal | Earlier conversations |
|
||||
| `<Space>ln` | normal | New conversation |
|
||||
| `<Space>lc` | normal | Commands and skills |
|
||||
| `<Space>lS` | normal | Status |
|
||||
| `<Space>li` | normal | Sign in |
|
||||
| `<Space>l?` | normal | The plugin's commands and keys |
|
||||
| `<CR> <Right> l` | the tree | Open the file; open or close the directory (→ opens, ← closes) |
|
||||
| `<Left> h` | the tree | Close the directory, or go to the one above |
|
||||
| `a` | the tree | New file, or directory with a / at the end |
|
||||
| `r` | the tree | Rename or move |
|
||||
| `d` | the tree | Delete, after asking (to the trash where there is one) |
|
||||
| `/` | the tree | Filter by name as you type (empty: everything again) |
|
||||
| `.` | the tree | Hidden files, show and hide |
|
||||
| `R` | the tree | Read the directory again |
|
||||
| `<CR>` | the settings lines | Open the line's choices, or take the one under the cursor |
|
||||
| `<Up> <Down>` | the settings lines | Move between the lines and the choices |
|
||||
| `<Esc>` | the settings lines | Close the choices; from the lines, back to the code |
|
||||
| `<CR>` | the prompt | Send (while a turn runs: steer it) |
|
||||
| `<Tab>` | the prompt | In an empty prompt: what Enter will do — ask, rewrite, add |
|
||||
| `<C-j>` | the prompt | A new line in the prompt |
|
||||
| `<Esc>` | the prompt | Back to the code |
|
||||
| `<CR>` | the transcript | Open the file:line under the cursor |
|
||||
| `K` | the transcript | What the tool on this line printed |
|
||||
| `i` | the transcript | To the prompt |
|
||||
|
||||
**Session**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space>sr` | normal | Restore this directory's session |
|
||||
| `<Space>sw` | normal | Save the session now |
|
||||
| `<Space>sd` | normal | Forget this directory's session |
|
||||
|
||||
**Terminal**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space>tt` | normal | Terminal, open and close |
|
||||
| `<C-/>` | normal, terminal | Terminal, open and close |
|
||||
| `<C-_>` | normal, terminal | The same, as some terminals send it |
|
||||
| `<Esc><Esc>` | terminal | Leave the terminal's typing mode |
|
||||
|
||||
**Look**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space>ut` | normal | Dark and light theme |
|
||||
| `<Space>uw` | normal | Wrap long lines, on and off |
|
||||
| `<Space>un` | normal | Relative line numbers, on and off |
|
||||
|
||||
**IDE**
|
||||
|
||||
| Keys | In | What it does |
|
||||
|---|---|---|
|
||||
| `<Space>ih` | normal | Start screen |
|
||||
| `<Space>ik` | normal | This list of keys |
|
||||
| `<Space>id` | normal | Check the installation |
|
||||
| `<Space>iu` | normal | Open your own settings file |
|
||||
| `<Space>iv` | normal | Versions |
|
||||
<!-- keys:end -->
|
||||
|
||||
`<S-h>` and `<S-l>` replace Neovim's "top and bottom of the window" motions, `s` belongs to
|
||||
surround, and `<Esc>` in normal mode also clears the search highlight. `<M-Left>` and `<M-Right>`
|
||||
move between the bars. Everything else of Neovim's is as it was.
|
||||
|
||||
The open buffers have no line of their own while the top bar is shown: `<Space>,` lists them,
|
||||
`<S-h>` and `<S-l>` go through them, and the tree marks the one you are in.
|
||||
|
||||
## Make it yours
|
||||
|
||||
`~/.config/llembas-ide/lua/user/init.lua` (open it with `<Space>iu`) is loaded last, so what it
|
||||
sets wins: options, keys, the theme (`vim.o.background = "light"`, or another colourscheme
|
||||
altogether), the LLeMbas plugin's settings (`require("llembas").setup({ … })`, see
|
||||
`:help llembas-setup`), more language servers (`vim.lsp.enable("name")`).
|
||||
|
||||
**The bars** are one table. Each can be switched off and the side bars have widths:
|
||||
|
||||
```lua
|
||||
require("llembas").setup({ bars = {
|
||||
top = true, bottom = true, -- off: the IDE's line of open buffers / its statusline instead
|
||||
tree = true, chat = true, -- whether the side bars are open when a directory is new to you
|
||||
tree_width = 26, chat_width = 42,
|
||||
min_code = 60, -- the side bars fold away below this many columns of code
|
||||
} })
|
||||
require("llembas").setup({ bars = false }) -- none of it: one window and the plain chat panel
|
||||
```
|
||||
|
||||
What you then switch by key in a directory is remembered for that directory and holds over the
|
||||
table; the menu's *Forget what this directory chose for itself* takes it back.
|
||||
|
||||
**LLeMbas's keys** are one table too (`:help llembas-keys`). Change an entry and map again, and
|
||||
the bottom bar, the menu and this list follow:
|
||||
|
||||
```lua
|
||||
local keys = require("llembas.keys")
|
||||
keys.by_id.ask.chord = "<F2>" -- instead of Ctrl+Shift+A
|
||||
keys.by_id.tree.alt = "<Leader>t" -- instead of <Space>lb
|
||||
require("llembas").setup({ keys = { prefix = "<Leader>l" } })
|
||||
```
|
||||
|
||||
Any other key is Neovim's own to map (`vim.keymap.set`), and what you map there wins.
|
||||
|
||||
Your own plugins go in `~/.config/llembas-ide/pack/user/start/<name>/`: clone each there
|
||||
yourself and set it up in your file. The IDE loads them and never installs or updates them.
|
||||
|
||||
The colourscheme `llembas` has two halves from LLeMbas's two themes: `moria` (dark, the default)
|
||||
and `shire` (light). `<Space>ut` switches.
|
||||
|
||||
## Update, check, remove
|
||||
|
||||
```sh
|
||||
llembas-ide update # the newest release over this one; your settings are kept
|
||||
llembas-ide doctor # what is installed, what is missing, what is off without it
|
||||
llembas-ide --version # the IDE, Neovim and the LLeMbas plugin
|
||||
llembas-ide uninstall # remove it; --purge also removes your settings
|
||||
```
|
||||
|
||||
`update` runs the installed installer: it finds the newest release of the channel you are on (a
|
||||
beta stays with the betas), downloads it, checks it against the release's `SHA256SUMS` — which must be signed with the LLeMbas release key, the one the LLeMbas CLI's installer checks — and runs
|
||||
the installer inside it. Running `install.sh` again does the same. Plugins that did not change
|
||||
are kept as they are, so an update only fetches what is new.
|
||||
|
||||
`uninstall` removes what the installer placed and the IDE's history and cache. It keeps your
|
||||
settings unless you say otherwise, and touches nothing else.
|
||||
|
||||
## Privacy: what leaves the machine, and when
|
||||
|
||||
- **Installing and updating** download Neovim and the plugins from GitHub, and the release from
|
||||
this repository. That is all the network the IDE itself ever uses.
|
||||
- **Running the editor sends nothing.** No telemetry, no update check, nothing loaded from a
|
||||
network at start or later. Opening, editing, searching and completing are local.
|
||||
- **LLeMbas features** talk to the LLeMbas CLI on your machine, which talks to the LLeMbas server
|
||||
you signed in to, and to nothing else. That begins when you use one: open the chat, ask,
|
||||
rewrite, or type with suggestions on. Suggestions as you type are on once the CLI is
|
||||
installed; `<Space>lt` turns them off, and `complete = { auto = false }` in your settings
|
||||
keeps them off.
|
||||
- **What a suggestion sends** to your server: the text around the cursor, and pieces of up to
|
||||
six other files you have open. **What a message sends** besides what you typed: the name of
|
||||
the file you are in, the cursor's line, the lines that came along, and the names of the other
|
||||
open files. Other files go along — by name or by text — only when they are **inside the
|
||||
working directory**, and never when they **look like they hold secrets** (`.env`, keys and
|
||||
certificate stores, `credentials*`, `secrets.*`, anything under `.ssh/`, `.gnupg/`, `.aws/`,
|
||||
`.kube/`; the whole list is in `:help llembas-privacy`) or when the project's **`.gitignore`**
|
||||
leaves them out. In a file that looks like it holds secrets no suggestion is asked for at
|
||||
all. The agent itself reads files as a turn needs them, under the CLI's permissions.
|
||||
- **The LLeMbas CLI**, when you let the installer install it, comes from its own release: its
|
||||
installer is run only once it matches that release's signed checksums.
|
||||
- **A language server** you installed runs locally; what it does on the network is its own.
|
||||
- **LLeMbas off** (`Ctrl+Shift+I`, `<Space>lI`) makes it a plain editor: the agent is stopped, no
|
||||
suggestion is asked for, the chat is put away, and it stays so in that directory until you
|
||||
switch it on.
|
||||
- **Inside the LLeMbas terminal** (`$LLEMBAS_TERM` or `$LLEMBAS_TTY` set) the IDE tells the
|
||||
terminal that it is in front, by a user var (`llembas_ide=1`, cleared on the way out), so the
|
||||
terminal passes its chords on. That goes to the terminal and no further; in any other terminal
|
||||
nothing is written.
|
||||
|
||||
What a model writes is shown as text and never run. Modelines and per-directory configuration
|
||||
files (`exrc`) are off, and a `Session.vim` lying in a project is not read.
|
||||
|
||||
## For developers
|
||||
|
||||
`scripts/test-ide.sh` checks all of this: the scripts with shellcheck, a dry run, real installs
|
||||
into a temporary home (with the pinned Neovim and with the oldest supported one), a headless
|
||||
start with the checks in [`tests/headless.lua`](tests/headless.lua), updating in place, and
|
||||
uninstalling. `scripts/gen-ide-theme.py` writes the colourscheme from the design tokens
|
||||
([`tokens.css`](tokens.css)); `scripts/package-ide.sh` writes the release files into `dist/`.
|
||||
|
||||
The oldest Neovim the IDE runs on is 0.10. The one it installs is the pinned release.
|
||||
@@ -0,0 +1,57 @@
|
||||
# Third-party software in LLeMbas IDE
|
||||
|
||||
LLeMbas IDE itself is MIT (see `LICENSE`). It does not carry the software below in its repository or
|
||||
its release: `install.sh` fetches each piece from its own home at exactly the version or commit
|
||||
named here and checks it (a SHA-256 for Neovim, the commit hash for everything fetched with git).
|
||||
Each keeps its own licence, which is in its directory after installation. Only permissively
|
||||
licensed software is used; each licence below was read in the project's own licence file at the
|
||||
pinned commit.
|
||||
|
||||
## Neovim
|
||||
|
||||
| Name | From | Licence | Pinned |
|
||||
|---|---|---|---|
|
||||
| Neovim | https://github.com/neovim/neovim/releases | Apache-2.0 (and the Vim licence for code from Vim) | release v0.12.7, SHA-256 per platform in `neovim.sha256` |
|
||||
|
||||
## Plugins (`plugins.lock`)
|
||||
|
||||
| Name | From | Licence | Pinned commit | What the IDE uses it for |
|
||||
|---|---|---|---|---|
|
||||
| mini.nvim (v0.18.0) | https://github.com/nvim-mini/mini.nvim | MIT | `1345d191bb3da9c7b0e977f4387c5761f9bff68d` | file explorer, fuzzy finder, key hints, statusline and tabline, git signs and hunks, surround, autopairs, sessions, buffer removal |
|
||||
| blink.cmp (v1.10.2) | https://github.com/Saghen/blink.cmp | MIT | `78336bc89ee5365633bcf754d93df01678b5c08f` | the completion menu (language server, paths, buffer words), with its Lua matcher: no binary is downloaded |
|
||||
| conform.nvim (v9.1.0) | https://github.com/stevearc/conform.nvim | MIT | `3543d000dafbc41cc7761d860cfdb24e82154f75` | format on demand with the formatters installed on the machine |
|
||||
| nvim-lspconfig (v2.13.0) | https://github.com/neovim/nvim-lspconfig | Apache-2.0 | `4648fd8ba5c678d7e2db75ae44ffac269bb589d8` | the start commands and root markers of language servers, for Neovim's built-in client |
|
||||
| nvim-treesitter (master) | https://github.com/nvim-treesitter/nvim-treesitter | Apache-2.0 | `cf12346a3414fa1b06af75c79faebe7f76df080a` | its highlight queries only, with the compiled grammars; its installer and commands are not loaded |
|
||||
|
||||
## Treesitter grammars (`parsers.lock`)
|
||||
|
||||
Compiled on the machine at install when a C compiler is there; the revisions are the ones
|
||||
nvim-treesitter's `lockfile.json` names at the commit above.
|
||||
|
||||
| Language | From | Licence | Pinned commit |
|
||||
|---|---|---|---|
|
||||
| bash | https://github.com/tree-sitter/tree-sitter-bash | MIT | `0c46d792d54c536be5ff7eb18eb95c70fccdb232` |
|
||||
| c | https://github.com/tree-sitter/tree-sitter-c | MIT | `2a265d69a4caf57108a73ad2ed1e6922dd2f998c` |
|
||||
| css | https://github.com/tree-sitter/tree-sitter-css | MIT | `6e327db434fec0ee90f006697782e43ec855adf5` |
|
||||
| go | https://github.com/tree-sitter/tree-sitter-go | MIT | `5e73f476efafe5c768eda19bbe877f188ded6144` |
|
||||
| html | https://github.com/tree-sitter/tree-sitter-html | MIT | `cbb91a0ff3621245e890d1c50cc811bffb77a26b` |
|
||||
| javascript | https://github.com/tree-sitter/tree-sitter-javascript | MIT | `6fbef40512dcd9f0a61ce03a4c9ae7597b36ab5c` |
|
||||
| json | https://github.com/tree-sitter/tree-sitter-json | MIT | `46aa487b3ade14b7b05ef92507fdaa3915a662a3` |
|
||||
| lua | https://github.com/MunifTanjim/tree-sitter-lua | MIT | `db16e76558122e834ee214c8dc755b4a3edc82a9` |
|
||||
| markdown | https://github.com/MDeiml/tree-sitter-markdown (`tree-sitter-markdown/`) | MIT | `413285231ce8fa8b11e7074bbe265b48aa7277f9` |
|
||||
| markdown_inline | https://github.com/MDeiml/tree-sitter-markdown (`tree-sitter-markdown-inline/`) | MIT | `413285231ce8fa8b11e7074bbe265b48aa7277f9` |
|
||||
| python | https://github.com/tree-sitter/tree-sitter-python | MIT | `710796b8b877a970297106e5bbc8e2afa47f86ec` |
|
||||
| query | https://github.com/nvim-treesitter/tree-sitter-query | Apache-2.0 | `930202c2a80965a7a9ca018b5b2a08b25dfa7f12` |
|
||||
| rust | https://github.com/tree-sitter/tree-sitter-rust | MIT | `e86119bdb4968b9799f6a014ca2401c178d54b5f` |
|
||||
| toml | https://github.com/tree-sitter-grammars/tree-sitter-toml | MIT | `64b56832c2cffe41758f28e05c756a3a98d16f41` |
|
||||
| tsx | https://github.com/tree-sitter/tree-sitter-typescript (`tsx/`) | MIT | `75b3874edb2dc714fb1fd77a32013d0f8699989f` |
|
||||
| typescript | https://github.com/tree-sitter/tree-sitter-typescript (`typescript/`) | MIT | `75b3874edb2dc714fb1fd77a32013d0f8699989f` |
|
||||
| vim | https://github.com/neovim/tree-sitter-vim | MIT | `11b688a1f0e97c0c4e3dbabf4a38016335f4d237` |
|
||||
| vimdoc | https://github.com/neovim/tree-sitter-vimdoc | Apache-2.0 | `2694c3d27e2ca98a0ccde72f33887394300d524e` |
|
||||
| yaml | https://github.com/tree-sitter-grammars/tree-sitter-yaml | MIT | `1805917414a9a8ba2473717fd69447277a175fae` |
|
||||
|
||||
## Not installed by the IDE
|
||||
|
||||
The LLeMbas CLI is offered by the installer and installed by the CLI's own installer, which checks
|
||||
its release signature. Language servers and formatters are never installed: the IDE uses the ones
|
||||
already on the machine.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.2 KiB |
Executable
+331
@@ -0,0 +1,331 @@
|
||||
#!/usr/bin/env bash
|
||||
# LLeMbas IDE: the launcher. It starts the IDE's own Neovim with the IDE's own configuration
|
||||
# (NVIM_APPNAME=llembas-ide), so a Neovim configuration of your own is never read or written.
|
||||
#
|
||||
# llembas-ide [files…] start the editor; every argument goes to Neovim
|
||||
# llembas-ide --version the versions of the IDE, Neovim and the LLeMbas plugin
|
||||
# llembas-ide doctor check the installation, and say what is off without what
|
||||
# llembas-ide update install the newest release over this one (keeps your settings)
|
||||
# llembas-ide uninstall remove it (--purge: your settings too; --yes: ask nothing)
|
||||
#
|
||||
# A file named like one of those words is opened as ./doctor.
|
||||
set -euo pipefail
|
||||
|
||||
PREFIX='' # set by install.sh
|
||||
APP="llembas-ide"
|
||||
|
||||
say() { printf '%s\n' "$*"; }
|
||||
die() {
|
||||
printf 'llembas-ide: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
[ -n "$PREFIX" ] || die "this launcher was not put in place by the installer (ide/install.sh)"
|
||||
case "$PREFIX" in /*/*) ;; *) die "the installation's directory ($PREFIX) is not one of the IDE's own" ;; esac
|
||||
CONFIG="${XDG_CONFIG_HOME:-$HOME/.config}/$APP"
|
||||
STATE="${XDG_STATE_HOME:-$HOME/.local/state}/$APP"
|
||||
CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/$APP"
|
||||
DATA="${XDG_DATA_HOME:-$HOME/.local/share}/$APP"
|
||||
LIB="$PREFIX/lib"
|
||||
# Before Neovim is run for anything: its own log and state go to the IDE's directories.
|
||||
export NVIM_APPNAME="$APP"
|
||||
|
||||
recorded() { sed -n "s/^$1=//p" "$LIB/installed" 2>/dev/null | head -n1; }
|
||||
nvim_path() { cat "$LIB/nvim-path" 2>/dev/null || true; }
|
||||
sha256_of() {
|
||||
if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi
|
||||
}
|
||||
has_tty() { [ -r /dev/tty ] && { : </dev/tty; } 2>/dev/null; }
|
||||
git_quiet() { GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 git "$@"; }
|
||||
lock_lines() { grep -v -E '^[[:space:]]*(#|$)' "$1"; }
|
||||
|
||||
# Where the LLeMbas CLI is, or nothing: on PATH, or where its installer puts it. The installer has
|
||||
# this function word for word, and the plugin the same rule in Lua (require("llembas").cli());
|
||||
# scripts/test-ide.sh holds the three together.
|
||||
find_cli() {
|
||||
command -v lembas 2>/dev/null && return 0
|
||||
[ -x "$HOME/.local/bin/lembas" ] && printf '%s\n' "$HOME/.local/bin/lembas" && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
# What was changed in a plugin's directory since its commit was checked out: files edited or
|
||||
# deleted, and files added (ignored ones too: Neovim loads whatever lies there). The help tags
|
||||
# the installer writes itself are not a change.
|
||||
changed_in() {
|
||||
git_quiet -C "$1" status --porcelain --untracked-files=all --ignored 2>/dev/null | grep -v -E '^(\?\?|!!) doc/tags$' || true
|
||||
}
|
||||
|
||||
# Remove a directory only when it is the IDE's own: its last part is the application's name.
|
||||
remove_app_dir() {
|
||||
case "$1" in
|
||||
*/"$APP") rm -rf -- "$1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
versions() {
|
||||
local nvim
|
||||
nvim="$(nvim_path)"
|
||||
say "LLeMbas IDE $(cat "$LIB/VERSION" 2>/dev/null || echo unknown)"
|
||||
say "Neovim $("$nvim" --version 2>/dev/null | sed -n '1s/^NVIM v//p' || true)"
|
||||
say "LLeMbas plugin $(cat "$LIB/llembas/VERSION" 2>/dev/null || echo missing)"
|
||||
}
|
||||
|
||||
# --- doctor ------------------------------------------------------------------------------------
|
||||
|
||||
BAD=0
|
||||
WARNED=0
|
||||
good() { printf ' ok %s\n' "$*"; }
|
||||
off() {
|
||||
WARNED=$((WARNED + 1))
|
||||
printf ' note %s\n' "$*"
|
||||
}
|
||||
bad() {
|
||||
BAD=$((BAD + 1))
|
||||
printf ' FAIL %s\n' "$*"
|
||||
}
|
||||
|
||||
doctor() {
|
||||
local nvim name where _url commit rest dir count have out lembas paths index
|
||||
nvim="$(nvim_path)"
|
||||
say "LLeMbas IDE $(cat "$LIB/VERSION" 2>/dev/null || echo '(version unknown)') in $PREFIX"
|
||||
say ""
|
||||
say "The editor"
|
||||
if [ -n "$nvim" ] && "$nvim" --version >/dev/null 2>&1; then
|
||||
good "Neovim $("$nvim" --version | sed -n '1s/^NVIM v//p') runs ($nvim; $(cut -d' ' -f1,2 "$LIB/nvim-source" 2>/dev/null))"
|
||||
else
|
||||
bad "Neovim does not run (${nvim:-no path recorded}); run the installer again"
|
||||
fi
|
||||
if [ -f "$CONFIG/init.lua" ]; then
|
||||
if [ "$(sha256_of "$CONFIG/init.lua")" = "$(recorded init_sha)" ]; then
|
||||
good "configuration $CONFIG/init.lua is the IDE's own"
|
||||
else
|
||||
off "$CONFIG/init.lua was edited; an update keeps yours and writes init.lua.new beside it"
|
||||
fi
|
||||
else
|
||||
bad "$CONFIG/init.lua is missing; run the installer again"
|
||||
fi
|
||||
if [ -f "$CONFIG/lua/user/init.lua" ]; then
|
||||
good "your settings: $CONFIG/lua/user/init.lua"
|
||||
else
|
||||
off "no settings file of your own ($CONFIG/lua/user/init.lua); the installer creates one"
|
||||
fi
|
||||
|
||||
say ""
|
||||
say "Plugins, each at its pinned commit"
|
||||
if [ ! -f "$LIB/ide/plugins.lock" ]; then
|
||||
bad "the list of pinned plugins ($LIB/ide/plugins.lock) is missing; run the installer again"
|
||||
elif command -v git >/dev/null 2>&1; then
|
||||
while read -r name where _url commit rest; do
|
||||
dir="$PREFIX/site/pack/llembas/$where/$name"
|
||||
if [ ! -d "$dir/.git" ]; then
|
||||
bad "$name is missing"
|
||||
elif [ "$(git_quiet -C "$dir" rev-parse HEAD 2>/dev/null)" != "$commit" ]; then
|
||||
bad "$name is at $(git_quiet -C "$dir" rev-parse --short HEAD 2>/dev/null), not its pin ${commit:0:12}"
|
||||
elif [ -n "$(changed_in "$dir")" ]; then
|
||||
bad "$name is at its pin but its files were changed or added to"
|
||||
else
|
||||
good "$name ${commit:0:12}"
|
||||
fi
|
||||
done < <(lock_lines "$LIB/ide/plugins.lock")
|
||||
else
|
||||
off "git is not installed: the plugins' commits cannot be checked, and git signs and diffs are off"
|
||||
fi
|
||||
if [ -f "$LIB/llembas/nvim/plugin/llembas.lua" ]; then
|
||||
good "LLeMbas plugin $(cat "$LIB/llembas/VERSION")"
|
||||
else
|
||||
bad "the LLeMbas plugin is missing"
|
||||
fi
|
||||
count="$(lock_lines "$LIB/ide/parsers.lock" 2>/dev/null | wc -l | tr -d ' ' || true)"
|
||||
have="$(find "$PREFIX/site/pack/llembas/start/llembas-parsers/parser" -name '*.so' 2>/dev/null | wc -l | tr -d ' ' || true)"
|
||||
if [ "$have" = "$count" ] && [ "$count" != 0 ]; then
|
||||
good "$have Treesitter grammars compiled"
|
||||
else
|
||||
off "Treesitter grammars are not compiled: Neovim's bundled ones colour C, Lua, Markdown, Vimscript and help;"
|
||||
printf ' %s\n' "other languages use plain syntax files. With a C compiler installed, run: $APP update"
|
||||
fi
|
||||
|
||||
say ""
|
||||
say "A start, headless"
|
||||
if [ -n "$nvim" ]; then
|
||||
out="$(NVIM_APPNAME="$APP" LLEMBAS_IDE_PREFIX="$PREFIX" "$nvim" --headless \
|
||||
--cmd 'lua vim.g.llembas_ide_no_session = true; vim.g.llembas_ide_no_dashboard = true' \
|
||||
-c 'lua local ok, ide = pcall(require, "llembas_ide"); io.stdout:write(ok and ("problems=" .. #ide.problems .. " " .. table.concat(ide.problems, " | ")) or "problems=all the IDE did not load")' \
|
||||
-c 'qa!' 2>&1 || true)"
|
||||
# As the installer judges the same start: a line of Neovim's own beside it is not a failure.
|
||||
case "$out" in
|
||||
*"problems=0"*) good "every part of the IDE loads" ;;
|
||||
*) bad "the IDE does not start cleanly: ${out#*problems=}" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
say ""
|
||||
say "Tools the IDE uses when they are there"
|
||||
if command -v git >/dev/null 2>&1; then good "git"; else off "git: no git signs, no diff, no update"; fi
|
||||
if command -v rg >/dev/null 2>&1; then
|
||||
good "rg (ripgrep)"
|
||||
else
|
||||
off "rg (ripgrep) is missing: searching in files (<Space>/) is off; finding files falls back to git or fd"
|
||||
fi
|
||||
if command -v fd >/dev/null 2>&1 || command -v fdfind >/dev/null 2>&1; then
|
||||
good "fd"
|
||||
else
|
||||
off "fd is missing: nothing is off, rg or git lists the files"
|
||||
fi
|
||||
if command -v cc >/dev/null 2>&1 || command -v gcc >/dev/null 2>&1 || command -v clang >/dev/null 2>&1; then
|
||||
good "a C compiler"
|
||||
else
|
||||
off "no C compiler: Treesitter grammars cannot be compiled at install"
|
||||
fi
|
||||
if command -v curl >/dev/null 2>&1; then good "curl"; else off "curl is missing: $APP update cannot download"; fi
|
||||
if command -v ssh-keygen >/dev/null 2>&1; then
|
||||
good "ssh-keygen"
|
||||
else
|
||||
off "ssh-keygen (openssh-client) is missing: $APP update cannot check a release's signature, and stops"
|
||||
fi
|
||||
if [ -n "${WAYLAND_DISPLAY:-}" ] && ! command -v wl-copy >/dev/null 2>&1; then
|
||||
off "wl-clipboard is missing: the system clipboard is off"
|
||||
fi
|
||||
if [ -z "${WAYLAND_DISPLAY:-}" ] && [ -n "${DISPLAY:-}" ] && ! command -v xclip >/dev/null 2>&1 && ! command -v xsel >/dev/null 2>&1; then
|
||||
off "xclip or xsel is missing: the system clipboard is off"
|
||||
fi
|
||||
case ":$PATH:" in *":$(dirname "$0"):"*) ;; *) off "$(dirname "$0") is not on your PATH" ;; esac
|
||||
|
||||
say ""
|
||||
say "LLeMbas"
|
||||
lembas="$(find_cli || true)"
|
||||
if [ -z "$lembas" ]; then
|
||||
off "the LLeMbas CLI (lembas) is not installed: chat, asking, rewriting and suggestions are off; the editor works. https://github.com/LLeMbas/LLeMbas-CLI"
|
||||
else
|
||||
good "LLeMbas CLI $("$lembas" --version 2>/dev/null || echo '(no version)') ($lembas)"
|
||||
command -v lembas >/dev/null 2>&1 || off "$(dirname "$lembas") is not on your PATH: the IDE finds the CLI there all the same; a terminal does not"
|
||||
# Where the CLI keeps its sign-ins; it has no command that only says whether there is one.
|
||||
paths="$("$lembas" __paths 2>/dev/null || true)"
|
||||
index="$(printf '%s\n' "$paths" | sed -n 's/^config=//p')/lembas.json"
|
||||
if [ -z "$paths" ]; then
|
||||
off "could not tell whether the CLI is signed in; try: lembas login <your server's address>"
|
||||
elif [ -f "$index" ] && grep -q '"base_url"' "$index"; then
|
||||
good "signed in to a LLeMbas server"
|
||||
else
|
||||
off "not signed in: lembas login <your server's address>"
|
||||
fi
|
||||
fi
|
||||
|
||||
say ""
|
||||
if [ "$BAD" -gt 0 ]; then
|
||||
if [ "$BAD" = 1 ]; then say "1 check failed. $APP update installs it again."; else say "$BAD checks failed. $APP update installs it again."; fi
|
||||
return 1
|
||||
fi
|
||||
if [ "$WARNED" -gt 0 ]; then
|
||||
if [ "$WARNED" = 1 ]; then say "The installation is sound; the note above says what is off."; else say "The installation is sound; the $WARNED notes above say what is off."; fi
|
||||
else
|
||||
say "The installation is sound."
|
||||
fi
|
||||
}
|
||||
|
||||
# --- update ------------------------------------------------------------------------------------
|
||||
|
||||
update() {
|
||||
local channel=stable args=()
|
||||
[ -f "$LIB/ide/install.sh" ] || die "the installer is missing from $LIB; install again from https://github.com/LLeMbas/LLeMbas-IDE"
|
||||
# A beta stays with the betas, a release with the releases; --channel says otherwise.
|
||||
case "$(cat "$LIB/VERSION" 2>/dev/null)" in *-beta.*) channel=beta ;; esac
|
||||
args=(--prefix "$PREFIX" --channel "$channel")
|
||||
case "$(cat "$LIB/nvim-source" 2>/dev/null)" in own\ *) args+=(--nvim-bin "$(nvim_path)") ;; esac
|
||||
# Left out on purpose at install, the grammars stay out.
|
||||
[ "$(recorded parsers)" != off ] || args+=(--no-parsers)
|
||||
# The installed installer finds the newest release, checks it, and runs the installer inside it.
|
||||
exec bash "$LIB/ide/install.sh" "${args[@]}" "$@"
|
||||
}
|
||||
|
||||
# --- uninstall ---------------------------------------------------------------------------------
|
||||
|
||||
uninstall() {
|
||||
local purge=0 yes=0 a answer launcher desktop icon keep_config=1
|
||||
for a in "$@"; do
|
||||
case "$a" in
|
||||
--purge) purge=1 ;;
|
||||
--yes | -y) yes=1 ;;
|
||||
*) die "uninstall takes --purge and --yes" ;;
|
||||
esac
|
||||
done
|
||||
launcher="$(recorded launcher)"
|
||||
desktop="$(recorded desktop)"
|
||||
icon="$(recorded icon)"
|
||||
[ -n "$launcher" ] || launcher="$0"
|
||||
say "This removes LLeMbas IDE:"
|
||||
say " $PREFIX/nvim, $PREFIX/site/pack/llembas, $PREFIX/lib"
|
||||
say " $launcher${desktop:+, $desktop, $icon}"
|
||||
say " its history and cache ($STATE, $CACHE)"
|
||||
if [ "$purge" = 1 ]; then say " and your own settings: $CONFIG"; else say "Your own settings in $CONFIG are kept."; fi
|
||||
say "Nothing else is touched: not ~/.config/nvim, not the LLeMbas CLI."
|
||||
if [ "$yes" != 1 ]; then
|
||||
has_tty || die "no terminal to ask on; add --yes"
|
||||
printf 'Remove it? [y/N] ' >/dev/tty
|
||||
read -r answer </dev/tty || answer=""
|
||||
case "$answer" in y | Y | yes | Yes) ;; *) say "Nothing removed." && return 0 ;; esac
|
||||
if [ "$purge" != 1 ] && [ -d "$CONFIG" ]; then
|
||||
printf 'Remove your own settings in %s too? [y/N] ' "$CONFIG" >/dev/tty
|
||||
read -r answer </dev/tty || answer=""
|
||||
case "$answer" in y | Y | yes | Yes) keep_config=0 ;; esac
|
||||
fi
|
||||
fi
|
||||
[ "$purge" != 1 ] || keep_config=0
|
||||
|
||||
# The configuration: the IDE's own init.lua goes when it is still the IDE's; what you wrote stays.
|
||||
if [ "$keep_config" = 0 ]; then
|
||||
remove_app_dir "$CONFIG"
|
||||
else
|
||||
if [ -f "$CONFIG/init.lua" ] && [ "$(sha256_of "$CONFIG/init.lua")" = "$(recorded init_sha)" ]; then
|
||||
rm -f -- "$CONFIG/init.lua"
|
||||
fi
|
||||
rm -f -- "$CONFIG/init.lua.new"
|
||||
fi
|
||||
[ -z "$desktop" ] || rm -f -- "$desktop"
|
||||
[ -z "$icon" ] || rm -f -- "$icon"
|
||||
remove_app_dir "$STATE"
|
||||
remove_app_dir "$CACHE"
|
||||
rm -rf -- "${PREFIX:?}/nvim" "${PREFIX:?}/site/pack/llembas" "${PREFIX:?}/lib"
|
||||
find "${PREFIX:?}" -maxdepth 1 \( -name '.staging.*' -o -name '.old.*' \) -exec rm -rf -- {} + 2>/dev/null || true
|
||||
rmdir "$PREFIX/site/pack" "$PREFIX/site" 2>/dev/null || true
|
||||
# What Neovim itself left in its data directory goes with a purge; otherwise only if empty.
|
||||
[ "$purge" != 1 ] || remove_app_dir "$DATA"
|
||||
rmdir "$PREFIX" 2>/dev/null || true
|
||||
rmdir "$DATA" 2>/dev/null || true
|
||||
rm -f -- "$launcher"
|
||||
if [ "$keep_config" = 1 ] && [ -d "$CONFIG" ]; then
|
||||
say "LLeMbas IDE is removed. Your settings are still in $CONFIG."
|
||||
else
|
||||
say "LLeMbas IDE is removed."
|
||||
fi
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
--version | -V)
|
||||
versions
|
||||
exit 0
|
||||
;;
|
||||
doctor)
|
||||
doctor
|
||||
exit $?
|
||||
;;
|
||||
update)
|
||||
shift
|
||||
update "$@"
|
||||
;;
|
||||
uninstall)
|
||||
shift
|
||||
uninstall "$@"
|
||||
exit 0
|
||||
;;
|
||||
--launcher-help)
|
||||
sed -n '2,/^set -euo/p' "$0" | sed -e '$d' -e 's/^# \{0,1\}//'
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
|
||||
NVIM="$(nvim_path)"
|
||||
if [ -z "$NVIM" ] || [ ! -x "$NVIM" ]; then
|
||||
die "the IDE's Neovim is missing (${NVIM:-no path recorded}); run the installer again"
|
||||
fi
|
||||
export NVIM_APPNAME="$APP" LLEMBAS_IDE_PREFIX="$PREFIX" LLEMBAS_IDE_LAUNCHER="$0"
|
||||
exec "$NVIM" "$@"
|
||||
@@ -0,0 +1,341 @@
|
||||
-- LLeMbas: the colourscheme of LLeMbas IDE. moria when 'background' is dark, shire when light.
|
||||
-- GENERATED by scripts/gen-ide-theme.py from the design tokens. Do not edit: change the tokens
|
||||
-- or the generator, and run it again. Your own colours belong in lua/user/init.lua.
|
||||
local palettes = {
|
||||
dark = { -- moria
|
||||
accent = "#8FD8E8",
|
||||
accent_hover = "#B4E6F1",
|
||||
accent_ink = "#061418",
|
||||
accent_soft = "#1B252A",
|
||||
add_bg = "#1D2F22",
|
||||
bg = "#0B0D10",
|
||||
bg_sunken = "#07090B",
|
||||
border = "#26303A",
|
||||
border_strong = "#5C6976",
|
||||
change_bg = "#2B2317",
|
||||
danger = "#F0735F",
|
||||
danger_soft = "#291A1A",
|
||||
delete_bg = "#301D1D",
|
||||
ghost = "#636D76",
|
||||
guide = "#1E252D",
|
||||
ink = "#E2E8EC",
|
||||
ink_faint = "#808D98",
|
||||
ink_inverse = "#07090B",
|
||||
ink_muted = "#A6B2BC",
|
||||
leaf = "#7EE081",
|
||||
leaf_hover = "#A2EAA3",
|
||||
leaf_soft = "#19261E",
|
||||
line = "#15191F",
|
||||
match = "#503C1E",
|
||||
selection = "#354E55",
|
||||
success = "#5FD6B0",
|
||||
success_soft = "#162725",
|
||||
surface = "#11151A",
|
||||
surface_active = "#232B34",
|
||||
surface_hover = "#1D232B",
|
||||
surface_raised = "#171C22",
|
||||
text_bg = "#543F1F",
|
||||
warning = "#F0A840",
|
||||
warning_soft = "#292116",
|
||||
},
|
||||
light = { -- shire
|
||||
accent = "#285F3C",
|
||||
accent_hover = "#1F4D30",
|
||||
accent_ink = "#F8F3E5",
|
||||
accent_soft = "#DDDCC7",
|
||||
add_bg = "#D4D6B8",
|
||||
bg = "#F1EAD6",
|
||||
bg_sunken = "#E7DEC6",
|
||||
border = "#CBBF9D",
|
||||
border_strong = "#2A2E22",
|
||||
change_bg = "#E1D5B8",
|
||||
danger = "#A3321F",
|
||||
danger_soft = "#E9D8C4",
|
||||
delete_bg = "#E5CDB9",
|
||||
ghost = "#838472",
|
||||
guide = "#D6CCAE",
|
||||
ink = "#1F2418",
|
||||
ink_faint = "#5E6250",
|
||||
ink_inverse = "#F8F3E5",
|
||||
ink_muted = "#474D3B",
|
||||
leaf = "#3D6B1C",
|
||||
leaf_hover = "#2F5615",
|
||||
leaf_soft = "#DFDDC3",
|
||||
line = "#EEE7D2",
|
||||
match = "#CEBC96",
|
||||
selection = "#C1C9B1",
|
||||
success = "#2B6A55",
|
||||
success_soft = "#DDDDC9",
|
||||
surface = "#F8F3E5",
|
||||
surface_active = "#E2D8BD",
|
||||
surface_hover = "#ECE4CF",
|
||||
surface_raised = "#FCF9F0",
|
||||
text_bg = "#CCB992",
|
||||
warning = "#7E5200",
|
||||
warning_soft = "#E6DBC1",
|
||||
},
|
||||
}
|
||||
|
||||
local groups = {
|
||||
["Normal"] = { fg = "ink", bg = "bg" },
|
||||
["NormalNC"] = { fg = "ink", bg = "bg" },
|
||||
["NormalFloat"] = { fg = "ink", bg = "surface" },
|
||||
["FloatBorder"] = { fg = "border_strong", bg = "surface" },
|
||||
["FloatTitle"] = { fg = "leaf", bg = "surface", bold = true },
|
||||
["FloatFooter"] = { fg = "ink_faint", bg = "surface" },
|
||||
["Cursor"] = { fg = "bg", bg = "ink" },
|
||||
["CursorLine"] = { bg = "line" },
|
||||
["CursorColumn"] = { bg = "line" },
|
||||
["ColorColumn"] = { bg = "surface" },
|
||||
["LineNr"] = { fg = "ink_faint" },
|
||||
["CursorLineNr"] = { fg = "leaf", bg = "line", bold = true },
|
||||
["SignColumn"] = { fg = "ink_faint", bg = "bg" },
|
||||
["FoldColumn"] = { fg = "ink_faint", bg = "bg" },
|
||||
["Folded"] = { fg = "ink_muted", bg = "surface" },
|
||||
["WinSeparator"] = { fg = "border" },
|
||||
["VertSplit"] = { fg = "border" },
|
||||
["Visual"] = { bg = "selection" },
|
||||
["VisualNOS"] = { bg = "selection" },
|
||||
["Search"] = { fg = "ink", bg = "match" },
|
||||
["CurSearch"] = { fg = "ink_inverse", bg = "warning", bold = true },
|
||||
["IncSearch"] = { fg = "ink_inverse", bg = "warning", bold = true },
|
||||
["Substitute"] = { fg = "ink_inverse", bg = "danger" },
|
||||
["MatchParen"] = { fg = "accent", bg = "surface_active", bold = true },
|
||||
["NonText"] = { fg = "guide" },
|
||||
["Whitespace"] = { fg = "guide" },
|
||||
["SpecialKey"] = { fg = "guide" },
|
||||
["EndOfBuffer"] = { fg = "bg" },
|
||||
["Conceal"] = { fg = "ink_faint" },
|
||||
["Directory"] = { fg = "accent" },
|
||||
["Title"] = { fg = "leaf", bold = true },
|
||||
["ErrorMsg"] = { fg = "danger" },
|
||||
["WarningMsg"] = { fg = "warning" },
|
||||
["MoreMsg"] = { fg = "accent" },
|
||||
["ModeMsg"] = { fg = "ink_muted" },
|
||||
["Question"] = { fg = "accent" },
|
||||
["MsgArea"] = { fg = "ink" },
|
||||
["MsgSeparator"] = { fg = "border", bg = "bg" },
|
||||
["QuickFixLine"] = { bg = "surface_active", bold = true },
|
||||
["WildMenu"] = { fg = "accent_ink", bg = "accent" },
|
||||
["WinBar"] = { fg = "ink_muted", bg = "bg" },
|
||||
["WinBarNC"] = { fg = "ink_faint", bg = "bg" },
|
||||
["Pmenu"] = { fg = "ink", bg = "surface_raised" },
|
||||
["PmenuSel"] = { fg = "accent_ink", bg = "accent" },
|
||||
["PmenuKind"] = { fg = "ink_faint", bg = "surface_raised" },
|
||||
["PmenuExtra"] = { fg = "ink_faint", bg = "surface_raised" },
|
||||
["PmenuSbar"] = { bg = "surface_hover" },
|
||||
["PmenuThumb"] = { bg = "border_strong" },
|
||||
["PmenuMatch"] = { fg = "accent", bold = true },
|
||||
["PmenuMatchSel"] = { fg = "accent_ink", bold = true },
|
||||
["StatusLine"] = { fg = "ink", bg = "surface_raised" },
|
||||
["StatusLineNC"] = { fg = "ink_faint", bg = "surface" },
|
||||
["TabLine"] = { fg = "ink_muted", bg = "surface" },
|
||||
["TabLineSel"] = { fg = "ink", bg = "bg", bold = true },
|
||||
["TabLineFill"] = { bg = "bg_sunken" },
|
||||
["SpellBad"] = { undercurl = true, sp = "danger" },
|
||||
["SpellCap"] = { undercurl = true, sp = "warning" },
|
||||
["SpellRare"] = { undercurl = true, sp = "accent" },
|
||||
["SpellLocal"] = { undercurl = true, sp = "success" },
|
||||
["Comment"] = { fg = "ink_faint", italic = true },
|
||||
["Constant"] = { fg = "warning" },
|
||||
["String"] = { fg = "leaf" },
|
||||
["Character"] = { fg = "leaf" },
|
||||
["Number"] = { fg = "warning" },
|
||||
["Boolean"] = { fg = "warning" },
|
||||
["Float"] = { fg = "warning" },
|
||||
["Identifier"] = { fg = "ink" },
|
||||
["Function"] = { fg = "accent_hover" },
|
||||
["Statement"] = { fg = "accent" },
|
||||
["Conditional"] = { fg = "accent" },
|
||||
["Repeat"] = { fg = "accent" },
|
||||
["Label"] = { fg = "accent" },
|
||||
["Operator"] = { fg = "ink_muted" },
|
||||
["Keyword"] = { fg = "accent" },
|
||||
["Exception"] = { fg = "danger" },
|
||||
["PreProc"] = { fg = "success" },
|
||||
["Include"] = { fg = "accent" },
|
||||
["Define"] = { fg = "success" },
|
||||
["Macro"] = { fg = "success" },
|
||||
["Type"] = { fg = "success" },
|
||||
["StorageClass"] = { fg = "accent" },
|
||||
["Structure"] = { fg = "success" },
|
||||
["Typedef"] = { fg = "success" },
|
||||
["Special"] = { fg = "accent_hover" },
|
||||
["SpecialChar"] = { fg = "warning" },
|
||||
["Tag"] = { fg = "accent" },
|
||||
["Delimiter"] = { fg = "ink_muted" },
|
||||
["SpecialComment"] = { fg = "ink_muted", italic = true },
|
||||
["Debug"] = { fg = "danger" },
|
||||
["Underlined"] = { fg = "accent", underline = true },
|
||||
["Ignore"] = { fg = "ink_faint" },
|
||||
["Error"] = { fg = "danger" },
|
||||
["Todo"] = { fg = "ink_inverse", bg = "warning", bold = true },
|
||||
["Added"] = { fg = "leaf" },
|
||||
["Changed"] = { fg = "warning" },
|
||||
["Removed"] = { fg = "danger" },
|
||||
["DiffAdd"] = { bg = "add_bg" },
|
||||
["DiffChange"] = { bg = "change_bg" },
|
||||
["DiffDelete"] = { fg = "danger", bg = "delete_bg" },
|
||||
["DiffText"] = { bg = "text_bg", bold = true },
|
||||
["@variable"] = { fg = "ink" },
|
||||
["@variable.builtin"] = { fg = "danger" },
|
||||
["@variable.parameter"] = { fg = "ink", italic = true },
|
||||
["@variable.member"] = { fg = "ink_muted" },
|
||||
["@property"] = { fg = "ink_muted" },
|
||||
["@constant.builtin"] = { fg = "warning" },
|
||||
["@module"] = { fg = "ink" },
|
||||
["@constructor"] = { fg = "success" },
|
||||
["@punctuation"] = { fg = "ink_muted" },
|
||||
["@tag"] = { fg = "accent" },
|
||||
["@tag.attribute"] = { fg = "success" },
|
||||
["@tag.delimiter"] = { fg = "ink_faint" },
|
||||
["@markup.heading"] = { fg = "leaf", bold = true },
|
||||
["@markup.strong"] = { bold = true },
|
||||
["@markup.italic"] = { italic = true },
|
||||
["@markup.link"] = { fg = "accent", underline = true },
|
||||
["@markup.raw"] = { fg = "warning" },
|
||||
["@markup.list"] = { fg = "accent" },
|
||||
["@markup.quote"] = { fg = "ink_muted", italic = true },
|
||||
["LspReferenceText"] = { bg = "surface_active" },
|
||||
["LspReferenceRead"] = { bg = "surface_active" },
|
||||
["LspReferenceWrite"] = { bg = "surface_active" },
|
||||
["LspInlayHint"] = { fg = "ghost", italic = true },
|
||||
["LspSignatureActiveParameter"] = { fg = "warning", bold = true },
|
||||
["DiagnosticError"] = { fg = "danger" },
|
||||
["DiagnosticWarn"] = { fg = "warning" },
|
||||
["DiagnosticInfo"] = { fg = "accent" },
|
||||
["DiagnosticHint"] = { fg = "success" },
|
||||
["DiagnosticOk"] = { fg = "leaf" },
|
||||
["DiagnosticVirtualTextError"] = { fg = "danger", bg = "danger_soft" },
|
||||
["DiagnosticVirtualTextWarn"] = { fg = "warning", bg = "warning_soft" },
|
||||
["DiagnosticVirtualTextInfo"] = { fg = "accent", bg = "accent_soft" },
|
||||
["DiagnosticVirtualTextHint"] = { fg = "success", bg = "success_soft" },
|
||||
["DiagnosticUnderlineError"] = { undercurl = true, sp = "danger" },
|
||||
["DiagnosticUnderlineWarn"] = { undercurl = true, sp = "warning" },
|
||||
["DiagnosticUnderlineInfo"] = { undercurl = true, sp = "accent" },
|
||||
["DiagnosticUnderlineHint"] = { undercurl = true, sp = "success" },
|
||||
["DiagnosticUnnecessary"] = { fg = "ink_faint" },
|
||||
["MiniStatuslineModeNormal"] = { fg = "ink_inverse", bg = "leaf", bold = true },
|
||||
["MiniStatuslineModeInsert"] = { fg = "accent_ink", bg = "accent", bold = true },
|
||||
["MiniStatuslineModeVisual"] = { fg = "ink_inverse", bg = "warning", bold = true },
|
||||
["MiniStatuslineModeReplace"] = { fg = "ink_inverse", bg = "danger", bold = true },
|
||||
["MiniStatuslineModeCommand"] = { fg = "ink_inverse", bg = "success", bold = true },
|
||||
["MiniStatuslineModeOther"] = { fg = "ink_inverse", bg = "ink_muted", bold = true },
|
||||
["MiniStatuslineDevinfo"] = { fg = "ink_muted", bg = "surface_active" },
|
||||
["MiniStatuslineFilename"] = { fg = "ink", bg = "surface_raised" },
|
||||
["MiniStatuslineFileinfo"] = { fg = "ink_muted", bg = "surface_active" },
|
||||
["MiniStatuslineInactive"] = { fg = "ink_faint", bg = "surface" },
|
||||
["MiniTablineCurrent"] = { fg = "ink", bg = "bg", bold = true },
|
||||
["MiniTablineVisible"] = { fg = "ink_muted", bg = "surface" },
|
||||
["MiniTablineHidden"] = { fg = "ink_faint", bg = "bg_sunken" },
|
||||
["MiniTablineModifiedCurrent"] = { fg = "warning", bg = "bg", bold = true },
|
||||
["MiniTablineModifiedVisible"] = { fg = "warning", bg = "surface" },
|
||||
["MiniTablineModifiedHidden"] = { fg = "warning", bg = "bg_sunken" },
|
||||
["MiniTablineFill"] = { bg = "bg_sunken" },
|
||||
["MiniTablineTabpagesection"] = { fg = "ink_inverse", bg = "leaf", bold = true },
|
||||
["MiniTablineTrunc"] = { fg = "ink_faint", bg = "bg_sunken" },
|
||||
["MiniPickMatchCurrent"] = { bg = "surface_active", bold = true },
|
||||
["MiniPickMatchRanges"] = { fg = "accent", bold = true },
|
||||
["MiniPickPrompt"] = { fg = "leaf", bg = "surface", bold = true },
|
||||
["MiniPickBorderText"] = { fg = "leaf", bg = "surface" },
|
||||
["MiniFilesTitleFocused"] = { fg = "leaf", bg = "surface", bold = true },
|
||||
["MiniFilesDirectory"] = { fg = "accent" },
|
||||
["MiniFilesCursorLine"] = { bg = "surface_active" },
|
||||
["MiniClueNextKey"] = { fg = "leaf", bg = "surface", bold = true },
|
||||
["MiniClueNextKeyWithPostkeys"] = { fg = "warning", bg = "surface", bold = true },
|
||||
["MiniClueDescGroup"] = { fg = "accent", bg = "surface" },
|
||||
["MiniClueDescSingle"] = { fg = "ink", bg = "surface" },
|
||||
["MiniClueSeparator"] = { fg = "border_strong", bg = "surface" },
|
||||
["MiniClueTitle"] = { fg = "leaf", bg = "surface", bold = true },
|
||||
["MiniDiffSignAdd"] = { fg = "leaf" },
|
||||
["MiniDiffSignChange"] = { fg = "warning" },
|
||||
["MiniDiffSignDelete"] = { fg = "danger" },
|
||||
["MiniDiffOverAdd"] = { bg = "add_bg" },
|
||||
["MiniDiffOverChange"] = { bg = "text_bg" },
|
||||
["MiniDiffOverChangeBuf"] = { bg = "change_bg" },
|
||||
["MiniDiffOverContext"] = { bg = "change_bg" },
|
||||
["MiniDiffOverContextBuf"] = { },
|
||||
["MiniDiffOverDelete"] = { bg = "delete_bg" },
|
||||
["MiniIconsAzure"] = { fg = "accent" },
|
||||
["MiniIconsBlue"] = { fg = "accent" },
|
||||
["MiniIconsCyan"] = { fg = "success" },
|
||||
["MiniIconsGreen"] = { fg = "leaf" },
|
||||
["MiniIconsGrey"] = { fg = "ink_muted" },
|
||||
["MiniIconsOrange"] = { fg = "warning" },
|
||||
["MiniIconsPurple"] = { fg = "accent_hover" },
|
||||
["MiniIconsRed"] = { fg = "danger" },
|
||||
["MiniIconsYellow"] = { fg = "warning" },
|
||||
["BlinkCmpMenu"] = { fg = "ink", bg = "surface_raised" },
|
||||
["BlinkCmpMenuBorder"] = { fg = "border_strong", bg = "surface_raised" },
|
||||
["BlinkCmpMenuSelection"] = { fg = "accent_ink", bg = "accent" },
|
||||
["BlinkCmpLabelMatch"] = { fg = "accent", bold = true },
|
||||
["BlinkCmpKind"] = { fg = "ink_faint" },
|
||||
["BlinkCmpDoc"] = { fg = "ink", bg = "surface" },
|
||||
["BlinkCmpDocBorder"] = { fg = "border_strong", bg = "surface" },
|
||||
["LLeMbasBrand"] = { fg = "leaf", bold = true },
|
||||
["LLeMbasUserHeader"] = { fg = "accent", bold = true },
|
||||
["LLeMbasAgentHeader"] = { fg = "leaf", bold = true },
|
||||
["LLeMbasThought"] = { fg = "ink_faint", italic = true },
|
||||
["LLeMbasToolPending"] = { fg = "warning" },
|
||||
["LLeMbasToolDone"] = { fg = "success" },
|
||||
["LLeMbasToolFail"] = { fg = "danger" },
|
||||
["LLeMbasToolDenied"] = { fg = "danger", italic = true },
|
||||
["LLeMbasPlanHeader"] = { fg = "accent", bold = true },
|
||||
["LLeMbasDiffAdd"] = { bg = "add_bg" },
|
||||
["LLeMbasDiffDelete"] = { fg = "danger", bg = "delete_bg" },
|
||||
["LLeMbasDiffHint"] = { fg = "ink_faint", italic = true },
|
||||
["LLeMbasGhost"] = { fg = "ghost", italic = true },
|
||||
["LLeMbasSeparator"] = { fg = "border" },
|
||||
["LLeMbasIdeLeaf"] = { fg = "leaf" },
|
||||
["LLeMbasIdeSign"] = { fg = "accent" },
|
||||
["LLeMbasIdeTitle"] = { fg = "ink", bold = true },
|
||||
["LLeMbasIdeVersion"] = { fg = "ink_faint" },
|
||||
["LLeMbasIdeKey"] = { fg = "leaf", bold = true },
|
||||
["LLeMbasIdeAction"] = { fg = "ink" },
|
||||
["LLeMbasIdeMuted"] = { fg = "ink_faint" },
|
||||
["LLeMbasIdeNote"] = { fg = "ink_muted", italic = true },
|
||||
["LLeMbasIdeGood"] = { fg = "success" },
|
||||
["LLeMbasIdeWarn"] = { fg = "warning" },
|
||||
["LLeMbasIdeStatus"] = { fg = "leaf", bg = "surface_raised" },
|
||||
["LLeMbasIdeStatusOff"] = { fg = "ink_faint", bg = "surface_raised" },
|
||||
["LLeMbasBar"] = { fg = "ink_muted", bg = "surface_raised" },
|
||||
["LLeMbasBarKey"] = { fg = "leaf", bg = "surface_raised", bold = true },
|
||||
["LLeMbasBarTitle"] = { fg = "ink", bg = "surface_raised", bold = true },
|
||||
["LLeMbasBarSeparator"] = { fg = "border_strong", bg = "surface_raised" },
|
||||
["LLeMbasBarFact"] = { fg = "ink_faint", bg = "surface_raised" },
|
||||
["LLeMbasBarIdle"] = { fg = "leaf", bg = "surface_raised" },
|
||||
["LLeMbasBarBusy"] = { fg = "warning", bg = "surface_raised", bold = true },
|
||||
["LLeMbasBarWaiting"] = { fg = "accent", bg = "surface_raised", bold = true },
|
||||
["LLeMbasBarOff"] = { fg = "ink_faint", bg = "surface_raised" },
|
||||
["LLeMbasBarVim"] = { fg = "ink", bg = "surface_active" },
|
||||
["LLeMbasPromptPrefix"] = { fg = "leaf", bold = true },
|
||||
["LLeMbasChip"] = { fg = "accent", bg = "accent_soft" },
|
||||
["LLeMbasLineLabel"] = { fg = "ink_faint" },
|
||||
["LLeMbasLineValue"] = { fg = "ink" },
|
||||
["LLeMbasLineOff"] = { fg = "ink_faint", italic = true },
|
||||
["LLeMbasLineCurrent"] = { fg = "leaf", bold = true },
|
||||
["LLeMbasTreeDirectory"] = { fg = "accent" },
|
||||
["LLeMbasTreeCurrent"] = { bg = "surface_active", bold = true },
|
||||
["LLeMbasTreeChanged"] = { fg = "warning" },
|
||||
["LLeMbasTreeAdded"] = { fg = "success" },
|
||||
["LLeMbasTreeNew"] = { fg = "leaf" },
|
||||
["LLeMbasTreeDeleted"] = { fg = "danger" },
|
||||
["LLeMbasTreeConflict"] = { fg = "danger", bold = true },
|
||||
}
|
||||
|
||||
local terminal = { "bg_sunken", "danger", "leaf", "warning", "accent", "accent_hover", "success", "ink_muted", "border_strong", "danger", "leaf_hover", "warning", "accent_hover", "accent_hover", "success", "ink" }
|
||||
|
||||
if vim.g.colors_name then vim.cmd("highlight clear") end
|
||||
vim.g.colors_name = "llembas"
|
||||
local p = palettes[vim.o.background == "light" and "light" or "dark"]
|
||||
for name, spec in pairs(groups) do
|
||||
local hl = {}
|
||||
for key, value in pairs(spec) do
|
||||
if key == "fg" or key == "bg" or key == "sp" then hl[key] = p[value] else hl[key] = value end
|
||||
end
|
||||
vim.api.nvim_set_hl(0, name, hl)
|
||||
end
|
||||
for i, name in ipairs(terminal) do vim.g["terminal_color_" .. (i - 1)] = p[name] end
|
||||
|
||||
-- For the configuration: the palette in use, by token name.
|
||||
return p
|
||||
@@ -0,0 +1,20 @@
|
||||
-- LLeMbas IDE. This file starts the distribution and is replaced when the IDE is updated.
|
||||
-- Your own settings, keys and plugins belong in lua/user/init.lua beside it, which is loaded
|
||||
-- last and is never overwritten.
|
||||
local prefix = vim.env.LLEMBAS_IDE_PREFIX
|
||||
if not prefix or prefix == "" then prefix = vim.fn.stdpath("data") end
|
||||
local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h")
|
||||
if vim.fn.isdirectory(here .. "/lua/llembas_ide") == 0 then
|
||||
-- Installed: the distribution and its pinned plugins are packages under the prefix.
|
||||
vim.opt.packpath:prepend(prefix .. "/site")
|
||||
end
|
||||
local ok, ide = pcall(require, "llembas_ide")
|
||||
if not ok then
|
||||
vim.api.nvim_echo({
|
||||
{ "LLeMbas IDE is not installed where this configuration expects it (" .. prefix .. ").\n", "WarningMsg" },
|
||||
{ "Run the installer again, or `llembas-ide doctor`. Neovim itself works.\n", "WarningMsg" },
|
||||
{ tostring(ide) .. "\n", "Comment" },
|
||||
}, true, {})
|
||||
return
|
||||
end
|
||||
ide.start({ prefix = prefix })
|
||||
@@ -0,0 +1,56 @@
|
||||
-- The bars. LLeMbas IDE's own are the LLeMbas plugin's layout (lua/llembas/layout.lua): the top
|
||||
-- bar is the tabline, the bottom bar the statusline. What is here is what stands in when one of
|
||||
-- them is switched off: mini.statusline for the bottom, mini.tabline (the open buffers) for the top.
|
||||
local M = {}
|
||||
local set = { statusline = false, tabline = false }
|
||||
|
||||
local function active()
|
||||
local s = require("mini.statusline")
|
||||
local mode, mode_hl = s.section_mode({ trunc_width = 100 })
|
||||
local git = s.section_git({ trunc_width = 60 })
|
||||
local diff = s.section_diff({ trunc_width = 80 })
|
||||
local diagnostics = s.section_diagnostics({ trunc_width = 80 })
|
||||
local lsp = s.section_lsp({ trunc_width = 100 })
|
||||
local filename = s.section_filename({ trunc_width = 140 })
|
||||
local fileinfo = s.section_fileinfo({ trunc_width = 120 })
|
||||
local llembas, live = require("llembas_ide.llembas").status()
|
||||
if s.is_truncated(70) then llembas = "" end
|
||||
return s.combine_groups({
|
||||
{ hl = mode_hl, strings = { mode } },
|
||||
{ hl = "MiniStatuslineDevinfo", strings = { git, diff, diagnostics, lsp } },
|
||||
"%<",
|
||||
{ hl = "MiniStatuslineFilename", strings = { filename } },
|
||||
"%=",
|
||||
{ hl = live and "LLeMbasIdeStatus" or "LLeMbasIdeStatusOff", strings = { (llembas:gsub("%%", "%%%%")) } },
|
||||
{ hl = "MiniStatuslineFileinfo", strings = { fileinfo } },
|
||||
{ hl = mode_hl, strings = { "%l:%v" } },
|
||||
})
|
||||
end
|
||||
|
||||
--- Set up the stand-in for each bar of the layout that is off. Called at the start and whenever
|
||||
--- the layout's bars change (`User LLeMbasBars`).
|
||||
function M.refresh()
|
||||
local ok, layout = pcall(require, "llembas.layout")
|
||||
local o = ok and layout.options() or { on = false }
|
||||
if not (o.on and o.bottom) and not set.statusline then
|
||||
set.statusline = true
|
||||
require("mini.statusline").setup({ use_icons = false, content = { active = active } })
|
||||
end
|
||||
if not (o.on and o.top) and not set.tabline then
|
||||
set.tabline = true
|
||||
require("mini.tabline").setup({ show_icons = false })
|
||||
end
|
||||
end
|
||||
|
||||
M.active = active
|
||||
|
||||
function M.setup()
|
||||
M.refresh()
|
||||
vim.api.nvim_create_autocmd("User", {
|
||||
group = vim.api.nvim_create_augroup("llembas_ide_bars", { clear = true }),
|
||||
pattern = "LLeMbasBars",
|
||||
callback = function() M.refresh() end,
|
||||
})
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,20 @@
|
||||
-- The LLeMbas IDE mark as text: the mallorn leaf with the editor's angle brackets, drawn in
|
||||
-- half blocks from the product icon. Each row is { leaf, sign }: two colours, one picture.
|
||||
local M = {}
|
||||
|
||||
M.name = "LLeMbas IDE"
|
||||
M.mark = {
|
||||
{ " ▄▄▄▄▄ ", "" },
|
||||
{ " ▄▄███████ ", "" },
|
||||
{ " ▄████████ ", "" },
|
||||
{ " ▄████████▀ ", "" },
|
||||
{ " ███████▀ ", "" },
|
||||
{ " ███▀▀▀ ", "" },
|
||||
{ " ▄▀ ", "▄▄ ▄▄ " },
|
||||
{ "▀ ", "▄█▀ ▀█▄" },
|
||||
{ " ", "▀█▄ ▄█▀ " },
|
||||
}
|
||||
-- The welcome line: the one place the road shows.
|
||||
M.welcome = "Waybread for the code ahead."
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,48 @@
|
||||
-- The IDE's own commands. All begin with :LLeMbasIde.
|
||||
local M = {}
|
||||
|
||||
local function launcher()
|
||||
local l = vim.env.LLEMBAS_IDE_LAUNCHER
|
||||
if l and l ~= "" and vim.fn.executable(l) == 1 then return l end
|
||||
if vim.fn.executable("llembas-ide") == 1 then return "llembas-ide" end
|
||||
return nil
|
||||
end
|
||||
|
||||
function M.versions()
|
||||
local ide = require("llembas_ide")
|
||||
local v = vim.version()
|
||||
return {
|
||||
("LLeMbas IDE %s"):format(ide.version),
|
||||
("Neovim %d.%d.%d"):format(v.major, v.minor, v.patch),
|
||||
("LLeMbas plugin %s"):format(require("llembas_ide.llembas").version() or "not installed"),
|
||||
}
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
local cmd = vim.api.nvim_create_user_command
|
||||
cmd("LLeMbasIdeKeys", function() require("llembas_ide.keys").show() end, { desc = "LLeMbas IDE: the keys" })
|
||||
cmd("LLeMbasIdeHome", function() require("llembas_ide.dashboard").open() end, { desc = "LLeMbas IDE: the start screen" })
|
||||
cmd("LLeMbasIdeLsp", function() require("llembas_ide.lsp").guide() end, { desc = "LLeMbas IDE: language servers, found and missing" })
|
||||
cmd("LLeMbasIdeFormat", function() require("llembas_ide.plugins").format() end, { range = true, desc = "LLeMbas IDE: format the file or the selection" })
|
||||
cmd("LLeMbasIdeTerminal", function() require("llembas_ide.terminal").toggle() end, { desc = "LLeMbas IDE: the terminal, open and close" })
|
||||
cmd("LLeMbasIdeDiff", function() require("llembas_ide.git").diff_head() end, { desc = "LLeMbas IDE: this file beside its committed version" })
|
||||
cmd("LLeMbasIdeSignIn", function() require("llembas_ide.llembas").sign_in() end, { desc = "LLeMbas IDE: sign in to LLeMbas" })
|
||||
cmd("LLeMbasIdeVersion", function() vim.notify(table.concat(M.versions(), "\n")) end, { desc = "LLeMbas IDE: versions" })
|
||||
cmd("LLeMbasIdeConfig", function()
|
||||
vim.cmd.edit(vim.fn.fnameescape(vim.fn.stdpath("config") .. "/lua/user/init.lua"))
|
||||
end, { desc = "LLeMbas IDE: open your own settings file" })
|
||||
cmd("LLeMbasIdeProblems", function()
|
||||
local p = require("llembas_ide").problems
|
||||
local lines = #p == 0 and { "Every part of the IDE started." } or vim.list_extend({ "These parts did not start:", "" }, p)
|
||||
require("llembas_ide.ui").page("LLeMbas IDE: problems", lines)
|
||||
end, { desc = "LLeMbas IDE: what did not start" })
|
||||
cmd("LLeMbasIdeDoctor", function()
|
||||
local l = launcher()
|
||||
if not l then
|
||||
return vim.notify("The llembas-ide command is not on PATH; run `llembas-ide doctor` from where it was installed (~/.local/bin).", vim.log.levels.WARN)
|
||||
end
|
||||
require("llembas_ide.terminal").run({ l, "doctor" })
|
||||
end, { desc = "LLeMbas IDE: check the installation" })
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,43 @@
|
||||
-- The completion menu: language server, paths and words of the open buffers.
|
||||
--
|
||||
-- It shares insert mode with LLeMbas's suggestions (the grey text ahead of the cursor), and the
|
||||
-- two never want the same key:
|
||||
-- <Tab> accepts LLeMbas's suggestion (<M-Right> one word of it). Never the menu.
|
||||
-- <C-n> <C-p> or <Down> <Up> move in the menu; nothing in it is chosen until you do.
|
||||
-- <CR> takes the menu entry you moved to; with none chosen it is a plain Enter.
|
||||
-- <C-y> takes the first entry without moving.
|
||||
-- <C-e> closes the menu. <C-Space> opens it, or shows the entry's documentation.
|
||||
local M = {}
|
||||
|
||||
function M.setup()
|
||||
require("blink.cmp").setup({
|
||||
keymap = {
|
||||
preset = "none",
|
||||
["<C-Space>"] = { "show", "show_documentation", "hide_documentation" },
|
||||
["<C-e>"] = { "hide", "fallback" },
|
||||
["<C-y>"] = { "select_and_accept", "fallback" },
|
||||
["<CR>"] = { "accept", "fallback" },
|
||||
["<C-n>"] = { "select_next", "fallback_to_mappings" },
|
||||
["<C-p>"] = { "select_prev", "fallback_to_mappings" },
|
||||
["<Down>"] = { "select_next", "fallback" },
|
||||
["<Up>"] = { "select_prev", "fallback" },
|
||||
["<C-f>"] = { "scroll_documentation_down", "fallback" },
|
||||
["<C-b>"] = { "scroll_documentation_up", "fallback" },
|
||||
},
|
||||
completion = {
|
||||
list = { selection = { preselect = false, auto_insert = false } },
|
||||
ghost_text = { enabled = false }, -- the grey text is LLeMbas's
|
||||
documentation = { auto_show = true, auto_show_delay_ms = 400, window = { border = "rounded" } },
|
||||
menu = {
|
||||
border = "rounded",
|
||||
draw = { columns = { { "label", "label_description", gap = 1 }, { "kind" } } }, -- kinds in words: no icon font needed
|
||||
},
|
||||
},
|
||||
sources = { default = { "lsp", "path", "buffer" } },
|
||||
cmdline = { enabled = false }, -- the command line keeps Neovim's own completion
|
||||
-- The matcher written in Lua: the compiled one would be a binary downloaded at run time.
|
||||
fuzzy = { implementation = "lua", prebuilt_binaries = { download = false } },
|
||||
})
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,176 @@
|
||||
-- The start screen: the mark, the name and version, and what to do next, one key each.
|
||||
-- Shown when the IDE starts without a file; <leader>ih brings it back.
|
||||
local M = {}
|
||||
|
||||
local ns = vim.api.nvim_create_namespace("llembas_ide_dashboard")
|
||||
|
||||
local function act(fn) return function() vim.schedule(fn) end end
|
||||
|
||||
-- { key, what it does, action }
|
||||
M.actions = {
|
||||
{ "n", "New file", function() vim.cmd.enew() end },
|
||||
{ "f", "Find a file", function() require("mini.pick").builtin.files() end },
|
||||
{ "r", "Recent files", function() require("mini.extra").pickers.oldfiles() end },
|
||||
{ "s", "Restore this directory's session", function() require("llembas_ide.sessions").restore() end },
|
||||
{ "l", "LLeMbas chat", function() require("llembas_ide.llembas").cmd("LLeMbasPrompt")() end },
|
||||
{ "i", "Sign in to LLeMbas", function() require("llembas_ide.llembas").sign_in() end },
|
||||
{ "k", "Keys", function() require("llembas_ide.keys").show() end },
|
||||
{ "d", "Check the installation", function() vim.cmd("LLeMbasIdeDoctor") end },
|
||||
{ "q", "Quit", function() vim.cmd("confirm qall") end },
|
||||
}
|
||||
|
||||
local function first_run()
|
||||
local marker = vim.fn.stdpath("state") .. "/welcomed"
|
||||
if vim.fn.filereadable(marker) == 1 then return false end
|
||||
vim.fn.mkdir(vim.fn.stdpath("state"), "p")
|
||||
pcall(vim.fn.writefile, { os.date("%Y-%m-%d") }, marker)
|
||||
return true
|
||||
end
|
||||
|
||||
-- The block: the mark, the name and the actions share one column of a known width, so the keys
|
||||
-- line up by construction. Notes are short lines centred on their own.
|
||||
local ACTION_WIDTH = 38
|
||||
|
||||
--- The screen's rows: { text, { {from, to, group}, … }, in_block }.
|
||||
function M.content(welcome)
|
||||
local ide, brand = require("llembas_ide"), require("llembas_ide.brand")
|
||||
local llembas = require("llembas_ide.llembas")
|
||||
local rows = {}
|
||||
local function row(text, marks, in_block) table.insert(rows, { text, marks or {}, in_block == true }) end
|
||||
local function inside(text) -- centred within the block's own width
|
||||
return string.rep(" ", math.max(0, math.floor((ACTION_WIDTH - vim.fn.strdisplaywidth(text)) / 2)))
|
||||
end
|
||||
local function note(text, group) row(text, { { 0, -1, group or "LLeMbasIdeMuted" } }) end
|
||||
|
||||
for _, pair in ipairs(brand.mark) do
|
||||
local pad = inside(brand.mark[1][1])
|
||||
row(pad .. pair[1] .. pair[2], {
|
||||
{ #pad, #pad + #pair[1], "LLeMbasIdeLeaf" },
|
||||
{ #pad + #pair[1], #pad + #pair[1] + #pair[2], "LLeMbasIdeSign" },
|
||||
}, true)
|
||||
end
|
||||
row("")
|
||||
local title = brand.name .. " " .. ide.version
|
||||
local pad = inside(title)
|
||||
row(pad .. title, { { #pad, #pad + #brand.name, "LLeMbasIdeTitle" }, { #pad + #brand.name, #pad + #title, "LLeMbasIdeVersion" } }, true)
|
||||
pad = inside(brand.welcome)
|
||||
row(pad .. brand.welcome, { { #pad, -1, "LLeMbasIdeNote" } }, true)
|
||||
row("")
|
||||
for _, a in ipairs(M.actions) do
|
||||
local text = ("%s %-" .. (ACTION_WIDTH - 4) .. "s"):format(a[1], a[2])
|
||||
row(text, { { 0, 1, "LLeMbasIdeKey" }, { 1, #text, "LLeMbasIdeAction" } }, true)
|
||||
end
|
||||
row("")
|
||||
if not llembas.loaded then
|
||||
note("The LLeMbas plugin is missing. The editor works.")
|
||||
note("Press d to check the installation.")
|
||||
elseif not llembas.has_cli() then
|
||||
note("The LLeMbas CLI is not installed.")
|
||||
note("The editor works without it. Press i.")
|
||||
else
|
||||
-- Whether there is a sign-in is looked up on this machine once; until it is known, and when
|
||||
-- it cannot be told, nothing is claimed either way.
|
||||
local signed = llembas.signed_in(M.redraw)
|
||||
if signed == true then
|
||||
note("LLeMbas is signed in: press l to chat.")
|
||||
elseif signed == false then
|
||||
note("LLeMbas needs a server and a sign-in: press i.")
|
||||
note("The editor works without them.")
|
||||
else
|
||||
note("LLeMbas: press l to chat, i to sign in.")
|
||||
end
|
||||
end
|
||||
if welcome then
|
||||
row("")
|
||||
note("Welcome. <Space> is the leader key:")
|
||||
note("press it and wait to see what follows.")
|
||||
note("Your own settings: <Space>iu")
|
||||
note("Nothing leaves this machine until you use LLeMbas.")
|
||||
end
|
||||
if #ide.problems > 0 then
|
||||
row("")
|
||||
note((#ide.problems == 1 and "1 part" or (#ide.problems .. " parts")) .. " did not start: :LLeMbasIdeProblems", "LLeMbasIdeWarn")
|
||||
end
|
||||
return rows
|
||||
end
|
||||
|
||||
local function draw(buf, win, welcome)
|
||||
local rows = M.content(welcome)
|
||||
local width, height = vim.api.nvim_win_get_width(win), vim.api.nvim_win_get_height(win)
|
||||
local block_pad = math.max(0, math.floor((width - ACTION_WIDTH) / 2))
|
||||
local pad_top = math.max(0, math.floor((height - #rows) / 2))
|
||||
local lines, pads = {}, {}
|
||||
for _ = 1, pad_top do table.insert(lines, "") end
|
||||
for i, r in ipairs(rows) do
|
||||
pads[i] = r[3] and block_pad or math.max(0, math.floor((width - vim.fn.strdisplaywidth(r[1])) / 2))
|
||||
table.insert(lines, r[1] == "" and "" or string.rep(" ", pads[i]) .. r[1])
|
||||
end
|
||||
vim.bo[buf].modifiable = true
|
||||
vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
|
||||
vim.bo[buf].modifiable = false
|
||||
vim.bo[buf].modified = false
|
||||
vim.api.nvim_buf_clear_namespace(buf, ns, 0, -1)
|
||||
for i, r in ipairs(rows) do
|
||||
for _, m in ipairs(r[2]) do
|
||||
vim.api.nvim_buf_add_highlight(buf, ns, m[3], pad_top + i - 1, pads[i] + m[1], m[2] == -1 and -1 or pads[i] + m[2])
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Draw the start screen again where it is shown (its notes changed).
|
||||
function M.redraw()
|
||||
for _, w in ipairs(vim.api.nvim_list_wins()) do
|
||||
local b = vim.api.nvim_win_get_buf(w)
|
||||
if vim.bo[b].filetype == "llembas-ide-dashboard" then draw(b, w, vim.b[b].llembas_ide_welcome == true) end
|
||||
end
|
||||
end
|
||||
|
||||
function M.open(welcome)
|
||||
local buf = vim.api.nvim_create_buf(false, true)
|
||||
vim.b[buf].llembas_ide_welcome = welcome == true
|
||||
vim.bo[buf].bufhidden = "wipe"
|
||||
vim.bo[buf].buftype = "nofile"
|
||||
vim.bo[buf].swapfile = false
|
||||
vim.bo[buf].filetype = "llembas-ide-dashboard"
|
||||
vim.api.nvim_set_current_buf(buf)
|
||||
local win = vim.api.nvim_get_current_win()
|
||||
for opt, value in pairs({ number = false, relativenumber = false, cursorline = false, signcolumn = "no", list = false, wrap = false }) do
|
||||
vim.api.nvim_set_option_value(opt, value, { scope = "local", win = win })
|
||||
end
|
||||
draw(buf, win, welcome == true)
|
||||
for _, a in ipairs(M.actions) do
|
||||
vim.keymap.set("n", a[1], act(a[3]), { buffer = buf, nowait = true, silent = true, desc = a[2] })
|
||||
end
|
||||
local group = vim.api.nvim_create_augroup("llembas_ide_dashboard_" .. buf, { clear = true })
|
||||
-- Drawn again when the screen changes size, and when the bars beside it have been laid out.
|
||||
vim.api.nvim_create_autocmd({ "VimResized", "User" }, {
|
||||
group = group,
|
||||
pattern = { "*", "LLeMbasLayout" },
|
||||
callback = function(ev)
|
||||
if ev.event == "User" and ev.match ~= "LLeMbasLayout" then return end
|
||||
local w = vim.fn.bufwinid(buf)
|
||||
if w ~= -1 then draw(buf, w, welcome == true) end
|
||||
end,
|
||||
})
|
||||
vim.api.nvim_create_autocmd("BufWipeout", {
|
||||
group = group, buffer = buf,
|
||||
callback = function() pcall(vim.api.nvim_del_augroup_by_id, group) end,
|
||||
})
|
||||
return buf
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
vim.api.nvim_create_autocmd("VimEnter", {
|
||||
group = vim.api.nvim_create_augroup("llembas_ide_dashboard", { clear = true }),
|
||||
once = true,
|
||||
callback = function()
|
||||
-- Only on an empty start: no file named, nothing piped in, nothing typed into the buffer.
|
||||
if vim.fn.argc() > 0 or vim.g.llembas_ide_no_dashboard then return end
|
||||
if vim.api.nvim_buf_get_name(0) ~= "" or vim.bo.modified or vim.bo.filetype ~= "" then return end
|
||||
if vim.api.nvim_buf_line_count(0) > 1 or vim.api.nvim_buf_get_lines(0, 0, 1, false)[1] ~= "" then return end
|
||||
M.open(first_run())
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,98 @@
|
||||
-- A directory opened like a file — `llembas-ide .`, `llembas-ide src/`, `:e src/` — goes to the
|
||||
-- tree, the left bar. Neither netrw nor mini.files takes it over: either one would open a second
|
||||
-- explorer over the bars. mini.files stays on <Space>E, asked for by name.
|
||||
--
|
||||
-- At the start the directory becomes the working directory, so the tree is rooted there and the
|
||||
-- start screen shows. Later it is opened in the tree and the focus goes there; the window keeps
|
||||
-- what it showed before. Without the bars, or for a directory outside the tree, it is mini.files.
|
||||
local M = {}
|
||||
|
||||
--- The directory `buf` names, as a full path, or nil when it is not a directory.
|
||||
function M.dir_of(buf)
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
if name == "" or vim.bo[buf].buftype ~= "" then return nil end
|
||||
if vim.fn.isdirectory(name) == 0 then return nil end
|
||||
return vim.fs.normalize(vim.uv.fs_realpath(name) or name)
|
||||
end
|
||||
|
||||
--- The directory the editor was started with, alone (`llembas-ide .`), or nil.
|
||||
function M.start_dir()
|
||||
if vim.fn.argc() ~= 1 then return nil end
|
||||
local arg = vim.fn.argv(0)
|
||||
if type(arg) ~= "string" or vim.fn.isdirectory(arg) == 0 then return nil end
|
||||
return vim.fs.normalize(vim.uv.fs_realpath(arg) or arg)
|
||||
end
|
||||
|
||||
local function layout_on()
|
||||
local ok, layout = pcall(require, "llembas.layout")
|
||||
return ok and layout.options().on == true
|
||||
end
|
||||
|
||||
--- Put something else in `win` instead of the directory buffer `buf`, then wipe `buf`: the file
|
||||
--- shown before, when there was one, else an empty buffer.
|
||||
local function replace(win, buf)
|
||||
if not vim.api.nvim_win_is_valid(win) then return end
|
||||
local alt = vim.fn.bufnr("#")
|
||||
if alt > 0 and alt ~= buf and vim.api.nvim_buf_is_valid(alt) and vim.bo[alt].buflisted and M.dir_of(alt) == nil then
|
||||
vim.api.nvim_win_set_buf(win, alt)
|
||||
else
|
||||
local empty = vim.api.nvim_create_buf(true, false)
|
||||
vim.api.nvim_win_set_buf(win, empty)
|
||||
end
|
||||
if vim.api.nvim_buf_is_valid(buf) then pcall(vim.api.nvim_buf_delete, buf, { force = true }) end
|
||||
end
|
||||
|
||||
--- The directory buffer `buf`, entered in `win` after the start: shown in the tree.
|
||||
function M.open_later(buf, win)
|
||||
local dir = M.dir_of(buf)
|
||||
if not dir then return end
|
||||
replace(win, buf)
|
||||
if layout_on() then
|
||||
local layout, tree = require("llembas.layout"), require("llembas.tree")
|
||||
if not tree.is_open() then layout.toggle("tree", true) end
|
||||
if tree.show_dir(dir) then return layout.focus("tree") end
|
||||
end
|
||||
local ok, files = pcall(require, "mini.files")
|
||||
if ok then
|
||||
files.open(dir)
|
||||
else
|
||||
vim.notify(dir .. " is a directory", vim.log.levels.INFO)
|
||||
end
|
||||
end
|
||||
|
||||
--- At the start: the directory argument becomes the working directory, and its buffer goes.
|
||||
function M.open_at_start()
|
||||
local dir = M.start_dir()
|
||||
if not dir then return false end
|
||||
vim.cmd.cd(vim.fn.fnameescape(dir))
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
if M.dir_of(b) then
|
||||
for _, w in ipairs(vim.fn.win_findbuf(b)) do
|
||||
vim.api.nvim_win_set_buf(w, vim.api.nvim_create_buf(true, false))
|
||||
end
|
||||
pcall(vim.api.nvim_buf_delete, b, { force = true })
|
||||
end
|
||||
end
|
||||
-- The empty buffer counts as a start without a file: no argument is left to name.
|
||||
pcall(vim.cmd, "silent! argdelete *")
|
||||
vim.g.llembas_ide_started_in_dir = dir
|
||||
return true
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
local group = vim.api.nvim_create_augroup("llembas_ide_directories", { clear = true })
|
||||
-- Registered before the start screen's own VimEnter, so that it sees an empty start.
|
||||
vim.api.nvim_create_autocmd("VimEnter", { group = group, once = true, callback = M.open_at_start })
|
||||
vim.api.nvim_create_autocmd("BufEnter", {
|
||||
group = group,
|
||||
callback = function(ev)
|
||||
if vim.v.vim_did_enter ~= 1 or not M.dir_of(ev.buf) then return end
|
||||
local win = vim.api.nvim_get_current_win()
|
||||
vim.schedule(function()
|
||||
if vim.api.nvim_buf_is_valid(ev.buf) then M.open_later(ev.buf, win) end
|
||||
end)
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,46 @@
|
||||
-- The file beside its committed version, as a two-window diff.
|
||||
local M = {}
|
||||
|
||||
function M.diff_head()
|
||||
local file = vim.api.nvim_buf_get_name(0)
|
||||
if file == "" or vim.bo.buftype ~= "" then return vim.notify("Diff: this buffer is not a file", vim.log.levels.INFO) end
|
||||
if vim.fn.executable("git") == 0 then return vim.notify("Diff: git is not installed", vim.log.levels.WARN) end
|
||||
local dir = vim.fn.fnamemodify(file, ":h")
|
||||
local rel = vim.fn.systemlist({ "git", "-C", dir, "ls-files", "--full-name", "--", file })[1]
|
||||
if vim.v.shell_error ~= 0 or not rel or rel == "" then
|
||||
return vim.notify("Diff: this file is not tracked by git", vim.log.levels.INFO)
|
||||
end
|
||||
local old = vim.fn.systemlist({ "git", "-C", dir, "show", "HEAD:" .. rel })
|
||||
if vim.v.shell_error ~= 0 then return vim.notify("Diff: no committed version of this file yet", vim.log.levels.INFO) end
|
||||
|
||||
local ft, win = vim.bo.filetype, vim.api.nvim_get_current_win()
|
||||
vim.cmd("leftabove vnew")
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
vim.api.nvim_buf_set_lines(buf, 0, -1, false, old)
|
||||
vim.bo[buf].buftype = "nofile"
|
||||
vim.bo[buf].bufhidden = "wipe"
|
||||
vim.bo[buf].swapfile = false
|
||||
vim.bo[buf].modifiable = false
|
||||
vim.bo[buf].filetype = ft
|
||||
pcall(vim.api.nvim_buf_set_name, buf, "HEAD:" .. rel)
|
||||
vim.cmd.diffthis()
|
||||
vim.api.nvim_set_current_win(win)
|
||||
vim.cmd.diffthis()
|
||||
local function close()
|
||||
if vim.api.nvim_buf_is_valid(buf) then vim.api.nvim_buf_delete(buf, { force = true }) end
|
||||
if vim.api.nvim_win_is_valid(win) then vim.api.nvim_win_call(win, function() vim.cmd.diffoff() end) end
|
||||
end
|
||||
vim.keymap.set("n", "q", close, { buffer = buf, nowait = true, desc = "Close the diff" })
|
||||
end
|
||||
|
||||
local function hunk_at_cursor(action)
|
||||
local ok, diff = pcall(require, "mini.diff")
|
||||
if not ok then return end
|
||||
local line = vim.api.nvim_win_get_cursor(0)[1]
|
||||
pcall(diff.do_hunks, 0, action, { line_start = line, line_end = line })
|
||||
end
|
||||
|
||||
function M.stage_hunk() hunk_at_cursor("apply") end
|
||||
function M.reset_hunk() hunk_at_cursor("reset") end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,72 @@
|
||||
-- LLeMbas IDE: a complete Neovim, with LLeMbas built in. Everything here works from what the
|
||||
-- installer placed: nothing is fetched, installed or updated when the editor starts.
|
||||
local M = {}
|
||||
|
||||
M.name = "LLeMbas IDE"
|
||||
M.problems = {} -- what could not be set up, in words; the dashboard and :LLeMbasIdeDoctor show it
|
||||
M.prefix = nil
|
||||
M.version = "dev"
|
||||
|
||||
--- Run one part of the setup; a part that fails is named, and the editor still starts.
|
||||
function M.try(what, fn)
|
||||
local ok, err = xpcall(fn, debug.traceback)
|
||||
if not ok then table.insert(M.problems, what .. ": " .. tostring(err):gsub("\n.*", "")) end
|
||||
return ok
|
||||
end
|
||||
|
||||
local function read_first_line(path)
|
||||
local f = io.open(path, "r")
|
||||
if not f then return nil end
|
||||
local line = f:read("*l")
|
||||
f:close()
|
||||
return line and vim.trim(line) or nil
|
||||
end
|
||||
|
||||
--- Whether a plugin the installer places is there: a module that `require` can find.
|
||||
function M.has(module)
|
||||
return #vim.api.nvim_get_runtime_file("lua/" .. module:gsub("%.", "/") .. ".lua", false) > 0
|
||||
or #vim.api.nvim_get_runtime_file("lua/" .. module:gsub("%.", "/") .. "/init.lua", false) > 0
|
||||
end
|
||||
|
||||
function M.start(opts)
|
||||
if M.started then return end
|
||||
M.started = true
|
||||
M.prefix = opts and opts.prefix or vim.fn.stdpath("data")
|
||||
local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h")
|
||||
M.version = read_first_line(M.prefix .. "/lib/VERSION")
|
||||
or read_first_line(vim.fn.fnamemodify(here, ":h:h:h:h") .. "/VERSION") -- a checkout
|
||||
or "dev"
|
||||
|
||||
-- The LLeMbas plugin sits beside its VERSION file, as it does in its repository.
|
||||
local plugin = M.prefix .. "/lib/llembas/nvim"
|
||||
if vim.fn.isdirectory(plugin) == 0 then plugin = vim.fn.fnamemodify(here, ":h:h:h:h") .. "/nvim" end
|
||||
if vim.fn.isdirectory(plugin) == 1 then vim.opt.runtimepath:prepend(plugin) end
|
||||
|
||||
M.try("options", function() require("llembas_ide.options").setup() end)
|
||||
M.try("theme", function() vim.cmd.colorscheme("llembas") end)
|
||||
M.try("plugins", function() require("llembas_ide.plugins").setup() end)
|
||||
M.try("treesitter", function() require("llembas_ide.treesitter").setup() end)
|
||||
M.try("completion", function() require("llembas_ide.completion").setup() end)
|
||||
M.try("lsp", function() require("llembas_ide.lsp").setup() end)
|
||||
M.try("llembas", function() require("llembas_ide.llembas").setup() end)
|
||||
M.try("bars", function() require("llembas_ide.bars").setup() end)
|
||||
M.try("sessions", function() require("llembas_ide.sessions").setup() end)
|
||||
M.try("keys", function() require("llembas_ide.keys").setup() end)
|
||||
M.try("commands", function() require("llembas_ide.commands").setup() end)
|
||||
M.try("directories", function() require("llembas_ide.directories").setup() end)
|
||||
M.try("dashboard", function() require("llembas_ide.dashboard").setup() end)
|
||||
|
||||
-- The person's own file, last: it may change anything above.
|
||||
local user = vim.fn.stdpath("config") .. "/lua/user/init.lua"
|
||||
if vim.fn.filereadable(user) == 1 then
|
||||
M.try("your lua/user/init.lua", function() dofile(user) end)
|
||||
end
|
||||
|
||||
if #M.problems > 0 then
|
||||
vim.schedule(function()
|
||||
vim.notify("LLeMbas IDE: " .. (#M.problems == 1 and "1 part" or (#M.problems .. " parts")) .. " did not start. :LLeMbasIdeProblems lists them.", vim.log.levels.WARN)
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,273 @@
|
||||
-- Every key the IDE adds, in one table: the mappings, the hints that appear after <Space>, the
|
||||
-- cheat sheet (:LLeMbasIdeKeys) and the table in the README are all made from it.
|
||||
-- The leader is <Space>. Neovim's own keys are unchanged unless listed here.
|
||||
--
|
||||
-- LLeMbas's own keys are not written here a second time: they are the LLeMbas plugin's key table
|
||||
-- (lua/llembas/keys.lua), which maps them, feeds the bottom bar, and is read below for the cheat
|
||||
-- sheet. Each action there has two forms: a chord (Ctrl+Shift+A …) that arrives from a terminal
|
||||
-- with the kitty keyboard protocol, and a key after <Space>l that always arrives.
|
||||
local M = {}
|
||||
|
||||
local function pick(name, opts) return function() require("mini.pick").builtin[name](opts) end end
|
||||
local function extra(name, opts) return function() require("mini.extra").pickers[name](opts) end end
|
||||
local function problem(count)
|
||||
return function()
|
||||
if vim.diagnostic.jump then return vim.diagnostic.jump({ count = count, float = true }) end
|
||||
if count > 0 then vim.diagnostic.goto_next() else vim.diagnostic.goto_prev() end -- Neovim 0.10
|
||||
end
|
||||
end
|
||||
local function mod(module, fn) return function(...) return require(module)[fn](...) end end
|
||||
|
||||
M.groups = {
|
||||
{ "<Leader>f", "find" },
|
||||
{ "<Leader>b", "buffer" },
|
||||
{ "<Leader>c", "code" },
|
||||
{ "<Leader>g", "git" },
|
||||
{ "<Leader>l", "LLeMbas" },
|
||||
{ "<Leader>s", "session" },
|
||||
{ "<Leader>t", "terminal" },
|
||||
{ "<Leader>u", "look" },
|
||||
{ "<Leader>x", "problems" },
|
||||
{ "<Leader>i", "IDE" },
|
||||
}
|
||||
|
||||
-- { modes, keys, action, what it does, section }
|
||||
M.map = {
|
||||
-- Files and search
|
||||
{ "n", "<Leader><Space>", pick("files"), "Find a file", "Find" },
|
||||
{ "n", "<Leader>/", pick("grep_live"), "Search in files (needs rg)", "Find" },
|
||||
{ "n", "<Leader>,", pick("buffers"), "Switch buffer", "Find" },
|
||||
{ "n", "<Leader>e", function() require("llembas.layout").toggle("tree") end, "File tree (the left bar), show and hide", "Find" },
|
||||
{ "n", "<Leader>E", function() require("mini.files").open(vim.api.nvim_buf_get_name(0)) end, "Directories side by side, at this file (edit them like text)", "Find" },
|
||||
{ "n", "<Leader>ff", pick("files"), "Find a file", "Find" },
|
||||
{ "n", "<Leader>fg", pick("grep_live"), "Search in files (needs rg)", "Find" },
|
||||
{ "n", "<Leader>fw", function() require("mini.pick").builtin.grep({ pattern = vim.fn.expand("<cword>") }) end, "Search the word under the cursor", "Find" },
|
||||
{ "n", "<Leader>fb", pick("buffers"), "Open buffers", "Find" },
|
||||
{ "n", "<Leader>fr", extra("oldfiles"), "Recent files", "Find" },
|
||||
{ "n", "<Leader>fs", extra("lsp", { scope = "document_symbol" }), "Symbols in this file", "Find" },
|
||||
{ "n", "<Leader>fS", extra("lsp", { scope = "workspace_symbol" }), "Symbols in the project", "Find" },
|
||||
{ "n", "<Leader>fR", extra("lsp", { scope = "references" }), "References to the symbol under the cursor", "Find" },
|
||||
{ "n", "<Leader>fd", extra("diagnostic", { scope = "all" }), "Problems in the project", "Find" },
|
||||
{ "n", "<Leader>fh", pick("help"), "Help pages", "Find" },
|
||||
{ "n", "<Leader>fk", extra("keymaps"), "All key mappings", "Find" },
|
||||
{ "n", "<Leader>f.", pick("resume"), "The last search again", "Find" },
|
||||
-- Buffers and windows
|
||||
{ "n", "<Leader>bd", function() require("mini.bufremove").delete() end, "Close the buffer, keep the window", "Buffers" },
|
||||
{ "n", "<Leader>bn", "<Cmd>bnext<CR>", "Next buffer", "Buffers" },
|
||||
{ "n", "<Leader>bp", "<Cmd>bprevious<CR>", "Previous buffer", "Buffers" },
|
||||
{ "n", "<S-l>", "<Cmd>bnext<CR>", "Next buffer", "Buffers" },
|
||||
{ "n", "<S-h>", "<Cmd>bprevious<CR>", "Previous buffer", "Buffers" },
|
||||
{ "n", "<Leader>w", "<Cmd>write<CR>", "Save", "Buffers" },
|
||||
{ "n", "<Leader>q", "<Cmd>quit<CR>", "Close the window", "Buffers" },
|
||||
{ "n", "<Esc>", "<Cmd>nohlsearch<CR>", "Clear the search highlight", "Buffers" },
|
||||
-- Code
|
||||
{ "n", "<Leader>ca", function() vim.lsp.buf.code_action() end, "Code action", "Code" },
|
||||
{ "n", "<Leader>cr", function() vim.lsp.buf.rename() end, "Rename the symbol", "Code" },
|
||||
{ { "n", "x" }, "<Leader>cf", mod("llembas_ide.plugins", "format"), "Format the file or the selection", "Code" },
|
||||
{ "n", "<Leader>cd", function() vim.diagnostic.open_float() end, "The problem on this line", "Code" },
|
||||
{ "n", "<Leader>cl", mod("llembas_ide.lsp", "guide"), "Language servers: found, missing, how to install", "Code" },
|
||||
-- Problems
|
||||
{ "n", "<Leader>xx", function() vim.diagnostic.setloclist() end, "Problems in this file, as a list", "Problems" },
|
||||
{ "n", "<Leader>xw", function() vim.diagnostic.setqflist() end, "Problems in the project, as a list", "Problems" },
|
||||
{ "n", "<Leader>xn", problem(1), "Next problem", "Problems" },
|
||||
{ "n", "<Leader>xp", problem(-1), "Previous problem", "Problems" },
|
||||
-- Git
|
||||
{ "n", "<Leader>gs", extra("git_files", { scope = "modified" }), "Changed files", "Git" },
|
||||
{ "n", "<Leader>gh", extra("git_hunks"), "Changes, hunk by hunk", "Git" },
|
||||
{ "n", "<Leader>gd", mod("llembas_ide.git", "diff_head"), "This file beside its committed version", "Git" },
|
||||
{ "n", "<Leader>go", function() require("mini.diff").toggle_overlay(0) end, "Show changes inline, on and off", "Git" },
|
||||
{ "n", "<Leader>ga", mod("llembas_ide.git", "stage_hunk"), "Stage the change under the cursor", "Git" },
|
||||
{ "n", "<Leader>gr", mod("llembas_ide.git", "reset_hunk"), "Undo the change under the cursor", "Git" },
|
||||
{ "n", "<Leader>gb", function() require("mini.git").show_at_cursor() end, "Who changed this line, and the commit", "Git" },
|
||||
-- (LLeMbas: the plugin's own key table; see the top of this file.)
|
||||
-- Sessions
|
||||
{ "n", "<Leader>sr", mod("llembas_ide.sessions", "restore"), "Restore this directory's session", "Session" },
|
||||
{ "n", "<Leader>sw", mod("llembas_ide.sessions", "save"), "Save the session now", "Session" },
|
||||
{ "n", "<Leader>sd", mod("llembas_ide.sessions", "delete"), "Forget this directory's session", "Session" },
|
||||
-- Terminal
|
||||
{ "n", "<Leader>tt", mod("llembas_ide.terminal", "toggle"), "Terminal, open and close", "Terminal" },
|
||||
{ { "n", "t" }, "<C-/>", mod("llembas_ide.terminal", "toggle"), "Terminal, open and close", "Terminal" },
|
||||
{ { "n", "t" }, "<C-_>", mod("llembas_ide.terminal", "toggle"), "The same, as some terminals send it", "Terminal" },
|
||||
{ "t", "<Esc><Esc>", "<C-\\><C-n>", "Leave the terminal's typing mode", "Terminal" },
|
||||
-- Look
|
||||
{ "n", "<Leader>ut", function() vim.o.background = vim.o.background == "dark" and "light" or "dark" end, "Dark and light theme", "Look" },
|
||||
{ "n", "<Leader>uw", function() vim.wo.wrap = not vim.wo.wrap end, "Wrap long lines, on and off", "Look" },
|
||||
{ "n", "<Leader>un", function() vim.wo.relativenumber = not vim.wo.relativenumber end, "Relative line numbers, on and off", "Look" },
|
||||
-- The IDE itself
|
||||
{ "n", "<Leader>ih", mod("llembas_ide.dashboard", "open"), "Start screen", "IDE" },
|
||||
{ "n", "<Leader>ik", function() M.show() end, "This list of keys", "IDE" },
|
||||
{ "n", "<Leader>id", "<Cmd>LLeMbasIdeDoctor<CR>", "Check the installation", "IDE" },
|
||||
{ "n", "<Leader>iu", "<Cmd>LLeMbasIdeConfig<CR>", "Open your own settings file", "IDE" },
|
||||
{ "n", "<Leader>iv", "<Cmd>LLeMbasIdeVersion<CR>", "Versions", "IDE" },
|
||||
}
|
||||
|
||||
-- Added to a buffer when a language server attaches to it.
|
||||
M.lsp = {
|
||||
{ "n", "gd", function() vim.lsp.buf.definition() end, "Go to the definition" },
|
||||
{ "n", "gD", function() vim.lsp.buf.declaration() end, "Go to the declaration" },
|
||||
{ "n", "gI", function() vim.lsp.buf.implementation() end, "Go to the implementation" },
|
||||
{ "n", "gy", function() vim.lsp.buf.type_definition() end, "Go to the type's definition" },
|
||||
}
|
||||
|
||||
-- Keys that are not the IDE's mappings but belong on the cheat sheet: plugins' and Neovim's own.
|
||||
M.also = {
|
||||
{ "i", "<M-\\>", "Ask LLeMbas for a suggestion now (accepting one: under LLeMbas, below)", "Typing" },
|
||||
{ "i", "<C-n> <C-p>", "Move in the completion menu (also <Down> <Up>)", "Typing" },
|
||||
{ "i", "<CR>", "Take the menu entry you moved to; otherwise a new line", "Typing" },
|
||||
{ "i", "<C-y>", "Take the menu's first entry", "Typing" },
|
||||
{ "i", "<C-e>", "Close the menu", "Typing" },
|
||||
{ "i", "<C-Space>", "Open the menu, or the entry's documentation", "Typing" },
|
||||
{ "n", "gcc", "Comment the line, on and off (gc with a motion or a selection)", "Editing" },
|
||||
{ "n", "sa sd sr", "Surround: add (saiw\"), delete (sd\"), replace (sr\"')", "Editing" },
|
||||
{ "n", "K", "Documentation of the symbol under the cursor", "Editing" },
|
||||
{ "n", "gd gD gI gy", "Definition, declaration, implementation, type (with a language server)", "Editing" },
|
||||
{ "n", "]g [g", "Next and previous git change (]G [G: last and first)", "Git" },
|
||||
}
|
||||
|
||||
--- LLeMbas's keys, from the plugin's table: { keys, where, what it does } for the cheat sheet.
|
||||
--- Both forms of an action are in the one cell, the chord first.
|
||||
local WHERE = {
|
||||
tree = "the tree", settings = "the settings lines", prompt = "the prompt", chat = "the transcript",
|
||||
change = "a proposed change", suggestion = "insert, with a suggestion",
|
||||
}
|
||||
function M.llembas_rows()
|
||||
local ok, keys = pcall(require, "llembas.keys")
|
||||
if not ok then return {} end
|
||||
local out = {}
|
||||
for _, r in ipairs(keys.rows()) do
|
||||
local both = {}
|
||||
if r.chord then both[#both + 1] = r.chord end
|
||||
if r.alt ~= "" then both[#both + 1] = r.alt end
|
||||
local where = WHERE[r.where]
|
||||
if not where then
|
||||
local names = {}
|
||||
for _, m in ipairs(r.modes) do names[#names + 1] = ({ n = "normal", x = "visual", i = "insert" })[m] or m end
|
||||
where = table.concat(names, ", ")
|
||||
-- The chord form is mapped in normal, visual and insert mode, whatever the other form is.
|
||||
if r.chord then
|
||||
local more = {}
|
||||
for _, m in ipairs({ "n", "x", "i" }) do
|
||||
if not vim.tbl_contains(r.modes, m) then more[#more + 1] = ({ n = "normal", x = "visual", i = "insert" })[m] end
|
||||
end
|
||||
if #more > 0 then where = where .. "; the chord also in " .. table.concat(more, ", ") end
|
||||
end
|
||||
end
|
||||
if #both > 0 then out[#out + 1] = { table.concat(both, " or "), where, r.desc } end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function modes(m) return type(m) == "table" and m or { m } end
|
||||
|
||||
--- Bindings given more than once (the same mode and keys), as text. Empty when the map is sound.
|
||||
function M.duplicates()
|
||||
local seen, dup = {}, {}
|
||||
-- LLeMbas's keys that are mapped everywhere count too: nothing here may take one of them.
|
||||
local ok, llembas = pcall(require, "llembas.keys")
|
||||
for _, k in ipairs(ok and llembas.table or {}) do
|
||||
if k.run and not k.virtual then
|
||||
local function take(mode, lhs)
|
||||
seen[mode .. " " .. vim.api.nvim_replace_termcodes(llembas.lhs(lhs), true, true, true)] = true
|
||||
end
|
||||
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do
|
||||
for _, mode in ipairs({ "n", "x", "i" }) do take(mode, lhs) end
|
||||
end
|
||||
if not k.scope then
|
||||
for _, lhs in ipairs(llembas.alts(k)) do
|
||||
for _, mode in ipairs(k.modes or { "n" }) do take(mode, lhs) end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
for _, list in ipairs({ M.map, M.lsp }) do
|
||||
for _, k in ipairs(list) do
|
||||
for _, mode in ipairs(modes(k[1])) do
|
||||
local id = mode .. " " .. vim.api.nvim_replace_termcodes(k[2], true, true, true)
|
||||
if seen[id] then table.insert(dup, mode .. " " .. k[2]) end
|
||||
seen[id] = true
|
||||
end
|
||||
end
|
||||
end
|
||||
return dup
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
for _, k in ipairs(M.map) do
|
||||
vim.keymap.set(k[1], k[2], k[3], { desc = k[4], silent = type(k[3]) ~= "string" or k[3]:sub(1, 1) ~= ":" })
|
||||
end
|
||||
end
|
||||
|
||||
local function shown(lhs) return (lhs:gsub("<Leader>", "<Space>")) end
|
||||
local mode_names = { n = "normal", x = "visual", i = "insert", t = "terminal" }
|
||||
local function mode_text(m)
|
||||
local out = {}
|
||||
for _, mode in ipairs(modes(m)) do table.insert(out, mode_names[mode] or mode) end
|
||||
return table.concat(out, ", ")
|
||||
end
|
||||
|
||||
--- The sections of the cheat sheet in order: { name, { {keys, modes, text}, … } }.
|
||||
function M.sections()
|
||||
local order, by = {}, {}
|
||||
local function add(section, keys, mode, text)
|
||||
if not by[section] then
|
||||
by[section] = {}
|
||||
table.insert(order, section)
|
||||
end
|
||||
table.insert(by[section], { shown(keys), mode_text(mode), text })
|
||||
end
|
||||
for _, k in ipairs(M.also) do if k[4] == "Typing" or k[4] == "Editing" then add(k[4], k[2], k[1], k[3]) end end
|
||||
for _, k in ipairs(M.map) do add(k[5], k[2], k[1], k[4]) end
|
||||
for _, k in ipairs(M.also) do if k[4] ~= "Typing" and k[4] ~= "Editing" then add(k[4], k[2], k[1], k[3]) end end
|
||||
local out = {}
|
||||
for _, name in ipairs(order) do
|
||||
table.insert(out, { name, by[name] })
|
||||
-- LLeMbas's own section stands after Git, where it always stood.
|
||||
if name == "Git" then
|
||||
local rows = {}
|
||||
for _, r in ipairs(M.llembas_rows()) do table.insert(rows, { shown(r[1]), r[2], r[3] }) end
|
||||
if #rows > 0 then table.insert(out, { "LLeMbas", rows }) end
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- The cheat sheet as the README has it.
|
||||
function M.markdown()
|
||||
local out = {}
|
||||
for _, s in ipairs(M.sections()) do
|
||||
vim.list_extend(out, { "**" .. s[1] .. "**", "", "| Keys | In | What it does |", "|---|---|---|" })
|
||||
for _, r in ipairs(s[2]) do
|
||||
table.insert(out, ("| `%s` | %s | %s |"):format(r[1]:gsub("|", "\\|"), r[2], (r[3]:gsub("|", "\\|"))))
|
||||
end
|
||||
table.insert(out, "")
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- :LLeMbasIdeKeys
|
||||
function M.show()
|
||||
local lines, titles = { "The leader key is <Space>. Press it and wait: the next keys are shown.", "" }, {}
|
||||
for _, s in ipairs(M.sections()) do
|
||||
table.insert(lines, s[1])
|
||||
table.insert(titles, #lines - 1)
|
||||
-- The keys' column is as wide as this section's longest, so every row of it shares one edge.
|
||||
local kw, ww = 16, 16
|
||||
for _, r in ipairs(s[2]) do
|
||||
kw, ww = math.max(kw, vim.fn.strdisplaywidth(r[1])), math.max(ww, vim.fn.strdisplaywidth(r[2]))
|
||||
end
|
||||
for _, r in ipairs(s[2]) do
|
||||
table.insert(lines, " " .. r[1] .. (" "):rep(kw - vim.fn.strdisplaywidth(r[1]) + 1) .. r[2] .. (" "):rep(ww - vim.fn.strdisplaywidth(r[2]) + 1) .. r[3])
|
||||
end
|
||||
table.insert(lines, "")
|
||||
end
|
||||
local buf = require("llembas_ide.ui").page("LLeMbas IDE: keys", lines)
|
||||
for _, l in ipairs(titles) do vim.api.nvim_buf_add_highlight(buf, -1, "Title", l, 0, -1) end
|
||||
for i = 2, #lines - 1 do
|
||||
if lines[i + 1]:sub(1, 2) == " " then
|
||||
local keys_end = lines[i + 1]:find(" ", 3, true) or 18
|
||||
vim.api.nvim_buf_add_highlight(buf, -1, "LLeMbasIdeKey", i, 2, keys_end)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,137 @@
|
||||
-- LLeMbas, built in. The plugin is the one in this repository's nvim/ directory, used through
|
||||
-- its documented commands and setup; the agent is the LLeMbas CLI. Nothing about a server, a
|
||||
-- model or a key is set here: they come from the CLI's sign-in.
|
||||
local M = {}
|
||||
|
||||
M.loaded = false
|
||||
|
||||
--- The agent's program, or nil: `lembas` on PATH or where its installer puts it, or whatever
|
||||
--- `cmd` was set to. The plugin decides (`require("llembas").cli()`): there is one rule for
|
||||
--- "is the LLeMbas CLI installed", and the launcher's `doctor` keeps the same one in shell.
|
||||
function M.cli()
|
||||
local ok, llembas = pcall(require, "llembas")
|
||||
if not ok or type(llembas.cli) ~= "function" then return nil end
|
||||
local cmd = llembas.cli()
|
||||
return cmd and cmd[1] or nil
|
||||
end
|
||||
|
||||
function M.has_cli() return M.cli() ~= nil end
|
||||
|
||||
local signed = nil -- true | false once it was looked up; nil before, and when it cannot be told
|
||||
|
||||
--- Whether the CLI is signed in to a server: true, false, or nil when that is not known (yet).
|
||||
--- Looked up once, on this machine only — where the CLI keeps its sign-ins (`lembas __paths`),
|
||||
--- as `llembas-ide doctor` does; no server is asked. `cb()` is called when the answer is in.
|
||||
function M.signed_in(cb)
|
||||
if signed ~= nil or M.looking then return signed end
|
||||
local exe = M.cli()
|
||||
if not exe then return nil end
|
||||
M.looking = true
|
||||
local ok = pcall(vim.system, { exe, "__paths" }, { text = true, timeout = 5000 }, function(res)
|
||||
local dir = res.code == 0 and (res.stdout or ""):match("config=([^\r\n]+)") or nil
|
||||
vim.schedule(function()
|
||||
M.looking = false
|
||||
if dir then
|
||||
local f = io.open(dir .. "/lembas.json", "r")
|
||||
local text = f and f:read("*a") or ""
|
||||
if f then f:close() end
|
||||
signed = text:find('"base_url"', 1, true) ~= nil
|
||||
end
|
||||
if cb then cb() end
|
||||
end)
|
||||
end)
|
||||
if not ok then M.looking = false end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- The layout LLeMbas IDE starts with: all four bars. `lua/user/init.lua` changes it with
|
||||
--- require("llembas").setup({ bars = { … } }); see |llembas-bars|.
|
||||
M.bars = { top = true, bottom = true, tree = true, chat = true, tree_width = 26, chat_width = 42 }
|
||||
|
||||
function M.setup()
|
||||
local ok, llembas = pcall(require, "llembas")
|
||||
if not ok then
|
||||
table.insert(require("llembas_ide").problems, "llembas: the LLeMbas plugin is not installed")
|
||||
return
|
||||
end
|
||||
llembas.setup({
|
||||
-- Without the CLI the IDE is an editor and stays quiet: no suggestions are asked for.
|
||||
complete = { auto = M.has_cli() },
|
||||
-- The keys are the plugin's own table, mapped in both forms; an action that needs the agent
|
||||
-- says what is missing instead of failing when there is no CLI.
|
||||
keys = {
|
||||
prefix = "<Leader>l",
|
||||
guard = function()
|
||||
if M.has_cli() then return true end
|
||||
M.sign_in()
|
||||
return false
|
||||
end,
|
||||
},
|
||||
bars = vim.deepcopy(M.bars),
|
||||
})
|
||||
M.loaded = true
|
||||
end
|
||||
|
||||
--- The plugin's version, or nil.
|
||||
function M.version()
|
||||
local ok, llembas = pcall(require, "llembas")
|
||||
return ok and llembas.version or nil
|
||||
end
|
||||
|
||||
--- Whether suggestions as you type are on.
|
||||
function M.autocomplete_on()
|
||||
local ok, llembas = pcall(require, "llembas")
|
||||
return ok and type(llembas.config) == "table" and type(llembas.config.complete) == "table" and llembas.config.complete.auto == true
|
||||
end
|
||||
|
||||
--- For the statusline: what LLeMbas is doing, in a few characters.
|
||||
function M.status()
|
||||
if not M.loaded then return "", false end
|
||||
if not M.has_cli() then return "◈ no CLI", false end
|
||||
local ok, text = pcall(function() return require("llembas").statusline() end)
|
||||
text = (ok and type(text) == "string" and text ~= "") and text or "◈ LLeMbas"
|
||||
return text .. (M.autocomplete_on() and " · suggest on" or " · suggest off"), true
|
||||
end
|
||||
|
||||
--- Signing in is the CLI's. With a plugin that offers :LLeMbasLogin that is used; otherwise the
|
||||
--- one command to type is shown.
|
||||
function M.sign_in()
|
||||
if vim.fn.exists(":LLeMbasLogin") == 2 then return vim.cmd("LLeMbasLogin") end
|
||||
local lines
|
||||
if M.has_cli() then
|
||||
lines = {
|
||||
"LLeMbas needs two things: a LLeMbas server, and a sign-in to it.",
|
||||
"",
|
||||
"In a terminal (<Space>tt opens one here), with your server's address:",
|
||||
"",
|
||||
" lembas login https://your-server.example.org",
|
||||
"",
|
||||
"It shows a code to confirm in the browser. After that the chat (<Space>ll),",
|
||||
"asking about code and suggestions as you type work in this editor.",
|
||||
"The models and the permissions are your account's; nothing is set here.",
|
||||
}
|
||||
else
|
||||
lines = {
|
||||
"The LLeMbas CLI (the `lembas` command) is not installed.",
|
||||
"",
|
||||
"It is the agent this editor talks to. Everything else in the IDE works without it.",
|
||||
"To get it, run the installer again and answer yes to the CLI, or see",
|
||||
"",
|
||||
" https://github.com/LLeMbas/LLeMbas-CLI",
|
||||
"",
|
||||
"Then sign in to your LLeMbas server: lembas login https://your-server.example.org",
|
||||
}
|
||||
end
|
||||
require("llembas_ide.ui").page("Sign in to LLeMbas", lines)
|
||||
end
|
||||
|
||||
--- Run a plugin command only when the plugin and the CLI are there; otherwise say what is missing.
|
||||
function M.cmd(command)
|
||||
return function()
|
||||
if not M.loaded then return vim.notify("LLeMbas: the plugin is not installed", vim.log.levels.WARN) end
|
||||
if not M.has_cli() then return M.sign_in() end
|
||||
vim.cmd(command)
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,91 @@
|
||||
-- Language servers through Neovim's own client. A server is a program of yours: the IDE starts
|
||||
-- the ones it finds on PATH and never downloads one. :LLeMbasIdeLsp says which are found and how
|
||||
-- each is installed.
|
||||
local M = {}
|
||||
|
||||
-- name (nvim-lspconfig's), the program looked for, what it is for, one way to install it.
|
||||
M.servers = {
|
||||
{ "lua_ls", "lua-language-server", "Lua", "your package manager, or github.com/LuaLS/lua-language-server releases" },
|
||||
{ "pyright", "pyright-langserver", "Python", "npm install -g pyright (or: pipx install pyright)" },
|
||||
{ "ruff", "ruff", "Python lint and format", "pipx install ruff" },
|
||||
{ "ts_ls", "typescript-language-server", "TypeScript, JavaScript", "npm install -g typescript typescript-language-server" },
|
||||
{ "rust_analyzer", "rust-analyzer", "Rust", "rustup component add rust-analyzer" },
|
||||
{ "gopls", "gopls", "Go", "go install golang.org/x/tools/gopls@latest" },
|
||||
{ "clangd", "clangd", "C, C++", "your package manager: clangd" },
|
||||
{ "bashls", "bash-language-server", "Shell", "npm install -g bash-language-server" },
|
||||
{ "jsonls", "vscode-json-language-server", "JSON", "npm install -g vscode-langservers-extracted" },
|
||||
{ "html", "vscode-html-language-server", "HTML", "npm install -g vscode-langservers-extracted" },
|
||||
{ "cssls", "vscode-css-language-server", "CSS", "npm install -g vscode-langservers-extracted" },
|
||||
{ "yamlls", "yaml-language-server", "YAML", "npm install -g yaml-language-server" },
|
||||
{ "marksman", "marksman", "Markdown", "your package manager, or github.com/artempyanykh/marksman releases" },
|
||||
}
|
||||
|
||||
M.enabled = {}
|
||||
|
||||
function M.setup()
|
||||
local modern = vim.fn.has("nvim-0.11") == 1 and vim.lsp.enable ~= nil
|
||||
-- Below 0.11 nvim-lspconfig's start-up file only announces that old Neovim is deprecated.
|
||||
if not modern then vim.g.lspconfig = 1 end
|
||||
|
||||
local capabilities
|
||||
local ok, blink = pcall(require, "blink.cmp")
|
||||
if ok then capabilities = blink.get_lsp_capabilities() end
|
||||
|
||||
for _, s in ipairs(M.servers) do
|
||||
local name, bin = s[1], s[2]
|
||||
if vim.fn.executable(bin) == 1 then
|
||||
if modern then
|
||||
vim.lsp.enable(name)
|
||||
table.insert(M.enabled, name)
|
||||
else
|
||||
local has, lspconfig = pcall(require, "lspconfig")
|
||||
if has and lspconfig[name] then
|
||||
lspconfig[name].setup({ capabilities = capabilities })
|
||||
table.insert(M.enabled, name)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
vim.api.nvim_create_autocmd("LspAttach", {
|
||||
group = vim.api.nvim_create_augroup("llembas_ide_lsp", { clear = true }),
|
||||
callback = function(ev)
|
||||
for _, k in ipairs(require("llembas_ide.keys").lsp) do
|
||||
vim.keymap.set(k[1], k[2], k[3], { buffer = ev.buf, desc = k[4] })
|
||||
end
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
--- The guide: every server the IDE knows, whether it is found, and how to get it.
|
||||
function M.guide()
|
||||
local lines = {
|
||||
"Language servers",
|
||||
"",
|
||||
"The IDE starts a server it finds on PATH when you open a file of its language.",
|
||||
"It never downloads one: install the ones you want yourself, then restart the IDE.",
|
||||
"",
|
||||
}
|
||||
local marks = {}
|
||||
for _, s in ipairs(M.servers) do
|
||||
local found = vim.fn.executable(s[2]) == 1
|
||||
table.insert(lines, (" %s %-14s %-24s %s"):format(found and "found " or "missing", s[1], s[3], s[2]))
|
||||
table.insert(marks, { #lines - 1, found and "LLeMbasIdeGood" or "LLeMbasIdeWarn" })
|
||||
if not found then
|
||||
table.insert(lines, " " .. s[4])
|
||||
table.insert(marks, { #lines - 1, "LLeMbasIdeMuted" })
|
||||
end
|
||||
end
|
||||
vim.list_extend(lines, {
|
||||
"",
|
||||
"Running in this buffer's window: :checkhealth vim.lsp",
|
||||
"Another server: vim.lsp.enable(\"name\") in lua/user/init.lua (Neovim 0.11 or newer).",
|
||||
})
|
||||
local buf = require("llembas_ide.ui").page("LLeMbas IDE: language servers", lines)
|
||||
for _, m in ipairs(marks) do
|
||||
vim.api.nvim_buf_add_highlight(buf, -1, m[2], m[1], 2, 9)
|
||||
end
|
||||
vim.api.nvim_buf_add_highlight(buf, -1, "Title", 0, 0, -1)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,93 @@
|
||||
-- The editor's options. Plain Neovim settings; lua/user/init.lua may change any of them.
|
||||
local M = {}
|
||||
|
||||
function M.setup()
|
||||
local o = vim.opt
|
||||
vim.g.mapleader = " "
|
||||
vim.g.maplocalleader = "\\"
|
||||
|
||||
-- What a file or a model writes is text, never settings or commands: no modelines, no
|
||||
-- per-directory configuration files.
|
||||
-- No netrw: a directory opened like a file goes to the tree (directories.lua).
|
||||
vim.g.loaded_netrw = 1
|
||||
vim.g.loaded_netrwPlugin = 1
|
||||
|
||||
o.modeline = false
|
||||
o.modelines = 0
|
||||
o.exrc = false
|
||||
|
||||
o.number = true
|
||||
o.relativenumber = false
|
||||
o.cursorline = true
|
||||
o.signcolumn = "yes"
|
||||
o.termguicolors = true
|
||||
o.showmode = false -- the statusline shows it
|
||||
o.laststatus = 3
|
||||
o.title = true
|
||||
o.titlestring = "%t%( %M%) — LLeMbas IDE"
|
||||
o.scrolloff = 4
|
||||
o.sidescrolloff = 8
|
||||
o.wrap = false
|
||||
o.linebreak = true
|
||||
o.list = true
|
||||
o.listchars = { tab = "→ ", trail = "·", nbsp = "␣" }
|
||||
o.fillchars = { eob = " " }
|
||||
o.pumheight = 12
|
||||
o.shortmess:append("I") -- the dashboard is the start screen
|
||||
|
||||
o.mouse = "a"
|
||||
o.clipboard = "unnamedplus" -- the system clipboard, where a provider is installed
|
||||
o.undofile = true
|
||||
o.swapfile = true
|
||||
o.updatetime = 300
|
||||
o.timeoutlen = 400
|
||||
o.confirm = true -- ask instead of failing on unsaved changes
|
||||
|
||||
o.splitright = true
|
||||
o.splitbelow = true
|
||||
o.splitkeep = "screen"
|
||||
|
||||
o.ignorecase = true
|
||||
o.smartcase = true
|
||||
o.incsearch = true
|
||||
o.hlsearch = true
|
||||
o.inccommand = "split"
|
||||
|
||||
o.expandtab = true
|
||||
o.shiftwidth = 2
|
||||
o.tabstop = 2
|
||||
o.softtabstop = 2
|
||||
o.smartindent = true
|
||||
o.shiftround = true
|
||||
o.breakindent = true
|
||||
|
||||
o.completeopt = { "menu", "menuone", "noselect" }
|
||||
o.wildmode = { "longest:full", "full" }
|
||||
-- A session holds windows and buffers, not options or variables.
|
||||
o.sessionoptions = { "buffers", "curdir", "folds", "help", "tabpages", "winsize" }
|
||||
|
||||
vim.diagnostic.config({
|
||||
severity_sort = true,
|
||||
underline = true,
|
||||
virtual_text = { spacing = 2, source = "if_many" },
|
||||
float = { border = "rounded", source = "if_many" },
|
||||
})
|
||||
|
||||
local group = vim.api.nvim_create_augroup("llembas_ide_options", { clear = true })
|
||||
vim.api.nvim_create_autocmd("TextYankPost", {
|
||||
group = group,
|
||||
callback = function() pcall(vim.highlight.on_yank, { timeout = 150 }) end,
|
||||
})
|
||||
-- Back to where the cursor was when the file was last open.
|
||||
vim.api.nvim_create_autocmd("BufReadPost", {
|
||||
group = group,
|
||||
callback = function(ev)
|
||||
local mark = vim.api.nvim_buf_get_mark(ev.buf, '"')
|
||||
if mark[1] > 0 and mark[1] <= vim.api.nvim_buf_line_count(ev.buf) then
|
||||
pcall(vim.api.nvim_win_set_cursor, 0, mark)
|
||||
end
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,108 @@
|
||||
-- The third-party plugins, set up. Each is a package the installer placed at a pinned commit
|
||||
-- (ide/plugins.lock); a missing one is named as a problem and the rest still work.
|
||||
local M = {}
|
||||
|
||||
local function mini(name, opts)
|
||||
local ide = require("llembas_ide")
|
||||
ide.try("mini." .. name, function() require("mini." .. name).setup(opts or {}) end)
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
-- Icons as plain letters: a terminal's font is not ours to assume. With a Nerd Font, put
|
||||
-- require("mini.icons").setup({ style = "glyph" }) in lua/user/init.lua.
|
||||
mini("icons", { style = "ascii" })
|
||||
mini("files", {
|
||||
content = { prefix = function() end }, -- no icon column
|
||||
windows = { preview = true, width_preview = 60 },
|
||||
-- Not the default explorer: a directory opened like a file goes to the tree (directories.lua);
|
||||
-- mini.files is <Space>E, and what a directory outside the tree or without the bars opens in.
|
||||
options = { use_as_default_explorer = false },
|
||||
})
|
||||
mini("pick", { window = { prompt_prefix = "› " } })
|
||||
require("llembas_ide").try("mini.pick as vim.ui.select", function() vim.ui.select = require("mini.pick").ui_select end)
|
||||
mini("extra")
|
||||
mini("surround")
|
||||
mini("pairs")
|
||||
mini("bufremove")
|
||||
mini("git")
|
||||
mini("diff", {
|
||||
view = { style = "sign", signs = { add = "▎", change = "▎", delete = "▁" } },
|
||||
-- ]h and [h, ga and gr are the LLeMbas plugin's (its proposed changes): git hunks move on g.
|
||||
mappings = {
|
||||
apply = "", reset = "", textobject = "ih",
|
||||
goto_first = "[G", goto_prev = "[g", goto_next = "]g", goto_last = "]G",
|
||||
},
|
||||
})
|
||||
|
||||
local keys = require("llembas_ide.keys")
|
||||
local ok, clue = pcall(require, "mini.clue")
|
||||
if ok then
|
||||
local clues = {
|
||||
clue.gen_clues.g(), clue.gen_clues.z(), clue.gen_clues.windows(),
|
||||
clue.gen_clues.registers(), clue.gen_clues.marks(), clue.gen_clues.builtin_completion(),
|
||||
}
|
||||
for _, g in ipairs(keys.groups) do
|
||||
table.insert(clues, { mode = "n", keys = g[1], desc = "+" .. g[2] })
|
||||
table.insert(clues, { mode = "x", keys = g[1], desc = "+" .. g[2] })
|
||||
end
|
||||
mini("clue", {
|
||||
triggers = {
|
||||
{ mode = "n", keys = "<Leader>" }, { mode = "x", keys = "<Leader>" },
|
||||
{ mode = "n", keys = "g" }, { mode = "x", keys = "g" },
|
||||
{ mode = "n", keys = "z" }, { mode = "x", keys = "z" },
|
||||
{ mode = "n", keys = "<C-w>" },
|
||||
{ mode = "n", keys = '"' }, { mode = "x", keys = '"' },
|
||||
{ mode = "n", keys = "'" }, { mode = "n", keys = "`" },
|
||||
{ mode = "n", keys = "[" }, { mode = "n", keys = "]" },
|
||||
{ mode = "i", keys = "<C-x>" },
|
||||
},
|
||||
clues = clues,
|
||||
window = { delay = 300, config = { width = "auto", border = "rounded" } },
|
||||
})
|
||||
else
|
||||
table.insert(require("llembas_ide").problems, "mini.clue: not installed")
|
||||
end
|
||||
|
||||
require("llembas_ide").try("conform", function()
|
||||
-- Formatting happens when asked for (<leader>cf, :LLeMbasIdeFormat), never on save.
|
||||
-- A formatter listed here is used when it is installed; otherwise the language server formats.
|
||||
require("conform").setup({
|
||||
formatters_by_ft = {
|
||||
lua = { "stylua" },
|
||||
python = { "ruff_format", "black", stop_after_first = true },
|
||||
javascript = { "prettierd", "prettier", stop_after_first = true },
|
||||
typescript = { "prettierd", "prettier", stop_after_first = true },
|
||||
javascriptreact = { "prettierd", "prettier", stop_after_first = true },
|
||||
typescriptreact = { "prettierd", "prettier", stop_after_first = true },
|
||||
json = { "prettierd", "prettier", stop_after_first = true },
|
||||
yaml = { "prettierd", "prettier", stop_after_first = true },
|
||||
markdown = { "prettierd", "prettier", stop_after_first = true },
|
||||
html = { "prettierd", "prettier", stop_after_first = true },
|
||||
css = { "prettierd", "prettier", stop_after_first = true },
|
||||
sh = { "shfmt" },
|
||||
bash = { "shfmt" },
|
||||
go = { "gofmt" },
|
||||
rust = { "rustfmt" },
|
||||
c = { "clang-format" },
|
||||
cpp = { "clang-format" },
|
||||
},
|
||||
default_format_opts = { lsp_format = "fallback" },
|
||||
notify_no_formatters = true,
|
||||
})
|
||||
end)
|
||||
end
|
||||
|
||||
--- Format the buffer, or the selected lines.
|
||||
function M.format()
|
||||
local ok, conform = pcall(require, "conform")
|
||||
if ok then
|
||||
conform.format({ async = true, lsp_format = "fallback" }, function(err, did)
|
||||
if err then vim.notify("Format: " .. tostring(err), vim.log.levels.WARN)
|
||||
elseif did == false then vim.notify("Format: nothing to change") end
|
||||
end)
|
||||
else
|
||||
vim.lsp.buf.format({ async = true })
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,76 @@
|
||||
-- One session per directory: the windows and buffers of the last time the IDE was closed there.
|
||||
-- Saved on leaving, restored when asked for (the dashboard, <leader>sr). Session files live in
|
||||
-- the IDE's own state directory and nowhere else: a Session.vim found in a project is not read.
|
||||
local M = {}
|
||||
|
||||
local function dir() return vim.fn.stdpath("state") .. "/sessions" end
|
||||
|
||||
--- The session's name for a directory: readable, and unique to the full path.
|
||||
function M.name(cwd)
|
||||
cwd = cwd or vim.fn.getcwd()
|
||||
local base = vim.fn.fnamemodify(cwd, ":t"):gsub("[^%w%-_.]", "_")
|
||||
if base == "" then base = "root" end
|
||||
return base .. "-" .. vim.fn.sha256(cwd):sub(1, 12) .. ".vim"
|
||||
end
|
||||
|
||||
function M.exists(cwd) return vim.fn.filereadable(dir() .. "/" .. M.name(cwd)) == 1 end
|
||||
|
||||
local function has_files()
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
if vim.bo[b].buflisted and vim.bo[b].buftype == "" and vim.api.nvim_buf_get_name(b) ~= "" then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
function M.save(quiet, leaving)
|
||||
if not has_files() then
|
||||
if not quiet then vim.notify("Session: no files are open") end
|
||||
return false
|
||||
end
|
||||
-- A session holds the code's windows: the bars are put away while it is written, and are
|
||||
-- laid out again by the layout itself, the next time as now.
|
||||
local bars, layout = pcall(require, "llembas.layout")
|
||||
if bars then
|
||||
pcall(layout.remember_widths)
|
||||
pcall(layout.hide)
|
||||
end
|
||||
local ok, err = pcall(function() require("mini.sessions").write(M.name(), { verbose = false }) end)
|
||||
if bars and not leaving then pcall(layout.apply) end
|
||||
if not quiet then vim.notify(ok and "Session saved for " .. vim.fn.getcwd() or "Session: " .. tostring(err)) end
|
||||
return ok
|
||||
end
|
||||
|
||||
function M.restore()
|
||||
if not M.exists() then return vim.notify("Session: none saved for " .. vim.fn.getcwd()) end
|
||||
local bars, layout = pcall(require, "llembas.layout")
|
||||
if bars then pcall(layout.hide) end
|
||||
local ok, err = pcall(function() require("mini.sessions").read(M.name(), { verbose = false }) end)
|
||||
if bars then vim.schedule(function() pcall(layout.apply) end) end
|
||||
if not ok then vim.notify("Session: " .. tostring(err), vim.log.levels.WARN) end
|
||||
end
|
||||
|
||||
function M.delete()
|
||||
if not M.exists() then return vim.notify("Session: none saved for " .. vim.fn.getcwd()) end
|
||||
vim.fn.delete(dir() .. "/" .. M.name())
|
||||
vim.notify("Session forgotten for " .. vim.fn.getcwd())
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
vim.fn.mkdir(dir(), "p")
|
||||
require("mini.sessions").setup({
|
||||
autoread = false,
|
||||
autowrite = false,
|
||||
directory = dir(),
|
||||
file = "", -- never a session file from the working directory
|
||||
verbose = { read = false, write = false, delete = false },
|
||||
})
|
||||
vim.api.nvim_create_autocmd("VimLeavePre", {
|
||||
group = vim.api.nvim_create_augroup("llembas_ide_sessions", { clear = true }),
|
||||
callback = function()
|
||||
if vim.g.llembas_ide_no_session then return end
|
||||
M.save(true, true)
|
||||
end,
|
||||
})
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,40 @@
|
||||
-- One terminal at the bottom that opens and closes; what runs in it keeps running.
|
||||
local M = {}
|
||||
|
||||
local state = { buf = nil, win = nil }
|
||||
|
||||
function M.toggle()
|
||||
if state.win and vim.api.nvim_win_is_valid(state.win) then
|
||||
vim.api.nvim_win_hide(state.win)
|
||||
state.win = nil
|
||||
return
|
||||
end
|
||||
vim.cmd("botright " .. math.max(8, math.floor(vim.o.lines * 0.3)) .. "split")
|
||||
state.win = vim.api.nvim_get_current_win()
|
||||
if state.buf and vim.api.nvim_buf_is_valid(state.buf) then
|
||||
vim.api.nvim_win_set_buf(state.win, state.buf)
|
||||
else
|
||||
vim.cmd.terminal()
|
||||
state.buf = vim.api.nvim_get_current_buf()
|
||||
vim.bo[state.buf].buflisted = false
|
||||
end
|
||||
vim.wo[state.win].number = false
|
||||
vim.wo[state.win].signcolumn = "no"
|
||||
vim.cmd.startinsert()
|
||||
end
|
||||
|
||||
--- Run a command of the IDE's own in a terminal split and leave its output on the screen.
|
||||
function M.run(argv)
|
||||
vim.cmd("botright " .. math.max(12, math.floor(vim.o.lines * 0.45)) .. "new")
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
vim.bo[buf].bufhidden = "wipe"
|
||||
if vim.fn.has("nvim-0.11") == 1 then
|
||||
vim.fn.jobstart(argv, { term = true })
|
||||
else
|
||||
vim.fn.termopen(argv)
|
||||
end
|
||||
vim.bo[buf].buflisted = false
|
||||
vim.keymap.set("n", "q", "<Cmd>bwipeout!<CR>", { buffer = buf, nowait = true })
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,72 @@
|
||||
-- Treesitter highlighting. With the grammars the installer compiled (ide/parsers.lock, when a
|
||||
-- C compiler was there) the queries of nvim-treesitter are used with them. Without, Neovim's own
|
||||
-- bundled grammars and queries are (C, Lua, Markdown, Vimscript, help, queries) and every other
|
||||
-- language is coloured by Neovim's regular syntax files. Nothing is ever installed from here.
|
||||
local M = {}
|
||||
|
||||
M.compiled = false
|
||||
|
||||
--- A grammar, and the file types it colours beside the one of its own name.
|
||||
M.filetypes = {
|
||||
bash = { "sh" },
|
||||
tsx = { "typescriptreact" },
|
||||
javascript = { "javascriptreact" },
|
||||
vimdoc = { "help" },
|
||||
json = { "jsonc" },
|
||||
html = { "xhtml" },
|
||||
}
|
||||
|
||||
local function parsers_dir()
|
||||
local dir = require("llembas_ide").prefix .. "/site/pack/llembas/start/llembas-parsers/parser"
|
||||
return vim.fn.isdirectory(dir) == 1 and dir or nil
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
if parsers_dir() then
|
||||
-- The plugin's own start-up (its module system and :TSInstall commands) stays off: only its
|
||||
-- queries and the predicates they use are wanted.
|
||||
vim.g.loaded_nvim_treesitter = true
|
||||
local ok = pcall(vim.cmd.packadd, "nvim-treesitter")
|
||||
if ok and pcall(require, "nvim-treesitter.query_predicates") then
|
||||
M.compiled = true
|
||||
-- File types whose name is not their grammar's. nvim-treesitter names these when it starts
|
||||
-- up; its start-up is off here, so they are named here, for the grammars that are compiled.
|
||||
local has = {}
|
||||
for _, lang in ipairs(M.languages()) do has[lang] = true end
|
||||
for lang, fts in pairs(M.filetypes) do
|
||||
if has[lang] then pcall(vim.treesitter.language.register, lang, fts) end
|
||||
end
|
||||
else
|
||||
table.insert(require("llembas_ide").problems, "treesitter: grammars are compiled but nvim-treesitter's queries are missing")
|
||||
end
|
||||
end
|
||||
vim.api.nvim_create_autocmd("FileType", {
|
||||
group = vim.api.nvim_create_augroup("llembas_ide_treesitter", { clear = true }),
|
||||
callback = function(ev) M.start(ev.buf) end,
|
||||
})
|
||||
end
|
||||
|
||||
--- Start highlighting for a buffer when its language has a grammar and a query; quietly not otherwise.
|
||||
function M.start(buf)
|
||||
local ft = vim.bo[buf].filetype
|
||||
if ft == "" or vim.bo[buf].buftype == "terminal" then return false end
|
||||
local lang = vim.treesitter.language.get_lang(ft) or ft
|
||||
local ok, added = pcall(vim.treesitter.language.add, lang)
|
||||
if not ok or added == false then return false end
|
||||
local has_query, query = pcall(vim.treesitter.query.get, lang, "highlights")
|
||||
if not has_query or not query then return false end
|
||||
return (pcall(vim.treesitter.start, buf, lang))
|
||||
end
|
||||
|
||||
--- The languages with a compiled grammar.
|
||||
function M.languages()
|
||||
local out = {}
|
||||
for _, f in ipairs(vim.api.nvim_get_runtime_file("parser/*.so", true)) do
|
||||
out[vim.fn.fnamemodify(f, ":t:r")] = true
|
||||
end
|
||||
local list = vim.tbl_keys(out)
|
||||
table.sort(list)
|
||||
return list
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Small shared pieces of the IDE's own screens.
|
||||
local M = {}
|
||||
|
||||
--- A read-only page in a centred floating window; q or <Esc> closes it. Returns the buffer.
|
||||
function M.page(title, lines)
|
||||
local buf = vim.api.nvim_create_buf(false, true)
|
||||
vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
|
||||
vim.bo[buf].modifiable = false
|
||||
vim.bo[buf].bufhidden = "wipe"
|
||||
vim.bo[buf].filetype = "llembas-ide-page"
|
||||
local width = 20
|
||||
for _, l in ipairs(lines) do width = math.max(width, vim.fn.strdisplaywidth(l)) end
|
||||
width = math.min(width + 2, math.max(20, vim.o.columns - 4))
|
||||
local height = math.min(#lines, math.max(3, vim.o.lines - 6))
|
||||
local win = vim.api.nvim_open_win(buf, true, {
|
||||
relative = "editor", style = "minimal", border = "rounded",
|
||||
title = " " .. title .. " ", title_pos = "center",
|
||||
width = width, height = height,
|
||||
row = math.max(0, math.floor((vim.o.lines - height) / 2) - 1),
|
||||
col = math.max(0, math.floor((vim.o.columns - width) / 2)),
|
||||
})
|
||||
vim.wo[win].wrap = false
|
||||
vim.wo[win].cursorline = false
|
||||
for _, key in ipairs({ "q", "<Esc>" }) do
|
||||
vim.keymap.set("n", key, function() pcall(vim.api.nvim_win_close, win, true) end, { buffer = buf, nowait = true })
|
||||
end
|
||||
return buf, win
|
||||
end
|
||||
|
||||
return M
|
||||
Executable
+805
@@ -0,0 +1,805 @@
|
||||
#!/usr/bin/env bash
|
||||
# LLeMbas IDE from nothing: a complete Neovim editor with LLeMbas built in, for this user only.
|
||||
#
|
||||
# curl -fsSL https://github.com/LLeMbas/LLeMbas-IDE/releases/latest/download/install.sh | bash
|
||||
# curl -fsSL <…>/install.sh | bash -s -- --channel beta # options go after --; the betas
|
||||
# ide/install.sh --from-checkout # from a clone of the repository
|
||||
#
|
||||
# Run it with --help for what it installs and where, the options and the environment. In short:
|
||||
# everything goes under ~/.local/share/llembas-ide, ~/.config/llembas-ide and ~/.local/bin, for
|
||||
# this user only; nothing runs as root; a failure leaves the previous installation, or nothing.
|
||||
set -euo pipefail
|
||||
|
||||
FORGE="${LLEMBAS_IDE_FORGE:-https://github.com}"
|
||||
FORGE="${FORGE%/}"
|
||||
SLUG="${LLEMBAS_IDE_SLUG:-LLeMbas/LLeMbas-IDE}"
|
||||
# The key LLeMbas releases are signed with (the LLeMbas CLI's get.sh checks the same one): a
|
||||
# release without a good SHA256SUMS.sig (ssh-keygen -Y sign, namespace lembas-release) is refused.
|
||||
# Set LLEMBAS_IDE_PUBKEY to another key for a build of your own, or to nothing for an unsigned
|
||||
# one, which is then checked against its own SHA256SUMS only.
|
||||
PUBKEY="${LLEMBAS_IDE_PUBKEY-ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDSZO3Byow7R3ZpOH3MCvpPIga2pZBzhfX5wXfNP1cLa}"
|
||||
SIGN_NAMESPACE="lembas-release"
|
||||
CLI_SLUG="LLeMbas/LLeMbas-CLI"
|
||||
CLI_HOME="https://github.com/LLeMbas/LLeMbas-CLI"
|
||||
NVIM_RELEASES="https://github.com/neovim/neovim/releases/download"
|
||||
APP="llembas-ide"
|
||||
MIN_NVIM="0.10"
|
||||
|
||||
VERSION_WANTED=""
|
||||
CHANNEL="stable"
|
||||
PREFIX=""
|
||||
FROM_CHECKOUT=0
|
||||
FROM_DIR=""
|
||||
NVIM_BIN=""
|
||||
WITH_CLI=1
|
||||
WITH_PARSERS=1
|
||||
YES=0
|
||||
DRY=0
|
||||
|
||||
TMP=""
|
||||
STAGE=""
|
||||
OLD=""
|
||||
MADE=""
|
||||
SWAPPED=()
|
||||
PLACED=()
|
||||
DONE=0
|
||||
|
||||
# Everything is inside functions called on the last line: a download cut short runs nothing.
|
||||
say() { printf '%s\n' "$*"; }
|
||||
note() { printf ' %s\n' "$*"; }
|
||||
warn() { printf 'install.sh: %s\n' "$*" >&2; }
|
||||
die() {
|
||||
printf 'install.sh: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
# One line per action. With --dry-run the line is all that happens.
|
||||
step() {
|
||||
if [ "$DRY" = 1 ]; then printf ' would %s\n' "$*"; else printf ' %s\n' "$*"; fi
|
||||
}
|
||||
|
||||
rollback() {
|
||||
local i unit
|
||||
# Files placed outside the prefix, newest first: the old one back, or gone if there was none.
|
||||
for ((i = ${#PLACED[@]} - 1; i >= 0; i--)); do
|
||||
unit="${PLACED[$i]}"
|
||||
rm -f "$unit"
|
||||
if [ -e "$OLD/files/$i" ]; then mv "$OLD/files/$i" "$unit"; fi
|
||||
done
|
||||
for ((i = ${#SWAPPED[@]} - 1; i >= 0; i--)); do
|
||||
unit="${SWAPPED[$i]}"
|
||||
rm -rf "${PREFIX:?}/$unit"
|
||||
if [ -e "$OLD/$unit" ]; then mv "$OLD/$unit" "$PREFIX/$unit"; fi
|
||||
done
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
local status=$?
|
||||
trap - EXIT
|
||||
if [ "$DONE" != 1 ] && [ -n "$OLD" ] && [ -d "$OLD" ]; then
|
||||
rollback || true
|
||||
warn "nothing was changed: the installation is as it was before."
|
||||
fi
|
||||
if [ "$status" != 0 ] && [ "$DONE" != 1 ] && { [ -z "$OLD" ] || [ ! -d "$OLD" ]; } && [ -n "$STAGE" ]; then
|
||||
warn "stopped before anything was put in place: nothing was installed or changed."
|
||||
fi
|
||||
[ -z "$TMP" ] || rm -rf "$TMP"
|
||||
[ -z "$STAGE" ] || rm -rf "$STAGE"
|
||||
[ -z "$OLD" ] || rm -rf "$OLD"
|
||||
# A prefix this run made and left empty goes again.
|
||||
if [ -n "$PREFIX" ] && [ -d "$PREFIX" ] && [ "$DONE" != 1 ]; then
|
||||
rmdir "$PREFIX/site/pack" "$PREFIX/site" "$PREFIX" 2>/dev/null || true
|
||||
if [ ! -d "$PREFIX" ] && [ -n "${MADE:-}" ]; then
|
||||
while IFS= read -r made; do
|
||||
[ -z "$made" ] || rmdir "$made" 2>/dev/null || break
|
||||
done <<<"$MADE"
|
||||
fi
|
||||
fi
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
# The help is text of its own, not the comment at the top read back from the file: piped into
|
||||
# bash (curl … | bash -s -- --help) there is no file to read it from.
|
||||
usage() {
|
||||
cat <<'HELP'
|
||||
LLeMbas IDE from nothing: a complete Neovim editor with LLeMbas built in, for this user only.
|
||||
|
||||
curl -fsSL <release>/install.sh | bash -s -- --channel beta # options go after --
|
||||
ide/install.sh --from-checkout # from a clone of the repository
|
||||
|
||||
What it installs, and where (nothing else is written, nothing runs as root):
|
||||
<prefix>/nvim/ a pinned Neovim release, its SHA-256 checked (ide/neovim.sha256)
|
||||
<prefix>/site/pack/llembas/ the IDE's configuration and its plugins, each plugin fetched
|
||||
with git at the one commit ide/plugins.lock names
|
||||
<prefix>/lib/ the LLeMbas plugin, this installer, the lock files
|
||||
~/.config/llembas-ide/ init.lua, and lua/user/init.lua: yours, never overwritten
|
||||
~/.local/bin/llembas-ide the launcher (NVIM_APPNAME=llembas-ide: your own Neovim
|
||||
configuration in ~/.config/nvim is never read or written)
|
||||
~/.local/share/applications/llembas-ide.desktop and an icon (Linux)
|
||||
<prefix> is ${XDG_DATA_HOME:-~/.local/share}/llembas-ide unless --prefix says otherwise.
|
||||
|
||||
Everything is built in a staging directory and tried there before it replaces what is
|
||||
installed; a failure leaves the previous installation, or nothing, exactly as it was.
|
||||
Running it again updates in place.
|
||||
|
||||
Options:
|
||||
--version X install release X (1.2.3 or v1.2.3) instead of the newest
|
||||
--channel NAME stable (default) or beta: which releases "newest" looks at
|
||||
--prefix DIR where the IDE itself goes
|
||||
--from-checkout install from the repository this script sits in, not from a release
|
||||
--nvim-bin PATH use this Neovim (0.10 or newer) instead of downloading the pinned one
|
||||
--no-cli do not offer to install the LLeMbas CLI
|
||||
--no-parsers do not compile the Treesitter grammars
|
||||
--yes ask nothing: yes to the CLI offer
|
||||
--dry-run print every action, do nothing
|
||||
|
||||
Environment:
|
||||
LLEMBAS_IDE_FORGE where releases come from (default https://github.com)
|
||||
LLEMBAS_IDE_SLUG owner/name there (default LLeMbas/LLeMbas-IDE)
|
||||
LLEMBAS_IDE_RELEASE_BASE the releases' download directory, when it is not the forge's own:
|
||||
an https:// address, or file:// for a release on this machine
|
||||
LLEMBAS_IDE_PUBKEY the ssh-ed25519 key a release's SHA256SUMS.sig must be signed with
|
||||
LLEMBAS_IDE_GIT_MIRROR a directory of git repositories named like the plugins' own, to
|
||||
fetch from instead of the network; the commit is checked all the same
|
||||
LLEMBAS_IDE_CLI_VERSION the LLeMbas CLI release to offer (2.0.0 or v2.0.0) instead of the
|
||||
newest of the channel
|
||||
LLEMBAS_IDE_CLI_RELEASE_BASE the CLI releases' download directory, when it is not the forge's own
|
||||
|
||||
Needs bash, git, curl, tar, sha256sum (or shasum) and ssh-keygen (openssh-client: it checks the
|
||||
release's signature). A C compiler is used when there is one.
|
||||
Linux x86-64 and arm64. macOS is written for and has not been tried.
|
||||
HELP
|
||||
}
|
||||
|
||||
need() {
|
||||
command -v "$1" >/dev/null 2>&1 || die "needs $1, which is not installed${2:+ ($2)}"
|
||||
}
|
||||
|
||||
sha256_of() {
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
sha256sum "$1" | cut -d' ' -f1
|
||||
elif command -v shasum >/dev/null 2>&1; then
|
||||
shasum -a 256 "$1" | cut -d' ' -f1
|
||||
else
|
||||
die "needs sha256sum or shasum to check what it downloads"
|
||||
fi
|
||||
}
|
||||
|
||||
# Only https, or a file on this machine: nothing is fetched over a connection that cannot be trusted.
|
||||
fetch() {
|
||||
local url="$1" out="$2"
|
||||
case "$url" in
|
||||
https://* | file:///*) ;;
|
||||
*) die "refusing to download $url: only https:// (or a local file://) is used" ;;
|
||||
esac
|
||||
curl -fsSL --retry 2 --proto '=https,file' --proto-redir '=https' -o "$out" "$url"
|
||||
}
|
||||
|
||||
# Questions go to the terminal: piped into bash, this script's stdin is the script itself.
|
||||
has_tty() { [ -r /dev/tty ] && { : </dev/tty; } 2>/dev/null; }
|
||||
ask_yes() {
|
||||
local answer=""
|
||||
[ "$YES" = 1 ] && return 0
|
||||
has_tty || return 1
|
||||
printf '%s [y/N] ' "$1" >/dev/tty
|
||||
read -r answer </dev/tty || return 1
|
||||
case "$answer" in y | Y | yes | Yes) return 0 ;; *) return 1 ;; esac
|
||||
}
|
||||
|
||||
# Neovim run by the installer keeps its log and state in the temporary directory, not in the home.
|
||||
nvim_quiet() {
|
||||
local scratch="${TMP:-/dev/null}"
|
||||
if [ -d "$scratch" ]; then
|
||||
XDG_STATE_HOME="$scratch/nvim-state" XDG_CACHE_HOME="$scratch/nvim-cache" XDG_DATA_HOME="$scratch/nvim-data" \
|
||||
XDG_CONFIG_HOME="$scratch/nvim-config" NVIM_LOG_FILE="$scratch/nvim.log" "$@"
|
||||
else
|
||||
NVIM_LOG_FILE=/dev/null "$@"
|
||||
fi
|
||||
}
|
||||
|
||||
git_quiet() {
|
||||
# Nobody's git configuration, no questions, and no transport but https (or a local mirror).
|
||||
GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_TERMINAL_PROMPT=0 GIT_ALLOW_PROTOCOL=https:file git "$@"
|
||||
}
|
||||
|
||||
# The lines of a lock file that say something.
|
||||
lock_lines() { grep -v -E '^[[:space:]]*(#|$)' "$1"; }
|
||||
|
||||
# Where the LLeMbas CLI is, or nothing: on PATH, or where its installer puts it. The launcher has
|
||||
# this function word for word, and the plugin the same rule in Lua (require("llembas").cli());
|
||||
# scripts/test-ide.sh holds the three together.
|
||||
find_cli() {
|
||||
command -v lembas 2>/dev/null && return 0
|
||||
[ -x "$HOME/.local/bin/lembas" ] && printf '%s\n' "$HOME/.local/bin/lembas" && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
# What was changed in a plugin's directory since its commit was checked out: files edited or
|
||||
# deleted, and files added (ignored ones too: Neovim loads whatever lies there). The help tags
|
||||
# this installer writes itself are not a change.
|
||||
changed_in() {
|
||||
git_quiet -C "$1" status --porcelain --untracked-files=all --ignored 2>/dev/null | grep -v -E '^(\?\?|!!) doc/tags$' || true
|
||||
}
|
||||
|
||||
# --- which release -----------------------------------------------------------------------------
|
||||
|
||||
api_base() {
|
||||
if [ "$FORGE" = https://github.com ]; then echo https://api.github.com; else echo "$FORGE/api/v1"; fi
|
||||
}
|
||||
|
||||
# The newest release tag of the channel, by version: vX.Y.Z, and for beta also vX.Y.Z-beta.N
|
||||
# (a beta sorts below its own release).
|
||||
newest_tag() { # [owner/name] [channel]: this product's own and the chosen channel unless said
|
||||
local slug="${1:-$SLUG}" channel="${2:-$CHANNEL}" json tags
|
||||
json="$(curl -fsSL --proto '=https' --proto-redir '=https' "$(api_base)/repos/$slug/releases?per_page=50&limit=50")" || return 1
|
||||
tags="$(printf '%s' "$json" | tr ',' '\n' | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p')"
|
||||
if [ "$channel" = beta ]; then
|
||||
tags="$(printf '%s\n' "$tags" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$' || true)"
|
||||
else
|
||||
tags="$(printf '%s\n' "$tags" | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' || true)"
|
||||
fi
|
||||
printf '%s\n' "$tags" | sed '/^$/d' | sed -E 's/^v//; s/-beta\.([0-9]+)$/.beta.\1/; /beta/!s/$/.zz/' | sort -V | tail -n1 |
|
||||
sed -E 's/\.zz$//; s/\.beta\.([0-9]+)$/-beta.\1/; s/^/v/'
|
||||
}
|
||||
|
||||
check_signature() {
|
||||
local dir="$1"
|
||||
if [ -z "$PUBKEY" ]; then
|
||||
note "checked against the release's SHA256SUMS only: LLEMBAS_IDE_PUBKEY is empty, so no signature is asked for"
|
||||
return 0
|
||||
fi
|
||||
need ssh-keygen "openssh-client; it checks the release's signature"
|
||||
[ -s "$dir/SHA256SUMS.sig" ] || die "the release is not signed (no SHA256SUMS.sig) — nothing installed"
|
||||
printf '%s %s\n' "$SIGN_NAMESPACE" "$PUBKEY" >"$dir/allowed"
|
||||
ssh-keygen -Y verify -f "$dir/allowed" -I "$SIGN_NAMESPACE" -n "$SIGN_NAMESPACE" -s "$dir/SHA256SUMS.sig" <"$dir/SHA256SUMS" >/dev/null 2>&1 ||
|
||||
die "SHA256SUMS is not signed by the release key — nothing installed"
|
||||
note "signature good (release key)"
|
||||
}
|
||||
|
||||
# No release in hand: fetch one, check it, and hand over to the installer inside it.
|
||||
from_release() {
|
||||
local tag version base tarball top listed
|
||||
need curl
|
||||
need tar
|
||||
if [ -n "$VERSION_WANTED" ]; then
|
||||
tag="v${VERSION_WANTED#v}"
|
||||
elif [ "$DRY" = 1 ]; then
|
||||
say "LLeMbas IDE (dry run: nothing is downloaded or written)"
|
||||
step "ask $(api_base)/repos/$SLUG/releases for the newest $CHANNEL release"
|
||||
step "download its llembas-ide-<version>.tar.gz and SHA256SUMS, and check the one against the other"
|
||||
step "unpack it in a temporary directory and run the installer inside it with the same options"
|
||||
note "what that installer does is listed by: ide/install.sh --from-checkout --dry-run"
|
||||
return 0
|
||||
else
|
||||
tag="$(newest_tag)" || die "could not list the releases at $FORGE/$SLUG (network, or a rate limit) — nothing installed"
|
||||
if [ -z "$tag" ]; then
|
||||
[ "$CHANNEL" = stable ] && die "there is no stable release of LLeMbas IDE yet — nothing installed. The betas: add --channel beta (piped: … | bash -s -- --channel beta)"
|
||||
die "there is no release at $FORGE/$SLUG — nothing installed"
|
||||
fi
|
||||
fi
|
||||
version="${tag#v}"
|
||||
[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$ ]] || die "not a version: $version"
|
||||
base="${LLEMBAS_IDE_RELEASE_BASE:-$FORGE/$SLUG/releases/download}"
|
||||
base="${base%/}/$tag"
|
||||
# Said here, in words: the first download below keeps curl quiet, and would keep this quiet too.
|
||||
case "$base" in
|
||||
https://* | file:///*) ;;
|
||||
*) die "refusing to download from $base: only https:// (or a local file://) is used — nothing installed" ;;
|
||||
esac
|
||||
tarball="llembas-ide-$version.tar.gz"
|
||||
if [ "$DRY" = 1 ]; then
|
||||
say "LLeMbas IDE $version (dry run: nothing is downloaded or written)"
|
||||
step "download $base/$tarball and $base/SHA256SUMS, and check the one against the other"
|
||||
step "unpack it in a temporary directory and run the installer inside it with the same options"
|
||||
note "what that installer does is listed by: ide/install.sh --from-checkout --dry-run"
|
||||
return 0
|
||||
fi
|
||||
TMP="$(mktemp -d)"
|
||||
say "LLeMbas IDE $version"
|
||||
note "downloading $tarball"
|
||||
fetch "$base/$tarball" "$TMP/$tarball" 2>/dev/null ||
|
||||
die "could not download $tarball: release $tag has no LLeMbas IDE in it, or the network failed — nothing installed"
|
||||
fetch "$base/SHA256SUMS" "$TMP/SHA256SUMS" || die "could not download SHA256SUMS from release $tag — nothing installed"
|
||||
if [ -n "$PUBKEY" ]; then fetch "$base/SHA256SUMS.sig" "$TMP/SHA256SUMS.sig" 2>/dev/null || rm -f "$TMP/SHA256SUMS.sig"; fi
|
||||
check_signature "$TMP"
|
||||
listed="$(awk -v f="$tarball" '$2 == f || $2 == "*" f { print $1 }' "$TMP/SHA256SUMS")"
|
||||
[ "$(printf '%s\n' "$listed" | sed '/^$/d' | wc -l | tr -d ' ')" = 1 ] || die "SHA256SUMS does not list $tarball exactly once — nothing installed"
|
||||
[ "$listed" = "$(sha256_of "$TMP/$tarball")" ] || die "$tarball does not match SHA256SUMS — nothing installed"
|
||||
note "checksum good"
|
||||
# Nothing in the archive may land outside the directory it is unpacked into.
|
||||
top="llembas-ide-$version"
|
||||
if tar -tzf "$TMP/$tarball" | grep -v -E "^$top(/|\$)" | grep -q .; then die "$tarball holds files outside $top/ — nothing installed"; fi
|
||||
if tar -tzf "$TMP/$tarball" | grep -q -E '(^|/)\.\.(/|$)'; then die "$tarball holds a path with .. — nothing installed"; fi
|
||||
# Files and directories only: a link could point anywhere, and the IDE has none.
|
||||
if tar -tvzf "$TMP/$tarball" | grep -q -E '^[lh]'; then die "$tarball holds a link — nothing installed"; fi
|
||||
mkdir "$TMP/payload"
|
||||
tar -xzf "$TMP/$tarball" -C "$TMP/payload"
|
||||
[ "$(tr -d '[:space:]' <"$TMP/payload/$top/VERSION")" = "$version" ] || die "release $tag carries the files of another version — nothing installed"
|
||||
[ -f "$TMP/payload/$top/ide/install.sh" ] || die "release $tag has no installer in it — nothing installed"
|
||||
local args=(--from-dir "$TMP/payload/$top")
|
||||
[ -z "$PREFIX" ] || args+=(--prefix "$PREFIX")
|
||||
[ -z "$NVIM_BIN" ] || args+=(--nvim-bin "$NVIM_BIN")
|
||||
[ "$WITH_CLI" = 1 ] || args+=(--no-cli)
|
||||
[ "$WITH_PARSERS" = 1 ] || args+=(--no-parsers)
|
||||
[ "$YES" = 0 ] || args+=(--yes)
|
||||
bash "$TMP/payload/$top/ide/install.sh" "${args[@]}"
|
||||
}
|
||||
|
||||
# --- the parts ---------------------------------------------------------------------------------
|
||||
|
||||
nvim_asset() {
|
||||
case "$(uname -s)-$(uname -m)" in
|
||||
Linux-x86_64) echo nvim-linux-x86_64 ;;
|
||||
Linux-aarch64 | Linux-arm64) echo nvim-linux-arm64 ;;
|
||||
Darwin-arm64) echo nvim-macos-arm64 ;;
|
||||
Darwin-x86_64) echo nvim-macos-x86_64 ;;
|
||||
*) return 1 ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# "NVIM v0.10.4" is at least MIN_NVIM.
|
||||
nvim_new_enough() {
|
||||
local v major minor
|
||||
v="$(nvim_quiet "$1" --version 2>/dev/null | sed -n '1s/^NVIM v\([0-9][0-9.]*\).*/\1/p')"
|
||||
[ -n "$v" ] || return 1
|
||||
major="${v%%.*}"
|
||||
minor="${v#*.}"
|
||||
minor="${minor%%.*}"
|
||||
[ "$major" -gt "${MIN_NVIM%%.*}" ] || { [ "$major" -eq "${MIN_NVIM%%.*}" ] && [ "$minor" -ge "${MIN_NVIM#*.}" ]; }
|
||||
}
|
||||
|
||||
# A git repository at exactly one commit: fetched by its hash, and the hash is the check.
|
||||
fetch_commit() {
|
||||
local url="$1" commit="$2" dest="$3" from="$1" mirror="${LLEMBAS_IDE_GIT_MIRROR:-}"
|
||||
if [ -n "$mirror" ] && [ -d "$mirror/$(basename "$url")" ]; then from="$mirror/$(basename "$url")"; fi
|
||||
mkdir -p "$dest"
|
||||
git_quiet -C "$dest" init -q
|
||||
git_quiet -C "$dest" remote add origin "$url"
|
||||
git_quiet -C "$dest" fetch -q --depth 1 "$from" "$commit" 2>/dev/null ||
|
||||
die "could not fetch $url at $commit (network?) — nothing installed"
|
||||
git_quiet -C "$dest" -c advice.detachedHead=false checkout -q --detach FETCH_HEAD
|
||||
[ "$(git_quiet -C "$dest" rev-parse HEAD)" = "$commit" ] || die "$url did not give commit $commit — nothing installed"
|
||||
}
|
||||
|
||||
# An installed plugin is at its pin, and no file in it was changed or added.
|
||||
at_pin() {
|
||||
local dir="$1" commit="$2"
|
||||
[ -d "$dir/.git" ] || return 1
|
||||
[ "$(git_quiet -C "$dir" rev-parse HEAD 2>/dev/null)" = "$commit" ] || return 1
|
||||
[ -z "$(changed_in "$dir")" ]
|
||||
}
|
||||
|
||||
stage_neovim() {
|
||||
local src="$1" version asset want got dir="$STAGE/nvim"
|
||||
if [ -n "$NVIM_BIN" ]; then
|
||||
step "use the Neovim at $NVIM_BIN instead of the pinned release"
|
||||
[ "$DRY" = 1 ] && return 0
|
||||
printf '%s\n' "$NVIM_BIN" >"$STAGE/lib/nvim-path"
|
||||
printf 'own %s\n' "$NVIM_BIN" >"$STAGE/lib/nvim-source"
|
||||
return 0
|
||||
fi
|
||||
version="$(tr -d '[:space:]' <"$src/ide/neovim.version")"
|
||||
asset="$(nvim_asset)" || die "there is no Neovim release build for $(uname -s) $(uname -m); install Neovim $MIN_NVIM or newer yourself and pass --nvim-bin <path>"
|
||||
want="$(awk -v f="$asset.tar.gz" '$2 == f { print $1 }' "$src/ide/neovim.sha256")"
|
||||
[ -n "$want" ] || die "ide/neovim.sha256 has no checksum for $asset.tar.gz"
|
||||
if [ -f "$PREFIX/lib/nvim-source" ] && [ "$(cat "$PREFIX/lib/nvim-source")" = "release $version $want" ] && [ -x "$PREFIX/nvim/bin/nvim" ]; then
|
||||
step "keep Neovim $version (already installed, checksum $want)"
|
||||
[ "$DRY" = 1 ] && return 0
|
||||
cp -a "$PREFIX/nvim" "$dir"
|
||||
else
|
||||
step "download $NVIM_RELEASES/v$version/$asset.tar.gz"
|
||||
step "check its SHA-256 is $want, and unpack it to $PREFIX/nvim"
|
||||
[ "$DRY" = 1 ] && return 0
|
||||
fetch "$NVIM_RELEASES/v$version/$asset.tar.gz" "$TMP/$asset.tar.gz" || die "could not download Neovim $version — nothing installed"
|
||||
got="$(sha256_of "$TMP/$asset.tar.gz")"
|
||||
[ "$got" = "$want" ] || die "Neovim $version's download has SHA-256 $got, not the pinned $want — nothing installed"
|
||||
if tar -tzf "$TMP/$asset.tar.gz" | grep -v -E "^$asset(/|\$)" | grep -q .; then die "the Neovim archive holds files outside $asset/ — nothing installed"; fi
|
||||
mkdir "$TMP/nvim"
|
||||
tar -xzf "$TMP/$asset.tar.gz" -C "$TMP/nvim"
|
||||
mv "$TMP/nvim/$asset" "$dir"
|
||||
fi
|
||||
printf '%s\n' "$PREFIX/nvim/bin/nvim" >"$STAGE/lib/nvim-path"
|
||||
printf 'release %s %s\n' "$version" "$want" >"$STAGE/lib/nvim-source"
|
||||
}
|
||||
|
||||
stage_plugins() {
|
||||
local src="$1" name where url commit licence rest dest have
|
||||
while read -r name where url commit licence rest; do
|
||||
[[ "$commit" =~ ^[0-9a-f]{40}$ ]] || die "ide/plugins.lock: $name is not pinned to a full commit"
|
||||
case "$url" in https://*) ;; *) die "ide/plugins.lock: $name does not come over https" ;; esac
|
||||
case "$where" in start | opt) ;; *) die "ide/plugins.lock: $name is neither start nor opt" ;; esac
|
||||
dest="$STAGE/site/pack/llembas/$where/$name"
|
||||
have="$PREFIX/site/pack/llembas/$where/$name"
|
||||
if at_pin "$have" "$commit"; then
|
||||
step "keep $name at $commit (already installed, unchanged)"
|
||||
[ "$DRY" = 1 ] || { mkdir -p "$(dirname "$dest")" && cp -a "$have" "$dest"; }
|
||||
else
|
||||
step "fetch $name from $url at commit $commit ($licence)"
|
||||
[ "$DRY" = 1 ] || fetch_commit "$url" "$commit" "$dest"
|
||||
fi
|
||||
done < <(lock_lines "$src/ide/plugins.lock")
|
||||
}
|
||||
|
||||
stage_own() {
|
||||
local src="$1" dest="$STAGE/site/pack/llembas/start/llembas-ide"
|
||||
step "place the IDE's configuration (ide/config) as the package llembas-ide"
|
||||
step "place the LLeMbas plugin (nvim/) $(tr -d '[:space:]' <"$src/VERSION")"
|
||||
[ "$DRY" = 1 ] && return 0
|
||||
mkdir -p "$dest" "$STAGE/lib/llembas"
|
||||
cp -R "$src/ide/config/lua" "$src/ide/config/colors" "$dest/"
|
||||
[ -f "$src/nvim/plugin/llembas.lua" ] || die "the LLeMbas plugin (nvim/) is not in $src — nothing installed"
|
||||
cp -R "$src/nvim" "$STAGE/lib/llembas/nvim"
|
||||
rm -rf "$STAGE/lib/llembas/nvim/tests"
|
||||
# The plugin reads its version from the VERSION file beside its directory.
|
||||
cp "$src/VERSION" "$STAGE/lib/llembas/VERSION"
|
||||
cp "$src/VERSION" "$STAGE/lib/VERSION"
|
||||
mkdir -p "$STAGE/lib/ide"
|
||||
cp "$src/ide/install.sh" "$src/ide/plugins.lock" "$src/ide/parsers.lock" "$src/ide/neovim.version" \
|
||||
"$src/ide/neovim.sha256" "$src/ide/user-init.lua" "$src/ide/THIRD_PARTY.md" "$STAGE/lib/ide/"
|
||||
cp -R "$src/ide/bin" "$src/ide/assets" "$src/ide/config" "$STAGE/lib/ide/"
|
||||
[ ! -f "$src/LICENSE" ] || cp "$src/LICENSE" "$STAGE/lib/LICENSE"
|
||||
}
|
||||
|
||||
c_compiler() {
|
||||
local c
|
||||
for c in cc gcc clang; do
|
||||
if command -v "$c" >/dev/null 2>&1; then
|
||||
echo "$c"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# The Treesitter grammars, all or none: a half set would colour some files by one rule and some
|
||||
# by another. Without them the IDE uses the grammars Neovim itself carries.
|
||||
stage_parsers() {
|
||||
local src="$1" cc lang url commit dir licence rest sources out have="$PREFIX/site/pack/llembas/start/llembas-parsers"
|
||||
local dest="$STAGE/site/pack/llembas/start/llembas-parsers" shared="-shared" count
|
||||
count="$(lock_lines "$src/ide/parsers.lock" | wc -l | tr -d ' ')"
|
||||
if [ "$WITH_PARSERS" != 1 ]; then
|
||||
step "leave the Treesitter grammars out (--no-parsers): Neovim's bundled ones are used"
|
||||
return 0
|
||||
fi
|
||||
if ! cc="$(c_compiler)"; then
|
||||
step "leave the Treesitter grammars out: no C compiler here (cc, gcc or clang). Neovim's bundled ones are used; install a compiler and run this again for all $count"
|
||||
return 0
|
||||
fi
|
||||
if [ -f "$PREFIX/lib/ide/parsers.lock" ] && cmp -s "$PREFIX/lib/ide/parsers.lock" "$src/ide/parsers.lock" &&
|
||||
[ "$(find "$have/parser" -name '*.so' 2>/dev/null | wc -l | tr -d ' ')" = "$count" ]; then
|
||||
step "keep the $count compiled Treesitter grammars (already installed, same pins)"
|
||||
[ "$DRY" = 1 ] || { mkdir -p "$(dirname "$dest")" && cp -a "$have" "$dest"; }
|
||||
return 0
|
||||
fi
|
||||
[ "$(uname -s)" != Darwin ] || shared="-bundle"
|
||||
if [ "$DRY" = 1 ]; then
|
||||
while read -r lang url commit dir licence rest; do
|
||||
step "fetch the $lang grammar from $url at commit $commit ($licence) and compile it with $cc"
|
||||
done < <(lock_lines "$src/ide/parsers.lock")
|
||||
return 0
|
||||
fi
|
||||
note "compiling $count Treesitter grammars with $cc (a minute or two)"
|
||||
mkdir -p "$dest/parser" "$TMP/grammars"
|
||||
while read -r lang url commit dir licence rest; do
|
||||
[[ "$commit" =~ ^[0-9a-f]{40}$ ]] || die "ide/parsers.lock: $lang is not pinned to a full commit"
|
||||
case "$url" in https://*) ;; *) die "ide/parsers.lock: $lang does not come over https" ;; esac
|
||||
[ -d "$TMP/grammars/$commit" ] || fetch_commit "$url" "$commit" "$TMP/grammars/$commit"
|
||||
out="$TMP/grammars/$commit/$dir/src"
|
||||
sources=("$out/parser.c")
|
||||
[ ! -f "$out/scanner.c" ] || sources+=("$out/scanner.c")
|
||||
if [ ! -f "$out/parser.c" ] || [ -f "$out/scanner.cc" ] ||
|
||||
! "$cc" -o "$dest/parser/$lang.so" -I "$out" "${sources[@]}" -Os -fPIC "$shared" 2>"$TMP/cc.log"; then
|
||||
warn "the $lang grammar did not compile with $cc ($(head -n1 "$TMP/cc.log" 2>/dev/null)); the IDE is installed without compiled grammars and uses Neovim's bundled ones."
|
||||
rm -rf "$dest"
|
||||
return 0
|
||||
fi
|
||||
done < <(lock_lines "$src/ide/parsers.lock")
|
||||
step "compiled $count Treesitter grammars"
|
||||
}
|
||||
|
||||
# Help tags for every plugin that has documentation and no tags yet, so :help finds them.
|
||||
stage_helptags() {
|
||||
local nvim="$1" d
|
||||
[ "$DRY" = 1 ] && return 0
|
||||
for d in "$STAGE"/site/pack/llembas/*/*/doc "$STAGE/lib/llembas/nvim/doc"; do
|
||||
if [ ! -d "$d" ] || [ -f "$d/tags" ]; then continue; fi
|
||||
nvim_quiet "$nvim" --headless -u NONE -i NONE -c "silent! helptags $d" -c qa >/dev/null 2>&1 || true
|
||||
done
|
||||
}
|
||||
|
||||
# The whole thing started once where it was built, away from the person's own files: a
|
||||
# configuration that does not start is never swapped in.
|
||||
try_staged() {
|
||||
local src="$1" nvim="$2" out
|
||||
step "start the staged IDE once, headless, to see that every part loads"
|
||||
[ "$DRY" = 1 ] && return 0
|
||||
mkdir -p "$TMP/try/config/$APP" "$TMP/try/state" "$TMP/try/cache" "$TMP/try/data"
|
||||
cp "$src/ide/config/init.lua" "$TMP/try/config/$APP/init.lua"
|
||||
out="$(XDG_CONFIG_HOME="$TMP/try/config" XDG_STATE_HOME="$TMP/try/state" XDG_CACHE_HOME="$TMP/try/cache" XDG_DATA_HOME="$TMP/try/data" \
|
||||
NVIM_LOG_FILE="$TMP/nvim.log" NVIM_APPNAME="$APP" LLEMBAS_IDE_PREFIX="$STAGE" "$nvim" --headless \
|
||||
--cmd 'lua vim.g.llembas_ide_no_session = true; vim.g.llembas_ide_no_dashboard = true' \
|
||||
-c 'lua local ok, ide = pcall(require, "llembas_ide"); io.stdout:write(ok and ("problems=" .. #ide.problems .. " " .. table.concat(ide.problems, " | ")) or "problems=all the IDE did not load")' \
|
||||
-c 'qa!' 2>&1)" || die "the staged IDE did not start ($out) — nothing installed"
|
||||
case "$out" in
|
||||
*"problems=0"*) ;;
|
||||
*) die "the staged IDE did not start cleanly (${out#*problems=}) — nothing installed" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Put one of the three managed directories in place, keeping the old one until the end.
|
||||
swap_unit() {
|
||||
local unit="$1"
|
||||
[ -e "$STAGE/$unit" ] || {
|
||||
# Nothing staged (no Neovim of our own with --nvim-bin): the old one still goes.
|
||||
if [ -e "$PREFIX/$unit" ]; then
|
||||
mkdir -p "$(dirname "$OLD/$unit")"
|
||||
mv "$PREFIX/$unit" "$OLD/$unit"
|
||||
SWAPPED+=("$unit")
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
mkdir -p "$(dirname "$OLD/$unit")" "$(dirname "$PREFIX/$unit")"
|
||||
SWAPPED+=("$unit")
|
||||
if [ -e "$PREFIX/$unit" ]; then mv "$PREFIX/$unit" "$OLD/$unit"; fi
|
||||
mv "$STAGE/$unit" "$PREFIX/$unit"
|
||||
}
|
||||
|
||||
# Put one file in place outside the prefix, keeping what was there until the end.
|
||||
place_file() {
|
||||
local from="$1" to="$2" mode="$3" n="${#PLACED[@]}"
|
||||
mkdir -p "$(dirname "$to")" "$OLD/files"
|
||||
PLACED+=("$to")
|
||||
if [ -e "$to" ] || [ -L "$to" ]; then mv "$to" "$OLD/files/$n"; fi
|
||||
cp "$from" "$to.tmp.$$"
|
||||
chmod "$mode" "$to.tmp.$$"
|
||||
mv "$to.tmp.$$" "$to"
|
||||
}
|
||||
|
||||
# The CLI's own installer (get.sh) from one release of the CLI, checked before it is run: the
|
||||
# release's SHA256SUMS must be signed with the release key, and get.sh must be the file it lists.
|
||||
# Run in a subshell by install_cli: a failure here ends the check, not the installation.
|
||||
checked_cli_installer() { # checked_cli_installer <release's download directory> <directory to keep it in>
|
||||
local base="$1" dir="$2" listed
|
||||
case "$base" in
|
||||
https://* | file:///*) ;;
|
||||
*) die "refusing to download from $base: only https:// (or a local file://) is used" ;;
|
||||
esac
|
||||
mkdir -p "$dir"
|
||||
fetch "$base/SHA256SUMS" "$dir/SHA256SUMS" 2>/dev/null || die "could not download the SHA256SUMS of the LLeMbas CLI's release"
|
||||
if [ -n "$PUBKEY" ]; then fetch "$base/SHA256SUMS.sig" "$dir/SHA256SUMS.sig" 2>/dev/null || rm -f "$dir/SHA256SUMS.sig"; fi
|
||||
check_signature "$dir"
|
||||
fetch "$base/get.sh" "$dir/get.sh" 2>/dev/null || die "could not download the LLeMbas CLI's installer (get.sh)"
|
||||
listed="$(awk -v f=get.sh '$2 == f || $2 == "*" f { print $1 }' "$dir/SHA256SUMS")"
|
||||
[ "$(printf '%s\n' "$listed" | sed '/^$/d' | wc -l | tr -d ' ')" = 1 ] || die "the LLeMbas CLI release's SHA256SUMS does not list get.sh exactly once"
|
||||
[ "$listed" = "$(sha256_of "$dir/get.sh")" ] || die "the LLeMbas CLI's installer does not match its release's SHA256SUMS"
|
||||
note "the LLeMbas CLI's installer matches its release"
|
||||
}
|
||||
|
||||
install_cli() {
|
||||
local channel=stable version="$1" at tag base later
|
||||
[ "$WITH_CLI" = 1 ] || return 0
|
||||
if at="$(find_cli)"; then
|
||||
step "leave the LLeMbas CLI alone: it is installed ($at)"
|
||||
return 0
|
||||
fi
|
||||
later="Later: $APP update offers it again, or see $CLI_HOME"
|
||||
# A beta of the IDE goes with a beta of the CLI.
|
||||
case "$version" in *-beta.*) channel=beta ;; esac
|
||||
if [ "$(uname -s)" != Linux ]; then
|
||||
step "leave the LLeMbas CLI out: its installer is for Linux. See $CLI_HOME"
|
||||
return 0
|
||||
fi
|
||||
if [ "$DRY" = 1 ]; then
|
||||
step "offer to install the LLeMbas CLI ($channel): its own installer (get.sh) from its newest $channel release at $CLI_HOME, run only once it matches that release's signed SHA256SUMS"
|
||||
return 0
|
||||
fi
|
||||
say ""
|
||||
say "The LLeMbas CLI (the lembas command) is the agent the IDE talks to, and it is not installed."
|
||||
if ! ask_yes "Install it now with its own installer?"; then
|
||||
note "not installed. $later"
|
||||
return 0
|
||||
fi
|
||||
# Which release of the CLI: the one named, else the newest of the channel.
|
||||
if [ -n "${LLEMBAS_IDE_CLI_VERSION:-}" ]; then
|
||||
tag="v${LLEMBAS_IDE_CLI_VERSION#v}"
|
||||
else
|
||||
tag="$(newest_tag "$CLI_SLUG" "$channel" 2>/dev/null)" || tag=""
|
||||
fi
|
||||
if ! [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$ ]]; then
|
||||
warn "could not find a $channel release of the LLeMbas CLI (network, or a rate limit); the IDE is installed and works as an editor. $later"
|
||||
return 0
|
||||
fi
|
||||
base="${LLEMBAS_IDE_CLI_RELEASE_BASE:-$FORGE/$CLI_SLUG/releases/download}"
|
||||
base="${base%/}/$tag"
|
||||
note "LLeMbas CLI ${tag#v}"
|
||||
# Its own installer, from that release, and only after checking it. It then checks the
|
||||
# program it downloads itself.
|
||||
if ! (checked_cli_installer "$base" "$TMP/cli"); then
|
||||
warn "the LLeMbas CLI's installer could not be checked, so it was not run; the IDE is installed and works as an editor. $later"
|
||||
return 0
|
||||
fi
|
||||
if [ "$YES" = 1 ] || ! has_tty; then
|
||||
LEMBAS_REF="$tag" LEMBAS_CHANNEL="$channel" bash "$TMP/cli/get.sh" --yes || warn "the CLI's installer failed; the IDE itself is installed."
|
||||
else
|
||||
LEMBAS_REF="$tag" LEMBAS_CHANNEL="$channel" bash "$TMP/cli/get.sh" </dev/tty || warn "the CLI's installer failed; the IDE itself is installed."
|
||||
fi
|
||||
}
|
||||
|
||||
# --- the installation --------------------------------------------------------------------------
|
||||
|
||||
install_from() {
|
||||
local src="$1" version config bin data desktop icon nvim old_init_sha="" init_state launcher
|
||||
if [ ! -f "$src/VERSION" ] || [ ! -f "$src/ide/plugins.lock" ] || [ ! -d "$src/ide/config" ] || [ ! -d "$src/nvim" ]; then
|
||||
die "$src is not LLeMbas IDE (it needs VERSION, ide/ and nvim/)"
|
||||
fi
|
||||
version="$(tr -d '[:space:]' <"$src/VERSION")"
|
||||
data="${XDG_DATA_HOME:-$HOME/.local/share}"
|
||||
config="${XDG_CONFIG_HOME:-$HOME/.config}/$APP"
|
||||
bin="$HOME/.local/bin"
|
||||
[ -n "$PREFIX" ] || PREFIX="$data/$APP"
|
||||
case "$PREFIX" in /*) ;; *) die "--prefix must be an absolute path" ;; esac
|
||||
PREFIX="${PREFIX%/}"
|
||||
case "$PREFIX" in /*/*) ;; *) die "--prefix must be a directory of the IDE's own, not $PREFIX" ;; esac
|
||||
[ "$PREFIX" != "${HOME%/}" ] || die "--prefix must be a directory of the IDE's own, not your home directory"
|
||||
launcher="$bin/$APP"
|
||||
desktop="$data/applications/$APP.desktop"
|
||||
icon="$data/icons/hicolor/256x256/apps/$APP.png"
|
||||
|
||||
need git "the plugins are fetched with it"
|
||||
need tar
|
||||
[ -n "$NVIM_BIN" ] || need curl
|
||||
if [ -n "$NVIM_BIN" ]; then
|
||||
case "$NVIM_BIN" in /*) ;; *) die "--nvim-bin must be an absolute path" ;; esac
|
||||
[ -x "$NVIM_BIN" ] || die "--nvim-bin $NVIM_BIN is not a program"
|
||||
nvim_new_enough "$NVIM_BIN" || die "$NVIM_BIN is older than Neovim $MIN_NVIM, the oldest the IDE runs on"
|
||||
else
|
||||
nvim_asset >/dev/null || die "there is no Neovim release build for $(uname -s) $(uname -m); install Neovim $MIN_NVIM or newer yourself and pass --nvim-bin <path>"
|
||||
fi
|
||||
[ ! -f "$PREFIX/lib/installed" ] || old_init_sha="$(sed -n 's/^init_sha=//p' "$PREFIX/lib/installed")"
|
||||
|
||||
if [ "$DRY" = 1 ]; then
|
||||
say "LLeMbas IDE $version (dry run: nothing is downloaded or written)"
|
||||
else
|
||||
say "LLeMbas IDE $version"
|
||||
# The directories above the prefix that are not there yet: made now, and taken away again,
|
||||
# deepest first, if this run ends with nothing installed.
|
||||
MADE=""
|
||||
up="$(dirname "$PREFIX")"
|
||||
while [ ! -d "$up" ] && [ "$up" != / ] && [ "$up" != . ]; do
|
||||
MADE="$MADE$up"$'\n'
|
||||
up="$(dirname "$up")"
|
||||
done
|
||||
mkdir -p "$PREFIX"
|
||||
TMP="$(mktemp -d)"
|
||||
STAGE="$(mktemp -d "$PREFIX/.staging.XXXXXX")"
|
||||
mkdir -p "$STAGE/lib" "$STAGE/site/pack/llembas"
|
||||
fi
|
||||
step "build everything in a staging directory inside $PREFIX"
|
||||
|
||||
stage_neovim "$src"
|
||||
stage_plugins "$src"
|
||||
stage_own "$src"
|
||||
stage_parsers "$src"
|
||||
if [ "$DRY" != 1 ]; then
|
||||
if [ -n "$NVIM_BIN" ]; then nvim="$NVIM_BIN"; else nvim="$STAGE/nvim/bin/nvim"; fi
|
||||
nvim_quiet "$nvim" --version >/dev/null 2>&1 || die "the Neovim at $nvim does not run on this machine — nothing installed"
|
||||
stage_helptags "$nvim"
|
||||
fi
|
||||
try_staged "$src" "${nvim:-}"
|
||||
|
||||
step "swap the staged nvim/, site/pack/llembas/ and lib/ into $PREFIX"
|
||||
if [ -f "$config/init.lua" ] && [ "$(sha256_of "$config/init.lua")" != "$(sha256_of "$src/ide/config/init.lua")" ] &&
|
||||
[ "$(sha256_of "$config/init.lua")" != "$old_init_sha" ]; then
|
||||
init_state=edited
|
||||
step "keep your edited $config/init.lua; the IDE's own goes beside it as init.lua.new"
|
||||
else
|
||||
init_state=ours
|
||||
step "write $config/init.lua"
|
||||
fi
|
||||
if [ -f "$config/lua/user/init.lua" ]; then
|
||||
step "keep your $config/lua/user/init.lua as it is"
|
||||
else
|
||||
step "create $config/lua/user/init.lua, yours: comments only"
|
||||
fi
|
||||
step "write the launcher $launcher"
|
||||
if [ "$(uname -s)" = Linux ]; then
|
||||
step "write the menu entry $desktop and its icon $icon"
|
||||
fi
|
||||
if [ "$DRY" = 1 ]; then
|
||||
install_cli "$version"
|
||||
say "Dry run: nothing was changed."
|
||||
return 0
|
||||
fi
|
||||
|
||||
{
|
||||
printf 'version=%s\n' "$version"
|
||||
printf 'config=%s\n' "$config"
|
||||
printf 'launcher=%s\n' "$launcher"
|
||||
printf 'init_sha=%s\n' "$(sha256_of "$src/ide/config/init.lua")"
|
||||
printf 'user_sha=%s\n' "$(sha256_of "$src/ide/user-init.lua")"
|
||||
[ "$WITH_PARSERS" = 1 ] || printf 'parsers=off\n'
|
||||
if [ "$(uname -s)" = Linux ]; then
|
||||
printf 'desktop=%s\n' "$desktop"
|
||||
printf 'icon=%s\n' "$icon"
|
||||
fi
|
||||
} >"$STAGE/lib/installed"
|
||||
|
||||
OLD="$(mktemp -d "$PREFIX/.old.XXXXXX")"
|
||||
swap_unit nvim
|
||||
swap_unit site/pack/llembas
|
||||
swap_unit lib
|
||||
|
||||
if [ "$init_state" = edited ]; then
|
||||
place_file "$src/ide/config/init.lua" "$config/init.lua.new" 644
|
||||
else
|
||||
place_file "$src/ide/config/init.lua" "$config/init.lua" 644
|
||||
fi
|
||||
if [ ! -f "$config/lua/user/init.lua" ]; then
|
||||
place_file "$src/ide/user-init.lua" "$config/lua/user/init.lua" 644
|
||||
fi
|
||||
sed "s|^PREFIX=.*# set by install.sh\$|PREFIX='$(printf '%s' "$PREFIX" | sed "s/'/'\\\\\\\\''/g; s/[|&]/\\\\&/g")' # set by install.sh|" \
|
||||
"$src/ide/bin/llembas-ide" >"$TMP/launcher"
|
||||
grep -q "^PREFIX='" "$TMP/launcher" || die "the launcher could not be written — nothing installed"
|
||||
place_file "$TMP/launcher" "$launcher" 755
|
||||
if [ "$(uname -s)" = Linux ]; then
|
||||
{
|
||||
printf '[Desktop Entry]\nType=Application\nName=LLeMbas IDE\nGenericName=Text Editor\n'
|
||||
printf 'Comment=A complete Neovim editor with LLeMbas built in\n'
|
||||
printf 'Exec="%s" %%F\nTryExec=%s\nIcon=%s\nTerminal=true\n' "$launcher" "$launcher" "$APP"
|
||||
printf 'Categories=Development;TextEditor;IDE;\nKeywords=editor;code;neovim;llembas;\n'
|
||||
printf 'MimeType=text/plain;\nStartupNotify=false\n'
|
||||
} >"$TMP/desktop"
|
||||
place_file "$TMP/desktop" "$desktop" 644
|
||||
place_file "$src/ide/assets/llembas-ide.png" "$icon" 644
|
||||
fi
|
||||
"$launcher" --version >/dev/null 2>&1 || die "the launcher does not run — nothing installed"
|
||||
DONE=1
|
||||
|
||||
say ""
|
||||
say "LLeMbas IDE $version is installed. Start it with: $APP"
|
||||
case ":$PATH:" in
|
||||
*":$bin:"*) ;;
|
||||
*) note "$bin is not on your PATH: add it (export PATH=\"\$HOME/.local/bin:\$PATH\"), or run $launcher" ;;
|
||||
esac
|
||||
[ "$init_state" != edited ] || note "your edited init.lua was kept; compare it with init.lua.new. Your own settings are safer in lua/user/init.lua"
|
||||
note "check it any time: $APP doctor update: $APP update remove: $APP uninstall"
|
||||
install_cli "$version"
|
||||
}
|
||||
|
||||
main() {
|
||||
trap cleanup EXIT
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--version) VERSION_WANTED="${2:?--version needs a version}" && shift ;;
|
||||
--channel) CHANNEL="${2:?--channel needs stable or beta}" && shift ;;
|
||||
--prefix) PREFIX="${2:?--prefix needs a directory}" && shift ;;
|
||||
--from-checkout) FROM_CHECKOUT=1 ;;
|
||||
--from-dir) FROM_DIR="${2:?--from-dir needs a directory}" && shift ;;
|
||||
--nvim-bin) NVIM_BIN="${2:?--nvim-bin needs a path}" && shift ;;
|
||||
--no-cli) WITH_CLI=0 ;;
|
||||
--no-parsers) WITH_PARSERS=0 ;;
|
||||
--yes | -y) YES=1 ;;
|
||||
--dry-run) DRY=1 ;;
|
||||
-h | --help)
|
||||
usage
|
||||
return 0
|
||||
;;
|
||||
*) die "unknown option $1 (--help lists them)" ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
case "$CHANNEL" in stable | beta) ;; *) die "--channel is stable or beta" ;; esac
|
||||
if [ -z "${HOME:-}" ] || [ ! -d "$HOME" ]; then die "HOME is not set to a directory"; fi
|
||||
[ "$(id -u)" != 0 ] || warn "running as root: LLeMbas IDE is installed for one user and needs no root."
|
||||
|
||||
if [ -n "$FROM_DIR" ]; then
|
||||
install_from "$(cd "$FROM_DIR" && pwd)"
|
||||
elif [ "$FROM_CHECKOUT" = 1 ]; then
|
||||
[ -f "${BASH_SOURCE[0]:-}" ] || die "--from-checkout needs this script run as a file inside a clone of the repository"
|
||||
install_from "$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
else
|
||||
from_release
|
||||
fi
|
||||
}
|
||||
|
||||
main "$@"
|
||||
@@ -0,0 +1,6 @@
|
||||
# SHA-256 of the official Neovim release tarballs for the version in neovim.version, as published
|
||||
# with the release at https://github.com/neovim/neovim/releases. install.sh refuses anything else.
|
||||
bb488a65a18b75c4bf35f128ac91b962eab845ba0e89685f33609b70f6090a12 nvim-linux-x86_64.tar.gz
|
||||
30a7b798b35426f6d3197c6b780f6f3860125c14f8cc12d10df1d43e60aee4eb nvim-linux-arm64.tar.gz
|
||||
465d836c7a5bf950f026c4f2debc4764f5699a26e56f431da098bcbbfeab2c70 nvim-macos-arm64.tar.gz
|
||||
1a50e1483158dd5a12e7ebdbdef194848950e25589e948ddfa00ec02fd49c7b5 nvim-macos-x86_64.tar.gz
|
||||
@@ -0,0 +1 @@
|
||||
0.12.7
|
||||
@@ -0,0 +1,23 @@
|
||||
# The Treesitter grammars compiled at install when a C compiler is there, each at exactly one
|
||||
# commit: the revisions nvim-treesitter's own lockfile.json names at the commit in plugins.lock,
|
||||
# so the grammars and its queries belong together. All of them or none.
|
||||
# language url commit directory licence
|
||||
bash https://github.com/tree-sitter/tree-sitter-bash 0c46d792d54c536be5ff7eb18eb95c70fccdb232 . MIT
|
||||
c https://github.com/tree-sitter/tree-sitter-c 2a265d69a4caf57108a73ad2ed1e6922dd2f998c . MIT
|
||||
css https://github.com/tree-sitter/tree-sitter-css 6e327db434fec0ee90f006697782e43ec855adf5 . MIT
|
||||
go https://github.com/tree-sitter/tree-sitter-go 5e73f476efafe5c768eda19bbe877f188ded6144 . MIT
|
||||
html https://github.com/tree-sitter/tree-sitter-html cbb91a0ff3621245e890d1c50cc811bffb77a26b . MIT
|
||||
javascript https://github.com/tree-sitter/tree-sitter-javascript 6fbef40512dcd9f0a61ce03a4c9ae7597b36ab5c . MIT
|
||||
json https://github.com/tree-sitter/tree-sitter-json 46aa487b3ade14b7b05ef92507fdaa3915a662a3 . MIT
|
||||
lua https://github.com/MunifTanjim/tree-sitter-lua db16e76558122e834ee214c8dc755b4a3edc82a9 . MIT
|
||||
markdown https://github.com/MDeiml/tree-sitter-markdown 413285231ce8fa8b11e7074bbe265b48aa7277f9 tree-sitter-markdown MIT
|
||||
markdown_inline https://github.com/MDeiml/tree-sitter-markdown 413285231ce8fa8b11e7074bbe265b48aa7277f9 tree-sitter-markdown-inline MIT
|
||||
python https://github.com/tree-sitter/tree-sitter-python 710796b8b877a970297106e5bbc8e2afa47f86ec . MIT
|
||||
query https://github.com/nvim-treesitter/tree-sitter-query 930202c2a80965a7a9ca018b5b2a08b25dfa7f12 . Apache-2.0
|
||||
rust https://github.com/tree-sitter/tree-sitter-rust e86119bdb4968b9799f6a014ca2401c178d54b5f . MIT
|
||||
toml https://github.com/tree-sitter-grammars/tree-sitter-toml 64b56832c2cffe41758f28e05c756a3a98d16f41 . MIT
|
||||
tsx https://github.com/tree-sitter/tree-sitter-typescript 75b3874edb2dc714fb1fd77a32013d0f8699989f tsx MIT
|
||||
typescript https://github.com/tree-sitter/tree-sitter-typescript 75b3874edb2dc714fb1fd77a32013d0f8699989f typescript MIT
|
||||
vim https://github.com/neovim/tree-sitter-vim 11b688a1f0e97c0c4e3dbabf4a38016335f4d237 . MIT
|
||||
vimdoc https://github.com/neovim/tree-sitter-vimdoc 2694c3d27e2ca98a0ccde72f33887394300d524e . Apache-2.0
|
||||
yaml https://github.com/tree-sitter-grammars/tree-sitter-yaml 1805917414a9a8ba2473717fd69447277a175fae . MIT
|
||||
@@ -0,0 +1,8 @@
|
||||
# The third-party plugins of LLeMbas IDE, each at exactly one commit. install.sh fetches that
|
||||
# commit with git and refuses anything else; nothing here is ever updated by the installed IDE.
|
||||
# name where(start|opt) url commit licence version
|
||||
mini.nvim start https://github.com/nvim-mini/mini.nvim 1345d191bb3da9c7b0e977f4387c5761f9bff68d MIT v0.18.0
|
||||
blink.cmp start https://github.com/Saghen/blink.cmp 78336bc89ee5365633bcf754d93df01678b5c08f MIT v1.10.2
|
||||
conform.nvim start https://github.com/stevearc/conform.nvim 3543d000dafbc41cc7761d860cfdb24e82154f75 MIT v9.1.0
|
||||
nvim-lspconfig start https://github.com/neovim/nvim-lspconfig 4648fd8ba5c678d7e2db75ae44ffac269bb589d8 Apache-2.0 v2.13.0
|
||||
nvim-treesitter opt https://github.com/nvim-treesitter/nvim-treesitter cf12346a3414fa1b06af75c79faebe7f76df080a Apache-2.0 master
|
||||
@@ -0,0 +1,356 @@
|
||||
-- The installed IDE, started headless through its own launcher, checked from the inside.
|
||||
-- llembas-ide --headless -c "luafile ide/tests/headless.lua"
|
||||
-- Environment: IDE_TEST_REPO (the repository), IDE_TEST_PARSERS (1 when the grammars were
|
||||
-- compiled), IDE_TEST_BG_DARK / IDE_TEST_BG_LIGHT (the tokens' backgrounds, #RRGGBB),
|
||||
-- IDE_TEST_FIRST (1 on the first start in a new home), IDE_TEST_USER (1 when lua/user/init.lua was given a marker line).
|
||||
local repo = assert(vim.env.IDE_TEST_REPO, "IDE_TEST_REPO")
|
||||
local passed, failed = 0, {}
|
||||
|
||||
local function check(name, fn)
|
||||
local ok, err = pcall(fn)
|
||||
if ok then
|
||||
passed = passed + 1
|
||||
else
|
||||
table.insert(failed, name .. ": " .. tostring(err))
|
||||
end
|
||||
end
|
||||
|
||||
local function eq(a, b, what)
|
||||
if not vim.deep_equal(a, b) then error((what or "") .. " expected " .. vim.inspect(b) .. ", got " .. vim.inspect(a), 2) end
|
||||
end
|
||||
|
||||
local function lock(path)
|
||||
local rows = {}
|
||||
for line in io.lines(path) do
|
||||
if not line:match("^%s*#") and line:match("%S") then table.insert(rows, vim.split(vim.trim(line), "%s+")) end
|
||||
end
|
||||
return rows
|
||||
end
|
||||
|
||||
local function run()
|
||||
local ide = require("llembas_ide")
|
||||
local prefix = ide.prefix
|
||||
|
||||
check("starts with no error message", function()
|
||||
for _, line in ipairs(vim.split(vim.fn.execute("messages"), "\n")) do
|
||||
assert(not line:match("^E%d+:") and not line:match("^Error") and not line:lower():match("deprecated"), line)
|
||||
end
|
||||
end)
|
||||
check("every part of the IDE started", function() eq(ide.problems, {}) end)
|
||||
check("the version is the repository's", function()
|
||||
eq(ide.version, vim.trim(table.concat(vim.fn.readfile(repo .. "/VERSION"), "")))
|
||||
end)
|
||||
check("its own NVIM_APPNAME", function()
|
||||
eq(vim.env.NVIM_APPNAME, "llembas-ide")
|
||||
assert(vim.fn.stdpath("config"):match("/llembas%-ide$"), vim.fn.stdpath("config"))
|
||||
end)
|
||||
|
||||
-- Plugins: each at its pin, and what Lua loads comes from that directory.
|
||||
local modules = {
|
||||
["mini.nvim"] = "mini.pick", ["blink.cmp"] = "blink.cmp", ["conform.nvim"] = "conform",
|
||||
["nvim-lspconfig"] = "lspconfig", ["nvim-treesitter"] = "nvim-treesitter.query_predicates",
|
||||
}
|
||||
local compiled = vim.env.IDE_TEST_PARSERS == "1"
|
||||
for _, p in ipairs(lock(repo .. "/ide/plugins.lock")) do
|
||||
local name, where, commit = p[1], p[2], p[4]
|
||||
local dir = prefix .. "/site/pack/llembas/" .. where .. "/" .. name
|
||||
check("plugin " .. name .. " is at its pinned commit", function()
|
||||
eq(vim.trim(vim.fn.system({ "git", "-C", dir, "rev-parse", "HEAD" })), commit)
|
||||
eq(vim.trim(vim.fn.system({ "git", "-C", dir, "status", "--porcelain", "--untracked-files=no" })), "", "changed files:")
|
||||
end)
|
||||
if name ~= "nvim-treesitter" or compiled then
|
||||
check("plugin " .. name .. " loads from its pinned directory", function()
|
||||
local module = assert(modules[name], "no module known for " .. name)
|
||||
require(module)
|
||||
local file = vim.api.nvim_get_runtime_file("lua/" .. module:gsub("%.", "/") .. ".lua", false)[1]
|
||||
or vim.api.nvim_get_runtime_file("lua/" .. module:gsub("%.", "/") .. "/init.lua", false)[1]
|
||||
assert(file and vim.startswith(vim.fn.resolve(file), vim.fn.resolve(dir)), tostring(file) .. " is not under " .. dir)
|
||||
end)
|
||||
end
|
||||
end
|
||||
check("no plugin manager, and nothing that installs", function()
|
||||
for _, c in ipairs({ "Lazy", "PackerSync", "Mason", "TSInstall", "TSUpdate" }) do
|
||||
eq(vim.fn.exists(":" .. c), 0, c)
|
||||
end
|
||||
end)
|
||||
|
||||
-- The colourscheme.
|
||||
check("the LLeMbas colourscheme is applied (dark: moria)", function()
|
||||
eq(vim.g.colors_name, "llembas")
|
||||
eq(vim.o.background, "dark")
|
||||
eq(("#%06X"):format(vim.api.nvim_get_hl(0, { name = "Normal" }).bg), vim.env.IDE_TEST_BG_DARK:upper())
|
||||
end)
|
||||
check("light is shire, and dark comes back", function()
|
||||
vim.o.background = "light"
|
||||
eq(vim.g.colors_name, "llembas")
|
||||
eq(("#%06X"):format(vim.api.nvim_get_hl(0, { name = "Normal" }).bg), vim.env.IDE_TEST_BG_LIGHT:upper())
|
||||
vim.o.background = "dark"
|
||||
eq(("#%06X"):format(vim.api.nvim_get_hl(0, { name = "Normal" }).bg), vim.env.IDE_TEST_BG_DARK:upper())
|
||||
end)
|
||||
check("the plugin's and the IDE's own groups are coloured by the theme", function()
|
||||
for _, g in ipairs({ "LLeMbasBrand", "LLeMbasGhost", "LLeMbasIdeLeaf", "MiniStatuslineModeNormal", "DiagnosticError" }) do
|
||||
assert(next(vim.api.nvim_get_hl(0, { name = g, link = false })) ~= nil, g .. " has no colours")
|
||||
end
|
||||
end)
|
||||
|
||||
-- The start screen.
|
||||
check("the dashboard is the start screen and shows its lines", function()
|
||||
eq(vim.bo.filetype, "llembas-ide-dashboard")
|
||||
local text = table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")
|
||||
assert(text:find("LLeMbas IDE " .. ide.version, 1, true), "no name and version")
|
||||
assert(text:find("▄▄███████", 1, true), "no mark")
|
||||
for _, a in ipairs(require("llembas_ide.dashboard").actions) do
|
||||
assert(text:find(a[1] .. " " .. a[2], 1, true), "no line for " .. a[2])
|
||||
assert(vim.fn.maparg(a[1], "n", false, true).buffer == 1, "no key " .. a[1])
|
||||
end
|
||||
if vim.env.IDE_TEST_FIRST == "1" then assert(text:find("Welcome.", 1, true), "no first-run welcome") end
|
||||
assert(text:find("The editor works", 1, true), "no line saying the editor works without LLeMbas")
|
||||
end)
|
||||
check("the dashboard's block shares one left edge", function()
|
||||
local edge
|
||||
for _, l in ipairs(vim.api.nvim_buf_get_lines(0, 0, -1, false)) do
|
||||
if l:match("^%s*%a %u") then
|
||||
local at = #l:match("^%s*")
|
||||
edge = edge or at
|
||||
eq(at, edge, l)
|
||||
end
|
||||
end
|
||||
assert(edge, "no action lines")
|
||||
end)
|
||||
check("the dashboard's block is 38 columns and no line is over 52", function()
|
||||
local rows = require("llembas_ide.dashboard").content(false)
|
||||
assert(#rows > 15)
|
||||
for _, r in ipairs(rows) do assert(vim.fn.strdisplaywidth(r[1]) <= 52, r[1]) end
|
||||
for _, r in ipairs(rows) do
|
||||
if r[3] then assert(vim.fn.strdisplaywidth(r[1]) <= 38, r[1]) end
|
||||
end
|
||||
end)
|
||||
check("the window title names the IDE", function()
|
||||
assert(vim.o.title and vim.o.titlestring:find("LLeMbas IDE", 1, true))
|
||||
end)
|
||||
|
||||
-- LLeMbas built in.
|
||||
check("the LLeMbas plugin's commands exist", function()
|
||||
for _, c in ipairs({ "LLeMbas", "LLeMbasAsk", "LLeMbasEdit", "LLeMbasExplain", "LLeMbasFix", "LLeMbasGenerate",
|
||||
"LLeMbasAutocomplete", "LLeMbasMode", "LLeMbasModel", "LLeMbasSessions", "LLeMbasNew", "LLeMbasStatus" }) do
|
||||
eq(vim.fn.exists(":" .. c), 2, c)
|
||||
end
|
||||
eq(require("llembas").version, ide.version, "plugin version")
|
||||
end)
|
||||
check("the IDE's own commands exist", function()
|
||||
for _, c in ipairs({ "LLeMbasIdeKeys", "LLeMbasIdeHome", "LLeMbasIdeLsp", "LLeMbasIdeFormat", "LLeMbasIdeTerminal",
|
||||
"LLeMbasIdeDiff", "LLeMbasIdeSignIn", "LLeMbasIdeVersion", "LLeMbasIdeConfig", "LLeMbasIdeProblems", "LLeMbasIdeDoctor" }) do
|
||||
eq(vim.fn.exists(":" .. c), 2, c)
|
||||
end
|
||||
end)
|
||||
check("nothing predefined: the plugin starts the CLI by name, with no server or model", function()
|
||||
local c = require("llembas").config
|
||||
eq(c.cmd, { "lembas", "serve", "--stdio" })
|
||||
eq(c.model, nil)
|
||||
eq(c.complete.model, nil)
|
||||
end)
|
||||
check("without the CLI: no suggestions asked for, and the statusline says so", function()
|
||||
if vim.fn.executable("lembas") == 1 then return end
|
||||
eq(require("llembas_ide.llembas").autocomplete_on(), false)
|
||||
local text, live = require("llembas_ide.llembas").status()
|
||||
eq({ text, live }, { "◈ no CLI", false })
|
||||
end)
|
||||
check("sign in shows the one command when the plugin has no :LLeMbasLogin", function()
|
||||
if vim.fn.exists(":LLeMbasLogin") == 2 then return end
|
||||
vim.cmd("LLeMbasIdeSignIn")
|
||||
local text = table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n")
|
||||
assert(text:find("lembas login", 1, true) or text:find("LLeMbas-CLI", 1, true), text)
|
||||
vim.cmd("close")
|
||||
end)
|
||||
|
||||
-- Keys.
|
||||
local keys = require("llembas_ide.keys")
|
||||
check("the key map has no binding twice", function() eq(keys.duplicates(), {}) end)
|
||||
check("every key of the map is mapped", function()
|
||||
for _, k in ipairs(keys.map) do
|
||||
for _, mode in ipairs(type(k[1]) == "table" and k[1] or { k[1] }) do
|
||||
assert(vim.fn.maparg(k[2], mode) ~= "" or vim.fn.maparg(k[2], mode, false, true).callback, mode .. " " .. k[2])
|
||||
end
|
||||
end
|
||||
end)
|
||||
check("the leader is <Space>, and <Tab> in insert mode is left to LLeMbas", function()
|
||||
eq(vim.g.mapleader, " ")
|
||||
-- Neovim 0.11 and newer map <Tab> themselves (to move in a snippet); nothing of the menu's may be on it.
|
||||
local tab = vim.fn.maparg("<Tab>", "i", false, true)
|
||||
assert(not tostring(tab.rhs or tab.callback and debug.getinfo(tab.callback, "S").source or ""):find("blink"), vim.inspect(tab))
|
||||
local menu = require("blink.cmp.config").keymap
|
||||
eq(menu.preset, "none")
|
||||
eq(menu["<Tab>"], nil, "the menu's <Tab>")
|
||||
assert(menu["<C-y>"] and menu["<CR>"], "the menu's own keys")
|
||||
end)
|
||||
check("the README's cheat sheet is the key map", function()
|
||||
local readme = table.concat(vim.fn.readfile(repo .. "/ide/README.md"), "\n")
|
||||
local block = readme:match("<!%-%- keys:begin %-%->\n(.-)\n<!%-%- keys:end %-%->")
|
||||
assert(block, "no keys block in ide/README.md")
|
||||
eq(vim.trim(block), vim.trim(table.concat(keys.markdown(), "\n")))
|
||||
end)
|
||||
check(":LLeMbasIdeKeys, :LLeMbasIdeLsp and :LLeMbasIdeProblems open", function()
|
||||
for _, c in ipairs({ "LLeMbasIdeKeys", "LLeMbasIdeLsp", "LLeMbasIdeProblems" }) do
|
||||
vim.cmd(c)
|
||||
eq(vim.bo.filetype, "llembas-ide-page", c)
|
||||
assert(vim.api.nvim_buf_line_count(0) > 0)
|
||||
vim.cmd("close")
|
||||
end
|
||||
end)
|
||||
|
||||
-- Safety and options.
|
||||
check("modelines and per-directory configuration are off", function()
|
||||
eq({ vim.o.modeline, vim.o.modelines, vim.o.exrc }, { false, 0, false })
|
||||
end)
|
||||
check("the everyday options", function()
|
||||
eq({ vim.go.number, vim.o.mouse, vim.o.undofile, vim.o.splitright, vim.o.ignorecase, vim.o.smartcase },
|
||||
{ true, "a", true, true, true, true })
|
||||
assert(vim.o.clipboard:find("unnamedplus"), vim.o.clipboard)
|
||||
end)
|
||||
|
||||
-- Bars.
|
||||
check("the top and the bottom bar are the layout's, and draw", function()
|
||||
assert(vim.o.tabline:find("llembas.layout", 1, true) and vim.o.showtabline == 2, vim.o.tabline)
|
||||
assert(vim.o.statusline:find("llembas.layout", 1, true) and vim.o.laststatus == 3, vim.o.statusline)
|
||||
local top = vim.api.nvim_eval_statusline(vim.o.tabline, { use_tabline = true })
|
||||
eq(top.width, vim.o.columns, "the top bar's width")
|
||||
assert(top.str:find("no conversation", 1, true), top.str)
|
||||
local bottom = vim.api.nvim_eval_statusline(vim.o.statusline, {})
|
||||
assert(bottom.str:find(" ask ", 1, true) and bottom.str:find("NOR", 1, true), bottom.str)
|
||||
end)
|
||||
check("the IDE's own statusline is ready to stand in for the bottom bar", function()
|
||||
local s = vim.api.nvim_eval_statusline(require("llembas_ide.bars").active(), {})
|
||||
assert(#s.str > 0)
|
||||
end)
|
||||
|
||||
-- Treesitter.
|
||||
check("a Lua buffer is highlighted by Treesitter", function()
|
||||
vim.cmd("enew")
|
||||
vim.api.nvim_buf_set_lines(0, 0, -1, false, { "local x = 1", "return x" })
|
||||
vim.bo.filetype = "lua"
|
||||
assert(vim.treesitter.highlighter.active[vim.api.nvim_get_current_buf()], "no highlighter")
|
||||
vim.cmd("bwipeout!")
|
||||
end)
|
||||
if compiled then
|
||||
local ft_of = { bash = "sh", tsx = "typescriptreact", vimdoc = "help", markdown_inline = false }
|
||||
for _, p in ipairs(lock(repo .. "/ide/parsers.lock")) do
|
||||
local lang = p[1]
|
||||
check("grammar " .. lang .. " loads and its queries fit it", function()
|
||||
local ok, added = pcall(vim.treesitter.language.add, lang)
|
||||
assert(ok and added ~= false, "the grammar does not load: " .. tostring(added))
|
||||
for _, q in ipairs({ "highlights", "injections" }) do
|
||||
local good, err = pcall(vim.treesitter.query.get, lang, q)
|
||||
assert(good, q .. ": " .. tostring(err))
|
||||
end
|
||||
local file = vim.api.nvim_get_runtime_file("parser/" .. lang .. ".so", false)[1]
|
||||
assert(file and file:find("llembas%-parsers"), "not the compiled one: " .. tostring(file))
|
||||
local ft = ft_of[lang] == nil and lang or ft_of[lang]
|
||||
if ft then
|
||||
vim.cmd("enew")
|
||||
vim.bo.filetype = ft
|
||||
assert(vim.treesitter.highlighter.active[vim.api.nvim_get_current_buf()], "no highlighter for filetype " .. ft)
|
||||
vim.cmd("bwipeout!")
|
||||
end
|
||||
end)
|
||||
end
|
||||
check("a Python buffer parses and draws with the compiled grammar", function()
|
||||
vim.cmd("enew")
|
||||
vim.api.nvim_buf_set_lines(0, 0, -1, false, { "def f(a):", " return 'x' + str(a) # note" })
|
||||
vim.bo.filetype = "python"
|
||||
local parser = vim.treesitter.get_parser(0, "python")
|
||||
parser:parse(true)
|
||||
eq(parser:trees()[1]:root():type(), "module")
|
||||
local caps = vim.treesitter.get_captures_at_pos(0, 0, 0)
|
||||
assert(#caps > 0 and caps[1].capture:find("keyword"), vim.inspect(caps))
|
||||
vim.cmd("bwipeout!")
|
||||
end)
|
||||
end
|
||||
|
||||
-- Completion, LSP, formatting: set up, and quiet when nothing is installed for them.
|
||||
check("the completion menu is set up with the Lua matcher and never downloads", function()
|
||||
local c = require("blink.cmp.config")
|
||||
local function value(v) if type(v) == "function" then return v() end return v end
|
||||
eq(c.fuzzy.implementation, "lua")
|
||||
eq(value(c.fuzzy.prebuilt_binaries.download), false)
|
||||
eq(value(c.sources.default), { "lsp", "path", "buffer" })
|
||||
eq(value(c.completion.ghost_text.enabled), false)
|
||||
eq(value(c.cmdline.enabled), false)
|
||||
end)
|
||||
check("language servers: only those found on PATH are enabled", function()
|
||||
local lsp = require("llembas_ide.lsp")
|
||||
for _, name in ipairs(lsp.enabled) do
|
||||
local found = false
|
||||
for _, s in ipairs(lsp.servers) do
|
||||
if s[1] == name then found = vim.fn.executable(s[2]) == 1 end
|
||||
end
|
||||
assert(found, name .. " is enabled without its program")
|
||||
end
|
||||
end)
|
||||
check("format on demand does not fail without a formatter", function()
|
||||
vim.cmd("enew")
|
||||
vim.bo.filetype = "text"
|
||||
vim.cmd("silent LLeMbasIdeFormat")
|
||||
vim.cmd("bwipeout!")
|
||||
end)
|
||||
|
||||
-- Sessions.
|
||||
check("a session is per directory and round-trips", function()
|
||||
local sessions = require("llembas_ide.sessions")
|
||||
local dir = vim.fn.tempname()
|
||||
vim.fn.mkdir(dir, "p")
|
||||
vim.fn.writefile({ "one" }, dir .. "/a.txt")
|
||||
vim.cmd("cd " .. vim.fn.fnameescape(dir))
|
||||
assert(sessions.name(dir) ~= sessions.name(dir .. "x"))
|
||||
eq(sessions.exists(), false)
|
||||
vim.cmd("edit a.txt")
|
||||
assert(sessions.save(true), "not saved")
|
||||
eq(sessions.exists(), true)
|
||||
assert(vim.startswith(vim.fn.stdpath("state"), vim.env.XDG_STATE_HOME or "\0") or true)
|
||||
vim.cmd("bwipeout!")
|
||||
sessions.restore()
|
||||
eq(vim.fn.fnamemodify(vim.api.nvim_buf_get_name(0), ":t"), "a.txt")
|
||||
sessions.delete()
|
||||
eq(sessions.exists(), false)
|
||||
vim.cmd("bwipeout!")
|
||||
vim.fn.delete(dir, "rf")
|
||||
end)
|
||||
check("a Session.vim in the working directory is not read", function()
|
||||
eq(require("mini.sessions").config.file, "")
|
||||
eq(require("mini.sessions").config.autoread, false)
|
||||
end)
|
||||
|
||||
-- The terminal and the diff.
|
||||
check("the terminal opens and closes", function()
|
||||
local n = #vim.api.nvim_list_wins()
|
||||
vim.cmd("LLeMbasIdeTerminal")
|
||||
eq(#vim.api.nvim_list_wins(), n + 1)
|
||||
eq(vim.bo.buftype, "terminal")
|
||||
vim.cmd("stopinsert")
|
||||
require("llembas_ide.terminal").toggle()
|
||||
eq(#vim.api.nvim_list_wins(), n)
|
||||
end)
|
||||
|
||||
-- The person's own file.
|
||||
check("lua/user/init.lua exists, and is loaded last when it says something", function()
|
||||
eq(vim.fn.filereadable(vim.fn.stdpath("config") .. "/lua/user/init.lua"), 1)
|
||||
if vim.env.IDE_TEST_USER == "1" then
|
||||
eq(vim.g.llembas_ide_test_user, 42)
|
||||
eq(vim.g.llembas_ide_test_plugin, "loaded", "the person's own plugin in pack/user/start")
|
||||
end
|
||||
end)
|
||||
|
||||
vim.g.llembas_ide_no_session = true
|
||||
io.stdout:write("\n")
|
||||
for _, f in ipairs(failed) do io.stdout:write("FAIL " .. f .. "\n") end
|
||||
io.stdout:write(("ide-headless: %d passed, %d failed (Neovim %s, %s)\n"):format(passed, #failed, tostring(vim.version()),
|
||||
compiled and "compiled grammars" or "bundled grammars"))
|
||||
if #failed > 0 then vim.cmd("cquit 1") else vim.cmd("qa!") end
|
||||
end
|
||||
|
||||
vim.schedule(function()
|
||||
local ok, err = xpcall(run, debug.traceback)
|
||||
if not ok then
|
||||
io.stdout:write("ide-headless: the checks themselves failed: " .. tostring(err) .. "\n")
|
||||
vim.cmd("cquit 2")
|
||||
end
|
||||
end)
|
||||
@@ -0,0 +1,516 @@
|
||||
-- The installed IDE's four bars, checked on its own screen at three sizes, through its launcher:
|
||||
-- llembas-ide --headless -c "luafile ide/tests/layout.lua"
|
||||
-- Environment: IDE_TEST_REPO (the repository). The stand-in agent is nvim/tests/agent_levels.py.
|
||||
-- With IDE_LAYOUT_STEP set this is one start of the IDE for the checks that need a new process
|
||||
-- (what is remembered, what is written to the terminal); the answer is one line, RESULT {json}.
|
||||
local repo = assert(vim.env.IDE_TEST_REPO, "IDE_TEST_REPO")
|
||||
local agent = repo .. "/nvim/tests/agent_levels.py"
|
||||
local step = vim.env.IDE_LAYOUT_STEP
|
||||
local passed, failed = 0, {}
|
||||
|
||||
local function check(name, cond, extra)
|
||||
if cond then passed = passed + 1 else
|
||||
table.insert(failed, name .. (extra ~= nil and (": " .. (type(extra) == "string" and extra or vim.inspect(extra))) or ""))
|
||||
end
|
||||
end
|
||||
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
|
||||
local function t(keys) return vim.api.nvim_replace_termcodes(keys, true, false, true) end
|
||||
local function feed(keys) vim.api.nvim_feedkeys(t(keys), "mx", false) end
|
||||
local function row(r)
|
||||
vim.cmd("redraw")
|
||||
local out = {}
|
||||
for c = 1, vim.o.columns do out[#out + 1] = vim.fn.screenstring(r, c) end
|
||||
return table.concat(out)
|
||||
end
|
||||
local function top() return row(1) end
|
||||
local function bottom() return row(vim.o.lines - vim.o.cmdheight) end
|
||||
local function rtrim(s) return (s:gsub("%s+$", "")) end
|
||||
local function cell(text, w) return text .. (" "):rep(w - vim.fn.strdisplaywidth(text)) end
|
||||
local function width(s) return vim.fn.strdisplaywidth(s) end
|
||||
local function seg() return vim.o.columns < 60 and 15 or vim.o.columns < 120 and 20 or 35 end
|
||||
local function keys_part() return rtrim(vim.fn.strcharpart(bottom(), 0, vim.o.columns - seg())) end
|
||||
-- (At full width the segment's last six cells are the pending operator's, Neovim's own: not compared.)
|
||||
local function vim_part() return vim.fn.strcharpart(bottom(), vim.o.columns - seg(), seg() == 35 and 29 or seg()) end
|
||||
local function wins()
|
||||
local out = {}
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.api.nvim_win_get_config(w).relative == "" then
|
||||
local b = vim.api.nvim_win_get_buf(w)
|
||||
local ft, name = vim.bo[b].filetype, vim.api.nvim_buf_get_name(b)
|
||||
local kind = ft == "llembas-tree" and "tree" or ft == "llembas-settings" and "settings"
|
||||
or name:match("llembas://chat$") and "chat" or name:match("llembas://prompt$") and "prompt" or "code"
|
||||
out[kind] = { win = w, width = vim.api.nvim_win_get_width(w), height = vim.api.nvim_win_get_height(w) }
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
local function kinds(w)
|
||||
local names = vim.tbl_keys(w)
|
||||
table.sort(names)
|
||||
return table.concat(names, " ")
|
||||
end
|
||||
local function resize(cols, rows)
|
||||
vim.o.columns, vim.o.lines = cols, rows
|
||||
vim.api.nvim_exec_autocmds("VimResized", {})
|
||||
vim.wait(80)
|
||||
vim.cmd("redraw")
|
||||
end
|
||||
local function calls(method)
|
||||
local out = {}
|
||||
for _, line in ipairs(vim.fn.filereadable(vim.env.FAKE_AGENT_LOG) == 1 and vim.fn.readfile(vim.env.FAKE_AGENT_LOG) or {}) do
|
||||
local m = vim.json.decode(line)
|
||||
if m.method == method then out[#out + 1] = m.params end
|
||||
end
|
||||
return out
|
||||
end
|
||||
local function last_call(method) local c = calls(method); return c[#c] end
|
||||
|
||||
local function finish()
|
||||
vim.g.llembas_ide_no_session = true
|
||||
pcall(function() require("llembas").restart(true) end)
|
||||
io.stdout:write("\n")
|
||||
for _, f in ipairs(failed) do io.stdout:write("FAIL " .. f .. "\n") end
|
||||
io.stdout:write(("ide-layout: %d passed, %d failed (Neovim %s)\n"):format(passed, #failed, tostring(vim.version())))
|
||||
vim.cmd(#failed > 0 and "cquit 1" or "qa!")
|
||||
end
|
||||
|
||||
-- ── One start, for the parent's questions. ──────────────────────────────────────────────────────
|
||||
local function one_start()
|
||||
vim.g.llembas_ide_no_session = true
|
||||
vim.notify = function() end
|
||||
local L = require("llembas")
|
||||
local out = {}
|
||||
if step == "dir" then
|
||||
-- Started with a directory (`llembas-ide sub`): the tree is the only explorer on the screen.
|
||||
local tree = require("llembas.tree")
|
||||
vim.o.columns, vim.o.lines = 160, 45 -- headless starts at 80 columns, where the tree folds away
|
||||
vim.api.nvim_exec_autocmds("VimResized", {})
|
||||
wait(function() return tree.is_open() and table.concat(tree.lines(), "|"):find("inner.txt", 1, true) ~= nil end)
|
||||
local function floats()
|
||||
local n = 0
|
||||
for _, w in ipairs(vim.api.nvim_list_wins()) do
|
||||
if vim.api.nvim_win_get_config(w).relative ~= "" then n = n + 1 end
|
||||
end
|
||||
return n
|
||||
end
|
||||
local function dir_bufs()
|
||||
local n = 0
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
local name = vim.api.nvim_buf_get_name(b)
|
||||
if name ~= "" and vim.fn.isdirectory(name) == 1 then n = n + 1 end
|
||||
end
|
||||
return n
|
||||
end
|
||||
out.cwd = vim.fn.getcwd()
|
||||
out.floats, out.dir_bufs = floats(), dir_bufs()
|
||||
out.dashboard = vim.bo.filetype == "llembas-ide-dashboard"
|
||||
out.tree_lines = tree.lines()
|
||||
out.netrw = vim.fn.exists(":Explore") == 2
|
||||
-- Later: a directory opened like a file goes to the tree, and the window keeps its file.
|
||||
vim.cmd("edit inner.txt")
|
||||
vim.cmd("edit deeper")
|
||||
vim.wait(200)
|
||||
out.later_floats, out.later_dir_bufs = floats(), dir_bufs()
|
||||
out.later_where = require("llembas.layout").where()
|
||||
out.later_code = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(vim.api.nvim_win_get_buf(require("llembas.layout").code_win())), ":t")
|
||||
out.later_tree_row = vim.api.nvim_get_current_line()
|
||||
io.stdout:write("RESULT " .. vim.json.encode(out) .. "\n")
|
||||
vim.cmd("qa!")
|
||||
return
|
||||
end
|
||||
if step ~= "start" then
|
||||
L.setup({ cmd = { "python3", agent }, complete = { auto = true } })
|
||||
vim.o.columns, vim.o.lines = 160, 45
|
||||
vim.api.nvim_exec_autocmds("VimResized", {})
|
||||
vim.wait(80)
|
||||
end
|
||||
local layout, store = require("llembas.layout"), require("llembas.store")
|
||||
if step == "change" then
|
||||
L.mode("edit")
|
||||
wait(function() return store.get().mode == "edit" end)
|
||||
L.effort("high")
|
||||
L.autocomplete(false)
|
||||
layout.toggle("tree", false)
|
||||
vim.api.nvim_win_set_width(vim.fn.bufwinid(require("llembas.chat").tbuf), 46)
|
||||
elseif step == "change_b" then
|
||||
L.mode("plan")
|
||||
wait(function() return store.get().mode == "plan" end)
|
||||
elseif step == "session" then
|
||||
local done = false
|
||||
L.choices("mode", function() done = true end)
|
||||
wait(function() return done end)
|
||||
local p = last_call("session/new")
|
||||
out.new_mode, out.new_effort = p and (p._meta or {}).mode, p and (p._meta or {}).effort
|
||||
end
|
||||
layout.remember_widths()
|
||||
local s, o = L.settings(), layout.options()
|
||||
out.mode, out.effort, out.autocomplete = s.mode, s.effort, s.autocomplete
|
||||
out.tree, out.chat_width, out.top, out.bottom = o.tree, o.chat_width, o.top, o.bottom
|
||||
out.tree_open = require("llembas.tree").is_open()
|
||||
out.kinds = kinds(wins())
|
||||
out.state_file = store.path()
|
||||
out.tabline, out.statusline = vim.o.tabline, vim.o.statusline
|
||||
out.ask_chord = require("llembas.keys").by_id.ask.chord
|
||||
out.f2 = vim.fn.maparg("<F2>", "n") ~= "" or vim.fn.maparg("<F2>", "n", false, true).callback ~= nil
|
||||
io.stdout:write("RESULT " .. vim.json.encode(out) .. "\n")
|
||||
pcall(function() L.restart(true) end)
|
||||
vim.cmd("qa!")
|
||||
end
|
||||
|
||||
--- Start the IDE again through its launcher in `dir`; returns the decoded RESULT and what it wrote on stderr.
|
||||
local function start(dir, name, env, args)
|
||||
local e = vim.tbl_extend("force", { IDE_LAYOUT_STEP = name, PYTHONDONTWRITEBYTECODE = "1" }, env or {})
|
||||
local argv = { vim.env.LLEMBAS_IDE_LAUNCHER, "--headless" }
|
||||
vim.list_extend(argv, args or {})
|
||||
vim.list_extend(argv, { "-c", "luafile " .. repo .. "/ide/tests/layout.lua" })
|
||||
local done = vim.system(argv,
|
||||
{ cwd = dir, env = e, text = false }):wait(60000)
|
||||
local ok, data = pcall(vim.json.decode, (done.stdout or ""):match("RESULT (%b{})") or "", { luanil = { object = true, array = true } })
|
||||
return ok and data or { failed = true, out = done.stdout, code = done.code }, done.stderr or ""
|
||||
end
|
||||
|
||||
local function run()
|
||||
local ide = require("llembas_ide")
|
||||
local L = require("llembas")
|
||||
local layout = require("llembas.layout")
|
||||
local keys = require("llembas.keys")
|
||||
local tree = require("llembas.tree")
|
||||
local lines = require("llembas.lines")
|
||||
local chat = require("llembas.chat")
|
||||
local said = {}
|
||||
vim.notify = function(m) said[#said + 1] = tostring(m) end
|
||||
|
||||
local work = vim.fn.tempname()
|
||||
local project = work .. "/project"
|
||||
vim.fn.mkdir(project .. "/src", "p")
|
||||
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, project .. "/sample.py")
|
||||
vim.fn.writefile({ "x = 1" }, project .. "/src/util.py")
|
||||
work = vim.uv.fs_realpath(work)
|
||||
project = work .. "/project"
|
||||
vim.env.FAKE_AGENT_LOG = work .. "/agent.log"
|
||||
vim.env.PYTHONDONTWRITEBYTECODE = "1"
|
||||
|
||||
check("every part of the IDE started", #ide.problems == 0, ide.problems)
|
||||
|
||||
-- ── As installed, with no CLI: the bars are there, and the keys say what is missing. ─────────────
|
||||
vim.o.columns, vim.o.lines = 160, 45
|
||||
vim.api.nvim_exec_autocmds("VimResized", {})
|
||||
vim.wait(80)
|
||||
check("the layout is on by default, all four bars", layout.options().on and layout.options().top and layout.options().bottom
|
||||
and layout.options().tree and layout.options().chat, layout.options())
|
||||
check("the start screen stands between the tree and the right bar", vim.bo.filetype == "llembas-ide-dashboard"
|
||||
and kinds(wins()) == "chat code prompt settings tree", { vim.bo.filetype, kinds(wins()) })
|
||||
if not require("llembas_ide.llembas").has_cli() then
|
||||
check("without the CLI the top bar says so, and nothing is asked of anybody",
|
||||
vim.startswith(top(), " ● no CLI │ ") and top():find("│ AC off ", 1, true) ~= nil and L._state.conn == nil, top())
|
||||
local ide_llembas = require("llembas_ide.llembas")
|
||||
local sign_in, asked_to = ide_llembas.sign_in, 0
|
||||
ide_llembas.sign_in = function() asked_to = asked_to + 1 end
|
||||
feed(" la")
|
||||
check("without the CLI <Space>la leads to signing in instead of failing, and opens nothing",
|
||||
asked_to == 1 and vim.bo.filetype == "llembas-ide-dashboard" and L._state.conn == nil, { asked_to, vim.bo.filetype })
|
||||
ide_llembas.sign_in = sign_in
|
||||
feed(" e")
|
||||
check("<Space>e hides the tree without the CLI as with it", not tree.is_open())
|
||||
feed(" e")
|
||||
check("…and shows it again", tree.is_open())
|
||||
end
|
||||
|
||||
-- ── With an agent (the stand-in). 160×45. ───────────────────────────────────────────────────────
|
||||
L.setup({ cmd = { "python3", agent }, complete = { auto = true } })
|
||||
vim.cmd("cd " .. vim.fn.fnameescape(project))
|
||||
vim.cmd("edit " .. vim.fn.fnameescape(project .. "/sample.py"))
|
||||
local fbuf = vim.api.nvim_get_current_buf()
|
||||
vim.wait(100)
|
||||
local w = wins()
|
||||
check("160×45: tree, code, settings lines, chat and prompt", kinds(w) == "chat code prompt settings tree", kinds(w))
|
||||
check("160×45: the tree is 26 columns, the right bar 42, the code the rest",
|
||||
w.tree.width == 26 and w.chat.width == 42 and w.settings.width == 42 and w.prompt.width == 42 and w.code.width == 160 - 26 - 42 - 2, w)
|
||||
check("160×45: the top bar, cell for cell",
|
||||
top() == " ● idle │ " .. cell("no conversation yet", 160 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6)
|
||||
.. " │ " .. cell("— · — · —", 32) .. " │ ctx — │ AC on ", top())
|
||||
check("160×45: both bars are exactly as wide as the screen", width(top()) == 160 and width(bottom()) == 160)
|
||||
check("160×45, in the code: the keys that always arrive (no chord was seen in this terminal)",
|
||||
keys_part() == " Spc la ask · Tab accept suggestion · Alt+→ one word · Spc lp menu · Alt+←→ bars · Spc lb tree · Spc ll chat", keys_part())
|
||||
check("160×45: Neovim's own state in its cells", vim_part() == " NOR" .. (" "):rep(19) .. "1:1 ", "[" .. vim_part() .. "]")
|
||||
check("the tree shows the directory and marks the file you are in", vim.deep_equal(tree.lines(), { " ▸ src/", " sample.py" }), tree.lines())
|
||||
|
||||
-- The keys: the plugin's one table, mapped here in both forms, and nothing beside it.
|
||||
local missing = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
if not k.virtual and k.run then
|
||||
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do
|
||||
for _, mode in ipairs({ "n", "x", "i" }) do
|
||||
if next(vim.fn.maparg(lhs, mode, false, true)) == nil then missing[#missing + 1] = mode .. " " .. lhs end
|
||||
end
|
||||
end
|
||||
if not k.scope then
|
||||
for _, lhs in ipairs(keys.alts(k)) do
|
||||
for _, mode in ipairs(k.modes or { "n" }) do
|
||||
if next(vim.fn.maparg(keys.lhs(lhs), mode, false, true)) == nil then missing[#missing + 1] = mode .. " " .. keys.lhs(lhs) end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: every key of the table is mapped", #missing == 0, missing)
|
||||
local in_table = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do in_table[t(lhs)] = true end
|
||||
for _, lhs in ipairs(keys.alts(k)) do in_table[t(keys.lhs(lhs))] = true end
|
||||
end
|
||||
local strays = {}
|
||||
for _, mode in ipairs({ "n", "x", "i" }) do
|
||||
for _, m in ipairs(vim.api.nvim_get_keymap(mode)) do
|
||||
local lhs = t(m.lhs)
|
||||
local ours = (m.desc or ""):match("^LLeMbas: ") or (vim.startswith(lhs, " l") and #lhs > 2)
|
||||
if ours and not in_table[lhs] and lhs ~= t(L.config.complete.trigger) then strays[#strays + 1] = mode .. " " .. m.lhs end
|
||||
end
|
||||
end
|
||||
check("keys: every mapping of the LLeMbas group (<Space>l…, and LLeMbas's own) is in the table", #strays == 0, strays)
|
||||
local shown = {}
|
||||
for _, where in ipairs({ "code", "tree", "prompt", "settings", "chat", "change" }) do
|
||||
for _, form in ipairs({ true, false }) do
|
||||
for _, k in ipairs(keys.for_bar(where, form)) do
|
||||
local e = keys.by_id[k.id]
|
||||
local lhs = (form and e.chord) or keys.alts(e)[1] or e.chord
|
||||
if type(lhs) == "table" then lhs = lhs[1] end
|
||||
local buf = ({ tree = tree.buf(), settings = lines.buf(), prompt = chat.ibuf, chat = chat.tbuf })[e.scope or ""]
|
||||
local bound
|
||||
if e.virtual or e.scope == "change" or e.scope == "suggestion" then
|
||||
-- Neovim's own arrows, or mapped only while a change or a suggestion is shown (checked
|
||||
-- below and in the plugin's own suite).
|
||||
bound = true
|
||||
elseif buf and not (form and e.chord) then
|
||||
bound = vim.api.nvim_buf_call(buf, function()
|
||||
return vim.fn.maparg(lhs, "n", false, true).buffer == 1 or vim.fn.maparg(lhs, "i", false, true).buffer == 1
|
||||
end)
|
||||
else
|
||||
bound = next(vim.fn.maparg(keys.lhs(lhs), "n", false, true)) ~= nil
|
||||
end
|
||||
if not bound then shown[#shown + 1] = where .. " " .. k.id .. " " .. tostring(lhs) end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: every key the bottom bar can show is bound where it shows it", #shown == 0, shown)
|
||||
check("keys: the IDE's own map takes none of LLeMbas's keys", #require("llembas_ide.keys").duplicates() == 0, require("llembas_ide.keys").duplicates())
|
||||
|
||||
-- The bottom bar for each bar that has the focus.
|
||||
layout.focus("tree")
|
||||
check("focus tree", keys_part() == " Enter open · a new · r rename · d delete · / filter · Alt+→ code · . hidden files · Spc la ask · Spc lp menu · Spc lb tree", keys_part())
|
||||
layout.focus("chat")
|
||||
check("focus prompt", keys_part() == " Enter send · Tab ask/rewrite/add · Spc lm mode · Spc lM model · Esc back to code · Spc l. stop", keys_part())
|
||||
vim.cmd("stopinsert")
|
||||
vim.api.nvim_set_current_win(wins().settings.win)
|
||||
check("focus settings lines", keys_part() == " Enter change · ↑↓ move · Esc back · Alt+← code", keys_part())
|
||||
vim.api.nvim_set_current_win(wins().chat.win)
|
||||
check("focus transcript", keys_part() == " Enter open file · K tool output · i prompt · Alt+← code · Spc l. stop · Spc la ask · Spc lp menu · Spc ll chat", keys_part())
|
||||
layout.focus("code")
|
||||
|
||||
-- A chord that arrives: the bar shows the chords from then on.
|
||||
feed("<C-S-E>")
|
||||
check("Ctrl+Shift+E hides the tree", wait(function() return not tree.is_open() end))
|
||||
feed("<C-S-E>")
|
||||
wait(function() return tree.is_open() end)
|
||||
check("code, chords", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars · ^⇧E tree · ^⇧D chat", keys_part())
|
||||
layout.focus("tree")
|
||||
check("tree, chords", vim.startswith(keys_part(), " Enter open · a new · r rename · d delete · / filter · Alt+→ code"), keys_part())
|
||||
layout.focus("chat")
|
||||
check("prompt, chords", vim.startswith(keys_part(), " Enter send · Tab ask/rewrite/add · ^Tab mode · ^⇧M model · Esc back to code"), keys_part())
|
||||
|
||||
-- Tab in the prompt.
|
||||
local function prompt_rows()
|
||||
local pw = wins().prompt.win
|
||||
local pos = vim.fn.win_screenpos(pw)
|
||||
local out = {}
|
||||
for r = pos[1], pos[1] + vim.api.nvim_win_get_height(pw) - 1 do
|
||||
out[#out + 1] = vim.fn.strcharpart(row(r), pos[2] - 1, vim.api.nvim_win_get_width(pw))
|
||||
end
|
||||
return out
|
||||
end
|
||||
check("the prompt begins with what Enter does", prompt_rows()[2] == cell("ask ›", 42), prompt_rows())
|
||||
feed("<Tab>")
|
||||
check("Tab in an empty prompt: rewrite", L.intent() == "rewrite" and vim.startswith(prompt_rows()[2], "rewrite › "), prompt_rows())
|
||||
feed("<Tab>")
|
||||
check("Tab: add", L.intent() == "add" and vim.startswith(prompt_rows()[2], "add › "), prompt_rows())
|
||||
feed("<Tab>")
|
||||
check("Tab: ask again", L.intent() == "ask" and vim.startswith(prompt_rows()[2], "ask › "), prompt_rows())
|
||||
local menu = require("blink.cmp.config").keymap
|
||||
check("the completion menu has no <Tab>, and is not offered over the prompt", menu["<Tab>"] == nil and vim.b[chat.ibuf].completion == false)
|
||||
feed("<Esc>")
|
||||
check("Esc is back in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
|
||||
-- What comes along.
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("Vj<C-S-A>")
|
||||
check("Ctrl+Shift+A with a selection: the chip names the lines", vim.api.nvim_get_current_buf() == chat.ibuf and rtrim(prompt_rows()[1]) == " sample.py:1-2", prompt_rows())
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "what is this?" })
|
||||
feed("<CR>")
|
||||
check("Enter sends the question with the selection", wait(function() return last_call("session/prompt") ~= nil end) and wait(function() return not L._state.busy end)
|
||||
and ((((last_call("session/prompt") or {})._meta or {}).lembas or {}).editor or {}).selection ~= nil, last_call("session/prompt"))
|
||||
check("the top bar and the settings lines follow the session",
|
||||
wait(function() return L.settings().context == 4 end)
|
||||
and top():find("│ " .. cell("model-a · manual · default", 32) .. " │ ctx 4% │ AC on ", 1, true) ~= nil
|
||||
and vim.deep_equal(lines.lines(), { "model model-a", "mode manual", "effort default", "autocomplete on" }), { top(), lines.lines() })
|
||||
layout.focus("code")
|
||||
vim.api.nvim_win_set_cursor(0, { 4, 0 })
|
||||
feed(" la")
|
||||
check("<Space>la without a selection: the cursor's line, as a point", rtrim(prompt_rows()[1]) == " sample.py:4", prompt_rows())
|
||||
feed("<Esc>")
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("Vj le")
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "REPLACE def a():\\n return 100" })
|
||||
feed("<CR>")
|
||||
check("rewrite: shown in the file as a change; the bar shows the change's keys",
|
||||
wait(function() return require("llembas.diff").pending(fbuf) == 1 end) and vim.api.nvim_get_current_buf() == fbuf
|
||||
and wait(function() return keys_part() == " ^⇧Y accept · ^⇧J reject · ]h next · Alt+^⇧Y accept all · [h previous · ^⇧P menu" end), keys_part())
|
||||
feed("<C-S-Y>")
|
||||
check("Ctrl+Shift+Y accepts it", vim.api.nvim_buf_get_lines(fbuf, 1, 2, false)[1] == " return 100")
|
||||
vim.cmd("silent write")
|
||||
|
||||
-- The settings lines, through the agent.
|
||||
vim.api.nvim_set_current_win(wins().settings.win)
|
||||
vim.api.nvim_win_set_cursor(0, { 2, 0 })
|
||||
feed("<CR>")
|
||||
check("Enter on mode opens its choices in the bar", wait(function() return #lines.lines() == 8 end) and lines.lines()[3] == " ● manual" and wins().settings.height == 8, lines.lines())
|
||||
feed("j<CR>")
|
||||
check("a choice is set through the agent and shown", wait(function() return (last_call("session/set_mode") or {}).modeId == "edit" end)
|
||||
and wait(function() return lines.lines()[2] == "mode edit" and #lines.lines() == 4 end) and top():find("model-a · edit · default", 1, true) ~= nil, { lines.lines(), top() })
|
||||
L.set("effort", "high")
|
||||
check("the effort too", wait(function() return (last_call("_lembas/configure") or {}).effort == "high" end)
|
||||
and wait(function() return lines.lines()[3] == "effort high" end), lines.lines())
|
||||
feed("<Esc>")
|
||||
local asked
|
||||
local select = vim.ui.select
|
||||
vim.ui.select = function(items, opts) asked = { items = items, opts = opts } end
|
||||
feed("<C-S-P>")
|
||||
local menu_text = {}
|
||||
for _, i in ipairs(asked and asked.items or {}) do menu_text[#menu_text + 1] = asked.opts.format_item(i) end
|
||||
menu_text = table.concat(menu_text, "\n")
|
||||
check("Ctrl+Shift+P: the menu has the effort and the bars", menu_text:find("Effort: high", 1, true) and menu_text:find("Tree: shown", 1, true)
|
||||
and menu_text:find("Top bar: shown", 1, true), menu_text)
|
||||
vim.ui.select = select
|
||||
|
||||
-- ── 100×30 and 80×24. ───────────────────────────────────────────────────────────────────────────
|
||||
vim.api.nvim_set_current_win(wins().code.win)
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
resize(100, 30)
|
||||
w = wins()
|
||||
check("100×30: the chat folds away, the tree stays", kinds(w) == "code tree" and w.tree.width == 26 and w.code.width == 73, w)
|
||||
check("100×30: the top bar",
|
||||
top() == " ● idle │ " .. cell("conversation", 100 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-a · edit · high", 32) .. " │ ctx 4% │ AC on ", top())
|
||||
check("100×30: the bottom bar", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars"
|
||||
and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ", { keys_part(), "[" .. vim_part() .. "]" })
|
||||
check("100×30: both rows are 100 wide", width(top()) == 100 and width(bottom()) == 100)
|
||||
layout.focus("tree")
|
||||
check("100×30, in the tree", keys_part() == " Enter open · a new · r rename · d delete · / filter · Alt+→ code", keys_part())
|
||||
layout.focus("code")
|
||||
resize(80, 24)
|
||||
w = wins()
|
||||
check("80×24: the code alone, all 80 columns", kinds(w) == "code" and w.code.width == 80, w)
|
||||
check("80×24: the top bar",
|
||||
top() == " ● idle │ " .. cell("conversation", 80 - 2 - 9 - 3 - 3 - 26 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-a · edit · high", 26) .. " │ ctx 4% │ AC on ", top())
|
||||
check("80×24: the bottom bar", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu"
|
||||
and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ", { keys_part(), "[" .. vim_part() .. "]" })
|
||||
check("80×24: both rows are 80 wide", width(top()) == 80 and width(bottom()) == 80)
|
||||
feed("<M-Right>")
|
||||
check("80×24: Alt+→ still reaches the chat", chat.is_open() and vim.api.nvim_get_current_buf() == chat.ibuf)
|
||||
check("80×24, in the prompt", keys_part() == " Enter send · Tab ask/rewrite/add · ^Tab mode · ^⇧M model", keys_part())
|
||||
feed("<Esc>")
|
||||
resize(160, 45)
|
||||
check("160×45 again: everything is back", kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
|
||||
|
||||
-- ── A bar switched off: the IDE's stand-ins. ────────────────────────────────────────────────────
|
||||
layout.toggle("top", false)
|
||||
check("the top bar off: the line of open buffers stands in", vim.o.tabline:find("MiniTabline", 1, true) ~= nil and vim.o.showtabline == 2, vim.o.tabline)
|
||||
layout.toggle("bottom", false)
|
||||
check("the bottom bar off: the IDE's statusline stands in",
|
||||
#vim.api.nvim_eval_statusline(require("mini.statusline").active(), {}).str > 0 and not vim.o.statusline:find("llembas.layout", 1, true), vim.o.statusline)
|
||||
layout.toggle("top", true)
|
||||
layout.toggle("bottom", true)
|
||||
check("…and on again", vim.startswith(top(), " ● idle") and vim.startswith(keys_part(), " ^⇧A ask"), { top(), keys_part() })
|
||||
|
||||
-- ── A session holds the code's windows, not the bars. ───────────────────────────────────────────
|
||||
local sessions = require("llembas_ide.sessions")
|
||||
check("a session is saved with the bars put away, and they are back after", sessions.save(true) and kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
|
||||
local session_text = table.concat(vim.fn.readfile(vim.fn.stdpath("state") .. "/sessions/" .. sessions.name()), "\n")
|
||||
check("the session file names no bar", not session_text:find("llembas://", 1, true), session_text:match("[^\n]*llembas://[^\n]*"))
|
||||
sessions.restore()
|
||||
vim.wait(200)
|
||||
check("restored: the file, with the bars around it", kinds(wins()) == "chat code prompt settings tree"
|
||||
and vim.fn.fnamemodify(vim.api.nvim_buf_get_name(vim.api.nvim_win_get_buf(wins().code.win)), ":t") == "sample.py", kinds(wins()))
|
||||
sessions.delete()
|
||||
pcall(function() L.restart(true) end)
|
||||
|
||||
-- ── Remembered across restarts, per directory; and a person's own file. ─────────────────────────
|
||||
local dir_a, dir_b = work .. "/dir-a", work .. "/dir-b"
|
||||
vim.fn.mkdir(dir_a, "p")
|
||||
vim.fn.mkdir(dir_b, "p")
|
||||
local env = { FAKE_AGENT_LOG = work .. "/remember.log" }
|
||||
local r = start(dir_a, "change", env)
|
||||
check("remember: changed in one directory", r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false and r.chat_width == 46, r)
|
||||
check("remember: kept in the IDE's own state directory", type(r.state_file) == "string"
|
||||
and r.state_file:find("/llembas%-ide/llembas/settings%.json$") ~= nil and vim.fn.filereadable(r.state_file) == 1, r.state_file)
|
||||
r = start(dir_b, "look", env)
|
||||
check("remember: another directory starts as the IDE does", r.mode == nil and r.effort == nil and r.autocomplete == true and r.tree == true
|
||||
and r.chat_width == 42 and r.kinds == "chat code prompt settings tree", r)
|
||||
r = start(dir_b, "change_b", env)
|
||||
r = start(dir_a, "look", env)
|
||||
check("remember: the first directory, started again", r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false
|
||||
and r.tree_open == false and r.chat_width == 46 and r.kinds == "chat code prompt settings", r)
|
||||
r = start(dir_a, "session", env)
|
||||
check("remember: a session there starts on that mode and effort", r.new_mode == "edit" and r.new_effort == "high", r)
|
||||
r = start(dir_b, "look", env)
|
||||
check("remember: the second directory has its own", r.mode == "plan" and r.effort == nil and r.tree == true, r)
|
||||
|
||||
local user = vim.fn.stdpath("config") .. "/lua/user/init.lua"
|
||||
local before = vim.fn.readfile(user)
|
||||
vim.fn.writefile(vim.list_extend(vim.list_slice(before), {
|
||||
'require("llembas.keys").by_id.ask.chord = "<F2>"',
|
||||
'require("llembas").setup({ bars = { top = false, chat_width = 48 }, keys = { prefix = "<Leader>l" } })',
|
||||
}), user)
|
||||
r = start(dir_b, "look", env)
|
||||
check("your own file: a bar switched off, a width, a key changed in the table and mapped",
|
||||
r.top == false and r.bottom == true and r.chat_width == 48 and r.tabline:find("MiniTabline", 1, true) ~= nil
|
||||
and r.statusline:find("llembas.layout", 1, true) ~= nil and r.ask_chord == "<F2>" and r.f2 == true, r)
|
||||
vim.fn.writefile(vim.list_extend(vim.list_slice(before), { 'require("llembas").setup({ bars = false })' }), user)
|
||||
r = start(dir_b, "look", env)
|
||||
check("your own file: no bars at all — one window, the IDE's statusline and buffer line",
|
||||
r.kinds == "code" and r.tabline:find("MiniTabline", 1, true) ~= nil and not r.statusline:find("llembas.layout", 1, true), r)
|
||||
vim.fn.writefile(before, user)
|
||||
|
||||
-- ── The terminal. ───────────────────────────────────────────────────────────────────────────────
|
||||
local set, clear = "\27]1337;SetUserVar=llembas_ide=MQ==\7", "\27]1337;SetUserVar=llembas_ide=\7"
|
||||
local _, err = start(dir_b, "start", { LLEMBAS_TERM = "1" })
|
||||
check("user var: in the LLeMbas terminal llembas_ide=1 is set on start and cleared on exit, and nothing else is written", err == set .. clear, vim.inspect(err))
|
||||
_, err = start(dir_b, "start", { LLEMBAS_TTY = "pane-1" })
|
||||
check("user var: $LLEMBAS_TTY counts as well", err == set .. clear, vim.inspect(err))
|
||||
_, err = start(dir_b, "start", {})
|
||||
check("user var: in any other terminal nothing is written", err == "", vim.inspect(err))
|
||||
|
||||
-- ── A directory opened like a file. ────────────────────────────────────────────────────────────
|
||||
local proj = work .. "/withdir"
|
||||
vim.fn.mkdir(proj .. "/sub/deeper", "p")
|
||||
vim.fn.writefile({ "x" }, proj .. "/sub/deeper/leaf.txt")
|
||||
vim.fn.writefile({ "y" }, proj .. "/sub/inner.txt")
|
||||
r = start(proj, "dir", {}, { "sub" })
|
||||
local real_sub = vim.uv.fs_realpath(proj .. "/sub")
|
||||
check("a directory at the start: it is the working directory, the start screen shows, no explorer floats over the bars",
|
||||
r.cwd == real_sub and r.dashboard == true and r.floats == 0 and r.dir_bufs == 0 and r.netrw == false, r)
|
||||
check("a directory at the start: the tree is rooted there",
|
||||
type(r.tree_lines) == "table" and table.concat(r.tree_lines, "|"):find("deeper/", 1, true) ~= nil
|
||||
and table.concat(r.tree_lines, "|"):find("inner.txt", 1, true) ~= nil, r.tree_lines)
|
||||
check("a directory later (:e dir): opened in the tree with the focus there, the file stays, nothing floats",
|
||||
r.later_floats == 0 and r.later_dir_bufs == 0 and r.later_where == "tree" and r.later_code == "inner.txt"
|
||||
and type(r.later_tree_row) == "string" and r.later_tree_row:find("deeper/", 1, true) ~= nil, r)
|
||||
|
||||
vim.cmd("cd /")
|
||||
vim.fn.delete(work, "rf")
|
||||
end
|
||||
|
||||
vim.schedule(function()
|
||||
local ok, err = xpcall(step and one_start or run, debug.traceback)
|
||||
if not ok then table.insert(failed, "the checks themselves stopped: " .. tostring(err)) end
|
||||
if step and ok then return end
|
||||
finish()
|
||||
end)
|
||||
@@ -0,0 +1,39 @@
|
||||
-- Typing in the installed IDE, headless: the completion menu opens from the buffer's words, and
|
||||
-- the keys are the ones the README promises.
|
||||
-- llembas-ide --headless -c "luafile ide/tests/typing.lua"
|
||||
local function finish(problems)
|
||||
vim.g.llembas_ide_no_session = true
|
||||
io.stdout:write("\n")
|
||||
for _, p in ipairs(problems) do io.stdout:write("FAIL " .. p .. "\n") end
|
||||
io.stdout:write(("ide-typing: %s\n"):format(#problems == 0 and "the menu opens, <Tab> is not the menu's" or #problems .. " failed"))
|
||||
vim.cmd(#problems == 0 and "qa!" or "cquit 1")
|
||||
end
|
||||
|
||||
vim.schedule(function()
|
||||
vim.cmd("enew")
|
||||
vim.api.nvim_buf_set_lines(0, 0, -1, false, { "alphabet_soup = 1", "alphabet_city = 2", "" })
|
||||
vim.api.nvim_win_set_cursor(0, { 3, 0 })
|
||||
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("ialph", true, false, true), "tx!", false)
|
||||
end)
|
||||
|
||||
local waited = 0
|
||||
local function look()
|
||||
waited = waited + 200
|
||||
local blink = require("blink.cmp")
|
||||
if not blink.is_visible() and waited < 6000 then return vim.defer_fn(look, 200) end
|
||||
local problems = {}
|
||||
if not blink.is_visible() then table.insert(problems, "the completion menu did not open on typed text") end
|
||||
local items = require("blink.cmp.completion.list").items or {}
|
||||
local labels = {}
|
||||
for _, item in ipairs(items) do labels[item.label] = true end
|
||||
if not (labels.alphabet_soup and labels.alphabet_city) then table.insert(problems, "the buffer's words are not offered: " .. vim.inspect(vim.tbl_keys(labels))) end
|
||||
if require("blink.cmp.completion.list").selected_item_idx ~= nil then table.insert(problems, "an entry is chosen before the person moved") end
|
||||
local tab = vim.fn.maparg("<Tab>", "i", false, true)
|
||||
if tab.buffer == 1 then table.insert(problems, "<Tab> is mapped in the buffer while only the menu is showing: " .. vim.inspect(tab.desc)) end
|
||||
if vim.fn.maparg("<CR>", "i", false, true).buffer ~= 1 or vim.fn.maparg("<C-y>", "i", false, true).buffer ~= 1 then
|
||||
table.insert(problems, "the menu's <CR> and <C-y> are not mapped")
|
||||
end
|
||||
if vim.api.nvim_buf_get_lines(0, 2, 3, false)[1] ~= "alph" then table.insert(problems, "the typed text was changed: " .. vim.api.nvim_buf_get_lines(0, 2, 3, false)[1]) end
|
||||
finish(problems)
|
||||
end
|
||||
vim.defer_fn(look, 200)
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
The colours of LLeMbas, as the LLeMbas server's tokens.css declares them: its two themes,
|
||||
moria (dark) and shire (light). A copy of the colour declarations only; the server's file is
|
||||
the source. scripts/gen-ide-theme.py turns this into the editor's colourscheme.
|
||||
*/
|
||||
|
||||
:root[data-theme="moria"] {
|
||||
--bg: #0B0D10;
|
||||
--bg-sunken: #07090B;
|
||||
--surface: #11151A;
|
||||
--surface-raised: #171C22;
|
||||
--surface-hover: #1D232B;
|
||||
--surface-active: #232B34;
|
||||
--border: #26303A;
|
||||
--border-strong: #5C6976;
|
||||
--ink: #E2E8EC;
|
||||
--ink-muted: #A6B2BC;
|
||||
--ink-faint: #808D98;
|
||||
--ink-inverse: #07090B;
|
||||
--accent: #8FD8E8;
|
||||
--accent-hover: #B4E6F1;
|
||||
--accent-ink: #061418;
|
||||
--accent-soft: rgba(143, 216, 232, 0.12);
|
||||
--selection: rgba(143, 216, 232, 0.32);
|
||||
--leaf: #7EE081;
|
||||
--leaf-hover: #A2EAA3;
|
||||
--leaf-soft: rgba(126, 224, 129, 0.12);
|
||||
--danger: #F0735F;
|
||||
--danger-hover: #F4907F;
|
||||
--danger-soft: rgba(240, 115, 95, 0.13);
|
||||
--success: #5FD6B0;
|
||||
--success-soft: rgba(95, 214, 176, 0.13);
|
||||
--warning: #F0A840;
|
||||
--warning-soft: rgba(240, 168, 64, 0.13);
|
||||
--bubble-user: #161C23;
|
||||
--bubble-assistant: transparent;
|
||||
--code-bg: #07090B;
|
||||
--code-border: #26303A;
|
||||
}
|
||||
|
||||
:root[data-theme="shire"] {
|
||||
--bg: #F1EAD6;
|
||||
--bg-sunken: #E7DEC6;
|
||||
--surface: #F8F3E5;
|
||||
--surface-raised: #FCF9F0;
|
||||
--surface-hover: #ECE4CF;
|
||||
--surface-active: #E2D8BD;
|
||||
--border: #CBBF9D;
|
||||
--border-strong: #2A2E22;
|
||||
--ink: #1F2418;
|
||||
--ink-muted: #474D3B;
|
||||
--ink-faint: #5E6250;
|
||||
--ink-inverse: #F8F3E5;
|
||||
--accent: #285F3C;
|
||||
--accent-hover: #1F4D30;
|
||||
--accent-ink: #F8F3E5;
|
||||
--accent-soft: rgba(40, 95, 60, 0.1);
|
||||
--selection: rgba(40, 95, 60, 0.24);
|
||||
--leaf: #3D6B1C;
|
||||
--leaf-hover: #2F5615;
|
||||
--leaf-soft: rgba(61, 107, 28, 0.1);
|
||||
--danger: #A3321F;
|
||||
--danger-hover: #862818;
|
||||
--danger-soft: rgba(163, 50, 31, 0.1);
|
||||
--success: #2B6A55;
|
||||
--success-soft: rgba(43, 106, 85, 0.1);
|
||||
--warning: #7E5200;
|
||||
--warning-soft: rgba(126, 82, 0, 0.1);
|
||||
--bubble-user: #ECE4CF;
|
||||
--bubble-assistant: transparent;
|
||||
--code-bg: #F1EAD6;
|
||||
--code-border: #CBBF9D;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
-- Your own settings for LLeMbas IDE. This file is yours: an update never touches it.
|
||||
-- It is loaded last, so anything set here wins. Open it from the IDE with <Space>iu.
|
||||
--
|
||||
-- Options:
|
||||
-- vim.opt.relativenumber = true
|
||||
-- vim.opt.wrap = true
|
||||
-- vim.o.background = "light" -- the light theme (shire); "dark" is moria
|
||||
--
|
||||
-- Keys:
|
||||
-- vim.keymap.set("n", "<Leader>W", "<Cmd>wall<CR>", { desc = "Save everything" })
|
||||
--
|
||||
-- LLeMbas (the plugin's own settings; see :help llembas-setup):
|
||||
-- require("llembas").setup({ position = "bottom", complete = { auto = false } })
|
||||
--
|
||||
-- Icons, when your terminal's font is a Nerd Font:
|
||||
-- require("mini.icons").setup({ style = "glyph" })
|
||||
--
|
||||
-- Another language server that is on your PATH (Neovim 0.11 or newer):
|
||||
-- vim.lsp.enable("zls")
|
||||
--
|
||||
-- Your own plugins: put each in ~/.config/llembas-ide/pack/user/start/<name>/ (git clone it
|
||||
-- there yourself) and set it up here. The IDE never installs or updates them.
|
||||
-- require("some_plugin").setup({})
|
||||
--
|
||||
-- The four bars (top, bottom, the tree on the left, LLeMbas on the right). Each can be switched
|
||||
-- off, and the side bars have widths; what you then switch by key in a directory is remembered
|
||||
-- for that directory (the LLeMbas menu forgets it again). See :help llembas-bars.
|
||||
-- require("llembas").setup({ bars = { top = true, bottom = true, tree = true, chat = true,
|
||||
-- tree_width = 26, chat_width = 42 } })
|
||||
-- require("llembas").setup({ bars = false }) -- no bars at all: the plain chat panel
|
||||
--
|
||||
-- LLeMbas's keys are one table (:help llembas-keys). Change an entry, then map again:
|
||||
-- local keys = require("llembas.keys")
|
||||
-- keys.by_id.ask.chord = "<F2>" -- instead of Ctrl+Shift+A
|
||||
-- keys.by_id.tree.alt = "<Leader>t" -- instead of <Space>lb
|
||||
-- require("llembas").setup({ keys = { prefix = "<Leader>l" } })
|
||||
-- When your terminal reports Ctrl+Shift chords and the bottom bar still shows the <Space> keys
|
||||
-- (or the other way round), say which it is:
|
||||
-- require("llembas").setup({ keys = { chords = true } })
|
||||
+317
-10
@@ -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*
|
||||
|
||||
@@ -11,6 +18,11 @@ COMMANDS *llembas-commands*
|
||||
In the prompt, <CR> in normal mode or <C-s> sends (or steers while busy),
|
||||
<C-c> stops the turn, <C-x><C-f> inserts @file, <C-x><C-o> inserts a
|
||||
/command, q closes the panel, g? opens help.
|
||||
The prompt's first line begins with what <CR> will do: `ask ›`,
|
||||
`rewrite ›` or `add ›` (|llembas-intent|). <Tab> in an empty prompt
|
||||
switches between them; with text in the prompt it is Neovim's own <Tab>.
|
||||
<C-j> is a new line. With the bars (|llembas-bars|) <CR> sends from
|
||||
insert mode too and <Esc> goes back to the code.
|
||||
In the transcript, <CR> or gf opens file:line under the cursor, K inspects
|
||||
tool output in a float, y yanks the fenced code block under the cursor, i
|
||||
jumps into the prompt, q closes.
|
||||
@@ -35,6 +47,37 @@ COMMANDS *llembas-commands*
|
||||
:LLeMbasGenerate [instruction] *:LLeMbasGenerate*
|
||||
Generate code at the cursor line and show it as inline proposed hunks.
|
||||
|
||||
:[range]LLeMbasPrompt [ask|rewrite|add] *:LLeMbasPrompt*
|
||||
To the prompt, with the lines of [range] — without one, the cursor's
|
||||
line — as the attachment: its name stands above the prompt
|
||||
(`main.rs:12-18`). The argument sets what <CR> will do. *llembas-intent*
|
||||
ask the question goes to the chat, the lines with it as context
|
||||
rewrite the lines are rewritten; the result is shown in the file as
|
||||
changes to accept or reject (as |:LLeMbasEdit|)
|
||||
add new code is written at the point, shown the same way
|
||||
(as |:LLeMbasGenerate|)
|
||||
After a rewrite or an add the prompt says `ask ›` again.
|
||||
|
||||
:LLeMbasEffort [level] *:LLeMbasEffort*
|
||||
The effort of the conversation: off, minimal, low, medium, high, xhigh,
|
||||
max or default. Without a level, pick one. A level the model does not
|
||||
offer is said, with the level it runs on.
|
||||
|
||||
:LLeMbasAI [on|off] *:LLeMbasAI*
|
||||
Everything of LLeMbas on or off. Off is a plain editor: the agent is
|
||||
stopped, no suggestion is asked for, nothing is sent, and it stays off in
|
||||
this directory until it is switched on.
|
||||
|
||||
:LLeMbasMenu *:LLeMbasMenu*
|
||||
Every command and every setting — the model, the mode, the effort,
|
||||
suggestions, the bars — in one list to pick from.
|
||||
|
||||
:LLeMbasBars [on|off|top|bottom|tree|chat [on|off]] *:LLeMbasBars*
|
||||
The four bars (|llembas-bars|) on or off, or one of them.
|
||||
|
||||
:LLeMbasTree *:LLeMbasTree*
|
||||
The file tree, show and hide (|llembas-tree|).
|
||||
|
||||
:LLeMbasCancelEdit *:LLeMbasCancelEdit*
|
||||
Cancel an in-flight rewrite or generation in the current buffer.
|
||||
|
||||
@@ -54,7 +97,7 @@ COMMANDS *llembas-commands*
|
||||
a picker with presets and a custom token count input.
|
||||
|
||||
:LLeMbasAutocompleteInstructions [text|-] *:LLeMbasAutocompleteInstructions*
|
||||
Set custom instructions sent with autocomplete requests ("-" clears them).
|
||||
Your own instructions for suggestions ("-" clears them).
|
||||
|
||||
:LLeMbasAutocompleteModel[!] [model] *:LLeMbasAutocompleteModel*
|
||||
The model that writes suggestions, saved in your account; without a name,
|
||||
@@ -65,12 +108,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.
|
||||
@@ -85,13 +129,17 @@ COMMANDS *llembas-commands*
|
||||
Toggle showing model thinking in the transcript.
|
||||
|
||||
:LLeMbasOpen *:LLeMbasOpen*
|
||||
Open the file the agent showed last with the system's viewer.
|
||||
Open the file the agent showed last. Only a picture, a PDF, sound, video
|
||||
or plain text, and only when the file's first bytes are what its name
|
||||
says: plain text opens here (read-only), the rest in the system's
|
||||
viewer. Anything else is named and left alone.
|
||||
|
||||
:LLeMbasStop *:LLeMbasStop*
|
||||
Stop the running turn.
|
||||
|
||||
:LLeMbasNew[!] *:LLeMbasNew*
|
||||
Start a new session (! ends a hung turn). Old sessions stay in the CLI.
|
||||
Start a new session (! also ends the agent when a turn hangs). Old
|
||||
sessions stay in the CLI.
|
||||
|
||||
:LLeMbasMode [mode] *:LLeMbasMode*
|
||||
Change the session's mode (works live mid-turn); without an arg, pick.
|
||||
@@ -100,7 +148,253 @@ 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.
|
||||
|
||||
==============================================================================
|
||||
THE BARS *llembas-bars*
|
||||
|
||||
`bars = true` in |llembas-setup| lays the editor out in four bars, each of
|
||||
which can be switched off (`bars = { top = false }`, |:LLeMbasBars|):
|
||||
|
||||
top what LLeMbas is doing, the conversation's title, model · mode ·
|
||||
effort, the context in percent, suggestions on or off, and the
|
||||
git branch and the file's problems when there is room. It is the
|
||||
'tabline'.
|
||||
bottom the keys for the bar that has the focus (|llembas-keys|), and
|
||||
Neovim's own state: mode, modified, macro, search count, line
|
||||
and column, pending operator. It is the 'statusline' (with
|
||||
'laststatus' 3). From 120 columns the search count and the
|
||||
pending operator have cells in it ('showcmdloc' statusline);
|
||||
narrower, the keys need the room and both are where stock Neovim
|
||||
shows them, in the command line's row.
|
||||
With several tab pages the top bar says which one this is.
|
||||
tree the file tree on the left (|llembas-tree|).
|
||||
chat the right bar: the settings lines (model, mode, effort,
|
||||
autocomplete — <CR> on a line opens its choices under it, <CR>
|
||||
on a choice takes it, <Esc> closes), the transcript, and the
|
||||
prompt with the attachment's name above it.
|
||||
|
||||
Every row is made of cells of a known width; one cell takes what is left and
|
||||
is cut with an ellipsis. Nothing wraps. When the code would have fewer than
|
||||
`min_code` columns the chat folds away, then the tree; a bar opened by key at
|
||||
that width is shown all the same. Under 18 rows the settings lines are left
|
||||
out. Switched off, the top and bottom bars give 'tabline' and 'statusline'
|
||||
back as they were (`User LLeMbasBars` is fired, for a distribution that puts
|
||||
its own there).
|
||||
>lua
|
||||
require("llembas").setup({ bars = {
|
||||
top = true, bottom = true, tree = true, chat = true,
|
||||
tree_width = 26, -- 16 to 60
|
||||
chat_width = 42, -- 34 to 50
|
||||
prompt_height = 3,
|
||||
min_code = 60,
|
||||
} })
|
||||
<
|
||||
The tree *llembas-tree*
|
||||
The working directory as lines. <CR> or l opens a file, and opens or
|
||||
closes a directory; <Right> opens, <Left> or h closes or goes to the
|
||||
directory above. a makes a file (a directory when the name ends in /),
|
||||
r renames or moves, d deletes after asking — into the trash where the
|
||||
system has one (`gio trash`, `trash-put`, `trash`), and for good, said so
|
||||
in the question, where it has none. / filters by name as you type, .
|
||||
shows hidden files, R reads the directory again. The file you are in is
|
||||
followed. The first column of a row is its git state: M changed, A added,
|
||||
? new, D deleted, ! conflict, • a directory with changes inside.
|
||||
|
||||
==============================================================================
|
||||
KEYS *llembas-keys*
|
||||
|
||||
`keys = true` (or `bars`) maps LLeMbas's keys from one table,
|
||||
`require("llembas.keys").table`. An action has two forms, and both are
|
||||
mapped:
|
||||
|
||||
the chord the LLeMbas terminal's: <C-S-A> and so on. It reaches
|
||||
Neovim only from a terminal that reports such keys (the
|
||||
kitty keyboard protocol).
|
||||
the other a key after the prefix (<Leader>l), or a plain key in one of
|
||||
the bars. It always arrives.
|
||||
|
||||
<C-S-A> <Leader>la to the prompt; the selection or the cursor's line
|
||||
comes along (|:LLeMbasPrompt|)
|
||||
<Leader>le the same, to rewrite <Leader>lg to add
|
||||
<C-Tab> <Leader>lm switch the mode
|
||||
<C-S-M> <Leader>lM choose the model <Leader>lE the effort
|
||||
<C-M-m> <Leader>lC choose the autocomplete model
|
||||
<C-M-a> <Leader>lt suggestions as you type, on and off
|
||||
<C-S-I> <Leader>lI LLeMbas on and off (|:LLeMbasAI|)
|
||||
<C-S-G> <Leader>l. stop the running turn
|
||||
<C-S-Y> ga accept the proposed change under the cursor
|
||||
<C-S-J> gr reject it <M-C-S-Y> gA accept all
|
||||
<C-S-E> <Leader>lb the tree, show and hide
|
||||
<C-S-D> <Leader>ll the chat, show and hide
|
||||
<M-Left> <M-Right> to the bar on the left, on the right
|
||||
<C-S-P> <Leader>lp the menu (|:LLeMbasMenu|)
|
||||
<Leader>ls sessions, ln new, lc commands, lx explain, lf fix, lS status,
|
||||
li sign in, l? help.
|
||||
|
||||
The bottom bar shows the form that works: the chords once one has arrived
|
||||
from this terminal (remembered) or when the terminal is one known to report
|
||||
them, the other form otherwise. `keys = { chords = true }` or `false` says it
|
||||
by hand; `keys = { prefix = "<Leader>a" }` moves the other form.
|
||||
To change a key, change its entry and set up again:
|
||||
>lua
|
||||
local keys = require("llembas.keys")
|
||||
keys.by_id.ask.chord = "<F2>"
|
||||
require("llembas").setup({ keys = true })
|
||||
<
|
||||
<Tab> has three jobs that never meet: while typing code it accepts a shown
|
||||
suggestion and is Neovim's own otherwise (the mapping exists only while a
|
||||
suggestion is shown); in an empty prompt it switches ask, rewrite, add; and
|
||||
it is never a completion menu's.
|
||||
|
||||
Inside the LLeMbas terminal (`$LLEMBAS_TERM` or `$LLEMBAS_TTY`) the plugin
|
||||
sets the terminal's user var `llembas_ide` to 1 when the keys are mapped and
|
||||
clears it on exit, so that the terminal hands its own chords through. Nothing
|
||||
is written in any other terminal.
|
||||
|
||||
==============================================================================
|
||||
FOR A STATUSLINE, A BAR, A SCRIPT *llembas-api*
|
||||
|
||||
require("llembas").settings() *llembas.settings()*
|
||||
What holds now: `state` ("idle", "thinking", "tools", "writing",
|
||||
"waiting", "starting", "signed_out", "no_cli", "off"), `title`,
|
||||
`session` (boolean), `model`, `mode`, `effort`, `context` (percent of the
|
||||
model's window, or nil), `autocomplete`, `ai`, `intent`, `attachment`,
|
||||
`busy`, `changes` (proposed changes in this buffer).
|
||||
|
||||
User LLeMbasChanged *LLeMbasChanged*
|
||||
Fired when any of that changes. `User LLeMbasBars`: the top or bottom bar
|
||||
was switched; `User LLeMbasLayout`: the side bars were laid out.
|
||||
|
||||
require("llembas").setting_lines() *llembas.setting_lines()*
|
||||
The settings as lines: `{ id, label, value, off }` for model, mode,
|
||||
effort, autocomplete.
|
||||
require("llembas").choices({id}, {cb}) *llembas.choices()*
|
||||
What a setting can be set to: `cb(list)` of `{ value, label, current }`,
|
||||
or `cb(nil, why)`. The models and modes are asked of the CLI.
|
||||
require("llembas").set({id}, {value}) *llembas.set()*
|
||||
Set it.
|
||||
require("llembas").prompt({opts}) *llembas.prompt()*
|
||||
|:LLeMbasPrompt|: `intent`, `first`, `last`, `attach = false`.
|
||||
require("llembas").intent([{name}]) *llembas.intent()*
|
||||
Set, and return, what <CR> in the prompt will do.
|
||||
require("llembas").cli() *llembas.cli()*
|
||||
The command that starts the agent, as a list, or nil and why: `cmd` as
|
||||
set, and a bare `lembas` that is not on this editor's PATH where the
|
||||
CLI's installer puts it (~/.local/bin). The one place that decides
|
||||
whether the LLeMbas CLI is installed.
|
||||
require("llembas").effort([{level}]) .ai([{on}]) .autocomplete([{on}])
|
||||
require("llembas").cycle_mode() .menu()
|
||||
As the commands of those names.
|
||||
require("llembas.layout").toggle({bar} [, {on}]) .focus("tree"|"code"|"chat")
|
||||
.go(-1|1) .where() .options() .top_text([{width}])
|
||||
.bottom_text([{where} [, {width} [, {chords}]]])
|
||||
The bars: show and hide, move the focus, where it is, and the two rows as
|
||||
plain text of exactly the width asked for.
|
||||
require("llembas.keys").table .by_id .for_bar({where}) .rows()
|
||||
.written({lhs}) .chords()
|
||||
The key table, the keys a bar shows, the rows of a cheat sheet, a key as
|
||||
the bar writes it, and whether the chords arrive.
|
||||
|
||||
What is remembered *llembas-remembered*
|
||||
The mode, the effort, suggestions and LLeMbas on or off, which bars are
|
||||
shown and how wide the side bars are: per working directory, with a
|
||||
machine-wide level under it, in `stdpath("state")/llembas/settings.json`.
|
||||
A change is the directory's own. *Make these settings the default* in
|
||||
the menu copies what holds here to the machine-wide level; *Forget what
|
||||
this directory chose* removes the directory's own. `remember = false`
|
||||
keeps nothing. The models are not kept here: the session's model is the
|
||||
LLeMbas CLI's to remember (the model last used in a directory), and the
|
||||
autocomplete and main model are your account's
|
||||
(|:LLeMbasAutocompleteModel|, |:LLeMbasMainModel|).
|
||||
|
||||
After |:cd| the new directory's own hold: the mode and the effort a
|
||||
session starts with, LLeMbas and suggestions on or off.
|
||||
|
||||
==============================================================================
|
||||
WHAT IS SENT *llembas-privacy*
|
||||
|
||||
Everything goes to the LLeMbas CLI on this computer, and from there to your
|
||||
LLeMbas server: nowhere else.
|
||||
|
||||
What you send the message you type; lines you ask about, have
|
||||
explained or rewritten; a file you name with @.
|
||||
With a message the name of the file you are in, the cursor's line, the
|
||||
lines that came along, the diagnostics on them, and the
|
||||
NAMES (not the text) of the other open files
|
||||
(`send_open_file = false`: none of this).
|
||||
With a suggestion the text around the cursor (up to 400 lines before it
|
||||
and 100 after), the file's name and type, and the TEXT
|
||||
of up to six other open files (the first 400 lines of
|
||||
each), of which the CLI puts pieces beside it.
|
||||
|
||||
What goes along without your pointing at it — the other files' names and
|
||||
text — is held to three rules:
|
||||
|
||||
1. Only files inside the working directory (|:pwd|).
|
||||
2. Never a file that looks like it holds secrets, by its name or its place:
|
||||
`.env` and `.env.*` (but not `.env.example`, `.env.sample`,
|
||||
`.env.template`), `*.env`, `*.pem`, `*.key`, `*.p12`, `*.pfx`, `*.jks`,
|
||||
`*.keystore`, `*.ppk`, `*.kdbx`, `id_rsa*`, `id_ed25519*`, `id_ecdsa*`,
|
||||
`id_dsa*`, `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
|
||||
`.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and
|
||||
anything under `.ssh/`, `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or
|
||||
`.azure/`.
|
||||
3. Never a file the project's .gitignore leaves out (git is asked, once a
|
||||
file; a file git has not answered for yet is left out).
|
||||
|
||||
In a file that looks like it holds secrets no suggestion is asked for at
|
||||
all, so nothing of it is sent; that is said once. A file the project
|
||||
ignores, or one outside the working directory, still gets suggestions while
|
||||
you type in it: its own text around the cursor is what a suggestion is made
|
||||
from.
|
||||
|
||||
The agent itself reads and writes files as a turn needs them, under the
|
||||
CLI's permissions; that is the CLI's to allow or ask about, and is not
|
||||
limited by the rules above. |:LLeMbasAI| off sends nothing at all.
|
||||
|
||||
==============================================================================
|
||||
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 +409,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
|
||||
@@ -126,13 +423,23 @@ SETUP *llembas-setup*
|
||||
accept_word = "<M-Right>", -- accepts next word of suggestion
|
||||
trigger = "<M-\\>", -- asks for a suggestion now
|
||||
},
|
||||
keys = false, -- true or { prefix, chords }: |llembas-keys|
|
||||
bars = false, -- true or a table: |llembas-bars|
|
||||
remember = true, -- |llembas-remembered|
|
||||
})
|
||||
<
|
||||
Statusline component: `require("llembas").statusline()`.
|
||||
Highlights: `LLeMbasBrand`, `LLeMbasUserHeader`, `LLeMbasAgentHeader`,
|
||||
`LLeMbasThought`, `LLeMbasToolPending`, `LLeMbasToolDone`, `LLeMbasToolFail`,
|
||||
`LLeMbasToolDenied`, `LLeMbasPlanHeader`, `LLeMbasDiffAdd`, `LLeMbasDiffDelete`,
|
||||
`LLeMbasDiffHint`, `LLeMbasGhost`, `LLeMbasSeparator` (all `default = true`).
|
||||
`LLeMbasDiffHint`, `LLeMbasGhost`, `LLeMbasSeparator`; the bars' `LLeMbasBar`,
|
||||
`LLeMbasBarKey`, `LLeMbasBarTitle`, `LLeMbasBarSeparator`, `LLeMbasBarFact`,
|
||||
`LLeMbasBarIdle`, `LLeMbasBarBusy`, `LLeMbasBarWaiting`, `LLeMbasBarOff`,
|
||||
`LLeMbasBarVim`; `LLeMbasPromptPrefix`, `LLeMbasChip`, `LLeMbasLineLabel`,
|
||||
`LLeMbasLineValue`, `LLeMbasLineOff`, `LLeMbasLineCurrent`; the tree's
|
||||
`LLeMbasTreeDirectory`, `LLeMbasTreeCurrent`, `LLeMbasTreeChanged`,
|
||||
`LLeMbasTreeAdded`, `LLeMbasTreeNew`, `LLeMbasTreeDeleted`,
|
||||
`LLeMbasTreeConflict` (all `default = true`).
|
||||
|
||||
What the model writes is shown as text. It is never run, and the panel's
|
||||
buffers read no modeline.
|
||||
|
||||
+115
-16
@@ -5,7 +5,11 @@ local ui = require("llembas.ui")
|
||||
local M = {
|
||||
tbuf = nil, ibuf = nil, marks = {}, details = {},
|
||||
on_send = nil, on_stop = nil, on_help = nil, on_files = nil, on_commands = nil,
|
||||
on_intent = nil, on_back = nil,
|
||||
bars = false, -- opened as the right bar of the layout: settings lines above, Enter sends, Esc goes back
|
||||
intent = "ask", -- what Enter will do, shown before the prompt's first line
|
||||
}
|
||||
M.PREFIX_WIDTH = 10 -- "rewrite › ", the longest; every prefix is padded to it
|
||||
local ns = vim.api.nvim_create_namespace("llembas")
|
||||
local ns_hl = vim.api.nvim_create_namespace("llembas-hl")
|
||||
local ns_welcome = vim.api.nvim_create_namespace("llembas-welcome")
|
||||
@@ -30,7 +34,7 @@ local function sync_welcome()
|
||||
vim.api.nvim_buf_clear_namespace(M.tbuf, ns_welcome, 0, -1)
|
||||
if is_empty_buf(M.tbuf) then
|
||||
vim.api.nvim_buf_set_extmark(M.tbuf, ns_welcome, 0, 0, {
|
||||
virt_lines = ui.welcome_virt_lines(),
|
||||
virt_lines = ui.welcome_virt_lines(M.bars),
|
||||
virt_lines_above = false,
|
||||
})
|
||||
end
|
||||
@@ -127,15 +131,15 @@ local function buffers()
|
||||
M.details = {}
|
||||
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" })
|
||||
vim.keymap.set("n", "<C-c>", function() if M.on_stop then M.on_stop() end end, { buffer = M.tbuf, desc = "LLeMbas: stop the turn" })
|
||||
vim.keymap.set("n", "<CR>", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" })
|
||||
vim.keymap.set("n", "gf", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" })
|
||||
vim.keymap.set("n", "K", inspect_line, { buffer = M.tbuf, desc = "LLeMbas: inspect tool output" })
|
||||
vim.keymap.set("n", "y", yank_code_block, { buffer = M.tbuf, desc = "LLeMbas: yank code block under cursor" })
|
||||
vim.keymap.set("n", "g?", function() if M.on_help then M.on_help() end end, { buffer = M.tbuf, desc = "LLeMbas: help" })
|
||||
vim.keymap.set("n", "i", function()
|
||||
local iw = win_of(M.ibuf)
|
||||
if iw then vim.api.nvim_set_current_win(iw); pcall(vim.cmd, "startinsert") end
|
||||
end, { buffer = M.tbuf, desc = "LLeMbas: jump to prompt" })
|
||||
require("llembas.keys").bind("chat", M.tbuf, {
|
||||
chat_open = open_at_cursor,
|
||||
chat_output = inspect_line,
|
||||
chat_prompt = function() M.focus_prompt() end,
|
||||
})
|
||||
vim.b[M.tbuf].completion = false -- no completion menu in a buffer nobody types in
|
||||
sync_welcome()
|
||||
end
|
||||
if not valid(M.ibuf) then
|
||||
@@ -145,7 +149,33 @@ local function buffers()
|
||||
if not text:match("%S") then return end
|
||||
if M.on_send and M.on_send(text) ~= false then vim.api.nvim_buf_set_lines(M.ibuf, 0, -1, false, {}) end
|
||||
end
|
||||
vim.keymap.set("n", "<CR>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
|
||||
local function key(k) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(k, true, false, true), "n", false) end
|
||||
local function empty()
|
||||
return not table.concat(vim.api.nvim_buf_get_lines(M.ibuf, 0, -1, false), ""):match("%S")
|
||||
end
|
||||
-- The prompt's keys are the key table's (scope "prompt"). <Tab> has one job here: in an empty
|
||||
-- prompt it switches what Enter will do; with text in the prompt it is Neovim's own Tab.
|
||||
-- In the layout's right bar Enter sends from insert mode too (<C-j> is the new line) and
|
||||
-- Esc goes back to the code; in the panel on its own they stay Neovim's.
|
||||
require("llembas.keys").bind("prompt", M.ibuf, {
|
||||
send = function()
|
||||
if vim.api.nvim_get_mode().mode:sub(1, 1) == "i" and not M.bars then return key("<CR>") end
|
||||
send()
|
||||
end,
|
||||
intent = function()
|
||||
if empty() then
|
||||
if M.on_intent then M.on_intent() end
|
||||
elseif vim.api.nvim_get_mode().mode:sub(1, 1) == "i" then
|
||||
key("<Tab>")
|
||||
end
|
||||
end,
|
||||
newline = function() key("<CR>") end,
|
||||
back = function()
|
||||
if not M.bars then return key("<Esc>") end
|
||||
if M.on_back then M.on_back() end
|
||||
end,
|
||||
}, { send = { "n", "i" }, intent = { "n", "i" }, newline = "i", back = { "n", "i" } })
|
||||
vim.b[M.ibuf].completion = false -- the prompt is one line of words, not code: no menu over it
|
||||
vim.keymap.set({ "n", "i" }, "<C-s>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
|
||||
vim.keymap.set({ "n", "i" }, "<C-c>", function() if M.on_stop then M.on_stop() end end, { buffer = M.ibuf, desc = "LLeMbas: stop the turn" })
|
||||
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.ibuf, desc = "LLeMbas: close the panel" })
|
||||
@@ -161,9 +191,56 @@ end
|
||||
|
||||
function M.is_open() return win_of(M.tbuf) ~= nil end
|
||||
|
||||
--- Open the panel (`opts` may be a width number or `{ width, position, prompt_height, border }`).
|
||||
--- What stands before the prompt's first line: what Enter will do. Every prefix has the same
|
||||
--- width, and the lines under the first are indented by it, so the text has one left edge.
|
||||
function M.prefix()
|
||||
if vim.v.lnum == 1 and vim.v.virtnum == 0 then
|
||||
local word = M.intent .. " ›"
|
||||
return "%#LLeMbasPromptPrefix#" .. word .. (" "):rep(M.PREFIX_WIDTH - vim.fn.strdisplaywidth(word)) .. "%*"
|
||||
end
|
||||
return (" "):rep(M.PREFIX_WIDTH)
|
||||
end
|
||||
|
||||
--- What Enter will do: "ask", "rewrite" or "add". The prefix shows it.
|
||||
function M.set_intent(intent)
|
||||
M.intent = intent
|
||||
local w = win_of(M.ibuf)
|
||||
if w then
|
||||
if not pcall(vim.api.nvim__redraw, { win = w, statuscolumn = true }) then pcall(vim.cmd, "redraw!") end
|
||||
end
|
||||
end
|
||||
|
||||
--- The focus into the prompt, typing.
|
||||
function M.focus_prompt()
|
||||
local iw = win_of(M.ibuf)
|
||||
if not iw then return false end
|
||||
vim.api.nvim_set_current_win(iw)
|
||||
pcall(vim.cmd, "startinsert!")
|
||||
return true
|
||||
end
|
||||
|
||||
--- No `~` under the text of a bar: the rows past the end are empty.
|
||||
local function quiet_end(win)
|
||||
local fc = vim.wo[win].fillchars
|
||||
if not fc:find("eob:", 1, true) then vim.wo[win].fillchars = (fc ~= "" and (fc .. ",") or "") .. "eob: " end
|
||||
end
|
||||
|
||||
local function prompt_options(iw)
|
||||
if M.bars then quiet_end(iw) end
|
||||
-- The prefix is the window's status column: the number column's place, with our text in it.
|
||||
vim.wo[iw].number = true
|
||||
vim.wo[iw].numberwidth = 1
|
||||
vim.wo[iw].statuscolumn = "%{%v:lua.require'llembas.chat'.prefix()%}"
|
||||
vim.wo[iw].foldcolumn = "0"
|
||||
end
|
||||
|
||||
--- Open the panel (`opts` may be a width number or `{ width, position, prompt_height, border }`;
|
||||
--- `bars = true` opens it as the layout's right bar: `lines = true` puts the settings lines above
|
||||
--- the transcript).
|
||||
function M.open(opts, focus)
|
||||
M.bars = type(opts) == "table" and opts.bars == true
|
||||
buffers()
|
||||
sync_welcome()
|
||||
local width = type(opts) == "number" and opts or (opts and opts.width) or 64
|
||||
local position = type(opts) == "table" and opts.position or "right"
|
||||
local prompt_h = type(opts) == "table" and opts.prompt_height or 5
|
||||
@@ -206,27 +283,45 @@ function M.open(opts, focus)
|
||||
else vim.cmd("botright vertical " .. width .. "split") end
|
||||
tw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(tw, M.tbuf)
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = position ~= "bottom" }) do
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = position ~= "bottom",
|
||||
statuscolumn = "", foldcolumn = "0", list = false, cursorline = false }) do
|
||||
vim.wo[tw][k] = v
|
||||
end
|
||||
if M.bars and type(opts) == "table" and opts.lines then
|
||||
local lines = require("llembas.lines")
|
||||
vim.cmd("aboveleft " .. lines.height() .. "split")
|
||||
local sw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(sw, lines.buffer())
|
||||
for k, v in pairs({ wrap = false, number = false, relativenumber = false, signcolumn = "no", winfixheight = true, winfixwidth = true,
|
||||
statuscolumn = "", foldcolumn = "0", list = false, cursorline = true, winbar = "" }) do
|
||||
vim.wo[sw][k] = v
|
||||
end
|
||||
lines.render()
|
||||
quiet_end(sw)
|
||||
vim.api.nvim_set_current_win(tw)
|
||||
end
|
||||
if M.bars then quiet_end(tw) end
|
||||
end
|
||||
if not iw then
|
||||
vim.api.nvim_set_current_win(tw)
|
||||
vim.cmd("belowright " .. prompt_h .. "split")
|
||||
-- In the layout the height is the prompt's own rows: the chip's row is one more.
|
||||
vim.cmd("belowright " .. (M.bars and prompt_h + 1 or prompt_h) .. "split")
|
||||
iw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(iw, M.ibuf)
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true }) do
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true,
|
||||
winfixwidth = position ~= "bottom", list = false, cursorline = false }) do
|
||||
vim.wo[iw][k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
if iw and vim.api.nvim_win_is_valid(iw) then prompt_options(iw) end
|
||||
|
||||
if focus == false and vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back)
|
||||
elseif iw and vim.api.nvim_win_is_valid(iw) then vim.api.nvim_set_current_win(iw) end
|
||||
end
|
||||
|
||||
function M.close()
|
||||
for _, b in ipairs({ M.ibuf, M.tbuf }) do
|
||||
for _, b in ipairs({ M.ibuf, M.tbuf, require("llembas.lines").buf() }) do
|
||||
local w = win_of(b)
|
||||
if w and #vim.api.nvim_tabpage_list_wins(0) > 1 then pcall(vim.api.nvim_win_close, w, true) end
|
||||
end
|
||||
@@ -235,13 +330,17 @@ end
|
||||
--- The header line above the transcript: brand, session title, mode, model, usage.
|
||||
function M.header(text)
|
||||
local w = win_of(M.tbuf)
|
||||
if w then vim.wo[w].winbar = (text or ""):gsub("%%", "%%%%") end
|
||||
-- In the layout the top bar says all of this: the transcript has no line of its own.
|
||||
if w then vim.wo[w].winbar = M.bars and "" or (text or ""):gsub("%%", "%%%%") end
|
||||
end
|
||||
|
||||
--- The line above the prompt: what the next message carries, the mode, the model.
|
||||
function M.status(text)
|
||||
function M.status(text, hl)
|
||||
local w = win_of(M.ibuf)
|
||||
if w then vim.wo[w].winbar = (text or ""):gsub("%%", "%%%%") end
|
||||
if not w then return end
|
||||
-- Never empty: the row is there with or without an attachment, so the prompt does not move.
|
||||
local shown = ((text and text ~= "") and text or " "):gsub("%%", "%%%%")
|
||||
vim.wo[w].winbar = (hl and text and text ~= "") and ("%#" .. hl .. "#" .. shown .. "%*") or shown
|
||||
end
|
||||
|
||||
local function edit(fn)
|
||||
|
||||
@@ -4,10 +4,44 @@
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace("llembas-complete")
|
||||
|
||||
local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil, installed = false }
|
||||
local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil, installed = false, said_private = {} }
|
||||
|
||||
local PREFIX_MAX, SUFFIX_MAX = 16000, 4000
|
||||
local REFUSALS = { no_model = true, not_allowed = true, not_logged_in = true, unsupported = true }
|
||||
-- Refusals that stay true until something is changed: said once, and typing asks no more.
|
||||
local REFUSALS = { no_model = true, not_allowed = true, unknown_model = true, not_logged_in = true, unsupported = true }
|
||||
-- What to do about each, said after the server's own sentence.
|
||||
local HINTS = {
|
||||
no_model = ":LLeMbasAutocompleteModel chooses one",
|
||||
not_allowed = ":LLeMbasAutocompleteModel chooses another",
|
||||
unknown_model = ":LLeMbasAutocompleteModel chooses another",
|
||||
unsupported = "it needs a newer LLeMbas server or CLI",
|
||||
}
|
||||
|
||||
--- The last `max` bytes of `text`, or its first, never cutting a character in two.
|
||||
local function tail_bytes(text, max)
|
||||
if #text <= max then return text end
|
||||
local at = #text - max + 1
|
||||
while at <= #text and text:byte(at) >= 0x80 and text:byte(at) <= 0xBF do at = at + 1 end
|
||||
return text:sub(at)
|
||||
end
|
||||
local function head_bytes(text, max)
|
||||
if #text <= max then return text end
|
||||
local at = max
|
||||
while at > 0 and text:byte(at + 1) and text:byte(at + 1) >= 0x80 and text:byte(at + 1) <= 0xBF do at = at - 1 end
|
||||
return text:sub(1, at)
|
||||
end
|
||||
M._tail_bytes, M._head_bytes = tail_bytes, head_bytes
|
||||
|
||||
--- Say why no suggestion comes. Asked for on the key, it is said whole; while you type it is one
|
||||
--- short line, so that nothing waits for a key press — `:LLeMbasStatus` has the whole of it.
|
||||
local function say(text, manual)
|
||||
if not manual then
|
||||
local room = math.max(40, vim.o.columns - 12)
|
||||
local tail = "… (:LLeMbasStatus)"
|
||||
if vim.fn.strdisplaywidth(text) > room then text = vim.fn.strcharpart(text, 0, room - vim.fn.strdisplaywidth(tail)) .. tail end
|
||||
end
|
||||
vim.notify("LLeMbas: " .. text, vim.log.levels.WARN)
|
||||
end
|
||||
|
||||
local LENGTH_PRESETS = {
|
||||
auto = { tokens = nil, instruction = "" },
|
||||
@@ -91,6 +125,7 @@ local function show(buf, row, col, text)
|
||||
st.shown.maps[#st.shown.maps + 1] = { key = key, before = before }
|
||||
vim.keymap.set("i", key, fn, { buffer = buf, nowait = true, desc = desc })
|
||||
end
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
bind(c.accept, function() M.accept() end, "LLeMbas: accept the suggestion")
|
||||
if c.accept_word and c.accept_word ~= "" and c.accept_word ~= c.accept then
|
||||
bind(c.accept_word, function() M.accept_word() end, "LLeMbas: accept next word of suggestion")
|
||||
@@ -101,15 +136,25 @@ local function usable(buf)
|
||||
return vim.bo[buf].buftype == "" and vim.bo[buf].modifiable
|
||||
end
|
||||
|
||||
--- Collect up to 6 other loaded file buffers' text so the CLI can prefer unsaved open buffers
|
||||
--- for session-aware autocomplete context.
|
||||
--- Whether `buf` is a file that looks like it holds secrets: no suggestion is asked for in it,
|
||||
--- so that nothing of it is sent.
|
||||
function M.private(buf)
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
return name ~= "" and require("llembas.private").looks_secret(name)
|
||||
end
|
||||
|
||||
--- The text of up to six other open files (the first 400 lines of each), which the CLI may put
|
||||
--- pieces of beside the text around the cursor. Only files of this project, and never one that
|
||||
--- looks like it holds secrets or that the project's .gitignore leaves out (|llembas-privacy|).
|
||||
local function open_snippets(exclude_buf)
|
||||
local private = require("llembas.private")
|
||||
local roots = private.roots()
|
||||
local out = {}
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
if #out >= 6 then break end
|
||||
if b ~= exclude_buf and vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then
|
||||
local name = vim.api.nvim_buf_get_name(b)
|
||||
if name ~= "" then
|
||||
if name ~= "" and private.may_send(name, roots) then
|
||||
local text = table.concat(vim.api.nvim_buf_get_lines(b, 0, 400, false), "\n")
|
||||
if #text > 0 and #text <= 32768 then
|
||||
out[#out + 1] = { path = name, text = text }
|
||||
@@ -127,7 +172,7 @@ function M.warm(buf)
|
||||
local conn = L()._state.conn
|
||||
if not conn or not L()._state.ready or not L()._state.caps.editor then return end
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
if name == "" then return end
|
||||
if name == "" or require("llembas.private").looks_secret(name) then return end
|
||||
local cwd = vim.fn.getcwd()
|
||||
local key = (L()._state.session or "") .. "|" .. cwd .. "|" .. name
|
||||
if st.last_warm == key then return end
|
||||
@@ -145,6 +190,18 @@ end
|
||||
function M.request(manual)
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
if not usable(buf) then return end
|
||||
if L()._state.ai == false then
|
||||
if manual then say("no suggestion: LLeMbas is off", true) end
|
||||
return
|
||||
end
|
||||
if M.private(buf) then
|
||||
-- Said once a file, and again when it is asked for by hand.
|
||||
if manual or not st.said_private[buf] then
|
||||
st.said_private[buf] = true
|
||||
say("no suggestions in this file: its name says it may hold secrets, so nothing of it is sent", true)
|
||||
end
|
||||
return
|
||||
end
|
||||
local win = vim.api.nvim_get_current_win()
|
||||
local pos = vim.api.nvim_win_get_cursor(win)
|
||||
local row, col = pos[1] - 1, pos[2]
|
||||
@@ -154,8 +211,7 @@ function M.request(manual)
|
||||
before[#before + 1] = line:sub(1, col)
|
||||
table.insert(after, 1, line:sub(col + 1))
|
||||
local prefix, suffix = table.concat(before, "\n"), table.concat(after, "\n")
|
||||
if #prefix > PREFIX_MAX then prefix = prefix:sub(-PREFIX_MAX) end
|
||||
if #suffix > SUFFIX_MAX then suffix = suffix:sub(1, SUFFIX_MAX) end
|
||||
prefix, suffix = tail_bytes(prefix, PREFIX_MAX), head_bytes(suffix, SUFFIX_MAX)
|
||||
cancel()
|
||||
local seq = st.seq
|
||||
L()._connect(function(conn)
|
||||
@@ -163,12 +219,20 @@ function M.request(manual)
|
||||
if not conn then
|
||||
-- An agent that does not start is not started again at every pause: once a minute at most.
|
||||
st.wait_until = vim.uv.now() + 60000
|
||||
if manual then vim.notify("LLeMbas: " .. (L()._state.start_error or "the agent did not start"), vim.log.levels.WARN) end
|
||||
st.why = L()._state.start_error or "the agent did not start"
|
||||
if manual or not st.said_start then
|
||||
st.said_start = true
|
||||
say("no suggestions: " .. st.why, manual)
|
||||
end
|
||||
return
|
||||
end
|
||||
if not L()._state.caps.editor then
|
||||
st.off = "this LLeMbas CLI does not offer autocomplete yet"
|
||||
if manual then vim.notify("LLeMbas: " .. st.off, vim.log.levels.WARN) end
|
||||
st.off = L()._words.too_old
|
||||
st.why = st.off
|
||||
if manual or not st.said then
|
||||
st.said = true
|
||||
say("no suggestions: " .. st.off, manual)
|
||||
end
|
||||
return
|
||||
end
|
||||
local id = ("c%d"):format(seq)
|
||||
@@ -192,28 +256,31 @@ function M.request(manual)
|
||||
if seq ~= st.seq then return end
|
||||
if err then
|
||||
local reason = (type(err.data) == "table" and type(err.data.reason) == "string") and err.data.reason or ""
|
||||
local msg = tostring(err.message or "completion failed")
|
||||
if REFUSALS[reason] or reason == "" then
|
||||
-- Permanent refusal (e.g. no model): said once, stops asking until a model is chosen.
|
||||
st.off = msg
|
||||
local msg = L()._say(err)
|
||||
if REFUSALS[reason] then
|
||||
-- It stays refused until something is changed: said once, and typing asks no more.
|
||||
st.off = msg .. (HINTS[reason] and (" (" .. HINTS[reason] .. ")") or "")
|
||||
st.why = st.off
|
||||
if manual or not st.said then
|
||||
st.said = true
|
||||
vim.notify("LLeMbas: no suggestions: " .. st.off .. " (:LLeMbasAutocompleteModel chooses a model)", vim.log.levels.WARN)
|
||||
say("no suggestions: " .. st.off, manual)
|
||||
end
|
||||
else
|
||||
-- Transient server failure: pause briefly instead of shutting off permanently.
|
||||
-- Anything else may pass (the server is busy, or away): typing asks again in a while.
|
||||
st.wait_until = vim.uv.now() + 15000
|
||||
if manual then vim.notify("LLeMbas: " .. msg, vim.log.levels.WARN) end
|
||||
st.why = msg
|
||||
if manual then say("no suggestion: " .. msg, true) end
|
||||
end
|
||||
return
|
||||
end
|
||||
st.why = nil
|
||||
if manual and st.off then st.off, st.said = nil, false end
|
||||
if not r or r.cancelled or type(r.text) ~= "string" or r.text == "" then return end
|
||||
if vim.api.nvim_get_current_buf() ~= buf or not M._typing() then return end
|
||||
local now = vim.api.nvim_win_get_cursor(0)
|
||||
if now[1] - 1 ~= row or now[2] ~= col then return end
|
||||
show(buf, row, col, (r.text:gsub("\r\n", "\n")))
|
||||
end)
|
||||
end, 60000)
|
||||
end, not manual)
|
||||
end
|
||||
|
||||
@@ -279,14 +346,23 @@ function M.auto(on)
|
||||
end
|
||||
|
||||
--- A model or token/instruction setting was chosen: ask again.
|
||||
function M.reset() st.off, st.said, st.last_warm, st.wait_until = nil, false, nil, nil end
|
||||
function M.reset() st.off, st.said, st.said_start, st.last_warm, st.wait_until, st.why = nil, false, false, nil, nil, nil end
|
||||
|
||||
--- Why no suggestion came last time, or nil.
|
||||
function M.why() return st.why end
|
||||
|
||||
local function typed()
|
||||
M.clear()
|
||||
local c = L().config.complete
|
||||
if not c.auto or st.off or (st.wait_until and vim.uv.now() < st.wait_until) then return cancel() end
|
||||
if not usable(vim.api.nvim_get_current_buf()) then return end
|
||||
if not c.auto or st.off or L()._state.ai == false or (st.wait_until and vim.uv.now() < st.wait_until) then return cancel() end
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
if not usable(buf) then return end
|
||||
cancel()
|
||||
-- A file that is never sent asks for nothing; that is said once, when typing in it begins.
|
||||
if M.private(buf) then
|
||||
if not st.said_private[buf] then M.request(false) end
|
||||
return
|
||||
end
|
||||
st.timer = st.timer or vim.uv.new_timer()
|
||||
st.timer:start(c.debounce_ms, 0, vim.schedule_wrap(function()
|
||||
if M._typing() then M.request(false) end
|
||||
|
||||
@@ -85,6 +85,10 @@ function M.editor(buf, first, last)
|
||||
end
|
||||
end
|
||||
if #diags > 0 then out.diagnostics = diags end
|
||||
-- The other open files, by name: only files of this project, never one that looks like it
|
||||
-- holds secrets or that the project's .gitignore leaves out (|llembas-privacy|).
|
||||
local private = require("llembas.private")
|
||||
local roots = private.roots()
|
||||
local open = {}
|
||||
local seen = {}
|
||||
if name then seen[name] = true end
|
||||
@@ -92,7 +96,7 @@ function M.editor(buf, first, last)
|
||||
if #open >= 30 then break end
|
||||
if b ~= buf and vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then
|
||||
local p = vim.api.nvim_buf_get_name(b)
|
||||
if p ~= "" and not seen[p] then
|
||||
if p ~= "" and not seen[p] and private.may_send(p, roots) then
|
||||
seen[p] = true
|
||||
open[#open + 1] = p
|
||||
end
|
||||
@@ -115,43 +119,110 @@ function M.buffer_of(path)
|
||||
end
|
||||
end
|
||||
|
||||
--- A buffer's text as it would be saved: its lines with the file's line ends, and a last line
|
||||
--- break when the file has one.
|
||||
local function buffer_text(buf)
|
||||
local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
|
||||
if #lines == 1 and lines[1] == "" then return "" end
|
||||
local nl = vim.bo[buf].fileformat == "dos" and "\r\n" or "\n"
|
||||
return table.concat(lines, nl) .. ((vim.bo[buf].eol or vim.bo[buf].fixeol) and nl or "")
|
||||
end
|
||||
|
||||
-- What the agent wrote last into a buffer, and the buffer's change count right after: while the
|
||||
-- buffer has not changed since, the agent is given back exactly the text it wrote. It compares
|
||||
-- texts to know whether a file changed behind it, and a buffer never holds a text quite as it
|
||||
-- was written (line ends are the file's, the last line break is the editor's).
|
||||
local written = {} -- buf -> { tick, content }
|
||||
|
||||
--- Whether `text` is UTF-8 text: no NUL, and no byte that is not part of a character.
|
||||
local function valid_utf8(text)
|
||||
local i, n = 1, #text
|
||||
while i <= n do
|
||||
i = text:find("[%z\128-\255]", i)
|
||||
if not i then return true end
|
||||
local c = text:byte(i)
|
||||
local more = (c >= 0xC2 and c <= 0xDF) and 1 or (c >= 0xE0 and c <= 0xEF) and 2 or (c >= 0xF0 and c <= 0xF4) and 3 or nil
|
||||
if not more or i + more > n then return false end
|
||||
for k = 1, more do
|
||||
local b = text:byte(i + k)
|
||||
if b < 0x80 or b > 0xBF then return false end
|
||||
end
|
||||
i = i + more + 1
|
||||
end
|
||||
return true
|
||||
end
|
||||
M._valid_utf8 = valid_utf8
|
||||
|
||||
--- The agent writes a file (ACP `fs/write_text_file`): one that is open here gets the text in its
|
||||
--- buffer and is saved at once, so the buffer and the disk agree when the agent is answered. A file
|
||||
--- that is not open is refused, and the agent writes the disk itself.
|
||||
--- buffer and is saved at once, so the buffer and the disk agree when the agent is answered; one
|
||||
--- that is not open is written to the disk. Either way the text is the file's content before the
|
||||
--- answer, as ACP asks -- an editor that answers reads must take writes too, or the agent could
|
||||
--- never change a file it has read here.
|
||||
function M.write_for_agent(params, reply)
|
||||
local path, content = params.path, params.content
|
||||
if type(path) ~= "string" or type(content) ~= "string" then return reply(nil, { code = -32602, message = "no path or no text" }) end
|
||||
if type(path) ~= "string" or type(content) ~= "string" or not path:match("^/") then
|
||||
return reply(nil, { code = -32602, message = "an absolute path and the content are needed" })
|
||||
end
|
||||
local buf = M.buffer_of(path)
|
||||
if not buf then return reply(nil, { code = -32002, message = "not open in the editor" }) end
|
||||
if not buf then
|
||||
local dir = vim.fs.dirname(path)
|
||||
if vim.fn.isdirectory(dir) == 0 and not pcall(vim.fn.mkdir, dir, "p") then
|
||||
return reply(nil, { code = -32002, message = "the editor could not make the folder " .. dir })
|
||||
end
|
||||
local f, err = io.open(path, "wb")
|
||||
if not f then return reply(nil, { code = -32002, message = "the editor could not write it: " .. tostring(err) }) end
|
||||
f:write(content)
|
||||
f:close()
|
||||
return reply(vim.NIL)
|
||||
end
|
||||
if not vim.bo[buf].modifiable or vim.bo[buf].readonly then
|
||||
return reply(nil, { code = -32002, message = "the editor holds that file read-only" })
|
||||
end
|
||||
local lines = vim.split((content:gsub("\r\n", "\n")), "\n", { plain = true })
|
||||
if lines[#lines] == "" and #lines > 1 then table.remove(lines) end
|
||||
local ends = lines[#lines] == ""
|
||||
if ends and #lines > 1 then table.remove(lines) end
|
||||
vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
|
||||
-- Saved as it is: no autocommand (a formatter) may change what the agent believes it wrote.
|
||||
local ok, err = pcall(vim.api.nvim_buf_call, buf, function() vim.cmd("silent noautocmd write!") end)
|
||||
if not ok then return reply(nil, { code = -32002, message = "the editor could not save it: " .. tostring(err) }) end
|
||||
written[buf] = { tick = vim.api.nvim_buf_get_changedtick(buf), content = content }
|
||||
reply(vim.NIL)
|
||||
end
|
||||
|
||||
--- The agent asks for a file's text (ACP `fs/read_text_file`): a file open here is answered from its
|
||||
--- buffer, saved or not, so the agent sees what you see. Anything else is read from disk.
|
||||
--- buffer, saved or not, so the agent sees what you see. Anything else is read from disk, byte for
|
||||
--- byte. A file that is not text is refused, and the agent reads the disk itself.
|
||||
function M.read_for_agent(params, reply)
|
||||
local path = params.path
|
||||
if type(path) ~= "string" or path == "" then return reply(nil, { code = -32602, message = "no path" }) end
|
||||
local lines
|
||||
local text
|
||||
local buf = M.buffer_of(path)
|
||||
if buf then
|
||||
lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
|
||||
local w = written[buf]
|
||||
if w and w.tick == vim.api.nvim_buf_get_changedtick(buf) then text = w.content
|
||||
else
|
||||
written[buf] = nil
|
||||
text = buffer_text(buf)
|
||||
end
|
||||
else
|
||||
local ok, read = pcall(vim.fn.readfile, path)
|
||||
if not ok then return reply(nil, { code = -32002, message = "cannot read " .. path }) end
|
||||
lines = read
|
||||
local f = io.open(path, "rb")
|
||||
if not f then return reply(nil, { code = -32002, message = "cannot read " .. path }) end
|
||||
text = f:read("*a") or ""
|
||||
f:close()
|
||||
if not valid_utf8(text) then return reply(nil, { code = -32002, message = "not a text file: " .. path }) end
|
||||
end
|
||||
local first = math.max(1, tonumber(params.line) or 1)
|
||||
local last = params.limit and (first + tonumber(params.limit) - 1) or #lines
|
||||
reply({ content = table.concat(vim.list_slice(lines, first, last), "\n") })
|
||||
if params.line or params.limit then
|
||||
local lines = vim.split(text, "\n", { plain = true })
|
||||
local first = math.max(1, tonumber(params.line) or 1)
|
||||
local last = tonumber(params.limit) and (first + tonumber(params.limit) - 1) or #lines
|
||||
text = table.concat(vim.list_slice(lines, first, last), "\n")
|
||||
end
|
||||
reply({ content = text })
|
||||
end
|
||||
|
||||
vim.api.nvim_create_autocmd({ "BufWipeout", "BufUnload" }, {
|
||||
group = vim.api.nvim_create_augroup("llembas-context", { clear = true }),
|
||||
callback = function(ev) written[ev.buf] = nil end,
|
||||
})
|
||||
|
||||
return M
|
||||
+22
-12
@@ -29,6 +29,7 @@ local function drop(buf, hunk)
|
||||
if #list == 0 then
|
||||
proposals[buf] = nil
|
||||
unmap(buf)
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
end
|
||||
end
|
||||
|
||||
@@ -169,9 +170,12 @@ function M.propose(buf, first, last, new)
|
||||
virt_lines = virt(lines), virt_lines_above = hunk.above, right_gravity = false })
|
||||
end
|
||||
if i == 1 and hint_row then
|
||||
-- The keys as the key table has them, in the form that arrives in this terminal.
|
||||
local K = require("llembas.keys")
|
||||
local function key(id) return K.shown(K.by_id[id]) end
|
||||
local label = #hunks > 1
|
||||
and (" ◈ LLeMbas (%d changes): ga accept · gr reject · gA/gR all · ]h/[h jump"):format(#hunks)
|
||||
or " ◈ LLeMbas: ga accept · gr reject"
|
||||
and (" ◈ LLeMbas (%d changes): %s accept · %s reject · %s all · %s next"):format(#hunks, key("accept"), key("reject"), key("accept_all"), key("next_change"))
|
||||
or (" ◈ LLeMbas: %s accept · %s reject"):format(key("accept"), key("reject"))
|
||||
hunk.hint = vim.api.nvim_buf_set_extmark(buf, ns, hint_row, 0, {
|
||||
virt_text = { { label, "LLeMbasDiffHint" } },
|
||||
virt_text_pos = "eol",
|
||||
@@ -186,13 +190,16 @@ function M.propose(buf, first, last, new)
|
||||
if next(before) and before.buffer == 1 then table.insert(saved[buf], before) end
|
||||
end
|
||||
end
|
||||
local function map(k, fn, desc) vim.keymap.set("n", k, fn, { buffer = buf, desc = desc, nowait = true }) end
|
||||
map("ga", function() M.accept(false) end, "LLeMbas: accept this change")
|
||||
map("gr", function() M.reject(false) end, "LLeMbas: reject this change")
|
||||
map("gA", function() M.accept(true) end, "LLeMbas: accept all changes")
|
||||
map("gR", function() M.reject(true) end, "LLeMbas: reject all changes")
|
||||
map("]h", function() M.next_hunk() end, "LLeMbas: next proposed change")
|
||||
map("[h", function() M.prev_hunk() end, "LLeMbas: previous proposed change")
|
||||
-- The buffer's own keys while changes are shown: the key table's (scope "change").
|
||||
require("llembas.keys").bind("change", buf, {
|
||||
accept = function() M.accept(false) end,
|
||||
reject = function() M.reject(false) end,
|
||||
accept_all = function() M.accept(true) end,
|
||||
reject_all = function() M.reject(true) end,
|
||||
next_change = function() M.next_hunk() end,
|
||||
prev_change = function() M.prev_hunk() end,
|
||||
})
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
return #hunks
|
||||
end
|
||||
|
||||
@@ -244,19 +251,22 @@ local function run_edit(buf, first, last, instruction, verb)
|
||||
if not conn then
|
||||
rewriting[buf] = nil
|
||||
written_by_id[id] = nil
|
||||
return vim.notify("LLeMbas: the agent did not start", vim.log.levels.ERROR)
|
||||
vim.api.nvim_echo({ { "" } }, false, {})
|
||||
return vim.notify("LLeMbas: " .. (L._state.start_error or "the agent did not start"), vim.log.levels.ERROR)
|
||||
end
|
||||
local body_text = table.concat(text, "\n")
|
||||
if body_text == "" then body_text = " " end
|
||||
conn:request("_lembas/edit", {
|
||||
id = id, cwd = vim.fn.getcwd(), sessionId = L._state.session, path = name ~= "" and name or nil,
|
||||
text = body_text, before = table.concat(before, "\n"), after = table.concat(after, "\n"),
|
||||
language = vim.bo[buf].filetype, instruction = instruction, model = L.config.model,
|
||||
language = vim.bo[buf].filetype ~= "" and vim.bo[buf].filetype or nil, instruction = instruction,
|
||||
-- With a session its model writes; without one, the model a session here would start on.
|
||||
model = (not L._state.session) and L.config.model or nil,
|
||||
}, function(err, r)
|
||||
if rewriting[buf] == id then rewriting[buf] = nil end
|
||||
written_by_id[id] = nil
|
||||
vim.api.nvim_echo({ { "" } }, false, {})
|
||||
if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end
|
||||
if err then return vim.notify("LLeMbas: " .. L._say(err), vim.log.levels.ERROR) end
|
||||
if not r or r.cancelled or not vim.api.nvim_buf_is_valid(buf) then return end
|
||||
if vim.api.nvim_buf_get_changedtick(buf) ~= tick then
|
||||
return vim.notify("LLeMbas: the buffer changed while the rewrite was written; nothing is shown. Ask again.", vim.log.levels.WARN)
|
||||
|
||||
+1066
-213
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,330 @@
|
||||
-- Every key of LLeMbas, in one table. The mappings are made from it, the bottom bar shows the keys
|
||||
-- of the bar that has the focus from it, and the help and a distribution's cheat sheet read it:
|
||||
-- a key the bar shows is a key that is bound.
|
||||
--
|
||||
-- Each action has two forms. The chord is the LLeMbas terminal's (Ctrl+Shift+A …) and reaches
|
||||
-- Neovim only from a terminal that reports such keys distinctly (the kitty keyboard protocol).
|
||||
-- The other form always arrives: a key after the prefix (<Leader>l by default), or a plain key
|
||||
-- inside one of the bars. Both are bound; the bar shows the one that works.
|
||||
local M = {}
|
||||
|
||||
local function L() return require("llembas") end
|
||||
local function layout() return require("llembas.layout") end
|
||||
local function diff() return require("llembas.diff") end
|
||||
|
||||
--- { id, chord, alt, modes, scope, label, desc, run, bar }
|
||||
--- chord the chord form, or nil. alt: the form that always arrives: "<Prefix>x" (global), or a
|
||||
--- plain key (in a bar's own buffer, or global when `scope` is nil). Either may be a list.
|
||||
--- modes where `alt` is mapped when it is global (default: normal). The chord is mapped in
|
||||
--- normal, visual and insert mode.
|
||||
--- scope nil: everywhere. Otherwise the bar whose buffer has the key: "tree", "settings",
|
||||
--- "prompt", "chat" (the transcript), "change" (a buffer with proposed changes),
|
||||
--- "suggestion" (while a suggestion is shown).
|
||||
--- bar where the bottom bar shows it, with its priority there (1 first; cut from the end):
|
||||
--- { code = 1 } or { tree = { 6, "code" } } to say another word there.
|
||||
--- show how the keys are written in the bar when that is not the key's own name.
|
||||
--- virtual a line of the bar that stands for keys bound elsewhere (two entries' keys in one, or
|
||||
--- Neovim's own arrows); `sheet = false` keeps it out of a cheat sheet that has the others.
|
||||
--- free needs no agent: a distribution's guard is not asked.
|
||||
M.table = {
|
||||
-- From the code to the chat, with what you are on.
|
||||
{ id = "ask", chord = "<C-S-A>", alt = "<Prefix>a", modes = { "n", "x" }, label = "ask",
|
||||
desc = "To the chat prompt; the selection, or else the cursor's line, comes along",
|
||||
run = function() L().prompt({ intent = "ask" }) end, bar = { code = 1, tree = 8, chat = 6 } },
|
||||
{ id = "rewrite", alt = "<Prefix>e", modes = { "n", "x" }, label = "rewrite",
|
||||
desc = "To the prompt, to have the selection or the line rewritten (shown as changes)",
|
||||
run = function() L().prompt({ intent = "rewrite" }) end },
|
||||
{ id = "add", alt = "<Prefix>g", modes = { "n", "x" }, label = "add",
|
||||
desc = "To the prompt, to have new code written at the cursor (shown as changes)",
|
||||
run = function() L().prompt({ intent = "add" }) end },
|
||||
{ id = "explain", alt = "<Prefix>x", modes = { "n", "x" }, label = "explain", range = true,
|
||||
desc = "Explain the line or the selection", run = function(first, last) L().explain(first, last) end },
|
||||
{ id = "fix", alt = "<Prefix>f", label = "fix", desc = "Fix this file's problems", run = function() L().fix() end },
|
||||
|
||||
-- Suggestions as you type.
|
||||
-- (Their keys are the plugin's settings `complete.accept` and `complete.accept_word`.)
|
||||
{ id = "suggestion_accept", alt = "<Tab>", scope = "suggestion", label = "accept suggestion", setting = "accept",
|
||||
desc = "Accept the suggestion (the grey text); without one, Neovim's own Tab", bar = { code = 2 } },
|
||||
{ id = "suggestion_word", alt = "<M-Right>", scope = "suggestion", label = "one word", setting = "accept_word",
|
||||
desc = "Accept one word of the suggestion", bar = { code = 3 } },
|
||||
{ id = "autocomplete", chord = "<C-M-a>", alt = "<Prefix>t", label = "autocomplete",
|
||||
desc = "Suggestions as you type, on and off", run = function() L().autocomplete() end },
|
||||
{ id = "autocomplete_model", chord = "<C-M-m>", alt = "<Prefix>C", label = "autocomplete model",
|
||||
desc = "Choose the model that writes suggestions", run = function() L().autocomplete_model() end },
|
||||
|
||||
-- The menu and the settings.
|
||||
{ id = "menu", chord = "<C-S-P>", alt = "<Prefix>p", label = "menu",
|
||||
desc = "The LLeMbas menu: every command and every setting", run = function() L().menu() end,
|
||||
bar = { code = 4, tree = 9, chat = 7, change = 6 } },
|
||||
{ id = "mode", chord = "<C-Tab>", alt = "<Prefix>m", label = "mode",
|
||||
desc = "Switch the mode", run = function() L().cycle_mode() end, bar = { prompt = 3 } },
|
||||
{ id = "model", chord = "<C-S-M>", alt = "<Prefix>M", label = "model",
|
||||
desc = "Choose the model", run = function() L().model() end, bar = { prompt = 4 } },
|
||||
{ id = "effort", alt = "<Prefix>E", label = "effort",
|
||||
desc = "Choose the effort", run = function() L().effort() end },
|
||||
{ id = "ai", chord = "<C-S-I>", alt = "<Prefix>I", label = "AI on/off", free = true,
|
||||
desc = "LLeMbas on and off (off: a plain editor, nothing is sent)", run = function() L().ai() end },
|
||||
{ id = "stop", chord = "<C-S-G>", alt = "<Prefix>.", label = "stop",
|
||||
desc = "Stop the running turn", run = function() L().stop() end, bar = { prompt = 6, chat = 5 } },
|
||||
|
||||
-- A proposed change.
|
||||
{ id = "accept", chord = "<C-S-Y>", alt = "ga", scope = "change", label = "accept",
|
||||
desc = "Accept the proposed change under the cursor", run = function() diff().accept(false) end, bar = { change = 1 } },
|
||||
{ id = "reject", chord = "<C-S-J>", alt = "gr", scope = "change", label = "reject",
|
||||
desc = "Reject the proposed change under the cursor", run = function() diff().reject(false) end, bar = { change = 2 } },
|
||||
{ id = "next_change", alt = "]h", scope = "change", label = "next",
|
||||
desc = "The next proposed change", run = function() diff().next_hunk() end, bar = { change = 3 } },
|
||||
{ id = "prev_change", alt = "[h", scope = "change", label = "previous",
|
||||
desc = "The previous proposed change", run = function() diff().prev_hunk() end, bar = { change = 5 } },
|
||||
{ id = "accept_all", chord = "<M-C-S-Y>", alt = "gA", scope = "change", label = "accept all",
|
||||
desc = "Accept every proposed change in the file", run = function() diff().accept(true) end, bar = { change = 4 } },
|
||||
{ id = "reject_all", alt = "gR", scope = "change", label = "reject all",
|
||||
desc = "Reject every proposed change in the file", run = function() diff().reject(true) end },
|
||||
|
||||
-- The bars.
|
||||
{ id = "tree", chord = "<C-S-E>", alt = "<Prefix>b", label = "tree", free = true,
|
||||
desc = "The file tree, show and hide", run = function() layout().toggle("tree") end, bar = { code = 6, tree = 10 } },
|
||||
{ id = "chat", chord = "<C-S-D>", alt = "<Prefix>l", label = "chat",
|
||||
desc = "The chat (the right bar), show and hide", run = function() layout().toggle("chat") end, bar = { code = 7, chat = 8 } },
|
||||
{ id = "left", alt = "<M-Left>", modes = { "n", "i" }, label = "bars", show = "Alt+←", free = true,
|
||||
desc = "To the bar on the left: chat, code, tree", run = function() layout().go(-1) end,
|
||||
bar = { chat = { 4, "code" }, settings = { 4, "code" } } },
|
||||
{ id = "right", alt = "<M-Right>", modes = { "n", "i" }, label = "bars", show = "Alt+→", free = true,
|
||||
desc = "To the bar on the right: tree, code, chat", run = function() layout().go(1) end,
|
||||
bar = { tree = { 6, "code" } } },
|
||||
{ id = "bars", alt = { "<M-Left>", "<M-Right>" }, virtual = true, sheet = false, label = "bars", show = "Alt+←→",
|
||||
desc = "Move between the tree, the code and the chat", bar = { code = 5 } },
|
||||
|
||||
-- Conversations.
|
||||
{ id = "sessions", alt = "<Prefix>s", label = "sessions", desc = "Earlier conversations", run = function() L().sessions() end },
|
||||
{ id = "new", alt = "<Prefix>n", label = "new", desc = "New conversation", run = function() L().new() end },
|
||||
{ id = "commands", alt = "<Prefix>c", label = "commands", desc = "Commands and skills", run = function() L().commands() end },
|
||||
{ id = "status", alt = "<Prefix>S", label = "status", free = true, desc = "Status", run = function() L().status_popup() end },
|
||||
{ id = "login", alt = "<Prefix>i", label = "sign in", free = true, desc = "Sign in", run = function() require("llembas.login").login() end },
|
||||
{ id = "help", alt = "<Prefix>?", label = "help", free = true, desc = "The plugin's commands and keys", run = function() L().help() end },
|
||||
|
||||
-- In the tree.
|
||||
{ id = "tree_open", alt = { "<CR>", "<Right>", "l" }, scope = "tree", label = "open", show = "Enter",
|
||||
desc = "Open the file; open or close the directory (→ opens, ← closes)", bar = { tree = 1 } },
|
||||
{ id = "tree_close", alt = { "<Left>", "h" }, scope = "tree", label = "close", desc = "Close the directory, or go to the one above" },
|
||||
{ id = "tree_new", alt = "a", scope = "tree", label = "new", desc = "New file, or directory with a / at the end", bar = { tree = 2 } },
|
||||
{ id = "tree_rename", alt = "r", scope = "tree", label = "rename", desc = "Rename or move", bar = { tree = 3 } },
|
||||
{ id = "tree_delete", alt = "d", scope = "tree", label = "delete", desc = "Delete, after asking (to the trash where there is one)", bar = { tree = 4 } },
|
||||
{ id = "tree_filter", alt = "/", scope = "tree", label = "filter", desc = "Filter by name as you type (empty: everything again)", bar = { tree = 5 } },
|
||||
{ id = "tree_hidden", alt = ".", scope = "tree", label = "hidden files", desc = "Hidden files, show and hide", bar = { tree = 7 } },
|
||||
{ id = "tree_refresh", alt = "R", scope = "tree", label = "refresh", desc = "Read the directory again" },
|
||||
|
||||
-- In the settings lines.
|
||||
{ id = "settings_change", alt = "<CR>", scope = "settings", label = "change", show = "Enter",
|
||||
desc = "Open the line's choices, or take the one under the cursor", bar = { settings = 1 } },
|
||||
{ id = "settings_move", alt = { "<Up>", "<Down>" }, virtual = true, scope = "settings", label = "move", show = "↑↓",
|
||||
desc = "Move between the lines and the choices", bar = { settings = 2 } },
|
||||
{ id = "settings_back", alt = "<Esc>", scope = "settings", label = "back", show = "Esc",
|
||||
desc = "Close the choices; from the lines, back to the code", bar = { settings = 3 } },
|
||||
|
||||
-- In the prompt.
|
||||
{ id = "send", alt = "<CR>", scope = "prompt", label = "send", show = "Enter",
|
||||
desc = "Send (while a turn runs: steer it)", bar = { prompt = 1 } },
|
||||
{ id = "intent", alt = "<Tab>", scope = "prompt", label = "ask/rewrite/add", show = "Tab",
|
||||
desc = "In an empty prompt: what Enter will do — ask, rewrite, add", bar = { prompt = 2 } },
|
||||
{ id = "newline", alt = "<C-j>", scope = "prompt", label = "new line", desc = "A new line in the prompt" },
|
||||
{ id = "back", alt = "<Esc>", scope = "prompt", label = "back to code", show = "Esc",
|
||||
desc = "Back to the code", bar = { prompt = 5 } },
|
||||
|
||||
-- In the transcript.
|
||||
{ id = "chat_open", alt = "<CR>", scope = "chat", label = "open file", show = "Enter",
|
||||
desc = "Open the file:line under the cursor", bar = { chat = 1 } },
|
||||
{ id = "chat_output", alt = "K", scope = "chat", label = "tool output", desc = "What the tool on this line printed", bar = { chat = 2 } },
|
||||
{ id = "chat_prompt", alt = "i", scope = "chat", label = "prompt", desc = "To the prompt", bar = { chat = 3 } },
|
||||
}
|
||||
|
||||
M.by_id = {}
|
||||
for _, k in ipairs(M.table) do M.by_id[k.id] = k end
|
||||
|
||||
local state = { set = false, prefix = "<Leader>l", guard = nil, seen = false, bound = {} }
|
||||
|
||||
local function list(v) return type(v) == "table" and v or (v and { v } or {}) end
|
||||
|
||||
--- The keys of an entry that always arrive, as a list: the table's, or the setting's it names.
|
||||
function M.alts(entry)
|
||||
if entry.setting then
|
||||
local set = (L().config.complete or {})[entry.setting]
|
||||
return (type(set) == "string" and set ~= "") and { set } or {}
|
||||
end
|
||||
return list(entry.alt)
|
||||
end
|
||||
|
||||
--- The prefix of the keys that always arrive.
|
||||
function M.prefix() return state.prefix end
|
||||
|
||||
--- `alt` of an entry as it is mapped: the prefix written out.
|
||||
function M.lhs(alt) return (alt:gsub("<Prefix>", state.prefix)) end
|
||||
|
||||
--- Where the terminal says what it is: the name the chords are remembered under.
|
||||
local function terminal_id()
|
||||
local e = vim.env
|
||||
if e.LLEMBAS_TERM or e.LLEMBAS_TTY then return "llembas" end
|
||||
if e.TMUX then return "tmux:" .. (e.TERM or "") end
|
||||
return (e.TERM_PROGRAM and e.TERM_PROGRAM ~= "" and e.TERM_PROGRAM) or e.TERM or ""
|
||||
end
|
||||
|
||||
--- Whether a terminal known to report the chords is in front: by what it says of itself.
|
||||
local function terminal_reports()
|
||||
local e = vim.env
|
||||
-- The LLeMbas terminal hands its own chords through while this editor is in front.
|
||||
if e.LLEMBAS_TERM or e.LLEMBAS_TTY then return true end
|
||||
-- A multiplexer in between takes the protocol away unless it is set up to pass it on.
|
||||
if e.TMUX or e.STY or e.ZELLIJ then return false end
|
||||
if e.KITTY_WINDOW_ID or e.GHOSTTY_RESOURCES_DIR then return true end
|
||||
local term, program = e.TERM or "", (e.TERM_PROGRAM or ""):lower()
|
||||
if term:find("kitty", 1, true) or term:find("ghostty", 1, true) or term:match("^foot") then return true end
|
||||
if program == "ghostty" or program == "rio" then return true end
|
||||
return false
|
||||
end
|
||||
|
||||
--- Whether the chords arrive, so that the bar shows them: as set (`keys.chords`), else as seen —
|
||||
--- a chord that fired in this terminal proves it, and is remembered — else as the terminal says
|
||||
--- of itself.
|
||||
function M.chords()
|
||||
local set = type(L().config.keys) == "table" and L().config.keys.chords or nil
|
||||
if set == true or set == false then return set end
|
||||
if state.seen then return true end
|
||||
if require("llembas.store").terminal(terminal_id()) then return true end
|
||||
return terminal_reports()
|
||||
end
|
||||
|
||||
--- A chord arrived: this terminal reports them.
|
||||
function M.saw_chord()
|
||||
if state.seen then return end
|
||||
state.seen = true
|
||||
pcall(function() require("llembas.store").saw_terminal(terminal_id()) end)
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
end
|
||||
|
||||
M._terminal_id, M._terminal_reports = terminal_id, terminal_reports
|
||||
function M._forget_seen() state.seen = false end
|
||||
|
||||
local NAMES = {
|
||||
["<CR>"] = "Enter", ["<Esc>"] = "Esc", ["<Tab>"] = "Tab", ["<Up>"] = "↑", ["<Down>"] = "↓",
|
||||
["<Left>"] = "←", ["<Right>"] = "→", ["<Space>"] = "Space",
|
||||
}
|
||||
|
||||
--- A key as the bar writes it: <C-S-A> is ^⇧A, <M-C-S-Y> is Alt+^⇧Y, <Leader>la is "Spc la".
|
||||
function M.written(lhs)
|
||||
lhs = M.lhs(lhs)
|
||||
if NAMES[lhs] then return NAMES[lhs] end
|
||||
local leader = vim.g.mapleader == nil and "\\" or vim.g.mapleader
|
||||
local rest = lhs:match("^<[Ll]eader>(.+)$")
|
||||
if rest then return (leader == " " and "Spc " or leader) .. rest end
|
||||
local mods, key = lhs:match("^<([CMSAD%-]-)%-?([^%-<>]+)>$")
|
||||
if mods and mods ~= "" then
|
||||
local out = ""
|
||||
if mods:find("[MA]") then out = out .. "Alt+" end
|
||||
if mods:find("C") then out = out .. "^" end
|
||||
if mods:find("S") then out = out .. "⇧" end
|
||||
key = NAMES["<" .. key .. ">"] or (#key == 1 and key:upper() or key)
|
||||
return out .. key
|
||||
end
|
||||
return lhs
|
||||
end
|
||||
|
||||
--- An entry's keys for the bar: the chord when chords arrive and it has one, else the other form.
|
||||
function M.shown(entry, chords)
|
||||
if chords == nil then chords = M.chords() end
|
||||
if chords and entry.chord then return M.written(list(entry.chord)[1]) end
|
||||
if entry.show then return entry.show end
|
||||
local alts = M.alts(entry)
|
||||
if #alts == 0 then return entry.chord and M.written(list(entry.chord)[1]) or "" end
|
||||
return M.written(alts[1])
|
||||
end
|
||||
|
||||
--- The keys the bottom bar shows where the focus is `where`, most needed first:
|
||||
--- a list of { keys, label, id }.
|
||||
function M.for_bar(where, chords)
|
||||
if chords == nil then chords = M.chords() end
|
||||
local out = {}
|
||||
for _, k in ipairs(M.table) do
|
||||
local at = k.bar and k.bar[where]
|
||||
if at then
|
||||
local prio, label = at, k.label
|
||||
if type(at) == "table" then prio, label = at[1], at[2] end
|
||||
out[#out + 1] = { keys = M.shown(k, chords), label = label, id = k.id, prio = prio }
|
||||
end
|
||||
end
|
||||
table.sort(out, function(a, b) return a.prio < b.prio end)
|
||||
return out
|
||||
end
|
||||
|
||||
--- The rows of a cheat sheet: { id, chord, alt, where, desc } with the keys as Neovim writes them.
|
||||
function M.rows()
|
||||
local out = {}
|
||||
for _, k in ipairs(M.table) do
|
||||
local alts = {}
|
||||
for _, a in ipairs(M.alts(k)) do alts[#alts + 1] = M.lhs(a) end
|
||||
if k.sheet ~= false then out[#out + 1] = {
|
||||
id = k.id, chord = list(k.chord)[1], alt = table.concat(alts, " "),
|
||||
where = k.scope or "everywhere", desc = k.desc, modes = k.modes or { "n" },
|
||||
} end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
local function run(entry, by_chord)
|
||||
return function()
|
||||
if by_chord then M.saw_chord() end
|
||||
if state.guard and not entry.free and state.guard(entry) == false then return end
|
||||
if entry.range then
|
||||
-- The selection's lines, or the cursor's.
|
||||
local first, last = vim.fn.line("v"), vim.fn.line(".")
|
||||
if not vim.api.nvim_get_mode().mode:match("^[vV\22]") then first = last end
|
||||
if first > last then first, last = last, first end
|
||||
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "nx", false)
|
||||
return entry.run(first, last)
|
||||
end
|
||||
return entry.run()
|
||||
end
|
||||
end
|
||||
|
||||
--- Map the keys of the bar `scope` in its buffer, each to `handlers[id]`. The table says which
|
||||
--- keys; the bar's own module says what they do there.
|
||||
function M.bind(scope, buf, handlers, modes)
|
||||
for _, k in ipairs(M.table) do
|
||||
if k.scope == scope and not k.virtual and handlers[k.id] then
|
||||
for _, lhs in ipairs(list(k.alt)) do
|
||||
vim.keymap.set(modes and modes[k.id] or "n", lhs, handlers[k.id], { buffer = buf, nowait = true, silent = true, desc = "LLeMbas: " .. k.desc })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- The keys that are mapped everywhere: every chord, and every other form that is not a bar's own.
|
||||
--- `opts`: `{ prefix = "<Leader>l", guard = function(entry) … end }`; a guard that returns false
|
||||
--- stops the action (a distribution uses it to say what is missing).
|
||||
function M.setup(opts)
|
||||
opts = opts or {}
|
||||
M.clear()
|
||||
state.prefix = type(opts.prefix) == "string" and opts.prefix ~= "" and opts.prefix or "<Leader>l"
|
||||
state.guard = opts.guard
|
||||
state.set = true
|
||||
local function map(modes, lhs, entry, by_chord)
|
||||
vim.keymap.set(modes, lhs, run(entry, by_chord), { silent = true, desc = "LLeMbas: " .. entry.desc })
|
||||
for _, m in ipairs(list(modes)) do state.bound[#state.bound + 1] = { m, lhs } end
|
||||
end
|
||||
for _, k in ipairs(M.table) do
|
||||
if k.run then
|
||||
for _, lhs in ipairs(list(k.chord)) do map({ "n", "x", "i" }, lhs, k, true) end
|
||||
if not k.scope then
|
||||
for _, lhs in ipairs(list(k.alt)) do map(k.modes or "n", M.lhs(lhs), k, false) end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function M.clear()
|
||||
for _, b in ipairs(state.bound) do pcall(vim.keymap.del, b[1], b[2]) end
|
||||
state.bound, state.set = {}, false
|
||||
end
|
||||
|
||||
function M.is_set() return state.set end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,624 @@
|
||||
-- The four bars: the top bar (what LLeMbas is doing, the conversation, the settings), the bottom
|
||||
-- bar (the keys for where the focus is, and Neovim's own state), the tree on the left, and on the
|
||||
-- right the settings lines over the chat over the prompt. Each can be switched off; the side bars
|
||||
-- fold away by themselves when the code would get too narrow.
|
||||
--
|
||||
-- Every row is laid out from widths that are known: a cell has a fixed width, or it is the one
|
||||
-- cell that takes what is left and is cut with an ellipsis. Nothing lines up by the length of a text.
|
||||
local M = {}
|
||||
|
||||
local function L() return require("llembas") end
|
||||
local function tree() return require("llembas.tree") end
|
||||
local function chat() return require("llembas.chat") end
|
||||
local function lines() return require("llembas.lines") end
|
||||
local function keys() return require("llembas.keys") end
|
||||
local function store() return require("llembas.store") end
|
||||
|
||||
M.defaults = {
|
||||
top = true, -- the top bar (the tabline)
|
||||
bottom = true, -- the bottom bar (the statusline)
|
||||
tree = true, -- the file tree, open
|
||||
chat = true, -- the right bar, open
|
||||
tree_width = 26,
|
||||
chat_width = 42, -- kept between 34 and 50
|
||||
prompt_height = 3,
|
||||
min_code = 60, -- the side bars fold when the code would be narrower: the chat first, then the tree
|
||||
}
|
||||
|
||||
local Y = {
|
||||
on = false, prefs = vim.deepcopy(M.defaults), folded = { tree = false, chat = false }, forced = {},
|
||||
code = nil, saved = {}, shape = nil, announced = false, applying = false,
|
||||
}
|
||||
|
||||
-- ── text in cells ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
local function width_of(text) return vim.fn.strdisplaywidth(text) end
|
||||
|
||||
--- `text` in exactly `width` cells: cut with an ellipsis when longer, padded when shorter.
|
||||
function M.cell(text, width, right)
|
||||
text = (tostring(text or ""):gsub("[%c]+", " "))
|
||||
if width <= 0 then return "" end
|
||||
local w = width_of(text)
|
||||
if w > width then
|
||||
local out = ""
|
||||
for i = 0, vim.fn.strchars(text) - 1 do
|
||||
local ch = vim.fn.strcharpart(text, i, 1)
|
||||
if width_of(out .. ch) > width - 1 then break end
|
||||
out = out .. ch
|
||||
end
|
||||
text = out .. "…"
|
||||
w = width_of(text)
|
||||
end
|
||||
local pad = (" "):rep(width - w)
|
||||
return right and (pad .. text) or (text .. pad)
|
||||
end
|
||||
|
||||
--- Lay `cells` out in `width` columns. A cell is `{ text, width = n }` or `{ text, flex = true,
|
||||
--- min = n }` (one at most), with `prio` (1 stays longest; the highest number goes first when it
|
||||
--- does not fit) and `hl`. Between cells stands `sep`. Returns the cells that fit, each with its
|
||||
--- final `text`, and the row as plain text, which is exactly `width` cells wide.
|
||||
function M.fit(cells, width, sep)
|
||||
sep = sep or " │ "
|
||||
local sw = width_of(sep)
|
||||
local kept = {}
|
||||
for _, c in ipairs(cells) do kept[#kept + 1] = c end
|
||||
local function need()
|
||||
local n = 2 + math.max(#kept - 1, 0) * sw
|
||||
for _, c in ipairs(kept) do n = n + (c.flex and (c.min or 0) or c.width) end
|
||||
return n
|
||||
end
|
||||
while #kept > 1 and need() > width do
|
||||
local worst = 1
|
||||
for i, c in ipairs(kept) do if (c.prio or 1) > (kept[worst].prio or 1) then worst = i end end
|
||||
table.remove(kept, worst)
|
||||
end
|
||||
local left = width - need()
|
||||
local out, plain = {}, " "
|
||||
for i, c in ipairs(kept) do
|
||||
local w = c.flex and ((c.min or 0) + math.max(left, 0)) or c.width
|
||||
if not c.flex and #kept == 1 then w = math.min(w, math.max(width - 2, 0)) end
|
||||
local text = M.cell(c.text, w, c.right)
|
||||
out[#out + 1] = { text = text, hl = c.hl, id = c.id }
|
||||
plain = plain .. text .. (i < #kept and sep or "")
|
||||
end
|
||||
-- No flexible cell among those kept: what is left stays empty at the end.
|
||||
plain = M.cell(plain .. " ", width)
|
||||
return out, plain
|
||||
end
|
||||
|
||||
local function esc(text) return (text:gsub("%%", "%%%%")) end
|
||||
|
||||
local function line_of(cells, width, sep, sep_hl, base_hl)
|
||||
local parts = { "%#" .. base_hl .. "# " }
|
||||
for i, c in ipairs(cells) do
|
||||
parts[#parts + 1] = "%#" .. (c.hl or base_hl) .. "#" .. esc(c.text)
|
||||
if i < #cells then parts[#parts + 1] = "%#" .. sep_hl .. "#" .. esc(sep) end
|
||||
end
|
||||
parts[#parts + 1] = "%#" .. base_hl .. "#"
|
||||
local used = 1
|
||||
for i, c in ipairs(cells) do used = used + width_of(c.text) + (i < #cells and width_of(sep) or 0) end
|
||||
parts[#parts + 1] = (" "):rep(math.max(width - used, 0))
|
||||
return table.concat(parts)
|
||||
end
|
||||
|
||||
-- ── the top bar ────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
local STATE = {
|
||||
idle = { "idle", "idle", "LLeMbasBarIdle" },
|
||||
thinking = { "thinking", "think", "LLeMbasBarBusy" },
|
||||
tools = { "tools", "tools", "LLeMbasBarBusy" },
|
||||
writing = { "writing", "write", "LLeMbasBarBusy" },
|
||||
waiting = { "waiting for you", "waiting", "LLeMbasBarWaiting" },
|
||||
starting = { "starting", "start", "LLeMbasBarBusy" },
|
||||
signed_out = { "not signed in", "sign in", "LLeMbasBarOff" },
|
||||
no_cli = { "no CLI", "no CLI", "LLeMbasBarOff" },
|
||||
off = { "AI off", "AI off", "LLeMbasBarOff" },
|
||||
}
|
||||
M.STATE_WIDTH, M.STATE_WIDTH_NARROW = 17, 9
|
||||
|
||||
local function short_model(ref)
|
||||
if type(ref) ~= "string" or ref == "" then return "—" end
|
||||
return ref:match("[^/]+$") or ref
|
||||
end
|
||||
|
||||
local function diagnostics()
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
local ok, count = pcall(vim.diagnostic.count, buf)
|
||||
if not ok or type(count) ~= "table" then return "" end
|
||||
local e, w = count[vim.diagnostic.severity.ERROR] or 0, count[vim.diagnostic.severity.WARN] or 0
|
||||
if e == 0 and w == 0 then return "" end
|
||||
return ("E%d W%d"):format(math.min(e, 99), math.min(w, 99))
|
||||
end
|
||||
|
||||
local function branch()
|
||||
local b = tree().branch()
|
||||
if b and b ~= "" then return b end
|
||||
local s = vim.b.minigit_summary
|
||||
if type(s) == "table" and type(s.head_name) == "string" then return s.head_name end
|
||||
return type(vim.b.gitsigns_head) == "string" and vim.b.gitsigns_head or ""
|
||||
end
|
||||
|
||||
--- The cells of the top bar for `width` columns.
|
||||
function M.top_cells(width)
|
||||
local s = L().settings()
|
||||
local narrow = width < 100
|
||||
local st = STATE[s.state] or STATE.idle
|
||||
local busy = s.state == "thinking" or s.state == "tools" or s.state == "writing" or s.state == "starting"
|
||||
local sw = narrow and M.STATE_WIDTH_NARROW or M.STATE_WIDTH
|
||||
local model_room = narrow and 10 or 16
|
||||
local rest = " · " .. (s.mode or "—") .. " · " .. (s.effort or "—")
|
||||
local model = short_model(s.model)
|
||||
if width_of(model) > model_room then model = M.cell(model, model_room) end
|
||||
local cells = {
|
||||
{ id = "state", text = (busy and "◐ " or "● ") .. (narrow and st[2] or st[1]), width = sw, prio = 1, hl = st[3] },
|
||||
{ id = "title", text = (s.title and s.title ~= "") and s.title or (s.session and "conversation" or "no conversation yet"),
|
||||
flex = true, min = 8, prio = 3, hl = "LLeMbasBarTitle" },
|
||||
{ id = "settings", text = model .. rest, width = model_room + 16, prio = 2, hl = "LLeMbasBar" },
|
||||
{ id = "context", text = s.context and ("ctx %d%%"):format(s.context) or "ctx —", width = 8, prio = 5, hl = "LLeMbasBar" },
|
||||
{ id = "autocomplete", text = "AC " .. (s.autocomplete and "on" or "off"), width = 6, prio = 4,
|
||||
hl = s.autocomplete and "LLeMbasBar" or "LLeMbasBarOff" },
|
||||
}
|
||||
-- Tab pages have no line of their own under this bar: which one this is, when there are several.
|
||||
local tabs = #vim.api.nvim_list_tabpages()
|
||||
if tabs > 1 then
|
||||
cells[#cells + 1] = { id = "tabs", text = ("tab %d/%d"):format(vim.api.nvim_tabpage_get_number(0), tabs), width = 9, prio = 4, hl = "LLeMbasBarFact" }
|
||||
cells[5].prio = 5
|
||||
cells[4].prio = 6
|
||||
end
|
||||
local b, d = branch(), diagnostics()
|
||||
if b ~= "" then cells[#cells + 1] = { id = "branch", text = b, width = 14, prio = 9, hl = "LLeMbasBarFact" } end
|
||||
if d ~= "" then cells[#cells + 1] = { id = "problems", text = d, width = 7, prio = 8, hl = "LLeMbasBarFact" } end
|
||||
return cells
|
||||
end
|
||||
|
||||
--- The top bar as plain text, exactly `width` cells (the screen's width when not given).
|
||||
function M.top_text(width)
|
||||
width = width or vim.o.columns
|
||||
local _, plain = M.fit(M.top_cells(width), width)
|
||||
return plain
|
||||
end
|
||||
|
||||
--- 'tabline'.
|
||||
function M.top()
|
||||
local ok, out = pcall(function()
|
||||
local width = vim.o.columns
|
||||
local cells = M.fit(M.top_cells(width), width)
|
||||
return line_of(cells, width, " │ ", "LLeMbasBarSeparator", "LLeMbasBar")
|
||||
end)
|
||||
return ok and out or ""
|
||||
end
|
||||
|
||||
-- ── the bottom bar ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
local MODES = {
|
||||
n = "NOR", no = "O-P", i = "INS", ic = "INS", ix = "INS", v = "VIS", V = "V-L", ["\22"] = "V-B",
|
||||
s = "SEL", S = "S-L", ["\19"] = "S-B", R = "REP", Rv = "REP", c = "CMD", cv = "CMD", t = "TER", nt = "NOR",
|
||||
r = "ASK", rm = "ASK", ["r?"] = "ASK", ["!"] = "RUN",
|
||||
}
|
||||
|
||||
local function mode_word()
|
||||
local m = vim.api.nvim_get_mode().mode
|
||||
return MODES[m] or MODES[m:sub(1, 2)] or MODES[m:sub(1, 1)] or "???"
|
||||
end
|
||||
|
||||
local function search_count()
|
||||
if vim.v.hlsearch ~= 1 then return "" end
|
||||
local ok, c = pcall(vim.fn.searchcount, { maxcount = 999, timeout = 10 })
|
||||
if not ok or type(c) ~= "table" or (c.total or 0) == 0 then return "" end
|
||||
if c.incomplete == 1 then return "?/?" end
|
||||
return ("%d/%s"):format(c.current or 0, c.incomplete == 2 and "999+" or tostring(c.total))
|
||||
end
|
||||
|
||||
--- Where the focus is, as the bottom bar and the keys name it: "tree", "settings", "chat" (the
|
||||
--- transcript), "prompt", "change" (code with proposed changes) or "code".
|
||||
function M.where(win)
|
||||
win = win or vim.api.nvim_get_current_win()
|
||||
if not vim.api.nvim_win_is_valid(win) then return "code" end
|
||||
local buf = vim.api.nvim_win_get_buf(win)
|
||||
if buf == tree().buf() then return "tree" end
|
||||
if buf == lines().buf() then return "settings" end
|
||||
if buf == chat().tbuf then return "chat" end
|
||||
if buf == chat().ibuf then return "prompt" end
|
||||
if require("llembas.diff").pending(buf) > 0 then return "change" end
|
||||
return "code"
|
||||
end
|
||||
|
||||
--- Neovim's own state, in cells of fixed width: the mode, the modified flag, the macro being
|
||||
--- recorded, the search count, the cursor's line and column, and last the pending operator.
|
||||
--- `%l`, `%v` and `%S` are the statusline's own items, so they are as live as Neovim's. `%S` is
|
||||
--- the one item whose width Neovim decides (an empty one takes no cell at all), so it stands at
|
||||
--- the very end, in the five cells kept for it, where it moves nothing else.
|
||||
--- Under 120 columns the keys need the room: the search count and the pending operator are then
|
||||
--- where stock Neovim shows them, in the command line's row ('showcmdloc' is "last").
|
||||
local function vim_segment(width)
|
||||
local rec = vim.fn.reg_recording()
|
||||
local mode = mode_word()
|
||||
local modified = vim.bo.modified and "+" or " "
|
||||
local macro = rec ~= "" and ("@" .. rec) or " "
|
||||
if width < 60 then return 15, (" %s %%5l:%%-3v "):format(mode), (" %s "):format(mode) end
|
||||
if width < 120 then
|
||||
return 20, (" %s %s %s %%5l:%%-3v "):format(mode, modified, macro), (" %s %s %s "):format(mode, modified, macro)
|
||||
end
|
||||
local search = M.cell(search_count(), 8, true)
|
||||
return 35, (" %s %s %s %s %%5l:%%-3v %%<%%.5S"):format(mode, modified, macro, esc(search)),
|
||||
(" %s %s %s %s "):format(mode, modified, macro, search)
|
||||
end
|
||||
|
||||
--- The keys of the bottom bar for the focus `where`, cut to `room` cells by priority: a list of
|
||||
--- { keys, label } and the text.
|
||||
function M.bottom_keys(where, room, chords)
|
||||
local list = keys().for_bar(where, chords)
|
||||
local function text_of(items)
|
||||
local parts = {}
|
||||
for _, k in ipairs(items) do parts[#parts + 1] = k.keys .. " " .. k.label end
|
||||
return " " .. table.concat(parts, " · ")
|
||||
end
|
||||
while #list > 0 and width_of(text_of(list)) > room do table.remove(list) end
|
||||
return list, #list > 0 and text_of(list) or ""
|
||||
end
|
||||
|
||||
--- The bottom bar's keys as plain text for the focus `where` (now, when not given), cut to the
|
||||
--- screen's width less Neovim's own segment.
|
||||
function M.bottom_text(where, width, chords)
|
||||
width = width or vim.o.columns
|
||||
local seg = vim_segment(width)
|
||||
local _, text = M.bottom_keys(where or M.where(), width - seg, chords)
|
||||
return text
|
||||
end
|
||||
|
||||
--- 'statusline'.
|
||||
function M.bottom()
|
||||
local ok, out = pcall(function()
|
||||
local width = vim.o.columns
|
||||
local seg, items = vim_segment(width)
|
||||
local room = width - seg
|
||||
local list = M.bottom_keys(M.where(), room)
|
||||
local parts, used = { "%#LLeMbasBar# " }, 1
|
||||
for i, k in ipairs(list) do
|
||||
local tail = " " .. k.label .. (i < #list and " · " or "")
|
||||
parts[#parts + 1] = "%#LLeMbasBarKey#" .. esc(k.keys) .. "%#LLeMbasBar#" .. esc(tail)
|
||||
used = used + width_of(k.keys) + width_of(tail)
|
||||
end
|
||||
parts[#parts + 1] = (" "):rep(math.max(room - used, 0))
|
||||
parts[#parts + 1] = "%#LLeMbasBarVim#" .. items
|
||||
return table.concat(parts)
|
||||
end)
|
||||
return ok and out or ""
|
||||
end
|
||||
|
||||
-- ── the windows ────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
local function is_bar(win)
|
||||
local buf = vim.api.nvim_win_get_buf(win)
|
||||
return buf == tree().buf() or buf == lines().buf() or buf == chat().tbuf or buf == chat().ibuf
|
||||
end
|
||||
|
||||
local function floating(win) return vim.api.nvim_win_get_config(win).relative ~= "" end
|
||||
|
||||
--- A window beside the code that is not where a file is opened: a terminal, a quickfix list.
|
||||
local function aside(win)
|
||||
local bt = vim.bo[vim.api.nvim_win_get_buf(win)].buftype
|
||||
return bt == "terminal" or bt == "quickfix" or bt == "prompt"
|
||||
end
|
||||
|
||||
--- The window the code is in: the last one that had the focus and is not a bar.
|
||||
function M.code_win()
|
||||
if Y.code and vim.api.nvim_win_is_valid(Y.code) and not is_bar(Y.code) and not floating(Y.code) and not aside(Y.code)
|
||||
and vim.api.nvim_win_get_tabpage(Y.code) == vim.api.nvim_get_current_tabpage() then
|
||||
return Y.code
|
||||
end
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if not is_bar(w) and not floating(w) and not aside(w) then
|
||||
Y.code = w
|
||||
return w
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function clamp(n, lo, hi) return math.max(lo, math.min(hi, n)) end
|
||||
|
||||
--- Which side bars are shown at this size: what is wanted, less what does not leave the code
|
||||
--- `min_code` columns — the chat goes first, then the tree. Returns { tree, chat } and the
|
||||
--- widths. A bar the person opened by hand at this size stays.
|
||||
function M.plan(columns, rows)
|
||||
columns, rows = columns or vim.o.columns, rows or vim.o.lines
|
||||
local p = Y.prefs
|
||||
local tw, cw = clamp(p.tree_width, 16, 60), clamp(p.chat_width, 34, 50)
|
||||
local ai = L().settings().ai
|
||||
local want = { tree = p.tree, chat = p.chat and ai }
|
||||
local function code(t, c) return columns - (t and (tw + 1) or 0) - (c and (cw + 1) or 0) end
|
||||
local folded = { tree = false, chat = false }
|
||||
if want.chat and not Y.forced.chat and code(want.tree, true) < p.min_code then folded.chat = true end
|
||||
local chat_on = want.chat and not folded.chat
|
||||
if want.tree and not Y.forced.tree and code(true, chat_on) < p.min_code then folded.tree = true end
|
||||
local tree_on = want.tree and not folded.tree
|
||||
-- A screen too low for a chat with its prompt: the chat goes.
|
||||
if chat_on and rows < 10 and not Y.forced.chat then chat_on, folded.chat = false, true end
|
||||
return { tree = tree_on, chat = chat_on, folded = folded, tree_width = tw, chat_width = cw,
|
||||
lines = rows >= 18, prompt_height = rows >= 18 and p.prompt_height or 1 }
|
||||
end
|
||||
|
||||
--- Open and close the side bars as `plan` says.
|
||||
function M.apply()
|
||||
if not Y.on or Y.applying then return end
|
||||
Y.applying = true
|
||||
local ok, err = pcall(function()
|
||||
local plan = M.plan()
|
||||
Y.folded = plan.folded
|
||||
M.code_win()
|
||||
if plan.tree then
|
||||
local w = tree().open(plan.tree_width)
|
||||
if w and vim.api.nvim_win_get_width(w) ~= plan.tree_width then
|
||||
pcall(vim.api.nvim_win_set_width, w, plan.tree_width)
|
||||
end
|
||||
else
|
||||
tree().close()
|
||||
end
|
||||
local shape = ("%s:%d:%d"):format(tostring(plan.lines), plan.prompt_height, plan.chat_width)
|
||||
if plan.chat then
|
||||
if chat().is_open() and Y.shape ~= shape then chat().close() end
|
||||
if not chat().is_open() then
|
||||
Y.shape = shape
|
||||
L()._open_bar({
|
||||
width = plan.chat_width, position = "right", prompt_height = plan.prompt_height,
|
||||
bars = true, lines = plan.lines,
|
||||
})
|
||||
end
|
||||
elseif chat().is_open() then
|
||||
chat().close()
|
||||
end
|
||||
end)
|
||||
Y.applying = false
|
||||
if not ok then vim.schedule(function() vim.notify("LLeMbas: the bars could not be laid out: " .. tostring(err), vim.log.levels.WARN) end) end
|
||||
pcall(vim.cmd, "redrawtabline")
|
||||
pcall(vim.cmd, "redrawstatus")
|
||||
-- The windows have their sizes: anything drawn to fit one may draw again.
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasLayout", modeline = false })
|
||||
end
|
||||
|
||||
--- Whether a side bar is on the screen now.
|
||||
function M.shown(which)
|
||||
if which == "tree" then return tree().is_open() end
|
||||
if which == "chat" then return chat().is_open() end
|
||||
return Y.prefs[which] == true
|
||||
end
|
||||
|
||||
local function remember(key, value) pcall(function() store().set(key, value) end) end
|
||||
|
||||
--- Show or hide a bar: "tree", "chat", "top", "bottom". `on` nil: the other of the two. A side
|
||||
--- bar asked for at a width where it would be folded away is shown all the same.
|
||||
function M.toggle(which, on)
|
||||
if which ~= "tree" and which ~= "chat" and which ~= "top" and which ~= "bottom" then return end
|
||||
if not Y.on then
|
||||
if which == "chat" then return L().toggle() end
|
||||
if which == "tree" then
|
||||
if tree().is_open() then tree().close() else tree().open(Y.prefs.tree_width) end
|
||||
end
|
||||
return
|
||||
end
|
||||
if which == "top" or which == "bottom" then
|
||||
if on == nil then on = not Y.prefs[which] end
|
||||
Y.prefs[which] = on
|
||||
remember(which, on)
|
||||
return M.bars()
|
||||
end
|
||||
local is = M.shown(which)
|
||||
if on == nil then on = not is end
|
||||
Y.prefs[which] = on
|
||||
Y.forced[which] = on and true or nil
|
||||
remember(which, on)
|
||||
if which == "chat" and on and not L().settings().ai then
|
||||
return vim.notify("LLeMbas is off (" .. keys().shown(keys().by_id.ai) .. " turns it on)", vim.log.levels.INFO)
|
||||
end
|
||||
M.apply()
|
||||
end
|
||||
|
||||
--- Put the focus in a bar: "tree", "code" or "chat" (the prompt). A side bar that is hidden is shown.
|
||||
function M.focus(which)
|
||||
if which == "tree" then
|
||||
if not tree().is_open() then M.toggle("tree", true) end
|
||||
local w = tree().win()
|
||||
if w then
|
||||
vim.cmd("stopinsert")
|
||||
vim.api.nvim_set_current_win(w)
|
||||
end
|
||||
elseif which == "chat" then
|
||||
if not L().settings().ai then
|
||||
return vim.notify("LLeMbas is off (" .. keys().shown(keys().by_id.ai) .. " turns it on)", vim.log.levels.INFO)
|
||||
end
|
||||
if not chat().is_open() then
|
||||
if Y.on then M.toggle("chat", true) else L().open(true) end
|
||||
end
|
||||
chat().focus_prompt()
|
||||
else
|
||||
local w = M.code_win()
|
||||
if w then
|
||||
vim.cmd("stopinsert")
|
||||
vim.api.nvim_set_current_win(w)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
local ORDER = { "tree", "code", "chat" }
|
||||
|
||||
--- Move the focus one bar to the left (-1) or to the right (1): tree, code, chat.
|
||||
function M.go(step)
|
||||
local where = M.where()
|
||||
local at = (where == "tree" and 1) or ((where == "code" or where == "change") and 2) or 3
|
||||
local to = clamp(at + step, 1, 3)
|
||||
if to == at then return end
|
||||
M.focus(ORDER[to])
|
||||
end
|
||||
|
||||
-- ── the terminal ───────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
--- The bytes that set the terminal's user var `llembas_ide` to `value` ("" clears it): iTerm2's
|
||||
--- OSC 1337 SetUserVar, which WezTerm and the LLeMbas terminal read. Inside tmux it is wrapped
|
||||
--- so that tmux passes it on.
|
||||
function M.uservar_bytes(value, tmux)
|
||||
local seq = "\27]1337;SetUserVar=llembas_ide=" .. vim.base64.encode(value or "") .. "\7"
|
||||
if tmux then seq = "\27Ptmux;" .. seq:gsub("\27", "\27\27") .. "\27\\" end
|
||||
return seq
|
||||
end
|
||||
|
||||
local function in_llembas_terminal()
|
||||
local e = vim.env
|
||||
return (e.LLEMBAS_TERM ~= nil and e.LLEMBAS_TERM ~= "") or (e.LLEMBAS_TTY ~= nil and e.LLEMBAS_TTY ~= "")
|
||||
end
|
||||
|
||||
--- Tell the LLeMbas terminal that this editor is the program in front (`on`), or no longer is:
|
||||
--- it hands its own chords (Ctrl+Shift+A …) through to the program that says `llembas_ide=1`.
|
||||
--- Written only inside that terminal (`$LLEMBAS_TERM` or `$LLEMBAS_TTY`), and nowhere else.
|
||||
function M.announce(on)
|
||||
if not in_llembas_terminal() then return false end
|
||||
if on == Y.announced then return true end
|
||||
Y.announced = on
|
||||
-- Standard error is the terminal itself, whatever Neovim draws with (as Neovim's own OSC 52 does).
|
||||
pcall(vim.api.nvim_chan_send, 2, M.uservar_bytes(on and "1" or "", vim.env.TMUX ~= nil and vim.env.TMUX ~= ""))
|
||||
return true
|
||||
end
|
||||
|
||||
-- ── setting up ─────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
--- Put the top and the bottom bar where the settings say, and give back what was there when one
|
||||
--- is switched off.
|
||||
function M.bars()
|
||||
local p = Y.prefs
|
||||
if Y.on and p.top then
|
||||
if not Y.saved.tabline then Y.saved.tabline = { vim.o.tabline, vim.o.showtabline } end
|
||||
vim.o.tabline = "%!v:lua.require'llembas.layout'.top()"
|
||||
vim.o.showtabline = 2
|
||||
elseif Y.saved.tabline then
|
||||
vim.o.tabline, vim.o.showtabline = Y.saved.tabline[1], Y.saved.tabline[2]
|
||||
Y.saved.tabline = nil
|
||||
end
|
||||
if Y.on and p.bottom then
|
||||
if not Y.saved.statusline then Y.saved.statusline = { vim.o.statusline, vim.o.laststatus, vim.o.showcmdloc } end
|
||||
vim.o.statusline = "%!v:lua.require'llembas.layout'.bottom()"
|
||||
vim.o.laststatus = 3
|
||||
-- The pending operator: the bar's %S where the bar is wide enough to have a cell for it,
|
||||
-- otherwise in the command line's row, as Neovim itself shows it.
|
||||
vim.o.showcmdloc = vim.o.columns >= 120 and "statusline" or "last"
|
||||
elseif Y.saved.statusline then
|
||||
vim.o.statusline, vim.o.laststatus, vim.o.showcmdloc = Y.saved.statusline[1], Y.saved.statusline[2], Y.saved.statusline[3]
|
||||
Y.saved.statusline = nil
|
||||
end
|
||||
pcall(vim.cmd, "redrawtabline")
|
||||
pcall(vim.cmd, "redrawstatus")
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasBars", modeline = false })
|
||||
end
|
||||
|
||||
--- What the layout is set to now (a copy), with what is folded away at this size.
|
||||
function M.options()
|
||||
local out = vim.deepcopy(Y.prefs)
|
||||
out.on, out.folded = Y.on, vim.deepcopy(Y.folded)
|
||||
return out
|
||||
end
|
||||
|
||||
local function widths_changed()
|
||||
if not Y.on then return end
|
||||
local tw, cw = tree().win(), chat().is_open() and vim.fn.bufwinid(chat().tbuf) or -1
|
||||
if tw and not Y.folded.tree then
|
||||
local w = vim.api.nvim_win_get_width(tw)
|
||||
if w ~= Y.prefs.tree_width and w >= 16 and w <= 60 then
|
||||
Y.prefs.tree_width = w
|
||||
tree().width = w
|
||||
remember("tree_width", w)
|
||||
end
|
||||
end
|
||||
if cw and cw ~= -1 and not Y.folded.chat then
|
||||
local w = vim.api.nvim_win_get_width(cw)
|
||||
if w ~= Y.prefs.chat_width and w >= 34 and w <= 50 then
|
||||
Y.prefs.chat_width = w
|
||||
remember("chat_width", w)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- Remember the side bars' widths as they are now (also done when Neovim sees a window resized,
|
||||
--- and on the way out).
|
||||
function M.remember_widths() widths_changed() end
|
||||
|
||||
--- Close the side bars, for something that must see only the code's windows (saving a session);
|
||||
--- `M.apply()` brings them back.
|
||||
function M.hide()
|
||||
tree().close()
|
||||
chat().close()
|
||||
end
|
||||
|
||||
--- Turn the layout on with `opts` (see `M.defaults`; `false` turns it off). `opts` are what a
|
||||
--- directory starts with. What the person then changed by hand there — which bars are shown, how
|
||||
--- wide the side bars are — is remembered for that directory and holds the next time.
|
||||
function M.setup(opts)
|
||||
if opts == false then
|
||||
Y.on = false
|
||||
pcall(vim.api.nvim_del_augroup_by_name, "llembas-layout")
|
||||
M.bars()
|
||||
return
|
||||
end
|
||||
Y.given = vim.tbl_extend("force", Y.given or {}, type(opts) == "table" and opts or {})
|
||||
local prefs = vim.tbl_extend("force", vim.deepcopy(M.defaults), Y.given)
|
||||
local remembered = store().get()
|
||||
for _, k in ipairs({ "top", "bottom", "tree", "chat", "tree_width", "chat_width" }) do
|
||||
if remembered[k] ~= nil then prefs[k] = remembered[k] end
|
||||
end
|
||||
Y.prefs = prefs
|
||||
Y.on = true
|
||||
require("llembas.ui").setup_highlights()
|
||||
M.bars()
|
||||
|
||||
local group = vim.api.nvim_create_augroup("llembas-layout", { clear = true })
|
||||
local function redraw()
|
||||
pcall(vim.cmd, "redrawtabline")
|
||||
pcall(vim.cmd, "redrawstatus")
|
||||
end
|
||||
vim.api.nvim_create_autocmd("User", { group = group, pattern = "LLeMbasChanged", callback = function()
|
||||
-- AI switched on or off changes what is laid out.
|
||||
local ai = L().settings().ai
|
||||
if Y.ai ~= ai then
|
||||
Y.ai = ai
|
||||
vim.schedule(M.apply)
|
||||
end
|
||||
redraw()
|
||||
end })
|
||||
vim.api.nvim_create_autocmd({ "WinEnter", "BufEnter", "ModeChanged", "DiagnosticChanged", "RecordingEnter", "RecordingLeave" },
|
||||
{ group = group, callback = function()
|
||||
local w = vim.api.nvim_get_current_win()
|
||||
if not is_bar(w) and not floating(w) and not aside(w) then Y.code = w end
|
||||
vim.schedule(redraw)
|
||||
end })
|
||||
vim.api.nvim_create_autocmd("VimResized", { group = group, callback = function()
|
||||
-- A new size is judged anew: what was opened by hand at the old one no longer holds.
|
||||
Y.forced = {}
|
||||
if Y.saved.statusline then vim.o.showcmdloc = vim.o.columns >= 120 and "statusline" or "last" end
|
||||
vim.schedule(M.apply)
|
||||
end })
|
||||
vim.api.nvim_create_autocmd({ "WinResized", "VimLeavePre" }, { group = group, callback = function()
|
||||
if not Y.applying then widths_changed() end
|
||||
end })
|
||||
vim.api.nvim_create_autocmd("QuitPre", { group = group, callback = function()
|
||||
-- Leaving the last window of code leaves the editor: the bars do not keep it open.
|
||||
local cur = vim.api.nvim_get_current_win()
|
||||
if is_bar(cur) or floating(cur) then return end
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if w ~= cur and not is_bar(w) and not floating(w) then return end
|
||||
end
|
||||
if #vim.api.nvim_list_tabpages() > 1 then return end
|
||||
Y.applying = true
|
||||
M.hide()
|
||||
Y.applying = false
|
||||
-- A quit that did not happen (unsaved changes, a no to the question): the bars come back.
|
||||
vim.defer_fn(function() if Y.on then M.apply() end end, 60)
|
||||
end })
|
||||
Y.ai = L().settings().ai
|
||||
if vim.v.vim_did_enter == 1 then
|
||||
M.apply()
|
||||
else
|
||||
vim.api.nvim_create_autocmd("VimEnter", { group = group, once = true, callback = function() vim.schedule(M.apply) end })
|
||||
end
|
||||
end
|
||||
|
||||
M._state = Y
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,161 @@
|
||||
-- The settings lines: what holds now — model, mode, effort, autocomplete — one line each, at the
|
||||
-- top of the right bar. Enter on a line opens its choices right under it, in the bar; Enter on a
|
||||
-- choice takes it. The values and the choices are the plugin's public ones (`setting_lines`,
|
||||
-- `choices`, `set`): this module only draws them.
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace("llembas-lines")
|
||||
|
||||
local P = { buf = nil, open = nil, choices = nil, note = nil, rows = {} }
|
||||
M.LABEL_WIDTH = 14 -- every label is cut or padded to this, so the values share one edge
|
||||
M.MAX_CHOICES = 8 -- rows the bar gives a list of choices before it scrolls
|
||||
|
||||
local function L() return require("llembas") end
|
||||
local function valid() return P.buf and vim.api.nvim_buf_is_valid(P.buf) end
|
||||
|
||||
function M.win()
|
||||
if not valid() then return nil end
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.api.nvim_win_get_buf(w) == P.buf then return w end
|
||||
end
|
||||
end
|
||||
|
||||
local function one_line(text) return (tostring(text or ""):gsub("[%c]+", " ")) end
|
||||
|
||||
--- How many rows the lines want now: the settings, and the open list up to its limit.
|
||||
function M.height()
|
||||
local settings = #L().setting_lines()
|
||||
if not P.open then return settings end
|
||||
local extra = P.choices and #P.choices or 1
|
||||
return settings + math.min(math.max(extra, 1), M.MAX_CHOICES)
|
||||
end
|
||||
|
||||
function M.render()
|
||||
if not valid() then return end
|
||||
local lines, rows, marks = {}, {}, {}
|
||||
for _, s in ipairs(L().setting_lines()) do
|
||||
local label = vim.fn.strcharpart(s.label, 0, M.LABEL_WIDTH - 1)
|
||||
lines[#lines + 1] = label .. (" "):rep(M.LABEL_WIDTH - vim.fn.strdisplaywidth(label)) .. one_line(s.value)
|
||||
rows[#rows + 1] = { kind = "setting", id = s.id }
|
||||
marks[#marks + 1] = { #lines - 1, 0, #label, "LLeMbasLineLabel" }
|
||||
marks[#marks + 1] = { #lines - 1, M.LABEL_WIDTH, #lines[#lines], s.off and "LLeMbasLineOff" or "LLeMbasLineValue" }
|
||||
if P.open == s.id then
|
||||
if P.choices then
|
||||
for _, c in ipairs(P.choices) do
|
||||
lines[#lines + 1] = (c.current and " ● " or " ○ ") .. one_line(c.label)
|
||||
rows[#rows + 1] = { kind = "choice", id = s.id, value = c.value }
|
||||
if c.current then marks[#marks + 1] = { #lines - 1, 0, #lines[#lines], "LLeMbasLineCurrent" } end
|
||||
end
|
||||
if #P.choices == 0 then
|
||||
lines[#lines + 1] = " (nothing to choose from)"
|
||||
rows[#rows + 1] = { kind = "note" }
|
||||
end
|
||||
else
|
||||
lines[#lines + 1] = " " .. one_line(P.note or "…")
|
||||
rows[#rows + 1] = { kind = "note" }
|
||||
marks[#marks + 1] = { #lines - 1, 0, #lines[#lines], "LLeMbasNote" }
|
||||
end
|
||||
end
|
||||
end
|
||||
P.rows = rows
|
||||
vim.bo[P.buf].modifiable = true
|
||||
vim.api.nvim_buf_set_lines(P.buf, 0, -1, false, lines)
|
||||
vim.bo[P.buf].modifiable = false
|
||||
vim.api.nvim_buf_clear_namespace(P.buf, ns, 0, -1)
|
||||
for _, m in ipairs(marks) do
|
||||
pcall(vim.api.nvim_buf_set_extmark, P.buf, ns, m[1], m[2], { end_col = m[3], hl_group = m[4] })
|
||||
end
|
||||
local win = M.win()
|
||||
if win then pcall(vim.api.nvim_win_set_height, win, M.height()) end
|
||||
end
|
||||
|
||||
local function row_here()
|
||||
local win = M.win()
|
||||
if not win then return nil end
|
||||
return P.rows[vim.api.nvim_win_get_cursor(win)[1]], win
|
||||
end
|
||||
|
||||
local function cursor_to(pred)
|
||||
local win = M.win()
|
||||
if not win then return end
|
||||
for i, r in ipairs(P.rows) do
|
||||
if pred(r) then return pcall(vim.api.nvim_win_set_cursor, win, { i, 0 }) end
|
||||
end
|
||||
end
|
||||
|
||||
--- Close the open list. True when one was open.
|
||||
function M.close_choices()
|
||||
if not P.open then return false end
|
||||
local id = P.open
|
||||
P.open, P.choices, P.note = nil, nil, nil
|
||||
M.render()
|
||||
cursor_to(function(r) return r.kind == "setting" and r.id == id end)
|
||||
return true
|
||||
end
|
||||
|
||||
--- Open the choices of the setting `id` under its line.
|
||||
function M.open_choices(id)
|
||||
P.open, P.choices, P.note = id, nil, nil
|
||||
M.render()
|
||||
L().choices(id, function(choices, why)
|
||||
if P.open ~= id then return end
|
||||
if not choices then
|
||||
P.note = why or "not available now"
|
||||
else
|
||||
P.choices = choices
|
||||
end
|
||||
M.render()
|
||||
cursor_to(function(r) return r.kind == "choice" and r.id == id and (function()
|
||||
for _, c in ipairs(P.choices or {}) do if c.current and c.value == r.value then return true end end
|
||||
return false
|
||||
end)() end)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Enter: on a setting, its choices open (or close, when they are open); on a choice, it is taken.
|
||||
function M.enter()
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
if r.kind == "setting" then
|
||||
if P.open == r.id then return M.close_choices() end
|
||||
return M.open_choices(r.id)
|
||||
elseif r.kind == "choice" then
|
||||
local id, value = r.id, r.value
|
||||
P.open, P.choices, P.note = nil, nil, nil
|
||||
M.render()
|
||||
cursor_to(function(x) return x.kind == "setting" and x.id == id end)
|
||||
L().set(id, value)
|
||||
end
|
||||
end
|
||||
|
||||
--- Esc: the open list closes; with none open, back to the code.
|
||||
function M.back()
|
||||
if M.close_choices() then return end
|
||||
pcall(function() require("llembas.layout").focus("code") end)
|
||||
end
|
||||
|
||||
function M.buffer()
|
||||
if valid() then return P.buf end
|
||||
P.buf = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[P.buf].buftype = "nofile"
|
||||
vim.bo[P.buf].bufhidden = "hide"
|
||||
vim.bo[P.buf].swapfile = false
|
||||
vim.bo[P.buf].modeline = false
|
||||
vim.bo[P.buf].undolevels = -1
|
||||
vim.bo[P.buf].filetype = "llembas-settings"
|
||||
pcall(vim.api.nvim_buf_set_name, P.buf, "llembas://settings")
|
||||
vim.bo[P.buf].modifiable = false
|
||||
require("llembas.keys").bind("settings", P.buf, { settings_change = M.enter, settings_back = M.back })
|
||||
vim.api.nvim_create_autocmd("User", {
|
||||
group = vim.api.nvim_create_augroup("llembas-lines", { clear = true }),
|
||||
pattern = "LLeMbasChanged",
|
||||
callback = function() if M.win() then M.render() end end,
|
||||
})
|
||||
return P.buf
|
||||
end
|
||||
|
||||
--- The lines as text, and which setting's list is open: for the tests.
|
||||
function M.lines() return valid() and vim.api.nvim_buf_get_lines(P.buf, 0, -1, false) or {} end
|
||||
function M.opened() return P.open end
|
||||
function M.buf() return valid() and P.buf or nil end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,219 @@
|
||||
-- Signing in and out from the editor: `lembas login --json <address>` and `lembas logout`, run with
|
||||
-- the same program the plugin 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.
|
||||
local M = {}
|
||||
|
||||
local running = nil -- { proc, killer, cancelled }
|
||||
|
||||
local function L() return require("llembas") end
|
||||
|
||||
local function same_server(a, b)
|
||||
local function bare(s) return (tostring(s or ""):gsub("^https?://", ""):gsub("/+$", "")):lower() end
|
||||
return bare(a) ~= "" and bare(a) == bare(b)
|
||||
end
|
||||
|
||||
--- The events `lembas login --json` wrote: one JSON object a line (`code`, `done`, `error`).
|
||||
local function events_of(text)
|
||||
local out = {}
|
||||
for line in tostring(text or ""):gmatch("[^\r\n]+") do
|
||||
local ok, ev = pcall(vim.json.decode, line, { luanil = { object = true, array = true } })
|
||||
if ok and type(ev) == "table" and type(ev.event) == "string" then out[#out + 1] = ev end
|
||||
end
|
||||
return out
|
||||
end
|
||||
M._events_of = events_of
|
||||
|
||||
--- A reader of `lembas login --json`'s output as it arrives: `feed(data)` takes the pieces, and
|
||||
--- `on_event(ev)` is called for every event on a line that has ended. A line cut in two by the
|
||||
--- pipe is one line; what has no line break yet is not read. The same reading as the VS Code
|
||||
--- extension's (vscode/src/login.js); tests/rules/login_events.json holds the cases.
|
||||
local function reader(on_event)
|
||||
local buf = ""
|
||||
return function(data)
|
||||
if not data or data == "" then return end
|
||||
buf = buf .. data
|
||||
while true do
|
||||
local nl = buf:find("\n", 1, true)
|
||||
if not nl then break end
|
||||
local line = buf:sub(1, nl - 1)
|
||||
buf = buf:sub(nl + 1)
|
||||
for _, ev in ipairs(events_of(line)) do on_event(ev) end
|
||||
end
|
||||
end
|
||||
end
|
||||
M._reader = reader
|
||||
|
||||
--- A server's address as the person typed it, fit to be one argument of `lembas login`: one
|
||||
--- word, and never something the program would read as an option. The address, or nil.
|
||||
function M.address(text)
|
||||
local s = type(text) == "string" and vim.trim(text) or ""
|
||||
if s == "" or #s > 2048 or s:find("[%s%c]") or s:sub(1, 1) == "-" then return nil end
|
||||
return s
|
||||
end
|
||||
|
||||
local function last_line(text)
|
||||
local last = ""
|
||||
for line in tostring(text or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end
|
||||
return last
|
||||
end
|
||||
|
||||
local function kill(proc)
|
||||
pcall(function() proc:kill(15) end)
|
||||
local t = vim.uv.new_timer()
|
||||
t:start(require("llembas.rpc").KILL_AFTER_MS, 0, function()
|
||||
pcall(function() t:stop(); t:close() end)
|
||||
pcall(function() proc:kill(9) end)
|
||||
end)
|
||||
pcall(function() t:unref() end)
|
||||
return t
|
||||
end
|
||||
|
||||
--- The server this computer is signed in to now, or nil: `lembas login --json` with no address
|
||||
--- reads the one login there is anew, and says whose it is. `cb(base_url | nil)`.
|
||||
function M.current(exe, cb)
|
||||
local done = false
|
||||
local proc
|
||||
local function finish(v)
|
||||
if done then return end
|
||||
done = true
|
||||
vim.schedule(function() cb(v) end)
|
||||
end
|
||||
-- Read by lines, as the sign-in itself is: a `done` cut in two by the pipe must not read as
|
||||
-- "not signed in", which would let another sign-in replace this one without the question.
|
||||
local feed = reader(function(ev)
|
||||
-- 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" and type(ev.instance) == "table" then
|
||||
finish(ev.instance.base_url)
|
||||
kill(proc)
|
||||
elseif ev.event == "done" then finish(ev.base_url)
|
||||
end
|
||||
end)
|
||||
local ok
|
||||
ok, proc = pcall(vim.system, { exe, "login", "--json" }, {
|
||||
text = true,
|
||||
stdout = function(_, data) feed(data) end,
|
||||
timeout = 15000,
|
||||
}, function() finish(nil) end)
|
||||
if not ok then finish(nil) end
|
||||
end
|
||||
|
||||
--- Stop a sign-in that is under way. False when none is.
|
||||
function M.cancel()
|
||||
local r = running
|
||||
if not r then return false end
|
||||
r.cancelled = true
|
||||
kill(r.proc)
|
||||
return true
|
||||
end
|
||||
|
||||
function M.running() return running ~= nil end
|
||||
|
||||
local function run(exe, address, ca)
|
||||
local words = L()._words
|
||||
local argv = { exe, "login", "--json", address }
|
||||
if ca and ca ~= "" then vim.list_extend(argv, { "--ca", vim.fn.expand(ca) }) end
|
||||
local me = { cancelled = false }
|
||||
local settled = false
|
||||
local function on_event(ev)
|
||||
if ev.event == "code" then
|
||||
local where = type(ev.instance) == "table" and (ev.instance.name or ev.instance.base_url) or address
|
||||
local url = ev.verification_uri_complete or ev.verification_uri
|
||||
L()._note(("To sign in to %s, approve the code %s at %s. The page is opened in your browser where there is one; if none opens, go to that address yourself. :LLeMbasLoginCancel stops waiting.")
|
||||
:format(tostring(where), tostring(ev.user_code), tostring(ev.verification_uri)))
|
||||
-- Only a web address is handed to the system, whatever the program printed.
|
||||
if type(url) == "string" and url:match("^https?://[^%s]+$") and vim.ui.open then pcall(vim.ui.open, url) end
|
||||
-- The CLI says when the code has run out; should it not, nothing waits for ever.
|
||||
local limit = (tonumber(ev.expires_in) or 600) + 30
|
||||
me.expiry = vim.defer_fn(function() if running == me then kill(me.proc) end end, limit * 1000)
|
||||
elseif ev.event == "done" then
|
||||
settled = true
|
||||
if running == me then running = nil end
|
||||
L().restart(true)
|
||||
L()._note(("Signed in to %s%s. The next message starts a session."):format(tostring(ev.base_url or address),
|
||||
tonumber(ev.models) and (" (%d models)"):format(ev.models) or ""))
|
||||
elseif ev.event == "error" then
|
||||
settled = true
|
||||
if running == me then running = nil end
|
||||
L()._note("Not signed in: " .. L()._say({ message = ev.message, code = ev.code }), "error")
|
||||
end
|
||||
end
|
||||
local feed = reader(function(ev) vim.schedule(function() on_event(ev) end) end)
|
||||
local ok, proc = pcall(vim.system, argv, {
|
||||
text = true,
|
||||
stdout = function(_, data) feed(data) end,
|
||||
}, function(res)
|
||||
vim.schedule(function()
|
||||
if running == me then running = nil end
|
||||
if me.expiry then pcall(function() me.expiry:stop(); me.expiry:close() end) end
|
||||
if settled then return end
|
||||
if me.cancelled then return L()._note("Signing in was cancelled.") end
|
||||
local why = last_line(res.stderr)
|
||||
L()._note("Not signed in: " .. (why ~= "" and why or ("the LLeMbas CLI ended (exit " .. tostring(res.code) .. ")")), "error")
|
||||
end)
|
||||
end)
|
||||
if not ok then return L()._note(words.not_found:format(exe), "error") end
|
||||
me.proc = proc
|
||||
running = me
|
||||
end
|
||||
|
||||
--- Sign this computer in to a LLeMbas server. `address`: asked for when not given. `ca`: a file
|
||||
--- with the certificate authority of a server that has a private one.
|
||||
function M.login(address, ca)
|
||||
if running then return vim.notify("LLeMbas: a sign-in is under way (:LLeMbasLoginCancel stops it)", vim.log.levels.WARN) end
|
||||
local cmd, why = L()._command()
|
||||
if not cmd then return L()._note(why, "error") end
|
||||
local exe = cmd[1]
|
||||
if not address or not address:match("%S") then
|
||||
return vim.ui.input({ prompt = "LLeMbas server address: " }, function(text)
|
||||
if text and text:match("%S") then M.login(vim.trim(text), ca) end
|
||||
end)
|
||||
end
|
||||
local typed = address
|
||||
address = M.address(address)
|
||||
if not address then
|
||||
return vim.notify(("LLeMbas: %q is not a server's address: one word, such as ai.example.org, and not an option"):format(vim.trim(typed)), vim.log.levels.WARN)
|
||||
end
|
||||
ca = ca or (L().config.login or {}).ca
|
||||
M.current(exe, function(now)
|
||||
-- The same server again, without a certificate: the CLI reads its login anew and replaces nothing.
|
||||
if not now or (same_server(now, address) and not (ca and ca ~= "")) then return run(exe, address, ca) end
|
||||
local choices = {
|
||||
{ go = false, label = "Cancel" },
|
||||
{ go = true, label = ("Sign in to %s (replaces the sign-in to %s)"):format(address, now) },
|
||||
}
|
||||
vim.ui.select(choices, {
|
||||
prompt = ("This computer is signed in to %s. The LLeMbas CLI keeps one sign-in: the terminal and the linked service use it too."):format(now),
|
||||
format_item = function(c) return c.label end,
|
||||
}, function(choice)
|
||||
if choice and choice.go then run(exe, address, ca) end
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Sign this computer out: the terminal and the linked service are signed out with it.
|
||||
function M.logout()
|
||||
local cmd, why = L()._command()
|
||||
if not cmd then return L()._note(why, "error") end
|
||||
local exe = cmd[1]
|
||||
M.current(exe, function(now)
|
||||
if not now then return vim.notify("LLeMbas: this computer is not signed in to a server", vim.log.levels.INFO) end
|
||||
vim.ui.select({ { go = false, label = "Cancel" }, { go = true, label = "Sign out of " .. now } }, {
|
||||
prompt = ("Sign this computer out of %s? The terminal and the linked service use the same sign-in."):format(now),
|
||||
format_item = function(c) return c.label end,
|
||||
}, function(choice)
|
||||
if not choice or not choice.go then return end
|
||||
vim.system({ exe, "logout" }, { text = true, timeout = 30000 }, function(res)
|
||||
vim.schedule(function()
|
||||
if res.code ~= 0 then
|
||||
return L()._note("Not signed out: " .. (last_line(res.stderr) ~= "" and last_line(res.stderr) or ("exit " .. tostring(res.code))), "error")
|
||||
end
|
||||
L().restart(true)
|
||||
L()._note(last_line(res.stdout) ~= "" and last_line(res.stdout) or ("Signed out of " .. now .. "."))
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,119 @@
|
||||
-- What is never sent along by itself: files that look like they hold secrets, files outside the
|
||||
-- project, and files the project's .gitignore leaves out. Used for what goes with a request
|
||||
-- without the person having pointed at it: pieces of other open files with a suggestion, and the
|
||||
-- names of the other open files with a message. The same rules as the VS Code extension's
|
||||
-- (vscode/src/private.js); tests/rules/private_files.json holds the cases both must answer alike.
|
||||
local M = {}
|
||||
|
||||
local ENV_EXAMPLES = { [".env.example"] = true, [".env.sample"] = true, [".env.template"] = true }
|
||||
local NAMES = {
|
||||
[".netrc"] = true, ["_netrc"] = true, [".npmrc"] = true, [".pypirc"] = true, [".pgpass"] = true,
|
||||
[".htpasswd"] = true, [".git-credentials"] = true,
|
||||
}
|
||||
local ENDINGS = { pem = true, key = true, p12 = true, pfx = true, jks = true, keystore = true, ppk = true, kdbx = true, env = true }
|
||||
local KEY_NAMES = { "id_rsa", "id_ed25519", "id_ecdsa", "id_dsa" }
|
||||
local DIRECTORIES = { [".ssh"] = true, [".gnupg"] = true, [".aws"] = true, [".kube"] = true, [".docker"] = true, [".azure"] = true }
|
||||
|
||||
local function parts_of(path)
|
||||
local out = {}
|
||||
for part in (tostring(path or ""):gsub("\\", "/")):gmatch("[^/]+") do out[#out + 1] = part:lower() end
|
||||
return out
|
||||
end
|
||||
|
||||
--- Whether a file's name or place says it may hold secrets: `.env` and `.env.*` (not the
|
||||
--- `.example`, `.sample` and `.template` ones), `*.env`, key and certificate stores (`*.pem`,
|
||||
--- `*.key`, `*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`), SSH key names (`id_rsa*`,
|
||||
--- `id_ed25519*`, `id_ecdsa*`, `id_dsa*`), `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
|
||||
--- `.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`,
|
||||
--- `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`.
|
||||
function M.looks_secret(path)
|
||||
local parts = parts_of(path)
|
||||
local base = parts[#parts]
|
||||
if not base then return false end
|
||||
for i = 1, #parts - 1 do
|
||||
if DIRECTORIES[parts[i]] then return true end
|
||||
end
|
||||
if base == ".env" or (base:sub(1, 5) == ".env." and not ENV_EXAMPLES[base]) then return true end
|
||||
if NAMES[base] then return true end
|
||||
local ending = base:match("%.([^.]+)$")
|
||||
if ending and ENDINGS[ending] then return true end
|
||||
for _, k in ipairs(KEY_NAMES) do
|
||||
if base:sub(1, #k) == k then return true end
|
||||
end
|
||||
if base:sub(1, 11) == "credentials" then return true end
|
||||
if base:sub(1, 8) == "secrets." or base:sub(1, 7) == "secret." then return true end
|
||||
return false
|
||||
end
|
||||
|
||||
--- A path with `.` and `..` worked out and one kind of slash, or nil when it is not absolute.
|
||||
local function absolute(path)
|
||||
local p = tostring(path or ""):gsub("\\", "/")
|
||||
local drive = p:match("^(%a:)/") or ""
|
||||
if drive ~= "" then p = p:sub(3) end
|
||||
if p:sub(1, 1) ~= "/" then return nil end
|
||||
local out = {}
|
||||
for part in p:gmatch("[^/]+") do
|
||||
if part == ".." then table.remove(out)
|
||||
elseif part ~= "." then out[#out + 1] = part end
|
||||
end
|
||||
return drive:lower() .. "/" .. table.concat(out, "/")
|
||||
end
|
||||
|
||||
--- Whether `path` is a file inside one of the folders `roots` (never a folder itself, and never
|
||||
--- "inside" the root of the disk).
|
||||
function M.inside(path, roots)
|
||||
local p = absolute(path)
|
||||
if not p then return false end
|
||||
for _, root in ipairs(roots or {}) do
|
||||
local r = absolute(root)
|
||||
if r and r ~= "/" and not r:match("^%a:/$") and p:sub(1, #r + 1) == r .. "/" then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local ignored = {} -- path -> true | false | "asking"
|
||||
|
||||
--- Whether the project's .gitignore leaves `path` out: true or false once git has answered, nil
|
||||
--- while it has not (the question is then on its way; `cb(answer)` is called with it). Without
|
||||
--- git, or outside a repository, nothing is ignored. Asked once a file.
|
||||
function M.ignored(path, cb)
|
||||
local known = ignored[path]
|
||||
if known == true or known == false then
|
||||
if cb then cb(known) end
|
||||
return known
|
||||
end
|
||||
if known == "asking" then return nil end
|
||||
if vim.fn.executable("git") == 0 then
|
||||
ignored[path] = false
|
||||
if cb then cb(false) end
|
||||
return false
|
||||
end
|
||||
ignored[path] = "asking"
|
||||
local ok = pcall(vim.system, { "git", "-C", vim.fs.dirname(path), "check-ignore", "-q", "--", path },
|
||||
{ text = true, timeout = 5000, env = { GIT_OPTIONAL_LOCKS = "0" } }, function(res)
|
||||
-- 0: ignored. 1: not. Anything else: no repository there, or git failed.
|
||||
ignored[path] = res.code == 0
|
||||
if cb then vim.schedule(function() cb(ignored[path]) end) end
|
||||
end)
|
||||
if not ok then
|
||||
ignored[path] = false
|
||||
if cb then cb(false) end
|
||||
return false
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- A .gitignore changed, or the directory did: what git said before is asked again.
|
||||
function M.forget() ignored = {} end
|
||||
|
||||
--- The folders that are the project here: the working directory.
|
||||
function M.roots() return { vim.fn.getcwd() } end
|
||||
|
||||
--- Whether a file other than the one being worked on may go along by itself: inside the
|
||||
--- project, not secret by its name, and known not to be ignored by the project's .gitignore.
|
||||
function M.may_send(path, roots)
|
||||
if not M.inside(path, roots or M.roots()) or M.looks_secret(path) then return false end
|
||||
return M.ignored(path) == false
|
||||
end
|
||||
|
||||
return M
|
||||
+75
-18
@@ -2,12 +2,15 @@
|
||||
local M = {}
|
||||
M.__index = M
|
||||
|
||||
local MAX_BUF_BYTES = 64 * 1024 * 1024 -- 64 MB cap against an unbounded unterminated stream
|
||||
local MAX_LINE_BYTES = 64 * 1024 * 1024 -- a line that never ends is dropped, not kept
|
||||
|
||||
local MAX_ERR_BYTES = 64 * 1024 -- what is kept of the agent's stderr: its end
|
||||
M.KILL_AFTER_MS = 5000
|
||||
|
||||
--- Start `cmd` and speak JSON-RPC with it. `on.request(method, params, reply)` and
|
||||
--- `on.notify(method, params)` run on the main loop; `on.exit(code, stderr)` when the process ends.
|
||||
function M.start(cmd, on, opts)
|
||||
local self = setmetatable({ next_id = 1, waiting = {}, on = on, buf = "", err = {}, closed = false }, M)
|
||||
local self = setmetatable({ next_id = 1, waiting = {}, timers = {}, on = on, buf = "", err = "", closed = false }, M)
|
||||
local ok, proc = pcall(vim.system, cmd, {
|
||||
stdin = true,
|
||||
cwd = opts and opts.cwd or nil,
|
||||
@@ -15,17 +18,20 @@ function M.start(cmd, on, opts)
|
||||
stdout = function(_, data) if data then self:_feed(data) end end,
|
||||
stderr = function(_, data)
|
||||
if data then
|
||||
self.err[#self.err + 1] = data
|
||||
while #self.err > 40 do table.remove(self.err, 1) end
|
||||
self.err = self.err .. data
|
||||
if #self.err > MAX_ERR_BYTES then self.err = self.err:sub(-MAX_ERR_BYTES) end
|
||||
end
|
||||
end,
|
||||
}, function(res)
|
||||
vim.schedule(function()
|
||||
self.closed = true
|
||||
if self.killer then pcall(function() self.killer:stop(); self.killer:close() end); self.killer = nil end
|
||||
local waiting = self.waiting
|
||||
self.waiting = {}
|
||||
for _, cb in pairs(waiting) do cb({ code = -32000, message = "the agent stopped" }, nil) end
|
||||
if on.exit then on.exit(res.code, table.concat(self.err)) end
|
||||
for id in pairs(self.timers) do self:_untime(id) end
|
||||
-- The exit is said first, so that what was waited for fails knowing the agent is gone.
|
||||
if on.exit then pcall(on.exit, res.code, self.err, res.signal) end
|
||||
for _, cb in pairs(waiting) do pcall(cb, { code = -32000, message = "the agent stopped" }, nil) end
|
||||
end)
|
||||
end)
|
||||
if not ok then return nil, tostring(proc) end
|
||||
@@ -33,21 +39,32 @@ function M.start(cmd, on, opts)
|
||||
return self
|
||||
end
|
||||
|
||||
--- Bytes from the agent. A line longer than the reader keeps is dropped whole: what was read of
|
||||
--- it, and the rest of it up to its line break — never a message that merely follows it. The
|
||||
--- same reading as the VS Code extension's (vscode/src/rpc.js); tests/rules/rpc_lines.json.
|
||||
function M:_feed(data)
|
||||
if #self.buf + #data > MAX_BUF_BYTES then
|
||||
-- Drop oversized unterminated line rather than exhausting editor memory.
|
||||
self.buf = ""
|
||||
return
|
||||
end
|
||||
self.buf = self.buf .. data
|
||||
while true do
|
||||
local nl = self.buf:find("\n", 1, true)
|
||||
if not nl then break end
|
||||
if not nl then
|
||||
if #self.buf > (self.max_line or MAX_LINE_BYTES) then
|
||||
self.buf = ""
|
||||
self.dropping = true -- the rest of that line, when its end comes, is not a message
|
||||
end
|
||||
break
|
||||
end
|
||||
local line = self.buf:sub(1, nl - 1)
|
||||
self.buf = self.buf:sub(nl + 1)
|
||||
if line:match("%S") then
|
||||
if self.dropping then
|
||||
self.dropping = false
|
||||
elseif line:match("%S") then
|
||||
local ok, msg = pcall(vim.json.decode, line, { luanil = { object = true, array = true } })
|
||||
if ok and type(msg) == "table" then vim.schedule(function() self:_message(msg) end) end
|
||||
if ok and type(msg) == "table" then
|
||||
vim.schedule(function() self:_message(msg) end)
|
||||
else
|
||||
-- Not the protocol: something printed on stdout. Kept with what the agent said on stderr.
|
||||
self.err = (self.err .. "[stdout] " .. line:sub(1, 400) .. "\n"):sub(-MAX_ERR_BYTES)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -65,38 +82,78 @@ function M:_message(msg)
|
||||
local ok, e = pcall(self.on.request, msg.method, msg.params or {}, reply)
|
||||
if not ok then reply(nil, { code = -32603, message = tostring(e) }) end
|
||||
elseif self.on.notify then
|
||||
pcall(self.on.notify, msg.method, msg.params or {})
|
||||
-- A notification has nobody to tell when it fails here: said where the agent's own words are kept.
|
||||
local ok, e = pcall(self.on.notify, msg.method, msg.params or {})
|
||||
if not ok then
|
||||
self.err = (self.err .. "[editor] " .. tostring(msg.method) .. " was not taken in: " .. tostring(e):sub(1, 300) .. "\n"):sub(-MAX_ERR_BYTES)
|
||||
end
|
||||
end
|
||||
elseif msg.id ~= nil then
|
||||
local cb = self.waiting[msg.id]
|
||||
self.waiting[msg.id] = nil
|
||||
self:_untime(msg.id)
|
||||
if cb then cb(msg.error, msg.result) end
|
||||
end
|
||||
end
|
||||
|
||||
function M:_untime(id)
|
||||
local t = self.timers[id]
|
||||
if not t then return end
|
||||
self.timers[id] = nil
|
||||
pcall(function() t:stop(); t:close() end)
|
||||
end
|
||||
|
||||
function M:_write(msg)
|
||||
if self.closed then return end
|
||||
pcall(function() self.proc:write(vim.json.encode(msg) .. "\n") end)
|
||||
end
|
||||
|
||||
--- A request; `cb(err, result)` on the main loop.
|
||||
function M:request(method, params, cb)
|
||||
--- A request; `cb(err, result)` on the main loop. `timeout_ms`: no answer by then is an error
|
||||
--- (`err.timeout`), and an answer that comes later is dropped.
|
||||
function M:request(method, params, cb, timeout_ms)
|
||||
if self.closed then return cb and cb({ code = -32000, message = "the agent is not running" }, nil) end
|
||||
local id = self.next_id
|
||||
self.next_id = id + 1
|
||||
self.waiting[id] = cb or function() end
|
||||
if timeout_ms and timeout_ms > 0 then
|
||||
local t = vim.uv.new_timer()
|
||||
self.timers[id] = t
|
||||
t:start(timeout_ms, 0, vim.schedule_wrap(function()
|
||||
self:_untime(id)
|
||||
local waiting = self.waiting[id]
|
||||
self.waiting[id] = nil
|
||||
if waiting then
|
||||
waiting({ code = -32001, timeout = true,
|
||||
message = ("the LLeMbas CLI did not answer %s within %d seconds"):format(method, math.floor(timeout_ms / 1000 + 0.5)) }, nil)
|
||||
end
|
||||
end))
|
||||
end
|
||||
self:_write({ jsonrpc = "2.0", id = id, method = method, params = params })
|
||||
return id
|
||||
end
|
||||
|
||||
--- What the agent wrote on stderr (its end, when it was long).
|
||||
function M:stderr() return self.err end
|
||||
|
||||
function M:notify(method, params)
|
||||
self:_write({ jsonrpc = "2.0", method = method, params = params })
|
||||
end
|
||||
|
||||
--- End the process: its input is closed (the CLI ends by itself then), it is asked to stop, and
|
||||
--- one that is still there five seconds later is killed. Nothing is left running.
|
||||
function M:stop()
|
||||
if self.closed then return end
|
||||
if self.closed or self.stopping then return end
|
||||
self.stopping = true
|
||||
pcall(function() self.proc:write(nil) end)
|
||||
pcall(function() self.proc:kill(15) end)
|
||||
local t = vim.uv.new_timer()
|
||||
self.killer = t
|
||||
t:start(M.KILL_AFTER_MS, 0, function()
|
||||
pcall(function() t:stop(); t:close() end)
|
||||
if not self.closed then pcall(function() self.proc:kill(9) end) end
|
||||
end)
|
||||
-- The timer must not keep an editor that is quitting alive.
|
||||
pcall(function() t:unref() end)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,112 @@
|
||||
-- Which files the agent showed may be opened: only kinds that are merely looked at or listened
|
||||
-- to, and only when the file's first bytes are that kind and its name ends as that kind does (the
|
||||
-- system picks its program by the name, so a name the bytes do not back is never handed to it).
|
||||
-- The same rule as the VS Code extension's (vscode/src/media.js); tests/rules/openable.json holds
|
||||
-- the cases both must answer alike.
|
||||
local M = {}
|
||||
|
||||
local TEXT_ENDINGS = {}
|
||||
for _, e in ipairs({ "txt", "text", "log", "md", "markdown", "csv", "tsv", "json", "jsonl", "yaml", "yml", "toml", "ini", "diff", "patch" }) do
|
||||
TEXT_ENDINGS[e] = true
|
||||
end
|
||||
|
||||
local function has(list, v) return vim.tbl_contains(list, v) end
|
||||
|
||||
local function picture(b)
|
||||
if #b < 12 then return nil end
|
||||
if b:sub(1, 6) == "\137PNG\r\n" then return { "png" } end
|
||||
if b:sub(1, 3) == "\255\216\255" then return { "jpg", "jpeg" } end
|
||||
if b:sub(1, 6) == "GIF87a" or b:sub(1, 6) == "GIF89a" then return { "gif" } end
|
||||
if b:sub(1, 4) == "RIFF" and b:sub(9, 12) == "WEBP" then return { "webp" } end
|
||||
if b:sub(5, 8) == "ftyp" and (b:sub(9, 12) == "avif" or b:sub(9, 12) == "avis") then return { "avif" } end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function brand(b) return b:sub(5, 8) == "ftyp" and b:sub(9, 12) or "" end
|
||||
local function one_of(v, list) return has(list, v) end
|
||||
|
||||
local KINDS = {
|
||||
{ "pdf", { "pdf" }, function(b) return b:sub(1, 5) == "%PDF-" end },
|
||||
{ "audio", { "mp3" }, function(b)
|
||||
return b:sub(1, 3) == "ID3" or (b:byte(1) == 0xff and bit.band(b:byte(2), 0xe6) == 0xe2)
|
||||
end },
|
||||
{ "audio", { "wav" }, function(b) return b:sub(1, 4) == "RIFF" and b:sub(9, 12) == "WAVE" end },
|
||||
{ "audio", { "ogg", "oga", "opus" }, function(b) return b:sub(1, 4) == "OggS" end },
|
||||
{ "audio", { "flac" }, function(b) return b:sub(1, 4) == "fLaC" end },
|
||||
{ "audio", { "m4a" }, function(b) return one_of(brand(b), { "M4A ", "M4B ", "mp42", "isom" }) end },
|
||||
{ "video", { "mp4", "m4v" }, function(b)
|
||||
local br = brand(b)
|
||||
return one_of(br, { "isom", "mp41", "mp42", "avc1", "M4V ", "dash" }) or br:match("^iso[2-9]$") ~= nil
|
||||
end },
|
||||
{ "video", { "mov" }, function(b) return brand(b) == "qt " end },
|
||||
{ "video", { "webm", "mkv" }, function(b) return b:sub(1, 4) == "\26\69\223\163" end },
|
||||
}
|
||||
|
||||
local function looks_like_text(b)
|
||||
if #b == 0 then return false end
|
||||
for i = 1, #b do
|
||||
local c = b:byte(i)
|
||||
if c == 0 or (c < 0x20 and c ~= 0x09 and c ~= 0x0a and c ~= 0x0d and c ~= 0x0c) then return false end
|
||||
end
|
||||
-- The window may end inside a character; up to three bytes are let go before judging.
|
||||
for cut = 0, math.min(3, #b - 1) do
|
||||
if M._valid_utf8(b:sub(1, #b - cut)) then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
--- Whether `s` is well-formed UTF-8.
|
||||
function M._valid_utf8(s)
|
||||
local i, n = 1, #s
|
||||
while i <= n do
|
||||
local c = s:byte(i)
|
||||
local more, low
|
||||
if c < 0x80 then more = 0
|
||||
elseif c >= 0xc2 and c <= 0xdf then more = 1
|
||||
elseif c >= 0xe0 and c <= 0xef then more = 2
|
||||
elseif c >= 0xf0 and c <= 0xf4 then more = 3
|
||||
else return false end
|
||||
if i + more > n then return false end
|
||||
for k = 1, more do
|
||||
low = s:byte(i + k)
|
||||
if low < 0x80 or low > 0xbf then return false end
|
||||
end
|
||||
-- No overlong forms, no surrogates, nothing past U+10FFFF.
|
||||
local second = more > 0 and s:byte(i + 1) or 0
|
||||
if (c == 0xe0 and second < 0xa0) or (c == 0xed and second > 0x9f) or (c == 0xf0 and second < 0x90) or (c == 0xf4 and second > 0x8f) then
|
||||
return false
|
||||
end
|
||||
i = i + more + 1
|
||||
end
|
||||
return true
|
||||
end
|
||||
|
||||
--- What a shown file is, from its first bytes (`head`, a string) and its name: "image", "pdf",
|
||||
--- "audio", "video" or "text" when it may be opened, nil when it may only be named.
|
||||
function M.openable(head, name)
|
||||
local ending = (tostring(name or ""):match("%.([%w]+)$") or ""):lower()
|
||||
if type(head) ~= "string" or ending == "" then return nil end
|
||||
local pic = picture(head)
|
||||
if pic then return has(pic, ending) and "image" or nil end
|
||||
local known = false
|
||||
for _, k in ipairs(KINDS) do
|
||||
if #head >= 12 and k[3](head) then
|
||||
if has(k[2], ending) then return k[1] end
|
||||
known = true
|
||||
end
|
||||
end
|
||||
if known then return nil end -- the bytes are a kind the name does not say
|
||||
if TEXT_ENDINGS[ending] and looks_like_text(head) then return "text" end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- The first bytes of the file at `path`, or nil.
|
||||
function M.head(path)
|
||||
local f = io.open(path, "rb")
|
||||
if not f then return nil end
|
||||
local b = f:read(4096)
|
||||
f:close()
|
||||
return b or ""
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,129 @@
|
||||
-- What the person chose in this editor, remembered across restarts: at two levels, for everywhere
|
||||
-- and for a working directory, the directory's own winning. One JSON file in Neovim's state
|
||||
-- directory. Only the editor's own things are here (the mode, the effort, suggestions and AI on or
|
||||
-- off, the bars and their widths): the models are remembered by the LLeMbas CLI and the account.
|
||||
local M = {}
|
||||
|
||||
--- The keys that are kept, and the kind of value each takes.
|
||||
M.KEYS = {
|
||||
mode = "string", effort = "string", autocomplete = "boolean", ai = "boolean",
|
||||
top = "boolean", bottom = "boolean", tree = "boolean", chat = "boolean",
|
||||
tree_width = "number", chat_width = "number", hidden_files = "boolean",
|
||||
}
|
||||
M.MAX_DIRECTORIES = 500
|
||||
M.enabled = true
|
||||
|
||||
function M.path() return vim.fn.stdpath("state") .. "/llembas/settings.json" end
|
||||
|
||||
local function empty() return { version = 1, global = {}, directories = {}, terminals = {}, seq = 0 } end
|
||||
|
||||
local function read()
|
||||
local f = io.open(M.path(), "r")
|
||||
if not f then return empty() end
|
||||
local text = f:read("*a")
|
||||
f:close()
|
||||
local ok, data = pcall(vim.json.decode, text, { luanil = { object = true, array = true } })
|
||||
if not ok or type(data) ~= "table" then return empty() end
|
||||
for _, k in ipairs({ "global", "directories", "terminals" }) do
|
||||
if type(data[k]) ~= "table" or vim.islist(data[k]) and next(data[k]) ~= nil then data[k] = {} end
|
||||
end
|
||||
data.seq = tonumber(data.seq) or 0
|
||||
return data
|
||||
end
|
||||
|
||||
local function write(data)
|
||||
local path = M.path()
|
||||
vim.fn.mkdir(vim.fs.dirname(path), "p", "0700")
|
||||
-- An empty table must be written as an object, or the next read finds a list.
|
||||
for _, k in ipairs({ "global", "directories", "terminals" }) do
|
||||
if next(data[k]) == nil then data[k] = vim.empty_dict() end
|
||||
end
|
||||
local tmp = ("%s.%d.tmp"):format(path, vim.uv.os_getpid())
|
||||
local f = io.open(tmp, "w")
|
||||
if not f then return false end
|
||||
f:write(vim.json.encode(data))
|
||||
f:close()
|
||||
pcall(vim.uv.fs_chmod, tmp, 384) -- 0600
|
||||
local ok = vim.uv.fs_rename(tmp, path)
|
||||
if not ok then pcall(os.remove, tmp) end
|
||||
return ok and true or false
|
||||
end
|
||||
|
||||
--- The directory's name as the store keys it: absolute, links resolved where it exists.
|
||||
function M.dir(cwd)
|
||||
cwd = cwd or vim.fn.getcwd()
|
||||
return vim.uv.fs_realpath(cwd) or vim.fs.normalize(cwd)
|
||||
end
|
||||
|
||||
local function known(level)
|
||||
local out = {}
|
||||
for k, v in pairs(type(level) == "table" and level or {}) do
|
||||
if k ~= "seq" and M.KEYS[k] and type(v) == M.KEYS[k] then out[k] = v end
|
||||
end
|
||||
return out
|
||||
end
|
||||
|
||||
--- What is remembered for `cwd`: the machine-wide values, with the directory's own over them.
|
||||
--- Second value: the directory's own entry alone.
|
||||
function M.get(cwd)
|
||||
if not M.enabled then return {}, {} end
|
||||
local data = read()
|
||||
local own = known(data.directories[M.dir(cwd)])
|
||||
return vim.tbl_extend("force", known(data.global), own), own
|
||||
end
|
||||
|
||||
--- Remember `key = value` for the directory (`value` nil forgets it there).
|
||||
function M.set(key, value, cwd)
|
||||
if not M.enabled or not M.KEYS[key] then return false end
|
||||
if value ~= nil and type(value) ~= M.KEYS[key] then return false end
|
||||
local data = read()
|
||||
local dir = M.dir(cwd)
|
||||
local entry = type(data.directories[dir]) == "table" and data.directories[dir] or {}
|
||||
if entry[key] == value then return true end
|
||||
entry[key] = value
|
||||
data.seq = data.seq + 1
|
||||
entry.seq = data.seq
|
||||
data.directories[dir] = entry
|
||||
-- The directories written longest ago go first.
|
||||
local names = vim.tbl_keys(data.directories)
|
||||
if #names > M.MAX_DIRECTORIES then
|
||||
table.sort(names, function(a, b) return (tonumber(data.directories[a].seq) or 0) < (tonumber(data.directories[b].seq) or 0) end)
|
||||
for i = 1, #names - M.MAX_DIRECTORIES do data.directories[names[i]] = nil end
|
||||
end
|
||||
return write(data)
|
||||
end
|
||||
|
||||
--- Make what holds in `cwd` now the machine-wide default: what a directory without a choice of
|
||||
--- its own starts with.
|
||||
function M.make_default(cwd)
|
||||
if not M.enabled then return false end
|
||||
local data = read()
|
||||
local now = vim.tbl_extend("force", known(data.global), known(data.directories[M.dir(cwd)]))
|
||||
data.global = now
|
||||
return write(data)
|
||||
end
|
||||
|
||||
--- Forget what the directory chose for itself: it takes the machine-wide values again.
|
||||
function M.forget(cwd)
|
||||
if not M.enabled then return false end
|
||||
local data = read()
|
||||
if data.directories[M.dir(cwd)] == nil then return true end
|
||||
data.directories[M.dir(cwd)] = nil
|
||||
return write(data)
|
||||
end
|
||||
|
||||
--- Whether the key chords were seen to arrive from the terminal named `id` (nil: never seen).
|
||||
function M.terminal(id)
|
||||
if not M.enabled or not id or id == "" then return nil end
|
||||
return read().terminals[id] == true or nil
|
||||
end
|
||||
|
||||
function M.saw_terminal(id)
|
||||
if not M.enabled or not id or id == "" then return end
|
||||
local data = read()
|
||||
if data.terminals[id] == true then return end
|
||||
data.terminals[id] = true
|
||||
write(data)
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,527 @@
|
||||
-- The file tree: the working directory as lines, in a window on the left. Directories open and
|
||||
-- close, the file you are in is followed and marked, and each row carries one mark of its git
|
||||
-- state. New, rename and delete are asked for in words; nothing is removed without a yes.
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace("llembas-tree")
|
||||
|
||||
local T = {
|
||||
buf = nil, root = nil, open = {}, rows = {}, hidden = false, filter = "",
|
||||
git = {}, git_dirs = {}, git_root = nil, branch = nil, current = nil, git_job = 0,
|
||||
}
|
||||
M.SCAN_MAX = 4000 -- how many entries a filter looks through
|
||||
|
||||
--- Asked before anything is deleted. A function of its own so that the tests can answer.
|
||||
function M._confirm(question) return vim.fn.confirm(question, "&Yes\n&No", 2) == 1 end
|
||||
|
||||
--- The program that moves a file to the trash, as a command without the file, or nil.
|
||||
function M._trash()
|
||||
if vim.fn.executable("gio") == 1 then return { "gio", "trash", "--" } end
|
||||
if vim.fn.executable("trash-put") == 1 then return { "trash-put", "--" } end
|
||||
if vim.fn.executable("trash") == 1 then return { "trash" } end
|
||||
return nil
|
||||
end
|
||||
|
||||
local function valid() return T.buf and vim.api.nvim_buf_is_valid(T.buf) end
|
||||
|
||||
function M.win()
|
||||
if not valid() then return nil end
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.api.nvim_win_get_buf(w) == T.buf then return w end
|
||||
end
|
||||
end
|
||||
|
||||
local function scan(dir)
|
||||
local out = {}
|
||||
local fd = vim.uv.fs_scandir(dir)
|
||||
while fd do
|
||||
local name, kind = vim.uv.fs_scandir_next(fd)
|
||||
if not name then break end
|
||||
if kind == "link" or not kind then
|
||||
local st = vim.uv.fs_stat(dir .. "/" .. name)
|
||||
kind = st and st.type or "file"
|
||||
end
|
||||
if name ~= ".git" and (T.hidden or name:sub(1, 1) ~= ".") then
|
||||
out[#out + 1] = { name = name, dir = kind == "directory", path = dir .. "/" .. name }
|
||||
end
|
||||
end
|
||||
table.sort(out, function(a, b)
|
||||
if a.dir ~= b.dir then return a.dir end
|
||||
local x, y = a.name:lower(), b.name:lower()
|
||||
if x ~= y then return x < y end
|
||||
return a.name < b.name
|
||||
end)
|
||||
return out
|
||||
end
|
||||
|
||||
local function relative(path)
|
||||
if path == T.root then return "" end
|
||||
return path:sub(#T.root + 2)
|
||||
end
|
||||
|
||||
local function build()
|
||||
local rows = {}
|
||||
if T.filter ~= "" then
|
||||
-- A filter is a flat list of the files whose path has the text, wherever they are.
|
||||
local needle, seen = T.filter:lower(), 0
|
||||
local function walk(dir)
|
||||
for _, e in ipairs(scan(dir)) do
|
||||
seen = seen + 1
|
||||
if seen > M.SCAN_MAX then return end
|
||||
if e.dir then
|
||||
if e.name ~= "node_modules" then walk(e.path) end
|
||||
elseif relative(e.path):lower():find(needle, 1, true) then
|
||||
rows[#rows + 1] = { path = e.path, name = relative(e.path), dir = false, depth = 0 }
|
||||
end
|
||||
end
|
||||
end
|
||||
walk(T.root)
|
||||
return rows
|
||||
end
|
||||
local function walk(dir, depth)
|
||||
for _, e in ipairs(scan(dir)) do
|
||||
rows[#rows + 1] = { path = e.path, name = e.name, dir = e.dir, depth = depth }
|
||||
if e.dir and T.open[e.path] then walk(e.path, depth + 1) end
|
||||
end
|
||||
end
|
||||
walk(T.root, 0)
|
||||
return rows
|
||||
end
|
||||
|
||||
local MARK_HL = {
|
||||
M = "LLeMbasTreeChanged", A = "LLeMbasTreeAdded", ["?"] = "LLeMbasTreeNew", D = "LLeMbasTreeDeleted",
|
||||
["!"] = "LLeMbasTreeConflict", ["•"] = "LLeMbasTreeChanged",
|
||||
}
|
||||
|
||||
local function mark_of(row)
|
||||
if row.dir then return T.git_dirs[row.path] and "•" or " " end
|
||||
return T.git[row.path] or " "
|
||||
end
|
||||
|
||||
--- A row as its line: the git mark, the indent, the fold mark of a directory, the name.
|
||||
local function line_of(row)
|
||||
local fold = row.dir and (T.open[row.path] and "▾ " or "▸ ") or " "
|
||||
-- A name is shown as text on one line, whatever bytes it has.
|
||||
local name = row.name:gsub("[%c]", "?")
|
||||
return mark_of(row) .. " " .. (" "):rep(row.depth) .. fold .. name .. (row.dir and "/" or "")
|
||||
end
|
||||
|
||||
function M.render()
|
||||
if not valid() then return end
|
||||
T.rows = build()
|
||||
local lines = {}
|
||||
for i, r in ipairs(T.rows) do lines[i] = line_of(r) end
|
||||
if #lines == 0 then lines = { T.filter ~= "" and " (no file has that in its name)" or " (empty)" } end
|
||||
local win = M.win()
|
||||
local at = win and vim.api.nvim_win_get_cursor(win) or nil
|
||||
vim.bo[T.buf].modifiable = true
|
||||
vim.api.nvim_buf_set_lines(T.buf, 0, -1, false, lines)
|
||||
vim.bo[T.buf].modifiable = false
|
||||
vim.api.nvim_buf_clear_namespace(T.buf, ns, 0, -1)
|
||||
for i, r in ipairs(T.rows) do
|
||||
local mark = mark_of(r)
|
||||
if mark ~= " " then
|
||||
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, 0, { end_col = #mark, hl_group = MARK_HL[mark] or "LLeMbasTreeChanged" })
|
||||
end
|
||||
if r.dir then
|
||||
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, #mark + 1, { end_col = #lines[i], hl_group = "LLeMbasTreeDirectory" })
|
||||
end
|
||||
if r.path == T.current then
|
||||
vim.api.nvim_buf_set_extmark(T.buf, ns, i - 1, 0, { line_hl_group = "LLeMbasTreeCurrent" })
|
||||
end
|
||||
end
|
||||
if win and at then pcall(vim.api.nvim_win_set_cursor, win, { math.min(at[1], #lines), 0 }) end
|
||||
if win then
|
||||
vim.wo[win].winbar = T.filter ~= "" and (" / " .. T.filter:gsub("%%", "%%%%")) or ""
|
||||
end
|
||||
end
|
||||
|
||||
--- The row under the cursor of the tree's window, or nil.
|
||||
local function row_here()
|
||||
local win = M.win()
|
||||
if not win then return nil end
|
||||
return T.rows[vim.api.nvim_win_get_cursor(win)[1]]
|
||||
end
|
||||
|
||||
local function go_to(path)
|
||||
local win = M.win()
|
||||
if not win then return false end
|
||||
for i, r in ipairs(T.rows) do
|
||||
if r.path == path then
|
||||
pcall(vim.api.nvim_win_set_cursor, win, { i, 0 })
|
||||
return true
|
||||
end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
--- The window a file is opened in: the one the layout says is the code's, else any window with
|
||||
--- an ordinary buffer, else a new one beside the tree.
|
||||
local function code_win()
|
||||
local ok, w = pcall(function() return require("llembas.layout").code_win() end)
|
||||
if ok and w and vim.api.nvim_win_is_valid(w) then return w end
|
||||
for _, win in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
local b = vim.api.nvim_win_get_buf(win)
|
||||
if vim.api.nvim_win_get_config(win).relative == "" and vim.bo[b].buftype == "" then return win end
|
||||
end
|
||||
local tw = M.win()
|
||||
if tw then vim.api.nvim_set_current_win(tw) end
|
||||
vim.cmd("rightbelow vnew")
|
||||
local win = vim.api.nvim_get_current_win()
|
||||
if tw then pcall(vim.api.nvim_win_set_width, tw, M.width or 26) end
|
||||
return win
|
||||
end
|
||||
|
||||
function M.open_file(path)
|
||||
local win = code_win()
|
||||
vim.api.nvim_set_current_win(win)
|
||||
local ok, err = pcall(vim.cmd.edit, vim.fn.fnameescape(path))
|
||||
if not ok then vim.notify("LLeMbas: " .. tostring(err):gsub("^.-:%s*", ""), vim.log.levels.WARN) end
|
||||
end
|
||||
|
||||
--- Enter on a row: a file is opened, a directory opens or closes.
|
||||
function M.activate(only_open)
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
if r.dir then
|
||||
if T.open[r.path] and only_open then return end
|
||||
T.open[r.path] = not T.open[r.path] or nil
|
||||
M.render()
|
||||
go_to(r.path)
|
||||
else
|
||||
M.open_file(r.path)
|
||||
end
|
||||
end
|
||||
|
||||
--- ← on a row: an open directory closes; anything else goes to the directory it is in.
|
||||
function M.collapse()
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
if r.dir and T.open[r.path] then
|
||||
T.open[r.path] = nil
|
||||
M.render()
|
||||
return go_to(r.path)
|
||||
end
|
||||
local parent = vim.fs.dirname(r.path)
|
||||
if parent and parent ~= T.root then go_to(parent) end
|
||||
end
|
||||
|
||||
--- The directory a new file goes into: the directory under the cursor, or the one the file under
|
||||
--- the cursor is in.
|
||||
local function dir_here()
|
||||
local r = row_here()
|
||||
if not r then return T.root end
|
||||
return r.dir and r.path or vim.fs.dirname(r.path)
|
||||
end
|
||||
|
||||
local function inside(path)
|
||||
return path == T.root or vim.startswith(path, T.root .. "/")
|
||||
end
|
||||
|
||||
--- A name typed by the person as a path under `base`; nil when it would leave the tree's root.
|
||||
local function resolve(base, name)
|
||||
name = vim.trim(name or "")
|
||||
if name == "" then return nil end
|
||||
local path = vim.fs.normalize(name:sub(1, 1) == "/" and name or (base .. "/" .. name))
|
||||
if not inside(path) or path == T.root then return nil, "that is outside " .. T.root end
|
||||
return path
|
||||
end
|
||||
|
||||
local function reveal(path)
|
||||
local dir = vim.fs.dirname(path)
|
||||
while dir and inside(dir) and dir ~= T.root do
|
||||
T.open[dir] = true
|
||||
dir = vim.fs.dirname(dir)
|
||||
end
|
||||
end
|
||||
|
||||
--- A directory shown in the tree: it and the directories above it open, the cursor on its row.
|
||||
--- False when it is not under the tree's root (or the tree is not open), and nothing changes.
|
||||
function M.show_dir(path)
|
||||
if not valid() or not T.root or not path then return false end
|
||||
path = vim.fs.normalize(vim.uv.fs_realpath(path) or path)
|
||||
if not inside(path) then return false end
|
||||
if T.filter ~= "" then T.filter = "" end
|
||||
if path ~= T.root then
|
||||
reveal(path)
|
||||
T.open[path] = true
|
||||
end
|
||||
M.render()
|
||||
if path ~= T.root then go_to(path) end
|
||||
return true
|
||||
end
|
||||
|
||||
--- Make a file, or a directory when the name ends in `/`. Asks for the name when none is given.
|
||||
function M.create(name)
|
||||
local base = dir_here()
|
||||
local function make(text)
|
||||
if not text or not text:match("%S") then return end
|
||||
local is_dir = vim.trim(text):sub(-1) == "/"
|
||||
local path, why = resolve(base, text)
|
||||
if not path then return vim.notify("LLeMbas: not made" .. (why and (": " .. why) or ""), vim.log.levels.WARN) end
|
||||
if vim.uv.fs_stat(path) then return vim.notify("LLeMbas: " .. relative(path) .. " is there already", vim.log.levels.WARN) end
|
||||
if is_dir then
|
||||
vim.fn.mkdir(path, "p")
|
||||
T.open[path] = true
|
||||
else
|
||||
vim.fn.mkdir(vim.fs.dirname(path), "p")
|
||||
local f, err = io.open(path, "w")
|
||||
if not f then return vim.notify("LLeMbas: not made: " .. tostring(err), vim.log.levels.WARN) end
|
||||
f:close()
|
||||
end
|
||||
reveal(path)
|
||||
M.render()
|
||||
go_to(path)
|
||||
M.git_refresh()
|
||||
if not is_dir then M.open_file(path) end
|
||||
end
|
||||
if name then return make(name) end
|
||||
local shown = relative(base)
|
||||
vim.ui.input({ prompt = ("New file in %s/ (a name ending in / makes a directory): "):format(shown == "" and "." or shown) }, make)
|
||||
end
|
||||
|
||||
--- Rename or move the row under the cursor. An open buffer of the file follows it.
|
||||
function M.rename(to)
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
local function move(text)
|
||||
if not text or not text:match("%S") then return end
|
||||
local path, why = resolve(T.root, text)
|
||||
if not path then return vim.notify("LLeMbas: not moved" .. (why and (": " .. why) or ""), vim.log.levels.WARN) end
|
||||
if path == r.path then return end
|
||||
if vim.uv.fs_stat(path) then return vim.notify("LLeMbas: " .. relative(path) .. " is there already", vim.log.levels.WARN) end
|
||||
vim.fn.mkdir(vim.fs.dirname(path), "p")
|
||||
local ok, err = vim.uv.fs_rename(r.path, path)
|
||||
if not ok then return vim.notify("LLeMbas: not moved: " .. tostring(err), vim.log.levels.WARN) end
|
||||
-- Buffers of the file, or of files under the directory, take the new name.
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
local name = vim.api.nvim_buf_get_name(b)
|
||||
if vim.bo[b].buftype == "" and (name == r.path or vim.startswith(name, r.path .. "/")) then
|
||||
local new = path .. name:sub(#r.path + 1)
|
||||
pcall(vim.api.nvim_buf_set_name, b, new)
|
||||
if vim.api.nvim_buf_is_loaded(b) then
|
||||
pcall(vim.api.nvim_buf_call, b, function() vim.cmd("silent! write!") end)
|
||||
end
|
||||
end
|
||||
end
|
||||
if T.open[r.path] then T.open[r.path], T.open[path] = nil, true end
|
||||
if T.current == r.path then T.current = path end
|
||||
reveal(path)
|
||||
M.render()
|
||||
go_to(path)
|
||||
M.git_refresh()
|
||||
end
|
||||
if to then return move(to) end
|
||||
vim.ui.input({ prompt = "Rename or move to: ", default = relative(r.path) }, move)
|
||||
end
|
||||
|
||||
--- Delete the row under the cursor, after asking: to the trash where the system has one.
|
||||
function M.delete()
|
||||
local r = row_here()
|
||||
if not r then return end
|
||||
local name = relative(r.path) .. (r.dir and "/" or "")
|
||||
local trash = M._trash()
|
||||
local question = trash and ("Move %s to the trash?"):format(name)
|
||||
or ("Delete %s for good? (No trash was found on this system.)"):format(name)
|
||||
if not M._confirm(question) then return end
|
||||
local ok, why = true, nil
|
||||
if trash then
|
||||
local cmd = vim.list_extend(vim.list_slice(trash), { r.path })
|
||||
local done = vim.system(cmd, { text = true }):wait(15000)
|
||||
ok, why = done.code == 0, vim.trim(done.stderr or "")
|
||||
else
|
||||
ok = vim.fn.delete(r.path, r.dir and "rf" or "") == 0
|
||||
end
|
||||
if not ok then return vim.notify("LLeMbas: not deleted" .. (why and why ~= "" and (": " .. why) or ""), vim.log.levels.WARN) end
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
local bname = vim.api.nvim_buf_get_name(b)
|
||||
if vim.bo[b].buftype == "" and (bname == r.path or vim.startswith(bname, r.path .. "/")) and not vim.bo[b].modified then
|
||||
-- A window keeps its place: the buffer goes, an empty one stands in.
|
||||
for _, w in ipairs(vim.fn.win_findbuf(b)) do
|
||||
pcall(vim.api.nvim_win_call, w, function() vim.cmd("enew") end)
|
||||
end
|
||||
pcall(vim.api.nvim_buf_delete, b, {})
|
||||
end
|
||||
end
|
||||
T.open[r.path] = nil
|
||||
M.render()
|
||||
M.git_refresh()
|
||||
end
|
||||
|
||||
--- Show only the files whose path has `text` (empty: the tree again).
|
||||
function M.set_filter(text)
|
||||
T.filter = text or ""
|
||||
M.render()
|
||||
end
|
||||
|
||||
--- `/`: the filter, typed on the command line and applied at every key.
|
||||
function M.ask_filter()
|
||||
local group = vim.api.nvim_create_augroup("llembas-tree-filter", { clear = true })
|
||||
vim.api.nvim_create_autocmd("CmdlineChanged", {
|
||||
group = group,
|
||||
callback = function()
|
||||
M.set_filter(vim.fn.getcmdline())
|
||||
vim.cmd("redraw")
|
||||
end,
|
||||
})
|
||||
local ok, text = pcall(vim.fn.input, { prompt = "/", default = T.filter, cancelreturn = "" })
|
||||
pcall(vim.api.nvim_del_augroup_by_id, group)
|
||||
M.set_filter(ok and text or "")
|
||||
end
|
||||
|
||||
function M.toggle_hidden(on)
|
||||
if on == nil then T.hidden = not T.hidden else T.hidden = on end
|
||||
pcall(function() require("llembas.store").set("hidden_files", T.hidden) end)
|
||||
M.render()
|
||||
end
|
||||
|
||||
function M.refresh()
|
||||
M.render()
|
||||
M.git_refresh()
|
||||
end
|
||||
|
||||
--- One `git status` for the whole tree, off the main loop; the rows are marked when it answers.
|
||||
function M.git_refresh()
|
||||
if not T.root or vim.fn.executable("git") == 0 then return end
|
||||
T.git_job = T.git_job + 1
|
||||
local job, root = T.git_job, T.root
|
||||
local ok = pcall(vim.system, { "git", "-C", root, "status", "--porcelain=v1", "-z", "--branch", "--untracked-files=normal" },
|
||||
{ text = true, env = { GIT_OPTIONAL_LOCKS = "0" } },
|
||||
vim.schedule_wrap(function(done)
|
||||
if job ~= T.git_job or root ~= T.root then return end
|
||||
local git, dirs, branch = {}, {}, nil
|
||||
if done.code == 0 then
|
||||
local top = vim.trim(vim.fn.system({ "git", "-C", root, "rev-parse", "--show-toplevel" }))
|
||||
local parts = vim.split(done.stdout or "", "\0", { plain = true })
|
||||
local i = 1
|
||||
while i <= #parts do
|
||||
local e = parts[i]
|
||||
if e:sub(1, 2) == "##" then
|
||||
branch = e:sub(4):gsub("%.%.%..*$", ""):gsub("^No commits yet on ", "")
|
||||
elseif #e > 3 then
|
||||
local x, y, path = e:sub(1, 1), e:sub(2, 2), e:sub(4)
|
||||
if x == "R" or x == "C" then i = i + 1 end -- the name it had follows
|
||||
local mark = (x == "U" or y == "U" or (x == "A" and y == "A") or (x == "D" and y == "D")) and "!"
|
||||
or (x == "?" and "?") or ((x == "D" or y == "D") and "D") or ((x == "A") and "A") or "M"
|
||||
local full = top .. "/" .. path:gsub("/$", "")
|
||||
git[full] = mark
|
||||
local dir = full
|
||||
if path:sub(-1) == "/" then dirs[full] = true end
|
||||
while true do
|
||||
dir = vim.fs.dirname(dir)
|
||||
if not dir or #dir < #top or dirs[dir] then break end
|
||||
dirs[dir] = true
|
||||
end
|
||||
end
|
||||
i = i + 1
|
||||
end
|
||||
end
|
||||
T.git, T.git_dirs, T.branch = git, dirs, branch
|
||||
M.render()
|
||||
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
|
||||
end))
|
||||
if not ok then T.git, T.git_dirs = {}, {} end
|
||||
end
|
||||
|
||||
--- The branch the tree's directory is on, or nil (not a repository, or not asked yet).
|
||||
function M.branch() return T.branch end
|
||||
|
||||
--- The file in `buf` is the one you are in: its directories open, its row is marked and shown.
|
||||
function M.follow(buf)
|
||||
if not valid() or T.filter ~= "" then return end
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
if name == "" or vim.bo[buf].buftype ~= "" or not T.root then return end
|
||||
name = vim.fs.normalize(name)
|
||||
if not vim.startswith(name, T.root .. "/") or name == T.current then return end
|
||||
T.current = name
|
||||
reveal(name)
|
||||
M.render()
|
||||
go_to(name)
|
||||
end
|
||||
|
||||
local function buffer()
|
||||
if valid() then return T.buf end
|
||||
T.buf = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[T.buf].buftype = "nofile"
|
||||
vim.bo[T.buf].bufhidden = "hide"
|
||||
vim.bo[T.buf].swapfile = false
|
||||
vim.bo[T.buf].modeline = false
|
||||
vim.bo[T.buf].undolevels = -1
|
||||
vim.bo[T.buf].filetype = "llembas-tree"
|
||||
pcall(vim.api.nvim_buf_set_name, T.buf, "llembas://tree")
|
||||
vim.bo[T.buf].modifiable = false
|
||||
require("llembas.keys").bind("tree", T.buf, {
|
||||
tree_open = function() M.activate(false) end,
|
||||
tree_close = M.collapse,
|
||||
tree_new = function() M.create() end,
|
||||
tree_rename = function() M.rename() end,
|
||||
tree_delete = M.delete,
|
||||
tree_filter = M.ask_filter,
|
||||
tree_hidden = function() M.toggle_hidden() end,
|
||||
tree_refresh = M.refresh,
|
||||
})
|
||||
-- → only opens: an open directory stays open (Enter and l open and close).
|
||||
vim.keymap.set("n", "<Right>", function() M.activate(true) end, { buffer = T.buf, nowait = true, silent = true, desc = "LLeMbas: Open the file, or the directory" })
|
||||
vim.keymap.set("n", "<2-LeftMouse>", function() M.activate(false) end, { buffer = T.buf, nowait = true, silent = true, desc = "LLeMbas: Open the file; open or close the directory" })
|
||||
local group = vim.api.nvim_create_augroup("llembas-tree", { clear = true })
|
||||
vim.api.nvim_create_autocmd("BufEnter", { group = group, callback = function(ev) M.follow(ev.buf) end })
|
||||
vim.api.nvim_create_autocmd({ "BufWritePost", "FocusGained" }, { group = group, callback = function() if M.win() then M.refresh() end end })
|
||||
vim.api.nvim_create_autocmd("DirChanged", {
|
||||
group = group,
|
||||
callback = function()
|
||||
if vim.v.event.scope == "global" and M.win() then M.set_root(vim.fn.getcwd()) end
|
||||
end,
|
||||
})
|
||||
return T.buf
|
||||
end
|
||||
|
||||
function M.set_root(dir)
|
||||
dir = vim.fs.normalize(vim.uv.fs_realpath(dir) or dir)
|
||||
if dir == T.root then return end
|
||||
T.root, T.open, T.git, T.git_dirs, T.branch, T.current, T.filter = dir, {}, {}, {}, nil, nil, ""
|
||||
M.refresh()
|
||||
end
|
||||
|
||||
--- Open the tree's window on the left, `width` columns. Returns the window. The focus stays.
|
||||
function M.open(width)
|
||||
require("llembas.ui").setup_highlights()
|
||||
buffer()
|
||||
M.width = width or M.width or 26
|
||||
local win = M.win()
|
||||
if win then return win end
|
||||
if not T.root then
|
||||
T.root = vim.fs.normalize(vim.uv.fs_realpath(vim.fn.getcwd()) or vim.fn.getcwd())
|
||||
local remembered = require("llembas.store").get()
|
||||
if remembered.hidden_files ~= nil then T.hidden = remembered.hidden_files end
|
||||
end
|
||||
local back = vim.api.nvim_get_current_win()
|
||||
vim.cmd("topleft vertical " .. M.width .. "split")
|
||||
win = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(win, T.buf)
|
||||
for k, v in pairs({
|
||||
wrap = false, number = false, relativenumber = false, signcolumn = "no", foldcolumn = "0", list = false,
|
||||
cursorline = true, winfixwidth = true, spell = false, statuscolumn = "",
|
||||
}) do
|
||||
vim.api.nvim_set_option_value(k, v, { scope = "local", win = win })
|
||||
end
|
||||
vim.wo[win].fillchars = "eob: "
|
||||
if vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back) end
|
||||
M.render()
|
||||
M.git_refresh()
|
||||
local cur = vim.api.nvim_get_current_buf()
|
||||
M.follow(cur)
|
||||
return win
|
||||
end
|
||||
|
||||
function M.close()
|
||||
local win = M.win()
|
||||
if win and #vim.api.nvim_tabpage_list_wins(0) > 1 then pcall(vim.api.nvim_win_close, win, true) end
|
||||
end
|
||||
|
||||
function M.is_open() return M.win() ~= nil end
|
||||
|
||||
--- The tree's lines as text, and its rows: for the tests and for anyone drawing it elsewhere.
|
||||
function M.lines() return valid() and vim.api.nvim_buf_get_lines(T.buf, 0, -1, false) or {} end
|
||||
function M.buf() return valid() and T.buf or nil end
|
||||
M._state = T
|
||||
|
||||
return M
|
||||
+54
-1
@@ -33,14 +33,50 @@ local HIGHLIGHTS = {
|
||||
LLeMbasStatusModel = { link = "Comment" },
|
||||
LLeMbasStatusBusy = { link = "DiagnosticWarn" },
|
||||
LLeMbasStatusAttach = { link = "DiagnosticHint" },
|
||||
-- The bars.
|
||||
LLeMbasBar = { link = "StatusLine" },
|
||||
LLeMbasBarVim = { link = "StatusLine" },
|
||||
-- The prompt and the settings lines.
|
||||
LLeMbasPromptPrefix = { link = "Special" },
|
||||
LLeMbasChip = { link = "DiagnosticHint" },
|
||||
LLeMbasLineLabel = { link = "Comment" },
|
||||
LLeMbasLineValue = { link = "Normal" },
|
||||
LLeMbasLineOff = { link = "Comment" },
|
||||
LLeMbasLineCurrent = { link = "Title" },
|
||||
-- The tree.
|
||||
LLeMbasTreeDirectory = { link = "Directory" },
|
||||
LLeMbasTreeCurrent = { link = "Visual" },
|
||||
LLeMbasTreeChanged = { link = "DiagnosticWarn" },
|
||||
LLeMbasTreeAdded = { link = "DiagnosticOk" },
|
||||
LLeMbasTreeNew = { link = "DiagnosticHint" },
|
||||
LLeMbasTreeDeleted = { link = "DiagnosticError" },
|
||||
LLeMbasTreeConflict = { link = "DiagnosticError" },
|
||||
}
|
||||
|
||||
-- The coloured cells of the bars: each takes its colour from a standard group and its ground
|
||||
-- from StatusLine, so that a row of cells has one ground whatever the colourscheme.
|
||||
local BAR_CELLS = {
|
||||
LLeMbasBarKey = "Special", LLeMbasBarTitle = "Title", LLeMbasBarSeparator = "WinSeparator", LLeMbasBarFact = "Comment",
|
||||
LLeMbasBarIdle = "DiagnosticOk", LLeMbasBarBusy = "DiagnosticWarn", LLeMbasBarWaiting = "DiagnosticInfo", LLeMbasBarOff = "Comment",
|
||||
}
|
||||
|
||||
local function bar_cells()
|
||||
local base = vim.api.nvim_get_hl(0, { name = "StatusLine", link = false })
|
||||
local fg, bg = base.fg, base.bg
|
||||
if base.reverse then fg, bg = bg, fg end
|
||||
for name, from in pairs(BAR_CELLS) do
|
||||
local own = vim.api.nvim_get_hl(0, { name = from, link = false })
|
||||
vim.api.nvim_set_hl(0, name, { default = true, fg = own.fg or fg, bg = bg, bold = own.bold, italic = own.italic })
|
||||
end
|
||||
end
|
||||
|
||||
local hi_installed = false
|
||||
|
||||
function M.setup_highlights()
|
||||
for name, spec in pairs(HIGHLIGHTS) do
|
||||
vim.api.nvim_set_hl(0, name, vim.tbl_extend("force", { default = true }, spec))
|
||||
end
|
||||
bar_cells()
|
||||
if not hi_installed then
|
||||
hi_installed = true
|
||||
local group = vim.api.nvim_create_augroup("llembas-highlights", { clear = true })
|
||||
@@ -50,6 +86,7 @@ function M.setup_highlights()
|
||||
for name, spec in pairs(HIGHLIGHTS) do
|
||||
vim.api.nvim_set_hl(0, name, vim.tbl_extend("force", { default = true }, spec))
|
||||
end
|
||||
bar_cells()
|
||||
end,
|
||||
})
|
||||
end
|
||||
@@ -78,7 +115,18 @@ function M.progress_bar(done, total, width)
|
||||
end
|
||||
|
||||
--- Welcome virtual lines shown in an empty transcript (never written to the buffer text).
|
||||
function M.welcome_virt_lines()
|
||||
function M.welcome_virt_lines(narrow)
|
||||
if narrow then
|
||||
-- For a bar of 34 columns: no line is wider than 32.
|
||||
return {
|
||||
{ { "", "Normal" } },
|
||||
{ { " ◈ ", "LLeMbasBrand" }, { "LLeMbas", "LLeMbasUserHeader" } },
|
||||
{ { " Waybread for the code ahead.", "LLeMbasNote" } },
|
||||
{ { "", "Normal" } },
|
||||
{ { " Type below; Enter sends.", "LLeMbasNote" } },
|
||||
{ { " Tab: ask, rewrite or add.", "LLeMbasNote" } },
|
||||
}
|
||||
end
|
||||
return {
|
||||
{ { "", "Normal" } },
|
||||
{ { " ◈ ", "LLeMbasBrand" }, { "LLeMbas", "LLeMbasUserHeader" }, { " · Waybread for the code ahead.", "LLeMbasNote" } },
|
||||
@@ -93,6 +141,11 @@ end
|
||||
--- Open a read-only floating window with rounded borders (`q` or `<Esc>` closes).
|
||||
function M.float(title, lines, opts)
|
||||
opts = opts or {}
|
||||
local flat = {}
|
||||
for _, l in ipairs(lines) do
|
||||
for _, part in ipairs(vim.split(tostring(l), "\n", { plain = true })) do flat[#flat + 1] = (part:gsub("\r", "")) end
|
||||
end
|
||||
lines = flat
|
||||
local b = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[b].buftype = "nofile"
|
||||
vim.bo[b].bufhidden = "wipe"
|
||||
|
||||
+40
-6
@@ -1,7 +1,7 @@
|
||||
if vim.g.loaded_llembas then return end
|
||||
vim.g.loaded_llembas = true
|
||||
if vim.fn.has("nvim-0.10") == 0 then
|
||||
vim.notify("llembas.nvim needs Neovim 0.10 or newer", vim.log.levels.WARN)
|
||||
vim.notify("LLeMbas needs Neovim 0.10 or newer", vim.log.levels.WARN)
|
||||
return
|
||||
end
|
||||
|
||||
@@ -27,10 +27,29 @@ cmd("LLeMbasAccept", function(o) require("llembas.diff").accept(o.bang) end, { b
|
||||
cmd("LLeMbasReject", function(o) require("llembas.diff").reject(o.bang) end, { bang = true, desc = "LLeMbas: reject the change under the cursor (! all)" })
|
||||
cmd("LLeMbasNextHunk", function() require("llembas.diff").next_hunk() end, { desc = "LLeMbas: jump to next proposed change" })
|
||||
cmd("LLeMbasPrevHunk", function() require("llembas.diff").prev_hunk() end, { desc = "LLeMbas: jump to previous proposed change" })
|
||||
cmd("LLeMbasAutocomplete", function(o)
|
||||
local on = require("llembas.complete").auto(o.args == "on" and true or o.args == "off" and false or nil)
|
||||
vim.notify("LLeMbas: suggestions as you type are " .. (on and "on" or "off"))
|
||||
end, { nargs = "?", complete = function() return { "on", "off" } end, desc = "LLeMbas: suggestions as you type on or off" })
|
||||
local function on_off(arg) if arg == "on" then return true elseif arg == "off" then return false end end
|
||||
local function on_off_words() return { "on", "off" } end
|
||||
cmd("LLeMbasAutocomplete", function(o) L().autocomplete(on_off(o.args)) end,
|
||||
{ nargs = "?", complete = on_off_words, desc = "LLeMbas: suggestions as you type on or off" })
|
||||
cmd("LLeMbasAI", function(o) L().ai(on_off(o.args)) end,
|
||||
{ nargs = "?", complete = on_off_words, desc = "LLeMbas: everything of LLeMbas on or off (off: a plain editor)" })
|
||||
cmd("LLeMbasEffort", function(o) L().effort(o.args) end,
|
||||
{ nargs = "?", complete = function() return L().EFFORTS end, desc = "LLeMbas: the effort of the conversation" })
|
||||
cmd("LLeMbasPrompt", function(o)
|
||||
local intent = o.args ~= "" and o.args or nil
|
||||
if o.range > 0 then L().prompt({ intent = intent, first = o.line1, last = o.line2 }) else L().prompt({ intent = intent }) end
|
||||
end, { range = true, nargs = "?", complete = function() return { "ask", "rewrite", "add" } end,
|
||||
desc = "LLeMbas: to the prompt with the lines or the cursor's line (ask, rewrite or add)" })
|
||||
cmd("LLeMbasMenu", function() L().menu() end, { desc = "LLeMbas: every command and every setting" })
|
||||
cmd("LLeMbasTree", function() require("llembas.layout").toggle("tree") end, { desc = "LLeMbas: the file tree, show and hide" })
|
||||
cmd("LLeMbasBars", function(o)
|
||||
local layout = require("llembas.layout")
|
||||
local a = o.fargs
|
||||
if #a == 0 then return L().setup({ bars = not layout.options().on and true or false }) end
|
||||
if a[1] == "on" or a[1] == "off" then return L().setup({ bars = a[1] == "on" }) end
|
||||
layout.toggle(a[1], on_off(a[2]))
|
||||
end, { nargs = "*", complete = function() return { "on", "off", "top", "bottom", "tree", "chat" } end,
|
||||
desc = "LLeMbas: the four bars on or off, or one of them (top, bottom, tree, chat) [on|off]" })
|
||||
cmd("LLeMbasAutocompleteTokens", function(o) L().autocomplete_tokens(o.args) end,
|
||||
{ nargs = "?", complete = function() return { "auto", "words", "line", "block", "file", "24", "64", "256", "1024", "2048" } end,
|
||||
desc = "LLeMbas: set autocomplete max tokens or prediction length preset" })
|
||||
@@ -44,7 +63,7 @@ cmd("LLeMbasOpen", function() L().open_shown() end, { desc = "LLeMbas: open the
|
||||
cmd("LLeMbasFiles", function(o) L().files(o.args, o.bang) end,
|
||||
{ nargs = "?", bang = true, desc = "LLeMbas: search project files and attach @path (! opens file in editor)" })
|
||||
cmd("LLeMbasOpenFile", function(o) L().files(o.args, true) end,
|
||||
{ nargs = "?", desc = "LLeMbas: open a file from the project index" })
|
||||
{ nargs = "?", desc = "LLeMbas: open a file of this project" })
|
||||
cmd("LLeMbasCommands", function() L().commands() end, { desc = "LLeMbas: pick a /command or skill" })
|
||||
cmd("LLeMbasSessions", function() L().sessions() end, { desc = "LLeMbas: list and resume a previous session" })
|
||||
cmd("LLeMbasExplain", function(o) L().explain(o.line1, o.line2) end,
|
||||
@@ -52,4 +71,19 @@ cmd("LLeMbasExplain", function(o) L().explain(o.line1, o.line2) end,
|
||||
cmd("LLeMbasFix", function() L().fix() end, { desc = "LLeMbas: fix diagnostics in the current buffer" })
|
||||
cmd("LLeMbasToggleThoughts", function() L().toggle_thoughts() end, { desc = "LLeMbas: toggle showing model thinking" })
|
||||
cmd("LLeMbasStatus", function() L().status_popup() end, { desc = "LLeMbas: show agent, session and autocomplete status" })
|
||||
cmd("LLeMbasLogin", function(o)
|
||||
local address, ca = nil, nil
|
||||
local args = o.fargs
|
||||
local i = 1
|
||||
while i <= #args do
|
||||
if args[i] == "--ca" then ca = args[i + 1]; i = i + 2 else address = address or args[i]; i = i + 1 end
|
||||
end
|
||||
require("llembas.login").login(address, ca)
|
||||
end, { nargs = "*", desc = "LLeMbas: sign this computer in to a LLeMbas server ([address] [--ca file])" })
|
||||
cmd("LLeMbasLoginCancel", function()
|
||||
if not require("llembas.login").cancel() then vim.notify("LLeMbas: no sign-in is under way", vim.log.levels.INFO) end
|
||||
end, { desc = "LLeMbas: stop a sign-in that is waiting to be approved" })
|
||||
cmd("LLeMbasLogout", function() require("llembas.login").logout() end, { desc = "LLeMbas: sign this computer out of its LLeMbas server" })
|
||||
cmd("LLeMbasRestart", function() L().restart() end, { desc = "LLeMbas: stop the agent (it starts again when needed)" })
|
||||
cmd("LLeMbasLog", function() L().log() end, { desc = "LLeMbas: show what the agent wrote on stderr" })
|
||||
cmd("LLeMbasHelp", function() L().help() end, { desc = "LLeMbas: show commands and keymaps" })
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The stand-in agent (tests/fake_agent.py) with one thing more: it keeps the effort it is given.
|
||||
|
||||
The shared stand-in answers every effort with `default`. The layout's tests set the effort from
|
||||
the settings lines and need the answer to say the level that is used, as the LLeMbas CLI does:
|
||||
a level this "model" offers (low, medium, high, off) is used as asked, and any other is read as
|
||||
its start level, `medium`. Everything else is the shared stand-in's, run unchanged.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
here = os.path.dirname(os.path.abspath(__file__))
|
||||
fake = os.path.join(here, "..", "..", "tests", "fake_agent.py")
|
||||
with open(fake, encoding="utf-8") as f:
|
||||
source = f.read().rstrip()
|
||||
if not source.endswith("\nmain()"):
|
||||
sys.exit("agent_levels: tests/fake_agent.py no longer ends by calling main()")
|
||||
ns = {"__name__": "fake_agent", "__file__": fake}
|
||||
exec(compile(source[: -len("main()")], fake, "exec"), ns)
|
||||
|
||||
OFFERED = ("off", "low", "medium", "high")
|
||||
level = {"now": None}
|
||||
shared_handle, shared_out = ns["handle"], ns["out"]
|
||||
|
||||
|
||||
def taken(asked):
|
||||
return asked if asked in OFFERED else "medium"
|
||||
|
||||
|
||||
def handle(msg):
|
||||
params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
|
||||
if msg.get("method") == "session/new":
|
||||
asked = (params.get("_meta") or {}).get("effort")
|
||||
level["now"] = taken(asked) if isinstance(asked, str) else None
|
||||
if msg.get("method") == "_lembas/configure" and isinstance(params.get("effort"), str):
|
||||
level["now"] = taken(params["effort"])
|
||||
return shared_handle(msg)
|
||||
|
||||
|
||||
def out(msg):
|
||||
# A `model` event says the effort too, as the CLI's does.
|
||||
event = (msg.get("params") or {}).get("event") if msg.get("method") == "_lembas/event" else None
|
||||
if level["now"] and isinstance(event, dict) and event.get("type") == "model":
|
||||
event["effort"] = level["now"]
|
||||
result = msg.get("result")
|
||||
if level["now"] and isinstance(result, dict):
|
||||
if "effort" in result:
|
||||
result["effort"] = level["now"]
|
||||
inner = (result.get("_meta") or {}).get("lembas")
|
||||
if isinstance(inner, dict) and "effort" in inner:
|
||||
inner["effort"] = level["now"]
|
||||
shared_out(msg)
|
||||
|
||||
|
||||
ns["handle"], ns["out"] = handle, out
|
||||
ns["main"]()
|
||||
@@ -0,0 +1,76 @@
|
||||
-- One start of Neovim with the plugin, for the checks that need a new process: what is remembered
|
||||
-- from one start to the next, and what is written to the terminal on the way in and out.
|
||||
-- Run by nvim/tests/layout.lua in the directory under test; $STEP says what to do. The answer is
|
||||
-- one line on standard output: RESULT {json}. Standard error is left to the plugin alone.
|
||||
local step = vim.env.STEP or "look"
|
||||
local repo = assert(vim.env.LLEMBAS_TEST_REPO, "LLEMBAS_TEST_REPO")
|
||||
local agent = repo .. "/nvim/tests/agent_levels.py"
|
||||
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
|
||||
|
||||
local function finish(data)
|
||||
io.stdout:write("RESULT " .. vim.json.encode(data) .. "\n")
|
||||
pcall(function() require("llembas").restart(true) end)
|
||||
vim.cmd("qa!")
|
||||
end
|
||||
|
||||
vim.schedule(function()
|
||||
local ok, err = xpcall(function()
|
||||
vim.notify = function() end
|
||||
vim.o.columns, vim.o.lines = 160, 45
|
||||
vim.g.mapleader = " "
|
||||
vim.cmd("runtime plugin/llembas.lua")
|
||||
local L = require("llembas")
|
||||
if step == "plain" then
|
||||
L.setup({ cmd = { "python3", agent } })
|
||||
return finish({ plain = true })
|
||||
end
|
||||
L.setup({ cmd = { "python3", agent }, bars = true })
|
||||
local layout = require("llembas.layout")
|
||||
local keys = require("llembas.keys")
|
||||
local chat = require("llembas.chat")
|
||||
vim.wait(50)
|
||||
local out = {}
|
||||
if step == "start" then return finish({ started = true }) end
|
||||
if step == "chords" then return finish({ chords = keys.chords(), guess = keys._terminal_reports() }) end
|
||||
if step == "change" then
|
||||
L.mode("edit")
|
||||
-- (Until the agent has answered: its event says the new mode before its answer does.)
|
||||
wait(function() return require("llembas.store").get().mode == "edit" end)
|
||||
L.effort("high")
|
||||
wait(function() return L._state.effort == "high" end)
|
||||
L.autocomplete(false)
|
||||
layout.toggle("tree", false)
|
||||
-- The right bar dragged wider: remembered on the way out.
|
||||
vim.api.nvim_win_set_width(vim.fn.bufwinid(chat.tbuf), 46)
|
||||
elseif step == "change_b" then
|
||||
L.mode("plan")
|
||||
wait(function() return require("llembas.store").get().mode == "plan" end)
|
||||
elseif step == "session" then
|
||||
local done = false
|
||||
L.choices("mode", function() done = true end)
|
||||
wait(function() return done end)
|
||||
for _, line in ipairs(vim.fn.readfile(vim.env.FAKE_AGENT_LOG)) do
|
||||
local m = vim.json.decode(line)
|
||||
if m.method == "session/new" then out.new_mode, out.new_effort = (m.params._meta or {}).mode, (m.params._meta or {}).effort end
|
||||
end
|
||||
elseif step == "default" then
|
||||
require("llembas.store").make_default()
|
||||
elseif step == "ai_off" then
|
||||
L.ai(false)
|
||||
elseif step == "cd" then
|
||||
-- Another working directory without a restart: what is remembered there holds.
|
||||
vim.cmd("cd " .. vim.fn.fnameescape((assert(vim.env.CD_TO, "CD_TO"))))
|
||||
vim.wait(50)
|
||||
end
|
||||
layout.remember_widths()
|
||||
local s, o = L.settings(), layout.options()
|
||||
out.mode, out.effort, out.autocomplete, out.ai = s.mode, s.effort, s.autocomplete, s.ai
|
||||
out.tree, out.chat, out.chat_width, out.tree_width = o.tree, o.chat, o.chat_width, o.tree_width
|
||||
out.tree_open = require("llembas.tree").is_open()
|
||||
finish(out)
|
||||
end, debug.traceback)
|
||||
if not ok then
|
||||
io.stdout:write("CHILD FAILED " .. tostring(err) .. "\n")
|
||||
vim.cmd("cquit!")
|
||||
end
|
||||
end)
|
||||
@@ -1,239 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A stand-in for `lembas serve --stdio`, for the plugin's tests: ACP version 1 over lines.
|
||||
|
||||
What it does is steered by words in the prompt's last text block: PERM asks for an approval,
|
||||
WRITE <path> rewrites that file, SLOW waits to be cancelled, CRASH exits. Every request it gets is
|
||||
appended to the file named by FAKE_AGENT_LOG, one JSON object a line.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
LOG = os.environ.get("FAKE_AGENT_LOG")
|
||||
lock = threading.Lock()
|
||||
waiting = {}
|
||||
cancelled = threading.Event()
|
||||
next_id = [1000]
|
||||
|
||||
|
||||
def out(msg):
|
||||
with lock:
|
||||
sys.stdout.write(json.dumps(msg) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def update(session, body):
|
||||
out({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": session, "update": body}})
|
||||
|
||||
|
||||
def ask(method, params):
|
||||
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(10)
|
||||
return waiting.pop(rid)[1]
|
||||
|
||||
|
||||
EDITOR = os.environ.get("FAKE_EDITOR") == "1"
|
||||
SETTINGS = {"autocomplete": {"model": None, "source": None}, "main": {"model": None}}
|
||||
gone = set()
|
||||
|
||||
|
||||
def complete(msg):
|
||||
p = msg["params"]
|
||||
prefix = p["prefix"]
|
||||
if "NOMODEL" in prefix:
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32602, "message": "no autocomplete model is chosen"}})
|
||||
return
|
||||
if "SLOWC" in prefix:
|
||||
for _ in range(40):
|
||||
if p.get("id") in gone:
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"text": "", "cancelled": True}})
|
||||
return
|
||||
threading.Event().wait(0.05)
|
||||
text = "tail()\n second line" if "TWO" in prefix else "<" + prefix[-3:] + "|" + (p.get("suffix") or "")[:3] + ">"
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"text": text, "model": p.get("model") or "example/model-a", "finish": "stop"}})
|
||||
|
||||
|
||||
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"}})
|
||||
update(session, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Hello "}})
|
||||
update(session, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "there.\nSecond line"}})
|
||||
if "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": [{"optionId": "once", "name": "Allow once", "kind": "allow_once"},
|
||||
{"optionId": "deny", "name": "Deny", "kind": "reject_once"}],
|
||||
"_meta": {"lembas": {"tool": "bash", "reason": "deletes files"}}})
|
||||
got = (answer or {}).get("outcome", {})
|
||||
update(session, {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": "\nanswer=" + str(got.get("optionId") or got.get("outcome"))}})
|
||||
if "PERMDIFF" in text:
|
||||
answer = ask("session/request_permission", {
|
||||
"sessionId": session,
|
||||
"toolCall": {"toolCallId": "diff-" + str(msg["id"]), "title": "edit sample.py", "kind": "edit", "status": "pending",
|
||||
"rawInput": {}, "content": [{"type": "diff", "path": "sample.py", "oldText": "one\ntwo", "newText": "one\nTWO"}]},
|
||||
"options": [{"optionId": "once", "name": "Allow once", "kind": "allow_once"},
|
||||
{"optionId": "deny", "name": "Deny", "kind": "reject_once"}]})
|
||||
got = (answer or {}).get("outcome", {})
|
||||
update(session, {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": "\nanswer=" + str(got.get("optionId") or got.get("outcome"))}})
|
||||
if "READ " in text:
|
||||
path = text.split("READ ", 1)[1].split()[0]
|
||||
answer = ask("fs/read_text_file", {"sessionId": session, "path": path})
|
||||
update(session, {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": "\nread=" + json.dumps((answer or {}).get("content"))}})
|
||||
if "PUT " in text:
|
||||
path = text.split("PUT ", 1)[1].split()[0]
|
||||
with lock:
|
||||
next_id[0] += 1
|
||||
rid = next_id[0]
|
||||
done = threading.Event()
|
||||
waiting[rid] = [done, "error"]
|
||||
out({"jsonrpc": "2.0", "id": rid, "method": "fs/write_text_file",
|
||||
"params": {"sessionId": session, "path": path, "content": "written by the agent\nsecond\n"}})
|
||||
done.wait(10)
|
||||
got = waiting.pop(rid)[1]
|
||||
update(session, {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": "\nput=" + ("error" if got == "error" else "ok")}})
|
||||
if "SHOW " in text:
|
||||
path = text.split("SHOW ", 1)[1].split()[0]
|
||||
kind = "image" if path.endswith(".png") else "code"
|
||||
answer = ask("_lembas/show", {"sessionId": session, "toolCallId": "show-" + str(msg["id"]), "path": os.path.basename(path),
|
||||
"uri": "file://" + path, "kind": kind, "line": 2})
|
||||
update(session, {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": "\nshown=" + json.dumps(answer)}})
|
||||
if "WRITE " in text:
|
||||
path = text.split("WRITE ", 1)[1].split()[0]
|
||||
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 "QUESTION" in text:
|
||||
answer = ask("_lembas/question", {
|
||||
"sessionId": session,
|
||||
"toolCallId": "q-" + str(msg["id"]),
|
||||
"why": "Pick a backend",
|
||||
"questions": [{"header": "DB", "question": "Which DB?", "options": [{"label": "SQLite"}, {"label": "Postgres"}]}],
|
||||
})
|
||||
update(session, {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": "\nquestion=" + json.dumps(answer, sort_keys=True)}})
|
||||
if "PLANCARD" in text:
|
||||
answer = ask("_lembas/plan", {
|
||||
"sessionId": session,
|
||||
"toolCallId": "p-" + str(msg["id"]),
|
||||
"text": "# Plan\n- step 1",
|
||||
"plan": {"title": "Upgrade"},
|
||||
})
|
||||
update(session, {"sessionUpdate": "agent_message_chunk",
|
||||
"content": {"type": "text", "text": "\nplan=" + 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:
|
||||
stop = "cancelled" if cancelled.wait(10) else "end_turn"
|
||||
cancelled.clear()
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"stopReason": stop}})
|
||||
|
||||
|
||||
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:
|
||||
if "error" not in msg:
|
||||
entry[1] = msg.get("result")
|
||||
entry[0].set()
|
||||
elif method == "initialize":
|
||||
result = {"protocolVersion": 1, "agentCapabilities": {}}
|
||||
if EDITOR:
|
||||
result["_meta"] = {"lembas": {"capabilities": ["editor", "media", "files", "commands", "steer", "sessions", "ask", "plan", "compact"]}}
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": result})
|
||||
elif method == "_lembas/complete":
|
||||
threading.Thread(target=complete, args=(msg,), daemon=True).start()
|
||||
elif method == "_lembas/complete/cancel":
|
||||
gone.add(msg["params"]["id"])
|
||||
elif method == "_lembas/complete/warm":
|
||||
pass
|
||||
elif method == "_lembas/files/search":
|
||||
q = str((msg.get("params") or {}).get("query") or "").lower()
|
||||
sample = [{"path": "sample.py", "kind": "file"}, {"path": "other.py", "kind": "file"}, {"path": "sub", "kind": "dir"}]
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"root": os.getcwd(), "files": [f for f in sample if not q or q in f["path"].lower()]}})
|
||||
elif method == "_lembas/commands":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"commands": [{"name": "review", "description": "Review changes", "_meta": {"lembas": {"kind": "builtin"}}}]}})
|
||||
elif method == "_lembas/session/compact":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"summary": "Compacted 1 turn."}})
|
||||
elif method == "_lembas/steer":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"queued": 1}})
|
||||
elif method == "_lembas/sessions/list":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"sessions": [{"id": "ses_prev", "title": "Previous run", "model": "example/model-a"}]}})
|
||||
elif method == "_lembas/sessions/resume":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {
|
||||
"sessionId": "ses_prev",
|
||||
"title": "Previous run",
|
||||
"modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]},
|
||||
"turns": [
|
||||
{"role": "user", "text": "old prompt"},
|
||||
{"role": "assistant", "text": "old reply", "reasoning": "", "tools": [{"id": "h1", "name": "read", "args": "{}", "output": "file text"}]},
|
||||
],
|
||||
"_meta": {"lembas": {"model": "example/model-a", "mode": "edit"}},
|
||||
}})
|
||||
elif method == "_lembas/edit":
|
||||
p = msg["params"]
|
||||
if "REFUSE" in p["instruction"]:
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32602, "message": "no model to rewrite with"}})
|
||||
continue
|
||||
out({"jsonrpc": "2.0", "method": "_lembas/edit/delta", "params": {"id": p.get("id"), "delta": "abc"}})
|
||||
lines = p["text"].split("\n")
|
||||
if "SAME" in p["instruction"]:
|
||||
new = lines
|
||||
else:
|
||||
# The first line rewritten, a line added after the second, the rest as it was.
|
||||
new = [lines[0].upper()] + lines[1:2] + [" # added by the rewrite"] + lines[2:]
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"text": "\n".join(new), "model": "example/model-a"}})
|
||||
elif method == "_lembas/models":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"models": [
|
||||
{"id": "example/model-a", "name": "Model A", "for": ["main", "autocomplete"]},
|
||||
{"id": "example/model-b", "name": "Model B", "for": ["main"]}],
|
||||
"autocomplete": SETTINGS["autocomplete"], "main": SETTINGS["main"]}})
|
||||
elif method == "_lembas/editor/settings":
|
||||
for key, value in (msg["params"].get("set") or {}).items():
|
||||
which = "autocomplete" if key == "autocomplete_model" else "main"
|
||||
SETTINGS[which] = {"model": value, "source": "person" if value else None}
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": SETTINGS})
|
||||
elif method == "session/new":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {
|
||||
"sessionId": "ses_test",
|
||||
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]},
|
||||
"_meta": {"lembas": {"model": "example/model-a", "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":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {}})
|
||||
elif method == "_lembas/configure":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"model": msg["params"].get("model"), "effort": "default"}})
|
||||
elif "id" in msg:
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32601, "message": "Method not found"}})
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,755 @@
|
||||
-- The four bars, tested on the plugin alone (no distribution): what is on the screen at three
|
||||
-- sizes, the keys, the prompt's intent and attachment, the settings lines, the tree, what is
|
||||
-- remembered, and what is said to the terminal. Against the stand-in agent.
|
||||
-- Run by scripts/test-nvim.sh, with a screen (no -l), so that the bars are read as drawn:
|
||||
-- nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -c "luafile nvim/tests/layout.lua"
|
||||
local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h")
|
||||
local repo = vim.fs.normalize(here .. "/../..")
|
||||
vim.opt.rtp:append(repo .. "/nvim")
|
||||
local levels = here .. "/agent_levels.py"
|
||||
local child = here .. "/child.lua"
|
||||
local work = vim.env.LLEMBAS_NVIM_TEST_WORK
|
||||
local own_work = false
|
||||
if not work or work == "" then
|
||||
-- Run by hand: a state directory of the test's own all the same.
|
||||
work = vim.fn.tempname()
|
||||
own_work = true
|
||||
vim.fn.mkdir(work .. "/state", "p")
|
||||
vim.env.XDG_STATE_HOME = work .. "/state"
|
||||
end
|
||||
work = vim.uv.fs_realpath(work)
|
||||
local tmp = work .. "/layout-project"
|
||||
local log = work .. "/layout-agent.log"
|
||||
vim.fn.mkdir(tmp .. "/src/deep", "p")
|
||||
vim.env.FAKE_AGENT_LOG = log
|
||||
vim.env.PYTHONDONTWRITEBYTECODE = "1"
|
||||
-- Whatever terminal this is run in says nothing about itself to the plugin.
|
||||
for _, name in ipairs({ "LLEMBAS_TERM", "LLEMBAS_TTY", "TMUX", "STY", "ZELLIJ", "KITTY_WINDOW_ID", "GHOSTTY_RESOURCES_DIR", "TERM_PROGRAM" }) do vim.env[name] = nil end
|
||||
vim.env.TERM = "dumb"
|
||||
|
||||
local failed, ran = 0, 0
|
||||
local function say(text) io.stdout:write(text .. "\n") end
|
||||
local function check(name, cond, extra)
|
||||
ran = ran + 1
|
||||
if cond then say("ok " .. name) else
|
||||
failed = failed + 1
|
||||
say("FAIL " .. name .. (extra ~= nil and ("\n " .. (type(extra) == "string" and extra or vim.inspect(extra))) or ""))
|
||||
end
|
||||
end
|
||||
local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end
|
||||
local function t(keys) return vim.api.nvim_replace_termcodes(keys, true, false, true) end
|
||||
local function feed(keys) vim.api.nvim_feedkeys(t(keys), "mx", false) end
|
||||
local function sent()
|
||||
local out = {}
|
||||
for _, line in ipairs(vim.fn.filereadable(log) == 1 and vim.fn.readfile(log) or {}) do out[#out + 1] = vim.json.decode(line) end
|
||||
return out
|
||||
end
|
||||
local function calls(method)
|
||||
local out = {}
|
||||
for _, m in ipairs(sent()) do if m.method == method then out[#out + 1] = m.params end end
|
||||
return out
|
||||
end
|
||||
local function last_call(method) local c = calls(method); return c[#c] end
|
||||
local function row(r)
|
||||
vim.cmd("redraw")
|
||||
local out = {}
|
||||
for c = 1, vim.o.columns do out[#out + 1] = vim.fn.screenstring(r, c) end
|
||||
return table.concat(out)
|
||||
end
|
||||
local function top() return row(1) end
|
||||
local function bottom() return row(vim.o.lines - 1) end
|
||||
local function rtrim(s) return (s:gsub("%s+$", "")) end
|
||||
--- `text` in exactly `w` cells, padded with spaces (the tests' own, not the layout's).
|
||||
local function cell(text, w) return text .. (" "):rep(w - vim.fn.strdisplaywidth(text)) end
|
||||
local function width(s) return vim.fn.strdisplaywidth(s) end
|
||||
local function keys_part() return rtrim(vim.fn.strcharpart(bottom(), 0, vim.o.columns - (vim.o.columns < 60 and 15 or vim.o.columns < 120 and 20 or 35))) end
|
||||
--- Neovim's own segment at the right end. At full width its last six cells are the pending
|
||||
--- operator's (`%S`, Neovim's own text, which keys fed by a test leave things in): not compared.
|
||||
local function vim_part()
|
||||
local n = vim.o.columns < 60 and 15 or vim.o.columns < 120 and 20 or 35
|
||||
return vim.fn.strcharpart(bottom(), vim.o.columns - n, n == 35 and 29 or n)
|
||||
end
|
||||
local function wins()
|
||||
local out = {}
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.api.nvim_win_get_config(w).relative == "" then
|
||||
local b = vim.api.nvim_win_get_buf(w)
|
||||
local ft = vim.bo[b].filetype
|
||||
local name = vim.api.nvim_buf_get_name(b)
|
||||
local kind = ft == "llembas-tree" and "tree" or ft == "llembas-settings" and "settings"
|
||||
or name:match("llembas://chat$") and "chat" or name:match("llembas://prompt$") and "prompt" or "code"
|
||||
out[kind] = { win = w, width = vim.api.nvim_win_get_width(w), height = vim.api.nvim_win_get_height(w) }
|
||||
end
|
||||
end
|
||||
return out
|
||||
end
|
||||
local function kinds(w)
|
||||
local names = vim.tbl_keys(w)
|
||||
table.sort(names)
|
||||
return table.concat(names, " ")
|
||||
end
|
||||
local function resize(cols, rows)
|
||||
vim.o.columns, vim.o.lines = cols, rows
|
||||
vim.api.nvim_exec_autocmds("VimResized", {})
|
||||
vim.wait(60)
|
||||
vim.cmd("redraw")
|
||||
end
|
||||
local said_msgs = {}
|
||||
local function was_said(text) return table.concat(said_msgs, "|"):find(text, 1, true) ~= nil end
|
||||
|
||||
--- Run a child Neovim (nvim/tests/child.lua) in `dir` with `env`; returns its stdout, stderr and code.
|
||||
local function run_child(dir, env)
|
||||
local e = vim.tbl_extend("force", { PYTHONDONTWRITEBYTECODE = "1", LLEMBAS_TEST_REPO = repo, TERM = "dumb" }, env or {})
|
||||
local done = vim.system({ vim.v.progpath, "--headless", "-u", "NONE", "-i", "NONE", "--cmd", "set rtp+=" .. repo .. "/nvim",
|
||||
"-c", "luafile " .. child }, { cwd = dir, env = e, text = false }):wait(40000)
|
||||
return done.stdout or "", done.stderr or "", done.code
|
||||
end
|
||||
local function child_json(dir, env)
|
||||
local out, err, code = run_child(dir, env)
|
||||
local line = out:match("RESULT (%b{})")
|
||||
local ok, data = pcall(vim.json.decode, line or "", { luanil = { object = true, array = true } })
|
||||
return ok and data or { failed = true, out = out, err = err, code = code }
|
||||
end
|
||||
|
||||
local function run()
|
||||
vim.notify = function(m) said_msgs[#said_msgs + 1] = tostring(m) end
|
||||
vim.g.mapleader = " "
|
||||
vim.cmd("cd " .. vim.fn.fnameescape(tmp))
|
||||
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, tmp .. "/sample.py")
|
||||
vim.fn.writefile({ "x = 1" }, tmp .. "/src/util.py")
|
||||
vim.fn.writefile({ "y = 2" }, tmp .. "/src/deep/inner.py")
|
||||
vim.fn.writefile({ "# readme" }, tmp .. "/README.md")
|
||||
vim.fn.writefile({ "secret" }, tmp .. "/.env.example")
|
||||
vim.cmd("runtime plugin/llembas.lua")
|
||||
|
||||
local L = require("llembas")
|
||||
local chat = require("llembas.chat")
|
||||
local layout = require("llembas.layout")
|
||||
local keys = require("llembas.keys")
|
||||
local tree = require("llembas.tree")
|
||||
local lines = require("llembas.lines")
|
||||
local store = require("llembas.store")
|
||||
local C = require("llembas.complete")
|
||||
|
||||
-- ── The plugin on its own: nothing of the bars unless asked for. ────────────────────────────────
|
||||
L.setup({ cmd = { "python3", levels } })
|
||||
check("alone: without `bars` no tabline, no statusline of ours, no window but the one",
|
||||
vim.o.tabline == "" and not vim.o.statusline:find("llembas", 1, true) and #vim.api.nvim_tabpage_list_wins(0) == 1)
|
||||
check("alone: without `keys` no key is mapped", vim.fn.maparg("<C-S-A>", "n") == "" and vim.fn.maparg("<Space>la", "n") == ""
|
||||
and vim.fn.maparg("<M-Right>", "n") == "")
|
||||
check("alone: the public functions are there", type(L.settings) == "function" and type(L.setting_lines) == "function"
|
||||
and type(L.choices) == "function" and type(L.set) == "function" and type(L.prompt) == "function" and type(L.intent) == "function"
|
||||
and type(L.effort) == "function" and type(L.ai) == "function" and type(L.menu) == "function")
|
||||
local s0 = L.settings()
|
||||
check("alone: settings() says idle, no session, AI and suggestions on, the intent ask",
|
||||
s0.state == "idle" and s0.session == false and s0.ai == true and s0.autocomplete == true and s0.intent == "ask" and s0.model == nil, s0)
|
||||
|
||||
-- ── One option turns the bars on. 160×45. ───────────────────────────────────────────────────────
|
||||
vim.o.columns, vim.o.lines = 160, 45
|
||||
L.setup({ bars = true })
|
||||
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/sample.py"))
|
||||
local fbuf = vim.api.nvim_get_current_buf()
|
||||
vim.wait(100)
|
||||
local w = wins()
|
||||
check("160×45: the windows are tree, code, settings, chat and prompt", kinds(w) == "chat code prompt settings tree", kinds(w))
|
||||
check("160×45: the tree is 26 columns, the right bar 42, the code has the rest",
|
||||
w.tree.width == 26 and w.chat.width == 42 and w.settings.width == 42 and w.prompt.width == 42 and w.code.width == 160 - 26 - 42 - 2, w)
|
||||
check("160×45: the settings are four lines, the prompt three and its chip's row", w.settings.height == 4 and w.prompt.height == 4, w)
|
||||
check("160×45: the focus is in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
check("160×45: the top bar, cell for cell",
|
||||
top() == " ● idle │ " .. cell("no conversation yet", 160 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6)
|
||||
.. " │ " .. cell("— · — · —", 32) .. " │ ctx — │ AC on ", top())
|
||||
check("160×45: the bottom bar in the code shows the keys that always arrive (no chord was seen)",
|
||||
keys_part() == " Spc la ask · Tab accept suggestion · Alt+→ one word · Spc lp menu · Alt+←→ bars · Spc lb tree · Spc ll chat", keys_part())
|
||||
check("160×45: and Neovim's own state at its right end, in cells of fixed width",
|
||||
vim_part() == " NOR" .. (" "):rep(19) .. "1:1 ", "[" .. vim_part() .. "]")
|
||||
check("the bars are exactly as wide as the screen", width(top()) == 160 and width(bottom()) == 160)
|
||||
|
||||
-- Every width from 30 to 220: the rows are exactly that wide, never wrapped, never short.
|
||||
local bad = {}
|
||||
for cols = 30, 220 do
|
||||
if width(layout.top_text(cols)) ~= cols then bad[#bad + 1] = "top " .. cols end
|
||||
for _, where in ipairs({ "code", "tree", "prompt", "settings", "chat", "change" }) do
|
||||
local seg = cols < 60 and 15 or cols < 120 and 20 or 35
|
||||
if width(layout.bottom_text(where, cols)) > cols - seg then bad[#bad + 1] = where .. " " .. cols end
|
||||
end
|
||||
end
|
||||
check("every width from 30 to 220: the top bar is exactly that wide and the keys never pass their room", #bad == 0, bad)
|
||||
local _, cut = layout.fit({ { text = "a title that is much too long to fit", flex = true, min = 8, prio = 2 }, { text = "x", width = 5, prio = 1 } }, 24)
|
||||
check("a text that does not fit its cell is cut with an ellipsis; nothing wraps", cut == " a title that … │ x " and width(cut) == 24, "[" .. cut .. "]")
|
||||
|
||||
-- ── The keys: one table. ────────────────────────────────────────────────────────────────────────
|
||||
local missing = {}
|
||||
local function mapped(mode, lhs, buf)
|
||||
local m = vim.fn.maparg(lhs, mode, false, true)
|
||||
if next(m) == nil then return false end
|
||||
if buf then return m.buffer == 1 end
|
||||
return true
|
||||
end
|
||||
for _, k in ipairs(keys.table) do
|
||||
if not k.virtual then
|
||||
if k.chord then
|
||||
for _, mode in ipairs({ "n", "x", "i" }) do
|
||||
if not mapped(mode, k.chord) then missing[#missing + 1] = mode .. " " .. k.chord end
|
||||
end
|
||||
end
|
||||
if not k.scope then
|
||||
for _, lhs in ipairs(keys.alts(k)) do
|
||||
for _, mode in ipairs(k.modes or { "n" }) do
|
||||
if not mapped(mode, keys.lhs(lhs)) then missing[#missing + 1] = mode .. " " .. keys.lhs(lhs) end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: every chord and every key after the prefix of the table is mapped", #missing == 0, missing)
|
||||
local in_table = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
for _, lhs in ipairs(type(k.chord) == "table" and k.chord or { k.chord }) do in_table[t(lhs)] = true end
|
||||
for _, lhs in ipairs(keys.alts(k)) do in_table[t(keys.lhs(lhs))] = true end
|
||||
end
|
||||
local strays = {}
|
||||
for _, mode in ipairs({ "n", "x", "i" }) do
|
||||
for _, m in ipairs(vim.api.nvim_get_keymap(mode)) do
|
||||
if (m.desc or ""):match("^LLeMbas: ") and not in_table[t(m.lhs)] and t(m.lhs) ~= t(L.config.complete.trigger) then strays[#strays + 1] = mode .. " " .. m.lhs end
|
||||
end
|
||||
end
|
||||
check("keys: every mapping of LLeMbas's is in the table (but the one that asks for a suggestion, a setting)", #strays == 0, strays)
|
||||
local shown_unbound = {}
|
||||
for _, where in ipairs({ "code", "tree", "prompt", "settings", "chat", "change" }) do
|
||||
for _, form in ipairs({ true, false }) do
|
||||
for _, k in ipairs(keys.for_bar(where, form)) do
|
||||
local e = keys.by_id[k.id]
|
||||
if not (e.chord or #keys.alts(e) > 0) then shown_unbound[#shown_unbound + 1] = where .. " " .. k.id end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: nothing the bottom bar can show is without a key", #shown_unbound == 0, shown_unbound)
|
||||
check("keys: a key is written as the owner's table writes it",
|
||||
keys.written("<C-S-A>") == "^⇧A" and keys.written("<M-C-S-Y>") == "Alt+^⇧Y" and keys.written("<C-Tab>") == "^Tab"
|
||||
and keys.written("<C-M-m>") == "Alt+^M" and keys.written("<M-Left>") == "Alt+←" and keys.written("<Prefix>a") == "Spc la"
|
||||
and keys.written("<CR>") == "Enter", { keys.written("<C-M-m>"), keys.written("<Prefix>a") })
|
||||
|
||||
-- The bars' own keys, in their buffers.
|
||||
local scoped = {}
|
||||
local bufs = { tree = tree.buf(), settings = lines.buf(), prompt = chat.ibuf, chat = chat.tbuf }
|
||||
for _, k in ipairs(keys.table) do
|
||||
if k.scope and bufs[k.scope] and not k.virtual then
|
||||
for _, lhs in ipairs(keys.alts(k)) do
|
||||
local m = vim.api.nvim_buf_call(bufs[k.scope], function()
|
||||
return { vim.fn.maparg(lhs, "n", false, true).buffer, vim.fn.maparg(lhs, "i", false, true).buffer }
|
||||
end)
|
||||
if m[1] ~= 1 and m[2] ~= 1 then scoped[#scoped + 1] = k.scope .. " " .. lhs end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: every key of the tree, the settings lines, the prompt and the transcript is mapped in its buffer", #scoped == 0, scoped)
|
||||
|
||||
-- ── The bottom bar follows the focus. ───────────────────────────────────────────────────────────
|
||||
layout.focus("tree")
|
||||
check("focus tree: the bar shows the tree's keys",
|
||||
keys_part() == " Enter open · a new · r rename · d delete · / filter · Alt+→ code · . hidden files · Spc la ask · Spc lp menu · Spc lb tree", keys_part())
|
||||
feed("<M-Right>")
|
||||
check("Alt+→ from the tree is the code", vim.api.nvim_get_current_buf() == fbuf and layout.where() == "code")
|
||||
feed("<M-Right>")
|
||||
check("Alt+→ from the code is the prompt", vim.api.nvim_get_current_buf() == chat.ibuf and layout.where() == "prompt")
|
||||
check("focus prompt: the bar shows the prompt's keys",
|
||||
keys_part() == " Enter send · Tab ask/rewrite/add · Spc lm mode · Spc lM model · Esc back to code · Spc l. stop", keys_part())
|
||||
feed("<M-Left>")
|
||||
check("Alt+← from the prompt is the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
vim.api.nvim_set_current_win(w.settings.win)
|
||||
check("focus settings: the bar shows the settings' keys", keys_part() == " Enter change · ↑↓ move · Esc back · Alt+← code", keys_part())
|
||||
vim.api.nvim_set_current_win(w.chat.win)
|
||||
check("focus transcript: the bar shows the transcript's keys",
|
||||
keys_part() == " Enter open file · K tool output · i prompt · Alt+← code · Spc l. stop · Spc la ask · Spc lp menu · Spc ll chat", keys_part())
|
||||
layout.focus("code")
|
||||
|
||||
-- A chord that arrives proves the terminal reports them: from then the bar shows the chords.
|
||||
check("chords: none seen, none assumed (no terminal says it reports them)", keys.chords() == false)
|
||||
feed("<C-S-E>")
|
||||
check("Ctrl+Shift+E hides the tree", wait(function() return not tree.is_open() end) and wins().code.width == 160 - 43)
|
||||
check("chords: one arrived, so they arrive", keys.chords() == true)
|
||||
check("chords: that is remembered for this terminal", store.terminal(keys._terminal_id()) == true, keys._terminal_id())
|
||||
feed("<C-S-E>")
|
||||
check("Ctrl+Shift+E shows it again, 26 columns", wait(function() return tree.is_open() end) and wins().tree.width == 26)
|
||||
check("code, chords: the owner's line",
|
||||
keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars · ^⇧E tree · ^⇧D chat", keys_part())
|
||||
layout.focus("tree")
|
||||
check("tree, chords: the owner's line",
|
||||
vim.startswith(keys_part(), " Enter open · a new · r rename · d delete · / filter · Alt+→ code"), keys_part())
|
||||
layout.focus("chat")
|
||||
check("prompt, chords: the owner's line",
|
||||
vim.startswith(keys_part(), " Enter send · Tab ask/rewrite/add · ^Tab mode · ^⇧M model · Esc back to code"), keys_part())
|
||||
vim.api.nvim_set_current_win(wins().settings.win)
|
||||
check("settings, chords: the owner's line", vim.startswith(keys_part(), " Enter change · ↑↓ move · Esc back"), keys_part())
|
||||
layout.focus("code")
|
||||
feed("<C-S-D>")
|
||||
check("Ctrl+Shift+D hides the right bar: settings, chat and prompt", wait(function() return not chat.is_open() end) and kinds(wins()) == "code tree", kinds(wins()))
|
||||
feed("<C-S-D>")
|
||||
check("Ctrl+Shift+D shows it again", wait(function() return chat.is_open() end) and kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
|
||||
check("the focus stayed in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
|
||||
-- ── The prompt: its prefix, Tab, the attachment. ────────────────────────────────────────────────
|
||||
local function prompt_rows()
|
||||
local pw = wins().prompt.win
|
||||
local pos = vim.fn.win_screenpos(pw)
|
||||
local out = {}
|
||||
for r = pos[1], pos[1] + vim.api.nvim_win_get_height(pw) - 1 do
|
||||
out[#out + 1] = vim.fn.strcharpart(row(r), pos[2] - 1, vim.api.nvim_win_get_width(pw))
|
||||
end
|
||||
return out
|
||||
end
|
||||
local pr = prompt_rows()
|
||||
check("prompt: the row above it is the chip's and is empty; the first line begins with what Enter does",
|
||||
rtrim(pr[1]) == "" and pr[2] == "ask ›" .. (" "):rep(42 - 5), pr)
|
||||
layout.focus("chat")
|
||||
feed("<Tab>")
|
||||
check("Tab in an empty prompt: rewrite", L.intent() == "rewrite" and vim.startswith(prompt_rows()[2], "rewrite › "), prompt_rows())
|
||||
feed("<Tab>")
|
||||
check("Tab again: add", L.intent() == "add" and vim.startswith(prompt_rows()[2], "add › "), prompt_rows())
|
||||
feed("i<Tab>")
|
||||
check("Tab again, while typing: ask", L.intent() == "ask" and vim.startswith(prompt_rows()[2], "ask › "), prompt_rows())
|
||||
check("Tab in an empty prompt leaves it empty", table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "")
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "some text" })
|
||||
vim.bo[chat.ibuf].expandtab = false
|
||||
feed("A<Tab>")
|
||||
check("Tab with text in the prompt is Neovim's own Tab, and what Enter does stays",
|
||||
L.intent() == "ask" and vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false)[1] == "some text\t", vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false))
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "a long line that is wider than the bar and so goes on to a second row of the prompt" })
|
||||
local wrapped = prompt_rows()
|
||||
check("a long prompt keeps one left edge: the rows under the first are indented by the prefix",
|
||||
vim.startswith(wrapped[2], "ask › a long") and vim.startswith(wrapped[3], (" "):rep(10)) and wrapped[3]:sub(11, 11) ~= " ", wrapped)
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
|
||||
feed("<Esc>")
|
||||
check("Esc in the prompt is back in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
|
||||
-- A selection comes along.
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("Vj<C-S-A>")
|
||||
check("Ctrl+Shift+A with a selection: the prompt has the focus and the chip names the lines",
|
||||
vim.api.nvim_get_current_buf() == chat.ibuf and rtrim(prompt_rows()[1]) == " sample.py:1-2", prompt_rows())
|
||||
check("…and it is an ask", L.intent() == "ask" and L.settings().attachment == "sample.py:1-2")
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "META what is this?" })
|
||||
feed("<CR>")
|
||||
check("Enter sends", wait(function() return last_call("session/prompt") ~= nil end) and wait(function() return not L._state.busy end))
|
||||
local p = last_call("session/prompt")
|
||||
local ed = ((p._meta or {}).lembas or {}).editor
|
||||
check("ask: the question goes with the selection as the editor's context",
|
||||
ed and ed.selection and ed.selection.start == 1 and ed.selection["end"] == 2 and ed.selection.text == "def a():\n return 1"
|
||||
and p.prompt[#p.prompt].text == "META what is this?", p)
|
||||
check("ask: the transcript names what came along", chat.text():find("[sample.py:1-2]\nMETA what is this?", 1, true) ~= nil, chat.text())
|
||||
check("ask: the chip is gone and the prompt is empty", rtrim(prompt_rows()[1]) == "" and L.settings().attachment == nil
|
||||
and table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "")
|
||||
check("a session started: the top bar and the settings lines say the model, the mode, the effort and the context",
|
||||
wait(function() return L.settings().context == 4 end)
|
||||
and top():find("│ " .. cell("model-a · manual · default", 32) .. " │ ctx 4% │ AC on ", 1, true) ~= nil
|
||||
and vim.deep_equal(lines.lines(), { "model model-a", "mode manual", "effort default", "autocomplete on" }),
|
||||
{ top(), lines.lines() })
|
||||
check("idle again", vim.startswith(top(), " ● idle │ "), top())
|
||||
|
||||
-- A bare cursor: the line comes along as a point.
|
||||
layout.focus("code")
|
||||
vim.api.nvim_win_set_cursor(0, { 4, 0 })
|
||||
feed(" la")
|
||||
check("<Space>la without a selection: the cursor's line comes along as a point",
|
||||
vim.api.nvim_get_current_buf() == chat.ibuf and rtrim(prompt_rows()[1]) == " sample.py:4", prompt_rows())
|
||||
feed("<Esc>")
|
||||
|
||||
-- Rewrite: the selection is rewritten in place, shown as changes.
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("Vj le")
|
||||
check("<Space>le with a selection: the prompt says rewrite and carries the lines",
|
||||
vim.api.nvim_get_current_buf() == chat.ibuf and L.intent() == "rewrite" and vim.startswith(prompt_rows()[2], "rewrite › ")
|
||||
and rtrim(prompt_rows()[1]) == " sample.py:1-2", prompt_rows())
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "REPLACE def a():\\n return 100" })
|
||||
local before = #calls("session/prompt")
|
||||
feed("<CR>")
|
||||
check("rewrite: the lines go to the rewrite, not to the chat",
|
||||
wait(function() return last_call("_lembas/edit") ~= nil end) and last_call("_lembas/edit").text == "def a():\n return 1"
|
||||
and #calls("session/prompt") == before, last_call("_lembas/edit"))
|
||||
check("rewrite: shown in the file as a change, nothing written", wait(function() return require("llembas.diff").pending(fbuf) == 1 end)
|
||||
and vim.api.nvim_buf_get_lines(fbuf, 1, 2, false)[1] == " return 1")
|
||||
check("rewrite: the focus is in the code, and what Enter does is ask again",
|
||||
vim.api.nvim_get_current_buf() == fbuf and L.intent() == "ask" and L.settings().attachment == nil)
|
||||
check("on a proposed change, chords: the owner's line",
|
||||
wait(function() return keys_part() == " ^⇧Y accept · ^⇧J reject · ]h next · Alt+^⇧Y accept all · [h previous · ^⇧P menu" end), keys_part())
|
||||
local change = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
if k.scope == "change" then
|
||||
for _, lhs in ipairs(keys.alts(k)) do
|
||||
if vim.fn.maparg(lhs, "n", false, true).buffer ~= 1 then change[#change + 1] = lhs end
|
||||
end
|
||||
end
|
||||
end
|
||||
check("keys: with a change shown, the change's own keys are mapped in the buffer", #change == 0, change)
|
||||
feed("<C-S-Y>")
|
||||
check("Ctrl+Shift+Y accepts it", vim.api.nvim_buf_get_lines(fbuf, 1, 2, false)[1] == " return 100" and require("llembas.diff").pending(fbuf) == 0)
|
||||
check("…and the bar is the code's again", wait(function() return vim.startswith(keys_part(), " ^⇧A ask") end), keys_part())
|
||||
|
||||
-- Add: new code at the point.
|
||||
vim.api.nvim_win_set_cursor(0, { 3, 0 })
|
||||
feed(" lg")
|
||||
check("<Space>lg: the prompt says add", L.intent() == "add" and vim.startswith(prompt_rows()[2], "add › ") and rtrim(prompt_rows()[1]) == " sample.py:3", prompt_rows())
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "REPLACE # a comment" })
|
||||
feed("<CR>")
|
||||
check("add: asked for at the point, and shown as a change",
|
||||
wait(function() return require("llembas.diff").pending(fbuf) == 1 end) and last_call("_lembas/edit").instruction == "At this line, REPLACE # a comment",
|
||||
last_call("_lembas/edit"))
|
||||
feed("<C-S-J>")
|
||||
check("Ctrl+Shift+J rejects it", require("llembas.diff").pending(fbuf) == 0 and vim.api.nvim_buf_get_lines(fbuf, 2, 3, false)[1] == "")
|
||||
|
||||
-- ── Tab's three jobs never collide. ─────────────────────────────────────────────────────────────
|
||||
C._typing = function() return true end
|
||||
vim.api.nvim_win_set_cursor(0, { 5, 12 })
|
||||
C.request(true)
|
||||
check("a suggestion is shown, and <Tab> is the buffer's while it is", wait(function() return C.visible() end)
|
||||
and vim.fn.maparg("<Tab>", "i", false, true).buffer == 1 and vim.fn.maparg("<M-Right>", "i", false, true).buffer == 1)
|
||||
C.accept()
|
||||
check("accepted: <Tab> is nobody's in the code again (Neovim's own)", not C.visible() and vim.fn.maparg("<Tab>", "i", false, true).buffer ~= 1)
|
||||
check("Alt+→ in the code without a suggestion is the bars' key, with one it was the suggestion's",
|
||||
(vim.fn.maparg("<M-Right>", "i", false, true).desc or ""):find("bar on the right", 1, true) ~= nil)
|
||||
vim.cmd("silent undo")
|
||||
|
||||
-- ── The settings lines: Enter opens the choices in place. ──────────────────────────────────────
|
||||
vim.api.nvim_set_current_win(wins().settings.win)
|
||||
vim.api.nvim_win_set_cursor(0, { 2, 0 })
|
||||
feed("<CR>")
|
||||
check("Enter on mode: its choices open under the line, in the bar, the current one marked",
|
||||
wait(function() return #lines.lines() == 8 end)
|
||||
and vim.deep_equal(vim.list_slice(lines.lines(), 2, 6), { "mode manual", " ● manual", " ○ edit", " ○ auto", " ○ plan" })
|
||||
and wins().settings.height == 8 and vim.api.nvim_win_get_cursor(0)[1] == 3, { lines.lines(), wins().settings })
|
||||
check("…and no window floats in the middle of the screen", (function()
|
||||
for _, win in ipairs(vim.api.nvim_list_wins()) do if vim.api.nvim_win_get_config(win).relative ~= "" then return false end end
|
||||
return true
|
||||
end)())
|
||||
feed("j<CR>")
|
||||
check("Enter on a choice sets it through the agent, the list closes, the line and the top bar follow",
|
||||
wait(function() return L._state.mode == "edit" end) and last_call("session/set_mode").modeId == "edit"
|
||||
and wait(function() return lines.lines()[2] == "mode edit" and #lines.lines() == 4 end)
|
||||
and top():find("model-a · edit · default", 1, true) ~= nil and wins().settings.height == 4, { lines.lines(), top() })
|
||||
vim.api.nvim_win_set_cursor(0, { 3, 0 })
|
||||
feed("<CR>")
|
||||
check("Enter on effort: the levels", wait(function() return #lines.lines() == 4 + #L.EFFORTS end) and lines.lines()[4] == " ○ off", lines.lines())
|
||||
feed("<Esc>")
|
||||
check("Esc closes the choices and stays in the lines", #lines.lines() == 4 and layout.where() == "settings")
|
||||
L.set("effort", "high")
|
||||
check("effort: set through the agent (`_lembas/configure`), and shown",
|
||||
wait(function() return (last_call("_lembas/configure") or {}).effort == "high" end)
|
||||
and wait(function() return lines.lines()[3] == "effort high" end) and top():find("model-a · edit · high", 1, true) ~= nil, { lines.lines(), top() })
|
||||
said_msgs = {}
|
||||
L.set("effort", "xhigh")
|
||||
check("effort: a level the model does not offer is said, with the level it runs on",
|
||||
wait(function() return was_said("does not offer the effort xhigh; it runs on medium") end) and L.settings().effort == "medium", said_msgs)
|
||||
L.set("effort", "high")
|
||||
wait(function() return L.settings().effort == "high" end)
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("<CR>")
|
||||
check("Enter on model: the account's models, by name", wait(function() return #lines.lines() == 7 end)
|
||||
and vim.deep_equal(vim.list_slice(lines.lines(), 2, 4), { " ● Model A", " ○ Model B", " ○ Model C" }), lines.lines())
|
||||
feed("j<CR>")
|
||||
check("model: set through the agent, and shown", wait(function() return L._state.model == "example/model-b" end)
|
||||
and wait(function() return lines.lines()[1] == "model model-b" end), lines.lines())
|
||||
vim.api.nvim_win_set_cursor(0, { 4, 0 })
|
||||
feed("<CR>j<CR>")
|
||||
check("autocomplete: off from its line; the top bar says so", wait(function() return L.settings().autocomplete == false end)
|
||||
and wait(function() return lines.lines()[4] == "autocomplete off" end) and top():find("│ AC off ", 1, true) ~= nil, { lines.lines(), top() })
|
||||
L.set("autocomplete", "on")
|
||||
feed("<Esc>")
|
||||
check("Esc from the lines is back in the code", vim.api.nvim_get_current_buf() == fbuf)
|
||||
feed("<C-Tab>")
|
||||
check("Ctrl+Tab switches to the next mode", wait(function() return L._state.mode == "auto" end), L._state.mode)
|
||||
|
||||
-- The state the top bar says.
|
||||
layout.focus("chat")
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "SLOW" })
|
||||
feed("<CR>")
|
||||
check("a turn runs: the top bar says what the agent does", wait(function() return top():match("^ ◐ %a+ ") ~= nil end)
|
||||
and (L.settings().state == "writing" or L.settings().state == "thinking" or L.settings().state == "tools"), top())
|
||||
feed("<C-S-G>")
|
||||
check("Ctrl+Shift+G stops it", wait(function() return not L._state.busy end) and wait(function() return vim.startswith(top(), " ● idle ") end), top())
|
||||
local asked
|
||||
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts, cb = cb } end
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, { "PERM" })
|
||||
feed("<CR>")
|
||||
check("the agent asks: the top bar says it waits for you", wait(function() return asked ~= nil end)
|
||||
and wait(function() return vim.startswith(top(), " ● waiting for you │ ") end), top())
|
||||
asked.cb(asked.items[1])
|
||||
wait(function() return not L._state.busy end)
|
||||
|
||||
-- The menu has every command and every setting, effort among them.
|
||||
asked = nil
|
||||
feed("<C-S-P>")
|
||||
local menu = {}
|
||||
for _, i in ipairs(asked and asked.items or {}) do menu[#menu + 1] = asked.opts.format_item(i) end
|
||||
local menu_text = table.concat(menu, "\n")
|
||||
check("Ctrl+Shift+P: the menu has the settings — model, mode, effort, autocomplete — and the commands with their keys",
|
||||
menu_text:find("Model: example/model-b", 1, true) and menu_text:find("Mode: auto", 1, true) and menu_text:find("Effort: high", 1, true)
|
||||
and menu_text:find("Autocomplete: on", 1, true) and menu_text:find("Tree: shown", 1, true)
|
||||
and menu_text:find("Stop the running turn [^⇧G]", 1, true) and menu_text:find("Earlier conversations [Spc ls]", 1, true), menu_text)
|
||||
local in_menu = {}
|
||||
for _, k in ipairs(keys.table) do
|
||||
if k.run and not k.scope and not menu_text:find(k.desc, 1, true) then in_menu[#in_menu + 1] = k.id end
|
||||
end
|
||||
check("…every action of the key table is in the menu", #in_menu == 0, in_menu)
|
||||
for _, i in ipairs(asked.items) do
|
||||
if i.text:match("^Effort") then
|
||||
local inner
|
||||
vim.ui.select = function(items, _, cb) inner = items; cb("low") end
|
||||
i.run()
|
||||
check("menu: Effort opens the levels, and the one picked is set", inner and vim.deep_equal(inner, L.EFFORTS)
|
||||
and wait(function() return L.settings().effort == "low" end), inner)
|
||||
end
|
||||
end
|
||||
layout.focus("code")
|
||||
|
||||
-- ── 100×30 and 80×24: the bars fold. ────────────────────────────────────────────────────────────
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
vim.bo[fbuf].modified = false
|
||||
resize(100, 30)
|
||||
w = wins()
|
||||
check("100×30: the chat folds away, the tree stays", kinds(w) == "code tree" and w.tree.width == 26 and w.code.width == 73, w)
|
||||
check("100×30: the top bar, narrower cells",
|
||||
top() == " ● idle │ " .. cell("conversation", 100 - 2 - 17 - 3 - 3 - 32 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-b · auto · low", 32) .. " │ ctx 4% │ AC on ", top())
|
||||
check("100×30: the bottom bar is cut by priority, and Neovim's state is the short one",
|
||||
keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu · Alt+←→ bars" and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ",
|
||||
{ keys_part(), "[" .. vim_part() .. "]" })
|
||||
check("100×30: both rows are 100 wide", width(top()) == 100 and width(bottom()) == 100)
|
||||
check("100×30: the layout says what is folded", layout.options().folded.chat == true and layout.options().folded.tree == false)
|
||||
feed("<C-S-D>")
|
||||
check("100×30: Ctrl+Shift+D shows the chat all the same", wait(function() return chat.is_open() end) and wins().chat.width == 42, wins())
|
||||
feed("<C-S-D>")
|
||||
wait(function() return not chat.is_open() end)
|
||||
L._state.busy = false
|
||||
resize(80, 24)
|
||||
w = wins()
|
||||
check("80×24: only the code, all 80 columns", kinds(w) == "code" and w.code.width == 80, w)
|
||||
check("80×24: the top bar",
|
||||
top() == " ● idle │ " .. cell("conversation", 80 - 2 - 9 - 3 - 3 - 26 - 3 - 8 - 3 - 6) .. " │ " .. cell("model-b · auto · low", 26) .. " │ ctx 4% │ AC on ", top())
|
||||
check("80×24: the bottom bar", keys_part() == " ^⇧A ask · Tab accept suggestion · Alt+→ one word · ^⇧P menu" and vim_part() == " NOR" .. (" "):rep(10) .. "1:1 ",
|
||||
{ keys_part(), "[" .. vim_part() .. "]" })
|
||||
check("80×24: both rows are 80 wide", width(top()) == 80 and width(bottom()) == 80)
|
||||
feed("<M-Right>")
|
||||
check("80×24: Alt+→ opens the chat and goes to its prompt", chat.is_open() and vim.api.nvim_get_current_buf() == chat.ibuf)
|
||||
feed("<Esc>")
|
||||
resize(50, 12)
|
||||
check("50×12: still one row each, exactly as wide, the least needed gone", width(top()) == 50 and width(bottom()) == 50
|
||||
and vim.startswith(top(), " ● idle │ ") and vim_part() == " NOR" .. (" "):rep(5) .. "1:1 ", { top(), bottom() })
|
||||
resize(160, 14)
|
||||
w = wins()
|
||||
check("160×14: too low for the settings lines; the prompt is one row", kinds(w) == "chat code prompt tree" and w.prompt.height == 2, w)
|
||||
resize(160, 45)
|
||||
check("160×45 again: everything is back", kinds(wins()) == "chat code prompt settings tree", kinds(wins()))
|
||||
|
||||
-- Neovim's own state in the bottom bar.
|
||||
layout.focus("code")
|
||||
vim.api.nvim_buf_set_lines(fbuf, 0, 1, false, { "def a(): # changed" })
|
||||
feed("qq")
|
||||
check("modified and recording: the flags are in their cells", vim_part() == " NOR + @q" .. (" "):rep(14) .. "1:1 ", "[" .. vim_part() .. "]")
|
||||
feed("q")
|
||||
vim.api.nvim_win_set_cursor(0, { 2, 4 })
|
||||
check("the cursor's line and column", vim_part():sub(-10) == " 2:5 ", "[" .. vim_part() .. "]")
|
||||
vim.cmd("silent! undo")
|
||||
|
||||
-- ── The tree. ───────────────────────────────────────────────────────────────────────────────────
|
||||
check("tree: the directory as lines, directories first, the file you are in shown",
|
||||
vim.deep_equal(tree.lines(), { " ▸ src/", " README.md", " sample.py" }), tree.lines())
|
||||
layout.focus("tree")
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
feed("<CR>")
|
||||
check("tree: Enter opens a directory", vim.deep_equal(tree.lines(), { " ▾ src/", " ▸ deep/", " util.py", " README.md", " sample.py" }), tree.lines())
|
||||
feed("<Left>")
|
||||
check("tree: ← closes it", tree.lines()[1] == " ▸ src/" and #tree.lines() == 3, tree.lines())
|
||||
feed("<Right><Right>")
|
||||
check("tree: → opens it and leaves it open", tree.lines()[1] == " ▾ src/" and #tree.lines() == 5, tree.lines())
|
||||
vim.api.nvim_win_set_cursor(0, { 3, 0 })
|
||||
feed("<CR>")
|
||||
check("tree: Enter on a file opens it in the code's window", vim.api.nvim_buf_get_name(0) == tmp .. "/src/util.py" and layout.where() == "code")
|
||||
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/src/deep/inner.py"))
|
||||
check("tree: the file you are in is followed — its directories open, its row under the tree's cursor",
|
||||
tree.lines()[3] == " inner.py" and vim.api.nvim_win_get_cursor(tree.win())[1] == 3, tree.lines())
|
||||
layout.focus("tree")
|
||||
feed(".")
|
||||
check("tree: . shows hidden files", vim.tbl_contains(tree.lines(), " .env.example"), tree.lines())
|
||||
feed(".")
|
||||
check("tree: . hides them again", not vim.tbl_contains(tree.lines(), " .env.example"))
|
||||
tree.set_filter("inner")
|
||||
check("tree: a filter shows the files whose path has the text", vim.deep_equal(tree.lines(), { " src/deep/inner.py" }), tree.lines())
|
||||
tree.set_filter("")
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
tree.create("new/thing.py")
|
||||
check("tree: a new file, its directories made, opened", vim.fn.filereadable(tmp .. "/src/new/thing.py") == 1
|
||||
and vim.api.nvim_buf_get_name(0) == tmp .. "/src/new/thing.py", tree.lines())
|
||||
layout.focus("tree")
|
||||
tree.create("../../../outside.py")
|
||||
tree.create("/somewhere/else.py")
|
||||
check("tree: nothing is made outside the tree's directory", vim.fn.filereadable(vim.fs.dirname(tmp) .. "/outside.py") == 0 and vim.fn.isdirectory("/somewhere") == 0)
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
tree.create("pkg/")
|
||||
check("tree: a name ending in / makes a directory", vim.fn.isdirectory(tmp .. "/src/pkg") == 1)
|
||||
for i, l in ipairs(tree.lines()) do if l:find("thing.py", 1, true) then vim.api.nvim_win_set_cursor(tree.win(), { i, 0 }) end end
|
||||
tree.rename("src/pkg/renamed.py")
|
||||
check("tree: rename moves the file, and its open buffer with it", vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 1
|
||||
and vim.fn.filereadable(tmp .. "/src/new/thing.py") == 0 and vim.fn.bufnr(tmp .. "/src/pkg/renamed.py") ~= -1, tree.lines())
|
||||
local question
|
||||
tree._confirm = function(q) question = q; return false end
|
||||
tree._trash = function() return nil end
|
||||
tree.delete()
|
||||
check("tree: delete asks first, and says when there is no trash; a no deletes nothing",
|
||||
question == "Delete src/pkg/renamed.py for good? (No trash was found on this system.)" and vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 1, question)
|
||||
local trash = work .. "/trash.sh"
|
||||
vim.fn.writefile({ "#!/bin/sh", 'mkdir -p "' .. work .. '/trashed" && mv "$1" "' .. work .. '/trashed/"' }, trash)
|
||||
vim.fn.setfperm(trash, "rwx------")
|
||||
tree._trash = function() return { trash } end
|
||||
tree._confirm = function(q) question = q; return true end
|
||||
tree.delete()
|
||||
check("tree: with a trash the file goes there", question == "Move src/pkg/renamed.py to the trash?"
|
||||
and vim.fn.filereadable(tmp .. "/src/pkg/renamed.py") == 0 and vim.fn.filereadable(work .. "/trashed/renamed.py") == 1, question)
|
||||
if vim.fn.executable("git") == 1 then
|
||||
vim.fn.system({ "git", "-C", tmp, "init", "-q", "-b", "trunk" })
|
||||
vim.fn.system({ "git", "-C", tmp, "add", "README.md" })
|
||||
tree.refresh()
|
||||
check("tree: one git mark a row — a new file, an added one, a directory with changes inside",
|
||||
wait(function() return vim.tbl_contains(tree.lines(), "? sample.py") end, 5000) and vim.tbl_contains(tree.lines(), "A README.md")
|
||||
and tree.lines()[1] == "• ▾ src/", tree.lines())
|
||||
check("the top bar's right end has the branch when it fits", wait(function() return top():find("│ trunk ", 1, true) ~= nil end, 3000), top())
|
||||
end
|
||||
layout.focus("code")
|
||||
vim.cmd("edit " .. vim.fn.fnameescape(tmp .. "/sample.py"))
|
||||
|
||||
-- ── What a model or a file's name says is text. ─────────────────────────────────────────────────
|
||||
local title = L._state.title
|
||||
L._state.title = "50% done\nnext %#Error#line %{1+1}"
|
||||
check("a title is shown as text on one line: no line break, no highlight or expression of its own, the bar as wide as ever",
|
||||
top():find("│ 50% done next %#Error#line %{1+1} ", 1, true) ~= nil and width(top()) == 160, top())
|
||||
L._state.title = title
|
||||
local odd = tmp .. "/odd\nname.py"
|
||||
if pcall(vim.fn.writefile, { "" }, odd) and vim.uv.fs_stat(odd) then
|
||||
tree.refresh()
|
||||
check("a file's name with a line break in it is one row of the tree", vim.tbl_contains(tree.lines(), " odd?name.py")
|
||||
or vim.tbl_contains(tree.lines(), "? odd?name.py"), tree.lines())
|
||||
vim.fn.delete(odd)
|
||||
tree.refresh()
|
||||
end
|
||||
vim.cmd("tabnew")
|
||||
check("a second tab page: the top bar says which one this is", top():find("│ tab 2/2 ", 1, true) ~= nil and width(top()) == 160, top())
|
||||
vim.cmd("tabclose")
|
||||
vim.cmd("2,3LLeMbasPrompt rewrite")
|
||||
check(":2,3LLeMbasPrompt rewrite: the lines come along and the prompt says rewrite",
|
||||
L.intent() == "rewrite" and L.settings().attachment == "sample.py:2-3" and vim.api.nvim_get_current_buf() == chat.ibuf, L.settings())
|
||||
L.intent("ask")
|
||||
feed("<Esc>")
|
||||
|
||||
-- ── AI off: a plain editor. ─────────────────────────────────────────────────────────────────────
|
||||
local agent = L._state.conn and L._state.conn.proc.pid
|
||||
feed("<C-S-I>")
|
||||
check("Ctrl+Shift+I: LLeMbas is off — the agent is stopped, the chat put away, the top bar says so",
|
||||
L.settings().ai == false and L._state.conn == nil and wait(function() return not chat.is_open() end)
|
||||
and vim.startswith(top(), " ● AI off │ ") and kinds(wins()) == "code tree", { top(), kinds(wins()) })
|
||||
check("AI off: the agent's process ends", wait(function() return not (agent and vim.uv.kill(agent, 0) == 0) end, 7000))
|
||||
local n_complete = #calls("_lembas/complete")
|
||||
C.request(false)
|
||||
vim.wait(200)
|
||||
check("AI off: no suggestion is asked for", #calls("_lembas/complete") == n_complete)
|
||||
said_msgs = {}
|
||||
feed("<C-S-A>")
|
||||
check("AI off: asking says that it is off, and opens nothing", was_said("LLeMbas is off") and not chat.is_open(), said_msgs)
|
||||
feed("<C-S-I>")
|
||||
check("Ctrl+Shift+I again: on, and the chat is back", L.settings().ai == true and wait(function() return chat.is_open() end))
|
||||
|
||||
-- ── Each bar can be switched off. ───────────────────────────────────────────────────────────────
|
||||
layout.toggle("top", false)
|
||||
check("the top bar off: Neovim's own tabline setting is back", vim.o.showtabline ~= 2 and vim.o.tabline == "")
|
||||
layout.toggle("bottom", false)
|
||||
check("the bottom bar off: Neovim's own statusline is back", vim.o.statusline == "")
|
||||
layout.toggle("top", true)
|
||||
layout.toggle("bottom", true)
|
||||
check("…and on again", vim.startswith(top(), " ● idle") and vim.startswith(keys_part(), " ^⇧A ask"), { top(), keys_part() })
|
||||
|
||||
-- ── Remembered across restarts, per directory. ──────────────────────────────────────────────────
|
||||
local dir_a, dir_b, dir_c = work .. "/dir-a", work .. "/dir-b", work .. "/dir-c"
|
||||
for _, d in ipairs({ dir_a, dir_b, dir_c }) do vim.fn.mkdir(d, "p") end
|
||||
local state_home = work .. "/remember-state"
|
||||
vim.fn.mkdir(state_home, "p")
|
||||
local env = { XDG_STATE_HOME = state_home, FAKE_AGENT_LOG = work .. "/remember.log", PATH = vim.env.PATH, HOME = vim.env.HOME }
|
||||
local function step(dir, name, more) return child_json(dir, vim.tbl_extend("force", env, { STEP = name }, more or {})) end
|
||||
local r = step(dir_a, "change")
|
||||
check("remember: in a first directory the mode, the effort, suggestions and the bars are changed", r.mode == "edit" and r.effort == "high"
|
||||
and r.autocomplete == false and r.tree == false and r.chat_width == 46, r)
|
||||
r = step(dir_b, "look")
|
||||
check("remember: another directory knows nothing of that", r.mode == nil and r.effort == nil and r.autocomplete == true and r.tree == true and r.chat_width == 42, r)
|
||||
r = step(dir_b, "change_b")
|
||||
check("remember: and is changed in its own way", r.mode == "plan" and r.tree == true, r)
|
||||
r = step(dir_a, "look")
|
||||
check("remember: the first directory, started again, has what was chosen there — before any session",
|
||||
r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false and r.chat_width == 46 and r.tree_open == false, r)
|
||||
r = step(dir_a, "session")
|
||||
check("remember: a session there starts on that mode and that effort", r.new_mode == "edit" and r.new_effort == "high" and r.mode == "edit" and r.effort == "high", r)
|
||||
r = step(dir_b, "look")
|
||||
check("remember: the second directory has its own", r.mode == "plan" and r.effort == nil and r.autocomplete == true and r.tree == true, r)
|
||||
r = step(dir_a, "default")
|
||||
r = step(dir_c, "look")
|
||||
check("remember: made the default, the first directory's choices are what a new directory starts with",
|
||||
r.mode == "edit" and r.effort == "high" and r.autocomplete == false and r.tree == false, r)
|
||||
r = step(dir_b, "look")
|
||||
check("remember: and a directory keeps what it chose itself (the mode), over the default it now takes the rest from",
|
||||
r.mode == "plan" and r.effort == "high" and r.tree == false, r)
|
||||
r = step(dir_a, "ai_off")
|
||||
r = step(dir_a, "look")
|
||||
check("remember: AI off is remembered too", r.ai == false, r)
|
||||
r = step(dir_b, "cd", { CD_TO = dir_a })
|
||||
check("remember: after :cd the new directory's choices hold — AI off, its mode, its suggestions",
|
||||
r.ai == false and r.mode == "edit" and r.autocomplete == false, r)
|
||||
r = step(dir_a, "cd", { CD_TO = dir_b })
|
||||
check("remember: and :cd back to a directory with AI on turns it on, with that directory's mode",
|
||||
r.ai == true and r.mode == "plan", r)
|
||||
local f = io.open(state_home .. "/nvim/llembas/settings.json")
|
||||
local stored = f and vim.json.decode(f:read("*a")) or {}
|
||||
if f then f:close() end
|
||||
check("remember: one file in Neovim's state directory, with a machine-wide level and one per directory, and no model in it",
|
||||
stored.global and stored.global.mode == "edit" and stored.directories[dir_a].mode == "edit" and stored.directories[dir_b].mode == "plan"
|
||||
and stored.directories[dir_a].model == nil and stored.global.model == nil, stored)
|
||||
local perm = vim.uv.fs_stat(state_home .. "/nvim/llembas/settings.json")
|
||||
check("remember: the file is the person's alone (0600)", perm and bit.band(perm.mode, 511) == 384, perm and bit.band(perm.mode, 511))
|
||||
|
||||
-- ── The terminal: the user var. ─────────────────────────────────────────────────────────────────
|
||||
local set, clear = "\27]1337;SetUserVar=llembas_ide=MQ==\7", "\27]1337;SetUserVar=llembas_ide=\7"
|
||||
check("user var: the bytes are OSC 1337 SetUserVar with base64 of 1, and an empty value to clear",
|
||||
layout.uservar_bytes("1") == set and layout.uservar_bytes("") == clear)
|
||||
local _, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TERM = "1" }))
|
||||
check("user var: in the LLeMbas terminal it is set on start and cleared on exit, and nothing else is written",
|
||||
err == set .. clear, vim.inspect(err))
|
||||
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TTY = "pane-1" }))
|
||||
check("user var: $LLEMBAS_TTY counts as well", err == set .. clear, vim.inspect(err))
|
||||
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start" }))
|
||||
check("user var: in any other terminal nothing is written", err == "", vim.inspect(err))
|
||||
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "start", LLEMBAS_TERM = "1", TMUX = "/tmp/tmux-1/default,1,0" }))
|
||||
check("user var: inside tmux it is wrapped for tmux to pass on",
|
||||
err == "\27Ptmux;\27\27]1337;SetUserVar=llembas_ide=MQ==\7\27\\" .. "\27Ptmux;\27\27]1337;SetUserVar=llembas_ide=\7\27\\", vim.inspect(err))
|
||||
_, err = run_child(dir_c, vim.tbl_extend("force", env, { STEP = "plain", LLEMBAS_TERM = "1" }))
|
||||
check("user var: a plugin set up without keys or bars says nothing, in that terminal either", err == "", vim.inspect(err))
|
||||
r = step(dir_c, "chords", { LLEMBAS_TERM = "1" })
|
||||
check("chords: in the LLeMbas terminal the bar shows the chords from the start", r.chords == true and r.guess == true, r)
|
||||
r = step(dir_c, "chords", { TMUX = "/tmp/tmux-1/default,1,0", KITTY_WINDOW_ID = "1" })
|
||||
check("chords: behind a multiplexer they are not assumed", r.guess == false, r)
|
||||
r = step(dir_c, "chords", { KITTY_WINDOW_ID = "1" })
|
||||
check("chords: a terminal known to report them is taken at its word", r.guess == true, r)
|
||||
end
|
||||
|
||||
|
||||
vim.schedule(function()
|
||||
local ok, err = xpcall(run, debug.traceback)
|
||||
if not ok then
|
||||
failed = failed + 1
|
||||
say("FAIL the checks themselves stopped: " .. tostring(err))
|
||||
end
|
||||
local leftover = vim.fn.execute("messages")
|
||||
if leftover:match("E%d+:") then
|
||||
failed = failed + 1
|
||||
say("FAIL an error message was left: " .. leftover)
|
||||
end
|
||||
say(("RAN %d, failed %d (layout)"):format(ran, failed))
|
||||
pcall(function() require("llembas").restart(true) end)
|
||||
vim.cmd("cd /")
|
||||
if own_work then vim.fn.delete(work, "rf") end
|
||||
vim.cmd(failed == 0 and "qall!" or "cquit!")
|
||||
end)
|
||||
@@ -0,0 +1,80 @@
|
||||
-- The rules both editors keep, against the cases in tests/rules/ (the VS Code extension reads the
|
||||
-- same files in vscode/tests/rules.test.js). Run by scripts/test-nvim.sh:
|
||||
-- nvim --headless -u NONE --cmd "set rtp+=nvim" -l nvim/tests/rules.lua
|
||||
local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h")
|
||||
local repo = vim.fs.normalize(here .. "/../..")
|
||||
vim.opt.rtp:append(repo .. "/nvim")
|
||||
|
||||
local failed, ran = 0, 0
|
||||
local function check(name, cond, extra)
|
||||
ran = ran + 1
|
||||
if cond then print("ok " .. name) else
|
||||
failed = failed + 1
|
||||
print("FAIL " .. name .. (extra and ("\n " .. tostring(extra)) or ""))
|
||||
end
|
||||
end
|
||||
local function cases(name)
|
||||
local f = assert(io.open(repo .. "/tests/rules/" .. name .. ".json", "rb"))
|
||||
local text = f:read("*a")
|
||||
f:close()
|
||||
return vim.json.decode(text, { luanil = { object = true, array = true } })
|
||||
end
|
||||
local function unhex(s) return (s:gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end)) end
|
||||
|
||||
local L = require("llembas")
|
||||
local private = require("llembas.private")
|
||||
local login = require("llembas.login")
|
||||
local rpc = require("llembas.rpc")
|
||||
local shown = require("llembas.shown")
|
||||
|
||||
-- versions
|
||||
local versions = cases("versions")
|
||||
for _, c in ipairs(versions.compare) do
|
||||
check(("versions: %q against %q is %d"):format(c[1], c[2], c[3]), L.compare_versions(c[1], c[2]) == c[3], vim.inspect(L.compare_versions(c[1], c[2])))
|
||||
check(("versions: and %q against %q is %d"):format(c[2], c[1], -c[3]), L.compare_versions(c[2], c[1]) == -c[3])
|
||||
end
|
||||
for _, v in ipairs(versions.not_versions) do
|
||||
check(("versions: %q is no version"):format(v), L.compare_versions(v, "1.0.0") == nil and L.compare_versions("1.0.0", v) == nil)
|
||||
end
|
||||
|
||||
-- files that are never sent along
|
||||
local files = cases("private_files")
|
||||
for _, p in ipairs(files.secret) do check("private: looks secret: " .. p, private.looks_secret(p) == true) end
|
||||
for _, p in ipairs(files.plain) do check("private: does not look secret: " .. p, private.looks_secret(p) == false) end
|
||||
for _, c in ipairs(files.inside) do
|
||||
check(("private: %s inside %s: %s"):format(c[1], vim.inspect(c[2]), tostring(c[3])), private.inside(c[1], c[2]) == c[3])
|
||||
end
|
||||
|
||||
-- the server's address
|
||||
local addresses = cases("server_address")
|
||||
for _, a in ipairs(addresses.ok) do check(("address: %q is taken"):format(a), login.address(a) == vim.trim(a)) end
|
||||
for _, a in ipairs(addresses.refused) do check(("address: %q is refused"):format(a), login.address(a) == nil) end
|
||||
|
||||
-- the sign-in's events, in whatever pieces they arrive
|
||||
for i, c in ipairs(cases("login_events")) do
|
||||
local got = {}
|
||||
local feed = login._reader(function(ev) got[#got + 1] = ev.event end)
|
||||
for _, chunk in ipairs(c.chunks) do feed(chunk) end
|
||||
check(("login: case %d reads %s"):format(i, vim.inspect(c.events)), vim.deep_equal(got, c.events), vim.inspect(got))
|
||||
end
|
||||
|
||||
-- a line longer than the reader keeps
|
||||
local lines = cases("rpc_lines")
|
||||
for i, c in ipairs(lines.cases) do
|
||||
local got = {}
|
||||
local reader = setmetatable({ buf = "", err = "", max_line = lines.max, on = {} }, rpc)
|
||||
reader._message = function(_, msg) got[#got + 1] = msg.method end
|
||||
for _, chunk in ipairs(c.chunks) do reader:_feed(chunk) end
|
||||
vim.wait(500, function() return #got >= #c.methods end, 5)
|
||||
vim.wait(20)
|
||||
check(("rpc: case %d keeps %s"):format(i, vim.inspect(c.methods)), vim.deep_equal(got, c.methods), vim.inspect(got))
|
||||
end
|
||||
|
||||
-- what may be opened
|
||||
for _, c in ipairs(cases("openable")) do
|
||||
local kind = shown.openable(unhex(c.head), c.name)
|
||||
check(("open: %s is %s"):format(c.name, tostring(c.kind)), kind == c.kind, tostring(kind))
|
||||
end
|
||||
|
||||
print(("RAN %d, failed %d"):format(ran, failed))
|
||||
vim.cmd(failed == 0 and "qall!" or "cquit!")
|
||||
+745
-165
File diff suppressed because it is too large.
Load diff
Executable
+440
@@ -0,0 +1,440 @@
|
||||
#!/usr/bin/env python3
|
||||
"""The colourscheme of LLeMbas IDE, generated from the family's design tokens.
|
||||
|
||||
scripts/gen-ide-theme.py writes ide/config/colors/llembas.lua
|
||||
scripts/gen-ide-theme.py --check exits 1 when that file is not what the tokens give
|
||||
scripts/gen-ide-theme.py --tokens FILE --out FILE
|
||||
|
||||
The tokens file is the LLeMbas server's tokens.css, or the copy of its colour declarations in
|
||||
ide/tokens.css. Its two themes become the two halves of one colourscheme: `moria` when
|
||||
'background' is dark, `shire` when it is light. Every colour the editor draws comes out of this
|
||||
file's output; the configuration itself names highlight groups, never colours.
|
||||
|
||||
Standard library only.
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
THEMES = {"dark": "moria", "light": "shire"}
|
||||
NEEDED = [
|
||||
"bg", "bg-sunken", "surface", "surface-raised", "surface-hover", "surface-active", "border",
|
||||
"border-strong", "ink", "ink-muted", "ink-faint", "ink-inverse", "accent", "accent-hover",
|
||||
"accent-ink", "accent-soft", "selection", "leaf", "leaf-hover", "leaf-soft", "danger",
|
||||
"danger-soft", "success", "success-soft", "warning", "warning-soft",
|
||||
]
|
||||
|
||||
|
||||
def parse(css: str) -> dict:
|
||||
"""{theme: {token: value}} for the theme blocks of a tokens file."""
|
||||
out = {}
|
||||
for match in re.finditer(r"([^{}]*)\{([^{}]*)\}", css):
|
||||
names = re.findall(r'data-theme="([a-z0-9-]+)"', match.group(1))
|
||||
if not names:
|
||||
continue
|
||||
decls = dict(re.findall(r"--([a-z0-9-]+):\s*([^;]+);", match.group(2)))
|
||||
for name in names:
|
||||
out.setdefault(name, {}).update({k: " ".join(v.split()) for k, v in decls.items()})
|
||||
return out
|
||||
|
||||
|
||||
def rgb(value: str):
|
||||
value = value.strip()
|
||||
m = re.fullmatch(r"#([0-9A-Fa-f]{6})", value)
|
||||
if m:
|
||||
h = m.group(1)
|
||||
return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4)), 1.0
|
||||
m = re.fullmatch(r"rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([0-9.]+)\s*)?\)", value)
|
||||
if m:
|
||||
return (int(m.group(1)), int(m.group(2)), int(m.group(3))), float(m.group(4) or 1)
|
||||
raise ValueError(f"not a colour this generator reads: {value!r}")
|
||||
|
||||
|
||||
def mix(top, bottom, share):
|
||||
"""`share` of top over bottom."""
|
||||
return tuple(round(t * share + b * (1 - share)) for t, b in zip(top, bottom))
|
||||
|
||||
|
||||
def hexa(c):
|
||||
return "#{:02X}{:02X}{:02X}".format(*c)
|
||||
|
||||
|
||||
def palette(tokens: dict) -> dict:
|
||||
"""The tokens as opaque colours (a translucent one is laid over the background), plus the
|
||||
few mixes an editor needs that a web page does not."""
|
||||
missing = [n for n in NEEDED if n not in tokens]
|
||||
if missing:
|
||||
raise ValueError("the tokens file lacks: " + ", ".join(missing))
|
||||
bg, _ = rgb(tokens["bg"])
|
||||
p = {}
|
||||
for name in NEEDED:
|
||||
colour, alpha = rgb(tokens[name])
|
||||
p[name.replace("-", "_")] = colour if alpha >= 1 else mix(colour, bg, alpha)
|
||||
# What an editor needs between the tokens: all of them mixes of two tokens.
|
||||
p["line"] = mix(p["surface_hover"], p["bg"], 0.55) # the cursor's line
|
||||
p["ghost"] = mix(p["ink_faint"], p["bg"], 0.75) # text that is not there yet
|
||||
p["guide"] = mix(p["border"], p["bg"], 0.7) # whitespace, indent guides
|
||||
p["match"] = mix(p["warning"], p["bg"], 0.3) # a search match's background
|
||||
p["add_bg"] = mix(p["leaf"], p["bg"], 0.16)
|
||||
p["change_bg"] = mix(p["warning"], p["bg"], 0.14)
|
||||
p["delete_bg"] = mix(p["danger"], p["bg"], 0.16)
|
||||
p["text_bg"] = mix(p["warning"], p["bg"], 0.32)
|
||||
return {k: hexa(v) for k, v in p.items()}
|
||||
|
||||
|
||||
# group = (foreground, background, attributes) by palette name, or a link to another group.
|
||||
# One table for both themes: the palettes differ, the roles do not.
|
||||
GROUPS = [
|
||||
# --- the editor ---
|
||||
("Normal", "ink", "bg", ""),
|
||||
("NormalNC", "ink", "bg", ""),
|
||||
("NormalFloat", "ink", "surface", ""),
|
||||
("FloatBorder", "border_strong", "surface", ""),
|
||||
("FloatTitle", "leaf", "surface", "bold"),
|
||||
("FloatFooter", "ink_faint", "surface", ""),
|
||||
("Cursor", "bg", "ink", ""),
|
||||
("CursorLine", None, "line", ""),
|
||||
("CursorColumn", None, "line", ""),
|
||||
("ColorColumn", None, "surface", ""),
|
||||
("LineNr", "ink_faint", None, ""),
|
||||
("CursorLineNr", "leaf", "line", "bold"),
|
||||
("SignColumn", "ink_faint", "bg", ""),
|
||||
("FoldColumn", "ink_faint", "bg", ""),
|
||||
("Folded", "ink_muted", "surface", ""),
|
||||
("WinSeparator", "border", None, ""),
|
||||
("VertSplit", "border", None, ""),
|
||||
("Visual", None, "selection", ""),
|
||||
("VisualNOS", None, "selection", ""),
|
||||
("Search", "ink", "match", ""),
|
||||
("CurSearch", "ink_inverse", "warning", "bold"),
|
||||
("IncSearch", "ink_inverse", "warning", "bold"),
|
||||
("Substitute", "ink_inverse", "danger", ""),
|
||||
("MatchParen", "accent", "surface_active", "bold"),
|
||||
("NonText", "guide", None, ""),
|
||||
("Whitespace", "guide", None, ""),
|
||||
("SpecialKey", "guide", None, ""),
|
||||
("EndOfBuffer", "bg", None, ""),
|
||||
("Conceal", "ink_faint", None, ""),
|
||||
("Directory", "accent", None, ""),
|
||||
("Title", "leaf", None, "bold"),
|
||||
("ErrorMsg", "danger", None, ""),
|
||||
("WarningMsg", "warning", None, ""),
|
||||
("MoreMsg", "accent", None, ""),
|
||||
("ModeMsg", "ink_muted", None, ""),
|
||||
("Question", "accent", None, ""),
|
||||
("MsgArea", "ink", None, ""),
|
||||
("MsgSeparator", "border", "bg", ""),
|
||||
("QuickFixLine", None, "surface_active", "bold"),
|
||||
("WildMenu", "accent_ink", "accent", ""),
|
||||
("WinBar", "ink_muted", "bg", ""),
|
||||
("WinBarNC", "ink_faint", "bg", ""),
|
||||
("Pmenu", "ink", "surface_raised", ""),
|
||||
("PmenuSel", "accent_ink", "accent", ""),
|
||||
("PmenuKind", "ink_faint", "surface_raised", ""),
|
||||
("PmenuExtra", "ink_faint", "surface_raised", ""),
|
||||
("PmenuSbar", None, "surface_hover", ""),
|
||||
("PmenuThumb", None, "border_strong", ""),
|
||||
("PmenuMatch", "accent", None, "bold"),
|
||||
("PmenuMatchSel", "accent_ink", None, "bold"),
|
||||
("StatusLine", "ink", "surface_raised", ""),
|
||||
("StatusLineNC", "ink_faint", "surface", ""),
|
||||
("TabLine", "ink_muted", "surface", ""),
|
||||
("TabLineSel", "ink", "bg", "bold"),
|
||||
("TabLineFill", None, "bg_sunken", ""),
|
||||
("SpellBad", None, None, "undercurl sp=danger"),
|
||||
("SpellCap", None, None, "undercurl sp=warning"),
|
||||
("SpellRare", None, None, "undercurl sp=accent"),
|
||||
("SpellLocal", None, None, "undercurl sp=success"),
|
||||
# --- syntax ---
|
||||
("Comment", "ink_faint", None, "italic"),
|
||||
("Constant", "warning", None, ""),
|
||||
("String", "leaf", None, ""),
|
||||
("Character", "leaf", None, ""),
|
||||
("Number", "warning", None, ""),
|
||||
("Boolean", "warning", None, ""),
|
||||
("Float", "warning", None, ""),
|
||||
("Identifier", "ink", None, ""),
|
||||
("Function", "accent_hover", None, ""),
|
||||
("Statement", "accent", None, ""),
|
||||
("Conditional", "accent", None, ""),
|
||||
("Repeat", "accent", None, ""),
|
||||
("Label", "accent", None, ""),
|
||||
("Operator", "ink_muted", None, ""),
|
||||
("Keyword", "accent", None, ""),
|
||||
("Exception", "danger", None, ""),
|
||||
("PreProc", "success", None, ""),
|
||||
("Include", "accent", None, ""),
|
||||
("Define", "success", None, ""),
|
||||
("Macro", "success", None, ""),
|
||||
("Type", "success", None, ""),
|
||||
("StorageClass", "accent", None, ""),
|
||||
("Structure", "success", None, ""),
|
||||
("Typedef", "success", None, ""),
|
||||
("Special", "accent_hover", None, ""),
|
||||
("SpecialChar", "warning", None, ""),
|
||||
("Tag", "accent", None, ""),
|
||||
("Delimiter", "ink_muted", None, ""),
|
||||
("SpecialComment", "ink_muted", None, "italic"),
|
||||
("Debug", "danger", None, ""),
|
||||
("Underlined", "accent", None, "underline"),
|
||||
("Ignore", "ink_faint", None, ""),
|
||||
("Error", "danger", None, ""),
|
||||
("Todo", "ink_inverse", "warning", "bold"),
|
||||
("Added", "leaf", None, ""),
|
||||
("Changed", "warning", None, ""),
|
||||
("Removed", "danger", None, ""),
|
||||
("DiffAdd", None, "add_bg", ""),
|
||||
("DiffChange", None, "change_bg", ""),
|
||||
("DiffDelete", "danger", "delete_bg", ""),
|
||||
("DiffText", None, "text_bg", "bold"),
|
||||
# --- Treesitter and LSP, where the default link is not the role ---
|
||||
("@variable", "ink", None, ""),
|
||||
("@variable.builtin", "danger", None, ""),
|
||||
("@variable.parameter", "ink", None, "italic"),
|
||||
("@variable.member", "ink_muted", None, ""),
|
||||
("@property", "ink_muted", None, ""),
|
||||
("@constant.builtin", "warning", None, ""),
|
||||
("@module", "ink", None, ""),
|
||||
("@constructor", "success", None, ""),
|
||||
("@punctuation", "ink_muted", None, ""),
|
||||
("@tag", "accent", None, ""),
|
||||
("@tag.attribute", "success", None, ""),
|
||||
("@tag.delimiter", "ink_faint", None, ""),
|
||||
("@markup.heading", "leaf", None, "bold"),
|
||||
("@markup.strong", None, None, "bold"),
|
||||
("@markup.italic", None, None, "italic"),
|
||||
("@markup.link", "accent", None, "underline"),
|
||||
("@markup.raw", "warning", None, ""),
|
||||
("@markup.list", "accent", None, ""),
|
||||
("@markup.quote", "ink_muted", None, "italic"),
|
||||
("LspReferenceText", None, "surface_active", ""),
|
||||
("LspReferenceRead", None, "surface_active", ""),
|
||||
("LspReferenceWrite", None, "surface_active", ""),
|
||||
("LspInlayHint", "ghost", None, "italic"),
|
||||
("LspSignatureActiveParameter", "warning", None, "bold"),
|
||||
# --- diagnostics ---
|
||||
("DiagnosticError", "danger", None, ""),
|
||||
("DiagnosticWarn", "warning", None, ""),
|
||||
("DiagnosticInfo", "accent", None, ""),
|
||||
("DiagnosticHint", "success", None, ""),
|
||||
("DiagnosticOk", "leaf", None, ""),
|
||||
("DiagnosticVirtualTextError", "danger", "danger_soft", ""),
|
||||
("DiagnosticVirtualTextWarn", "warning", "warning_soft", ""),
|
||||
("DiagnosticVirtualTextInfo", "accent", "accent_soft", ""),
|
||||
("DiagnosticVirtualTextHint", "success", "success_soft", ""),
|
||||
("DiagnosticUnderlineError", None, None, "undercurl sp=danger"),
|
||||
("DiagnosticUnderlineWarn", None, None, "undercurl sp=warning"),
|
||||
("DiagnosticUnderlineInfo", None, None, "undercurl sp=accent"),
|
||||
("DiagnosticUnderlineHint", None, None, "undercurl sp=success"),
|
||||
("DiagnosticUnnecessary", "ink_faint", None, ""),
|
||||
# --- the bars ---
|
||||
("MiniStatuslineModeNormal", "ink_inverse", "leaf", "bold"),
|
||||
("MiniStatuslineModeInsert", "accent_ink", "accent", "bold"),
|
||||
("MiniStatuslineModeVisual", "ink_inverse", "warning", "bold"),
|
||||
("MiniStatuslineModeReplace", "ink_inverse", "danger", "bold"),
|
||||
("MiniStatuslineModeCommand", "ink_inverse", "success", "bold"),
|
||||
("MiniStatuslineModeOther", "ink_inverse", "ink_muted", "bold"),
|
||||
("MiniStatuslineDevinfo", "ink_muted", "surface_active", ""),
|
||||
("MiniStatuslineFilename", "ink", "surface_raised", ""),
|
||||
("MiniStatuslineFileinfo", "ink_muted", "surface_active", ""),
|
||||
("MiniStatuslineInactive", "ink_faint", "surface", ""),
|
||||
("MiniTablineCurrent", "ink", "bg", "bold"),
|
||||
("MiniTablineVisible", "ink_muted", "surface", ""),
|
||||
("MiniTablineHidden", "ink_faint", "bg_sunken", ""),
|
||||
("MiniTablineModifiedCurrent", "warning", "bg", "bold"),
|
||||
("MiniTablineModifiedVisible", "warning", "surface", ""),
|
||||
("MiniTablineModifiedHidden", "warning", "bg_sunken", ""),
|
||||
("MiniTablineFill", None, "bg_sunken", ""),
|
||||
("MiniTablineTabpagesection", "ink_inverse", "leaf", "bold"),
|
||||
("MiniTablineTrunc", "ink_faint", "bg_sunken", ""),
|
||||
# --- pickers, explorer, hints, git ---
|
||||
("MiniPickMatchCurrent", None, "surface_active", "bold"),
|
||||
("MiniPickMatchRanges", "accent", None, "bold"),
|
||||
("MiniPickPrompt", "leaf", "surface", "bold"),
|
||||
("MiniPickBorderText", "leaf", "surface", ""),
|
||||
("MiniFilesTitleFocused", "leaf", "surface", "bold"),
|
||||
("MiniFilesDirectory", "accent", None, ""),
|
||||
("MiniFilesCursorLine", None, "surface_active", ""),
|
||||
("MiniClueNextKey", "leaf", "surface", "bold"),
|
||||
("MiniClueNextKeyWithPostkeys", "warning", "surface", "bold"),
|
||||
("MiniClueDescGroup", "accent", "surface", ""),
|
||||
("MiniClueDescSingle", "ink", "surface", ""),
|
||||
("MiniClueSeparator", "border_strong", "surface", ""),
|
||||
("MiniClueTitle", "leaf", "surface", "bold"),
|
||||
("MiniDiffSignAdd", "leaf", None, ""),
|
||||
("MiniDiffSignChange", "warning", None, ""),
|
||||
("MiniDiffSignDelete", "danger", None, ""),
|
||||
("MiniDiffOverAdd", None, "add_bg", ""),
|
||||
("MiniDiffOverChange", None, "text_bg", ""),
|
||||
("MiniDiffOverChangeBuf", None, "change_bg", ""),
|
||||
("MiniDiffOverContext", None, "change_bg", ""),
|
||||
("MiniDiffOverContextBuf", None, None, ""),
|
||||
("MiniDiffOverDelete", None, "delete_bg", ""),
|
||||
("MiniIconsAzure", "accent", None, ""),
|
||||
("MiniIconsBlue", "accent", None, ""),
|
||||
("MiniIconsCyan", "success", None, ""),
|
||||
("MiniIconsGreen", "leaf", None, ""),
|
||||
("MiniIconsGrey", "ink_muted", None, ""),
|
||||
("MiniIconsOrange", "warning", None, ""),
|
||||
("MiniIconsPurple", "accent_hover", None, ""),
|
||||
("MiniIconsRed", "danger", None, ""),
|
||||
("MiniIconsYellow", "warning", None, ""),
|
||||
("BlinkCmpMenu", "ink", "surface_raised", ""),
|
||||
("BlinkCmpMenuBorder", "border_strong", "surface_raised", ""),
|
||||
("BlinkCmpMenuSelection", "accent_ink", "accent", ""),
|
||||
("BlinkCmpLabelMatch", "accent", None, "bold"),
|
||||
("BlinkCmpKind", "ink_faint", None, ""),
|
||||
("BlinkCmpDoc", "ink", "surface", ""),
|
||||
("BlinkCmpDocBorder", "border_strong", "surface", ""),
|
||||
# --- LLeMbas: the plugin's groups, and the IDE's own ---
|
||||
("LLeMbasBrand", "leaf", None, "bold"),
|
||||
("LLeMbasUserHeader", "accent", None, "bold"),
|
||||
("LLeMbasAgentHeader", "leaf", None, "bold"),
|
||||
("LLeMbasThought", "ink_faint", None, "italic"),
|
||||
("LLeMbasToolPending", "warning", None, ""),
|
||||
("LLeMbasToolDone", "success", None, ""),
|
||||
("LLeMbasToolFail", "danger", None, ""),
|
||||
("LLeMbasToolDenied", "danger", None, "italic"),
|
||||
("LLeMbasPlanHeader", "accent", None, "bold"),
|
||||
("LLeMbasDiffAdd", None, "add_bg", ""),
|
||||
("LLeMbasDiffDelete", "danger", "delete_bg", ""),
|
||||
("LLeMbasDiffHint", "ink_faint", None, "italic"),
|
||||
("LLeMbasGhost", "ghost", None, "italic"),
|
||||
("LLeMbasSeparator", "border", None, ""),
|
||||
("LLeMbasIdeLeaf", "leaf", None, ""),
|
||||
("LLeMbasIdeSign", "accent", None, ""),
|
||||
("LLeMbasIdeTitle", "ink", None, "bold"),
|
||||
("LLeMbasIdeVersion", "ink_faint", None, ""),
|
||||
("LLeMbasIdeKey", "leaf", None, "bold"),
|
||||
("LLeMbasIdeAction", "ink", None, ""),
|
||||
("LLeMbasIdeMuted", "ink_faint", None, ""),
|
||||
("LLeMbasIdeNote", "ink_muted", None, "italic"),
|
||||
("LLeMbasIdeGood", "success", None, ""),
|
||||
("LLeMbasIdeWarn", "warning", None, ""),
|
||||
("LLeMbasIdeStatus", "leaf", "surface_raised", ""),
|
||||
("LLeMbasIdeStatusOff", "ink_faint", "surface_raised", ""),
|
||||
# --- the layout: the top and the bottom bar share one ground, so no cell stands out by it ---
|
||||
("LLeMbasBar", "ink_muted", "surface_raised", ""),
|
||||
("LLeMbasBarKey", "leaf", "surface_raised", "bold"),
|
||||
("LLeMbasBarTitle", "ink", "surface_raised", "bold"),
|
||||
("LLeMbasBarSeparator", "border_strong", "surface_raised", ""),
|
||||
("LLeMbasBarFact", "ink_faint", "surface_raised", ""),
|
||||
("LLeMbasBarIdle", "leaf", "surface_raised", ""),
|
||||
("LLeMbasBarBusy", "warning", "surface_raised", "bold"),
|
||||
("LLeMbasBarWaiting", "accent", "surface_raised", "bold"),
|
||||
("LLeMbasBarOff", "ink_faint", "surface_raised", ""),
|
||||
("LLeMbasBarVim", "ink", "surface_active", ""),
|
||||
# --- the prompt, the settings lines, the tree ---
|
||||
("LLeMbasPromptPrefix", "leaf", None, "bold"),
|
||||
("LLeMbasChip", "accent", "accent_soft", ""),
|
||||
("LLeMbasLineLabel", "ink_faint", None, ""),
|
||||
("LLeMbasLineValue", "ink", None, ""),
|
||||
("LLeMbasLineOff", "ink_faint", None, "italic"),
|
||||
("LLeMbasLineCurrent", "leaf", None, "bold"),
|
||||
("LLeMbasTreeDirectory", "accent", None, ""),
|
||||
("LLeMbasTreeCurrent", None, "surface_active", "bold"),
|
||||
("LLeMbasTreeChanged", "warning", None, ""),
|
||||
("LLeMbasTreeAdded", "success", None, ""),
|
||||
("LLeMbasTreeNew", "leaf", None, ""),
|
||||
("LLeMbasTreeDeleted", "danger", None, ""),
|
||||
("LLeMbasTreeConflict", "danger", None, "bold"),
|
||||
]
|
||||
|
||||
# The terminal's sixteen colours, by palette name.
|
||||
TERMINAL = [
|
||||
"bg_sunken", "danger", "leaf", "warning", "accent", "accent_hover", "success", "ink_muted",
|
||||
"border_strong", "danger", "leaf_hover", "warning", "accent_hover", "accent_hover", "success", "ink",
|
||||
]
|
||||
|
||||
|
||||
def render(themes: dict) -> str:
|
||||
palettes = {}
|
||||
for background, name in THEMES.items():
|
||||
if name not in themes:
|
||||
raise ValueError(f'the tokens file has no data-theme="{name}" block')
|
||||
palettes[background] = palette(themes[name])
|
||||
keys = sorted(palettes["dark"])
|
||||
for _, fg, bg, attrs in GROUPS:
|
||||
for used in [fg, bg] + re.findall(r"sp=(\w+)", attrs):
|
||||
if used is not None and used not in keys:
|
||||
raise ValueError(f"a group names the colour {used}, which the palette lacks")
|
||||
out = [
|
||||
"-- LLeMbas: the colourscheme of LLeMbas IDE. moria when 'background' is dark, shire when light.",
|
||||
"-- GENERATED by scripts/gen-ide-theme.py from the design tokens. Do not edit: change the tokens",
|
||||
"-- or the generator, and run it again. Your own colours belong in lua/user/init.lua.",
|
||||
"local palettes = {",
|
||||
]
|
||||
for background in ("dark", "light"):
|
||||
out.append(f" {background} = {{ -- {THEMES[background]}")
|
||||
for key in keys:
|
||||
out.append(f' {key} = "{palettes[background][key]}",')
|
||||
out.append(" },")
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
"local groups = {",
|
||||
]
|
||||
for name, fg, bg, attrs in GROUPS:
|
||||
parts = []
|
||||
if fg:
|
||||
parts.append(f'fg = "{fg}"')
|
||||
if bg:
|
||||
parts.append(f'bg = "{bg}"')
|
||||
for attr in attrs.split():
|
||||
if attr.startswith("sp="):
|
||||
parts.append(f'sp = "{attr[3:]}"')
|
||||
else:
|
||||
parts.append(f"{attr} = true")
|
||||
out.append(f' ["{name}"] = {{ {", ".join(parts)} }},')
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
"local terminal = { " + ", ".join(f'"{name}"' for name in TERMINAL) + " }",
|
||||
"",
|
||||
'if vim.g.colors_name then vim.cmd("highlight clear") end',
|
||||
'vim.g.colors_name = "llembas"',
|
||||
'local p = palettes[vim.o.background == "light" and "light" or "dark"]',
|
||||
"for name, spec in pairs(groups) do",
|
||||
" local hl = {}",
|
||||
" for key, value in pairs(spec) do",
|
||||
' if key == "fg" or key == "bg" or key == "sp" then hl[key] = p[value] else hl[key] = value end',
|
||||
" end",
|
||||
" vim.api.nvim_set_hl(0, name, hl)",
|
||||
"end",
|
||||
'for i, name in ipairs(terminal) do vim.g["terminal_color_" .. (i - 1)] = p[name] end',
|
||||
"",
|
||||
"-- For the configuration: the palette in use, by token name.",
|
||||
"return p",
|
||||
"",
|
||||
]
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
||||
ap.add_argument("--tokens", type=Path, default=ROOT / "ide" / "tokens.css")
|
||||
ap.add_argument("--out", type=Path, default=ROOT / "ide" / "config" / "colors" / "llembas.lua")
|
||||
ap.add_argument("--check", action="store_true", help="write nothing; fail when the file is stale")
|
||||
args = ap.parse_args()
|
||||
try:
|
||||
text = render(parse(args.tokens.read_text(encoding="utf-8")))
|
||||
except (OSError, ValueError) as err:
|
||||
print(f"gen-ide-theme: {err}", file=sys.stderr)
|
||||
return 2
|
||||
if args.check:
|
||||
current = args.out.read_text(encoding="utf-8") if args.out.exists() else ""
|
||||
if current != text:
|
||||
print(f"gen-ide-theme: {args.out} is not what {args.tokens} gives; run scripts/gen-ide-theme.py", file=sys.stderr)
|
||||
return 1
|
||||
print(f"gen-ide-theme: {args.out.name} matches the tokens")
|
||||
return 0
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.out.write_text(text, encoding="utf-8")
|
||||
print(f"gen-ide-theme: wrote {args.out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+12
-1
@@ -18,9 +18,20 @@ patterns=(
|
||||
'\bgamebox\b'
|
||||
'\bthor\b'
|
||||
)
|
||||
# What is allowed to match, each for a reason — a line of `file:line:text` as grep prints it:
|
||||
allowed=(
|
||||
# The public forge the releases are made on: the workflow that republishes them must name it.
|
||||
'^\.github/workflows/release\.yml:[0-9]+:.*git\.houmeres\.sk'
|
||||
)
|
||||
allow="$(IFS='|'; echo "${allowed[*]}")"
|
||||
|
||||
found=0
|
||||
for pattern in "${patterns[@]}"; do
|
||||
if git ls-files -z | grep -zv '^scripts/hygiene.sh$' | xargs -0 grep -nIEi -- "$pattern" ; then
|
||||
# The output decides, not the exit status: xargs answers 123 when any one batch of files has no
|
||||
# match, and grep 2 on an error -- either would have read as "clean" around real matches.
|
||||
hits=$(git ls-files -z | grep -zv '^scripts/hygiene.sh$' | xargs -0 grep -nIEi -- "$pattern" 2>/dev/null | grep -vE -- "$allow" || true)
|
||||
if [ -n "$hits" ]; then
|
||||
printf '%s\n' "$hits"
|
||||
echo "hygiene: the lines above match /$pattern/" >&2
|
||||
found=1
|
||||
fi
|
||||
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env bash
|
||||
# What a release of LLeMbas IDE carries, written into dist/:
|
||||
# llembas-ide-<version>.tar.gz ide/ (the installer, the configuration, the lock files) and
|
||||
# nvim/ (the LLeMbas plugin), with VERSION and LICENSE
|
||||
# install.sh the installer, for: curl -fsSL <release>/install.sh | bash
|
||||
# SHA256SUMS of every release file in dist/ (the .vsix too, when it is there)
|
||||
# SHA256SUMS.sig with --sign <key file>: signed with ssh-keygen in the namespace
|
||||
# lembas-release, which install.sh checks once it is given the key
|
||||
#
|
||||
# scripts/package-ide.sh [--sign <ssh private key>]
|
||||
#
|
||||
# The archive is made from the files git tracks, in a fixed order with fixed times and owners, so
|
||||
# the same commit gives the same bytes. The version is the repository's VERSION file.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
sign=""
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--sign) sign="${2:?--sign needs a key file}" && shift ;;
|
||||
*) echo "package-ide: unknown option $1" >&2 && exit 2 ;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
version="$(tr -d '[:space:]' <VERSION)"
|
||||
name="llembas-ide-$version"
|
||||
python3 scripts/gen-ide-theme.py --check
|
||||
mkdir -p dist
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
mkdir "$work/$name"
|
||||
git ls-files -z -- VERSION LICENSE ide nvim | grep -zv -E '^(ide|nvim)/tests/' |
|
||||
while IFS= read -r -d '' f; do
|
||||
mkdir -p "$work/$name/$(dirname "$f")"
|
||||
cp -p "$f" "$work/$name/$f"
|
||||
done
|
||||
chmod 755 "$work/$name/ide/install.sh" "$work/$name/ide/bin/llembas-ide"
|
||||
stamp="$(git log -1 --format=%ct)"
|
||||
tar -C "$work" --sort=name --mtime="@$stamp" --owner=0 --group=0 --numeric-owner -cf - "$name" | gzip -n -9 >"dist/$name.tar.gz"
|
||||
cp ide/install.sh dist/install.sh
|
||||
|
||||
(
|
||||
cd dist
|
||||
files=("$name.tar.gz" install.sh)
|
||||
[ ! -f "llembas-$version.vsix" ] || files+=("llembas-$version.vsix")
|
||||
sha256sum "${files[@]}" >SHA256SUMS
|
||||
)
|
||||
rm -f dist/SHA256SUMS.sig
|
||||
if [ -n "$sign" ]; then
|
||||
ssh-keygen -Y sign -q -f "$sign" -n lembas-release dist/SHA256SUMS
|
||||
fi
|
||||
echo "package-ide: dist/$name.tar.gz, dist/install.sh, dist/SHA256SUMS$([ -z "$sign" ] || echo ", dist/SHA256SUMS.sig")"
|
||||
Executable
+554
@@ -0,0 +1,554 @@
|
||||
#!/usr/bin/env bash
|
||||
# The tests of the LLeMbas IDE distribution (ide/): the scripts, a dry run, real installs into
|
||||
# temporary homes, a headless start checked from the inside, updating in place, failing without
|
||||
# leaving anything half-done, and uninstalling.
|
||||
#
|
||||
# scripts/test-ide.sh everything: also downloads the pinned Neovim (about 12 MB, its
|
||||
# SHA-256 checked) and compiles the Treesitter grammars, twice
|
||||
# scripts/test-ide.sh --quick no download and no compiling: the Neovim on this machine and
|
||||
# its bundled grammars only
|
||||
# scripts/test-ide.sh --update-readme rewrite the key table in ide/README.md from the key map
|
||||
#
|
||||
# Needs bash, git, curl, tar, shellcheck, python3 and a Neovim 0.10 or newer on PATH (or in
|
||||
# IDE_TEST_NVIM): the oldest supported one is what the installed IDE is also run on.
|
||||
# The plugins are fetched from GitHub at their pinned commits; LLEMBAS_IDE_GIT_MIRROR (a
|
||||
# directory of clones) spares the network. Nothing is written outside a temporary directory,
|
||||
# which is removed on every way out.
|
||||
# shellcheck disable=SC2016 # the small scripts given to bash -c are single-quoted on purpose
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
REPO="$PWD"
|
||||
|
||||
QUICK=0
|
||||
case "${1:-}" in
|
||||
--quick) QUICK=1 ;;
|
||||
--update-readme)
|
||||
# LLeMbas's own rows are read from the plugin's key table, so the plugin is on the path too.
|
||||
nvim --headless -u NONE --cmd "set rtp+=ide/config" --cmd "set rtp+=nvim" \
|
||||
-c 'lua io.stdout:write(table.concat(require("llembas_ide.keys").markdown(), "\n"))' -c q >ide/README.keys.tmp
|
||||
python3 - <<'PY'
|
||||
import re
|
||||
from pathlib import Path
|
||||
keys = Path("ide/README.keys.tmp").read_text(encoding="utf-8").strip()
|
||||
readme = Path("ide/README.md")
|
||||
text = readme.read_text(encoding="utf-8")
|
||||
text = re.sub(r"<!-- keys:begin -->\n.*?<!-- keys:end -->", lambda _: "<!-- keys:begin -->\n" + keys + "\n<!-- keys:end -->", text, flags=re.S)
|
||||
readme.write_text(text, encoding="utf-8")
|
||||
PY
|
||||
rm -f ide/README.keys.tmp
|
||||
echo "test-ide: ide/README.md has the key map's table"
|
||||
exit 0
|
||||
;;
|
||||
"") ;;
|
||||
*) echo "test-ide: unknown option $1" >&2 && exit 2 ;;
|
||||
esac
|
||||
|
||||
SYSTEM_NVIM="${IDE_TEST_NVIM:-$(command -v nvim || true)}"
|
||||
[ -n "$SYSTEM_NVIM" ] || { echo "test-ide: needs a Neovim on PATH (or IDE_TEST_NVIM)" >&2 && exit 2; }
|
||||
VERSION="$(tr -d '[:space:]' <VERSION)"
|
||||
WORK="$(mktemp -d "${TMPDIR:-/tmp}/llembas-ide-test.XXXXXX")"
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
|
||||
PASSED=0
|
||||
FAILED=0
|
||||
ok() {
|
||||
PASSED=$((PASSED + 1))
|
||||
printf ' ok %s\n' "$1"
|
||||
}
|
||||
fail() {
|
||||
FAILED=$((FAILED + 1))
|
||||
printf ' FAIL %s\n' "$1"
|
||||
[ -z "${2:-}" ] || printf '%s\n' "$2" | sed 's/^/ /' | tail -n 15
|
||||
}
|
||||
# check "name" command… passes when the command does
|
||||
check() {
|
||||
local name="$1" out
|
||||
shift
|
||||
if out="$("$@" 2>&1)"; then ok "$name"; else fail "$name" "$out"; fi
|
||||
}
|
||||
# attempt command… runs it; its output is in OUT and its exit status in RC
|
||||
OUT=""
|
||||
RC=0
|
||||
attempt() {
|
||||
if OUT="$("$@" 2>&1)"; then RC=0; else RC=$?; fi
|
||||
}
|
||||
passes() { if [ "$RC" = 0 ]; then ok "$1"; else fail "$1" "$OUT"; fi; }
|
||||
refuses() { if [ "$RC" != 0 ]; then ok "$1"; else fail "$1" "$OUT"; fi; }
|
||||
has() { grep -q -F -- "$2" <<<"$1"; }
|
||||
expect() { # expect "name" "text" "needle"
|
||||
if has "$2" "$3"; then ok "$1"; else fail "$1" "wanted: $3
|
||||
$2"; fi
|
||||
}
|
||||
|
||||
# PATH without any LLeMbas CLI of this machine: the tests decide whether there is one.
|
||||
CLEAN_PATH=""
|
||||
IFS=: read -r -a parts <<<"$PATH"
|
||||
for d in "${parts[@]}"; do
|
||||
if [ -n "$d" ] && [ ! -x "$d/lembas" ]; then CLEAN_PATH="${CLEAN_PATH:+$CLEAN_PATH:}$d"; fi
|
||||
done
|
||||
BG_DARK="$(sed -n '/data-theme="moria"/,/}/s/^ *--bg: *\(#[0-9A-Fa-f]*\);.*/\1/p' ide/tokens.css)"
|
||||
BG_LIGHT="$(sed -n '/data-theme="shire"/,/}/s/^ *--bg: *\(#[0-9A-Fa-f]*\);.*/\1/p' ide/tokens.css)"
|
||||
|
||||
# Run something as a person whose home is $1, with nothing of this machine's environment.
|
||||
as() {
|
||||
local home="$1"
|
||||
shift
|
||||
env -i PATH="$home/.local/bin:${EXTRA_PATH:+$EXTRA_PATH:}$CLEAN_PATH" HOME="$home" TERM=dumb LANG=C.UTF-8 LLEMBAS_IDE_PUBKEY= \
|
||||
${LLEMBAS_IDE_GIT_MIRROR:+LLEMBAS_IDE_GIT_MIRROR="$LLEMBAS_IDE_GIT_MIRROR"} "$@"
|
||||
}
|
||||
installer() { # installer <home> <options…>
|
||||
local home="$1"
|
||||
shift
|
||||
as "$home" bash "$REPO/ide/install.sh" --no-cli "$@" 2>&1
|
||||
}
|
||||
# The headless checks, through the launcher. headless <home> <parsers 0|1> [VAR=value…]
|
||||
headless() {
|
||||
local home="$1" parsers="$2"
|
||||
shift 2
|
||||
(cd "$WORK" && as "$home" env IDE_TEST_REPO="$REPO" IDE_TEST_PARSERS="$parsers" IDE_TEST_BG_DARK="$BG_DARK" \
|
||||
IDE_TEST_BG_LIGHT="$BG_LIGHT" "$@" timeout 120 "$home/.local/bin/llembas-ide" --headless \
|
||||
-c "luafile $REPO/ide/tests/headless.lua" 2>&1)
|
||||
}
|
||||
typing() { # the completion menu, through the launcher
|
||||
local home="$1" out
|
||||
out="$( (cd "$WORK" && as "$home" timeout 60 "$home/.local/bin/llembas-ide" --headless -c "luafile $REPO/ide/tests/typing.lua" 2>&1) || true)"
|
||||
if grep -q -F 'ide-typing: the menu opens' <<<"$out"; then ok "$2"; else fail "$2" "$out"; fi
|
||||
}
|
||||
# The four bars, on the installed IDE's own screen. layout <home> "name"
|
||||
layout() {
|
||||
local home="$1" out line
|
||||
out="$( (cd "$WORK" && as "$home" env IDE_TEST_REPO="$REPO" timeout 420 "$home/.local/bin/llembas-ide" --headless \
|
||||
-c "luafile $REPO/ide/tests/layout.lua" 2>&1) || true)"
|
||||
line="$(grep -o -E 'ide-layout: [0-9]+ passed, 0 failed.*' <<<"$out" || true)"
|
||||
if [ -n "$line" ]; then ok "$2: ${line#ide-layout: }"; else fail "$2" "$(grep -E '^(FAIL|ide-layout:)' <<<"$out" | cut -c1-600 || true)
|
||||
$(tail -n 5 <<<"$out" | cut -c1-300)"; fi
|
||||
}
|
||||
report_headless() { # report_headless "name" "output"
|
||||
local line
|
||||
line="$(grep -o -E 'ide-headless: [0-9]+ passed, 0 failed.*' <<<"$2" || true)"
|
||||
if [ -n "$line" ]; then ok "$1: ${line#ide-headless: }"; else fail "$1" "$(cut -c1-600 <<<"$2")"; fi
|
||||
}
|
||||
startup_ms() { # the best of three starts, in milliseconds
|
||||
local home="$1" best="" ms i
|
||||
for i in 1 2 3; do
|
||||
rm -f "$WORK/startup.$i"
|
||||
as "$home" "$home/.local/bin/llembas-ide" --headless --startuptime "$WORK/startup.$i" -c 'qa!' >/dev/null 2>&1 || true
|
||||
ms="$(grep -F 'NVIM STARTED' "$WORK/startup.$i" 2>/dev/null | tail -n1 | awk '{ print $1 + 0 }')"
|
||||
if [ -n "$ms" ] && { [ -z "$best" ] || awk -v a="$ms" -v b="$best" 'BEGIN { exit !(a < b) }'; }; then best="$ms"; fi
|
||||
done
|
||||
echo "${best:-?}"
|
||||
}
|
||||
files_in() { (cd "$1" && find . -type f -o -type l | sort); }
|
||||
# A copy of what a release carries, to break on purpose.
|
||||
payload_copy() {
|
||||
local to="$1"
|
||||
mkdir -p "$to"
|
||||
git ls-files -z -- VERSION LICENSE ide nvim | while IFS= read -r -d '' f; do
|
||||
mkdir -p "$to/$(dirname "$f")"
|
||||
cp -p "$f" "$to/$f"
|
||||
done
|
||||
}
|
||||
|
||||
# --- 1. the files themselves -------------------------------------------------------------------
|
||||
echo "The scripts and the pins"
|
||||
check "shellcheck: install.sh, the launcher, the packaging and test scripts" \
|
||||
shellcheck ide/install.sh ide/bin/llembas-ide scripts/package-ide.sh scripts/test-ide.sh
|
||||
check "the colourscheme is what the tokens give" python3 scripts/gen-ide-theme.py --check
|
||||
check "install.sh runs nothing until its last line" bash -c '[ "$(tail -n1 ide/install.sh)" = "main \"\$@\"" ]'
|
||||
check "no sudo anywhere in the scripts" bash -c '! grep -n -w sudo ide/install.sh ide/bin/llembas-ide'
|
||||
check "no colour is written outside the generated theme" \
|
||||
bash -c '! grep -rn -E "#[0-9A-Fa-f]{6}\b" ide/config/init.lua ide/config/lua'
|
||||
check "every plugin is pinned to a full commit over https, under MIT, Apache-2.0, BSD or ISC" \
|
||||
bash -c 'grep -v -E "^\s*(#|$)" ide/plugins.lock | awk "{ if (\$3 !~ /^https:\/\/github\.com\// || \$4 !~ /^[0-9a-f]{40}\$/ || \$5 !~ /^(MIT|Apache-2\.0|BSD-[23]-Clause|ISC)\$/) { print; bad = 1 } } END { exit bad }"'
|
||||
check "every grammar is pinned to a full commit over https, under MIT, Apache-2.0, BSD or ISC" \
|
||||
bash -c 'grep -v -E "^\s*(#|$)" ide/parsers.lock | awk "{ if (\$2 !~ /^https:\/\/github\.com\// || \$3 !~ /^[0-9a-f]{40}\$/ || \$5 !~ /^(MIT|Apache-2\.0|BSD-[23]-Clause|ISC)\$/) { print; bad = 1 } } END { exit bad }"'
|
||||
check "THIRD_PARTY.md names every pinned commit" \
|
||||
bash -c 'for c in $(grep -v -E "^\s*(#|$)" ide/plugins.lock | awk "{ print \$4 }") $(grep -v -E "^\s*(#|$)" ide/parsers.lock | awk "{ print \$3 }"); do grep -q "$c" ide/THIRD_PARTY.md || { echo "missing $c"; exit 1; }; done'
|
||||
check "Neovim is pinned with a SHA-256 for each of the four platforms" \
|
||||
bash -c '[ "$(grep -c -E "^[0-9a-f]{64} nvim-(linux|macos)-(x86_64|arm64)\.tar\.gz$" ide/neovim.sha256)" = 4 ] && grep -q -E "^[0-9]+\.[0-9]+\.[0-9]+$" ide/neovim.version'
|
||||
check "nothing private in the tracked files" scripts/hygiene.sh
|
||||
check "the Lua of the configuration parses" \
|
||||
bash -c 'for f in ide/config/init.lua ide/config/colors/llembas.lua ide/config/lua/llembas_ide/*.lua ide/user-init.lua ide/tests/headless.lua ide/tests/layout.lua ide/tests/typing.lua; do "$0" --headless -u NONE -c "lua local f, e = loadfile([[$f]]); if not f then io.stdout:write(e) vim.cmd([[cquit 1]]) end" -c q || exit 1; done' "$SYSTEM_NVIM"
|
||||
|
||||
# --- 2. a dry run ------------------------------------------------------------------------------
|
||||
echo "A dry run"
|
||||
A="$WORK/a"
|
||||
mkdir -p "$A"
|
||||
out="$(installer "$A" --from-checkout --dry-run || true)"
|
||||
expect "says it is a dry run" "$out" "dry run: nothing is downloaded or written"
|
||||
case "$(uname -s)-$(uname -m)" in
|
||||
Linux-x86_64) ASSET=nvim-linux-x86_64 ;;
|
||||
Linux-aarch64 | Linux-arm64) ASSET=nvim-linux-arm64 ;;
|
||||
Darwin-arm64) ASSET=nvim-macos-arm64 ;;
|
||||
*) ASSET=nvim-macos-x86_64 ;;
|
||||
esac
|
||||
expect "names the pinned Neovim's address" "$out" "download https://github.com/neovim/neovim/releases/download/v$(cat ide/neovim.version)/$ASSET.tar.gz"
|
||||
expect "and its checksum" "$out" "check its SHA-256 is $(awk -v f="$ASSET.tar.gz" '$2 == f { print $1 }' ide/neovim.sha256)"
|
||||
while read -r name _ url commit _; do
|
||||
expect "names $name, its source and its commit" "$out" "fetch $name from $url at commit $commit"
|
||||
done < <(grep -v -E '^\s*(#|$)' ide/plugins.lock)
|
||||
expect "names the staging and the swap" "$out" "would swap the staged nvim/, site/pack/llembas/ and lib/ into $A/.local/share/llembas-ide"
|
||||
expect "names the launcher" "$out" "would write the launcher $A/.local/bin/llembas-ide"
|
||||
expect "names the person's own file" "$out" "would create $A/.config/llembas-ide/lua/user/init.lua"
|
||||
expect "names the menu entry" "$out" "would write the menu entry $A/.local/share/applications/llembas-ide.desktop"
|
||||
if [ -z "$(find "$A" -mindepth 1 | head -n1)" ]; then ok "writes nothing"; else fail "writes nothing" "$(find "$A" -mindepth 1 | head)"; fi
|
||||
out="$(as "$A" bash "$REPO/ide/install.sh" --from-checkout --dry-run 2>&1 || true)"
|
||||
expect "with the CLI missing, offers the CLI's own installer" "$out" "offer to install the LLeMbas CLI (beta): its own installer (get.sh)"
|
||||
out="$(as "$A" bash "$REPO/ide/install.sh" --dry-run --version 9.9.9 2>&1 || true)"
|
||||
expect "from a release: names the archive and the checksum check" "$out" "releases/download/v9.9.9/llembas-ide-9.9.9.tar.gz"
|
||||
out="$(installer "$A" --from-checkout --prefix relative/dir 2>&1 || true)"
|
||||
expect "a relative --prefix is refused in words" "$out" "--prefix must be an absolute path"
|
||||
out="$(installer "$A" --from-checkout --nvim-bin /bin/true 2>&1 || true)"
|
||||
expect "a --nvim-bin that is not Neovim 0.10 or newer is refused in words" "$out" "older than Neovim 0.10"
|
||||
out="$(as "$A" bash -c 'cat "$1" | bash -s -- --from-checkout' _ "$REPO/ide/install.sh" 2>&1 || true)"
|
||||
expect "piped into bash, --from-checkout is refused in words" "$out" "--from-checkout needs this script run as a file"
|
||||
if [ -z "$(find "$A" -mindepth 1 | head -n1)" ]; then ok "refusals write nothing"; else fail "refusals write nothing" "$(find "$A" -mindepth 1 | head)"; fi
|
||||
# The help, also when the script comes down a pipe and there is no file to read it from.
|
||||
attempt as "$A" bash -c 'cat "$1" | bash -s -- --help' _ "$REPO/ide/install.sh"
|
||||
passes "piped into bash, --help ends well"
|
||||
expect "…and prints the options" "$OUT" "--channel NAME stable (default) or beta"
|
||||
expect "…and what the script needs, ssh-keygen with it" "$OUT" "ssh-keygen (openssh-client"
|
||||
if [ "$(as "$A" bash "$REPO/ide/install.sh" --help 2>&1)" = "$OUT" ]; then ok "the same help as from the file"; else fail "the same help as from the file"; fi
|
||||
if [ -z "$(find "$A" -mindepth 1 | head -n1)" ]; then ok "the help writes nothing"; else fail "the help writes nothing" "$(find "$A" -mindepth 1 | head)"; fi
|
||||
|
||||
# --- 3. a real install, with the Neovim of this machine and its bundled grammars ---------------
|
||||
echo "A real install (the Neovim on this machine: $("$SYSTEM_NVIM" --version | head -n1), bundled grammars)"
|
||||
attempt installer "$A" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers
|
||||
out="$OUT"
|
||||
passes "installs"
|
||||
expect "says so" "$out" "LLeMbas IDE $VERSION is installed"
|
||||
P="$A/.local/share/llembas-ide"
|
||||
check "the launcher, the configuration, the person's file, the menu entry and the icon are there" \
|
||||
test -x "$A/.local/bin/llembas-ide" -a -f "$A/.config/llembas-ide/init.lua" -a -f "$A/.config/llembas-ide/lua/user/init.lua" \
|
||||
-a -f "$A/.local/share/applications/llembas-ide.desktop" -a -f "$A/.local/share/icons/hicolor/256x256/apps/llembas-ide.png"
|
||||
check "the menu entry is a terminal application with the IDE's name" \
|
||||
bash -c 'grep -q "^Terminal=true$" "$1" && grep -q "^Name=LLeMbas IDE$" "$1" && grep -q "^Icon=llembas-ide$" "$1"' _ "$A/.local/share/applications/llembas-ide.desktop"
|
||||
stray="$(files_in "$A" | grep -v -E '^\./(\.local/share/llembas-ide/|\.config/llembas-ide/|\.local/bin/llembas-ide$|\.local/share/applications/llembas-ide\.desktop$|\.local/share/icons/hicolor/256x256/apps/llembas-ide\.png$|\.local/state/llembas-ide/|\.cache/llembas-ide/)' || true)"
|
||||
if [ -z "$stray" ]; then ok "nothing is written outside the IDE's own places"; else fail "nothing is written outside the IDE's own places" "$stray"; fi
|
||||
check "no ~/.config/nvim is made" test ! -e "$A/.config/nvim"
|
||||
if [ -z "$(find "$P" -maxdepth 1 \( -name '.staging.*' -o -name '.old.*' \) | head -n1)" ]; then ok "no staging directory is left"; else fail "no staging directory is left"; fi
|
||||
out="$(as "$A" "$A/.local/bin/llembas-ide" --version 2>&1 || true)"
|
||||
expect "--version: the IDE" "$out" "LLeMbas IDE $VERSION"
|
||||
expect "--version: Neovim" "$out" "Neovim $("$SYSTEM_NVIM" --version | sed -n '1s/^NVIM v//p')"
|
||||
expect "--version: the plugin" "$out" "LLeMbas plugin $VERSION"
|
||||
report_headless "headless start, from the inside" "$(headless "$A" 0 IDE_TEST_FIRST=1 || true)"
|
||||
typing "$A" "typing: the completion menu opens with the buffer's words, and <Tab> stays LLeMbas's"
|
||||
layout "$A" "the four bars at 160×45, 100×30 and 80×24, the keys, what is remembered, the terminal's user var"
|
||||
check "the plugin alone, in a Neovim without the distribution, loads and has no bars unless asked" \
|
||||
bash -c 'cd "$1" && env -i PATH="$PATH" HOME="$2" XDG_STATE_HOME="$2/plain-state" TERM=dumb "$3" --headless -u NONE -i NONE --cmd "set rtp+=nvim" \
|
||||
-c "runtime plugin/llembas.lua" \
|
||||
-c "lua require([[llembas]]).setup({}); assert(vim.o.tabline == [[]] and vim.fn.maparg([[<C-S-A>]], [[n]]) == [[]] and #vim.api.nvim_list_wins() == 1); require([[llembas]]).setup({ bars = true }); assert(vim.o.tabline:find([[llembas.layout]], 1, true) and vim.fn.maparg([[<C-S-A>]], [[n]], false, true).desc)" \
|
||||
-c "qa!" 2>&1 | { ! grep -q .; }' _ "$REPO" "$WORK" "$SYSTEM_NVIM"
|
||||
attempt as "$A" "$A/.local/bin/llembas-ide" doctor
|
||||
out="$OUT"
|
||||
passes "doctor finds the installation sound"
|
||||
expect "doctor: plugins at their pins" "$out" "ok mini.nvim $(awk '$1 == "mini.nvim" { print substr($4, 1, 12) }' ide/plugins.lock)"
|
||||
expect "doctor: says what is off without compiled grammars" "$out" "Treesitter grammars are not compiled"
|
||||
expect "doctor: says the CLI is missing and the editor works" "$out" "the LLeMbas CLI (lembas) is not installed"
|
||||
expect "doctor: a clean headless start" "$out" "every part of the IDE loads"
|
||||
START_A="$(startup_ms "$A")"
|
||||
ok "startup, best of three: ${START_A} ms"
|
||||
out="$(as "$A" "$A/.local/bin/llembas-ide" --headless -c 'lua io.stdout:write(vim.env.NVIM_APPNAME .. " " .. vim.fn.argv(0))' -c 'qa!' some-file.txt 2>&1 || true)"
|
||||
expect "arguments go through to Neovim" "$out" "llembas-ide some-file.txt"
|
||||
|
||||
# --- 4. again: an update in place --------------------------------------------------------------
|
||||
echo "Installing again"
|
||||
echo 'vim.g.llembas_ide_test_user = 42' >>"$A/.config/llembas-ide/lua/user/init.lua"
|
||||
# A plugin of the person's own, in the directory the README names.
|
||||
mkdir -p "$A/.config/llembas-ide/pack/user/start/mine/plugin"
|
||||
echo 'vim.g.llembas_ide_test_plugin = "loaded"' >"$A/.config/llembas-ide/pack/user/start/mine/plugin/mine.lua"
|
||||
user_before="$(sha256sum "$A/.config/llembas-ide/lua/user/init.lua")"
|
||||
attempt installer "$A" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers
|
||||
out="$OUT"
|
||||
passes "installs over itself"
|
||||
if [ "$(grep -c 'already installed, unchanged' <<<"$out")" = "$(grep -c -v -E '^\s*(#|$)' ide/plugins.lock)" ]; then ok "keeps every plugin that is at its pin"; else fail "keeps every plugin that is at its pin" "$out"; fi
|
||||
expect "keeps the person's own file" "$out" "keep your $A/.config/llembas-ide/lua/user/init.lua as it is"
|
||||
if [ "$(sha256sum "$A/.config/llembas-ide/lua/user/init.lua")" = "$user_before" ]; then ok "the person's own file is byte for byte the same"; else fail "the person's own file is byte for byte the same"; fi
|
||||
report_headless "headless start again, with the person's file saying something" "$(headless "$A" 0 IDE_TEST_USER=1 || true)"
|
||||
echo '-- mine' >>"$A/.config/llembas-ide/init.lua"
|
||||
out="$(installer "$A" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers || true)"
|
||||
expect "an init.lua the person edited is kept" "$out" "keep your edited $A/.config/llembas-ide/init.lua"
|
||||
check "and the IDE's own lies beside it" bash -c 'grep -q "^-- mine$" "$1/init.lua" && cmp -s "$1/init.lua.new" ide/config/init.lua' _ "$A/.config/llembas-ide"
|
||||
cp ide/config/init.lua "$A/.config/llembas-ide/init.lua"
|
||||
rm -f "$A/.config/llembas-ide/init.lua.new"
|
||||
# A plugin somebody changed is fetched again, not trusted.
|
||||
echo '-- changed' >>"$P/site/pack/llembas/start/conform.nvim/lua/conform/init.lua"
|
||||
out="$(as "$A" "$A/.local/bin/llembas-ide" doctor 2>&1 || true)"
|
||||
expect "doctor: a plugin whose files were changed is a failure" "$out" "FAIL conform.nvim is at its pin but its files were changed"
|
||||
out="$(installer "$A" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers || true)"
|
||||
expect "the installer fetches that plugin again" "$out" "fetch conform.nvim from"
|
||||
check "and doctor is content" as "$A" "$A/.local/bin/llembas-ide" doctor
|
||||
# A file somebody added is loaded by Neovim like any other: it is a change too.
|
||||
echo 'vim.g.llembas_ide_test_added = true' >"$P/site/pack/llembas/start/conform.nvim/plugin/added.lua"
|
||||
out="$(as "$A" "$A/.local/bin/llembas-ide" doctor 2>&1 || true)"
|
||||
expect "doctor: a plugin with a file added to it is a failure" "$out" "FAIL conform.nvim is at its pin but its files were changed or added to"
|
||||
expect "doctor: and says how many checks failed, in words" "$out" "1 check failed. llembas-ide update installs it again."
|
||||
out="$(installer "$A" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers || true)"
|
||||
expect "the installer fetches that plugin again too" "$out" "fetch conform.nvim from"
|
||||
check "and the added file is gone" test ! -e "$P/site/pack/llembas/start/conform.nvim/plugin/added.lua"
|
||||
check "and doctor is content again" as "$A" "$A/.local/bin/llembas-ide" doctor
|
||||
|
||||
# --- 5. failing without leaving anything half-done ----------------------------------------------
|
||||
echo "Failures"
|
||||
before="$(files_in "$A" | grep -v -E '/(\.local/state|\.cache)/' | sha256sum)"
|
||||
payload_copy "$WORK/broken"
|
||||
echo 'error("broken on purpose")' >>"$WORK/broken/ide/config/lua/llembas_ide/options.lua"
|
||||
attempt as "$A" bash "$WORK/broken/ide/install.sh" --no-cli --from-dir "$WORK/broken" --nvim-bin "$SYSTEM_NVIM" --no-parsers
|
||||
out="$OUT"
|
||||
refuses "a configuration that does not start is refused"
|
||||
expect "in words" "$out" "the staged IDE did not start"
|
||||
expect "and says nothing was installed" "$out" "nothing installed"
|
||||
payload_copy "$WORK/wrongpin"
|
||||
sed -i -E 's/^(conform\.nvim .*)[0-9a-f]{6}( +MIT)/\1000000\2/' "$WORK/wrongpin/ide/plugins.lock"
|
||||
attempt as "$A" bash "$WORK/wrongpin/ide/install.sh" --no-cli --from-dir "$WORK/wrongpin" --nvim-bin "$SYSTEM_NVIM" --no-parsers
|
||||
out="$OUT"
|
||||
refuses "a commit that cannot be fetched stops the install"
|
||||
expect "in words" "$out" "could not fetch https://github.com/stevearc/conform.nvim at"
|
||||
if [ "$(files_in "$A" | grep -v -E '/(\.local/state|\.cache)/' | sha256sum)" = "$before" ]; then ok "after both, the installation has exactly the files it had"; else fail "after both, the installation has exactly the files it had"; fi
|
||||
if [ -z "$(find "$P" -maxdepth 1 \( -name '.staging.*' -o -name '.old.*' \) | head -n1)" ]; then ok "and no staging directory is left"; else fail "and no staging directory is left"; fi
|
||||
check "and it still starts" as "$A" "$A/.local/bin/llembas-ide" doctor
|
||||
E="$WORK/empty"
|
||||
mkdir -p "$E"
|
||||
out="$(as "$E" bash "$WORK/broken/ide/install.sh" --no-cli --from-dir "$WORK/broken" --nvim-bin "$SYSTEM_NVIM" --no-parsers 2>&1 || true)"
|
||||
left="$(files_in "$E")$(cd "$E" && find . -mindepth 1 -type d -name '*llembas*')"
|
||||
if [ -z "$left" ]; then ok "a failed first install leaves no file and no directory of the IDE's"; else fail "a failed first install leaves no file and no directory of the IDE's" "$left"; fi
|
||||
|
||||
# --- 6. with a LLeMbas CLI on PATH (a stand-in) -------------------------------------------------
|
||||
echo "With a LLeMbas CLI"
|
||||
mkdir -p "$WORK/cli/bin" "$WORK/cli/config"
|
||||
cat >"$WORK/cli/bin/lembas" <<EOF
|
||||
#!/bin/sh
|
||||
case "\$1" in
|
||||
--version) echo 2.0.0-beta.99 ;;
|
||||
__paths) printf 'config=%s\ndata=%s\nstate=%s\n' "$WORK/cli/config" "$WORK/cli/data" "$WORK/cli/state" ;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
EOF
|
||||
chmod +x "$WORK/cli/bin/lembas"
|
||||
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" "$A/.local/bin/llembas-ide" doctor 2>&1 || true)"
|
||||
expect "doctor: finds it and its version" "$out" "LLeMbas CLI 2.0.0-beta.99"
|
||||
expect "doctor: not signed in" "$out" "not signed in: lembas login"
|
||||
printf '{ "instances": { "home": { "base_url": "https://llembas.example.org" } } }\n' >"$WORK/cli/config/lembas.json"
|
||||
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" "$A/.local/bin/llembas-ide" doctor 2>&1 || true)"
|
||||
expect "doctor: signed in" "$out" "signed in to a LLeMbas server"
|
||||
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" bash "$REPO/ide/install.sh" --from-checkout --dry-run 2>&1 || true)"
|
||||
expect "the installer leaves an installed CLI alone" "$out" "leave the LLeMbas CLI alone: it is installed"
|
||||
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" "$A/.local/bin/llembas-ide" --headless \
|
||||
-c 'lua local t, live = require("llembas_ide.llembas").status(); io.stdout:write(t .. " live=" .. tostring(live))' -c 'qa!' 2>&1 || true)"
|
||||
expect "the statusline shows LLeMbas and that suggestions are on" "$out" "◈ LLeMbas · suggest on live=true"
|
||||
dash='lua local l, d = require("llembas_ide.llembas"), require("llembas_ide.dashboard"); local function notes() local t = {}; for _, r in ipairs(d.content(false)) do t[#t + 1] = r[1] end; return table.concat(t, "|") end; local first = notes(); vim.wait(5000, function() return l.signed_in() ~= nil end, 20); io.stdout:write(first .. " THEN " .. notes())'
|
||||
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" "$A/.local/bin/llembas-ide" --headless -c "$dash" -c 'qa!' 2>&1 || true)"
|
||||
expect "the start screen claims nothing before it has looked" "${out%% THEN *}" "LLeMbas: press l to chat, i to sign in."
|
||||
expect "the start screen of somebody signed in does not ask for a sign-in" "${out##* THEN }" "LLeMbas is signed in: press l to chat."
|
||||
if has "${out##* THEN }" "needs a server and a sign-in"; then fail "and no longer says one is needed" "$out"; else ok "and no longer says one is needed"; fi
|
||||
rm -f "$WORK/cli/config/lembas.json"
|
||||
out="$(EXTRA_PATH="$WORK/cli/bin" as "$A" "$A/.local/bin/llembas-ide" --headless -c "$dash" -c 'qa!' 2>&1 || true)"
|
||||
expect "the start screen of somebody not signed in says what is needed" "${out##* THEN }" "LLeMbas needs a server and a sign-in: press i."
|
||||
printf '{ "instances": { "home": { "base_url": "https://llembas.example.org" } } }\n' >"$WORK/cli/config/lembas.json"
|
||||
|
||||
# One rule for "is the LLeMbas CLI installed": the installer's and the launcher's shell function,
|
||||
# word for word the same, and the plugin's require("llembas").cli(), in the three places a CLI
|
||||
# can be: on PATH, in ~/.local/bin without that being on PATH (the state right after a first
|
||||
# install), and nowhere.
|
||||
rule_installer="$(sed -n '/^find_cli() {$/,/^}$/p' ide/install.sh)"
|
||||
rule_launcher="$(sed -n '/^find_cli() {$/,/^}$/p' ide/bin/llembas-ide)"
|
||||
if [ -n "$rule_installer" ] && [ "$rule_installer" = "$rule_launcher" ]; then
|
||||
ok "the installer and the launcher find the CLI by the same function, word for word"
|
||||
else
|
||||
fail "the installer and the launcher find the CLI by the same function, word for word" "$rule_installer
|
||||
---
|
||||
$rule_launcher"
|
||||
fi
|
||||
for where in path home nowhere; do
|
||||
H="$WORK/find-$where"
|
||||
mkdir -p "$H/.local/bin" "$H/xdg"
|
||||
p="$CLEAN_PATH"
|
||||
want=none
|
||||
case "$where" in
|
||||
path)
|
||||
p="$WORK/cli/bin:$CLEAN_PATH"
|
||||
want="$WORK/cli/bin/lembas"
|
||||
;;
|
||||
home)
|
||||
cp "$WORK/cli/bin/lembas" "$H/.local/bin/lembas"
|
||||
want="$H/.local/bin/lembas"
|
||||
;;
|
||||
esac
|
||||
by_shell="$(env -i PATH="$p" HOME="$H" bash -c "$rule_installer"'
|
||||
find_cli || echo none' 2>&1)"
|
||||
by_plugin="$(env -i PATH="$p" HOME="$H" XDG_STATE_HOME="$H/xdg" XDG_DATA_HOME="$H/xdg" XDG_CACHE_HOME="$H/xdg" XDG_CONFIG_HOME="$H/xdg" TERM=dumb \
|
||||
"$SYSTEM_NVIM" --headless -u NONE -i NONE --cmd "set rtp+=$REPO/nvim" \
|
||||
-c 'lua local c = require("llembas").cli(); io.stdout:write(c and vim.fn.exepath(c[1]) or "none")' -c 'qa!' 2>&1)"
|
||||
if [ "$by_shell" = "$want" ] && [ "$by_plugin" = "$want" ]; then
|
||||
ok "a CLI $where: the scripts and the plugin agree ($want)"
|
||||
else
|
||||
fail "a CLI $where: the scripts and the plugin agree ($want)" "shell: $by_shell
|
||||
plugin: $by_plugin"
|
||||
fi
|
||||
done
|
||||
# The state right after a first install: the CLI in ~/.local/bin, which is not on PATH.
|
||||
cp "$WORK/cli/bin/lembas" "$A/.local/bin/lembas"
|
||||
out="$(env -i PATH="$CLEAN_PATH" HOME="$A" TERM=dumb LANG=C.UTF-8 "$A/.local/bin/llembas-ide" doctor 2>&1 || true)"
|
||||
expect "doctor finds a CLI that is in ~/.local/bin and not on PATH" "$out" "LLeMbas CLI 2.0.0-beta.99 ($A/.local/bin/lembas)"
|
||||
expect "doctor: and says that a terminal will not find it" "$out" "$A/.local/bin is not on your PATH"
|
||||
out="$(env -i PATH="$CLEAN_PATH" HOME="$A" TERM=dumb LANG=C.UTF-8 "$A/.local/bin/llembas-ide" --headless \
|
||||
-c 'lua local t, live = require("llembas_ide.llembas").status(); io.stdout:write(t .. " live=" .. tostring(live))' -c 'qa!' 2>&1 || true)"
|
||||
expect "and so does the IDE: LLeMbas is on, not \"no CLI\"" "$out" "◈ LLeMbas · suggest on live=true"
|
||||
rm -f "$A/.local/bin/lembas"
|
||||
|
||||
# The CLI's own installer is run only once it matches its release's signed SHA256SUMS. The
|
||||
# stand-in installer leaves a mark saying it ran, and with what.
|
||||
CLIREL="$WORK/cli-releases"
|
||||
mkdir -p "$CLIREL/v2.0.0-beta.99"
|
||||
printf '%s\n' '#!/usr/bin/env bash' "echo \"ran ref=\${LEMBAS_REF:-} channel=\${LEMBAS_CHANNEL:-} args=\$*\" >\"$WORK/cli-installer-ran\"" >"$CLIREL/v2.0.0-beta.99/get.sh"
|
||||
(cd "$CLIREL/v2.0.0-beta.99" && sha256sum get.sh >SHA256SUMS)
|
||||
ssh-keygen -q -t ed25519 -N '' -C cli -f "$WORK/clikey" >/dev/null
|
||||
ssh-keygen -q -t ed25519 -N '' -C stranger -f "$WORK/strangerkey" >/dev/null
|
||||
cli_install() { # the installer over the installation in A, saying yes to the CLI, against a CLI release
|
||||
as "$A" env LLEMBAS_IDE_CLI_RELEASE_BASE="file://$CLIREL" LLEMBAS_IDE_CLI_VERSION=2.0.0-beta.99 LLEMBAS_IDE_PUBKEY="$(cut -d' ' -f1,2 "$WORK/clikey.pub")" \
|
||||
bash "$REPO/ide/install.sh" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers --yes 2>&1 || true
|
||||
}
|
||||
out="$(cli_install)"
|
||||
expect "a CLI release that is not signed: its installer is not run" "$out" "the LLeMbas CLI's installer could not be checked, so it was not run"
|
||||
check "…really not" test ! -e "$WORK/cli-installer-ran"
|
||||
expect "…and the IDE is installed all the same" "$out" "is installed. Start it with: llembas-ide"
|
||||
ssh-keygen -Y sign -q -f "$WORK/strangerkey" -n lembas-release "$CLIREL/v2.0.0-beta.99/SHA256SUMS" 2>/dev/null
|
||||
out="$(cli_install)"
|
||||
expect "a CLI release signed with another key: its installer is not run" "$out" "SHA256SUMS is not signed by the release key"
|
||||
check "…really not" test ! -e "$WORK/cli-installer-ran"
|
||||
rm -f "$CLIREL/v2.0.0-beta.99/SHA256SUMS.sig"
|
||||
ssh-keygen -Y sign -q -f "$WORK/clikey" -n lembas-release "$CLIREL/v2.0.0-beta.99/SHA256SUMS" 2>/dev/null
|
||||
echo '# one line more' >>"$CLIREL/v2.0.0-beta.99/get.sh"
|
||||
out="$(cli_install)"
|
||||
expect "an installer that is not the one the signed list names is not run" "$out" "the LLeMbas CLI's installer does not match its release's SHA256SUMS"
|
||||
check "…really not" test ! -e "$WORK/cli-installer-ran"
|
||||
sed -i '$d' "$CLIREL/v2.0.0-beta.99/get.sh"
|
||||
out="$(cli_install)"
|
||||
expect "signed by the release key and matching: the CLI's installer is checked" "$out" "the LLeMbas CLI's installer matches its release"
|
||||
if [ "$(cat "$WORK/cli-installer-ran" 2>/dev/null)" = "ran ref=v2.0.0-beta.99 channel=beta args=--yes" ]; then
|
||||
ok "…and run, for that release and its channel"
|
||||
else
|
||||
fail "…and run, for that release and its channel" "$(cat "$WORK/cli-installer-ran" 2>&1)
|
||||
$out"
|
||||
fi
|
||||
check "and doctor is still content" as "$A" "$A/.local/bin/llembas-ide" doctor
|
||||
|
||||
# --- 7. a release: packaged, checked, installed with the pinned Neovim and compiled grammars ----
|
||||
echo "A release"
|
||||
check "package-ide.sh writes the release files" scripts/package-ide.sh
|
||||
REL="$WORK/rel"
|
||||
mkdir -p "$REL/v$VERSION"
|
||||
cp "dist/llembas-ide-$VERSION.tar.gz" dist/install.sh dist/SHA256SUMS "$REL/v$VERSION/"
|
||||
check "SHA256SUMS lists the archive and the installer, and they match" \
|
||||
bash -c 'cd "$1" && sha256sum -c --quiet SHA256SUMS && grep -q " install.sh$" SHA256SUMS && grep -q " llembas-ide-.*\.tar\.gz$" SHA256SUMS' _ "$REL/v$VERSION"
|
||||
check "the release's install.sh is the repository's" cmp -s "$REL/v$VERSION/install.sh" ide/install.sh
|
||||
check "the archive holds the installer, the configuration, the plugin and no tests" \
|
||||
bash -c 't="$(tar -tzf "$1")"; for f in ide/install.sh ide/plugins.lock ide/config/init.lua nvim/plugin/llembas.lua VERSION LICENSE; do grep -q "^llembas-ide-$2/$f$" <<<"$t" || { echo "missing $f"; exit 1; }; done; ! grep -q "/tests/" <<<"$t"' _ "$REL/v$VERSION/llembas-ide-$VERSION.tar.gz" "$VERSION"
|
||||
B="$WORK/b"
|
||||
C="$WORK/c"
|
||||
mkdir -p "$B" "$C"
|
||||
# Tampered with: one byte of the archive changed.
|
||||
mkdir -p "$WORK/bad/v$VERSION"
|
||||
cp "$REL/v$VERSION"/* "$WORK/bad/v$VERSION/"
|
||||
printf 'x' >>"$WORK/bad/v$VERSION/llembas-ide-$VERSION.tar.gz"
|
||||
attempt as "$C" env LLEMBAS_IDE_RELEASE_BASE="file://$WORK/bad" bash "$REL/v$VERSION/install.sh" --no-cli --version "$VERSION" --nvim-bin "$SYSTEM_NVIM" --no-parsers
|
||||
out="$OUT"
|
||||
refuses "an archive that does not match SHA256SUMS is refused"
|
||||
expect "in words" "$out" "does not match SHA256SUMS — nothing installed"
|
||||
out="$(as "$C" env LLEMBAS_IDE_RELEASE_BASE="http://example.org/releases" bash "$REL/v$VERSION/install.sh" --no-cli --version "$VERSION" 2>&1 || true)"
|
||||
expect "a release over plain http is refused" "$out" "only https://"
|
||||
# Signed releases: a key made here, for this test only.
|
||||
ssh-keygen -q -t ed25519 -N '' -C test -f "$WORK/key" >/dev/null
|
||||
ssh-keygen -q -t ed25519 -N '' -C other -f "$WORK/otherkey" >/dev/null
|
||||
out="$(as "$C" env LLEMBAS_IDE_RELEASE_BASE="file://$REL" LLEMBAS_IDE_PUBKEY="$(cut -d' ' -f1,2 "$WORK/key.pub")" bash "$REL/v$VERSION/install.sh" --no-cli --version "$VERSION" --nvim-bin "$SYSTEM_NVIM" --no-parsers 2>&1 || true)"
|
||||
expect "with a release key set, an unsigned release is refused" "$out" "the release is not signed"
|
||||
ssh-keygen -Y sign -q -f "$WORK/otherkey" -n lembas-release "$REL/v$VERSION/SHA256SUMS" 2>/dev/null
|
||||
out="$(as "$C" env LLEMBAS_IDE_RELEASE_BASE="file://$REL" LLEMBAS_IDE_PUBKEY="$(cut -d' ' -f1,2 "$WORK/key.pub")" bash "$REL/v$VERSION/install.sh" --no-cli --version "$VERSION" --nvim-bin "$SYSTEM_NVIM" --no-parsers 2>&1 || true)"
|
||||
expect "one signed with another key is refused" "$out" "SHA256SUMS is not signed by the release key"
|
||||
if [ -z "$(find "$C" -mindepth 1 | head -n1)" ]; then ok "every refusal leaves nothing behind"; else fail "every refusal leaves nothing behind" "$(find "$C" -mindepth 1 | head)"; fi
|
||||
rm -f "$REL/v$VERSION/SHA256SUMS.sig"
|
||||
ssh-keygen -Y sign -q -f "$WORK/key" -n lembas-release "$REL/v$VERSION/SHA256SUMS" 2>/dev/null
|
||||
|
||||
if [ "$QUICK" = 1 ]; then
|
||||
attempt as "$B" env LLEMBAS_IDE_RELEASE_BASE="file://$REL" LLEMBAS_IDE_PUBKEY="$(cut -d' ' -f1,2 "$WORK/key.pub")" bash "$REL/v$VERSION/install.sh" --no-cli --version "$VERSION" --nvim-bin "$SYSTEM_NVIM" --no-parsers
|
||||
out="$OUT"
|
||||
passes "installs from the release (quick: this machine's Neovim, bundled grammars)"
|
||||
expect "its signature is checked" "$out" "signature good (release key)"
|
||||
expect "its checksum is checked" "$out" "checksum good"
|
||||
report_headless "headless start of the release's install" "$(headless "$B" 0 IDE_TEST_FIRST=1 || true)"
|
||||
else
|
||||
attempt as "$B" env LLEMBAS_IDE_RELEASE_BASE="file://$REL" LLEMBAS_IDE_PUBKEY="$(cut -d' ' -f1,2 "$WORK/key.pub")" bash "$REL/v$VERSION/install.sh" --no-cli --version "$VERSION"
|
||||
out="$OUT"
|
||||
passes "installs from the release, with the pinned Neovim downloaded and the grammars compiled"
|
||||
expect "its signature is checked" "$out" "signature good (release key)"
|
||||
expect "its checksum is checked" "$out" "checksum good"
|
||||
expect "Neovim's SHA-256 is checked before unpacking" "$out" "check its SHA-256 is"
|
||||
expect "the grammars are compiled" "$out" "compiled $(grep -c -v -E '^\s*(#|$)' ide/parsers.lock) Treesitter grammars"
|
||||
out="$(as "$B" "$B/.local/bin/llembas-ide" --version 2>&1 || true)"
|
||||
expect "the installed Neovim is the pinned one" "$out" "Neovim $(cat ide/neovim.version)"
|
||||
check "it is the IDE's own copy" test -x "$B/.local/share/llembas-ide/nvim/bin/nvim"
|
||||
report_headless "headless start on the pinned Neovim with compiled grammars" "$(headless "$B" 1 IDE_TEST_FIRST=1 || true)"
|
||||
typing "$B" "typing on the pinned Neovim: the completion menu opens, and <Tab> stays LLeMbas's"
|
||||
layout "$B" "the four bars on the pinned Neovim"
|
||||
check "the plugin on its own passes its whole suite (scripts/test-nvim.sh)" scripts/test-nvim.sh
|
||||
attempt as "$B" "$B/.local/bin/llembas-ide" doctor
|
||||
out="$OUT"
|
||||
passes "doctor finds it sound"
|
||||
expect "doctor: the grammars" "$out" "Treesitter grammars compiled"
|
||||
START_B="$(startup_ms "$B")"
|
||||
ok "startup on the pinned Neovim, best of three: ${START_B} ms"
|
||||
# A Neovim download that is not the pinned bytes.
|
||||
payload_copy "$WORK/wrongsha"
|
||||
sed -i -E 's/^[0-9a-f]{8}/00000000/' "$WORK/wrongsha/ide/neovim.sha256"
|
||||
attempt as "$C" bash "$WORK/wrongsha/ide/install.sh" --no-cli --from-dir "$WORK/wrongsha" --no-parsers
|
||||
out="$OUT"
|
||||
refuses "a Neovim download with another SHA-256 is refused"
|
||||
expect "in words" "$out" "not the pinned"
|
||||
if [ -z "$(find "$C" -mindepth 1 | head -n1)" ]; then ok "and leaves nothing behind"; else fail "and leaves nothing behind" "$(find "$C" -mindepth 1 | head)"; fi
|
||||
# The oldest supported Neovim with the compiled grammars: the first home, updated in place.
|
||||
attempt installer "$A" --from-checkout --nvim-bin "$SYSTEM_NVIM"
|
||||
out="$OUT"
|
||||
passes "the first home takes the compiled grammars in an update"
|
||||
report_headless "headless start on this machine's Neovim with compiled grammars" "$(headless "$A" 1 IDE_TEST_USER=1 || true)"
|
||||
fi
|
||||
attempt as "$B" env LLEMBAS_IDE_RELEASE_BASE="file://$REL" LLEMBAS_IDE_PUBKEY="$(cut -d' ' -f1,2 "$WORK/key.pub")" "$B/.local/bin/llembas-ide" update --no-cli --version "$VERSION"
|
||||
out="$OUT"
|
||||
passes "llembas-ide update runs the installed installer against the release"
|
||||
expect "and keeps what is already there" "$out" "already installed, unchanged"
|
||||
if [ "$QUICK" != 1 ]; then
|
||||
expect "Neovim included" "$out" "keep Neovim $(cat ide/neovim.version)"
|
||||
expect "and the compiled grammars" "$out" "compiled Treesitter grammars (already installed, same pins)"
|
||||
fi
|
||||
|
||||
# --- 8. somewhere else: --prefix -----------------------------------------------------------------
|
||||
echo "A prefix of the person's choosing"
|
||||
D="$WORK/d"
|
||||
mkdir -p "$D"
|
||||
attempt installer "$D" --from-checkout --nvim-bin "$SYSTEM_NVIM" --no-parsers --prefix "$WORK/opt/my ide"
|
||||
passes "installs into a directory with a space in its name"
|
||||
check "the IDE is there and not in the default place" test -d "$WORK/opt/my ide/lib" -a ! -e "$D/.local/share/llembas-ide"
|
||||
check "doctor is content" as "$D" "$D/.local/bin/llembas-ide" doctor
|
||||
attempt as "$D" "$D/.local/bin/llembas-ide" uninstall --purge --yes
|
||||
passes "uninstall --purge --yes"
|
||||
if [ -z "$(files_in "$D")" ] && [ ! -e "$WORK/opt/my ide" ]; then ok "leaves nothing, and the prefix is gone"; else fail "leaves nothing, and the prefix is gone" "$(files_in "$D"; ls -la "$WORK/opt")"; fi
|
||||
|
||||
# --- 9. uninstalling ---------------------------------------------------------------------------
|
||||
echo "Uninstalling"
|
||||
attempt as "$A" "$A/.local/bin/llembas-ide" uninstall --yes
|
||||
out="$OUT"
|
||||
passes "uninstall --yes"
|
||||
left="$(files_in "$A" | tr '\n' ' ')"
|
||||
if [ "$left" = "./.config/llembas-ide/lua/user/init.lua ./.config/llembas-ide/pack/user/start/mine/plugin/mine.lua " ]; then ok "leaves nothing but the person's own file and plugin"; else fail "leaves nothing but the person's own file and plugin" "$left"; fi
|
||||
check "which still has what the person wrote" grep -q 'llembas_ide_test_user = 42' "$A/.config/llembas-ide/lua/user/init.lua"
|
||||
attempt as "$B" "$B/.local/bin/llembas-ide" uninstall --purge --yes
|
||||
out="$OUT"
|
||||
passes "uninstall --purge --yes"
|
||||
left="$(files_in "$B")"
|
||||
if [ -z "$left" ]; then ok "leaves nothing at all"; else fail "leaves nothing at all" "$left"; fi
|
||||
left="$(cd "$B" && find . -mindepth 1 -type d -name '*llembas*')"
|
||||
if [ -z "$left" ]; then ok "not even an empty directory of its own"; else fail "not even an empty directory of its own" "$left"; fi
|
||||
|
||||
echo
|
||||
echo "test-ide: $PASSED passed, $FAILED failed$([ "$QUICK" = 1 ] && echo ' (quick)')"
|
||||
echo "test-ide: startup ${START_A} ms on $("$SYSTEM_NVIM" --version | head -n1)${START_B:+, ${START_B} ms on the pinned NVIM v$(cat ide/neovim.version) with compiled grammars}"
|
||||
[ "$FAILED" = 0 ]
|
||||
+35
-2
@@ -1,5 +1,38 @@
|
||||
#!/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.
|
||||
#
|
||||
# scripts/test-nvim.sh all of them
|
||||
# scripts/test-nvim.sh rules the rules both editors keep, against tests/rules/
|
||||
# scripts/test-nvim.sh plugin the plugin on its own: chat, rewrite, suggestions, sign-in
|
||||
# scripts/test-nvim.sh layout the bars: top, bottom, tree, right bar, keys, what is remembered
|
||||
#
|
||||
# Nothing of this machine's own Neovim is read or written: the state, data, cache and configuration
|
||||
# directories are temporary ones, removed on every way out.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua
|
||||
WORK="$(mktemp -d "${TMPDIR:-/tmp}/llembas-nvim-test.XXXXXX")"
|
||||
trap 'rm -rf "$WORK"' EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
mkdir -p "$WORK/state" "$WORK/data" "$WORK/cache" "$WORK/config"
|
||||
export XDG_STATE_HOME="$WORK/state" XDG_DATA_HOME="$WORK/data" XDG_CACHE_HOME="$WORK/cache" XDG_CONFIG_HOME="$WORK/config"
|
||||
export LLEMBAS_NVIM_TEST_WORK="$WORK"
|
||||
# The terminal these tests run in says nothing about itself to the plugin.
|
||||
unset LLEMBAS_TERM LLEMBAS_TTY TMUX STY ZELLIJ KITTY_WINDOW_ID GHOSTTY_RESOURCES_DIR TERM_PROGRAM
|
||||
export TERM=dumb
|
||||
|
||||
which="${1:-all}"
|
||||
status=0
|
||||
if [ "$which" = all ] || [ "$which" = rules ]; then
|
||||
# The rules both editors keep, against the shared cases in tests/rules/.
|
||||
nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/rules.lua || status=$?
|
||||
fi
|
||||
if [ "$which" = all ] || [ "$which" = plugin ]; then
|
||||
nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua || status=$?
|
||||
fi
|
||||
if [ "$which" = all ] || [ "$which" = layout ]; then
|
||||
# With a screen (no -l): the bars are read from what is drawn.
|
||||
nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -c "luafile nvim/tests/layout.lua" || status=$?
|
||||
fi
|
||||
exit "$status"
|
||||
@@ -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")/.."
|
||||
|
||||
Executable
+985
@@ -0,0 +1,985 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A stand-in for `lembas serve --stdio`, for the tests of both editors.
|
||||
|
||||
It answers in the shapes of the LLeMbas CLI (2.0.0-beta.17, `src/acp/agent.ts`, harness spec
|
||||
3.11.0) and in no other: every result, refusal, notification and request it sends is written as
|
||||
the CLI writes it, and what it is sent is checked as the CLI checks it. A client that reads an
|
||||
older or an invented shape fails here, as it would against the CLI. When the CLI's protocol
|
||||
changes, this file changes with it -- it is the one place the tests learn the protocol from.
|
||||
|
||||
A turn is steered by words in the prompt's last text block:
|
||||
PERM an approval for a command (`session/request_permission`)
|
||||
SETTLE an approval that is then withdrawn (`_lembas/permission/settled`)
|
||||
DIFFPERM <path> an approval for an edit, carrying ACP diff items; the file is written when allowed
|
||||
READ <path> the read tool: the client's text when it gives one, else the disk's
|
||||
PUT <path> the write tool: "put by the agent" + a line break becomes the file's text
|
||||
EDIT <path> the edit tool: the file's first line in capitals, the rest as it is
|
||||
WRITE <path> the agent writes the disk itself (a session whose client offers no `fs`)
|
||||
SHOW <path> the show tool (text with its content; anything else by a handle); `AT <n>`: a line
|
||||
BADHASH with SHOW: the handle's hash is not the file's
|
||||
QUESTION `_lembas/question` (MULTI: a question that takes several options)
|
||||
PLANCARD `_lembas/plan`
|
||||
TOOL a tool call with its events (phase, tool_end with ms, usage)
|
||||
DENIED a call that was refused
|
||||
PLAN a `plan` update
|
||||
TEAM a `team` event
|
||||
NOTICE a `notice` event
|
||||
META says back the editor context the prompt carried
|
||||
FAIL the turn fails: an `error` event, and the answer's `_meta.lembas.error`
|
||||
FAILFIELD the same, said by the answer alone
|
||||
SLOW waits to be cancelled
|
||||
CRASH writes to stderr and exits 3
|
||||
A prompt that is `/compact` is the command, as the CLI runs it. A completion is steered by words
|
||||
in its prefix (SLOWC waits to be cancelled, FAILC is a server failure, BUSYC is `busy`), a rewrite
|
||||
by words in its instruction (SLOWE waits to be cancelled, `REPLACE <text>` answers that text,
|
||||
SAME answers the selection, ADDLINE puts the first line in capitals and adds a line after the second,
|
||||
EMPTYE is a model that answered nothing; anything else answers the selection in capitals).
|
||||
|
||||
Environment:
|
||||
FAKE_AGENT_LOG every message received is appended, one JSON object a line
|
||||
FAKE_AGENT_VERSION the version it says (default 2.0.0-beta.17); before 2.0.0-beta.14 it
|
||||
has no editor methods, before 2.0.0-beta.15 no `_lembas/sessions/*`
|
||||
FAKE_AGENT_LOGIN=none this computer is not logged in to a server
|
||||
FAKE_AGENT_AUTOCOMPLETE the saved autocomplete model; "none": nobody has chosen one
|
||||
FAKE_AGENT_HANG=<method> that request is never answered
|
||||
FAKE_AGENT_MIN_CLIENT `_meta.lembas.min_client` of the hello: the oldest version of this client
|
||||
the signed-in server works with
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
LOG = os.environ.get("FAKE_AGENT_LOG")
|
||||
VERSION = os.environ.get("FAKE_AGENT_VERSION", "2.0.0-beta.17")
|
||||
LOGGED_IN = os.environ.get("FAKE_AGENT_LOGIN") != "none"
|
||||
HANG = os.environ.get("FAKE_AGENT_HANG", "")
|
||||
|
||||
INVALID_PARAMS = -32602
|
||||
METHOD_NOT_FOUND = -32601
|
||||
INTERNAL_ERROR = -32603
|
||||
|
||||
MODES = ["manual", "edit", "auto", "plan"]
|
||||
NOT_LOGGED_IN_SESSION = ("Not logged in to a LLeMbas server. LLeMbas CLI uses the models of the server it is logged in to: "
|
||||
"lembas login <address> (e.g. lembas login ai.example.org).")
|
||||
NOT_LOGGED_IN_EDITOR = "this computer is not logged in to a LLeMbas server (lembas login <address>)"
|
||||
|
||||
CAPABILITIES = [
|
||||
"directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands",
|
||||
"attachments", "ask", "plan", "model", "turns", "context", "library", "plan_state", "rewind", "jobs", "show",
|
||||
"progress", "tree", "agents", "scheduled", "reports", "directory_model", "harness_turns", "editor", "media",
|
||||
]
|
||||
COMMANDS = [
|
||||
{"name": "compact", "description": "summarise the conversation to free context", "_meta": {"lembas": {"kind": "builtin"}}},
|
||||
{"name": "plan", "description": "plan mode — read, investigate, write a plan for approval; with a task, start on it",
|
||||
"input": {"hint": "task"}, "_meta": {"lembas": {"kind": "builtin"}}},
|
||||
{"name": "undo", "description": "take back the last prompt: its file changes and its conversation", "_meta": {"lembas": {"kind": "builtin"}}},
|
||||
{"name": "review", "description": "a read-only review of this session's changes (or since the last commit, or against a branch)",
|
||||
"input": {"hint": "head | <branch>"}, "_meta": {"lembas": {"kind": "builtin"}}},
|
||||
{"name": "bake", "description": "a skill of the project", "input": {"hint": "instruction"}, "_meta": {"lembas": {"kind": "skill"}}},
|
||||
]
|
||||
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"]},
|
||||
]
|
||||
ALLOWED = ["example/model-a", "example/model-b"]
|
||||
|
||||
|
||||
def version_key(v):
|
||||
"""2.0.0-beta.10 sorts above 2.0.0-beta.9, and a release above its betas."""
|
||||
core, _, pre = v.split("+")[0].partition("-")
|
||||
nums = [int(x) for x in core.split(".")[:3]]
|
||||
n = re.search(r"(\d+)$", pre)
|
||||
return nums + [0 if pre else 1, int(n.group(1)) if n else 0]
|
||||
|
||||
|
||||
HAS_EDITOR = version_key(VERSION) >= version_key("2.0.0-beta.14")
|
||||
HAS_SESSIONS = version_key(VERSION) >= version_key("2.0.0-beta.15")
|
||||
|
||||
lock = threading.Lock()
|
||||
waiting = {} # our request id -> [Event, result, error]
|
||||
next_id = [0]
|
||||
client = {"lembas": False, "protocol": 1, "editor": False, "show": False, "media": False, "read": False, "write": False}
|
||||
sessions = {} # id -> {cwd, mode, model, working, cancel: Event, seen: {path: sha}}
|
||||
saved = os.environ.get("FAKE_AGENT_AUTOCOMPLETE", "example/model-a")
|
||||
settings = {"autocomplete_model": None if saved == "none" else saved, "main_model": None}
|
||||
completion = [None] # (client id, Event) of the one completion under way
|
||||
complete_lock = threading.Lock()
|
||||
rewrites = {} # Event -> client id
|
||||
handles = {} # handle -> bytes
|
||||
deleted = {} # ids of stored sessions that were deleted
|
||||
PREVIOUS = {"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000100000, "created": 1700000000000}
|
||||
|
||||
|
||||
class Refusal(Exception):
|
||||
def __init__(self, code, message, reason=None):
|
||||
super().__init__(message)
|
||||
self.code, self.message, self.reason = code, message, reason
|
||||
|
||||
|
||||
def out(msg):
|
||||
with lock:
|
||||
sys.stdout.write(json.dumps(msg) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def notify(method, params):
|
||||
out({"jsonrpc": "2.0", "method": method, "params": params})
|
||||
|
||||
|
||||
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 ask(method, params, wait=30):
|
||||
"""A request to the client: (result, None), (None, error), or (None, 'timeout')."""
|
||||
with lock:
|
||||
next_id[0] += 1
|
||||
rid = next_id[0]
|
||||
entry = [threading.Event(), None, None]
|
||||
waiting[rid] = entry
|
||||
out({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
|
||||
if not entry[0].wait(wait):
|
||||
waiting.pop(rid, None)
|
||||
return None, "timeout"
|
||||
waiting.pop(rid, None)
|
||||
return entry[1], entry[2]
|
||||
|
||||
|
||||
def sha(text):
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def read_disk(path):
|
||||
with open(path, "rb") as f:
|
||||
return f.read().decode("utf-8")
|
||||
|
||||
|
||||
def write_disk(path, text):
|
||||
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
||||
with open(path, "wb") as f:
|
||||
f.write(text.encode("utf-8"))
|
||||
|
||||
|
||||
def word_after(text, word):
|
||||
return text.split(word + " ", 1)[1].split()[0]
|
||||
|
||||
|
||||
# ---- what the CLI sends about a session ---------------------------------------------------
|
||||
|
||||
|
||||
def update(sid, body):
|
||||
notify("session/update", {"sessionId": sid, "update": body})
|
||||
|
||||
|
||||
def event(sid, body):
|
||||
if client["lembas"]:
|
||||
notify("_lembas/event", {"sessionId": sid, "event": body})
|
||||
|
||||
|
||||
def say(sid, text):
|
||||
event(sid, {"type": "text", "text": text})
|
||||
update(sid, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}})
|
||||
|
||||
|
||||
def think(sid, text):
|
||||
event(sid, {"type": "reasoning", "text": text})
|
||||
update(sid, {"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": text}})
|
||||
|
||||
|
||||
def phase(sid, name, **data):
|
||||
event(sid, {"type": "phase", "progress": {"phase": name, "since": int(time.time() * 1000), **data} if name else None})
|
||||
|
||||
|
||||
def set_mode(sid, mode):
|
||||
sessions[sid]["mode"] = mode
|
||||
event(sid, {"type": "mode", "mode": mode})
|
||||
update(sid, {"sessionUpdate": "current_mode_update", "currentModeId": mode})
|
||||
|
||||
|
||||
def tool_start(sid, call, name, kind, title, args):
|
||||
phase(sid, "running_tool", tool=name, what=title)
|
||||
event(sid, {"type": "tool_start", "id": call, "name": name, "args": args, "title": title})
|
||||
update(sid, {"sessionUpdate": "tool_call", "toolCallId": call, "title": title, "kind": kind, "status": "in_progress", "rawInput": args})
|
||||
|
||||
|
||||
def tool_end(sid, call, name, output, failed=False, files=None, ms=42):
|
||||
event(sid, {"type": "tool_end", "id": call, "name": name, "result": {"output": output, **({"isError": True} if failed else {})}, "ms": ms})
|
||||
content = [{"type": "content", "content": {"type": "text", "text": output[:20000]}}]
|
||||
if files and not failed and client["editor"]:
|
||||
content += diff_items(files)
|
||||
update(sid, {"sessionUpdate": "tool_call_update", "toolCallId": call, "status": "failed" if failed else "completed", "content": content})
|
||||
|
||||
|
||||
def tool_denied(sid, call, name, kind, title, args, reason):
|
||||
event(sid, {"type": "tool_denied", "id": call, "name": name, "reason": reason, "args": args, "title": title})
|
||||
update(sid, {"sessionUpdate": "tool_call", "toolCallId": call, "title": title, "kind": kind, "status": "failed", "rawInput": args,
|
||||
"content": [{"type": "content", "content": {"type": "text", "text": reason}}], "_meta": {"lembas": {"denied": True}}})
|
||||
|
||||
|
||||
def diff_items(files):
|
||||
return [{"type": "diff", "path": f["path"], "oldText": f["oldText"], "newText": f["newText"] if f["newText"] is not None else "",
|
||||
**({"_meta": {"lembas": {"deleted": True}}} if f["newText"] is None else {})} for f in files]
|
||||
|
||||
|
||||
def approval(sid, tool, kind, title, args, reason, files=None, always=True):
|
||||
"""`session/request_permission`, and the answer as the CLI reads it: once, session or deny."""
|
||||
call = str(uuid.uuid4())
|
||||
tool_call = {"toolCallId": call, "title": title, "kind": kind, "status": "pending", "rawInput": args}
|
||||
if files:
|
||||
if client["editor"]:
|
||||
tool_call["content"] = diff_items(files)
|
||||
else:
|
||||
tool_call["content"] = [{"type": "content", "content": {"type": "text", "text": "--- a\n+++ b\n(the change as a unified diff)"}}]
|
||||
options = [{"optionId": "once", "kind": "allow_once", "name": "Allow once"}]
|
||||
if always:
|
||||
options.append({"optionId": "session", "kind": "allow_always", "name": "Always, this session"})
|
||||
options.append({"optionId": "deny", "kind": "reject_once", "name": "Deny"})
|
||||
phase(sid, "waiting_for_person")
|
||||
answer, error = ask("session/request_permission", {
|
||||
"sessionId": sid, "toolCall": tool_call, "options": options,
|
||||
"_meta": {"lembas": {"tool": tool, "reason": reason, "purpose": "what the model says the call is for"}}})
|
||||
if error:
|
||||
notify("_lembas/permission/settled", {"sessionId": sid, "toolCallId": call})
|
||||
return "deny"
|
||||
outcome = (answer or {}).get("outcome") or {}
|
||||
chosen = str(outcome.get("optionId")) if outcome.get("outcome") == "selected" else "deny"
|
||||
if chosen == "once" or (chosen == "session" and always):
|
||||
return chosen
|
||||
return "deny"
|
||||
|
||||
|
||||
# ---- the file tools, with the client's buffers (acp.md *Unsaved text*, src/tool/buffers.ts) ----
|
||||
|
||||
|
||||
def client_read(sid, path):
|
||||
if not client["read"]:
|
||||
return None
|
||||
answer, error = ask("fs/read_text_file", {"sessionId": sid, "path": path}, 10)
|
||||
if error or not isinstance((answer or {}).get("content"), str):
|
||||
return None
|
||||
return answer["content"]
|
||||
|
||||
|
||||
def tool_read(sid, path):
|
||||
"""The read tool: what the client gives is what "read" means from then on."""
|
||||
text = client_read(sid, path)
|
||||
if text is not None:
|
||||
sessions[sid]["seen"][path] = sha(text)
|
||||
return text
|
||||
return read_disk(path)
|
||||
|
||||
|
||||
def file_text(sid, path):
|
||||
"""A file's text for a tool that changes it: the client's, else the disk's -- never the disk's
|
||||
for a file the session read through the client."""
|
||||
text = client_read(sid, path)
|
||||
if text is not None:
|
||||
return text
|
||||
if path in sessions[sid]["seen"]:
|
||||
raise Refusal(0, f"{path} is open in the editor, and the editor did not give its text just now. Read it again before changing it.")
|
||||
return read_disk(path)
|
||||
|
||||
|
||||
def guard(sid, path):
|
||||
seen = sessions[sid]["seen"].get(path)
|
||||
if seen is None or not client["read"]:
|
||||
return
|
||||
now = client_read(sid, path)
|
||||
if now is None:
|
||||
raise Refusal(0, f"{path} is open in the editor, and the editor did not give its text just now. Read it again before changing it.")
|
||||
if sha(now) != seen:
|
||||
raise Refusal(0, f"{path} changed since you last read it. Read it again before changing it.")
|
||||
|
||||
|
||||
def put_text(sid, path, content):
|
||||
"""Write through the client where it takes the text, else to the disk. True: the client took it."""
|
||||
seen = sessions[sid]["seen"]
|
||||
tracked = path in seen
|
||||
if not client["write"]:
|
||||
write_disk(path, content)
|
||||
if tracked:
|
||||
seen[path] = sha(content)
|
||||
return False
|
||||
answer, error = ask("fs/write_text_file", {"sessionId": sid, "path": path, "content": content}, 10)
|
||||
if error == "timeout":
|
||||
seen[path] = "unknown"
|
||||
raise Refusal(0, f"The editor did not confirm writing {path}; it may or may not have been written. Read it again to see what is there before going on.")
|
||||
if not error:
|
||||
seen[path] = sha(content)
|
||||
return True
|
||||
if tracked:
|
||||
raise Refusal(0, f"{path} is open in the editor, which refused the write. Nothing was written; tell the user, or read it again.")
|
||||
write_disk(path, content)
|
||||
return False
|
||||
|
||||
|
||||
# ---- a turn ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def prompt(msg, s, text):
|
||||
p = msg["params"]
|
||||
sid = s["id"]
|
||||
turn = str((((p.get("_meta") or {}).get("lembas") or {}).get("turnId")) or uuid.uuid4())
|
||||
done = {"turnId": turn}
|
||||
s["working"] = True
|
||||
|
||||
def answer(value):
|
||||
# The turn is over before its answer is on the wire: a request that follows the answer
|
||||
# at once (a compact, a delete) must not find the session still working.
|
||||
s["working"] = False
|
||||
return result(msg, value)
|
||||
|
||||
try:
|
||||
if text.startswith("/compact"):
|
||||
event(sid, {"type": "compacted", "summary": "Compacted 2 turns."})
|
||||
return answer({"stopReason": "end_turn", "_meta": {"lembas": {**done, "command": "compact", "summary": "Compacted 2 turns."}}})
|
||||
event(sid, {"type": "prompt", "text": text, "turnId": turn})
|
||||
event(sid, {"type": "task", "state": "start", "turnId": turn})
|
||||
phase(sid, "waiting_for_model", model=s["model"])
|
||||
phase(sid, "thinking")
|
||||
think(sid, "hidden thought")
|
||||
phase(sid, "writing")
|
||||
say(sid, "Hello ")
|
||||
say(sid, "there.\nSecond line")
|
||||
stop = turn_body(sid, s, p, text)
|
||||
# A subagent's usage counts toward the task, and says nothing about the session's own.
|
||||
event(sid, {"type": "usage", "usage": {"input": 700000, "output": 9000}, "child": True})
|
||||
event(sid, {"type": "usage", "usage": {"input": 1200, "output": 34, "cached": 1000}, "context": 32768, "used": 1234, "rate": 41.5})
|
||||
if "FAIL" in text.replace("FAILC", ""):
|
||||
# A turn that fails ends as any other (`end_turn`): the `error` event says why, the phase
|
||||
# is `failed`, and the answer carries the same in `_meta.lembas.error`.
|
||||
why = "the server answered 502: the model is not loaded"
|
||||
if "FAILFIELD" not in text:
|
||||
event(sid, {"type": "error", "message": why})
|
||||
phase(sid, "failed", reason=why)
|
||||
event(sid, {"type": "task", "state": "end", "turnId": turn})
|
||||
event(sid, {"type": "done", "reason": "error"})
|
||||
return answer({"stopReason": "end_turn", "_meta": {"lembas": {**done, "error": {"code": "unreachable", "message": why}}}})
|
||||
phase(sid, None)
|
||||
event(sid, {"type": "task", "state": "end", "turnId": turn})
|
||||
event(sid, {"type": "done", "reason": "cancelled" if stop == "cancelled" else "stop"})
|
||||
answer({"stopReason": stop, "_meta": {"lembas": done}})
|
||||
finally:
|
||||
s["working"] = False
|
||||
|
||||
|
||||
def run_tool(sid, name, kind, title, args, fn, files=None):
|
||||
call = "call_" + uuid.uuid4().hex[:8]
|
||||
tool_start(sid, call, name, kind, title, args)
|
||||
try:
|
||||
output = fn()
|
||||
except Refusal as e:
|
||||
return tool_end(sid, call, name, e.message, failed=True)
|
||||
except OSError as e:
|
||||
return tool_end(sid, call, name, str(e), failed=True)
|
||||
tool_end(sid, call, name, output, files=files() if callable(files) else files)
|
||||
|
||||
|
||||
def turn_body(sid, s, p, text):
|
||||
if "META" in text:
|
||||
say(sid, "\neditor=" + json.dumps(((p.get("_meta") or {}).get("lembas") or {}).get("editor"), sort_keys=True))
|
||||
if "NOTICE" in text:
|
||||
event(sid, {"type": "notice", "level": "warn", "message": "the server is slow to answer; trying again"})
|
||||
if "TEAM" in text:
|
||||
event(sid, {"type": "team", "tree": {"min": 1, "max": 3, "size": 1, "open_slots": 2, "ended": [], "agents": [
|
||||
{"id": "a1", "name": "scout", "position": "1", "parent": None, "state": "working", "model": s["model"], "mode": "plan",
|
||||
"request": [], "manager": False, "task": "read the tests", "progress": None, "findings": 0, "messages": 0}]}})
|
||||
if "PLAN" in text.replace("PLANCARD", ""):
|
||||
plan = {"version": 1, "title": "Upgrade", "summary": "", "findings": [], "objectives": [],
|
||||
"phases": [{"title": "Phase 1", "tasks": [{"text": "Step 1", "status": "done"}, {"text": "Step 2", "status": "doing"}, {"text": "Step 3", "status": "todo"}]}]}
|
||||
event(sid, {"type": "plan", "plan": plan})
|
||||
update(sid, {"sessionUpdate": "plan", "entries": [
|
||||
{"content": "Step 1", "status": "completed", "priority": "medium"},
|
||||
{"content": "Step 2", "status": "in_progress", "priority": "medium"},
|
||||
{"content": "Step 3", "status": "pending", "priority": "medium"}], "_meta": {"lembas": {"plan": plan}}})
|
||||
if "TOOL" in text:
|
||||
run_tool(sid, "grep", "search", "grep waybread", {"pattern": "waybread"}, lambda: "src/oven.py:3: waybread = bake()")
|
||||
if "DENIED" in text:
|
||||
tool_denied(sid, "call_denied", "bash", "execute", "rm -rf /", {"command": "rm -rf /"}, "The hardline never allows this command.")
|
||||
if "DIFFPERM " in text:
|
||||
path = word_after(text, "DIFFPERM")
|
||||
old = file_text(sid, path) if os.path.exists(path) else None
|
||||
new = "rewritten by the agent\n"
|
||||
files = [{"path": path, "oldText": old, "newText": new}]
|
||||
args = {"path": path, "content": new}
|
||||
title = "write " + os.path.basename(path)
|
||||
got = approval(sid, "write", "edit", title, args, "manual mode asks about every edit", files)
|
||||
if got == "deny":
|
||||
tool_denied(sid, "call_w", "write", "edit", title, args, "The user denied this call.")
|
||||
else:
|
||||
run_tool(sid, "write", "edit", title, args, lambda: (put_text(sid, path, new), "Wrote " + path)[1], files)
|
||||
say(sid, "\nanswer=" + got)
|
||||
elif "SETTLE" in text:
|
||||
call = str(uuid.uuid4())
|
||||
with lock:
|
||||
next_id[0] += 1
|
||||
rid = next_id[0]
|
||||
entry = [threading.Event(), None, None]
|
||||
waiting[rid] = entry
|
||||
out({"jsonrpc": "2.0", "id": rid, "method": "session/request_permission", "params": {
|
||||
"sessionId": sid,
|
||||
"toolCall": {"toolCallId": call, "title": "make build", "kind": "execute", "status": "pending", "rawInput": {"command": "make build"}},
|
||||
"options": [{"optionId": "once", "kind": "allow_once", "name": "Allow once"},
|
||||
{"optionId": "session", "kind": "allow_always", "name": "Always, this session"},
|
||||
{"optionId": "deny", "kind": "reject_once", "name": "Deny"}],
|
||||
"_meta": {"lembas": {"tool": "bash", "reason": "the rules ask about this command"}}}})
|
||||
# The device stops waiting (its time ran out, or it was answered at a terminal): the card is taken down.
|
||||
def settle():
|
||||
# Whatever the client answers from here on is not read: the call was refused already.
|
||||
waiting.pop(rid, None)
|
||||
notify("_lembas/permission/settled", {"sessionId": sid, "toolCallId": call})
|
||||
entry[0].set()
|
||||
threading.Timer(0.2, settle).start()
|
||||
entry[0].wait(30)
|
||||
say(sid, "\nanswer=deny (Nobody answered the approval in time, so it was refused.)")
|
||||
elif "PERM" in text:
|
||||
args = {"command": "rm -r build"}
|
||||
got = approval(sid, "bash", "execute", "rm -r build", args, "deletes files")
|
||||
if got == "deny":
|
||||
tool_denied(sid, "call_p", "bash", "execute", "rm -r build", args, "The user denied this call.")
|
||||
say(sid, "\nanswer=" + got)
|
||||
if "WRITE " in text:
|
||||
path = word_after(text, "WRITE")
|
||||
old = read_disk(path) if os.path.exists(path) else None
|
||||
new = "rewritten by the agent\n"
|
||||
run_tool(sid, "write", "edit", "write " + os.path.basename(path), {"path": path, "content": new},
|
||||
lambda: (write_disk(path, new), "Wrote " + path)[1], [{"path": path, "oldText": old, "newText": new}])
|
||||
if "READ " in text:
|
||||
path = word_after(text, "READ")
|
||||
got = {}
|
||||
|
||||
def read():
|
||||
got["text"] = tool_read(sid, path)
|
||||
return got["text"]
|
||||
run_tool(sid, "read", "read", "read " + os.path.basename(path), {"path": path}, read)
|
||||
say(sid, "\nread=" + json.dumps(got.get("text")))
|
||||
if "PUT " in text:
|
||||
path = word_after(text, "PUT")
|
||||
got = {}
|
||||
|
||||
def put():
|
||||
if os.path.exists(path):
|
||||
guard(sid, path)
|
||||
got["by"] = "client" if put_text(sid, path, "put by the agent\n") else "disk"
|
||||
return "Wrote " + path
|
||||
run_tool(sid, "write", "edit", "write " + os.path.basename(path), {"path": path, "content": "put by the agent\n"}, put)
|
||||
say(sid, "\nput=" + got.get("by", "refused"))
|
||||
if "EDIT " in text:
|
||||
path = word_after(text, "EDIT")
|
||||
got = {}
|
||||
|
||||
def edit():
|
||||
guard(sid, path)
|
||||
before = file_text(sid, path)
|
||||
first, sep, rest = before.partition("\n")
|
||||
after = first.upper() + sep + rest
|
||||
got["files"] = [{"path": path, "oldText": before, "newText": after}]
|
||||
got["by"] = "client" if put_text(sid, path, after) else "disk"
|
||||
return "Edited " + path
|
||||
run_tool(sid, "edit", "edit", "edit " + os.path.basename(path), {"path": path}, edit, lambda: got.get("files"))
|
||||
say(sid, "\nedit=" + got.get("by", "refused"))
|
||||
if "SHOW " in text:
|
||||
say(sid, "\nshown=" + json.dumps(show(sid, s, text), sort_keys=True))
|
||||
if "QUESTION" in text:
|
||||
say(sid, "\nquestion=" + json.dumps(question(sid, "MULTI" in text), sort_keys=True))
|
||||
if "PLANCARD" in text:
|
||||
say(sid, "\nplan=" + json.dumps(plan_card(sid), sort_keys=True))
|
||||
if "CRASH" in text:
|
||||
sys.stderr.write("error: the session store could not be opened\n")
|
||||
sys.stderr.flush()
|
||||
os._exit(3)
|
||||
if "SLOW" in text.replace("SLOWC", "").replace("SLOWE", ""):
|
||||
got = s["cancel"].wait(10)
|
||||
s["cancel"].clear()
|
||||
return "cancelled" if got else "end_turn"
|
||||
return "end_turn"
|
||||
|
||||
|
||||
TEXT_KINDS = {"md": ("markdown", None), "html": ("html", None), "py": ("code", "python"), "js": ("code", "javascript"),
|
||||
"ts": ("code", "typescript"), "lua": ("code", "lua"), "csv": ("table", None), "svg": ("svg", None)}
|
||||
MEDIA = {"png": ("image", "image/png"), "jpg": ("image", "image/jpeg"), "gif": ("image", "image/gif"), "pdf": ("pdf", "application/pdf"),
|
||||
"mp3": ("audio", "audio/mpeg"), "mp4": ("video", "video/mp4"), "zip": ("archive", "application/zip")}
|
||||
|
||||
|
||||
def show(sid, s, text):
|
||||
"""The show tool: a text file with its content, any other file by a handle (and, on stdio, where it is)."""
|
||||
if not client["show"]:
|
||||
return {"shown": False, "reason": "the show tool is not offered to this client"}
|
||||
path = word_after(text, "SHOW")
|
||||
with open(path, "rb") as f:
|
||||
data = f.read()
|
||||
rel = os.path.relpath(path, s["root"])
|
||||
ext = os.path.splitext(path)[1][1:].lower()
|
||||
call = "call_show_" + uuid.uuid4().hex[:6]
|
||||
if b"\0" not in data and ext not in MEDIA:
|
||||
kind, language = TEXT_KINDS.get(ext, ("text", None))
|
||||
if not client["media"] and kind in ("table", "svg"):
|
||||
kind = "text"
|
||||
params = {"sessionId": sid, "toolCallId": call, "path": rel, "kind": kind, "text": data.decode("utf-8")}
|
||||
if language:
|
||||
params["language"] = language
|
||||
if " AT " in text:
|
||||
params["line"] = int(word_after(text, "AT"))
|
||||
answer, error = ask("_lembas/show", params, 30)
|
||||
else:
|
||||
if not client["media"]:
|
||||
return {"shown": False, "reason": "not a text file"}
|
||||
kind, mime = MEDIA.get(ext, ("binary", "application/octet-stream"))
|
||||
handle = "h_" + str(uuid.uuid4())
|
||||
handles[handle] = data
|
||||
digest = "0" * 64 if "BADHASH" in text else hashlib.sha256(data).hexdigest()
|
||||
answer, error = ask("_lembas/show", {
|
||||
"sessionId": sid, "toolCallId": call, "path": rel, "kind": kind, "mimeType": mime, "size": len(data),
|
||||
"hash": "sha256:" + digest, "handle": handle, "uri": "file://" + "/".join(quote(x) for x in os.path.abspath(path).split("/"))}, 30)
|
||||
handles.pop(handle, None)
|
||||
if error or not isinstance(answer, dict):
|
||||
return {"shown": False, "reason": "the client did not show it"}
|
||||
if answer.get("shown") is True:
|
||||
return {"shown": True}
|
||||
reason = answer.get("reason")
|
||||
return {"shown": False, "reason": reason if isinstance(reason, str) and reason else "the client did not show it"}
|
||||
|
||||
|
||||
def quote(part):
|
||||
from urllib.parse import quote as q
|
||||
return q(part, safe="")
|
||||
|
||||
|
||||
def question(sid, multiple):
|
||||
"""`_lembas/question`, and its answer as the CLI reads it (`questionReplyFrom`)."""
|
||||
questions = [{"header": "Database", "question": "Which backend?", "multiple": multiple, "options": [
|
||||
{"label": "SQLite", "description": "local file", "recommended": True}, {"label": "Postgres", "description": "server"}]},
|
||||
{"header": "Name", "question": "What is it called?", "multiple": False, "options": []}]
|
||||
phase(sid, "waiting_for_person")
|
||||
answer, error = ask("_lembas/question", {"sessionId": sid, "toolCallId": "call_q_" + uuid.uuid4().hex[:6], "why": "Need a choice",
|
||||
"questions": questions, "_meta": {"lembas": {}}})
|
||||
if error or not isinstance(answer, dict) or answer.get("outcome") != "answered" or not isinstance(answer.get("answers"), list):
|
||||
return {"dismissed": True}
|
||||
answers = []
|
||||
for i, a in enumerate(answer["answers"]):
|
||||
if i >= len(questions):
|
||||
break
|
||||
if isinstance(a, dict) and a.get("kind") == "options" and isinstance(a.get("labels"), list):
|
||||
answers.append({"kind": "options", "labels": [x for x in a["labels"] if isinstance(x, str)]})
|
||||
elif isinstance(a, dict) and a.get("kind") in ("custom", "back") and isinstance(a.get("text"), str):
|
||||
answers.append({"kind": a["kind"], "text": a["text"]})
|
||||
elif a is None or (isinstance(a, dict) and a.get("kind") == "skipped"):
|
||||
answers.append(None)
|
||||
else:
|
||||
return {"dismissed": True}
|
||||
return {"answers": answers}
|
||||
|
||||
|
||||
def plan_card(sid):
|
||||
"""`_lembas/plan`, and its answer as the CLI reads it (`planReplyFrom`)."""
|
||||
plan = {"version": 1, "title": "Upgrade", "summary": "", "findings": [], "objectives": [],
|
||||
"phases": [{"title": "Phase 1", "tasks": [{"text": "Step 1", "status": "todo"}]}]}
|
||||
phase(sid, "waiting_for_person")
|
||||
answer, error = ask("_lembas/plan", {"sessionId": sid, "toolCallId": "call_plan_" + uuid.uuid4().hex[:6], "path": ".agent/plans/upgrade.md",
|
||||
"text": "# Upgrade\n\n- Step 1\n- Step 2", "plan": plan, "_meta": {"lembas": {}}})
|
||||
a = answer if isinstance(answer, dict) and not error else {}
|
||||
if a.get("outcome") == "approve":
|
||||
mode = "manual" if a.get("mode") == "manual" else "edit"
|
||||
set_mode(sid, mode)
|
||||
return {"kind": "approve", "mode": mode}
|
||||
if a.get("outcome") == "revise" and isinstance(a.get("feedback"), str) and a["feedback"].strip():
|
||||
return {"kind": "revise", "feedback": a["feedback"].strip()}
|
||||
return {"kind": "dismissed"}
|
||||
|
||||
|
||||
# ---- the editor's methods (acp.md *An editor as the client*) ----------------------------------
|
||||
|
||||
|
||||
def login_or_refuse():
|
||||
if not LOGGED_IN:
|
||||
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_EDITOR, "not_logged_in")
|
||||
|
||||
|
||||
def editor_settings():
|
||||
return {"autocomplete": {"model": settings["autocomplete_model"], "source": "person" if settings["autocomplete_model"] else None, "allowed": ALLOWED},
|
||||
"main": {"model": settings["main_model"]}}
|
||||
|
||||
|
||||
def complete(msg):
|
||||
p = msg["params"]
|
||||
cid = p.get("id") if isinstance(p.get("id"), str) and p.get("id") else None
|
||||
mine = threading.Event()
|
||||
with complete_lock:
|
||||
before = completion[0]
|
||||
completion[0] = (cid, mine)
|
||||
if before:
|
||||
before[1].set() # a newer request stops the older, which is answered as cancelled
|
||||
try:
|
||||
model = p.get("model") or settings["autocomplete_model"]
|
||||
if not model:
|
||||
return refuse(msg, INVALID_PARAMS, "No autocomplete model is chosen. Choose one in your settings on the server.", "no_model")
|
||||
if model not in [m["id"] for m in MODELS]:
|
||||
return refuse(msg, INVALID_PARAMS, f"{model} is not a model of this account.", "unknown_model")
|
||||
if model not in ALLOWED:
|
||||
return refuse(msg, INVALID_PARAMS, "Model C is not allowed for autocomplete.", "not_allowed")
|
||||
prefix = p["prefix"]
|
||||
if "FAILC" in prefix:
|
||||
return refuse(msg, INTERNAL_ERROR, "autocomplete failed on the server (502)")
|
||||
if "BUSYC" in prefix:
|
||||
return refuse(msg, INVALID_PARAMS, "too many completions at once — the next keystroke will try again", "busy")
|
||||
mine.wait(10 if "SLOWC" in prefix else 0.05)
|
||||
if mine.is_set():
|
||||
return result(msg, {"text": "", "cancelled": True})
|
||||
if "TWO" in prefix:
|
||||
text = "tail()\n second line"
|
||||
else:
|
||||
last = prefix.split()[-1] if prefix.split() else ""
|
||||
text = "<" + last + "|" + model + ">"
|
||||
result(msg, {"text": text, "model": model, "finish": "stop"})
|
||||
finally:
|
||||
with complete_lock:
|
||||
if completion[0] and completion[0][1] is mine:
|
||||
completion[0] = None
|
||||
|
||||
|
||||
def edit(msg):
|
||||
p = msg["params"]
|
||||
eid = p.get("id") if isinstance(p.get("id"), str) and p.get("id") else None
|
||||
mine = threading.Event()
|
||||
rewrites[mine] = eid
|
||||
try:
|
||||
if "EMPTYE" in p["instruction"]:
|
||||
return refuse(msg, INTERNAL_ERROR, "the model answered with no text for this selection — try again, or say more in the instruction")
|
||||
if "SLOWE" in p["instruction"]:
|
||||
mine.wait(10)
|
||||
if mine.is_set():
|
||||
return result(msg, {"text": "", "cancelled": True})
|
||||
text = p["text"]
|
||||
if p["instruction"].startswith("REPLACE "):
|
||||
new = p["instruction"][len("REPLACE "):].replace("\\n", "\n")
|
||||
elif "SAME" in p["instruction"]:
|
||||
new = text
|
||||
elif "ADDLINE" in p["instruction"]:
|
||||
# The first line in capitals, a line added after the second, the rest as it was.
|
||||
lines = text.split("\n")
|
||||
new = "\n".join([lines[0].upper()] + lines[1:2] + [" # added by the rewrite"] + lines[2:])
|
||||
else:
|
||||
new = text.upper()
|
||||
# The text ends with a line break exactly when the selection did.
|
||||
new = new.rstrip("\n") + ("\n" if text.endswith("\n") else "")
|
||||
if eid:
|
||||
half = len(new) // 2
|
||||
for piece in (new[:half], new[half:]):
|
||||
if piece:
|
||||
notify("_lembas/edit/delta", {"id": eid, "delta": piece})
|
||||
model = p.get("model") or (sessions[p["sessionId"]]["model"] if p.get("sessionId") else settings["main_model"] or "example/model-a")
|
||||
result(msg, {"text": new, "model": model})
|
||||
finally:
|
||||
rewrites.pop(mine, None)
|
||||
|
||||
|
||||
def list_files(root, query, limit):
|
||||
"""The project's files and folders matching `query`; an empty query gives the recent ones, and nothing is recent here."""
|
||||
if not query:
|
||||
return []
|
||||
q = query.lower()
|
||||
found = []
|
||||
for base, dirs, names in os.walk(root):
|
||||
dirs[:] = sorted(d for d in dirs if not d.startswith(".") and d != "node_modules")
|
||||
rel = os.path.relpath(base, root)
|
||||
for d in dirs:
|
||||
found.append((os.path.join(rel, d) if rel != "." else d, "dir"))
|
||||
for n in sorted(names):
|
||||
if not n.startswith("."):
|
||||
found.append((os.path.join(rel, n) if rel != "." else n, "file"))
|
||||
return [{"path": path.replace(os.sep, "/"), "kind": kind} for path, kind in found if q in path.lower()][:limit]
|
||||
|
||||
|
||||
def directory_of(p):
|
||||
"""A session's directory, or `cwd`: absolute and a directory, as `session/new` asks."""
|
||||
sid = p.get("sessionId") if isinstance(p.get("sessionId"), str) else ""
|
||||
if sid:
|
||||
if sid not in sessions:
|
||||
raise Refusal(INVALID_PARAMS, "no such session")
|
||||
return sessions[sid]["cwd"]
|
||||
cwd = p.get("cwd").strip() if isinstance(p.get("cwd"), str) else ""
|
||||
if not cwd or not os.path.isabs(cwd):
|
||||
raise Refusal(INVALID_PARAMS, "a sessionId, or a cwd that is an absolute path")
|
||||
if not os.path.isdir(cwd):
|
||||
raise Refusal(INVALID_PARAMS, f"{cwd} is not a directory on this machine")
|
||||
return cwd
|
||||
|
||||
|
||||
def session_of(p):
|
||||
s = sessions.get(str(p.get("sessionId") or ""))
|
||||
if not s:
|
||||
raise Refusal(INVALID_PARAMS, "no such session")
|
||||
return s
|
||||
|
||||
|
||||
def session_result(s, extra=None):
|
||||
return {"sessionId": s["id"], **(extra or {}),
|
||||
"modes": {"currentModeId": s["mode"], "availableModes": [{"id": m, "name": m} for m in MODES]},
|
||||
"_meta": {"lembas": {"model": s["model"], "mode": s["mode"], "effort": "default", "instance": False}}}
|
||||
|
||||
|
||||
def open_session(sid, cwd, mode, model):
|
||||
s = {"id": sid, "cwd": cwd, "root": cwd, "mode": mode, "model": model, "working": False, "cancel": threading.Event(), "seen": {}}
|
||||
sessions[sid] = s
|
||||
return s
|
||||
|
||||
|
||||
def after_answer(fn):
|
||||
threading.Timer(0.01, fn).start()
|
||||
|
||||
|
||||
def handle(msg):
|
||||
method = msg.get("method")
|
||||
p = msg.get("params")
|
||||
p = p if isinstance(p, dict) else {}
|
||||
msg["params"] = p
|
||||
is_request = msg.get("id") is not None
|
||||
if method == HANG:
|
||||
return
|
||||
if method == "initialize":
|
||||
said = ((p.get("clientCapabilities") or {}).get("_meta") or {}).get("lembas")
|
||||
fs = (p.get("clientCapabilities") or {}).get("fs") or {}
|
||||
client["lembas"] = bool(said)
|
||||
said = said if isinstance(said, dict) else {}
|
||||
client["protocol"] = said.get("protocol") if isinstance(said.get("protocol"), (int, float)) else 1
|
||||
client["show"] = said.get("show") is True
|
||||
client["editor"] = said.get("editor") is True and HAS_EDITOR
|
||||
client["media"] = said.get("media") is True and HAS_EDITOR
|
||||
client["read"] = fs.get("readTextFile") is True and HAS_EDITOR
|
||||
client["write"] = fs.get("writeTextFile") is True and HAS_EDITOR
|
||||
capabilities = [c for c in CAPABILITIES if HAS_EDITOR or c not in ("editor", "media")]
|
||||
return result(msg, {
|
||||
"protocolVersion": 1,
|
||||
"agentCapabilities": {"loadSession": False, "promptCapabilities": {"image": True, "audio": False, "embeddedContext": True},
|
||||
"mcpCapabilities": {"http": False, "sse": False}},
|
||||
"authMethods": [],
|
||||
"agentInfo": {"name": "LLeMbas CLI", "version": VERSION},
|
||||
"_meta": {"lembas": {"protocol": 3, "harness_spec": "3.11.0" if HAS_EDITOR else "3.10.0", "limits": None, "connection": None,
|
||||
"capabilities": capabilities,
|
||||
**({"min_client": os.environ["FAKE_AGENT_MIN_CLIENT"]} if os.environ.get("FAKE_AGENT_MIN_CLIENT") else {})}}})
|
||||
if method == "authenticate":
|
||||
return result(msg, {})
|
||||
if method == "session/new":
|
||||
cwd = p.get("cwd") if isinstance(p.get("cwd"), str) else ""
|
||||
if not cwd or not os.path.isabs(cwd):
|
||||
raise Refusal(INVALID_PARAMS, "cwd must be an absolute path")
|
||||
if not os.path.isdir(cwd):
|
||||
raise Refusal(INVALID_PARAMS, f"{cwd} is not a directory on this machine")
|
||||
if not LOGGED_IN:
|
||||
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION)
|
||||
meta = p.get("_meta") if isinstance(p.get("_meta"), dict) else {}
|
||||
mode = meta.get("mode") if meta.get("mode") in MODES else "manual"
|
||||
model = meta.get("model") if isinstance(meta.get("model"), str) else settings["main_model"] or "example/model-a"
|
||||
if model not in [m["id"] for m in MODELS]:
|
||||
raise Refusal(INVALID_PARAMS, f"unknown model {model} — the server offers: " + ", ".join(m["id"] for m in MODELS))
|
||||
s = open_session("ses_test" if "ses_test" not in sessions else "ses_test" + str(len(sessions)), cwd, mode, model)
|
||||
after_answer(lambda: update(s["id"], {"sessionUpdate": "available_commands_update", "availableCommands": COMMANDS}))
|
||||
return result(msg, session_result(s))
|
||||
if method == "session/prompt":
|
||||
s = session_of(p)
|
||||
blocks = p.get("prompt")
|
||||
if not isinstance(blocks, list):
|
||||
raise Refusal(INVALID_PARAMS, "prompt must be an array of content blocks")
|
||||
texts = [b["text"] for b in blocks if isinstance(b, dict) and b.get("type") == "text" and isinstance(b.get("text"), str)]
|
||||
return threading.Thread(target=guarded, args=(msg, lambda: prompt(msg, s, texts[-1] if texts else "")), daemon=True).start()
|
||||
if method == "session/cancel":
|
||||
s = sessions.get(str(p.get("sessionId") or ""))
|
||||
ran = bool(s and s["working"])
|
||||
if s:
|
||||
s["cancel"].set()
|
||||
return result(msg, {"cancelled": "running" if ran else "none"}) if is_request else None
|
||||
if method == "session/set_mode":
|
||||
if p.get("modeId") not in MODES:
|
||||
raise Refusal(INVALID_PARAMS, f"unknown mode {p.get('modeId')}")
|
||||
s = session_of(p)
|
||||
set_mode(s["id"], p["modeId"])
|
||||
return result(msg, {})
|
||||
if method == "_lembas/configure":
|
||||
s = session_of(p)
|
||||
if "model" in p:
|
||||
raw = p["model"].strip() if isinstance(p["model"], str) else ""
|
||||
if not raw:
|
||||
raise Refusal(INVALID_PARAMS, "model must be a non-empty string")
|
||||
if raw not in [m["id"] for m in MODELS]:
|
||||
raise Refusal(INVALID_PARAMS, f"unknown model {raw} — the server offers: " + ", ".join(m["id"] for m in MODELS))
|
||||
if raw != s["model"]:
|
||||
s["model"] = raw
|
||||
event(s["id"], {"type": "model", "ref": raw, "effort": "default", "connection": "example", "instance": False})
|
||||
return result(msg, {"model": s["model"], "effort": "default"})
|
||||
if method == "_lembas/steer":
|
||||
text = p.get("text").strip() if isinstance(p.get("text"), str) else ""
|
||||
if not text:
|
||||
raise Refusal(INVALID_PARAMS, "nothing to send")
|
||||
s = session_of(p)
|
||||
if not s["working"]:
|
||||
raise Refusal(INVALID_PARAMS, "this session is not working on anything; send it as a prompt")
|
||||
event(s["id"], {"type": "inbox", "texts": [text], "mode": "steer"})
|
||||
return result(msg, {"queued": 1})
|
||||
if method == "_lembas/session/compact":
|
||||
s = session_of(p)
|
||||
if s["working"]:
|
||||
raise Refusal(INVALID_PARAMS, "this session is working — compact it when the reply is done")
|
||||
event(s["id"], {"type": "compacted", "summary": "Compacted 2 turns."})
|
||||
return result(msg, {"summary": "Compacted 2 turns."})
|
||||
if method == "_lembas/files/search":
|
||||
root = directory_of(p)
|
||||
limit = max(1, min(50, int(p.get("limit") or 20)))
|
||||
return result(msg, {"root": root, "files": list_files(root, p.get("query") if isinstance(p.get("query"), str) else "", limit)})
|
||||
if method == "_lembas/commands":
|
||||
directory_of(p)
|
||||
return result(msg, {"commands": COMMANDS})
|
||||
if method in ("_lembas/sessions/list", "_lembas/sessions/resume") and not HAS_SESSIONS:
|
||||
raise Refusal(METHOD_NOT_FOUND, "Method not found: " + method)
|
||||
if method == "_lembas/sessions/list":
|
||||
if not LOGGED_IN:
|
||||
return result(msg, {"sessions": []})
|
||||
cwd = p.get("cwd") if isinstance(p.get("cwd"), str) and os.path.isabs(p.get("cwd")) else "/"
|
||||
return result(msg, {"sessions": [] if deleted.get(PREVIOUS["id"]) else [{**PREVIOUS, "root": cwd}]})
|
||||
if method == "_lembas/sessions/resume":
|
||||
sid = str(p.get("sessionId") or "").strip()
|
||||
if not sid:
|
||||
raise Refusal(INVALID_PARAMS, "sessionId is required")
|
||||
if (sid != PREVIOUS["id"] or deleted.get(sid)) and sid not in sessions:
|
||||
raise Refusal(INVALID_PARAMS, "no such session")
|
||||
if not LOGGED_IN:
|
||||
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION)
|
||||
s = sessions.get(sid) or open_session(sid, os.getcwd(), "edit", PREVIOUS["model"])
|
||||
after_answer(lambda: update(s["id"], {"sessionUpdate": "available_commands_update", "availableCommands": COMMANDS}))
|
||||
return result(msg, session_result(s, {"title": PREVIOUS["title"], "cwd": s["cwd"], "turns": [
|
||||
{"role": "user", "text": "earlier question", "turnId": "t1", "attachments": [{"name": "notes.md", "mimeType": "text/markdown", "size": 120}]},
|
||||
{"role": "assistant", "text": "earlier answer", "reasoning": "earlier thinking",
|
||||
"tools": [{"id": "call_1", "name": "read", "args": "{\"path\":\"notes.md\"}", "output": "the notes", "isError": False},
|
||||
{"id": "call_2", "name": "bash", "args": "{\"command\":\"make\"}", "output": "make: no rule", "isError": True}]},
|
||||
{"role": "user", "text": "⏎ the job is done", "turnId": "t2", "machine": True},
|
||||
{"role": "assistant", "text": "noted", "reasoning": "", "tools": []}]}))
|
||||
if method == "_lembas/session/delete":
|
||||
# As the CLI answers it (src/acp/agent.ts `deleteSession`): `{deleted}`, false for a session
|
||||
# it does not have; one that works is stopped first; nothing is notified on `serve --stdio`
|
||||
# (`_lembas/session/deleted` goes to the LLeMbas link only).
|
||||
sid = str(p.get("sessionId") or "")
|
||||
s = sessions.pop(sid, None)
|
||||
if s:
|
||||
s["cancel"].set()
|
||||
return result(msg, {"deleted": True})
|
||||
if sid == PREVIOUS["id"] and LOGGED_IN and not deleted.get(sid):
|
||||
deleted[sid] = True
|
||||
return result(msg, {"deleted": True})
|
||||
return result(msg, {"deleted": False})
|
||||
if method.startswith("_lembas/") and not HAS_EDITOR and method.split("/")[1] in ("complete", "edit", "models", "editor", "show"):
|
||||
if is_request:
|
||||
raise Refusal(METHOD_NOT_FOUND, "Method not found: " + method)
|
||||
return None
|
||||
if method == "_lembas/models":
|
||||
login_or_refuse()
|
||||
return result(msg, {"models": MODELS, **editor_settings()})
|
||||
if method == "_lembas/editor/settings":
|
||||
to_set = p.get("set")
|
||||
if to_set is not None:
|
||||
if not isinstance(to_set, dict) or not any(k in to_set for k in settings):
|
||||
raise Refusal(INVALID_PARAMS, "set must name autocomplete_model or main_model", "invalid")
|
||||
for key in settings:
|
||||
if key in to_set and to_set[key] is not None and (not isinstance(to_set[key], str) or not to_set[key].strip()):
|
||||
raise Refusal(INVALID_PARAMS, f"{key} must be a model's id, or null for the instance's", "invalid")
|
||||
login_or_refuse()
|
||||
for key in settings:
|
||||
if to_set and key in to_set:
|
||||
if to_set[key] is not None and to_set[key] not in [m["id"] for m in MODELS]:
|
||||
raise Refusal(INVALID_PARAMS, f"{to_set[key]} is not a model of this account.", "unknown_model")
|
||||
settings[key] = to_set[key]
|
||||
return result(msg, editor_settings())
|
||||
if method == "_lembas/complete":
|
||||
if not isinstance(p.get("prefix"), str):
|
||||
raise Refusal(INVALID_PARAMS, "prefix must be the text before the cursor", "invalid")
|
||||
login_or_refuse()
|
||||
return threading.Thread(target=guarded, args=(msg, lambda: complete(msg)), daemon=True).start()
|
||||
if method == "_lembas/complete/cancel":
|
||||
running = completion[0]
|
||||
if running and running[0] and running[0] == p.get("id"):
|
||||
running[1].set()
|
||||
return None
|
||||
if method == "_lembas/complete/warm":
|
||||
return None
|
||||
if method == "_lembas/edit":
|
||||
if not isinstance(p.get("text"), str) or not p["text"]:
|
||||
raise Refusal(INVALID_PARAMS, "text must be the selected text", "invalid")
|
||||
if not isinstance(p.get("instruction"), str) or not p["instruction"].strip():
|
||||
raise Refusal(INVALID_PARAMS, "instruction must say what to do with the selection", "invalid")
|
||||
if len(rewrites) >= 4:
|
||||
raise Refusal(INVALID_PARAMS, "4 rewrites are already being written — wait for one, or cancel it", "busy")
|
||||
if p.get("sessionId") and p["sessionId"] not in sessions:
|
||||
raise Refusal(INVALID_PARAMS, "no such session", "invalid")
|
||||
if not LOGGED_IN:
|
||||
raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION, "not_logged_in")
|
||||
return threading.Thread(target=guarded, args=(msg, lambda: edit(msg)), daemon=True).start()
|
||||
if method == "_lembas/edit/cancel":
|
||||
for ev, eid in list(rewrites.items()):
|
||||
if eid and eid == p.get("id"):
|
||||
ev.set()
|
||||
return None
|
||||
if method == "_lembas/show/read":
|
||||
data = handles.get(str(p.get("handle") or ""))
|
||||
if data is None:
|
||||
raise Refusal(INVALID_PARAMS, "that file is not being handed over any more — a handle is good until its _lembas/show is answered", "invalid")
|
||||
offset = p["offset"] if isinstance(p.get("offset"), int) and p["offset"] > 0 else 0
|
||||
length = min(1000, p["length"] if isinstance(p.get("length"), int) and p["length"] >= 0 else 1000) # small parts, so a client has to loop
|
||||
part = data[offset:offset + length]
|
||||
return result(msg, {"data": base64.b64encode(part).decode(), "offset": offset, "eof": offset + len(part) >= len(data)})
|
||||
if is_request:
|
||||
raise Refusal(METHOD_NOT_FOUND, "Method not found: " + str(method))
|
||||
return None
|
||||
|
||||
|
||||
def guarded(msg, fn):
|
||||
try:
|
||||
fn()
|
||||
except Refusal as e:
|
||||
if msg.get("id") is not None:
|
||||
refuse(msg, e.code or INTERNAL_ERROR, e.message, e.reason)
|
||||
except Exception as e: # what the CLI answers when a handler throws
|
||||
if msg.get("id") is not None:
|
||||
refuse(msg, INTERNAL_ERROR, str(e))
|
||||
|
||||
|
||||
def main():
|
||||
for line in sys.stdin:
|
||||
if not line.strip():
|
||||
continue
|
||||
try:
|
||||
msg = json.loads(line)
|
||||
except ValueError:
|
||||
out({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}})
|
||||
continue
|
||||
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
|
||||
continue
|
||||
if LOG:
|
||||
with open(LOG, "a") as f:
|
||||
f.write(json.dumps(msg) + "\n")
|
||||
if msg.get("method") is None:
|
||||
entry = waiting.get(msg.get("id"))
|
||||
if entry:
|
||||
if msg.get("error"):
|
||||
entry[2] = msg["error"]
|
||||
else:
|
||||
entry[1] = msg.get("result")
|
||||
entry[0].set()
|
||||
continue
|
||||
guarded(msg, lambda: handle(msg))
|
||||
# The client went away: what was under way goes with it.
|
||||
os._exit(0)
|
||||
|
||||
|
||||
main()
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A stand-in for the `lembas` program itself, for the tests of signing in and out from an editor.
|
||||
|
||||
lembas serve --stdio the stand-in agent (tests/fake_agent.py); signed in only when the
|
||||
state file says so
|
||||
lembas login --json [address] [--ca file]
|
||||
one JSON object a line, as LLeMbas CLI 2.0 writes them
|
||||
(`src/lembas/login.ts`: `code`, then `done`; `error` with a message
|
||||
and a machine `code`), and its exit codes
|
||||
lembas logout signs out of the one login there is
|
||||
|
||||
The login is one for the whole computer, kept in the file FAKE_LEMBAS_STATE names. Words in the
|
||||
address steer a sign-in: `unreachable` cannot be reached, `expires` is never approved and its code
|
||||
runs out, `slow` waits to be cancelled, `plain` is an older CLI whose errors carry no code.
|
||||
FAKE_LEMBAS_LOG gets every command line, one JSON array a line.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
STATE = os.environ.get("FAKE_LEMBAS_STATE", "")
|
||||
LOG = os.environ.get("FAKE_LEMBAS_LOG", "")
|
||||
|
||||
|
||||
def state():
|
||||
try:
|
||||
with open(STATE) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def emit(obj):
|
||||
sys.stdout.write(json.dumps(obj) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def fail(message, code=1):
|
||||
sys.stderr.write(message + "\n")
|
||||
sys.exit(code)
|
||||
|
||||
|
||||
def base_of(address):
|
||||
a = address.strip().rstrip("/")
|
||||
return a if a.startswith(("http://", "https://")) else "https://" + a
|
||||
|
||||
|
||||
def done(base, fresh):
|
||||
emit({"event": "done", "fresh": fresh, "connection": "example", "base_url": base, "version": "2.0.0", "models": 3, "changes": []})
|
||||
|
||||
|
||||
def login(args):
|
||||
ca = None
|
||||
rest = []
|
||||
it = iter(args)
|
||||
for a in it:
|
||||
if a == "--ca":
|
||||
ca = next(it, None)
|
||||
elif a != "--json":
|
||||
rest.append(a)
|
||||
if "--json" not in args:
|
||||
fail("this stand-in only signs in for a program (--json)", 2)
|
||||
had = state().get("base_url")
|
||||
address = rest[0] if rest else ""
|
||||
if not address or (had and base_of(address) == had and not ca):
|
||||
# Again, with no address or the same one: the login there is, read anew.
|
||||
if not had:
|
||||
fail("usage: lembas login <instance address>", 2)
|
||||
return done(had, False)
|
||||
base = base_of(address)
|
||||
if "unreachable" in address:
|
||||
message = f"{base} could not be reached (connection refused) — is the address right, and the server up?"
|
||||
emit({"event": "error", "message": message, **({} if "plain" in address else {"code": "unreachable"})})
|
||||
fail(message)
|
||||
expires = 1 if "expires" in address else 600
|
||||
emit({"event": "code", "user_code": "WAYB-READ", "verification_uri": base + "/device",
|
||||
"verification_uri_complete": base + "/device?code=WAYB-READ", "expires_in": expires,
|
||||
"instance": {"name": "Example", "version": "2.0.0", "base_url": base}})
|
||||
if "expires" in address:
|
||||
time.sleep(expires + 0.2)
|
||||
message = "the code ran out before it was approved — sign in again for a new one"
|
||||
emit({"event": "error", "message": message, "code": "timeout"})
|
||||
fail(message)
|
||||
if "slow" in address:
|
||||
time.sleep(30)
|
||||
time.sleep(0.15)
|
||||
with open(STATE, "w") as f:
|
||||
json.dump({"base_url": base, "ca": ca}, f)
|
||||
done(base, True)
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
if LOG:
|
||||
with open(LOG, "a") as f:
|
||||
f.write(json.dumps(args) + "\n")
|
||||
if args[:1] == ["serve"]:
|
||||
if STATE and not state().get("base_url"):
|
||||
os.environ["FAKE_AGENT_LOGIN"] = "none"
|
||||
agent = os.path.join(os.path.dirname(os.path.abspath(__file__)), "fake_agent.py")
|
||||
os.execv(sys.executable, [sys.executable, agent])
|
||||
if args[:1] == ["login"]:
|
||||
return login(args[1:])
|
||||
if args[:1] == ["logout"]:
|
||||
had = state().get("base_url")
|
||||
if not had:
|
||||
fail("not logged in to any instance", 2)
|
||||
os.remove(STATE)
|
||||
print("Signed out of example; its connection is removed.")
|
||||
return
|
||||
fail("usage: lembas serve --stdio | login --json [address] | logout", 2)
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,15 @@
|
||||
# Rules both editors keep
|
||||
|
||||
The Neovim plugin (Lua) and the VS Code extension (JavaScript) each carry their own copy of a few
|
||||
small rules. These files are the cases both copies must answer the same way: data, read by
|
||||
`nvim/tests/rules.lua` and `vscode/tests/rules.test.js`. A rule changed in one editor fails here
|
||||
until the other follows.
|
||||
|
||||
| File | The rule |
|
||||
|---|---|
|
||||
| `versions.json` | which of two versions is newer, and what is no version at all |
|
||||
| `private_files.json` | which files look like they hold secrets, and what counts as inside a folder |
|
||||
| `server_address.json` | what may be handed to `lembas login` as the server's address |
|
||||
| `login_events.json` | the events of `lembas login --json`, whatever pieces its output arrives in |
|
||||
| `rpc_lines.json` | which messages survive a line that is longer than the reader keeps |
|
||||
| `openable.json` | which shown files may be opened, by their first bytes and their name |
|
||||
@@ -0,0 +1,11 @@
|
||||
[
|
||||
{ "chunks": ["{\"event\":\"done\",\"base_url\":\"https://ai.example.org\"}\n"], "events": ["done"] },
|
||||
{ "chunks": ["{\"event\":\"done\",\"base_", "url\":\"https://ai.example.org\"}\n"], "events": ["done"] },
|
||||
{ "chunks": ["{\"event\":\"code\",\"user_code\":\"ABCD\"}\n{\"event\":\"do", "ne\"}\n"], "events": ["code", "done"] },
|
||||
{ "chunks": ["{\"event\":\"code\"}\r\n", "{\"event\":\"error\",\"message\":\"no\"}\r\n"], "events": ["code", "error"] },
|
||||
{ "chunks": ["not json\n", "{\"event\":\"done\"}\n"], "events": ["done"] },
|
||||
{ "chunks": ["{\"no_event\":1}\n[1,2]\n\"text\"\n{\"event\":7}\n"], "events": [] },
|
||||
{ "chunks": ["{\"event\":\"done\"}"], "events": [] },
|
||||
{ "chunks": ["{\"event\":\"code\"}\n{\"event\":\"done\"}"], "events": ["code"] },
|
||||
{ "chunks": ["", "\n", "{\"event\":\"done\"}\n"], "events": ["done"] }
|
||||
]
|
||||
@@ -0,0 +1,177 @@
|
||||
[
|
||||
{
|
||||
"name": "picture.png",
|
||||
"head": "89504e470d0a1a0a00000000000000000000000000000000",
|
||||
"kind": "image"
|
||||
},
|
||||
{
|
||||
"name": "picture.PNG",
|
||||
"head": "89504e470d0a1a0a00000000000000000000000000000000",
|
||||
"kind": "image"
|
||||
},
|
||||
{
|
||||
"name": "photo.jpg",
|
||||
"head": "ffd8ffe000000000000000000000000000000000",
|
||||
"kind": "image"
|
||||
},
|
||||
{
|
||||
"name": "photo.jpeg",
|
||||
"head": "ffd8ffe000000000000000000000000000000000",
|
||||
"kind": "image"
|
||||
},
|
||||
{
|
||||
"name": "picture.jpg",
|
||||
"head": "89504e470d0a1a0a00000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "picture.pdf",
|
||||
"head": "89504e470d0a1a0a00000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "picture",
|
||||
"head": "89504e470d0a1a0a00000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "paper.pdf",
|
||||
"head": "255044462d312e370a256162636465666768",
|
||||
"kind": "pdf"
|
||||
},
|
||||
{
|
||||
"name": "paper.txt",
|
||||
"head": "255044462d312e370a256162636465666768",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "paper.pdf",
|
||||
"head": "6e616d652c636f756e740a66697273742c310a",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "tune.mp3",
|
||||
"head": "4944330300000000000000000000000000000000",
|
||||
"kind": "audio"
|
||||
},
|
||||
{
|
||||
"name": "tune.wav",
|
||||
"head": "524946460000000057415645666d7420",
|
||||
"kind": "audio"
|
||||
},
|
||||
{
|
||||
"name": "tune.ogg",
|
||||
"head": "4f67675300000000000000000000000000000000",
|
||||
"kind": "audio"
|
||||
},
|
||||
{
|
||||
"name": "tune.mp3",
|
||||
"head": "4f67675300000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "clip.mp4",
|
||||
"head": "000000186674797069736f6d00000000",
|
||||
"kind": "video"
|
||||
},
|
||||
{
|
||||
"name": "clip.webm",
|
||||
"head": "1a45dfa300000000000000000000000000000000",
|
||||
"kind": "video"
|
||||
},
|
||||
{
|
||||
"name": "clip.mkv",
|
||||
"head": "1a45dfa300000000000000000000000000000000",
|
||||
"kind": "video"
|
||||
},
|
||||
{
|
||||
"name": "clip.mp4",
|
||||
"head": "1a45dfa300000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "table.csv",
|
||||
"head": "6e616d652c636f756e740a66697273742c310a",
|
||||
"kind": "text"
|
||||
},
|
||||
{
|
||||
"name": "notes.txt",
|
||||
"head": "6e616d652c636f756e740a66697273742c310a",
|
||||
"kind": "text"
|
||||
},
|
||||
{
|
||||
"name": "notes.md",
|
||||
"head": "6e616d652c636f756e740a66697273742c310a",
|
||||
"kind": "text"
|
||||
},
|
||||
{
|
||||
"name": "data.json",
|
||||
"head": "6e616d652c636f756e740a66697273742c310a",
|
||||
"kind": "text"
|
||||
},
|
||||
{
|
||||
"name": "run.sh",
|
||||
"head": "23212f62696e2f73680a6563686f2068656c6c6f2074686572650a",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "run.txt",
|
||||
"head": "23212f62696e2f73680a6563686f2068656c6c6f2074686572650a",
|
||||
"kind": "text"
|
||||
},
|
||||
{
|
||||
"name": "page.html",
|
||||
"head": "3c21646f63747970652068746d6c3e3c7363726970743e313c2f7363726970743e",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "page.svg",
|
||||
"head": "3c21646f63747970652068746d6c3e3c7363726970743e313c2f7363726970743e",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "program",
|
||||
"head": "7f454c4600000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "program.txt",
|
||||
"head": "7f454c4600000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "program.png",
|
||||
"head": "7f454c4600000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "program.exe",
|
||||
"head": "7f454c4600000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "shortcut.desktop",
|
||||
"head": "6e616d652c636f756e740a66697273742c310a",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "model.glb",
|
||||
"head": "676c544600000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "model.obj",
|
||||
"head": "6e616d652c636f756e740a66697273742c310a",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "macro.docm",
|
||||
"head": "504b030400000000000000000000000000000000",
|
||||
"kind": null
|
||||
},
|
||||
{
|
||||
"name": "empty.txt",
|
||||
"head": "",
|
||||
"kind": null
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"secret": [
|
||||
"/home/sam/app/.env",
|
||||
"/home/sam/app/.env.local",
|
||||
"/home/sam/app/.env.production",
|
||||
"/home/sam/app/.ENV",
|
||||
"/home/sam/app/prod.env",
|
||||
"/home/sam/app/certs/server.pem",
|
||||
"/home/sam/app/certs/server.KEY",
|
||||
"/home/sam/app/store.p12",
|
||||
"/home/sam/app/store.pfx",
|
||||
"/home/sam/app/release.jks",
|
||||
"/home/sam/app/release.keystore",
|
||||
"/home/sam/app/putty.ppk",
|
||||
"/home/sam/app/passwords.kdbx",
|
||||
"/home/sam/app/id_rsa",
|
||||
"/home/sam/app/id_rsa.pub",
|
||||
"/home/sam/app/id_ed25519",
|
||||
"/home/sam/app/id_ed25519_work",
|
||||
"/home/sam/app/id_ecdsa",
|
||||
"/home/sam/app/id_dsa",
|
||||
"/home/sam/app/.netrc",
|
||||
"/home/sam/app/_netrc",
|
||||
"/home/sam/app/.npmrc",
|
||||
"/home/sam/app/.pypirc",
|
||||
"/home/sam/app/.pgpass",
|
||||
"/home/sam/app/.htpasswd",
|
||||
"/home/sam/app/.git-credentials",
|
||||
"/home/sam/app/credentials",
|
||||
"/home/sam/app/credentials.json",
|
||||
"/home/sam/app/Credentials.yaml",
|
||||
"/home/sam/app/secrets.yaml",
|
||||
"/home/sam/app/secrets.toml",
|
||||
"/home/sam/app/secret.json",
|
||||
"/home/sam/.ssh/config",
|
||||
"/home/sam/.ssh/known_hosts",
|
||||
"/home/sam/app/.ssh/notes.txt",
|
||||
"/home/sam/.gnupg/gpg.conf",
|
||||
"/home/sam/.aws/config",
|
||||
"/home/sam/.kube/config",
|
||||
"/home/sam/.docker/config.json",
|
||||
"/home/sam/.azure/profile.json",
|
||||
"C:\\Users\\sam\\app\\.env",
|
||||
"C:\\Users\\sam\\.ssh\\config"
|
||||
],
|
||||
"plain": [
|
||||
"/home/sam/app/main.py",
|
||||
"/home/sam/app/.env.example",
|
||||
"/home/sam/app/.env.sample",
|
||||
"/home/sam/app/.env.template",
|
||||
"/home/sam/app/environment.ts",
|
||||
"/home/sam/app/env.py",
|
||||
"/home/sam/app/keyboard.rs",
|
||||
"/home/sam/app/key.go",
|
||||
"/home/sam/app/pem.rs",
|
||||
"/home/sam/app/secretsanta.py",
|
||||
"/home/sam/app/secrets/readme.md",
|
||||
"/home/sam/app/src/credential_store.rs",
|
||||
"/home/sam/app/ssh/client.go",
|
||||
"/home/sam/app/aws/s3.py",
|
||||
"/home/sam/app/README.md",
|
||||
"/home/sam/app/.gitignore",
|
||||
"/home/sam/app/package.json",
|
||||
"/home/sam/app/identity.rs"
|
||||
],
|
||||
"inside": [
|
||||
["/home/sam/app/src/main.py", ["/home/sam/app"], true],
|
||||
["/home/sam/app/main.py", ["/home/sam/app/"], true],
|
||||
["/home/sam/app", ["/home/sam/app"], false],
|
||||
["/home/sam/application/main.py", ["/home/sam/app"], false],
|
||||
["/home/sam/other/main.py", ["/home/sam/app"], false],
|
||||
["/home/sam/other/main.py", ["/home/sam/app", "/home/sam/other"], true],
|
||||
["/home/sam/app/../other/main.py", ["/home/sam/app"], false],
|
||||
["/home/sam/app/main.py", [], false],
|
||||
["/etc/passwd", ["/home/sam/app"], false],
|
||||
["/etc/passwd", ["/"], false],
|
||||
["relative/main.py", ["/home/sam/app"], false]
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"max": 64,
|
||||
"cases": [
|
||||
{ "chunks": ["{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["a", "b"] },
|
||||
{ "chunks": ["{\"jsonrpc\":\"2.0\",\"me", "thod\":\"a\"}\n"], "methods": ["a"] },
|
||||
{ "chunks": ["{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "tail of the long line\n{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["a", "b"] },
|
||||
{ "chunks": ["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "{\"jsonrpc\":\"2.0\",\"method\":\"lost\"}\n", "{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["b"] },
|
||||
{ "chunks": ["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "\n", "{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["b"] },
|
||||
{ "chunks": ["printed by mistake\n", "\n", "{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n"], "methods": ["a"] }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"ok": ["ai.example.org", "https://ai.example.org", "http://localhost:8000", "https://ai.example.org/base/", " ai.example.org ", "[::1]:8000"],
|
||||
"refused": ["", " ", "-h", "--ca", "--json", "ai.example.org --ca /tmp/x", "ai.example.org\n--ca", "a\tb", "-"]
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"compare": [
|
||||
["2.0.0-beta.9", "2.0.0-beta.10", -1],
|
||||
["2.0.0-beta.10", "2.0.0-beta.9", 1],
|
||||
["2.0.0-beta.16", "2.0.0-beta.16", 0],
|
||||
["2.0.0", "2.0.0-beta.99", 1],
|
||||
["2.0.0-alpha.3", "2.0.0-beta.1", -1],
|
||||
["2.0.0-beta.4", "2.0.0-rc.1", -1],
|
||||
["v2.0.0", "2.0.0", 0],
|
||||
["2.0", "2.0.0", 0],
|
||||
["2", "2.0.0", 0],
|
||||
["1.9.9", "2.0.0-beta.1", -1],
|
||||
["2.0.1", "2.0.0", 1],
|
||||
["2.0.0+build.7", "2.0.0", 0],
|
||||
["2.0.0-beta.3+build.7", "2.0.0-beta.3", 0],
|
||||
[" 2.0.0 ", "2.0.0", 0],
|
||||
["10.0.0", "9.9.9", 1]
|
||||
],
|
||||
"not_versions": ["", "latest", "1.2.3junk", "1.2.3 junk", "x1.2.3", "1.2.3-", "1..2", ".1.2", "1.2.", "-beta.1", "1.2.3-beta 4", "v"]
|
||||
}
|
||||
+207
-50
@@ -1,21 +1,26 @@
|
||||
# LLeMbas for VS Code and VSCodium
|
||||
|
||||
LLeMbas in the editor: an agentic chat beside your files, questions and plans as interactive cards,
|
||||
rewriting and generating code as inline diffs, session resume, `@file` and `/command` completion,
|
||||
and tunable inline autocomplete.
|
||||
LLeMbas in the editor, **in one side panel**: an agentic chat beside your files, questions and plans
|
||||
as interactive cards, rewriting and generating code as inline diffs, session resume, `@file` and
|
||||
`/command` completion, tunable inline autocomplete — and, in the same frame, the sessions, the
|
||||
models, every setting, the sign-in and the agent's status. Nothing sends you to a Quick Pick, an
|
||||
input box, a notification that wants an answer, or the editor's Settings page.
|
||||
|
||||
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.
|
||||
about a server or a model is stored in the editor: the panel signs in and chooses models through
|
||||
the CLI, which keeps the sign-in, and your account, which keeps the models. The editor's own
|
||||
settings are which command starts the CLI and how the panel and the suggestions behave.
|
||||
|
||||
## 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: the panel's **Account** view (*LLeMbas: Sign In*), 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,20 +40,60 @@ 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 the program's full path in the panel under **Settings → Program** (`llembas.command`).
|
||||
|
||||
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. The header shows the connection
|
||||
status, session title, mode (switchable live mid-turn), session model, **Tune** (autocomplete
|
||||
settings drawer), **Compact**, **History** (resume previous sessions), and **New**. Enter sends
|
||||
(or steers mid-run), Shift+Enter starts a new line, `@` searches project files and folders, and `/`
|
||||
completes slash commands and skills. Approval cards open edited files in the diff view first;
|
||||
question cards support single/multi-select, recommended markers, custom answers, and skip; plan
|
||||
cards render formatted Markdown with Approve (Edit/Manual), Revise, and Dismiss actions.
|
||||
**One panel.** The LLeMbas icon in the activity bar opens it. A strip of tabs runs along its top —
|
||||
**Chat, Sessions, Models, Autocomplete, Settings, Account, Status** — icons in a narrow side bar
|
||||
(each with its name as a tooltip and for a screen reader), icons with their names in a wide one.
|
||||
The arrow keys walk the strip, `Home` and `End` go to its ends, and the view that is open is the
|
||||
one you find again after closing the panel or reloading the window, with what you were typing.
|
||||
|
||||
**Whole, or beside the conversation.** One rule decides how a view opens:
|
||||
|
||||
- **A tab opens its view in the whole frame**, and so does a command that is about how LLeMbas is
|
||||
set up (*Models*, *Settings*, *Sign In*, *Status*). The **Chat** tab is the way back.
|
||||
- **Anything reached from the conversation opens beside it** — the model button and **History** in
|
||||
the chat's header, a note's *Sign in* or *Status* button, and the commands that are about the
|
||||
conversation in progress (*Resume a Previous Session*, *Choose This Session's Model*, *Open a File
|
||||
of This Project*). The conversation stays where it is: the view takes the lower half of the
|
||||
panel, or the right half when the panel is 640 px wide or more. **Esc** or **Close** puts it away
|
||||
and gives the keyboard back to where it was; the composer's text and the place you had scrolled
|
||||
to are untouched.
|
||||
|
||||
Something in the conversation that waits for your answer while another view fills the frame marks
|
||||
the **Chat** tab; it does not pull you away from what you are doing.
|
||||
|
||||
**Chat.** The header shows the connection status, the session's title, the mode (switchable live
|
||||
mid-turn), the session's model (a button: the models open beside the conversation), **Compact**,
|
||||
**History** and **New**. Enter sends (while LLeMbas works the button reads **Send now**: the
|
||||
message reaches it mid-turn), Shift+Enter starts a new line, `@`
|
||||
searches project files and folders, and `/` completes slash commands and skills. Approval cards
|
||||
open edited files in the diff view first; question cards support single/multi-select, recommended
|
||||
markers, custom answers, and skip; plan cards render formatted Markdown with **Approve: edit without
|
||||
asking**, **Approve: ask before each edit**, Revise, and Dismiss.
|
||||
|
||||
**Sessions.** The earlier sessions of this folder, with a filter. A press resumes one; **Delete**
|
||||
(where the CLI can delete a session) asks again in the row before anything goes.
|
||||
|
||||
**Models.** Three lists from your server, the one in force marked: the model of **this
|
||||
conversation**, the **chat and rewrite** model new sessions start with, and the **autocomplete**
|
||||
model. The last two are kept *saved in your account* (every editor you sign in from uses it) or for
|
||||
*this window only* (a quick switch, saved nowhere) — chosen next to each list.
|
||||
|
||||
**Settings, in the panel.** Every `llembas.*` setting has a field in the panel: autocomplete's in
|
||||
**Autocomplete**, the certificate file in **Account**, the rest in **Settings**. They are the
|
||||
editor's own settings underneath, so `settings.json`, Settings Sync and policies work as ever. Each
|
||||
field says where the value in force comes from (the default, your User settings, the Workspace, a
|
||||
folder), lets you choose the level your change is written to (**User** or **Workspace**; what starts
|
||||
a program is User only) and has a **Reset** for that level. A change made anywhere else — the
|
||||
editor's Settings page, `settings.json` — shows in the panel at once. A small link at the foot of
|
||||
**Settings** opens the editor's own Settings page; nothing needs it.
|
||||
|
||||
What a model writes is drawn as text through the extension's own Markdown reader: paragraphs,
|
||||
headings, lists, task checklists, quotes, real GFM tables (in horizontally scrollable wrappers),
|
||||
@@ -58,82 +103,194 @@ references. HTML in a reply stays text, pictures in a reply are not loaded, and
|
||||
status, kind, duration, clickable changed files, and expandable output; thinking blocks collapse
|
||||
cleanly.
|
||||
|
||||
**Ask, Explain, Fix, Generate & Rewrite.** Ask about or explain a selection, fix reported warnings
|
||||
and errors in the active file, generate code at the cursor, or rewrite selected lines as proposed
|
||||
hunks with *Accept* / *Reject* CodeLenses and a side-by-side diff view. Nothing is written until you
|
||||
accept, and hunks whose lines you edited meanwhile are dropped safely.
|
||||
**Ask, Explain, Fix, Generate & Rewrite.** *Ask About the Selection* attaches the selection to your
|
||||
next message and puts the keyboard in the composer. *Explain* and *Fix Problems* send at once.
|
||||
*Generate* and *Rewrite* ask for their instruction in the panel, above the composer (Enter sends it,
|
||||
Esc puts it away, and the keyboard goes back to your text); while the model writes, the same place
|
||||
shows how far it is, with **Cancel**. The result is proposed hunks in the file, with *Accept* /
|
||||
*Reject* CodeLenses and a side-by-side diff view — and, in the panel, **Accept all**, **Reject all**
|
||||
and **Show as a diff**. Nothing is written until you accept, and hunks whose lines you edited
|
||||
meanwhile are dropped safely.
|
||||
|
||||
**Tunable Autocomplete.** Inline suggestions appear as you type and on `Alt+\` (Tab accepts, Escape
|
||||
dismisses). Use the **Tune** drawer in the chat header (or Settings) to slide **Max Tokens** from a
|
||||
few words up to a full file (`0`..`4096`), pick a prediction scope preset (`Auto`, `Few words`,
|
||||
`Single line`, `Function / block`, `Large / file`), and add custom **Autocomplete instructions**.
|
||||
dismisses). The panel's **Autocomplete** view holds all of it: on or off as you type, how much to
|
||||
suggest (`Auto`, a few words, one line, a function or block, a large part of the file), the most
|
||||
tokens (`0`..`4096`), the pause before asking, and your own instructions for suggestions.
|
||||
|
||||
**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), saved
|
||||
in your account or switched for this window only.
|
||||
**In the status bar.** The *LLeMbas* item says which autocomplete model is in use and whether
|
||||
suggestions are on, for when the panel is closed; a press opens the panel on **Models** (or, when
|
||||
there are no suggestions because no model is chosen or nobody is signed in, where that is put
|
||||
right).
|
||||
|
||||
**Files the agent shows.** Pictures appear inline in the chat. Other files appear with *Open* (only
|
||||
for display-only kinds whose bytes match their filename) or *Show in folder* for anything else. Files
|
||||
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.** The **Account** view says who this computer is signed in as. Type your server's
|
||||
address (nothing is predefined) and press **Sign in**: the CLI's own sign-in runs, the view shows
|
||||
the code to approve and where, with **Open the approval page** (your browser is opened when you
|
||||
press it, never by itself) and **Cancel**. 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 view 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, the certificate file is a field of the same view
|
||||
(`llembas.login.caFile`); with it the CLI always makes a new sign-in. **Sign out** signs the
|
||||
computer out, after asking in the view.
|
||||
|
||||
**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 a button to where it is put right; a turn that failed
|
||||
says why. The **Status** view has the agent's state, the program that is started and its version,
|
||||
the oldest version this needs, what your server asks for, what went wrong lately, what the agent
|
||||
last wrote on stderr (kept after it is gone), and **Restart the agent**. The same lines go to the
|
||||
*LLeMbas* channel of the Output panel.
|
||||
|
||||
## What stays outside the panel, and why
|
||||
|
||||
- **Inline suggestions** (ghost text at the cursor) — they are about the text you are typing.
|
||||
- **A rewrite's changes**: the marks in the file, the *Accept* / *Reject* CodeLenses above each
|
||||
change, and the editor's own diff view — a change is judged where the code is.
|
||||
- **The diff of an edit the agent asks about**, in the editor's diff view (the question itself is a
|
||||
card in the chat).
|
||||
- **The editor context menu, the keys and the command palette** — every command is still there, so
|
||||
keys can be bound to them; each one opens the panel where it belongs or does its work in the file.
|
||||
- **The status bar item** — one glance when the panel is closed; a press opens the panel.
|
||||
- **A line of the editor's own** (a notification with no button) when a command could not start in
|
||||
the editor: nothing selected, a rewrite already under way in that file.
|
||||
|
||||
## Commands and keys
|
||||
|
||||
| Command | Key | |
|
||||
|---|---|---|
|
||||
| LLeMbas: Open the Chat | `Ctrl+Alt+L` | |
|
||||
| LLeMbas: Ask About the Selection | `Ctrl+Alt+K` | also in editor context menu |
|
||||
| LLeMbas: Open the Chat | `Ctrl+Alt+L` | the panel on Chat, the keyboard in the composer |
|
||||
| LLeMbas: Ask About the Selection | `Ctrl+Alt+K` | also in editor context menu; type the question in the composer |
|
||||
| LLeMbas: Explain the Selection | | editor context menu |
|
||||
| LLeMbas: Fix Problems in This File | | editor context menu |
|
||||
| LLeMbas: Generate Code at Cursor | | editor context menu |
|
||||
| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in editor context menu |
|
||||
| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in editor context menu; the instruction is typed in the panel |
|
||||
| LLeMbas: Suggest a Completion Here | `Alt+\` | |
|
||||
| LLeMbas: Toggle Autocomplete as You Type | | |
|
||||
| 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 CodeLenses above each change |
|
||||
| LLeMbas: Show the Proposed Changes as a Diff | | |
|
||||
| LLeMbas: Open File from Project Index / Add File to Chat | | |
|
||||
| LLeMbas: New Session / Resume a Previous Session | | |
|
||||
| LLeMbas: Open a File of This Project | | a search beside the conversation |
|
||||
| LLeMbas: Add File to Chat | | an `@` in the composer, with the project's files listed under it |
|
||||
| LLeMbas: New Session | | |
|
||||
| LLeMbas: Resume a Previous Session | | the Sessions view, beside the conversation |
|
||||
| LLeMbas: Compact Session Context | | |
|
||||
| LLeMbas: Stop the Running Turn | | |
|
||||
| LLeMbas: Choose the Mode / Choose This Session's Model | | |
|
||||
| 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: Choose the Mode | | the keyboard on the mode list of the chat's header |
|
||||
| LLeMbas: Choose This Session's Model | | the Models view, beside the conversation |
|
||||
| LLeMbas: Models (Autocomplete, Chat and Rewrite) | | the Models view; also the status bar item |
|
||||
| LLeMbas: Choose the Autocomplete Model | | the Models view, on that list |
|
||||
| LLeMbas: Settings (in the Panel) | | the Settings view |
|
||||
| LLeMbas: Status of the Agent | | the Status view |
|
||||
| LLeMbas: Stop the Agent | | it starts again when it is needed (**Restart the agent** in Status stops it and starts it at once) |
|
||||
| LLeMbas: Sign In / Sign Out | | the Account view; the CLI's one sign-in for this computer |
|
||||
|
||||
On macOS the keys use `Cmd` in place of `Ctrl`.
|
||||
|
||||
## Settings
|
||||
|
||||
Each has a field in the panel (the view is named in the last column), and is an ordinary setting of
|
||||
the editor underneath.
|
||||
|
||||
| Setting | Default | |
|
||||
|---|---|---|
|
||||
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path (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) |
|
||||
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` |
|
||||
| `llembas.complete.debounce` | 250 | pause in milliseconds before requesting a completion |
|
||||
| `llembas.complete.maxTokens` | 0 | max tokens to predict (`0`: server default or preset; up to `4096`) |
|
||||
| `llembas.complete.length` | `auto` | prediction scope preset (`auto`, `words`, `line`, `block`, `file`) |
|
||||
| `llembas.complete.instructions` | `""` | custom instructions sent with autocomplete requests |
|
||||
| `llembas.rewrite.openDiff` | on | open diff view beside the file when a rewrite is proposed |
|
||||
| `llembas.media.maxMegabytes` | 64 | largest shown file accepted from the agent |
|
||||
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path (User level only) — *Settings* |
|
||||
| `llembas.login.caFile` | | the CA file of a server with a private certificate authority, for signing in (User level only) — *Account* |
|
||||
| `llembas.chat.sendEditorContext` | on | with each message: the file in front, the cursor, the selection, the problems shown there, and the paths of the other open tabs of this project (see *What is sent*) — *Settings* |
|
||||
| `llembas.chat.showThinking` | off | show collapsible model thinking blocks — *Settings* |
|
||||
| `llembas.chat.startMode` | | initial mode for a new session (User level only) — *Settings* |
|
||||
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` — *Autocomplete* |
|
||||
| `llembas.complete.debounce` | 250 | pause in milliseconds before requesting a completion — *Autocomplete* |
|
||||
| `llembas.complete.maxTokens` | 0 | the longest suggestion, in tokens (`0`: as the length says; up to `4096`) — *Autocomplete* |
|
||||
| `llembas.complete.length` | `auto` | how much a suggestion writes (`auto`, `words`, `line`, `block`, `file`) — *Autocomplete* |
|
||||
| `llembas.complete.instructions` | `""` | your own instructions for suggestions — *Autocomplete* |
|
||||
| `llembas.rewrite.openDiff` | on | open diff view beside the file when a rewrite is proposed — *Settings* |
|
||||
| `llembas.media.maxMegabytes` | 64 | largest shown file accepted from the agent — *Settings* |
|
||||
|
||||
## What is sent
|
||||
|
||||
Everything goes to the LLeMbas CLI on this computer, and from there to **your** LLeMbas server —
|
||||
nowhere else; the extension has no telemetry and fetches nothing.
|
||||
|
||||
- **What you send**: the message you type; a selection you ask about, have explained or
|
||||
rewritten; a file you name with `@`.
|
||||
- **With a message** (`llembas.chat.sendEditorContext`, on by default): the path of the file in
|
||||
front, the cursor's line, the selection, the problems the editor shows there, and the **paths**
|
||||
(not the text) of the other open tabs.
|
||||
- **With a suggestion** (autocomplete): the text around the cursor (about 12,000 characters before
|
||||
it and 4,000 after), the file's path and language, and the **text** of up to six other open
|
||||
files (the first 400 lines of each), of which the CLI puts pieces beside it.
|
||||
|
||||
What goes along without your pointing at it — the tab paths and the other files' text — is held
|
||||
to three rules, in both cases:
|
||||
|
||||
1. **Only files inside this window's folders.** A file open from somewhere else is never named or
|
||||
read for this, and with no folder open nothing of other files goes along.
|
||||
2. **Never a file that looks like it holds secrets**, by its name or its place: `.env` and
|
||||
`.env.*` (but not `.env.example`, `.env.sample`, `.env.template`), `*.env`, `*.pem`, `*.key`,
|
||||
`*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`, `id_rsa*`, `id_ed25519*`,
|
||||
`id_ecdsa*`, `id_dsa*`, `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
|
||||
`.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`,
|
||||
`.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`.
|
||||
3. **Never a file the project's `.gitignore` leaves out** (git is asked, once a file; a file git
|
||||
has not answered for yet is left out).
|
||||
|
||||
And **in a file that looks like it holds secrets no suggestion is asked for at all**, so nothing
|
||||
of it is sent; the editor says so once. A file the project ignores, or one outside the folders,
|
||||
still gets suggestions while you type in it: its own text around the cursor is what a suggestion
|
||||
is made from.
|
||||
|
||||
The agent itself reads and writes files as a turn needs them, under the CLI's permissions; that
|
||||
is the CLI's to allow or ask about, and is not limited by the rules above.
|
||||
|
||||
## Not there yet
|
||||
|
||||
- Sound, video, PDF and 3D files are not rendered inline in the chat: they appear with *Open*.
|
||||
- Sound, video and PDF files are not rendered inline in the chat: they appear with *Open*. Any
|
||||
other kind — a document, a program — can only be shown in its folder.
|
||||
- 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.
|
||||
- The effort of a conversation is shown (in **Models**) and cannot be changed from the editor: the
|
||||
CLI does not tell an editor which levels a model has.
|
||||
- A setting a folder of a multi-root workspace holds is shown as coming from that folder, and is
|
||||
changed there: the panel writes the User and the Workspace level.
|
||||
- In VS Code 1.85 itself, fields that stand side by side in a wide panel do not share their rows:
|
||||
it is built on Electron 25 with Chromium 114, and `subgrid` came with Chromium 117. From VS Code
|
||||
1.86 (Electron 27, Chromium 118) they do. In a narrow side bar fields are stacked either way.
|
||||
- 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.
|
||||
without one. The panel's page (`src/webview.js`, `media/chat.js`) builds elements with
|
||||
`createElement` and `textContent` only, under a strict Content-Security-Policy (no remote resource,
|
||||
no inline script or style); every colour comes from VS Code's theme variables, and high-contrast
|
||||
themes and "reduce motion" are respected.
|
||||
|
||||
- **The settings come from one table** (`src/settings.js`) made from the manifest: a setting that is
|
||||
contributed cannot be missing from the panel, and a test fails when the table and the manifest
|
||||
differ.
|
||||
- **What the page sends is checked against a schema** (`src/messages.js`) — type, shapes, lengths,
|
||||
enumerations — before anything is done. A setting is written only when it is one of the table,
|
||||
with a value of its declared type and range, at a level it has; a model or a session only when
|
||||
the server or the CLI listed it. A path typed in the panel is stored, never run: the CLI is
|
||||
started as one list of arguments, and a server's address is refused when the program would read
|
||||
it as an option.
|
||||
- **Forms line up by construction**: a field is always its four parts — label, control, hint, level
|
||||
— on the rows of the form it is in (`subgrid`), so two fields side by side keep their parts on
|
||||
the same lines whatever the text does; a track gives up its minimum before a 240 px side bar
|
||||
scrolls sideways; what is pressed is 28 px high.
|
||||
- The page says what happens to a screen reader (a turn began or ended, something waits for your
|
||||
answer, which view is in front), labels are tied to their controls, and everything in it can be
|
||||
reached with the keyboard.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
+782
-339
File diff suppressed because it is too large.
Load diff
+407
-84
@@ -1,10 +1,12 @@
|
||||
/* Every colour is one of the editor's theme variables. */
|
||||
html, body { height: 100%; }
|
||||
html, body { height: 100%; overflow: hidden; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100vh;
|
||||
display: grid;
|
||||
grid-template-rows: auto auto auto minmax(0, 1fr) auto;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: auto minmax(0, 1fr); /* the tab strip, then the one frame everything is in */
|
||||
color: var(--vscode-foreground);
|
||||
background: var(--vscode-sideBar-background);
|
||||
font-family: var(--vscode-font-family);
|
||||
@@ -12,8 +14,372 @@ body {
|
||||
line-height: 1.5;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
.chrome { min-width: 0; }
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
/* ---- The tab strip --------------------------------------------------------------------- */
|
||||
/* Seven equal tracks that give way before the frame does: nothing here has a width of its own. */
|
||||
|
||||
.tabs {
|
||||
min-width: 0;
|
||||
background: var(--vscode-sideBarSectionHeader-background, var(--vscode-sideBar-background));
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
}
|
||||
.tablist {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, minmax(0, 1fr));
|
||||
gap: 2px;
|
||||
padding: 3px 6px 0;
|
||||
}
|
||||
button.tab {
|
||||
display: grid;
|
||||
grid-auto-flow: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
height: 30px;
|
||||
padding: 0 2px;
|
||||
overflow: hidden;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-bottom: 2px solid transparent;
|
||||
border-radius: 4px 4px 0 0;
|
||||
}
|
||||
button.tab:hover {
|
||||
color: var(--vscode-foreground);
|
||||
background: var(--vscode-toolbar-hoverBackground);
|
||||
}
|
||||
button.tab[aria-selected="true"] {
|
||||
color: var(--vscode-foreground);
|
||||
border-bottom-color: var(--vscode-panelTitle-activeBorder, var(--vscode-focusBorder));
|
||||
}
|
||||
/* The view that is open beside the conversation: marked, not selected. */
|
||||
button.tab.is-beside {
|
||||
color: var(--vscode-foreground);
|
||||
border-bottom-color: var(--vscode-descriptionForeground);
|
||||
border-bottom-style: dashed;
|
||||
}
|
||||
.tab-icon { flex: none; }
|
||||
/* Something in the conversation waits for an answer while another view has the frame. */
|
||||
button.tab.needs-you {
|
||||
color: var(--vscode-editorWarning-foreground);
|
||||
border-bottom-color: var(--vscode-editorWarning-foreground);
|
||||
}
|
||||
/* Too narrow for words: the label stays the tab's name for a screen reader, and its tooltip. */
|
||||
.tab-label { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
|
||||
@media (min-width: 680px) {
|
||||
.tab-label { position: static; width: auto; height: auto; margin: 0; clip: auto; text-overflow: ellipsis; font-size: 0.9em; }
|
||||
}
|
||||
|
||||
/* ---- The frame: one view, or the conversation with one view beside it ------------------- */
|
||||
|
||||
.stage {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.view { min-width: 0; min-height: 0; }
|
||||
.chat-view {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: auto minmax(0, 1fr) auto;
|
||||
}
|
||||
.pane {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: auto minmax(0, 1fr);
|
||||
overflow: hidden;
|
||||
background: var(--vscode-sideBar-background);
|
||||
}
|
||||
.pane:focus { outline: none; }
|
||||
.stage.split { grid-template-rows: minmax(0, 1fr) minmax(0, 1fr); }
|
||||
.stage.split .pane { border-top: 2px solid var(--vscode-panelTitle-activeBorder, var(--vscode-focusBorder)); }
|
||||
@media (min-width: 640px) {
|
||||
.stage.split {
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
.stage.split .pane {
|
||||
border-top: 0;
|
||||
border-left: 2px solid var(--vscode-panelTitle-activeBorder, var(--vscode-focusBorder));
|
||||
}
|
||||
}
|
||||
.pane-head {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
min-height: 36px;
|
||||
padding: 4px 10px;
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
}
|
||||
.pane-title {
|
||||
margin: 0;
|
||||
font-size: 0.95em;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.pane-close { display: none; }
|
||||
.stage.split .pane-close { display: inline-block; }
|
||||
.pane-body {
|
||||
min-width: 0;
|
||||
padding: 10px;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.pane-status {
|
||||
margin: 0 0 8px;
|
||||
min-height: 1.5em;
|
||||
font-size: 0.9em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.pane-status.error { color: var(--vscode-errorForeground); }
|
||||
.pane-status:empty { display: none; }
|
||||
.pane-note {
|
||||
margin: 8px 0;
|
||||
font-size: 0.88em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.pane-note:empty { display: none; }
|
||||
.pane-tools {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
|
||||
gap: 6px;
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
.pane-tools input { grid-column: 1 / -1; margin: 0; }
|
||||
.pane-tools button { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.pane-actions {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 120px), 1fr));
|
||||
gap: 6px;
|
||||
margin: 4px 0 10px;
|
||||
}
|
||||
.pane-actions button { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
h3.group {
|
||||
margin: 12px 0 8px;
|
||||
padding-bottom: 3px;
|
||||
font-size: 0.82em;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
}
|
||||
.pane-body > h3.group:first-child { margin-top: 0; }
|
||||
|
||||
/* ---- Forms: every field is label, control, hint, level — on the form's own rows ---------- */
|
||||
/* The form is the grid; a field takes four of its rows and hands them on (subgrid), so two
|
||||
fields side by side have their labels, controls, hints and levels on the same lines whatever
|
||||
the text in either does. A track gives up its minimum before the frame scrolls sideways. */
|
||||
|
||||
.form {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 230px), 1fr));
|
||||
column-gap: 14px;
|
||||
row-gap: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.field {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-rows: subgrid;
|
||||
grid-row: span 4;
|
||||
min-width: 0;
|
||||
padding-bottom: 14px;
|
||||
}
|
||||
.f-label {
|
||||
font-size: 0.92em;
|
||||
font-weight: 600;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.f-control {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
align-content: start;
|
||||
min-width: 0;
|
||||
min-height: 28px;
|
||||
margin-top: 3px;
|
||||
}
|
||||
.f-control input[type="text"], .f-control input[type="number"], .f-control textarea, .pane-body .q-input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
padding: 2px 8px;
|
||||
margin: 0;
|
||||
color: var(--vscode-input-foreground);
|
||||
background: var(--vscode-input-background);
|
||||
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
|
||||
border-radius: 4px;
|
||||
}
|
||||
.f-control textarea { height: auto; min-height: 64px; resize: vertical; }
|
||||
.f-control textarea:focus { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; }
|
||||
.f-control .mono { font-family: var(--vscode-editor-font-family); }
|
||||
.f-control input:invalid { border-color: var(--vscode-inputValidation-errorBorder, var(--vscode-errorForeground)); }
|
||||
/* On or off: a switch of a known size, 28 px high. */
|
||||
.f-control input[type="checkbox"] {
|
||||
appearance: none;
|
||||
position: relative;
|
||||
width: 48px;
|
||||
height: 28px;
|
||||
margin: 0;
|
||||
cursor: pointer;
|
||||
background: var(--vscode-input-background);
|
||||
border: 1px solid var(--vscode-contrastBorder, var(--vscode-descriptionForeground));
|
||||
border-radius: 99px;
|
||||
}
|
||||
.f-control input[type="checkbox"]::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
left: 3px;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 99px;
|
||||
background: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.f-control input[type="checkbox"]:checked {
|
||||
background: var(--vscode-button-background);
|
||||
border-color: var(--vscode-contrastActiveBorder, var(--vscode-button-background));
|
||||
}
|
||||
.f-control input[type="checkbox"]:checked::before {
|
||||
left: 23px;
|
||||
background: var(--vscode-button-foreground);
|
||||
}
|
||||
.f-control input[type="checkbox"]:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: 2px; }
|
||||
.f-hint {
|
||||
margin: 4px 0 0;
|
||||
font-size: 0.86em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.f-key {
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.92em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.f-level {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 4px 6px;
|
||||
align-items: center;
|
||||
margin-top: 5px;
|
||||
font-size: 0.86em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.f-level:empty { margin-top: 0; }
|
||||
.f-origin { grid-column: 1 / -1; overflow-wrap: anywhere; }
|
||||
.f-origin:empty { display: none; }
|
||||
.f-fixed { overflow-wrap: anywhere; }
|
||||
|
||||
/* ---- Lists in a pane: sessions, files, problems ------------------------------------------ */
|
||||
|
||||
.rows { display: grid; grid-template-columns: minmax(0, 1fr); gap: 4px; }
|
||||
.row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
min-height: 40px;
|
||||
padding: 3px 6px;
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 5px;
|
||||
}
|
||||
.row.current { border-color: var(--vscode-focusBorder); }
|
||||
.row.plain-row { min-height: 0; padding: 5px 8px; font-size: 0.9em; overflow-wrap: anywhere; }
|
||||
.row.plain-row.error { color: var(--vscode-errorForeground); }
|
||||
button.row-main {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 1px;
|
||||
height: auto;
|
||||
min-height: 32px;
|
||||
min-width: 0;
|
||||
padding: 2px 4px;
|
||||
text-align: left;
|
||||
white-space: normal;
|
||||
color: var(--vscode-foreground);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
}
|
||||
button.row-main:hover { background: var(--vscode-list-hoverBackground, var(--vscode-toolbar-hoverBackground)); }
|
||||
.row-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.row-detail { font-size: 0.84em; color: var(--vscode-descriptionForeground); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.row-buttons { display: flex; gap: 4px; }
|
||||
.row[aria-selected="true"] { background: var(--vscode-list-activeSelectionBackground); color: var(--vscode-list-activeSelectionForeground); }
|
||||
|
||||
.facts {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 8.5em) minmax(0, 1fr);
|
||||
gap: 5px 10px;
|
||||
margin: 0 0 8px;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
.facts dt { font-weight: 600; color: var(--vscode-descriptionForeground); overflow-wrap: anywhere; }
|
||||
.facts dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.facts dd.warn { color: var(--vscode-editorWarning-foreground); }
|
||||
.facts dd.error { color: var(--vscode-errorForeground); }
|
||||
.stderr { max-height: 16em; overflow: auto; font-size: 0.86em; }
|
||||
.stderr:empty::before { content: "Nothing."; color: var(--vscode-descriptionForeground); }
|
||||
|
||||
/* ---- Account: the steps of a sign-in, as cards ------------------------------------------- */
|
||||
|
||||
.flow { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; margin: 0 0 10px; }
|
||||
.flow:empty { display: none; }
|
||||
.flow .card .title { font-family: var(--vscode-font-family); }
|
||||
.code-big {
|
||||
margin: 6px 0;
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 1.5em;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.12em;
|
||||
overflow-wrap: anywhere;
|
||||
user-select: all;
|
||||
}
|
||||
|
||||
/* ---- What an editor command left to be answered, above the composer ---------------------- */
|
||||
|
||||
.tasks { display: grid; grid-template-columns: minmax(0, 1fr); gap: 6px; margin-bottom: 6px; }
|
||||
.task {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
gap: 5px;
|
||||
padding: 7px 8px;
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-input-background));
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-left: 3px solid var(--vscode-editorInfo-foreground, var(--vscode-charts-blue));
|
||||
border-radius: 5px;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
.task-title { font-weight: 600; overflow-wrap: anywhere; }
|
||||
.task-detail { color: var(--vscode-descriptionForeground); overflow-wrap: anywhere; }
|
||||
.task .q-input { margin-top: 0; }
|
||||
.task-buttons { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
|
||||
button.linkish {
|
||||
height: auto;
|
||||
min-height: 28px;
|
||||
padding: 0 2px;
|
||||
color: var(--vscode-textLink-foreground);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
text-align: left;
|
||||
text-decoration: underline;
|
||||
white-space: normal;
|
||||
}
|
||||
button.linkish:hover { color: var(--vscode-textLink-activeForeground); background: transparent; }
|
||||
button.model-btn { min-width: 0; padding: 0 8px; text-align: left; }
|
||||
.model-name { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
/* ---- Header bar ------------------------------------------------------------------------ */
|
||||
|
||||
.bar {
|
||||
@@ -52,6 +418,8 @@ body {
|
||||
}
|
||||
.bar-btns {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
@@ -95,7 +463,7 @@ select, button, textarea, input { font: inherit; }
|
||||
select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 26px;
|
||||
height: 28px;
|
||||
padding: 0 6px;
|
||||
color: var(--vscode-dropdown-foreground);
|
||||
background: var(--vscode-dropdown-background);
|
||||
@@ -103,7 +471,7 @@ select {
|
||||
border-radius: 4px;
|
||||
}
|
||||
button {
|
||||
height: 26px;
|
||||
height: 28px;
|
||||
padding: 0 10px;
|
||||
color: var(--vscode-button-foreground);
|
||||
background: var(--vscode-button-background);
|
||||
@@ -119,11 +487,21 @@ button.second {
|
||||
}
|
||||
button.second:hover { background: var(--vscode-button-secondaryHoverBackground); }
|
||||
button.icon-btn {
|
||||
height: 24px;
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
font-size: 0.88em;
|
||||
}
|
||||
/* Small to look at, 28 px to press: the part outside the drawn button takes the press too. */
|
||||
button.mini::after, button.plain::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: -4px;
|
||||
right: 0;
|
||||
bottom: -4px;
|
||||
left: 0;
|
||||
}
|
||||
button.mini {
|
||||
position: relative;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
font-size: 0.82em;
|
||||
@@ -137,6 +515,7 @@ button.mini:hover {
|
||||
background: var(--vscode-toolbar-hoverBackground);
|
||||
}
|
||||
button.plain {
|
||||
position: relative;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
@@ -151,82 +530,6 @@ select:focus, button:focus-visible, textarea:focus, input:focus, .link:focus-vis
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
/* ---- Settings / Autocomplete Tune Drawer ----------------------------------------------- */
|
||||
|
||||
.settings-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 8px 10px;
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background));
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.sp-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.sp-label {
|
||||
font-size: 0.88em;
|
||||
font-weight: 600;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.sp-val {
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.86em;
|
||||
padding: 0 6px;
|
||||
border-radius: 99px;
|
||||
background: var(--vscode-badge-background);
|
||||
color: var(--vscode-badge-foreground);
|
||||
}
|
||||
.sp-slider {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
accent-color: var(--vscode-button-background);
|
||||
cursor: pointer;
|
||||
}
|
||||
.sp-presets {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
.preset-btn.active {
|
||||
color: var(--vscode-button-foreground);
|
||||
background: var(--vscode-button-background);
|
||||
border-color: var(--vscode-button-background);
|
||||
}
|
||||
.sp-grid {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
.sp-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.sp-checks {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.sp-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 0.88em;
|
||||
color: var(--vscode-foreground);
|
||||
cursor: pointer;
|
||||
}
|
||||
.sp-check input {
|
||||
margin: 0;
|
||||
accent-color: var(--vscode-button-background);
|
||||
}
|
||||
|
||||
/* ---- Subagent / Team strip ------------------------------------------------------------- */
|
||||
|
||||
.team-bar {
|
||||
@@ -664,7 +967,7 @@ pre {
|
||||
.q-block { margin: 0 0 10px; }
|
||||
.q-header { font-size: 0.82em; font-weight: 600; text-transform: uppercase; letter-spacing: 0.03em; color: var(--vscode-descriptionForeground); }
|
||||
.q-options { display: flex; flex-wrap: wrap; gap: 5px; margin: 5px 0 6px; }
|
||||
.q-opt { height: auto; min-height: 26px; padding: 3px 9px; white-space: normal; text-align: left; }
|
||||
.q-opt { height: auto; min-height: 28px; padding: 3px 9px; white-space: normal; text-align: left; }
|
||||
.q-input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
@@ -693,7 +996,7 @@ pre {
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
min-height: 26px;
|
||||
min-height: 28px;
|
||||
margin-top: 4px;
|
||||
font-size: 0.9em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
@@ -762,6 +1065,7 @@ footer {
|
||||
|
||||
.attached {
|
||||
display: grid;
|
||||
min-height: 28px;
|
||||
grid-template-columns: minmax(0, 1fr) 22px;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
@@ -801,7 +1105,7 @@ textarea::placeholder { color: var(--vscode-input-placeholderForeground); }
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
min-height: 26px;
|
||||
min-height: 28px;
|
||||
margin-top: 6px;
|
||||
padding-top: 6px;
|
||||
border-top: 1px solid var(--vscode-panel-border);
|
||||
@@ -840,3 +1144,22 @@ 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; }
|
||||
|
||||
/* ---- High contrast, and no motion where none is wanted ----------------------------------- */
|
||||
|
||||
.vscode-high-contrast button.tab[aria-selected="true"], .vscode-high-contrast-light button.tab[aria-selected="true"] {
|
||||
outline: 1px solid var(--vscode-contrastActiveBorder);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.vscode-high-contrast .row, .vscode-high-contrast .task, .vscode-high-contrast-light .row, .vscode-high-contrast-light .task {
|
||||
border-color: var(--vscode-contrastBorder);
|
||||
}
|
||||
button.tab:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: -2px; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; }
|
||||
}
|
||||
+976
-158
File diff suppressed because it is too large.
Load diff
+29
-17
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"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.",
|
||||
"description": "LLeMbas in your editor, in one side panel: chat with the agent, ask about a selection, have it rewritten as a diff, autocomplete, and every setting — a client of the LLeMbas CLI.",
|
||||
"version": "0.0.0",
|
||||
"publisher": "llembas",
|
||||
"icon": "media/logo.png",
|
||||
@@ -43,7 +43,7 @@
|
||||
{ "command": "llembas.rewrite", "title": "Rewrite the Selection", "category": "LLeMbas" },
|
||||
{ "command": "llembas.complete", "title": "Suggest a Completion Here", "category": "LLeMbas" },
|
||||
{ "command": "llembas.toggleAutocomplete", "title": "Toggle Autocomplete as You Type", "category": "LLeMbas" },
|
||||
{ "command": "llembas.openFile", "title": "Open File from Project Index", "category": "LLeMbas" },
|
||||
{ "command": "llembas.openFile", "title": "Open a File of This Project", "category": "LLeMbas" },
|
||||
{ "command": "llembas.addFile", "title": "Add File to Chat", "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" },
|
||||
@@ -52,10 +52,13 @@
|
||||
{ "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.modelSettings", "title": "Models (Autocomplete, Chat and Rewrite)", "category": "LLeMbas" },
|
||||
{ "command": "llembas.settings", "title": "Settings (in the Panel)", "category": "LLeMbas" },
|
||||
{ "command": "llembas.status", "title": "Status of the Agent", "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", "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 +81,10 @@
|
||||
{ "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.settings", "when": "view == llembas.chat", "group": "llembas@5" },
|
||||
{ "command": "llembas.signIn", "when": "view == llembas.chat", "group": "llembas@6" },
|
||||
{ "command": "llembas.status", "when": "view == llembas.chat", "group": "llembas@7" },
|
||||
{ "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@8" }
|
||||
],
|
||||
"commandPalette": [
|
||||
{ "command": "llembas.acceptChange", "when": "llembas.hasProposal" },
|
||||
@@ -95,12 +101,18 @@
|
||||
"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."
|
||||
"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`. The server, the sign-in, the models and the permissions are the CLI's own: the panel shows and changes them through the CLI, and none of them is stored in the editor's settings."
|
||||
},
|
||||
"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,
|
||||
"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."
|
||||
"description": "Tell the agent, with each message you type, which file is in front, where the cursor is, what is selected, the problems the editor shows there, and the paths of the other open tabs. Only tabs of files inside this window's folders are named, and never a file that looks like it holds secrets (.env, keys, credentials) or that the project's .gitignore leaves out."
|
||||
},
|
||||
"llembas.chat.showThinking": {
|
||||
"type": "boolean",
|
||||
@@ -116,7 +128,7 @@
|
||||
"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\"."
|
||||
"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 in the LLeMbas panel under Models. A request sends your server the text around the cursor and pieces of up to six other open files of this window's folders; never a file that looks like it holds secrets (.env, keys, credentials) or that the project's .gitignore leaves out, and in such a file no suggestion is asked for at all."
|
||||
},
|
||||
"llembas.complete.debounce": {
|
||||
"type": "number",
|
||||
@@ -130,25 +142,25 @@
|
||||
"default": 0,
|
||||
"minimum": 0,
|
||||
"maximum": 4096,
|
||||
"description": "Maximum tokens to predict for autocomplete (0: server default or preset; e.g. 24 for a few words, 256 for a block, 2048 for a large file section)."
|
||||
"description": "The longest suggestion, in tokens. 0: as the length setting says."
|
||||
},
|
||||
"llembas.complete.length": {
|
||||
"type": "string",
|
||||
"default": "auto",
|
||||
"enum": ["auto", "words", "line", "block", "file"],
|
||||
"enumDescriptions": [
|
||||
"Use the server's default prediction length",
|
||||
"Few words — finish the current expression or identifier (~24 tokens)",
|
||||
"Single line — finish the current line (~64 tokens)",
|
||||
"Function / block — complete a block or function (~256 tokens)",
|
||||
"Large / file — predict a large multi-block or full-file continuation (~2048 tokens)"
|
||||
"As the server sets it",
|
||||
"A few words (about 24 tokens)",
|
||||
"One line (about 64 tokens)",
|
||||
"A function or block (about 256 tokens)",
|
||||
"A long passage (about 2048 tokens)"
|
||||
],
|
||||
"description": "How much code autocomplete should aim to predict, paired with guidance instructions."
|
||||
"description": "How much a suggestion writes."
|
||||
},
|
||||
"llembas.complete.instructions": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"description": "Custom instructions sent with autocomplete requests (e.g. style, brevity, or scope guidance)."
|
||||
"description": "Your own instructions for suggestions, for example about style."
|
||||
},
|
||||
"llembas.rewrite.openDiff": {
|
||||
"type": "boolean",
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
'use strict';
|
||||
// The sign-in as the panel's Account view shows it: who this computer is signed in as, and a
|
||||
// sign-in or sign-out under way, step by step. Every step that used to be a question of the
|
||||
// editor's (which address, replace the login there is, sign out) is a state here that the page
|
||||
// draws and answers. The work itself is `lembas login --json` and `lembas logout` (src/login.js).
|
||||
// No `vscode` here.
|
||||
const { EventEmitter } = require('node:events');
|
||||
const loginModule = require('./login');
|
||||
const { serverAddress } = require('./messages');
|
||||
const { WORDS, say } = require('./words');
|
||||
|
||||
class Account extends EventEmitter {
|
||||
/**
|
||||
* @param {{ command: () => string, commandName?: () => string, ca?: () => string, env?: object,
|
||||
* login?: typeof loginModule, killAfterMs?: number }} io
|
||||
* Events: `change`, `signedIn (done)`, `signedOut (message)`.
|
||||
*/
|
||||
constructor(io) {
|
||||
super();
|
||||
this.io = io;
|
||||
this.login = io.login || loginModule;
|
||||
this.server = '';
|
||||
this.checked = false;
|
||||
this.checking = false;
|
||||
this.flow = null;
|
||||
this.run = null;
|
||||
this.step = 0; // a newer step makes an older one's late answer nothing
|
||||
}
|
||||
|
||||
/** What the page is told. */
|
||||
state() {
|
||||
return { checked: this.checked, checking: this.checking, server: this.server, busy: !!this.run, flow: this.flow ? { ...this.flow } : null };
|
||||
}
|
||||
|
||||
_set(flow) {
|
||||
this.flow = flow;
|
||||
this.emit('change');
|
||||
}
|
||||
|
||||
_ca() {
|
||||
return String((this.io.ca && this.io.ca()) || '').trim();
|
||||
}
|
||||
|
||||
async _current() {
|
||||
this.checking = true;
|
||||
this.emit('change');
|
||||
let now = '';
|
||||
try {
|
||||
now = await this.login.current(this.io.command(), this.io.env);
|
||||
} catch {
|
||||
now = '';
|
||||
}
|
||||
this.checking = false;
|
||||
this.checked = true;
|
||||
this.server = now;
|
||||
return now;
|
||||
}
|
||||
|
||||
/** Read anew whose sign-in this computer has. */
|
||||
async refresh() {
|
||||
if (this.checking || this.run) return this.server;
|
||||
const now = await this._current();
|
||||
this.emit('change');
|
||||
return now;
|
||||
}
|
||||
|
||||
/** Sign in to `address`. A sign-in there already is is asked about first (`confirm`). */
|
||||
async begin(address) {
|
||||
if (this.run) return false;
|
||||
const server = serverAddress(address);
|
||||
if (!server) {
|
||||
this._set({ stage: 'error', message: "Type your LLeMbas server's address: the one you open LLeMbas at in the browser." });
|
||||
return false;
|
||||
}
|
||||
const step = ++this.step;
|
||||
this.flow = { stage: 'checking', server };
|
||||
const now = await this._current();
|
||||
if (step !== this.step) return false;
|
||||
// The same server again, without a certificate: the CLI reads its login anew and replaces nothing.
|
||||
if (now && !(this.login.sameServer(now, server) && !this._ca())) {
|
||||
this._set({ stage: 'confirm', server, replaces: now });
|
||||
return false;
|
||||
}
|
||||
return this._run(server);
|
||||
}
|
||||
|
||||
/** The answer to "replace the sign-in there is?": yes. */
|
||||
confirm() {
|
||||
if (this.run || !this.flow || this.flow.stage !== 'confirm') return false;
|
||||
return this._run(this.flow.server);
|
||||
}
|
||||
|
||||
_run(server) {
|
||||
const step = ++this.step;
|
||||
const ca = this._ca();
|
||||
this._set({ stage: 'starting', server });
|
||||
const run = this.login.signIn({
|
||||
command: this.io.command(),
|
||||
address: server,
|
||||
ca: ca || undefined,
|
||||
env: this.io.env,
|
||||
killAfterMs: this.io.killAfterMs,
|
||||
onCode: (ev) => {
|
||||
if (step !== this.step) return;
|
||||
const where = String((ev.instance && (ev.instance.name || ev.instance.base_url)) || server);
|
||||
// Only a web address is ever handed to the browser, whatever the program printed.
|
||||
const url = this.login.webAddress(ev.verification_uri_complete) || this.login.webAddress(ev.verification_uri);
|
||||
const minutes = Number(ev.expires_in) > 0 ? Math.max(1, Math.round(Number(ev.expires_in) / 60)) : 0;
|
||||
this._set({ stage: 'code', server, where, code: String(ev.user_code || ''), page: String(ev.verification_uri || ''), canOpen: !!url, url, minutes });
|
||||
},
|
||||
});
|
||||
this.run = run;
|
||||
return run.result.then(
|
||||
(r) => this._ended(step, run, server, r),
|
||||
(e) => this._ended(step, run, server, { ok: false, error: { message: String((e && e.message) || e) } }),
|
||||
);
|
||||
}
|
||||
|
||||
_ended(step, run, server, r) {
|
||||
if (this.run === run) this.run = null;
|
||||
if (step !== this.step) return false;
|
||||
if (r.ok) {
|
||||
this.server = String(r.done.base_url || server);
|
||||
this.checked = true;
|
||||
this._set({ stage: 'done', server: this.server, models: Number.isFinite(r.done.models) ? r.done.models : null });
|
||||
this.emit('signedIn', r.done);
|
||||
return true;
|
||||
}
|
||||
if (r.cancelled) {
|
||||
this._set({ stage: 'cancelled', server });
|
||||
return false;
|
||||
}
|
||||
const name = String((this.io.commandName && this.io.commandName()) || 'lembas');
|
||||
const why = r.error && r.error.code === 'not_found' ? WORDS.not_found(name) : say(r.error);
|
||||
this._set({ stage: 'error', server, message: 'Not signed in: ' + why });
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Stop the sign-in under way, or take back a question not yet answered. */
|
||||
cancel() {
|
||||
if (this.run) return this.run.cancel();
|
||||
this.step++;
|
||||
if (this.flow && this.flow.stage !== 'done' && this.flow.stage !== 'out') this._set(this.flow.stage === 'checking' ? { stage: 'cancelled', server: this.flow.server } : null);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The address the page's "Open the approval page" button opens, or ''. */
|
||||
approvalUrl() {
|
||||
return this.flow && this.flow.stage === 'code' && this.flow.url ? this.flow.url : '';
|
||||
}
|
||||
|
||||
/** Sign out: asked first, saying whose sign-in goes. */
|
||||
async askSignOut() {
|
||||
if (this.run) return false;
|
||||
const step = ++this.step;
|
||||
const now = await this._current();
|
||||
if (step !== this.step) return false;
|
||||
if (!now) this._set({ stage: 'note', message: 'This computer is not signed in to a server.' });
|
||||
else this._set({ stage: 'confirmOut', server: now });
|
||||
return !!now;
|
||||
}
|
||||
|
||||
async confirmSignOut() {
|
||||
if (this.run || !this.flow || this.flow.stage !== 'confirmOut') return false;
|
||||
const step = ++this.step;
|
||||
const was = this.flow.server;
|
||||
this._set({ stage: 'leaving', server: was });
|
||||
const r = await this.login.signOut(this.io.command(), this.io.env);
|
||||
if (step !== this.step) return false;
|
||||
if (!r.ok) {
|
||||
this._set({ stage: 'error', server: was, message: 'Not signed out: ' + r.message });
|
||||
return false;
|
||||
}
|
||||
this.server = '';
|
||||
const message = r.message || `Signed out of ${was}.`;
|
||||
this._set({ stage: 'out', message });
|
||||
this.emit('signedOut', message);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Put away a result that has been read. */
|
||||
dismiss() {
|
||||
if (this.run) return;
|
||||
this.step++;
|
||||
this._set(null);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
if (this.run) this.run.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Account };
|
||||
+114
-26
@@ -4,28 +4,62 @@
|
||||
// No `vscode` here.
|
||||
const { EventEmitter } = require('node:events');
|
||||
const childProcess = require('node:child_process');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { Rpc, RpcError } = require('./rpc');
|
||||
const { MIN_CLI, WORDS, compareVersions } = require('./words');
|
||||
|
||||
const PROTOCOL_VERSION = 1;
|
||||
const START_TIMEOUT_MS = 10000; // how long the agent has to answer `initialize`
|
||||
const KILL_AFTER_MS = 5000; // an agent that was asked to stop and is still there is killed
|
||||
const STDERR_LINES = 40;
|
||||
|
||||
/**
|
||||
* The command to start: as set. A bare `lembas` that is not on this editor's PATH (an editor
|
||||
* started from the desktop does not always have the shell's) is looked for where the CLI's
|
||||
* installer puts it.
|
||||
*/
|
||||
function resolveCommand(command, env, home) {
|
||||
if (command !== 'lembas') return command;
|
||||
const dirs = String((env && env.PATH) || '').split(path.delimiter).filter(Boolean);
|
||||
const names = process.platform === 'win32' ? ['lembas.exe', 'lembas.cmd', 'lembas'] : ['lembas'];
|
||||
for (const dir of dirs) for (const name of names) if (isProgram(path.join(dir, name))) return command;
|
||||
const fallback = path.join(home || os.homedir(), '.local', 'bin', 'lembas');
|
||||
return isProgram(fallback) ? fallback : command;
|
||||
}
|
||||
|
||||
function isProgram(file) {
|
||||
try {
|
||||
fs.accessSync(file, fs.constants.X_OK);
|
||||
return fs.statSync(file).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
class Agent extends EventEmitter {
|
||||
/**
|
||||
* @param {{ command: string, args?: string[], cwd?: string, env?: object,
|
||||
* @param {{ command: string, args?: string[], cwd?: string, env?: object, home?: string,
|
||||
* clientInfo?: { name: string, version: string }, writeTextFile?: boolean,
|
||||
* startTimeoutMs?: number, killAfterMs?: number,
|
||||
* onRequest?: (method: string, params: any) => any }} options
|
||||
* Events: `notify (method, params)`, `stderr (text)`, `exit ({ code, last })`.
|
||||
* Events: `notify (method, params)`, `stderr (text)`, `exit ({ code, signal, last, started })`.
|
||||
*/
|
||||
constructor(options) {
|
||||
super();
|
||||
this.options = options;
|
||||
this.capabilities = new Set();
|
||||
this.info = null;
|
||||
this.version = '';
|
||||
this.ready = false;
|
||||
this.stopped = false;
|
||||
this.gone = false;
|
||||
this.stderr = [];
|
||||
this.proc = null;
|
||||
this.rpc = null;
|
||||
this.starting = null;
|
||||
this.killer = null;
|
||||
}
|
||||
|
||||
/** Start the process and say hello. The same promise for every caller. */
|
||||
@@ -34,6 +68,16 @@ class Agent extends EventEmitter {
|
||||
return this.starting;
|
||||
}
|
||||
|
||||
_keep(text) {
|
||||
for (const line of String(text).split(/\r?\n/)) if (line.trim()) this.stderr.push(line);
|
||||
while (this.stderr.length > STDERR_LINES) this.stderr.shift();
|
||||
}
|
||||
|
||||
/** The last thing the agent wrote on stderr, or ''. */
|
||||
get lastWords() {
|
||||
return this.stderr.length ? this.stderr[this.stderr.length - 1] : '';
|
||||
}
|
||||
|
||||
_start() {
|
||||
const o = this.options;
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -46,17 +90,20 @@ class Agent extends EventEmitter {
|
||||
reject(new Error(message));
|
||||
}
|
||||
};
|
||||
const env = o.env || process.env;
|
||||
const command = resolveCommand(o.command, env, o.home);
|
||||
let proc;
|
||||
try {
|
||||
proc = childProcess.spawn(o.command, o.args || ['serve', '--stdio'], {
|
||||
proc = childProcess.spawn(command, o.args || ['serve', '--stdio'], {
|
||||
cwd: o.cwd,
|
||||
env: o.env || process.env,
|
||||
env,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
});
|
||||
} catch (e) {
|
||||
return fail(`could not start ${o.command}: ${e.message}`);
|
||||
this.gone = true;
|
||||
return fail(`${WORDS.not_found(o.command)} (${e.message})`);
|
||||
}
|
||||
this.proc = proc;
|
||||
this.rpc = new Rpc({
|
||||
@@ -66,73 +113,102 @@ class Agent extends EventEmitter {
|
||||
return o.onRequest(method, params);
|
||||
},
|
||||
onNotify: (method, params) => this.emit('notify', method, params),
|
||||
onStray: (line) => {
|
||||
this._keep('[stdout] ' + line);
|
||||
this.emit('stderr', '[stdout] ' + line + '\n');
|
||||
},
|
||||
});
|
||||
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._keep(text);
|
||||
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.gone = true;
|
||||
this._unkill();
|
||||
const why = e.code === 'ENOENT' || e.code === 'EACCES' ? WORDS.not_found(o.command) : `Could not start ${o.command}: ${e.message}.`;
|
||||
fail(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 last = this.lastWords;
|
||||
const was = this.ready;
|
||||
this.ready = false;
|
||||
this.gone = true;
|
||||
this._unkill();
|
||||
fail(`the agent stopped (${signal || 'exit ' + code})${last ? ': ' + last : ''}`);
|
||||
this.emit('exit', { code, signal, last, started: was });
|
||||
});
|
||||
const limit = o.startTimeoutMs || START_TIMEOUT_MS;
|
||||
this.rpc
|
||||
.request('initialize', {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
clientCapabilities: {
|
||||
// Unsaved text: reading always; writing only where the editor can put the text into the
|
||||
// open document and save it before it answers.
|
||||
fs: { readTextFile: true, writeTextFile: !!o.writeTextFile },
|
||||
// `protocol: 2` enables `_lembas/question`, `_lembas/plan`, and `_lembas/event`.
|
||||
// `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: { protocol: 2, editor: true, media: true, show: true } },
|
||||
.request(
|
||||
'initialize',
|
||||
{
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
clientCapabilities: {
|
||||
// Unsaved text: reading always; writing only where the editor can put the text into the
|
||||
// open document and save it before it answers.
|
||||
fs: { readTextFile: true, writeTextFile: !!o.writeTextFile },
|
||||
// `protocol: 3`: LLeMbas CLI 2.0's own (question and plan cards come with 2 or later).
|
||||
// `show` with `media`: the show tool is offered to a client that says `show`, and
|
||||
// hands over files that are not text to one that also says `media`.
|
||||
_meta: { lembas: { protocol: 3, editor: true, media: true, show: true } },
|
||||
},
|
||||
clientInfo: o.clientInfo || { name: 'llembas-vscode', version: '0' },
|
||||
},
|
||||
clientInfo: o.clientInfo || { name: 'llembas-vscode', version: '0' },
|
||||
})
|
||||
limit,
|
||||
)
|
||||
.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.version = r && r.agentInfo && typeof r.agentInfo.version === 'string' ? r.agentInfo.version : '';
|
||||
this.ready = true;
|
||||
settled = true;
|
||||
resolve(this);
|
||||
},
|
||||
(e) => {
|
||||
if (settled) return;
|
||||
const last = this.lastWords;
|
||||
this.stop();
|
||||
fail('the agent refused to start: ' + e.message);
|
||||
const what = e.timeout ? WORDS.no_answer(Math.round(limit / 1000)) : 'The agent refused to start: ' + e.message + '.';
|
||||
fail(what + (last ? ' Its last words: ' + last : ''));
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/** The sentence for a CLI older than this needs, or '' when it is new enough (or says no version). */
|
||||
get tooOld() {
|
||||
return this.version && compareVersions(this.version, MIN_CLI) === -1 ? WORDS.cli_too_old(this.version, MIN_CLI) : '';
|
||||
}
|
||||
|
||||
has(capability) {
|
||||
return this.capabilities.has(capability);
|
||||
}
|
||||
|
||||
request(method, params) {
|
||||
request(method, params, timeoutMs) {
|
||||
if (!this.rpc || this.stopped) return Promise.reject(new RpcError({ code: -32000, message: 'the agent is not running' }));
|
||||
return this.rpc.request(method, params);
|
||||
return this.rpc.request(method, params, timeoutMs);
|
||||
}
|
||||
|
||||
notify(method, params) {
|
||||
if (this.rpc && !this.stopped) this.rpc.notify(method, params);
|
||||
}
|
||||
|
||||
_unkill() {
|
||||
if (this.killer) clearTimeout(this.killer);
|
||||
this.killer = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* End the process: its input is closed (the CLI ends by itself then), it is asked to stop, and
|
||||
* one that is still there five seconds later is killed. Nothing is left running.
|
||||
*/
|
||||
stop() {
|
||||
if (!this.proc || this.stopped) return;
|
||||
this.stopped = true;
|
||||
@@ -146,7 +222,19 @@ class Agent extends EventEmitter {
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
if (this.gone) return;
|
||||
const proc = this.proc;
|
||||
this.killer = setTimeout(() => {
|
||||
this.killer = null;
|
||||
try {
|
||||
proc.kill('SIGKILL');
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
}, this.options.killAfterMs || KILL_AFTER_MS);
|
||||
// The timer must not keep an editor that is closing alive.
|
||||
if (typeof this.killer.unref === 'function') this.killer.unref();
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Agent, PROTOCOL_VERSION };
|
||||
module.exports = { Agent, PROTOCOL_VERSION, START_TIMEOUT_MS, resolveCommand };
|
||||
+189
-71
@@ -4,20 +4,41 @@
|
||||
// in a shown file — is a hook. No `vscode` here.
|
||||
const { EventEmitter } = require('node:events');
|
||||
const { promptParams } = require('./context');
|
||||
const { MIN_CLI, 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
|
||||
// the view waiting for ever has one.
|
||||
const WAIT = { session: 60000, quick: 30000, mode: 15000, compact: 600000 };
|
||||
|
||||
/**
|
||||
* A progress object of the CLI (`phase` and its data) as the few words the view shows, or ''.
|
||||
* The same reading as the Neovim plugin's.
|
||||
*/
|
||||
function progressText(p) {
|
||||
if (!p || typeof p !== 'object' || typeof p.phase !== 'string') return '';
|
||||
const one = (v) => (typeof v === 'string' && v.trim() ? v.replace(/\s+/g, ' ').trim().slice(0, 80) : '');
|
||||
const text = p.phase.replace(/_/g, ' ');
|
||||
let more = '';
|
||||
if (p.phase === 'running_tool') more = one(p.what) || one(p.tool);
|
||||
else if (p.phase === 'loading_model' || p.phase === 'waiting_for_model') more = one(p.model);
|
||||
else if (p.phase === 'failed' || p.phase === 'stopped') more = one(p.reason);
|
||||
else if (p.phase === 'retrying') {
|
||||
more = one(p.reason);
|
||||
if (Number.isFinite(p.in)) more = (more ? more + ', ' : '') + `again in ${Math.max(0, Math.round(p.in))} s`;
|
||||
} else if (p.phase === 'queued' && Number.isFinite(p.ahead)) more = `${p.ahead} ahead`;
|
||||
else if (p.phase === 'waiting_for_subagents' && Number.isFinite(p.running)) more = `${p.running} running`;
|
||||
else if (p.phase === 'reading_prompt' && Number.isFinite(p.done) && p.total > 0) more = `${Math.floor((100 * p.done) / p.total)}%`;
|
||||
return more ? `${text}: ${more}` : text;
|
||||
}
|
||||
|
||||
function sentence(text) {
|
||||
const s = String(text || '').trim();
|
||||
return s ? s[0].toUpperCase() + s.slice(1) + (/[.!?…]$/.test(s) ? '' : '.') : '';
|
||||
}
|
||||
|
||||
/** Normalize an entry from `_lembas/files/search` (`{ path, kind }` or plain string). */
|
||||
/** An entry of `_lembas/files/search` (`{ path, kind }`), or `null` for anything else. */
|
||||
function normalizeFileEntry(entry) {
|
||||
if (typeof entry === 'string') {
|
||||
const clean = entry.replace(/\/$/, '');
|
||||
return clean ? { path: clean, kind: entry.endsWith('/') ? 'dir' : 'file' } : null;
|
||||
}
|
||||
if (entry && typeof entry === 'object' && typeof entry.path === 'string' && entry.path) {
|
||||
return { path: entry.path.replace(/\/$/, ''), kind: entry.kind === 'dir' ? 'dir' : 'file' };
|
||||
}
|
||||
@@ -73,8 +94,7 @@ class Chat extends EventEmitter {
|
||||
* cwd: () => string,
|
||||
* options?: () => { mode?: string, model?: string, showThoughts?: boolean },
|
||||
* hooks?: { readTextFile?: Function, writeTextFile?: Function, showDiffs?: Function,
|
||||
* closeDiffs?: Function, showMedia?: Function, showText?: Function,
|
||||
* filesChanged?: Function },
|
||||
* closeDiffs?: Function, showMedia?: Function, showText?: Function },
|
||||
* now?: () => number }} io
|
||||
* Events: `item (item)`, `reset`, `state`, `connected (agent)`, `stopped`, `editDelta (params)`, `stderr (text)`.
|
||||
*/
|
||||
@@ -90,15 +110,20 @@ class Chat extends EventEmitter {
|
||||
this._clearSession();
|
||||
this.models = [];
|
||||
this.settings = null;
|
||||
this.lastStderr = []; // what the last agent wrote, kept after it is gone
|
||||
this.lastExit = '';
|
||||
}
|
||||
|
||||
_clearSession() {
|
||||
this.session = null;
|
||||
this.sessionCwd = null;
|
||||
this.sessionStarting = null;
|
||||
this.failed = false;
|
||||
this.busy = false;
|
||||
this.modes = [];
|
||||
this.mode = null;
|
||||
this.model = null;
|
||||
this.effort = null;
|
||||
this.title = '';
|
||||
this.progress = '';
|
||||
this.usage = null;
|
||||
@@ -129,10 +154,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);
|
||||
}
|
||||
|
||||
@@ -146,6 +173,7 @@ class Chat extends EventEmitter {
|
||||
mode: this.mode,
|
||||
modes: this.modes.map((m) => ({ id: String(m.id), name: String(m.name || m.id) })),
|
||||
model: this.model,
|
||||
effort: this.effort,
|
||||
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) })),
|
||||
progress: this.progress,
|
||||
usage: this.usage,
|
||||
@@ -156,6 +184,27 @@ class Chat extends EventEmitter {
|
||||
};
|
||||
}
|
||||
|
||||
/** The agent as the Status view shows it: whether it runs, what it is, and what it last wrote. */
|
||||
status() {
|
||||
const agent = this.agent && !this.agent.stopped ? this.agent : null;
|
||||
const ready = !!(agent && agent.ready);
|
||||
const min = ready ? minClient(agent.info) : '';
|
||||
const mine = this.io.version || '';
|
||||
return {
|
||||
agent: ready ? 'running' : agent ? 'starting' : this.startError ? 'failed' : 'stopped',
|
||||
cliVersion: ready ? agent.version : '',
|
||||
minCli: MIN_CLI,
|
||||
tooOld: ready ? agent.tooOld : '',
|
||||
minClient: min,
|
||||
clientTooOld: min && mine && compareVersions(mine, min) === -1 ? WORDS.client_too_old_for_server(mine, min) : '',
|
||||
startError: this.startError || '',
|
||||
lastExit: this.lastExit,
|
||||
stderr: (agent ? agent.stderr : this.lastStderr).slice(-40),
|
||||
session: !!this.session,
|
||||
busy: this.busy,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- the agent ------------------------------------------------------------------------
|
||||
|
||||
/** A running agent that has answered `initialize`, or `null`. `quiet`: a failure is not written into the chat. */
|
||||
@@ -181,14 +230,23 @@ class Chat extends EventEmitter {
|
||||
await agent.connect();
|
||||
this.failedAt = 0;
|
||||
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;
|
||||
} catch (e) {
|
||||
if (this.agent === agent) this.agent = null;
|
||||
this.failedAt = this.now();
|
||||
this.startError = e.message;
|
||||
if (!quiet) this.note(sentence(e.message), 'error');
|
||||
this.startError = sentence(e.message);
|
||||
if (!quiet) this.note(this.startError, 'error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -202,29 +260,47 @@ class Chat extends EventEmitter {
|
||||
if (this.agent !== agent) return;
|
||||
const had = this.session !== null || this.sessionStarting !== null || this.busy;
|
||||
this.agent = null;
|
||||
this.lastStderr = Array.isArray(agent.stderr) ? agent.stderr.slice() : [];
|
||||
this.lastExit = e && e.started ? `The agent stopped (${e.signal ? 'signal ' + e.signal : 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}` : '';
|
||||
for (const card of [...this.cards.values()]) this._settle(card, 'The agent stopped before this was answered.');
|
||||
for (const q of [...this.questions.values()]) this._settleQuestion(q, 'The agent stopped before this was answered.');
|
||||
for (const pl of [...this.planCards.values()]) this._settlePlan(pl, 'The agent stopped before this was answered.');
|
||||
this._clearSession();
|
||||
if (e && e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`, 'error');
|
||||
else if (!e && had) this.note('The agent was stopped. The next message starts a new session.');
|
||||
if (e && e.started && had) {
|
||||
this.note(`The agent stopped (${e.signal ? 'signal ' + e.signal : 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`, 'error');
|
||||
this.note('The next message starts it again. Status shows what it wrote.', 'info', 'status');
|
||||
} else if (!e && had && !this.quietRetire) this.note('The agent was stopped. The next message starts a new session.');
|
||||
this.emit('stopped');
|
||||
this.emit('state');
|
||||
}
|
||||
|
||||
/** Stop the agent on purpose (another command, or the person asked). It starts again when needed. */
|
||||
stopAgent() {
|
||||
stopAgent(quiet) {
|
||||
const agent = this.agent;
|
||||
if (!agent) return;
|
||||
agent.stop();
|
||||
this._retire(agent, null);
|
||||
this.quietRetire = !!quiet;
|
||||
try {
|
||||
this._retire(agent, null);
|
||||
} finally {
|
||||
this.quietRetire = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A failure in words for the person. One that says the CLI is not signed in also ends the
|
||||
* agent: one started before the sign-in is not asked to notice it, the next use starts anew.
|
||||
*/
|
||||
words(e) {
|
||||
if (notSignedIn(e) && this.agent && !this.busy) this.stopAgent(true);
|
||||
return say(e);
|
||||
}
|
||||
|
||||
/** A request of the editor's own (`_lembas/complete`, `_lembas/edit`, …). Rejects when the agent cannot be had. */
|
||||
async request(method, params, quiet) {
|
||||
async request(method, params, quiet, timeoutMs) {
|
||||
const agent = await this.connect(quiet);
|
||||
if (!agent) throw new Error(this.startError || 'the agent is not running');
|
||||
return agent.request(method, params);
|
||||
return agent.request(method, params, timeoutMs);
|
||||
}
|
||||
|
||||
notify(method, params) {
|
||||
@@ -240,25 +316,39 @@ class Chat extends EventEmitter {
|
||||
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 agent;
|
||||
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), 'error');
|
||||
return false;
|
||||
const cwd = this.io.cwd();
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
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;
|
||||
try {
|
||||
r = await agent.request('session/new', { cwd, mcpServers: [], _meta: meta }, WAIT.session);
|
||||
break;
|
||||
} catch (e) {
|
||||
if (this.agent !== agent) return false;
|
||||
if (notSignedIn(e)) {
|
||||
// This agent may have started before the person signed in: a new one is asked once
|
||||
// before anything is said.
|
||||
this.stopAgent(true);
|
||||
if (attempt === 0) continue;
|
||||
this.note(say(e), 'error', 'signIn');
|
||||
} else this.note('No session: ' + sentence(say(e)), 'error');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (this.agent !== agent || !r || typeof r.sessionId !== 'string') return false;
|
||||
this.session = r.sessionId;
|
||||
this.sessionCwd = cwd;
|
||||
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.effort = typeof lembas.effort === 'string' ? lembas.effort : null;
|
||||
this.emit('state');
|
||||
if (agent.has('editor')) this.loadModels().catch(() => {});
|
||||
if (agent.has('commands')) this.loadCommands().catch(() => {});
|
||||
@@ -282,6 +372,7 @@ class Chat extends EventEmitter {
|
||||
this.add({ kind: 'user', text, label: w.label || '' });
|
||||
this.said = 'user';
|
||||
this.busy = true;
|
||||
this.failed = false;
|
||||
this.progress = '';
|
||||
this.emit('state');
|
||||
try {
|
||||
@@ -290,13 +381,22 @@ class Chat extends EventEmitter {
|
||||
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) || {};
|
||||
// The failure as the answer carries it, unless the event has said it already.
|
||||
if (lembas.error && typeof lembas.error === 'object' && typeof lembas.error.message === 'string' && !this.failed) {
|
||||
this.note('The turn failed: ' + sentence(say(lembas.error)), 'error');
|
||||
}
|
||||
if (typeof lembas.message === 'string' && lembas.message) this.note(lembas.message);
|
||||
if (typeof lembas.summary === 'string' && lembas.summary) this.note('Compacted: ' + lembas.summary);
|
||||
if (r && r.stopReason && r.stopReason !== 'end_turn') {
|
||||
this.note(r.stopReason === 'cancelled' ? 'Stopped.' : 'The turn ended: ' + String(r.stopReason).replace(/_/g, ' ') + '.');
|
||||
}
|
||||
// Messages sent while it worked that the turn ended before taking in: said, so they are not lost.
|
||||
if (Array.isArray(lembas.unsent) && lembas.unsent.length) {
|
||||
this.note('Not taken in before the turn ended (send again): ' + lembas.unsent.map(String).join(' | '), 'warn');
|
||||
}
|
||||
} catch (e) {
|
||||
if (this.agent === agent) this.note('The turn failed: ' + sentence(e.message), 'error');
|
||||
// An agent that stopped has said so itself; anything else is the turn's own failure.
|
||||
if (this.agent === agent) this.note('The turn failed: ' + sentence(say(e)), 'error');
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
@@ -312,15 +412,15 @@ class Chat extends EventEmitter {
|
||||
if (!this.busy || !this.agent || !this.session || !this.has('steer')) return false;
|
||||
const trimmed = String(text || '').trim();
|
||||
if (!trimmed) return false;
|
||||
await this.agent.request('_lembas/steer', { sessionId: this.session, text: trimmed });
|
||||
this.add({ kind: 'user', text: trimmed, label: 'sent while working' });
|
||||
await this.agent.request('_lembas/steer', { sessionId: this.session, text: trimmed }, WAIT.mode);
|
||||
this.add({ kind: 'user', text: trimmed, steered: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Compact the session's conversation history (`_lembas/session/compact`). */
|
||||
async compact() {
|
||||
if (this.busy || !this.agent || !this.session) return false;
|
||||
const r = await this.agent.request('_lembas/session/compact', { sessionId: this.session });
|
||||
const r = await this.agent.request('_lembas/session/compact', { sessionId: this.session }, WAIT.compact);
|
||||
const summary = r && typeof r.summary === 'string' ? r.summary.trim() : '';
|
||||
this.note(summary ? 'Session compacted: ' + summary : 'Session compacted.');
|
||||
return true;
|
||||
@@ -356,7 +456,7 @@ class Chat extends EventEmitter {
|
||||
|
||||
async setMode(id) {
|
||||
if (!(await this.ensureSession())) return false;
|
||||
await this.agent.request('session/set_mode', { sessionId: this.session, modeId: id });
|
||||
await this.agent.request('session/set_mode', { sessionId: this.session, modeId: id }, WAIT.mode);
|
||||
this.mode = id;
|
||||
this.emit('state');
|
||||
return true;
|
||||
@@ -365,15 +465,16 @@ class Chat extends EventEmitter {
|
||||
/** 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 });
|
||||
const r = await this.agent.request('_lembas/configure', { sessionId: this.session, model: id }, WAIT.quick);
|
||||
this.model = (r && r.model) || id;
|
||||
if (r && typeof r.effort === 'string') this.effort = r.effort;
|
||||
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);
|
||||
const r = await this.request('_lembas/models', {}, quiet, WAIT.quick);
|
||||
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');
|
||||
@@ -383,7 +484,7 @@ class Chat extends EventEmitter {
|
||||
/** Slash commands & skills available in this session (`_lembas/commands`). */
|
||||
async loadCommands() {
|
||||
if (!this.agent || !this.session) return [];
|
||||
const r = await this.agent.request('_lembas/commands', { sessionId: this.session });
|
||||
const r = await this.agent.request('_lembas/commands', { sessionId: this.session }, WAIT.quick);
|
||||
const list = r && Array.isArray(r.commands) ? r.commands : [];
|
||||
this.commands = list
|
||||
.filter((c) => c && typeof c.name === 'string')
|
||||
@@ -391,7 +492,7 @@ class Chat extends EventEmitter {
|
||||
name: String(c.name),
|
||||
description: String(c.description || ''),
|
||||
hint: String((c.input && c.input.hint) || ''),
|
||||
kind: String((c._meta && c._meta.lembas && c._meta.lembas.kind) || c.source || ''),
|
||||
kind: String((c._meta && c._meta.lembas && c._meta.lembas.kind) || ''),
|
||||
}));
|
||||
this.emit('state');
|
||||
return this.commands;
|
||||
@@ -404,13 +505,13 @@ class Chat extends EventEmitter {
|
||||
const params = { query: String(query || ''), limit: limit || 30 };
|
||||
if (this.session) params.sessionId = this.session;
|
||||
else params.cwd = this.io.cwd();
|
||||
const r = await agent.request('_lembas/files/search', params);
|
||||
const r = await agent.request('_lembas/files/search', params, WAIT.quick);
|
||||
return (r && Array.isArray(r.files) ? r.files : []).map(normalizeFileEntry).filter(Boolean);
|
||||
}
|
||||
|
||||
/** List previous sessions in this project (`_lembas/sessions/list`). */
|
||||
async listSessions(limit) {
|
||||
const r = await this.request('_lembas/sessions/list', { cwd: this.io.cwd(), limit: limit || 30 });
|
||||
const r = await this.request('_lembas/sessions/list', { cwd: this.io.cwd(), limit: limit || 30 }, false, WAIT.quick);
|
||||
return r && Array.isArray(r.sessions) ? r.sessions : [];
|
||||
}
|
||||
|
||||
@@ -419,18 +520,20 @@ class Chat extends EventEmitter {
|
||||
if (this.busy) return false;
|
||||
const agent = await this.connect(false);
|
||||
if (!agent) return false;
|
||||
const r = await agent.request('_lembas/sessions/resume', { sessionId });
|
||||
const r = await agent.request('_lembas/sessions/resume', { sessionId }, WAIT.session);
|
||||
if (this.agent !== agent || !r || typeof r.sessionId !== 'string') return false;
|
||||
const models = this.models;
|
||||
this._clearSession();
|
||||
this.agent = agent;
|
||||
this.models = models;
|
||||
this.session = r.sessionId;
|
||||
this.sessionCwd = typeof r.cwd === 'string' && r.cwd ? r.cwd : this.io.cwd();
|
||||
this.title = typeof r.title === 'string' ? r.title : '';
|
||||
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.effort = typeof lembas.effort === 'string' ? lembas.effort : null;
|
||||
this.items = [];
|
||||
const showThoughts = !!this.options().showThoughts;
|
||||
for (const turn of Array.isArray(r.turns) ? r.turns : []) {
|
||||
@@ -453,8 +556,8 @@ class Chat extends EventEmitter {
|
||||
id: 'i' + this.nextItem++,
|
||||
kind: 'tool',
|
||||
toolCallId: String(t.id || 'h' + this.nextItem),
|
||||
title: String(t.title || t.name || 'tool'),
|
||||
toolKind: String(t.kind || ''),
|
||||
title: String(t.name || 'tool'),
|
||||
toolKind: '',
|
||||
status: t.isError ? 'failed' : 'completed',
|
||||
output: out.length > DETAIL_MAX ? out.slice(0, DETAIL_MAX) + '\n…' : out,
|
||||
files: [],
|
||||
@@ -464,27 +567,6 @@ class Chat extends EventEmitter {
|
||||
if (typeof turn.text === 'string' && turn.text.trim()) {
|
||||
this.items.push({ id: 'i' + this.nextItem++, kind: 'agent', text: turn.text });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Legacy combined shape fallback ({ user, assistant, tools })
|
||||
if (typeof turn.user === 'string' && turn.user.trim()) {
|
||||
this.items.push({ id: 'i' + this.nextItem++, kind: 'user', text: turn.user, label: '' });
|
||||
}
|
||||
for (const t of Array.isArray(turn.tools) ? turn.tools : []) {
|
||||
this.items.push({
|
||||
id: 'i' + this.nextItem++,
|
||||
kind: 'tool',
|
||||
toolCallId: String(t.id || 'h' + this.nextItem),
|
||||
title: String(t.title || t.name || 'tool'),
|
||||
toolKind: String(t.kind || ''),
|
||||
status: t.isError ? 'failed' : 'completed',
|
||||
output: typeof t.output === 'string' ? t.output.slice(0, DETAIL_MAX) : '',
|
||||
files: [],
|
||||
denied: false,
|
||||
});
|
||||
}
|
||||
if (typeof turn.assistant === 'string' && turn.assistant.trim()) {
|
||||
this.items.push({ id: 'i' + this.nextItem++, kind: 'agent', text: turn.assistant });
|
||||
}
|
||||
}
|
||||
this.emit('reset');
|
||||
@@ -494,9 +576,36 @@ class Chat extends EventEmitter {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a stored session (`_lembas/session/delete`). The one that is open is let go of.
|
||||
* Resolves '' when it is deleted, and otherwise why not: `'agent'` (it did not start),
|
||||
* `'too_old'` (this CLI cannot), `'working'` (a turn runs in it), `'gone'` (the CLI has no such
|
||||
* session any more). The CLI answers `{ deleted }`; on `serve --stdio` it sends no
|
||||
* notification about it, so the panel reads its list again.
|
||||
*/
|
||||
async deleteSession(sessionId) {
|
||||
const agent = await this.connect(false);
|
||||
if (!agent) return 'agent';
|
||||
if (!agent.has('delete')) return 'too_old';
|
||||
if (sessionId === this.session && this.busy) return 'working';
|
||||
const r = await agent.request('_lembas/session/delete', { sessionId }, WAIT.quick);
|
||||
if (this.agent === agent && sessionId === this.session) await this.newSession();
|
||||
return r && r.deleted === false ? 'gone' : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The account changed (signed in, perhaps to another server, or signed out): what was read
|
||||
* from the old one — its models, the two saved model settings — is let go.
|
||||
*/
|
||||
forgetAccount() {
|
||||
this.models = [];
|
||||
this.settings = null;
|
||||
this.emit('state');
|
||||
}
|
||||
|
||||
/** 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 } : {});
|
||||
const r = await this.request('_lembas/editor/settings', set ? { set } : {}, false, WAIT.quick);
|
||||
this.settings = { autocomplete: (r && r.autocomplete) || null, main: (r && r.main) || null };
|
||||
return this.settings;
|
||||
}
|
||||
@@ -524,6 +633,7 @@ class Chat extends EventEmitter {
|
||||
if (params.sessionId !== this.session || !ev) return;
|
||||
if (ev.type === 'model' && typeof ev.ref === 'string') {
|
||||
this.model = ev.ref;
|
||||
if (typeof ev.effort === 'string') this.effort = ev.effort;
|
||||
this.emit('state');
|
||||
} else if (ev.type === 'mode' && typeof ev.mode === 'string') {
|
||||
this.mode = ev.mode;
|
||||
@@ -532,12 +642,21 @@ class Chat extends EventEmitter {
|
||||
this.title = ev.title;
|
||||
this.emit('state');
|
||||
} else if (ev.type === 'phase') {
|
||||
const p = ev.progress;
|
||||
this.progress = p && typeof p.phase === 'string' ? p.phase.replace(/_/g, ' ') + (p.detail ? ': ' + p.detail : '') : '';
|
||||
// The main agent's phase; a subagent's (`agent`) is the tree's to show.
|
||||
if (ev.agent !== undefined && ev.agent !== null) return;
|
||||
this.progress = progressText(ev.progress);
|
||||
this.emit('state');
|
||||
} else if (ev.type === 'usage') {
|
||||
const input = Number(ev.input_tokens ?? ev.input ?? ev.tokens_in ?? 0) || 0;
|
||||
const output = Number(ev.output_tokens ?? ev.output ?? ev.tokens_out ?? 0) || 0;
|
||||
} else if (ev.type === 'error' && typeof ev.message === 'string' && ev.message.trim()) {
|
||||
// A turn that failed ends as any other does (`end_turn`): this is where it says why.
|
||||
this.failed = true;
|
||||
this.note('The turn failed: ' + sentence(say({ message: ev.message, code: ev.code })), 'error');
|
||||
this.busy = false;
|
||||
this.progress = '';
|
||||
this.emit('state');
|
||||
} else if (ev.type === 'usage' && ev.usage && typeof ev.usage === 'object' && !ev.child) {
|
||||
// The session's own requests; a subagent's (`child`) say nothing about this conversation.
|
||||
const input = Number(ev.usage.input) || 0;
|
||||
const output = Number(ev.usage.output) || 0;
|
||||
if (input || output) {
|
||||
this.usage = {
|
||||
input: (this.usage ? this.usage.input : 0) + input,
|
||||
@@ -594,7 +713,6 @@ class Chat extends EventEmitter {
|
||||
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 : [];
|
||||
const structured = (u._meta && u._meta.lembas && u._meta.lembas.plan) || null;
|
||||
@@ -765,7 +883,7 @@ class Chat extends EventEmitter {
|
||||
if (outcome === 'approve') {
|
||||
const m = modeOrFeedback === 'manual' ? 'manual' : 'edit';
|
||||
reply = { outcome: 'approve', mode: m };
|
||||
label = m === 'manual' ? 'Approved (manual mode)' : 'Approved (edit mode)';
|
||||
label = m === 'manual' ? 'Approved: asks before each edit' : 'Approved: edits without asking';
|
||||
} else if (outcome === 'revise') {
|
||||
const feedback = String(modeOrFeedback || '').trim();
|
||||
reply = { outcome: 'revise', feedback };
|
||||
@@ -870,4 +988,4 @@ function diffItems(content) {
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = { Chat, diffItems, normalizeFileEntry, normalizeAnswer };
|
||||
module.exports = { Chat, diffItems, normalizeFileEntry, normalizeAnswer, progressText };
|
||||
@@ -2,7 +2,8 @@
|
||||
// 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']);
|
||||
// Refusals that stay true until something is changed: said once, and typing asks no more.
|
||||
const REFUSALS = new Set(['no_model', 'not_allowed', 'unknown_model', 'not_logged_in', 'unsupported']);
|
||||
|
||||
const LENGTH_PRESETS = {
|
||||
auto: { tokens: 0, instruction: '' },
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
'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;
|
||||
}
|
||||
|
||||
/**
|
||||
* A reader of `lembas login --json`'s output as it arrives: the function returned takes the
|
||||
* pieces, and `onEvent(ev)` is called for every event on a line that has ended. A line cut in
|
||||
* two by the pipe is one line; what has no line break yet is not read. The same reading as the
|
||||
* Neovim plugin's (nvim/lua/llembas/login.lua); tests/rules/login_events.json holds the cases.
|
||||
*/
|
||||
function reader(onEvent) {
|
||||
let buffer = '';
|
||||
return (text) => {
|
||||
buffer += String(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)) onEvent(ev);
|
||||
};
|
||||
}
|
||||
|
||||
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 timer = null;
|
||||
const feed = reader((ev) => {
|
||||
events.push(ev);
|
||||
if (o.onEvent) o.onEvent(ev);
|
||||
});
|
||||
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);
|
||||
feed(text);
|
||||
});
|
||||
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, reader, sameServer, webAddress, current, signIn, signOut };
|
||||
@@ -0,0 +1,120 @@
|
||||
'use strict';
|
||||
// What the panel's page may say to the extension, as a schema. The page draws text a model wrote
|
||||
// and is not trusted with any decision: every message is checked here — its type, the shape and
|
||||
// the length of every field, every enumeration — and only what the schema names is passed on.
|
||||
// A message that does not fit is dropped whole. No `vscode` here.
|
||||
|
||||
const str = (max, o) => ({ kind: 'string', max, ...(o || {}) });
|
||||
const int = (min, max) => ({ kind: 'int', min, max });
|
||||
const oneOf = (...values) => ({ kind: 'enum', values });
|
||||
const bool = { kind: 'bool' };
|
||||
const opt = (rule) => ({ ...rule, optional: true });
|
||||
|
||||
const TEXT = str(1000000, { filled: true });
|
||||
const ID = str(200, { filled: true, line: true });
|
||||
const CARD = str(40, { filled: true, line: true });
|
||||
|
||||
const SCHEMA = {
|
||||
// the conversation
|
||||
ready: {},
|
||||
send: { text: TEXT },
|
||||
steer: { text: TEXT },
|
||||
stop: {},
|
||||
new: {},
|
||||
compact: {},
|
||||
explain: {},
|
||||
fix: {},
|
||||
detach: {},
|
||||
copyCode: { text: str(1000000) },
|
||||
insertCode: { text: str(1000000) },
|
||||
searchFiles: { query: str(400, { line: true }), seq: int(0, 1000000000) },
|
||||
setMode: { id: ID },
|
||||
setModel: { id: ID },
|
||||
answer: { card: CARD, option: str(200, { line: true }) },
|
||||
answerQuestion: { card: CARD, answers: { kind: 'answers' } },
|
||||
dismissQuestion: { card: CARD },
|
||||
answerPlan: { card: CARD, outcome: oneOf('approve', 'revise', 'dismissed', 'dismiss'), value: opt(str(20000)) },
|
||||
showDiff: { card: CARD },
|
||||
openLink: { href: str(8192, { filled: true, line: true }) },
|
||||
openFile: { path: str(4096, { filled: true, line: true }), line: opt(int(1, 100000000)), soft: opt(bool) },
|
||||
openMedia: { key: str(40, { filled: true, line: true }) },
|
||||
// the other views
|
||||
load: { what: oneOf('config', 'models', 'sessions', 'account', 'status') },
|
||||
setSetting: { key: str(80, { filled: true, line: true }), value: { kind: 'setting' }, target: oneOf('user', 'workspace') },
|
||||
resetSetting: { key: str(80, { filled: true, line: true }), target: oneOf('user', 'workspace') },
|
||||
openSettingsUi: {},
|
||||
chooseModel: { kind: oneOf('main', 'autocomplete'), id: { kind: 'model' }, keep: oneOf('account', 'window') },
|
||||
resume: { id: ID },
|
||||
deleteSession: { id: ID },
|
||||
signIn: { address: str(2048, { filled: true, line: true }) },
|
||||
signInConfirm: {},
|
||||
signInCancel: {},
|
||||
openApproval: {},
|
||||
signOut: {},
|
||||
signOutConfirm: {},
|
||||
accountDismiss: {},
|
||||
restartAgent: {},
|
||||
// what an editor command left in the panel to be answered
|
||||
instruction: { id: CARD, text: str(20000, { filled: true }) },
|
||||
cancelTask: { id: CARD },
|
||||
proposal: { id: CARD, answer: oneOf('accept', 'reject', 'show') },
|
||||
};
|
||||
|
||||
function fits(rule, v) {
|
||||
if (rule.kind === 'string') {
|
||||
if (typeof v !== 'string' || v.length > rule.max) return false;
|
||||
if (rule.filled && !v.trim()) return false;
|
||||
if (rule.line && /[\u0000-\u001f\u007f]/.test(v)) return false;
|
||||
return true;
|
||||
}
|
||||
if (rule.kind === 'int') return typeof v === 'number' && Number.isInteger(v) && v >= rule.min && v <= rule.max;
|
||||
if (rule.kind === 'enum') return typeof v === 'string' && rule.values.includes(v);
|
||||
if (rule.kind === 'bool') return typeof v === 'boolean';
|
||||
// A setting's value: one plain value; which, and in what range, the settings table says.
|
||||
if (rule.kind === 'setting') return typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= 4096);
|
||||
// A model's id, or null for the server's own.
|
||||
if (rule.kind === 'model') return v === null || (typeof v === 'string' && v.trim() !== '' && v.length <= 300 && !/[\u0000-\u001f\u007f]/.test(v));
|
||||
// The answers to a question card: a short list of plain things, read again by the chat.
|
||||
if (rule.kind === 'answers') {
|
||||
if (!Array.isArray(v) || v.length > 32) return false;
|
||||
try {
|
||||
return JSON.stringify(v).length <= 200000;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A message from the page, checked. Returns a new object holding only what the schema names, or
|
||||
* `null` when the message is not one the page may send.
|
||||
*/
|
||||
function validate(m) {
|
||||
if (!m || typeof m !== 'object' || Array.isArray(m) || typeof m.type !== 'string') return null;
|
||||
if (!Object.prototype.hasOwnProperty.call(SCHEMA, m.type)) return null;
|
||||
const schema = SCHEMA[m.type];
|
||||
const out = { type: m.type };
|
||||
for (const [name, rule] of Object.entries(schema)) {
|
||||
const v = m[name];
|
||||
if (v === undefined) {
|
||||
if (rule.optional) continue;
|
||||
return null;
|
||||
}
|
||||
if (!fits(rule, v)) return null;
|
||||
out[name] = rule.kind === 'answers' ? JSON.parse(JSON.stringify(v)) : v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A server's address as the person typed it, fit to be one argument of `lembas login`: one word,
|
||||
* and never something the program would read as an option. Returns the address or ''.
|
||||
*/
|
||||
function serverAddress(text) {
|
||||
const s = typeof text === 'string' ? text.trim() : '';
|
||||
if (!s || s.length > 2048 || /[\s\u0000-\u001f\u007f]/.test(s) || s.startsWith('-')) return '';
|
||||
return s;
|
||||
}
|
||||
|
||||
module.exports = { SCHEMA, validate, serverAddress };
|
||||
@@ -0,0 +1,136 @@
|
||||
'use strict';
|
||||
// What is never sent along by itself: files that look like they hold secrets, files outside the
|
||||
// project, and files the project's .gitignore leaves out. Used for what goes with a request
|
||||
// without the person having pointed at it: pieces of other open files with a suggestion, and the
|
||||
// names of the open tabs with a message. The same rules as the Neovim plugin's
|
||||
// (nvim/lua/llembas/private.lua); tests/rules/private_files.json holds the cases both must
|
||||
// answer alike. No `vscode` here.
|
||||
const childProcess = require('node:child_process');
|
||||
|
||||
const ENV_EXAMPLES = new Set(['.env.example', '.env.sample', '.env.template']);
|
||||
const NAMES = new Set(['.netrc', '_netrc', '.npmrc', '.pypirc', '.pgpass', '.htpasswd', '.git-credentials']);
|
||||
const ENDINGS = new Set(['pem', 'key', 'p12', 'pfx', 'jks', 'keystore', 'ppk', 'kdbx', 'env']);
|
||||
const KEY_NAMES = ['id_rsa', 'id_ed25519', 'id_ecdsa', 'id_dsa'];
|
||||
const DIRECTORIES = new Set(['.ssh', '.gnupg', '.aws', '.kube', '.docker', '.azure']);
|
||||
|
||||
const partsOf = (path) => String(path || '').replace(/\\/g, '/').split('/').filter(Boolean).map((p) => p.toLowerCase());
|
||||
|
||||
/**
|
||||
* Whether a file's name or place says it may hold secrets: `.env` and `.env.*` (not the
|
||||
* `.example`, `.sample` and `.template` ones), `*.env`, key and certificate stores (`*.pem`,
|
||||
* `*.key`, `*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`), SSH key names (`id_rsa*`,
|
||||
* `id_ed25519*`, `id_ecdsa*`, `id_dsa*`), `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`,
|
||||
* `.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`,
|
||||
* `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`.
|
||||
*/
|
||||
function looksSecret(path) {
|
||||
const parts = partsOf(path);
|
||||
const base = parts[parts.length - 1];
|
||||
if (!base) return false;
|
||||
if (parts.slice(0, -1).some((p) => DIRECTORIES.has(p))) return true;
|
||||
if (base === '.env' || (base.startsWith('.env.') && !ENV_EXAMPLES.has(base))) return true;
|
||||
if (NAMES.has(base)) return true;
|
||||
const ending = /\.([^.]+)$/.exec(base);
|
||||
if (ending && ENDINGS.has(ending[1])) return true;
|
||||
if (KEY_NAMES.some((k) => base.startsWith(k))) return true;
|
||||
if (base.startsWith('credentials')) return true;
|
||||
return base.startsWith('secrets.') || base.startsWith('secret.');
|
||||
}
|
||||
|
||||
/** A path with `.` and `..` worked out and one kind of slash, or '' when it is not absolute. */
|
||||
function absolute(path) {
|
||||
let p = String(path || '').replace(/\\/g, '/');
|
||||
const drive = (/^([A-Za-z]:)\//.exec(p) || ['', ''])[1];
|
||||
if (drive) p = p.slice(2);
|
||||
if (!p.startsWith('/')) return '';
|
||||
const out = [];
|
||||
for (const part of p.split('/')) {
|
||||
if (!part || part === '.') continue;
|
||||
if (part === '..') out.pop();
|
||||
else out.push(part);
|
||||
}
|
||||
return drive.toLowerCase() + '/' + out.join('/');
|
||||
}
|
||||
|
||||
/** Whether `path` is a file inside one of the folders `roots` (never a folder itself, and never "inside" the root of the disk). */
|
||||
function inside(path, roots) {
|
||||
const p = absolute(path);
|
||||
if (!p) return false;
|
||||
for (const root of roots || []) {
|
||||
const r = absolute(root);
|
||||
if (r && r !== '/' && !/^[a-z]:\/$/.test(r) && p.startsWith(r + '/')) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the project's .gitignore leaves out, asked of git once a file. Without git, or outside a
|
||||
* repository, nothing is ignored.
|
||||
*/
|
||||
class Ignored {
|
||||
/** @param {{ run?: (dir: string, file: string) => Promise<boolean> }} [io] */
|
||||
constructor(io) {
|
||||
this.answers = new Map(); // path -> boolean | Promise<boolean>
|
||||
this.run = (io && io.run) || Ignored.git;
|
||||
}
|
||||
|
||||
static git(dir, file) {
|
||||
return new Promise((resolve) => {
|
||||
try {
|
||||
// 0: ignored. 1: not. Anything else: no repository there, or git is not installed.
|
||||
childProcess.execFile(
|
||||
'git',
|
||||
['-C', dir, 'check-ignore', '-q', '--', file],
|
||||
{ timeout: 5000, windowsHide: true, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } },
|
||||
(err) => resolve(!err),
|
||||
);
|
||||
} catch {
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** `true` or `false` once git has answered, `undefined` while it has not (the question is then on its way). */
|
||||
known(path) {
|
||||
const a = this.answers.get(path);
|
||||
if (typeof a === 'boolean') return a;
|
||||
if (!a) this.check(path).then(undefined, () => {});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Ask (once), and wait for the answer. */
|
||||
check(path) {
|
||||
const a = this.answers.get(path);
|
||||
if (typeof a === 'boolean') return Promise.resolve(a);
|
||||
if (a) return a;
|
||||
const dir = String(path).replace(/[\\/][^\\/]*$/, '') || '/';
|
||||
const asking = Promise.resolve(this.run(dir, path)).then(
|
||||
(v) => {
|
||||
this.answers.set(path, !!v);
|
||||
return !!v;
|
||||
},
|
||||
() => {
|
||||
this.answers.set(path, false);
|
||||
return false;
|
||||
},
|
||||
);
|
||||
this.answers.set(path, asking);
|
||||
return asking;
|
||||
}
|
||||
|
||||
/** A .gitignore changed, or the folders did: what git said before is asked again. */
|
||||
forget() {
|
||||
this.answers.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a file other than the one being worked on may go along by itself, by what is known
|
||||
* now: inside the project, not secret by its name, and known not to be ignored.
|
||||
*/
|
||||
function maySend(path, roots, ignored) {
|
||||
if (!inside(path, roots) || looksSecret(path)) return false;
|
||||
return ignored ? ignored.known(path) === false : true;
|
||||
}
|
||||
|
||||
module.exports = { looksSecret, inside, maySend, Ignored };
|
||||
+34
-5
@@ -16,6 +16,8 @@ class RpcError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_LINE_BYTES = 64 * 1024 * 1024; // a line that never ends is dropped, not kept
|
||||
|
||||
class Rpc {
|
||||
/**
|
||||
* @param {{ write: (line: string) => void,
|
||||
@@ -38,7 +40,18 @@ class Rpc {
|
||||
this.buffer += typeof chunk === 'string' ? chunk : this.decoder.write(chunk);
|
||||
for (;;) {
|
||||
const nl = this.buffer.indexOf('\n');
|
||||
if (nl < 0) break;
|
||||
if (nl < 0) {
|
||||
if (this.buffer.length > (this.io.maxLine || MAX_LINE_BYTES)) {
|
||||
this.buffer = '';
|
||||
this.dropping = true; // the rest of that line, when its end comes, is not a message
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (this.dropping) {
|
||||
this.dropping = false;
|
||||
this.buffer = this.buffer.slice(nl + 1);
|
||||
continue;
|
||||
}
|
||||
const line = this.buffer.slice(0, nl);
|
||||
this.buffer = this.buffer.slice(nl + 1);
|
||||
if (line.trim() === '') continue;
|
||||
@@ -46,7 +59,9 @@ class Rpc {
|
||||
try {
|
||||
msg = JSON.parse(line);
|
||||
} catch {
|
||||
continue; // not ours: a stray line on stdout
|
||||
// Not the protocol: something printed on stdout. Said to whoever keeps the agent's words.
|
||||
if (this.io.onStray) this.io.onStray(line.slice(0, 400));
|
||||
continue;
|
||||
}
|
||||
if (msg && typeof msg === 'object' && !Array.isArray(msg)) this._message(msg);
|
||||
}
|
||||
@@ -70,6 +85,7 @@ class Rpc {
|
||||
const entry = this.waiting.get(msg.id);
|
||||
if (!entry) return;
|
||||
this.waiting.delete(msg.id);
|
||||
if (entry.timer) clearTimeout(entry.timer);
|
||||
if (msg.error) entry.reject(new RpcError(msg.error));
|
||||
else entry.resolve(msg.result === undefined ? null : msg.result);
|
||||
}
|
||||
@@ -106,12 +122,24 @@ class Rpc {
|
||||
}
|
||||
}
|
||||
|
||||
/** A request; resolves with the result, rejects with an RpcError. */
|
||||
request(method, params) {
|
||||
/**
|
||||
* A request; resolves with the result, rejects with an RpcError. `timeoutMs`: no answer by then
|
||||
* rejects (`error.timeout`), and an answer that comes later is dropped.
|
||||
*/
|
||||
request(method, params, timeoutMs) {
|
||||
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 });
|
||||
const entry = { resolve, reject, timer: null };
|
||||
if (timeoutMs > 0) {
|
||||
entry.timer = setTimeout(() => {
|
||||
if (!this.waiting.delete(id)) return;
|
||||
const e = new RpcError({ code: -32001, message: `the LLeMbas CLI did not answer ${method} within ${Math.round(timeoutMs / 1000)} seconds` });
|
||||
e.timeout = true;
|
||||
reject(e);
|
||||
}, timeoutMs);
|
||||
}
|
||||
this.waiting.set(id, entry);
|
||||
this._write({ jsonrpc: '2.0', id, method, params: params === undefined ? {} : params });
|
||||
});
|
||||
}
|
||||
@@ -126,6 +154,7 @@ class Rpc {
|
||||
this.closed = true;
|
||||
const waiting = [...this.waiting.values()];
|
||||
this.waiting.clear();
|
||||
for (const w of waiting) if (w.timer) clearTimeout(w.timer);
|
||||
for (const w of waiting) w.reject(new RpcError({ code: -32000, message: message || 'the agent stopped' }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
'use strict';
|
||||
// The settings, as the panel shows them. What a setting IS — its type, default, range, choices and
|
||||
// whether a folder may set it — is read from the manifest (`contributes.configuration`), the one
|
||||
// place the editor reads it from too. What is added here is only where the panel puts it and what
|
||||
// it is called there. A setting the manifest has and this table has not still appears (under
|
||||
// Settings, by its key), so nothing contributed can be missing from the panel; a test keeps the
|
||||
// table complete. No `vscode` here.
|
||||
|
||||
const PREFIX = 'llembas.';
|
||||
const VIEWS = ['autocomplete', 'settings', 'account'];
|
||||
const CONTROLS = { toggle: 'boolean', number: 'number', select: 'string', text: 'string', path: 'string', longtext: 'string' };
|
||||
// The longest text a setting takes from the panel.
|
||||
const MAX_TEXT = { text: 200, path: 4096, longtext: 2000 };
|
||||
|
||||
/** key (without `llembas.`) -> where it is shown and how. `group` is a heading inside the view. */
|
||||
const PRESENT = {
|
||||
'complete.auto': { view: 'autocomplete', group: '', label: 'Suggest as you type', control: 'toggle' },
|
||||
'complete.length': {
|
||||
view: 'autocomplete',
|
||||
group: '',
|
||||
label: 'How much to suggest',
|
||||
control: 'select',
|
||||
choices: { auto: 'As the server sets it', words: 'A few words', line: 'One line', block: 'A function or block', file: 'A long passage' },
|
||||
},
|
||||
'complete.maxTokens': { view: 'autocomplete', group: '', label: 'Longest suggestion, in tokens (0: as the length says)', control: 'number' },
|
||||
'complete.debounce': { view: 'autocomplete', group: '', label: 'Pause before asking (milliseconds)', control: 'number' },
|
||||
'complete.instructions': { view: 'autocomplete', group: '', label: 'Instructions for suggestions', control: 'longtext' },
|
||||
'chat.sendEditorContext': { view: 'settings', group: 'Chat', label: 'Send what the editor shows', control: 'toggle' },
|
||||
'chat.showThinking': { view: 'settings', group: 'Chat', label: "Show the model's thinking", control: 'toggle' },
|
||||
'chat.startMode': { view: 'settings', group: 'Chat', label: 'Mode a new session starts in', control: 'text' },
|
||||
'rewrite.openDiff': { view: 'settings', group: 'Rewrite', label: 'Open the diff beside the file', control: 'toggle' },
|
||||
'media.maxMegabytes': { view: 'settings', group: 'Shown files', label: 'Largest file taken from the agent (megabytes)', control: 'number' },
|
||||
command: { view: 'settings', group: 'Program', label: 'The LLeMbas CLI', control: 'path' },
|
||||
'login.caFile': { view: 'account', group: '', label: 'Certificate authority file', control: 'path' },
|
||||
};
|
||||
|
||||
/** A manifest description as plain words: Markdown's code marks are taken away. */
|
||||
function plain(text) {
|
||||
return String(text || '').replace(/`/g, '').replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
/** A key as part of an element's id. */
|
||||
function idOf(key) {
|
||||
return String(key).replace(/[^A-Za-z0-9]+/g, '-');
|
||||
}
|
||||
|
||||
/**
|
||||
* Every contributed setting as a field of the panel, in the table's order, anything the table
|
||||
* does not know last.
|
||||
* @param {object} properties the manifest's `contributes.configuration.properties`
|
||||
*/
|
||||
function fields(properties) {
|
||||
const out = [];
|
||||
const known = Object.keys(PRESENT);
|
||||
const keys = Object.keys(properties || {})
|
||||
.filter((k) => k.startsWith(PREFIX))
|
||||
.map((k) => k.slice(PREFIX.length));
|
||||
keys.sort((a, b) => {
|
||||
const x = known.indexOf(a);
|
||||
const y = known.indexOf(b);
|
||||
return (x < 0 ? known.length : x) - (y < 0 ? known.length : y);
|
||||
});
|
||||
for (const key of keys) {
|
||||
const def = properties[PREFIX + key] || {};
|
||||
const type = def.type === 'boolean' || def.type === 'number' || def.type === 'integer' ? (def.type === 'integer' ? 'number' : def.type) : 'string';
|
||||
const p = PRESENT[key];
|
||||
const choices = Array.isArray(def.enum) ? def.enum.map(String) : null;
|
||||
let control = p ? p.control : type === 'boolean' ? 'toggle' : type === 'number' ? 'number' : choices ? 'select' : 'text';
|
||||
if (CONTROLS[control] !== type) control = type === 'boolean' ? 'toggle' : type === 'number' ? 'number' : 'text';
|
||||
if (choices && control !== 'select') control = 'select';
|
||||
out.push({
|
||||
key,
|
||||
id: idOf(key),
|
||||
view: p && VIEWS.includes(p.view) ? p.view : 'settings',
|
||||
group: p ? p.group : 'Other',
|
||||
label: p ? p.label : PREFIX + key,
|
||||
hint: plain(def.markdownDescription || def.description),
|
||||
type,
|
||||
control,
|
||||
choices,
|
||||
choiceLabels: choices ? choices.map((c) => (p && p.choices && p.choices[c]) || c) : null,
|
||||
min: typeof def.minimum === 'number' ? def.minimum : null,
|
||||
max: typeof def.maximum === 'number' ? def.maximum : null,
|
||||
maxLength: type === 'string' ? MAX_TEXT[control] || MAX_TEXT.text : null,
|
||||
default: def.default,
|
||||
// What starts or reaches a program is the machine's to say: never a folder's.
|
||||
machine: def.scope === 'machine' || def.scope === 'application' || def.scope === 'machine-overridable',
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A write the panel asks for, checked: only a setting of the table, only a value of its declared
|
||||
* type and range, only at a level the setting has. Returns `{ ok: true, key, value, target }`
|
||||
* (`value` `undefined`: take the value at that level away) or `{ ok: false, why }`.
|
||||
* @param {ReturnType<typeof fields>} table
|
||||
* @param {{ key: unknown, value?: unknown, target?: unknown, reset?: boolean }} w
|
||||
*/
|
||||
function checkWrite(table, w) {
|
||||
if (!w || typeof w !== 'object' || typeof w.key !== 'string') return { ok: false, why: 'no setting is named' };
|
||||
const f = table.find((x) => x.key === w.key);
|
||||
if (!f) return { ok: false, why: 'not a setting of LLeMbas: ' + w.key.slice(0, 80) };
|
||||
const target = w.target === undefined ? 'user' : w.target;
|
||||
if (target !== 'user' && target !== 'workspace') return { ok: false, why: 'no such level' };
|
||||
if (target === 'workspace' && f.machine) return { ok: false, why: `${f.label}: set for this computer only, never by a folder` };
|
||||
if (w.reset === true) return { ok: true, key: f.key, value: undefined, target };
|
||||
const v = w.value;
|
||||
if (f.type === 'boolean') {
|
||||
if (typeof v !== 'boolean') return { ok: false, why: `${f.label}: on or off` };
|
||||
return { ok: true, key: f.key, value: v, target };
|
||||
}
|
||||
if (f.type === 'number') {
|
||||
if (typeof v !== 'number' || !Number.isFinite(v) || !Number.isInteger(v)) return { ok: false, why: `${f.label}: a whole number` };
|
||||
if ((f.min !== null && v < f.min) || (f.max !== null && v > f.max)) return { ok: false, why: `${f.label}: from ${f.min} to ${f.max}` };
|
||||
return { ok: true, key: f.key, value: v, target };
|
||||
}
|
||||
if (typeof v !== 'string') return { ok: false, why: `${f.label}: a text` };
|
||||
if (v.length > f.maxLength) return { ok: false, why: `${f.label}: at most ${f.maxLength} characters` };
|
||||
if (f.choices) {
|
||||
if (!f.choices.includes(v)) return { ok: false, why: `${f.label}: one of ${f.choices.join(', ')}` };
|
||||
return { ok: true, key: f.key, value: v, target };
|
||||
}
|
||||
// A line break belongs in instructions only; no other control character belongs anywhere.
|
||||
const control = f.control === 'longtext' ? /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/ : /[\u0000-\u001f\u007f]/;
|
||||
if (control.test(v)) return { ok: false, why: `${f.label}: no control characters` };
|
||||
return { ok: true, key: f.key, value: f.control === 'longtext' ? v : v.trim(), target };
|
||||
}
|
||||
|
||||
/**
|
||||
* A setting as the panel is told it: the value in force, the level it comes from, and which
|
||||
* levels hold a value of their own.
|
||||
* @param {{ defaultValue?: any, globalValue?: any, workspaceValue?: any, workspaceFolderValue?: any } | undefined} inspected
|
||||
*/
|
||||
function levelsOf(field, inspected, effective) {
|
||||
const i = inspected || {};
|
||||
const has = (v) => v !== undefined;
|
||||
const from = has(i.workspaceFolderValue) ? 'folder' : has(i.workspaceValue) ? 'workspace' : has(i.globalValue) ? 'user' : 'default';
|
||||
let value = effective === undefined ? field.default : effective;
|
||||
if (field.type === 'boolean') value = !!value;
|
||||
else if (field.type === 'number') value = Number.isFinite(Number(value)) ? Number(value) : Number(field.default) || 0;
|
||||
else value = String(value === null || value === undefined ? '' : value).slice(0, field.maxLength);
|
||||
return { value, from, user: has(i.globalValue), workspace: has(i.workspaceValue) };
|
||||
}
|
||||
|
||||
module.exports = { PREFIX, VIEWS, PRESENT, CONTROLS, fields, checkWrite, levelsOf, idOf, plain };
|
||||
+175
-47
@@ -1,10 +1,96 @@
|
||||
'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.
|
||||
// The panel's page: a fixed skeleton with a strict Content-Security-Policy. The one frame holds
|
||||
// everything — the conversation and, behind a strip of tabs, the sessions, the models, the
|
||||
// settings, the account and the agent's status. Nothing a model or a server writes is ever part
|
||||
// of this text; it reaches the page as messages and is drawn with `textContent`. What is written
|
||||
// into the text here is the extension's own: the settings table's labels and the manifest's
|
||||
// descriptions, escaped. No `vscode` here.
|
||||
|
||||
/** The views of the panel, in the order of the tab strip. `icon` is the path of a 16 px drawing. */
|
||||
const TABS = [
|
||||
{ id: 'chat', label: 'Chat', icon: 'M2.5 3.5h11v7h-6l-3 2.5v-2.5h-2z' },
|
||||
{ id: 'sessions', label: 'Sessions', icon: 'M2.6 6.2A5.5 5.5 0 1 1 3.4 11M2.2 3.2v3h3M8 5v3l2 1.5' },
|
||||
{ id: 'models', label: 'Models', icon: 'M8 2l5 2.8v6.4L8 14l-5-2.8V4.8zM3 4.8l5 2.8 5-2.8M8 7.6V14' },
|
||||
{ id: 'autocomplete', label: 'Autocomplete', icon: 'M2.5 5h6M2.5 8h4M2.5 11h6M11.5 3.5v9M10 3.5h3M10 12.5h3' },
|
||||
{ id: 'settings', label: 'Settings', icon: 'M2.5 4.5h2M8 4.5h5.5M2.5 8h6M12 8h1.5M2.5 11.5h1M7 11.5h6.5M6.2 3v3M10.2 6.5v3M5.2 10v3' },
|
||||
{ id: 'account', label: 'Account', icon: 'M10.5 5.5a2.5 2.5 0 1 1-5 0 2.5 2.5 0 0 1 5 0zM3 13.5c.6-2.6 2.6-4 5-4s4.4 1.4 5 4' },
|
||||
{ id: 'status', label: 'Status', icon: 'M1.5 8h3L6 4l3 8 1.5-4h4' },
|
||||
];
|
||||
/** A pane that has no tab: it is only ever opened beside the conversation. */
|
||||
const SHEETS = [{ id: 'files', label: 'Open a file' }];
|
||||
|
||||
function esc(text) {
|
||||
return String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string, logoUri?: string }} o
|
||||
* One field of a form: four slots, always all four — label, control, hint, level — so that fields
|
||||
* side by side share their rows (the form's grid, `subgrid` in the field) whatever the text does.
|
||||
* `level` is where the value is kept; a field without levels still has the slot.
|
||||
*/
|
||||
function slots(id, label, control, hint, level) {
|
||||
return `<div class="field" data-field="${esc(id)}">
|
||||
<label class="f-label" for="${esc(id)}">${esc(label)}</label>
|
||||
<div class="f-control">${control}</div>
|
||||
<p class="f-hint" id="${esc(id)}-hint">${hint}</p>
|
||||
<div class="f-level">${level || ''}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/** A setting of the table as a field. Its value is put in by the page's script, from a message. */
|
||||
function settingField(f) {
|
||||
const id = 'set-' + f.id;
|
||||
const common = `id="${esc(id)}" data-setting="${esc(f.key)}" aria-describedby="${esc(id)}-hint"`;
|
||||
let control;
|
||||
if (f.control === 'toggle') control = `<input ${common} type="checkbox">`;
|
||||
else if (f.control === 'number') {
|
||||
control = `<input ${common} type="number" inputmode="numeric" step="1"${f.min !== null ? ` min="${esc(f.min)}"` : ''}${f.max !== null ? ` max="${esc(f.max)}"` : ''}>`;
|
||||
} else if (f.control === 'select') {
|
||||
control = `<select ${common}>${f.choices.map((c, i) => `<option value="${esc(c)}">${esc(f.choiceLabels[i])}</option>`).join('')}</select>`;
|
||||
} else if (f.control === 'longtext') {
|
||||
control = `<textarea ${common} rows="3" maxlength="${esc(f.maxLength)}" spellcheck="true"></textarea>`;
|
||||
} else {
|
||||
control = `<input ${common} type="text" maxlength="${esc(f.maxLength)}" spellcheck="false" autocomplete="off"${f.control === 'path' ? ' class="mono"' : ''}>`;
|
||||
}
|
||||
// Where the value is kept: a setting a folder may hold offers both levels; one of the machine's only the user's.
|
||||
const where = f.machine
|
||||
? `<span class="f-fixed">User settings only: a folder cannot set this.</span><input type="hidden" id="${esc(id)}-level" value="user">`
|
||||
: `<select id="${esc(id)}-level" class="level" data-level-for="${esc(f.key)}" aria-label="Where “${esc(f.label)}” is saved"><option value="user">User</option><option value="workspace">Workspace</option></select>`;
|
||||
const level = `<span class="f-origin" id="${esc(id)}-origin"></span>${where}<button type="button" class="second" id="${esc(id)}-reset" data-reset="${esc(f.key)}" aria-label="Reset “${esc(f.label)}” at this level">Reset</button>`;
|
||||
return slots(id, f.label, control, `${esc(f.hint)} <span class="f-key">llembas.${esc(f.key)}</span>`, level);
|
||||
}
|
||||
|
||||
/** The fields of one view, under their groups' headings. */
|
||||
function settingForms(fields, view) {
|
||||
const mine = fields.filter((f) => f.view === view);
|
||||
const groups = [];
|
||||
for (const f of mine) if (!groups.includes(f.group)) groups.push(f.group);
|
||||
return groups
|
||||
.map((g) => `${g ? `<h3 class="group">${esc(g)}</h3>\n` : ''}<div class="form">\n${mine.filter((f) => f.group === g).map(settingField).join('\n')}\n</div>`)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function tabButton(t, first) {
|
||||
return `<button type="button" role="tab" id="tab-${t.id}" class="tab" data-view="${t.id}" aria-controls="view-${t.id}" aria-selected="${first ? 'true' : 'false'}" tabindex="${first ? '0' : '-1'}" title="${esc(t.label)}"><svg class="tab-icon" viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false"><path d="${t.icon}" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg><span class="tab-label">${esc(t.label)}</span></button>`;
|
||||
}
|
||||
|
||||
/** A pane: a heading, a way back to the conversation, and its body. */
|
||||
function pane(id, label, body, tabbed) {
|
||||
const role = tabbed ? `role="tabpanel" aria-labelledby="tab-${id}"` : `role="region" aria-labelledby="h-${id}"`;
|
||||
return `<section id="view-${id}" class="view pane" data-pane="${id}" ${role} tabindex="-1" hidden>
|
||||
<header class="pane-head">
|
||||
<h2 id="h-${id}" class="pane-title">${esc(label)}</h2>
|
||||
<button type="button" class="second pane-close" data-close="${id}" title="Back to the conversation (Esc)">Close</button>
|
||||
</header>
|
||||
<div class="pane-body">
|
||||
${body}
|
||||
</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string, logoUri?: string,
|
||||
* fields?: ReturnType<import('./settings').fields> }} o
|
||||
*/
|
||||
function chatHtml(o) {
|
||||
// VS Code / VSCodium's `webview.cspSource` may list multiple space-separated origins
|
||||
@@ -17,6 +103,7 @@ function chatHtml(o) {
|
||||
for (const v of uris) {
|
||||
if (typeof v !== 'string' || !v || /["<>\s]/.test(v)) throw new Error('unsafe value for the chat page');
|
||||
}
|
||||
const fields = Array.isArray(o.fields) ? o.fields : [];
|
||||
const csp = [
|
||||
"default-src 'none'",
|
||||
`img-src ${o.cspSource}`,
|
||||
@@ -26,7 +113,61 @@ function chatHtml(o) {
|
||||
"form-action 'none'",
|
||||
].join('; ');
|
||||
const brandImg = o.logoUri ? `<img class="brand-logo" src="${o.logoUri}" alt="" width="18" height="18">` : '';
|
||||
const heroImg = o.logoUri ? `<img class="hero-logo" src="${o.logoUri}" alt="LLeMbas IDE" width="44" height="44">` : '';
|
||||
const heroImg = o.logoUri ? `<img class="hero-logo" src="${o.logoUri}" alt="" width="44" height="44">` : '';
|
||||
|
||||
const sessions = `<div class="pane-tools">
|
||||
<input id="sessions-filter" class="q-input" type="search" placeholder="Filter by title or model" aria-label="Filter the sessions" autocomplete="off" spellcheck="false">
|
||||
<button id="sessions-new" type="button">New session</button>
|
||||
<button id="sessions-refresh" type="button" class="second">Refresh</button>
|
||||
</div>
|
||||
<p id="sessions-status" class="pane-status" role="status" aria-live="polite"></p>
|
||||
<div id="sessions-list" class="rows" role="list" aria-label="Earlier sessions in this folder"></div>`;
|
||||
|
||||
const keep = (kind, label) =>
|
||||
`<select id="m-${kind}-keep" class="level" aria-label="Where the ${label} model is kept"><option value="account">Saved in my account</option><option value="window">This window only</option></select>`;
|
||||
const models = `<p id="models-status" class="pane-status" role="status" aria-live="polite"></p>
|
||||
<div class="form">
|
||||
${slots('m-session', 'This conversation', '<select id="m-session" aria-describedby="m-session-hint"></select>', 'The model of the session that is open, for that session only.', '')}
|
||||
${slots('m-main', 'Chat and rewrite', '<select id="m-main" aria-describedby="m-main-hint"></select>', 'The model new sessions and rewrites start with.', keep('main', 'chat and rewrite'))}
|
||||
${slots('m-autocomplete', 'Autocomplete', '<select id="m-autocomplete" aria-describedby="m-autocomplete-hint"></select>', 'The model that suggests as you type.', keep('autocomplete', 'autocomplete'))}
|
||||
</div>
|
||||
<div class="pane-actions">
|
||||
<button id="models-refresh" type="button" class="second">Read the list again</button>
|
||||
</div>
|
||||
<p id="models-effort" class="pane-note"></p>`;
|
||||
|
||||
const autocomplete = `<p class="pane-note"><span id="ac-model-line">Autocomplete model: not read yet.</span> <button type="button" class="linkish" data-goto="models">Change the model</button></p>
|
||||
${settingForms(fields, 'autocomplete')}`;
|
||||
|
||||
const settings = `${settingForms(fields, 'settings')}
|
||||
<p class="pane-note">Each of these is a setting of the editor (<span class="f-key">llembas.*</span>): what is changed here is written to your settings, and what is changed there shows here. <button type="button" class="linkish" id="open-settings-ui">Open the editor's Settings</button></p>`;
|
||||
|
||||
const account = `<p id="account-who" class="pane-status" role="status" aria-live="polite">Not checked yet.</p>
|
||||
<div id="account-flow" class="flow" aria-live="polite"></div>
|
||||
<div class="form">
|
||||
${slots('account-address', 'Server address', '<input id="account-address" type="text" inputmode="url" maxlength="2048" spellcheck="false" autocomplete="off" aria-describedby="account-address-hint">', 'The address you open LLeMbas at in the browser. The LLeMbas CLI keeps one sign-in for this computer: the terminal uses it too.', '')}
|
||||
${fields.filter((f) => f.view === 'account').map(settingField).join('\n')}
|
||||
</div>
|
||||
<div class="pane-actions">
|
||||
<button id="account-signin" type="button">Sign in</button>
|
||||
<button id="account-signout" type="button" class="second">Sign out</button>
|
||||
<button id="account-refresh" type="button" class="second">Check again</button>
|
||||
</div>`;
|
||||
|
||||
const status = `<dl id="status-list" class="facts" aria-live="polite"></dl>
|
||||
<div class="pane-actions">
|
||||
<button id="status-restart" type="button" title="Stops the agent and starts it again at once. The conversation shown stays; the next message starts a new session.">Restart the agent</button>
|
||||
<button id="status-refresh" type="button" class="second">Refresh</button>
|
||||
</div>
|
||||
<h3 class="group" id="status-problems-h">Problems</h3>
|
||||
<div id="status-problems" class="rows" role="list" aria-labelledby="status-problems-h"></div>
|
||||
<h3 class="group" id="status-stderr-h">What the agent last wrote</h3>
|
||||
<pre id="status-stderr" class="stderr" tabindex="0" aria-labelledby="status-stderr-h"></pre>`;
|
||||
|
||||
const files = `<input id="files-query" class="q-input" type="search" placeholder="Part of the file's name" aria-label="Part of the file's name" aria-controls="files-list" autocomplete="off" spellcheck="false">
|
||||
<p id="files-status" class="pane-status" role="status" aria-live="polite"></p>
|
||||
<div id="files-list" class="rows" role="listbox" aria-label="Files of the project"></div>`;
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
@@ -37,17 +178,24 @@ function chatHtml(o) {
|
||||
<title>LLeMbas</title>
|
||||
</head>
|
||||
<body>
|
||||
<nav class="tabs" aria-label="Views of LLeMbas">
|
||||
<div id="tabs" class="tablist" role="tablist" aria-label="LLeMbas" aria-orientation="horizontal">
|
||||
${TABS.map((t, i) => tabButton(t, i === 0)).join('\n')}
|
||||
</div>
|
||||
</nav>
|
||||
<div id="stage" class="stage">
|
||||
<section id="view-chat" class="view chat-view" data-pane="chat" role="tabpanel" aria-labelledby="tab-chat">
|
||||
<div class="chrome">
|
||||
<header class="bar">
|
||||
<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">
|
||||
<button id="compact" type="button" class="second icon-btn" title="Compact session context" hidden>Compact</button>
|
||||
<button id="settings-toggle" type="button" class="second icon-btn" title="Autocomplete length, tokens & instructions" aria-expanded="false">Tune</button>
|
||||
<button id="sessions" type="button" class="second icon-btn" title="Resume a previous session">History</button>
|
||||
<button id="sessions" type="button" class="second icon-btn" title="Earlier sessions, beside the conversation" aria-controls="view-sessions">History</button>
|
||||
<button id="new" type="button" class="icon-btn" title="Start a new session">New</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -56,43 +204,12 @@ function chatHtml(o) {
|
||||
<span id="mode-dot" class="dot mode-dot" aria-hidden="true"></span>
|
||||
<select id="mode" title="Mode (can be changed mid-turn)" aria-label="Mode"></select>
|
||||
</div>
|
||||
<select id="model" title="This session's model" aria-label="Model"></select>
|
||||
<button id="model-open" type="button" class="second model-btn" title="Models, beside the conversation" aria-controls="view-models"><span id="model-name" class="model-name">Model</span></button>
|
||||
</div>
|
||||
</header>
|
||||
<section id="settings-panel" class="settings-panel" hidden aria-label="Autocomplete settings">
|
||||
<div class="sp-row">
|
||||
<label class="sp-label" for="ac-tokens">Autocomplete max tokens</label>
|
||||
<span id="ac-tokens-val" class="sp-val">Default</span>
|
||||
</div>
|
||||
<input id="ac-tokens" class="sp-slider" type="range" min="0" max="4096" step="16" value="0" aria-label="Autocomplete maximum tokens">
|
||||
<div class="sp-presets">
|
||||
<button type="button" class="mini preset-btn" data-length="auto" data-tokens="0">Default</button>
|
||||
<button type="button" class="mini preset-btn" data-length="words" data-tokens="24">Words</button>
|
||||
<button type="button" class="mini preset-btn" data-length="line" data-tokens="64">Line</button>
|
||||
<button type="button" class="mini preset-btn" data-length="block" data-tokens="256">Block</button>
|
||||
<button type="button" class="mini preset-btn" data-length="file" data-tokens="2048">File</button>
|
||||
</div>
|
||||
<div class="sp-grid">
|
||||
<label class="sp-label" for="ac-length">Prediction scope</label>
|
||||
<select id="ac-length" aria-label="Autocomplete prediction scope">
|
||||
<option value="auto">Auto (server default)</option>
|
||||
<option value="words">Few words</option>
|
||||
<option value="line">Single line</option>
|
||||
<option value="block">Function / block</option>
|
||||
<option value="file">Large / full file</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="sp-field">
|
||||
<label class="sp-label" for="ac-instructions">Autocomplete instructions</label>
|
||||
<input id="ac-instructions" class="q-input" type="text" placeholder="Optional guidance (e.g. concise idiomatic code, no comments)">
|
||||
</div>
|
||||
<div class="sp-checks">
|
||||
<label class="sp-check"><input id="ac-auto" type="checkbox"> Suggest as you type</label>
|
||||
<label class="sp-check"><input id="chat-thinking" type="checkbox"> Show thinking</label>
|
||||
</div>
|
||||
</section>
|
||||
<div id="team-bar" class="team-bar" hidden aria-live="polite"></div>
|
||||
<main id="log" aria-live="polite">
|
||||
</div>
|
||||
<main id="log" aria-label="Conversation" tabindex="-1">
|
||||
<section id="empty" class="empty">
|
||||
<div class="hero">
|
||||
${heroImg}
|
||||
@@ -108,21 +225,22 @@ function chatHtml(o) {
|
||||
<div class="hero-hints">
|
||||
<span class="hint-pill">@file</span>
|
||||
<span class="hint-pill">/command</span>
|
||||
<span class="hint-pill">Alt+\ complete</span>
|
||||
<span class="hint-pill">Alt+\\ complete</span>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<footer>
|
||||
<div id="popup" class="popup" hidden role="listbox" aria-label="Suggestions"></div>
|
||||
<div id="tasks" class="tasks" hidden role="group" aria-label="Waiting for you"></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>
|
||||
<button id="add-file" type="button" class="second" title="Add a file of this project (@file)">@ File</button>
|
||||
<span id="working" class="working" hidden><span class="pulse-dot" aria-hidden="true"></span><span id="working-text">Working…</span></span>
|
||||
<span id="usage" class="usage" hidden></span>
|
||||
</div>
|
||||
@@ -133,9 +251,19 @@ function chatHtml(o) {
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
${pane('sessions', 'Sessions', sessions, true)}
|
||||
${pane('models', 'Models', models, true)}
|
||||
${pane('autocomplete', 'Autocomplete', autocomplete, true)}
|
||||
${pane('settings', 'Settings', settings, true)}
|
||||
${pane('account', 'Account', account, true)}
|
||||
${pane('status', 'Status', status, true)}
|
||||
${pane('files', 'Open a file', files, false)}
|
||||
</div>
|
||||
<div id="announce" class="sr-only" role="status" aria-live="polite"></div>
|
||||
<script nonce="${o.nonce}" src="${o.scriptUri}"></script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
module.exports = { chatHtml };
|
||||
module.exports = { chatHtml, TABS, SHEETS, settingField, slots, esc };
|
||||
@@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
// The same failure in the same words as the Neovim plugin says it (nvim/lua/llembas/init.lua),
|
||||
// and the comparing of versions. No `vscode` here.
|
||||
|
||||
/** The oldest LLeMbas CLI everything here works with (`_lembas/configure` on `serve --stdio`). */
|
||||
const MIN_CLI = '2.0.0-beta.16';
|
||||
|
||||
const WORDS = {
|
||||
not_found: (command) =>
|
||||
`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. 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',
|
||||
tls_untrusted: "The LLeMbas server's certificate is not trusted on this computer",
|
||||
not_lembas: 'That address is not a LLeMbas server',
|
||||
server_too_old: 'The LLeMbas server is older than this LLeMbas CLI needs; update the server',
|
||||
client_too_old: 'The LLeMbas server needs a newer LLeMbas CLI; update the CLI (lembas update)',
|
||||
not_allowed: 'The server does not allow that',
|
||||
busy: 'The server is busy; try again in a moment',
|
||||
// Said by the editor itself, in one wording wherever it applies.
|
||||
working: 'LLeMbas is still working. Stop it first.',
|
||||
too_old: 'This LLeMbas CLI is too old for that. Update it: lembas update',
|
||||
};
|
||||
const WHOLE = new Set(['not_logged_in', 'signed_out']);
|
||||
const SERVER_SAYS = new Set(['not_allowed', 'busy']);
|
||||
const PREFIXES = new Set(['unreachable', 'timeout', 'tls_untrusted', 'not_lembas', 'server_too_old', 'client_too_old', 'not_allowed', 'busy']);
|
||||
|
||||
/** A version as numbers: `2.0.0-beta.10` is newer than `2.0.0-beta.9`, and `2.0.0` newer than both. */
|
||||
function versionKey(v) {
|
||||
// Digits and dots, then perhaps `-` and a pre-release name, then perhaps `+` and build words:
|
||||
// anything else ("1.2.3junk") is no version. The Neovim plugin reads it the same way
|
||||
// (nvim/lua/llembas/init.lua); tests/rules/versions.json holds the cases both must answer alike.
|
||||
const m = /^v?(\d+(?:\.\d+)*)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/.exec(String(v === undefined || v === null ? '' : v).trim());
|
||||
if (!m) return null;
|
||||
const key = m[1].split('.').slice(0, 3).map(Number);
|
||||
while (key.length < 3) key.push(0);
|
||||
const pre = m[2] || '';
|
||||
// A release is above its pre-releases; among those the name (alpha, beta, rc), then the number.
|
||||
key.push(pre ? 0 : 1, (/^[A-Za-z]+/.exec(pre) || [''])[0], Number((/(\d+)\D*$/.exec(pre) || [0, 0])[1]));
|
||||
return key;
|
||||
}
|
||||
|
||||
/** -1, 0 or 1 as version `a` is older than, the same as, or newer than `b`; `null` when either is no version. */
|
||||
function compareVersions(a, b) {
|
||||
const x = versionKey(a);
|
||||
const y = versionKey(b);
|
||||
if (!x || !y) return null;
|
||||
for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
||||
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 '';
|
||||
const d = e.data && typeof e.data === 'object' ? e.data : {};
|
||||
if (typeof d.reason === 'string' && d.reason) return d.reason;
|
||||
if (typeof d.code === 'string' && d.code) return d.code;
|
||||
if (typeof e.code === 'string' && e.code) return e.code;
|
||||
// `session/new` refuses a computer that is not signed in with a sentence and no code.
|
||||
if (/not logged in/i.test(String(e.message || ''))) return 'not_logged_in';
|
||||
return '';
|
||||
}
|
||||
|
||||
/** Whether a failure says that the CLI is not signed in to a server. */
|
||||
function notSignedIn(e) {
|
||||
const code = codeOf(e);
|
||||
return code === 'not_logged_in' || code === 'signed_out';
|
||||
}
|
||||
|
||||
/**
|
||||
* A failure in words for the person: a known code in its fixed words, with what the CLI said
|
||||
* where that adds something; anything else as the CLI said it.
|
||||
*/
|
||||
function say(e) {
|
||||
const said = String((e && typeof e === 'object' ? e.message : e) || '').replace(/\s+/g, ' ').trim();
|
||||
const code = codeOf(e);
|
||||
if (WHOLE.has(code)) return WORDS[code];
|
||||
if (!PREFIXES.has(code)) return said || 'it failed';
|
||||
if (!said) return WORDS[code] + '.';
|
||||
// A refusal the server put in words of its own is said in those.
|
||||
if (SERVER_SAYS.has(code)) return said;
|
||||
return WORDS[code] + ': ' + said;
|
||||
}
|
||||
|
||||
module.exports = { MIN_CLI, WORDS, compareVersions, codeOf, notSignedIn, say, minClient };
|
||||
@@ -1,7 +1,11 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { Agent } = require('../src/agent');
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { Agent, resolveCommand } = require('../src/agent');
|
||||
const { MIN_CLI, compareVersions } = require('../src/words');
|
||||
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) => {
|
||||
@@ -9,7 +13,10 @@ test('the hello says what this client is: an editor that shows media and has uns
|
||||
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, { protocol: 2, editor: true, media: true, show: true });
|
||||
assert.deepEqual(hello.params.clientCapabilities._meta.lembas, { protocol: 3, editor: true, media: true, show: true });
|
||||
assert.deepEqual(hello.params.clientInfo, { name: 'test', version: '0' });
|
||||
assert.equal(agent.version, '2.0.0-beta.17');
|
||||
assert.equal(agent.tooOld, '');
|
||||
assert.deepEqual(hello.params.clientCapabilities.fs, { readTextFile: true, writeTextFile: false }, 'writing is offered only by a client that can do it');
|
||||
assert.ok(agent.ready && agent.has('editor') && agent.has('media') && !agent.has('fs'));
|
||||
});
|
||||
@@ -27,18 +34,63 @@ test('every caller of connect gets the same start', async (t) => {
|
||||
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' });
|
||||
test('an older CLI is known by its version, compared as numbers, and lacks what it lacks', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t), { FAKE_AGENT_VERSION: '2.0.0-beta.9' });
|
||||
await agent.connect();
|
||||
assert.ok(!agent.has('editor'));
|
||||
assert.ok(!agent.has('editor') && agent.has('steer'));
|
||||
assert.equal(agent.tooOld, `LLeMbas CLI 2.0.0-beta.9 is older than this needs (${MIN_CLI} or newer), so parts of it will not work. Update the CLI: lembas update`);
|
||||
await assert.rejects(agent.request('_lembas/models', {}), (e) => e.code === -32601);
|
||||
});
|
||||
|
||||
test('versions are compared as numbers, and a release is newer than its betas', () => {
|
||||
assert.equal(compareVersions('2.0.0-beta.10', '2.0.0-beta.9'), 1);
|
||||
assert.equal(compareVersions('2.0.0-beta.9', '2.0.0-beta.16'), -1);
|
||||
assert.equal(compareVersions('2.0.0', '2.0.0-beta.99'), 1);
|
||||
assert.equal(compareVersions('2.0.0-beta.17+build', '2.0.0-beta.17'), 0);
|
||||
assert.equal(compareVersions('1.9.9', '2.0.0-beta.1'), -1);
|
||||
assert.equal(compareVersions('2.1.0-rc.1', '2.1.0-beta.9'), 1);
|
||||
assert.equal(compareVersions('nonsense', '1.0.0'), null);
|
||||
});
|
||||
|
||||
test('an agent that never answers the hello is given up on, said in words, and ended', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t), { FAKE_AGENT_HANG: 'initialize' }, { startTimeoutMs: 300 });
|
||||
let gone = false;
|
||||
agent.on('exit', () => (gone = true));
|
||||
await assert.rejects(agent.connect(), /The LLeMbas CLI did not answer within 0 seconds\./);
|
||||
await until(() => gone);
|
||||
});
|
||||
|
||||
test('an agent that ignores a polite stop is killed, so none is left behind', async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const script = path.join(dir, 'stubborn.py');
|
||||
fs.writeFileSync(script, "import signal, sys, json\nsignal.signal(signal.SIGTERM, signal.SIG_IGN)\nfor line in sys.stdin:\n m = json.loads(line)\n print(json.dumps({'jsonrpc': '2.0', 'id': m['id'], 'result': {}}), flush=True)\nimport time\nwhile True: time.sleep(1)\n");
|
||||
const agent = new Agent({ command: 'python3', args: [script], cwd: dir, killAfterMs: 200 });
|
||||
await agent.connect();
|
||||
const pid = agent.proc.pid;
|
||||
let exit = null;
|
||||
agent.on('exit', (e) => (exit = e));
|
||||
agent.stop();
|
||||
await until(() => exit !== null, 4000);
|
||||
assert.equal(exit.signal, 'SIGKILL');
|
||||
assert.throws(() => process.kill(pid, 0));
|
||||
});
|
||||
|
||||
test('a bare `lembas` that is not on the PATH is looked for where the installer puts it', (t) => {
|
||||
const home = tempDir(t);
|
||||
assert.equal(resolveCommand('lembas', { PATH: '/nonexistent-a:/nonexistent-b' }, home), 'lembas');
|
||||
fs.mkdirSync(path.join(home, '.local', 'bin'), { recursive: true });
|
||||
const at = path.join(home, '.local', 'bin', 'lembas');
|
||||
fs.writeFileSync(at, '#!/bin/sh\n', { mode: 0o755 });
|
||||
assert.equal(resolveCommand('lembas', { PATH: '/nonexistent-a' }, home), at);
|
||||
assert.equal(resolveCommand('lembas', { PATH: path.dirname(at) }, home), 'lembas', 'one on the PATH is used as it is');
|
||||
assert.equal(resolveCommand('/opt/x/lembas', { PATH: '' }, home), '/opt/x/lembas', 'a set command is never replaced');
|
||||
});
|
||||
|
||||
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.connect(), /The LLeMbas CLI was not found: `lembas-that-is-not-installed` is not a program this editor can start\. Install the CLI, or set "LLeMbas: Command" \(llembas\.command\) to its full path\./);
|
||||
await assert.rejects(agent.request('x', {}), /not running/);
|
||||
assert.equal(exits.length, 1);
|
||||
assert.equal(exits[0].started, false);
|
||||
@@ -49,13 +101,13 @@ test('an agent that exits fails what was asked and says its last words', async (
|
||||
await agent.connect();
|
||||
const exits = [];
|
||||
agent.on('exit', (e) => exits.push(e));
|
||||
const r = await agent.request('session/new', { cwd: '/', mcpServers: [] });
|
||||
const r = await agent.request('session/new', { cwd: os.tmpdir(), 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 assert.rejects(turn, /the agent stopped \(exit 3\): error: the session store could not be opened/);
|
||||
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/);
|
||||
assert.match(exits[0].last, /session store/);
|
||||
});
|
||||
|
||||
test('stop ends the process', async (t) => {
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
'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.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', 'workspace.onDidSaveTextDocument': '1.30', 'workspace.onDidChangeWorkspaceFolders': '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', 'OverviewRulerLane.Left': '1.30', 'ConfigurationTarget.Global': '1.30', 'ConfigurationTarget.Workspace': '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',
|
||||
// The Settings editor with a query (`@ext:` since 1.45), and the keyboard back to the editor.
|
||||
'workbench.action.openSettings': '1.45', 'workbench.action.focusActiveEditorGroup': '1.30',
|
||||
};
|
||||
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 panel is the only place that asks: no Quick Pick, no input box, no progress notification, no message with an answer', () => {
|
||||
const code = source.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
for (const banned of ['showQuickPick', 'showInputBox', 'withProgress', 'createQuickPick', 'createInputBox', 'showOpenDialog', 'showSaveDialog', 'modal:']) {
|
||||
assert.ok(!code.includes(banned), `extension.js must not use ${banned}`);
|
||||
}
|
||||
// A message of the editor's is said and nothing more: one argument, the text.
|
||||
const calls = [...code.matchAll(/show(?:Information|Warning|Error)Message\(/g)];
|
||||
assert.ok(calls.length > 10, 'the source was read');
|
||||
for (const m of calls) {
|
||||
let depth = 1;
|
||||
let i = m.index + m[0].length;
|
||||
let commas = 0;
|
||||
let quote = '';
|
||||
for (; i < code.length && depth > 0; i++) {
|
||||
const ch = code[i];
|
||||
if (quote) {
|
||||
if (ch === '\\') i++;
|
||||
else if (ch === quote) quote = '';
|
||||
// A template's own expressions are not arguments: commas inside `${…}` are counted by depth below.
|
||||
continue;
|
||||
}
|
||||
if (ch === "'" || ch === '"' || ch === '`') quote = ch;
|
||||
else if (ch === '(' || ch === '[' || ch === '{') depth++;
|
||||
else if (ch === ')' || ch === ']' || ch === '}') depth--;
|
||||
else if (ch === ',' && depth === 1) commas++;
|
||||
}
|
||||
const text = code.slice(m.index, i);
|
||||
if (/,\s*\)$/.test(text)) commas--; // a comma after the last argument is not another one
|
||||
assert.equal(commas, 0, 'a message with more than its text: ' + text.slice(0, 120));
|
||||
}
|
||||
});
|
||||
|
||||
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.equal(Object.keys(c.views).length, 1, 'one panel: everything is a view inside it');
|
||||
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');
|
||||
});
|
||||
+180
-41
@@ -18,8 +18,10 @@ test('a typed prompt is answered: what was typed, then the reply, in order', asy
|
||||
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.deepEqual(chat.state().modes.map((m) => m.id), ['manual', 'edit', 'auto', 'plan']);
|
||||
assert.equal(chat.state().mode, 'manual');
|
||||
assert.deepEqual(chat.usage, { input: 1200, output: 34 }, "the session's own usage; a subagent's is not added to it");
|
||||
assert.equal(agents[0].log().find((m) => m.method === 'session/new').params.cwd, chat.sessionCwd);
|
||||
assert.equal(chat.state().model, 'example/model-a');
|
||||
const sent = lastPrompt(agents[0]);
|
||||
assert.deepEqual(sent.params.prompt, [{ type: 'text', text: 'hello' }]);
|
||||
@@ -71,7 +73,7 @@ test('the editor context goes in _meta.lembas.editor, not into the prompt', asyn
|
||||
});
|
||||
|
||||
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 { chat, agents } = fakeChat(t, { env: { FAKE_AGENT_VERSION: '2.0.0-beta.9' } });
|
||||
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]);
|
||||
@@ -81,6 +83,47 @@ test('an agent that does not read the editor context gets it as blocks in front
|
||||
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');
|
||||
assert.equal(chat.items.filter((i) => i.kind === 'note' && /LLeMbas CLI 2\.0\.0-beta\.9 is older than this needs/.test(i.text)).length, 1, 'an older CLI is said once');
|
||||
});
|
||||
|
||||
test('a turn that fails says why, once, whether the event, the answer or both carry it', async (t) => {
|
||||
const { chat } = fakeChat(t);
|
||||
await chat.send('FAIL');
|
||||
const failures = () => chat.items.filter((i) => i.kind === 'note' && i.level === 'error');
|
||||
assert.equal(failures().length, 1);
|
||||
assert.equal(failures()[0].text, 'The turn failed: The server answered 502: the model is not loaded.', 'the event has no code: said as the CLI said it');
|
||||
assert.equal(chat.busy, false);
|
||||
await chat.send('FAILFIELD');
|
||||
assert.equal(failures().length, 2, 'an answer that carries the error alone is shown too');
|
||||
assert.equal(failures()[1].text, 'The turn failed: The LLeMbas server cannot be reached: the server answered 502: the model is not loaded.', 'a known code in its fixed words');
|
||||
await chat.send('hello');
|
||||
assert.equal(failures().length, 2);
|
||||
});
|
||||
|
||||
test('what the agent does is shown from the fields the CLI sends', async (t) => {
|
||||
const { progressText } = require('../src/chat');
|
||||
assert.equal(progressText({ phase: 'running_tool', since: 1, tool: 'grep', what: 'grep waybread' }), 'running tool: grep waybread');
|
||||
assert.equal(progressText({ phase: 'waiting_for_model', model: 'example/model-a' }), 'waiting for model: example/model-a');
|
||||
assert.equal(progressText({ phase: 'failed', reason: 'the server answered 502' }), 'failed: the server answered 502');
|
||||
assert.equal(progressText({ phase: 'retrying', reason: 'overloaded', in: 5 }), 'retrying: overloaded, again in 5 s');
|
||||
assert.equal(progressText({ phase: 'thinking' }), 'thinking');
|
||||
assert.equal(progressText(null), '');
|
||||
const { chat } = fakeChat(t);
|
||||
const seen = [];
|
||||
chat.on('state', () => seen.push(chat.progress));
|
||||
await chat.send('TOOL TEAM NOTICE PLAN DENIED');
|
||||
assert.ok(seen.includes('running tool: grep waybread'), seen.join('|'));
|
||||
const tool = chat.items.find((i) => i.kind === 'tool' && i.title === 'grep waybread');
|
||||
assert.equal(tool.ms, 42);
|
||||
assert.equal(tool.toolKind, 'search');
|
||||
assert.equal(tool.output, 'src/oven.py:3: waybread = bake()');
|
||||
assert.equal(chat.team.agents[0].name, 'scout');
|
||||
assert.ok(chat.items.some((i) => i.kind === 'note' && i.level === 'warn' && /slow to answer/.test(i.text)));
|
||||
const plan = chat.items.find((i) => i.kind === 'plan');
|
||||
assert.deepEqual([plan.title, plan.done, plan.all], ['Upgrade', 1, 3]);
|
||||
const denied = chat.items.find((i) => i.kind === 'tool' && i.denied);
|
||||
assert.equal(denied.title, 'rm -rf /');
|
||||
assert.equal(denied.output, 'The hardline never allows this command.');
|
||||
});
|
||||
|
||||
test('an approval card waits for the answer, and the answer reaches the agent', async (t) => {
|
||||
@@ -91,7 +134,7 @@ test('an approval card waits for the answer, and the answer reaches the agent',
|
||||
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.deepEqual(card.options.map((o) => [o.optionId, o.name, o.kind]), [['once', 'Allow once', 'allow_once'], ['session', 'Always, this session', 'allow_always'], ['deny', 'Deny', 'reject_once']]);
|
||||
assert.equal(card.state, 'open');
|
||||
assert.equal(chat.answer(card.id, 'no-such-option'), false);
|
||||
assert.equal(chat.answer(card.id, 'deny'), true);
|
||||
@@ -112,7 +155,6 @@ test('a card with a diff is shown as a diff before the answer, and nothing is wr
|
||||
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}`);
|
||||
@@ -128,7 +170,6 @@ test('a card with a diff is shown as a diff before the answer, and nothing is wr
|
||||
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]);
|
||||
@@ -144,7 +185,9 @@ test('a rejected diff leaves the file alone', async (t) => {
|
||||
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'));
|
||||
const refused = chat.items.filter((i) => i.kind === 'tool');
|
||||
assert.equal(refused.length, 1);
|
||||
assert.ok(refused[0].denied, 'the call is shown as refused, not as run');
|
||||
});
|
||||
|
||||
test('a card the agent withdraws is taken down', async (t) => {
|
||||
@@ -153,7 +196,7 @@ test('a card the agent withdraws is taken down', async (t) => {
|
||||
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/);
|
||||
assert.match(text(chat), /answer=deny/);
|
||||
});
|
||||
|
||||
test('Stop answers an open card as cancelled', async (t) => {
|
||||
@@ -163,7 +206,7 @@ test('Stop answers an open card as cancelled', async (t) => {
|
||||
chat.stop();
|
||||
await turn;
|
||||
assert.equal(chat.items.find((i) => i.kind === 'card').state, 'settled');
|
||||
assert.match(text(chat), /answer=cancelled/);
|
||||
assert.match(text(chat), /answer=deny/, 'a card closed without a choice is a denial to the agent');
|
||||
});
|
||||
|
||||
test('a tool call is one line that changes as the call goes on', async (t) => {
|
||||
@@ -173,7 +216,9 @@ test('a tool call is one line that changes as the call goes on', async (t) => {
|
||||
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].title, 'write b.txt');
|
||||
assert.equal(tools[0].ms, 42);
|
||||
assert.deepEqual(tools[0].files, [file], 'the files an edit changed come with its last update');
|
||||
assert.equal(tools[0].status, 'completed');
|
||||
});
|
||||
|
||||
@@ -202,6 +247,7 @@ test("the agent's write of a file goes to the hook; an error tells it to write t
|
||||
const asked = [];
|
||||
const { chat } = fakeChat(t, {
|
||||
dir,
|
||||
agent: { writeTextFile: true },
|
||||
hooks: {
|
||||
writeTextFile: async (p) => {
|
||||
asked.push(p);
|
||||
@@ -294,7 +340,8 @@ test("the window's own model and mode start a session", async (t) => {
|
||||
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.match(text(chat), /> The agent stopped \(exit 3\): error: the session store could not be opened\n> The next message starts it again\./);
|
||||
assert.ok(!/The turn failed/.test(text(chat)), 'said once');
|
||||
assert.equal(chat.session, null);
|
||||
assert.equal(chat.busy, false);
|
||||
await chat.send('hello again');
|
||||
@@ -324,7 +371,7 @@ test('a command that is not there is said once in the chat, and not tried at eve
|
||||
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.match(text(chat), /> The LLeMbas CLI was not found: `lembas-that-is-not-installed` is not a program this editor can start\. Install the CLI, or set "LLeMbas: Command" \(llembas\.command\) to its full path\.$/);
|
||||
assert.equal(chat.busy, false);
|
||||
});
|
||||
|
||||
@@ -385,7 +432,7 @@ test('a file that is not a picture is a line with Open; one on this machine is n
|
||||
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`);
|
||||
await chat.send(`SHOW ${file}`);
|
||||
const item = chat.items.find((i) => i.kind === 'media');
|
||||
assert.equal(item.picture, false);
|
||||
assert.equal(item.name, 'report.pdf');
|
||||
@@ -396,15 +443,14 @@ test('a file that is not a picture is a line with Open; one on this machine is n
|
||||
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) => {
|
||||
test('a file of a kind nobody knows is named where it is, and never opened', 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}`);
|
||||
const plain = path.join(dir, 'notes.bin');
|
||||
fs.writeFileSync(plain, Buffer.concat([Buffer.from([0, 1, 2]), crypto.randomBytes(2500)]));
|
||||
await chat.send(`SHOW ${plain}`);
|
||||
assert.equal(got[0].picture, false);
|
||||
assert.ok(got[0].file.startsWith(store + path.sep));
|
||||
assert.ok(fs.readFileSync(got[0].file).equals(bytes));
|
||||
assert.equal(got[0].original, plain, 'on this machine the agent says where the file is');
|
||||
assert.deepEqual(fs.readdirSync(store), [], 'so nothing is fetched');
|
||||
assert.equal(got[0].open, null, 'a kind nobody knows is never opened');
|
||||
assert.equal(chat.items.find((i) => i.kind === 'media').opens, false);
|
||||
});
|
||||
@@ -435,41 +481,134 @@ test('a text file the agent shows goes to the hook that opens it', async (t) =>
|
||||
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}`);
|
||||
await chat.send(`SHOW ${file} AT 1`);
|
||||
assert.equal(opened[0].path, 'page.html');
|
||||
assert.equal(opened[0].kind, 'html');
|
||||
assert.equal(opened[0].line, 1);
|
||||
assert.equal(opened[0].uri, undefined, 'text comes with its content, not with a place');
|
||||
assert.equal(opened[0].text, '<script>alert(1)</script>');
|
||||
assert.match(text(chat), /> Shown: page\.html/);
|
||||
});
|
||||
|
||||
test('real CLI shapes: files/search objects, historyTurns resume, question Answer[], plan dismissed, and compact', async (t) => {
|
||||
const { chat } = fakeChat(t);
|
||||
const files = await chat.searchFiles('src');
|
||||
assert.deepEqual(files, [
|
||||
test('the file index, a resumed session, question and plan cards, and compact, in the CLI\'s shapes', async (t) => {
|
||||
const dir = tempDir(t);
|
||||
fs.mkdirSync(path.join(dir, 'src'));
|
||||
fs.writeFileSync(path.join(dir, 'src', 'app.py'), '');
|
||||
fs.writeFileSync(path.join(dir, 'src', 'utils.py'), '');
|
||||
const { chat, agents } = fakeChat(t, { dir, options: { showThoughts: true } });
|
||||
assert.deepEqual(await chat.searchFiles('src'), [
|
||||
{ path: 'src', kind: 'dir' },
|
||||
{ path: 'src/app.py', kind: 'file' },
|
||||
{ path: 'src/utils.py', kind: 'file' },
|
||||
{ path: 'src', kind: 'dir' },
|
||||
]);
|
||||
assert.deepEqual(await chat.searchFiles(''), [], 'with nothing typed the index has only the files used lately');
|
||||
assert.deepEqual(agents[0].log().find((m) => m.method === '_lembas/files/search').params, { query: 'src', limit: 30, cwd: dir }, 'no session is opened to look for a file');
|
||||
|
||||
assert.deepEqual((await chat.listSessions(40)).map((s) => [s.id, s.title, s.root]), [['ses_prev', 'Earlier work', dir]]);
|
||||
assert.equal(await chat.resumeSession('ses_prev'), true);
|
||||
assert.equal(chat.session, 'ses_prev');
|
||||
assert.equal(chat.title, 'Earlier work');
|
||||
assert.ok(chat.items.some((i) => i.kind === 'user' && i.text === 'earlier question'));
|
||||
assert.ok(chat.items.some((i) => i.kind === 'tool' && i.title === 'read' && i.output === 'ok'));
|
||||
assert.ok(chat.items.some((i) => i.kind === 'agent' && i.text === 'earlier answer'));
|
||||
assert.equal(chat.mode, 'edit');
|
||||
assert.deepEqual(
|
||||
chat.items.map((i) => [i.kind, i.kind === 'tool' ? `${i.title}:${i.status}:${i.output}` : i.text, i.label || '']),
|
||||
[
|
||||
['user', 'earlier question', 'notes.md'],
|
||||
['thought', 'earlier thinking', ''],
|
||||
['tool', 'read:completed:the notes', ''],
|
||||
['tool', 'bash:failed:make: no rule', ''],
|
||||
['agent', 'earlier answer', ''],
|
||||
['user', '⏎ the job is done', 'harness'],
|
||||
['agent', 'noted', ''],
|
||||
],
|
||||
);
|
||||
await assert.rejects(chat.resumeSession('ses_nope'), /no such session/);
|
||||
|
||||
const qTurn = chat.send('QUESTION');
|
||||
await until(() => chat.questions.size === 1);
|
||||
const qItem = chat.items.find((i) => i.kind === 'question');
|
||||
chat.answerQuestion(qItem.id, [{ kind: 'options', labels: ['SQLite'] }]);
|
||||
await qTurn;
|
||||
assert.match(text(chat), /"kind": "options".*"SQLite"/);
|
||||
const answerTo = async (word, answers) => {
|
||||
const turn = chat.send(word);
|
||||
await until(() => chat.questions.size === 1);
|
||||
const item = chat.items.filter((i) => i.kind === 'question').pop();
|
||||
if (answers) chat.answerQuestion(item.id, answers);
|
||||
else chat.dismissQuestion(item.id);
|
||||
await turn;
|
||||
return item;
|
||||
};
|
||||
const q = await answerTo('QUESTION', [{ kind: 'options', labels: ['SQLite'] }, { kind: 'custom', text: 'waybread' }]);
|
||||
assert.deepEqual(q.questions[0].options[0], { label: 'SQLite', description: 'local file', recommended: true });
|
||||
assert.match(text(chat), /question=\{"answers": \[\{"kind": "options", "labels": \["SQLite"\]\}, \{"kind": "custom", "text": "waybread"\}\]\}/);
|
||||
await answerTo('QUESTION', [{ kind: 'options', labels: ['Postgres'] }, { kind: 'skipped' }]);
|
||||
assert.match(text(chat), /question=\{"answers": \[\{"kind": "options", "labels": \["Postgres"\]\}, null\]\}/, 'one left blank is skipped, and the other still counts');
|
||||
const multi = await answerTo('QUESTION MULTI', [{ kind: 'options', labels: ['SQLite', 'Postgres'] }, { kind: 'skipped' }]);
|
||||
assert.equal(multi.questions[0].multiple, true);
|
||||
assert.match(text(chat), /"labels": \["SQLite", "Postgres"\]/);
|
||||
await answerTo('QUESTION', null);
|
||||
assert.match(text(chat), /question=\{"dismissed": true\}/);
|
||||
|
||||
const pTurn = chat.send('PLANCARD');
|
||||
await until(() => chat.planCards.size === 1);
|
||||
const pItem = chat.items.find((i) => i.kind === 'plancard');
|
||||
chat.answerPlan(pItem.id, 'dismissed');
|
||||
await pTurn;
|
||||
assert.match(text(chat), /"outcome": "dismissed"/);
|
||||
const plan = async (outcome, value) => {
|
||||
const turn = chat.send('PLANCARD');
|
||||
await until(() => chat.planCards.size === 1);
|
||||
const item = chat.items.filter((i) => i.kind === 'plancard').pop();
|
||||
chat.answerPlan(item.id, outcome, value);
|
||||
await turn;
|
||||
return item;
|
||||
};
|
||||
const card = await plan('dismissed');
|
||||
assert.deepEqual([card.title, card.path], ['Upgrade', '.agent/plans/upgrade.md']);
|
||||
assert.match(text(chat), /plan=\{"kind": "dismissed"\}/);
|
||||
await plan('revise', 'smaller steps');
|
||||
assert.match(text(chat), /plan=\{"feedback": "smaller steps", "kind": "revise"\}/);
|
||||
await plan('approve', 'manual');
|
||||
assert.match(text(chat), /plan=\{"kind": "approve", "mode": "manual"\}/);
|
||||
assert.equal(chat.mode, 'manual', 'the session is in the mode that was approved');
|
||||
|
||||
await chat.send('/compact');
|
||||
assert.match(text(chat), /> Compacted: Compacted 2 turns\./, 'the command typed in the prompt');
|
||||
assert.equal(await chat.compact(), true);
|
||||
assert.match(text(chat), /> Session compacted: Compacted 2 turns\./);
|
||||
});
|
||||
|
||||
test('not signed in: said with what to do, the agent is not kept, and after the sign-in the next message works', async (t) => {
|
||||
const env = { FAKE_AGENT_LOGIN: 'none' };
|
||||
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. 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. 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)));
|
||||
});
|
||||
+714
-118
File diff suppressed because it is too large.
Load diff
@@ -1,408 +0,0 @@
|
||||
#!/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
|
||||
PUT <path> asks the client to make "put by the agent" + a line break the file's text; writes
|
||||
the disk itself when the client answers with an error, as the CLI does
|
||||
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 "PUT " in text:
|
||||
path = word_after(text, "PUT")
|
||||
with lock:
|
||||
next_id[0] += 1
|
||||
rid = next_id[0]
|
||||
done = threading.Event()
|
||||
waiting[rid] = [done, None]
|
||||
out({"jsonrpc": "2.0", "id": rid, "method": "fs/write_text_file",
|
||||
"params": {"sessionId": session, "path": path, "content": "put by the agent\n"}})
|
||||
done.wait(10)
|
||||
answer = waiting.pop(rid)[1]
|
||||
if answer is None:
|
||||
with open(path, "w") as f:
|
||||
f.write("put by the agent\n")
|
||||
say(session, "\nput=" + ("client" if answer is not None else "disk"))
|
||||
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 "QUESTION" in text:
|
||||
answer = ask("_lembas/question", {
|
||||
"sessionId": session,
|
||||
"toolCallId": "q-" + str(msg["id"]),
|
||||
"why": "Need a choice",
|
||||
"questions": [{
|
||||
"header": "Database",
|
||||
"question": "Which backend?",
|
||||
"multiple": False,
|
||||
"options": [{"label": "SQLite", "description": "local file"}, {"label": "Postgres", "description": "server"}],
|
||||
}],
|
||||
})
|
||||
say(session, "\nquestion=" + json.dumps(answer, sort_keys=True))
|
||||
if "PLANCARD" in text:
|
||||
answer = ask("_lembas/plan", {
|
||||
"sessionId": session,
|
||||
"toolCallId": "p-" + str(msg["id"]),
|
||||
"path": ".agent/plans/test.md",
|
||||
"text": "# Upgrade\n- Step 1\n- Step 2",
|
||||
"plan": {"title": "Upgrade", "phases": [{"title": "Phase 1", "tasks": [{"text": "Step 1", "status": "todo"}]}]},
|
||||
})
|
||||
say(session, "\nplan=" + 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", "files", "commands", "steer", "sessions", "ask", "plan", "compact"]}}
|
||||
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 method == "_lembas/complete/warm":
|
||||
pass
|
||||
elif method == "_lembas/files/search":
|
||||
q = str((msg.get("params") or {}).get("query") or "").lower()
|
||||
sample = [
|
||||
{"path": "src/app.py", "kind": "file"},
|
||||
{"path": "src/utils.py", "kind": "file"},
|
||||
{"path": "src", "kind": "dir"},
|
||||
{"path": "README.md", "kind": "file"},
|
||||
]
|
||||
result(msg, {"root": os.getcwd(), "files": [f for f in sample if not q or q in f["path"].lower()]})
|
||||
elif method == "_lembas/commands":
|
||||
result(msg, {"commands": [{"name": "compact", "description": "Compact context", "_meta": {"lembas": {"kind": "builtin"}}}]})
|
||||
elif method == "_lembas/session/compact":
|
||||
result(msg, {"summary": "Compacted 2 turns."})
|
||||
elif method == "_lembas/steer":
|
||||
result(msg, {"queued": 1})
|
||||
elif method == "_lembas/sessions/list":
|
||||
result(msg, {"sessions": [{"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000000000}]})
|
||||
elif method == "_lembas/sessions/resume":
|
||||
sid = (msg.get("params") or {}).get("sessionId") or "ses_prev"
|
||||
result(msg, {
|
||||
"sessionId": sid,
|
||||
"title": "Earlier work",
|
||||
"modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]},
|
||||
"turns": [
|
||||
{"role": "user", "text": "earlier question"},
|
||||
{"role": "assistant", "text": "earlier answer", "reasoning": "", "tools": [{"id": "t1", "name": "read", "args": "{}", "output": "ok"}]},
|
||||
],
|
||||
"_meta": {"lembas": {"model": session_model[0], "mode": "edit"}},
|
||||
})
|
||||
elif "id" in msg:
|
||||
refuse(msg, -32601, "Method not found")
|
||||
|
||||
|
||||
main()
|
||||
@@ -6,11 +6,13 @@ const path = require('node:path');
|
||||
const { Agent } = require('../src/agent');
|
||||
const { Chat } = require('../src/chat');
|
||||
|
||||
const FAKE = path.join(__dirname, 'fake_agent.py');
|
||||
// The stand-in both editors' tests share: it answers in the LLeMbas CLI's own shapes.
|
||||
const FAKE = path.join(__dirname, '..', '..', 'tests', '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 }));
|
||||
// An agent that is ending may still write its log: tried again rather than failed.
|
||||
t.after(() => fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }));
|
||||
return dir;
|
||||
}
|
||||
|
||||
|
||||
@@ -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));
|
||||
});
|
||||
@@ -278,6 +278,8 @@ test('an item of the transcript is drawn from its fields as text', () => {
|
||||
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 steered = page.renderItem(doc, { id: 'i3', kind: 'user', text: 'and this', steered: true }, post);
|
||||
assert.ok(steered.textContent.startsWith('You (sent while working)'), steered.textContent);
|
||||
|
||||
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');
|
||||
@@ -327,6 +329,14 @@ test('the page: a strict policy, one script with a nonce, nothing from elsewhere
|
||||
});
|
||||
assert.ok(multi.includes('style-src vscode-resource: https://file+.vscode-resource.vscode-cdn.net;'));
|
||||
assert.throws(() => chatHtml({ cspSource: "https://a.example; script-src 'unsafe-inline'", nonce: 'abc', scriptUri: 's', styleUri: 't' }));
|
||||
// Layout invariant: the body is the tab strip and the frame; the conversation is one view of the
|
||||
// frame with its own three rows (.chrome, #log, footer), so nothing hidden inside .chrome ever
|
||||
// shifts #log or the footer off their tracks.
|
||||
const body = /<body>([\s\S]*)<\/body>/.exec(html)[1];
|
||||
assert.match(body, /^\s*<nav class="tabs"[\s\S]*<\/nav>\s*<div id="stage" class="stage">[\s\S]*<\/div>\s*<div id="announce"[^>]*><\/div>\s*<script\b/);
|
||||
assert.match(body, /<section id="view-chat"[^>]*>\s*<div class="chrome">[\s\S]*<\/div>\s*<main id="log"[\s\S]*<\/main>\s*<footer>[\s\S]*<\/footer>\s*<\/section>/);
|
||||
const css = fs.readFileSync(path.join(__dirname, '..', 'media', 'chat.css'), 'utf8');
|
||||
assert.match(css, /grid-template-rows:\s*auto minmax\(0,\s*1fr\) auto;/);
|
||||
});
|
||||
|
||||
test('the stylesheet takes every colour from the editor\'s theme', () => {
|
||||
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user