-- JSON-RPC 2.0 over lines on a child process's stdin and stdout: the framing ACP uses on stdio. local M = {} M.__index = M local MAX_LINE_BYTES = 64 * 1024 * 1024 -- a line that never ends is dropped, not kept 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 = {}, timers = {}, on = on, buf = "", err = "", closed = false }, M) local ok, proc = pcall(vim.system, cmd, { stdin = true, cwd = opts and opts.cwd or nil, env = opts and opts.env or nil, stdout = function(_, data) if data then self:_feed(data) end end, stderr = function(_, data) if data then 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 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 self.proc = proc return self end --- Bytes from the agent. A line longer than the reader keeps is dropped whole: what was read of --- it, and the rest of it up to its line break — never a message that merely follows it. The --- same reading as the VS Code extension's (vscode/src/rpc.js); tests/rules/rpc_lines.json. function M:_feed(data) self.buf = self.buf .. data while true do local nl = self.buf:find("\n", 1, true) if not nl then if #self.buf > (self.max_line or MAX_LINE_BYTES) then self.buf = "" self.dropping = true -- the rest of that line, when its end comes, is not a message end break end local line = self.buf:sub(1, nl - 1) self.buf = self.buf:sub(nl + 1) if self.dropping then self.dropping = false elseif 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) 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 function M:_message(msg) if msg.method then if msg.id ~= nil then local answered = false local function reply(result, err) if answered then return end answered = true if err then self:_write({ jsonrpc = "2.0", id = msg.id, error = err }) else self:_write({ jsonrpc = "2.0", id = msg.id, result = result == nil and vim.NIL or result }) end end local ok, e = pcall(self.on.request, msg.method, msg.params or {}, reply) if not ok then reply(nil, { code = -32603, message = tostring(e) }) end elseif self.on.notify then -- A notification has nobody to tell when it fails here: said where the agent's own words are kept. local ok, e = pcall(self.on.notify, msg.method, msg.params or {}) if not ok then self.err = (self.err .. "[editor] " .. tostring(msg.method) .. " was not taken in: " .. tostring(e):sub(1, 300) .. "\n"):sub(-MAX_ERR_BYTES) end end 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. `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 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