:LLeMbasLogin [address] [--ca file] runs the CLI's own sign-in (lembas login --json), shows the code, opens the approval page and restarts the agent when it is done; it says whose sign-in it replaces and asks first. :LLeMbasLoginCancel and :LLeMbasLogout. A server that asks for a newer plugin (min_client in the CLI's hello) is said once. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
1604 lines
73 KiB
Lua
1604 lines
73 KiB
Lua
-- 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 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.5"
|
|
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
|
|
},
|
|
}
|
|
|
|
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,
|
|
}
|
|
|
|
--- 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, " · "))
|
|
|
|
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] = (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.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 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"
|
|
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" }
|
|
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
|
|
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" }
|
|
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
|
|
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
|
|
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 }
|
|
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
|
|
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 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; 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)
|
|
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
|
|
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 = {}
|
|
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 = 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) 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
|
|
-- 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
|
|
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
|
|
|
|
--- 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.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
|
|
local attached, label = S.attached, S.attached_label
|
|
S.attached, S.attached_label = nil, nil
|
|
S.busy = true
|
|
connect(function()
|
|
local blocks, shown, meta = {}, text, nil
|
|
if attached then
|
|
shown = ("[%s]\n%s"):format(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 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)
|
|
ui.setup_highlights()
|
|
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.on_help = M.help
|
|
chat.on_files = function() M.files("", false) end
|
|
chat.on_commands = M.commands
|
|
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 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 what = label(buf, first, last)
|
|
S.attached = { blocks = context.selection(buf, first, last), editor = context.editor(buf, first, last) }
|
|
S.attached_label = what
|
|
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 = nil, 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
|
|
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
|
|
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",
|
|
"",
|
|
"Inline Diff Proposal Keys:",
|
|
" ga / gr Accept / reject hunk under cursor",
|
|
" gA / gR Accept / reject all hunks",
|
|
" ]h / [h Next / previous proposed hunk",
|
|
"",
|
|
"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
|
|
|
|
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()
|
|
require("llembas.complete").setup()
|
|
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._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
|