LLeMbas IDE: the Neovim plugin's first version

A chat panel on `lembas serve --stdio` of the LLeMbas CLI: ask about a selection, have it
rewritten, approvals asked in the editor, mode and model. The VS Code extension is a placeholder.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-11-24 06:57:37 +00:00
commit 85a26a811c
16 files changed
+1122

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
*.vsix
node_modules/
__pycache__/
*.pyc
+14
View File
@@ -0,0 +1,14 @@
# Changelog
## [Unreleased]
### Neovim plugin
- First version. A chat panel beside your files, on `lembas serve --stdio` of the LLeMbas CLI:
`:LLeMbas` opens it, `:LLeMbasAsk` asks about the selected lines (with a question at once, without one
the lines go with the next message you type), `:LLeMbasEdit` has the selected lines rewritten,
`:LLeMbasStop`, `:LLeMbasNew`, `:LLeMbasMode` and `:LLeMbasModel`.
- A selection is sent as the buffer has it, saved or not, with its file, its lines and the
diagnostics shown on them. A typed message names the file you are in.
- The CLI's approval cards are asked in the editor; closing one is a denial.
- Files the agent changes are reloaded in buffers that have no changes of their own.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Jaroslav Beneš
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+54
View File
@@ -0,0 +1,54 @@
# LLeMbas IDE
LLeMbas in your editor: a Neovim plugin, and a VS Code / VSCodium extension (not written yet).
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.
This is a beta. It needs LLeMbas CLI 2.0.0-beta.12 or newer, signed in (`lembas login <address>`).
## Neovim
Needs Neovim 0.10 or newer. The plugin lives in `nvim/`, so the runtime path points there.
lazy.nvim:
```lua
{
"LLeMbas/LLeMbas-IDE",
branch = "dev",
config = function(plugin)
vim.opt.rtp:append(plugin.dir .. "/nvim")
vim.cmd("runtime plugin/llembas.lua")
require("llembas").setup({})
end,
}
```
vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }`
| Command | What it does |
|---|---|
| `:LLeMbas` | open or close the chat panel |
| `:'<,'>LLeMbasAsk [question]` | ask about the selected lines; without a question they go with the next message |
| `:'<,'>LLeMbasEdit [instruction]` | have the selected lines rewritten (the file must be saved) |
| `:LLeMbasStop` | stop the running turn |
| `:LLeMbasNew` | start a new session |
| `:LLeMbasMode [mode]` | change the mode |
| `:LLeMbasModel [model]` | show or change the model |
In the prompt: Enter (normal mode) or Ctrl-S sends, Ctrl-C stops the turn, `q` closes the panel.
Help: `:help llembas`.
Not there yet: completion as you type, a rewrite shown as a diff you accept or reject, picking an
older session. In this version the agent changes files on disk itself, under the CLI's permissions.
## Tests
`scripts/test-nvim.sh` runs the plugin headless against a stand-in agent (needs `nvim` and `python3`).
## Licence
MIT.
+1
View File
@@ -0,0 +1 @@
1.0.0-beta.1
+51
View File
@@ -0,0 +1,51 @@
*llembas.txt* LLeMbas in Neovim
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.
==============================================================================
COMMANDS *llembas-commands*
:LLeMbas *:LLeMbas*
Open or close the chat panel: the transcript, and the prompt under it.
In the prompt, <CR> in normal mode or <C-s> sends, <C-c> stops the turn,
q closes the panel.
:[range]LLeMbasAsk [question] *:LLeMbasAsk*
Ask about the lines of [range]. They are sent as the buffer has them,
saved or not, with the file, the line numbers and the diagnostics on them.
Without a question the lines are attached to the next message you type.
:[range]LLeMbasEdit [instruction] *:LLeMbasEdit*
Have the lines of [range] rewritten. The agent changes the file on disk
under the CLI's permissions, so the buffer must be saved first; it is
reloaded when the agent is done.
:LLeMbasStop *:LLeMbasStop*
Stop the running turn.
:LLeMbasNew *:LLeMbasNew*
Start a new session. The old one stays in the CLI's store.
:LLeMbasMode [mode] *:LLeMbasMode*
Change the session's mode; without an argument, pick from a list.
:LLeMbasModel [model] *:LLeMbasModel*
Show the session's model, or change it to one your server serves.
==============================================================================
SETUP *llembas-setup*
>lua
require("llembas").setup({
cmd = { "lembas", "serve", "--stdio" }, -- the agent
width = 64, -- the panel's columns
mode = nil, -- the mode a session starts in
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
})
<
What the model writes is shown as text. It is never run, and the panel's
buffers read no modeline.
vim:tw=78:ts=8:ft=help:norl:
+175
View File
@@ -0,0 +1,175 @@
-- The chat panel: a transcript nobody types in and a prompt under it. What the model writes is put
-- there as text and nothing else: it is never run, and modelines are off in both buffers.
local M = { tbuf = nil, ibuf = nil, marks = {}, on_send = nil, on_stop = nil }
local ns = vim.api.nvim_create_namespace("llembas")
local function valid(b) return b and vim.api.nvim_buf_is_valid(b) end
local function win_of(buf)
if not valid(buf) then return nil end
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if vim.api.nvim_win_get_buf(w) == buf then return w end
end
end
local function scratch(name, ft)
local b = vim.api.nvim_create_buf(false, true)
vim.bo[b].buftype = "nofile"
vim.bo[b].bufhidden = "hide"
vim.bo[b].swapfile = false
vim.bo[b].modeline = false
vim.bo[b].filetype = ft
pcall(vim.api.nvim_buf_set_name, b, name)
return b
end
local function buffers()
if not valid(M.tbuf) then
M.tbuf = scratch("llembas://chat", "markdown")
vim.bo[M.tbuf].modifiable = false
M.marks = {}
end
if not valid(M.ibuf) then
M.ibuf = scratch("llembas://prompt", "markdown")
local function send()
local text = table.concat(vim.api.nvim_buf_get_lines(M.ibuf, 0, -1, false), "\n")
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" })
vim.keymap.set({ "n", "i" }, "<C-s>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
vim.keymap.set("n", "<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" })
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" })
end
end
function M.is_open() return win_of(M.tbuf) ~= nil end
--- Open the panel (a column on the right: the transcript, and the prompt under it).
function M.open(width, focus)
buffers()
local back = vim.api.nvim_get_current_win()
local tw = win_of(M.tbuf)
if not tw then
vim.cmd("botright vertical " .. width .. "split")
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 = true }) do
vim.wo[tw][k] = v
end
end
local iw = win_of(M.ibuf)
if not iw then
vim.api.nvim_set_current_win(tw)
vim.cmd("belowright 5split")
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
vim.wo[iw][k] = v
end
end
if focus == false and vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back)
else vim.api.nvim_set_current_win(iw) end
end
function M.close()
for _, b in ipairs({ M.ibuf, M.tbuf }) 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
end
--- The line above the prompt: what the next message carries, the mode, the model.
function M.status(text)
local w = win_of(M.ibuf)
if w then vim.wo[w].winbar = (text or ""):gsub("%%", "%%%%") end
end
local function edit(fn)
buffers()
local tw = win_of(M.tbuf)
local last = vim.api.nvim_buf_line_count(M.tbuf)
local follow = tw and vim.api.nvim_win_get_cursor(tw)[1] >= last
vim.bo[M.tbuf].modifiable = true
local ok, err = pcall(fn)
vim.bo[M.tbuf].modifiable = false
if follow and tw and vim.api.nvim_win_is_valid(tw) then
pcall(vim.api.nvim_win_set_cursor, tw, { vim.api.nvim_buf_line_count(M.tbuf), 0 })
end
if not ok then error(err, 0) end
end
--- Add text at the end, continuing the last line.
function M.append(text)
if not text or text == "" then return end
edit(function()
-- Inserted at the very end, so a line that is rewritten later keeps its mark.
local parts = vim.split(text, "\n", { plain = true })
local n = vim.api.nvim_buf_line_count(M.tbuf)
local tail = vim.api.nvim_buf_get_lines(M.tbuf, n - 1, n, false)[1] or ""
vim.api.nvim_buf_set_text(M.tbuf, n - 1, #tail, n - 1, #tail, parts)
end)
end
local function last_line()
local n = vim.api.nvim_buf_line_count(M.tbuf)
return n, vim.api.nvim_buf_get_lines(M.tbuf, n - 1, n, false)[1] or ""
end
--- Start a new line unless the transcript already ends on an empty one.
function M.newline()
buffers()
local n, tail = last_line()
if tail ~= "" then M.append("\n") elseif n == 1 then return end
end
function M.section(title)
buffers()
local n, tail = last_line()
if not (n == 1 and tail == "") then
M.newline()
local _, t = last_line()
local prev = vim.api.nvim_buf_get_lines(M.tbuf, -3, -2, false)[1]
if t == "" and prev ~= "" then M.append("\n") end
end
M.append("## " .. title .. "\n\n")
end
--- One line that is rewritten later under the same `id` (a tool call, the plan).
function M.line(id, text)
buffers()
text = (text:gsub("[\r\n]+", " "))
local mark = M.marks[id]
if mark then
local pos = vim.api.nvim_buf_get_extmark_by_id(M.tbuf, ns, mark, {})
if pos[1] then
edit(function()
local old = vim.api.nvim_buf_get_lines(M.tbuf, pos[1], pos[1] + 1, false)[1] or ""
vim.api.nvim_buf_set_text(M.tbuf, pos[1], 0, pos[1], #old, { text })
end)
return
end
end
M.newline()
M.append(text)
local n = vim.api.nvim_buf_line_count(M.tbuf)
M.marks[id] = vim.api.nvim_buf_set_extmark(M.tbuf, ns, n - 1, 0, { right_gravity = false })
M.append("\n")
end
function M.clear()
buffers()
M.marks = {}
vim.bo[M.tbuf].modifiable = true
vim.api.nvim_buf_clear_namespace(M.tbuf, ns, 0, -1)
vim.api.nvim_buf_set_lines(M.tbuf, 0, -1, false, {})
vim.bo[M.tbuf].modifiable = false
end
function M.text()
buffers()
return table.concat(vim.api.nvim_buf_get_lines(M.tbuf, 0, -1, false), "\n")
end
return M
+53
View File
@@ -0,0 +1,53 @@
-- What the editor knows and the agent is told: the file, the selection, the diagnostics on it.
local M = {}
local function uri_of(buf)
local name = vim.api.nvim_buf_get_name(buf)
if name == "" then return nil, nil end
return vim.uri_from_fname(name), name
end
--- Lines `first..last` (1-based, inclusive) of `buf` as prompt blocks: a sentence saying where the
--- text is from, and the text itself as an embedded resource. The text is the buffer's, saved or not.
function M.selection(buf, first, last)
local lines = vim.api.nvim_buf_get_lines(buf, first - 1, last, false)
local uri, name = uri_of(buf)
local where = name and vim.fn.fnamemodify(name, ":.") or "an unnamed buffer"
local ft = vim.bo[buf].filetype
local head = ("Selected in the editor: %s, lines %d-%d%s%s."):format(
where, first, last, ft ~= "" and (" (" .. ft .. ")") or "",
vim.bo[buf].modified and ", not saved yet" or "")
local blocks = { { type = "text", text = head } }
blocks[#blocks + 1] = {
type = "resource",
resource = { uri = (uri or "untitled:buffer") .. "#L" .. first .. "-" .. last, mimeType = "text/plain", text = table.concat(lines, "\n") },
}
local diags = M.diagnostics(buf, first, last)
if diags then blocks[#blocks + 1] = { type = "text", text = diags } end
return blocks
end
--- The diagnostics on lines `first..last`, as one text; nil when there are none.
function M.diagnostics(buf, first, last)
local out = {}
for _, d in ipairs(vim.diagnostic.get(buf)) do
local l = d.lnum + 1
if l >= first and l <= last and #out < 30 then
local sev = vim.diagnostic.severity[d.severity] or "INFO"
out[#out + 1] = ("- line %d, %s%s: %s"):format(l, sev:lower(), d.source and (" (" .. d.source .. ")") or "", (d.message:gsub("%s+", " ")))
end
end
if #out == 0 then return nil end
return "Diagnostics the editor shows there:\n" .. table.concat(out, "\n")
end
--- The file in `buf` named to the agent, without its text (the agent reads it itself).
function M.file(buf)
local _, name = uri_of(buf)
if not name then return nil end
local row = vim.api.nvim_win_get_cursor(0)[1]
return { type = "text", text = ("Open in the editor: %s, cursor on line %d%s."):format(
vim.fn.fnamemodify(name, ":."), row, vim.bo[buf].modified and " (the buffer has changes that are not saved)" or "") }
end
return M
+327
View File
@@ -0,0 +1,327 @@
-- LLeMbas in Neovim. The agent is the LLeMbas CLI, unchanged: this plugin starts `lembas serve --stdio`
-- and is its client (Agent Client Protocol, version 1). Models, permissions, tools and the sign-in are
-- the CLI's; nothing is set here but how the panel looks and which command starts the agent.
local rpc = require("llembas.rpc")
local chat = require("llembas.chat")
local context = require("llembas.context")
local M = {}
M.config = {
cmd = { "lembas", "serve", "--stdio" }, -- the agent
width = 64, -- the panel's columns
mode = nil, -- the mode a session starts in (the CLI's own when nil)
model = nil, -- the model a session starts on (the CLI's own when nil)
show_thoughts = false, -- the model's thinking in the transcript
send_open_file = true, -- a prompt names the file you are in
}
local S = { conn = nil, session = nil, starting = nil, busy = false, modes = {}, mode = nil, model = nil,
attached = nil, attached_label = nil, last_buf = nil, said = nil }
local function note(text) chat.newline(); chat.append("> " .. text .. "\n") end
local function status()
local parts = {}
if S.attached_label then parts[#parts + 1] = "with " .. S.attached_label end
if S.mode then parts[#parts + 1] = "mode " .. S.mode end
if S.model then parts[#parts + 1] = S.model end
if S.busy then parts[#parts + 1] = "working (Ctrl-C stops)" end
chat.status(" " .. table.concat(parts, " | "))
end
local function reload_files()
-- The agent writes files itself; a buffer without changes of its own takes the new text.
pcall(vim.cmd, "silent! checktime")
end
local ICON = { pending = "…", in_progress = "…", completed = "✓", failed = "✗" }
local tools = {}
local function on_update(u)
local kind = u.sessionUpdate
if kind == "agent_message_chunk" then
if S.said ~= "agent" then chat.section("LLeMbas"); S.said = "agent" end
if u.content and u.content.type == "text" then chat.append(u.content.text) end
elseif kind == "agent_thought_chunk" then
if M.config.show_thoughts and u.content and u.content.type == "text" then
if S.said ~= "thought" then chat.section("Thinking"); S.said = "thought" end
chat.append(u.content.text)
end
elseif kind == "tool_call" or kind == "tool_call_update" then
local t = tools[u.toolCallId] or {}
tools[u.toolCallId] = t
t.title = u.title or t.title or "tool"
t.status = u.status or t.status or "pending"
chat.line("tool:" .. u.toolCallId, ("- %s %s"):format(ICON[t.status] or "…", t.title))
S.said = "tool"
if t.status == "completed" then reload_files() end
elseif kind == "plan" then
local done, all = 0, 0
for _, e in ipairs(u.entries or {}) do
all = all + 1
if e.status == "completed" then done = done + 1 end
end
if all > 0 then chat.line("plan", ("- plan: %d of %d tasks done"):format(done, all)); S.said = "tool" end
elseif kind == "current_mode_update" then
S.mode = u.currentModeId or S.mode
status()
end
end
local function on_permission(p, reply)
local call = p.toolCall or {}
local meta = (p._meta or {}).lembas or {}
local options = p.options or {}
chat.line("ask:" .. tostring(call.toolCallId), "- ? " .. (call.title or meta.tool or "a tool") .. " (waits for your answer)")
local prompt = "LLeMbas asks: " .. (call.title or meta.tool or "a tool")
if meta.reason then prompt = prompt .. " (" .. meta.reason .. ")" end
vim.ui.select(options, {
prompt = prompt:gsub("[\r\n]+", " "):sub(1, 400),
format_item = function(o) return o.name or o.optionId end,
}, function(choice)
if not choice then
chat.line("ask:" .. tostring(call.toolCallId), "- ✗ " .. (call.title or "a tool") .. " (not answered: denied)")
return reply({ outcome = { outcome = "cancelled" } })
end
chat.line("ask:" .. tostring(call.toolCallId), ("- %s: %s"):format(choice.name or choice.optionId, call.title or "a tool"))
reply({ outcome = { outcome = "selected", optionId = choice.optionId } })
end)
end
local function stopped(code, stderr)
local was = S.conn ~= nil or S.starting ~= nil
local waiting = S.starting
S.conn, S.session, S.starting, S.busy = nil, nil, nil, false
if was then
local last = ""
for line in (stderr or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end
note(("The agent stopped (exit %s)%s"):format(tostring(code), last ~= "" and (": " .. last) or "."))
end
for _, cb in ipairs(waiting or {}) do cb(false) end
status()
end
--- Have a running agent and an open session, then call `cb(true)`; `cb(false)` when that failed.
local function ensure(cb)
if S.session then return cb(true) end
if S.starting then S.starting[#S.starting + 1] = cb; return end
S.starting = { cb }
local function fail(what)
note(what)
local conn = S.conn
local waiting = S.starting or {}
S.conn, S.starting, S.session = nil, nil, nil
if conn then conn:stop() end
for _, f in ipairs(waiting) do f(false) end
end
local conn, err = rpc.start(M.config.cmd, {
notify = function(method, params)
if method == "session/update" and params.sessionId == S.session then on_update(params.update or {}) end
end,
request = function(method, params, reply)
if method == "session/request_permission" then return on_permission(params, reply) end
reply(nil, { code = -32601, message = "Method not found: " .. method })
end,
exit = stopped,
}, { cwd = vim.fn.getcwd() })
if not conn then
S.starting = nil
note(("Could not start %s: %s"):format(M.config.cmd[1], err))
return cb(false)
end
S.conn = conn
conn:request("initialize", { protocolVersion = 1, clientCapabilities = {},
clientInfo = { name = "llembas.nvim", version = M.version } }, function(e1)
if S.conn ~= conn then return end
if e1 then return fail("The agent refused to start: " .. tostring(e1.message)) end
local meta = {}
if M.config.mode then meta.mode = M.config.mode end
if M.config.model then meta.model = M.config.model end
conn:request("session/new", { cwd = vim.fn.getcwd(), mcpServers = {}, _meta = meta }, function(e2, r)
if S.conn ~= conn then return end
if e2 then return fail("No session: " .. tostring(e2.message)) end
S.session = r.sessionId
S.modes = (r.modes and r.modes.availableModes) or {}
local lm = (r._meta or {}).lembas or {}
S.mode = (r.modes and r.modes.currentModeId) or lm.mode
S.model = lm.model
local waiting = S.starting or {}
S.starting = nil
status()
for _, f in ipairs(waiting) do f(true) end
end)
end)
end
--- Send `blocks` as a prompt; `shown` is what the transcript says you wrote.
local function send(blocks, shown)
if S.busy then
vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN)
return false
end
chat.section("You")
chat.append(shown .. "\n")
S.said = "you"
S.busy = true
status()
ensure(function(ok)
if not ok then S.busy = false; status(); return end
S.conn:request("session/prompt", { sessionId = S.session, prompt = blocks }, function(err, r)
S.busy = false
if err then note("The turn failed: " .. tostring(err.message))
elseif r and r.stopReason and r.stopReason ~= "end_turn" then note("The turn ended: " .. r.stopReason) end
chat.newline()
reload_files()
status()
end)
end)
return true
end
local function editing_buf()
local b = vim.api.nvim_get_current_buf()
if vim.bo[b].buftype == "" then return b end
if S.last_buf and vim.api.nvim_buf_is_valid(S.last_buf) then return S.last_buf end
end
--- A prompt typed in the panel: with what was attached, or else the name of the open file.
local function send_typed(text)
local blocks, shown = {}, text
if S.attached then
vim.list_extend(blocks, S.attached)
shown = ("[%s]\n%s"):format(S.attached_label, text)
elseif M.config.send_open_file and not text:match("^/") then
local b = editing_buf()
local f = b and context.file(b)
if f then blocks[#blocks + 1] = f end
end
blocks[#blocks + 1] = { type = "text", text = text }
if send(blocks, shown) == false then return false end
S.attached, S.attached_label = nil, nil
status()
end
local function label(buf, first, last)
local name = vim.api.nvim_buf_get_name(buf)
return ("%s:%d-%d"):format(name ~= "" and vim.fn.fnamemodify(name, ":.") or "buffer", first, last)
end
function M.open(focus)
local b = vim.api.nvim_get_current_buf()
if vim.bo[b].buftype == "" then S.last_buf = b end
chat.on_send = send_typed
chat.on_stop = M.stop
chat.open(M.config.width, focus)
status()
end
function M.toggle()
if chat.is_open() then chat.close() else M.open() end
end
--- Ask about lines `first..last` of the current buffer. With `question` it is sent at once; without,
--- the lines are attached to the next message you type.
function M.ask(first, last, question)
local buf = vim.api.nvim_get_current_buf()
local blocks = context.selection(buf, first, last)
local what = label(buf, first, last)
if question and question:match("%S") then
M.open(false)
blocks[#blocks + 1] = { type = "text", text = question }
send(blocks, ("[%s]\n%s"):format(what, question))
else
S.attached, S.attached_label = blocks, what
M.open(true)
end
end
--- Have lines `first..last` rewritten as `instruction` says. The agent changes the file itself, under
--- its own permissions, so the buffer has to be saved first.
function M.edit(first, last, instruction)
local buf = vim.api.nvim_get_current_buf()
if vim.api.nvim_buf_get_name(buf) == "" or vim.bo[buf].buftype ~= "" then
return vim.notify("LLeMbas: this buffer is not a file", vim.log.levels.WARN)
end
if vim.bo[buf].modified then
return vim.notify("LLeMbas: save the file first (the agent edits the file on disk)", vim.log.levels.WARN)
end
if not instruction or not instruction:match("%S") then
return vim.ui.input({ prompt = "Rewrite the selection: " }, function(text)
if text and text:match("%S") then M.edit(first, last, text) end
end)
end
local blocks = context.selection(buf, first, last)
blocks[#blocks + 1] = { type = "text", text =
"Rewrite exactly those lines of that file as asked below. Change nothing outside them unless the request "
.. "cannot work otherwise, and then say what else you changed. Answer with one or two sentences, not with the code.\n\n"
.. instruction }
M.open(false)
send(blocks, ("[rewrite %s]\n%s"):format(label(buf, first, last), instruction))
end
function M.stop()
if S.conn and S.session and S.busy then S.conn:notify("session/cancel", { sessionId = S.session }) end
end
--- A new session; the old one stays in the CLI's store.
function M.new()
if S.busy then return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop)", vim.log.levels.WARN) end
local conn = S.conn
S.conn, S.session, S.starting, S.said = nil, nil, nil, nil
tools = {}
if conn then conn:stop() end
chat.clear()
M.open()
end
function M.mode(id)
ensure(function(ok)
if not ok then return end
local function set(mode)
S.conn:request("session/set_mode", { sessionId = S.session, modeId = mode }, function(err)
if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end
S.mode = mode
status()
end)
end
if id and id ~= "" then return set(id) end
vim.ui.select(S.modes, { prompt = "LLeMbas mode", format_item = function(m) return m.name or m.id end },
function(m) if m then set(m.id) end end)
end)
end
function M.model(name)
if not name or name == "" then return vim.notify("LLeMbas: model " .. (S.model or "not known yet"), vim.log.levels.INFO) end
ensure(function(ok)
if not ok then return end
S.conn:request("_lembas/configure", { sessionId = S.session, model = name }, function(err, r)
if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end
S.model = (r and r.model) or name
status()
end)
end)
end
function M.mode_ids()
return vim.tbl_map(function(m) return m.id end, S.modes)
end
function M.setup(opts)
M.config = vim.tbl_deep_extend("force", M.config, opts or {})
if type(M.config.cmd) == "string" then M.config.cmd = { M.config.cmd, "serve", "--stdio" } end
end
M.version = "1.0.0-beta.1"
M._state = S -- for the tests
vim.api.nvim_create_autocmd("VimLeavePre", {
group = vim.api.nvim_create_augroup("llembas", { clear = true }),
callback = function() if S.conn then S.conn:stop() end end,
})
vim.api.nvim_create_autocmd("BufEnter", {
group = "llembas",
callback = function(ev) if vim.bo[ev.buf].buftype == "" then S.last_buf = ev.buf end end,
})
return M
+95
View File
@@ -0,0 +1,95 @@
-- JSON-RPC 2.0 over lines on a child process's stdin and stdout: the framing ACP uses on stdio.
local M = {}
M.__index = M
--- 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 ok, proc = pcall(vim.system, cmd, {
stdin = true,
cwd = opts and opts.cwd or nil,
env = opts and opts.env or nil,
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
end
end,
}, function(res)
vim.schedule(function()
self.closed = true
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
end)
end)
if not ok then return nil, tostring(proc) end
self.proc = proc
return self
end
function M:_feed(data)
self.buf = self.buf .. data
while true do
local nl = self.buf:find("\n", 1, true)
if not nl then break end
local line = self.buf:sub(1, nl - 1)
self.buf = self.buf:sub(nl + 1)
if 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
end
end
end
function M:_message(msg)
if msg.method then
if msg.id ~= nil then
local answered = false
local function reply(result, err)
if answered then return end
answered = true
if err then self:_write({ jsonrpc = "2.0", id = msg.id, error = err })
else self:_write({ jsonrpc = "2.0", id = msg.id, result = result == nil and vim.NIL or result }) end
end
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 {})
end
elseif msg.id ~= nil then
local cb = self.waiting[msg.id]
self.waiting[msg.id] = nil
if cb then cb(msg.error, msg.result) end
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)
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
self:_write({ jsonrpc = "2.0", id = id, method = method, params = params })
return id
end
function M:notify(method, params)
self:_write({ jsonrpc = "2.0", method = method, params = params })
end
function M:stop()
if self.closed then return end
pcall(function() self.proc:write(nil) end)
pcall(function() self.proc:kill(15) end)
end
return M
+20
View File
@@ -0,0 +1,20 @@
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)
return
end
local function L() return require("llembas") end
local cmd = vim.api.nvim_create_user_command
cmd("LLeMbas", function() L().toggle() end, { desc = "LLeMbas: open or close the chat panel" })
cmd("LLeMbasAsk", function(o) L().ask(o.line1, o.line2, o.args) end,
{ range = true, nargs = "*", desc = "LLeMbas: ask about the selected lines" })
cmd("LLeMbasEdit", function(o) L().edit(o.line1, o.line2, o.args) end,
{ range = true, nargs = "*", desc = "LLeMbas: have the selected lines rewritten" })
cmd("LLeMbasStop", function() L().stop() end, { desc = "LLeMbas: stop the running turn" })
cmd("LLeMbasNew", function() L().new() end, { desc = "LLeMbas: start a new session" })
cmd("LLeMbasMode", function(o) L().mode(o.args) end,
{ nargs = "?", complete = function() return L().mode_ids() end, desc = "LLeMbas: change the mode" })
cmd("LLeMbasModel", function(o) L().model(o.args) end, { nargs = "?", desc = "LLeMbas: show or change the model" })
+109
View File
@@ -0,0 +1,109 @@
#!/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]
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 "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 "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:
entry[1] = msg.get("result")
entry[0].set()
elif method == "initialize":
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"protocolVersion": 1, "agentCapabilities": {}}})
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()
+161
View File
@@ -0,0 +1,161 @@
-- The plugin's tests, against tests/fake_agent.py. Run by scripts/test-nvim.sh:
-- nvim --headless -u NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua
local here = debug.getinfo(1, "S").source:sub(2):match("(.*/)")
local tmp = vim.fn.tempname()
vim.fn.mkdir(tmp, "p")
local log = tmp .. "/agent.log"
vim.env.FAKE_AGENT_LOG = log
vim.cmd("runtime plugin/llembas.lua")
local L = require("llembas")
local chat = require("llembas.chat")
L.setup({ cmd = { "python3", here .. "fake_agent.py" }, width = 50 })
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 wait(cond) return vim.wait(8000, cond, 20) end
local function idle() return wait(function() return not L._state.busy end) 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 last_prompt()
local all = sent()
for i = #all, 1, -1 do if all[i].method == "session/prompt" then return all[i].params.prompt end end
end
local function type_and_send(text)
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, vim.split(text, "\n"))
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<CR>", true, false, true), "x", false)
end
local version = vim.trim(table.concat(vim.fn.readfile(here .. "../../VERSION"), ""))
check("version: the plugin says the repository's version", L.version == version, L.version .. " / " .. version)
-- A file to work in.
local file = tmp .. "/sample.py"
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, file)
vim.cmd("edit " .. vim.fn.fnameescape(file))
local fbuf = vim.api.nvim_get_current_buf()
-- 1. The panel opens beside the file and a typed prompt is answered.
vim.cmd("LLeMbas")
check("panel: two windows are added and the prompt has the focus",
#vim.api.nvim_tabpage_list_wins(0) == 3 and vim.api.nvim_get_current_buf() == chat.ibuf)
type_and_send("hello")
check("prompt: the turn ends", idle())
local text = chat.text()
check("prompt: what was typed and the answer are in the transcript, in order",
text:find("## You\n\nhello\n\n## LLeMbas\n\nHello there.\nSecond line", 1, true) ~= nil, text)
check("prompt: thinking is not shown by default", not text:find("hidden thought", 1, true))
check("prompt: the prompt buffer is emptied", table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "")
local p = last_prompt()
check("prompt: the open file is named, its text is not sent",
#p == 2 and p[1].text:find("sample.py", 1, true) and p[1].text:find("cursor on line 1", 1, true) and p[2].text == "hello", vim.inspect(p))
local init
for _, m in ipairs(sent()) do if m.method == "initialize" then init = m end end
check("start: plain ACP, no LLeMbas client capability claimed",
init and init.params.protocolVersion == 1 and next(init.params.clientCapabilities) == nil)
check("start: the transcript cannot be typed in and reads no modeline",
vim.bo[chat.tbuf].modifiable == false and vim.bo[chat.tbuf].modeline == false and vim.bo[chat.ibuf].modeline == false)
-- 2. A selection with a question goes at once, with the unsaved text and the place.
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
vim.api.nvim_buf_set_lines(fbuf, 1, 2, false, { " return 10 # unsaved" })
vim.cmd("1,2LLeMbasAsk what does this return?")
check("ask: the turn ends", idle())
p = last_prompt()
check("ask: place, text as the buffer has it, then the question",
#p == 3 and p[1].text:find("lines 1-2", 1, true) and p[1].text:find("not saved yet", 1, true)
and p[2].type == "resource" and p[2].resource.text == "def a():\n return 10 # unsaved"
and p[2].resource.uri:find("#L1-2", 1, true) and p[3].text == "what does this return?", vim.inspect(p))
check("ask: the focus stays in the file", vim.api.nvim_get_current_buf() == fbuf)
-- 3. A selection without a question waits for the next typed message, once.
vim.cmd("4,5LLeMbasAsk")
check("attach: the prompt has the focus and says what it carries",
vim.api.nvim_get_current_buf() == chat.ibuf and vim.wo[vim.fn.bufwinid(chat.ibuf)].winbar:find("sample.py:4-5", 1, true) ~= nil)
type_and_send("and this?")
idle()
p = last_prompt()
check("attach: the lines go with the message", #p == 3 and p[2].resource.text == "def b():\n return 2" and p[3].text == "and this?", vim.inspect(p))
type_and_send("again")
idle()
p = last_prompt()
check("attach: the next message carries them no more", #p == 2 and p[2].text == "again", vim.inspect(p))
-- 4. An approval is put to the person; the answer goes back.
local asked
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end
type_and_send("PERM")
idle()
check("approval: asked with the command and the reason",
asked and asked.opts.prompt:find("rm -r build", 1, true) and asked.opts.prompt:find("deletes files", 1, true)
and asked.opts.format_item(asked.items[2]) == "Deny")
check("approval: the choice reaches the agent", chat.text():find("answer=once", 1, true) ~= nil, chat.text())
vim.ui.select = function(_, _, cb) cb(nil) end
type_and_send("PERM")
idle()
check("approval: closing the question is a denial", chat.text():find("answer=cancelled", 1, true) ~= nil)
check("approval: each card is one line, rewritten with its answer",
not chat.text():find("waits for your answer", 1, true) and select(2, chat.text():gsub("rm %-r build", "")) == 2, chat.text())
-- 5. A rewrite: refused on unsaved text, then done by the agent, and the buffer takes the new text.
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
local before = #sent()
vim.cmd("1,2LLeMbasEdit make it shorter")
check("rewrite: nothing is sent while the buffer is unsaved", #sent() == before and not L._state.busy)
vim.cmd("silent write")
vim.o.autoread = true
vim.cmd("1,2LLeMbasEdit WRITE " .. file)
idle()
check("rewrite: the buffer shows what the agent wrote",
wait(function() return vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "rewritten by the agent" end),
vim.inspect(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false)))
check("rewrite: the tool call is one line, marked done", select(2, chat.text():gsub("%- ✓ edit sample%.py", "")) == 1
and not chat.text():find("… edit sample.py", 1, true), chat.text())
-- 6. A second message while one runs is refused; stop ends the turn.
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
type_and_send("SLOW")
wait(function() local q = last_prompt(); return q and q[#q].text == "SLOW" end)
before = #sent()
type_and_send("too early")
check("busy: a second message is not sent and stays in the prompt",
#sent() == before and vim.api.nvim_buf_get_lines(chat.ibuf, 0, 1, false)[1] == "too early")
vim.cmd("LLeMbasStop")
check("stop: the turn ends as cancelled", idle() and chat.text():find("The turn ended: cancelled", 1, true) ~= nil)
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
-- 7. Mode and model.
vim.cmd("LLeMbasMode edit")
check("mode: set and shown", wait(function() return L._state.mode == "edit" end))
vim.cmd("LLeMbasModel example/model-b")
check("model: set and shown", wait(function() return L._state.model == "example/model-b" end)
and vim.wo[vim.fn.bufwinid(chat.ibuf)].winbar:find("example/model-b", 1, true) ~= nil)
-- 8. The agent dying is said, with its last words, and the next message starts it again.
type_and_send("CRASH")
check("crash: the turn is over and the reason is in the transcript",
wait(function() return not L._state.busy and chat.text():find("run lembas login", 1, true) ~= nil end), chat.text())
type_and_send("back")
check("crash: the next message gets an answer from a new agent", idle() and chat.text():match("back\n\n## LLeMbas") ~= nil)
-- 9. A command that does not exist is said, not thrown.
L.setup({ cmd = { "llembas-no-such-command" } })
vim.cmd("LLeMbasNew")
type_and_send("anyone?")
check("missing: said in the transcript", wait(function() return chat.text():find("Could not start", 1, true) ~= nil end) and not L._state.busy, chat.text())
print(("RAN %d, failed %d"):format(ran, failed))
vim.fn.delete(tmp, "rf")
vim.cmd(failed == 0 and "qall!" or "cquit!")
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
# The repository is public: nothing in it may name the private estate it was written on.
# The LLeMbas section rule ("everything public is current-state and estate-free"), as a check
# that runs in CI on every push rather than a sentence somebody has to remember.
#
# Patterns are the kinds of thing that leak: a private domain, an internal `.lan` name, a
# container number, a private address range, a machine's name. This file is the one place that
# may spell them, and is skipped.
set -euo pipefail
cd "$(dirname "$0")/.."
patterns=(
'houmeres'
'\b[a-z0-9-]+\.lan\b'
'\bCT ?2[0-9]{2}\b'
'\b10\.0\.0\.[0-9]+'
'\b192\.168\.[0-9]+\.[0-9]+'
'\bgamebox\b'
'\bthor\b'
)
found=0
for pattern in "${patterns[@]}"; do
if git ls-files -z | grep -zv '^scripts/hygiene.sh$' | xargs -0 grep -nIEi -- "$pattern" ; then
echo "hygiene: the lines above match /$pattern/" >&2
found=1
fi
done
[ "$found" -eq 0 ] && echo "hygiene: nothing private in the tracked files"
exit "$found"
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# The Neovim plugin's tests: headless, against a stand-in agent. Needs nvim 0.10+ and python3.
set -eu
cd "$(dirname "$0")/.."
exec nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua
+3
View File
@@ -0,0 +1,3 @@
# LLeMbas for VS Code and VSCodium
Not written yet. It will be a client of `lembas serve --stdio`, like the Neovim plugin beside it.