Neovim: the CLI's real shapes, a failed turn said, the agent's life, and a stand-in both editors share

The stand-in agent (tests/fake_agent.py) now answers only as LLeMbas CLI 2.0.0-beta.17 does and
checks what it is sent as the CLI checks it; the Neovim tests also run against the CLI itself when
its source is at hand, with a home of its own.

Fixed in the plugin: a failed turn was silent; token usage and progress were read from fields the
CLI does not send; a file the agent had read here and that was not open could not be edited; a
server failure switched autocomplete off; not being signed in pointed at the model picker; no
request had a time limit; an agent that ignored a stop was left running.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
HomerandClaude Fable 5.2 committed 2026-12-01 19:18:05 +00:00
1 parent dd2bc2dcae
commit e4381217b4
10 files changed
+2211 -582

No files matched your search

+62 -15
View File
@@ -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()
+81 -14
View File
@@ -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
+6 -3
View File
@@ -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)
+443 -141
View File
@@ -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 <server>` in a terminal, then try again.",
signed_out = "The server no longer accepts this computer's sign-in. Run `lembas login <server>` 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" }, {
+56 -9
View File
@@ -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
+5
View File
@@ -93,6 +93,11 @@ end
--- Open a read-only floating window with rounded borders (`q` or `<Esc>` 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"
+2
View File
@@ -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" })
-239
View File
@@ -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 <path> rewrites that file, SLOW waits to be cancelled, CRASH exits. Every request it gets is
appended to the file named by FAKE_AGENT_LOG, one JSON object a line.
"""
import json
import os
import sys
import threading
LOG = os.environ.get("FAKE_AGENT_LOG")
lock = threading.Lock()
waiting = {}
cancelled = threading.Event()
next_id = [1000]
def out(msg):
with lock:
sys.stdout.write(json.dumps(msg) + "\n")
sys.stdout.flush()
def update(session, body):
out({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": session, "update": body}})
def ask(method, params):
with lock:
next_id[0] += 1
rid = next_id[0]
done = threading.Event()
waiting[rid] = [done, None]
out({"jsonrpc": "2.0", "id": rid, "method": method, "params": params})
done.wait(10)
return waiting.pop(rid)[1]
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()
+598 -161
View File
File diff suppressed because it is too large. Load diff
+958
View File
@@ -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 <path> an approval for an edit, carrying ACP diff items; the file is written when allowed
READ <path> the read tool: the client's text when it gives one, else the disk's
PUT <path> the write tool: "put by the agent" + a line break becomes the file's text
EDIT <path> the edit tool: the file's first line in capitals, the rest as it is
WRITE <path> the agent writes the disk itself (a session whose client offers no `fs`)
SHOW <path> the show tool (text with its content; anything else by a handle); `AT <n>`: 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 <text>` 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=<method> 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 <address> (e.g. lembas login ai.example.org).")
NOT_LOGGED_IN_EDITOR = "this computer is not logged in to a LLeMbas server (lembas login <address>)"
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 | <branch>"}, "_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()