diff --git a/nvim/lua/llembas/complete.lua b/nvim/lua/llembas/complete.lua index e95f08d..e428989 100644 --- a/nvim/lua/llembas/complete.lua +++ b/nvim/lua/llembas/complete.lua @@ -7,7 +7,41 @@ local ns = vim.api.nvim_create_namespace("llembas-complete") local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil, installed = false } local PREFIX_MAX, SUFFIX_MAX = 16000, 4000 -local REFUSALS = { no_model = true, not_allowed = true, not_logged_in = true, unsupported = true } +-- Refusals that stay true until something is changed: said once, and typing asks no more. +local REFUSALS = { no_model = true, not_allowed = true, unknown_model = true, not_logged_in = true, unsupported = true } +-- What to do about each, said after the server's own sentence. +local HINTS = { + no_model = ":LLeMbasAutocompleteModel chooses one", + not_allowed = ":LLeMbasAutocompleteModel chooses another", + unknown_model = ":LLeMbasAutocompleteModel chooses another", + unsupported = "it needs a newer LLeMbas server or CLI", +} + +--- The last `max` bytes of `text`, or its first, never cutting a character in two. +local function tail_bytes(text, max) + if #text <= max then return text end + local at = #text - max + 1 + while at <= #text and text:byte(at) >= 0x80 and text:byte(at) <= 0xBF do at = at + 1 end + return text:sub(at) +end +local function head_bytes(text, max) + if #text <= max then return text end + local at = max + while at > 0 and text:byte(at + 1) and text:byte(at + 1) >= 0x80 and text:byte(at + 1) <= 0xBF do at = at - 1 end + return text:sub(1, at) +end +M._tail_bytes, M._head_bytes = tail_bytes, head_bytes + +--- Say why no suggestion comes. Asked for on the key, it is said whole; while you type it is one +--- short line, so that nothing waits for a key press — `:LLeMbasStatus` has the whole of it. +local function say(text, manual) + if not manual then + local room = math.max(40, vim.o.columns - 12) + local tail = "… (:LLeMbasStatus)" + if vim.fn.strdisplaywidth(text) > room then text = vim.fn.strcharpart(text, 0, room - vim.fn.strdisplaywidth(tail)) .. tail end + end + vim.notify("LLeMbas: " .. text, vim.log.levels.WARN) +end local LENGTH_PRESETS = { auto = { tokens = nil, instruction = "" }, @@ -154,8 +188,7 @@ function M.request(manual) before[#before + 1] = line:sub(1, col) table.insert(after, 1, line:sub(col + 1)) local prefix, suffix = table.concat(before, "\n"), table.concat(after, "\n") - if #prefix > PREFIX_MAX then prefix = prefix:sub(-PREFIX_MAX) end - if #suffix > SUFFIX_MAX then suffix = suffix:sub(1, SUFFIX_MAX) end + prefix, suffix = tail_bytes(prefix, PREFIX_MAX), head_bytes(suffix, SUFFIX_MAX) cancel() local seq = st.seq L()._connect(function(conn) @@ -163,12 +196,20 @@ function M.request(manual) if not conn then -- An agent that does not start is not started again at every pause: once a minute at most. st.wait_until = vim.uv.now() + 60000 - if manual then vim.notify("LLeMbas: " .. (L()._state.start_error or "the agent did not start"), vim.log.levels.WARN) end + st.why = L()._state.start_error or "the agent did not start" + if manual or not st.said_start then + st.said_start = true + say("no suggestions: " .. st.why, manual) + end return end if not L()._state.caps.editor then - st.off = "this LLeMbas CLI does not offer autocomplete yet" - if manual then vim.notify("LLeMbas: " .. st.off, vim.log.levels.WARN) end + st.off = "this LLeMbas CLI has no autocomplete yet. Update the CLI." + st.why = st.off + if manual or not st.said then + st.said = true + say("no suggestions: " .. st.off, manual) + end return end local id = ("c%d"):format(seq) @@ -192,28 +233,31 @@ function M.request(manual) if seq ~= st.seq then return end if err then local reason = (type(err.data) == "table" and type(err.data.reason) == "string") and err.data.reason or "" - local msg = tostring(err.message or "completion failed") - if REFUSALS[reason] or reason == "" then - -- Permanent refusal (e.g. no model): said once, stops asking until a model is chosen. - st.off = msg + local msg = L()._say(err) + if REFUSALS[reason] then + -- It stays refused until something is changed: said once, and typing asks no more. + st.off = msg .. (HINTS[reason] and (" (" .. HINTS[reason] .. ")") or "") + st.why = st.off if manual or not st.said then st.said = true - vim.notify("LLeMbas: no suggestions: " .. st.off .. " (:LLeMbasAutocompleteModel chooses a model)", vim.log.levels.WARN) + say("no suggestions: " .. st.off, manual) end else - -- Transient server failure: pause briefly instead of shutting off permanently. + -- Anything else may pass (the server is busy, or away): typing asks again in a while. st.wait_until = vim.uv.now() + 15000 - if manual then vim.notify("LLeMbas: " .. msg, vim.log.levels.WARN) end + st.why = msg + if manual then say("no suggestion: " .. msg, true) end end return end + st.why = nil if manual and st.off then st.off, st.said = nil, false end if not r or r.cancelled or type(r.text) ~= "string" or r.text == "" then return end if vim.api.nvim_get_current_buf() ~= buf or not M._typing() then return end local now = vim.api.nvim_win_get_cursor(0) if now[1] - 1 ~= row or now[2] ~= col then return end show(buf, row, col, (r.text:gsub("\r\n", "\n"))) - end) + end, 60000) end, not manual) end @@ -279,7 +323,10 @@ function M.auto(on) end --- A model or token/instruction setting was chosen: ask again. -function M.reset() st.off, st.said, st.last_warm, st.wait_until = nil, false, nil, nil end +function M.reset() st.off, st.said, st.said_start, st.last_warm, st.wait_until, st.why = nil, false, false, nil, nil, nil end + +--- Why no suggestion came last time, or nil. +function M.why() return st.why end local function typed() M.clear() diff --git a/nvim/lua/llembas/context.lua b/nvim/lua/llembas/context.lua index 5028a99..69c8e5e 100644 --- a/nvim/lua/llembas/context.lua +++ b/nvim/lua/llembas/context.lua @@ -115,43 +115,110 @@ function M.buffer_of(path) end end +--- A buffer's text as it would be saved: its lines with the file's line ends, and a last line +--- break when the file has one. +local function buffer_text(buf) + local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false) + if #lines == 1 and lines[1] == "" then return "" end + local nl = vim.bo[buf].fileformat == "dos" and "\r\n" or "\n" + return table.concat(lines, nl) .. ((vim.bo[buf].eol or vim.bo[buf].fixeol) and nl or "") +end + +-- What the agent wrote last into a buffer, and the buffer's change count right after: while the +-- buffer has not changed since, the agent is given back exactly the text it wrote. It compares +-- texts to know whether a file changed behind it, and a buffer never holds a text quite as it +-- was written (line ends are the file's, the last line break is the editor's). +local written = {} -- buf -> { tick, content } + +--- Whether `text` is UTF-8 text: no NUL, and no byte that is not part of a character. +local function valid_utf8(text) + local i, n = 1, #text + while i <= n do + i = text:find("[%z\128-\255]", i) + if not i then return true end + local c = text:byte(i) + local more = (c >= 0xC2 and c <= 0xDF) and 1 or (c >= 0xE0 and c <= 0xEF) and 2 or (c >= 0xF0 and c <= 0xF4) and 3 or nil + if not more or i + more > n then return false end + for k = 1, more do + local b = text:byte(i + k) + if b < 0x80 or b > 0xBF then return false end + end + i = i + more + 1 + end + return true +end +M._valid_utf8 = valid_utf8 + --- The agent writes a file (ACP `fs/write_text_file`): one that is open here gets the text in its ---- buffer and is saved at once, so the buffer and the disk agree when the agent is answered. A file ---- that is not open is refused, and the agent writes the disk itself. +--- buffer and is saved at once, so the buffer and the disk agree when the agent is answered; one +--- that is not open is written to the disk. Either way the text is the file's content before the +--- answer, as ACP asks -- an editor that answers reads must take writes too, or the agent could +--- never change a file it has read here. function M.write_for_agent(params, reply) local path, content = params.path, params.content - if type(path) ~= "string" or type(content) ~= "string" then return reply(nil, { code = -32602, message = "no path or no text" }) end + if type(path) ~= "string" or type(content) ~= "string" or not path:match("^/") then + return reply(nil, { code = -32602, message = "an absolute path and the content are needed" }) + end local buf = M.buffer_of(path) - if not buf then return reply(nil, { code = -32002, message = "not open in the editor" }) end + if not buf then + local dir = vim.fs.dirname(path) + if vim.fn.isdirectory(dir) == 0 and not pcall(vim.fn.mkdir, dir, "p") then + return reply(nil, { code = -32002, message = "the editor could not make the folder " .. dir }) + end + local f, err = io.open(path, "wb") + if not f then return reply(nil, { code = -32002, message = "the editor could not write it: " .. tostring(err) }) end + f:write(content) + f:close() + return reply(vim.NIL) + end if not vim.bo[buf].modifiable or vim.bo[buf].readonly then return reply(nil, { code = -32002, message = "the editor holds that file read-only" }) end local lines = vim.split((content:gsub("\r\n", "\n")), "\n", { plain = true }) - if lines[#lines] == "" and #lines > 1 then table.remove(lines) end + local ends = lines[#lines] == "" + if ends and #lines > 1 then table.remove(lines) end vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines) -- Saved as it is: no autocommand (a formatter) may change what the agent believes it wrote. local ok, err = pcall(vim.api.nvim_buf_call, buf, function() vim.cmd("silent noautocmd write!") end) if not ok then return reply(nil, { code = -32002, message = "the editor could not save it: " .. tostring(err) }) end + written[buf] = { tick = vim.api.nvim_buf_get_changedtick(buf), content = content } reply(vim.NIL) end --- The agent asks for a file's text (ACP `fs/read_text_file`): a file open here is answered from its ---- buffer, saved or not, so the agent sees what you see. Anything else is read from disk. +--- buffer, saved or not, so the agent sees what you see. Anything else is read from disk, byte for +--- byte. A file that is not text is refused, and the agent reads the disk itself. function M.read_for_agent(params, reply) local path = params.path if type(path) ~= "string" or path == "" then return reply(nil, { code = -32602, message = "no path" }) end - local lines + local text local buf = M.buffer_of(path) if buf then - lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false) + local w = written[buf] + if w and w.tick == vim.api.nvim_buf_get_changedtick(buf) then text = w.content + else + written[buf] = nil + text = buffer_text(buf) + end else - local ok, read = pcall(vim.fn.readfile, path) - if not ok then return reply(nil, { code = -32002, message = "cannot read " .. path }) end - lines = read + local f = io.open(path, "rb") + if not f then return reply(nil, { code = -32002, message = "cannot read " .. path }) end + text = f:read("*a") or "" + f:close() + if not valid_utf8(text) then return reply(nil, { code = -32002, message = "not a text file: " .. path }) end end - local first = math.max(1, tonumber(params.line) or 1) - local last = params.limit and (first + tonumber(params.limit) - 1) or #lines - reply({ content = table.concat(vim.list_slice(lines, first, last), "\n") }) + if params.line or params.limit then + local lines = vim.split(text, "\n", { plain = true }) + local first = math.max(1, tonumber(params.line) or 1) + local last = tonumber(params.limit) and (first + tonumber(params.limit) - 1) or #lines + text = table.concat(vim.list_slice(lines, first, last), "\n") + end + reply({ content = text }) end +vim.api.nvim_create_autocmd({ "BufWipeout", "BufUnload" }, { + group = vim.api.nvim_create_augroup("llembas-context", { clear = true }), + callback = function(ev) written[ev.buf] = nil end, +}) + return M diff --git a/nvim/lua/llembas/diff.lua b/nvim/lua/llembas/diff.lua index bdc551d..5c63bb6 100644 --- a/nvim/lua/llembas/diff.lua +++ b/nvim/lua/llembas/diff.lua @@ -244,19 +244,22 @@ local function run_edit(buf, first, last, instruction, verb) if not conn then rewriting[buf] = nil written_by_id[id] = nil - return vim.notify("LLeMbas: the agent did not start", vim.log.levels.ERROR) + vim.api.nvim_echo({ { "" } }, false, {}) + return vim.notify("LLeMbas: " .. (L._state.start_error or "the agent did not start"), vim.log.levels.ERROR) end local body_text = table.concat(text, "\n") if body_text == "" then body_text = " " end conn:request("_lembas/edit", { id = id, cwd = vim.fn.getcwd(), sessionId = L._state.session, path = name ~= "" and name or nil, text = body_text, before = table.concat(before, "\n"), after = table.concat(after, "\n"), - language = vim.bo[buf].filetype, instruction = instruction, model = L.config.model, + language = vim.bo[buf].filetype ~= "" and vim.bo[buf].filetype or nil, instruction = instruction, + -- With a session its model writes; without one, the model a session here would start on. + model = (not L._state.session) and L.config.model or nil, }, function(err, r) if rewriting[buf] == id then rewriting[buf] = nil end written_by_id[id] = nil vim.api.nvim_echo({ { "" } }, false, {}) - if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + if err then return vim.notify("LLeMbas: " .. L._say(err), vim.log.levels.ERROR) end if not r or r.cancelled or not vim.api.nvim_buf_is_valid(buf) then return end if vim.api.nvim_buf_get_changedtick(buf) ~= tick then return vim.notify("LLeMbas: the buffer changed while the rewrite was written; nothing is shown. Ask again.", vim.log.levels.WARN) diff --git a/nvim/lua/llembas/init.lua b/nvim/lua/llembas/init.lua index 63009b8..41264d4 100644 --- a/nvim/lua/llembas/init.lua +++ b/nvim/lua/llembas/init.lua @@ -20,6 +20,86 @@ local function read_repo_version() 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 + +--- 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. Run `lembas login ` in a terminal, then try again.", + signed_out = "The server no longer accepts this computer's sign-in. Run `lembas login ` in a terminal, then try again.", + -- 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" @@ -47,8 +127,33 @@ 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") @@ -92,6 +197,11 @@ local function status() 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 @@ -224,8 +334,10 @@ local function on_permission(p, reply) prompt = prompt:gsub("[\r\n]+", " "):sub(1, 400), format_item = function(o) return o.name or o.optionId end, }, function(choice) - pending_cards[call_id] = nil 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" } }) @@ -246,12 +358,14 @@ local function on_question(p, reply) 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" }) @@ -302,7 +416,8 @@ local function on_question(p, reply) end if choice._custom then return vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text) - if not text or not text:match("%S") then return dismiss_all() end + 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) @@ -337,7 +452,8 @@ local function on_question(p, reply) end if choice._custom then vim.ui.input({ prompt = (q.question or "Answer") .. ": " }, function(text) - if not text or not text:match("%S") then return dismiss_all() end + 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) @@ -383,6 +499,7 @@ local function on_plan(p, reply) 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") @@ -407,23 +524,55 @@ local function on_plan(p, reply) end) end -local function stopped(code, stderr) - local was = S.session ~= nil or S.starting ~= nil +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 = nil, nil + 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 = "" - for line in (stderr or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end - note(("The agent stopped (exit %s)%s"):format(tostring(code), last ~= "" and (": " .. last) or "."), "error") + 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) @@ -436,7 +585,14 @@ local function connect(cb, quiet) for _, f in ipairs(waiting) do f(ok) end end local me = {} - local conn, err = rpc.start(M.config.cmd, { + 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) @@ -453,12 +609,20 @@ local function connect(cb, quiet) 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 - local pr = ev.progress - S.progress = (pr and type(pr.phase) == "string") and (pr.phase:gsub("_", " ") .. (pr.detail and (": " .. pr.detail) or "")) or nil + -- 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" then - local inp = tonumber(ev.input_tokens or ev.input or ev.tokens_in) or 0 - local outp = tonumber(ev.output_tokens or ev.output or ev.tokens_out) or 0 + 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() @@ -489,38 +653,52 @@ local function connect(cb, quiet) 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) if S.conn == me.conn then stopped(code, stderr) end end, - }, { cwd = vim.fn.getcwd() }) + 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 - if not quiet then note(("Could not start %s: %s"):format(M.config.cmd[1], err), "error") end - S.start_error = ("could not start %s: %s"):format(M.config.cmd[1], err) + 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 = conn, false, nil + 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 = 2, editor = true, show = true, media = true } } }, - clientInfo = { name = "llembas.nvim", version = M.version }, + _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 - if not quiet then note("The agent refused to start: " .. tostring(e1.message), "error") end + 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 + -- 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) + 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) +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 } @@ -535,10 +713,22 @@ local function ensure(cb) local meta = {} if M.config.mode then meta.mode = M.config.mode end if M.config.model then meta.model = M.config.model end - conn:request("session/new", { cwd = vim.fn.getcwd(), mcpServers = {}, _meta = meta }, function(e2, r) + 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 then - note("No session: " .. tostring(e2.message), "error") + 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 @@ -546,9 +736,11 @@ local function ensure(cb) 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) + end, 60000) end) end @@ -559,18 +751,32 @@ local function send(blocks, shown, meta) 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 note("The turn failed: " .. tostring(err.message), "error") + 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 and r.stopReason ~= "end_turn" then note("The turn ended: " .. r.stopReason) 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() @@ -594,8 +800,8 @@ local function send_typed(text) 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("Steer failed: " .. tostring(err.message), "error") end - end) + 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) @@ -725,6 +931,40 @@ 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 @@ -732,12 +972,14 @@ function M.new(force) 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 = nil, nil, nil, 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 @@ -746,10 +988,10 @@ 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: " .. tostring(err.message), vim.log.levels.ERROR) end + 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) + end, 600000) end function M.mode(id) @@ -757,10 +999,10 @@ function M.mode(id) if not ok then return end local function set(mode) S.conn:request("session/set_mode", { sessionId = S.session, modeId = mode }, function(err) - if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end S.mode = mode status() - end) + 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 }, @@ -770,7 +1012,13 @@ 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) - ensure(function(ok) + 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 = {} @@ -785,7 +1033,7 @@ function M.files(query, open_directly) }, function(entry) if not entry then return end if open_directly then - local full = entry.path:match("^/") and entry.path or (vim.fn.getcwd() .. "/" .. entry.path) + 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 @@ -800,10 +1048,13 @@ function M.files(query, open_directly) end) end if S.caps.files then - S.conn:request("_lembas/files/search", { sessionId = S.session, query = query or "", limit = 50 }, function(err, r) - if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + -- 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) + end, 30000) else local found = vim.fn.glob("**/*", false, true) local out = {} @@ -821,7 +1072,7 @@ end --- Pick a session slash command (`/compact`, `/review`, skills, etc.) and insert it into the prompt. function M.commands() - ensure(function(ok) + 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 @@ -840,98 +1091,110 @@ function M.commands() end if #S.commands > 0 then return pick_cmd(S.commands) end if S.caps.commands then - S.conn:request("_lembas/commands", { sessionId = S.session }, function(err, r) - if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end + 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 (c.source 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) + 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 - S.conn:request("_lembas/sessions/list", { cwd = vim.fn.getcwd(), limit = 40 }, function(err, r) - if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) 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 directory", vim.log.levels.INFO) end + 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) return (s.title or s.id) .. (s.model and (" (" .. s.model .. ")") or "") end, + 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 then return end - S.conn:request("_lembas/sessions/resume", { sessionId = chosen.id }, function(e2, res) - if e2 then return vim.notify("LLeMbas: " .. tostring(e2.message), vim.log.levels.ERROR) end + 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 or chosen.title + 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) - for _, turn in ipairs(res.turns or {}) do - if type(turn) == "table" then - if turn.role == "user" then - local u_text = type(turn.text) == "string" and turn.text or "" - if u_text ~= "" then - chat.section(turn.machine and "Harness" or "You", "LLeMbasUserHeader") - chat.append(u_text .. "\n") - end - elseif 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(turn.tools or {}) do - local tid = tostring(t.id or ("h" .. tostring(#tools + 1))) - local entry = { id = tid, title = t.title or 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("hist:" .. tid, render_tool_line(entry), tool_hl(entry), entry.output) - end - if type(turn.text) == "string" and turn.text ~= "" then - chat.section("LLeMbas", "LLeMbasAgentHeader") - chat.append(turn.text .. "\n") - end - else - -- Legacy combined shape fallback - if type(turn.user) == "string" and turn.user ~= "" then - chat.section("You", "LLeMbasUserHeader") - chat.append(turn.user .. "\n") - end - for _, t in ipairs(turn.tools or {}) do - chat.line("hist:" .. tostring(t.id or ""), ("- %s %s"):format(t.isError and "✗" or "✓", t.title or t.name or "tool"), t.isError and "LLeMbasToolFail" or "LLeMbasToolDone") - end - if type(turn.assistant) == "string" and turn.assistant ~= "" then - chat.section("LLeMbas", "LLeMbasAgentHeader") - chat.append(turn.assistant .. "\n") - end - end - end - end + replay(res.turns) S.said = nil status() - end) + end, 60000) end) - end) + end, 30000) end) end @@ -967,9 +1230,9 @@ local function settings(set, cb) 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: " .. tostring(err.message), vim.log.levels.ERROR) end + if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end cb(r or {}) - end) + end, 30000) end) end @@ -978,15 +1241,16 @@ local function pick(which, cb) 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: " .. tostring(err.message), vim.log.levels.ERROR) end + 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 vim.tbl_contains(m["for"] or { "main" }, which) then items[#items + 1] = m end + 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) + end, 30000) end) end @@ -995,10 +1259,10 @@ function M.model(name) 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: " .. tostring(err.message), vim.log.levels.ERROR) end + if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end S.model = (r and r.model) or id status() - end) + end, 30000) end) end if name and name ~= "" then return set(name) end @@ -1006,48 +1270,77 @@ function M.model(name) vim.notify("LLeMbas: model " .. (S.model or "not known yet"), vim.log.levels.INFO) end ---- The agent shows a file (the `show` tool). The agent runs on this machine, so the file is opened ---- from where it is: text in the window you edit in, anything else named in the chat and opened by ---- the system's own viewer on request. Nothing here is rendered or run. -function M._show(p, reply) - local path = p.uri and vim.uri_to_fname(p.uri) or p.path - local target +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 target = w break end + if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then return w end end - if type(path) == "string" and path ~= "" then - if not path:match("^/") then path = vim.fn.getcwd() .. "/" .. path 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 - if (not path or path == "" or vim.fn.filereadable(path) == 0) and type(p.text) == "string" then - local b = vim.api.nvim_create_buf(false, true) - vim.bo[b].buftype = "nofile" - vim.bo[b].bufhidden = "wipe" - vim.bo[b].swapfile = false - vim.bo[b].modeline = false - vim.api.nvim_buf_set_lines(b, 0, -1, false, vim.split(p.text, "\n", { plain = true })) - if type(p.language) == "string" and p.language ~= "" then pcall(function() vim.bo[b].filetype = p.language end) end - vim.bo[b].modifiable = false - if target then vim.api.nvim_win_set_buf(target, b) end - chat.line("show:" .. tostring(p.toolCallId), "- shown: " .. tostring(p.path or "text"), "LLeMbasNote") +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 - if type(path) ~= "string" or path == "" then return reply({ shown = false, reason = "no path" }) end - if vim.fn.filereadable(path) == 0 then return reply({ shown = false, reason = "the editor cannot read that file" }) end - local texty = ({ markdown = true, code = true, text = true, html = true, table = true, svg = true, notebook = true })[p.kind or ""] + -- 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 - local rel = vim.fn.fnamemodify(path, ":.") - if texty then - if target then - vim.api.nvim_win_call(target, function() - pcall(vim.cmd, "keepalt edit " .. vim.fn.fnameescape(path)) - if tonumber(p.line) then pcall(vim.api.nvim_win_set_cursor, 0, { tonumber(p.line), 0 }) end - end) - end - chat.line("show:" .. tostring(p.toolCallId), "- shown: " .. rel, "LLeMbasNote") - else - chat.line("show:" .. tostring(p.toolCallId), ("- shown: %s (%s) — :LLeMbasOpen opens it"):format(rel, tostring(p.kind or "file")), "LLeMbasNote") - end + 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 @@ -1163,7 +1456,9 @@ function M.status_popup() local lines = { "◈ LLeMbas " .. M.version, "──────────────────────────────────────────", - "Agent: " .. (S.ready and "connected" or S.conn and "starting…" or "idle"), + "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 "—"), @@ -1171,7 +1466,8 @@ function M.status_popup() "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)", + "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)"), @@ -1194,6 +1490,8 @@ function M.help() " :LLeMbasCompact Compact session context", " :LLeMbasStop Stop running turn", " :LLeMbasStatus Show agent & autocomplete status", + " :LLeMbasRestart Stop the agent (starts again when needed)", + " :LLeMbasLog What the agent wrote on stderr", "", "Coding:", " :[range]LLeMbasAsk Ask about selection (or attach)", @@ -1259,9 +1557,13 @@ end M.version = read_repo_version() M._state = S -- for the tests +M._words = WORDS +M._say = words 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 end, }) vim.api.nvim_create_autocmd({ "FileChangedShellPost", "BufReadPost" }, { diff --git a/nvim/lua/llembas/rpc.lua b/nvim/lua/llembas/rpc.lua index f9ba1a3..aa15f34 100644 --- a/nvim/lua/llembas/rpc.lua +++ b/nvim/lua/llembas/rpc.lua @@ -4,10 +4,13 @@ M.__index = M local MAX_BUF_BYTES = 64 * 1024 * 1024 -- 64 MB cap against an unbounded unterminated stream +local MAX_ERR_BYTES = 64 * 1024 -- what is kept of the agent's stderr: its end +M.KILL_AFTER_MS = 5000 + --- Start `cmd` and speak JSON-RPC with it. `on.request(method, params, reply)` and --- `on.notify(method, params)` run on the main loop; `on.exit(code, stderr)` when the process ends. function M.start(cmd, on, opts) - local self = setmetatable({ next_id = 1, waiting = {}, on = on, buf = "", err = {}, closed = false }, M) + local self = setmetatable({ next_id = 1, waiting = {}, timers = {}, on = on, buf = "", err = "", closed = false }, M) local ok, proc = pcall(vim.system, cmd, { stdin = true, cwd = opts and opts.cwd or nil, @@ -15,17 +18,20 @@ function M.start(cmd, on, opts) stdout = function(_, data) if data then self:_feed(data) end end, stderr = function(_, data) if data then - self.err[#self.err + 1] = data - while #self.err > 40 do table.remove(self.err, 1) end + self.err = self.err .. data + if #self.err > MAX_ERR_BYTES then self.err = self.err:sub(-MAX_ERR_BYTES) end end end, }, function(res) vim.schedule(function() self.closed = true + if self.killer then pcall(function() self.killer:stop(); self.killer:close() end); self.killer = nil end local waiting = self.waiting self.waiting = {} - for _, cb in pairs(waiting) do cb({ code = -32000, message = "the agent stopped" }, nil) end - if on.exit then on.exit(res.code, table.concat(self.err)) end + for id in pairs(self.timers) do self:_untime(id) end + -- The exit is said first, so that what was waited for fails knowing the agent is gone. + if on.exit then pcall(on.exit, res.code, self.err, res.signal) end + for _, cb in pairs(waiting) do pcall(cb, { code = -32000, message = "the agent stopped" }, nil) end end) end) if not ok then return nil, tostring(proc) end @@ -47,7 +53,12 @@ function M:_feed(data) self.buf = self.buf:sub(nl + 1) if line:match("%S") then local ok, msg = pcall(vim.json.decode, line, { luanil = { object = true, array = true } }) - if ok and type(msg) == "table" then vim.schedule(function() self:_message(msg) end) end + if ok and type(msg) == "table" then + vim.schedule(function() self:_message(msg) end) + else + -- Not the protocol: something printed on stdout. Kept with what the agent said on stderr. + self.err = (self.err .. "[stdout] " .. line:sub(1, 400) .. "\n"):sub(-MAX_ERR_BYTES) + end end end end @@ -70,33 +81,69 @@ function M:_message(msg) elseif msg.id ~= nil then local cb = self.waiting[msg.id] self.waiting[msg.id] = nil + self:_untime(msg.id) if cb then cb(msg.error, msg.result) end end end +function M:_untime(id) + local t = self.timers[id] + if not t then return end + self.timers[id] = nil + pcall(function() t:stop(); t:close() end) +end + function M:_write(msg) if self.closed then return end pcall(function() self.proc:write(vim.json.encode(msg) .. "\n") end) end ---- A request; `cb(err, result)` on the main loop. -function M:request(method, params, cb) +--- A request; `cb(err, result)` on the main loop. `timeout_ms`: no answer by then is an error +--- (`err.timeout`), and an answer that comes later is dropped. +function M:request(method, params, cb, timeout_ms) if self.closed then return cb and cb({ code = -32000, message = "the agent is not running" }, nil) end local id = self.next_id self.next_id = id + 1 self.waiting[id] = cb or function() end + if timeout_ms and timeout_ms > 0 then + local t = vim.uv.new_timer() + self.timers[id] = t + t:start(timeout_ms, 0, vim.schedule_wrap(function() + self:_untime(id) + local waiting = self.waiting[id] + self.waiting[id] = nil + if waiting then + waiting({ code = -32001, timeout = true, + message = ("the LLeMbas CLI did not answer %s within %d seconds"):format(method, math.floor(timeout_ms / 1000 + 0.5)) }, nil) + end + end)) + end self:_write({ jsonrpc = "2.0", id = id, method = method, params = params }) return id end +--- What the agent wrote on stderr (its end, when it was long). +function M:stderr() return self.err end + function M:notify(method, params) self:_write({ jsonrpc = "2.0", method = method, params = params }) end +--- End the process: its input is closed (the CLI ends by itself then), it is asked to stop, and +--- one that is still there five seconds later is killed. Nothing is left running. function M:stop() - if self.closed then return end + if self.closed or self.stopping then return end + self.stopping = true pcall(function() self.proc:write(nil) end) pcall(function() self.proc:kill(15) end) + local t = vim.uv.new_timer() + self.killer = t + t:start(M.KILL_AFTER_MS, 0, function() + pcall(function() t:stop(); t:close() end) + if not self.closed then pcall(function() self.proc:kill(9) end) end + end) + -- The timer must not keep an editor that is quitting alive. + pcall(function() t:unref() end) end return M diff --git a/nvim/lua/llembas/ui.lua b/nvim/lua/llembas/ui.lua index e4f1161..a3b4945 100644 --- a/nvim/lua/llembas/ui.lua +++ b/nvim/lua/llembas/ui.lua @@ -93,6 +93,11 @@ end --- Open a read-only floating window with rounded borders (`q` or `` closes). function M.float(title, lines, opts) opts = opts or {} + local flat = {} + for _, l in ipairs(lines) do + for _, part in ipairs(vim.split(tostring(l), "\n", { plain = true })) do flat[#flat + 1] = (part:gsub("\r", "")) end + end + lines = flat local b = vim.api.nvim_create_buf(false, true) vim.bo[b].buftype = "nofile" vim.bo[b].bufhidden = "wipe" diff --git a/nvim/plugin/llembas.lua b/nvim/plugin/llembas.lua index c35dd2a..06fcf57 100644 --- a/nvim/plugin/llembas.lua +++ b/nvim/plugin/llembas.lua @@ -52,4 +52,6 @@ cmd("LLeMbasExplain", function(o) L().explain(o.line1, o.line2) end, cmd("LLeMbasFix", function() L().fix() end, { desc = "LLeMbas: fix diagnostics in the current buffer" }) cmd("LLeMbasToggleThoughts", function() L().toggle_thoughts() end, { desc = "LLeMbas: toggle showing model thinking" }) cmd("LLeMbasStatus", function() L().status_popup() end, { desc = "LLeMbas: show agent, session and autocomplete status" }) +cmd("LLeMbasRestart", function() L().restart() end, { desc = "LLeMbas: stop the agent (it starts again when needed)" }) +cmd("LLeMbasLog", function() L().log() end, { desc = "LLeMbas: show what the agent wrote on stderr" }) cmd("LLeMbasHelp", function() L().help() end, { desc = "LLeMbas: show commands and keymaps" }) diff --git a/nvim/tests/fake_agent.py b/nvim/tests/fake_agent.py deleted file mode 100755 index e817681..0000000 --- a/nvim/tests/fake_agent.py +++ /dev/null @@ -1,239 +0,0 @@ -#!/usr/bin/env python3 -"""A stand-in for `lembas serve --stdio`, for the plugin's tests: ACP version 1 over lines. - -What it does is steered by words in the prompt's last text block: PERM asks for an approval, -WRITE rewrites that file, SLOW waits to be cancelled, CRASH exits. Every request it gets is -appended to the file named by FAKE_AGENT_LOG, one JSON object a line. -""" -import json -import os -import sys -import threading - -LOG = os.environ.get("FAKE_AGENT_LOG") -lock = threading.Lock() -waiting = {} -cancelled = threading.Event() -next_id = [1000] - - -def out(msg): - with lock: - sys.stdout.write(json.dumps(msg) + "\n") - sys.stdout.flush() - - -def update(session, body): - out({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": session, "update": body}}) - - -def ask(method, params): - with lock: - next_id[0] += 1 - rid = next_id[0] - done = threading.Event() - waiting[rid] = [done, None] - out({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}) - done.wait(10) - return waiting.pop(rid)[1] - - -EDITOR = os.environ.get("FAKE_EDITOR") == "1" -SETTINGS = {"autocomplete": {"model": None, "source": None}, "main": {"model": None}} -gone = set() - - -def complete(msg): - p = msg["params"] - prefix = p["prefix"] - if "NOMODEL" in prefix: - out({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32602, "message": "no autocomplete model is chosen"}}) - return - if "SLOWC" in prefix: - for _ in range(40): - if p.get("id") in gone: - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"text": "", "cancelled": True}}) - return - threading.Event().wait(0.05) - text = "tail()\n second line" if "TWO" in prefix else "<" + prefix[-3:] + "|" + (p.get("suffix") or "")[:3] + ">" - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"text": text, "model": p.get("model") or "example/model-a", "finish": "stop"}}) - - -def prompt(msg): - p = msg["params"] - session = p["sessionId"] - text = [b["text"] for b in p["prompt"] if b["type"] == "text"][-1] - update(session, {"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": "hidden thought"}}) - update(session, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Hello "}}) - update(session, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "there.\nSecond line"}}) - if "PERM" in text: - answer = ask("session/request_permission", { - "sessionId": session, - "toolCall": {"toolCallId": "perm-" + str(msg["id"]), "title": "rm -r build", "kind": "execute", "status": "pending", "rawInput": {}}, - "options": [{"optionId": "once", "name": "Allow once", "kind": "allow_once"}, - {"optionId": "deny", "name": "Deny", "kind": "reject_once"}], - "_meta": {"lembas": {"tool": "bash", "reason": "deletes files"}}}) - got = (answer or {}).get("outcome", {}) - update(session, {"sessionUpdate": "agent_message_chunk", - "content": {"type": "text", "text": "\nanswer=" + str(got.get("optionId") or got.get("outcome"))}}) - if "PERMDIFF" in text: - answer = ask("session/request_permission", { - "sessionId": session, - "toolCall": {"toolCallId": "diff-" + str(msg["id"]), "title": "edit sample.py", "kind": "edit", "status": "pending", - "rawInput": {}, "content": [{"type": "diff", "path": "sample.py", "oldText": "one\ntwo", "newText": "one\nTWO"}]}, - "options": [{"optionId": "once", "name": "Allow once", "kind": "allow_once"}, - {"optionId": "deny", "name": "Deny", "kind": "reject_once"}]}) - got = (answer or {}).get("outcome", {}) - update(session, {"sessionUpdate": "agent_message_chunk", - "content": {"type": "text", "text": "\nanswer=" + str(got.get("optionId") or got.get("outcome"))}}) - if "READ " in text: - path = text.split("READ ", 1)[1].split()[0] - answer = ask("fs/read_text_file", {"sessionId": session, "path": path}) - update(session, {"sessionUpdate": "agent_message_chunk", - "content": {"type": "text", "text": "\nread=" + json.dumps((answer or {}).get("content"))}}) - if "PUT " in text: - path = text.split("PUT ", 1)[1].split()[0] - with lock: - next_id[0] += 1 - rid = next_id[0] - done = threading.Event() - waiting[rid] = [done, "error"] - out({"jsonrpc": "2.0", "id": rid, "method": "fs/write_text_file", - "params": {"sessionId": session, "path": path, "content": "written by the agent\nsecond\n"}}) - done.wait(10) - got = waiting.pop(rid)[1] - update(session, {"sessionUpdate": "agent_message_chunk", - "content": {"type": "text", "text": "\nput=" + ("error" if got == "error" else "ok")}}) - if "SHOW " in text: - path = text.split("SHOW ", 1)[1].split()[0] - kind = "image" if path.endswith(".png") else "code" - answer = ask("_lembas/show", {"sessionId": session, "toolCallId": "show-" + str(msg["id"]), "path": os.path.basename(path), - "uri": "file://" + path, "kind": kind, "line": 2}) - update(session, {"sessionUpdate": "agent_message_chunk", - "content": {"type": "text", "text": "\nshown=" + json.dumps(answer)}}) - if "WRITE " in text: - path = text.split("WRITE ", 1)[1].split()[0] - update(session, {"sessionUpdate": "tool_call", "toolCallId": "c1", "title": "edit " + os.path.basename(path), - "kind": "edit", "status": "in_progress"}) - with open(path, "w") as f: - f.write("rewritten by the agent\n") - update(session, {"sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "completed"}) - if "QUESTION" in text: - answer = ask("_lembas/question", { - "sessionId": session, - "toolCallId": "q-" + str(msg["id"]), - "why": "Pick a backend", - "questions": [{"header": "DB", "question": "Which DB?", "options": [{"label": "SQLite"}, {"label": "Postgres"}]}], - }) - update(session, {"sessionUpdate": "agent_message_chunk", - "content": {"type": "text", "text": "\nquestion=" + json.dumps(answer, sort_keys=True)}}) - if "PLANCARD" in text: - answer = ask("_lembas/plan", { - "sessionId": session, - "toolCallId": "p-" + str(msg["id"]), - "text": "# Plan\n- step 1", - "plan": {"title": "Upgrade"}, - }) - update(session, {"sessionUpdate": "agent_message_chunk", - "content": {"type": "text", "text": "\nplan=" + json.dumps(answer, sort_keys=True)}}) - if "CRASH" in text: - sys.stderr.write("not signed in: run lembas login\n") - sys.stderr.flush() - os._exit(3) - stop = "end_turn" - if "SLOW" in text: - stop = "cancelled" if cancelled.wait(10) else "end_turn" - cancelled.clear() - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"stopReason": stop}}) - - -def main(): - for line in sys.stdin: - if not line.strip(): - continue - msg = json.loads(line) - if LOG: - with open(LOG, "a") as f: - f.write(json.dumps(msg) + "\n") - method = msg.get("method") - if method is None: - entry = waiting.get(msg.get("id")) - if entry: - if "error" not in msg: - entry[1] = msg.get("result") - entry[0].set() - elif method == "initialize": - result = {"protocolVersion": 1, "agentCapabilities": {}} - if EDITOR: - result["_meta"] = {"lembas": {"capabilities": ["editor", "media", "files", "commands", "steer", "sessions", "ask", "plan", "compact"]}} - out({"jsonrpc": "2.0", "id": msg["id"], "result": result}) - elif method == "_lembas/complete": - threading.Thread(target=complete, args=(msg,), daemon=True).start() - elif method == "_lembas/complete/cancel": - gone.add(msg["params"]["id"]) - elif method == "_lembas/complete/warm": - pass - elif method == "_lembas/files/search": - q = str((msg.get("params") or {}).get("query") or "").lower() - sample = [{"path": "sample.py", "kind": "file"}, {"path": "other.py", "kind": "file"}, {"path": "sub", "kind": "dir"}] - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"root": os.getcwd(), "files": [f for f in sample if not q or q in f["path"].lower()]}}) - elif method == "_lembas/commands": - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"commands": [{"name": "review", "description": "Review changes", "_meta": {"lembas": {"kind": "builtin"}}}]}}) - elif method == "_lembas/session/compact": - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"summary": "Compacted 1 turn."}}) - elif method == "_lembas/steer": - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"queued": 1}}) - elif method == "_lembas/sessions/list": - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"sessions": [{"id": "ses_prev", "title": "Previous run", "model": "example/model-a"}]}}) - elif method == "_lembas/sessions/resume": - out({"jsonrpc": "2.0", "id": msg["id"], "result": { - "sessionId": "ses_prev", - "title": "Previous run", - "modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]}, - "turns": [ - {"role": "user", "text": "old prompt"}, - {"role": "assistant", "text": "old reply", "reasoning": "", "tools": [{"id": "h1", "name": "read", "args": "{}", "output": "file text"}]}, - ], - "_meta": {"lembas": {"model": "example/model-a", "mode": "edit"}}, - }}) - elif method == "_lembas/edit": - p = msg["params"] - if "REFUSE" in p["instruction"]: - out({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32602, "message": "no model to rewrite with"}}) - continue - out({"jsonrpc": "2.0", "method": "_lembas/edit/delta", "params": {"id": p.get("id"), "delta": "abc"}}) - lines = p["text"].split("\n") - if "SAME" in p["instruction"]: - new = lines - else: - # The first line rewritten, a line added after the second, the rest as it was. - new = [lines[0].upper()] + lines[1:2] + [" # added by the rewrite"] + lines[2:] - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"text": "\n".join(new), "model": "example/model-a"}}) - elif method == "_lembas/models": - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"models": [ - {"id": "example/model-a", "name": "Model A", "for": ["main", "autocomplete"]}, - {"id": "example/model-b", "name": "Model B", "for": ["main"]}], - "autocomplete": SETTINGS["autocomplete"], "main": SETTINGS["main"]}}) - elif method == "_lembas/editor/settings": - for key, value in (msg["params"].get("set") or {}).items(): - which = "autocomplete" if key == "autocomplete_model" else "main" - SETTINGS[which] = {"model": value, "source": "person" if value else None} - out({"jsonrpc": "2.0", "id": msg["id"], "result": SETTINGS}) - elif method == "session/new": - out({"jsonrpc": "2.0", "id": msg["id"], "result": { - "sessionId": "ses_test", - "modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]}, - "_meta": {"lembas": {"model": "example/model-a", "mode": "ask"}}}}) - elif method == "session/prompt": - threading.Thread(target=prompt, args=(msg,), daemon=True).start() - elif method == "session/cancel": - cancelled.set() - elif method == "session/set_mode": - out({"jsonrpc": "2.0", "id": msg["id"], "result": {}}) - elif method == "_lembas/configure": - out({"jsonrpc": "2.0", "id": msg["id"], "result": {"model": msg["params"].get("model"), "effort": "default"}}) - elif "id" in msg: - out({"jsonrpc": "2.0", "id": msg["id"], "error": {"code": -32601, "message": "Method not found"}}) - - -main() diff --git a/nvim/tests/run.lua b/nvim/tests/run.lua index da7e0dd..2e1ff93 100644 --- a/nvim/tests/run.lua +++ b/nvim/tests/run.lua @@ -1,15 +1,24 @@ --- The plugin's tests, against tests/fake_agent.py. Run by scripts/test-nvim.sh: +-- The plugin's tests, against tests/fake_agent.py (the stand-in both editors share: it answers in +-- the LLeMbas CLI's own shapes) and, where its source is at hand, against the CLI itself. +-- Run by scripts/test-nvim.sh: -- nvim --headless -u NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua -local here = debug.getinfo(1, "S").source:sub(2):match("(.*/)") -local tmp = vim.fn.tempname() +local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h") +local repo = vim.fs.normalize(here .. "/../..") +vim.opt.rtp:append(repo .. "/nvim") +local fake = repo .. "/tests/fake_agent.py" +local tmp = vim.uv.fs_realpath(vim.fn.tempname():match("(.*)/[^/]*$")) .. "/llembas-nvim-test-" .. vim.uv.os_getpid() vim.fn.mkdir(tmp, "p") local log = tmp .. "/agent.log" vim.env.FAKE_AGENT_LOG = log +vim.env.PYTHONDONTWRITEBYTECODE = "1" +-- The agent works in the folder the editor is in. +vim.cmd("cd " .. vim.fn.fnameescape(tmp)) vim.cmd("runtime plugin/llembas.lua") local L = require("llembas") local chat = require("llembas.chat") -L.setup({ cmd = { "python3", here .. "fake_agent.py" }, width = 50 }) +local rpc = require("llembas.rpc") +L.setup({ cmd = { "python3", fake }, width = 50 }) local failed, ran = 0, 0 local function check(name, cond, extra) @@ -19,7 +28,7 @@ local function check(name, cond, extra) print("FAIL " .. name .. (extra and ("\n " .. tostring(extra)) or "")) end end -local function wait(cond) return vim.wait(8000, cond, 20) end +local function wait(cond, ms) return vim.wait(ms or 8000, cond, 20) end local function idle() return wait(function() return not L._state.busy end) end local function sent() local out = {} @@ -28,18 +37,33 @@ local function sent() end return out end -local function last_prompt() - local all = sent() - for i = #all, 1, -1 do if all[i].method == "session/prompt" then return all[i].params.prompt end end +local function calls(method) + local out = {} + for _, m in ipairs(sent()) do if m.method == method then out[#out + 1] = m.params end end + return out end +local function last_call(method) local c = calls(method); return c[#c] end +local function last_prompt() local p = last_call("session/prompt"); return p and p.prompt end local function type_and_send(text) vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, vim.split(text, "\n")) vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("", true, false, true), "x", false) end +local function has(text) return chat.text():find(text, 1, true) ~= nil end +local function alive(pid) return pid and vim.uv.kill(pid, 0) == 0 end +local said_msgs = {} +local notify = vim.notify +vim.notify = function(m) said_msgs[#said_msgs + 1] = tostring(m) end +local function was_said(text) return table.concat(said_msgs, "|"):find(text, 1, true) ~= nil end +local pids = {} +local function note_pid() if L._state.conn then pids[L._state.conn.proc.pid] = true end end -local version = vim.trim(table.concat(vim.fn.readfile(here .. "../../VERSION"), "")) +local version = vim.trim(table.concat(vim.fn.readfile(repo .. "/VERSION"), "")) check("version: the plugin says the repository's version", L.version == version, L.version .. " / " .. version) +check("version: numbers are compared as numbers, and a release is newer than its betas", + L.compare_versions("2.0.0-beta.10", "2.0.0-beta.9") == 1 and L.compare_versions("2.0.0-beta.9", "2.0.0-beta.16") == -1 + and L.compare_versions("2.0.0", "2.0.0-beta.99") == 1 and L.compare_versions("2.0.0-beta.17+abc", "2.0.0-beta.17") == 0 + and L.compare_versions("1.9.9", "2.0.0-beta.1") == -1 and L.compare_versions("nonsense", "1.0.0") == nil) -- A file to work in. local file = tmp .. "/sample.py" @@ -47,42 +71,49 @@ vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, vim.cmd("edit " .. vim.fn.fnameescape(file)) local fbuf = vim.api.nvim_get_current_buf() --- 1. The panel opens beside the file and a typed prompt is answered. +-- ── An older CLI (before the editor's methods): said once, and the plain paths still work. ────────── +vim.env.FAKE_AGENT_VERSION = "2.0.0-beta.9" vim.cmd("LLeMbas") check("panel: two windows are added and the prompt has the focus", #vim.api.nvim_tabpage_list_wins(0) == 3 and vim.api.nvim_get_current_buf() == chat.ibuf) type_and_send("hello") check("prompt: the turn ends", idle()) +note_pid() local text = chat.text() check("prompt: what was typed and the answer are in the transcript, in order", text:find("## You\n\nhello\n\n## LLeMbas\n\nHello there.\nSecond line", 1, true) ~= nil, text) -check("prompt: thinking is not shown by default", not text:find("hidden thought", 1, true)) +check("old CLI: said once, with both versions and how to update", + select(2, text:gsub("LLeMbas CLI 2%.0%.0%-beta%.9 is older than this needs %(" .. vim.pesc(L.MIN_CLI) .. " or newer%)", "")) == 1 + and has("lembas update"), text) +check("prompt: thinking is not shown by default", not has("hidden thought")) check("prompt: the prompt buffer is emptied", table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), "") == "") local p = last_prompt() -check("prompt: the open file is named, its text is not sent", +check("old CLI: the open file is named in a sentence, its text is not sent", #p == 2 and p[1].text:find("sample.py", 1, true) and p[1].text:find("cursor on line 1", 1, true) and p[2].text == "hello", vim.inspect(p)) -local init -for _, m in ipairs(sent()) do if m.method == "initialize" then init = m end end -local lm = init and (init.params.clientCapabilities._meta or {}).lembas or {} -check("start: ACP version 1, and the client says it is an editor that shows files and serves and takes text", - init and init.params.protocolVersion == 1 and lm.editor == true and lm.media == true - and init.params.clientCapabilities.fs.readTextFile == true and init.params.clientCapabilities.fs.writeTextFile == true) -check("start: the transcript cannot be typed in and reads no modeline", - vim.bo[chat.tbuf].modifiable == false and vim.bo[chat.tbuf].modeline == false and vim.bo[chat.ibuf].modeline == false) +local init = last_call("initialize") +local lm = init and (init.clientCapabilities._meta or {}).lembas or {} +check("start: ACP version 1, protocol 3, and the client says it is an editor that shows files and serves and takes text", + init and init.protocolVersion == 1 and lm.protocol == 3 and lm.editor == true and lm.media == true and lm.show == true + and init.clientCapabilities.fs.readTextFile == true and init.clientCapabilities.fs.writeTextFile == true, vim.inspect(init)) +check("start: the client names itself and its version", init.clientInfo.name == "llembas-nvim" and init.clientInfo.version == version) +check("start: the session is opened in the editor's folder", last_call("session/new").cwd == tmp, vim.inspect(last_call("session/new"))) +check("start: the transcript cannot be typed in, keeps no undo history and reads no modeline", + vim.bo[chat.tbuf].modifiable == false and vim.bo[chat.tbuf].modeline == false and vim.bo[chat.ibuf].modeline == false + and vim.bo[chat.tbuf].undolevels == -1 and #vim.fn.undotree(chat.tbuf).entries == 0) --- 2. A selection with a question goes at once, with the unsaved text and the place. +-- A selection with a question goes at once, with the unsaved text and the place. vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf)) vim.api.nvim_buf_set_lines(fbuf, 1, 2, false, { " return 10 # unsaved" }) vim.cmd("1,2LLeMbasAsk what does this return?") check("ask: the turn ends", idle()) p = last_prompt() -check("ask: place, text as the buffer has it, then the question", +check("old CLI: place, text as the buffer has it, then the question", #p == 3 and p[1].text:find("lines 1-2", 1, true) and p[1].text:find("not saved yet", 1, true) and p[2].type == "resource" and p[2].resource.text == "def a():\n return 10 # unsaved" and p[2].resource.uri:find("#L1-2", 1, true) and p[3].text == "what does this return?", vim.inspect(p)) check("ask: the focus stays in the file", vim.api.nvim_get_current_buf() == fbuf) --- 3. A selection without a question waits for the next typed message, once. +-- A selection without a question waits for the next typed message, once. vim.cmd("4,5LLeMbasAsk") check("attach: the prompt has the focus and says what it carries", vim.api.nvim_get_current_buf() == chat.ibuf and vim.wo[vim.fn.bufwinid(chat.ibuf)].winbar:find("sample.py:4-5", 1, true) ~= nil) @@ -95,7 +126,7 @@ idle() p = last_prompt() check("attach: the next message carries them no more", #p == 2 and p[2].text == "again", vim.inspect(p)) --- 4. An approval is put to the person; the answer goes back. +-- An approval is put to the person; the answer goes back. local asked local function option(items, id) for _, o in ipairs(items) do if o.optionId == id then return o end end end vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(option(items, "once")) end @@ -103,111 +134,216 @@ type_and_send("PERM") idle() check("approval: asked with the command and the reason", asked and asked.opts.prompt:find("rm -r build", 1, true) and asked.opts.prompt:find("deletes files", 1, true) - and asked.opts.format_item(asked.items[1]) == "Deny") -check("approval: the first choice is a denial, so a stray 1 and Enter allows nothing", asked.items[1].optionId == "deny") -check("approval: the choice reaches the agent", chat.text():find("answer=once", 1, true) ~= nil, chat.text()) + and asked.opts.format_item(asked.items[1]) == "Deny", vim.inspect(asked)) +check("approval: the first choice is a denial, so a stray 1 and Enter allows nothing", + asked.items[1].optionId == "deny" and #asked.items == 3) +check("approval: the choice reaches the agent", has("answer=once"), chat.text()) vim.ui.select = function(_, _, cb) cb(nil) end type_and_send("PERM") idle() -check("approval: closing the question is a denial", chat.text():find("answer=cancelled", 1, true) ~= nil) -check("approval: each card is one line, rewritten with its answer", - not chat.text():find("waits for your answer", 1, true) and select(2, chat.text():gsub("rm %-r build", "")) == 2, chat.text()) +check("approval: closing the question is a denial", has("answer=deny") and has("(not answered: denied)"), chat.text()) +check("approval: a card is one line, rewritten with its answer", not has("waits for your answer"), chat.text()) +check("approval: the call that was refused is shown as refused, not as failed", has("⊘ [execute] rm -r build (not allowed)"), chat.text()) --- 5. A rewrite: refused on unsaved text, then done by the agent, and the buffer takes the new text. +-- A rewrite with an older CLI: refused on unsaved text, then done by the agent, and the buffer takes the new text. vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf)) local before = #sent() vim.cmd("1,2LLeMbasEdit make it shorter") -check("rewrite: nothing is sent while the buffer is unsaved", #sent() == before and not L._state.busy) +check("old CLI: no rewrite is asked for while the buffer is unsaved", #sent() == before and not L._state.busy) vim.cmd("silent write") vim.o.autoread = true vim.cmd("1,2LLeMbasEdit WRITE " .. file) idle() -check("rewrite: the buffer shows what the agent wrote", +check("old CLI: the buffer shows what the agent wrote on the disk", wait(function() return vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "rewritten by the agent" end), vim.inspect(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false))) -check("rewrite: the tool call is one line, marked done", select(2, chat.text():gsub("%- ✓ edit sample%.py", "")) == 1 - and not chat.text():find("… edit sample.py", 1, true), chat.text()) +check("tool: the call is one line, marked done, with how long it took", + select(2, chat.text():gsub("%- ✓ %[edit%] write sample%.py · 42ms", "")) == 1 and not has("◐ [edit] write sample.py"), chat.text()) --- 6. A second message while one runs is refused; stop ends the turn. +-- A message while one runs is steered into it; stop ends the turn. vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) type_and_send("SLOW") wait(function() local q = last_prompt(); return q and q[#q].text == "SLOW" end) -before = #sent() -type_and_send("too early") -check("busy: a second message is not sent and stays in the prompt", - #sent() == before and vim.api.nvim_buf_get_lines(chat.ibuf, 0, 1, false)[1] == "too early") +check("busy: the header says what the agent is doing", wait(function() return vim.wo[vim.fn.bufwinid(chat.tbuf)].winbar:find("◐", 1, true) ~= nil end)) +type_and_send("one more thing") +check("busy: a message typed meanwhile is given to the running turn", + wait(function() local s = last_call("_lembas/steer"); return s and s.text == "one more thing" and s.sessionId == L._state.session end) + and has("## You (while working)\n\none more thing"), chat.text()) vim.cmd("LLeMbasStop") -check("stop: the turn ends as cancelled", idle() and chat.text():find("The turn ended: cancelled", 1, true) ~= nil) -vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {}) +check("stop: the turn ends as stopped", idle() and has("> Stopped."), chat.text()) +check("stop: the cancel names the session", last_call("session/cancel").sessionId == "ses_test") --- 7. Mode and model. +-- Mode and model. +check("mode: the CLI's own modes are offered", vim.deep_equal(L.mode_ids(), { "manual", "edit", "auto", "plan" }), vim.inspect(L.mode_ids())) vim.cmd("LLeMbasMode edit") -check("mode: set and shown", wait(function() return L._state.mode == "edit" end)) +check("mode: set and shown", wait(function() return L._state.mode == "edit" end) + and wait(function() return vim.wo[vim.fn.bufwinid(chat.ibuf)].winbar:find("mode edit", 1, true) ~= nil end)) +said_msgs = {} +vim.cmd("LLeMbasMode nonsense") +check("mode: one the CLI does not know is said in its words", wait(function() return was_said("unknown mode nonsense") end) and L._state.mode == "edit") vim.cmd("LLeMbasModel example/model-b") check("model: set and shown", wait(function() return L._state.model == "example/model-b" end) and vim.wo[vim.fn.bufwinid(chat.ibuf)].winbar:find("example/model-b", 1, true) ~= nil) --- 8. The agent dying is said, with its last words, and the next message starts it again. +-- The agent dying is said, with its last words, and the next message starts it again. +local pid = L._state.conn.proc.pid type_and_send("CRASH") -check("crash: the turn is over and the reason is in the transcript", - wait(function() return not L._state.busy and chat.text():find("run lembas login", 1, true) ~= nil end), chat.text()) +check("crash: the turn is over and the reason is in the transcript, once", + wait(function() return not L._state.busy and has("The agent stopped (exit 3): error: the session store could not be opened") end) + and select(2, chat.text():gsub("The agent stopped", "")) == 1 and not has("The turn failed"), chat.text()) +check("crash: nothing of the old agent is kept", L._state.conn == nil and L._state.session == nil and next(L._state.caps) == nil) +vim.cmd("LLeMbasLog") +local logwin = vim.api.nvim_get_current_win() +check("crash: :LLeMbasLog shows what it wrote on stderr", + table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n"):find("the session store could not be opened", 1, true) ~= nil) +pcall(vim.api.nvim_win_close, logwin, true) type_and_send("back") -check("crash: the next message gets an answer from a new agent", idle() and chat.text():match("back\n\n## LLeMbas") ~= nil) +check("crash: the next message gets an answer from a new agent", idle() and chat.text():match("back\n\n## LLeMbas") ~= nil, chat.text()) +note_pid() +check("crash: the new agent is another process", L._state.conn.proc.pid ~= pid and not alive(pid)) --- 8b. An agent that offers the editor's methods (spec 3.11.0). -vim.env.FAKE_EDITOR = "1" +-- ── The CLI as it is now (2.0.0-beta.17, harness spec 3.11.0). ─────────────────────────────────────── +vim.env.FAKE_AGENT_VERSION = nil +pid = L._state.conn.proc.pid vim.cmd("LLeMbasNew") +check("new: the agent of the old session is ended, not left running", wait(function() return not alive(pid) end)) vim.fn.delete(log) -local function calls(method) - local out = {} - for _, m in ipairs(sent()) do if m.method == method then out[#out + 1] = m.params end end - return out -end vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, file) vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf)) vim.cmd("edit!") -- Context as data, not as a sentence. vim.api.nvim_win_set_cursor(0, { 4, 0 }) -type_and_send("hello editor") +type_and_send("hello editor TOOL TEAM NOTICE PLAN") idle() -local all = sent() -local pr -for i = #all, 1, -1 do if all[i].method == "session/prompt" then pr = all[i].params break end end +note_pid() +local pr = last_call("session/prompt") check("editor: a typed message carries the file and the cursor as data and no sentence", pr and #pr.prompt == 1 and pr._meta.lembas.editor.path == file and pr._meta.lembas.editor.cursor.line == 4, vim.inspect(pr)) +check("new CLI: nothing is said about its version", not has("is older than")) +local bar = vim.wo[vim.fn.bufwinid(chat.tbuf)].winbar +check("events: the session's own usage is shown, a subagent's is not added to it", bar:find("↑1.2k ↓34", 1, true) ~= nil, bar) +check("events: the subagents at work are counted", bar:find("1 subagent", 1, true) ~= nil, bar) +check("events: a notice of the agent's is in the transcript", has("> the server is slow to answer; trying again")) +check("events: the plan is drawn with its tasks", has("Upgrade: ") and has("1 of 3 tasks done — Step 2") and has("▸ Step 2"), chat.text()) +check("events: a tool call has its kind, its title and its time", has("- ✓ grep waybread · 42ms") or has("- ✓ [search] grep waybread · 42ms"), chat.text()) +check("progress: a phase is said with what it is about", + L._progress_text({ phase = "running_tool", since = 1, tool = "grep", what = "grep waybread" }) == "running tool: grep waybread" + and L._progress_text({ phase = "waiting_for_model", model = "example/model-a" }) == "waiting for model: example/model-a" + and L._progress_text({ phase = "failed", reason = "the server answered 502" }) == "failed: the server answered 502" + and L._progress_text({ phase = "retrying", reason = "overloaded", ["in"] = 5 }) == "retrying: overloaded, again in 5 s" + and L._progress_text({ phase = "thinking" }) == "thinking" and L._progress_text(nil) == nil) +type_and_send("DENIED") +idle() +check("events: a refused call is one line that says so", has("- ⊘ [execute] rm -rf / (not allowed)"), chat.text()) + +-- A turn that fails says why, once. +type_and_send("FAIL") +check("failed turn: the reason is in the transcript and the turn is over", + idle() and has("> The turn failed: The LLeMbas server cannot be reached: the server answered 502: the model is not loaded") + or has("> The turn failed: the server answered 502: the model is not loaded"), chat.text()) +check("failed turn: said once, though the event and the answer both carry it", + select(2, chat.text():gsub("The turn failed", "")) == 1, chat.text()) +type_and_send("FAILFIELD") +check("failed turn: an answer that carries the error alone is shown too", + idle() and select(2, chat.text():gsub("The turn failed", "")) == 2 + and has("The LLeMbas server cannot be reached: the server answered 502"), chat.text()) + vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf)) vim.cmd("4,5LLeMbasAsk what is b?") idle() -all = sent() -for i = #all, 1, -1 do if all[i].method == "session/prompt" then pr = all[i].params break end end +pr = last_call("session/prompt") local sel = pr._meta.lembas.editor.selection check("editor: a selection goes as data with its lines and text", #pr.prompt == 1 and sel.start == 4 and sel["end"] == 5 and sel.text == "def b():\n return 2", vim.inspect(pr)) --- Unsaved text is what the agent reads. +-- Unsaved text is what the agent reads, as it would be saved. vim.api.nvim_buf_set_lines(fbuf, 2, 3, false, { "# not saved" }) vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) type_and_send("READ " .. file) idle() -check("unsaved: the agent's read of an open file gets the buffer's text", - chat.text():find('read="def a():\\n return 1\\n# not saved\\ndef b():\\n return 2"', 1, true) ~= nil, chat.text()) +check("unsaved: the agent's read of an open file gets the buffer's text, with its last line break", + has('read="def a():\\n return 1\\n# not saved\\ndef b():\\n return 2\\n"'), chat.text()) type_and_send("READ " .. tmp .. "/none.txt") idle() -check("unsaved: a file that cannot be read is an error, not a crash", chat.text():find("read=null", 1, true) ~= nil) +check("unsaved: a file that cannot be read is an error, not a crash", has("read=null") and has("✗ read none.txt"), chat.text()) +local short = tmp .. "/sample" +vim.fn.writefile({ "the short one" }, short) +type_and_send("READ " .. short) +idle() +check("unsaved: a file is found by its whole name, not by a part of another's — and one not open comes from the disk, byte for byte", + has('read="the short one\\n"'), chat.text()) +local crlf = tmp .. "/dos.txt" +local cf = io.open(crlf, "wb"); cf:write("one\r\ntwo\r\n"); cf:close() +vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf)) +vim.cmd("edit ++ff=dos " .. vim.fn.fnameescape(crlf)) +local dbuf = vim.api.nvim_get_current_buf() +type_and_send("READ " .. crlf) +idle() +check("unsaved: a file with DOS line ends is given with them", vim.bo[dbuf].fileformat == "dos" and has('read="one\\r\\ntwo\\r\\n"'), chat.text()) +vim.api.nvim_win_set_buf(vim.fn.bufwinid(dbuf), fbuf) +local binary = tmp .. "/blob.bin" +local bf = io.open(binary, "wb"); bf:write("a\0b\255"); bf:close() +type_and_send("READ " .. binary) +idle() +check("unsaved: a file that is not text is left to the agent", wait(function() + for _, m in ipairs(sent()) do if m.error and tostring(m.error.message):find("not a text file", 1, true) then return true end end +end)) + +-- The agent's writes: into the open buffer and onto the disk together; a file that is not open, onto the disk. +vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "old text, not saved" }) +type_and_send("PUT " .. file) +idle() +check("write: a file whose text changed in the editor since the agent read it is not written over", + has("put=refused") and vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "old text, not saved", chat.text()) +type_and_send("READ " .. file) +idle() +type_and_send("PUT " .. file) +idle() +check("write: the agent's text is in the buffer, on the disk, and the buffer is not left modified", + vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), { "put by the agent" }) + and vim.deep_equal(vim.fn.readfile(file), { "put by the agent" }) and not vim.bo[fbuf].modified and has("put=client"), chat.text()) +type_and_send("EDIT " .. file) +idle() +check("write: an edit right after it is not refused as 'changed since you last read it'", + has("edit=client") and vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "PUT BY THE AGENT", chat.text()) +vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "typed by the person since" }) +type_and_send("EDIT " .. file) +idle() +check("write: text the person changed since the agent read it is not written over", + has("edit=refused") and vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "typed by the person since", chat.text()) +check("write: … and the tool's line says why", (function() + local found = false + for _, d in pairs(chat.details) do if tostring(d):find("changed since you last read it", 1, true) then found = true end end + return found +end)()) +vim.api.nvim_buf_call(fbuf, function() vim.cmd("silent write") end) +local closed = tmp .. "/sub/not-open.txt" +vim.fn.mkdir(tmp .. "/sub", "p") +vim.fn.writefile({ "first line", "second line" }, closed) +type_and_send("READ " .. closed) +idle() +type_and_send("EDIT " .. closed) +idle() +check("write: a file the agent read here and that is not open can still be edited (the editor writes the disk)", + has("edit=client") and vim.deep_equal(vim.fn.readfile(closed), { "FIRST LINE", "second line" }), chat.text()) +type_and_send("PUT " .. tmp .. "/new/dir/made.txt") +idle() +check("write: a new file in a new folder is made", vim.deep_equal(vim.fn.readfile(tmp .. "/new/dir/made.txt"), { "put by the agent" }), chat.text()) +vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf)) +vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, file) +vim.cmd("edit!") -- A rewrite is shown, and nothing is written before it is accepted. -vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf)) -vim.api.nvim_buf_set_lines(fbuf, 2, 3, false, { "" }) local D = require("llembas.diff") local before_text = vim.api.nvim_buf_get_lines(fbuf, 0, -1, false) vim.cmd("1,2LLeMbasEdit make it louder") -check("rewrite: two changes are shown on unsaved text", wait(function() return D.pending(fbuf) == 2 end), tostring(D.pending(fbuf))) +check("rewrite: two changes are shown", wait(function() return D.pending(fbuf) == 2 end), tostring(D.pending(fbuf))) check("rewrite: the buffer is as it was", vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), before_text)) -local e = calls("_lembas/edit")[1] -check("rewrite: the request has the text, the lines around it, the instruction and an id", +local e = last_call("_lembas/edit") +check("rewrite: the request has the text, the lines around it, the instruction, the session and an id", e and e.text == "def a():\n return 1" and e.after:find("def b", 1, true) and e.before == "" and e.instruction == "make it louder" - and e.path == file and type(e.id) == "string", vim.inspect(e)) + and e.path == file and type(e.id) == "string" and e.sessionId == "ses_test" and e.model == nil, vim.inspect(e)) vim.api.nvim_win_set_cursor(0, { 1, 0 }) vim.cmd("LLeMbasAccept") check("rewrite: accepting one change makes that one and leaves the other shown", @@ -224,14 +360,19 @@ check("rewrite: accepting all makes both, in the right places", D.pending(fbuf) == 0 and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), { "DEF A():", " return 1", "", "DEF B():", " return 2", " # added by the rewrite" }), vim.inspect(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false))) -local said_msgs = {} -local notify = vim.notify -vim.notify = function(m) said_msgs[#said_msgs + 1] = m end +said_msgs = {} vim.cmd("1,2LLeMbasEdit SAME") -check("rewrite: one that changes nothing says so", wait(function() return table.concat(said_msgs, "|"):find("changes nothing", 1, true) ~= nil end)) -vim.cmd("1,2LLeMbasEdit REFUSE") -check("rewrite: a refusal is said in the agent's words", wait(function() return table.concat(said_msgs, "|"):find("no model to rewrite with", 1, true) ~= nil end) +check("rewrite: one that changes nothing says so", wait(function() return was_said("changes nothing") end)) +vim.cmd("1,2LLeMbasEdit EMPTYE") +check("rewrite: a failure is said in the agent's words", wait(function() return was_said("the model answered with no text for this selection") end) and D.pending(fbuf) == 0) +vim.cmd("1,2LLeMbasEdit SLOWE") +wait(function() local c = last_call("_lembas/edit"); return c and c.instruction == "SLOWE" end) +local slow_id = last_call("_lembas/edit").id +vim.cmd("LLeMbasCancelEdit") +check("rewrite: cancelling names the request by the client's own id, and nothing is proposed", + wait(function() local c = last_call("_lembas/edit/cancel"); return c and c.id == slow_id end) and D.pending(fbuf) == 0) +vim.wait(150) -- A change whose lines you removed meanwhile takes nothing else with it. vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "def a():", " return 1", "keep me", "and me" }) @@ -252,28 +393,7 @@ vim.cmd("LLeMbasReject!") check("rewrite: a buffer mapping the proposal's keys replaced is given back", vim.fn.maparg("ga", "n", false, true).rhs == "let g:mine = 1", vim.inspect(vim.fn.maparg("ga", "n", false, true))) vim.keymap.del("n", "ga", { buffer = fbuf }) - --- The agent's read never takes a file for another whose name merely begins the same. -local short = tmp .. "/sample" -vim.fn.writefile({ "the short one" }, short) -vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) -type_and_send("READ " .. short) -idle() -check("unsaved: a file is found by its whole name, not by a part of another's", - chat.text():find('read="the short one"', 1, true) ~= nil, chat.text()) --- A write by the agent goes into the open buffer and onto the disk together. -vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "old text, not saved" }) -type_and_send("PUT " .. file) -idle() -check("write: the agent's text is in the buffer, on the disk, and the buffer is not left modified", - vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), { "written by the agent", "second" }) - and vim.deep_equal(vim.fn.readfile(file), { "written by the agent", "second" }) and not vim.bo[fbuf].modified - and chat.text():find("put=ok", 1, true) ~= nil, chat.text()) -type_and_send("PUT " .. tmp .. "/not-open.txt") -idle() -check("write: a file that is not open is left to the agent", chat.text():find("put=error", 1, true) ~= nil - and vim.fn.filereadable(tmp .. "/not-open.txt") == 0) -vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf)) +vim.cmd("silent write") -- An approval that carries a diff shows it while the question is open. local wins_during @@ -287,37 +407,66 @@ vim.ui.select = function(items, _, cb) end local wins_before = #vim.api.nvim_tabpage_list_wins(0) vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) -type_and_send("PERMDIFF") +type_and_send("DIFFPERM " .. file) idle() local joined = table.concat(wins_during or {}, "\n") check("approval: the diff is on the screen while the question is asked", - joined:find("--- sample.py", 1, true) and joined:find("-two", 1, true) and joined:find("+TWO", 1, true), joined) -check("approval: the diff's window is gone afterwards and the answer went back", - #vim.api.nvim_tabpage_list_wins(0) == wins_before and chat.text():find("answer=deny", 1, true) ~= nil) + joined:find("--- " .. file, 1, true) and joined:find("-keep me", 1, true) and joined:find("+rewritten by the agent", 1, true), joined) +check("approval: the diff's window is gone afterwards, the answer went back and nothing was written", + #vim.api.nvim_tabpage_list_wins(0) == wins_before and has("answer=deny") and vim.fn.readfile(file)[1] == " return 1") +vim.ui.select = function(items, _, cb) cb(option(items, "once")) end +type_and_send("DIFFPERM " .. file) +idle() +check("approval: allowed, the edit goes through the buffer", has("answer=once") + and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), { "rewritten by the agent" }) and not vim.bo[fbuf].modified, chat.text()) +-- A card the agent takes down is not answered afterwards. +local late +vim.ui.select = function(items, _, cb) late = function() cb(option(items, "once")) end end +type_and_send("SETTLE") +check("approval: a card that is no longer waited for says so", wait(function() return has("make build (answered elsewhere or expired)") end), chat.text()) +local n_before = #sent() +late() +vim.wait(100) +check("approval: … and choosing afterwards answers nothing and changes nothing", #sent() == n_before and has("make build (answered elsewhere or expired)")) +idle() -- Shown files. local png = tmp .. "/chart.png" -vim.fn.writefile({ "not really a picture" }, png) +local pf = io.open(png, "wb"); pf:write("\137PNG\r\n\26\n not really a picture \0"); pf:close() local opened vim.ui.open = function(pth) opened = pth end type_and_send("SHOW " .. png) idle() check("show: a file that is not text is named in the chat and answered as shown", - chat.text():find("chart.png (image)", 1, true) ~= nil and chat.text():find('shown={"shown": true}', 1, true) ~= nil, chat.text()) + has("chart.png (image)") and has('shown={"shown": true}'), chat.text()) vim.cmd("LLeMbasOpen") -check("show: :LLeMbasOpen hands it to the system's viewer", opened == png) +check("show: :LLeMbasOpen hands it to the system's viewer", opened == png, tostring(opened)) L._state.shown = tmp .. "/run.desktop" opened = nil vim.cmd("LLeMbasOpen") check("show: a file that may run is not handed to the system", opened == nil) local other = tmp .. "/other.py" vim.fn.writefile({ "x = 1", "y = 2", "z = 3" }, other) -type_and_send("SHOW " .. other) +type_and_send("SHOW " .. other .. " AT 2") idle() -check("show: a text file is opened in the window you edit in, at its line, and the prompt keeps the focus", - vim.api.nvim_buf_get_name(vim.api.nvim_win_get_buf(vim.fn.bufwinid(fbuf) ~= -1 and vim.fn.bufwinid(fbuf) or vim.fn.win_getid(1))) ~= "" - and vim.fn.bufwinid(vim.fn.bufnr(other)) ~= -1 and vim.api.nvim_win_get_cursor(vim.fn.bufwinid(vim.fn.bufnr(other)))[1] == 2 - and vim.api.nvim_get_current_buf() == chat.ibuf) +check("show: a text file that is here as it was sent is opened itself, at its line, and the prompt keeps the focus", + vim.fn.bufwinid(vim.fn.bufnr(other)) ~= -1 and vim.api.nvim_win_get_cursor(vim.fn.bufwinid(vim.fn.bufnr(other)))[1] == 2 + and vim.api.nvim_get_current_buf() == chat.ibuf and has("- shown: other.py"), chat.text()) +local outside = vim.fn.fnamemodify(tmp, ":h") .. "/llembas-outside-" .. vim.uv.os_getpid() .. ".md" +vim.fn.writefile({ "# Notes", "", "vim: set modeline shell=/bin/false :" }, outside) +type_and_send("SHOW " .. outside) +idle() +local shown_buf +for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do + local b = vim.api.nvim_win_get_buf(w) + if vim.api.nvim_buf_get_name(b):find("llembas://shown/", 1, true) then shown_buf = b end +end +check("show: text that is not a file here is shown as it was sent, in a buffer that cannot be written and runs nothing", + shown_buf and vim.bo[shown_buf].buftype == "nofile" and vim.bo[shown_buf].modifiable == false and vim.bo[shown_buf].modeline == false + and vim.bo[shown_buf].filetype == "" and vim.api.nvim_buf_get_lines(shown_buf, 0, 1, false)[1] == "# Notes" + and has("(as the agent sent it)"), chat.text()) +vim.fn.delete(outside) +vim.api.nvim_win_set_buf(vim.fn.bufwinid(shown_buf), vim.fn.bufnr(other)) -- Suggestions. local C = require("llembas.complete") @@ -332,22 +481,22 @@ local function ghost(buf) end local obuf = vim.fn.bufnr(other) vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf)) -vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "abc = fo", "tail" }) +vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "abc = TWO", "tail" }) vim.bo[obuf].filetype = "python" C._typing = function() return true end vim.o.virtualedit = "onemore" -- so the cursor can stand after the last character, as it does while typing -vim.api.nvim_win_set_cursor(0, { 1, 8 }) +vim.api.nvim_win_set_cursor(0, { 1, 9 }) C.request(true) check("suggest: asked on the key, the text is drawn at the cursor and is not in the buffer", - wait(function() return ghost(obuf) ~= nil end) and ghost(obuf) == "< fo|\nta>" and vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1] == "abc = fo", + wait(function() return ghost(obuf) ~= nil end) and ghost(obuf) == "tail()\n second line" and vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1] == "abc = TWO", vim.inspect({ ghost(obuf) })) -local c = calls("_lembas/complete") -check("suggest: the request has what is before and after the cursor, the file and the language", - c[#c].prefix == "abc = fo" and c[#c].suffix == "\ntail" and c[#c].path == other and c[#c].language == "python" and type(c[#c].id) == "string", - vim.inspect(c[#c])) +local c = last_call("_lembas/complete") +check("suggest: the request has what is before and after the cursor, the file, the language and the folder", + c.prefix == "abc = TWO" and c.suffix == "\ntail" and c.path == other and c.language == "python" and type(c.id) == "string" + and c.cwd == tmp and c.sessionId == "ses_test", vim.inspect(c)) check("suggest: accepting puts it in and moves the cursor to its end", - C.accept() and vim.deep_equal(vim.api.nvim_buf_get_lines(obuf, 0, -1, false), { "abc = fo< fo|", "ta>", "tail" }) - and vim.deep_equal(vim.api.nvim_win_get_cursor(0), { 2, 3 }) and ghost(obuf) == nil, + C.accept() and vim.deep_equal(vim.api.nvim_buf_get_lines(obuf, 0, -1, false), { "abc = TWOtail()", " second line", "tail" }) + and vim.deep_equal(vim.api.nvim_win_get_cursor(0), { 2, 15 }) and ghost(obuf) == nil, vim.inspect(vim.api.nvim_buf_get_lines(obuf, 0, -1, false))) check("suggest: with nothing shown there is nothing to accept", C.accept() == false) vim.keymap.set("i", "", "let g:tab = 1", { buffer = obuf }) @@ -362,77 +511,172 @@ check("suggest: Tab is the plugin's only while a suggestion is shown, and yours during.desc == "LLeMbas: accept the suggestion" and after.rhs == "let g:tab = 1", vim.inspect({ during.desc, after.rhs })) vim.keymap.del("i", "", { buffer = obuf }) check("suggest: without a suggestion the plugin maps Tab nowhere", vim.fn.maparg("", "i") == "") +check("suggest: a long text is cut between characters, never inside one", + C._tail_bytes("aé€😀", 5) == "😀" and C._tail_bytes("aé€😀", 6) == "😀" and C._tail_bytes("aé€😀", 7) == "€😀" + and C._head_bytes("😀€éa", 5) == "😀" and C._head_bytes("😀€éa", 7) == "😀€" and C._head_bytes("abc", 9) == "abc") -- As you type: asked after the pause, and an answer for a place you have left is not drawn. L.config.complete.debounce_ms = 30 -vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "" }) -vim.api.nvim_win_set_cursor(0, { 1, 0 }) -local n0 = #calls("_lembas/complete") vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "xy" }) vim.api.nvim_win_set_cursor(0, { 1, 2 }) vim.cmd("doautocmd TextChangedI") -check("suggest: typing asks by itself after the pause", wait(function() return ghost(obuf) == "" end), vim.inspect({ ghost(obuf) })) +check("suggest: typing asks by itself after the pause", wait(function() return ghost(obuf) == "" end), vim.inspect({ ghost(obuf) })) vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "SLOWC" }) vim.api.nvim_win_set_cursor(0, { 1, 5 }) vim.cmd("doautocmd TextChangedI") -wait(function() local k = calls("_lembas/complete"); return k[#k] and k[#k].prefix == "SLOWC" end) +wait(function() local k = last_call("_lembas/complete"); return k and k.prefix == "SLOWC" end) +local slow_c = last_call("_lembas/complete").id vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "SLOWCz" }) vim.api.nvim_win_set_cursor(0, { 1, 6 }) vim.cmd("doautocmd TextChangedI") check("suggest: a newer keystroke cancels the request before it by its id", - wait(function() return #calls("_lembas/complete/cancel") >= 1 end)) -vim.wait(400) -local g = ghost(obuf) -check("suggest: only the answer for where the cursor is now is ever drawn", g == nil or g == "", tostring(g)) + wait(function() for _, k in ipairs(calls("_lembas/complete/cancel")) do if k.id == slow_c then return true end end end)) +vim.cmd("LLeMbasAutocomplete off") +vim.wait(300) +check("suggest: only the answer for where the cursor is now is ever drawn", ghost(obuf) == nil, tostring(ghost(obuf))) +vim.cmd("LLeMbasAutocomplete on") C.clear() --- A refusal is said once and the asking stops. +-- A failure that may pass is not said while you type, and typing asks again later. said_msgs = {} -vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "NOMODEL" }) +vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "FAILC" }) +vim.api.nvim_win_set_cursor(0, { 1, 5 }) +local n0 = #calls("_lembas/complete") +vim.cmd("doautocmd TextChangedI") +wait(function() return #calls("_lembas/complete") == n0 + 1 end) +vim.wait(150) +vim.cmd("doautocmd TextChangedI") +vim.wait(150) +check("suggest: a server failure is not a refusal — nothing is said, and asking pauses instead of stopping", + #said_msgs == 0 and #calls("_lembas/complete") == n0 + 1 and C.why() == "autocomplete failed on the server (502)", vim.inspect({ said_msgs, C.why() })) +C.request(true) +check("suggest: asked on the key, the failure is said", wait(function() return was_said("no suggestion: autocomplete failed on the server (502)") end), vim.inspect(said_msgs)) +C.reset() +-- A refusal that stays is said once, with what to do about it, and the asking stops. +said_msgs = {} +L.config.complete.model = "example/model-c" +vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "refused" }) vim.api.nvim_win_set_cursor(0, { 1, 7 }) vim.cmd("doautocmd TextChangedI") -check("suggest: no model chosen is said once", wait(function() return table.concat(said_msgs, "|"):find("no autocomplete model is chosen", 1, true) ~= nil end)) +check("suggest: a model not allowed for it is said once, with the way out", + wait(function() return was_said("no suggestions: Model C is not allowed") end) + and C.why() == "Model C is not allowed for autocomplete. (:LLeMbasAutocompleteModel chooses another)", vim.inspect({ said_msgs, C.why() })) n0 = #calls("_lembas/complete") vim.cmd("doautocmd TextChangedI") vim.wait(200) -check("suggest: and nothing more is asked until a model is chosen", #calls("_lembas/complete") == n0 and #said_msgs == 1) +check("suggest: and nothing more is asked until something is changed", #calls("_lembas/complete") == n0 and #said_msgs == 1) -- Choosing models. -vim.cmd("LLeMbasAutocompleteModel example/model-a") +vim.cmd("LLeMbasAutocompleteModel! -") +check("models: the quick switch is undone with -", L.config.complete.model == nil and C.why() == nil) +vim.cmd("LLeMbasAutocompleteModel example/model-b") check("models: the autocomplete model is saved through the agent", - wait(function() local k = calls("_lembas/editor/settings"); return k[#k] and k[#k].set and k[#k].set.autocomplete_model == "example/model-a" end)) + wait(function() local k = last_call("_lembas/editor/settings"); return k and k.set and k.set.autocomplete_model == "example/model-b" end)) vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end +asked = nil vim.cmd("LLeMbasAutocompleteModel") check("models: without a name the list offers only models allowed for it", - wait(function() return asked and asked.opts.prompt:find("autocomplete", 1, true) ~= nil end) and #asked.items == 1 and asked.items[1].id == "example/model-a") + wait(function() return asked and asked.opts.prompt:find("autocomplete", 1, true) ~= nil end) and #asked.items == 2 and asked.items[1].id == "example/model-a" + and wait(function() return last_call("_lembas/editor/settings").set.autocomplete_model == "example/model-a" end), vim.inspect(asked)) vim.cmd("LLeMbasAutocompleteModel! example/model-b") check("models: the quick switch is this editor's only", L.config.complete.model == "example/model-b" - and (function() local k = calls("_lembas/editor/settings"); return k[#k].set.autocomplete_model ~= "example/model-b" end)()) + and last_call("_lembas/editor/settings").set.autocomplete_model == "example/model-a") +L.config.complete.model = nil +said_msgs = {} +vim.cmd("LLeMbasMainModel example/model-nope") +check("models: a model the account does not have is refused in the server's words", + wait(function() return was_said("example/model-nope is not a model of this account.") end), vim.inspect(said_msgs)) vim.cmd("LLeMbasMainModel example/model-b") check("models: the main model is saved as its own entry", - wait(function() local k = calls("_lembas/editor/settings"); return k[#k].set and k[#k].set.main_model == "example/model-b" end)) --- Agentic IDE features: question card, plan card, file index attach & session resume. + wait(function() local k = last_call("_lembas/editor/settings"); return k.set and k.set.main_model == "example/model-b" end)) +vim.cmd("LLeMbasMainModel -") +check("models: - goes back to the server's own (null)", + wait(function() local k = last_call("_lembas/editor/settings"); return k.set and k.set.main_model == vim.NIL end)) + +-- Question card, plan card, the file index, commands, sessions. +local typed_answer = "waybread" +vim.ui.input = function(_, cb) cb(typed_answer) end vim.ui.select = function(items, opts, cb) - if opts.prompt:find("Which DB", 1, true) then return cb(items[1]) end + if opts.prompt:find("Which backend", 1, true) then + check("question: the recommended option is marked", opts.format_item(items[1]):find("SQLite ★", 1, true) ~= nil, opts.format_item(items[1])) + return cb(items[1]) + end if opts.prompt:find("LLeMbas plan", 1, true) then return cb(items[2]) end return cb(items[1]) end +vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) type_and_send("QUESTION") -check("question: interactive spec-compliant Answer reaches agent", - idle() and chat.text():find('"kind": "options"', 1, true) ~= nil and chat.text():find("SQLite", 1, true) ~= nil, chat.text()) +check("question: each answer reaches the agent in the shape it reads", + idle() and has('question={"answers": [{"kind": "options", "labels": ["SQLite"]}, {"kind": "custom", "text": "waybread"}]}'), chat.text()) +typed_answer = "" +type_and_send("QUESTION") +check("question: one left blank is skipped, and the others still count", + idle() and has('question={"answers": [{"kind": "options", "labels": ["SQLite"]}, null]}'), chat.text()) +local picks = 0 +vim.ui.select = function(items, opts, cb) + picks = picks + 1 + if opts.prompt:find("Which backend", 1, true) then + if picks <= 2 then return cb(items[picks]) end -- SQLite, then Postgres + for _, it in ipairs(items) do if it._done then return cb(it) end end + end + return cb(items[1]) +end +typed_answer = "oven" +type_and_send("QUESTION MULTI") +check("question: several options can be chosen where the question takes them", + idle() and has('{"kind": "options", "labels": ["SQLite", "Postgres"]}, {"kind": "custom", "text": "oven"}'), chat.text()) +vim.ui.select = function(_, _, cb) cb(nil) end +type_and_send("QUESTION") +check("question: closing it dismisses the card", idle() and has('question={"dismissed": true}'), chat.text()) +vim.ui.select = function(items, opts, cb) + if opts.prompt:find("LLeMbas plan", 1, true) then + check("plan: dismissing is the first choice", items[1].id == "dismiss") + return cb(items[3]) + end + return cb(items[1]) +end type_and_send("PLANCARD") -check("plan: interactive approval reaches agent", idle() and chat.text():find("approve", 1, true) ~= nil, chat.text()) -vim.cmd("LLeMbasFiles other") -check("files: attaches @path from real CLI {path, kind} entries", - wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@other.py", 1, true) ~= nil end)) +check("plan: the approval reaches the agent, and the session is in the mode approved", + idle() and has('plan={"kind": "approve", "mode": "manual"}') and L._state.mode == "manual" and has("## Plan: Upgrade"), chat.text()) +vim.ui.select = function(items, opts, cb) + for _, it in ipairs(items) do if it.id == "revise" then return cb(it) end end + cb(items[1]) +end +vim.ui.input = function(_, cb) cb("smaller steps") end +type_and_send("PLANCARD") +check("plan: a revision carries the feedback", idle() and has('plan={"feedback": "smaller steps", "kind": "revise"}'), chat.text()) +vim.ui.select = function(items, _, cb) cb(items[1]) end +vim.fn.writefile({ "x" }, tmp .. "/my notes#1.md") +asked = nil +vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end +vim.cmd("LLeMbasFiles notes") +check("files: a file's name is searched for in the agent's index and attached as @path, spaces and # escaped", + wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@my\\ notes\\#1.md", 1, true) ~= nil end), + vim.inspect(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false))) +check("files: the search names the session", (function() local f = last_call("_lembas/files/search"); return f.sessionId == "ses_test" and f.query == "notes" end)()) +vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {}) +vim.ui.input = function(_, cb) cb("sub") end +vim.cmd("LLeMbasFiles") +check("files: without a name it asks for one, and a folder is attached as a folder", + wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@sub/", 1, true) ~= nil end), + vim.inspect(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false))) vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {}) vim.cmd("LLeMbasCommands") -check("commands: picks and inserts /command into prompt", - wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("/review", 1, true) ~= nil end)) +check("commands: the session's own set is offered, and the choice is put into the prompt", + wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("/compact", 1, true) ~= nil end) + and asked.opts.format_item(asked.items[5]) == "[skill] /bake — a skill of the project", vim.inspect(asked and asked.items)) vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {}) -vim.cmd("LLeMbasSessions") -check("sessions: resumes previous session and replays real CLI historyTurns", - wait(function() return L._state.session == "ses_prev" and chat.text():find("old reply", 1, true) ~= nil end), chat.text()) +type_and_send("/compact") +check("commands: /compact typed in the prompt is the command, and its summary is said", + idle() and has("> Compacted: Compacted 2 turns.") or has("Context compacted: Compacted 2 turns."), chat.text()) vim.cmd("LLeMbasCompact") -check("compact: compacts session and prints summary note", - wait(function() return chat.text():find("Compacted 1 turn", 1, true) ~= nil end), chat.text()) +check("compact: the session is compacted and the summary is said", + wait(function() return has("Session compacted: Compacted 2 turns.") end), chat.text()) +L.config.show_thoughts = true +vim.cmd("LLeMbasSessions") +check("sessions: a previous session is resumed and its turns are drawn as they were", + wait(function() return L._state.session == "ses_prev" and has("earlier answer") end) + and has("## You\n\n[notes.md]\nearlier question") and has("## Thinking\n\nearlier thinking") and has("- ✓ read") and has("- ✗ bash") + and has("## Harness\n\n⏎ the job is done") and L._state.title == "Earlier work" and L._state.mode == "edit", chat.text()) +L.config.show_thoughts = false +check("sessions: the list was asked for this folder", last_call("_lembas/sessions/list").cwd == tmp) -- Autocomplete tokens preset, custom instructions & word-by-word acceptance. vim.cmd("LLeMbasAutocompleteTokens block") @@ -446,8 +690,7 @@ vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "def TWO" }) vim.api.nvim_win_set_cursor(0, { 1, 7 }) C.request(true) wait(function() return ghost(obuf) ~= nil end) -local c_last = calls("_lembas/complete") -local req = c_last[#c_last] +local req = last_call("_lembas/complete") check("autocomplete tuning: max_tokens and instructions context reach _lembas/complete", req and req.max_tokens == 256 and req.context and req.context[1].path == "llembas:autocomplete-instructions" and req.context[1].text:find("Keep it concise", 1, true) ~= nil, vim.inspect(req)) @@ -461,11 +704,10 @@ local d_ns = vim.api.nvim_create_namespace("test-diag") vim.diagnostic.set(d_ns, obuf, { { lnum = 0, col = 0, severity = vim.diagnostic.severity.ERROR, message = "broken syntax", source = "lint" } }) vim.cmd("LLeMbasFix") idle() -all = sent() -for i = #all, 1, -1 do if all[i].method == "session/prompt" then pr = all[i].params break end end +pr = last_call("session/prompt") check("fix: buffer diagnostics reach agent in _meta.lembas.editor.diagnostics", pr and pr._meta and pr._meta.lembas and pr._meta.lembas.editor and pr._meta.lembas.editor.diagnostics - and pr._meta.lembas.editor.diagnostics[1].message == "broken syntax", vim.inspect(pr)) + and pr._meta.lembas.editor.diagnostics[1].message == "broken syntax" and pr._meta.lembas.editor.diagnostics[1].severity == "error", vim.inspect(pr)) vim.diagnostic.reset(d_ns, obuf) -- :LLeMbasGenerate & statusline. @@ -477,15 +719,210 @@ check("generate: proposes inline diff hunks at cursor", wait(function() return D check("statusline: reports pending changes", L.statusline():find("change", 1, true) ~= nil, L.statusline()) vim.cmd("LLeMbasReject!") check("statusline: reports active session mode and model", L.statusline():find("edit", 1, true) ~= nil, L.statusline()) +vim.cmd("LLeMbasStatus") +local status_text = table.concat(vim.api.nvim_buf_get_lines(0, 0, -1, false), "\n") +check("status: says the CLI's version and the folder", status_text:find("LLeMbas CLI 2.0.0-beta.17", 1, true) ~= nil and status_text:find(tmp, 1, true) ~= nil, status_text) +pcall(vim.api.nvim_win_close, 0, true) -vim.notify = notify +-- ── The agent's life. ────────────────────────────────────────────────────────────────────────────── +vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) +pid = L._state.conn.proc.pid +vim.cmd("LLeMbasRestart") +check("restart: the agent is stopped and nothing of it is kept, and the transcript stays", + wait(function() return not alive(pid) end) and L._state.conn == nil and L._state.session == nil and has("The agent was stopped."), chat.text()) +type_and_send("after the restart") +check("restart: the next message starts a new one", idle() and has("after the restart\n\n## LLeMbas"), chat.text()) +note_pid() --- 9. A command that does not exist is said, not thrown. +-- An agent that ignores a polite stop is killed. +rpc.KILL_AFTER_MS = 200 +local stubborn = rpc.start({ "python3", "-c", "import signal,time,sys\nsignal.signal(signal.SIGTERM, signal.SIG_IGN)\nprint('up', file=sys.stderr, flush=True)\nwhile True: time.sleep(1)" }, {}) +wait(function() return stubborn:stderr():find("up", 1, true) ~= nil end) +local spid = stubborn.proc.pid +stubborn:stop() +check("stop: an agent that does not go when asked is killed, so none is left behind", wait(function() return not alive(spid) end, 3000)) +rpc.KILL_AFTER_MS = 5000 + +-- A request that is never answered ends in words, and an answer that comes late is dropped. +local quiet = rpc.start({ "python3", "-c", "import sys\nfor line in sys.stdin: pass" }, {}) +local got +quiet:request("initialize", {}, function(err) got = err end, 150) +check("timeout: a request nobody answers fails in words after its time", + wait(function() return got ~= nil end, 2000) and got.timeout == true and got.message:find("did not answer initialize within", 1, true) ~= nil, vim.inspect(got)) +quiet:stop() + +-- An agent that never answers the hello is not waited for for ever. +vim.env.FAKE_AGENT_HANG = "initialize" +L.START_TIMEOUT_MS = 300 +vim.cmd("LLeMbasNew") +pid = nil +type_and_send("anyone?") +wait(function() pid = L._state.conn and L._state.conn.proc.pid or pid; return has("did not answer within") end, 3000) +check("start: an agent that does not answer is given up on, said in words, and ended", + has("The LLeMbas CLI did not answer within 0 seconds.") and not L._state.busy and L._state.conn == nil and wait(function() return not alive(pid) end), + chat.text()) +vim.env.FAKE_AGENT_HANG = nil +L.START_TIMEOUT_MS = 10000 + +-- Not signed in: said with what to do, and after the sign-in the next message works. +vim.env.FAKE_AGENT_LOGIN = "none" +vim.cmd("LLeMbasNew") +type_and_send("hello?") +check("not signed in: the chat says to run lembas login, and is not left working", + wait(function() return has("The LLeMbas CLI is not signed in to a server. Run `lembas login ` in a terminal, then try again.") end) + and idle() and L._state.session == nil, chat.text()) +check("not signed in: said once, without a second sentence about the session", select(2, chat.text():gsub("not signed in", "")) == 1 and not has("No session")) +said_msgs = {} +vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf)) +vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "signed out" }) +vim.api.nvim_win_set_cursor(0, { 1, 10 }) +C.reset() +C.request(true) +check("not signed in: a suggestion asked for says the same, and nothing about choosing a model", + wait(function() return was_said("is not signed in to a server. Run `lembas login `") end) and not was_said("AutocompleteModel"), vim.inspect(said_msgs)) +said_msgs = {} +vim.cmd("LLeMbasEdit make it better") +check("not signed in: a rewrite says the same", wait(function() return was_said("is not signed in to a server. Run `lembas login `") end), vim.inspect(said_msgs)) +vim.cmd("LLeMbasMainModel") +check("not signed in: so does choosing a model", wait(function() return select(2, table.concat(said_msgs, "|"):gsub("is not signed in", "")) >= 2 end), vim.inspect(said_msgs)) +vim.ui.input = function(_, cb) cb("other") end +asked = nil +vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(nil) end +vim.cmd("LLeMbasFiles") +check("not signed in: the project's files can still be searched (no session is needed)", + wait(function() return asked and asked.items[1] and asked.items[1].path == "other.py" end) and last_call("_lembas/files/search").cwd == tmp, vim.inspect(asked)) +vim.env.FAKE_AGENT_LOGIN = nil +vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) +type_and_send("signed in now") +check("not signed in: after the sign-in the next message is answered", idle() and has("signed in now\n\n## LLeMbas\n\nHello there."), chat.text()) +note_pid() + +-- A command that does not exist is said, not thrown, and says what to do. L.setup({ cmd = { "llembas-no-such-command" } }) vim.cmd("LLeMbasNew") type_and_send("anyone?") -check("missing: said in the transcript", wait(function() return chat.text():find("Could not start", 1, true) ~= nil end) and not L._state.busy, chat.text()) +check("missing: said in the transcript, with the way out", + wait(function() return has("The LLeMbas CLI was not found: `llembas-no-such-command` is not a program this editor can start.") end) + and has("set `cmd` in require(\"llembas\").setup({})") and not L._state.busy, chat.text()) +said_msgs = {} +vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf)) +C.reset() +vim.cmd("doautocmd TextChangedI") +vim.wait(200) +vim.cmd("doautocmd TextChangedI") +vim.wait(200) +check("missing: while you type it is said once, in one short line", #said_msgs == 1 and #said_msgs[1] < vim.o.columns and said_msgs[1]:find("no suggestions", 1, true) ~= nil, + vim.inspect(said_msgs)) +-- `lembas` that is not on the PATH is looked for where the CLI's installer puts it. +local home = tmp .. "/home" +vim.fn.mkdir(home .. "/.local/bin", "p") +vim.fn.writefile({ "#!/bin/sh", "shift 2", 'exec python3 "' .. fake .. '" "$@"' }, home .. "/.local/bin/lembas") +vim.fn.setfperm(home .. "/.local/bin/lembas", "rwx------") +local real_home = vim.env.HOME +if vim.fn.executable("lembas") == 0 then + vim.env.HOME = home + L.setup({ cmd = { "lembas", "serve", "--stdio" } }) + vim.cmd("LLeMbasNew") + vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) + type_and_send("found?") + check("found: `lembas` in ~/.local/bin is started when the editor's PATH does not have it", idle() and has("found?\n\n## LLeMbas"), chat.text()) + note_pid() + vim.env.HOME = real_home +else + print("skip found: a `lembas` is on this PATH, so the fallback place is not looked in") +end +-- Nothing is left running: every agent these tests started is gone once the plugin lets go of it. +vim.cmd("LLeMbasRestart") +local left = {} +check("orphans: no agent process outlives its session", wait(function() + left = {} + for id in pairs(pids) do if alive(id) then left[#left + 1] = id end end + return #left == 0 +end, 7000), vim.inspect(left)) + +-- ── Against the LLeMbas CLI itself, when its source is at hand. ────────────────────────────────────── +-- It runs with a home of its own, so it is never signed in and never touches a person's sessions: +-- what is proved is the hello, the capabilities, what needs no sign-in, and that "not signed in" +-- ends in words that say what to do. +local function find_cli() + local dirs = { vim.env.LEMBAS_CLI_SOURCE } + local up = repo + for _ = 1, 4 do + up = vim.fs.dirname(up) + dirs[#dirs + 1] = up .. "/LLeMbas-CLI" + end + for _, d in ipairs(dirs) do + if d and d ~= "" and vim.fn.filereadable(d .. "/src/cli.ts") == 1 and vim.fn.isdirectory(d .. "/node_modules") == 1 then return d end + end +end +local function find_bun() + for _, b in ipairs({ vim.fn.exepath("bun"), (real_home or "") .. "/.local/bin/bun", (real_home or "") .. "/.bun/bin/bun" }) do + if b ~= "" and vim.fn.executable(b) == 1 then return b end + end +end +local cli, bun = find_cli(), find_bun() +if vim.env.LEMBAS_SKIP_REAL_CLI == "1" or not cli or not bun then + print(("skip real CLI: %s (set LEMBAS_CLI_SOURCE to a LLeMbas-CLI checkout with its dependencies installed, and have bun on the PATH)") + :format(vim.env.LEMBAS_SKIP_REAL_CLI == "1" and "LEMBAS_SKIP_REAL_CLI=1" or not cli and "the CLI's source was not found" or "bun was not found")) +else + local cli_home = tmp .. "/cli-home" + vim.fn.mkdir(cli_home, "p") + vim.env.LEMBAS_HOME = cli_home + local project = tmp .. "/project" + vim.fn.mkdir(project .. "/src", "p") + vim.fn.writefile({ "print('waybread')" }, project .. "/src/oven.py") + vim.fn.system({ "git", "-C", project, "init", "-q" }) + vim.cmd("cd " .. vim.fn.fnameescape(project)) + L.setup({ cmd = { bun, "run", cli .. "/src/cli.ts", "serve", "--stdio" } }) + L.START_TIMEOUT_MS = 30000 + vim.cmd("LLeMbasNew") + vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf)) + type_and_send("hello, real CLI") + check("real CLI: not signed in ends in the instruction to sign in, not in a stack trace or a wait", + wait(function() return has("The LLeMbas CLI is not signed in to a server. Run `lembas login ` in a terminal, then try again.") end, 40000) + and idle() and not has("at ") and not has("No session"), chat.text()) + said_msgs = {} + asked = nil + vim.ui.input = function(_, cb) cb("oven") end + vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end + vim.cmd("LLeMbasFiles") + check("real CLI: its file index answers without a sign-in, in the shape the plugin reads", + wait(function() return asked and asked.items[1] and asked.items[1].path == "src/oven.py" and asked.items[1].kind == "file" end, 40000) + and wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@src/oven.py", 1, true) ~= nil end), + vim.inspect({ asked and asked.items, said_msgs })) + local st = L._state + check("real CLI: it says its version, which is new enough, and lists what the plugin uses", + st.ready and st.cli and L.compare_versions(st.cli, L.MIN_CLI) ~= -1 + and st.caps.editor and st.caps.media and st.caps.show and st.caps.files and st.caps.commands and st.caps.steer and st.caps.sessions + and st.caps.compact and st.caps.configure and st.caps.ask and st.caps.plan and not st.caps.fs, vim.inspect({ st.cli, st.caps })) + vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {}) + asked = nil + vim.cmd("LLeMbasCommands") + check("real CLI: its commands are listed without a session", + wait(function() return asked and asked.items[1] and asked.items[1].name == "compact" and asked.items[1].kind == "builtin" end, 20000), vim.inspect(asked and asked.items)) + said_msgs = {} + vim.cmd("LLeMbasSessions") + check("real CLI: with no sessions here, that is what is said", wait(function() return was_said("no previous sessions in this folder") end, 20000), vim.inspect(said_msgs)) + said_msgs = {} + vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf)) + C.reset() + C.request(true) + check("real CLI: a suggestion asked for says to sign in", wait(function() return was_said("Run `lembas login `") end, 20000), vim.inspect(said_msgs)) + said_msgs = {} + vim.cmd("LLeMbasEdit make it better") + check("real CLI: so does a rewrite", wait(function() return was_said("Run `lembas login `") end, 20000), vim.inspect(said_msgs)) + said_msgs = {} + vim.cmd("LLeMbasMainModel ?") + check("real CLI: and the model settings", wait(function() return was_said("Run `lembas login `") end, 20000), vim.inspect(said_msgs)) + local rpid = L._state.conn and L._state.conn.proc.pid + vim.cmd("LLeMbasRestart") + check("real CLI: it ends when the plugin lets go of it", wait(function() return not alive(rpid) end, 7000)) + vim.env.LEMBAS_HOME = nil +end + +vim.notify = notify print(("RAN %d, failed %d"):format(ran, failed)) +vim.cmd("cd /") vim.fn.delete(tmp, "rf") vim.cmd(failed == 0 and "qall!" or "cquit!") diff --git a/tests/fake_agent.py b/tests/fake_agent.py new file mode 100644 index 0000000..eeeb1ed --- /dev/null +++ b/tests/fake_agent.py @@ -0,0 +1,958 @@ +#!/usr/bin/env python3 +"""A stand-in for `lembas serve --stdio`, for the tests of both editors. + +It answers in the shapes of the LLeMbas CLI (2.0.0-beta.17, `src/acp/agent.ts`, harness spec +3.11.0) and in no other: every result, refusal, notification and request it sends is written as +the CLI writes it, and what it is sent is checked as the CLI checks it. A client that reads an +older or an invented shape fails here, as it would against the CLI. When the CLI's protocol +changes, this file changes with it -- it is the one place the tests learn the protocol from. + +A turn is steered by words in the prompt's last text block: + PERM an approval for a command (`session/request_permission`) + SETTLE an approval that is then withdrawn (`_lembas/permission/settled`) + DIFFPERM an approval for an edit, carrying ACP diff items; the file is written when allowed + READ the read tool: the client's text when it gives one, else the disk's + PUT the write tool: "put by the agent" + a line break becomes the file's text + EDIT the edit tool: the file's first line in capitals, the rest as it is + WRITE the agent writes the disk itself (a session whose client offers no `fs`) + SHOW the show tool (text with its content; anything else by a handle); `AT `: a line + BADHASH with SHOW: the handle's hash is not the file's + QUESTION `_lembas/question` (MULTI: a question that takes several options) + PLANCARD `_lembas/plan` + TOOL a tool call with its events (phase, tool_end with ms, usage) + DENIED a call that was refused + PLAN a `plan` update + TEAM a `team` event + NOTICE a `notice` event + META says back the editor context the prompt carried + FAIL the turn fails: an `error` event, and the answer's `_meta.lembas.error` + FAILFIELD the same, said by the answer alone + SLOW waits to be cancelled + CRASH writes to stderr and exits 3 +A prompt that is `/compact` is the command, as the CLI runs it. A completion is steered by words +in its prefix (SLOWC waits to be cancelled, FAILC is a server failure, BUSYC is `busy`), a rewrite +by words in its instruction (SLOWE waits to be cancelled, `REPLACE ` answers that text, +SAME answers the selection, EMPTYE is a model that answered nothing). + +Environment: + FAKE_AGENT_LOG every message received is appended, one JSON object a line + FAKE_AGENT_VERSION the version it says (default 2.0.0-beta.17); before 2.0.0-beta.14 it + has no editor methods, before 2.0.0-beta.15 no `_lembas/sessions/*` + FAKE_AGENT_LOGIN=none this computer is not logged in to a server + FAKE_AGENT_AUTOCOMPLETE the saved autocomplete model; "none": nobody has chosen one + FAKE_AGENT_HANG= that request is never answered +""" +import base64 +import hashlib +import json +import os +import re +import sys +import threading +import time +import uuid + +LOG = os.environ.get("FAKE_AGENT_LOG") +VERSION = os.environ.get("FAKE_AGENT_VERSION", "2.0.0-beta.17") +LOGGED_IN = os.environ.get("FAKE_AGENT_LOGIN") != "none" +HANG = os.environ.get("FAKE_AGENT_HANG", "") + +INVALID_PARAMS = -32602 +METHOD_NOT_FOUND = -32601 +INTERNAL_ERROR = -32603 + +MODES = ["manual", "edit", "auto", "plan"] +NOT_LOGGED_IN_SESSION = ("Not logged in to a LLeMbas server. LLeMbas CLI uses the models of the server it is logged in to: " + "lembas login
(e.g. lembas login ai.example.org).") +NOT_LOGGED_IN_EDITOR = "this computer is not logged in to a LLeMbas server (lembas login
)" + +CAPABILITIES = [ + "directories", "configure", "steer", "sessions", "status", "delete", "compact", "title", "files", "commands", + "attachments", "ask", "plan", "model", "turns", "context", "library", "plan_state", "rewind", "jobs", "show", + "progress", "tree", "agents", "scheduled", "reports", "directory_model", "harness_turns", "editor", "media", +] +COMMANDS = [ + {"name": "compact", "description": "summarise the conversation to free context", "_meta": {"lembas": {"kind": "builtin"}}}, + {"name": "plan", "description": "plan mode — read, investigate, write a plan for approval; with a task, start on it", + "input": {"hint": "task"}, "_meta": {"lembas": {"kind": "builtin"}}}, + {"name": "undo", "description": "take back the last prompt: its file changes and its conversation", "_meta": {"lembas": {"kind": "builtin"}}}, + {"name": "review", "description": "a read-only review of this session's changes (or since the last commit, or against a branch)", + "input": {"hint": "head | "}, "_meta": {"lembas": {"kind": "builtin"}}}, + {"name": "bake", "description": "a skill of the project", "input": {"hint": "instruction"}, "_meta": {"lembas": {"kind": "skill"}}}, +] +MODELS = [ + {"id": "example/model-a", "name": "Model A", "for": ["main", "autocomplete"], "default": True}, + {"id": "example/model-b", "name": "Model B", "for": ["main", "autocomplete"]}, + {"id": "example/model-c", "name": "Model C", "for": ["main"]}, +] +ALLOWED = ["example/model-a", "example/model-b"] + + +def version_key(v): + """2.0.0-beta.10 sorts above 2.0.0-beta.9, and a release above its betas.""" + core, _, pre = v.split("+")[0].partition("-") + nums = [int(x) for x in core.split(".")[:3]] + n = re.search(r"(\d+)$", pre) + return nums + [0 if pre else 1, int(n.group(1)) if n else 0] + + +HAS_EDITOR = version_key(VERSION) >= version_key("2.0.0-beta.14") +HAS_SESSIONS = version_key(VERSION) >= version_key("2.0.0-beta.15") + +lock = threading.Lock() +waiting = {} # our request id -> [Event, result, error] +next_id = [0] +client = {"lembas": False, "protocol": 1, "editor": False, "show": False, "media": False, "read": False, "write": False} +sessions = {} # id -> {cwd, mode, model, working, cancel: Event, seen: {path: sha}} +saved = os.environ.get("FAKE_AGENT_AUTOCOMPLETE", "example/model-a") +settings = {"autocomplete_model": None if saved == "none" else saved, "main_model": None} +completion = [None] # (client id, Event) of the one completion under way +complete_lock = threading.Lock() +rewrites = {} # Event -> client id +handles = {} # handle -> bytes +PREVIOUS = {"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000100000, "created": 1700000000000} + + +class Refusal(Exception): + def __init__(self, code, message, reason=None): + super().__init__(message) + self.code, self.message, self.reason = code, message, reason + + +def out(msg): + with lock: + sys.stdout.write(json.dumps(msg) + "\n") + sys.stdout.flush() + + +def notify(method, params): + out({"jsonrpc": "2.0", "method": method, "params": params}) + + +def result(msg, value): + out({"jsonrpc": "2.0", "id": msg["id"], "result": value}) + + +def refuse(msg, code, message, reason=None): + error = {"code": code, "message": message} + if reason: + error["data"] = {"reason": reason} + out({"jsonrpc": "2.0", "id": msg["id"], "error": error}) + + +def ask(method, params, wait=30): + """A request to the client: (result, None), (None, error), or (None, 'timeout').""" + with lock: + next_id[0] += 1 + rid = next_id[0] + entry = [threading.Event(), None, None] + waiting[rid] = entry + out({"jsonrpc": "2.0", "id": rid, "method": method, "params": params}) + if not entry[0].wait(wait): + waiting.pop(rid, None) + return None, "timeout" + waiting.pop(rid, None) + return entry[1], entry[2] + + +def sha(text): + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + +def read_disk(path): + with open(path, "rb") as f: + return f.read().decode("utf-8") + + +def write_disk(path, text): + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + with open(path, "wb") as f: + f.write(text.encode("utf-8")) + + +def word_after(text, word): + return text.split(word + " ", 1)[1].split()[0] + + +# ---- what the CLI sends about a session --------------------------------------------------- + + +def update(sid, body): + notify("session/update", {"sessionId": sid, "update": body}) + + +def event(sid, body): + if client["lembas"]: + notify("_lembas/event", {"sessionId": sid, "event": body}) + + +def say(sid, text): + event(sid, {"type": "text", "text": text}) + update(sid, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}}) + + +def think(sid, text): + event(sid, {"type": "reasoning", "text": text}) + update(sid, {"sessionUpdate": "agent_thought_chunk", "content": {"type": "text", "text": text}}) + + +def phase(sid, name, **data): + event(sid, {"type": "phase", "progress": {"phase": name, "since": int(time.time() * 1000), **data} if name else None}) + + +def set_mode(sid, mode): + sessions[sid]["mode"] = mode + event(sid, {"type": "mode", "mode": mode}) + update(sid, {"sessionUpdate": "current_mode_update", "currentModeId": mode}) + + +def tool_start(sid, call, name, kind, title, args): + phase(sid, "running_tool", tool=name, what=title) + event(sid, {"type": "tool_start", "id": call, "name": name, "args": args, "title": title}) + update(sid, {"sessionUpdate": "tool_call", "toolCallId": call, "title": title, "kind": kind, "status": "in_progress", "rawInput": args}) + + +def tool_end(sid, call, name, output, failed=False, files=None, ms=42): + event(sid, {"type": "tool_end", "id": call, "name": name, "result": {"output": output, **({"isError": True} if failed else {})}, "ms": ms}) + content = [{"type": "content", "content": {"type": "text", "text": output[:20000]}}] + if files and not failed and client["editor"]: + content += diff_items(files) + update(sid, {"sessionUpdate": "tool_call_update", "toolCallId": call, "status": "failed" if failed else "completed", "content": content}) + + +def tool_denied(sid, call, name, kind, title, args, reason): + event(sid, {"type": "tool_denied", "id": call, "name": name, "reason": reason, "args": args, "title": title}) + update(sid, {"sessionUpdate": "tool_call", "toolCallId": call, "title": title, "kind": kind, "status": "failed", "rawInput": args, + "content": [{"type": "content", "content": {"type": "text", "text": reason}}], "_meta": {"lembas": {"denied": True}}}) + + +def diff_items(files): + return [{"type": "diff", "path": f["path"], "oldText": f["oldText"], "newText": f["newText"] if f["newText"] is not None else "", + **({"_meta": {"lembas": {"deleted": True}}} if f["newText"] is None else {})} for f in files] + + +def approval(sid, tool, kind, title, args, reason, files=None, always=True): + """`session/request_permission`, and the answer as the CLI reads it: once, session or deny.""" + call = str(uuid.uuid4()) + tool_call = {"toolCallId": call, "title": title, "kind": kind, "status": "pending", "rawInput": args} + if files: + if client["editor"]: + tool_call["content"] = diff_items(files) + else: + tool_call["content"] = [{"type": "content", "content": {"type": "text", "text": "--- a\n+++ b\n(the change as a unified diff)"}}] + options = [{"optionId": "once", "kind": "allow_once", "name": "Allow once"}] + if always: + options.append({"optionId": "session", "kind": "allow_always", "name": "Always, this session"}) + options.append({"optionId": "deny", "kind": "reject_once", "name": "Deny"}) + phase(sid, "waiting_for_person") + answer, error = ask("session/request_permission", { + "sessionId": sid, "toolCall": tool_call, "options": options, + "_meta": {"lembas": {"tool": tool, "reason": reason, "purpose": "what the model says the call is for"}}}) + if error: + notify("_lembas/permission/settled", {"sessionId": sid, "toolCallId": call}) + return "deny" + outcome = (answer or {}).get("outcome") or {} + chosen = str(outcome.get("optionId")) if outcome.get("outcome") == "selected" else "deny" + if chosen == "once" or (chosen == "session" and always): + return chosen + return "deny" + + +# ---- the file tools, with the client's buffers (acp.md *Unsaved text*, src/tool/buffers.ts) ---- + + +def client_read(sid, path): + if not client["read"]: + return None + answer, error = ask("fs/read_text_file", {"sessionId": sid, "path": path}, 10) + if error or not isinstance((answer or {}).get("content"), str): + return None + return answer["content"] + + +def tool_read(sid, path): + """The read tool: what the client gives is what "read" means from then on.""" + text = client_read(sid, path) + if text is not None: + sessions[sid]["seen"][path] = sha(text) + return text + return read_disk(path) + + +def file_text(sid, path): + """A file's text for a tool that changes it: the client's, else the disk's -- never the disk's + for a file the session read through the client.""" + text = client_read(sid, path) + if text is not None: + return text + if path in sessions[sid]["seen"]: + raise Refusal(0, f"{path} is open in the editor, and the editor did not give its text just now. Read it again before changing it.") + return read_disk(path) + + +def guard(sid, path): + seen = sessions[sid]["seen"].get(path) + if seen is None or not client["read"]: + return + now = client_read(sid, path) + if now is None: + raise Refusal(0, f"{path} is open in the editor, and the editor did not give its text just now. Read it again before changing it.") + if sha(now) != seen: + raise Refusal(0, f"{path} changed since you last read it. Read it again before changing it.") + + +def put_text(sid, path, content): + """Write through the client where it takes the text, else to the disk. True: the client took it.""" + seen = sessions[sid]["seen"] + tracked = path in seen + if not client["write"]: + write_disk(path, content) + if tracked: + seen[path] = sha(content) + return False + answer, error = ask("fs/write_text_file", {"sessionId": sid, "path": path, "content": content}, 10) + if error == "timeout": + seen[path] = "unknown" + raise Refusal(0, f"The editor did not confirm writing {path}; it may or may not have been written. Read it again to see what is there before going on.") + if not error: + seen[path] = sha(content) + return True + if tracked: + raise Refusal(0, f"{path} is open in the editor, which refused the write. Nothing was written; tell the user, or read it again.") + write_disk(path, content) + return False + + +# ---- a turn --------------------------------------------------------------------------------- + + +def prompt(msg, s, text): + p = msg["params"] + sid = s["id"] + turn = str((((p.get("_meta") or {}).get("lembas") or {}).get("turnId")) or uuid.uuid4()) + done = {"turnId": turn} + s["working"] = True + try: + if text.startswith("/compact"): + event(sid, {"type": "compacted", "summary": "Compacted 2 turns."}) + return result(msg, {"stopReason": "end_turn", "_meta": {"lembas": {**done, "command": "compact", "summary": "Compacted 2 turns."}}}) + event(sid, {"type": "prompt", "text": text, "turnId": turn}) + event(sid, {"type": "task", "state": "start", "turnId": turn}) + phase(sid, "waiting_for_model", model=s["model"]) + phase(sid, "thinking") + think(sid, "hidden thought") + phase(sid, "writing") + say(sid, "Hello ") + say(sid, "there.\nSecond line") + stop = turn_body(sid, s, p, text) + # A subagent's usage counts toward the task, and says nothing about the session's own. + event(sid, {"type": "usage", "usage": {"input": 700000, "output": 9000}, "child": True}) + event(sid, {"type": "usage", "usage": {"input": 1200, "output": 34, "cached": 1000}, "context": 32768, "used": 1234, "rate": 41.5}) + if "FAIL" in text.replace("FAILC", ""): + # A turn that fails ends as any other (`end_turn`): the `error` event says why, the phase + # is `failed`, and the answer carries the same in `_meta.lembas.error`. + why = "the server answered 502: the model is not loaded" + if "FAILFIELD" not in text: + event(sid, {"type": "error", "message": why}) + phase(sid, "failed", reason=why) + event(sid, {"type": "task", "state": "end", "turnId": turn}) + event(sid, {"type": "done", "reason": "error"}) + return result(msg, {"stopReason": "end_turn", "_meta": {"lembas": {**done, "error": {"code": "unreachable", "message": why}}}}) + phase(sid, None) + event(sid, {"type": "task", "state": "end", "turnId": turn}) + event(sid, {"type": "done", "reason": "cancelled" if stop == "cancelled" else "stop"}) + result(msg, {"stopReason": stop, "_meta": {"lembas": done}}) + finally: + s["working"] = False + + +def run_tool(sid, name, kind, title, args, fn, files=None): + call = "call_" + uuid.uuid4().hex[:8] + tool_start(sid, call, name, kind, title, args) + try: + output = fn() + except Refusal as e: + return tool_end(sid, call, name, e.message, failed=True) + except OSError as e: + return tool_end(sid, call, name, str(e), failed=True) + tool_end(sid, call, name, output, files=files() if callable(files) else files) + + +def turn_body(sid, s, p, text): + if "META" in text: + say(sid, "\neditor=" + json.dumps(((p.get("_meta") or {}).get("lembas") or {}).get("editor"), sort_keys=True)) + if "NOTICE" in text: + event(sid, {"type": "notice", "level": "warn", "message": "the server is slow to answer; trying again"}) + if "TEAM" in text: + event(sid, {"type": "team", "tree": {"min": 1, "max": 3, "size": 1, "open_slots": 2, "ended": [], "agents": [ + {"id": "a1", "name": "scout", "position": "1", "parent": None, "state": "working", "model": s["model"], "mode": "plan", + "request": [], "manager": False, "task": "read the tests", "progress": None, "findings": 0, "messages": 0}]}}) + if "PLAN" in text.replace("PLANCARD", ""): + plan = {"version": 1, "title": "Upgrade", "summary": "", "findings": [], "objectives": [], + "phases": [{"title": "Phase 1", "tasks": [{"text": "Step 1", "status": "done"}, {"text": "Step 2", "status": "doing"}, {"text": "Step 3", "status": "todo"}]}]} + event(sid, {"type": "plan", "plan": plan}) + update(sid, {"sessionUpdate": "plan", "entries": [ + {"content": "Step 1", "status": "completed", "priority": "medium"}, + {"content": "Step 2", "status": "in_progress", "priority": "medium"}, + {"content": "Step 3", "status": "pending", "priority": "medium"}], "_meta": {"lembas": {"plan": plan}}}) + if "TOOL" in text: + run_tool(sid, "grep", "search", "grep waybread", {"pattern": "waybread"}, lambda: "src/oven.py:3: waybread = bake()") + if "DENIED" in text: + tool_denied(sid, "call_denied", "bash", "execute", "rm -rf /", {"command": "rm -rf /"}, "The hardline never allows this command.") + if "DIFFPERM " in text: + path = word_after(text, "DIFFPERM") + old = file_text(sid, path) if os.path.exists(path) else None + new = "rewritten by the agent\n" + files = [{"path": path, "oldText": old, "newText": new}] + args = {"path": path, "content": new} + title = "write " + os.path.basename(path) + got = approval(sid, "write", "edit", title, args, "manual mode asks about every edit", files) + if got == "deny": + tool_denied(sid, "call_w", "write", "edit", title, args, "The user denied this call.") + else: + run_tool(sid, "write", "edit", title, args, lambda: (put_text(sid, path, new), "Wrote " + path)[1], files) + say(sid, "\nanswer=" + got) + elif "SETTLE" in text: + call = str(uuid.uuid4()) + with lock: + next_id[0] += 1 + rid = next_id[0] + entry = [threading.Event(), None, None] + waiting[rid] = entry + out({"jsonrpc": "2.0", "id": rid, "method": "session/request_permission", "params": { + "sessionId": sid, + "toolCall": {"toolCallId": call, "title": "make build", "kind": "execute", "status": "pending", "rawInput": {"command": "make build"}}, + "options": [{"optionId": "once", "kind": "allow_once", "name": "Allow once"}, + {"optionId": "session", "kind": "allow_always", "name": "Always, this session"}, + {"optionId": "deny", "kind": "reject_once", "name": "Deny"}], + "_meta": {"lembas": {"tool": "bash", "reason": "the rules ask about this command"}}}}) + # The device stops waiting (its time ran out, or it was answered at a terminal): the card is taken down. + def settle(): + # Whatever the client answers from here on is not read: the call was refused already. + waiting.pop(rid, None) + notify("_lembas/permission/settled", {"sessionId": sid, "toolCallId": call}) + entry[0].set() + threading.Timer(0.2, settle).start() + entry[0].wait(30) + say(sid, "\nanswer=deny (Nobody answered the approval in time, so it was refused.)") + elif "PERM" in text: + args = {"command": "rm -r build"} + got = approval(sid, "bash", "execute", "rm -r build", args, "deletes files") + if got == "deny": + tool_denied(sid, "call_p", "bash", "execute", "rm -r build", args, "The user denied this call.") + say(sid, "\nanswer=" + got) + if "WRITE " in text: + path = word_after(text, "WRITE") + old = read_disk(path) if os.path.exists(path) else None + new = "rewritten by the agent\n" + run_tool(sid, "write", "edit", "write " + os.path.basename(path), {"path": path, "content": new}, + lambda: (write_disk(path, new), "Wrote " + path)[1], [{"path": path, "oldText": old, "newText": new}]) + if "READ " in text: + path = word_after(text, "READ") + got = {} + + def read(): + got["text"] = tool_read(sid, path) + return got["text"] + run_tool(sid, "read", "read", "read " + os.path.basename(path), {"path": path}, read) + say(sid, "\nread=" + json.dumps(got.get("text"))) + if "PUT " in text: + path = word_after(text, "PUT") + got = {} + + def put(): + if os.path.exists(path): + guard(sid, path) + got["by"] = "client" if put_text(sid, path, "put by the agent\n") else "disk" + return "Wrote " + path + run_tool(sid, "write", "edit", "write " + os.path.basename(path), {"path": path, "content": "put by the agent\n"}, put) + say(sid, "\nput=" + got.get("by", "refused")) + if "EDIT " in text: + path = word_after(text, "EDIT") + got = {} + + def edit(): + guard(sid, path) + before = file_text(sid, path) + first, sep, rest = before.partition("\n") + after = first.upper() + sep + rest + got["files"] = [{"path": path, "oldText": before, "newText": after}] + got["by"] = "client" if put_text(sid, path, after) else "disk" + return "Edited " + path + run_tool(sid, "edit", "edit", "edit " + os.path.basename(path), {"path": path}, edit, lambda: got.get("files")) + say(sid, "\nedit=" + got.get("by", "refused")) + if "SHOW " in text: + say(sid, "\nshown=" + json.dumps(show(sid, s, text), sort_keys=True)) + if "QUESTION" in text: + say(sid, "\nquestion=" + json.dumps(question(sid, "MULTI" in text), sort_keys=True)) + if "PLANCARD" in text: + say(sid, "\nplan=" + json.dumps(plan_card(sid), sort_keys=True)) + if "CRASH" in text: + sys.stderr.write("error: the session store could not be opened\n") + sys.stderr.flush() + os._exit(3) + if "SLOW" in text.replace("SLOWC", "").replace("SLOWE", ""): + got = s["cancel"].wait(10) + s["cancel"].clear() + return "cancelled" if got else "end_turn" + return "end_turn" + + +TEXT_KINDS = {"md": ("markdown", None), "html": ("html", None), "py": ("code", "python"), "js": ("code", "javascript"), + "ts": ("code", "typescript"), "lua": ("code", "lua"), "csv": ("table", None), "svg": ("svg", None)} +MEDIA = {"png": ("image", "image/png"), "jpg": ("image", "image/jpeg"), "gif": ("image", "image/gif"), "pdf": ("pdf", "application/pdf"), + "mp3": ("audio", "audio/mpeg"), "mp4": ("video", "video/mp4"), "zip": ("archive", "application/zip")} + + +def show(sid, s, text): + """The show tool: a text file with its content, any other file by a handle (and, on stdio, where it is).""" + if not client["show"]: + return {"shown": False, "reason": "the show tool is not offered to this client"} + path = word_after(text, "SHOW") + with open(path, "rb") as f: + data = f.read() + rel = os.path.relpath(path, s["root"]) + ext = os.path.splitext(path)[1][1:].lower() + call = "call_show_" + uuid.uuid4().hex[:6] + if b"\0" not in data and ext not in MEDIA: + kind, language = TEXT_KINDS.get(ext, ("text", None)) + if not client["media"] and kind in ("table", "svg"): + kind = "text" + params = {"sessionId": sid, "toolCallId": call, "path": rel, "kind": kind, "text": data.decode("utf-8")} + if language: + params["language"] = language + if " AT " in text: + params["line"] = int(word_after(text, "AT")) + answer, error = ask("_lembas/show", params, 30) + else: + if not client["media"]: + return {"shown": False, "reason": "not a text file"} + kind, mime = MEDIA.get(ext, ("binary", "application/octet-stream")) + handle = "h_" + str(uuid.uuid4()) + handles[handle] = data + digest = "0" * 64 if "BADHASH" in text else hashlib.sha256(data).hexdigest() + answer, error = ask("_lembas/show", { + "sessionId": sid, "toolCallId": call, "path": rel, "kind": kind, "mimeType": mime, "size": len(data), + "hash": "sha256:" + digest, "handle": handle, "uri": "file://" + "/".join(quote(x) for x in os.path.abspath(path).split("/"))}, 30) + handles.pop(handle, None) + if error or not isinstance(answer, dict): + return {"shown": False, "reason": "the client did not show it"} + if answer.get("shown") is True: + return {"shown": True} + reason = answer.get("reason") + return {"shown": False, "reason": reason if isinstance(reason, str) and reason else "the client did not show it"} + + +def quote(part): + from urllib.parse import quote as q + return q(part, safe="") + + +def question(sid, multiple): + """`_lembas/question`, and its answer as the CLI reads it (`questionReplyFrom`).""" + questions = [{"header": "Database", "question": "Which backend?", "multiple": multiple, "options": [ + {"label": "SQLite", "description": "local file", "recommended": True}, {"label": "Postgres", "description": "server"}]}, + {"header": "Name", "question": "What is it called?", "multiple": False, "options": []}] + phase(sid, "waiting_for_person") + answer, error = ask("_lembas/question", {"sessionId": sid, "toolCallId": "call_q_" + uuid.uuid4().hex[:6], "why": "Need a choice", + "questions": questions, "_meta": {"lembas": {}}}) + if error or not isinstance(answer, dict) or answer.get("outcome") != "answered" or not isinstance(answer.get("answers"), list): + return {"dismissed": True} + answers = [] + for i, a in enumerate(answer["answers"]): + if i >= len(questions): + break + if isinstance(a, dict) and a.get("kind") == "options" and isinstance(a.get("labels"), list): + answers.append({"kind": "options", "labels": [x for x in a["labels"] if isinstance(x, str)]}) + elif isinstance(a, dict) and a.get("kind") in ("custom", "back") and isinstance(a.get("text"), str): + answers.append({"kind": a["kind"], "text": a["text"]}) + elif a is None or (isinstance(a, dict) and a.get("kind") == "skipped"): + answers.append(None) + else: + return {"dismissed": True} + return {"answers": answers} + + +def plan_card(sid): + """`_lembas/plan`, and its answer as the CLI reads it (`planReplyFrom`).""" + plan = {"version": 1, "title": "Upgrade", "summary": "", "findings": [], "objectives": [], + "phases": [{"title": "Phase 1", "tasks": [{"text": "Step 1", "status": "todo"}]}]} + phase(sid, "waiting_for_person") + answer, error = ask("_lembas/plan", {"sessionId": sid, "toolCallId": "call_plan_" + uuid.uuid4().hex[:6], "path": ".agent/plans/upgrade.md", + "text": "# Upgrade\n\n- Step 1\n- Step 2", "plan": plan, "_meta": {"lembas": {}}}) + a = answer if isinstance(answer, dict) and not error else {} + if a.get("outcome") == "approve": + mode = "manual" if a.get("mode") == "manual" else "edit" + set_mode(sid, mode) + return {"kind": "approve", "mode": mode} + if a.get("outcome") == "revise" and isinstance(a.get("feedback"), str) and a["feedback"].strip(): + return {"kind": "revise", "feedback": a["feedback"].strip()} + return {"kind": "dismissed"} + + +# ---- the editor's methods (acp.md *An editor as the client*) ---------------------------------- + + +def login_or_refuse(): + if not LOGGED_IN: + raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_EDITOR, "not_logged_in") + + +def editor_settings(): + return {"autocomplete": {"model": settings["autocomplete_model"], "source": "person" if settings["autocomplete_model"] else None, "allowed": ALLOWED}, + "main": {"model": settings["main_model"]}} + + +def complete(msg): + p = msg["params"] + cid = p.get("id") if isinstance(p.get("id"), str) and p.get("id") else None + mine = threading.Event() + with complete_lock: + before = completion[0] + completion[0] = (cid, mine) + if before: + before[1].set() # a newer request stops the older, which is answered as cancelled + try: + model = p.get("model") or settings["autocomplete_model"] + if not model: + return refuse(msg, INVALID_PARAMS, "No autocomplete model is chosen. Choose one in your settings on the server.", "no_model") + if model not in [m["id"] for m in MODELS]: + return refuse(msg, INVALID_PARAMS, f"{model} is not a model of this account.", "unknown_model") + if model not in ALLOWED: + return refuse(msg, INVALID_PARAMS, "Model C is not allowed for autocomplete.", "not_allowed") + prefix = p["prefix"] + if "FAILC" in prefix: + return refuse(msg, INTERNAL_ERROR, "autocomplete failed on the server (502)") + if "BUSYC" in prefix: + return refuse(msg, INVALID_PARAMS, "too many completions at once — the next keystroke will try again", "busy") + mine.wait(10 if "SLOWC" in prefix else 0.05) + if mine.is_set(): + return result(msg, {"text": "", "cancelled": True}) + if "TWO" in prefix: + text = "tail()\n second line" + else: + last = prefix.split()[-1] if prefix.split() else "" + text = "<" + last + "|" + model + ">" + result(msg, {"text": text, "model": model, "finish": "stop"}) + finally: + with complete_lock: + if completion[0] and completion[0][1] is mine: + completion[0] = None + + +def edit(msg): + p = msg["params"] + eid = p.get("id") if isinstance(p.get("id"), str) and p.get("id") else None + mine = threading.Event() + rewrites[mine] = eid + try: + if "EMPTYE" in p["instruction"]: + return refuse(msg, INTERNAL_ERROR, "the model answered with no text for this selection — try again, or say more in the instruction") + if "SLOWE" in p["instruction"]: + mine.wait(10) + if mine.is_set(): + return result(msg, {"text": "", "cancelled": True}) + text = p["text"] + if p["instruction"].startswith("REPLACE "): + new = p["instruction"][len("REPLACE "):].replace("\\n", "\n") + elif "SAME" in p["instruction"]: + new = text + else: + # The first line in capitals, a line added after the second, the rest as it was. + lines = text.split("\n") + new = "\n".join([lines[0].upper()] + lines[1:2] + [" # added by the rewrite"] + lines[2:]) + # The text ends with a line break exactly when the selection did. + new = new.rstrip("\n") + ("\n" if text.endswith("\n") else "") + if eid: + half = len(new) // 2 + for piece in (new[:half], new[half:]): + if piece: + notify("_lembas/edit/delta", {"id": eid, "delta": piece}) + model = p.get("model") or (sessions[p["sessionId"]]["model"] if p.get("sessionId") else settings["main_model"] or "example/model-a") + result(msg, {"text": new, "model": model}) + finally: + rewrites.pop(mine, None) + + +def list_files(root, query, limit): + """The project's files and folders matching `query`; an empty query gives the recent ones, and nothing is recent here.""" + if not query: + return [] + q = query.lower() + found = [] + for base, dirs, names in os.walk(root): + dirs[:] = sorted(d for d in dirs if not d.startswith(".") and d != "node_modules") + rel = os.path.relpath(base, root) + for d in dirs: + found.append((os.path.join(rel, d) if rel != "." else d, "dir")) + for n in sorted(names): + if not n.startswith("."): + found.append((os.path.join(rel, n) if rel != "." else n, "file")) + return [{"path": path.replace(os.sep, "/"), "kind": kind} for path, kind in found if q in path.lower()][:limit] + + +def directory_of(p): + """A session's directory, or `cwd`: absolute and a directory, as `session/new` asks.""" + sid = p.get("sessionId") if isinstance(p.get("sessionId"), str) else "" + if sid: + if sid not in sessions: + raise Refusal(INVALID_PARAMS, "no such session") + return sessions[sid]["cwd"] + cwd = p.get("cwd").strip() if isinstance(p.get("cwd"), str) else "" + if not cwd or not os.path.isabs(cwd): + raise Refusal(INVALID_PARAMS, "a sessionId, or a cwd that is an absolute path") + if not os.path.isdir(cwd): + raise Refusal(INVALID_PARAMS, f"{cwd} is not a directory on this machine") + return cwd + + +def session_of(p): + s = sessions.get(str(p.get("sessionId") or "")) + if not s: + raise Refusal(INVALID_PARAMS, "no such session") + return s + + +def session_result(s, extra=None): + return {"sessionId": s["id"], **(extra or {}), + "modes": {"currentModeId": s["mode"], "availableModes": [{"id": m, "name": m} for m in MODES]}, + "_meta": {"lembas": {"model": s["model"], "mode": s["mode"], "effort": "default", "instance": False}}} + + +def open_session(sid, cwd, mode, model): + s = {"id": sid, "cwd": cwd, "root": cwd, "mode": mode, "model": model, "working": False, "cancel": threading.Event(), "seen": {}} + sessions[sid] = s + return s + + +def after_answer(fn): + threading.Timer(0.01, fn).start() + + +def handle(msg): + method = msg.get("method") + p = msg.get("params") + p = p if isinstance(p, dict) else {} + msg["params"] = p + is_request = msg.get("id") is not None + if method == HANG: + return + if method == "initialize": + said = ((p.get("clientCapabilities") or {}).get("_meta") or {}).get("lembas") + fs = (p.get("clientCapabilities") or {}).get("fs") or {} + client["lembas"] = bool(said) + said = said if isinstance(said, dict) else {} + client["protocol"] = said.get("protocol") if isinstance(said.get("protocol"), (int, float)) else 1 + client["show"] = said.get("show") is True + client["editor"] = said.get("editor") is True and HAS_EDITOR + client["media"] = said.get("media") is True and HAS_EDITOR + client["read"] = fs.get("readTextFile") is True and HAS_EDITOR + client["write"] = fs.get("writeTextFile") is True and HAS_EDITOR + capabilities = [c for c in CAPABILITIES if HAS_EDITOR or c not in ("editor", "media")] + return result(msg, { + "protocolVersion": 1, + "agentCapabilities": {"loadSession": False, "promptCapabilities": {"image": True, "audio": False, "embeddedContext": True}, + "mcpCapabilities": {"http": False, "sse": False}}, + "authMethods": [], + "agentInfo": {"name": "LLeMbas CLI", "version": VERSION}, + "_meta": {"lembas": {"protocol": 3, "harness_spec": "3.11.0" if HAS_EDITOR else "3.10.0", "limits": None, "connection": None, + "capabilities": capabilities}}}) + if method == "authenticate": + return result(msg, {}) + if method == "session/new": + cwd = p.get("cwd") if isinstance(p.get("cwd"), str) else "" + if not cwd or not os.path.isabs(cwd): + raise Refusal(INVALID_PARAMS, "cwd must be an absolute path") + if not os.path.isdir(cwd): + raise Refusal(INVALID_PARAMS, f"{cwd} is not a directory on this machine") + if not LOGGED_IN: + raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION) + meta = p.get("_meta") if isinstance(p.get("_meta"), dict) else {} + mode = meta.get("mode") if meta.get("mode") in MODES else "manual" + model = meta.get("model") if isinstance(meta.get("model"), str) else settings["main_model"] or "example/model-a" + if model not in [m["id"] for m in MODELS]: + raise Refusal(INVALID_PARAMS, f"unknown model {model} — the server offers: " + ", ".join(m["id"] for m in MODELS)) + s = open_session("ses_test" if "ses_test" not in sessions else "ses_test" + str(len(sessions)), cwd, mode, model) + after_answer(lambda: update(s["id"], {"sessionUpdate": "available_commands_update", "availableCommands": COMMANDS})) + return result(msg, session_result(s)) + if method == "session/prompt": + s = session_of(p) + blocks = p.get("prompt") + if not isinstance(blocks, list): + raise Refusal(INVALID_PARAMS, "prompt must be an array of content blocks") + texts = [b["text"] for b in blocks if isinstance(b, dict) and b.get("type") == "text" and isinstance(b.get("text"), str)] + return threading.Thread(target=guarded, args=(msg, lambda: prompt(msg, s, texts[-1] if texts else "")), daemon=True).start() + if method == "session/cancel": + s = sessions.get(str(p.get("sessionId") or "")) + ran = bool(s and s["working"]) + if s: + s["cancel"].set() + return result(msg, {"cancelled": "running" if ran else "none"}) if is_request else None + if method == "session/set_mode": + if p.get("modeId") not in MODES: + raise Refusal(INVALID_PARAMS, f"unknown mode {p.get('modeId')}") + s = session_of(p) + set_mode(s["id"], p["modeId"]) + return result(msg, {}) + if method == "_lembas/configure": + s = session_of(p) + if "model" in p: + raw = p["model"].strip() if isinstance(p["model"], str) else "" + if not raw: + raise Refusal(INVALID_PARAMS, "model must be a non-empty string") + if raw not in [m["id"] for m in MODELS]: + raise Refusal(INVALID_PARAMS, f"unknown model {raw} — the server offers: " + ", ".join(m["id"] for m in MODELS)) + if raw != s["model"]: + s["model"] = raw + event(s["id"], {"type": "model", "ref": raw, "effort": "default", "connection": "example", "instance": False}) + return result(msg, {"model": s["model"], "effort": "default"}) + if method == "_lembas/steer": + text = p.get("text").strip() if isinstance(p.get("text"), str) else "" + if not text: + raise Refusal(INVALID_PARAMS, "nothing to send") + s = session_of(p) + if not s["working"]: + raise Refusal(INVALID_PARAMS, "this session is not working on anything; send it as a prompt") + event(s["id"], {"type": "inbox", "texts": [text], "mode": "steer"}) + return result(msg, {"queued": 1}) + if method == "_lembas/session/compact": + s = session_of(p) + if s["working"]: + raise Refusal(INVALID_PARAMS, "this session is working — compact it when the reply is done") + event(s["id"], {"type": "compacted", "summary": "Compacted 2 turns."}) + return result(msg, {"summary": "Compacted 2 turns."}) + if method == "_lembas/files/search": + root = directory_of(p) + limit = max(1, min(50, int(p.get("limit") or 20))) + return result(msg, {"root": root, "files": list_files(root, p.get("query") if isinstance(p.get("query"), str) else "", limit)}) + if method == "_lembas/commands": + directory_of(p) + return result(msg, {"commands": COMMANDS}) + if method in ("_lembas/sessions/list", "_lembas/sessions/resume") and not HAS_SESSIONS: + raise Refusal(METHOD_NOT_FOUND, "Method not found: " + method) + if method == "_lembas/sessions/list": + if not LOGGED_IN: + return result(msg, {"sessions": []}) + cwd = p.get("cwd") if isinstance(p.get("cwd"), str) and os.path.isabs(p.get("cwd")) else "/" + return result(msg, {"sessions": [{**PREVIOUS, "root": cwd}]}) + if method == "_lembas/sessions/resume": + sid = str(p.get("sessionId") or "").strip() + if not sid: + raise Refusal(INVALID_PARAMS, "sessionId is required") + if sid != PREVIOUS["id"] and sid not in sessions: + raise Refusal(INVALID_PARAMS, "no such session") + if not LOGGED_IN: + raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION) + s = sessions.get(sid) or open_session(sid, os.getcwd(), "edit", PREVIOUS["model"]) + after_answer(lambda: update(s["id"], {"sessionUpdate": "available_commands_update", "availableCommands": COMMANDS})) + return result(msg, session_result(s, {"title": PREVIOUS["title"], "cwd": s["cwd"], "turns": [ + {"role": "user", "text": "earlier question", "turnId": "t1", "attachments": [{"name": "notes.md", "mimeType": "text/markdown", "size": 120}]}, + {"role": "assistant", "text": "earlier answer", "reasoning": "earlier thinking", + "tools": [{"id": "call_1", "name": "read", "args": "{\"path\":\"notes.md\"}", "output": "the notes", "isError": False}, + {"id": "call_2", "name": "bash", "args": "{\"command\":\"make\"}", "output": "make: no rule", "isError": True}]}, + {"role": "user", "text": "⏎ the job is done", "turnId": "t2", "machine": True}, + {"role": "assistant", "text": "noted", "reasoning": "", "tools": []}]})) + if method.startswith("_lembas/") and not HAS_EDITOR and method.split("/")[1] in ("complete", "edit", "models", "editor", "show"): + if is_request: + raise Refusal(METHOD_NOT_FOUND, "Method not found: " + method) + return None + if method == "_lembas/models": + login_or_refuse() + return result(msg, {"models": MODELS, **editor_settings()}) + if method == "_lembas/editor/settings": + to_set = p.get("set") + if to_set is not None: + if not isinstance(to_set, dict) or not any(k in to_set for k in settings): + raise Refusal(INVALID_PARAMS, "set must name autocomplete_model or main_model", "invalid") + for key in settings: + if key in to_set and to_set[key] is not None and (not isinstance(to_set[key], str) or not to_set[key].strip()): + raise Refusal(INVALID_PARAMS, f"{key} must be a model's id, or null for the instance's", "invalid") + login_or_refuse() + for key in settings: + if to_set and key in to_set: + if to_set[key] is not None and to_set[key] not in [m["id"] for m in MODELS]: + raise Refusal(INVALID_PARAMS, f"{to_set[key]} is not a model of this account.", "unknown_model") + settings[key] = to_set[key] + return result(msg, editor_settings()) + if method == "_lembas/complete": + if not isinstance(p.get("prefix"), str): + raise Refusal(INVALID_PARAMS, "prefix must be the text before the cursor", "invalid") + login_or_refuse() + return threading.Thread(target=guarded, args=(msg, lambda: complete(msg)), daemon=True).start() + if method == "_lembas/complete/cancel": + running = completion[0] + if running and running[0] and running[0] == p.get("id"): + running[1].set() + return None + if method == "_lembas/complete/warm": + return None + if method == "_lembas/edit": + if not isinstance(p.get("text"), str) or not p["text"]: + raise Refusal(INVALID_PARAMS, "text must be the selected text", "invalid") + if not isinstance(p.get("instruction"), str) or not p["instruction"].strip(): + raise Refusal(INVALID_PARAMS, "instruction must say what to do with the selection", "invalid") + if len(rewrites) >= 4: + raise Refusal(INVALID_PARAMS, "4 rewrites are already being written — wait for one, or cancel it", "busy") + if p.get("sessionId") and p["sessionId"] not in sessions: + raise Refusal(INVALID_PARAMS, "no such session", "invalid") + if not LOGGED_IN: + raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION, "not_logged_in") + return threading.Thread(target=guarded, args=(msg, lambda: edit(msg)), daemon=True).start() + if method == "_lembas/edit/cancel": + for ev, eid in list(rewrites.items()): + if eid and eid == p.get("id"): + ev.set() + return None + if method == "_lembas/show/read": + data = handles.get(str(p.get("handle") or "")) + if data is None: + raise Refusal(INVALID_PARAMS, "that file is not being handed over any more — a handle is good until its _lembas/show is answered", "invalid") + offset = p["offset"] if isinstance(p.get("offset"), int) and p["offset"] > 0 else 0 + length = min(1000, p["length"] if isinstance(p.get("length"), int) and p["length"] >= 0 else 1000) # small parts, so a client has to loop + part = data[offset:offset + length] + return result(msg, {"data": base64.b64encode(part).decode(), "offset": offset, "eof": offset + len(part) >= len(data)}) + if is_request: + raise Refusal(METHOD_NOT_FOUND, "Method not found: " + str(method)) + return None + + +def guarded(msg, fn): + try: + fn() + except Refusal as e: + if msg.get("id") is not None: + refuse(msg, e.code or INTERNAL_ERROR, e.message, e.reason) + except Exception as e: # what the CLI answers when a handler throws + if msg.get("id") is not None: + refuse(msg, INTERNAL_ERROR, str(e)) + + +def main(): + for line in sys.stdin: + if not line.strip(): + continue + try: + msg = json.loads(line) + except ValueError: + out({"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}) + continue + if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0": + continue + if LOG: + with open(LOG, "a") as f: + f.write(json.dumps(msg) + "\n") + if msg.get("method") is None: + entry = waiting.get(msg.get("id")) + if entry: + if msg.get("error"): + entry[2] = msg["error"] + else: + entry[1] = msg.get("result") + entry[0].set() + continue + guarded(msg, lambda: handle(msg)) + # The client went away: what was under way goes with it. + os._exit(0) + + +main()