Files
LLeMbas-IDE/nvim/lua/llembas/init.lua
T
HomerandClaude Fable 5.2 572d12e967 LLeMbas IDE: the four bars are its screen; its keys for LLeMbas are the plugin's one table
The IDE starts with the tree open on the left and LLeMbas's settings, chat and prompt on the
right, the state on top and the keys for where the focus is at the bottom. Its cheat sheet and
README read LLeMbas's keys from the plugin's key table; the statusline and the line of buffers
stand in when a bar is switched off; a session saves the code's windows only. Tests at 160x45,
100x30 and 80x24 on the installed IDE's own screen.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:44:14 +00:00

2066 lines
93 KiB
Lua
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
-- 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 ui = require("llembas.ui")
local store = require("llembas.store")
local M = {}
local function read_repo_version()
local src = debug.getinfo(1, "S").source
if type(src) == "string" and src:sub(1, 1) == "@" then
local vfile = vim.fn.fnamemodify(src:sub(2), ":p:h:h:h:h") .. "/VERSION"
if vim.fn.filereadable(vfile) == 1 then
local v = vim.trim(table.concat(vim.fn.readfile(vfile), ""))
if v ~= "" then return v end
end
end
return "1.0.0-beta.7"
end
--- The oldest LLeMbas CLI everything here works with (`_lembas/configure` on `serve --stdio`).
M.MIN_CLI = "2.0.0-beta.16"
--- How long the agent has to answer `initialize`.
M.START_TIMEOUT_MS = 10000
--- The oldest version of this plugin the signed-in server works with, as the CLI's hello passes it
--- on, or nil. The one place that knows where the field is.
function M._min_client(init_result)
local lembas = type(init_result) == "table" and type(init_result._meta) == "table" and init_result._meta.lembas or nil
local v = type(lembas) == "table" and lembas.min_client or nil
return type(v) == "string" and v ~= "" and v or nil
end
--- A progress object of the CLI (`phase` and its data) as the few words the panel shows, or nil.
function M._progress_text(pr)
if type(pr) ~= "table" or type(pr.phase) ~= "string" then return nil end
local function one(v) return type(v) == "string" and v ~= "" and (v:gsub("%s+", " ")):sub(1, 80) or nil end
local text = (pr.phase:gsub("_", " "))
local more
if pr.phase == "running_tool" then more = one(pr.what) or one(pr.tool)
elseif pr.phase == "loading_model" or pr.phase == "waiting_for_model" then more = one(pr.model)
elseif pr.phase == "failed" or pr.phase == "stopped" then more = one(pr.reason)
elseif pr.phase == "retrying" then
more = one(pr.reason)
if tonumber(pr["in"]) then more = (more and (more .. ", ") or "") .. ("again in %d s"):format(math.max(0, math.floor(tonumber(pr["in"]) + 0.5))) end
elseif pr.phase == "queued" and tonumber(pr.ahead) then more = ("%d ahead"):format(pr.ahead)
elseif pr.phase == "waiting_for_subagents" and tonumber(pr.running) then more = ("%d running"):format(pr.running)
elseif pr.phase == "reading_prompt" and tonumber(pr.done) and tonumber(pr.total) and tonumber(pr.total) > 0 then
more = ("%d%%"):format(math.floor(100 * pr.done / pr.total))
end
return more and (text .. ": " .. more) or text
end
--- A version as numbers: `2.0.0-beta.10` is newer than `2.0.0-beta.9`, and `2.0.0` newer than both.
local function version_key(v)
local core, pre = tostring(v or ""):gsub("%+.*$", ""):match("^v?([%d%.]+)%-?(.*)$")
if not core then return nil end
local key = {}
for n in core:gmatch("%d+") do key[#key + 1] = tonumber(n) end
while #key < 3 do key[#key + 1] = 0 end
-- A release is above its pre-releases; among those the name (alpha, beta, rc) then the number.
key[4] = pre == "" and 1 or 0
key[5] = pre:match("^%a+") or ""
key[6] = tonumber(pre:match("(%d+)%D*$")) or 0
return key
end
--- -1, 0 or 1 as version `a` is older than, the same as, or newer than `b`; nil when either is no version.
function M.compare_versions(a, b)
local x, y = version_key(a), version_key(b)
if not x or not y then return nil end
for i = 1, 6 do
if x[i] ~= y[i] then return x[i] < y[i] and -1 or 1 end
end
return 0
end
-- The same failure in the same words as the VS Code extension says it (vscode/src/words.js).
local WORDS = {
not_found = "The LLeMbas CLI was not found: `%s` is not a program this editor can start. Install the CLI, or set `cmd` in require(\"llembas\").setup({}) to its full path.",
cli_too_old = "LLeMbas CLI %s is older than this needs (%s or newer), so parts of it will not work. Update the CLI: lembas update",
no_answer = "The LLeMbas CLI did not answer within %d seconds.",
not_logged_in = "The LLeMbas CLI is not signed in to a server. Sign in with :LLeMbasLogin (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 :LLeMbasLogin (or `lembas login <server>` in a terminal), then try again.",
client_too_old_for_server = "This plugin (%s) is older than your LLeMbas server asks for (%s or newer); the server may refuse parts of it. Update the plugin.",
-- 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",
}
local WHOLE = { not_logged_in = true, signed_out = true }
local SERVER_SAYS = { not_allowed = true, busy = true }
--- The code of a failure, where the CLI gives one (`data.reason`, `data.code`, or `code` of a turn's error).
local function code_of(err)
if type(err) ~= "table" then return nil end
local d = type(err.data) == "table" and err.data or {}
local code = (type(d.reason) == "string" and d.reason) or (type(d.code) == "string" and d.code) or (type(err.code) == "string" and err.code) or nil
if code then return code end
-- `session/new` refuses a computer that is not signed in with a sentence and no code.
if tostring(err.message or ""):lower():find("not logged in", 1, true) then return "not_logged_in" end
return nil
end
M.config = {
cmd = { "lembas", "serve", "--stdio" }, -- the agent
position = "right", -- "right" | "left" | "bottom" | "float"
width = 64, -- the panel's columns (right/left)
prompt_height = 5, -- the prompt window's rows
border = "rounded", -- border style for floating windows
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
login = {
ca = nil, -- a file with the certificate authority of a server that has a private one
},
complete = {
auto = true, -- suggest as you type (needs an autocomplete model on the server)
debounce_ms = 250, -- how long you must pause before a suggestion is asked for
model = nil, -- a quick switch for this editor only; nil: your saved choice
max_tokens = nil, -- maximum tokens to predict (nil/0: server default or length preset)
length = "auto", -- "auto" | "words" | "line" | "block" | "file"
instructions = "", -- custom instructions sent with autocomplete requests
accept = "<Tab>", -- accepts a shown suggestion; falls through when none is shown
accept_word = "<M-Right>", -- accepts the next word of a shown suggestion
trigger = "<M-\\>", -- asks for a suggestion now
},
keys = false, -- true, or { prefix = "<Leader>l", chords = nil | true | false }: map the keys
bars = false, -- true, or a table (see |llembas-bars|): the four-bar layout
remember = true, -- keep the mode, effort, on/off and the bars per directory
}
local S = {
conn = nil, session = nil, starting = nil, connecting = nil, ready = false, caps = {}, busy = false,
modes = {}, mode = nil, model = nil, title = nil, progress = nil, usage = nil, team = nil, commands = {},
attached = nil, attached_label = nil, last_buf = nil, said = nil, shown = nil,
cwd = nil, cli = nil, last_stderr = nil,
effort = nil, ctx = nil, activity = nil, intent = "ask", target = nil, ai = true, signed_out = false,
}
--- What is remembered for this directory (|llembas-remembered|), read once and after each change.
local kept
local function remembered()
if not kept then kept = store.get() end
return kept
end
local function remember(key, value)
store.set(key, value)
kept = nil
end
local changed_pending = false
--- Something a bar shows has changed: `User LLeMbasChanged`, once per turn of the event loop.
local function changed()
if changed_pending then return end
changed_pending = true
vim.schedule(function()
changed_pending = false
pcall(vim.api.nvim_exec_autocmds, "User", { pattern = "LLeMbasChanged", modeline = false })
end)
end
local function bars_on()
local ok, on = pcall(function() return require("llembas.layout")._state.on end)
return ok and on == true
end
local OFF = "LLeMbas is off: nothing is sent, nothing is asked. :LLeMbasAI on turns it on."
--- Whether an error of the agent's says that the CLI is not signed in to a server.
local function not_signed_in(err)
local code = code_of(err)
return code == "not_logged_in" or code == "signed_out"
end
--- 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.
local function words(err)
local said = vim.trim(tostring(type(err) == "table" and err.message or err or ""):gsub("%s+", " "))
local code = code_of(err)
local fixed = code and WORDS[code]
if not fixed or code == "not_found" or code == "cli_too_old" or code == "no_answer" then return said ~= "" and said or "it failed" end
if WHOLE[code] then
-- An agent started before the sign-in is not asked to notice it: the next use starts a new one.
if S.conn then vim.schedule(function() M.restart(true, true) end) end
return fixed
end
if said == "" then return fixed .. "." end
-- A refusal the server put in words of its own is said in those.
if SERVER_SAYS[code] then return said end
return fixed .. ": " .. said
end
local function note(text, level)
chat.newline()
chat.append("> " .. text .. "\n", level == "error" and "LLeMbasError" or level == "warn" and "LLeMbasWarn" or "LLeMbasNote")
end
local function escape_at_path(p)
return (tostring(p or ""):gsub("([ #])", "\\%1"))
end
local function normalize_file_entry(entry)
if type(entry) == "string" then
local clean = entry:gsub("/$", "")
if clean == "" then return nil end
return { path = clean, kind = entry:sub(-1) == "/" and "dir" or "file" }
end
if type(entry) == "table" and type(entry.path) == "string" and entry.path ~= "" then
return { path = entry.path:gsub("/$", ""), kind = entry.kind == "dir" and "dir" or "file" }
end
return nil
end
local function extract_text_content(content)
local parts = {}
for _, c in ipairs(content or {}) do
if type(c) == "table" then
if c.type == "content" and type(c.content) == "table" and c.content.type == "text" and type(c.content.text) == "string" then
parts[#parts + 1] = c.content.text
elseif c.type == "text" and type(c.text) == "string" then
parts[#parts + 1] = c.text
end
end
end
return table.concat(parts, "\n")
end
local function status()
local top = { "◈ LLeMbas" }
if S.title and S.title ~= "" then top[#top + 1] = S.title end
if S.mode then top[#top + 1] = "[" .. S.mode .. "]" end
if S.model then top[#top + 1] = S.model end
if S.usage and ((S.usage.input or 0) > 0 or (S.usage.output or 0) > 0) then
top[#top + 1] = ("↑%s ↓%s"):format(ui.format_tokens(S.usage.input), ui.format_tokens(S.usage.output))
end
local working = 0
for _, a in ipairs((type(S.team) == "table" and S.team.agents) or {}) do
if type(a) == "table" and a.state ~= "done" and a.state ~= "stopped" then working = working + 1 end
end
if working > 0 then top[#top + 1] = ("%d subagent%s"):format(working, working == 1 and "" or "s") end
if S.busy then
top[#top + 1] = (S.progress and S.progress ~= "" and ("◐ " .. S.progress) or "◐ working")
end
chat.header(" " .. table.concat(top, " · "))
changed()
if chat.bars then
-- In the layout the bars say the rest: the line above the prompt is the attachment's chip.
return chat.status(S.attached_label and (" " .. S.attached_label .. " ") or "", "LLeMbasChip")
end
local parts = {}
if S.intent ~= "ask" then parts[#parts + 1] = S.intent end
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] = (S.progress and S.progress ~= "" and (S.progress .. " (Ctrl-C stops)") or "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 PLAN_ICON = { pending = "☐", in_progress = "▸", completed = "✓" }
local tools = {}
local pending_cards = {} -- toolCallId -> { line_id, label }
local function tool_hl(t)
if t.denied then return "LLeMbasToolDenied" end
if t.status == "completed" then return "LLeMbasToolDone" end
if t.status == "failed" then return "LLeMbasToolFail" end
return "LLeMbasToolPending"
end
local function render_tool_line(t)
local icon = t.denied and "⊘" or (ICON[t.status] or "…")
local title = t.title or "tool"
local show_kind = t.kind and t.kind ~= "" and t.kind ~= "other" and not title:lower():match("^" .. vim.pesc(t.kind:lower()) .. "%f[%W]")
local tag = show_kind and ("[" .. t.kind .. "] ") or ""
local suffix = t.denied and " (not allowed)" or ""
local dur = t.ms and (" · " .. ui.format_ms(t.ms)) or ""
return ("- %s %s%s%s%s"):format(icon, tag, title, suffix, dur)
end
local function on_update(u)
local kind = u.sessionUpdate
if kind == "agent_message_chunk" then
if S.activity ~= "writing" then S.activity = "writing"; changed() end
if S.said ~= "agent" then chat.section("LLeMbas", "LLeMbasAgentHeader"); 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 S.activity ~= "thinking" then S.activity = "thinking"; changed() end
if M.config.show_thoughts and u.content and u.content.type == "text" then
if S.said ~= "thought" then chat.section("Thinking", "LLeMbasThoughtHeader"); S.said = "thought" end
chat.append(u.content.text, "LLeMbasThought")
end
elseif kind == "tool_call" or kind == "tool_call_update" then
local id = tostring(u.toolCallId or "")
local t = tools[id] or { id = id }
tools[id] = t
t.title = u.title or t.title or "tool"
t.kind = u.kind or t.kind
t.status = u.status or t.status or "pending"
if u._meta and u._meta.lembas and u._meta.lembas.denied then t.denied = true end
local text_out = extract_text_content(u.content)
if text_out ~= "" then t.output = text_out:sub(1, 20000) end
chat.line("tool:" .. id, render_tool_line(t), tool_hl(t), t.output)
S.said = "tool"
local doing = (t.status == "completed" or t.status == "failed") and "thinking" or "tools"
if S.activity ~= doing then S.activity = doing; changed() end
if t.status == "completed" then reload_files() end
elseif kind == "plan" then
local entries = u.entries or {}
local done, all = 0, 0
local active_task = nil
for _, e in ipairs(entries) do
all = all + 1
if e.status == "completed" then done = done + 1
elseif e.status == "in_progress" and not active_task then active_task = e.content end
end
local structured = (u._meta and u._meta.lembas and u._meta.lembas.plan) or nil
if all > 0 then
local title = (structured and structured.title and structured.title ~= "") and (structured.title .. ": ") or "plan: "
local bar = ui.progress_bar(done, all, 10)
local tail = active_task and (" — " .. active_task) or ""
chat.line("plan", ("- %s%s %d of %d tasks done%s"):format(title, bar, done, all, tail), "LLeMbasPlanHeader")
for idx, e in ipairs(entries) do
if idx > 16 then break end
local picon = PLAN_ICON[e.status] or "☐"
local phl = e.status == "completed" and "LLeMbasPlanDone" or e.status == "in_progress" and "LLeMbasPlanActive" or "LLeMbasPlanPending"
chat.line("plan:item:" .. idx, (" %s %s"):format(picon, tostring(e.content or "")), phl)
end
S.said = "tool"
end
elseif kind == "current_mode_update" then
S.mode = u.currentModeId or S.mode
status()
elseif kind == "available_commands_update" then
local list = {}
for _, c in ipairs(u.availableCommands or {}) do
if type(c) == "table" and type(c.name) == "string" then
list[#list + 1] = {
name = c.name,
description = type(c.description) == "string" and c.description or "",
hint = (c.input and type(c.input.hint) == "string") and c.input.hint or "",
kind = (c._meta and c._meta.lembas and type(c._meta.lembas.kind) == "string") and c._meta.lembas.kind or "",
}
end
end
S.commands = list
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 {}
local call_id = tostring(call.toolCallId or "")
local line_id = "ask:" .. call_id
local who = meta.subagent and meta.subagent.name and (" [" .. meta.subagent.name .. "]") or ""
chat.line(line_id, "- ? " .. (call.title or meta.tool or "a tool") .. who .. " (waits for your answer)", "LLeMbasToolPending")
pending_cards[call_id] = { line_id = line_id, title = call.title or meta.tool or "a tool" }
changed()
local preview = require("llembas.diff").preview(call.content)
local prompt = "LLeMbas asks" .. who .. ": " .. (call.title or meta.tool or "a tool")
if meta.reason then prompt = prompt .. " (" .. meta.reason .. ")" end
-- The refusals first: the question can open while you are typing, and a digit and Enter meant for
-- your code must not allow a command. The first choice is always a denial.
options = vim.list_slice(options)
table.sort(options, function(x, y)
local dx, dy = tostring(x.kind):match("^reject") and 0 or 1, tostring(y.kind):match("^reject") and 0 or 1
return dx < dy
end)
pcall(vim.cmd, "stopinsert")
pcall(vim.cmd, "redraw")
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 preview then preview() end
-- Taken down meanwhile (answered elsewhere, or no longer waited for): there is nobody to tell.
if not pending_cards[call_id] then return end
pending_cards[call_id] = nil
changed()
if not choice then
chat.line(line_id, "- ✗ " .. (call.title or "a tool") .. " (not answered: denied)", "LLeMbasToolFail")
return reply({ outcome = { outcome = "cancelled" } })
end
local denied = tostring(choice.kind):match("^reject") ~= nil
chat.line(line_id, ("- %s: %s"):format(choice.name or choice.optionId, call.title or "a tool"), denied and "LLeMbasToolDenied" or "LLeMbasToolDone")
reply({ outcome = { outcome = "selected", optionId = choice.optionId } })
end)
end
local function on_question(p, reply)
local qs = p.questions or {}
local call_id = tostring(p.toolCallId or "")
local id = "q:" .. call_id
chat.line(id, "- ? " .. (p.why or (qs[1] and qs[1].question) or "question") .. " (waits for your answer)", "LLeMbasToolPending")
pending_cards[call_id] = { line_id = id, title = "question" }
changed()
pcall(vim.cmd, "stopinsert")
local answers = {}
local summaries = {}
local function done_all()
if not pending_cards[call_id] then return end
pending_cards[call_id] = nil
changed()
local summary = table.concat(summaries, " · ")
chat.line(id, "- ✓ answered question" .. (summary ~= "" and (": " .. summary) or ""), "LLeMbasToolDone")
return reply({ outcome = "answered", answers = answers })
end
local function dismiss_all()
if not pending_cards[call_id] then return end
pending_cards[call_id] = nil
changed()
chat.line(id, "- ✗ question dismissed", "LLeMbasToolDenied")
return reply({ outcome = "dismissed" })
end
local function ask_idx(i)
if i > #qs then return done_all() end
local q = qs[i]
local opts = q.options or {}
local title_prompt = (q.header and (q.header .. ": ") or "") .. (q.question or "Choose")
if #opts > 0 and q.multiple then
local picked = {}
local function pick_multi()
local choices = {}
for _, o in ipairs(opts) do
choices[#choices + 1] = { label = o.label, description = o.description, recommended = o.recommended, _opt = true }
end
choices[#choices + 1] = { label = "__done__", _done = true }
choices[#choices + 1] = { label = "__custom__", _custom = true }
choices[#choices + 1] = { label = "__skip__", _skip = true }
vim.ui.select(choices, {
prompt = title_prompt .. " (select one or more, then Done)",
format_item = function(o)
if o._done then
local n = #picked
return n > 0 and ("Done (" .. n .. " selected)") or "Done (skip)"
end
if o._custom then return "Type a custom answer…" end
if o._skip then return "Skip this question" end
local mark = vim.tbl_contains(picked, o.label) and "[✓] " or "[ ] "
local star = o.recommended and " ★" or ""
return mark .. o.label .. star .. (o.description and o.description ~= "" and (" — " .. o.description) or "")
end,
}, function(choice)
if not choice then return dismiss_all() end
if choice._skip then
answers[i] = { kind = "skipped" }
summaries[#summaries + 1] = "skipped"
return ask_idx(i + 1)
end
if choice._done then
if #picked > 0 then
answers[i] = { kind = "options", labels = picked }
summaries[#summaries + 1] = table.concat(picked, ", ")
else
answers[i] = { kind = "skipped" }
end
return ask_idx(i + 1)
end
if choice._custom then
return vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text)
if not text then return dismiss_all() end
if not text:match("%S") then answers[i] = { kind = "skipped" }; return ask_idx(i + 1) end
answers[i] = { kind = "custom", text = vim.trim(text) }
summaries[#summaries + 1] = vim.trim(text)
ask_idx(i + 1)
end)
end
local idx = nil
for k, v in ipairs(picked) do if v == choice.label then idx = k break end end
if idx then table.remove(picked, idx) else picked[#picked + 1] = choice.label end
pick_multi()
end)
end
pick_multi()
elseif #opts > 0 then
local choices = {}
for _, o in ipairs(opts) do choices[#choices + 1] = o end
choices[#choices + 1] = { label = "__custom__", _custom = true }
choices[#choices + 1] = { label = "__skip__", _skip = true }
vim.ui.select(choices, {
prompt = title_prompt,
format_item = function(o)
if o._custom then return "Type a custom answer…" end
if o._skip then return "Skip this question" end
local star = o.recommended and " ★" or ""
return o.label .. star .. (o.description and o.description ~= "" and (" — " .. o.description) or "")
end,
}, function(choice)
if not choice then return dismiss_all() end
if choice._skip then
answers[i] = { kind = "skipped" }
summaries[#summaries + 1] = "skipped"
return ask_idx(i + 1)
end
if choice._custom then
vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text)
if not text then return dismiss_all() end
if not text:match("%S") then answers[i] = { kind = "skipped" }; return ask_idx(i + 1) end
answers[i] = { kind = "custom", text = vim.trim(text) }
summaries[#summaries + 1] = vim.trim(text)
ask_idx(i + 1)
end)
else
answers[i] = { kind = "options", labels = { choice.label } }
summaries[#summaries + 1] = choice.label
ask_idx(i + 1)
end
end)
else
vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text)
if not text then return dismiss_all() end
if not text:match("%S") then
answers[i] = { kind = "skipped" }
else
answers[i] = { kind = "custom", text = vim.trim(text) }
summaries[#summaries + 1] = vim.trim(text)
end
ask_idx(i + 1)
end)
end
end
ask_idx(1)
end
local function on_plan(p, reply)
local title = (p.plan and p.plan.title) or "Plan ready"
local call_id = tostring(p.toolCallId or "")
local id = "plan:" .. call_id
chat.section("Plan: " .. title, "LLeMbasPlanHeader")
if type(p.text) == "string" and p.text ~= "" then chat.append(p.text .. "\n") end
chat.line(id, "- ? " .. title .. " (waits for approval)", "LLeMbasToolPending")
pending_cards[call_id] = { line_id = id, title = title }
changed()
pcall(vim.cmd, "stopinsert")
local actions = {
{ id = "dismiss", label = "Dismiss" },
{ id = "approve_edit", label = "Approve (edit mode)" },
{ id = "approve_manual", label = "Approve (manual mode)" },
{ id = "revise", label = "Revise with feedback" },
}
vim.ui.select(actions, {
prompt = "LLeMbas plan: " .. title,
format_item = function(a) return a.label end,
}, function(choice)
if not pending_cards[call_id] then return end
pending_cards[call_id] = nil
changed()
if not choice or choice.id == "dismiss" then
chat.line(id, "- ✗ plan dismissed", "LLeMbasToolDenied")
return reply({ outcome = "dismissed" })
end
if choice.id == "approve_edit" then
chat.line(id, "- ✓ plan approved (edit mode)", "LLeMbasToolDone")
return reply({ outcome = "approve", mode = "edit" })
end
if choice.id == "approve_manual" then
chat.line(id, "- ✓ plan approved (manual mode)", "LLeMbasToolDone")
return reply({ outcome = "approve", mode = "manual" })
end
vim.ui.input({ prompt = "Plan revision feedback: " }, function(fb)
if not fb or not fb:match("%S") then
chat.line(id, "- ✗ plan dismissed", "LLeMbasToolDenied")
return reply({ outcome = "dismissed" })
end
chat.line(id, "- ↻ plan revision requested", "LLeMbasPlanActive")
reply({ outcome = "revise", feedback = vim.trim(fb) })
end)
end)
end
local function last_line_of(text)
local last = ""
for line in (text or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end
return last
end
--- The agent in use is gone: everything that belonged to it is let go, and the next request starts
--- a new one. `:LLeMbasLog` shows what it wrote before it went.
local function stopped(code, stderr, signal)
local was = S.session ~= nil or S.starting ~= nil or S.busy
local waiting = S.starting
local connecting = S.connecting
S.conn, S.session, S.starting, S.connecting, S.ready, S.busy = nil, nil, nil, nil, false, false
S.progress, S.team, S.caps, S.cli = nil, nil, {}, nil
S.last_stderr = stderr
for _, card in pairs(pending_cards) do
chat.line(card.line_id, "- ⊘ " .. card.title .. " (the agent stopped before this was answered)", "LLeMbasNote")
end
pending_cards = {}
tools = {}
for _, cb in ipairs(connecting or {}) do cb(false) end
if was then
local last = last_line_of(stderr)
local how = (signal and signal ~= 0) and ("signal " .. tostring(signal)) or ("exit " .. tostring(code))
note(("The agent stopped (%s)%s"):format(how, last ~= "" and (": " .. last) or "."), "error")
note("The next message starts it again. :LLeMbasLog shows what it wrote.")
end
for _, cb in ipairs(waiting or {}) do cb(false) end
status()
end
--- The command that starts the agent: as set; a bare `lembas` that is not on this editor's PATH is
--- looked for where the CLI's installer puts it. Returns the command, or nil and why.
local function agent_command()
local cmd = vim.list_slice(M.config.cmd)
local exe = cmd[1]
if type(exe) ~= "string" or exe == "" then return nil, WORDS.not_found:format(tostring(exe)) end
if vim.fn.executable(exe) == 1 then return cmd end
if exe == "lembas" then
local home = vim.uv.os_homedir()
local at = home and (home .. "/.local/bin/lembas")
if at and vim.fn.executable(at) == 1 then
cmd[1] = at
return cmd
end
end
return nil, WORDS.not_found:format(exe)
end
--- Have a running agent that has answered `initialize`, then call `cb(true)`; `cb(false)` when not.
--- `quiet`: a failure is not written into the chat (completion asks often and must not nag).
local function connect(cb, quiet)
if not S.ai then
S.start_error = OFF
if not quiet then vim.notify(OFF, vim.log.levels.INFO) end
return cb(false)
end
if S.conn and S.ready then return cb(true) end
if S.connecting then S.connecting[#S.connecting + 1] = cb; return end
S.connecting = { cb }
local function done(ok)
local waiting = S.connecting or {}
S.connecting = nil
for _, f in ipairs(waiting) do f(ok) end
end
local me = {}
local cmd, why = agent_command()
if not cmd then
S.start_error = why
if not quiet then note(why, "error") end
return done(false)
end
local cwd = vim.fn.getcwd()
local conn, err = rpc.start(cmd, {
notify = function(method, params)
if method == "session/update" and params.sessionId == S.session then on_update(params.update or {})
elseif method == "_lembas/edit/delta" then require("llembas.diff").delta(params)
elseif method == "_lembas/permission/settled" then
local cid = tostring(params.toolCallId or "")
local card = pending_cards[cid]
if card then
pending_cards[cid] = nil
chat.line(card.line_id, "- ⊘ " .. card.title .. " (answered elsewhere or expired)", "LLeMbasNote")
end
elseif method == "_lembas/event" and params.sessionId == S.session and params.event then
local ev = params.event
if ev.type == "model" and type(ev.ref) == "string" then
S.model = ev.ref
if type(ev.effort) == "string" then S.effort = ev.effort end
status()
elseif ev.type == "mode" and type(ev.mode) == "string" then S.mode = ev.mode; status()
elseif ev.type == "title" and type(ev.title) == "string" then S.title = ev.title; status()
elseif ev.type == "phase" then
-- The main agent's phase; a subagent's (`agent`) is the tree's to show.
if ev.agent == nil then
S.progress = M._progress_text(ev.progress)
local ph = type(ev.progress) == "table" and ev.progress.phase or nil
if ph == "running_tool" then S.activity = "tools" elseif ph and S.activity ~= "writing" then S.activity = "thinking" end
status()
end
elseif ev.type == "error" and type(ev.message) == "string" and ev.message:match("%S") then
-- A turn that failed ends as any other does (`end_turn`): this is where it says why.
S.failed = true
note("The turn failed: " .. words({ message = ev.message, code = ev.code }), "error")
S.busy, S.progress = false, nil
status()
elseif ev.type == "usage" and type(ev.usage) == "table" and not ev.child then
-- How much of the model's window the conversation fills, as the CLI's own bars say it.
local total, used = tonumber(ev.context), tonumber(ev.used)
if total and total > 0 and used and used >= 0 then
S.ctx = math.min(100, math.max(0, math.floor(used / total * 100 + 0.5)))
changed()
end
local inp = tonumber(ev.usage.input) or 0
local outp = tonumber(ev.usage.output) or 0
if inp > 0 or outp > 0 then
S.usage = { input = ((S.usage and S.usage.input) or 0) + inp, output = ((S.usage and S.usage.output) or 0) + outp }
status()
end
elseif ev.type == "tool_end" and type(ev.id) == "string" and tonumber(ev.ms) then
local t = tools[ev.id]
if t then
t.ms = tonumber(ev.ms)
chat.line("tool:" .. ev.id, render_tool_line(t), tool_hl(t), t.output)
end
elseif ev.type == "notice" and type(ev.message) == "string" and ev.message:match("%S") then
note(ev.message, ev.level)
elseif ev.type == "compacted" and type(ev.summary) == "string" and ev.summary:match("%S") then
note("Context compacted: " .. ev.summary)
elseif ev.type == "team" then
S.team = ev.tree
status()
end
end
end,
request = function(method, params, reply)
if method == "session/request_permission" then return on_permission(params, reply) end
if method == "_lembas/question" then return on_question(params, reply) end
if method == "_lembas/plan" then return on_plan(params, reply) end
if method == "fs/read_text_file" then return require("llembas.context").read_for_agent(params, reply) end
if method == "_lembas/show" then return M._show(params, reply) end
if method == "fs/write_text_file" then return require("llembas.context").write_for_agent(params, reply) end
reply(nil, { code = -32601, message = "Method not found: " .. method })
end,
-- Only the agent in use: one that was replaced (a new session) ends later and must not undo its successor.
exit = function(code, stderr, signal)
if S.conn == me.conn then stopped(code, stderr, signal) else S.last_stderr = S.last_stderr or stderr end
end,
}, { cwd = cwd })
if not conn then
S.start_error = WORDS.not_found:format(tostring(cmd[1])) .. " (" .. tostring(err):gsub("%s+", " "):sub(1, 200) .. ")"
if not quiet then note(S.start_error, "error") end
return done(false)
end
me.conn = conn
S.conn, S.ready, S.start_error, S.cwd = conn, false, nil, cwd
conn:request("initialize", {
protocolVersion = 1,
-- `protocol = 3`: LLeMbas CLI 2.0's own (question and plan cards come with 2 or later).
clientCapabilities = { fs = { readTextFile = true, writeTextFile = true },
_meta = { lembas = { protocol = 3, editor = true, show = true, media = true } } },
clientInfo = { name = "llembas-nvim", version = M.version },
}, function(e1, r)
if S.conn ~= conn then return done(false) end
if e1 then
local last = last_line_of(conn:stderr())
S.start_error = e1.timeout and WORDS.no_answer:format(math.floor(M.START_TIMEOUT_MS / 1000 + 0.5))
or ("The agent refused to start: " .. tostring(e1.message) .. ".")
if last ~= "" then S.start_error = S.start_error .. " Its last words: " .. last end
if not quiet then note(S.start_error, "error") end
S.conn = nil
S.last_stderr = conn:stderr()
conn:stop()
return done(false)
end
S.ready = true
S.caps = {}
for _, c in ipairs((((r or {})._meta or {}).lembas or {}).capabilities or {}) do S.caps[c] = true end
S.cli = type((r or {}).agentInfo) == "table" and r.agentInfo.version or nil
-- The signed-in server's own minimum for this plugin, when the CLI passes one on.
local min = M._min_client(r)
if min and M.compare_versions(M.version, min) == -1 and S.said_min ~= min then
S.said_min = min
local text = WORDS.client_too_old_for_server:format(M.version, min)
if chat.is_open() then note(text, "warn") else vim.notify("LLeMbas: " .. text, vim.log.levels.WARN) end
end
-- An older CLI is said once per agent, in the chat when it is open and as a message otherwise.
if S.cli and M.compare_versions(S.cli, M.MIN_CLI) == -1 then
local text = WORDS.cli_too_old:format(S.cli, M.MIN_CLI)
if chat.is_open() then note(text, "warn") else vim.notify("LLeMbas: " .. text, vim.log.levels.WARN) end
end
require("llembas.complete").warm(S.last_buf)
done(true)
end, M.START_TIMEOUT_MS)
end
--- Have a running agent and an open session, then call `cb(true)`; `cb(false)` when that failed.
local function ensure(cb, again)
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 finish(ok)
local waiting = S.starting or {}
S.starting = nil
for _, f in ipairs(waiting) do f(ok) end
end
connect(function(ok)
if not ok then return finish(false) end
local conn = S.conn
local meta = {}
-- The mode and the effort a session starts with: as set, else as chosen here last time. The
-- model is the CLI's to remember (the one last used in this directory).
local mode = M.config.mode or remembered().mode
if mode then meta.mode = mode end
if M.config.model then meta.model = M.config.model end
local effort = S.effort or remembered().effort
if effort then meta.effort = effort end
conn:request("session/new", { cwd = S.cwd or vim.fn.getcwd(), mcpServers = {}, _meta = meta }, function(e2, r)
if S.conn ~= conn then return finish(false) end
if e2 or type(r) ~= "table" or type(r.sessionId) ~= "string" then
if not_signed_in(e2) then S.signed_out = true end
if not_signed_in(e2) and not again then
-- This agent may have started before the person signed in: a new one is asked once
-- before anything is said.
local waiting, busy = S.starting or {}, S.busy
S.starting = nil
M.restart(true, true)
S.busy = busy
return ensure(function(ok) for _, f in ipairs(waiting) do f(ok) end end, true)
elseif not_signed_in(e2) then
note(words(e2), "error")
else
note("No session: " .. words(e2 or "the agent answered without one"), "error")
end
return finish(false)
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
S.effort = type(lm.effort) == "string" and lm.effort or S.effort
S.signed_out = false
-- A session means the sign-in works: suggestions that were refused for want of one are asked again.
require("llembas.complete").reset()
status()
finish(true)
end, 60000)
end)
end
--- Send `blocks` as a prompt; `shown` is what the transcript says you wrote.
local function send(blocks, shown, meta)
chat.section("You", "LLeMbasUserHeader")
chat.append(shown .. "\n")
S.said = "you"
S.busy = true
S.progress = nil
S.failed = false
S.activity = "thinking"
status()
ensure(function(ok)
if not ok then S.busy = false; status(); return end
S.conn:request("session/prompt", { sessionId = S.session, prompt = blocks, _meta = meta }, function(err, r)
S.busy = false
S.progress = nil
if err then
-- An agent that stopped has said so itself; anything else is the turn's own failure.
if S.conn then note("The turn failed: " .. words(err), "error") end
else
local lm = (r and r._meta and r._meta.lembas) or {}
-- The failure as the answer carries it, unless the event has said it already.
if type(lm.error) == "table" and type(lm.error.message) == "string" and not S.failed then
note("The turn failed: " .. words(lm.error), "error")
end
if type(lm.message) == "string" and lm.message ~= "" then note(lm.message) end
if type(lm.summary) == "string" and lm.summary ~= "" then note("Compacted: " .. lm.summary) end
if r and r.stopReason == "cancelled" then note("Stopped.")
elseif r and type(r.stopReason) == "string" and r.stopReason ~= "end_turn" then
note("The turn ended: " .. r.stopReason:gsub("_", " ") .. ".")
end
-- Messages sent while it worked that the turn ended before taking in: said, so they are not lost.
if type(lm.unsent) == "table" and #lm.unsent > 0 then
note("Not taken in before the turn ended (send again): " .. table.concat(lm.unsent, " | "), "warn")
end
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
--- Lines of a buffer as the chip and the transcript name them: `main.rs:12-18`, or `main.rs:12`
--- for one line reached without a selection.
local function label(buf, first, last, point)
local name = vim.api.nvim_buf_get_name(buf)
name = name ~= "" and vim.fn.fnamemodify(name, ":.") or "buffer"
if point and first == last then return ("%s:%d"):format(name, first) end
return ("%s:%d-%d"):format(name, first, last)
end
local function set_intent(intent)
if intent ~= "ask" and intent ~= "rewrite" and intent ~= "add" then return end
S.intent = intent
chat.set_intent(intent)
end
local function window_of(buf)
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
--- What was typed with the prompt saying `rewrite ›` or `add ›`: the lines that came along are
--- rewritten in place, or new code is written at the point — shown in the file as changes to
--- accept or reject, never written by themselves. The focus goes to the code, where they appear.
local function send_intent(text)
local intent, target = S.intent, S.target
if not target or not vim.api.nvim_buf_is_valid(target.buf) then
local b = S.last_buf and vim.api.nvim_buf_is_valid(S.last_buf) and S.last_buf or nil
local w = b and window_of(b)
if not w then
vim.notify("LLeMbas: there is no code to " .. intent .. " in — go to the file first", vim.log.levels.WARN)
return false
end
local row = vim.api.nvim_win_get_cursor(w)[1]
target = { buf = b, first = row, last = row, point = true }
end
local n = vim.api.nvim_buf_line_count(target.buf)
local first, last = math.min(target.first, n), math.min(target.last, n)
local what = label(target.buf, first, last, target.point)
S.attached, S.attached_label, S.target = nil, nil, nil
set_intent("ask")
local win = window_of(target.buf)
if not win then
local ok, w = pcall(function() return require("llembas.layout").code_win() end)
win = ok and w or nil
if not win then
vim.notify("LLeMbas: the file is no longer in a window", vim.log.levels.WARN)
return false
end
vim.api.nvim_win_set_buf(win, target.buf)
end
chat.section("You", "LLeMbasUserHeader")
chat.append(("[%s %s]\n%s\n"):format(intent, what, text))
S.said = "you"
pcall(vim.cmd, "stopinsert")
vim.api.nvim_set_current_win(win)
if intent == "rewrite" then
pcall(vim.api.nvim_win_set_cursor, win, { first, 0 })
M.edit(first, last, text)
else
pcall(vim.api.nvim_win_set_cursor, win, { last, 0 })
M.generate(text)
end
status()
return true
end
--- A prompt typed in the panel: with what was attached, or else the name of the open file. An agent
--- that takes the editor's context as data (`editor`) gets it so; an older one is told in a sentence.
local function send_typed(text)
if S.intent ~= "ask" and not text:match("^/") then return send_intent(text) end
if S.busy then
if S.conn and S.session and S.caps.steer then
chat.section("You (while working)", "LLeMbasUserHeader")
chat.append(text .. "\n")
S.conn:request("_lembas/steer", { sessionId = S.session, text = text }, function(err)
if err then note("Not sent to the running turn: " .. words(err), "error") end
end, 15000)
return true
end
vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN)
return false
end
if not S.ai then
vim.notify(OFF, vim.log.levels.INFO)
return false
end
local attached, attached_label = S.attached, S.attached_label
S.attached, S.attached_label, S.target = nil, nil, nil
S.busy = true
connect(function()
local blocks, shown, meta = {}, text, nil
if attached then
shown = ("[%s]\n%s"):format(attached_label, text)
if S.caps.editor and attached.editor then meta = { lembas = { editor = attached.editor } }
else vim.list_extend(blocks, attached.blocks) end
elseif M.config.send_open_file and not text:match("^/") then
local b = editing_buf()
if b and S.caps.editor then
local e = context.editor(b)
if e then meta = { lembas = { editor = e } } end
else
local f = b and context.file(b)
if f then blocks[#blocks + 1] = f end
end
end
blocks[#blocks + 1] = { type = "text", text = text }
send(blocks, shown, meta)
end, true)
status()
end
local function wire()
chat.on_send = send_typed
chat.on_stop = M.stop
chat.on_help = M.help
chat.on_files = function() M.files("", false) end
chat.on_commands = M.commands
chat.on_intent = function() M.cycle_intent() end
chat.on_back = function() require("llembas.layout").focus("code") end
chat.intent = S.intent
end
--- For the layout: open the panel as its right bar.
function M._open_bar(opts)
ui.setup_highlights()
wire()
chat.open(opts, false)
status()
end
function M.open(focus)
ui.setup_highlights()
local b = vim.api.nvim_get_current_buf()
if vim.bo[b].buftype == "" then S.last_buf = b end
wire()
if bars_on() then
-- The layout owns the right bar: it is shown (also at a width where it would fold away).
if not chat.is_open() then require("llembas.layout").toggle("chat", true) end
if chat.is_open() and focus ~= false then chat.focus_prompt() end
return status()
end
if not S.ai then return vim.notify(OFF, vim.log.levels.INFO) end
chat.open({
width = M.config.width,
position = M.config.position,
prompt_height = M.config.prompt_height,
border = M.config.border,
}, focus)
status()
end
function M.toggle()
if bars_on() then return require("llembas.layout").toggle("chat") end
if chat.is_open() then chat.close() else M.open() end
end
--- To the prompt, with what you are on: the selection, or else the cursor's line, comes along as
--- the attachment, and the prompt says what Enter will do. `opts`: `intent` ("ask", "rewrite",
--- "add"; nil keeps it), `first` and `last` (lines, instead of the selection or the cursor),
--- `attach = false` (nothing comes along).
function M.prompt(opts)
opts = opts or {}
if not S.ai then return vim.notify(OFF, vim.log.levels.INFO) end
local buf = vim.api.nvim_get_current_buf()
if opts.attach ~= false and vim.bo[buf].buftype == "" then
local first, last, point = opts.first, opts.last or opts.first, false
if not first then
if vim.api.nvim_get_mode().mode:match("^[vV\22]") then
first, last = vim.fn.line("v"), vim.fn.line(".")
if first > last then first, last = last, first end
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "nx", false)
else
first = vim.api.nvim_win_get_cursor(0)[1]
last, point = first, true
end
end
S.last_buf = buf
S.attached = { blocks = context.selection(buf, first, last), editor = context.editor(buf, first, last) }
S.attached_label = label(buf, first, last, point)
S.target = { buf = buf, first = first, last = last, point = point }
end
if opts.intent then set_intent(opts.intent) end
M.open(true)
status()
end
--- What Enter in the prompt will do: "ask" (the question goes to the chat, with what came
--- along), "rewrite" (the lines that came along are rewritten, shown as changes) or "add" (new
--- code at the point, shown as changes). With a name it is set; the current one is returned.
function M.intent(name)
if name then
set_intent(name)
status()
end
return S.intent
end
--- The next of ask, rewrite, add.
function M.cycle_intent()
local order = { ask = "rewrite", rewrite = "add", add = "ask" }
return M.intent(order[S.intent] or "ask")
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 what = label(buf, first, last)
S.attached = { blocks = context.selection(buf, first, last), editor = context.editor(buf, first, last) }
S.attached_label = what
S.target = { buf = buf, first = first, last = last }
if question and question:match("%S") then
M.open(false)
send_typed(question)
else
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 when using an older CLI.
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 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
if not S.ready then
-- Which way a rewrite goes depends on what the agent can do, known once it has started.
return connect(function(ok) if ok then M.edit(first, last, instruction) end end)
end
if S.caps.editor then return require("llembas.diff").rewrite(buf, first, last, instruction) end
if vim.bo[buf].modified then
return vim.notify("LLeMbas: save the file first (this LLeMbas CLI edits the file on disk)", vim.log.levels.WARN)
end
if S.busy then
return vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN)
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
--- Generate code at the current cursor line using `_lembas/edit`.
function M.generate(instruction)
local buf = vim.api.nvim_get_current_buf()
if vim.bo[buf].buftype ~= "" or not vim.bo[buf].modifiable then
return vim.notify("LLeMbas: open an editable buffer first", vim.log.levels.WARN)
end
if not instruction or not instruction:match("%S") then
return vim.ui.input({ prompt = "Generate code at cursor: " }, function(text)
if text and text:match("%S") then M.generate(text) end
end)
end
if not S.ready then
return connect(function(ok) if ok then M.generate(instruction) end end)
end
if not S.caps.editor then
return vim.notify("LLeMbas: this LLeMbas CLI does not support inline generation yet", vim.log.levels.WARN)
end
local row = vim.api.nvim_win_get_cursor(0)[1]
require("llembas.diff").generate(buf, row, 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
--- Stop the agent; the next message, suggestion or rewrite starts it again. The transcript stays.
function M.restart(quiet, keep_completion)
local conn = S.conn
if not conn then
if not quiet then vim.notify("LLeMbas: the agent is not running; it starts when it is needed", vim.log.levels.INFO) end
return
end
S.last_stderr = conn:stderr()
S.conn, S.session, S.starting, S.connecting, S.ready, S.busy = nil, nil, nil, nil, false, false
S.progress, S.team, S.caps, S.cli = nil, nil, {}, nil
for _, card in pairs(pending_cards) do
chat.line(card.line_id, "- ⊘ " .. card.title .. " (the agent was stopped before this was answered)", "LLeMbasNote")
end
pending_cards = {}
tools = {}
conn:stop()
if not keep_completion then require("llembas.complete").reset() end
if not quiet then note("The agent was stopped. The next message starts a new session.") end
status()
end
--- What the agent wrote on stderr (the running one's, else the last one's), in a window.
function M.log()
local text = (S.conn and S.conn:stderr()) or S.last_stderr or ""
local lines = vim.split(text, "\n", { plain = true })
while #lines > 0 and lines[#lines] == "" do table.remove(lines) end
if #lines == 0 then lines = { "(the agent has written nothing)" } end
if #lines > 400 then lines = vim.list_slice(lines, #lines - 399) end
table.insert(lines, 1, S.conn and ("The LLeMbas CLI " .. (S.cli or "") .. " is running; this is what it wrote on stderr:")
or "The LLeMbas CLI is not running; this is what the last one wrote on stderr:")
table.insert(lines, 2, "")
ui.float("LLeMbas Log", lines, { border = M.config.border })
end
--- A new session; the old one stays in the CLI's store.
function M.new(force)
if S.busy and not force then
return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop), or :LLeMbasNew! to end the agent", vim.log.levels.WARN)
end
S.busy = false
local conn = S.conn
if conn then S.last_stderr = conn:stderr() end
S.conn, S.session, S.starting, S.connecting, S.ready, S.said = nil, nil, nil, nil, false, nil
S.title, S.progress, S.usage, S.team, S.commands, S.caps, S.cli = nil, nil, nil, nil, {}, {}, nil
S.attached, S.attached_label, S.shown, S.target = nil, nil, nil, nil
S.ctx, S.activity = nil, nil
tools = {}
pending_cards = {}
if conn then conn:stop() end
require("llembas.complete").reset()
chat.clear()
M.open()
end
function M.compact()
if S.busy then return vim.notify("LLeMbas is working; wait for the turn to finish", vim.log.levels.WARN) end
if not S.session or not S.conn then return vim.notify("LLeMbas: no active session to compact", vim.log.levels.INFO) end
S.conn:request("_lembas/session/compact", { sessionId = S.session }, function(err, r)
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
local summary = r and type(r.summary) == "string" and r.summary or ""
note(summary ~= "" and ("Session compacted: " .. summary) or "Session compacted.")
end, 600000)
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: " .. words(err), vim.log.levels.ERROR) end
S.mode = mode
remember("mode", mode)
status()
end, 15000)
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
--- Search the project file index (`_lembas/files/search`) and either open a file or insert `@path` into chat.
function M.files(query, open_directly)
if not query or not query:match("%S") then
-- The index answers a name, or part of one: with nothing typed it has only the files used lately.
return vim.ui.input({ prompt = open_directly and "Open file (part of its name): " or "Attach file (part of its name): " }, function(text)
if text and text:match("%S") then M.files(vim.trim(text), open_directly) end
end)
end
connect(function(ok)
if not ok then return end
local function pick_from(raw_list)
local list = {}
for _, item in ipairs(raw_list or {}) do
local norm = normalize_file_entry(item)
if norm and (not open_directly or norm.kind ~= "dir") then list[#list + 1] = norm end
end
if #list == 0 then return vim.notify("LLeMbas: no matching files found", vim.log.levels.INFO) end
vim.ui.select(list, {
prompt = open_directly and "LLeMbas open file" or "LLeMbas attach file to chat",
format_item = function(f) return (f.kind == "dir" and "[dir] " or "[file] ") .. f.path .. (f.kind == "dir" and "/" or "") end,
}, function(entry)
if not entry then return end
if open_directly then
local full = entry.path:match("^/") and entry.path or ((S.cwd or vim.fn.getcwd()) .. "/" .. entry.path)
local target
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end
end
if target then vim.api.nvim_set_current_win(target) end
pcall(vim.cmd, "edit " .. vim.fn.fnameescape(full))
else
M.open(true)
local ref = escape_at_path(entry.path) .. (entry.kind == "dir" and "/" or "")
chat.insert_prompt("@" .. ref .. " ")
end
end)
end
if S.caps.files then
-- No session is needed (and none is opened) to look for a file: the folder is enough.
local params = { query = query, limit = 50 }
if S.session then params.sessionId = S.session else params.cwd = S.cwd or vim.fn.getcwd() end
S.conn:request("_lembas/files/search", params, function(err, r)
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
pick_from(r and r.files or {})
end, 30000)
else
local found = vim.fn.glob("**/*", false, true)
local out = {}
local q = (query or ""):lower()
for _, f in ipairs(found) do
if vim.fn.isdirectory(f) == 0 and (q == "" or f:lower():find(q, 1, true)) then
out[#out + 1] = { path = f, kind = "file" }
if #out >= 50 then break end
end
end
pick_from(out)
end
end)
end
--- Pick a session slash command (`/compact`, `/review`, skills, etc.) and insert it into the prompt.
function M.commands()
connect(function(ok)
if not ok then return end
local function pick_cmd(list)
if not list or #list == 0 then return vim.notify("LLeMbas: no slash commands available", vim.log.levels.INFO) end
vim.ui.select(list, {
prompt = "LLeMbas command",
format_item = function(c)
local tag = (c.kind and c.kind ~= "") and ("[" .. c.kind .. "] ") or ""
local desc = (c.description and c.description ~= "") and (" — " .. c.description) or ""
return tag .. "/" .. c.name .. desc
end,
}, function(chosen)
if not chosen then return end
M.open(true)
chat.insert_prompt("/" .. chosen.name .. " ")
end)
end
if #S.commands > 0 then return pick_cmd(S.commands) end
if S.caps.commands then
local params = {}
if S.session then params.sessionId = S.session else params.cwd = S.cwd or vim.fn.getcwd() end
S.conn:request("_lembas/commands", params, function(err, r)
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
local out = {}
for _, c in ipairs((r and r.commands) or {}) do
if type(c) == "table" and type(c.name) == "string" then
out[#out + 1] = {
name = c.name,
description = type(c.description) == "string" and c.description or "",
kind = (c._meta and c._meta.lembas and type(c._meta.lembas.kind) == "string") and c._meta.lembas.kind or "",
}
end
end
S.commands = out
pick_cmd(out)
end, 30000)
else
vim.notify("LLeMbas: this CLI does not list slash commands", vim.log.levels.INFO)
end
end)
end
--- A stored session's turns, drawn as the transcript (`_lembas/sessions/resume`): what was typed,
--- what the harness started by itself, and what the model thought, ran and said in answer.
local function replay(turns)
for _, turn in ipairs(turns or {}) do
if type(turn) == "table" and turn.role == "user" then
local text = type(turn.text) == "string" and turn.text or ""
local names = {}
for _, a in ipairs(type(turn.attachments) == "table" and turn.attachments or {}) do
if type(a) == "table" and type(a.name) == "string" then names[#names + 1] = a.name end
end
if text ~= "" or #names > 0 then
chat.section(turn.machine and "Harness" or "You", "LLeMbasUserHeader")
chat.append((#names > 0 and ("[" .. table.concat(names, ", ") .. "]\n") or "") .. text .. "\n")
end
elseif type(turn) == "table" and turn.role == "assistant" then
if M.config.show_thoughts and type(turn.reasoning) == "string" and turn.reasoning ~= "" then
chat.section("Thinking", "LLeMbasThoughtHeader")
chat.append(turn.reasoning .. "\n", "LLeMbasThought")
end
for _, t in ipairs(type(turn.tools) == "table" and turn.tools or {}) do
if type(t) == "table" then
local tid = tostring(t.id or "")
local entry = { id = tid, title = type(t.name) == "string" and t.name or "tool", status = t.isError and "failed" or "completed",
output = type(t.output) == "string" and t.output or nil }
tools[tid] = entry
chat.line("tool:" .. tid, render_tool_line(entry), tool_hl(entry), entry.output)
end
end
if type(turn.text) == "string" and turn.text ~= "" then
chat.section("LLeMbas", "LLeMbasAgentHeader")
chat.append(turn.text .. "\n")
end
end
end
end
--- List previous sessions in this project and resume one with its history (`_lembas/sessions/list` & `resume`).
function M.sessions()
if S.busy then return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop)", vim.log.levels.WARN) end
connect(function(ok)
if not ok then return end
if not S.caps.sessions then return vim.notify("LLeMbas: this LLeMbas CLI cannot list its sessions here yet. Update the CLI.", vim.log.levels.WARN) end
local conn = S.conn
conn:request("_lembas/sessions/list", { cwd = S.cwd or vim.fn.getcwd(), limit = 40 }, function(err, r)
if err then
if err.code == -32601 then return vim.notify("LLeMbas: this LLeMbas CLI cannot list its sessions here yet. Update the CLI.", vim.log.levels.WARN) end
return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR)
end
local list = (r and r.sessions) or {}
if #list == 0 then return vim.notify("LLeMbas: no previous sessions in this folder", vim.log.levels.INFO) end
vim.ui.select(list, {
prompt = "LLeMbas resume session",
format_item = function(s)
local when = tonumber(s.updated) and os.date("%Y-%m-%d %H:%M", math.floor(tonumber(s.updated) / 1000)) or nil
return tostring(s.title or s.id) .. (s.model and (" (" .. tostring(s.model) .. ")") or "") .. (when and (" " .. when) or "")
end,
}, function(chosen)
if not chosen or S.conn ~= conn then return end
conn:request("_lembas/sessions/resume", { sessionId = chosen.id }, function(e2, res)
if S.conn ~= conn then return end
if e2 or type(res) ~= "table" or type(res.sessionId) ~= "string" then
return vim.notify("LLeMbas: " .. words(e2 or "the agent answered without a session"), vim.log.levels.ERROR)
end
S.session = res.sessionId
S.title = (type(res.title) == "string" and res.title ~= "") and res.title or chosen.title
S.modes = (res.modes and res.modes.availableModes) or S.modes
local lm = (res._meta or {}).lembas or {}
S.mode = (res.modes and res.modes.currentModeId) or lm.mode or S.mode
S.model = lm.model or S.model
if type(res.cwd) == "string" and res.cwd ~= "" then S.cwd = res.cwd end
S.progress, S.usage, S.team = nil, nil, nil
tools = {}
pending_cards = {}
chat.clear()
M.open(false)
replay(res.turns)
S.said = nil
status()
end, 60000)
end)
end, 30000)
end)
end
--- Explain the selected lines concisely in the chat panel.
function M.explain(first, last)
M.ask(first, last, "Explain the selected code concisely, including any subtle behavior or edge cases.")
end
--- Send the current buffer's diagnostics to the agent to fix.
function M.fix()
local buf = editing_buf()
if not buf then return vim.notify("LLeMbas: open a file first", vim.log.levels.WARN) end
local diags = vim.diagnostic.get(buf)
if #diags == 0 then return vim.notify("LLeMbas: no diagnostics reported in this buffer", vim.log.levels.INFO) end
S.last_buf = buf
local editor = context.editor(buf)
local blocks = { context.file(buf) }
local dtext = context.diagnostics(buf)
if dtext then blocks[#blocks + 1] = { type = "text", text = dtext } end
S.attached = { blocks = blocks, editor = editor }
S.attached_label = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(buf), ":.") .. " (" .. #diags .. " diagnostics)"
M.open(false)
send_typed("Fix the reported diagnostics in this file.")
end
function M.toggle_thoughts()
M.config.show_thoughts = not M.config.show_thoughts
vim.notify("LLeMbas: show thinking is " .. (M.config.show_thoughts and "on" or "off"), vim.log.levels.INFO)
end
local function settings(set, cb)
connect(function(ok)
if not ok then return end
if not S.caps.editor then return vim.notify("LLeMbas: this LLeMbas CLI has no editor settings yet", vim.log.levels.WARN) end
S.conn:request("_lembas/editor/settings", set and { set = set } or vim.empty_dict(), function(err, r)
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
cb(r or {})
end, 30000)
end)
end
local function pick(which, cb)
connect(function(ok)
if not ok then return end
if not S.caps.editor then return vim.notify("LLeMbas: this LLeMbas CLI does not list models yet", vim.log.levels.WARN) end
S.conn:request("_lembas/models", vim.empty_dict(), function(err, r)
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
local items = {}
for _, m in ipairs((r or {}).models or {}) do
if type(m) == "table" and type(m.id) == "string" and vim.tbl_contains(m["for"] or { "main" }, which) then items[#items + 1] = m end
end
if #items == 0 then return vim.notify("LLeMbas: your server offers no model for that", vim.log.levels.WARN) end
vim.ui.select(items, { prompt = "LLeMbas " .. which .. " model",
format_item = function(m) return m.name and m.name ~= m.id and (m.name .. " (" .. m.id .. ")") or m.id end },
function(m) if m then cb(m.id) end end)
end, 30000)
end)
end
function M.model(name)
local function set(id)
ensure(function(ok)
if not ok then return end
S.conn:request("_lembas/configure", { sessionId = S.session, model = id }, function(err, r)
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
S.model = (r and r.model) or id
if r and type(r.effort) == "string" then S.effort = r.effort end
status()
end, 30000)
end)
end
if name and name ~= "" then return set(name) end
if S.ready and S.caps.editor then return pick("main", set) end
vim.notify("LLeMbas: model " .. (S.model or "not known yet"), vim.log.levels.INFO)
end
local function editing_win()
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then return w end
end
end
--- The file on this machine whose content is exactly `text`: `rel` under the session's folder or
--- one of the folders above it (the agent names a file from its project's root, which may be
--- above where the session works). Nil when there is none: the file changed, or is elsewhere.
local function file_with_text(rel, text)
if type(rel) ~= "string" or rel == "" or rel:match("^/") or rel:find("..", 1, true) then return nil end
local dir = S.cwd or vim.fn.getcwd()
for _ = 1, 12 do
local path = dir .. "/" .. rel
local f = io.open(path, "rb")
if f then
local same = f:read("*a") == text
f:close()
if same then return path end
end
local up = vim.fs.dirname(dir)
if not up or up == dir then break end
dir = up
end
end
--- The agent shows a file (the `show` tool, `_lembas/show`). Nothing here is rendered or run.
--- Text arrives with its content: it is opened as the file itself when the file on this machine
--- holds exactly that text, and otherwise as the text that was sent, in a buffer of its own that
--- cannot be written. A file that is not text arrives as a place on this machine: it is named in
--- the chat, and `:LLeMbasOpen` hands it to the system's viewer.
function M._show(p, reply)
if p.sessionId ~= S.session then return reply({ shown = false, reason = "This is not the session the editor shows." }) end
local id = "show:" .. tostring(p.toolCallId)
local name = type(p.path) == "string" and p.path:gsub("[\r\n]+", " ") or "a file"
local line = tonumber(p.line)
if type(p.text) == "string" then
local target = editing_win()
if not target then return reply({ shown = false, reason = "The editor has no window to show it in." }) end
local path = file_with_text(p.path, p.text)
if path then
vim.api.nvim_win_call(target, function()
pcall(vim.cmd, "keepalt edit " .. vim.fn.fnameescape(path))
if line then pcall(vim.api.nvim_win_set_cursor, 0, { line, 0 }) end
end)
S.shown = path
else
local b = vim.api.nvim_create_buf(false, true)
vim.bo[b].buftype, vim.bo[b].bufhidden, vim.bo[b].swapfile, vim.bo[b].modeline = "nofile", "wipe", false, false
vim.bo[b].undolevels = -1
local lines = vim.split((p.text:gsub("\r\n", "\n")), "\n", { plain = true })
if #lines > 1 and lines[#lines] == "" then table.remove(lines) end
vim.api.nvim_buf_set_lines(b, 0, -1, false, lines)
pcall(vim.api.nvim_buf_set_name, b, "llembas://shown/" .. tostring(p.toolCallId) .. "/" .. name)
-- Highlighting only, from the name: a file type's plugins are not started for text a model chose.
local ft = vim.filetype.match({ filename = name })
if ft then pcall(function() vim.bo[b].syntax = ft end) end
vim.bo[b].modifiable = false
vim.api.nvim_win_set_buf(target, b)
if line then pcall(vim.api.nvim_win_set_cursor, target, { math.min(line, #lines), 0 }) end
end
chat.line(id, "- shown: " .. name .. (path and "" or " (as the agent sent it)"), "LLeMbasNote")
S.said = "tool"
return reply({ shown = true })
end
-- Not text: on this machine the agent says where the file is (`uri`).
local ok, path = pcall(function() return type(p.uri) == "string" and vim.uri_to_fname(p.uri) or nil end)
if not ok or type(path) ~= "string" or path == "" then return reply({ shown = false, reason = "This editor shows only files on this computer." }) end
if vim.fn.filereadable(path) == 0 then return reply({ shown = false, reason = "The editor cannot read that file." }) end
S.shown = path
chat.line(id, ("- shown: %s (%s) — :LLeMbasOpen opens it"):format(vim.fn.fnamemodify(path, ":."), tostring(p.kind or "file"):gsub("[^%w_]", "")), "LLeMbasNote")
S.said = "tool"
reply({ shown = true })
end
--- Open the file the agent showed last with the system's viewer.
-- What the system's viewer is given: files that are only looked at or listened to. Anything else
-- (a script, a page, a shortcut, a document that can carry macros) is named and left alone.
local VIEWED = {}
for _, e in ipairs({ "png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "pdf", "mp3", "wav", "ogg", "oga", "flac", "m4a",
"mp4", "webm", "mkv", "mov", "glb", "gltf", "obj", "stl", "csv", "tsv", "txt" }) do VIEWED[e] = true end
function M.open_shown()
if not S.shown then return vim.notify("LLeMbas: nothing has been shown yet", vim.log.levels.INFO) end
local ext = (S.shown:match("%.([%w]+)$") or ""):lower()
if not VIEWED[ext] then
return vim.notify("LLeMbas: not opened, since a file of that kind may run: " .. S.shown, vim.log.levels.WARN)
end
vim.ui.open(S.shown)
end
local function said(r)
local a, m = r.autocomplete or {}, r.main or {}
vim.notify(("LLeMbas: autocomplete %s%s; main %s"):format(a.model or "not chosen",
a.source and (" (" .. a.source .. ")") or "", m.model or "as a session starts"), vim.log.levels.INFO)
end
--- The model that writes suggestions. No name: pick from the list. `quick`: for this editor only,
--- not saved; "-" goes back to the saved choice (quick) or to the instance's default (saved).
function M.autocomplete_model(name, quick)
local function set(id)
local complete = require("llembas.complete")
if quick then
M.config.complete.model = id ~= "-" and id or nil
complete.reset()
return vim.notify("LLeMbas: autocomplete here uses " .. (M.config.complete.model or "your saved choice"), vim.log.levels.INFO)
end
settings({ autocomplete_model = id ~= "-" and id or vim.NIL }, function(r) complete.reset(); said(r) end)
end
if name and name ~= "" then return set(name) end
pick("autocomplete", set)
end
--- The model for chat, rewriting and generating, saved in your account.
function M.main_model(name)
local function set(id) settings({ main_model = id ~= "-" and id or vim.NIL }, said) end
if name == "?" then return settings(nil, said) end
if name and name ~= "" then return set(name) end
pick("main", set)
end
--- Configure autocomplete max tokens & length scope preset interactively or by argument.
function M.autocomplete_tokens(arg)
local complete = require("llembas.complete")
local presets = {
{ id = "auto", tokens = 0, label = "Server default (auto)" },
{ id = "words", tokens = 24, label = "Few words — ~24 tokens (current expression)" },
{ id = "line", tokens = 64, label = "Single line — ~64 tokens (finish current line)" },
{ id = "block", tokens = 256, label = "Function / block — ~256 tokens" },
{ id = "file", tokens = 2048, label = "Large / full file — ~2048 tokens" },
{ id = "custom", tokens = nil, label = "Custom max tokens number…" },
}
local function apply(length, tokens)
if length then M.config.complete.length = length end
M.config.complete.max_tokens = (tokens and tokens > 0) and math.min(4096, math.floor(tokens)) or nil
complete.reset()
vim.notify(("LLeMbas: autocomplete scope=%s, max_tokens=%s"):format(
M.config.complete.length or "auto",
M.config.complete.max_tokens and tostring(M.config.complete.max_tokens) or "default"), vim.log.levels.INFO)
end
if arg and arg ~= "" then
local n = tonumber(arg)
if n then return apply(nil, n) end
for _, p in ipairs(presets) do
if p.id == arg and p.id ~= "custom" then return apply(p.id, p.tokens) end
end
return vim.notify("LLeMbas: use a number (0..4096) or auto|words|line|block|file", vim.log.levels.WARN)
end
vim.ui.select(presets, {
prompt = ("LLeMbas autocomplete length (now: %s, %s tokens)"):format(
M.config.complete.length or "auto", M.config.complete.max_tokens or "default"),
format_item = function(p) return p.label end,
}, function(choice)
if not choice then return end
if choice.id == "custom" then
return vim.ui.input({ prompt = "Max tokens (0 for server default, up to 4096): " }, function(val)
local n = tonumber(val or "")
if n then apply(nil, n) end
end)
end
apply(choice.id, choice.tokens)
end)
end
--- Configure custom autocomplete instructions (or "-" to clear).
function M.autocomplete_instructions(arg)
local function apply(text)
M.config.complete.instructions = (text == "-" or not text) and "" or vim.trim(text)
require("llembas.complete").reset()
vim.notify("LLeMbas: autocomplete instructions " .. (M.config.complete.instructions ~= "" and ("set: " .. M.config.complete.instructions) or "cleared"), vim.log.levels.INFO)
end
if arg and arg ~= "" then return apply(arg) end
vim.ui.input({ prompt = "Autocomplete instructions (empty or '-' to clear): ", default = M.config.complete.instructions or "" }, function(val)
if val ~= nil then apply(val) end
end)
end
--- Floating status overview card (`:LLeMbasStatus`).
function M.status_popup()
ui.setup_highlights()
local c = M.config.complete
local caps = vim.tbl_keys(S.caps)
table.sort(caps)
local lines = {
"◈ LLeMbas " .. M.version,
"──────────────────────────────────────────",
"Agent: " .. (S.ready and ("LLeMbas CLI " .. (S.cli or "(version not said)")) or S.conn and "starting…"
or (S.start_error and ("not running: " .. S.start_error) or "not running (starts when needed)")),
"Folder: " .. (S.cwd or vim.fn.getcwd()),
"Session: " .. (S.session or "(none)"),
"Title: " .. (S.title or "—"),
"Mode: " .. (S.mode or "—"),
"Model: " .. (S.model or "—"),
"Busy: " .. (S.busy and (S.progress or "working") or "no"),
"Usage: " .. (S.usage and ("↑" .. ui.format_tokens(S.usage.input) .. " ↓" .. ui.format_tokens(S.usage.output)) or "—"),
"",
"Autocomplete: " .. (c.auto and "on" or "off") .. " (debounce " .. tostring(c.debounce_ms) .. "ms)"
.. (require("llembas.complete").why() and ("\n no suggestions: " .. require("llembas.complete").why()) or ""),
"Scope / Cap: " .. (c.length or "auto") .. " · " .. (c.max_tokens and (tostring(c.max_tokens) .. " tokens") or "server default"),
"Instructions: " .. ((c.instructions and c.instructions ~= "") and c.instructions or "(none)"),
"Window model: " .. (c.model or "(account default)"),
"",
"Capabilities: " .. (#caps > 0 and table.concat(caps, ", ") or "(not connected yet)"),
}
ui.float("LLeMbas Status", lines, { border = M.config.border })
end
--- Floating keymaps & commands card (`:LLeMbasHelp`).
function M.help()
ui.setup_highlights()
local lines = {
"◈ LLeMbas IDE — Commands & Keys",
"───────────────────────────────────────────────",
"Panel:",
" :LLeMbas Toggle chat panel",
" :LLeMbasNew[!] New session (! kills hung turn)",
" :LLeMbasSessions Resume a previous session",
" :LLeMbasCompact Compact session context",
" :LLeMbasStop Stop running turn",
" :LLeMbasStatus Show agent & autocomplete status",
" :LLeMbasLogin [address] Sign this computer in to a server",
" :LLeMbasLogout Sign it out",
" :LLeMbasRestart Stop the agent (starts again when needed)",
" :LLeMbasLog What the agent wrote on stderr",
"",
"Coding:",
" :[range]LLeMbasAsk Ask about selection (or attach)",
" :[range]LLeMbasExplain Explain selected lines",
" :[range]LLeMbasEdit Rewrite selection as inline diff",
" :LLeMbasGenerate Generate code at cursor",
" :LLeMbasFix Fix buffer diagnostics",
" :LLeMbasFiles[!] Attach @file (! opens directly)",
" :LLeMbasCommands Pick a /command or skill",
"",
" :[range]LLeMbasPrompt To the prompt with the lines: ask, rewrite or add",
"",
"Inline Diff Proposal Keys:",
" ga / gr Accept / reject hunk under cursor",
" gA / gR Accept / reject all hunks",
" ]h / [h Next / previous proposed hunk",
"",
"Settings and bars:",
" :LLeMbasMenu Every command and every setting",
" :LLeMbasMode / Model / Effort",
" :LLeMbasAI [on|off] LLeMbas on or off (off: a plain editor)",
" :LLeMbasBars / Tree The four bars; the file tree",
" Prompt: <Tab> in an empty prompt switches ask, rewrite, add",
"",
"Autocomplete:",
" <Tab> / <M-Right> Accept suggestion / accept word",
" <M-\\> Trigger suggestion manually",
" :LLeMbasAutocompleteTokens [N|words|line|block|file|auto]",
" :LLeMbasAutocompleteInstructions [text|-]",
"",
"Transcript Keys: <CR>/gf open file · K tool output · y yank code · i prompt · q close",
}
ui.float("LLeMbas Help", lines, { border = M.config.border })
end
--- Compact statusline component for lualine / statusline integration.
function M.statusline()
local pending = require("llembas.diff").pending()
if pending > 0 then
return ("◈ LLeMbas: %d change%s (ga/gr)"):format(pending, pending == 1 and "" or "s")
end
if S.busy then
return "◈ LLeMbas ◐ " .. (S.progress or "working")
end
if S.session then
local short = S.model and (S.model:match("[^/]+$") or S.model) or ""
return "◈ LLeMbas" .. (S.mode and (" [" .. S.mode .. "]") or "") .. (short ~= "" and (" " .. short) or "")
end
return ""
end
function M.mode_ids()
return vim.tbl_map(function(m) return m.id end, S.modes)
end
--- The mode after the current one, in the CLI's own order.
function M.cycle_mode()
ensure(function(ok)
if not ok or #S.modes == 0 then return end
local at = 0
for i, m in ipairs(S.modes) do if m.id == S.mode then at = i end end
M.mode(S.modes[at % #S.modes + 1].id)
end)
end
--- The effort levels there are, in the CLI's order. A model offers some of them; one it does not
--- offer is read by the CLI as the model's own start level, and the answer says which is used.
M.EFFORTS = { "off", "minimal", "low", "medium", "high", "xhigh", "max", "default" }
--- The effort of the conversation. Without a level it is picked from a list. It is remembered for
--- this directory, and a session that starts later starts on it.
function M.effort(level)
if not level or level == "" then
return vim.ui.select(M.EFFORTS, { prompt = "LLeMbas effort" .. (S.effort and (" (now: " .. S.effort .. ")") or "") },
function(choice) if choice then M.effort(choice) end end)
end
if not vim.tbl_contains(M.EFFORTS, level) then
return vim.notify("LLeMbas: an effort is one of " .. table.concat(M.EFFORTS, ", "), vim.log.levels.WARN)
end
remember("effort", level)
S.effort = level
status()
if not (S.conn and S.session) then return end
S.conn:request("_lembas/configure", { sessionId = S.session, effort = level }, function(err, r)
if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end
local used = r and type(r.effort) == "string" and r.effort or level
S.effort = used
if r and type(r.model) == "string" then S.model = r.model end
if used ~= level then
vim.notify(("LLeMbas: this model does not offer the effort %s; it runs on %s"):format(level, used), vim.log.levels.INFO)
end
status()
end, 30000)
end
--- Suggestions as you type: on, off, or (nil) the other of the two. Remembered for this directory.
function M.autocomplete(on)
on = require("llembas.complete").auto(on)
remember("autocomplete", on)
status()
vim.notify("LLeMbas: suggestions as you type are " .. (on and "on" or "off"))
return on
end
--- LLeMbas on or off (nil: the other of the two). Off is a plain editor: the agent is stopped,
--- no suggestion is asked for, nothing is sent, and the chat is put away. Remembered for this
--- directory.
function M.ai(on)
if on == nil then on = not S.ai end
if on == S.ai then return on end
S.ai = on
remember("ai", on)
if not on then
pcall(function() require("llembas.complete").dismiss() end)
pcall(function() require("llembas.diff").cancel() end)
M.restart(true)
if not bars_on() then chat.close() end
end
status()
vim.notify(on and "LLeMbas is on." or OFF, vim.log.levels.INFO)
return on
end
local function state_word()
if not S.ai then return "off" end
if next(pending_cards) ~= nil then return "waiting" end
if S.busy then return S.activity or "thinking" end
if S.starting or S.connecting or (S.conn and not S.ready) then return "starting" end
if S.signed_out then return "signed_out" end
if not agent_command() then return "no_cli" end
return "idle"
end
--- What holds now, for anything that shows it (a statusline, a bar): `state` ("idle",
--- "thinking", "tools", "writing", "waiting" for your answer, "starting", "signed_out", "no_cli",
--- "off"), `title` and `session` (whether there is one), `model`, `mode`, `effort`, `context`
--- (percent of the model's window, or nil), `autocomplete` and `ai` (booleans), `intent`,
--- `attachment` (the chip's text or nil), `busy`, `changes` (proposed changes in this buffer).
--- `User LLeMbasChanged` is fired whenever one of them changes.
function M.settings()
local r = remembered()
return {
state = state_word(), title = S.title, session = S.session ~= nil,
model = S.model, mode = S.mode or M.config.mode or r.mode, effort = S.effort or r.effort,
context = S.ctx, autocomplete = M.config.complete.auto == true, ai = S.ai,
intent = S.intent, attachment = S.attached_label, busy = S.busy,
changes = require("llembas.diff").pending(),
}
end
--- The settings as lines to show: `{ id, label, value, off }` for model, mode, effort and
--- autocomplete, in that order. `choices(id, cb)` gives what a line can be set to, `set(id,
--- value)` sets it.
function M.setting_lines()
local s = M.settings()
return {
{ id = "model", label = "model", value = s.model and (s.model:match("[^/]+$") or s.model) or "—", off = not s.model },
{ id = "mode", label = "mode", value = s.mode or "—", off = not s.mode },
{ id = "effort", label = "effort", value = s.effort or "—", off = not s.effort },
{ id = "autocomplete", label = "autocomplete", value = s.autocomplete and "on" or "off", off = not s.autocomplete },
}
end
--- What the setting `id` can be set to: `cb(list)` of `{ value, label, current }`, or
--- `cb(nil, why)` when that cannot be said now. The models and the modes are the CLI's, asked
--- for now; this starts the agent when it is not running.
function M.choices(id, cb)
if id == "autocomplete" then
local on = M.config.complete.auto == true
return cb({ { value = "on", label = "on", current = on }, { value = "off", label = "off", current = not on } })
end
if not S.ai then return cb(nil, "LLeMbas is off") end
if id == "effort" then
local out, now = {}, S.effort or remembered().effort
for _, e in ipairs(M.EFFORTS) do out[#out + 1] = { value = e, label = e, current = e == now } end
return cb(out)
end
if id == "mode" then
return ensure(function(ok)
if not ok then return cb(nil, S.signed_out and "not signed in" or (S.start_error or "the agent did not start")) end
local out = {}
for _, m in ipairs(S.modes) do out[#out + 1] = { value = m.id, label = m.name or m.id, current = m.id == S.mode } end
cb(out)
end)
end
if id == "model" then
return connect(function(ok)
if not ok then return cb(nil, S.start_error or "the agent did not start") end
if not S.caps.editor then return cb(nil, "this LLeMbas CLI does not list models") end
S.conn:request("_lembas/models", vim.empty_dict(), function(err, r)
if err then return cb(nil, words(err)) end
local out = {}
for _, m in ipairs((r or {}).models or {}) do
if type(m) == "table" and type(m.id) == "string" and vim.tbl_contains(m["for"] or { "main" }, "main") then
out[#out + 1] = { value = m.id, label = (m.name and m.name ~= m.id) and m.name or (m.id:match("[^/]+$") or m.id), current = m.id == S.model }
end
end
cb(out)
end, 30000)
end, true)
end
cb(nil, "there is no such setting")
end
--- Set the setting `id` ("model", "mode", "effort", "autocomplete") to `value`.
function M.set(id, value)
if id == "model" then return M.model(value) end
if id == "mode" then return M.mode(value) end
if id == "effort" then return M.effort(value) end
if id == "autocomplete" then return M.autocomplete(value == true or value == "on") end
end
--- The LLeMbas menu: every command and every setting, to pick from.
function M.menu()
local keys = require("llembas.keys")
local s = M.settings()
local items = {
{ text = "Model: " .. (s.model or "—"), run = function() M.model() end },
{ text = "Mode: " .. (s.mode or "—"), run = function()
M.choices("mode", function(list, why)
if not list then return vim.notify("LLeMbas: " .. tostring(why), vim.log.levels.WARN) end
vim.ui.select(list, { prompt = "LLeMbas mode", format_item = function(c) return c.label .. (c.current and " (now)" or "") end },
function(c) if c then M.mode(c.value) end end)
end)
end },
{ text = "Effort: " .. (s.effort or "—"), run = function() M.effort() end },
{ text = "Autocomplete: " .. (s.autocomplete and "on" or "off"), run = function() M.autocomplete() end },
{ text = "Autocomplete model", run = function() M.autocomplete_model() end },
{ text = "Chat and rewrite model, saved in your account", run = function() M.main_model() end },
{ text = "LLeMbas: " .. (s.ai and "on" or "off"), run = function() M.ai() end },
}
if bars_on() then
local lay = require("llembas.layout")
local o = lay.options()
for _, b in ipairs({ { "top", "Top bar" }, { "bottom", "Bottom bar" }, { "tree", "Tree" }, { "chat", "Chat" } }) do
items[#items + 1] = { text = ("%s: %s"):format(b[2], o[b[1]] and "shown" or "hidden"), run = function() lay.toggle(b[1]) end }
end
end
items[#items + 1] = { text = "Make these settings the default for every directory", run = function()
store.make_default()
kept = nil
vim.notify("LLeMbas: these settings are now the default; a directory with its own keeps them")
end }
items[#items + 1] = { text = "Forget what this directory chose for itself (the default holds again at the next start)", run = function()
store.forget()
kept = nil
vim.notify("LLeMbas: this directory's own settings are forgotten")
end }
local done = {}
for _, k in ipairs(keys.table) do
if k.run and not k.scope and not done[k.desc] then
done[k.desc] = true
items[#items + 1] = { text = k.desc, keys = keys.shown(k), run = k.run }
end
end
for _, c in ipairs({ { "Compact the conversation", M.compact }, { "Show the model's thinking, on and off", M.toggle_thoughts },
{ "Sign out", function() require("llembas.login").logout() end }, { "Stop the agent (it starts again when needed)", function() M.restart() end },
{ "What the agent wrote on stderr", M.log } }) do
items[#items + 1] = { text = c[1], run = c[2] }
end
vim.ui.select(items, {
prompt = "LLeMbas",
format_item = function(i) return i.keys and i.keys ~= "" and ("%s [%s]"):format(i.text, i.keys) or i.text end,
}, function(choice) if choice then choice.run() end end)
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
ui.setup_highlights()
store.enabled = M.config.remember ~= false
kept = nil
-- What was switched off here before stays off; what the settings switch off is never switched on.
local r = remembered()
if r.ai == false then S.ai = false end
if r.autocomplete ~= nil and M.config.complete.auto then M.config.complete.auto = r.autocomplete end
require("llembas.complete").setup()
local keys = M.config.keys
if keys or M.config.bars then
require("llembas.keys").setup(type(keys) == "table" and keys or {})
-- Inside the LLeMbas terminal, say that this editor is in front, so that it hands its own
-- chords through; and take that back on the way out.
local layout = require("llembas.layout")
layout.announce(true)
local group = vim.api.nvim_create_augroup("llembas-terminal", { clear = true })
vim.api.nvim_create_autocmd({ "VimLeave", "VimSuspend" }, { group = group, callback = function() layout.announce(false) end })
vim.api.nvim_create_autocmd("VimResume", { group = group, callback = function() layout.announce(true) end })
else
require("llembas.keys").clear()
end
if M.config.bars then
require("llembas.layout").setup(type(M.config.bars) == "table" and M.config.bars or {})
elseif bars_on() then
require("llembas.layout").setup(false)
end
end
--- For the plugin's other parts: the connection once the agent has started (`cb(conn | nil)`).
function M._connect(cb, quiet)
connect(function(ok) cb(ok and S.conn or nil) end, quiet)
end
function M._note(text, level)
M.open(false)
note(text, level)
end
M.version = read_repo_version()
M._status = status
M._state = S -- for the tests
M._words = WORDS
M._say = words
M._command = agent_command
vim.api.nvim_create_autocmd("VimLeavePre", {
group = vim.api.nvim_create_augroup("llembas", { clear = true }),
-- The agent ends with the editor: its input closes, it is told to stop, and Neovim's own exit
-- closes the pipe of any that is slow, at which the CLI ends by itself.
callback = function()
if S.conn then S.conn:stop() end
pcall(function() require("llembas.login").cancel() end)
end,
})
vim.api.nvim_create_autocmd({ "FileChangedShellPost", "BufReadPost" }, {
group = "llembas",
callback = function(ev) require("llembas.diff").forget(ev.buf) 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