Files
LLeMbas-IDE/nvim/lua/llembas/login.lua
T
HomerandClaude Opus 5.5 2b1d42b976 Neovim plugin: only project files go along, the shared rules held by shared cases, review fixes
Privacy: pieces of other open files with a suggestion, and the names of other open files with a
message, now come only from files inside the working directory, never from a file that looks
like it holds secrets (one table, tests/rules/private_files.json, which the VS Code extension
reads too), and never from one the project's .gitignore leaves out. In a file that looks secret
no suggestion is asked for; said once. :help llembas-privacy says what is and is not sent.

- require("llembas").cli(): the one function that decides where the LLeMbas CLI is (PATH, then
  ~/.local/bin); LLeMbas IDE and its launcher follow it.
- A late answer from an agent that was replaced (:LLeMbasNew!, :LLeMbasRestart) no longer ends
  the new turn.
- :LLeMbasOpen judges a file by its first bytes and its name (llembas.shown), as VS Code does.
- The existing sign-in is read by whole lines; an address that reads as an option is refused.
- A protocol line over the limit is dropped whole, not the message after it; a notification
  that fails is noted in :LLeMbasLog.
- After :cd the remembered settings of the new directory hold.
- Versions: "1.2.3junk" is no version, as in VS Code.
- tests/rules/: versions, private files, server addresses, sign-in lines, protocol lines and
  openable files, as data both editors' suites read (scripts/test-nvim.sh rules).
- The stand-in agent answers _lembas/session/delete as the CLI does ({deleted}, no notification
  on serve --stdio).
- Texts: one sentence for "still working" and one for "this CLI is too old"; plain words in
  :LLeMbasStatus and the length presets; the help card is "LLeMbas — commands and keys".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 07:52:14 +00:00

220 lines
9.3 KiB
Lua

-- Signing in and out from the editor: `lembas login --json <address>` and `lembas logout`, run with
-- the same program the plugin starts as its agent. The command line is a list, never a shell's; the
-- address is the person's own (nothing is predefined here); what the CLI prints is read as data.
local M = {}
local running = nil -- { proc, killer, cancelled }
local function L() return require("llembas") end
local function same_server(a, b)
local function bare(s) return (tostring(s or ""):gsub("^https?://", ""):gsub("/+$", "")):lower() end
return bare(a) ~= "" and bare(a) == bare(b)
end
--- The events `lembas login --json` wrote: one JSON object a line (`code`, `done`, `error`).
local function events_of(text)
local out = {}
for line in tostring(text or ""):gmatch("[^\r\n]+") do
local ok, ev = pcall(vim.json.decode, line, { luanil = { object = true, array = true } })
if ok and type(ev) == "table" and type(ev.event) == "string" then out[#out + 1] = ev end
end
return out
end
M._events_of = events_of
--- A reader of `lembas login --json`'s output as it arrives: `feed(data)` takes the pieces, and
--- `on_event(ev)` is called for every event on a line that has ended. A line cut in two by the
--- pipe is one line; what has no line break yet is not read. The same reading as the VS Code
--- extension's (vscode/src/login.js); tests/rules/login_events.json holds the cases.
local function reader(on_event)
local buf = ""
return function(data)
if not data or data == "" then return end
buf = buf .. data
while true do
local nl = buf:find("\n", 1, true)
if not nl then break end
local line = buf:sub(1, nl - 1)
buf = buf:sub(nl + 1)
for _, ev in ipairs(events_of(line)) do on_event(ev) end
end
end
end
M._reader = reader
--- A server's address as the person typed it, fit to be one argument of `lembas login`: one
--- word, and never something the program would read as an option. The address, or nil.
function M.address(text)
local s = type(text) == "string" and vim.trim(text) or ""
if s == "" or #s > 2048 or s:find("[%s%c]") or s:sub(1, 1) == "-" then return nil end
return s
end
local function last_line(text)
local last = ""
for line in tostring(text or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end
return last
end
local function kill(proc)
pcall(function() proc:kill(15) end)
local t = vim.uv.new_timer()
t:start(require("llembas.rpc").KILL_AFTER_MS, 0, function()
pcall(function() t:stop(); t:close() end)
pcall(function() proc:kill(9) end)
end)
pcall(function() t:unref() end)
return t
end
--- The server this computer is signed in to now, or nil: `lembas login --json` with no address
--- reads the one login there is anew, and says whose it is. `cb(base_url | nil)`.
function M.current(exe, cb)
local done = false
local proc
local function finish(v)
if done then return end
done = true
vim.schedule(function() cb(v) end)
end
-- Read by lines, as the sign-in itself is: a `done` cut in two by the pipe must not read as
-- "not signed in", which would let another sign-in replace this one without the question.
local feed = reader(function(ev)
-- A sign-in the server no longer takes is begun anew by the CLI: that it asks for a code
-- says there was one. It is not gone through with here.
if ev.event == "code" and type(ev.instance) == "table" then
finish(ev.instance.base_url)
kill(proc)
elseif ev.event == "done" then finish(ev.base_url)
end
end)
local ok
ok, proc = pcall(vim.system, { exe, "login", "--json" }, {
text = true,
stdout = function(_, data) feed(data) end,
timeout = 15000,
}, function() finish(nil) end)
if not ok then finish(nil) end
end
--- Stop a sign-in that is under way. False when none is.
function M.cancel()
local r = running
if not r then return false end
r.cancelled = true
kill(r.proc)
return true
end
function M.running() return running ~= nil end
local function run(exe, address, ca)
local words = L()._words
local argv = { exe, "login", "--json", address }
if ca and ca ~= "" then vim.list_extend(argv, { "--ca", vim.fn.expand(ca) }) end
local me = { cancelled = false }
local settled = false
local function on_event(ev)
if ev.event == "code" then
local where = type(ev.instance) == "table" and (ev.instance.name or ev.instance.base_url) or address
local url = ev.verification_uri_complete or ev.verification_uri
L()._note(("To sign in to %s, approve the code %s at %s. The page is opened in your browser where there is one; if none opens, go to that address yourself. :LLeMbasLoginCancel stops waiting.")
:format(tostring(where), tostring(ev.user_code), tostring(ev.verification_uri)))
-- Only a web address is handed to the system, whatever the program printed.
if type(url) == "string" and url:match("^https?://[^%s]+$") and vim.ui.open then pcall(vim.ui.open, url) end
-- The CLI says when the code has run out; should it not, nothing waits for ever.
local limit = (tonumber(ev.expires_in) or 600) + 30
me.expiry = vim.defer_fn(function() if running == me then kill(me.proc) end end, limit * 1000)
elseif ev.event == "done" then
settled = true
if running == me then running = nil end
L().restart(true)
L()._note(("Signed in to %s%s. The next message starts a session."):format(tostring(ev.base_url or address),
tonumber(ev.models) and (" (%d models)"):format(ev.models) or ""))
elseif ev.event == "error" then
settled = true
if running == me then running = nil end
L()._note("Not signed in: " .. L()._say({ message = ev.message, code = ev.code }), "error")
end
end
local feed = reader(function(ev) vim.schedule(function() on_event(ev) end) end)
local ok, proc = pcall(vim.system, argv, {
text = true,
stdout = function(_, data) feed(data) end,
}, function(res)
vim.schedule(function()
if running == me then running = nil end
if me.expiry then pcall(function() me.expiry:stop(); me.expiry:close() end) end
if settled then return end
if me.cancelled then return L()._note("Signing in was cancelled.") end
local why = last_line(res.stderr)
L()._note("Not signed in: " .. (why ~= "" and why or ("the LLeMbas CLI ended (exit " .. tostring(res.code) .. ")")), "error")
end)
end)
if not ok then return L()._note(words.not_found:format(exe), "error") end
me.proc = proc
running = me
end
--- Sign this computer in to a LLeMbas server. `address`: asked for when not given. `ca`: a file
--- with the certificate authority of a server that has a private one.
function M.login(address, ca)
if running then return vim.notify("LLeMbas: a sign-in is under way (:LLeMbasLoginCancel stops it)", vim.log.levels.WARN) end
local cmd, why = L()._command()
if not cmd then return L()._note(why, "error") end
local exe = cmd[1]
if not address or not address:match("%S") then
return vim.ui.input({ prompt = "LLeMbas server address: " }, function(text)
if text and text:match("%S") then M.login(vim.trim(text), ca) end
end)
end
local typed = address
address = M.address(address)
if not address then
return vim.notify(("LLeMbas: %q is not a server's address: one word, such as ai.example.org, and not an option"):format(vim.trim(typed)), vim.log.levels.WARN)
end
ca = ca or (L().config.login or {}).ca
M.current(exe, function(now)
-- The same server again, without a certificate: the CLI reads its login anew and replaces nothing.
if not now or (same_server(now, address) and not (ca and ca ~= "")) then return run(exe, address, ca) end
local choices = {
{ go = false, label = "Cancel" },
{ go = true, label = ("Sign in to %s (replaces the sign-in to %s)"):format(address, now) },
}
vim.ui.select(choices, {
prompt = ("This computer is signed in to %s. The LLeMbas CLI keeps one sign-in: the terminal and the linked service use it too."):format(now),
format_item = function(c) return c.label end,
}, function(choice)
if choice and choice.go then run(exe, address, ca) end
end)
end)
end
--- Sign this computer out: the terminal and the linked service are signed out with it.
function M.logout()
local cmd, why = L()._command()
if not cmd then return L()._note(why, "error") end
local exe = cmd[1]
M.current(exe, function(now)
if not now then return vim.notify("LLeMbas: this computer is not signed in to a server", vim.log.levels.INFO) end
vim.ui.select({ { go = false, label = "Cancel" }, { go = true, label = "Sign out of " .. now } }, {
prompt = ("Sign this computer out of %s? The terminal and the linked service use the same sign-in."):format(now),
format_item = function(c) return c.label end,
}, function(choice)
if not choice or not choice.go then return end
vim.system({ exe, "logout" }, { text = true, timeout = 30000 }, function(res)
vim.schedule(function()
if res.code ~= 0 then
return L()._note("Not signed out: " .. (last_line(res.stderr) ~= "" and last_line(res.stderr) or ("exit " .. tostring(res.code))), "error")
end
L().restart(true)
L()._note(last_line(res.stdout) ~= "" and last_line(res.stdout) or ("Signed out of " .. now .. "."))
end)
end)
end)
end)
end
return M