Compare commits
7
Commits
main
...
v1.0.0-beta.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d40919ea20
|
||
|
|
a756280868
|
||
|
|
3298f1260a
|
||
|
|
f09432c25b
|
||
|
|
0e2aac5462
|
||
|
|
3d548bbd73
|
||
|
|
ea5dd1b1b3
|
No files matched your search
+58
-1
@@ -1,6 +1,6 @@
|
||||
# Changelog
|
||||
|
||||
## [Unreleased]
|
||||
## [1.0.0-beta.1] — 2026-11-24
|
||||
|
||||
### Neovim plugin
|
||||
|
||||
@@ -12,3 +12,60 @@
|
||||
diagnostics shown on them. A typed message names the file you are in.
|
||||
- The CLI's approval cards are asked in the editor; closing one is a denial.
|
||||
- Files the agent changes are reloaded in buffers that have no changes of their own.
|
||||
- **Suggestions as you type, and on a key** (`<M-\>`), from the autocomplete model chosen on your
|
||||
server; `<Tab>` accepts. A newer keystroke cancels the request before it, and an answer for a place
|
||||
you have left is never drawn. `:LLeMbasAutocomplete` turns typing-time suggestions on and off.
|
||||
- **A rewrite is a proposal.** `:LLeMbasEdit` shows the result as changes in place, old lines marked
|
||||
and new lines beside them; `ga` / `gr` accept or reject the one under the cursor, `gA` / `gR` all.
|
||||
Nothing is written before you accept, and the buffer need not be saved.
|
||||
- **Two model settings**, saved in your account: `:LLeMbasAutocompleteModel` and `:LLeMbasMainModel`
|
||||
(chat and rewriting). With `!` the autocomplete model is switched for this editor only.
|
||||
- An approval that carries a diff shows it while the question is open.
|
||||
- The agent reads a file that is open here from its buffer, saved or not.
|
||||
- A file the agent shows is opened in the window you edit in; one that is not text is named in the
|
||||
chat and `:LLeMbasOpen` hands it to the system's viewer.
|
||||
- The editor's context (file, cursor, selection, diagnostics) goes to the agent as data.
|
||||
- These need a LLeMbas CLI with harness spec 3.11.0. With an older one the plugin works as before.
|
||||
|
||||
- The agent's write to a file that is open here goes into the buffer and is saved at once, so the
|
||||
buffer and the disk never part.
|
||||
- `<Tab>` is the plugin's only while a suggestion is on the screen; whatever you had mapped to it
|
||||
is yours the rest of the time. The same holds for `ga`, `gr`, `gA`, `gR` and a shown rewrite.
|
||||
- An approval lists the refusal first, so a digit and Enter typed while the question opens allows
|
||||
nothing.
|
||||
- `:LLeMbasOpen` hands the system only files that are looked at or listened to, never one that may run.
|
||||
- `:LLeMbasNew!` ends an agent whose turn hangs.
|
||||
|
||||
### Fixed (Neovim)
|
||||
|
||||
- A file the agent asked for could be answered from another open file whose name began the same.
|
||||
- Accepting a change after deleting one of its lines removed a line that was not part of it.
|
||||
- A reloaded file kept the changes proposed for its old text.
|
||||
- An agent that does not start was started again at every typing pause.
|
||||
|
||||
- Starting a new session could leave the plugin believing the new agent had stopped.
|
||||
|
||||
### VS Code / VSCodium extension
|
||||
|
||||
- First version, in `vscode/`: a client of `lembas serve --stdio`, like the Neovim plugin. Plain
|
||||
JavaScript with no dependencies and no build; `scripts/package-vscode.sh` writes the `.vsix`.
|
||||
- A chat in the side bar: the transcript, the session's mode and model, Stop, and a new session.
|
||||
The CLI's approval cards are answered there; one that carries an edit opens the change in the
|
||||
editor's diff view before you answer, and nothing is written until you allow it.
|
||||
- Ask about a selection: the file, the lines, the selected text as the editor has it and the
|
||||
problems shown there go with the question; a typed message carries the file in front.
|
||||
- Rewrite a selection: the result is proposed in the file as changes to accept or reject, one by
|
||||
one or all at once, and as a diff beside it. Nothing is written before you accept.
|
||||
- Autocomplete as inline suggestions, as you type and on `Alt+\`. Without an autocomplete model
|
||||
it says so once, with a button to choose one.
|
||||
- The two model settings, autocomplete and main: saved in your account, or switched for one
|
||||
window only.
|
||||
- A picture the agent shows appears in the chat; any other file is a line there. Open is offered
|
||||
only for kinds that are merely displayed (pictures, plain text, PDF, sound, video), and only
|
||||
when the file's bytes and its name agree; everything else can only be shown in its folder.
|
||||
Files of more than 64 MB are refused.
|
||||
- The agent reads a file you have open as the editor has it, saved or not, and a file it writes
|
||||
is put into the open document and saved.
|
||||
- What a model writes is drawn as text through the extension's own small Markdown reader: HTML in
|
||||
a reply stays text, and only `http`, `https` and `mailto` links open.
|
||||
However long or oddly written a reply is, reading it takes time in step with its length.
|
||||
@@ -1,13 +1,14 @@
|
||||
# LLeMbas IDE
|
||||
|
||||
LLeMbas in your editor: a Neovim plugin, and a VS Code / VSCodium extension (not written yet).
|
||||
LLeMbas in your editor: a Neovim plugin, and a VS Code / VSCodium extension.
|
||||
|
||||
Both are clients of the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI). The CLI is the agent:
|
||||
it holds the sign-in to your LLeMbas server, the models, the tools and the permissions. The editor
|
||||
starts `lembas serve --stdio` and talks to it over the Agent Client Protocol. Nothing about a server
|
||||
or a model is set in the editor.
|
||||
|
||||
This is a beta. It needs LLeMbas CLI 2.0.0-beta.12 or newer, signed in (`lembas login <address>`).
|
||||
This is a beta. It needs LLeMbas CLI 2.0.0-beta.14 or newer, signed in (`lembas login <address>`).
|
||||
With an older CLI only the chat, asking about a selection and approvals work.
|
||||
|
||||
## Neovim
|
||||
|
||||
@@ -33,7 +34,12 @@ vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }`
|
||||
|---|---|
|
||||
| `:LLeMbas` | open or close the chat panel |
|
||||
| `:'<,'>LLeMbasAsk [question]` | ask about the selected lines; without a question they go with the next message |
|
||||
| `:'<,'>LLeMbasEdit [instruction]` | have the selected lines rewritten (the file must be saved) |
|
||||
| `:'<,'>LLeMbasEdit [instruction]` | have the selected lines rewritten; shown as changes to accept (`ga`, `gA`) or reject (`gr`, `gR`) |
|
||||
| `:LLeMbasAccept[!]`, `:LLeMbasReject[!]` | the same from the command line (`!`: all) |
|
||||
| `:LLeMbasAutocomplete [on\|off]` | suggestions as you type |
|
||||
| `:LLeMbasAutocompleteModel[!] [model]` | the model that writes suggestions (`!`: this editor only; `-`: back to the default) |
|
||||
| `:LLeMbasMainModel [model]` | the model for chat and rewriting, saved in your account (`?` shows both) |
|
||||
| `:LLeMbasOpen` | open the file the agent showed last |
|
||||
| `:LLeMbasStop` | stop the running turn |
|
||||
| `:LLeMbasNew` | start a new session |
|
||||
| `:LLeMbasMode [mode]` | change the mode |
|
||||
@@ -42,13 +48,35 @@ vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }`
|
||||
In the prompt: Enter (normal mode) or Ctrl-S sends, Ctrl-C stops the turn, `q` closes the panel.
|
||||
Help: `:help llembas`.
|
||||
|
||||
Not there yet: completion as you type, a rewrite shown as a diff you accept or reject, picking an
|
||||
older session. In this version the agent changes files on disk itself, under the CLI's permissions.
|
||||
While typing, `<Tab>` accepts a suggestion and `<M-\>` asks for one; both keys can be changed in `setup`.
|
||||
|
||||
Suggestions, rewrites shown as changes, the model settings and shown files need a LLeMbas CLI with
|
||||
harness spec 3.11.0 (2.0.0-beta.14 or newer). With an older CLI the chat, asking about a selection and
|
||||
approvals work, and a rewrite is done by the agent on the saved file.
|
||||
|
||||
Not there yet: picking an older session, and the agent's questions and plans as cards.
|
||||
|
||||
## VS Code and VSCodium
|
||||
|
||||
Needs VS Code or VSCodium 1.85 or newer. The extension lives in `vscode/`; it is plain JavaScript
|
||||
with no dependencies, and is installed from a package you build with Node alone:
|
||||
|
||||
```sh
|
||||
scripts/package-vscode.sh # writes dist/llembas-<version>.vsix
|
||||
codium --install-extension dist/llembas-<version>.vsix # or: code --install-extension …
|
||||
```
|
||||
|
||||
A chat in the side bar, questions about a selection, a selection rewritten as changes you accept or
|
||||
reject, autocomplete as you type and on `Alt+\`, the two model settings, and pictures the agent
|
||||
shows. Commands, keys, settings and what is not there yet: [`vscode/README.md`](vscode/README.md).
|
||||
|
||||
## Tests
|
||||
|
||||
`scripts/test-nvim.sh` runs the plugin headless against a stand-in agent (needs `nvim` and `python3`).
|
||||
|
||||
`scripts/test-vscode.sh` runs the extension's parts that need no editor against a stand-in agent of
|
||||
its own, and checks the package (needs Node 18 or newer and `python3`). It does not start VS Code.
|
||||
|
||||
## Licence
|
||||
|
||||
MIT.
|
||||
+31
-3
@@ -17,9 +17,30 @@ COMMANDS *llembas-commands*
|
||||
Without a question the lines are attached to the next message you type.
|
||||
|
||||
:[range]LLeMbasEdit [instruction] *:LLeMbasEdit*
|
||||
Have the lines of [range] rewritten. The agent changes the file on disk
|
||||
under the CLI's permissions, so the buffer must be saved first; it is
|
||||
reloaded when the agent is done.
|
||||
Have the lines of [range] rewritten. The result is shown in place as
|
||||
changes: old lines marked, new lines beside them. Nothing is written
|
||||
until you accept. ga accepts the change under the cursor, gr rejects it,
|
||||
gA and gR do all. (With a LLeMbas CLI older than harness spec 3.11.0 the
|
||||
agent edits the saved file on disk instead.)
|
||||
|
||||
:LLeMbasAccept[!] :LLeMbasReject[!] *:LLeMbasAccept* *:LLeMbasReject*
|
||||
Accept or reject the change under the cursor; with ! all of them.
|
||||
|
||||
:LLeMbasAutocomplete [on|off] *:LLeMbasAutocomplete*
|
||||
Suggestions as you type. While typing, <Tab> accepts a shown suggestion
|
||||
and <M-\> asks for one now.
|
||||
|
||||
:LLeMbasAutocompleteModel[!] [model] *:LLeMbasAutocompleteModel*
|
||||
The model that writes suggestions, saved in your account; without a name,
|
||||
pick from the list. With ! it is switched for this editor only. "-" goes
|
||||
back to the default.
|
||||
|
||||
:LLeMbasMainModel [model] *:LLeMbasMainModel*
|
||||
The model for chat and rewriting, saved in your account. "?" shows both
|
||||
settings.
|
||||
|
||||
:LLeMbasOpen *:LLeMbasOpen*
|
||||
Open the file the agent showed last with the system's viewer.
|
||||
|
||||
:LLeMbasStop *:LLeMbasStop*
|
||||
Stop the running turn.
|
||||
@@ -43,6 +64,13 @@ SETUP *llembas-setup*
|
||||
model = nil, -- the model a session starts on
|
||||
show_thoughts = false, -- the model's thinking in the transcript
|
||||
send_open_file = true, -- a typed message names the file you are in
|
||||
complete = {
|
||||
auto = true, -- suggest as you type
|
||||
debounce_ms = 250, -- the pause before a suggestion is asked for
|
||||
model = nil, -- a model for this editor only
|
||||
accept = "<Tab>", -- accepts a shown suggestion
|
||||
trigger = "<M-\\>", -- asks for a suggestion now
|
||||
},
|
||||
})
|
||||
<
|
||||
What the model writes is shown as text. It is never run, and the panel's
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
-- Suggestions as you type, and on a key. The text comes from the LLeMbas CLI (`_lembas/complete`),
|
||||
-- which asks your server's autocomplete model. A suggestion is drawn as virtual text and becomes part
|
||||
-- of the buffer only when you accept it; what the model wrote is never run.
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace("llembas-complete")
|
||||
|
||||
local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false }
|
||||
|
||||
local PREFIX_MAX, SUFFIX_MAX = 16000, 4000
|
||||
|
||||
local function L() return require("llembas") end
|
||||
|
||||
--- Whether you are typing (insert mode). A function of its own so the tests, which cannot stay in
|
||||
--- insert mode in a headless run, can say yes.
|
||||
function M._typing() return vim.api.nvim_get_mode().mode:sub(1, 1) == "i" end
|
||||
|
||||
--- The accept key is ours only while a suggestion is on the screen: a buffer mapping put there with
|
||||
--- the suggestion and taken away with it, whatever was mapped before given back as it was.
|
||||
local function unmap_accept()
|
||||
local s = st.shown
|
||||
if not s or not s.key then return end
|
||||
pcall(vim.keymap.del, "i", s.key, { buffer = s.buf })
|
||||
if s.before and next(s.before) and s.before.buffer == 1 then pcall(vim.fn.mapset, "i", false, s.before) end
|
||||
end
|
||||
|
||||
function M.clear()
|
||||
if st.shown then
|
||||
unmap_accept()
|
||||
pcall(vim.api.nvim_buf_del_extmark, st.shown.buf, ns, st.shown.mark)
|
||||
st.shown = nil
|
||||
end
|
||||
end
|
||||
|
||||
local function cancel()
|
||||
if st.timer then st.timer:stop() end
|
||||
st.seq = st.seq + 1
|
||||
local conn = L()._state.conn
|
||||
if st.asked and conn then conn:notify("_lembas/complete/cancel", { id = st.asked }) end
|
||||
st.asked = nil
|
||||
end
|
||||
|
||||
local function show(buf, row, col, text)
|
||||
M.clear()
|
||||
local lines = vim.split(text, "\n", { plain = true })
|
||||
local opts = { virt_text = { { lines[1], "Comment" } }, virt_text_pos = "inline" }
|
||||
if #lines > 1 then
|
||||
opts.virt_lines = {}
|
||||
for i = 2, #lines do opts.virt_lines[#opts.virt_lines + 1] = { { lines[i], "Comment" } } end
|
||||
end
|
||||
st.shown = { buf = buf, text = text, mark = vim.api.nvim_buf_set_extmark(buf, ns, row, col, opts) }
|
||||
local key = L().config.complete.accept
|
||||
if key and key ~= "" then
|
||||
local before = vim.fn.maparg(key, "i", false, true)
|
||||
st.shown.key, st.shown.before = key, before
|
||||
vim.keymap.set("i", key, function() M.accept() end, { buffer = buf, nowait = true, desc = "LLeMbas: accept the suggestion" })
|
||||
end
|
||||
end
|
||||
|
||||
local function usable(buf)
|
||||
return vim.bo[buf].buftype == "" and vim.bo[buf].modifiable
|
||||
end
|
||||
|
||||
--- Ask for a suggestion at the cursor now. `manual`: you pressed the key, so say why nothing came.
|
||||
function M.request(manual)
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
if not usable(buf) then return end
|
||||
local win = vim.api.nvim_get_current_win()
|
||||
local pos = vim.api.nvim_win_get_cursor(win)
|
||||
local row, col = pos[1] - 1, pos[2]
|
||||
local line = vim.api.nvim_buf_get_lines(buf, row, row + 1, false)[1] or ""
|
||||
local before = vim.api.nvim_buf_get_lines(buf, math.max(0, row - 400), row, false)
|
||||
local after = vim.api.nvim_buf_get_lines(buf, row + 1, row + 100, false)
|
||||
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
|
||||
cancel()
|
||||
local seq = st.seq
|
||||
L()._connect(function(conn)
|
||||
if seq ~= st.seq then return end
|
||||
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
|
||||
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
|
||||
return
|
||||
end
|
||||
local id = ("c%d"):format(seq)
|
||||
st.asked = id
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
conn:request("_lembas/complete", {
|
||||
id = id, prefix = prefix, suffix = suffix, path = name ~= "" and name or nil,
|
||||
language = vim.bo[buf].filetype ~= "" and vim.bo[buf].filetype or nil,
|
||||
model = L().config.complete.model,
|
||||
}, function(err, r)
|
||||
if st.asked == id then st.asked = nil end
|
||||
if seq ~= st.seq then return end
|
||||
if err then
|
||||
-- Asked on every pause, so a refusal is said once and the asking stops until you choose.
|
||||
st.off = tostring(err.message)
|
||||
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)
|
||||
end
|
||||
return
|
||||
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, not manual)
|
||||
end
|
||||
|
||||
--- Put the shown suggestion into the buffer. False when none is shown.
|
||||
function M.accept()
|
||||
local s = st.shown
|
||||
if not s or s.buf ~= vim.api.nvim_get_current_buf() then return false end
|
||||
-- Where the suggestion stands now: its mark moves with the text around it.
|
||||
local pos = vim.api.nvim_buf_get_extmark_by_id(s.buf, ns, s.mark, {})
|
||||
M.clear()
|
||||
st.seq = st.seq + 1
|
||||
if not pos[1] then return false end
|
||||
local at_row, at_col = pos[1], pos[2]
|
||||
local lines = vim.split(s.text, "\n", { plain = true })
|
||||
vim.api.nvim_buf_set_text(s.buf, at_row, at_col, at_row, at_col, lines)
|
||||
local row = at_row + #lines
|
||||
local col = #lines == 1 and (at_col + #lines[1]) or #lines[#lines]
|
||||
vim.api.nvim_win_set_cursor(0, { row, col })
|
||||
return true
|
||||
end
|
||||
|
||||
function M.visible() return st.shown ~= nil end
|
||||
|
||||
--- Suggestions as you type: on, off, or the other of the two.
|
||||
function M.auto(on)
|
||||
local c = L().config.complete
|
||||
if on == nil then c.auto = not c.auto else c.auto = on end
|
||||
if c.auto then st.off, st.said = nil, false else M.clear(); cancel() end
|
||||
return c.auto
|
||||
end
|
||||
|
||||
--- A model was chosen: ask again.
|
||||
function M.reset() st.off, st.said = nil, false end
|
||||
|
||||
local function typed()
|
||||
M.clear()
|
||||
local c = L().config.complete
|
||||
if not c.auto or st.off or (st.wait_until and vim.uv.now() < st.wait_until) then return cancel() end
|
||||
if not usable(vim.api.nvim_get_current_buf()) then return end
|
||||
cancel()
|
||||
st.timer = st.timer or vim.uv.new_timer()
|
||||
st.timer:start(c.debounce_ms, 0, vim.schedule_wrap(function()
|
||||
if M._typing() then M.request(false) end
|
||||
end))
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
local group = vim.api.nvim_create_augroup("llembas-complete", { clear = true })
|
||||
vim.api.nvim_create_autocmd({ "TextChangedI", "CursorMovedI" }, { group = group, callback = typed })
|
||||
vim.api.nvim_create_autocmd({ "InsertLeave", "BufLeave" }, { group = group, callback = function() M.clear(); cancel() end })
|
||||
local c = L().config.complete
|
||||
if c.trigger and c.trigger ~= "" then
|
||||
vim.keymap.set("i", c.trigger, function() M.request(true) end, { desc = "LLeMbas: suggest here" })
|
||||
end
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -50,4 +50,80 @@ function M.file(buf)
|
||||
vim.fn.fnamemodify(name, ":."), row, vim.bo[buf].modified and " (the buffer has changes that are not saved)" or "") }
|
||||
end
|
||||
|
||||
--- The same as data, for an agent that takes it so (`_meta.lembas.editor`): the file, the cursor, and
|
||||
--- with `first..last` the selection with its text and the diagnostics on it. Lines are 1-based, inclusive.
|
||||
function M.editor(buf, first, last)
|
||||
local _, name = uri_of(buf)
|
||||
local out = {}
|
||||
if name then out.path = name end
|
||||
local win = vim.fn.bufwinid(buf)
|
||||
if win ~= -1 then out.cursor = { line = vim.api.nvim_win_get_cursor(win)[1] } end
|
||||
if first and last then
|
||||
out.selection = { path = name, start = first, ["end"] = last,
|
||||
text = table.concat(vim.api.nvim_buf_get_lines(buf, first - 1, last, false), "\n") }
|
||||
local diags = {}
|
||||
for _, d in ipairs(vim.diagnostic.get(buf)) do
|
||||
local l = d.lnum + 1
|
||||
if l >= first and l <= last and #diags < 30 then
|
||||
diags[#diags + 1] = { path = name, line = l, severity = (vim.diagnostic.severity[d.severity] or "INFO"):lower(),
|
||||
message = (d.message:gsub("%s+", " ")), source = d.source }
|
||||
end
|
||||
end
|
||||
if #diags > 0 then out.diagnostics = diags end
|
||||
end
|
||||
if next(out) == nil then return nil end
|
||||
return out
|
||||
end
|
||||
|
||||
--- The loaded buffer that holds exactly this file, or nil. By the full name, never by a pattern:
|
||||
--- `README` must not find `README.md`.
|
||||
function M.buffer_of(path)
|
||||
local want = vim.fs.normalize(vim.fn.fnamemodify(path, ":p"))
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
if vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then
|
||||
local name = vim.api.nvim_buf_get_name(b)
|
||||
if name ~= "" and vim.fs.normalize(name) == want then return b end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
--- 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.
|
||||
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
|
||||
local buf = M.buffer_of(path)
|
||||
if not buf then return reply(nil, { code = -32002, message = "not open in the editor" }) 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
|
||||
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
|
||||
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.
|
||||
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 buf = M.buffer_of(path)
|
||||
if buf then
|
||||
lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
|
||||
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
|
||||
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") })
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -0,0 +1,217 @@
|
||||
-- Changes shown before they are made: a rewrite of a selection as hunks you accept or reject, and the
|
||||
-- diff of an edit the agent asks permission for. What the model wrote is only ever put into a buffer
|
||||
-- as text, and only when you accept it.
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace("llembas-diff")
|
||||
|
||||
local proposals = {} -- buf -> list of pending hunks { mark, old_count, new, above }
|
||||
|
||||
local function count(buf) return #(proposals[buf] or {}) end
|
||||
|
||||
local KEYS = { "ga", "gr", "gA", "gR" }
|
||||
local saved = {} -- buf -> the buffer mappings these keys had before
|
||||
|
||||
local function unmap(buf)
|
||||
for _, k in ipairs(KEYS) do pcall(vim.keymap.del, "n", k, { buffer = buf }) end
|
||||
for _, before in ipairs(saved[buf] or {}) do pcall(vim.fn.mapset, "n", false, before) end
|
||||
saved[buf] = nil
|
||||
end
|
||||
|
||||
local function drop(buf, hunk)
|
||||
pcall(vim.api.nvim_buf_del_extmark, buf, ns, hunk.mark)
|
||||
if hunk.mark2 then pcall(vim.api.nvim_buf_del_extmark, buf, ns, hunk.mark2) end
|
||||
local list = proposals[buf] or {}
|
||||
for i, h in ipairs(list) do if h == hunk then table.remove(list, i) break end end
|
||||
if #list == 0 then
|
||||
proposals[buf] = nil
|
||||
unmap(buf)
|
||||
end
|
||||
end
|
||||
|
||||
local function row_of(buf, hunk)
|
||||
local pos = vim.api.nvim_buf_get_extmark_by_id(buf, ns, hunk.mark, {})
|
||||
return pos[1]
|
||||
end
|
||||
|
||||
local function apply(buf, hunk)
|
||||
local pos = vim.api.nvim_buf_get_extmark_by_id(buf, ns, hunk.mark, { details = true })
|
||||
local row = pos[1]
|
||||
if not row then return drop(buf, hunk) end
|
||||
if hunk.old_count > 0 then
|
||||
-- What the mark covers now, not what it covered when shown: lines you removed since are not removed twice.
|
||||
local last = (pos[3] or {}).end_row or row
|
||||
if last <= row then
|
||||
drop(buf, hunk)
|
||||
return vim.notify("LLeMbas: the lines of that change are gone; it was dropped", vim.log.levels.WARN)
|
||||
end
|
||||
vim.api.nvim_buf_set_lines(buf, row, last, false, hunk.new)
|
||||
elseif hunk.above then
|
||||
vim.api.nvim_buf_set_lines(buf, row, row, false, hunk.new)
|
||||
else
|
||||
vim.api.nvim_buf_set_lines(buf, row + 1, row + 1, false, hunk.new)
|
||||
end
|
||||
drop(buf, hunk)
|
||||
end
|
||||
|
||||
--- The pending hunk the cursor is on, else the next one below, else the last.
|
||||
local function nearest(buf)
|
||||
local list = proposals[buf] or {}
|
||||
local cur = vim.api.nvim_win_get_cursor(0)[1] - 1
|
||||
local best
|
||||
for _, h in ipairs(list) do
|
||||
local row = row_of(buf, h)
|
||||
if row then
|
||||
if cur >= row and cur < row + math.max(h.old_count, 1) then return h end
|
||||
if row >= cur and (not best or row < row_of(buf, best)) then best = h end
|
||||
end
|
||||
end
|
||||
return best or list[#list]
|
||||
end
|
||||
|
||||
function M.accept(all)
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
if all then
|
||||
-- From the bottom up, so no accepted hunk moves one still waiting above it by more than its mark knows.
|
||||
local list = vim.list_slice(proposals[buf] or {})
|
||||
table.sort(list, function(a, b) return (row_of(buf, a) or 0) > (row_of(buf, b) or 0) end)
|
||||
for _, h in ipairs(list) do apply(buf, h) end
|
||||
else
|
||||
local h = nearest(buf)
|
||||
if h then apply(buf, h) end
|
||||
end
|
||||
end
|
||||
|
||||
function M.reject(all)
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
if all then
|
||||
for _, h in ipairs(vim.list_slice(proposals[buf] or {})) do drop(buf, h) end
|
||||
else
|
||||
local h = nearest(buf)
|
||||
if h then drop(buf, h) end
|
||||
end
|
||||
end
|
||||
|
||||
function M.pending(buf) return count(buf or vim.api.nvim_get_current_buf()) end
|
||||
|
||||
local function virt(lines)
|
||||
local out = {}
|
||||
for _, l in ipairs(lines) do out[#out + 1] = { { l == "" and " " or l, "DiffAdd" } } end
|
||||
return out
|
||||
end
|
||||
|
||||
--- Show `new` (a list of lines) as a proposed replacement of lines `first..last` of `buf`, hunk by hunk.
|
||||
--- Returns the number of hunks (0: nothing would change).
|
||||
function M.propose(buf, first, last, new)
|
||||
local old = vim.api.nvim_buf_get_lines(buf, first - 1, last, false)
|
||||
local hunks = vim.diff(table.concat(old, "\n") .. "\n", table.concat(new, "\n") .. "\n", { result_type = "indices" })
|
||||
if #hunks == 0 then return 0 end
|
||||
proposals[buf] = proposals[buf] or {}
|
||||
for _, h in ipairs(hunks) do
|
||||
local a_start, a_count, b_start, b_count = h[1], h[2], h[3], h[4]
|
||||
local lines = vim.list_slice(new, b_start, b_start + b_count - 1)
|
||||
local hunk = { old_count = a_count, new = lines }
|
||||
if a_count > 0 then
|
||||
local row = first - 1 + a_start - 1
|
||||
hunk.mark = vim.api.nvim_buf_set_extmark(buf, ns, row, 0, {
|
||||
end_row = row + a_count, hl_group = "DiffDelete", hl_eol = true, right_gravity = false })
|
||||
if #lines > 0 then
|
||||
hunk.mark2 = vim.api.nvim_buf_set_extmark(buf, ns, row + a_count - 1, 0, { virt_lines = virt(lines) })
|
||||
end
|
||||
else
|
||||
-- Lines added and none taken away: after old line `a_start`, or above the first when it is 0.
|
||||
local row = first - 1 + a_start - 1
|
||||
hunk.above = a_start == 0
|
||||
if hunk.above then row = first - 1 end
|
||||
row = math.min(math.max(row, 0), math.max(vim.api.nvim_buf_line_count(buf) - 1, 0))
|
||||
hunk.mark = vim.api.nvim_buf_set_extmark(buf, ns, row, 0, {
|
||||
virt_lines = virt(lines), virt_lines_above = hunk.above, right_gravity = false })
|
||||
end
|
||||
table.insert(proposals[buf], hunk)
|
||||
end
|
||||
if not saved[buf] then
|
||||
saved[buf] = {}
|
||||
for _, k in ipairs(KEYS) do
|
||||
local before = vim.fn.maparg(k, "n", false, true)
|
||||
if next(before) and before.buffer == 1 then table.insert(saved[buf], before) end
|
||||
end
|
||||
end
|
||||
local function map(k, fn, desc) vim.keymap.set("n", k, fn, { buffer = buf, desc = desc, nowait = true }) end
|
||||
map("ga", function() M.accept(false) end, "LLeMbas: accept this change")
|
||||
map("gr", function() M.reject(false) end, "LLeMbas: reject this change")
|
||||
map("gA", function() M.accept(true) end, "LLeMbas: accept all changes")
|
||||
map("gR", function() M.reject(true) end, "LLeMbas: reject all changes")
|
||||
return #hunks
|
||||
end
|
||||
|
||||
--- A buffer was reloaded from disk: what was proposed for its old text is void.
|
||||
function M.forget(buf)
|
||||
for _, h in ipairs(vim.list_slice(proposals[buf] or {})) do drop(buf, h) end
|
||||
end
|
||||
|
||||
local written = 0
|
||||
--- The agent says how far a rewrite has got.
|
||||
function M.delta(params)
|
||||
written = written + #(params.delta or "")
|
||||
vim.api.nvim_echo({ { ("LLeMbas is rewriting… %d characters"):format(written), "Comment" } }, false, {})
|
||||
end
|
||||
|
||||
--- Have lines `first..last` rewritten as `instruction` says, and show the result as hunks.
|
||||
function M.rewrite(buf, first, last, instruction)
|
||||
local L = require("llembas")
|
||||
if count(buf) > 0 then
|
||||
return vim.notify("LLeMbas: accept or reject the changes shown first (ga / gr, gA / gR)", vim.log.levels.WARN)
|
||||
end
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
local text = vim.api.nvim_buf_get_lines(buf, first - 1, last, false)
|
||||
local before = vim.api.nvim_buf_get_lines(buf, math.max(0, first - 41), first - 1, false)
|
||||
local after = vim.api.nvim_buf_get_lines(buf, last, last + 40, false)
|
||||
local tick = vim.api.nvim_buf_get_changedtick(buf)
|
||||
written = 0
|
||||
vim.api.nvim_echo({ { "LLeMbas is rewriting…", "Comment" } }, false, {})
|
||||
L._connect(function(conn)
|
||||
if not conn then return vim.notify("LLeMbas: the agent did not start", vim.log.levels.ERROR) end
|
||||
conn:request("_lembas/edit", {
|
||||
id = ("e%d"):format(tick), cwd = vim.fn.getcwd(), sessionId = L._state.session, path = name,
|
||||
text = table.concat(text, "\n"), before = table.concat(before, "\n"), after = table.concat(after, "\n"),
|
||||
language = vim.bo[buf].filetype, instruction = instruction, model = L.config.model,
|
||||
}, function(err, r)
|
||||
vim.api.nvim_echo({ { "" } }, false, {})
|
||||
if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end
|
||||
if 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)
|
||||
end
|
||||
local new = vim.split(((r or {}).text or ""):gsub("\r\n", "\n"), "\n", { plain = true })
|
||||
if new[#new] == "" and #new > 1 then table.remove(new) end
|
||||
local n = M.propose(buf, first, last, new)
|
||||
if n == 0 then return vim.notify("LLeMbas: the rewrite changes nothing", vim.log.levels.INFO) end
|
||||
vim.notify(("LLeMbas: %d change%s shown. ga accepts, gr rejects, gA / gR all."):format(n, n == 1 and "" or "s"), vim.log.levels.INFO)
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
--- An approval card that carries diffs (ACP `diff` content): shown in a window of its own while the
|
||||
--- question is open. Returns a function that closes it, or nil when there was nothing to show.
|
||||
function M.preview(content)
|
||||
local out = {}
|
||||
for _, c in ipairs(content or {}) do
|
||||
if type(c) == "table" and c.type == "diff" and type(c.newText) == "string" then
|
||||
out[#out + 1] = "--- " .. (tostring(c.path or "?"):gsub("[\r\n]+", " "))
|
||||
local d = vim.diff((c.oldText or "") .. "\n", c.newText .. "\n", { result_type = "unified", ctxlen = 3 })
|
||||
vim.list_extend(out, vim.split(d ~= "" and d or "(no change)", "\n", { plain = true, trimempty = true }))
|
||||
end
|
||||
end
|
||||
if #out == 0 then return nil end
|
||||
local back = vim.api.nvim_get_current_win()
|
||||
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.api.nvim_buf_set_lines(b, 0, -1, false, out)
|
||||
vim.bo[b].filetype, vim.bo[b].modifiable = "diff", false
|
||||
vim.cmd("botright " .. math.min(#out + 1, 18) .. "split")
|
||||
local w = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(w, b)
|
||||
if vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back) end
|
||||
return function() if vim.api.nvim_win_is_valid(w) then pcall(vim.api.nvim_win_close, w, true) end end
|
||||
end
|
||||
|
||||
return M
|
||||
+255
-62
@@ -14,10 +14,17 @@ M.config = {
|
||||
model = nil, -- the model a session starts on (the CLI's own when nil)
|
||||
show_thoughts = false, -- the model's thinking in the transcript
|
||||
send_open_file = true, -- a prompt names the file you are in
|
||||
complete = {
|
||||
auto = true, -- suggest as you type (needs an autocomplete model on the server)
|
||||
debounce_ms = 250, -- how long you must pause before a suggestion is asked for
|
||||
model = nil, -- a quick switch for this editor only; nil: your saved choice
|
||||
accept = "<Tab>", -- accepts a shown suggestion; falls through when none is shown
|
||||
trigger = "<M-\\>", -- asks for a suggestion now
|
||||
},
|
||||
}
|
||||
|
||||
local S = { conn = nil, session = nil, starting = nil, busy = false, modes = {}, mode = nil, model = nil,
|
||||
attached = nil, attached_label = nil, last_buf = nil, said = nil }
|
||||
local S = { conn = nil, session = nil, starting = nil, connecting = nil, ready = false, caps = {}, busy = false,
|
||||
modes = {}, mode = nil, model = nil, attached = nil, attached_label = nil, last_buf = nil, said = nil }
|
||||
|
||||
local function note(text) chat.newline(); chat.append("> " .. text .. "\n") end
|
||||
|
||||
@@ -74,12 +81,23 @@ local function on_permission(p, reply)
|
||||
local meta = (p._meta or {}).lembas or {}
|
||||
local options = p.options or {}
|
||||
chat.line("ask:" .. tostring(call.toolCallId), "- ? " .. (call.title or meta.tool or "a tool") .. " (waits for your answer)")
|
||||
local preview = require("llembas.diff").preview(call.content)
|
||||
local prompt = "LLeMbas asks: " .. (call.title or meta.tool or "a tool")
|
||||
if meta.reason then prompt = prompt .. " (" .. meta.reason .. ")" end
|
||||
-- The refusals first: the question can open while you are typing, and a digit and Enter meant for
|
||||
-- your code must not allow a command. The first choice is always a denial.
|
||||
options = vim.list_slice(options)
|
||||
table.sort(options, function(x, y)
|
||||
local dx, dy = tostring(x.kind):match("^reject") and 0 or 1, tostring(y.kind):match("^reject") and 0 or 1
|
||||
return dx < dy
|
||||
end)
|
||||
pcall(vim.cmd, "stopinsert")
|
||||
pcall(vim.cmd, "redraw")
|
||||
vim.ui.select(options, {
|
||||
prompt = prompt:gsub("[\r\n]+", " "):sub(1, 400),
|
||||
format_item = function(o) return o.name or o.optionId end,
|
||||
}, function(choice)
|
||||
if preview then preview() end
|
||||
if not choice then
|
||||
chat.line("ask:" .. tostring(call.toolCallId), "- ✗ " .. (call.title or "a tool") .. " (not answered: denied)")
|
||||
return reply({ outcome = { outcome = "cancelled" } })
|
||||
@@ -90,9 +108,11 @@ local function on_permission(p, reply)
|
||||
end
|
||||
|
||||
local function stopped(code, stderr)
|
||||
local was = S.conn ~= nil or S.starting ~= nil
|
||||
local was = S.session ~= nil or S.starting ~= nil
|
||||
local waiting = S.starting
|
||||
S.conn, S.session, S.starting, S.busy = nil, nil, nil, false
|
||||
local connecting = S.connecting
|
||||
S.conn, S.session, S.starting, S.connecting, S.ready, S.busy = nil, nil, nil, nil, false, false
|
||||
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
|
||||
@@ -102,64 +122,95 @@ local function stopped(code, stderr)
|
||||
status()
|
||||
end
|
||||
|
||||
--- Have a running agent that has answered `initialize`, then call `cb(true)`; `cb(false)` when not.
|
||||
--- `quiet`: a failure is not written into the chat (completion asks often and must not nag).
|
||||
local function connect(cb, quiet)
|
||||
if S.conn and S.ready then return cb(true) end
|
||||
if S.connecting then S.connecting[#S.connecting + 1] = cb; return end
|
||||
S.connecting = { cb }
|
||||
local function done(ok)
|
||||
local waiting = S.connecting or {}
|
||||
S.connecting = nil
|
||||
for _, f in ipairs(waiting) do f(ok) end
|
||||
end
|
||||
local me = {}
|
||||
local conn, err = rpc.start(M.config.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) end
|
||||
end,
|
||||
request = function(method, params, reply)
|
||||
if method == "session/request_permission" then return on_permission(params, reply) end
|
||||
if method == "fs/read_text_file" then return require("llembas.context").read_for_agent(params, reply) end
|
||||
if method == "_lembas/show" then return M._show(params, reply) end
|
||||
if method == "fs/write_text_file" then return require("llembas.context").write_for_agent(params, reply) end
|
||||
reply(nil, { code = -32601, message = "Method not found: " .. method })
|
||||
end,
|
||||
-- Only the agent in use: one that was replaced (a new session) ends later and must not undo its successor.
|
||||
exit = function(code, stderr) if S.conn == me.conn then stopped(code, stderr) end end,
|
||||
}, { cwd = vim.fn.getcwd() })
|
||||
if not conn then
|
||||
if not quiet then note(("Could not start %s: %s"):format(M.config.cmd[1], err)) end
|
||||
S.start_error = ("could not start %s: %s"):format(M.config.cmd[1], err)
|
||||
return done(false)
|
||||
end
|
||||
me.conn = conn
|
||||
S.conn, S.ready, S.start_error = conn, false, nil
|
||||
conn:request("initialize", {
|
||||
protocolVersion = 1,
|
||||
clientCapabilities = { fs = { readTextFile = true, writeTextFile = true },
|
||||
_meta = { lembas = { 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)) end
|
||||
S.conn = nil
|
||||
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
|
||||
done(true)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Have a running agent and an open session, then call `cb(true)`; `cb(false)` when that failed.
|
||||
local function ensure(cb)
|
||||
if S.session then return cb(true) end
|
||||
if S.starting then S.starting[#S.starting + 1] = cb; return end
|
||||
S.starting = { cb }
|
||||
local function fail(what)
|
||||
note(what)
|
||||
local conn = S.conn
|
||||
local function finish(ok)
|
||||
local waiting = S.starting or {}
|
||||
S.conn, S.starting, S.session = nil, nil, nil
|
||||
if conn then conn:stop() end
|
||||
for _, f in ipairs(waiting) do f(false) end
|
||||
end
|
||||
local conn, err = rpc.start(M.config.cmd, {
|
||||
notify = function(method, params)
|
||||
if method == "session/update" and params.sessionId == S.session then on_update(params.update or {}) end
|
||||
end,
|
||||
request = function(method, params, reply)
|
||||
if method == "session/request_permission" then return on_permission(params, reply) end
|
||||
reply(nil, { code = -32601, message = "Method not found: " .. method })
|
||||
end,
|
||||
exit = stopped,
|
||||
}, { cwd = vim.fn.getcwd() })
|
||||
if not conn then
|
||||
S.starting = nil
|
||||
note(("Could not start %s: %s"):format(M.config.cmd[1], err))
|
||||
return cb(false)
|
||||
for _, f in ipairs(waiting) do f(ok) end
|
||||
end
|
||||
S.conn = conn
|
||||
conn:request("initialize", { protocolVersion = 1, clientCapabilities = {},
|
||||
clientInfo = { name = "llembas.nvim", version = M.version } }, function(e1)
|
||||
if S.conn ~= conn then return end
|
||||
if e1 then return fail("The agent refused to start: " .. tostring(e1.message)) end
|
||||
connect(function(ok)
|
||||
if not ok then return finish(false) end
|
||||
local conn = S.conn
|
||||
local meta = {}
|
||||
if M.config.mode then meta.mode = M.config.mode end
|
||||
if M.config.model then meta.model = M.config.model end
|
||||
conn:request("session/new", { cwd = vim.fn.getcwd(), mcpServers = {}, _meta = meta }, function(e2, r)
|
||||
if S.conn ~= conn then return end
|
||||
if e2 then return fail("No session: " .. tostring(e2.message)) end
|
||||
if S.conn ~= conn then return finish(false) end
|
||||
if e2 then
|
||||
note("No session: " .. tostring(e2.message))
|
||||
return finish(false)
|
||||
end
|
||||
S.session = r.sessionId
|
||||
S.modes = (r.modes and r.modes.availableModes) or {}
|
||||
local lm = (r._meta or {}).lembas or {}
|
||||
S.mode = (r.modes and r.modes.currentModeId) or lm.mode
|
||||
S.model = lm.model
|
||||
local waiting = S.starting or {}
|
||||
S.starting = nil
|
||||
status()
|
||||
for _, f in ipairs(waiting) do f(true) end
|
||||
finish(true)
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Send `blocks` as a prompt; `shown` is what the transcript says you wrote.
|
||||
local function send(blocks, shown)
|
||||
if S.busy then
|
||||
vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN)
|
||||
return false
|
||||
end
|
||||
local function send(blocks, shown, meta)
|
||||
chat.section("You")
|
||||
chat.append(shown .. "\n")
|
||||
S.said = "you"
|
||||
@@ -167,7 +218,7 @@ local function send(blocks, shown)
|
||||
status()
|
||||
ensure(function(ok)
|
||||
if not ok then S.busy = false; status(); return end
|
||||
S.conn:request("session/prompt", { sessionId = S.session, prompt = blocks }, function(err, r)
|
||||
S.conn:request("session/prompt", { sessionId = S.session, prompt = blocks, _meta = meta }, function(err, r)
|
||||
S.busy = false
|
||||
if err then note("The turn failed: " .. tostring(err.message))
|
||||
elseif r and r.stopReason and r.stopReason ~= "end_turn" then note("The turn ended: " .. r.stopReason) end
|
||||
@@ -185,20 +236,35 @@ local function editing_buf()
|
||||
if S.last_buf and vim.api.nvim_buf_is_valid(S.last_buf) then return S.last_buf end
|
||||
end
|
||||
|
||||
--- A prompt typed in the panel: with what was attached, or else the name of the open file.
|
||||
--- A prompt typed in the panel: with what was attached, or else the name of the open file. An agent
|
||||
--- that takes the editor's context as data (`editor`) gets it so; an older one is told in a sentence.
|
||||
local function send_typed(text)
|
||||
local blocks, shown = {}, text
|
||||
if S.attached then
|
||||
vim.list_extend(blocks, S.attached)
|
||||
shown = ("[%s]\n%s"):format(S.attached_label, text)
|
||||
elseif M.config.send_open_file and not text:match("^/") then
|
||||
local b = editing_buf()
|
||||
local f = b and context.file(b)
|
||||
if f then blocks[#blocks + 1] = f end
|
||||
if S.busy then
|
||||
vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN)
|
||||
return false
|
||||
end
|
||||
blocks[#blocks + 1] = { type = "text", text = text }
|
||||
if send(blocks, shown) == false then return false end
|
||||
local attached, label = S.attached, S.attached_label
|
||||
S.attached, S.attached_label = nil, nil
|
||||
S.busy = true
|
||||
connect(function()
|
||||
local blocks, shown, meta = {}, text, nil
|
||||
if attached then
|
||||
shown = ("[%s]\n%s"):format(label, text)
|
||||
if S.caps.editor and attached.editor then meta = { lembas = { editor = attached.editor } }
|
||||
else vim.list_extend(blocks, attached.blocks) end
|
||||
elseif M.config.send_open_file and not text:match("^/") then
|
||||
local b = editing_buf()
|
||||
if b and S.caps.editor then
|
||||
local e = context.editor(b)
|
||||
if e then meta = { lembas = { editor = e } } end
|
||||
else
|
||||
local f = b and context.file(b)
|
||||
if f then blocks[#blocks + 1] = f end
|
||||
end
|
||||
end
|
||||
blocks[#blocks + 1] = { type = "text", text = text }
|
||||
send(blocks, shown, meta)
|
||||
end, true)
|
||||
status()
|
||||
end
|
||||
|
||||
@@ -224,14 +290,13 @@ end
|
||||
--- the lines are attached to the next message you type.
|
||||
function M.ask(first, last, question)
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
local blocks = context.selection(buf, first, last)
|
||||
local what = label(buf, first, last)
|
||||
S.attached = { blocks = context.selection(buf, first, last), editor = context.editor(buf, first, last) }
|
||||
S.attached_label = what
|
||||
if question and question:match("%S") then
|
||||
M.open(false)
|
||||
blocks[#blocks + 1] = { type = "text", text = question }
|
||||
send(blocks, ("[%s]\n%s"):format(what, question))
|
||||
send_typed(question)
|
||||
else
|
||||
S.attached, S.attached_label = blocks, what
|
||||
M.open(true)
|
||||
end
|
||||
end
|
||||
@@ -243,14 +308,22 @@ function M.edit(first, last, instruction)
|
||||
if vim.api.nvim_buf_get_name(buf) == "" or vim.bo[buf].buftype ~= "" then
|
||||
return vim.notify("LLeMbas: this buffer is not a file", vim.log.levels.WARN)
|
||||
end
|
||||
if vim.bo[buf].modified then
|
||||
return vim.notify("LLeMbas: save the file first (the agent edits the file on disk)", vim.log.levels.WARN)
|
||||
end
|
||||
if not instruction or not instruction:match("%S") then
|
||||
return vim.ui.input({ prompt = "Rewrite the selection: " }, function(text)
|
||||
if text and text:match("%S") then M.edit(first, last, text) end
|
||||
end)
|
||||
end
|
||||
if not S.ready then
|
||||
-- Which way a rewrite goes depends on what the agent can do, known once it has started.
|
||||
return connect(function(ok) if ok then M.edit(first, last, instruction) end end)
|
||||
end
|
||||
if S.caps.editor then return require("llembas.diff").rewrite(buf, first, last, instruction) end
|
||||
if vim.bo[buf].modified then
|
||||
return vim.notify("LLeMbas: save the file first (this LLeMbas CLI edits the file on disk)", vim.log.levels.WARN)
|
||||
end
|
||||
if S.busy then
|
||||
return vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN)
|
||||
end
|
||||
local blocks = context.selection(buf, first, last)
|
||||
blocks[#blocks + 1] = { type = "text", text =
|
||||
"Rewrite exactly those lines of that file as asked below. Change nothing outside them unless the request "
|
||||
@@ -265,10 +338,13 @@ function M.stop()
|
||||
end
|
||||
|
||||
--- A new session; the old one stays in the CLI's store.
|
||||
function M.new()
|
||||
if S.busy then return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop)", vim.log.levels.WARN) end
|
||||
function M.new(force)
|
||||
if S.busy and not force then
|
||||
return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop), or :LLeMbasNew! to end the agent", vim.log.levels.WARN)
|
||||
end
|
||||
S.busy = false
|
||||
local conn = S.conn
|
||||
S.conn, S.session, S.starting, S.said = nil, nil, nil, nil
|
||||
S.conn, S.session, S.starting, S.connecting, S.ready, S.said = nil, nil, nil, nil, false, nil
|
||||
tools = {}
|
||||
if conn then conn:stop() end
|
||||
chat.clear()
|
||||
@@ -303,13 +379,126 @@ function M.model(name)
|
||||
end)
|
||||
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
|
||||
if type(path) ~= "string" or path == "" then return reply({ shown = false, reason = "no path" }) end
|
||||
if not path:match("^/") then path = vim.fn.getcwd() .. "/" .. 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 ""]
|
||||
S.shown = path
|
||||
local rel = vim.fn.fnamemodify(path, ":.")
|
||||
if texty then
|
||||
local target
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
if vim.bo[vim.api.nvim_win_get_buf(w)].buftype == "" then target = w break end
|
||||
end
|
||||
if target then
|
||||
vim.api.nvim_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)
|
||||
else
|
||||
chat.line("show:" .. tostring(p.toolCallId), ("- shown: %s (%s) — :LLeMbasOpen opens it"):format(rel, tostring(p.kind or "file")))
|
||||
end
|
||||
S.said = "tool"
|
||||
reply({ shown = true })
|
||||
end
|
||||
|
||||
--- Open the file the agent showed last with the system's viewer.
|
||||
-- What the system's viewer is given: files that are only looked at or listened to. Anything else
|
||||
-- (a script, a page, a shortcut, a document that can carry macros) is named and left alone.
|
||||
local VIEWED = {}
|
||||
for _, e in ipairs({ "png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "pdf", "mp3", "wav", "ogg", "oga", "flac", "m4a",
|
||||
"mp4", "webm", "mkv", "mov", "glb", "gltf", "obj", "stl", "csv", "tsv", "txt" }) do VIEWED[e] = true end
|
||||
|
||||
function M.open_shown()
|
||||
if not S.shown then return vim.notify("LLeMbas: nothing has been shown yet", vim.log.levels.INFO) end
|
||||
local ext = (S.shown:match("%.([%w]+)$") or ""):lower()
|
||||
if not VIEWED[ext] then
|
||||
return vim.notify("LLeMbas: not opened, since a file of that kind may run: " .. S.shown, vim.log.levels.WARN)
|
||||
end
|
||||
vim.ui.open(S.shown)
|
||||
end
|
||||
|
||||
local function settings(set, cb)
|
||||
connect(function(ok)
|
||||
if not ok then return end
|
||||
if not S.caps.editor then return vim.notify("LLeMbas: this LLeMbas CLI has no editor settings yet", vim.log.levels.WARN) end
|
||||
S.conn:request("_lembas/editor/settings", set and { set = set } or vim.empty_dict(), function(err, r)
|
||||
if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end
|
||||
cb(r or {})
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
local function pick(which, cb)
|
||||
connect(function(ok)
|
||||
if not ok then return 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
|
||||
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
|
||||
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)
|
||||
end
|
||||
|
||||
local function said(r)
|
||||
local a, m = r.autocomplete or {}, r.main or {}
|
||||
vim.notify(("LLeMbas: autocomplete %s%s; main %s"):format(a.model or "not chosen",
|
||||
a.source and (" (" .. a.source .. ")") or "", m.model or "as a session starts"), vim.log.levels.INFO)
|
||||
end
|
||||
|
||||
--- The model that writes suggestions. No name: pick from the list. `quick`: for this editor only,
|
||||
--- not saved; "-" goes back to the saved choice (quick) or to the instance's default (saved).
|
||||
function M.autocomplete_model(name, quick)
|
||||
local function set(id)
|
||||
local complete = require("llembas.complete")
|
||||
if quick then
|
||||
M.config.complete.model = id ~= "-" and id or nil
|
||||
complete.reset()
|
||||
return vim.notify("LLeMbas: autocomplete here uses " .. (M.config.complete.model or "your saved choice"), vim.log.levels.INFO)
|
||||
end
|
||||
settings({ autocomplete_model = id ~= "-" and id or vim.NIL }, function(r) complete.reset(); said(r) end)
|
||||
end
|
||||
if name and name ~= "" then return set(name) end
|
||||
pick("autocomplete", set)
|
||||
end
|
||||
|
||||
--- The model for chat, rewriting and generating, saved in your account.
|
||||
function M.main_model(name)
|
||||
local function set(id) settings({ main_model = id ~= "-" and id or vim.NIL }, said) end
|
||||
if name == "?" then return settings(nil, said) end
|
||||
if name and name ~= "" then return set(name) end
|
||||
pick("main", set)
|
||||
end
|
||||
|
||||
function M.mode_ids()
|
||||
return vim.tbl_map(function(m) return m.id end, S.modes)
|
||||
end
|
||||
|
||||
function M.setup(opts)
|
||||
M.config = vim.tbl_deep_extend("force", M.config, opts or {})
|
||||
if type(M.config.cmd) == "string" then M.config.cmd = { M.config.cmd, "serve", "--stdio" } end
|
||||
if type(M.config.cmd) == "string" then M.config.cmd = { M.config.cmd, "serve", "--stdio" } end require("llembas.complete").setup()
|
||||
end
|
||||
|
||||
--- For the plugin's other parts: the connection once the agent has started (`cb(conn | nil)`).
|
||||
function M._connect(cb, quiet)
|
||||
connect(function(ok) cb(ok and S.conn or nil) end, quiet)
|
||||
end
|
||||
|
||||
function M._note(text)
|
||||
M.open(false)
|
||||
note(text)
|
||||
end
|
||||
|
||||
M.version = "1.0.0-beta.1"
|
||||
@@ -319,6 +508,10 @@ vim.api.nvim_create_autocmd("VimLeavePre", {
|
||||
group = vim.api.nvim_create_augroup("llembas", { clear = true }),
|
||||
callback = function() if S.conn then S.conn:stop() end end,
|
||||
})
|
||||
vim.api.nvim_create_autocmd({ "FileChangedShellPost", "BufReadPost" }, {
|
||||
group = "llembas",
|
||||
callback = function(ev) require("llembas.diff").forget(ev.buf) end,
|
||||
})
|
||||
vim.api.nvim_create_autocmd("BufEnter", {
|
||||
group = "llembas",
|
||||
callback = function(ev) if vim.bo[ev.buf].buftype == "" then S.last_buf = ev.buf end end,
|
||||
|
||||
+12
-1
@@ -14,7 +14,18 @@ cmd("LLeMbasAsk", function(o) L().ask(o.line1, o.line2, o.args) end,
|
||||
cmd("LLeMbasEdit", function(o) L().edit(o.line1, o.line2, o.args) end,
|
||||
{ range = true, nargs = "*", desc = "LLeMbas: have the selected lines rewritten" })
|
||||
cmd("LLeMbasStop", function() L().stop() end, { desc = "LLeMbas: stop the running turn" })
|
||||
cmd("LLeMbasNew", function() L().new() end, { desc = "LLeMbas: start a new session" })
|
||||
cmd("LLeMbasNew", function(o) L().new(o.bang) end, { bang = true, desc = "LLeMbas: start a new session (! also while a turn hangs)" })
|
||||
cmd("LLeMbasMode", function(o) L().mode(o.args) end,
|
||||
{ nargs = "?", complete = function() return L().mode_ids() end, desc = "LLeMbas: change the mode" })
|
||||
cmd("LLeMbasModel", function(o) L().model(o.args) end, { nargs = "?", desc = "LLeMbas: show or change the model" })
|
||||
cmd("LLeMbasAccept", function(o) require("llembas.diff").accept(o.bang) end, { bang = true, desc = "LLeMbas: accept the change under the cursor (! all)" })
|
||||
cmd("LLeMbasReject", function(o) require("llembas.diff").reject(o.bang) end, { bang = true, desc = "LLeMbas: reject the change under the cursor (! all)" })
|
||||
cmd("LLeMbasAutocomplete", function(o)
|
||||
local on = require("llembas.complete").auto(o.args == "on" and true or o.args == "off" and false or nil)
|
||||
vim.notify("LLeMbas: suggestions as you type are " .. (on and "on" or "off"))
|
||||
end, { nargs = "?", complete = function() return { "on", "off" } end, desc = "LLeMbas: suggestions as you type on or off" })
|
||||
cmd("LLeMbasAutocompleteModel", function(o) L().autocomplete_model(o.args, o.bang) end,
|
||||
{ nargs = "?", bang = true, desc = "LLeMbas: the autocomplete model (! for this editor only, - for the default)" })
|
||||
cmd("LLeMbasMainModel", function(o) L().main_model(o.args) end,
|
||||
{ nargs = "?", desc = "LLeMbas: the model for chat and rewriting, saved in your account (? shows both)" })
|
||||
cmd("LLeMbasOpen", function() L().open_shown() end, { desc = "LLeMbas: open the file the agent showed last" })
|
||||
@@ -38,6 +38,27 @@ def ask(method, params):
|
||||
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"]
|
||||
@@ -55,6 +76,41 @@ def prompt(msg):
|
||||
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),
|
||||
@@ -85,10 +141,41 @@ def main():
|
||||
if method is None:
|
||||
entry = waiting.get(msg.get("id"))
|
||||
if entry:
|
||||
entry[1] = msg.get("result")
|
||||
if "error" not in msg:
|
||||
entry[1] = msg.get("result")
|
||||
entry[0].set()
|
||||
elif method == "initialize":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"protocolVersion": 1, "agentCapabilities": {}}})
|
||||
result = {"protocolVersion": 1, "agentCapabilities": {}}
|
||||
if EDITOR:
|
||||
result["_meta"] = {"lembas": {"capabilities": ["editor", "media"]}}
|
||||
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/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",
|
||||
|
||||
+264
-4
@@ -63,8 +63,10 @@ check("prompt: the open file is named, its text is not sent",
|
||||
#p == 2 and p[1].text:find("sample.py", 1, true) and p[1].text:find("cursor on line 1", 1, true) and p[2].text == "hello", vim.inspect(p))
|
||||
local init
|
||||
for _, m in ipairs(sent()) do if m.method == "initialize" then init = m end end
|
||||
check("start: plain ACP, no LLeMbas client capability claimed",
|
||||
init and init.params.protocolVersion == 1 and next(init.params.clientCapabilities) == nil)
|
||||
local lm = init and (init.params.clientCapabilities._meta or {}).lembas or {}
|
||||
check("start: ACP version 1, and the client says it is an editor that shows files and serves and takes text",
|
||||
init and init.params.protocolVersion == 1 and lm.editor == true and lm.media == true
|
||||
and init.params.clientCapabilities.fs.readTextFile == true and init.params.clientCapabilities.fs.writeTextFile == true)
|
||||
check("start: the transcript cannot be typed in and reads no modeline",
|
||||
vim.bo[chat.tbuf].modifiable == false and vim.bo[chat.tbuf].modeline == false and vim.bo[chat.ibuf].modeline == false)
|
||||
|
||||
@@ -95,12 +97,14 @@ check("attach: the next message carries them no more", #p == 2 and p[2].text ==
|
||||
|
||||
-- 4. An approval is put to the person; the answer goes back.
|
||||
local asked
|
||||
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end
|
||||
local function option(items, id) for _, o in ipairs(items) do if o.optionId == id then return o end end end
|
||||
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(option(items, "once")) end
|
||||
type_and_send("PERM")
|
||||
idle()
|
||||
check("approval: asked with the command and the reason",
|
||||
asked and asked.opts.prompt:find("rm -r build", 1, true) and asked.opts.prompt:find("deletes files", 1, true)
|
||||
and asked.opts.format_item(asked.items[2]) == "Deny")
|
||||
and asked.opts.format_item(asked.items[1]) == "Deny")
|
||||
check("approval: the first choice is a denial, so a stray 1 and Enter allows nothing", asked.items[1].optionId == "deny")
|
||||
check("approval: the choice reaches the agent", chat.text():find("answer=once", 1, true) ~= nil, chat.text())
|
||||
vim.ui.select = function(_, _, cb) cb(nil) end
|
||||
type_and_send("PERM")
|
||||
@@ -150,6 +154,262 @@ check("crash: the turn is over and the reason is in the transcript",
|
||||
type_and_send("back")
|
||||
check("crash: the next message gets an answer from a new agent", idle() and chat.text():match("back\n\n## LLeMbas") ~= nil)
|
||||
|
||||
-- 8b. An agent that offers the editor's methods (spec 3.11.0).
|
||||
vim.env.FAKE_EDITOR = "1"
|
||||
vim.cmd("LLeMbasNew")
|
||||
vim.fn.delete(log)
|
||||
local function calls(method)
|
||||
local out = {}
|
||||
for _, m in ipairs(sent()) do if m.method == method then out[#out + 1] = m.params end end
|
||||
return out
|
||||
end
|
||||
vim.fn.writefile({ "def a():", " return 1", "", "def b():", " return 2" }, file)
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
|
||||
vim.cmd("edit!")
|
||||
|
||||
-- Context as data, not as a sentence.
|
||||
vim.api.nvim_win_set_cursor(0, { 4, 0 })
|
||||
type_and_send("hello editor")
|
||||
idle()
|
||||
local all = sent()
|
||||
local pr
|
||||
for i = #all, 1, -1 do if all[i].method == "session/prompt" then pr = all[i].params break end end
|
||||
check("editor: a typed message carries the file and the cursor as data and no sentence",
|
||||
pr and #pr.prompt == 1 and pr._meta.lembas.editor.path == file and pr._meta.lembas.editor.cursor.line == 4, vim.inspect(pr))
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
|
||||
vim.cmd("4,5LLeMbasAsk what is b?")
|
||||
idle()
|
||||
all = sent()
|
||||
for i = #all, 1, -1 do if all[i].method == "session/prompt" then pr = all[i].params break end end
|
||||
local sel = pr._meta.lembas.editor.selection
|
||||
check("editor: a selection goes as data with its lines and text",
|
||||
#pr.prompt == 1 and sel.start == 4 and sel["end"] == 5 and sel.text == "def b():\n return 2", vim.inspect(pr))
|
||||
|
||||
-- Unsaved text is what the agent reads.
|
||||
vim.api.nvim_buf_set_lines(fbuf, 2, 3, false, { "# not saved" })
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
|
||||
type_and_send("READ " .. file)
|
||||
idle()
|
||||
check("unsaved: the agent's read of an open file gets the buffer's text",
|
||||
chat.text():find('read="def a():\\n return 1\\n# not saved\\ndef b():\\n return 2"', 1, true) ~= nil, chat.text())
|
||||
type_and_send("READ " .. tmp .. "/none.txt")
|
||||
idle()
|
||||
check("unsaved: a file that cannot be read is an error, not a crash", chat.text():find("read=null", 1, true) ~= nil)
|
||||
|
||||
-- A rewrite is shown, and nothing is written before it is accepted.
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
|
||||
vim.api.nvim_buf_set_lines(fbuf, 2, 3, false, { "" })
|
||||
local D = require("llembas.diff")
|
||||
local before_text = vim.api.nvim_buf_get_lines(fbuf, 0, -1, false)
|
||||
vim.cmd("1,2LLeMbasEdit make it louder")
|
||||
check("rewrite: two changes are shown on unsaved text", wait(function() return D.pending(fbuf) == 2 end), tostring(D.pending(fbuf)))
|
||||
check("rewrite: the buffer is as it was", vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), before_text))
|
||||
local e = calls("_lembas/edit")[1]
|
||||
check("rewrite: the request has the text, the lines around it, the instruction and an id",
|
||||
e and e.text == "def a():\n return 1" and e.after:find("def b", 1, true) and e.before == "" and e.instruction == "make it louder"
|
||||
and e.path == file and type(e.id) == "string", vim.inspect(e))
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
vim.cmd("LLeMbasAccept")
|
||||
check("rewrite: accepting one change makes that one and leaves the other shown",
|
||||
vim.api.nvim_buf_get_lines(fbuf, 0, 1, false)[1] == "DEF A():" and D.pending(fbuf) == 1
|
||||
and #vim.api.nvim_buf_get_lines(fbuf, 0, -1, false) == 5)
|
||||
vim.cmd("LLeMbasReject")
|
||||
check("rewrite: rejecting the other leaves its lines alone and nothing shown",
|
||||
D.pending(fbuf) == 0 and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false),
|
||||
{ "DEF A():", " return 1", "", "def b():", " return 2" }))
|
||||
vim.cmd("4,5LLeMbasEdit again")
|
||||
wait(function() return D.pending(fbuf) == 2 end)
|
||||
vim.cmd("LLeMbasAccept!")
|
||||
check("rewrite: accepting all makes both, in the right places",
|
||||
D.pending(fbuf) == 0 and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false),
|
||||
{ "DEF A():", " return 1", "", "DEF B():", " return 2", " # added by the rewrite" }),
|
||||
vim.inspect(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false)))
|
||||
local said_msgs = {}
|
||||
local notify = vim.notify
|
||||
vim.notify = function(m) said_msgs[#said_msgs + 1] = m end
|
||||
vim.cmd("1,2LLeMbasEdit SAME")
|
||||
check("rewrite: one that changes nothing says so", wait(function() return table.concat(said_msgs, "|"):find("changes nothing", 1, true) ~= nil end))
|
||||
vim.cmd("1,2LLeMbasEdit REFUSE")
|
||||
check("rewrite: a refusal is said in the agent's words", wait(function() return table.concat(said_msgs, "|"):find("no model to rewrite with", 1, true) ~= nil end)
|
||||
and D.pending(fbuf) == 0)
|
||||
|
||||
-- A change whose lines you removed meanwhile takes nothing else with it.
|
||||
vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "def a():", " return 1", "keep me", "and me" })
|
||||
vim.cmd("1,2LLeMbasEdit once more")
|
||||
wait(function() return D.pending(fbuf) == 2 end)
|
||||
vim.api.nvim_buf_set_lines(fbuf, 0, 1, false, {})
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
vim.cmd("LLeMbasAccept!")
|
||||
check("rewrite: a change whose line you deleted is dropped, and no other line is taken",
|
||||
D.pending(fbuf) == 0 and vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false),
|
||||
{ " return 1", " # added by the rewrite", "keep me", "and me" }),
|
||||
vim.inspect(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false)))
|
||||
-- The keys of a proposal are yours again afterwards.
|
||||
vim.keymap.set("n", "ga", "<Cmd>let g:mine = 1<CR>", { buffer = fbuf })
|
||||
vim.cmd("1,1LLeMbasEdit keys")
|
||||
wait(function() return D.pending(fbuf) > 0 end)
|
||||
vim.cmd("LLeMbasReject!")
|
||||
check("rewrite: a buffer mapping the proposal's keys replaced is given back",
|
||||
vim.fn.maparg("ga", "n", false, true).rhs == "<Cmd>let g:mine = 1<CR>", vim.inspect(vim.fn.maparg("ga", "n", false, true)))
|
||||
vim.keymap.del("n", "ga", { buffer = fbuf })
|
||||
|
||||
-- The agent's read never takes a file for another whose name merely begins the same.
|
||||
local short = tmp .. "/sample"
|
||||
vim.fn.writefile({ "the short one" }, short)
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
|
||||
type_and_send("READ " .. short)
|
||||
idle()
|
||||
check("unsaved: a file is found by its whole name, not by a part of another's",
|
||||
chat.text():find('read="the short one"', 1, true) ~= nil, chat.text())
|
||||
-- A write by the agent goes into the open buffer and onto the disk together.
|
||||
vim.api.nvim_buf_set_lines(fbuf, 0, -1, false, { "old text, not saved" })
|
||||
type_and_send("PUT " .. file)
|
||||
idle()
|
||||
check("write: the agent's text is in the buffer, on the disk, and the buffer is not left modified",
|
||||
vim.deep_equal(vim.api.nvim_buf_get_lines(fbuf, 0, -1, false), { "written by the agent", "second" })
|
||||
and vim.deep_equal(vim.fn.readfile(file), { "written by the agent", "second" }) and not vim.bo[fbuf].modified
|
||||
and chat.text():find("put=ok", 1, true) ~= nil, chat.text())
|
||||
type_and_send("PUT " .. tmp .. "/not-open.txt")
|
||||
idle()
|
||||
check("write: a file that is not open is left to the agent", chat.text():find("put=error", 1, true) ~= nil
|
||||
and vim.fn.filereadable(tmp .. "/not-open.txt") == 0)
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(fbuf))
|
||||
|
||||
-- An approval that carries a diff shows it while the question is open.
|
||||
local wins_during
|
||||
vim.ui.select = function(items, _, cb)
|
||||
wins_during = {}
|
||||
for _, w in ipairs(vim.api.nvim_tabpage_list_wins(0)) do
|
||||
local b = vim.api.nvim_win_get_buf(w)
|
||||
if vim.bo[b].filetype == "diff" then wins_during = vim.api.nvim_buf_get_lines(b, 0, -1, false) end
|
||||
end
|
||||
cb(option(items, "deny"))
|
||||
end
|
||||
local wins_before = #vim.api.nvim_tabpage_list_wins(0)
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(chat.ibuf))
|
||||
type_and_send("PERMDIFF")
|
||||
idle()
|
||||
local joined = table.concat(wins_during or {}, "\n")
|
||||
check("approval: the diff is on the screen while the question is asked",
|
||||
joined:find("--- sample.py", 1, true) and joined:find("-two", 1, true) and joined:find("+TWO", 1, true), joined)
|
||||
check("approval: the diff's window is gone afterwards and the answer went back",
|
||||
#vim.api.nvim_tabpage_list_wins(0) == wins_before and chat.text():find("answer=deny", 1, true) ~= nil)
|
||||
|
||||
-- Shown files.
|
||||
local png = tmp .. "/chart.png"
|
||||
vim.fn.writefile({ "not really a picture" }, png)
|
||||
local opened
|
||||
vim.ui.open = function(pth) opened = pth end
|
||||
type_and_send("SHOW " .. png)
|
||||
idle()
|
||||
check("show: a file that is not text is named in the chat and answered as shown",
|
||||
chat.text():find("chart.png (image)", 1, true) ~= nil and chat.text():find('shown={"shown": true}', 1, true) ~= nil, chat.text())
|
||||
vim.cmd("LLeMbasOpen")
|
||||
check("show: :LLeMbasOpen hands it to the system's viewer", opened == png)
|
||||
L._state.shown = tmp .. "/run.desktop"
|
||||
opened = nil
|
||||
vim.cmd("LLeMbasOpen")
|
||||
check("show: a file that may run is not handed to the system", opened == nil)
|
||||
local other = tmp .. "/other.py"
|
||||
vim.fn.writefile({ "x = 1", "y = 2", "z = 3" }, other)
|
||||
type_and_send("SHOW " .. other)
|
||||
idle()
|
||||
check("show: a text file is opened in the window you edit in, at its line, and the prompt keeps the focus",
|
||||
vim.api.nvim_buf_get_name(vim.api.nvim_win_get_buf(vim.fn.bufwinid(fbuf) ~= -1 and vim.fn.bufwinid(fbuf) or vim.fn.win_getid(1))) ~= ""
|
||||
and vim.fn.bufwinid(vim.fn.bufnr(other)) ~= -1 and vim.api.nvim_win_get_cursor(vim.fn.bufwinid(vim.fn.bufnr(other)))[1] == 2
|
||||
and vim.api.nvim_get_current_buf() == chat.ibuf)
|
||||
|
||||
-- Suggestions.
|
||||
local C = require("llembas.complete")
|
||||
local ns_c = vim.api.nvim_get_namespaces()["llembas-complete"]
|
||||
local function ghost(buf)
|
||||
local m = vim.api.nvim_buf_get_extmarks(buf, ns_c, 0, -1, { details = true })[1]
|
||||
if not m then return nil end
|
||||
local d = m[4]
|
||||
local t = d.virt_text and d.virt_text[1][1] or ""
|
||||
for _, vl in ipairs(d.virt_lines or {}) do t = t .. "\n" .. vl[1][1] end
|
||||
return t, m[2], m[3]
|
||||
end
|
||||
local obuf = vim.fn.bufnr(other)
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf))
|
||||
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "abc = fo", "tail" })
|
||||
vim.bo[obuf].filetype = "python"
|
||||
C._typing = function() return true end
|
||||
vim.o.virtualedit = "onemore" -- so the cursor can stand after the last character, as it does while typing
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 8 })
|
||||
C.request(true)
|
||||
check("suggest: asked on the key, the text is drawn at the cursor and is not in the buffer",
|
||||
wait(function() return ghost(obuf) ~= nil end) and ghost(obuf) == "< fo|\nta>" and vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1] == "abc = fo",
|
||||
vim.inspect({ ghost(obuf) }))
|
||||
local c = calls("_lembas/complete")
|
||||
check("suggest: the request has what is before and after the cursor, the file and the language",
|
||||
c[#c].prefix == "abc = fo" and c[#c].suffix == "\ntail" and c[#c].path == other and c[#c].language == "python" and type(c[#c].id) == "string",
|
||||
vim.inspect(c[#c]))
|
||||
check("suggest: accepting puts it in and moves the cursor to its end",
|
||||
C.accept() and vim.deep_equal(vim.api.nvim_buf_get_lines(obuf, 0, -1, false), { "abc = fo< fo|", "ta>", "tail" })
|
||||
and vim.deep_equal(vim.api.nvim_win_get_cursor(0), { 2, 3 }) and ghost(obuf) == nil,
|
||||
vim.inspect(vim.api.nvim_buf_get_lines(obuf, 0, -1, false)))
|
||||
check("suggest: with nothing shown there is nothing to accept", C.accept() == false)
|
||||
vim.keymap.set("i", "<Tab>", "<Cmd>let g:tab = 1<CR>", { buffer = obuf })
|
||||
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "abc" })
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 3 })
|
||||
C.request(true)
|
||||
wait(function() return ghost(obuf) ~= nil end)
|
||||
local during = vim.fn.maparg("<Tab>", "i", false, true)
|
||||
C.clear()
|
||||
local after = vim.fn.maparg("<Tab>", "i", false, true)
|
||||
check("suggest: Tab is the plugin's only while a suggestion is shown, and yours again afterwards",
|
||||
during.desc == "LLeMbas: accept the suggestion" and after.rhs == "<Cmd>let g:tab = 1<CR>", vim.inspect({ during.desc, after.rhs }))
|
||||
vim.keymap.del("i", "<Tab>", { buffer = obuf })
|
||||
check("suggest: without a suggestion the plugin maps Tab nowhere", vim.fn.maparg("<Tab>", "i") == "")
|
||||
-- As you type: asked after the pause, and an answer for a place you have left is not drawn.
|
||||
L.config.complete.debounce_ms = 30
|
||||
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "" })
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
local n0 = #calls("_lembas/complete")
|
||||
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "xy" })
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 2 })
|
||||
vim.cmd("doautocmd TextChangedI")
|
||||
check("suggest: typing asks by itself after the pause", wait(function() return ghost(obuf) == "<xy|>" end), vim.inspect({ ghost(obuf) }))
|
||||
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "SLOWC" })
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 5 })
|
||||
vim.cmd("doautocmd TextChangedI")
|
||||
wait(function() local k = calls("_lembas/complete"); return k[#k] and k[#k].prefix == "SLOWC" end)
|
||||
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "SLOWCz" })
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 6 })
|
||||
vim.cmd("doautocmd TextChangedI")
|
||||
check("suggest: a newer keystroke cancels the request before it by its id",
|
||||
wait(function() return #calls("_lembas/complete/cancel") >= 1 end))
|
||||
vim.wait(400)
|
||||
local g = ghost(obuf)
|
||||
check("suggest: only the answer for where the cursor is now is ever drawn", g == nil or g == "<WCz|>", tostring(g))
|
||||
C.clear()
|
||||
-- A refusal is said once and the asking stops.
|
||||
said_msgs = {}
|
||||
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "NOMODEL" })
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 7 })
|
||||
vim.cmd("doautocmd TextChangedI")
|
||||
check("suggest: no model chosen is said once", wait(function() return table.concat(said_msgs, "|"):find("no autocomplete model is chosen", 1, true) ~= nil end))
|
||||
n0 = #calls("_lembas/complete")
|
||||
vim.cmd("doautocmd TextChangedI")
|
||||
vim.wait(200)
|
||||
check("suggest: and nothing more is asked until a model is chosen", #calls("_lembas/complete") == n0 and #said_msgs == 1)
|
||||
-- Choosing models.
|
||||
vim.cmd("LLeMbasAutocompleteModel example/model-a")
|
||||
check("models: the autocomplete model is saved through the agent",
|
||||
wait(function() local k = calls("_lembas/editor/settings"); return k[#k] and k[#k].set and k[#k].set.autocomplete_model == "example/model-a" end))
|
||||
vim.ui.select = function(items, opts, cb) asked = { items = items, opts = opts }; cb(items[1]) end
|
||||
vim.cmd("LLeMbasAutocompleteModel")
|
||||
check("models: without a name the list offers only models allowed for it",
|
||||
wait(function() return asked and asked.opts.prompt:find("autocomplete", 1, true) ~= nil end) and #asked.items == 1 and asked.items[1].id == "example/model-a")
|
||||
vim.cmd("LLeMbasAutocompleteModel! example/model-b")
|
||||
check("models: the quick switch is this editor's only", L.config.complete.model == "example/model-b"
|
||||
and (function() local k = calls("_lembas/editor/settings"); return k[#k].set.autocomplete_model ~= "example/model-b" end)())
|
||||
vim.cmd("LLeMbasMainModel example/model-b")
|
||||
check("models: the main model is saved as its own entry",
|
||||
wait(function() local k = calls("_lembas/editor/settings"); return k[#k].set and k[#k].set.main_model == "example/model-b" end))
|
||||
vim.notify = notify
|
||||
|
||||
-- 9. A command that does not exist is said, not thrown.
|
||||
L.setup({ cmd = { "llembas-no-such-command" } })
|
||||
vim.cmd("LLeMbasNew")
|
||||
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
# Builds the VS Code / VSCodium extension as dist/llembas-<version>.vsix. Needs only Node 18 or
|
||||
# newer: no packaging tool, no npm install. The version is the repository's VERSION file.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec node vscode/tools/vsix.js "$@"
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
# The extension's tests: the parts that need no editor, against a stand-in agent.
|
||||
# Needs Node 18 or newer and python3. Nothing here starts VS Code.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec node --test vscode/tests/*.test.js
|
||||
+161
-1
@@ -1,3 +1,163 @@
|
||||
# LLeMbas for VS Code and VSCodium
|
||||
|
||||
Not written yet. It will be a client of `lembas serve --stdio`, like the Neovim plugin beside it.
|
||||
LLeMbas in the editor: a chat with the agent beside your files, questions about a selection, a
|
||||
selection rewritten as a diff you accept or reject, and autocomplete.
|
||||
|
||||
The extension is a client of the [LLeMbas CLI](https://github.com/LLeMbas/LLeMbas-CLI). The CLI is
|
||||
the agent: it holds the sign-in to your LLeMbas server, the models, the tools and the permissions.
|
||||
The extension starts `lembas serve --stdio` and talks to it over the Agent Client Protocol. Nothing
|
||||
about a server or a model is set in the editor, only which command starts the CLI.
|
||||
|
||||
This is a beta. It has been tested without an editor (see *Tests*); it has not yet been run inside
|
||||
VS Code or VSCodium by its authors.
|
||||
|
||||
## What you need
|
||||
|
||||
- VS Code or VSCodium 1.85 or newer.
|
||||
- The LLeMbas CLI, signed in (`lembas login <address>`). The chat works with LLeMbas CLI 2.0 betas;
|
||||
autocomplete, rewriting a selection, the model settings and pictures in the chat need a CLI and a
|
||||
server that have the editor methods (harness spec 3.11.0). With an older one the extension says so
|
||||
where it matters and the rest keeps working.
|
||||
|
||||
## Install
|
||||
|
||||
Build the package (needs only Node 18 or newer — no `npm install`, no packaging tool):
|
||||
|
||||
```sh
|
||||
scripts/package-vscode.sh # writes dist/llembas-<version>.vsix
|
||||
```
|
||||
|
||||
Then install it:
|
||||
|
||||
```sh
|
||||
codium --install-extension dist/llembas-<version>.vsix # VSCodium
|
||||
code --install-extension dist/llembas-<version>.vsix # VS Code
|
||||
```
|
||||
|
||||
or in the editor: Extensions → `…` → *Install from VSIX…*.
|
||||
|
||||
If the editor does not find `lembas` (an editor started from the desktop does not always have your
|
||||
shell's `PATH`), set **LLeMbas: Command** to the program's full path.
|
||||
|
||||
The extension is off in a folder you have not trusted (Restricted Mode): it starts an agent that
|
||||
works in that folder.
|
||||
|
||||
## What it does
|
||||
|
||||
**Chat.** The LLeMbas icon in the activity bar opens the chat. Above the transcript: the session's
|
||||
mode, the session's model, and *New*. Enter sends, Shift+Enter starts a new line; while the agent
|
||||
works the button is *Stop*. When the agent asks before doing something, the question appears as a
|
||||
card with its answers as buttons. A question about an edit — in manual mode, every edit — opens
|
||||
the change in the editor's own diff view first; nothing is written until you allow it. Files the
|
||||
agent changed are named under the tool's line and open with a click.
|
||||
|
||||
What a model writes is shown as text. A small Markdown reader in the extension turns it into
|
||||
paragraphs, lists, code and links; HTML in a reply stays text, pictures in a reply are not loaded,
|
||||
and a link opens in your browser only when it is `http`, `https` or `mailto`. A reply of more than
|
||||
400,000 characters is shown as it was written.
|
||||
|
||||
**Ask about a selection.** Select text, then *LLeMbas: Ask About the Selection*. With a question it
|
||||
is sent at once; with an empty one the selection goes with the next message you type. The agent is
|
||||
told the file, the lines, the selected text as the editor has it (saved or not) and the problems
|
||||
the editor shows there. A message typed in the chat carries the file in front and the cursor's line
|
||||
the same way (setting *Send Editor Context*).
|
||||
|
||||
**Rewrite a selection.** Select lines, then *LLeMbas: Rewrite the Selection* and say what should
|
||||
change. The result comes back as proposed changes in the file: each one is marked, with *Accept*
|
||||
and *Reject* above it, *Accept all* / *Reject all* above the first, and the whole proposal in the
|
||||
diff view beside the file. Nothing is written until you accept; rejecting leaves the file as it
|
||||
was. A change whose lines you edited meanwhile is dropped instead of being applied to the wrong
|
||||
text.
|
||||
|
||||
**Autocomplete.** Suggestions appear as you type, after a short pause, as the editor's own inline
|
||||
suggestions: Tab accepts, Escape dismisses. `Alt+\` asks for one now. It needs an autocomplete
|
||||
model: when none is chosen the extension says so once, with a button to choose one, and stays quiet
|
||||
until one is set.
|
||||
|
||||
**Two model settings.** *LLeMbas: Models (Autocomplete and Main)* — also the *LLeMbas* item in the
|
||||
status bar — shows both: the **autocomplete** model, and the **main** model (chat and rewriting).
|
||||
Any model your server offers can be picked for either. *Save it* keeps the choice in your account,
|
||||
so every editor you sign in from uses it; *Only this window* is a quick switch that is saved
|
||||
nowhere. The picker in the chat changes the model of the session you are in.
|
||||
|
||||
**Files the agent shows.** A picture the agent shows (a screenshot, a chart) appears in the chat.
|
||||
Any other file is a line in the chat. *Open* is offered only for kinds that are merely displayed —
|
||||
pictures and plain text (opened inside the editor), PDF, sound and video (your system's viewer) —
|
||||
and only when the file's first bytes are that kind and its name says the same. Everything else,
|
||||
whatever it is called, gets *Show in folder* and is never opened for you. Files of more than 64 MB
|
||||
are refused, and the agent is told why (setting *Media: Max Megabytes*). Shown files are kept
|
||||
until the chat is cleared by a new session.
|
||||
|
||||
**Unsaved text.** When the agent reads a file you have open, it gets the text as the editor has
|
||||
it, saved or not. When it writes one, the new text is put into the open document and saved — one
|
||||
undo step in the editor — so the file and what you see never part ways. A file that is not open
|
||||
is read and written by the agent itself.
|
||||
|
||||
## Commands and keys
|
||||
|
||||
| Command | Key | |
|
||||
|---|---|---|
|
||||
| LLeMbas: Open the Chat | `Ctrl+Alt+L` | |
|
||||
| LLeMbas: Ask About the Selection | `Ctrl+Alt+K` | also in the editor's context menu |
|
||||
| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in the editor's context menu |
|
||||
| LLeMbas: Suggest a Completion Here | `Alt+\` | |
|
||||
| LLeMbas: Accept All Proposed Changes in This File | `Ctrl+Alt+Enter` | while changes are proposed |
|
||||
| LLeMbas: Reject All Proposed Changes in This File | `Ctrl+Alt+Backspace` | while changes are proposed |
|
||||
| LLeMbas: Accept / Reject the Proposed Change at the Cursor | | or the lines above each change |
|
||||
| LLeMbas: Show the Proposed Changes as a Diff | | |
|
||||
| LLeMbas: New Session | | the old session stays in the CLI's own store |
|
||||
| LLeMbas: Stop the Running Turn | | |
|
||||
| LLeMbas: Choose the Mode | | |
|
||||
| LLeMbas: Choose This Session's Model | | |
|
||||
| LLeMbas: Models (Autocomplete and Main) | | |
|
||||
| LLeMbas: Choose the Autocomplete Model / the Main Model | | |
|
||||
| LLeMbas: Stop the Agent | | it starts again when needed |
|
||||
|
||||
On macOS the keys use `Cmd` in place of `Ctrl`.
|
||||
|
||||
## Settings
|
||||
|
||||
| Setting | Default | |
|
||||
|---|---|---|
|
||||
| `llembas.command` | `lembas` | the LLeMbas CLI, or its full path. Set for the machine, never by a folder |
|
||||
| `llembas.chat.sendEditorContext` | on | tell the agent which file is in front, the cursor, the selection and its problems |
|
||||
| `llembas.chat.showThinking` | off | show the model's thinking |
|
||||
| `llembas.chat.startMode` | | the mode a new session starts in; empty: the CLI's own. Set for the machine, never by a folder |
|
||||
| `llembas.complete.auto` | on | suggest as you type; off: only on `Alt+\` |
|
||||
| `llembas.complete.debounce` | 250 | the pause, in milliseconds, before a suggestion is asked for |
|
||||
| `llembas.complete.maxTokens` | 0 | the longest suggestion; 0: the server's own number |
|
||||
| `llembas.rewrite.openDiff` | on | open the diff view beside the file when a rewrite is proposed |
|
||||
| `llembas.media.maxMegabytes` | 64 | the largest file taken from the agent to show or open |
|
||||
|
||||
## Not there yet
|
||||
|
||||
- Picking up an older session: a window starts a new one.
|
||||
- The agent's questions with choices (`ask_user`) and its plans for approval are not shown as
|
||||
cards; the agent is told nobody can be asked.
|
||||
- Sound, video, PDF and 3D files are not drawn in the chat: they are a line with *Open*.
|
||||
- A table in a reply is shown as written, not drawn as a table.
|
||||
- An edit the agent asks about in a chat is allowed or denied as a whole, not change by change.
|
||||
- A window with several folders works in the first one.
|
||||
- No marketplace listing: install from the `.vsix`.
|
||||
|
||||
## How it is made
|
||||
|
||||
Plain JavaScript, no bundler, no dependencies, nothing fetched from the network, no telemetry.
|
||||
`extension.js` is the only file that talks to the editor; everything else is in `src/` and runs
|
||||
without one: the protocol client (`rpc.js`, `agent.js`), the chat (`chat.js`), autocomplete's
|
||||
waiting and cancelling (`completion.js`), the changes of a rewrite (`hunks.js`), the Markdown
|
||||
reader (`markdown.js`), the editor context (`context.js`) and shown files (`media.js`). The chat's
|
||||
page (`media/chat.js`) builds what it shows from elements and text only, under a
|
||||
Content-Security-Policy that allows one script and nothing from elsewhere; every colour is one of
|
||||
the editor's theme variables.
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
scripts/test-vscode.sh # needs Node 18+ and python3
|
||||
```
|
||||
|
||||
They run the modules in `src/` against a stand-in agent (`tests/fake_agent.py`), check the
|
||||
package the script builds (its archive, its manifest, what is and is not in it), and load
|
||||
`extension.js` against an in-memory stand-in for the editor's API (`tests/stub_vscode.js`). None of
|
||||
them starts VS Code: how the extension looks and behaves in a real editor is not covered by them.
|
||||
+1001
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,205 @@
|
||||
/* Every colour is one of the editor's theme variables. */
|
||||
html, body { height: 100%; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: grid;
|
||||
grid-template-rows: auto minmax(0, 1fr) auto;
|
||||
color: var(--vscode-foreground);
|
||||
background: var(--vscode-sideBar-background);
|
||||
font-family: var(--vscode-font-family);
|
||||
font-size: var(--vscode-font-size);
|
||||
line-height: 1.45;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
.bar {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto;
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
}
|
||||
select, button, textarea { font: inherit; }
|
||||
select {
|
||||
width: 100%;
|
||||
height: 26px;
|
||||
color: var(--vscode-dropdown-foreground);
|
||||
background: var(--vscode-dropdown-background);
|
||||
border: 1px solid var(--vscode-dropdown-border);
|
||||
border-radius: 2px;
|
||||
}
|
||||
button {
|
||||
height: 26px;
|
||||
padding: 0 10px;
|
||||
color: var(--vscode-button-foreground);
|
||||
background: var(--vscode-button-background);
|
||||
border: 1px solid var(--vscode-button-border, transparent);
|
||||
border-radius: 2px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
button:hover { background: var(--vscode-button-hoverBackground); }
|
||||
button.second {
|
||||
color: var(--vscode-button-secondaryForeground);
|
||||
background: var(--vscode-button-secondaryBackground);
|
||||
}
|
||||
button.second:hover { background: var(--vscode-button-secondaryHoverBackground); }
|
||||
button.plain {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
color: var(--vscode-foreground);
|
||||
background: transparent;
|
||||
border-color: transparent;
|
||||
}
|
||||
button.plain:hover { background: var(--vscode-toolbar-hoverBackground); }
|
||||
button:disabled, select:disabled { opacity: 0.6; cursor: default; }
|
||||
select:focus, button:focus-visible, textarea:focus, .link:focus-visible {
|
||||
outline: 1px solid var(--vscode-focusBorder);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
#log {
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 8px;
|
||||
}
|
||||
.item { margin: 0 0 10px; overflow-wrap: anywhere; }
|
||||
.who {
|
||||
margin: 0 0 2px;
|
||||
font-size: 0.85em;
|
||||
font-weight: 600;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.user .text, .thought .text, .note { white-space: pre-wrap; }
|
||||
.user .body {
|
||||
padding: 6px 8px;
|
||||
background: var(--vscode-input-background);
|
||||
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
|
||||
border-radius: 3px;
|
||||
}
|
||||
.label { font-size: 0.85em; color: var(--vscode-descriptionForeground); }
|
||||
.thought .text { color: var(--vscode-descriptionForeground); font-style: italic; }
|
||||
.note { color: var(--vscode-descriptionForeground); font-size: 0.92em; }
|
||||
.tool, .plan {
|
||||
display: grid;
|
||||
grid-template-columns: 1.4em minmax(0, 1fr);
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-size: 0.92em;
|
||||
}
|
||||
.tool.failed .mark { color: var(--vscode-errorForeground); }
|
||||
.tool .files { grid-column: 2; }
|
||||
|
||||
.md p, .md ul, .md ol, .md pre, .md blockquote, .md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 0 0 8px; }
|
||||
.md > :last-child { margin-bottom: 0; }
|
||||
.md .plain { white-space: pre-wrap; }
|
||||
.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { font-size: 1em; font-weight: 600; }
|
||||
.md h1 { font-size: 1.2em; }
|
||||
.md h2 { font-size: 1.1em; }
|
||||
.md ul, .md ol { padding-left: 1.5em; }
|
||||
.md li.depth-1 { margin-left: 1.2em; }
|
||||
.md li.depth-2 { margin-left: 2.4em; }
|
||||
.md li.depth-3 { margin-left: 3.6em; }
|
||||
.md li.depth-4 { margin-left: 4.8em; }
|
||||
.md li.depth-5 { margin-left: 6em; }
|
||||
.md blockquote {
|
||||
padding: 0 0 0 8px;
|
||||
border-left: 3px solid var(--vscode-textBlockQuote-border);
|
||||
background: var(--vscode-textBlockQuote-background);
|
||||
}
|
||||
.md hr { border: 0; border-top: 1px solid var(--vscode-panel-border); margin: 8px 0; }
|
||||
code, pre {
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: var(--vscode-editor-font-size);
|
||||
}
|
||||
.md code { background: var(--vscode-textCodeBlock-background); padding: 0 3px; border-radius: 2px; }
|
||||
pre {
|
||||
margin: 0;
|
||||
padding: 6px 8px;
|
||||
overflow-x: auto; /* a wide line scrolls here, never the view */
|
||||
white-space: pre;
|
||||
background: var(--vscode-textCodeBlock-background);
|
||||
border-radius: 3px;
|
||||
}
|
||||
.md pre code { background: transparent; padding: 0; }
|
||||
.link {
|
||||
color: var(--vscode-textLink-foreground);
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.link:hover { color: var(--vscode-textLink-activeForeground); }
|
||||
|
||||
.card {
|
||||
padding: 8px;
|
||||
border: 1px solid var(--vscode-inputValidation-warningBorder, var(--vscode-panel-border));
|
||||
background: var(--vscode-inputValidation-warningBackground, var(--vscode-input-background));
|
||||
border-radius: 3px;
|
||||
}
|
||||
.card.closed {
|
||||
border-color: var(--vscode-panel-border);
|
||||
background: transparent;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.card .title { white-space: pre-wrap; font-family: var(--vscode-editor-font-family); margin: 2px 0 4px; }
|
||||
.card .reason { font-size: 0.92em; margin: 0 0 6px; }
|
||||
.card pre { margin: 0 0 6px; max-height: 16em; overflow: auto; }
|
||||
.card .buttons { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
|
||||
.media img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 60vh;
|
||||
height: auto;
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.media .caption {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
min-height: 26px;
|
||||
margin-top: 4px;
|
||||
font-size: 0.92em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.media .name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
footer { padding: 6px 8px 8px; border-top: 1px solid var(--vscode-panel-border); }
|
||||
textarea {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 5.2em;
|
||||
resize: none;
|
||||
padding: 5px 6px;
|
||||
color: var(--vscode-input-foreground);
|
||||
background: var(--vscode-input-background);
|
||||
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
|
||||
border-radius: 2px;
|
||||
}
|
||||
textarea::placeholder { color: var(--vscode-input-placeholderForeground); }
|
||||
.send {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
height: 26px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
.attached {
|
||||
grid-column: 1;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, auto) 22px;
|
||||
gap: 2px;
|
||||
align-items: center;
|
||||
justify-content: start;
|
||||
height: 26px;
|
||||
font-size: 0.92em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.attached-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.working { grid-column: 2; font-size: 0.92em; color: var(--vscode-descriptionForeground); }
|
||||
#send { grid-column: 3; }
|
||||
[hidden] { display: none !important; }
|
||||
@@ -0,0 +1,320 @@
|
||||
// The chat view's one script. It draws what the extension sends: items of a transcript, and
|
||||
// the Markdown of a model's text as a tree of plain objects (src/markdown.js). Everything is
|
||||
// built with createElement and textContent; no markup is ever parsed from a string here.
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var MARKS = { pending: '…', in_progress: '…', completed: '✓', failed: '✗' };
|
||||
var MAX_DEPTH = 8;
|
||||
|
||||
function el(doc, tag, cls, text) {
|
||||
var e = doc.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text !== undefined && text !== null) e.textContent = String(text);
|
||||
return e;
|
||||
}
|
||||
|
||||
function buildInline(doc, nodes, parent, depth) {
|
||||
if (!Array.isArray(nodes) || depth > MAX_DEPTH) return;
|
||||
for (var i = 0; i < nodes.length; i++) {
|
||||
var n = nodes[i];
|
||||
if (!n || typeof n !== 'object') continue;
|
||||
if (n.t === 'text') parent.appendChild(doc.createTextNode(String(n.v)));
|
||||
else if (n.t === 'br') parent.appendChild(doc.createElement('br'));
|
||||
else if (n.t === 'code') parent.appendChild(el(doc, 'code', '', n.v));
|
||||
else if (n.t === 'b' || n.t === 'i') {
|
||||
var e = doc.createElement(n.t === 'b' ? 'strong' : 'em');
|
||||
buildInline(doc, n.c, e, depth + 1);
|
||||
parent.appendChild(e);
|
||||
} else if (n.t === 'a') {
|
||||
// Not an anchor that navigates: the extension is asked to open the address, and checks it again.
|
||||
var a = doc.createElement('span');
|
||||
a.className = 'link';
|
||||
a.setAttribute('role', 'link');
|
||||
a.setAttribute('tabindex', '0');
|
||||
a.setAttribute('title', String(n.href));
|
||||
a.setAttribute('data-href', String(n.href));
|
||||
buildInline(doc, n.c, a, depth + 1);
|
||||
parent.appendChild(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function buildBlocks(doc, blocks, parent, depth) {
|
||||
if (!Array.isArray(blocks) || depth > MAX_DEPTH) return;
|
||||
for (var i = 0; i < blocks.length; i++) {
|
||||
var b = blocks[i];
|
||||
if (!b || typeof b !== 'object') continue;
|
||||
var e;
|
||||
if (b.t === 'p') {
|
||||
e = doc.createElement('p');
|
||||
buildInline(doc, b.c, e, 0);
|
||||
} else if (b.t === 'h') {
|
||||
var level = Math.max(1, Math.min(6, Number(b.l) || 1));
|
||||
e = doc.createElement('h' + level);
|
||||
buildInline(doc, b.c, e, 0);
|
||||
} else if (b.t === 'pre') {
|
||||
e = doc.createElement('pre');
|
||||
e.appendChild(el(doc, 'code', '', b.v));
|
||||
} else if (b.t === 'plain') {
|
||||
// A text too long to be read as Markdown: shown as it was written.
|
||||
e = el(doc, 'div', 'plain', b.v);
|
||||
} else if (b.t === 'hr') {
|
||||
e = doc.createElement('hr');
|
||||
} else if (b.t === 'quote') {
|
||||
e = doc.createElement('blockquote');
|
||||
buildBlocks(doc, b.c, e, depth + 1);
|
||||
} else if (b.t === 'ul' || b.t === 'ol') {
|
||||
e = doc.createElement(b.t);
|
||||
var items = Array.isArray(b.items) ? b.items : [];
|
||||
for (var j = 0; j < items.length; j++) {
|
||||
var d = Math.max(0, Math.min(5, Number(items[j] && items[j].d) || 0));
|
||||
var li = el(doc, 'li', d ? 'depth-' + d : '');
|
||||
buildInline(doc, items[j] && items[j].c, li, 0);
|
||||
e.appendChild(li);
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
parent.appendChild(e);
|
||||
}
|
||||
}
|
||||
|
||||
function button(doc, text, cls, onClick) {
|
||||
var b = el(doc, 'button', cls || '', text);
|
||||
b.setAttribute('type', 'button');
|
||||
b.addEventListener('click', onClick);
|
||||
return b;
|
||||
}
|
||||
|
||||
/** One item of the transcript as an element. `post` sends a message to the extension. */
|
||||
function renderItem(doc, item, post) {
|
||||
var root = el(doc, 'div', 'item ' + String(item.kind).replace(/[^a-z]/g, ''));
|
||||
root.setAttribute('data-id', String(item.id));
|
||||
if (item.kind === 'user') {
|
||||
root.appendChild(el(doc, 'div', 'who', 'You'));
|
||||
var body = el(doc, 'div', 'body');
|
||||
if (item.label) body.appendChild(el(doc, 'div', 'label', '[' + item.label + ']'));
|
||||
body.appendChild(el(doc, 'div', 'text', item.text));
|
||||
root.appendChild(body);
|
||||
} else if (item.kind === 'agent') {
|
||||
root.appendChild(el(doc, 'div', 'who', 'LLeMbas'));
|
||||
var md = el(doc, 'div', 'md');
|
||||
if (Array.isArray(item.ast)) buildBlocks(doc, item.ast, md, 0);
|
||||
else md.textContent = String(item.text || '');
|
||||
root.appendChild(md);
|
||||
} else if (item.kind === 'thought') {
|
||||
root.appendChild(el(doc, 'div', 'who', 'Thinking'));
|
||||
root.appendChild(el(doc, 'div', 'text', item.text));
|
||||
} else if (item.kind === 'note') {
|
||||
root.textContent = String(item.text);
|
||||
} else if (item.kind === 'tool') {
|
||||
if (item.status === 'failed') root.className += ' failed';
|
||||
root.appendChild(el(doc, 'span', 'mark', MARKS[item.status] || '…'));
|
||||
root.appendChild(el(doc, 'span', 'title', String(item.title) + (item.denied ? ' (not allowed)' : '')));
|
||||
var files = Array.isArray(item.files) ? item.files : [];
|
||||
if (files.length) {
|
||||
var list = el(doc, 'div', 'files');
|
||||
files.slice(0, 20).forEach(function (path, i) {
|
||||
if (i) list.appendChild(doc.createTextNode(', '));
|
||||
var f = el(doc, 'span', 'link', String(path).split(/[\\/]/).pop());
|
||||
f.setAttribute('role', 'link');
|
||||
f.setAttribute('tabindex', '0');
|
||||
f.setAttribute('title', String(path));
|
||||
f.setAttribute('data-file', String(path));
|
||||
list.appendChild(f);
|
||||
});
|
||||
root.appendChild(list);
|
||||
}
|
||||
} else if (item.kind === 'plan') {
|
||||
root.appendChild(el(doc, 'span', 'mark', item.done >= item.all ? '✓' : '…'));
|
||||
root.appendChild(el(doc, 'span', 'title', 'Plan: ' + Number(item.done) + ' of ' + Number(item.all) + ' tasks done'));
|
||||
} else if (item.kind === 'card') {
|
||||
var open = item.state === 'open';
|
||||
if (!open) root.className += ' closed';
|
||||
root.appendChild(el(doc, 'div', 'who', open ? 'LLeMbas asks' + (item.tool ? ' (' + item.tool + ')' : '') : 'Asked'));
|
||||
root.appendChild(el(doc, 'div', 'title', item.title));
|
||||
if (open && item.reason) root.appendChild(el(doc, 'div', 'reason', item.reason));
|
||||
if (open && item.detail) root.appendChild(el(doc, 'pre', '', item.detail));
|
||||
if (open) {
|
||||
var row = el(doc, 'div', 'buttons');
|
||||
(Array.isArray(item.options) ? item.options : []).forEach(function (o) {
|
||||
var deny = String(o.kind).indexOf('reject') === 0;
|
||||
row.appendChild(button(doc, o.name, deny ? 'second' : '', function () {
|
||||
post({ type: 'answer', card: item.id, option: o.optionId });
|
||||
}));
|
||||
});
|
||||
if (Array.isArray(item.files) && item.files.length) {
|
||||
row.appendChild(button(doc, 'Show the change', 'second', function () {
|
||||
post({ type: 'showDiff', card: item.id });
|
||||
}));
|
||||
}
|
||||
root.appendChild(row);
|
||||
} else {
|
||||
root.appendChild(el(doc, 'div', 'reason', item.answer));
|
||||
}
|
||||
} else if (item.kind === 'media') {
|
||||
if (item.picture && item.src) {
|
||||
var img = doc.createElement('img');
|
||||
img.setAttribute('src', String(item.src));
|
||||
img.setAttribute('alt', String(item.name));
|
||||
img.addEventListener('click', function () {
|
||||
post({ type: 'openMedia', key: item.key });
|
||||
});
|
||||
root.appendChild(img);
|
||||
}
|
||||
var cap = el(doc, 'div', 'caption');
|
||||
cap.appendChild(el(doc, 'span', 'name', String(item.name) + (item.sizeWords ? ' (' + item.sizeWords + ')' : '')));
|
||||
cap.appendChild(button(doc, item.opens ? 'Open' : 'Show in folder', 'second', function () {
|
||||
post({ type: 'openMedia', key: item.key });
|
||||
}));
|
||||
root.appendChild(cap);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) {
|
||||
module.exports = { buildBlocks: buildBlocks, buildInline: buildInline, renderItem: renderItem };
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- in the view ----------------------------------------------------------------------
|
||||
|
||||
var vscode = acquireVsCodeApi();
|
||||
var doc = document;
|
||||
var log = doc.getElementById('log');
|
||||
var prompt = doc.getElementById('prompt');
|
||||
var send = doc.getElementById('send');
|
||||
var mode = doc.getElementById('mode');
|
||||
var model = doc.getElementById('model');
|
||||
var attached = doc.getElementById('attached');
|
||||
var attachedLabel = doc.getElementById('attached-label');
|
||||
var working = doc.getElementById('working');
|
||||
var state = { busy: false, modes: [], models: [], mode: null, model: null };
|
||||
var nodes = {};
|
||||
|
||||
function post(msg) {
|
||||
vscode.postMessage(msg);
|
||||
}
|
||||
|
||||
function atBottom() {
|
||||
return log.scrollHeight - log.scrollTop - log.clientHeight < 40;
|
||||
}
|
||||
|
||||
function upsert(item) {
|
||||
var stick = atBottom();
|
||||
var fresh = renderItem(doc, item, post);
|
||||
var old = nodes[item.id];
|
||||
if (old && old.parentNode === log) log.replaceChild(fresh, old);
|
||||
else log.appendChild(fresh);
|
||||
nodes[item.id] = fresh;
|
||||
if (stick) log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function reset(items) {
|
||||
while (log.firstChild) log.removeChild(log.firstChild);
|
||||
nodes = {};
|
||||
(items || []).forEach(upsert);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function fill(select, options, current, placeholder) {
|
||||
while (select.firstChild) select.removeChild(select.firstChild);
|
||||
var seen = false;
|
||||
options.forEach(function (o) {
|
||||
var opt = el(doc, 'option', '', o.name);
|
||||
opt.value = o.id;
|
||||
if (o.id === current) {
|
||||
opt.selected = true;
|
||||
seen = true;
|
||||
}
|
||||
select.appendChild(opt);
|
||||
});
|
||||
if (!seen) {
|
||||
var opt = el(doc, 'option', '', current || placeholder);
|
||||
opt.value = current || '';
|
||||
opt.selected = true;
|
||||
select.insertBefore(opt, select.firstChild);
|
||||
}
|
||||
select.disabled = options.length === 0;
|
||||
}
|
||||
|
||||
function showState(s) {
|
||||
state = s;
|
||||
fill(mode, s.modes || [], s.mode, 'Mode');
|
||||
fill(model, s.models || [], s.model, 'Model');
|
||||
send.textContent = s.busy ? 'Stop' : 'Send';
|
||||
working.hidden = !s.busy;
|
||||
mode.disabled = mode.disabled || !!s.busy;
|
||||
model.disabled = model.disabled || !!s.busy;
|
||||
}
|
||||
|
||||
function submit() {
|
||||
if (state.busy) return post({ type: 'stop' });
|
||||
var text = prompt.value;
|
||||
if (!text.trim()) return;
|
||||
post({ type: 'send', text: text });
|
||||
prompt.value = '';
|
||||
vscode.setState({ draft: '' });
|
||||
}
|
||||
|
||||
send.addEventListener('click', submit);
|
||||
prompt.addEventListener('keydown', function (ev) {
|
||||
if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing) {
|
||||
ev.preventDefault();
|
||||
if (!state.busy) submit();
|
||||
}
|
||||
});
|
||||
prompt.addEventListener('input', function () {
|
||||
vscode.setState({ draft: prompt.value });
|
||||
});
|
||||
doc.getElementById('new').addEventListener('click', function () {
|
||||
post({ type: 'new' });
|
||||
});
|
||||
doc.getElementById('detach').addEventListener('click', function () {
|
||||
post({ type: 'detach' });
|
||||
});
|
||||
mode.addEventListener('change', function () {
|
||||
if (mode.value) post({ type: 'setMode', id: mode.value });
|
||||
});
|
||||
model.addEventListener('change', function () {
|
||||
if (model.value) post({ type: 'setModel', id: model.value });
|
||||
});
|
||||
|
||||
function follow(target) {
|
||||
var t = target;
|
||||
while (t && t !== log) {
|
||||
if (t.getAttribute && t.getAttribute('data-href')) return post({ type: 'openLink', href: t.getAttribute('data-href') });
|
||||
if (t.getAttribute && t.getAttribute('data-file')) return post({ type: 'openFile', path: t.getAttribute('data-file') });
|
||||
t = t.parentNode;
|
||||
}
|
||||
}
|
||||
log.addEventListener('click', function (ev) {
|
||||
follow(ev.target);
|
||||
});
|
||||
log.addEventListener('keydown', function (ev) {
|
||||
if (ev.key === 'Enter') follow(ev.target);
|
||||
});
|
||||
|
||||
window.addEventListener('message', function (ev) {
|
||||
var m = ev.data;
|
||||
if (!m || typeof m !== 'object') return;
|
||||
if (m.type === 'reset') {
|
||||
reset(m.items);
|
||||
showState(m.state);
|
||||
showAttached(m.attached);
|
||||
} else if (m.type === 'item') upsert(m.item);
|
||||
else if (m.type === 'state') showState(m.state);
|
||||
else if (m.type === 'attached') showAttached(m.label);
|
||||
else if (m.type === 'focus') prompt.focus();
|
||||
});
|
||||
|
||||
function showAttached(label) {
|
||||
attached.hidden = !label;
|
||||
attachedLabel.textContent = label ? 'With ' + label : '';
|
||||
}
|
||||
|
||||
var saved = vscode.getState();
|
||||
if (saved && typeof saved.draft === 'string') prompt.value = saved.draft;
|
||||
post({ type: 'ready' });
|
||||
})();
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" shape-rendering="crispEdges"><rect x="12" y="3" width="1" height="1"/><rect x="13" y="3" width="4" height="1"/><rect x="10" y="4" width="2" height="1"/><rect x="12" y="4" width="2" height="1"/><rect x="14" y="4" width="2" height="1"/><rect x="16" y="4" width="1" height="1"/><rect x="8" y="5" width="3" height="1"/><rect x="11" y="5" width="2" height="1"/><rect x="13" y="5" width="2" height="1"/><rect x="15" y="5" width="2" height="1"/><rect x="8" y="6" width="2" height="1"/><rect x="10" y="6" width="2" height="1"/><rect x="12" y="6" width="2" height="1"/><rect x="14" y="6" width="2" height="1"/><rect x="7" y="7" width="2" height="1"/><rect x="9" y="7" width="2" height="1"/><rect x="11" y="7" width="2" height="1"/><rect x="13" y="7" width="3" height="1"/><rect x="7" y="8" width="1" height="1"/><rect x="8" y="8" width="2" height="1"/><rect x="10" y="8" width="2" height="1"/><rect x="12" y="8" width="4" height="1"/><rect x="6" y="9" width="1" height="1"/><rect x="7" y="9" width="2" height="1"/><rect x="9" y="9" width="2" height="1"/><rect x="11" y="9" width="4" height="1"/><rect x="6" y="10" width="2" height="1"/><rect x="8" y="10" width="2" height="1"/><rect x="10" y="10" width="4" height="1"/><rect x="6" y="11" width="1" height="1"/><rect x="7" y="11" width="2" height="1"/><rect x="9" y="11" width="4" height="1"/><rect x="6" y="12" width="2" height="1"/><rect x="8" y="12" width="4" height="1"/><rect x="6" y="13" width="1" height="1"/><rect x="7" y="13" width="2" height="1"/><rect x="5" y="14" width="1" height="1"/><rect x="4" y="15" width="1" height="1"/><rect x="3" y="16" width="1" height="1"/><rect x="15" y="15" width="2" height="1"/><rect x="18" y="15" width="2" height="1"/><rect x="14" y="16" width="2" height="1"/><rect x="19" y="16" width="2" height="1"/><rect x="13" y="17" width="2" height="1"/><rect x="20" y="17" width="2" height="1"/><rect x="14" y="18" width="2" height="1"/><rect x="19" y="18" width="2" height="1"/><rect x="15" y="19" width="2" height="1"/><rect x="18" y="19" width="2" height="1"/></svg>
|
||||
|
After Width: | Height: | Size: 2.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.2 KiB |
@@ -0,0 +1,137 @@
|
||||
{
|
||||
"name": "llembas",
|
||||
"displayName": "LLeMbas",
|
||||
"description": "LLeMbas in your editor: chat with the agent, ask about a selection, have it rewritten as a diff, and autocomplete — a client of the LLeMbas CLI.",
|
||||
"version": "0.0.0",
|
||||
"publisher": "llembas",
|
||||
"icon": "media/logo.png",
|
||||
"license": "MIT",
|
||||
"repository": { "type": "git", "url": "https://github.com/LLeMbas/LLeMbas-IDE" },
|
||||
"engines": { "vscode": "^1.85.0" },
|
||||
"categories": ["Machine Learning", "Other"],
|
||||
"keywords": ["llembas", "agent", "chat", "autocomplete", "acp"],
|
||||
"main": "./extension.js",
|
||||
"extensionKind": ["workspace"],
|
||||
"activationEvents": ["onStartupFinished", "onView:llembas.chat"],
|
||||
"capabilities": {
|
||||
"untrustedWorkspaces": {
|
||||
"supported": false,
|
||||
"description": "LLeMbas starts an agent that works in the open folder; it stays off until you trust the folder."
|
||||
},
|
||||
"virtualWorkspaces": {
|
||||
"supported": false,
|
||||
"description": "The LLeMbas CLI works on files on this computer."
|
||||
}
|
||||
},
|
||||
"contributes": {
|
||||
"viewsContainers": {
|
||||
"activitybar": [{ "id": "llembas", "title": "LLeMbas", "icon": "media/icon.svg" }]
|
||||
},
|
||||
"views": {
|
||||
"llembas": [{ "type": "webview", "id": "llembas.chat", "name": "Chat" }]
|
||||
},
|
||||
"commands": [
|
||||
{ "command": "llembas.open", "title": "Open the Chat", "category": "LLeMbas" },
|
||||
{ "command": "llembas.newSession", "title": "New Session", "category": "LLeMbas" },
|
||||
{ "command": "llembas.stop", "title": "Stop the Running Turn", "category": "LLeMbas" },
|
||||
{ "command": "llembas.ask", "title": "Ask About the Selection", "category": "LLeMbas" },
|
||||
{ "command": "llembas.rewrite", "title": "Rewrite the Selection", "category": "LLeMbas" },
|
||||
{ "command": "llembas.complete", "title": "Suggest a Completion Here", "category": "LLeMbas" },
|
||||
{ "command": "llembas.acceptChange", "title": "Accept the Proposed Change at the Cursor", "category": "LLeMbas" },
|
||||
{ "command": "llembas.rejectChange", "title": "Reject the Proposed Change at the Cursor", "category": "LLeMbas" },
|
||||
{ "command": "llembas.acceptAllChanges", "title": "Accept All Proposed Changes in This File", "category": "LLeMbas" },
|
||||
{ "command": "llembas.rejectAllChanges", "title": "Reject All Proposed Changes in This File", "category": "LLeMbas" },
|
||||
{ "command": "llembas.showChanges", "title": "Show the Proposed Changes as a Diff", "category": "LLeMbas" },
|
||||
{ "command": "llembas.chooseMode", "title": "Choose the Mode", "category": "LLeMbas" },
|
||||
{ "command": "llembas.chooseModel", "title": "Choose This Session's Model", "category": "LLeMbas" },
|
||||
{ "command": "llembas.modelSettings", "title": "Models (Autocomplete and Main)", "category": "LLeMbas" },
|
||||
{ "command": "llembas.chooseAutocompleteModel", "title": "Choose the Autocomplete Model", "category": "LLeMbas" },
|
||||
{ "command": "llembas.chooseMainModel", "title": "Choose the Main Model", "category": "LLeMbas" },
|
||||
{ "command": "llembas.restart", "title": "Stop the Agent (It Starts Again When Needed)", "category": "LLeMbas" }
|
||||
],
|
||||
"keybindings": [
|
||||
{ "command": "llembas.open", "key": "ctrl+alt+l", "mac": "cmd+alt+l" },
|
||||
{ "command": "llembas.ask", "key": "ctrl+alt+k", "mac": "cmd+alt+k", "when": "editorTextFocus && editorHasSelection" },
|
||||
{ "command": "llembas.rewrite", "key": "ctrl+alt+e", "mac": "cmd+alt+e", "when": "editorTextFocus && editorHasSelection && !editorReadonly" },
|
||||
{ "command": "llembas.complete", "key": "alt+\\", "when": "editorTextFocus && !editorReadonly" },
|
||||
{ "command": "llembas.acceptAllChanges", "key": "ctrl+alt+enter", "mac": "cmd+alt+enter", "when": "editorTextFocus && llembas.hasProposal" },
|
||||
{ "command": "llembas.rejectAllChanges", "key": "ctrl+alt+backspace", "mac": "cmd+alt+backspace", "when": "editorTextFocus && llembas.hasProposal" }
|
||||
],
|
||||
"menus": {
|
||||
"editor/context": [
|
||||
{ "command": "llembas.ask", "when": "editorHasSelection", "group": "llembas@1" },
|
||||
{ "command": "llembas.rewrite", "when": "editorHasSelection && !editorReadonly", "group": "llembas@2" }
|
||||
],
|
||||
"view/title": [
|
||||
{ "command": "llembas.newSession", "when": "view == llembas.chat", "group": "llembas@1" },
|
||||
{ "command": "llembas.modelSettings", "when": "view == llembas.chat", "group": "llembas@2" },
|
||||
{ "command": "llembas.restart", "when": "view == llembas.chat", "group": "llembas@3" }
|
||||
],
|
||||
"commandPalette": [
|
||||
{ "command": "llembas.acceptChange", "when": "llembas.hasProposal" },
|
||||
{ "command": "llembas.rejectChange", "when": "llembas.hasProposal" },
|
||||
{ "command": "llembas.acceptAllChanges", "when": "llembas.hasProposal" },
|
||||
{ "command": "llembas.rejectAllChanges", "when": "llembas.hasProposal" },
|
||||
{ "command": "llembas.showChanges", "when": "llembas.hasProposal" }
|
||||
]
|
||||
},
|
||||
"configuration": {
|
||||
"title": "LLeMbas",
|
||||
"properties": {
|
||||
"llembas.command": {
|
||||
"type": "string",
|
||||
"default": "lembas",
|
||||
"scope": "machine",
|
||||
"markdownDescription": "The LLeMbas CLI: `lembas` when it is on your `PATH`, or the full path of the program. It is started as `lembas serve --stdio`. This is the only thing set here: the server, the sign-in, the models and the permissions are the CLI's own."
|
||||
},
|
||||
"llembas.chat.sendEditorContext": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Tell the agent, with each message you type, which file is in front, where the cursor is, what is selected, and the problems the editor shows there."
|
||||
},
|
||||
"llembas.chat.showThinking": {
|
||||
"type": "boolean",
|
||||
"default": false,
|
||||
"description": "Show the model's thinking in the chat."
|
||||
},
|
||||
"llembas.chat.startMode": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"scope": "machine",
|
||||
"description": "The mode a new session starts in (for example manual, in which every edit is shown as a diff to accept). Empty: the CLI's own. Set for the machine, never by a folder."
|
||||
},
|
||||
"llembas.complete.auto": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Suggest a completion as you type. Off: only when you ask for one (Alt+\\). It needs an autocomplete model, chosen on the server or with \"LLeMbas: Choose the Autocomplete Model\"."
|
||||
},
|
||||
"llembas.complete.debounce": {
|
||||
"type": "number",
|
||||
"default": 250,
|
||||
"minimum": 0,
|
||||
"maximum": 5000,
|
||||
"description": "How long you must pause, in milliseconds, before a completion is asked for."
|
||||
},
|
||||
"llembas.complete.maxTokens": {
|
||||
"type": "number",
|
||||
"default": 0,
|
||||
"minimum": 0,
|
||||
"maximum": 512,
|
||||
"description": "The longest completion to ask for, in tokens. 0: the server's own number."
|
||||
},
|
||||
"llembas.rewrite.openDiff": {
|
||||
"type": "boolean",
|
||||
"default": true,
|
||||
"description": "Open the diff view beside the file when a rewrite is proposed. Off: only the marks and the Accept / Reject lines in the file."
|
||||
},
|
||||
"llembas.media.maxMegabytes": {
|
||||
"type": "number",
|
||||
"default": 64,
|
||||
"minimum": 1,
|
||||
"maximum": 64,
|
||||
"description": "The largest file, in megabytes, the chat takes from the agent to show (a picture) or to open. A larger one is refused, and the agent is told why."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
'use strict';
|
||||
// The agent: `lembas serve --stdio` as a child process, spoken to over the Agent Client Protocol
|
||||
// (version 1). Everything about models, tools, permissions and the sign-in is the agent's own.
|
||||
// No `vscode` here.
|
||||
const { EventEmitter } = require('node:events');
|
||||
const childProcess = require('node:child_process');
|
||||
const { Rpc, RpcError } = require('./rpc');
|
||||
|
||||
const PROTOCOL_VERSION = 1;
|
||||
|
||||
class Agent extends EventEmitter {
|
||||
/**
|
||||
* @param {{ command: string, args?: string[], cwd?: string, env?: object,
|
||||
* clientInfo?: { name: string, version: string }, writeTextFile?: boolean,
|
||||
* onRequest?: (method: string, params: any) => any }} options
|
||||
* Events: `notify (method, params)`, `stderr (text)`, `exit ({ code, last })`.
|
||||
*/
|
||||
constructor(options) {
|
||||
super();
|
||||
this.options = options;
|
||||
this.capabilities = new Set();
|
||||
this.info = null;
|
||||
this.ready = false;
|
||||
this.stopped = false;
|
||||
this.stderr = [];
|
||||
this.proc = null;
|
||||
this.rpc = null;
|
||||
this.starting = null;
|
||||
}
|
||||
|
||||
/** Start the process and say hello. The same promise for every caller. */
|
||||
connect() {
|
||||
if (!this.starting) this.starting = this._start();
|
||||
return this.starting;
|
||||
}
|
||||
|
||||
_start() {
|
||||
const o = this.options;
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false;
|
||||
const fail = (message) => {
|
||||
this.stopped = true;
|
||||
if (this.rpc) this.rpc.close(message);
|
||||
if (!settled) {
|
||||
settled = true;
|
||||
reject(new Error(message));
|
||||
}
|
||||
};
|
||||
let proc;
|
||||
try {
|
||||
proc = childProcess.spawn(o.command, o.args || ['serve', '--stdio'], {
|
||||
cwd: o.cwd,
|
||||
env: o.env || process.env,
|
||||
stdio: ['pipe', 'pipe', 'pipe'],
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
});
|
||||
} catch (e) {
|
||||
return fail(`could not start ${o.command}: ${e.message}`);
|
||||
}
|
||||
this.proc = proc;
|
||||
this.rpc = new Rpc({
|
||||
write: (line) => proc.stdin.write(line),
|
||||
onRequest: (method, params) => {
|
||||
if (!o.onRequest) throw { code: -32601, message: 'Method not found: ' + method };
|
||||
return o.onRequest(method, params);
|
||||
},
|
||||
onNotify: (method, params) => this.emit('notify', method, params),
|
||||
});
|
||||
proc.stdin.on('error', () => {});
|
||||
proc.stdout.on('data', (d) => this.rpc.feed(d));
|
||||
proc.stderr.on('data', (d) => {
|
||||
const text = d.toString('utf8');
|
||||
for (const line of text.split(/\r?\n/)) if (line.trim()) this.stderr.push(line);
|
||||
while (this.stderr.length > 40) this.stderr.shift();
|
||||
this.emit('stderr', text);
|
||||
});
|
||||
proc.on('error', (e) => {
|
||||
const why = e.code === 'ENOENT' ? 'the command was not found' : e.message;
|
||||
fail(`could not start ${o.command}: ${why}`);
|
||||
this.emit('exit', { code: null, last: why, started: false });
|
||||
});
|
||||
proc.on('exit', (code, signal) => {
|
||||
const last = this.stderr.length ? this.stderr[this.stderr.length - 1] : '';
|
||||
const was = this.ready;
|
||||
this.ready = false;
|
||||
fail(`the agent stopped (${signal || 'exit ' + code})${last ? ': ' + last : ''}`);
|
||||
this.emit('exit', { code, signal, last, started: was });
|
||||
});
|
||||
this.rpc
|
||||
.request('initialize', {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
clientCapabilities: {
|
||||
// Unsaved text: reading always; writing only where the editor can put the text into the
|
||||
// open document and save it before it answers.
|
||||
fs: { readTextFile: true, writeTextFile: !!o.writeTextFile },
|
||||
// `show` with `media`: the spec offers the show tool to a client that says `show`,
|
||||
// and hands over files that are not text to one that also says `media`.
|
||||
_meta: { lembas: { editor: true, media: true, show: true } },
|
||||
},
|
||||
clientInfo: o.clientInfo || { name: 'llembas-vscode', version: '0' },
|
||||
})
|
||||
.then(
|
||||
(r) => {
|
||||
if (settled) return;
|
||||
const lembas = (r && r._meta && r._meta.lembas) || {};
|
||||
this.capabilities = new Set(Array.isArray(lembas.capabilities) ? lembas.capabilities : []);
|
||||
this.info = r || {};
|
||||
this.ready = true;
|
||||
settled = true;
|
||||
resolve(this);
|
||||
},
|
||||
(e) => {
|
||||
if (settled) return;
|
||||
this.stop();
|
||||
fail('the agent refused to start: ' + e.message);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
has(capability) {
|
||||
return this.capabilities.has(capability);
|
||||
}
|
||||
|
||||
request(method, params) {
|
||||
if (!this.rpc || this.stopped) return Promise.reject(new RpcError({ code: -32000, message: 'the agent is not running' }));
|
||||
return this.rpc.request(method, params);
|
||||
}
|
||||
|
||||
notify(method, params) {
|
||||
if (this.rpc && !this.stopped) this.rpc.notify(method, params);
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (!this.proc || this.stopped) return;
|
||||
this.stopped = true;
|
||||
try {
|
||||
this.proc.stdin.end();
|
||||
} catch {
|
||||
// already closed
|
||||
}
|
||||
try {
|
||||
this.proc.kill('SIGTERM');
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Agent, PROTOCOL_VERSION };
|
||||
@@ -0,0 +1,489 @@
|
||||
'use strict';
|
||||
// The chat: one agent process, one session, and the transcript as a list of plain items the
|
||||
// view draws. Everything the editor itself must do — show a diff, read an open document, take
|
||||
// in a shown file — is a hook. No `vscode` here.
|
||||
const { EventEmitter } = require('node:events');
|
||||
const { promptParams } = require('./context');
|
||||
|
||||
const DETAIL_MAX = 20000;
|
||||
|
||||
function sentence(text) {
|
||||
const s = String(text || '').trim();
|
||||
return s ? s[0].toUpperCase() + s.slice(1) + (/[.!?…]$/.test(s) ? '' : '.') : '';
|
||||
}
|
||||
|
||||
class Chat extends EventEmitter {
|
||||
/**
|
||||
* @param {{ makeAgent: (o: { cwd: string, onRequest: Function }) => import('./agent').Agent,
|
||||
* cwd: () => string,
|
||||
* options?: () => { mode?: string, model?: string, showThoughts?: boolean },
|
||||
* hooks?: { readTextFile?: Function, showDiffs?: Function, closeDiffs?: Function,
|
||||
* showMedia?: Function, showText?: Function, filesChanged?: Function },
|
||||
* now?: () => number }} io
|
||||
* Events: `item (item)`, `reset`, `state`, `connected (agent)`, `stopped`, `editDelta (params)`, `stderr (text)`.
|
||||
*/
|
||||
constructor(io) {
|
||||
super();
|
||||
this.io = io;
|
||||
this.hooks = io.hooks || {};
|
||||
this.now = io.now || Date.now;
|
||||
this.agent = null;
|
||||
this.failedAt = 0;
|
||||
this.items = [];
|
||||
this.nextItem = 1;
|
||||
this._clearSession();
|
||||
this.models = [];
|
||||
this.settings = null;
|
||||
}
|
||||
|
||||
_clearSession() {
|
||||
this.session = null;
|
||||
this.sessionStarting = null;
|
||||
this.busy = false;
|
||||
this.modes = [];
|
||||
this.mode = null;
|
||||
this.model = null;
|
||||
this.said = null;
|
||||
this.tools = new Map();
|
||||
this.cards = new Map();
|
||||
}
|
||||
|
||||
options() {
|
||||
return (this.io.options && this.io.options()) || {};
|
||||
}
|
||||
|
||||
// ---- the transcript -------------------------------------------------------------------
|
||||
|
||||
add(item) {
|
||||
item.id = 'i' + this.nextItem++;
|
||||
this.items.push(item);
|
||||
this.emit('item', item);
|
||||
return item;
|
||||
}
|
||||
|
||||
changed(item) {
|
||||
this.emit('item', item);
|
||||
}
|
||||
|
||||
note(text) {
|
||||
this.said = null;
|
||||
return this.add({ kind: 'note', text: String(text) });
|
||||
}
|
||||
|
||||
/** What the view needs besides the items. */
|
||||
state() {
|
||||
return {
|
||||
busy: this.busy,
|
||||
session: !!this.session,
|
||||
mode: this.mode,
|
||||
modes: this.modes.map((m) => ({ id: String(m.id), name: String(m.name || m.id) })),
|
||||
model: this.model,
|
||||
models: this.models.filter((m) => !Array.isArray(m.for) || m.for.includes('main')).map((m) => ({ id: String(m.id), name: String(m.name || m.id) })),
|
||||
};
|
||||
}
|
||||
|
||||
// ---- the agent ------------------------------------------------------------------------
|
||||
|
||||
/** A running agent that has answered `initialize`, or `null`. `quiet`: a failure is not written into the chat. */
|
||||
async connect(quiet) {
|
||||
if (this.agent && !this.agent.stopped) {
|
||||
try {
|
||||
return await this.agent.connect();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
// An agent that was told to stop but has not gone yet: its session goes now, not when its
|
||||
// exit is heard — by then a new agent is the current one and the exit would be ignored.
|
||||
if (this.agent) this._retire(this.agent, null);
|
||||
// Completion asks at every pause in typing: a command that is not there is not tried each time.
|
||||
if (quiet && this.failedAt && this.now() - this.failedAt < 60000) return null;
|
||||
const agent = this.io.makeAgent({ cwd: this.io.cwd(), onRequest: (method, params) => this._onRequest(agent, method, params) });
|
||||
this.agent = agent;
|
||||
agent.on('notify', (method, params) => this._onNotify(agent, method, params));
|
||||
agent.on('stderr', (text) => this.emit('stderr', text));
|
||||
agent.on('exit', (e) => this._onExit(agent, e));
|
||||
try {
|
||||
await agent.connect();
|
||||
this.failedAt = 0;
|
||||
this.startError = null;
|
||||
this.emit('connected', agent);
|
||||
return agent;
|
||||
} catch (e) {
|
||||
if (this.agent === agent) this.agent = null;
|
||||
this.failedAt = this.now();
|
||||
this.startError = e.message;
|
||||
if (!quiet) this.note(sentence(e.message));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
_onExit(agent, e) {
|
||||
this._retire(agent, e);
|
||||
}
|
||||
|
||||
/** The agent is gone, or going: everything that belonged to it is let go. Once per agent. */
|
||||
_retire(agent, e) {
|
||||
if (this.agent !== agent) return;
|
||||
const had = this.session !== null || this.sessionStarting !== null || this.busy;
|
||||
this.agent = null;
|
||||
for (const card of [...this.cards.values()]) this._settle(card, 'The agent stopped before this was answered.');
|
||||
this._clearSession();
|
||||
if (e && e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`);
|
||||
else if (!e && had) this.note('The agent was stopped. The next message starts a new session.');
|
||||
this.emit('stopped');
|
||||
this.emit('state');
|
||||
}
|
||||
|
||||
/** Stop the agent on purpose (another command, or the person asked). It starts again when needed. */
|
||||
stopAgent() {
|
||||
const agent = this.agent;
|
||||
if (!agent) return;
|
||||
agent.stop();
|
||||
this._retire(agent, null);
|
||||
}
|
||||
|
||||
/** A request of the editor's own (`_lembas/complete`, `_lembas/edit`, …). Rejects when the agent cannot be had. */
|
||||
async request(method, params, quiet) {
|
||||
const agent = await this.connect(quiet);
|
||||
if (!agent) throw new Error(this.startError || 'the agent is not running');
|
||||
return agent.request(method, params);
|
||||
}
|
||||
|
||||
notify(method, params) {
|
||||
if (this.agent && this.agent.ready) this.agent.notify(method, params);
|
||||
}
|
||||
|
||||
has(capability) {
|
||||
return !!(this.agent && this.agent.ready && this.agent.has(capability));
|
||||
}
|
||||
|
||||
/** An open session, started when there is none. Resolves `false` when that failed (the chat says why). */
|
||||
ensureSession() {
|
||||
if (this.session) return Promise.resolve(true);
|
||||
if (this.sessionStarting) return this.sessionStarting;
|
||||
const starting = (async () => {
|
||||
const agent = await this.connect(false);
|
||||
if (!agent) return false;
|
||||
const o = this.options();
|
||||
const meta = {};
|
||||
if (o.mode) meta.mode = o.mode;
|
||||
if (o.model) meta.model = o.model;
|
||||
let r;
|
||||
try {
|
||||
r = await agent.request('session/new', { cwd: this.io.cwd(), mcpServers: [], _meta: meta });
|
||||
} catch (e) {
|
||||
if (this.agent === agent) this.note('No session: ' + sentence(e.message));
|
||||
return false;
|
||||
}
|
||||
if (this.agent !== agent || !r || typeof r.sessionId !== 'string') return false;
|
||||
this.session = r.sessionId;
|
||||
const lembas = (r._meta && r._meta.lembas) || {};
|
||||
this.modes = (r.modes && Array.isArray(r.modes.availableModes) && r.modes.availableModes) || [];
|
||||
this.mode = (r.modes && r.modes.currentModeId) || lembas.mode || null;
|
||||
this.model = lembas.model || null;
|
||||
this.emit('state');
|
||||
if (agent.has('editor')) this.loadModels().catch(() => {});
|
||||
return true;
|
||||
})();
|
||||
this.sessionStarting = starting;
|
||||
const done = () => {
|
||||
if (this.sessionStarting === starting) this.sessionStarting = null;
|
||||
};
|
||||
starting.then(done, done);
|
||||
return starting;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a prompt. `editor` is what the editor shows (`editorContext`), `label` how the
|
||||
* transcript names an attached selection. Resolves `false` when a turn already runs.
|
||||
*/
|
||||
async send(text, with_) {
|
||||
if (this.busy) return false;
|
||||
const w = with_ || {};
|
||||
this.add({ kind: 'user', text, label: w.label || '' });
|
||||
this.said = 'user';
|
||||
this.busy = true;
|
||||
this.emit('state');
|
||||
try {
|
||||
if (!(await this.ensureSession())) return true;
|
||||
const agent = this.agent;
|
||||
try {
|
||||
const r = await agent.request('session/prompt', promptParams(this.session, text, w.editor, agent.has('editor')));
|
||||
const lembas = (r && r._meta && r._meta.lembas) || {};
|
||||
if (typeof lembas.message === 'string' && lembas.message) this.note(lembas.message);
|
||||
if (r && r.stopReason && r.stopReason !== 'end_turn') {
|
||||
this.note(r.stopReason === 'cancelled' ? 'Stopped.' : 'The turn ended: ' + String(r.stopReason).replace(/_/g, ' ') + '.');
|
||||
}
|
||||
} catch (e) {
|
||||
if (this.agent === agent) this.note('The turn failed: ' + sentence(e.message));
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
this.busy = false;
|
||||
this.said = null;
|
||||
this.emit('state');
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop the running turn. Cards still open are answered as cancelled, as ACP asks. */
|
||||
stop() {
|
||||
if (!this.agent || !this.session || !this.busy) return;
|
||||
this.agent.notify('session/cancel', { sessionId: this.session });
|
||||
for (const card of [...this.cards.values()]) this._settle(card, 'Not answered: the turn was stopped.');
|
||||
}
|
||||
|
||||
/** A new session; the old one stays in the agent's own store. Resolves `false` while a turn runs. */
|
||||
async newSession() {
|
||||
if (this.busy) return false;
|
||||
for (const card of [...this.cards.values()]) this._settle(card, 'Not answered.');
|
||||
const agent = this.agent;
|
||||
const models = this.models;
|
||||
this._clearSession();
|
||||
this.agent = agent;
|
||||
this.models = models;
|
||||
this.items = [];
|
||||
this.emit('reset');
|
||||
this.emit('state');
|
||||
return true;
|
||||
}
|
||||
|
||||
async setMode(id) {
|
||||
if (!(await this.ensureSession())) return false;
|
||||
await this.agent.request('session/set_mode', { sessionId: this.session, modeId: id });
|
||||
this.mode = id;
|
||||
this.emit('state');
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The session's model, for this session only. */
|
||||
async setModel(id) {
|
||||
if (!(await this.ensureSession())) return false;
|
||||
const r = await this.agent.request('_lembas/configure', { sessionId: this.session, model: id });
|
||||
this.model = (r && r.model) || id;
|
||||
this.emit('state');
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The models the sign-in offers, and the person's two settings (`_lembas/models`). */
|
||||
async loadModels(quiet) {
|
||||
const r = await this.request('_lembas/models', {}, quiet);
|
||||
this.models = r && Array.isArray(r.models) ? r.models.filter((m) => m && typeof m.id === 'string') : [];
|
||||
this.settings = { autocomplete: (r && r.autocomplete) || null, main: (r && r.main) || null };
|
||||
this.emit('state');
|
||||
return { models: this.models, ...this.settings };
|
||||
}
|
||||
|
||||
/** Read the two saved model settings, or save `set` first (`_lembas/editor/settings`). */
|
||||
async editorSettings(set) {
|
||||
const r = await this.request('_lembas/editor/settings', set ? { set } : {});
|
||||
this.settings = { autocomplete: (r && r.autocomplete) || null, main: (r && r.main) || null };
|
||||
return this.settings;
|
||||
}
|
||||
|
||||
// ---- what the agent sends -------------------------------------------------------------
|
||||
|
||||
_onNotify(agent, method, params) {
|
||||
if (this.agent !== agent || !params) return;
|
||||
if (method === 'session/update') {
|
||||
if (params.sessionId === this.session && params.update) this._onUpdate(params.update);
|
||||
} else if (method === '_lembas/edit/delta') {
|
||||
this.emit('editDelta', params);
|
||||
} else if (method === '_lembas/permission/settled') {
|
||||
for (const card of [...this.cards.values()]) {
|
||||
if (card.item.toolCallId === params.toolCallId) this._settle(card, 'Answered elsewhere, or no longer waited for.');
|
||||
}
|
||||
} else if (method === '_lembas/event') {
|
||||
const ev = params.event;
|
||||
if (params.sessionId !== this.session || !ev) return;
|
||||
if (ev.type === 'model' && typeof ev.ref === 'string') {
|
||||
this.model = ev.ref;
|
||||
this.emit('state');
|
||||
} else if (ev.type === 'mode' && typeof ev.mode === 'string') {
|
||||
this.mode = ev.mode;
|
||||
this.emit('state');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_onUpdate(u) {
|
||||
const kind = u.sessionUpdate;
|
||||
if (kind === 'agent_message_chunk' || kind === 'agent_thought_chunk') {
|
||||
const thought = kind === 'agent_thought_chunk';
|
||||
if (thought && !this.options().showThoughts) return;
|
||||
if (!u.content || u.content.type !== 'text' || typeof u.content.text !== 'string') return;
|
||||
const want = thought ? 'thought' : 'agent';
|
||||
if (this.said !== want || !this.current) {
|
||||
this.current = this.add({ kind: want, text: '' });
|
||||
this.said = want;
|
||||
}
|
||||
this.current.text += u.content.text;
|
||||
this.changed(this.current);
|
||||
} else if (kind === 'tool_call' || kind === 'tool_call_update') {
|
||||
const id = String(u.toolCallId);
|
||||
let item = this.tools.get(id);
|
||||
const fresh = !item;
|
||||
if (!item) {
|
||||
item = { kind: 'tool', toolCallId: id, title: 'tool', status: 'pending', files: [], denied: false };
|
||||
this.tools.set(id, item);
|
||||
}
|
||||
if (typeof u.title === 'string' && u.title) item.title = u.title;
|
||||
if (typeof u.status === 'string') item.status = u.status;
|
||||
if (u._meta && u._meta.lembas && u._meta.lembas.denied) item.denied = true;
|
||||
const files = diffItems(u.content).map((d) => d.path);
|
||||
if (files.length) item.files = [...new Set(files)];
|
||||
this.said = 'tool';
|
||||
if (fresh) this.add(item);
|
||||
else this.changed(item);
|
||||
if (item.status === 'completed' && item.files.length && this.hooks.filesChanged) this.hooks.filesChanged(item.files);
|
||||
} else if (kind === 'plan') {
|
||||
const entries = Array.isArray(u.entries) ? u.entries : [];
|
||||
if (!entries.length) return;
|
||||
const done = entries.filter((e) => e && e.status === 'completed').length;
|
||||
if (!this.planItem || !this.items.includes(this.planItem)) this.planItem = this.add({ kind: 'plan', done, all: entries.length });
|
||||
else {
|
||||
this.planItem.done = done;
|
||||
this.planItem.all = entries.length;
|
||||
this.changed(this.planItem);
|
||||
}
|
||||
this.said = 'tool';
|
||||
} else if (kind === 'current_mode_update') {
|
||||
if (typeof u.currentModeId === 'string') this.mode = u.currentModeId;
|
||||
this.emit('state');
|
||||
}
|
||||
}
|
||||
|
||||
_onRequest(agent, method, params) {
|
||||
if (this.agent !== agent) throw { code: -32000, message: 'this client has moved on' };
|
||||
if (method === 'session/request_permission') return this._onPermission(params);
|
||||
if (method === 'fs/read_text_file') {
|
||||
if (!this.hooks.readTextFile) throw { code: -32601, message: 'Method not found: ' + method };
|
||||
return this.hooks.readTextFile(params);
|
||||
}
|
||||
if (method === 'fs/write_text_file') {
|
||||
if (!this.hooks.writeTextFile) throw { code: -32601, message: 'Method not found: ' + method };
|
||||
return Promise.resolve(this.hooks.writeTextFile(params)).then(() => ({}));
|
||||
}
|
||||
if (method === '_lembas/show') return this._onShow(agent, params);
|
||||
throw { code: -32601, message: 'Method not found: ' + method };
|
||||
}
|
||||
|
||||
_onPermission(p) {
|
||||
const call = (p && p.toolCall) || {};
|
||||
const lembas = (p && p._meta && p._meta.lembas) || {};
|
||||
const options = (Array.isArray(p && p.options) ? p.options : [])
|
||||
.filter((o) => o && typeof o.optionId === 'string')
|
||||
.map((o) => ({ optionId: o.optionId, name: String(o.name || o.optionId), kind: String(o.kind || '') }));
|
||||
const diffs = diffItems(call.content);
|
||||
const text = (Array.isArray(call.content) ? call.content : [])
|
||||
.map((c) => (c && c.type === 'content' && c.content && c.content.type === 'text' ? c.content.text : c && c.type === 'text' ? c.text : ''))
|
||||
.filter((t) => typeof t === 'string' && t)
|
||||
.join('\n');
|
||||
const item = this.add({
|
||||
kind: 'card',
|
||||
toolCallId: String(call.toolCallId || ''),
|
||||
title: String(call.title || lembas.tool || 'a tool'),
|
||||
tool: typeof lembas.tool === 'string' ? lembas.tool : '',
|
||||
reason: typeof lembas.reason === 'string' ? lembas.reason : '',
|
||||
detail: text.length > DETAIL_MAX ? text.slice(0, DETAIL_MAX) + '\n…' : text,
|
||||
files: diffs.map((d) => d.path),
|
||||
options,
|
||||
state: 'open',
|
||||
answer: '',
|
||||
});
|
||||
this.said = 'tool';
|
||||
return new Promise((resolve) => {
|
||||
const card = { item, resolve, diffs };
|
||||
this.cards.set(item.id, card);
|
||||
if (diffs.length && this.hooks.showDiffs) {
|
||||
try {
|
||||
this.hooks.showDiffs(item.id, diffs, item.title);
|
||||
} catch {
|
||||
// the card itself still asks
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** The person's answer to a card. */
|
||||
answer(cardId, optionId) {
|
||||
const card = this.cards.get(cardId);
|
||||
if (!card) return false;
|
||||
const option = card.item.options.find((o) => o.optionId === optionId);
|
||||
if (!option) return false;
|
||||
this._close(card, 'answered', option.name);
|
||||
card.resolve({ outcome: { outcome: 'selected', optionId } });
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Show a card's diffs again. */
|
||||
reshow(cardId) {
|
||||
const card = this.cards.get(cardId);
|
||||
if (card && card.diffs.length && this.hooks.showDiffs) this.hooks.showDiffs(cardId, card.diffs, card.item.title);
|
||||
}
|
||||
|
||||
_settle(card, why) {
|
||||
this._close(card, 'settled', why);
|
||||
card.resolve({ outcome: { outcome: 'cancelled' } });
|
||||
}
|
||||
|
||||
_close(card, state, answer) {
|
||||
this.cards.delete(card.item.id);
|
||||
card.item.state = state;
|
||||
card.item.answer = answer;
|
||||
this.changed(card.item);
|
||||
if (card.diffs.length && this.hooks.closeDiffs) {
|
||||
try {
|
||||
this.hooks.closeDiffs(card.item.id);
|
||||
} catch {
|
||||
// a tab that is already closed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async _onShow(agent, p) {
|
||||
if (!p || p.sessionId !== this.session) return { shown: false, reason: 'This is not the session the editor shows.' };
|
||||
if (typeof p.handle === 'string') {
|
||||
if (!this.hooks.showMedia) return { shown: false, reason: 'This editor cannot show files.' };
|
||||
const got = await this.hooks.showMedia(p, (q) => agent.request('_lembas/show/read', q));
|
||||
if (!got || !got.ok) {
|
||||
const reason = (got && got.reason) || 'The file could not be shown.';
|
||||
this.note(`${(got && got.name) || 'A file'} was not shown: ${reason}`);
|
||||
return { shown: false, reason };
|
||||
}
|
||||
this.add({ kind: 'media', name: got.name, size: got.size, picture: !!got.picture, src: got.src || '', key: got.key || '', opens: !!got.open });
|
||||
this.said = 'tool';
|
||||
return { shown: true };
|
||||
}
|
||||
if (typeof p.text === 'string' && this.hooks.showText) {
|
||||
const r = await this.hooks.showText(p);
|
||||
if (r && r.shown) {
|
||||
this.note(`Shown: ${String(p.path || 'a file')}`);
|
||||
return { shown: true };
|
||||
}
|
||||
return { shown: false, reason: (r && r.reason) || 'The file could not be shown.' };
|
||||
}
|
||||
return { shown: false, reason: 'This editor cannot show that.' };
|
||||
}
|
||||
|
||||
dispose() {
|
||||
if (this.agent) this.agent.stop();
|
||||
}
|
||||
}
|
||||
|
||||
function diffItems(content) {
|
||||
const out = [];
|
||||
for (const c of Array.isArray(content) ? content : []) {
|
||||
if (c && c.type === 'diff' && typeof c.path === 'string' && typeof c.newText === 'string') {
|
||||
out.push({
|
||||
path: c.path,
|
||||
oldText: typeof c.oldText === 'string' ? c.oldText : null,
|
||||
newText: c.newText,
|
||||
deleted: !!(c._meta && c._meta.lembas && c._meta.lembas.deleted),
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = { Chat, diffItems };
|
||||
@@ -0,0 +1,138 @@
|
||||
'use strict';
|
||||
// Autocomplete on `_lembas/complete`: the waiting before a request is sent, the cancelling of
|
||||
// the one before it, and what happens to an answer nobody waits for any more. No `vscode` here.
|
||||
|
||||
const REFUSALS = new Set(['no_model', 'not_allowed', 'not_logged_in', 'unsupported']);
|
||||
|
||||
/** The text around the cursor that is sent: a window, not the file. */
|
||||
function windowAround(text, offset, limits) {
|
||||
const prefixMax = (limits && limits.prefixMax) || 12000;
|
||||
const suffixMax = (limits && limits.suffixMax) || 4000;
|
||||
const at = Math.max(0, Math.min(offset, text.length));
|
||||
let start = Math.max(0, at - prefixMax);
|
||||
let end = Math.min(text.length, at + suffixMax);
|
||||
// Never cut a surrogate pair in two.
|
||||
if (start > 0 && isLow(text.charCodeAt(start))) start += 1;
|
||||
if (end < text.length && isLow(text.charCodeAt(end))) end -= 1;
|
||||
return { prefix: text.slice(start, at), suffix: text.slice(at, end) };
|
||||
}
|
||||
|
||||
function isLow(code) {
|
||||
return code >= 0xdc00 && code <= 0xdfff;
|
||||
}
|
||||
|
||||
class Completer {
|
||||
/**
|
||||
* @param {{ request: (method: string, params: object) => Promise<any>,
|
||||
* notify: (method: string, params: object) => void,
|
||||
* debounceMs?: () => number,
|
||||
* model?: () => string | undefined,
|
||||
* maxTokens?: () => number | undefined,
|
||||
* onRefusal?: (reason: string, message: string, manual: boolean) => void,
|
||||
* onError?: (message: string, manual: boolean) => void,
|
||||
* setTimeout?: Function, clearTimeout?: Function, now?: () => number }} io
|
||||
*/
|
||||
constructor(io) {
|
||||
this.io = io;
|
||||
this.seq = 0;
|
||||
this.pending = null; // { seq, timer, id, sent, finish }
|
||||
this.blocked = ''; // the refusal that stopped asking as you type
|
||||
this.pausedUntil = 0;
|
||||
this.setTimeout = io.setTimeout || setTimeout;
|
||||
this.clearTimeout = io.clearTimeout || clearTimeout;
|
||||
this.now = io.now || Date.now;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask for the text that belongs at the cursor. Resolves with the text, or with `null` when
|
||||
* there is nothing to show: a newer request took its place, it was cancelled, the answer was
|
||||
* empty, or asking is stopped. Never rejects.
|
||||
* @param {{ prefix: string, suffix?: string, path?: string, language?: string }} what
|
||||
* @param {{ manual?: boolean }} [how]
|
||||
*/
|
||||
ask(what, how) {
|
||||
const manual = !!(how && how.manual);
|
||||
this.cancel(); // the one before this, waiting or sent
|
||||
if (!manual && (this.blocked || this.now() < this.pausedUntil)) return Promise.resolve(null);
|
||||
const seq = ++this.seq;
|
||||
return new Promise((resolve) => {
|
||||
const entry = { seq, id: 'c' + seq, sent: false, timer: null, finish: null };
|
||||
entry.finish = (value) => {
|
||||
if (entry.timer !== null) this.clearTimeout(entry.timer);
|
||||
entry.timer = null;
|
||||
if (this.pending === entry) this.pending = null;
|
||||
entry.finish = () => {};
|
||||
resolve(value);
|
||||
};
|
||||
this.pending = entry;
|
||||
const wait = manual ? 0 : Math.max(0, Number(this.io.debounceMs ? this.io.debounceMs() : 250) || 0);
|
||||
const go = () => {
|
||||
entry.timer = null;
|
||||
this._send(entry, what, manual);
|
||||
};
|
||||
if (wait === 0) go();
|
||||
else entry.timer = this.setTimeout(go, wait);
|
||||
});
|
||||
}
|
||||
|
||||
_send(entry, what, manual) {
|
||||
entry.sent = true;
|
||||
const params = { id: entry.id, prefix: what.prefix, suffix: what.suffix || '' };
|
||||
if (what.path) params.path = what.path;
|
||||
if (what.language) params.language = what.language;
|
||||
const model = this.io.model ? this.io.model() : undefined;
|
||||
if (model) params.model = model;
|
||||
const maxTokens = this.io.maxTokens ? this.io.maxTokens() : undefined;
|
||||
if (maxTokens) params.max_tokens = maxTokens;
|
||||
let asked;
|
||||
try {
|
||||
asked = Promise.resolve(this.io.request('_lembas/complete', params));
|
||||
} catch (e) {
|
||||
asked = Promise.reject(e);
|
||||
}
|
||||
asked.then(
|
||||
(r) => {
|
||||
// An answer to a request that is no longer the newest is thrown away, whatever it says.
|
||||
if (this.pending !== entry) return;
|
||||
if (manual && this.blocked) this.blocked = '';
|
||||
if (!r || r.cancelled || typeof r.text !== 'string' || r.text === '') return entry.finish(null);
|
||||
entry.finish(r.text);
|
||||
},
|
||||
(e) => {
|
||||
const reason = e && e.data && typeof e.data.reason === 'string' ? e.data.reason : '';
|
||||
const message = (e && e.message) || 'the completion failed';
|
||||
if (REFUSALS.has(reason)) {
|
||||
// Said once; as-you-type then stays quiet until a model is set (or it is asked by hand).
|
||||
const first = this.blocked !== reason;
|
||||
this.blocked = reason;
|
||||
if ((first || manual) && this.io.onRefusal) this.io.onRefusal(reason, message, manual);
|
||||
} else {
|
||||
this.pausedUntil = this.now() + 15000;
|
||||
if (this.io.onError) this.io.onError(message, manual);
|
||||
}
|
||||
if (this.pending === entry) entry.finish(null);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Stop what is waited for: the editor moved on. `seq` limits it to that request. */
|
||||
cancel(seq) {
|
||||
const entry = this.pending;
|
||||
if (!entry || (seq !== undefined && entry.seq !== seq)) return;
|
||||
if (entry.sent) this.io.notify('_lembas/complete/cancel', { id: entry.id });
|
||||
entry.finish(null);
|
||||
}
|
||||
|
||||
/** The number of the request now waited for, for `cancel(seq)`. */
|
||||
get current() {
|
||||
return this.pending ? this.pending.seq : 0;
|
||||
}
|
||||
|
||||
/** A model was chosen, or the agent started again: ask as you type again. */
|
||||
unblock() {
|
||||
this.blocked = '';
|
||||
this.pausedUntil = 0;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Completer, windowAround, REFUSALS };
|
||||
@@ -0,0 +1,106 @@
|
||||
'use strict';
|
||||
// What the editor knows and the agent is told with a prompt (`_meta.lembas.editor`), and the
|
||||
// answer to the agent's question for a file's text. No `vscode` here.
|
||||
|
||||
const LIMITS = { diagnostics: 20, diagnosticChars: 300, open: 30, selectionChars: 20000 };
|
||||
const SEVERITIES = ['error', 'warning', 'info', 'hint'];
|
||||
|
||||
function oneLine(text, max) {
|
||||
const flat = String(text).replace(/\s+/g, ' ').trim();
|
||||
return flat.length > max ? flat.slice(0, max - 1) + '…' : flat;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `editor` object of a prompt, from plain data. Lines are 1-based, a selection's range
|
||||
* inclusive. Returns `undefined` when there is nothing to say.
|
||||
* @param {{ path?: string, cursorLine?: number,
|
||||
* selection?: { path?: string, start: number, end: number, text?: string },
|
||||
* diagnostics?: { path?: string, line?: number, severity?: string, message: string, source?: string }[],
|
||||
* open?: string[] }} seen
|
||||
*/
|
||||
function editorContext(seen) {
|
||||
if (!seen) return undefined;
|
||||
const out = {};
|
||||
if (seen.path) out.path = seen.path;
|
||||
if (Number.isInteger(seen.cursorLine) && seen.cursorLine > 0) out.cursor = { line: seen.cursorLine };
|
||||
if (seen.selection && Number.isInteger(seen.selection.start) && Number.isInteger(seen.selection.end)) {
|
||||
const s = seen.selection;
|
||||
out.selection = { start: Math.max(1, s.start), end: Math.max(s.start, s.end) };
|
||||
if (s.path && s.path !== seen.path) out.selection.path = s.path;
|
||||
if (typeof s.text === 'string') out.selection.text = s.text;
|
||||
}
|
||||
const diagnostics = [];
|
||||
for (const d of seen.diagnostics || []) {
|
||||
if (!d || typeof d.message !== 'string' || !d.message.trim()) continue;
|
||||
if (diagnostics.length >= LIMITS.diagnostics) break;
|
||||
const item = { message: oneLine(d.message, LIMITS.diagnosticChars) };
|
||||
if (d.path) item.path = d.path;
|
||||
if (Number.isInteger(d.line) && d.line > 0) item.line = d.line;
|
||||
if (SEVERITIES.includes(d.severity)) item.severity = d.severity;
|
||||
if (d.source) item.source = oneLine(d.source, 60);
|
||||
diagnostics.push(item);
|
||||
}
|
||||
if (diagnostics.length) out.diagnostics = diagnostics;
|
||||
const open = [];
|
||||
for (const p of seen.open || []) {
|
||||
if (typeof p !== 'string' || !p || p === seen.path || open.includes(p)) continue;
|
||||
if (open.length >= LIMITS.open) break;
|
||||
open.push(p);
|
||||
}
|
||||
if (open.length) out.open = open;
|
||||
return Object.keys(out).length ? out : undefined;
|
||||
}
|
||||
|
||||
/** How a selection is named in the transcript: `file.py:3-9`. */
|
||||
function selectionLabel(name, start, end) {
|
||||
return `${name || 'untitled'}:${start}${end !== start ? '-' + end : ''}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The params of `session/prompt` for a typed text and what the editor shows. An agent that
|
||||
* lists the capability `editor` gets the context as `_meta.lembas.editor`; an older one gets a
|
||||
* sentence and the selected text in front of the prompt, as the prompt's own blocks.
|
||||
*/
|
||||
function promptParams(sessionId, text, editor, agentReadsEditor) {
|
||||
const params = { sessionId, prompt: [] };
|
||||
if (editor && agentReadsEditor) {
|
||||
params._meta = { lembas: { editor } };
|
||||
} else if (editor) {
|
||||
const sel = editor.selection;
|
||||
const where = (sel && sel.path) || editor.path || 'an unsaved file';
|
||||
if (sel) {
|
||||
params.prompt.push({ type: 'text', text: `Selected in the editor: ${where}, lines ${sel.start}-${sel.end}.` });
|
||||
if (typeof sel.text === 'string') {
|
||||
params.prompt.push({
|
||||
type: 'resource',
|
||||
resource: { uri: `untitled:selection#L${sel.start}-${sel.end}`, mimeType: 'text/plain', text: sel.text },
|
||||
});
|
||||
}
|
||||
} else if (editor.path) {
|
||||
const at = editor.cursor ? `, cursor on line ${editor.cursor.line}` : '';
|
||||
params.prompt.push({ type: 'text', text: `Open in the editor: ${editor.path}${at}.` });
|
||||
}
|
||||
if (editor.diagnostics && editor.diagnostics.length) {
|
||||
const lines = editor.diagnostics.map(
|
||||
(d) => `- ${d.line ? 'line ' + d.line + ', ' : ''}${d.severity || 'info'}${d.source ? ' (' + d.source + ')' : ''}: ${d.message}`,
|
||||
);
|
||||
params.prompt.push({ type: 'text', text: 'Diagnostics the editor shows there:\n' + lines.join('\n') });
|
||||
}
|
||||
}
|
||||
params.prompt.push({ type: 'text', text });
|
||||
return params;
|
||||
}
|
||||
|
||||
/**
|
||||
* The part of a text ACP's `fs/read_text_file` asks for: from `line` (1-based), at most `limit`
|
||||
* lines. Without either, the whole text.
|
||||
*/
|
||||
function sliceLines(text, line, limit) {
|
||||
const from = Number.isFinite(Number(line)) && Number(line) > 1 ? Math.floor(Number(line)) : 1;
|
||||
const count = Number.isFinite(Number(limit)) && Number(limit) >= 0 && limit !== null && limit !== undefined ? Math.floor(Number(limit)) : null;
|
||||
if (from === 1 && count === null) return text;
|
||||
const lines = String(text).split('\n');
|
||||
return lines.slice(from - 1, count === null ? undefined : from - 1 + count).join('\n');
|
||||
}
|
||||
|
||||
module.exports = { editorContext, promptParams, selectionLabel, sliceLines, LIMITS };
|
||||
@@ -0,0 +1,188 @@
|
||||
'use strict';
|
||||
// A rewrite shown before it is made: the proposed lines against the lines now, as hunks that are
|
||||
// accepted or rejected one by one. Lines are 0-based here. No `vscode` here.
|
||||
|
||||
const MAX_EDIT_DISTANCE = 4000;
|
||||
|
||||
function splitLines(text) {
|
||||
return String(text).replace(/\r\n/g, '\n').split('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* The differences between two lists of lines (Myers' algorithm), as
|
||||
* `{ aStart, aCount, bStart, bCount }` in order. Lists too different to compare in reasonable
|
||||
* time come back as one hunk that replaces everything between their common ends.
|
||||
*/
|
||||
function diffLines(a, b) {
|
||||
let head = 0;
|
||||
while (head < a.length && head < b.length && a[head] === b[head]) head++;
|
||||
let tail = 0;
|
||||
while (tail < a.length - head && tail < b.length - head && a[a.length - 1 - tail] === b[b.length - 1 - tail]) tail++;
|
||||
const n = a.length - head - tail;
|
||||
const m = b.length - head - tail;
|
||||
if (n === 0 && m === 0) return [];
|
||||
if (n === 0 || m === 0) return [{ aStart: head, aCount: n, bStart: head, bCount: m }];
|
||||
|
||||
const max = Math.min(n + m, MAX_EDIT_DISTANCE);
|
||||
const offset = max + 1;
|
||||
let v = new Int32Array(2 * max + 3);
|
||||
const trace = [];
|
||||
let found = -1;
|
||||
for (let d = 0; d <= max && found < 0; d++) {
|
||||
trace.push(v.slice());
|
||||
for (let k = -d; k <= d; k += 2) {
|
||||
let x;
|
||||
if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])) x = v[offset + k + 1];
|
||||
else x = v[offset + k - 1] + 1;
|
||||
let y = x - k;
|
||||
while (x < n && y < m && a[head + x] === b[head + y]) {
|
||||
x++;
|
||||
y++;
|
||||
}
|
||||
v[offset + k] = x;
|
||||
if (x >= n && y >= m) {
|
||||
found = d;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (found < 0) return [{ aStart: head, aCount: n, bStart: head, bCount: m }];
|
||||
|
||||
// Walk back from the end, collecting the single steps.
|
||||
const steps = []; // { x, y, del } : a line of a deleted at x, or a line of b inserted at y
|
||||
let x = n;
|
||||
let y = m;
|
||||
for (let d = found; d > 0; d--) {
|
||||
const prev = trace[d];
|
||||
const k = x - y;
|
||||
let prevK;
|
||||
if (k === -d || (k !== d && prev[offset + k - 1] < prev[offset + k + 1])) prevK = k + 1;
|
||||
else prevK = k - 1;
|
||||
const prevX = prev[offset + prevK];
|
||||
const prevY = prevX - prevK;
|
||||
while (x > prevX && y > prevY) {
|
||||
x--;
|
||||
y--;
|
||||
}
|
||||
if (x === prevX) steps.push({ x: prevX, y: prevY, del: false });
|
||||
else steps.push({ x: prevX, y: prevY, del: true });
|
||||
x = prevX;
|
||||
y = prevY;
|
||||
}
|
||||
steps.reverse();
|
||||
|
||||
const hunks = [];
|
||||
let cur = null;
|
||||
for (const s of steps) {
|
||||
const ax = head + s.x;
|
||||
const by = head + s.y;
|
||||
if (cur && cur.aStart + cur.aCount === ax && cur.bStart + cur.bCount === by) {
|
||||
if (s.del) cur.aCount++;
|
||||
else cur.bCount++;
|
||||
} else {
|
||||
cur = { aStart: ax, aCount: s.del ? 1 : 0, bStart: by, bCount: s.del ? 0 : 1 };
|
||||
hunks.push(cur);
|
||||
}
|
||||
}
|
||||
return hunks;
|
||||
}
|
||||
|
||||
/**
|
||||
* A rewrite of the document's lines `first .. first + oldLines.length - 1` as pending hunks.
|
||||
* Each hunk: `{ id, line, old: string[], new: string[] }` — `line` is where its old lines start
|
||||
* in the document now, or, when it only adds lines, the line they go in front of.
|
||||
*/
|
||||
function propose(first, oldLines, newLines) {
|
||||
return diffLines(oldLines, newLines).map((h, i) => ({
|
||||
id: i + 1,
|
||||
line: first + h.aStart,
|
||||
old: oldLines.slice(h.aStart, h.aStart + h.aCount),
|
||||
new: newLines.slice(h.bStart, h.bStart + h.bCount),
|
||||
}));
|
||||
}
|
||||
|
||||
/** Whether the document still says, at the hunk, what the hunk was made against. */
|
||||
function stillFits(hunk, lineAt, lineCount) {
|
||||
if (hunk.line < 0 || hunk.line + hunk.old.length > lineCount) return false;
|
||||
if (hunk.old.length === 0) return hunk.line <= lineCount;
|
||||
for (let i = 0; i < hunk.old.length; i++) if (lineAt(hunk.line + i) !== hunk.old[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one text edit that accepts a hunk in a document of `lineCount` lines:
|
||||
* `{ start: { line, end }, stop: { line, end }, text }` — a position is the start of its line,
|
||||
* or the line's end when `end` is true. Line breaks in `text` are "\n"; the caller puts the
|
||||
* document's own in.
|
||||
*/
|
||||
function editFor(hunk, lineCount) {
|
||||
const text = hunk.new.join('\n');
|
||||
if (hunk.old.length === 0) {
|
||||
if (hunk.line >= lineCount) {
|
||||
// After the last line.
|
||||
const last = Math.max(0, lineCount - 1);
|
||||
return { start: { line: last, end: true }, stop: { line: last, end: true }, text: '\n' + text };
|
||||
}
|
||||
return { start: { line: hunk.line, end: false }, stop: { line: hunk.line, end: false }, text: text + '\n' };
|
||||
}
|
||||
const lastOld = hunk.line + hunk.old.length - 1;
|
||||
if (hunk.new.length > 0) {
|
||||
return { start: { line: hunk.line, end: false }, stop: { line: lastOld, end: true }, text };
|
||||
}
|
||||
// Lines taken away, with their line break.
|
||||
if (lastOld + 1 < lineCount) {
|
||||
return { start: { line: hunk.line, end: false }, stop: { line: lastOld + 1, end: false }, text: '' };
|
||||
}
|
||||
if (hunk.line > 0) {
|
||||
return { start: { line: hunk.line - 1, end: true }, stop: { line: lastOld, end: true }, text: '' };
|
||||
}
|
||||
return { start: { line: 0, end: false }, stop: { line: lastOld, end: true }, text: '' };
|
||||
}
|
||||
|
||||
/** The hunks left after one was accepted: those below it move by what it added or took away. */
|
||||
function afterAccept(hunks, accepted) {
|
||||
const delta = accepted.new.length - accepted.old.length;
|
||||
return hunks
|
||||
.filter((h) => h !== accepted)
|
||||
.map((h) => (h.line > accepted.line || (h.line === accepted.line && h.id > accepted.id) ? { ...h, line: h.line + delta } : h));
|
||||
}
|
||||
|
||||
/**
|
||||
* The hunks left after the document changed by somebody else's hand: lines `startLine ..
|
||||
* endLine` (inclusive) were replaced by `newLineCount` lines. A hunk above the change stays, one
|
||||
* below it moves, and one the change reaches into is dropped — its text is no longer what was
|
||||
* shown.
|
||||
*/
|
||||
function afterChange(hunks, change) {
|
||||
const delta = change.newLineCount - (change.endLine - change.startLine + 1);
|
||||
const out = [];
|
||||
for (const h of hunks) {
|
||||
if (h.old.length === 0) {
|
||||
// Lines to add in front of `line`: a change at or below that line leaves the place alone.
|
||||
if (change.startLine >= h.line) out.push(h);
|
||||
else if (change.endLine < h.line) out.push({ ...h, line: h.line + delta });
|
||||
continue;
|
||||
}
|
||||
const last = h.line + h.old.length - 1;
|
||||
if (last < change.startLine) out.push(h);
|
||||
else if (h.line > change.endLine) out.push({ ...h, line: h.line + delta });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The whole text as it would be with every pending hunk accepted (for the diff view). */
|
||||
function withAll(lines, hunks) {
|
||||
const out = lines.slice();
|
||||
const ordered = hunks.slice().sort((p, q) => q.line - p.line || q.id - p.id);
|
||||
for (const h of ordered) out.splice(h.line, h.old.length, ...h.new);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The lines a selection covers: whole lines, and not the line a selection merely ends in front of. */
|
||||
function wholeLines(sel) {
|
||||
let last = sel.endLine;
|
||||
if (last > sel.startLine && sel.endCharacter === 0) last -= 1;
|
||||
return { first: sel.startLine, last };
|
||||
}
|
||||
|
||||
module.exports = { splitLines, diffLines, propose, stillFits, editFor, afterAccept, afterChange, withAll, wholeLines };
|
||||
@@ -0,0 +1,363 @@
|
||||
'use strict';
|
||||
// A small Markdown reader for what a model writes. It makes a tree of plain objects and never
|
||||
// a string of markup: the chat view builds elements from the tree with `createElement` and
|
||||
// `textContent`, so nothing a model writes is ever parsed as HTML. Raw HTML in the text stays
|
||||
// text. No `vscode` here.
|
||||
//
|
||||
// Blocks: { t: 'p', c } { t: 'h', l, c } { t: 'pre', lang, v } { t: 'hr' }
|
||||
// { t: 'quote', c: blocks } { t: 'ul' | 'ol', items: [{ d, c }] } { t: 'plain', v }
|
||||
// Inline: { t: 'text', v } { t: 'code', v } { t: 'b', c } { t: 'i', c }
|
||||
// { t: 'a', href, c } { t: 'br' }
|
||||
|
||||
const MAX_DEPTH = 6;
|
||||
// What a model writes is not trusted to be short or kind. Three bounds keep the reading of it
|
||||
// linear: a text longer than MAX_CHARS is shown as it was written; a line longer than MAX_LINE
|
||||
// is never matched against the block patterns; and the searches for a closing mark (emphasis,
|
||||
// a link's bracket) draw on one budget of steps per parse — when it is spent, the rest of the
|
||||
// text is plain text.
|
||||
const MAX_CHARS = 400000;
|
||||
const MAX_LINE = 4000;
|
||||
const BUDGET = 400000;
|
||||
const LABEL_MAX = 1000;
|
||||
|
||||
/** A link the chat may offer to open: http, https or mailto, and nothing else. */
|
||||
function safeHref(url) {
|
||||
if (typeof url !== 'string' || url.length > 2000) return null;
|
||||
// eslint-disable-next-line no-control-regex
|
||||
if (/[\u0000- \u007f"<>`\\]/.test(url)) return null;
|
||||
if (/^https?:\/\/[^/?#]+/i.test(url) || /^mailto:[^@\s]+@[^@\s]+$/i.test(url)) return url;
|
||||
return null;
|
||||
}
|
||||
|
||||
function pushText(out, v) {
|
||||
if (!v) return;
|
||||
const last = out[out.length - 1];
|
||||
if (last && last.t === 'text') last.v += v;
|
||||
else out.push({ t: 'text', v });
|
||||
}
|
||||
|
||||
function isWord(ch) {
|
||||
return ch !== undefined && /[\p{L}\p{N}]/u.test(ch);
|
||||
}
|
||||
|
||||
function findClosing(s, from, marker, work) {
|
||||
for (let i = from; i < s.length; i++) {
|
||||
if (--work.left < 0) return -1;
|
||||
if (s[i] === '\\') {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (s[i] === '`') {
|
||||
// Skip a code span whole.
|
||||
let n = 1;
|
||||
while (s[i + n] === '`') n++;
|
||||
const close = s.indexOf('`'.repeat(n), i + n);
|
||||
if (close < 0) return -1;
|
||||
i = close + n - 1;
|
||||
continue;
|
||||
}
|
||||
if (s.startsWith(marker, i)) {
|
||||
if (i === from) continue; // empty
|
||||
if (/\s/.test(s[i - 1])) continue;
|
||||
if (marker[0] === '_' && isWord(s[i + marker.length])) continue;
|
||||
if (marker.length === 1 && s[i + 1] === marker) {
|
||||
// A double marker inside single emphasis belongs to something else.
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function parseInline(s, depth, budget) {
|
||||
const out = [];
|
||||
const deep = (depth || 0) >= MAX_DEPTH;
|
||||
const work = budget || { left: BUDGET };
|
||||
const noTicks = {}; // run length -> no closing run of that length from here on
|
||||
let i = 0;
|
||||
while (i < s.length) {
|
||||
if (work.left < 0) {
|
||||
// The budget is spent: the rest is text, line breaks kept.
|
||||
const rest = s.slice(i).split('\n');
|
||||
rest.forEach((line, n) => {
|
||||
if (n) out.push({ t: 'br' });
|
||||
pushText(out, line);
|
||||
});
|
||||
break;
|
||||
}
|
||||
const ch = s[i];
|
||||
if (ch === '\n') {
|
||||
out.push({ t: 'br' });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '\\' && i + 1 < s.length && /[!-/:-@[-`{-~]/.test(s[i + 1])) {
|
||||
pushText(out, s[i + 1]);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (ch === '`') {
|
||||
let n = 1;
|
||||
while (s[i + n] === '`') n++;
|
||||
const close = noTicks[n] ? -1 : s.indexOf('`'.repeat(n), i + n);
|
||||
if (close < 0) noTicks[n] = true;
|
||||
if (close >= 0) {
|
||||
let v = s.slice(i + n, close).replace(/\n/g, ' ');
|
||||
if (v.length > 2 && v.startsWith(' ') && v.endsWith(' ')) v = v.slice(1, -1);
|
||||
out.push({ t: 'code', v });
|
||||
i = close + n;
|
||||
continue;
|
||||
}
|
||||
pushText(out, '`'.repeat(n));
|
||||
i += n;
|
||||
continue;
|
||||
}
|
||||
if (!deep && (ch === '*' || ch === '_')) {
|
||||
const double = s[i + 1] === ch;
|
||||
const marker = double ? ch + ch : ch;
|
||||
const next = s[i + marker.length];
|
||||
const opens = next !== undefined && !/\s/.test(next) && !(ch === '_' && isWord(s[i - 1]));
|
||||
if (opens) {
|
||||
const close = findClosing(s, i + marker.length, marker, work);
|
||||
if (close > 0) {
|
||||
out.push({ t: double ? 'b' : 'i', c: parseInline(s.slice(i + marker.length, close), (depth || 0) + 1, work) });
|
||||
i = close + marker.length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
pushText(out, marker);
|
||||
i += marker.length;
|
||||
continue;
|
||||
}
|
||||
if (!deep && (ch === '[' || (ch === '!' && s[i + 1] === '['))) {
|
||||
const open = ch === '!' ? i + 1 : i;
|
||||
let level = 0;
|
||||
let close = -1;
|
||||
for (let j = open; j < s.length && j < open + LABEL_MAX; j++) {
|
||||
if (--work.left < 0) break;
|
||||
if (s[j] === '\\') j++;
|
||||
else if (s[j] === '[') level++;
|
||||
else if (s[j] === ']' && --level === 0) {
|
||||
close = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (close > 0 && s[close + 1] === '(') {
|
||||
let end = -1;
|
||||
let parens = 0;
|
||||
for (let j = close + 1; j < s.length && j < close + 2100; j++) {
|
||||
if (--work.left < 0) break;
|
||||
if (s[j] === '(') parens++;
|
||||
else if (s[j] === ')' && --parens === 0) {
|
||||
end = j;
|
||||
break;
|
||||
} else if (s[j] === '\n') break;
|
||||
}
|
||||
if (end > 0) {
|
||||
const inside = s.slice(close + 2, end).trim();
|
||||
const url = inside.split(/\s+/)[0].replace(/^<|>$/g, '');
|
||||
const href = safeHref(url);
|
||||
const label = s.slice(open + 1, close);
|
||||
if (href) {
|
||||
// A picture is never loaded: it is a link like any other.
|
||||
const c = ch === '!' ? [{ t: 'text', v: label || href }] : parseInline(label, (depth || 0) + 1, work);
|
||||
out.push({ t: 'a', href, c: c.length ? c : [{ t: 'text', v: href }] });
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
// Not a link the chat opens: shown as it was written.
|
||||
pushText(out, s.slice(i, end + 1));
|
||||
i = end + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
pushText(out, ch);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === 'h' && !isWord(s[i - 1])) {
|
||||
const m = /^https?:\/\/[^\s<>()[\]"'`\\]+/i.exec(s.slice(i, i + 2000));
|
||||
if (m) {
|
||||
const raw = m[0].replace(/[.,;:!?*_]+$/, '');
|
||||
const href = safeHref(raw);
|
||||
if (href) {
|
||||
out.push({ t: 'a', href, c: [{ t: 'text', v: raw }] });
|
||||
i += raw.length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
pushText(out, ch);
|
||||
i++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/;
|
||||
const HEADING = /^ {0,3}(#{1,6})[ \t]+(\S.*)$/;
|
||||
const RULE = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/;
|
||||
const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
|
||||
const QUOTE = /^ {0,3}>\s?(.*)$/;
|
||||
|
||||
/** A heading's text without the closing run of # some write after it. */
|
||||
function headingText(text) {
|
||||
let end = text.length;
|
||||
while (end > 0 && (text[end - 1] === ' ' || text[end - 1] === '\t')) end--;
|
||||
let hashes = end;
|
||||
while (hashes > 0 && text[hashes - 1] === '#') hashes--;
|
||||
if (hashes < end && (hashes === 0 || text[hashes - 1] === ' ' || text[hashes - 1] === '\t')) end = hashes;
|
||||
while (end > 0 && (text[end - 1] === ' ' || text[end - 1] === '\t')) end--;
|
||||
return text.slice(0, end);
|
||||
}
|
||||
|
||||
/** Markdown text to a list of blocks. */
|
||||
function parse(src, depth, budget) {
|
||||
return read(src, depth, budget).blocks;
|
||||
}
|
||||
|
||||
/** As `parse`, and whether the text ended inside a fenced block that was not closed. */
|
||||
function read(src, depth, budget) {
|
||||
const level = depth || 0;
|
||||
const text = String(src === undefined || src === null ? '' : src).replace(/\r\n?/g, '\n');
|
||||
if (text.length > MAX_CHARS) return { blocks: [{ t: 'plain', v: text }], open: false };
|
||||
const work = budget || { left: BUDGET };
|
||||
const lines = text.split('\n');
|
||||
const blocks = [];
|
||||
let open = false;
|
||||
let openAt = -1; // where the fence that was not closed begins
|
||||
let para = [];
|
||||
const flush = () => {
|
||||
if (para.length) blocks.push({ t: 'p', c: parseInline(para.join('\n'), 0, work) });
|
||||
para = [];
|
||||
};
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (line.length > MAX_LINE) {
|
||||
para.push(line);
|
||||
continue;
|
||||
}
|
||||
const fence = FENCE.exec(line);
|
||||
if (fence) {
|
||||
flush();
|
||||
const mark = fence[1];
|
||||
const body = [];
|
||||
let j = i + 1;
|
||||
for (; j < lines.length; j++) {
|
||||
const t = lines[j].trim();
|
||||
if (t.startsWith(mark[0].repeat(mark.length)) && /^(`+|~+)$/.test(t)) break;
|
||||
body.push(lines[j]);
|
||||
}
|
||||
blocks.push({ t: 'pre', lang: fence[2].replace(/[^A-Za-z0-9_+#.-]/g, '').slice(0, 30), v: body.join('\n') });
|
||||
if (j >= lines.length) {
|
||||
open = true;
|
||||
openAt = 0;
|
||||
for (let k = 0; k < i; k++) openAt += lines[k].length + 1;
|
||||
}
|
||||
i = j; // an unclosed fence runs to the end: the text is still being written
|
||||
continue;
|
||||
}
|
||||
if (line.trim() === '') {
|
||||
flush();
|
||||
continue;
|
||||
}
|
||||
const heading = HEADING.exec(line);
|
||||
if (heading) {
|
||||
flush();
|
||||
blocks.push({ t: 'h', l: heading[1].length, c: parseInline(headingText(heading[2]), 0, work) });
|
||||
continue;
|
||||
}
|
||||
if (RULE.test(line)) {
|
||||
flush();
|
||||
blocks.push({ t: 'hr' });
|
||||
continue;
|
||||
}
|
||||
if (QUOTE.test(line) && level < MAX_DEPTH) {
|
||||
flush();
|
||||
const body = [];
|
||||
let j = i;
|
||||
for (; j < lines.length; j++) {
|
||||
const q = QUOTE.exec(lines[j]);
|
||||
if (!q) break;
|
||||
body.push(q[1]);
|
||||
}
|
||||
blocks.push({ t: 'quote', c: parse(body.join('\n'), level + 1, work) });
|
||||
i = j - 1;
|
||||
continue;
|
||||
}
|
||||
if (/^\s*\|/.test(line)) {
|
||||
// A table is kept as written, in the fixed-width face, so its columns still line up.
|
||||
flush();
|
||||
const body = [];
|
||||
let j = i;
|
||||
for (; j < lines.length && /^\s*\|/.test(lines[j]); j++) body.push(lines[j].trim());
|
||||
blocks.push({ t: 'pre', lang: '', v: body.join('\n') });
|
||||
i = j - 1;
|
||||
continue;
|
||||
}
|
||||
const item = ITEM.exec(line);
|
||||
if (item) {
|
||||
flush();
|
||||
const ordered = /\d/.test(item[2]);
|
||||
const base = item[1].length;
|
||||
const items = [];
|
||||
let j = i;
|
||||
for (; j < lines.length; j++) {
|
||||
const m = ITEM.exec(lines[j]);
|
||||
if (m) {
|
||||
const d = Math.max(0, Math.min(MAX_DEPTH - 1, Math.floor((m[1].replace(/\t/g, ' ').length - base) / 2)));
|
||||
items.push({ d, text: [m[3]] });
|
||||
} else if (lines[j].trim() !== '' && /^\s+/.test(lines[j]) && items.length && !FENCE.test(lines[j])) {
|
||||
items[items.length - 1].text.push(lines[j].trim());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
blocks.push({ t: ordered ? 'ol' : 'ul', items: items.map((it) => ({ d: it.d, c: parseInline(it.text.join('\n'), 0, work) })) });
|
||||
i = j - 1;
|
||||
continue;
|
||||
}
|
||||
para.push(line);
|
||||
}
|
||||
flush();
|
||||
return { blocks, open, openAt };
|
||||
}
|
||||
|
||||
/**
|
||||
* A reply read as it grows. Text that ends at a blank line outside a fenced block will never be
|
||||
* read differently, whatever follows, so it is read once and kept; only what comes after the
|
||||
* last such place is read again when more arrives. The result is always what `parse` gives for
|
||||
* the whole text.
|
||||
*/
|
||||
class Growing {
|
||||
constructor() {
|
||||
this.text = '';
|
||||
this.done = 0; // characters of `text` already read for good
|
||||
this.blocks = [];
|
||||
}
|
||||
|
||||
update(text) {
|
||||
const whole = String(text === undefined || text === null ? '' : text).replace(/\r\n?/g, '\n');
|
||||
if (whole.length > MAX_CHARS) return [{ t: 'plain', v: whole }];
|
||||
if (!whole.startsWith(this.text.slice(0, this.done))) {
|
||||
this.done = 0;
|
||||
this.blocks = [];
|
||||
}
|
||||
this.text = whole;
|
||||
let cut = whole.lastIndexOf('\n\n');
|
||||
for (let tries = 0; tries < 2 && cut >= this.done; tries++) {
|
||||
const piece = read(whole.slice(this.done, cut));
|
||||
if (!piece.open) {
|
||||
this.blocks.push(...piece.blocks);
|
||||
this.done = cut + 2;
|
||||
break;
|
||||
}
|
||||
// The blank line is inside a fenced block still being written: settle what is before it.
|
||||
cut = piece.openAt > 0 ? whole.lastIndexOf('\n\n', this.done + piece.openAt - 1) : -1;
|
||||
}
|
||||
return this.blocks.concat(read(whole.slice(this.done)).blocks);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { parse, parseInline, safeHref, Growing, MAX_CHARS };
|
||||
@@ -0,0 +1,187 @@
|
||||
'use strict';
|
||||
// Files the agent shows (`_lembas/show`): what a file is, read from its bytes, and the fetching
|
||||
// of those bytes through `_lembas/show/read`. No `vscode` here.
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
const PART = 1024 * 1024; // the most one answer carries
|
||||
|
||||
/** What the bytes are, when they are a picture the chat can draw; otherwise `null`. */
|
||||
function sniffPicture(buf) {
|
||||
if (!buf || buf.length < 12) return null;
|
||||
if (buf[0] === 0x89 && buf.toString('latin1', 1, 4) === 'PNG' && buf[4] === 0x0d && buf[5] === 0x0a) return { mime: 'image/png', ext: 'png' };
|
||||
if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return { mime: 'image/jpeg', ext: 'jpg' };
|
||||
const head = buf.toString('latin1', 0, 12);
|
||||
if (head.startsWith('GIF87a') || head.startsWith('GIF89a')) return { mime: 'image/gif', ext: 'gif' };
|
||||
if (head.startsWith('RIFF') && head.slice(8, 12) === 'WEBP') return { mime: 'image/webp', ext: 'webp' };
|
||||
if (head.slice(4, 8) === 'ftyp' && (head.slice(8, 12) === 'avif' || head.slice(8, 12) === 'avis')) return { mime: 'image/avif', ext: 'avif' };
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A size in words: "640 bytes", "48 KB", "1.4 MB" (1 MB is 1024 KB). */
|
||||
function sizeInWords(bytes) {
|
||||
const n = Number(bytes) || 0;
|
||||
if (n < 1024) return `${n} byte${n === 1 ? '' : 's'}`;
|
||||
if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;
|
||||
const mb = n / (1024 * 1024);
|
||||
if (mb < 1024) return `${Number.isInteger(mb) || mb >= 10 ? Math.round(mb) : mb.toFixed(1)} MB`;
|
||||
return `${(mb / 1024).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
/** A file name made only of harmless characters, from whatever path the agent gave. */
|
||||
function safeName(path, fallbackExt) {
|
||||
const base = String(path || '').split(/[\\/]/).pop() || '';
|
||||
let name = base.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '').slice(-80);
|
||||
if (!name) name = 'file';
|
||||
if (fallbackExt && !/\.[A-Za-z0-9]{1,8}$/.test(name)) name += '.' + fallbackExt;
|
||||
return name;
|
||||
}
|
||||
|
||||
// What Open may do with a shown file. Only kinds that are merely displayed are ever opened, and
|
||||
// only when the file's first bytes are that kind AND its name ends as that kind does: the system
|
||||
// chooses its program by the name, so a name the bytes do not back is never handed to it.
|
||||
// Everything else can only be shown in its folder.
|
||||
const TEXT_ENDINGS = new Set(['txt', 'text', 'log', 'md', 'markdown', 'csv', 'tsv', 'json', 'jsonl', 'yaml', 'yml', 'toml', 'ini', 'diff', 'patch']);
|
||||
const SHOWN_KINDS = [
|
||||
{ kind: 'pdf', endings: ['pdf'], is: (b) => b.toString('latin1', 0, 5) === '%PDF-' },
|
||||
{ kind: 'audio', endings: ['mp3'], is: (b) => b.toString('latin1', 0, 3) === 'ID3' || (b[0] === 0xff && (b[1] & 0xe6) === 0xe2) },
|
||||
{ kind: 'audio', endings: ['wav'], is: (b) => b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WAVE' },
|
||||
{ kind: 'audio', endings: ['ogg', 'oga', 'opus'], is: (b) => b.toString('latin1', 0, 4) === 'OggS' },
|
||||
{ kind: 'audio', endings: ['flac'], is: (b) => b.toString('latin1', 0, 4) === 'fLaC' },
|
||||
{ kind: 'audio', endings: ['m4a'], is: (b) => b.toString('latin1', 4, 8) === 'ftyp' && /^(M4A |M4B |mp42|isom)$/.test(b.toString('latin1', 8, 12)) },
|
||||
{ kind: 'video', endings: ['mp4', 'm4v'], is: (b) => b.toString('latin1', 4, 8) === 'ftyp' && /^(isom|iso[2-9]|mp41|mp42|avc1|M4V |dash)$/.test(b.toString('latin1', 8, 12)) },
|
||||
{ kind: 'video', endings: ['mov'], is: (b) => b.toString('latin1', 4, 8) === 'ftyp' && b.toString('latin1', 8, 12) === 'qt ' },
|
||||
{ kind: 'video', endings: ['webm', 'mkv'], is: (b) => b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3 },
|
||||
];
|
||||
const PICTURE_ENDINGS = { png: ['png'], jpg: ['jpg', 'jpeg'], gif: ['gif'], webp: ['webp'], avif: ['avif'] };
|
||||
|
||||
function ending(name) {
|
||||
const m = /\.([A-Za-z0-9]+)$/.exec(String(name || ''));
|
||||
return m ? m[1].toLowerCase() : '';
|
||||
}
|
||||
|
||||
function looksLikeText(buf) {
|
||||
if (!buf || buf.length === 0) return false;
|
||||
for (let i = 0; i < buf.length; i++) {
|
||||
const c = buf[i];
|
||||
if (c === 0 || (c < 0x20 && c !== 0x09 && c !== 0x0a && c !== 0x0d && c !== 0x0c)) return false;
|
||||
}
|
||||
// The window may end inside a character; up to three bytes are let go before judging.
|
||||
for (let cut = 0; cut <= 3 && cut < buf.length; cut++) {
|
||||
try {
|
||||
new TextDecoder('utf-8', { fatal: true }).decode(buf.subarray(0, buf.length - cut));
|
||||
return true;
|
||||
} catch {
|
||||
// try a shorter window
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* How a shown file may be opened, from its first bytes and its name:
|
||||
* `{ kind, how }` — `how` is `'editor'` (pictures and plain text: opened inside the editor, which
|
||||
* runs nothing) or `'system'` (pdf, sound, video: the system's viewer); or `null` when the file
|
||||
* may only be shown in its folder.
|
||||
*/
|
||||
function openable(head, name) {
|
||||
const end = ending(name);
|
||||
if (!head || !end) return null;
|
||||
const picture = sniffPicture(head);
|
||||
if (picture) return PICTURE_ENDINGS[picture.ext].includes(end) ? { kind: 'image', how: 'editor' } : null;
|
||||
let known = false;
|
||||
for (const k of SHOWN_KINDS) {
|
||||
if (head.length < 12 || !k.is(head)) continue;
|
||||
if (k.endings.includes(end)) return { kind: k.kind, how: 'system' };
|
||||
known = true;
|
||||
}
|
||||
if (known) return null; // the bytes are a kind the name does not say
|
||||
if (TEXT_ENDINGS.has(end) && looksLikeText(head)) return { kind: 'text', how: 'editor' };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a shown file to its end through `_lembas/show/read`.
|
||||
* @param {(params: object) => Promise<{ data: string, offset?: number, eof?: boolean }>} read
|
||||
* @param {{ handle: string, size?: number, hash?: string }} file
|
||||
* @param {{ maxBytes: number, length?: number }} limits
|
||||
* @returns {Promise<Buffer>} rejects with an Error whose message is a sentence for the person
|
||||
*/
|
||||
async function fetchShown(read, file, limits) {
|
||||
const max = limits.maxBytes;
|
||||
if (typeof file.size === 'number' && file.size > max) throw tooLarge(file.size, max);
|
||||
const parts = [];
|
||||
let offset = 0;
|
||||
for (let turn = 0; turn < 100000; turn++) {
|
||||
const r = await read({ handle: file.handle, offset, length: limits.length || PART });
|
||||
if (!r || typeof r.data !== 'string') throw new Error('The agent sent no data for the file.');
|
||||
const bytes = Buffer.from(r.data, 'base64');
|
||||
if (bytes.length > 0) {
|
||||
parts.push(bytes);
|
||||
offset += bytes.length;
|
||||
}
|
||||
if (offset > max) throw tooLarge(offset, max);
|
||||
if (r.eof) break;
|
||||
if (bytes.length === 0) throw new Error('The agent stopped sending the file before its end.');
|
||||
}
|
||||
const all = Buffer.concat(parts);
|
||||
if (typeof file.size === 'number' && all.length !== file.size) {
|
||||
throw new Error(`The file arrived as ${sizeInWords(all.length)}, not the ${sizeInWords(file.size)} the agent named.`);
|
||||
}
|
||||
if (typeof file.hash === 'string' && file.hash.startsWith('sha256:')) {
|
||||
const got = crypto.createHash('sha256').update(all).digest('hex');
|
||||
if (got !== file.hash.slice(7).toLowerCase()) throw new Error('The file did not arrive whole (its checksum differs).');
|
||||
}
|
||||
return all;
|
||||
}
|
||||
|
||||
function tooLarge(size, max) {
|
||||
return new Error(`The file is ${sizeInWords(size)}; this editor takes files of up to ${sizeInWords(max)}.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Take in a file the agent shows: find out what it is from its first bytes, and put it where
|
||||
* the editor can show or open it. A picture is always fetched into `dir`; anything else is
|
||||
* fetched only when the agent named no file on this machine (`uri`).
|
||||
* @param {object} p the params of `_lembas/show` (with a `handle`)
|
||||
* @param {(params: object) => Promise<object>} read `_lembas/show/read`
|
||||
* @param {{ dir: string, maxBytes: number, length?: number, fs?: object }} where
|
||||
* @returns {Promise<{ ok: boolean, reason?: string, name: string, size: number, picture: boolean,
|
||||
* mime?: string, file?: string, original?: string,
|
||||
* open: { kind: string, how: 'editor' | 'system' } | null }>}
|
||||
*/
|
||||
async function receiveShown(p, read, where) {
|
||||
const fs = where.fs || require('node:fs/promises');
|
||||
const path = require('node:path');
|
||||
const size = typeof p.size === 'number' ? p.size : undefined;
|
||||
const base = { ok: false, name: safeName(p.path), size: size || 0, picture: false };
|
||||
if (typeof p.handle !== 'string' || !p.handle) return { ...base, reason: 'The agent named no file to fetch.' };
|
||||
if (size !== undefined && size > where.maxBytes) return { ...base, reason: tooLarge(size, where.maxBytes).message };
|
||||
let original;
|
||||
if (typeof p.uri === 'string' && p.uri.startsWith('file:')) {
|
||||
try {
|
||||
original = require('node:url').fileURLToPath(p.uri);
|
||||
} catch {
|
||||
original = undefined;
|
||||
}
|
||||
}
|
||||
try {
|
||||
const head = await read({ handle: p.handle, offset: 0, length: 4096 });
|
||||
const first = Buffer.from(head && typeof head.data === 'string' ? head.data : '', 'base64');
|
||||
const picture = sniffPicture(first);
|
||||
if (!picture && original) return { ...base, ok: true, original, size: size === undefined ? 0 : size, open: openable(first, original) };
|
||||
const bytes = head && head.eof && (size === undefined || first.length === size) && !p.hash
|
||||
? first
|
||||
: await fetchShown(read, { handle: p.handle, size, hash: p.hash }, { maxBytes: where.maxBytes, length: where.length });
|
||||
receiveShown.count = (receiveShown.count || 0) + 1;
|
||||
let name = safeName(p.path, picture ? picture.ext : 'bin');
|
||||
// A picture is served by its name's ending, so the ending is what the bytes are.
|
||||
if (picture && !name.toLowerCase().endsWith('.' + picture.ext)) name = name.replace(/\.[A-Za-z0-9]{1,8}$/, '') + '.' + picture.ext;
|
||||
const file = path.join(where.dir, `${receiveShown.count}-${name}`);
|
||||
await fs.writeFile(file, bytes, { mode: 0o600, flag: 'wx' });
|
||||
return { ok: true, name, size: bytes.length, picture: !!picture, mime: picture ? picture.mime : undefined, file, original, open: openable(bytes.subarray(0, 4096), file) };
|
||||
} catch (e) {
|
||||
return { ...base, reason: (e && e.message) || 'The file could not be fetched.' };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { sniffPicture, sizeInWords, safeName, openable, fetchShown, receiveShown, PART };
|
||||
@@ -0,0 +1,133 @@
|
||||
'use strict';
|
||||
// JSON-RPC 2.0 over lines: the framing the Agent Client Protocol uses on stdio. No `vscode` here.
|
||||
const { StringDecoder } = require('node:string_decoder');
|
||||
|
||||
class RpcError extends Error {
|
||||
constructor(error) {
|
||||
super(error && typeof error.message === 'string' ? error.message : 'the request failed');
|
||||
this.name = 'RpcError';
|
||||
this.code = error && typeof error.code === 'number' ? error.code : -32603;
|
||||
this.data = error ? error.data : undefined;
|
||||
}
|
||||
|
||||
/** The `data.reason` word of a refusal, or ''. */
|
||||
get reason() {
|
||||
return this.data && typeof this.data.reason === 'string' ? this.data.reason : '';
|
||||
}
|
||||
}
|
||||
|
||||
class Rpc {
|
||||
/**
|
||||
* @param {{ write: (line: string) => void,
|
||||
* onRequest?: (method: string, params: any) => any,
|
||||
* onNotify?: (method: string, params: any) => void }} io
|
||||
* `onRequest` returns the result (or a promise of it); to refuse it throws an object with
|
||||
* `code` and `message`.
|
||||
*/
|
||||
constructor(io) {
|
||||
this.io = io;
|
||||
this.nextId = 1;
|
||||
this.waiting = new Map();
|
||||
this.buffer = '';
|
||||
this.decoder = new StringDecoder('utf8');
|
||||
this.closed = false;
|
||||
}
|
||||
|
||||
/** Bytes (or text) from the other side. */
|
||||
feed(chunk) {
|
||||
this.buffer += typeof chunk === 'string' ? chunk : this.decoder.write(chunk);
|
||||
for (;;) {
|
||||
const nl = this.buffer.indexOf('\n');
|
||||
if (nl < 0) break;
|
||||
const line = this.buffer.slice(0, nl);
|
||||
this.buffer = this.buffer.slice(nl + 1);
|
||||
if (line.trim() === '') continue;
|
||||
let msg;
|
||||
try {
|
||||
msg = JSON.parse(line);
|
||||
} catch {
|
||||
continue; // not ours: a stray line on stdout
|
||||
}
|
||||
if (msg && typeof msg === 'object' && !Array.isArray(msg)) this._message(msg);
|
||||
}
|
||||
}
|
||||
|
||||
_message(msg) {
|
||||
if (typeof msg.method === 'string') {
|
||||
const params = msg.params === undefined || msg.params === null ? {} : msg.params;
|
||||
if (msg.id !== undefined && msg.id !== null) {
|
||||
this._serve(msg.id, msg.method, params);
|
||||
} else if (this.io.onNotify) {
|
||||
try {
|
||||
this.io.onNotify(msg.method, params);
|
||||
} catch {
|
||||
// a notification has nobody to tell
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (msg.id === undefined || msg.id === null) return;
|
||||
const entry = this.waiting.get(msg.id);
|
||||
if (!entry) return;
|
||||
this.waiting.delete(msg.id);
|
||||
if (msg.error) entry.reject(new RpcError(msg.error));
|
||||
else entry.resolve(msg.result === undefined ? null : msg.result);
|
||||
}
|
||||
|
||||
_serve(id, method, params) {
|
||||
let answered = false;
|
||||
const reply = (result, error) => {
|
||||
if (answered) return;
|
||||
answered = true;
|
||||
if (error) {
|
||||
const out = { code: typeof error.code === 'number' ? error.code : -32603, message: String(error.message || error) };
|
||||
if (error.data !== undefined) out.data = error.data;
|
||||
this._write({ jsonrpc: '2.0', id, error: out });
|
||||
} else {
|
||||
this._write({ jsonrpc: '2.0', id, result: result === undefined ? null : result });
|
||||
}
|
||||
};
|
||||
if (!this.io.onRequest) return reply(null, { code: -32601, message: 'Method not found: ' + method });
|
||||
let out;
|
||||
try {
|
||||
out = this.io.onRequest(method, params);
|
||||
} catch (e) {
|
||||
return reply(null, e || { message: 'failed' });
|
||||
}
|
||||
Promise.resolve(out).then((r) => reply(r), (e) => reply(null, e || { message: 'failed' }));
|
||||
}
|
||||
|
||||
_write(msg) {
|
||||
if (this.closed) return;
|
||||
try {
|
||||
this.io.write(JSON.stringify(msg) + '\n');
|
||||
} catch {
|
||||
// the process is gone; its exit says so
|
||||
}
|
||||
}
|
||||
|
||||
/** A request; resolves with the result, rejects with an RpcError. */
|
||||
request(method, params) {
|
||||
if (this.closed) return Promise.reject(new RpcError({ code: -32000, message: 'the agent is not running' }));
|
||||
const id = this.nextId++;
|
||||
return new Promise((resolve, reject) => {
|
||||
this.waiting.set(id, { resolve, reject });
|
||||
this._write({ jsonrpc: '2.0', id, method, params: params === undefined ? {} : params });
|
||||
});
|
||||
}
|
||||
|
||||
notify(method, params) {
|
||||
this._write({ jsonrpc: '2.0', method, params: params === undefined ? {} : params });
|
||||
}
|
||||
|
||||
/** The other side is gone: everything still waited for fails. */
|
||||
close(message) {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
const waiting = [...this.waiting.values()];
|
||||
this.waiting.clear();
|
||||
for (const w of waiting) w.reject(new RpcError({ code: -32000, message: message || 'the agent stopped' }));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Rpc, RpcError };
|
||||
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
// The chat view's page: a fixed skeleton with a strict Content-Security-Policy. Nothing a model
|
||||
// or a server writes is ever part of this text; it reaches the page as messages and is drawn
|
||||
// with `textContent`. No `vscode` here.
|
||||
|
||||
/**
|
||||
* @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string }} o
|
||||
*/
|
||||
function chatHtml(o) {
|
||||
for (const v of [o.cspSource, o.nonce, o.scriptUri, o.styleUri]) {
|
||||
if (typeof v !== 'string' || /["<>\s]/.test(v)) throw new Error('unsafe value for the chat page');
|
||||
}
|
||||
const csp = [
|
||||
"default-src 'none'",
|
||||
`img-src ${o.cspSource}`,
|
||||
`style-src ${o.cspSource}`,
|
||||
`script-src 'nonce-${o.nonce}'`,
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
].join('; ');
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="${csp}">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="${o.styleUri}">
|
||||
<title>LLeMbas</title>
|
||||
</head>
|
||||
<body>
|
||||
<header class="bar">
|
||||
<select id="mode" title="Mode" aria-label="Mode"></select>
|
||||
<select id="model" title="This session's model" aria-label="Model"></select>
|
||||
<button id="new" type="button" title="Start a new session">New</button>
|
||||
</header>
|
||||
<main id="log" aria-live="polite"></main>
|
||||
<footer>
|
||||
<textarea id="prompt" rows="3" placeholder="Ask LLeMbas (Enter sends, Shift+Enter starts a new line)" aria-label="Message"></textarea>
|
||||
<div class="send">
|
||||
<div id="attached" class="attached" hidden>
|
||||
<span id="attached-label" class="attached-label"></span>
|
||||
<button id="detach" type="button" class="plain" title="Do not send the selection" aria-label="Do not send the selection">×</button>
|
||||
</div>
|
||||
<span id="working" class="working" hidden>Working…</span>
|
||||
<button id="send" type="button">Send</button>
|
||||
</div>
|
||||
</footer>
|
||||
<script nonce="${o.nonce}" src="${o.scriptUri}"></script>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
module.exports = { chatHtml };
|
||||
@@ -0,0 +1,69 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { Agent } = require('../src/agent');
|
||||
const { tempDir, fakeAgent, until } = require('./helpers');
|
||||
|
||||
test('the hello says what this client is: an editor that shows media and has unsaved text', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t));
|
||||
await agent.connect();
|
||||
const hello = agent.log().find((m) => m.method === 'initialize');
|
||||
assert.equal(hello.params.protocolVersion, 1);
|
||||
assert.deepEqual(hello.params.clientCapabilities._meta.lembas, { editor: true, media: true, show: true });
|
||||
assert.deepEqual(hello.params.clientCapabilities.fs, { readTextFile: true, writeTextFile: false }, 'writing is offered only by a client that can do it');
|
||||
assert.ok(agent.ready && agent.has('editor') && agent.has('media') && !agent.has('fs'));
|
||||
});
|
||||
|
||||
test('a client that can put text into its documents says so', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t), {}, { writeTextFile: true });
|
||||
await agent.connect();
|
||||
assert.deepEqual(agent.log().find((m) => m.method === 'initialize').params.clientCapabilities.fs, { readTextFile: true, writeTextFile: true });
|
||||
});
|
||||
|
||||
test('every caller of connect gets the same start', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t));
|
||||
const [a, b] = await Promise.all([agent.connect(), agent.connect()]);
|
||||
assert.equal(a, b);
|
||||
assert.equal(agent.log().filter((m) => m.method === 'initialize').length, 1);
|
||||
});
|
||||
|
||||
test('an agent from before the editor methods has no capabilities', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t), { FAKE_AGENT_PLAIN: '1' });
|
||||
await agent.connect();
|
||||
assert.ok(!agent.has('editor'));
|
||||
await assert.rejects(agent.request('_lembas/models', {}), (e) => e.code === -32601);
|
||||
});
|
||||
|
||||
test('a command that does not exist is said in words, once', async (t) => {
|
||||
const agent = new Agent({ command: 'lembas-that-is-not-installed', cwd: tempDir(t) });
|
||||
const exits = [];
|
||||
agent.on('exit', (e) => exits.push(e));
|
||||
await assert.rejects(agent.connect(), /could not start lembas-that-is-not-installed: the command was not found/);
|
||||
await assert.rejects(agent.request('x', {}), /not running/);
|
||||
assert.equal(exits.length, 1);
|
||||
assert.equal(exits[0].started, false);
|
||||
});
|
||||
|
||||
test('an agent that exits fails what was asked and says its last words', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t));
|
||||
await agent.connect();
|
||||
const exits = [];
|
||||
agent.on('exit', (e) => exits.push(e));
|
||||
const r = await agent.request('session/new', { cwd: '/', mcpServers: [] });
|
||||
const turn = agent.request('session/prompt', { sessionId: r.sessionId, prompt: [{ type: 'text', text: 'CRASH' }] });
|
||||
await assert.rejects(turn, /the agent stopped \(exit 3\): not signed in: run lembas login/);
|
||||
await until(() => exits.length === 1);
|
||||
assert.equal(exits[0].code, 3);
|
||||
assert.equal(exits[0].started, true);
|
||||
assert.match(exits[0].last, /not signed in/);
|
||||
});
|
||||
|
||||
test('stop ends the process', async (t) => {
|
||||
const agent = fakeAgent(t, tempDir(t));
|
||||
await agent.connect();
|
||||
let gone = false;
|
||||
agent.on('exit', () => (gone = true));
|
||||
agent.stop();
|
||||
await until(() => gone);
|
||||
await assert.rejects(agent.request('x', {}), /not running/);
|
||||
});
|
||||
@@ -0,0 +1,442 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { receiveShown } = require('../src/media');
|
||||
const { editorContext } = require('../src/context');
|
||||
const { fakeChat, tempDir, until, text } = require('./helpers');
|
||||
|
||||
const lastPrompt = (agent) => agent.log().filter((m) => m.method === 'session/prompt').pop();
|
||||
|
||||
test('a typed prompt is answered: what was typed, then the reply, in order', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
const states = [];
|
||||
chat.on('state', () => states.push(chat.state().busy));
|
||||
assert.equal(await chat.send('hello'), true);
|
||||
assert.equal(text(chat), 'You: hello\nLLeMbas: Hello there.\nSecond line');
|
||||
assert.equal(chat.busy, false);
|
||||
assert.ok(states.includes(true), 'the view heard that a turn runs');
|
||||
assert.deepEqual(chat.state().modes, [{ id: 'ask', name: 'Ask' }, { id: 'edit', name: 'Edit' }]);
|
||||
assert.equal(chat.state().mode, 'ask');
|
||||
assert.equal(chat.state().model, 'example/model-a');
|
||||
const sent = lastPrompt(agents[0]);
|
||||
assert.deepEqual(sent.params.prompt, [{ type: 'text', text: 'hello' }]);
|
||||
assert.equal(sent.params._meta, undefined);
|
||||
});
|
||||
|
||||
test('thinking is hidden unless asked for', async (t) => {
|
||||
const a = fakeChat(t);
|
||||
await a.chat.send('hello');
|
||||
assert.ok(!text(a.chat).includes('hidden thought'));
|
||||
const b = fakeChat(t, { options: { showThoughts: true } });
|
||||
await b.chat.send('hello');
|
||||
assert.equal(text(b.chat), 'You: hello\nThinking: hidden thought\nLLeMbas: Hello there.\nSecond line');
|
||||
});
|
||||
|
||||
test('a second prompt while one runs is refused, and Stop ends the turn', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
const turn = chat.send('SLOW please');
|
||||
await until(() => chat.items.some((i) => i.kind === 'agent'));
|
||||
assert.equal(await chat.send('another'), false);
|
||||
chat.stop();
|
||||
await turn;
|
||||
assert.match(text(chat), /> Stopped\.$/);
|
||||
assert.ok(agents[0].log().some((m) => m.method === 'session/cancel' && m.params.sessionId === 'ses_test'));
|
||||
assert.equal(agents[0].log().filter((m) => m.method === 'session/prompt').length, 1);
|
||||
});
|
||||
|
||||
test('the editor context goes in _meta.lembas.editor, not into the prompt', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
const editor = editorContext({
|
||||
path: '/home/user/project/src/oven.py',
|
||||
cursorLine: 12,
|
||||
selection: { start: 10, end: 14, text: 'def bake():\n pass' },
|
||||
diagnostics: [{ line: 12, severity: 'error', message: "name 'crumbs' is not defined", source: 'pyflakes' }],
|
||||
open: ['/home/user/project/src/oven.py', '/home/user/project/src/flour.py'],
|
||||
});
|
||||
await chat.send('META what is this', { editor, label: 'src/oven.py:10-14' });
|
||||
const sent = lastPrompt(agents[0]);
|
||||
assert.deepEqual(sent.params.prompt, [{ type: 'text', text: 'META what is this' }]);
|
||||
assert.deepEqual(sent.params._meta.lembas.editor, {
|
||||
path: '/home/user/project/src/oven.py',
|
||||
cursor: { line: 12 },
|
||||
selection: { start: 10, end: 14, text: 'def bake():\n pass' },
|
||||
diagnostics: [{ message: "name 'crumbs' is not defined", line: 12, severity: 'error', source: 'pyflakes' }],
|
||||
open: ['/home/user/project/src/flour.py'],
|
||||
});
|
||||
assert.match(text(chat), /^You: \[src\/oven\.py:10-14\] META what is this/);
|
||||
assert.match(text(chat), /editor=\{"cursor": \{"line": 12\}/);
|
||||
});
|
||||
|
||||
test('an agent that does not read the editor context gets it as blocks in front of the prompt', async (t) => {
|
||||
const { chat, agents } = fakeChat(t, { env: { FAKE_AGENT_PLAIN: '1' } });
|
||||
const editor = editorContext({ path: '/p/a.py', selection: { start: 3, end: 4, text: 'x = 1\ny = 2' }, diagnostics: [{ line: 3, severity: 'warning', message: 'unused' }] });
|
||||
await chat.send('why', { editor });
|
||||
const sent = lastPrompt(agents[0]);
|
||||
assert.equal(sent.params._meta, undefined);
|
||||
assert.deepEqual(sent.params.prompt.map((b) => b.type), ['text', 'resource', 'text', 'text']);
|
||||
assert.equal(sent.params.prompt[0].text, 'Selected in the editor: /p/a.py, lines 3-4.');
|
||||
assert.equal(sent.params.prompt[1].resource.text, 'x = 1\ny = 2');
|
||||
assert.match(sent.params.prompt[2].text, /- line 3, warning: unused/);
|
||||
assert.equal(sent.params.prompt[3].text, 'why');
|
||||
});
|
||||
|
||||
test('an approval card waits for the answer, and the answer reaches the agent', async (t) => {
|
||||
const { chat } = fakeChat(t);
|
||||
const turn = chat.send('PERM');
|
||||
await until(() => chat.cards.size === 1);
|
||||
const card = chat.items.find((i) => i.kind === 'card');
|
||||
assert.equal(card.title, 'rm -r build');
|
||||
assert.equal(card.tool, 'bash');
|
||||
assert.equal(card.reason, 'deletes files');
|
||||
assert.deepEqual(card.options.map((o) => o.optionId), ['once', 'deny']);
|
||||
assert.equal(card.state, 'open');
|
||||
assert.equal(chat.answer(card.id, 'no-such-option'), false);
|
||||
assert.equal(chat.answer(card.id, 'deny'), true);
|
||||
assert.equal(chat.answer(card.id, 'once'), false, 'a card is answered once');
|
||||
await turn;
|
||||
assert.equal(card.state, 'answered');
|
||||
assert.equal(card.answer, 'Deny');
|
||||
assert.match(text(chat), /answer=deny/);
|
||||
});
|
||||
|
||||
test('a card with a diff is shown as a diff before the answer, and nothing is written until then', async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const file = path.join(dir, 'waybread.py');
|
||||
fs.writeFileSync(file, 'old text\n');
|
||||
const calls = [];
|
||||
const { chat } = fakeChat(t, {
|
||||
dir,
|
||||
hooks: {
|
||||
showDiffs: (cardId, diffs) => calls.push(['show', cardId, diffs, fs.readFileSync(file, 'utf8')]),
|
||||
closeDiffs: (cardId) => calls.push(['close', cardId]),
|
||||
filesChanged: (files) => calls.push(['changed', files]),
|
||||
},
|
||||
});
|
||||
const turn = chat.send(`DIFFPERM ${file}`);
|
||||
await until(() => chat.cards.size === 1);
|
||||
const card = chat.items.find((i) => i.kind === 'card');
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0][0], 'show');
|
||||
assert.equal(calls[0][1], card.id);
|
||||
assert.deepEqual(calls[0][2], [{ path: file, oldText: 'old text\n', newText: 'rewritten by the agent\n', deleted: false }]);
|
||||
assert.equal(calls[0][3], 'old text\n', 'the file is as it was while the card is open');
|
||||
assert.deepEqual(card.files, [file]);
|
||||
chat.answer(card.id, 'once');
|
||||
await turn;
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), 'rewritten by the agent\n');
|
||||
assert.deepEqual(calls[1], ['close', card.id]);
|
||||
assert.deepEqual(calls[2], ['changed', [file]]);
|
||||
const tool = chat.items.find((i) => i.kind === 'tool');
|
||||
assert.equal(tool.status, 'completed');
|
||||
assert.deepEqual(tool.files, [file]);
|
||||
});
|
||||
|
||||
test('a rejected diff leaves the file alone', async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const file = path.join(dir, 'a.txt');
|
||||
fs.writeFileSync(file, 'keep me\n');
|
||||
const { chat } = fakeChat(t, { dir });
|
||||
const turn = chat.send(`DIFFPERM ${file}`);
|
||||
await until(() => chat.cards.size === 1);
|
||||
chat.answer(chat.items.find((i) => i.kind === 'card').id, 'deny');
|
||||
await turn;
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), 'keep me\n');
|
||||
assert.ok(!chat.items.some((i) => i.kind === 'tool'));
|
||||
});
|
||||
|
||||
test('a card the agent withdraws is taken down', async (t) => {
|
||||
const { chat } = fakeChat(t);
|
||||
await chat.send('SETTLE');
|
||||
const card = chat.items.find((i) => i.kind === 'card');
|
||||
assert.equal(card.state, 'settled');
|
||||
assert.equal(chat.cards.size, 0);
|
||||
assert.match(text(chat), /answer=cancelled/);
|
||||
});
|
||||
|
||||
test('Stop answers an open card as cancelled', async (t) => {
|
||||
const { chat } = fakeChat(t);
|
||||
const turn = chat.send('PERM');
|
||||
await until(() => chat.cards.size === 1);
|
||||
chat.stop();
|
||||
await turn;
|
||||
assert.equal(chat.items.find((i) => i.kind === 'card').state, 'settled');
|
||||
assert.match(text(chat), /answer=cancelled/);
|
||||
});
|
||||
|
||||
test('a tool call is one line that changes as the call goes on', async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const file = path.join(dir, 'b.txt');
|
||||
const { chat } = fakeChat(t, { dir });
|
||||
await chat.send(`WRITE ${file}`);
|
||||
const tools = chat.items.filter((i) => i.kind === 'tool');
|
||||
assert.equal(tools.length, 1);
|
||||
assert.equal(tools[0].title, 'edit b.txt');
|
||||
assert.equal(tools[0].status, 'completed');
|
||||
});
|
||||
|
||||
test("the agent's question for a file's text is the hook's to answer", async (t) => {
|
||||
const asked = [];
|
||||
const { chat } = fakeChat(t, {
|
||||
hooks: {
|
||||
readTextFile: (p) => {
|
||||
asked.push(p);
|
||||
if (p.path.endsWith('open.py')) return { content: 'unsaved text' };
|
||||
throw { code: -32002, message: 'not open in the editor' };
|
||||
},
|
||||
},
|
||||
});
|
||||
await chat.send('READ /p/open.py');
|
||||
assert.match(text(chat), /read="unsaved text"/);
|
||||
assert.deepEqual(asked[0], { sessionId: 'ses_test', path: '/p/open.py' });
|
||||
await chat.send('READ /p/closed.py');
|
||||
assert.match(text(chat), /read=null/, 'an error: the agent reads the disk itself');
|
||||
});
|
||||
|
||||
test("the agent's write of a file goes to the hook; an error tells it to write the disk itself", async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const open = path.join(dir, 'open.txt');
|
||||
const closed = path.join(dir, 'closed.txt');
|
||||
const asked = [];
|
||||
const { chat } = fakeChat(t, {
|
||||
dir,
|
||||
hooks: {
|
||||
writeTextFile: async (p) => {
|
||||
asked.push(p);
|
||||
if (p.path !== open) throw { code: -32002, message: 'not open in the editor' };
|
||||
},
|
||||
},
|
||||
});
|
||||
await chat.send(`PUT ${open}`);
|
||||
assert.match(text(chat), /put=client/);
|
||||
assert.deepEqual(asked[0], { sessionId: 'ses_test', path: open, content: 'put by the agent\n' });
|
||||
assert.ok(!fs.existsSync(open), 'the stand-in did not write: the client said it had');
|
||||
await chat.send(`PUT ${closed}`);
|
||||
assert.match(text(chat), /put=disk/);
|
||||
assert.equal(fs.readFileSync(closed, 'utf8'), 'put by the agent\n');
|
||||
});
|
||||
|
||||
test('without a write hook the method is not there', async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const { chat } = fakeChat(t, { dir });
|
||||
await chat.send(`PUT ${path.join(dir, 'a.txt')}`);
|
||||
assert.match(text(chat), /put=disk/);
|
||||
});
|
||||
|
||||
test('an agent stopped on purpose takes its session with it at once, before its exit is heard', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
await chat.send('hello');
|
||||
assert.equal(chat.session, 'ses_test');
|
||||
const turn = chat.send('PERM');
|
||||
await until(() => chat.cards.size === 1);
|
||||
// The old way: the process is told to stop, and something asks for the agent before it has gone.
|
||||
agents[0].stop();
|
||||
const second = await chat.connect(true);
|
||||
assert.equal(agents.length, 2);
|
||||
assert.equal(second, agents[1]);
|
||||
assert.equal(chat.session, null, 'no session id of the agent that is going');
|
||||
assert.equal(chat.cards.size, 0);
|
||||
assert.equal(chat.items.find((i) => i.kind === 'card').state, 'settled');
|
||||
await turn;
|
||||
assert.equal(chat.busy, false);
|
||||
await new Promise((r) => setTimeout(r, 150)); // the old agent's exit arrives and changes nothing
|
||||
assert.equal(chat.agent, agents[1]);
|
||||
await chat.send('hello again');
|
||||
assert.match(text(chat), /You: hello again\nLLeMbas: Hello there\.\nSecond line$/);
|
||||
assert.equal(agents[1].log().filter((m) => m.method === 'session/new').length, 1);
|
||||
|
||||
chat.stopAgent();
|
||||
assert.equal(chat.agent, null);
|
||||
assert.equal(chat.session, null);
|
||||
assert.match(text(chat), /> The agent was stopped\. The next message starts a new session\.$/);
|
||||
await chat.send('once more');
|
||||
assert.equal(agents.length, 3);
|
||||
});
|
||||
|
||||
test('the models, the session model and the mode', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
await chat.ensureSession();
|
||||
await until(() => chat.models.length === 3);
|
||||
assert.deepEqual(chat.state().models.map((m) => m.id), ['example/model-a', 'example/model-b', 'example/model-c']);
|
||||
assert.equal(await chat.setModel('example/model-b'), true);
|
||||
assert.equal(chat.model, 'example/model-b');
|
||||
const conf = agents[0].log().find((m) => m.method === '_lembas/configure');
|
||||
assert.deepEqual(conf.params, { sessionId: 'ses_test', model: 'example/model-b' });
|
||||
await chat.setMode('edit');
|
||||
assert.equal(chat.mode, 'edit');
|
||||
assert.deepEqual(agents[0].log().find((m) => m.method === 'session/set_mode').params, { sessionId: 'ses_test', modeId: 'edit' });
|
||||
});
|
||||
|
||||
test('the two saved model settings are read and saved through the agent', async (t) => {
|
||||
const { chat, agents } = fakeChat(t, { env: { FAKE_AGENT_AUTOCOMPLETE: 'none' } });
|
||||
const data = await chat.loadModels();
|
||||
assert.equal(data.autocomplete.model, null);
|
||||
assert.deepEqual(data.autocomplete.allowed, ['example/model-a', 'example/model-b']);
|
||||
assert.equal(data.main.model, null);
|
||||
const saved = await chat.editorSettings({ autocomplete_model: 'example/model-b' });
|
||||
assert.equal(saved.autocomplete.model, 'example/model-b');
|
||||
assert.equal(saved.autocomplete.source, 'person');
|
||||
assert.deepEqual(agents[0].log().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: 'example/model-b' } });
|
||||
assert.equal((await chat.editorSettings({ main_model: 'example/model-c' })).main.model, 'example/model-c');
|
||||
assert.equal((await chat.editorSettings()).autocomplete.model, 'example/model-b');
|
||||
assert.equal(chat.session, null, 'settings need no session');
|
||||
});
|
||||
|
||||
test("the window's own model and mode start a session", async (t) => {
|
||||
const { chat, agents } = fakeChat(t, { options: { model: 'example/model-c', mode: 'manual' } });
|
||||
await chat.ensureSession();
|
||||
assert.deepEqual(agents[0].log().find((m) => m.method === 'session/new').params._meta, { mode: 'manual', model: 'example/model-c' });
|
||||
assert.equal(chat.model, 'example/model-c');
|
||||
});
|
||||
|
||||
test('an agent that dies is said in the chat, and the next message starts a new one', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
await chat.send('CRASH');
|
||||
assert.match(text(chat), /> The agent stopped \(exit 3\): not signed in: run lembas login$/);
|
||||
assert.equal(chat.session, null);
|
||||
assert.equal(chat.busy, false);
|
||||
await chat.send('hello again');
|
||||
assert.equal(agents.length, 2);
|
||||
assert.match(text(chat), /You: hello again\nLLeMbas: Hello there\.\nSecond line$/);
|
||||
});
|
||||
|
||||
test('a command that is not there is said once in the chat, and not tried at every keystroke', async (t) => {
|
||||
const { Agent } = require('../src/agent');
|
||||
const { Chat } = require('../src/chat');
|
||||
let made = 0;
|
||||
let now = 1000;
|
||||
const chat = new Chat({
|
||||
makeAgent: (o) => {
|
||||
made++;
|
||||
return new Agent({ command: 'lembas-that-is-not-installed', cwd: o.cwd, onRequest: o.onRequest });
|
||||
},
|
||||
cwd: () => tempDir(t),
|
||||
now: () => now,
|
||||
});
|
||||
assert.equal(await chat.connect(true), null);
|
||||
assert.equal(chat.items.length, 0, 'quietly');
|
||||
assert.equal(await chat.connect(true), null);
|
||||
assert.equal(made, 1, 'not started again within the minute');
|
||||
now += 61000;
|
||||
assert.equal(await chat.connect(true), null);
|
||||
assert.equal(made, 2);
|
||||
await chat.send('hello');
|
||||
assert.equal(made, 3, 'a message always tries');
|
||||
assert.match(text(chat), /> Could not start lembas-that-is-not-installed: the command was not found\.$/);
|
||||
assert.equal(chat.busy, false);
|
||||
});
|
||||
|
||||
test('a new session clears the transcript and keeps the agent', async (t) => {
|
||||
const { chat, agents } = fakeChat(t);
|
||||
await chat.send('hello');
|
||||
let resets = 0;
|
||||
chat.on('reset', () => resets++);
|
||||
assert.equal(await chat.newSession(), true);
|
||||
assert.equal(resets, 1);
|
||||
assert.equal(chat.items.length, 0);
|
||||
assert.equal(chat.session, null);
|
||||
await chat.send('again');
|
||||
assert.equal(agents.length, 1);
|
||||
assert.equal(agents[0].log().filter((m) => m.method === 'session/new').length, 2);
|
||||
});
|
||||
|
||||
// ---- files the agent shows ---------------------------------------------------------------
|
||||
|
||||
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), crypto.randomBytes(5000)]);
|
||||
|
||||
function mediaChat(t, maxBytes) {
|
||||
const dir = tempDir(t);
|
||||
const store = path.join(dir, 'store');
|
||||
fs.mkdirSync(store);
|
||||
const got = [];
|
||||
const made = fakeChat(t, {
|
||||
dir,
|
||||
hooks: {
|
||||
showMedia: async (p, read) => {
|
||||
const r = await receiveShown(p, read, { dir: store, maxBytes: maxBytes || 1024 * 1024 });
|
||||
got.push(r);
|
||||
return r.ok ? { ...r, key: 'm' + got.length } : r;
|
||||
},
|
||||
},
|
||||
});
|
||||
return { ...made, got, store };
|
||||
}
|
||||
|
||||
test('a picture the agent shows is fetched in parts, checked, and kept for the chat', async (t) => {
|
||||
const { chat, agents, dir, got } = mediaChat(t);
|
||||
const file = path.join(dir, 'chart.html'); // the name lies; the bytes are a picture
|
||||
fs.writeFileSync(file, PNG);
|
||||
await chat.send(`SHOW ${file}`);
|
||||
assert.match(text(chat), /shown=\{"shown": true\}/);
|
||||
const item = chat.items.find((i) => i.kind === 'media');
|
||||
assert.equal(item.picture, true);
|
||||
assert.equal(item.name, 'chart.png', 'named by what the bytes are');
|
||||
assert.equal(item.size, PNG.length);
|
||||
assert.ok(fs.readFileSync(got[0].file).equals(PNG));
|
||||
assert.equal(got[0].mime, 'image/png');
|
||||
const reads = agents[0].log().filter((m) => m.method === '_lembas/show/read');
|
||||
assert.ok(reads.length >= 6, 'the stand-in gives a thousand bytes a time');
|
||||
assert.ok(reads.every((m) => m.params.handle === reads[0].params.handle));
|
||||
});
|
||||
|
||||
test('a file that is not a picture is a line with Open; one on this machine is not fetched', async (t) => {
|
||||
const { chat, agents, dir, got } = mediaChat(t);
|
||||
const file = path.join(dir, 'report.pdf');
|
||||
fs.writeFileSync(file, Buffer.concat([Buffer.from('%PDF-1.7\n'), crypto.randomBytes(3000)]));
|
||||
await chat.send(`SHOW ${file} WITHURI`);
|
||||
const item = chat.items.find((i) => i.kind === 'media');
|
||||
assert.equal(item.picture, false);
|
||||
assert.equal(item.name, 'report.pdf');
|
||||
assert.equal(got[0].original, file);
|
||||
assert.equal(got[0].file, undefined);
|
||||
assert.deepEqual(got[0].open, { kind: 'pdf', how: 'system' });
|
||||
assert.equal(item.opens, true);
|
||||
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/show/read').length, 1, 'only its first bytes were read');
|
||||
});
|
||||
|
||||
test('without a file on this machine, the bytes are fetched and written to the store', async (t) => {
|
||||
const { chat, dir, got, store } = mediaChat(t);
|
||||
const file = path.join(dir, 'notes.bin');
|
||||
const bytes = crypto.randomBytes(2500);
|
||||
fs.writeFileSync(file, bytes);
|
||||
await chat.send(`SHOW ${file}`);
|
||||
assert.equal(got[0].picture, false);
|
||||
assert.ok(got[0].file.startsWith(store + path.sep));
|
||||
assert.ok(fs.readFileSync(got[0].file).equals(bytes));
|
||||
assert.equal(got[0].open, null, 'a kind nobody knows is never opened');
|
||||
assert.equal(chat.items.find((i) => i.kind === 'media').opens, false);
|
||||
});
|
||||
|
||||
test('a file over the limit is refused in words, to the person and to the agent', async (t) => {
|
||||
const { chat, agents, dir } = mediaChat(t, 2048);
|
||||
const file = path.join(dir, 'big.png');
|
||||
fs.writeFileSync(file, PNG);
|
||||
await chat.send(`SHOW ${file}`);
|
||||
assert.match(text(chat), /> big\.png was not shown: The file is 5 KB; this editor takes files of up to 2 KB\./);
|
||||
assert.match(text(chat), /shown=\{"reason": "The file is 5 KB; this editor takes files of up to 2 KB\.", "shown": false\}/);
|
||||
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/show/read').length, 0);
|
||||
assert.ok(!chat.items.some((i) => i.kind === 'media'));
|
||||
});
|
||||
|
||||
test('a file whose checksum differs is not shown', async (t) => {
|
||||
const { chat, dir, store } = mediaChat(t);
|
||||
const file = path.join(dir, 'pic.png');
|
||||
fs.writeFileSync(file, PNG);
|
||||
await chat.send(`SHOW ${file} BADHASH`);
|
||||
assert.match(text(chat), /was not shown: The file did not arrive whole/);
|
||||
assert.deepEqual(fs.readdirSync(store), []);
|
||||
});
|
||||
|
||||
test('a text file the agent shows goes to the hook that opens it', async (t) => {
|
||||
const dir = tempDir(t);
|
||||
const file = path.join(dir, 'page.html');
|
||||
fs.writeFileSync(file, '<script>alert(1)</script>');
|
||||
const opened = [];
|
||||
const { chat } = fakeChat(t, { dir, hooks: { showText: async (p) => (opened.push(p), { shown: true }) } });
|
||||
await chat.send(`SHOWTEXT ${file}`);
|
||||
assert.equal(opened[0].path, 'page.html');
|
||||
assert.equal(opened[0].text, '<script>alert(1)</script>');
|
||||
assert.match(text(chat), /> Shown: page\.html/);
|
||||
});
|
||||
@@ -0,0 +1,273 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { Completer, windowAround } = require('../src/completion');
|
||||
const { fakeChat, until } = require('./helpers');
|
||||
|
||||
/** A Completer on a hand-wound clock and a hand-answered agent. */
|
||||
function rig(options) {
|
||||
const timers = [];
|
||||
const sent = [];
|
||||
const notes = [];
|
||||
const refusals = [];
|
||||
const errors = [];
|
||||
let now = 0;
|
||||
const completer = new Completer({
|
||||
request: (method, params) => new Promise((resolve, reject) => sent.push({ method, params, resolve, reject })),
|
||||
notify: (method, params) => notes.push({ method, params }),
|
||||
debounceMs: () => 250,
|
||||
model: () => (options && options.model) || undefined,
|
||||
onRefusal: (reason, message, manual) => refusals.push({ reason, message, manual }),
|
||||
onError: (message, manual) => errors.push({ message, manual }),
|
||||
setTimeout: (fn, ms) => {
|
||||
const timer = { fn, at: now + ms, dead: false };
|
||||
timers.push(timer);
|
||||
return timer;
|
||||
},
|
||||
clearTimeout: (timer) => {
|
||||
timer.dead = true;
|
||||
},
|
||||
now: () => now,
|
||||
});
|
||||
const tick = (ms) => {
|
||||
now += ms;
|
||||
for (const timer of timers.splice(0)) {
|
||||
if (timer.dead) continue;
|
||||
if (timer.at <= now) timer.fn();
|
||||
else timers.push(timer);
|
||||
}
|
||||
};
|
||||
const settle = () => new Promise((r) => setImmediate(r));
|
||||
return { completer, sent, notes, refusals, errors, tick, settle };
|
||||
}
|
||||
|
||||
const refusal = (reason, message) => Object.assign(new Error(message), { code: -32602, data: { reason } });
|
||||
|
||||
test('nothing is sent until the pause is over', async () => {
|
||||
const { completer, sent, tick } = rig();
|
||||
const p = completer.ask({ prefix: 'def bake(', suffix: '):', path: '/p/oven.py', language: 'python' });
|
||||
tick(249);
|
||||
assert.equal(sent.length, 0);
|
||||
tick(1);
|
||||
assert.equal(sent.length, 1);
|
||||
assert.deepEqual(sent[0], { method: '_lembas/complete', params: { id: 'c1', prefix: 'def bake(', suffix: '):', path: '/p/oven.py', language: 'python' }, resolve: sent[0].resolve, reject: sent[0].reject });
|
||||
sent[0].resolve({ text: 'flour', model: 'm', finish: 'stop' });
|
||||
assert.equal(await p, 'flour');
|
||||
});
|
||||
|
||||
test('typing on before the pause is over: the earlier request is never sent', async () => {
|
||||
const { completer, sent, notes, tick } = rig();
|
||||
const first = completer.ask({ prefix: 'a' });
|
||||
tick(100);
|
||||
const second = completer.ask({ prefix: 'ab' });
|
||||
assert.equal(await first, null);
|
||||
tick(250);
|
||||
assert.equal(sent.length, 1);
|
||||
assert.equal(sent[0].params.prefix, 'ab');
|
||||
assert.equal(notes.length, 0, 'nothing was under way, so nothing is cancelled');
|
||||
sent[0].resolve({ text: 'c' });
|
||||
assert.equal(await second, 'c');
|
||||
});
|
||||
|
||||
test('a request under way is cancelled by its own id when the next keystroke comes', async () => {
|
||||
const { completer, sent, notes, tick, settle } = rig();
|
||||
const first = completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
const second = completer.ask({ prefix: 'ab' });
|
||||
assert.deepEqual(notes, [{ method: '_lembas/complete/cancel', params: { id: 'c1' } }]);
|
||||
assert.equal(await first, null, 'answered at once, without waiting for the agent');
|
||||
// The agent's late answer to the first, whatever it says, is thrown away.
|
||||
sent[0].resolve({ text: 'STALE', model: 'm', finish: 'stop' });
|
||||
await settle();
|
||||
tick(250);
|
||||
assert.equal(sent[1].params.id, 'c2');
|
||||
sent[1].resolve({ text: 'fresh' });
|
||||
assert.equal(await second, 'fresh');
|
||||
});
|
||||
|
||||
test('a late error of a request that was replaced does not stop the newer one', async () => {
|
||||
const { completer, sent, errors, tick, settle } = rig();
|
||||
completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
const second = completer.ask({ prefix: 'ab' }, { manual: true });
|
||||
sent[0].reject(new Error('socket closed'));
|
||||
await settle();
|
||||
assert.equal(errors.length, 1);
|
||||
sent[1].resolve({ text: 'ok' });
|
||||
assert.equal(await second, 'ok');
|
||||
});
|
||||
|
||||
test('a result that says cancelled, or carries no text, shows nothing', async () => {
|
||||
const { completer, sent, tick } = rig();
|
||||
let p = completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
sent[0].resolve({ text: '', cancelled: true });
|
||||
assert.equal(await p, null);
|
||||
p = completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
sent[1].resolve({ text: '', model: 'm', finish: 'stop' });
|
||||
assert.equal(await p, null);
|
||||
p = completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
sent[2].resolve(null);
|
||||
assert.equal(await p, null);
|
||||
});
|
||||
|
||||
test('the editor moving on cancels only the request it meant', async () => {
|
||||
const { completer, sent, notes, tick } = rig();
|
||||
const first = completer.ask({ prefix: 'a' });
|
||||
const seq = completer.current;
|
||||
tick(250);
|
||||
completer.cancel(seq + 5);
|
||||
assert.equal(notes.length, 0);
|
||||
completer.cancel(seq);
|
||||
assert.equal(await first, null);
|
||||
assert.deepEqual(notes.map((n) => n.params.id), ['c1']);
|
||||
assert.equal(completer.current, 0);
|
||||
completer.cancel(seq); // again: nothing happens
|
||||
assert.equal(notes.length, 1);
|
||||
assert.equal(sent.length, 1);
|
||||
});
|
||||
|
||||
test('asked by hand, it is sent at once', async () => {
|
||||
const { completer, sent } = rig();
|
||||
const p = completer.ask({ prefix: 'a' }, { manual: true });
|
||||
assert.equal(sent.length, 1);
|
||||
sent[0].resolve({ text: 'b' });
|
||||
assert.equal(await p, 'b');
|
||||
});
|
||||
|
||||
test('the quick switch of this window is the request\'s model', () => {
|
||||
const { completer, sent } = rig({ model: 'example/model-b' });
|
||||
completer.ask({ prefix: 'a' }, { manual: true });
|
||||
assert.equal(sent[0].params.model, 'example/model-b');
|
||||
});
|
||||
|
||||
test('no autocomplete model: said once, then quiet until one is set', async () => {
|
||||
const { completer, sent, refusals, tick } = rig();
|
||||
let p = completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
sent[0].reject(refusal('no_model', 'No autocomplete model is chosen. Choose one in your settings.'));
|
||||
assert.equal(await p, null);
|
||||
assert.deepEqual(refusals, [{ reason: 'no_model', message: 'No autocomplete model is chosen. Choose one in your settings.', manual: false }]);
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
p = completer.ask({ prefix: 'more' + i });
|
||||
tick(250);
|
||||
assert.equal(await p, null);
|
||||
}
|
||||
assert.equal(sent.length, 1, 'no further request while typing');
|
||||
assert.equal(refusals.length, 1, 'and it is not said again');
|
||||
|
||||
completer.unblock(); // a model was chosen
|
||||
p = completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
assert.equal(sent.length, 2);
|
||||
sent[1].resolve({ text: 'x' });
|
||||
assert.equal(await p, 'x');
|
||||
});
|
||||
|
||||
test('asked by hand while it is quiet: the server is asked again, and its answer counts', async () => {
|
||||
const { completer, sent, refusals, tick } = rig();
|
||||
let p = completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
sent[0].reject(refusal('no_model', 'No autocomplete model is chosen.'));
|
||||
await p;
|
||||
p = completer.ask({ prefix: 'a' }, { manual: true });
|
||||
sent[1].reject(refusal('no_model', 'No autocomplete model is chosen.'));
|
||||
await p;
|
||||
assert.equal(refusals.length, 2, 'asked on purpose, so it is said again');
|
||||
assert.equal(refusals[1].manual, true);
|
||||
// Meanwhile a model was chosen elsewhere: the next request by hand works, and typing asks again.
|
||||
p = completer.ask({ prefix: 'a' }, { manual: true });
|
||||
sent[2].resolve({ text: 'yes' });
|
||||
assert.equal(await p, 'yes');
|
||||
p = completer.ask({ prefix: 'ab' });
|
||||
tick(250);
|
||||
assert.equal(sent.length, 4);
|
||||
});
|
||||
|
||||
test('another failure is not a refusal: typing pauses a while and then asks again', async () => {
|
||||
const { completer, sent, refusals, errors, tick } = rig();
|
||||
let p = completer.ask({ prefix: 'a' });
|
||||
tick(250);
|
||||
sent[0].reject(Object.assign(new Error('The server did not answer.'), { code: -32603 }));
|
||||
assert.equal(await p, null);
|
||||
assert.equal(refusals.length, 0);
|
||||
assert.deepEqual(errors, [{ message: 'The server did not answer.', manual: false }]);
|
||||
p = completer.ask({ prefix: 'ab' });
|
||||
tick(250);
|
||||
assert.equal(await p, null);
|
||||
assert.equal(sent.length, 1);
|
||||
tick(15000);
|
||||
completer.ask({ prefix: 'abc' });
|
||||
tick(250);
|
||||
assert.equal(sent.length, 2);
|
||||
});
|
||||
|
||||
test('the window around the cursor: the end of what is before, the start of what is after', () => {
|
||||
const text = 'a'.repeat(50) + '|' + 'b'.repeat(50);
|
||||
const w = windowAround(text, 51, { prefixMax: 10, suffixMax: 5 });
|
||||
assert.equal(w.prefix, 'aaaaaaaaa|');
|
||||
assert.equal(w.suffix, 'bbbbb');
|
||||
assert.deepEqual(windowAround('short', 2), { prefix: 'sh', suffix: 'ort' });
|
||||
assert.deepEqual(windowAround('x', 99), { prefix: 'x', suffix: '' });
|
||||
// A character of two units is never cut in half.
|
||||
const bread = 'ab🍞cd🍞ef';
|
||||
const cut = windowAround(bread, 5, { prefixMax: 2, suffixMax: 2 });
|
||||
assert.equal(cut.prefix, 'c');
|
||||
assert.equal(cut.suffix, 'd');
|
||||
});
|
||||
|
||||
// ---- against the stand-in agent, on the real clock ----------------------------------------
|
||||
|
||||
function onAgent(t, env, extra) {
|
||||
const { chat, agents } = fakeChat(t, { env });
|
||||
const refusals = [];
|
||||
const completer = new Completer({
|
||||
request: (m, p) => chat.request(m, p, true),
|
||||
notify: (m, p) => chat.notify(m, p),
|
||||
debounceMs: () => 20,
|
||||
onRefusal: (reason, message) => refusals.push({ reason, message }),
|
||||
...(extra || {}),
|
||||
});
|
||||
return { chat, agents, completer, refusals };
|
||||
}
|
||||
|
||||
test('agent: a completion comes back as text to insert', async (t) => {
|
||||
const { completer, agents } = onAgent(t);
|
||||
assert.equal(await completer.ask({ prefix: 'def bake', suffix: '', language: 'python' }), '<bake|example/model-a>');
|
||||
const sent = agents[0].log().find((m) => m.method === '_lembas/complete');
|
||||
assert.deepEqual(sent.params, { id: 'c1', prefix: 'def bake', suffix: '', language: 'python' });
|
||||
assert.ok(!agents[0].log().some((m) => m.method === 'session/new'), 'a completion needs no session');
|
||||
});
|
||||
|
||||
test('agent: a slow completion is cancelled by the next one, and only the newest is shown', async (t) => {
|
||||
const { completer, agents, chat } = onAgent(t);
|
||||
await chat.connect(true);
|
||||
const slow = completer.ask({ prefix: 'SLOWC one' }, { manual: true });
|
||||
await until(() => agents[0].log().some((m) => m.method === '_lembas/complete'));
|
||||
const fast = completer.ask({ prefix: 'two' }, { manual: true });
|
||||
assert.equal(await slow, null);
|
||||
assert.equal(await fast, '<two|example/model-a>');
|
||||
assert.deepEqual(agents[0].log().find((m) => m.method === '_lembas/complete/cancel').params, { id: 'c1' });
|
||||
});
|
||||
|
||||
test('agent: nobody has chosen a model — said once with the server\'s sentence, then a window choice works', async (t) => {
|
||||
let model;
|
||||
const { completer, agents, refusals } = onAgent(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' }, { model: () => model });
|
||||
assert.equal(await completer.ask({ prefix: 'a' }), null);
|
||||
assert.equal(await completer.ask({ prefix: 'ab' }), null);
|
||||
assert.equal(await completer.ask({ prefix: 'abc' }), null);
|
||||
assert.deepEqual(refusals, [{ reason: 'no_model', message: 'No autocomplete model is chosen. Choose one in your settings on the server.' }]);
|
||||
assert.equal(agents[0].log().filter((m) => m.method === '_lembas/complete').length, 1);
|
||||
model = 'example/model-b';
|
||||
completer.unblock();
|
||||
assert.equal(await completer.ask({ prefix: 'abc' }), '<abc|example/model-b>');
|
||||
});
|
||||
|
||||
test('agent: a model not allowed for autocomplete is a refusal of its own', async (t) => {
|
||||
const { completer, refusals } = onAgent(t, {}, { model: () => 'example/model-c' });
|
||||
assert.equal(await completer.ask({ prefix: 'a' }), null);
|
||||
assert.equal(refusals[0].reason, 'not_allowed');
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { editorContext, promptParams, selectionLabel, sliceLines, LIMITS } = require('../src/context');
|
||||
|
||||
test('nothing to say is no context at all', () => {
|
||||
assert.equal(editorContext(null), undefined);
|
||||
assert.equal(editorContext({}), undefined);
|
||||
assert.equal(editorContext({ diagnostics: [], open: [] }), undefined);
|
||||
});
|
||||
|
||||
test('lines are 1-based, a selection in another file names it, the open file is not listed twice', () => {
|
||||
assert.deepEqual(editorContext({ path: '/p/a.py', cursorLine: 3, selection: { path: '/p/a.py', start: 2, end: 2, text: 'x' }, open: ['/p/a.py', '/p/b.py', '/p/b.py'] }), {
|
||||
path: '/p/a.py',
|
||||
cursor: { line: 3 },
|
||||
selection: { start: 2, end: 2, text: 'x' },
|
||||
open: ['/p/b.py'],
|
||||
});
|
||||
assert.deepEqual(editorContext({ path: '/p/a.py', selection: { path: '/p/c.py', start: 5, end: 3 } }).selection, { start: 5, end: 5, path: '/p/c.py' });
|
||||
assert.equal(editorContext({ path: '/p/a.py', cursorLine: 0 }).cursor, undefined);
|
||||
});
|
||||
|
||||
test('diagnostics and open files are kept to the limits, each message one line', () => {
|
||||
const many = Array.from({ length: 50 }, (_, i) => ({ line: i + 1, severity: 'error', message: 'bad\n thing ' + i + ' ' + 'x'.repeat(400), source: 'lint' }));
|
||||
const ctx = editorContext({ path: '/p/a.py', diagnostics: [...many, { message: ' ' }, null], open: Array.from({ length: 80 }, (_, i) => '/p/f' + i) });
|
||||
assert.equal(ctx.diagnostics.length, LIMITS.diagnostics);
|
||||
assert.ok(ctx.diagnostics.every((d) => !d.message.includes('\n') && d.message.length <= LIMITS.diagnosticChars));
|
||||
assert.match(ctx.diagnostics[0].message, /^bad thing 0 x+…$/);
|
||||
assert.equal(ctx.open.length, LIMITS.open);
|
||||
assert.equal(editorContext({ diagnostics: [{ message: 'm', severity: 'fatal', line: -2 }] }).diagnostics[0].severity, undefined);
|
||||
});
|
||||
|
||||
test('the prompt: context beside the text for an agent that reads it', () => {
|
||||
const editor = editorContext({ path: '/p/a.py', cursorLine: 3 });
|
||||
assert.deepEqual(promptParams('ses_1', 'hi', editor, true), {
|
||||
sessionId: 'ses_1',
|
||||
prompt: [{ type: 'text', text: 'hi' }],
|
||||
_meta: { lembas: { editor: { path: '/p/a.py', cursor: { line: 3 } } } },
|
||||
});
|
||||
assert.deepEqual(promptParams('ses_1', 'hi', undefined, true), { sessionId: 'ses_1', prompt: [{ type: 'text', text: 'hi' }] });
|
||||
assert.deepEqual(promptParams('ses_1', 'hi', editor, false).prompt, [
|
||||
{ type: 'text', text: 'Open in the editor: /p/a.py, cursor on line 3.' },
|
||||
{ type: 'text', text: 'hi' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('how a selection is named', () => {
|
||||
assert.equal(selectionLabel('src/a.py', 3, 9), 'src/a.py:3-9');
|
||||
assert.equal(selectionLabel('src/a.py', 3, 3), 'src/a.py:3');
|
||||
assert.equal(selectionLabel('', 1, 2), 'untitled:1-2');
|
||||
});
|
||||
|
||||
test("the part of a text the agent asks for (ACP's line and limit)", () => {
|
||||
const text = 'one\ntwo\nthree\nfour\n';
|
||||
assert.equal(sliceLines(text), text);
|
||||
assert.equal(sliceLines(text, null, null), text);
|
||||
assert.equal(sliceLines(text, 1), text);
|
||||
assert.equal(sliceLines(text, 2, 2), 'two\nthree');
|
||||
assert.equal(sliceLines(text, 3), 'three\nfour\n');
|
||||
assert.equal(sliceLines(text, 1, 1), 'one');
|
||||
assert.equal(sliceLines(text, 99, 5), '');
|
||||
assert.equal(sliceLines(text, 2, 0), '');
|
||||
assert.equal(sliceLines(text, 'x', 'y'), text);
|
||||
});
|
||||
@@ -0,0 +1,646 @@
|
||||
'use strict';
|
||||
// extension.js, loaded against tests/stub_vscode.js and the stand-in agent. This is NOT a run
|
||||
// inside VS Code: the editor here is a few hundred lines of memory. It shows that the glue
|
||||
// loads, registers what the manifest names, and drives the tested modules the way it means to.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const Module = require('node:module');
|
||||
const crypto = require('node:crypto');
|
||||
const { make } = require('./stub_vscode');
|
||||
const { FAKE, tempDir, until } = require('./helpers');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
||||
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), crypto.randomBytes(3000)]);
|
||||
|
||||
/** Activate the extension in a fresh stand-in editor whose `lembas` is the stand-in agent. */
|
||||
function host(t, env) {
|
||||
const dir = tempDir(t);
|
||||
const log = path.join(dir, 'agent.log');
|
||||
const command = path.join(dir, 'lembas');
|
||||
const vars = { FAKE_AGENT_LOG: log, PYTHONDONTWRITEBYTECODE: '1', ...(env || {}) };
|
||||
const exports_ = Object.entries(vars).map(([k, v]) => `export ${k}='${v}'`).join('\n');
|
||||
// The extension starts `<command> serve --stdio`; this one is the stand-in, whatever it is told.
|
||||
fs.writeFileSync(command, `#!/bin/sh\n${exports_}\nexec python3 '${FAKE}'\n`, { mode: 0o755 });
|
||||
const vscode = make(pkg);
|
||||
vscode.__.config['llembas.command'] = command;
|
||||
vscode.workspace.workspaceFolders = [{ uri: vscode.Uri.file(dir) }];
|
||||
const load = Module._load;
|
||||
Module._load = function (request, ...rest) {
|
||||
return request === 'vscode' ? vscode : load.call(this, request, ...rest);
|
||||
};
|
||||
for (const key of Object.keys(require.cache)) if (key.startsWith(ROOT + path.sep) && !key.includes(`${path.sep}tests${path.sep}`)) delete require.cache[key];
|
||||
const extension = require('../extension.js');
|
||||
Module._load = load;
|
||||
const context = { subscriptions: [], extensionUri: vscode.Uri.file(ROOT), extension: { packageJSON: { version: '0.0.0' } } };
|
||||
extension.activate(context);
|
||||
t.after(() => {
|
||||
for (const s of context.subscriptions) s.dispose && s.dispose();
|
||||
extension.deactivate();
|
||||
});
|
||||
const view = vscode.__.view();
|
||||
vscode.__.viewProviders.get('llembas.chat').provider.resolveWebviewView(view);
|
||||
view.say({ type: 'ready' });
|
||||
const sent = () => (fs.existsSync(log) ? fs.readFileSync(log, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
|
||||
const run = (name, ...args) => vscode.__.commands.get(name)(...args);
|
||||
/** The newest version of every item the page was sent, in order. */
|
||||
const items = () => {
|
||||
const byId = new Map();
|
||||
for (const m of view.posted) {
|
||||
if (m.type === 'reset') {
|
||||
byId.clear();
|
||||
for (const i of m.items) byId.set(i.id, i);
|
||||
} else if (m.type === 'item') byId.set(m.item.id, m.item);
|
||||
}
|
||||
return [...byId.values()];
|
||||
};
|
||||
const state = () => view.posted.filter((m) => m.type === 'state' || m.type === 'reset').pop().state;
|
||||
const idle = () => until(() => state().busy === false && items().length > 0);
|
||||
return { vscode, view, dir, sent, run, items, state, idle, s: vscode.__ };
|
||||
}
|
||||
|
||||
const flat = (ast) => JSON.stringify(ast);
|
||||
|
||||
test('activation registers the view, every command of the manifest, the providers and a status item', (t) => {
|
||||
const { s, view } = host(t);
|
||||
assert.deepEqual([...s.commands.keys()].sort(), pkg.contributes.commands.map((c) => c.command).sort());
|
||||
assert.ok(s.viewProviders.get('llembas.chat').options.webviewOptions.retainContextWhenHidden);
|
||||
assert.equal(s.inlineProviders.length, 1);
|
||||
assert.equal(s.lensProviders.length, 1);
|
||||
assert.ok(s.contentProviders.has('llembas-diff'));
|
||||
assert.equal(s.statusItems[0].text, 'LLeMbas');
|
||||
assert.equal(s.statusItems[0].command, 'llembas.modelSettings');
|
||||
assert.equal(view.webview.options.enableScripts, true);
|
||||
assert.equal(view.webview.options.enableCommandUris, false);
|
||||
assert.equal(view.webview.options.localResourceRoots.length, 2);
|
||||
assert.match(view.webview.html, /Content-Security-Policy" content="default-src 'none'; img-src https:\/\/file\.example; style-src https:\/\/file\.example; script-src 'nonce-[A-Za-z0-9_-]{20,}'/);
|
||||
assert.deepEqual(view.posted[0], { type: 'reset', items: [], state: { busy: false, session: false, mode: null, modes: [], model: null, models: [] }, attached: '' });
|
||||
});
|
||||
|
||||
test('a message typed in the view is answered, and the reply reaches the page as a tree, not as markup', async (t) => {
|
||||
const { vscode, view, sent, items, state, idle, dir } = host(t);
|
||||
vscode.__.open(path.join(dir, 'oven.py'), 'def bake():\n pass\n', new vscode.Selection(1, 4, 1, 4), 'python');
|
||||
view.say({ type: 'send', text: 'hello' });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
const [user, agent] = items();
|
||||
assert.deepEqual({ kind: user.kind, text: user.text }, { kind: 'user', text: 'hello' });
|
||||
assert.equal(agent.text, undefined, "the model's text is not sent as a string to draw");
|
||||
assert.equal(flat(agent.ast), flat([{ t: 'p', c: [{ t: 'text', v: 'Hello there.' }, { t: 'br' }, { t: 'text', v: 'Second line' }] }]));
|
||||
assert.equal(state().mode, 'ask');
|
||||
assert.equal(state().model, 'example/model-a');
|
||||
await until(() => state().models.length === 3);
|
||||
// The file in front and the cursor went with the prompt.
|
||||
const prompt = sent().find((m) => m.method === 'session/prompt');
|
||||
assert.deepEqual(prompt.params._meta.lembas.editor, { path: path.join(dir, 'oven.py'), cursor: { line: 2 } });
|
||||
assert.equal(sent().find((m) => m.method === 'session/new').params.cwd, dir);
|
||||
// The page's own controls.
|
||||
view.say({ type: 'setModel', id: 'example/model-b' });
|
||||
await until(() => state().model === 'example/model-b');
|
||||
view.say({ type: 'setMode', id: 'edit' });
|
||||
await until(() => state().mode === 'edit');
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
});
|
||||
|
||||
test('messages from the page are checked: a bad link is not opened, a wrong shape is ignored', async (t) => {
|
||||
const { view, s } = host(t);
|
||||
for (const m of [null, 'send', { type: 7 }, { type: 'send', text: 42 }, { type: 'send', text: ' ' }, { type: 'answer', card: 1, option: {} }, { type: 'openLink', href: 'javascript:alert(1)' },
|
||||
{ type: 'openLink', href: 'command:workbench.action.terminal.new' }, { type: 'openLink', href: 'file:///etc/passwd' }, { type: 'openFile', path: 'relative/path' }, { type: 'openMedia', key: 'nope' }, { type: 'unknown' }]) {
|
||||
view.say(m);
|
||||
}
|
||||
view.say({ type: 'openLink', href: 'https://example.org/docs' });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.deepEqual(s.external, ['https://example.org/docs']);
|
||||
assert.equal(view.posted.filter((m) => m.type === 'item').length, 0, 'nothing was sent to the agent');
|
||||
});
|
||||
|
||||
test('ask about a selection: the answer in the chat, the selection as editor context', async (t) => {
|
||||
const { vscode, view, sent, items, idle, run, dir, s } = host(t);
|
||||
const file = path.join(dir, 'oven.py');
|
||||
vscode.__.open(file, 'import flour\n\ndef bake():\n return crumbs\n\nprint(bake())\n', new vscode.Selection(2, 0, 4, 0), 'python');
|
||||
s.diagnostics.set(vscode.Uri.file(file).toString(), [
|
||||
{ range: new vscode.Range(3, 11, 3, 17), severity: 0, message: "name 'crumbs' is not defined", source: 'lint' },
|
||||
{ range: new vscode.Range(0, 0, 0, 12), severity: 1, message: 'unused import', source: 'lint' },
|
||||
]);
|
||||
s.inputs.push('META why does this fail?');
|
||||
await run('llembas.ask');
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
const prompt = sent().find((m) => m.method === 'session/prompt');
|
||||
assert.deepEqual(prompt.params.prompt, [{ type: 'text', text: 'META why does this fail?' }]);
|
||||
assert.deepEqual(prompt.params._meta.lembas.editor, {
|
||||
path: file,
|
||||
cursor: { line: 5 },
|
||||
selection: { start: 3, end: 4, text: 'def bake():\n return crumbs\n' },
|
||||
diagnostics: [{ message: "name 'crumbs' is not defined", line: 4, severity: 'error', source: 'lint' }],
|
||||
});
|
||||
assert.equal(items()[0].label, 'oven.py:3-4');
|
||||
assert.ok(s.executed.some((e) => e[0] === 'llembas.chat.focus'), 'the chat is brought forward');
|
||||
|
||||
// Without a question the selection waits for the next message typed.
|
||||
s.inputs.push('');
|
||||
await run('llembas.ask');
|
||||
assert.deepEqual(view.posted.filter((m) => m.type === 'attached').pop(), { type: 'attached', label: 'oven.py:3-4' });
|
||||
view.say({ type: 'send', text: 'and this?' });
|
||||
await until(() => sent().filter((m) => m.method === 'session/prompt').length === 2);
|
||||
assert.equal(sent().filter((m) => m.method === 'session/prompt')[1].params._meta.lembas.editor.selection.start, 3);
|
||||
assert.deepEqual(view.posted.filter((m) => m.type === 'attached').pop(), { type: 'attached', label: '' });
|
||||
await idle();
|
||||
|
||||
// Nothing selected: said, and nothing sent.
|
||||
vscode.window.activeTextEditor.selection = new vscode.Selection(1, 0, 1, 0);
|
||||
await run('llembas.ask');
|
||||
assert.match(s.messages.pop().text, /select the text/);
|
||||
});
|
||||
|
||||
test('rewrite a selection: shown as changes to accept or reject, nothing written before', async (t) => {
|
||||
const { vscode, sent, run, dir, s } = host(t);
|
||||
const before = ['top', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'bottom'].join('\n');
|
||||
const editor = vscode.__.open(path.join(dir, 'list.txt'), before, new vscode.Selection(1, 0, 10, 0));
|
||||
const doc = editor.document;
|
||||
s.inputs.push('REPLACE A1\\na2\\na3\\na5\\na6\\nnew\\na7\\na8\\nA9\\ntail');
|
||||
await run('llembas.rewrite');
|
||||
|
||||
const asked = sent().find((m) => m.method === '_lembas/edit');
|
||||
assert.equal(asked.params.text, 'a1\na2\na3\na4\na5\na6\na7\na8\na9', 'whole lines, and not the line the selection only ends in front of');
|
||||
assert.equal(asked.params.before, 'top');
|
||||
assert.equal(asked.params.after, 'bottom');
|
||||
assert.equal(asked.params.path, path.join(dir, 'list.txt'));
|
||||
assert.equal(asked.params.id, 'e1');
|
||||
assert.ok(s.executed.some((e) => e[0] === 'progress'), 'the pieces written so far are shown');
|
||||
|
||||
assert.equal(doc.text, before, 'nothing is written before it is accepted');
|
||||
assert.match(s.messages.pop().text, /proposes 4 changes\. Nothing is written until you accept\./);
|
||||
const lenses = s.lensProviders[0].provideCodeLenses(doc);
|
||||
assert.deepEqual(lenses.map((l) => `${l.range.start.line}:${l.command.title}`), [
|
||||
'1:Accept', '1:Reject', '1:Accept all 4', '1:Reject all', '1:Show as a diff', '4:Accept', '4:Reject', '7:Accept', '7:Reject', '9:Accept', '9:Reject',
|
||||
]);
|
||||
const [removed, added] = [...editor.decorations.values()];
|
||||
assert.deepEqual(removed.map((d) => d.range.start.line), [1, 4, 9]);
|
||||
assert.deepEqual(added.map((d) => d.renderOptions.after.contentText), ['→ A1', 'taken away', 'added above: new', '→ A9 (+1 more line)']);
|
||||
|
||||
// The diff view: the file on the left, the whole proposal on the right.
|
||||
const diff = s.executed.find((e) => e[0] === 'vscode.diff');
|
||||
assert.equal(diff[1], doc.uri);
|
||||
assert.equal(diff[2].scheme, 'llembas-diff');
|
||||
const proposed = () => s.contentProviders.get('llembas-diff').provideTextDocumentContent(diff[2]);
|
||||
assert.equal(proposed(), ['top', 'A1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
|
||||
|
||||
// A second rewrite waits until this one is settled.
|
||||
s.inputs.push('anything');
|
||||
await run('llembas.rewrite');
|
||||
assert.match(s.messages.pop().text, /accept or reject the changes shown in this file first/);
|
||||
|
||||
// Accept the second change (a4 taken away) through its code lens.
|
||||
const second = lenses.find((l) => l.range.start.line === 4 && l.command.title === 'Accept').command;
|
||||
await run(second.command, ...second.arguments);
|
||||
assert.equal(doc.text, ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'a7', 'a8', 'a9', 'bottom'].join('\n'));
|
||||
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [1, 6, 8]);
|
||||
|
||||
// Reject the first (A1) at the cursor, by the command without arguments.
|
||||
editor.selection = new vscode.Selection(1, 0, 1, 0);
|
||||
await run('llembas.rejectChange');
|
||||
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [6, 8]);
|
||||
assert.equal(proposed(), ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
|
||||
|
||||
// Typing above moves what is left; then accept all.
|
||||
doc.text = 'typed\n' + doc.text;
|
||||
doc.version += 1;
|
||||
s.changed.fire({ document: doc, contentChanges: [{ range: new vscode.Range(0, 0, 0, 0), text: 'typed\n' }] });
|
||||
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line), [7, 9]);
|
||||
await run('llembas.acceptAllChanges');
|
||||
assert.equal(doc.text, ['typed', 'top', 'a1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail', 'bottom'].join('\n'));
|
||||
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc), []);
|
||||
assert.deepEqual([...editor.decorations.values()].map((d) => d.length), [0, 0]);
|
||||
assert.ok(!s.tabs.some((tab) => tab.input.modified), 'the diff view is closed with the last change');
|
||||
});
|
||||
|
||||
test('rewrite: a change typed over is dropped rather than applied to the wrong text; reject all leaves the file alone', async (t) => {
|
||||
const { vscode, run, dir, s } = host(t);
|
||||
const editor = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo\nthree', new vscode.Selection(0, 0, 2, 5));
|
||||
const doc = editor.document;
|
||||
s.inputs.push('REPLACE ONE\\ntwo\\nTHREE');
|
||||
await run('llembas.rewrite');
|
||||
assert.equal(s.lensProviders[0].provideCodeLenses(doc).filter((l) => l.command.title === 'Accept').length, 2);
|
||||
// The person edits line 3 behind the extension's back (no change event reaches it).
|
||||
doc.text = 'one\ntwo\nthree!';
|
||||
await run('llembas.acceptAllChanges');
|
||||
assert.equal(doc.text, 'ONE\ntwo\nthree!');
|
||||
assert.match(s.messages.pop().text, /the text changed where a change was proposed; it was dropped/);
|
||||
|
||||
s.inputs.push('REPLACE x');
|
||||
editor.selection = new vscode.Selection(0, 0, 2, 6);
|
||||
await run('llembas.rewrite');
|
||||
await run('llembas.rejectAllChanges');
|
||||
assert.equal(doc.text, 'ONE\ntwo\nthree!');
|
||||
assert.deepEqual(s.lensProviders[0].provideCodeLenses(doc), []);
|
||||
});
|
||||
|
||||
test('rewrite: the answer to the proposal\'s own message accepts all; a file that changed meanwhile shows nothing', async (t) => {
|
||||
const { vscode, run, dir, s } = host(t);
|
||||
const editor = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
|
||||
s.inputs.push('shout');
|
||||
s.answers.push('Accept all');
|
||||
await run('llembas.rewrite');
|
||||
assert.equal(editor.document.text, 'ONE\nTWO');
|
||||
|
||||
s.inputs.push('SLOWE shout');
|
||||
const going = run('llembas.rewrite');
|
||||
await until(() => typeof s.cancelProgress === 'function');
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
s.cancelProgress();
|
||||
await going;
|
||||
assert.equal(editor.document.text, 'ONE\nTWO', 'a cancelled rewrite proposes nothing');
|
||||
assert.deepEqual(s.lensProviders[0].provideCodeLenses(editor.document), []);
|
||||
});
|
||||
|
||||
test('autocomplete: as you type and by hand, as an inline completion at the cursor', async (t) => {
|
||||
const { vscode, sent, dir, s } = host(t);
|
||||
s.config['llembas.complete.debounce'] = 10;
|
||||
const editor = vscode.__.open(path.join(dir, 'oven.py'), 'def bake(flour):\n return \nprint(1)\n', new vscode.Selection(1, 11, 1, 11), 'python');
|
||||
const provider = s.inlineProviders[0];
|
||||
const token = () => ({ isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
|
||||
const at = new vscode.Position(1, 11);
|
||||
const got = await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1 }, token());
|
||||
assert.equal(got.length, 1);
|
||||
assert.equal(got[0].insertText, '<return|example/model-a>');
|
||||
assert.deepEqual(got[0].range.start, at);
|
||||
assert.deepEqual(sent().find((m) => m.method === '_lembas/complete').params, {
|
||||
id: 'c1', prefix: 'def bake(flour):\n return ', suffix: '\nprint(1)\n', path: path.join(dir, 'oven.py'), language: 'python',
|
||||
});
|
||||
// The editor's own suggestion list is open: stay out of its way.
|
||||
assert.equal(await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1, selectedCompletionInfo: {} }, token()), undefined);
|
||||
// Switched off: nothing as you type, still there by hand.
|
||||
s.config['llembas.complete.auto'] = false;
|
||||
assert.equal(await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 1 }, token()), undefined);
|
||||
assert.equal((await provider.provideInlineCompletionItems(editor.document, at, { triggerKind: 0 }, token()))[0].insertText, '<return|example/model-a>');
|
||||
s.config['llembas.complete.auto'] = true;
|
||||
// The editor moved on before the answer: the request is cancelled by its id and nothing is shown.
|
||||
editor.document.text = 'x = SLOWC \n';
|
||||
let cancel;
|
||||
const moving = provider.provideInlineCompletionItems(editor.document, new vscode.Position(0, 10), { triggerKind: 0 }, {
|
||||
isCancellationRequested: false,
|
||||
onCancellationRequested: (fn) => ((cancel = fn), { dispose() {} }),
|
||||
});
|
||||
await until(() => sent().filter((m) => m.method === '_lembas/complete').length === 3);
|
||||
cancel();
|
||||
assert.equal(await moving, undefined);
|
||||
await until(() => sent().some((m) => m.method === '_lembas/complete/cancel'));
|
||||
assert.deepEqual(sent().find((m) => m.method === '_lembas/complete/cancel').params, { id: 'c3' });
|
||||
// The command asks the editor for an inline suggestion, which comes back to the provider as "by hand".
|
||||
await s.commands.get('llembas.complete')();
|
||||
assert.ok(s.executed.some((e) => e[0] === 'editor.action.inlineSuggest.trigger'));
|
||||
});
|
||||
|
||||
test('autocomplete without a model: said once with a button, quiet until one is chosen; the quick switch is not saved', async (t) => {
|
||||
const { vscode, sent, dir, s } = host(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' });
|
||||
s.config['llembas.complete.debounce'] = 5;
|
||||
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = 1\ny = ', new vscode.Selection(1, 4, 1, 4), 'python');
|
||||
const provider = s.inlineProviders[0];
|
||||
const ask = () => provider.provideInlineCompletionItems(editor.document, new vscode.Position(1, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
|
||||
|
||||
// The person presses the button, picks Model B, for this window only.
|
||||
s.answers.push('Choose a model');
|
||||
s.picks.push((items) => {
|
||||
assert.deepEqual(items.map((i) => i.label), ['Model A', 'Model B', "Use the server's default"], 'only models allowed for autocomplete');
|
||||
return items[1];
|
||||
});
|
||||
s.picks.push((items) => items.find((i) => i.label === 'Only this window'));
|
||||
assert.equal(await ask(), undefined);
|
||||
assert.deepEqual(s.messages[0], { level: 'info', text: 'LLeMbas: No autocomplete model is chosen. Choose one in your settings on the server.', buttons: ['Choose a model'] });
|
||||
await until(() => s.statusItems[0].text === 'LLeMbas: model-b');
|
||||
assert.match(s.statusItems[0].tooltip, /example\/model-b \(this window only\)/);
|
||||
assert.equal(s.messages.length, 1);
|
||||
|
||||
const got = await ask();
|
||||
assert.equal(got[0].insertText, '<=|example/model-b>');
|
||||
assert.equal(sent().filter((m) => m.method === '_lembas/complete').pop().params.model, 'example/model-b');
|
||||
assert.ok(!sent().some((m) => m.method === '_lembas/editor/settings'), 'a quick switch is saved nowhere');
|
||||
});
|
||||
|
||||
test('autocomplete without a model: asked again and again while typing, the server is asked once', async (t) => {
|
||||
const { vscode, sent, dir, s } = host(t, { FAKE_AGENT_AUTOCOMPLETE: 'none' });
|
||||
s.config['llembas.complete.debounce'] = 5;
|
||||
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = ', new vscode.Selection(0, 4, 0, 4), 'python');
|
||||
const ask = () => s.inlineProviders[0].provideInlineCompletionItems(editor.document, new vscode.Position(0, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
|
||||
for (let i = 0; i < 4; i++) assert.equal(await ask(), undefined);
|
||||
assert.equal(sent().filter((m) => m.method === '_lembas/complete').length, 1);
|
||||
assert.equal(s.messages.length, 1);
|
||||
});
|
||||
|
||||
test('the two model settings: read, and saved in the account through the agent', async (t) => {
|
||||
const { sent, run, s } = host(t);
|
||||
s.picks.push((items) => {
|
||||
assert.deepEqual(items.map((i) => [i.label, i.description]), [['Autocomplete model', 'example/model-a'], ['Main model', 'not chosen']]);
|
||||
return items[1];
|
||||
});
|
||||
s.picks.push((items) => {
|
||||
assert.deepEqual(items.map((i) => i.label), ['Model A', 'Model B', 'Model C', "Use the server's default"]);
|
||||
return items[2];
|
||||
});
|
||||
s.picks.push((items) => items.find((i) => i.label === 'Save it'));
|
||||
await run('llembas.modelSettings');
|
||||
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { main_model: 'example/model-c' } });
|
||||
|
||||
s.picks.push((items) => items.find((i) => i.label === 'Model B'));
|
||||
s.picks.push((items) => items.find((i) => i.label === 'Save it'));
|
||||
await run('llembas.chooseAutocompleteModel');
|
||||
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: 'example/model-b' } });
|
||||
assert.equal(s.statusItems[0].text, 'LLeMbas: model-b');
|
||||
|
||||
s.picks.push((items) => items[items.length - 1]);
|
||||
await run('llembas.chooseAutocompleteModel');
|
||||
assert.deepEqual(sent().filter((m) => m.method === '_lembas/editor/settings').pop().params, { set: { autocomplete_model: null } });
|
||||
});
|
||||
|
||||
test("the window's main model starts sessions and rewrites, and is saved nowhere", async (t) => {
|
||||
const { vscode, view, sent, run, items, idle, dir, s } = host(t);
|
||||
s.picks.push((items_) => items_.find((i) => i.label === 'Model C'));
|
||||
s.picks.push((items_) => items_.find((i) => i.label === 'Only this window'));
|
||||
await run('llembas.chooseMainModel');
|
||||
assert.ok(!sent().some((m) => m.method === '_lembas/editor/settings'));
|
||||
view.say({ type: 'send', text: 'hello' });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
assert.equal(sent().find((m) => m.method === 'session/new').params._meta.model, 'example/model-c');
|
||||
vscode.__.open(path.join(dir, 'a.txt'), 'one', new vscode.Selection(0, 0, 0, 3));
|
||||
s.inputs.push('shout');
|
||||
await run('llembas.rewrite');
|
||||
const edit = sent().find((m) => m.method === '_lembas/edit');
|
||||
assert.equal(edit.params.model, 'example/model-c');
|
||||
assert.equal(edit.params.sessionId, 'ses_test');
|
||||
});
|
||||
|
||||
test("an approval that carries a diff opens the editor's diff view before the answer, and closes it after", async (t) => {
|
||||
const { view, items, idle, dir, s } = host(t);
|
||||
const file = path.join(dir, 'waybread.py');
|
||||
fs.writeFileSync(file, 'old text\n');
|
||||
view.say({ type: 'send', text: `DIFFPERM ${file}` });
|
||||
await until(() => items().some((i) => i.kind === 'card'));
|
||||
const card = items().find((i) => i.kind === 'card');
|
||||
assert.equal(card.state, 'open');
|
||||
assert.deepEqual(card.files, [file]);
|
||||
const diff = s.executed.find((e) => e[0] === 'vscode.diff');
|
||||
const provider = s.contentProviders.get('llembas-diff');
|
||||
assert.equal(provider.provideTextDocumentContent(diff[1]), 'old text\n');
|
||||
assert.equal(provider.provideTextDocumentContent(diff[2]), 'rewritten by the agent\n');
|
||||
assert.equal(diff[3], 'LLeMbas: waybread.py (proposed change)');
|
||||
assert.ok(diff[1].path.endsWith('/waybread.py'), 'named like the file, so the editor colours it as one');
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), 'old text\n');
|
||||
assert.deepEqual(view.shows, [true], 'the chat is shown without taking the keyboard');
|
||||
assert.equal(s.tabs.filter((tab) => tab.input.modified).length, 1);
|
||||
|
||||
view.say({ type: 'answer', card: card.id, option: 'once' });
|
||||
await until(() => fs.readFileSync(file, 'utf8') === 'rewritten by the agent\n');
|
||||
await idle();
|
||||
await until(() => items().find((i) => i.kind === 'card').state === 'answered'); // items reach the page a moment after the state
|
||||
await until(() => s.tabs.filter((tab) => tab.input.modified).length === 0);
|
||||
assert.equal(provider.provideTextDocumentContent(diff[2]), '', 'the texts are let go');
|
||||
assert.deepEqual(items().find((i) => i.kind === 'tool').files, [file]);
|
||||
});
|
||||
|
||||
test('unsaved text: the agent reads an open file from the editor, and any other file itself', async (t) => {
|
||||
const { vscode, view, items, idle, dir } = host(t);
|
||||
const file = path.join(dir, 'draft.md');
|
||||
fs.writeFileSync(file, 'saved text\n');
|
||||
vscode.__.open(file, 'unsaved text\nline two\n');
|
||||
view.say({ type: 'send', text: `READ ${file}` });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
assert.match(flat(items().find((i) => i.kind === 'agent').ast), /read=\\"unsaved text\\\\nline two\\\\n\\"/);
|
||||
view.say({ type: 'send', text: `READ ${path.join(dir, 'not-open.md')}` });
|
||||
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
|
||||
await idle();
|
||||
assert.match(flat(items().filter((i) => i.kind === 'agent')[1].ast), /read=null/);
|
||||
});
|
||||
|
||||
test('media: a picture is shown in the chat; only kinds that are merely displayed open, the rest are shown in their folder', async (t) => {
|
||||
const { view, items, idle, dir, s } = host(t);
|
||||
const picture = path.join(dir, 'chart.png');
|
||||
fs.writeFileSync(picture, PNG);
|
||||
view.say({ type: 'send', text: `SHOW ${picture}` });
|
||||
await until(() => items().some((i) => i.kind === 'media'));
|
||||
await idle();
|
||||
const shown = items().find((i) => i.kind === 'media');
|
||||
assert.equal(shown.picture, true);
|
||||
assert.equal(shown.sizeWords, '3 KB');
|
||||
const root = view.webview.options.localResourceRoots[1].path;
|
||||
assert.ok(shown.src.startsWith('https://file.example' + root + '/') && shown.src.endsWith('-chart.png'), shown.src);
|
||||
assert.ok(fs.readFileSync(shown.src.slice('https://file.example'.length)).equals(PNG));
|
||||
assert.equal(shown.opens, true);
|
||||
view.say({ type: 'openMedia', key: shown.key });
|
||||
await until(() => s.executed.some((e) => e[0] === 'vscode.open'));
|
||||
|
||||
// A new session clears the transcript, and the files that were shown in it go with it.
|
||||
const kept = shown.src.slice('https://file.example'.length);
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
await until(() => !fs.existsSync(kept));
|
||||
view.say({ type: 'openMedia', key: shown.key });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(s.executed.filter((e) => e[0] === 'vscode.open').length, 1, 'its key opens nothing any more');
|
||||
const script = path.join(dir, 'setup.sh');
|
||||
fs.writeFileSync(script, '#!/bin/sh\necho hello from a script that must not run\n');
|
||||
view.say({ type: 'send', text: `SHOW ${script} WITHURI` });
|
||||
await until(() => items().some((i) => i.kind === 'media'));
|
||||
await idle();
|
||||
const line = items().find((i) => i.kind === 'media');
|
||||
assert.equal(line.picture, false);
|
||||
assert.equal(line.src, '');
|
||||
assert.equal(line.opens, false);
|
||||
view.say({ type: 'openMedia', key: line.key });
|
||||
await until(() => s.executed.some((e) => e[0] === 'revealFileInOS'));
|
||||
assert.equal(s.executed.find((e) => e[0] === 'revealFileInOS')[1].fsPath, script, 'shown in its folder');
|
||||
assert.deepEqual(s.external, [], 'not handed to the system');
|
||||
assert.equal(s.executed.filter((e) => e[0] === 'vscode.open').length, 1, 'and not opened in the editor');
|
||||
|
||||
// A program that calls itself a PDF, and a document with macros: the same.
|
||||
for (const [name, content] of [['invoice.pdf', 'MZ\x90\x00 not a pdf at all'], ['letter.docm', 'PK\x03\x04 macros inside'], ['tool.pyw', 'import os\n']]) {
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
const file = path.join(dir, name);
|
||||
fs.writeFileSync(file, content, 'latin1');
|
||||
const reveals = s.executed.filter((e) => e[0] === 'revealFileInOS').length;
|
||||
view.say({ type: 'send', text: `SHOW ${file} WITHURI` });
|
||||
await until(() => items().some((i) => i.kind === 'media'));
|
||||
await idle();
|
||||
assert.equal(items().find((i) => i.kind === 'media').opens, false, name);
|
||||
view.say({ type: 'openMedia', key: items().find((i) => i.kind === 'media').key });
|
||||
await until(() => s.executed.filter((e) => e[0] === 'revealFileInOS').length === reveals + 1);
|
||||
assert.deepEqual(s.external, [], name);
|
||||
}
|
||||
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
const pdf = path.join(dir, 'report.pdf');
|
||||
fs.writeFileSync(pdf, '%PDF-1.7\n' + 'x'.repeat(2000));
|
||||
view.say({ type: 'send', text: `SHOW ${pdf} WITHURI` });
|
||||
await until(() => items().some((i) => i.kind === 'media'));
|
||||
await idle();
|
||||
view.say({ type: 'openMedia', key: items().find((i) => i.kind === 'media').key });
|
||||
await until(() => s.external.length === 1);
|
||||
assert.equal(s.external[0], 'file://' + pdf);
|
||||
});
|
||||
|
||||
test('a text the agent shows that is no file here opens as a read-only document, not as one that wants saving', async (t) => {
|
||||
const { view, items, idle, s } = host(t);
|
||||
const elsewhere = path.join(tempDir(t), 'page.html');
|
||||
fs.writeFileSync(elsewhere, '<script>alert(1)</script>\n');
|
||||
view.say({ type: 'send', text: `SHOWTEXT ${elsewhere}` });
|
||||
await until(() => items().some((i) => i.kind === 'note'));
|
||||
await idle();
|
||||
const [, doc] = s.executed.find((e) => e[0] === 'showTextDocument');
|
||||
assert.equal(doc.uri.scheme, 'llembas-diff', "the extension's own read-only documents");
|
||||
assert.ok(doc.uri.path.endsWith('/page.html'));
|
||||
assert.equal(doc.text, '<script>alert(1)</script>\n');
|
||||
assert.equal(doc.isDirty, false);
|
||||
view.say({ type: 'new' });
|
||||
await until(() => items().length === 0);
|
||||
assert.equal(s.contentProviders.get('llembas-diff').provideTextDocumentContent(doc.uri), '', 'let go with the transcript');
|
||||
});
|
||||
|
||||
test("the agent's write: put into the open document and saved before the answer; a file not open is left to the agent", async (t) => {
|
||||
const { vscode, view, items, idle, sent, dir, s } = host(t);
|
||||
const open = path.join(dir, 'open.txt');
|
||||
const closed = path.join(dir, 'closed.txt');
|
||||
const other = path.join(dir, 'other.txt');
|
||||
fs.writeFileSync(open, 'on disk\n');
|
||||
fs.writeFileSync(other, 'untouched\n');
|
||||
const editor = vscode.__.open(open, 'typed and not saved\n');
|
||||
const bystander = vscode.__.open(other, 'unsaved here too\n');
|
||||
view.say({ type: 'send', text: `PUT ${open}` });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
assert.deepEqual(sent().find((m) => m.method === 'initialize').params.clientCapabilities.fs, { readTextFile: true, writeTextFile: true });
|
||||
assert.match(flat(items().find((i) => i.kind === 'agent').ast), /put=client/);
|
||||
assert.equal(editor.document.text, 'put by the agent\n', 'in the document');
|
||||
assert.equal(fs.readFileSync(open, 'utf8'), 'put by the agent\n', 'and on disk');
|
||||
assert.equal(editor.document.isDirty, false);
|
||||
assert.equal(editor.document.saves, 1);
|
||||
assert.equal(bystander.document.text, 'unsaved here too\n', 'no other document is touched');
|
||||
assert.equal(bystander.document.saves, 0);
|
||||
assert.equal(fs.readFileSync(other, 'utf8'), 'untouched\n');
|
||||
|
||||
view.say({ type: 'send', text: `PUT ${closed}` });
|
||||
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
|
||||
await idle();
|
||||
assert.match(flat(items().filter((i) => i.kind === 'agent')[1].ast), /put=disk/);
|
||||
assert.ok(!vscode.workspace.textDocuments.some((d) => d.uri.fsPath === closed), 'nothing was opened for it');
|
||||
});
|
||||
|
||||
test('the agent\'s write keeps a document\'s own line breaks, and saves a document that already has the text', async (t) => {
|
||||
const { vscode, view, items, idle, dir } = host(t);
|
||||
const file = path.join(dir, 'crlf.txt');
|
||||
fs.writeFileSync(file, 'old\r\n');
|
||||
const editor = vscode.__.open(file, 'old\r\n');
|
||||
editor.document.eol = 2;
|
||||
view.say({ type: 'send', text: `PUT ${file}` });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), 'put by the agent\r\n');
|
||||
// Typed to exactly the wanted text, not saved: no edit is needed, the save still is.
|
||||
fs.writeFileSync(file, 'stale on disk\r\n');
|
||||
editor.document.isDirty = true;
|
||||
const version = editor.document.version;
|
||||
view.say({ type: 'send', text: `PUT ${file}` });
|
||||
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
|
||||
await idle();
|
||||
assert.equal(editor.document.version, version);
|
||||
assert.equal(fs.readFileSync(file, 'utf8'), 'put by the agent\r\n');
|
||||
});
|
||||
|
||||
test('two rewrites of one file do not overwrite each other; another file is not held up', async (t) => {
|
||||
const { vscode, run, sent, dir, s } = host(t);
|
||||
const a = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo', new vscode.Selection(0, 0, 1, 3));
|
||||
s.inputs.push('SLOWE shout', 'shout again', 'shout');
|
||||
const first = run('llembas.rewrite');
|
||||
await until(() => sent().some((m) => m.method === '_lembas/edit'));
|
||||
await run('llembas.rewrite'); // the same file, while the first is being written
|
||||
assert.match(s.messages.pop().text, /a rewrite of this file is still being written/);
|
||||
assert.equal(s.inputs.length, 2, 'refused before anything was asked');
|
||||
assert.equal(sent().filter((m) => m.method === '_lembas/edit').length, 1);
|
||||
s.inputs.shift();
|
||||
// Another file meanwhile: proposed and accepted while the first still waits.
|
||||
const b = vscode.__.open(path.join(dir, 'b.txt'), 'three', new vscode.Selection(0, 0, 0, 5));
|
||||
await run('llembas.rewrite');
|
||||
assert.equal(s.lensProviders[0].provideCodeLenses(b.document).filter((l) => l.command.title === 'Accept').length, 1);
|
||||
// The other file's change is accepted while the first rewrite is still out.
|
||||
s.cancelProgress = undefined;
|
||||
vscode.window.activeTextEditor = b;
|
||||
await run('llembas.acceptAllChanges');
|
||||
assert.equal(b.document.text, 'THREE');
|
||||
assert.equal(a.document.text, 'one\ntwo');
|
||||
sent(); // (the slow one is still out)
|
||||
vscode.__.commands.get('llembas.restart')();
|
||||
await first;
|
||||
assert.deepEqual(s.lensProviders[0].provideCodeLenses(a.document), []);
|
||||
});
|
||||
|
||||
test('typing in one file while a change is applied to another is still seen (no one flag for all documents)', async (t) => {
|
||||
const { vscode, run, dir, s } = host(t);
|
||||
const a = vscode.__.open(path.join(dir, 'a.txt'), 'one\ntwo\nthree', new vscode.Selection(0, 0, 2, 5));
|
||||
s.inputs.push('REPLACE ONE\\ntwo\\nTHREE');
|
||||
await run('llembas.rewrite');
|
||||
const b = vscode.__.open(path.join(dir, 'b.txt'), 'four', new vscode.Selection(0, 0, 0, 4));
|
||||
s.inputs.push('shout');
|
||||
await run('llembas.rewrite');
|
||||
const lines = () => s.lensProviders[0].provideCodeLenses(a.document).filter((l) => l.command.title === 'Accept').map((l) => l.range.start.line);
|
||||
assert.deepEqual(lines(), [0, 2]);
|
||||
// While the editor applies b's change, a line is typed at the top of a.
|
||||
const apply = vscode.workspace.applyEdit;
|
||||
vscode.workspace.applyEdit = async (edit) => {
|
||||
a.document.text = 'typed\n' + a.document.text;
|
||||
s.changed.fire({ document: a.document, contentChanges: [{ range: new vscode.Range(0, 0, 0, 0), text: 'typed\n' }] });
|
||||
return apply(edit);
|
||||
};
|
||||
await run('llembas.acceptAllChanges'); // b is in front
|
||||
vscode.workspace.applyEdit = apply;
|
||||
assert.equal(b.document.text, 'FOUR');
|
||||
assert.deepEqual(lines(), [3], "a's remaining change moved down with its line; the one on the line typed into was dropped");
|
||||
vscode.window.activeTextEditor = a;
|
||||
await run('llembas.acceptAllChanges');
|
||||
assert.equal(a.document.text, 'typed\none\ntwo\nTHREE');
|
||||
});
|
||||
|
||||
test('Stop the Agent lets go of the session at once', async (t) => {
|
||||
const { view, items, idle, run, sent, state } = host(t);
|
||||
view.say({ type: 'send', text: 'hello' });
|
||||
await until(() => items().some((i) => i.kind === 'agent'));
|
||||
await idle();
|
||||
assert.equal(state().session, true);
|
||||
await run('llembas.restart');
|
||||
await until(() => state().session === false);
|
||||
view.say({ type: 'send', text: 'hello again' });
|
||||
await until(() => items().filter((i) => i.kind === 'agent').length === 2);
|
||||
await idle();
|
||||
assert.ok(!items().some((i) => i.kind === 'note' && /failed/.test(i.text)));
|
||||
assert.ok(sent().filter((m) => m.method === 'session/new').length >= 1);
|
||||
});
|
||||
|
||||
test('media over the limit is refused in words', async (t) => {
|
||||
const { view, items, idle, dir, s } = host(t);
|
||||
s.config['llembas.media.maxMegabytes'] = 1;
|
||||
const big = path.join(dir, 'big.bin');
|
||||
fs.writeFileSync(big, Buffer.alloc(1024 * 1024 + 10));
|
||||
view.say({ type: 'send', text: `SHOW ${big}` });
|
||||
await until(() => items().some((i) => i.kind === 'note'));
|
||||
await idle();
|
||||
assert.equal(items().find((i) => i.kind === 'note').text, 'big.bin was not shown: The file is 1.0 MB; this editor takes files of up to 1 MB.');
|
||||
});
|
||||
|
||||
test('a command that is not installed is said in the chat, and autocomplete stays quiet about it', async (t) => {
|
||||
const { vscode, view, items, dir, s } = host(t);
|
||||
s.config['llembas.command'] = path.join(dir, 'no-such-lembas');
|
||||
s.config['llembas.complete.debounce'] = 5;
|
||||
const editor = vscode.__.open(path.join(dir, 'a.py'), 'x = ', new vscode.Selection(0, 4, 0, 4));
|
||||
const got = await s.inlineProviders[0].provideInlineCompletionItems(editor.document, new vscode.Position(0, 4), { triggerKind: 1 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
|
||||
assert.equal(got, undefined);
|
||||
assert.equal(s.messages.length, 0);
|
||||
assert.equal(items().length, 0);
|
||||
view.say({ type: 'send', text: 'hello' });
|
||||
await until(() => items().some((i) => i.kind === 'note'));
|
||||
assert.match(items().find((i) => i.kind === 'note').text, /^Could not start .*no-such-lembas: the command was not found\.$/);
|
||||
});
|
||||
Executable
+355
@@ -0,0 +1,355 @@
|
||||
#!/usr/bin/env python3
|
||||
"""A stand-in for `lembas serve --stdio`, for the extension's tests: ACP version 1 over lines,
|
||||
with the editor's methods of harness spec 3.11.0 (`_lembas/complete`, `_lembas/edit`,
|
||||
`_lembas/models`, `_lembas/editor/settings`, `_lembas/show` with `_lembas/show/read`).
|
||||
|
||||
It started as a copy of the Neovim plugin's stand-in and is kept separately on purpose.
|
||||
|
||||
A turn is steered by words in the prompt's last text block:
|
||||
PERM asks for an approval
|
||||
DIFFPERM <path> asks for an approval that carries a diff, and writes the file when allowed
|
||||
WRITE <path> rewrites that file
|
||||
READ <path> asks the client for the file's text and says it back
|
||||
PUT <path> asks the client to make "put by the agent" + a line break the file's text; writes
|
||||
the disk itself when the client answers with an error, as the CLI does
|
||||
SHOW <path> shows that file through a handle
|
||||
SHOWTEXT <path> shows that file as text
|
||||
META says back the editor context the prompt carried
|
||||
SETTLE asks for an approval and then withdraws it
|
||||
SLOW waits to be cancelled
|
||||
CRASH exits
|
||||
A completion is steered by words in its prefix (SLOWC waits to be cancelled, FAILC fails), a
|
||||
rewrite by words in its instruction (SLOWE waits to be cancelled).
|
||||
|
||||
Environment: FAKE_AGENT_LOG (every message received is appended, one JSON object a line),
|
||||
FAKE_AGENT_AUTOCOMPLETE (the saved autocomplete model; "none": nobody has chosen one),
|
||||
FAKE_AGENT_PLAIN=1 (an agent from before the editor's methods: no capabilities, no methods).
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
LOG = os.environ.get("FAKE_AGENT_LOG")
|
||||
PLAIN = os.environ.get("FAKE_AGENT_PLAIN") == "1"
|
||||
lock = threading.Lock()
|
||||
waiting = {}
|
||||
cancelled = threading.Event()
|
||||
next_id = [1000]
|
||||
|
||||
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"]},
|
||||
]
|
||||
saved = os.environ.get("FAKE_AGENT_AUTOCOMPLETE", "example/model-a")
|
||||
settings = {"autocomplete_model": None if saved == "none" else saved, "main_model": None}
|
||||
session_model = ["example/model-a"]
|
||||
|
||||
completions = {} # the client's id -> Event set when it is cancelled
|
||||
complete_lock = threading.Lock()
|
||||
running_completion = [None] # (client id, Event)
|
||||
edits = {}
|
||||
handles = {} # handle -> bytes
|
||||
|
||||
|
||||
def out(msg):
|
||||
with lock:
|
||||
sys.stdout.write(json.dumps(msg) + "\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
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 update(session, body):
|
||||
out({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": session, "update": body}})
|
||||
|
||||
|
||||
def say(session, text):
|
||||
update(session, {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}})
|
||||
|
||||
|
||||
def ask(method, params, wait=10):
|
||||
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(wait)
|
||||
return waiting.pop(rid)[1]
|
||||
|
||||
|
||||
def read(path, mode="r"):
|
||||
with open(path, mode) as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def word_after(text, word):
|
||||
return text.split(word + " ", 1)[1].split()[0]
|
||||
|
||||
|
||||
def editor_settings():
|
||||
return {"autocomplete": {"model": settings["autocomplete_model"],
|
||||
"source": "person" if settings["autocomplete_model"] else None,
|
||||
"allowed": ["example/model-a", "example/model-b"]},
|
||||
"main": {"model": settings["main_model"]}}
|
||||
|
||||
|
||||
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"}})
|
||||
say(session, "Hello ")
|
||||
say(session, "there.\nSecond line")
|
||||
options = [{"optionId": "once", "name": "Allow once", "kind": "allow_once"},
|
||||
{"optionId": "deny", "name": "Deny", "kind": "reject_once"}]
|
||||
if "META" in text:
|
||||
say(session, "\neditor=" + json.dumps(((p.get("_meta") or {}).get("lembas") or {}).get("editor"), sort_keys=True))
|
||||
if "DIFFPERM " in text:
|
||||
path = word_after(text, "DIFFPERM")
|
||||
old = read(path) if os.path.exists(path) else None
|
||||
new = "rewritten by the agent\n"
|
||||
diff = [{"type": "diff", "path": path, "oldText": old, "newText": new}]
|
||||
answer = ask("session/request_permission", {
|
||||
"sessionId": session,
|
||||
"toolCall": {"toolCallId": "edit-" + str(msg["id"]), "title": "edit " + os.path.basename(path), "kind": "edit",
|
||||
"status": "pending", "rawInput": {}, "content": diff},
|
||||
"options": options,
|
||||
"_meta": {"lembas": {"tool": "edit", "reason": "manual mode asks about every edit"}}})
|
||||
got = (answer or {}).get("outcome", {})
|
||||
if got.get("optionId") == "once":
|
||||
update(session, {"sessionUpdate": "tool_call", "toolCallId": "d1", "title": "edit " + os.path.basename(path),
|
||||
"kind": "edit", "status": "in_progress"})
|
||||
with open(path, "w") as f:
|
||||
f.write(new)
|
||||
update(session, {"sessionUpdate": "tool_call_update", "toolCallId": "d1", "status": "completed",
|
||||
"content": [{"type": "content", "content": {"type": "text", "text": "done"}}] + diff})
|
||||
say(session, "\nanswer=" + str(got.get("optionId") or got.get("outcome")))
|
||||
elif "SETTLE" in text:
|
||||
call = "settle-" + str(msg["id"])
|
||||
|
||||
def withdraw():
|
||||
out({"jsonrpc": "2.0", "method": "_lembas/permission/settled", "params": {"sessionId": session, "toolCallId": call}})
|
||||
threading.Timer(0.2, withdraw).start()
|
||||
answer = ask("session/request_permission", {
|
||||
"sessionId": session,
|
||||
"toolCall": {"toolCallId": call, "title": "make build", "kind": "execute", "status": "pending", "rawInput": {}},
|
||||
"options": options, "_meta": {"lembas": {"tool": "bash"}}})
|
||||
got = (answer or {}).get("outcome", {})
|
||||
say(session, "\nanswer=" + str(got.get("optionId") or got.get("outcome")))
|
||||
elif "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": options,
|
||||
"_meta": {"lembas": {"tool": "bash", "reason": "deletes files"}}})
|
||||
got = (answer or {}).get("outcome", {})
|
||||
say(session, "\nanswer=" + str(got.get("optionId") or got.get("outcome")))
|
||||
if "WRITE " in text:
|
||||
path = word_after(text, "WRITE")
|
||||
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 "READ " in text:
|
||||
path = word_after(text, "READ")
|
||||
answer = ask("fs/read_text_file", {"sessionId": session, "path": path})
|
||||
say(session, "\nread=" + json.dumps((answer or {}).get("content")))
|
||||
if "PUT " in text:
|
||||
path = word_after(text, "PUT")
|
||||
with lock:
|
||||
next_id[0] += 1
|
||||
rid = next_id[0]
|
||||
done = threading.Event()
|
||||
waiting[rid] = [done, None]
|
||||
out({"jsonrpc": "2.0", "id": rid, "method": "fs/write_text_file",
|
||||
"params": {"sessionId": session, "path": path, "content": "put by the agent\n"}})
|
||||
done.wait(10)
|
||||
answer = waiting.pop(rid)[1]
|
||||
if answer is None:
|
||||
with open(path, "w") as f:
|
||||
f.write("put by the agent\n")
|
||||
say(session, "\nput=" + ("client" if answer is not None else "disk"))
|
||||
if "SHOWTEXT " in text:
|
||||
path = word_after(text, "SHOWTEXT")
|
||||
answer = ask("_lembas/show", {"sessionId": session, "toolCallId": "show-t", "path": os.path.basename(path),
|
||||
"kind": "text", "text": read(path)})
|
||||
say(session, "\nshown=" + json.dumps(answer, sort_keys=True))
|
||||
elif "SHOW " in text:
|
||||
path = word_after(text, "SHOW")
|
||||
data = read(path, "rb")
|
||||
handle = "h_" + str(msg["id"])
|
||||
handles[handle] = data
|
||||
params = {"sessionId": session, "toolCallId": "show-" + str(msg["id"]), "path": os.path.basename(path),
|
||||
"kind": "binary", "mimeType": "application/octet-stream", "size": len(data),
|
||||
"hash": "sha256:" + hashlib.sha256(data).hexdigest(), "handle": handle}
|
||||
if "WITHURI" in text:
|
||||
params["uri"] = "file://" + os.path.abspath(path)
|
||||
if "BADHASH" in text:
|
||||
params["hash"] = "sha256:" + "0" * 64
|
||||
answer = ask("_lembas/show", params, 30)
|
||||
handles.pop(handle, None)
|
||||
say(session, "\nshown=" + 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.replace("SLOWC", "").replace("SLOWE", ""):
|
||||
stop = "cancelled" if cancelled.wait(10) else "end_turn"
|
||||
cancelled.clear()
|
||||
result(msg, {"stopReason": stop})
|
||||
|
||||
|
||||
def complete(msg):
|
||||
p = msg["params"]
|
||||
cid = p.get("id")
|
||||
mine = threading.Event()
|
||||
with complete_lock:
|
||||
before = running_completion[0]
|
||||
running_completion[0] = (cid, mine)
|
||||
if cid:
|
||||
completions[cid] = mine
|
||||
if before:
|
||||
before[1].set() # a newer request cancels the older
|
||||
try:
|
||||
model = p.get("model") or settings["autocomplete_model"]
|
||||
if not model:
|
||||
return refuse(msg, -32602, "No autocomplete model is chosen. Choose one in your settings on the server.", "no_model")
|
||||
if model == "example/model-c":
|
||||
return refuse(msg, -32602, "Model C is not allowed for autocomplete.", "not_allowed")
|
||||
prefix = p.get("prefix", "")
|
||||
if "FAILC" in prefix:
|
||||
return refuse(msg, -32603, "The server did not answer.")
|
||||
if "SLOWC" in prefix:
|
||||
mine.wait(10)
|
||||
elif mine.wait(0.05):
|
||||
pass
|
||||
if mine.is_set():
|
||||
return result(msg, {"text": "", "cancelled": True})
|
||||
last = prefix.split()[-1] if prefix.split() else ""
|
||||
result(msg, {"text": "<" + last + "|" + model + ">", "model": model, "finish": "stop"})
|
||||
finally:
|
||||
with complete_lock:
|
||||
if running_completion[0] and running_completion[0][1] is mine:
|
||||
running_completion[0] = None
|
||||
if cid:
|
||||
completions.pop(cid, None)
|
||||
|
||||
|
||||
def edit(msg):
|
||||
p = msg["params"]
|
||||
eid = p.get("id")
|
||||
mine = threading.Event()
|
||||
if eid:
|
||||
edits[eid] = mine
|
||||
try:
|
||||
if not p.get("text") or not p.get("instruction"):
|
||||
return refuse(msg, -32602, "text and instruction are needed")
|
||||
if "SLOWE" in p["instruction"]:
|
||||
mine.wait(10)
|
||||
if mine.is_set():
|
||||
return result(msg, {"text": "", "cancelled": True})
|
||||
if p["instruction"].startswith("REPLACE "):
|
||||
new = p["instruction"][len("REPLACE "):].replace("\\n", "\n")
|
||||
else:
|
||||
new = p["text"].upper()
|
||||
if eid:
|
||||
half = len(new) // 2
|
||||
for piece in (new[:half], new[half:]):
|
||||
out({"jsonrpc": "2.0", "method": "_lembas/edit/delta", "params": {"id": eid, "delta": piece}})
|
||||
result(msg, {"text": new, "model": p.get("model") or session_model[0]})
|
||||
finally:
|
||||
if eid:
|
||||
edits.pop(eid, None)
|
||||
|
||||
|
||||
def show_read(msg):
|
||||
p = msg["params"]
|
||||
data = handles.get(p.get("handle"))
|
||||
if data is None:
|
||||
return refuse(msg, -32602, "This file is no longer offered.")
|
||||
offset = int(p.get("offset") or 0)
|
||||
length = min(int(p.get("length") or 1000), 1000) # small parts, so a client has to loop
|
||||
part = data[offset:offset + length]
|
||||
result(msg, {"data": base64.b64encode(part).decode(), "offset": offset, "eof": offset + len(part) >= len(data)})
|
||||
|
||||
|
||||
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:
|
||||
entry[1] = msg.get("result")
|
||||
entry[0].set()
|
||||
elif method == "initialize":
|
||||
meta = {} if PLAIN else {"lembas": {"protocol": 3, "harness_spec": "3.11.0", "limits": None, "connection": "example",
|
||||
"capabilities": ["configure", "show", "editor", "media"]}}
|
||||
result(msg, {"protocolVersion": 1, "agentCapabilities": {}, "agentInfo": {"name": "stand-in", "version": "0"}, "_meta": meta})
|
||||
elif method == "session/new":
|
||||
wanted = (msg["params"].get("_meta") or {}).get("model")
|
||||
if wanted:
|
||||
session_model[0] = wanted
|
||||
result(msg, {
|
||||
"sessionId": "ses_test",
|
||||
"modes": {"currentModeId": "ask", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]},
|
||||
"_meta": {"lembas": {"model": session_model[0], "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":
|
||||
result(msg, {})
|
||||
update(msg["params"]["sessionId"], {"sessionUpdate": "current_mode_update", "currentModeId": msg["params"]["modeId"]})
|
||||
elif method == "_lembas/configure":
|
||||
session_model[0] = msg["params"].get("model") or session_model[0]
|
||||
result(msg, {"model": session_model[0], "effort": "default"})
|
||||
elif PLAIN and "id" in msg:
|
||||
refuse(msg, -32601, "Method not found")
|
||||
elif method == "_lembas/models":
|
||||
result(msg, {"models": MODELS, **editor_settings()})
|
||||
elif method == "_lembas/editor/settings":
|
||||
for key, value in (msg["params"].get("set") or {}).items():
|
||||
if key in settings:
|
||||
settings[key] = value
|
||||
result(msg, editor_settings())
|
||||
elif method == "_lembas/complete":
|
||||
threading.Thread(target=complete, args=(msg,), daemon=True).start()
|
||||
elif method == "_lembas/complete/cancel":
|
||||
event = completions.get(msg["params"].get("id"))
|
||||
if event:
|
||||
event.set()
|
||||
elif method == "_lembas/edit":
|
||||
threading.Thread(target=edit, args=(msg,), daemon=True).start()
|
||||
elif method == "_lembas/edit/cancel":
|
||||
event = edits.get(msg["params"].get("id"))
|
||||
if event:
|
||||
event.set()
|
||||
elif method == "_lembas/show/read":
|
||||
show_read(msg)
|
||||
elif "id" in msg:
|
||||
refuse(msg, -32601, "Method not found")
|
||||
|
||||
|
||||
main()
|
||||
@@ -0,0 +1,76 @@
|
||||
'use strict';
|
||||
// Shared by the tests: the stand-in agent, a place for files, and reading what the agent was sent.
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { Agent } = require('../src/agent');
|
||||
const { Chat } = require('../src/chat');
|
||||
|
||||
const FAKE = path.join(__dirname, 'fake_agent.py');
|
||||
|
||||
function tempDir(t) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'llembas-vscode-test-'));
|
||||
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** An Agent on the stand-in. `env` adds to the environment; the log of what it received is `agent.log()`. */
|
||||
function fakeAgent(t, dir, env, more) {
|
||||
const logFile = path.join(dir, `agent-${Math.random().toString(36).slice(2)}.log`);
|
||||
const agent = new Agent({
|
||||
command: 'python3',
|
||||
args: [FAKE],
|
||||
cwd: dir,
|
||||
env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1', FAKE_AGENT_LOG: logFile, ...(env || {}) },
|
||||
clientInfo: { name: 'test', version: '0' },
|
||||
...(more || {}),
|
||||
});
|
||||
agent.log = () => (fs.existsSync(logFile) ? fs.readFileSync(logFile, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []);
|
||||
t.after(() => agent.stop());
|
||||
return agent;
|
||||
}
|
||||
|
||||
/** A Chat on the stand-in. Returns `{ chat, agents, dir }`; `agents` fills as the chat starts them. */
|
||||
function fakeChat(t, options) {
|
||||
const o = options || {};
|
||||
const dir = o.dir || tempDir(t);
|
||||
const agents = [];
|
||||
const chat = new Chat({
|
||||
makeAgent: (m) => {
|
||||
const a = fakeAgent(t, dir, o.env, { cwd: m.cwd, onRequest: m.onRequest, ...(o.agent || {}) });
|
||||
agents.push(a);
|
||||
return a;
|
||||
},
|
||||
cwd: () => dir,
|
||||
options: () => o.options || {},
|
||||
hooks: o.hooks || {},
|
||||
});
|
||||
t.after(() => chat.dispose());
|
||||
return { chat, agents, dir };
|
||||
}
|
||||
|
||||
/** Wait until `test()` is true (checked every few milliseconds). */
|
||||
async function until(test, ms) {
|
||||
const end = Date.now() + (ms || 8000);
|
||||
for (;;) {
|
||||
if (test()) return true;
|
||||
if (Date.now() > end) throw new Error('waited too long for: ' + test);
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
}
|
||||
|
||||
const text = (chat) =>
|
||||
chat.items
|
||||
.map((i) => {
|
||||
if (i.kind === 'user') return `You: ${i.label ? '[' + i.label + '] ' : ''}${i.text}`;
|
||||
if (i.kind === 'agent') return `LLeMbas: ${i.text}`;
|
||||
if (i.kind === 'thought') return `Thinking: ${i.text}`;
|
||||
if (i.kind === 'note') return `> ${i.text}`;
|
||||
if (i.kind === 'tool') return `tool ${i.status}: ${i.title}`;
|
||||
if (i.kind === 'card') return `card ${i.state}: ${i.title} (${i.answer})`;
|
||||
if (i.kind === 'media') return `media: ${i.name}`;
|
||||
return i.kind;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
module.exports = { FAKE, tempDir, fakeAgent, fakeChat, until, text };
|
||||
@@ -0,0 +1,179 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const h = require('../src/hunks');
|
||||
|
||||
/** Apply an edit of `editFor` to a list of lines, as an editor would to its text. */
|
||||
function applyEdit(lines, e) {
|
||||
const text = lines.join('\n');
|
||||
const starts = [0];
|
||||
for (let i = 0; i < text.length; i++) if (text[i] === '\n') starts.push(i + 1);
|
||||
const offset = (p) => (p.end ? (p.line + 1 < starts.length ? starts[p.line + 1] - 1 : text.length) : starts[p.line]);
|
||||
return (text.slice(0, offset(e.start)) + e.text + text.slice(offset(e.stop))).split('\n');
|
||||
}
|
||||
|
||||
const apply = (a, hunks) => {
|
||||
const out = a.slice();
|
||||
for (const k of hunks.slice().reverse()) out.splice(k.aStart, k.aCount, ...k.b);
|
||||
return out;
|
||||
};
|
||||
|
||||
test('the differences between two lists of lines', () => {
|
||||
const a = ['one', 'two', 'three', 'four', 'five'];
|
||||
assert.deepEqual(h.diffLines(a, a), []);
|
||||
assert.deepEqual(h.diffLines(a, ['one', 'TWO', 'three', 'four', 'five']), [{ aStart: 1, aCount: 1, bStart: 1, bCount: 1 }]);
|
||||
assert.deepEqual(h.diffLines(a, ['one', 'three', 'four', 'five']), [{ aStart: 1, aCount: 1, bStart: 1, bCount: 0 }]);
|
||||
assert.deepEqual(h.diffLines(a, ['zero', 'one', 'two', 'three', 'four', 'five']), [{ aStart: 0, aCount: 0, bStart: 0, bCount: 1 }]);
|
||||
assert.deepEqual(h.diffLines(a, [...a, 'six', 'seven']), [{ aStart: 5, aCount: 0, bStart: 5, bCount: 2 }]);
|
||||
assert.deepEqual(h.diffLines(a, ['ONE', 'two', 'three', 'four', 'FIVE']), [
|
||||
{ aStart: 0, aCount: 1, bStart: 0, bCount: 1 },
|
||||
{ aStart: 4, aCount: 1, bStart: 4, bCount: 1 },
|
||||
]);
|
||||
assert.deepEqual(h.diffLines([], ['a']), [{ aStart: 0, aCount: 0, bStart: 0, bCount: 1 }]);
|
||||
assert.deepEqual(h.diffLines(['a'], []), [{ aStart: 0, aCount: 1, bStart: 0, bCount: 0 }]);
|
||||
});
|
||||
|
||||
test('whatever the two texts, the hunks turn the one into the other', () => {
|
||||
let seed = 7;
|
||||
const rnd = (n) => {
|
||||
seed = (seed * 1103515245 + 12345) & 0x7fffffff;
|
||||
return seed % n;
|
||||
};
|
||||
for (let round = 0; round < 300; round++) {
|
||||
const a = Array.from({ length: rnd(14) }, () => 'line ' + rnd(5));
|
||||
const b = a.slice();
|
||||
for (let edits = rnd(5); edits > 0; edits--) {
|
||||
const at = rnd(b.length + 1);
|
||||
if (rnd(2)) b.splice(at, rnd(3), 'new ' + rnd(4));
|
||||
else b.splice(at, rnd(3));
|
||||
}
|
||||
const hunks = h.diffLines(a, b);
|
||||
const withB = hunks.map((k) => ({ ...k, b: b.slice(k.bStart, k.bStart + k.bCount) }));
|
||||
assert.deepEqual(apply(a, withB), b, `round ${round}`);
|
||||
for (let i = 1; i < hunks.length; i++) {
|
||||
assert.ok(hunks[i].aStart > hunks[i - 1].aStart + hunks[i - 1].aCount, 'an unchanged line lies between two hunks');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('texts too different to compare come back as one hunk, still correct', () => {
|
||||
const a = Array.from({ length: 5000 }, (_, i) => 'a' + i);
|
||||
const b = Array.from({ length: 5000 }, (_, i) => 'b' + i);
|
||||
const hunks = h.diffLines(['same', ...a, 'end'], ['same', ...b, 'end']);
|
||||
assert.deepEqual(hunks, [{ aStart: 1, aCount: 5000, bStart: 1, bCount: 5000 }]);
|
||||
});
|
||||
|
||||
const DOC = ['# bread', 'def a():', ' return 1', '', 'def b():', ' return 2', 'print(a())'];
|
||||
|
||||
test('a rewrite of lines 2-6 becomes hunks at the document\'s own lines', () => {
|
||||
const old = DOC.slice(1, 6);
|
||||
const fresh = ['def a():', ' return 10', '', 'def b():', ' """Two."""', ' return 2'];
|
||||
const hunks = h.propose(1, old, fresh);
|
||||
assert.deepEqual(hunks, [
|
||||
{ id: 1, line: 2, old: [' return 1'], new: [' return 10'] },
|
||||
{ id: 2, line: 5, old: [], new: [' """Two."""'] },
|
||||
]);
|
||||
assert.deepEqual(h.withAll(DOC, hunks), ['# bread', ...fresh, 'print(a())']);
|
||||
});
|
||||
|
||||
const OLD = ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9'];
|
||||
const FRESH = ['A1', 'a2', 'a3', 'a5', 'a6', 'new', 'a7', 'a8', 'A9', 'tail'];
|
||||
const AROUND = ['top', ...OLD, 'bottom'];
|
||||
|
||||
test('accepting hunks one by one, in any order, gives the rewrite; rejecting leaves the text', () => {
|
||||
const orders = [[0, 1, 2, 3], [3, 2, 1, 0], [1, 3, 0, 2], [2, 0, 3, 1]];
|
||||
for (const order of orders) {
|
||||
let lines = AROUND.slice();
|
||||
let hunks = h.propose(1, OLD, FRESH);
|
||||
assert.equal(hunks.length, 4); // a1 replaced, a4 taken away, "new" added, a9 replaced with two lines
|
||||
const ids = order.map((i) => hunks[i].id);
|
||||
for (const id of ids) {
|
||||
const hunk = hunks.find((k) => k.id === id);
|
||||
assert.ok(h.stillFits(hunk, (i) => lines[i], lines.length), `hunk ${id} fits in order ${order}`);
|
||||
lines = applyEdit(lines, h.editFor(hunk, lines.length));
|
||||
hunks = h.afterAccept(hunks, hunk);
|
||||
}
|
||||
assert.deepEqual(lines, ['top', ...FRESH, 'bottom'], `order ${order}`);
|
||||
assert.equal(hunks.length, 0);
|
||||
}
|
||||
// Accept only the second and the fourth: where the others were proposed, the old text stays.
|
||||
let lines = AROUND.slice();
|
||||
let hunks = h.propose(1, OLD, FRESH);
|
||||
for (const id of [2, 4]) {
|
||||
const hunk = hunks.find((k) => k.id === id);
|
||||
lines = applyEdit(lines, h.editFor(hunk, lines.length));
|
||||
hunks = h.afterAccept(hunks, hunk);
|
||||
}
|
||||
assert.deepEqual(lines, ['top', 'a1', 'a2', 'a3', 'a5', 'a6', 'a7', 'a8', 'A9', 'tail', 'bottom']);
|
||||
assert.deepEqual(hunks.map((k) => [k.id, k.line]), [[1, 1], [3, 6]]);
|
||||
});
|
||||
|
||||
test('the edit for each kind of hunk, at the edges of a document', () => {
|
||||
// Lines added after the last line.
|
||||
let lines = ['a', 'b'];
|
||||
lines = applyEdit(lines, h.editFor({ line: 2, old: [], new: ['c', 'd'] }, 2));
|
||||
assert.deepEqual(lines, ['a', 'b', 'c', 'd']);
|
||||
// Lines added in front of the first.
|
||||
assert.deepEqual(applyEdit(['a', 'b'], h.editFor({ line: 0, old: [], new: ['z'] }, 2)), ['z', 'a', 'b']);
|
||||
// The last line taken away: the line break before it goes too.
|
||||
assert.deepEqual(applyEdit(['a', 'b', 'c'], h.editFor({ line: 2, old: ['c'], new: [] }, 3)), ['a', 'b']);
|
||||
// A middle line taken away.
|
||||
assert.deepEqual(applyEdit(['a', 'b', 'c'], h.editFor({ line: 1, old: ['b'], new: [] }, 3)), ['a', 'c']);
|
||||
// Every line taken away leaves one empty line, which is what an empty document is.
|
||||
assert.deepEqual(applyEdit(['a', 'b'], h.editFor({ line: 0, old: ['a', 'b'], new: [] }, 2)), ['']);
|
||||
// Lines replaced by more lines.
|
||||
assert.deepEqual(applyEdit(['a', 'b', 'c'], h.editFor({ line: 1, old: ['b'], new: ['x', 'y'] }, 3)), ['a', 'x', 'y', 'c']);
|
||||
});
|
||||
|
||||
test('all hunks as one set of edits against the same text (accept all)', () => {
|
||||
const hunks = h.propose(1, OLD, FRESH);
|
||||
// An editor applies edits given against one state; from the bottom up is the same thing.
|
||||
let lines = AROUND.slice();
|
||||
for (const hunk of hunks.slice().sort((p, q) => q.line - p.line)) lines = applyEdit(lines, h.editFor(hunk, AROUND.length));
|
||||
assert.deepEqual(lines, ['top', ...FRESH, 'bottom']);
|
||||
});
|
||||
|
||||
test('a hunk whose text was changed by hand no longer fits', () => {
|
||||
const [hunk] = h.propose(1, [' return 1'], [' return 10']);
|
||||
const lines = ['x', ' return 1'];
|
||||
assert.ok(h.stillFits(hunk, (i) => lines[i], lines.length));
|
||||
lines[1] = ' return 1 # edited';
|
||||
assert.ok(!h.stillFits(hunk, (i) => lines[i], lines.length));
|
||||
assert.ok(!h.stillFits({ line: 5, old: ['a'], new: [] }, (i) => lines[i], lines.length), 'past the end');
|
||||
assert.ok(h.stillFits({ line: 2, old: [], new: ['z'] }, (i) => lines[i], lines.length), 'adding after the last line');
|
||||
assert.ok(!h.stillFits({ line: 3, old: [], new: ['z'] }, (i) => lines[i], lines.length));
|
||||
});
|
||||
|
||||
test('typing elsewhere moves the hunks below it; typing inside one drops it', () => {
|
||||
const hunks = [
|
||||
{ id: 1, line: 2, old: ['b', 'c'], new: ['B'] },
|
||||
{ id: 2, line: 8, old: [], new: ['added'] },
|
||||
{ id: 3, line: 10, old: ['k'], new: [] },
|
||||
];
|
||||
// A new line typed at the end of line 0.
|
||||
let out = h.afterChange(hunks, { startLine: 0, endLine: 0, newLineCount: 2 });
|
||||
assert.deepEqual(out.map((k) => k.line), [3, 9, 11]);
|
||||
// Two lines deleted between the first and the second hunk.
|
||||
out = h.afterChange(hunks, { startLine: 5, endLine: 7, newLineCount: 1 });
|
||||
assert.deepEqual(out.map((k) => [k.id, k.line]), [[1, 2], [2, 6], [3, 8]]);
|
||||
// A character typed inside the first hunk's lines.
|
||||
out = h.afterChange(hunks, { startLine: 3, endLine: 3, newLineCount: 1 });
|
||||
assert.deepEqual(out.map((k) => k.id), [2, 3]);
|
||||
// A change below everything.
|
||||
out = h.afterChange(hunks, { startLine: 20, endLine: 20, newLineCount: 3 });
|
||||
assert.deepEqual(out, hunks);
|
||||
// A deletion that swallows the place an addition was meant for.
|
||||
out = h.afterChange(hunks, { startLine: 7, endLine: 9, newLineCount: 1 });
|
||||
assert.deepEqual(out.map((k) => [k.id, k.line]), [[1, 2], [3, 8]]);
|
||||
});
|
||||
|
||||
test('the lines a selection covers', () => {
|
||||
assert.deepEqual(h.wholeLines({ startLine: 3, endLine: 5, endCharacter: 4 }), { first: 3, last: 5 });
|
||||
assert.deepEqual(h.wholeLines({ startLine: 3, endLine: 6, endCharacter: 0 }), { first: 3, last: 5 }, 'not the line it only ends in front of');
|
||||
assert.deepEqual(h.wholeLines({ startLine: 3, endLine: 3, endCharacter: 0 }), { first: 3, last: 3 });
|
||||
});
|
||||
|
||||
test('a text is split into lines whatever its line breaks', () => {
|
||||
assert.deepEqual(h.splitLines('a\r\nb\nc'), ['a', 'b', 'c']);
|
||||
assert.deepEqual(h.splitLines('a\n'), ['a', '']);
|
||||
});
|
||||
@@ -0,0 +1,303 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { parse, parseInline, safeHref, Growing, MAX_CHARS } = require('../src/markdown');
|
||||
const { chatHtml } = require('../src/webview');
|
||||
const page = require('../media/chat.js');
|
||||
|
||||
// A document that can only do what the chat page is allowed to do: make elements and text.
|
||||
// It has no way to parse markup, so a test that passes here cannot have used one.
|
||||
class Node {
|
||||
constructor(tag, text) {
|
||||
this.tag = tag;
|
||||
this.text = text;
|
||||
this.children = [];
|
||||
this.attrs = {};
|
||||
this.className = '';
|
||||
this.listeners = {};
|
||||
}
|
||||
appendChild(c) {
|
||||
this.children.push(c);
|
||||
return c;
|
||||
}
|
||||
setAttribute(k, v) {
|
||||
this.attrs[k] = String(v);
|
||||
}
|
||||
addEventListener(name, fn) {
|
||||
this.listeners[name] = fn;
|
||||
}
|
||||
set textContent(v) {
|
||||
this.children = [new Node('#text', String(v))];
|
||||
}
|
||||
get textContent() {
|
||||
return this.tag === '#text' ? this.text : this.children.map((c) => c.textContent).join('');
|
||||
}
|
||||
all(out) {
|
||||
const list = out || [];
|
||||
for (const c of this.children) {
|
||||
list.push(c);
|
||||
c.all(list);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
/** A picture of the tree, for comparing: text in quotes, elements as tag(children). */
|
||||
show() {
|
||||
if (this.tag === '#text') return JSON.stringify(this.text);
|
||||
return `${this.tag}(${this.children.map((c) => c.show()).join(' ')})`;
|
||||
}
|
||||
}
|
||||
const doc = { createElement: (tag) => new Node(tag), createTextNode: (text) => new Node('#text', text) };
|
||||
|
||||
function render(src) {
|
||||
const root = new Node('div');
|
||||
page.buildBlocks(doc, parse(src), root, 0);
|
||||
return root;
|
||||
}
|
||||
const ALLOWED = new Set(['#text', 'div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code', 'hr', 'blockquote', 'ul', 'ol', 'li', 'strong', 'em', 'span', 'br']);
|
||||
|
||||
test('paragraphs, emphasis, code and line breaks', () => {
|
||||
assert.equal(render('Hello **bold** and *it* and `x < y`.\nnext').show(), 'div(p("Hello " strong("bold") " and " em("it") " and " code("x < y") "." br() "next"))');
|
||||
assert.equal(render('one\n\ntwo').show(), 'div(p("one") p("two"))');
|
||||
assert.equal(render('snake_case_name and 2 * 3 * 4').show(), 'div(p("snake_case_name and 2 * 3 * 4"))');
|
||||
assert.equal(render('__bold__ _it_ **a *b* c**').show(), 'div(p(strong("bold") " " em("it") " " strong("a " em("b") " c")))');
|
||||
assert.equal(render('\\*not\\* \\`code\\`').show(), 'div(p("*not* `code`"))');
|
||||
});
|
||||
|
||||
test('headings, rules, quotes and lists', () => {
|
||||
assert.equal(render('# One\n## Two ##\n####### seven').show(), 'div(h1("One") h2("Two") p("####### seven"))');
|
||||
assert.equal(render('a\n\n---\n\nb').show(), 'div(p("a") hr() p("b"))');
|
||||
assert.equal(render('> quoted **text**\n> more\n\nafter').show(), 'div(blockquote(p("quoted " strong("text") br() "more")) p("after"))');
|
||||
const list = render('- one\n- two\n - inner\n still inner\n- three\n\n1. first\n2) second');
|
||||
assert.equal(list.show(), 'div(ul(li("one") li("two") li("inner" br() "still inner") li("three")) ol(li("first") li("second")))');
|
||||
assert.equal(list.children[0].children[2].className, 'depth-1');
|
||||
});
|
||||
|
||||
test('a fenced block is text as written, and one still being written is a block already', () => {
|
||||
assert.equal(render('```python\nprint("<b>hi</b>")\n**not bold**\n```\nafter').show(), 'div(pre(code("print(\\"<b>hi</b>\\")\\n**not bold**")) p("after"))');
|
||||
assert.equal(render('text\n```js\nconst a = 1;').show(), 'div(p("text") pre(code("const a = 1;")))');
|
||||
assert.equal(parse('```js title="<x>"\n1\n```')[0].lang, 'js');
|
||||
assert.equal(render('~~~\na\n~~~').show(), 'div(pre(code("a")))');
|
||||
});
|
||||
|
||||
test('a table is kept as written, in a block that scrolls on its own', () => {
|
||||
assert.equal(render('| a | b |\n|---|---|\n| 1 | 2 |').show(), 'div(pre(code("| a | b |\\n|---|---|\\n| 1 | 2 |")))');
|
||||
});
|
||||
|
||||
test('markup a model writes is text, never elements', () => {
|
||||
const hostile = [
|
||||
'<script>alert(1)</script>',
|
||||
'<img src=x onerror=alert(1)>',
|
||||
'Click <a href="javascript:alert(1)">here</a>',
|
||||
'**<iframe src="https://example.org"></iframe>**',
|
||||
'# <style>body{display:none}</style>',
|
||||
'- <svg onload=alert(1)>',
|
||||
'> </div><script src="https://example.org/x.js"></script>',
|
||||
'```\n</code></pre><script>alert(1)</script>\n```',
|
||||
'`</code><script>alert(1)</script>`',
|
||||
'<script> <b>',
|
||||
].join('\n\n');
|
||||
const root = render(hostile);
|
||||
const nodes = root.all();
|
||||
for (const n of nodes) assert.ok(ALLOWED.has(n.tag), `unexpected element: ${n.tag}`);
|
||||
for (const n of nodes) for (const k of Object.keys(n.attrs)) assert.ok(['role', 'tabindex', 'title', 'data-href'].includes(k), `unexpected attribute: ${k}`);
|
||||
// Every character the model wrote is still there, as text.
|
||||
const text = root.textContent;
|
||||
for (const piece of ['<script>alert(1)</script>', '<img src=x onerror=alert(1)>', 'javascript:alert(1)', '<iframe src="', '<svg onload=alert(1)>', '<script> <b>']) {
|
||||
assert.ok(text.includes(piece), `kept as text: ${piece}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('only http, https and mailto become links, and a link never navigates by itself', () => {
|
||||
const root = render(
|
||||
'[site](https://example.org/a?b=c) [mail](mailto:person@example.org) [bad](javascript:alert(1)) [data](data:text/html,<b>) [file](file:///etc/passwd) [vs](vscode://x) [cmd](command:workbench.action.terminal.new) bare https://example.org/path. and ',
|
||||
);
|
||||
const links = root.all().filter((n) => n.attrs['data-href']);
|
||||
assert.deepEqual(links.map((n) => n.attrs['data-href']), ['https://example.org/a?b=c', 'mailto:person@example.org', 'https://example.org/path', 'https://example.org/p.png']);
|
||||
for (const n of links) {
|
||||
assert.equal(n.tag, 'span', 'not an anchor: the extension is asked to open it');
|
||||
assert.equal(n.attrs.href, undefined);
|
||||
assert.equal(n.attrs.title, n.attrs['data-href'], 'the address is shown before it is opened');
|
||||
}
|
||||
assert.ok(!root.all().some((n) => n.tag === 'img' || n.tag === 'a'), 'a picture in a reply is a link, never loaded');
|
||||
const text = root.textContent;
|
||||
assert.ok(text.includes('[bad](javascript:alert(1))') && text.includes('[cmd](command:workbench.action.terminal.new)'));
|
||||
});
|
||||
|
||||
test('what counts as a safe address', () => {
|
||||
for (const ok of ['https://example.org', 'http://192.0.2.7:8080/x?y#z', 'HTTPS://EXAMPLE.ORG/', 'mailto:a@example.org']) assert.equal(safeHref(ok), ok);
|
||||
for (const bad of ['javascript:alert(1)', ' https://example.org', 'https://exa mple.org', 'https://example.org/"onmouseover="x', 'data:text/html,x', 'file:///etc/passwd', 'command:x', 'vscode://file/x', '//example.org', 'https://', 'mailto:nobody', 'https://example.org/\u0000', 'ftp://example.org', '', null, 42, 'https://example.org/' + 'a'.repeat(3000)]) {
|
||||
assert.equal(safeHref(bad), null, String(bad));
|
||||
}
|
||||
});
|
||||
|
||||
test('deeply nested or enormous input does not hang or overflow', () => {
|
||||
const deep = '*a '.repeat(2000) + ' b*'.repeat(2000);
|
||||
assert.ok(parseInline(deep).length > 0);
|
||||
assert.ok(parse('> '.repeat(500) + 'x').length > 0);
|
||||
assert.ok(parse('['.repeat(5000) + 'x' + ']'.repeat(5000) + '(https://example.org)').length > 0);
|
||||
const big = ('word '.repeat(20) + '\n').repeat(5000);
|
||||
const started = Date.now();
|
||||
parse(big);
|
||||
assert.ok(Date.now() - started < 2000);
|
||||
assert.deepEqual(parse(''), []);
|
||||
assert.deepEqual(parse(null), []);
|
||||
});
|
||||
|
||||
test('hostile and very long replies are read in linear time', () => {
|
||||
const n = 200000;
|
||||
const cases = {
|
||||
'unclosed brackets': '['.repeat(n),
|
||||
'brackets with a far close': '[a '.repeat(n / 4) + ']',
|
||||
'unclosed emphasis': '*a '.repeat(n / 3),
|
||||
'unclosed double emphasis': '**a '.repeat(n / 4),
|
||||
'underscores': '_a '.repeat(n / 3),
|
||||
'mixed marks': '*_[`'.repeat(n / 4),
|
||||
'backtick runs of every length': Array.from({ length: 600 }, (_, i) => '`'.repeat(i + 1)).join(' '),
|
||||
'a heading of spaces and hashes': '# ' + ' #'.repeat(n / 2) + ' x',
|
||||
'a heading of spaces': '# a' + ' '.repeat(n) + 'b',
|
||||
'a rule that is not one': '- '.repeat(n / 2) + 'x',
|
||||
'one enormous line': 'word '.repeat(n / 5),
|
||||
'a list marker and spaces': '-' + ' '.repeat(n) + 'x',
|
||||
'links without an end': '[a](https://example.org/'.repeat(n / 24),
|
||||
'many paragraphs of marks': '*a [b `c\n\n'.repeat(n / 12),
|
||||
'quotes in quotes': '> '.repeat(n / 2) + 'x',
|
||||
};
|
||||
for (const [name, text] of Object.entries(cases)) {
|
||||
const started = process.hrtime.bigint();
|
||||
const blocks = parse(text);
|
||||
const ms = Number(process.hrtime.bigint() - started) / 1e6;
|
||||
assert.ok(ms < 1500, `${name}: ${Math.round(ms)} ms for ${text.length} characters`);
|
||||
assert.ok(blocks.length > 0, name);
|
||||
}
|
||||
// Nothing is lost when the budget runs out: the rest is text.
|
||||
const spent = parse('*a '.repeat(n / 3));
|
||||
const flatten = (nodes) => nodes.map((x) => (x.v !== undefined ? x.v : x.c ? flatten(x.c) : x.t === 'br' ? '\n' : '')).join('');
|
||||
assert.equal(flatten(spent), '*a '.repeat(n / 3));
|
||||
});
|
||||
|
||||
test('a text beyond the limit is shown as it was written', () => {
|
||||
const big = '**x** <b>'.repeat(MAX_CHARS / 9 + 10);
|
||||
assert.deepEqual(parse(big), [{ t: 'plain', v: big }]);
|
||||
const root = render(big);
|
||||
assert.equal(root.show().slice(0, 30), 'div(div("**x** <b>**x** <b>**x');
|
||||
assert.equal(root.textContent, big);
|
||||
});
|
||||
|
||||
test('a heading keeps its text and loses only a closing run of hashes', () => {
|
||||
assert.equal(render('## Two ## ').show(), 'div(h2("Two"))');
|
||||
assert.equal(render('# C# and F#').show(), 'div(h1("C# and F#"))');
|
||||
assert.equal(render('# a # b').show(), 'div(h1("a # b"))');
|
||||
assert.equal(render('###### deep').show(), 'div(h6("deep"))');
|
||||
assert.equal(render('#notaheading').show(), 'div(p("#notaheading"))');
|
||||
});
|
||||
|
||||
test('a reply read as it grows is read the same as the whole, and old text is not read again', () => {
|
||||
const reply = [
|
||||
'# Bread', '', 'Some **bold** text with `code` and a [link](https://example.org).', 'second line', '',
|
||||
'- one', '- two', ' - inner', '', '1. first', '2. second', '', '> quoted', '> more', '',
|
||||
'```python', 'def bake():', '', ' return "**not bold**"', '', '```', '', '| a | b |', '|---|---|', '', '---', '',
|
||||
'A last paragraph that ends without', 'a line break, then an open fence:', '', '~~~', 'still', '', 'open',
|
||||
].join('\n');
|
||||
// Fed in pieces of every size, as a model sends it.
|
||||
for (const step of [1, 2, 3, 7, 19, 64, 1000]) {
|
||||
const growing = new Growing();
|
||||
for (let end = step; end < reply.length + step; end += step) {
|
||||
const part = reply.slice(0, end);
|
||||
assert.deepEqual(growing.update(part), parse(part), `step ${step}, ${end} characters`);
|
||||
}
|
||||
}
|
||||
// What is settled is kept: a long reply costs its tail each time, not the whole of it.
|
||||
const growing = new Growing();
|
||||
const para = 'word '.repeat(40) + '\n\n';
|
||||
growing.update(para.repeat(500) + 'the tail');
|
||||
assert.equal(growing.done, para.length * 500);
|
||||
assert.equal(growing.blocks.length, 500);
|
||||
const before = growing.blocks;
|
||||
const out = growing.update(para.repeat(500) + 'the tail grows');
|
||||
assert.equal(growing.blocks, before);
|
||||
assert.equal(out.length, 501);
|
||||
// Inside an open fence nothing is settled, however many blank lines it holds.
|
||||
const fenced = new Growing();
|
||||
fenced.update('intro\n\n```\na\n\nb\n\nc');
|
||||
assert.equal(fenced.done, 'intro\n\n'.length);
|
||||
// A text that is not a continuation starts over.
|
||||
assert.deepEqual(growing.update('new text'), parse('new text'));
|
||||
});
|
||||
|
||||
test('an item of the transcript is drawn from its fields as text', () => {
|
||||
const posted = [];
|
||||
const post = (m) => posted.push(m);
|
||||
const card = page.renderItem(doc, {
|
||||
id: 'i7', kind: 'card', state: 'open', title: 'rm -rf <b>build</b>', tool: 'bash', reason: '<i>deletes</i> files', detail: '--- a\n+++ b',
|
||||
files: ['/p/a.py'], options: [{ optionId: 'once', name: 'Allow <once>', kind: 'allow_once' }, { optionId: 'deny', name: 'Deny', kind: 'reject_once' }],
|
||||
}, post);
|
||||
for (const n of card.all()) assert.ok(['#text', 'div', 'pre', 'button'].includes(n.tag), n.tag);
|
||||
assert.ok(card.textContent.includes('rm -rf <b>build</b>') && card.textContent.includes('<i>deletes</i> files'));
|
||||
const buttons = card.all().filter((n) => n.tag === 'button');
|
||||
assert.deepEqual(buttons.map((b) => b.textContent), ['Allow <once>', 'Deny', 'Show the change']);
|
||||
buttons[1].listeners.click();
|
||||
buttons[2].listeners.click();
|
||||
assert.deepEqual(posted, [{ type: 'answer', card: 'i7', option: 'deny' }, { type: 'showDiff', card: 'i7' }]);
|
||||
|
||||
const closed = page.renderItem(doc, { id: 'i7', kind: 'card', state: 'answered', title: 't', answer: 'Deny', options: [{ optionId: 'once', name: 'Allow' }] }, post);
|
||||
assert.equal(closed.all().filter((n) => n.tag === 'button').length, 0, 'an answered card has no buttons');
|
||||
|
||||
const user = page.renderItem(doc, { id: 'i1', kind: 'user', text: '<script>x</script>', label: 'a.py:1-2' }, post);
|
||||
assert.ok(user.textContent.includes('<script>x</script>') && user.textContent.includes('[a.py:1-2]'));
|
||||
assert.ok(!user.all().some((n) => n.tag === 'script'));
|
||||
|
||||
const picture = page.renderItem(doc, { id: 'i2', kind: 'media', picture: true, src: 'https://file.example/1-chart.png', name: 'chart.png', sizeWords: '5 KB', key: 'm1' }, post);
|
||||
const img = picture.all().find((n) => n.tag === 'img');
|
||||
assert.equal(img.attrs.src, 'https://file.example/1-chart.png');
|
||||
assert.ok(picture.textContent.includes('chart.png (5 KB)'));
|
||||
const other = page.renderItem(doc, { id: 'i3', kind: 'media', picture: false, name: 'report.pdf', key: 'm2' }, post);
|
||||
assert.ok(!other.all().some((n) => n.tag === 'img'));
|
||||
const folder = other.all().find((n) => n.tag === 'button');
|
||||
assert.equal(folder.textContent, 'Show in folder', 'a file that may not be opened says so on its button');
|
||||
folder.listeners.click();
|
||||
assert.deepEqual(posted.pop(), { type: 'openMedia', key: 'm2' });
|
||||
const opens = page.renderItem(doc, { id: 'i5', kind: 'media', picture: false, name: 'report.pdf', key: 'm3', opens: true }, post);
|
||||
assert.equal(opens.all().find((n) => n.tag === 'button').textContent, 'Open');
|
||||
|
||||
const unknown = page.renderItem(doc, { id: 'i4', kind: 'surprise<script>', text: 'x' }, post);
|
||||
assert.equal(unknown.children.length, 0);
|
||||
assert.equal(unknown.className, 'item surprisescript');
|
||||
});
|
||||
|
||||
test("the page's script never parses markup and never evaluates text", () => {
|
||||
const src = fs.readFileSync(path.join(__dirname, '..', 'media', 'chat.js'), 'utf8');
|
||||
for (const banned of ['innerHTML', 'outerHTML', 'insertAdjacentHTML', 'document.write', 'eval(', 'new Function', 'DOMParser', 'srcdoc', 'setTimeout("', "setTimeout('"]) {
|
||||
assert.ok(!src.includes(banned), `chat.js must not use ${banned}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('the page: a strict policy, one script with a nonce, nothing from elsewhere', () => {
|
||||
const html = chatHtml({ cspSource: 'https://file.example', nonce: 'abc123', scriptUri: 'https://file.example/media/chat.js', styleUri: 'https://file.example/media/chat.css' });
|
||||
const csp = /<meta http-equiv="Content-Security-Policy" content="([^"]+)">/.exec(html)[1];
|
||||
const rules = Object.fromEntries(csp.split('; ').map((r) => [r.split(' ')[0], r.split(' ').slice(1)]));
|
||||
assert.deepEqual(rules['default-src'], ["'none'"]);
|
||||
assert.deepEqual(rules['script-src'], ["'nonce-abc123'"]);
|
||||
assert.deepEqual(rules['style-src'], ['https://file.example']);
|
||||
assert.deepEqual(rules['img-src'], ['https://file.example']);
|
||||
assert.ok(!/unsafe-inline|unsafe-eval|\*|data:|blob:|http:/.test(csp));
|
||||
assert.equal((html.match(/<script/g) || []).length, 1);
|
||||
assert.match(html, /<script nonce="abc123" src="https:\/\/file\.example\/media\/chat\.js"><\/script>/);
|
||||
assert.ok(!/\son[a-z]+=/.test(html), 'no inline handlers');
|
||||
assert.ok(!/style=/.test(html), 'no inline styles');
|
||||
assert.throws(() => chatHtml({ cspSource: 'x', nonce: 'a"b', scriptUri: 's', styleUri: 't' }));
|
||||
});
|
||||
|
||||
test('the stylesheet takes every colour from the editor\'s theme', () => {
|
||||
const css = fs.readFileSync(path.join(__dirname, '..', 'media', 'chat.css'), 'utf8').replace(/\/\*[\s\S]*?\*\//g, '');
|
||||
assert.ok(!/#[0-9a-fA-F]{3,8}\b/.test(css), 'no hex colours');
|
||||
assert.ok(!/\b(rgb|rgba|hsl|hsla)\(/.test(css), 'no colour functions');
|
||||
assert.ok(!/url\(|@import/.test(css), 'nothing loaded from a stylesheet');
|
||||
for (const m of css.matchAll(/(?:^|[;{\s])(color|background|background-color|border(?:-[a-z]+)*|outline)\s*:\s*([^;}]+)/g)) {
|
||||
const value = m[2].trim();
|
||||
if (/^(0|none|transparent|inherit)$/.test(value)) continue;
|
||||
const colourless = value.replace(/var\(--vscode-[A-Za-z0-9-]+(?:,\s*(?:transparent|var\(--vscode-[A-Za-z0-9-]+\)))?\)/g, '').replace(/\b(\d+(\.\d+)?(px|em)?|solid|transparent)\b/g, '').trim();
|
||||
assert.equal(colourless, '', `${m[1]}: ${value}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const crypto = require('node:crypto');
|
||||
const { sniffPicture, sizeInWords, safeName, openable, fetchShown } = require('../src/media');
|
||||
|
||||
test('a picture is known by its bytes, not by its name or by what the agent calls it', () => {
|
||||
const pad = Buffer.alloc(16);
|
||||
assert.equal(sniffPicture(Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), pad])).mime, 'image/png');
|
||||
assert.equal(sniffPicture(Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), pad])).ext, 'jpg');
|
||||
assert.equal(sniffPicture(Buffer.concat([Buffer.from('GIF89a'), pad])).mime, 'image/gif');
|
||||
assert.equal(sniffPicture(Buffer.concat([Buffer.from('RIFF\x10\x00\x00\x00WEBPVP8 '), pad])).mime, 'image/webp');
|
||||
assert.equal(sniffPicture(Buffer.concat([Buffer.from('\x00\x00\x00\x1cftypavif', 'latin1'), pad])).mime, 'image/avif');
|
||||
for (const not of ['<svg xmlns="http://www.w3.org/2000/svg"><script/></svg>', '<!DOCTYPE html><html>', '%PDF-1.7 and more bytes', 'RIFF\x10\x00\x00\x00WAVEfmt ', 'short', '']) {
|
||||
assert.equal(sniffPicture(Buffer.from(not, 'latin1')), null, not);
|
||||
}
|
||||
assert.equal(sniffPicture(null), null);
|
||||
});
|
||||
|
||||
test('sizes are said in words', () => {
|
||||
assert.equal(sizeInWords(1), '1 byte');
|
||||
assert.equal(sizeInWords(640), '640 bytes');
|
||||
assert.equal(sizeInWords(48211), '47 KB');
|
||||
assert.equal(sizeInWords(1.5 * 1024 * 1024), '1.5 MB');
|
||||
assert.equal(sizeInWords(64 * 1024 * 1024), '64 MB');
|
||||
assert.equal(sizeInWords(3 * 1024 * 1024 * 1024), '3.0 GB');
|
||||
});
|
||||
|
||||
test('a file name is made harmless', () => {
|
||||
assert.equal(safeName('out/chart.png'), 'chart.png');
|
||||
assert.equal(safeName('C:\\Users\\person\\shot 1.PNG'), 'shot_1.PNG');
|
||||
assert.equal(safeName('../../.bashrc'), 'bashrc');
|
||||
assert.equal(safeName('a/b/"; rm -rf ~ #.txt'), '___rm_-rf____.txt');
|
||||
assert.equal(safeName('', 'bin'), 'file.bin');
|
||||
assert.equal(safeName('noext', 'png'), 'noext.png');
|
||||
assert.ok(safeName('x'.repeat(500) + '.png').length <= 80);
|
||||
});
|
||||
|
||||
const bytes = (text) => Buffer.concat([Buffer.from(text, 'latin1'), Buffer.alloc(16, 0x20)]);
|
||||
const PNG_HEAD = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(16)]);
|
||||
|
||||
test('Open is an allow-list: only kinds that are merely displayed, and only when bytes and name agree', () => {
|
||||
// What opens, and where.
|
||||
assert.deepEqual(openable(PNG_HEAD, 'chart.png'), { kind: 'image', how: 'editor' });
|
||||
assert.deepEqual(openable(bytes('\xff\xd8\xff\xe0'), 'photo.JPEG'), { kind: 'image', how: 'editor' });
|
||||
assert.deepEqual(openable(bytes('%PDF-1.7\n'), '/tmp/x/report.pdf'), { kind: 'pdf', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('ID3\x04\x00'), 'song.mp3'), { kind: 'audio', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('RIFF\x10\x00\x00\x00WAVEfmt '), 'beep.wav'), { kind: 'audio', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('OggS\x00'), 'voice.ogg'), { kind: 'audio', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('\x00\x00\x00\x20ftypisom'), 'clip.mp4'), { kind: 'video', how: 'system' });
|
||||
assert.deepEqual(openable(bytes('\x1a\x45\xdf\xa3'), 'clip.webm'), { kind: 'video', how: 'system' });
|
||||
assert.deepEqual(openable(Buffer.from('a,b\n1,2\n'), 'data.csv'), { kind: 'text', how: 'editor' }, 'plain text opens inside the editor, never in a spreadsheet');
|
||||
assert.deepEqual(openable(Buffer.from('žluťoučký 🍞\n'), 'notes.txt'), { kind: 'text', how: 'editor' });
|
||||
assert.deepEqual(openable(Buffer.from('abc 🍞').subarray(0, 6), 'cut.md'), { kind: 'text', how: 'editor' }, 'a window that ends inside a character');
|
||||
|
||||
// Everything the review named, and the rest of what a system might run: never opened.
|
||||
const script = Buffer.from('#!/bin/sh\necho run\n');
|
||||
for (const name of ['run.sh', 'tool.py', 'tool.pyw', 'help.chm', 'console.msc', 'page.mht', 'app.jnlp', 'letter.docm', 'sheet.xlsm', 'mod.psm1', 'x.ws',
|
||||
'setup.application', 'a.settingcontent-ms', 'fix.diagcab', 'setup.exe', 'a.desktop', 'page.html', 'pic.svg', 'x.jar', 'x.AppImage', 'link.lnk', 'site.url', 'noending', 'a.unknownkind']) {
|
||||
assert.equal(openable(script, name), null, name);
|
||||
assert.equal(openable(PNG_HEAD, name), null, name + ' with a picture inside');
|
||||
}
|
||||
// A name that lies about its bytes, either way round.
|
||||
assert.equal(openable(script, 'report.pdf'), null, 'not a PDF inside');
|
||||
assert.equal(openable(bytes('%PDF-1.7\n'), 'report.txt'), null, 'a PDF called text');
|
||||
assert.equal(openable(bytes('MZ\x90\x00\x03\x00\x00\x00'), 'song.mp3'), null, 'a program called a song');
|
||||
assert.equal(openable(PNG_HEAD, 'chart.gif'), null);
|
||||
assert.equal(openable(Buffer.from([0x74, 0x65, 0x00, 0x78, 0x74]), 'notes.txt'), null, 'text does not hold a zero byte');
|
||||
assert.equal(openable(Buffer.from([0xff, 0xfe, 0x41, 0x00]), 'notes.txt'), null);
|
||||
assert.equal(openable(Buffer.alloc(0), 'notes.txt'), null);
|
||||
assert.equal(openable(null, 'notes.txt'), null);
|
||||
});
|
||||
|
||||
function reader(bytes, part) {
|
||||
const calls = [];
|
||||
const read = async (p) => {
|
||||
calls.push(p);
|
||||
const chunk = bytes.subarray(p.offset, p.offset + Math.min(p.length, part));
|
||||
return { data: chunk.toString('base64'), offset: p.offset, eof: p.offset + chunk.length >= bytes.length };
|
||||
};
|
||||
return { read, calls };
|
||||
}
|
||||
|
||||
test('a file is read part by part to its end and checked', async () => {
|
||||
const bytes = crypto.randomBytes(10500);
|
||||
const hash = 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const { read, calls } = reader(bytes, 4000);
|
||||
const got = await fetchShown(read, { handle: 'h_1', size: bytes.length, hash }, { maxBytes: 1e6 });
|
||||
assert.ok(got.equals(bytes));
|
||||
assert.deepEqual(calls.map((c) => c.offset), [0, 4000, 8000]);
|
||||
assert.ok(calls.every((c) => c.handle === 'h_1' && c.length === 1024 * 1024));
|
||||
});
|
||||
|
||||
test('too large, cut short, the wrong size or the wrong checksum are refused in words', async () => {
|
||||
const bytes = crypto.randomBytes(5000);
|
||||
const { read, calls } = reader(bytes, 1000);
|
||||
await assert.rejects(fetchShown(read, { handle: 'h', size: 5000 }, { maxBytes: 4096 }), /The file is 5 KB; this editor takes files of up to 4 KB\./);
|
||||
assert.equal(calls.length, 0, 'a size over the limit is refused before anything is read');
|
||||
// The agent named no size, or a false one: the limit holds while reading.
|
||||
await assert.rejects(fetchShown(read, { handle: 'h' }, { maxBytes: 2500 }), /this editor takes files of up to 2 KB/);
|
||||
await assert.rejects(fetchShown(read, { handle: 'h', size: 100 }, { maxBytes: 1e6 }), /arrived as 5 KB, not the 100 bytes/);
|
||||
await assert.rejects(fetchShown(read, { handle: 'h', hash: 'sha256:' + 'a'.repeat(64) }, { maxBytes: 1e6 }), /checksum differs/);
|
||||
await assert.rejects(fetchShown(async () => ({ data: '', eof: false }), { handle: 'h' }, { maxBytes: 1e6 }), /stopped sending/);
|
||||
await assert.rejects(fetchShown(async () => ({}), { handle: 'h' }, { maxBytes: 1e6 }), /sent no data/);
|
||||
await assert.rejects(fetchShown(async () => { throw new Error('This file is no longer offered.'); }, { handle: 'h' }, { maxBytes: 1e6 }), /no longer offered/);
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { Rpc, RpcError } = require('../src/rpc');
|
||||
|
||||
function pair(handlers) {
|
||||
const sent = [];
|
||||
const rpc = new Rpc({ write: (line) => sent.push(line), ...(handlers || {}) });
|
||||
return { rpc, sent, last: () => JSON.parse(sent[sent.length - 1]) };
|
||||
}
|
||||
|
||||
test('a request is one line of JSON-RPC 2.0 and its answer resolves it', async () => {
|
||||
const { rpc, sent, last } = pair();
|
||||
const p = rpc.request('initialize', { protocolVersion: 1 });
|
||||
assert.equal(sent.length, 1);
|
||||
assert.ok(sent[0].endsWith('\n') && !sent[0].slice(0, -1).includes('\n'));
|
||||
assert.deepEqual(last(), { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: 1 } });
|
||||
rpc.feed('{"jsonrpc":"2.0","id":1,"result":{"ok":true}}\n');
|
||||
assert.deepEqual(await p, { ok: true });
|
||||
});
|
||||
|
||||
test('messages split across chunks, several in one chunk, and a character split in two', async () => {
|
||||
const got = [];
|
||||
const { rpc } = pair({ onNotify: (m, p) => got.push([m, p]) });
|
||||
const line = Buffer.from('{"jsonrpc":"2.0","method":"note","params":{"t":"žluťoučký 🍞"}}\n');
|
||||
const cut = line.indexOf(0xf0) + 2; // inside the four bytes of the bread
|
||||
rpc.feed(line.subarray(0, cut));
|
||||
assert.equal(got.length, 0);
|
||||
rpc.feed(Buffer.concat([line.subarray(cut), line, Buffer.from('\n \n')]));
|
||||
assert.equal(got.length, 2);
|
||||
assert.equal(got[0][1].t, 'žluťoučký 🍞');
|
||||
});
|
||||
|
||||
test('a line that is not JSON, or not an object, is skipped', () => {
|
||||
const got = [];
|
||||
const { rpc } = pair({ onNotify: (m) => got.push(m) });
|
||||
rpc.feed('warming up...\n[1,2]\n"text"\n{"jsonrpc":"2.0","method":"ok"}\n');
|
||||
assert.deepEqual(got, ['ok']);
|
||||
});
|
||||
|
||||
test('an error answer rejects with its code, message and reason', async () => {
|
||||
const { rpc } = pair();
|
||||
const p = rpc.request('_lembas/complete', {});
|
||||
rpc.feed('{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"No autocomplete model is chosen.","data":{"reason":"no_model"}}}\n');
|
||||
await assert.rejects(p, (e) => e instanceof RpcError && e.code === -32602 && e.reason === 'no_model' && /No autocomplete/.test(e.message));
|
||||
});
|
||||
|
||||
test('a request from the other side is answered: a value, a promise, a refusal, a throw', async () => {
|
||||
const { rpc, sent } = pair({
|
||||
onRequest: (method, params) => {
|
||||
if (method === 'value') return { echo: params.x };
|
||||
if (method === 'later') return new Promise((r) => setTimeout(() => r('done'), 5));
|
||||
if (method === 'refuse') throw { code: -32002, message: 'cannot read', data: { reason: 'missing' } };
|
||||
if (method === 'nothing') return undefined;
|
||||
throw new Error('boom');
|
||||
},
|
||||
});
|
||||
rpc.feed('{"jsonrpc":"2.0","id":"a","method":"value","params":{"x":7}}\n');
|
||||
rpc.feed('{"jsonrpc":"2.0","id":2,"method":"later"}\n');
|
||||
rpc.feed('{"jsonrpc":"2.0","id":3,"method":"refuse"}\n');
|
||||
rpc.feed('{"jsonrpc":"2.0","id":4,"method":"nothing"}\n');
|
||||
rpc.feed('{"jsonrpc":"2.0","id":5,"method":"other"}\n');
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
const byId = Object.fromEntries(sent.map((l) => JSON.parse(l)).map((m) => [m.id, m]));
|
||||
assert.deepEqual(byId.a.result, { echo: 7 });
|
||||
assert.equal(byId[2].result, 'done');
|
||||
assert.deepEqual(byId[3].error, { code: -32002, message: 'cannot read', data: { reason: 'missing' } });
|
||||
assert.equal(byId[4].result, null);
|
||||
assert.equal(byId[5].error.code, -32603);
|
||||
assert.match(byId[5].error.message, /boom/);
|
||||
});
|
||||
|
||||
test('without a handler a request is method-not-found', () => {
|
||||
const { rpc, last } = pair();
|
||||
rpc.feed('{"jsonrpc":"2.0","id":9,"method":"_lembas/question"}\n');
|
||||
assert.equal(last().error.code, -32601);
|
||||
});
|
||||
|
||||
test('closing fails everything waited for, and later requests too', async () => {
|
||||
const { rpc, sent } = pair();
|
||||
const p = rpc.request('session/prompt', {});
|
||||
rpc.close('the agent stopped (exit 3)');
|
||||
await assert.rejects(p, /the agent stopped \(exit 3\)/);
|
||||
await assert.rejects(rpc.request('x', {}), /not running/);
|
||||
rpc.notify('y', {});
|
||||
assert.equal(sent.length, 1);
|
||||
});
|
||||
|
||||
test('an answer nobody waits for is ignored', () => {
|
||||
const { rpc } = pair();
|
||||
rpc.feed('{"jsonrpc":"2.0","id":77,"result":1}\n');
|
||||
});
|
||||
@@ -0,0 +1,400 @@
|
||||
'use strict';
|
||||
// A stand-in for the `vscode` module, for tests/extension.test.js: just enough of the editor's
|
||||
// API, in memory, for extension.js to be loaded and driven. It is NOT VS Code — what passes
|
||||
// here shows that the glue code runs and calls the API the way it means to, not that the
|
||||
// editor behaves that way.
|
||||
const path = require('node:path');
|
||||
|
||||
class Position {
|
||||
constructor(line, character) {
|
||||
this.line = line;
|
||||
this.character = character;
|
||||
}
|
||||
}
|
||||
|
||||
class Range {
|
||||
constructor(a, b, c, d) {
|
||||
if (a instanceof Position) {
|
||||
this.start = a;
|
||||
this.end = b;
|
||||
} else {
|
||||
this.start = new Position(a, b);
|
||||
this.end = new Position(c, d);
|
||||
}
|
||||
}
|
||||
get isEmpty() {
|
||||
return this.start.line === this.end.line && this.start.character === this.end.character;
|
||||
}
|
||||
}
|
||||
|
||||
class Selection extends Range {
|
||||
constructor(a, b, c, d) {
|
||||
super(a, b, c, d);
|
||||
this.anchor = this.start;
|
||||
this.active = this.end;
|
||||
}
|
||||
}
|
||||
|
||||
class Uri {
|
||||
constructor(scheme, p) {
|
||||
this.scheme = scheme;
|
||||
this.path = p;
|
||||
}
|
||||
get fsPath() {
|
||||
return this.path;
|
||||
}
|
||||
toString() {
|
||||
return `${this.scheme}:${this.scheme === 'file' ? '//' : ''}${this.path}`;
|
||||
}
|
||||
static file(p) {
|
||||
return new Uri('file', p);
|
||||
}
|
||||
static from(o) {
|
||||
return new Uri(o.scheme, o.path);
|
||||
}
|
||||
static parse(text) {
|
||||
const m = /^([a-z][a-z0-9+.-]*):(.*)$/i.exec(text);
|
||||
return new Uri(m[1], m[2]);
|
||||
}
|
||||
static joinPath(base, ...parts) {
|
||||
return new Uri(base.scheme, path.posix.join(base.path, ...parts));
|
||||
}
|
||||
}
|
||||
|
||||
class EventEmitter {
|
||||
constructor() {
|
||||
this.listeners = [];
|
||||
this.event = (fn) => {
|
||||
this.listeners.push(fn);
|
||||
return { dispose: () => (this.listeners = this.listeners.filter((l) => l !== fn)) };
|
||||
};
|
||||
}
|
||||
fire(value) {
|
||||
for (const l of this.listeners.slice()) l(value);
|
||||
}
|
||||
}
|
||||
|
||||
class TextDocument {
|
||||
constructor(uri, text, languageId) {
|
||||
this.uri = uri;
|
||||
this.languageId = languageId || 'plaintext';
|
||||
this.version = 1;
|
||||
this.eol = 1;
|
||||
this.isClosed = false;
|
||||
this.isDirty = false;
|
||||
this.saves = 0;
|
||||
this.text = text;
|
||||
}
|
||||
get lines() {
|
||||
return this.text.split('\n');
|
||||
}
|
||||
get lineCount() {
|
||||
return this.lines.length;
|
||||
}
|
||||
lineAt(i) {
|
||||
const text = this.lines[i];
|
||||
if (text === undefined) throw new Error('no line ' + i);
|
||||
return { text, range: new Range(i, 0, i, text.length) };
|
||||
}
|
||||
offsetAt(pos) {
|
||||
const lines = this.lines;
|
||||
let offset = 0;
|
||||
for (let i = 0; i < Math.min(pos.line, lines.length); i++) offset += lines[i].length + 1;
|
||||
return Math.min(this.text.length, offset + Math.min(pos.character, (lines[pos.line] || '').length));
|
||||
}
|
||||
positionAt(offset) {
|
||||
const before = this.text.slice(0, Math.max(0, Math.min(offset, this.text.length))).split('\n');
|
||||
return new Position(before.length - 1, before[before.length - 1].length);
|
||||
}
|
||||
async save() {
|
||||
if (this.uri.scheme !== 'file') return false;
|
||||
require('node:fs').writeFileSync(this.uri.fsPath, this.text);
|
||||
this.isDirty = false;
|
||||
this.saves += 1;
|
||||
return true;
|
||||
}
|
||||
getText(range) {
|
||||
return range ? this.text.slice(this.offsetAt(range.start), this.offsetAt(range.end)) : this.text;
|
||||
}
|
||||
}
|
||||
|
||||
class TextEditor {
|
||||
constructor(document, selection) {
|
||||
this.document = document;
|
||||
this.selection = selection || new Selection(0, 0, 0, 0);
|
||||
this.decorations = new Map();
|
||||
}
|
||||
setDecorations(type, list) {
|
||||
this.decorations.set(type, list);
|
||||
}
|
||||
}
|
||||
|
||||
class WorkspaceEdit {
|
||||
constructor() {
|
||||
this.edits = [];
|
||||
}
|
||||
replace(uri, range, text) {
|
||||
this.edits.push({ uri, range, text });
|
||||
}
|
||||
}
|
||||
|
||||
class MarkdownString {
|
||||
constructor() {
|
||||
this.value = '';
|
||||
}
|
||||
appendText(t) {
|
||||
this.value += t;
|
||||
return this;
|
||||
}
|
||||
appendCodeblock(code, lang) {
|
||||
this.value += '\n```' + (lang || '') + '\n' + code + '\n```\n';
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
class TabInputText {
|
||||
constructor(uri) {
|
||||
this.uri = uri;
|
||||
}
|
||||
}
|
||||
class TabInputTextDiff {
|
||||
constructor(original, modified) {
|
||||
this.original = original;
|
||||
this.modified = modified;
|
||||
}
|
||||
}
|
||||
|
||||
function make(pkg) {
|
||||
const state = {
|
||||
config: {}, // 'llembas.command' -> value
|
||||
inputs: [], // answers to showInputBox, in order
|
||||
picks: [], // functions (items) => item, answers to showQuickPick, in order
|
||||
answers: [], // answers to show…Message, in order (undefined: dismissed)
|
||||
messages: [], // { level, text, buttons }
|
||||
executed: [], // commands of the editor's own that were run
|
||||
external: [],
|
||||
commands: new Map(),
|
||||
contentProviders: new Map(),
|
||||
viewProviders: new Map(),
|
||||
inlineProviders: [],
|
||||
lensProviders: [],
|
||||
statusItems: [],
|
||||
output: [],
|
||||
diagnostics: new Map(),
|
||||
tabs: [],
|
||||
changed: new EventEmitter(),
|
||||
closed: new EventEmitter(),
|
||||
configured: new EventEmitter(),
|
||||
visible: new EventEmitter(),
|
||||
active: new EventEmitter(),
|
||||
};
|
||||
const defaults = {};
|
||||
for (const [key, def] of Object.entries(pkg.contributes.configuration.properties)) defaults[key] = def.default;
|
||||
|
||||
const message = (level) => (text, ...buttons) => {
|
||||
state.messages.push({ level, text, buttons: buttons.filter((b) => typeof b === 'string') });
|
||||
return Promise.resolve(state.answers.length ? state.answers.shift() : undefined);
|
||||
};
|
||||
|
||||
const api = {
|
||||
__: state,
|
||||
Position,
|
||||
Range,
|
||||
Selection,
|
||||
Uri,
|
||||
EventEmitter,
|
||||
WorkspaceEdit,
|
||||
MarkdownString,
|
||||
TabInputText,
|
||||
TabInputTextDiff,
|
||||
TextDocument,
|
||||
TextEditor,
|
||||
ThemeColor: class {
|
||||
constructor(id) {
|
||||
this.id = id;
|
||||
}
|
||||
},
|
||||
CodeLens: class {
|
||||
constructor(range, command) {
|
||||
this.range = range;
|
||||
this.command = command;
|
||||
}
|
||||
},
|
||||
InlineCompletionItem: class {
|
||||
constructor(insertText, range) {
|
||||
this.insertText = insertText;
|
||||
this.range = range;
|
||||
}
|
||||
},
|
||||
EndOfLine: { LF: 1, CRLF: 2 },
|
||||
OverviewRulerLane: { Left: 1 },
|
||||
StatusBarAlignment: { Left: 1, Right: 2 },
|
||||
ProgressLocation: { Notification: 15 },
|
||||
ViewColumn: { Beside: -2 },
|
||||
InlineCompletionTriggerKind: { Invoke: 0, Automatic: 1 },
|
||||
DiagnosticSeverity: { Error: 0, Warning: 1, Information: 2, Hint: 3 },
|
||||
workspace: {
|
||||
workspaceFolders: undefined,
|
||||
textDocuments: [],
|
||||
getConfiguration: (section) => ({
|
||||
get: (key) => {
|
||||
const full = `${section}.${key}`;
|
||||
if (!(full in defaults)) throw new Error('a setting that is not declared: ' + full);
|
||||
return full in state.config ? state.config[full] : defaults[full];
|
||||
},
|
||||
}),
|
||||
registerTextDocumentContentProvider: (scheme, provider) => {
|
||||
state.contentProviders.set(scheme, provider);
|
||||
return { dispose() {} };
|
||||
},
|
||||
onDidChangeTextDocument: state.changed.event,
|
||||
onDidCloseTextDocument: state.closed.event,
|
||||
onDidChangeConfiguration: state.configured.event,
|
||||
asRelativePath: (uri) => path.basename(uri.path),
|
||||
openTextDocument: async (what) => {
|
||||
let doc;
|
||||
if (!(what instanceof Uri)) {
|
||||
doc = new TextDocument(new Uri('untitled', 'Untitled-1'), what.content);
|
||||
doc.isDirty = true; // as the editor has it: a document made from content wants saving
|
||||
} else if (what.scheme === 'file') doc = new TextDocument(what, require('node:fs').readFileSync(what.fsPath, 'utf8'));
|
||||
else doc = new TextDocument(what, await state.contentProviders.get(what.scheme).provideTextDocumentContent(what));
|
||||
api.workspace.textDocuments.push(doc);
|
||||
return doc;
|
||||
},
|
||||
applyEdit: async (edit) => {
|
||||
// Every range is against the text as it was; applied from the end of the text backwards.
|
||||
const byDoc = new Map();
|
||||
for (const e of edit.edits) {
|
||||
const doc = api.workspace.textDocuments.find((d) => d.uri.toString() === e.uri.toString());
|
||||
if (!doc) return false;
|
||||
if (!byDoc.has(doc)) byDoc.set(doc, []);
|
||||
byDoc.get(doc).push({ from: doc.offsetAt(e.range.start), to: doc.offsetAt(e.range.end), text: e.text, range: e.range });
|
||||
}
|
||||
for (const [doc, edits] of byDoc) {
|
||||
edits.sort((a, b) => b.from - a.from);
|
||||
for (let i = 1; i < edits.length; i++) if (edits[i].to > edits[i - 1].from) throw new Error('overlapping edits');
|
||||
for (const e of edits) doc.text = doc.text.slice(0, e.from) + e.text + doc.text.slice(e.to);
|
||||
doc.version += 1;
|
||||
doc.isDirty = true;
|
||||
state.changed.fire({ document: doc, contentChanges: edits.map((e) => ({ range: e.range, text: e.text })) });
|
||||
}
|
||||
return true;
|
||||
},
|
||||
},
|
||||
window: {
|
||||
activeTextEditor: undefined,
|
||||
visibleTextEditors: [],
|
||||
tabGroups: {
|
||||
get all() {
|
||||
return [{ tabs: state.tabs }];
|
||||
},
|
||||
close: async (tabs) => {
|
||||
state.tabs = state.tabs.filter((t) => !tabs.includes(t));
|
||||
return true;
|
||||
},
|
||||
},
|
||||
createOutputChannel: () => ({ append: (t) => state.output.push(t), appendLine: (t) => state.output.push(t + '\n'), dispose() {} }),
|
||||
registerWebviewViewProvider: (id, provider, options) => {
|
||||
state.viewProviders.set(id, { provider, options });
|
||||
return { dispose() {} };
|
||||
},
|
||||
createTextEditorDecorationType: (options) => ({ options, dispose() {} }),
|
||||
createStatusBarItem: () => {
|
||||
const item = { text: '', tooltip: '', command: '', shown: false, show: () => (item.shown = true), dispose() {} };
|
||||
state.statusItems.push(item);
|
||||
return item;
|
||||
},
|
||||
showInputBox: async () => state.inputs.shift(),
|
||||
showQuickPick: async (items, options) => {
|
||||
const pick = state.picks.shift();
|
||||
if (!pick) return undefined;
|
||||
const chosen = pick(items, options);
|
||||
if (chosen === undefined) throw new Error('the test picked nothing from: ' + items.map((i) => i.label).join(', '));
|
||||
return chosen;
|
||||
},
|
||||
showInformationMessage: message('info'),
|
||||
showWarningMessage: message('warning'),
|
||||
showErrorMessage: message('error'),
|
||||
showTextDocument: async (doc) => {
|
||||
state.executed.push(['showTextDocument', doc]);
|
||||
return new TextEditor(doc);
|
||||
},
|
||||
withProgress: (options, task) => {
|
||||
const cancel = new EventEmitter();
|
||||
state.cancelProgress = () => cancel.fire();
|
||||
return task({ report: (r) => state.executed.push(['progress', r.message]) }, { onCancellationRequested: cancel.event, isCancellationRequested: false });
|
||||
},
|
||||
onDidChangeVisibleTextEditors: state.visible.event,
|
||||
onDidChangeActiveTextEditor: state.active.event,
|
||||
},
|
||||
commands: {
|
||||
registerCommand: (name, fn) => {
|
||||
state.commands.set(name, fn);
|
||||
return { dispose() {} };
|
||||
},
|
||||
executeCommand: async (name, ...args) => {
|
||||
if (state.commands.has(name)) return state.commands.get(name)(...args);
|
||||
state.executed.push([name, ...args]);
|
||||
if (name === 'vscode.diff') state.tabs.push({ input: new TabInputTextDiff(args[0], args[1]), label: args[2] });
|
||||
return undefined;
|
||||
},
|
||||
},
|
||||
languages: {
|
||||
registerInlineCompletionItemProvider: (selector, provider) => {
|
||||
state.inlineProviders.push(provider);
|
||||
return { dispose() {} };
|
||||
},
|
||||
registerCodeLensProvider: (selector, provider) => {
|
||||
state.lensProviders.push(provider);
|
||||
return { dispose() {} };
|
||||
},
|
||||
getDiagnostics: (uri) => state.diagnostics.get(uri.toString()) || [],
|
||||
},
|
||||
env: {
|
||||
openExternal: async (uri) => {
|
||||
state.external.push(uri.toString());
|
||||
return true;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/** Open a document in an editor, in front. */
|
||||
api.__.open = (file, text, selection, languageId) => {
|
||||
const doc = new TextDocument(typeof file === 'string' ? Uri.file(file) : file, text, languageId);
|
||||
const editor = new TextEditor(doc, selection);
|
||||
api.workspace.textDocuments.push(doc);
|
||||
api.window.visibleTextEditors.push(editor);
|
||||
api.window.activeTextEditor = editor;
|
||||
state.tabs.push({ input: new TabInputText(doc.uri) });
|
||||
return editor;
|
||||
};
|
||||
/** A view of the chat: what the page was sent is `view.posted`; `view.say(m)` is the page speaking. */
|
||||
api.__.view = () => {
|
||||
const posted = [];
|
||||
let listener = () => {};
|
||||
const view = {
|
||||
posted,
|
||||
shows: [],
|
||||
webview: {
|
||||
options: null,
|
||||
html: '',
|
||||
cspSource: 'https://file.example',
|
||||
asWebviewUri: (uri) => Uri.parse('https://file.example' + uri.path),
|
||||
postMessage: async (m) => {
|
||||
posted.push(JSON.parse(JSON.stringify(m)));
|
||||
return true;
|
||||
},
|
||||
onDidReceiveMessage: (fn) => {
|
||||
listener = fn;
|
||||
},
|
||||
},
|
||||
show: (preserveFocus) => view.shows.push(preserveFocus),
|
||||
onDidDispose: () => {},
|
||||
say: (m) => listener(m),
|
||||
};
|
||||
return view;
|
||||
};
|
||||
return api;
|
||||
}
|
||||
|
||||
module.exports = { make };
|
||||
@@ -0,0 +1,178 @@
|
||||
'use strict';
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { execFileSync, spawnSync } = require('node:child_process');
|
||||
const { zip, unzip, crc32 } = require('../tools/zip');
|
||||
const { tempDir } = require('./helpers');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const REPO = path.join(ROOT, '..');
|
||||
const VERSION = fs.readFileSync(path.join(REPO, 'VERSION'), 'utf8').trim();
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
|
||||
|
||||
/** Whether a text is well-formed XML as far as elements and attributes go; returns its elements. */
|
||||
function elements(xml) {
|
||||
const out = [];
|
||||
const stack = [];
|
||||
const body = xml.replace(/^<\?xml[^?]*\?>\s*/, '');
|
||||
assert.ok(!/<\?|<!/.test(body), 'no processing instructions, doctypes or comments');
|
||||
const re = /<(\/?)([A-Za-z_][\w:.-]*)((?:\s+[\w:.-]+="[^"<]*")*)\s*(\/?)>|([^<]+)/g;
|
||||
let at = 0;
|
||||
for (let m; (m = re.exec(body)); ) {
|
||||
assert.equal(m.index, at, 'nothing unreadable at ' + at);
|
||||
at = re.lastIndex;
|
||||
if (m[5] !== undefined) {
|
||||
assert.ok(!/&(?!(amp|lt|gt|quot|apos);)/.test(m[5]), 'text is escaped');
|
||||
if (stack.length) stack[stack.length - 1].text += m[5];
|
||||
else assert.equal(m[5].trim(), '');
|
||||
continue;
|
||||
}
|
||||
if (m[1]) {
|
||||
assert.equal(stack.pop().name, m[2], 'closing tag matches');
|
||||
continue;
|
||||
}
|
||||
const attrs = {};
|
||||
for (const a of m[3].matchAll(/([\w:.-]+)="([^"]*)"/g)) attrs[a[1]] = a[2].replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
||||
const el = { name: m[2], attrs, text: '' };
|
||||
out.push(el);
|
||||
if (!m[4]) stack.push(el);
|
||||
}
|
||||
assert.equal(at, body.length);
|
||||
assert.equal(stack.length, 0, 'every element is closed');
|
||||
return out;
|
||||
}
|
||||
|
||||
test('the archive writer and reader agree, and with the system\'s unzip', (t) => {
|
||||
const files = [
|
||||
{ name: 'a.txt', data: Buffer.from('hello\n'.repeat(100)) },
|
||||
{ name: 'dir/ž 🍞.bin', data: Buffer.from([0, 1, 2, 3, 255]) },
|
||||
{ name: 'empty', data: Buffer.alloc(0) },
|
||||
];
|
||||
const archive = zip(files);
|
||||
assert.deepEqual(unzip(archive).map((f) => [f.name, f.data.toString('hex')]), files.map((f) => [f.name, f.data.toString('hex')]));
|
||||
assert.ok(archive.equals(zip(files)), 'the same input gives the same archive');
|
||||
assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926);
|
||||
assert.throws(() => zip([{ name: '../x', data: Buffer.alloc(0) }]));
|
||||
assert.throws(() => zip([{ name: 'a', data: Buffer.alloc(0) }, { name: 'a', data: Buffer.alloc(0) }]));
|
||||
const damaged = Buffer.from(archive);
|
||||
damaged[40] ^= 0xff;
|
||||
assert.throws(() => unzip(damaged));
|
||||
if (spawnSync('unzip', ['-v']).status === 0) {
|
||||
const file = path.join(tempDir(t), 'x.zip');
|
||||
fs.writeFileSync(file, archive);
|
||||
assert.match(execFileSync('unzip', ['-t', file], { encoding: 'utf8' }), /No errors detected/);
|
||||
}
|
||||
});
|
||||
|
||||
test('the package script builds a .vsix that is what an editor expects', (t) => {
|
||||
const out = tempDir(t);
|
||||
const said = execFileSync('sh', [path.join(REPO, 'scripts', 'package-vscode.sh'), out], { encoding: 'utf8' });
|
||||
const file = path.join(out, `llembas-${VERSION}.vsix`);
|
||||
assert.ok(said.startsWith(file + '\n'), said);
|
||||
const entries = unzip(fs.readFileSync(file));
|
||||
const names = entries.map((e) => e.name);
|
||||
const get = (name) => entries.find((e) => e.name === name).data.toString('utf8');
|
||||
|
||||
// The three things a .vsix is.
|
||||
assert.ok(names.includes('[Content_Types].xml') && names.includes('extension.vsixmanifest') && names.includes('extension/package.json'));
|
||||
assert.ok(names.every((n) => n === '[Content_Types].xml' || n === 'extension.vsixmanifest' || n.startsWith('extension/')), 'nothing outside extension/');
|
||||
|
||||
// The manifest: well-formed, and it says the repository's version and this extension's identity.
|
||||
const manifest = elements(get('extension.vsixmanifest'));
|
||||
assert.equal(manifest[0].name, 'PackageManifest');
|
||||
assert.equal(manifest[0].attrs.xmlns, 'http://schemas.microsoft.com/developer/vsx-schema/2011');
|
||||
const identity = manifest.find((e) => e.name === 'Identity');
|
||||
assert.deepEqual(identity.attrs, { Language: 'en-US', Id: 'llembas', Version: VERSION, Publisher: 'llembas' });
|
||||
assert.equal(manifest.find((e) => e.name === 'DisplayName').text, 'LLeMbas');
|
||||
const prop = (id) => manifest.find((e) => e.name === 'Property' && e.attrs.Id === id).attrs.Value;
|
||||
assert.equal(prop('Microsoft.VisualStudio.Code.Engine'), pkg.engines.vscode);
|
||||
assert.equal(prop('Microsoft.VisualStudio.Code.ExtensionKind'), 'workspace');
|
||||
assert.equal(manifest.find((e) => e.name === 'InstallationTarget').attrs.Id, 'Microsoft.VisualStudio.Code');
|
||||
const assets = manifest.filter((e) => e.name === 'Asset');
|
||||
assert.equal(assets.find((a) => a.attrs.Type === 'Microsoft.VisualStudio.Code.Manifest').attrs.Path, 'extension/package.json');
|
||||
for (const a of assets) assert.ok(names.includes(a.attrs.Path), `the asset ${a.attrs.Path} is in the package`);
|
||||
assert.ok(names.includes(manifest.find((e) => e.name === 'License').text));
|
||||
|
||||
// The content types name every kind of file in the package.
|
||||
const types = elements(get('[Content_Types].xml'));
|
||||
assert.equal(types[0].attrs.xmlns, 'http://schemas.openxmlformats.org/package/2006/content-types');
|
||||
const known = new Set(types.filter((e) => e.name === 'Default').map((e) => e.attrs.Extension));
|
||||
for (const n of names) if (n !== '[Content_Types].xml') assert.ok(known.has(path.extname(n)), `a content type for ${n}`);
|
||||
|
||||
// The packaged manifest of the extension: the version written in, everything it points at present.
|
||||
const packed = JSON.parse(get('extension/package.json'));
|
||||
assert.equal(packed.version, VERSION);
|
||||
assert.deepEqual({ ...packed, version: pkg.version }, pkg, 'otherwise the source manifest, unchanged');
|
||||
assert.ok(names.includes('extension/' + packed.main.replace(/^\.\//, '')));
|
||||
assert.ok(names.includes('extension/' + packed.contributes.viewsContainers.activitybar[0].icon));
|
||||
for (const need of ['extension/README.md', 'extension/LICENSE.txt', 'extension/media/chat.js', 'extension/media/chat.css', 'extension/src/rpc.js']) assert.ok(names.includes(need), need);
|
||||
assert.equal(get('extension/LICENSE.txt'), fs.readFileSync(path.join(REPO, 'LICENSE'), 'utf8'));
|
||||
|
||||
// Every module the code asks for is in the package, or is Node's or the editor's own.
|
||||
for (const e of entries.filter((x) => x.name.endsWith('.js') && !x.name.startsWith('extension/media/'))) {
|
||||
for (const m of e.data.toString('utf8').matchAll(/require\('([^']+)'\)/g)) {
|
||||
if (m[1] === 'vscode' || m[1].startsWith('node:')) continue;
|
||||
assert.ok(m[1].startsWith('.'), `${e.name} asks for ${m[1]}: no outside packages`);
|
||||
const target = path.posix.normalize(path.posix.join(path.posix.dirname(e.name), m[1])) + (m[1].endsWith('.js') ? '' : '.js');
|
||||
assert.ok(names.includes(target), `${e.name} asks for ${target}`);
|
||||
}
|
||||
}
|
||||
|
||||
// What does not ship.
|
||||
assert.ok(!names.some((n) => /\/(tests|tools|node_modules)\//.test(n)), 'no tests, tools or packages');
|
||||
assert.ok(!names.some((n) => /fake_agent|\.test\.js$|\.vsix$/.test(n)));
|
||||
|
||||
if (spawnSync('unzip', ['-v']).status === 0) {
|
||||
assert.match(execFileSync('unzip', ['-t', file], { encoding: 'utf8' }), /No errors detected/);
|
||||
}
|
||||
});
|
||||
|
||||
test('the manifest in the source tree: no dependencies, no build, the version only in VERSION', () => {
|
||||
assert.equal(pkg.version, '0.0.0', 'a placeholder: the package script writes the real one');
|
||||
assert.match(VERSION, /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/);
|
||||
for (const key of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies', 'scripts', 'extensionDependencies']) {
|
||||
assert.equal(pkg[key], undefined, `no ${key}`);
|
||||
}
|
||||
assert.match(pkg.engines.vscode, /^\^1\.\d+\.0$/);
|
||||
assert.ok(pkg.activationEvents.length > 0);
|
||||
assert.equal(pkg.contributes.configuration.properties['llembas.command'].scope, 'machine', 'a folder cannot say which program is started');
|
||||
assert.equal(pkg.contributes.configuration.properties['llembas.chat.startMode'].scope, 'machine', 'nor the mode a session starts in');
|
||||
assert.equal(pkg.capabilities.untrustedWorkspaces.supported, false);
|
||||
for (const file of fs.readdirSync(ROOT, { recursive: true })) {
|
||||
if (!/\.(js|json|css|md|py)$/.test(file) || /node_modules/.test(file)) continue;
|
||||
if (file === path.join('tests', 'vsix.test.js')) continue;
|
||||
const text = fs.readFileSync(path.join(ROOT, file), 'utf8');
|
||||
assert.ok(!text.includes(VERSION), `${file} repeats the version`);
|
||||
}
|
||||
});
|
||||
|
||||
test('every command, key and menu entry names a command the extension registers, and the other way round', () => {
|
||||
const source = fs.readFileSync(path.join(ROOT, 'extension.js'), 'utf8');
|
||||
const registered = new Set([...source.matchAll(/command\('(llembas\.[A-Za-z]+)'/g)].map((m) => m[1]));
|
||||
const contributed = new Set(pkg.contributes.commands.map((c) => c.command));
|
||||
assert.deepEqual([...registered].sort(), [...contributed].sort());
|
||||
for (const k of pkg.contributes.keybindings) assert.ok(contributed.has(k.command), k.command);
|
||||
for (const list of Object.values(pkg.contributes.menus)) for (const m of list) assert.ok(contributed.has(m.command), m.command);
|
||||
// Every setting the code reads is declared, and every declared setting is read.
|
||||
const read = new Set([...source.matchAll(/config\(\)\.get\('([A-Za-z.]+)'\)/g)].map((m) => 'llembas.' + m[1]));
|
||||
assert.deepEqual([...read].sort(), Object.keys(pkg.contributes.configuration.properties).sort());
|
||||
assert.ok(source.includes(`const VIEW_ID = '${pkg.contributes.views.llembas[0].id}'`));
|
||||
});
|
||||
|
||||
test('the modules that are tested without an editor do not ask for one, and nothing reaches the network', () => {
|
||||
for (const dir of ['src', 'tools', 'media']) {
|
||||
for (const file of fs.readdirSync(path.join(ROOT, dir))) {
|
||||
if (!file.endsWith('.js')) continue;
|
||||
const text = fs.readFileSync(path.join(ROOT, dir, file), 'utf8');
|
||||
assert.ok(!/require\(['"]vscode['"]\)/.test(text), `${dir}/${file} must not import vscode`);
|
||||
}
|
||||
}
|
||||
for (const file of ['extension.js', ...fs.readdirSync(path.join(ROOT, 'src')).map((f) => 'src/' + f), 'media/chat.js']) {
|
||||
const text = fs.readFileSync(path.join(ROOT, file), 'utf8');
|
||||
for (const banned of ["require('node:http')", "require('node:https')", "require('node:net')", "require('http')", "require('https')", 'fetch(', 'XMLHttpRequest', 'WebSocket', 'telemetry', 'eval(', 'new Function']) {
|
||||
assert.ok(!text.includes(banned), `${file} must not use ${banned}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
Executable
+136
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict';
|
||||
// Builds the extension's .vsix without any packaging tool. A .vsix is a zip that holds
|
||||
// `[Content_Types].xml`, `extension.vsixmanifest` and the extension itself under `extension/`.
|
||||
// The version comes from the repository's VERSION file and is written into the packaged
|
||||
// manifest; nothing in the source tree repeats it.
|
||||
//
|
||||
// node vscode/tools/vsix.js [output directory] (default: dist/)
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { zip } = require('./zip');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const REPO = path.resolve(ROOT, '..');
|
||||
// What ships: the code, the view's files and the read-me. Tests and tools stay behind.
|
||||
const SHIPPED = ['extension.js', 'README.md', 'src', 'media'];
|
||||
const SEMVER = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
|
||||
|
||||
function xml(text) {
|
||||
return String(text).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function walk(dir, base, out) {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
||||
const full = path.join(dir, entry.name);
|
||||
const rel = base ? base + '/' + entry.name : entry.name;
|
||||
if (entry.isDirectory()) walk(full, rel, out);
|
||||
else if (entry.isFile()) out.push({ name: rel, data: fs.readFileSync(full) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function manifestXml(pkg) {
|
||||
const kinds = Array.isArray(pkg.extensionKind) ? pkg.extensionKind.join(',') : 'workspace';
|
||||
return `<?xml version="1.0" encoding="utf-8"?>
|
||||
<PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
|
||||
<Metadata>
|
||||
<Identity Language="en-US" Id="${xml(pkg.name)}" Version="${xml(pkg.version)}" Publisher="${xml(pkg.publisher)}" />
|
||||
<DisplayName>${xml(pkg.displayName || pkg.name)}</DisplayName>
|
||||
<Description xml:space="preserve">${xml(pkg.description || '')}</Description>
|
||||
<Tags>${xml((pkg.keywords || []).join(','))}</Tags>
|
||||
<Categories>${xml((pkg.categories || []).join(','))}</Categories>
|
||||
<GalleryFlags>Public</GalleryFlags>
|
||||
<Properties>
|
||||
<Property Id="Microsoft.VisualStudio.Code.Engine" Value="${xml(pkg.engines.vscode)}" />
|
||||
<Property Id="Microsoft.VisualStudio.Code.ExtensionDependencies" Value="" />
|
||||
<Property Id="Microsoft.VisualStudio.Code.ExtensionPack" Value="" />
|
||||
<Property Id="Microsoft.VisualStudio.Code.ExtensionKind" Value="${xml(kinds)}" />
|
||||
<Property Id="Microsoft.VisualStudio.Code.LocalizedLanguages" Value="" />
|
||||
<Property Id="Microsoft.VisualStudio.Services.GitHubFlavoredMarkdown" Value="true" />
|
||||
<Property Id="Microsoft.VisualStudio.Services.Content.Pricing" Value="Free" />
|
||||
</Properties>
|
||||
<License>extension/LICENSE.txt</License>${pkg.icon ? `\n <Icon>extension/${xml(pkg.icon)}</Icon>` : ''}
|
||||
</Metadata>
|
||||
<Installation>
|
||||
<InstallationTarget Id="Microsoft.VisualStudio.Code" />
|
||||
</Installation>
|
||||
<Dependencies />
|
||||
<Assets>
|
||||
<Asset Type="Microsoft.VisualStudio.Code.Manifest" Path="extension/package.json" Addressable="true" />
|
||||
<Asset Type="Microsoft.VisualStudio.Services.Content.Details" Path="extension/README.md" Addressable="true" />
|
||||
<Asset Type="Microsoft.VisualStudio.Services.Content.License" Path="extension/LICENSE.txt" Addressable="true" />
|
||||
${pkg.icon ? ` <Asset Type="Microsoft.VisualStudio.Services.Icons.Default" Path="extension/${xml(pkg.icon)}" Addressable="true" />\n` : ''} </Assets>
|
||||
</PackageManifest>
|
||||
`;
|
||||
}
|
||||
|
||||
const TYPES = {
|
||||
'.json': 'application/json',
|
||||
'.vsixmanifest': 'text/xml',
|
||||
'.js': 'application/javascript',
|
||||
'.css': 'text/css',
|
||||
'.md': 'text/markdown',
|
||||
'.txt': 'text/plain',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
};
|
||||
|
||||
function contentTypesXml(names) {
|
||||
const used = new Set(['.vsixmanifest']);
|
||||
for (const n of names) used.add(path.extname(n).toLowerCase());
|
||||
const lines = [];
|
||||
for (const ext of [...used].sort()) {
|
||||
if (!TYPES[ext]) throw new Error(`a file of a kind the package does not know: ${ext || '(no ending)'}`);
|
||||
lines.push(`<Default Extension="${ext}" ContentType="${TYPES[ext]}" />`);
|
||||
}
|
||||
return `<?xml version="1.0" encoding="utf-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">${lines.join('')}</Types>\n`;
|
||||
}
|
||||
|
||||
/** The files of the archive, in order, and the manifest they were made from. */
|
||||
function build(options) {
|
||||
const root = (options && options.root) || ROOT;
|
||||
const repo = (options && options.repo) || REPO;
|
||||
const version = fs.readFileSync(path.join(repo, 'VERSION'), 'utf8').trim();
|
||||
if (!SEMVER.test(version)) throw new Error(`VERSION is not a version: ${version}`);
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
||||
pkg.version = version;
|
||||
const files = [{ name: 'package.json', data: Buffer.from(JSON.stringify(pkg, null, 2) + '\n') }];
|
||||
for (const item of SHIPPED) {
|
||||
const full = path.join(root, item);
|
||||
if (fs.statSync(full).isDirectory()) walk(full, item, files);
|
||||
else files.push({ name: item, data: fs.readFileSync(full) });
|
||||
}
|
||||
files.push({ name: 'LICENSE.txt', data: fs.readFileSync(path.join(repo, 'LICENSE')) });
|
||||
// Everything the manifest points at has to be in the package.
|
||||
const have = new Set(files.map((f) => f.name));
|
||||
const main = String(pkg.main || '').replace(/^\.\//, '');
|
||||
for (const need of [main, 'README.md', 'LICENSE.txt']) if (!have.has(need)) throw new Error('missing from the package: ' + need);
|
||||
const entries = [
|
||||
{ name: 'extension.vsixmanifest', data: Buffer.from(manifestXml(pkg)) },
|
||||
{ name: '[Content_Types].xml', data: Buffer.from(contentTypesXml(files.map((f) => f.name))) },
|
||||
...files.map((f) => ({ name: 'extension/' + f.name, data: f.data })),
|
||||
];
|
||||
return { pkg, version, entries, fileName: `${pkg.name}-${version}.vsix` };
|
||||
}
|
||||
|
||||
function main() {
|
||||
const outDir = path.resolve(process.argv[2] || path.join(REPO, 'dist'));
|
||||
const built = build();
|
||||
fs.mkdirSync(outDir, { recursive: true });
|
||||
const out = path.join(outDir, built.fileName);
|
||||
const archive = zip(built.entries);
|
||||
fs.writeFileSync(out, archive);
|
||||
process.stdout.write(`${out}\n${built.entries.length} files, ${archive.length} bytes, version ${built.version}\n`);
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
try {
|
||||
main();
|
||||
} catch (e) {
|
||||
process.stderr.write(`package-vscode: ${e.message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { build, manifestXml, contentTypesXml };
|
||||
@@ -0,0 +1,124 @@
|
||||
'use strict';
|
||||
// A zip archive written and read with Node alone (deflate from node:zlib): enough for a .vsix,
|
||||
// which is a zip, and for checking one. No dependencies.
|
||||
const zlib = require('node:zlib');
|
||||
|
||||
const CRC = (() => {
|
||||
const t = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
t[n] = c >>> 0;
|
||||
}
|
||||
return t;
|
||||
})();
|
||||
|
||||
function crc32(buf) {
|
||||
let c = 0xffffffff;
|
||||
for (let i = 0; i < buf.length; i++) c = CRC[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function dosTime(date) {
|
||||
const d = date || new Date(Date.UTC(2020, 0, 1));
|
||||
const time = (d.getUTCHours() << 11) | (d.getUTCMinutes() << 5) | (d.getUTCSeconds() >> 1);
|
||||
const day = ((Math.max(1980, d.getUTCFullYear()) - 1980) << 9) | ((d.getUTCMonth() + 1) << 5) | d.getUTCDate();
|
||||
return { time, day };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ name: string, data: Buffer }[]} files names with forward slashes
|
||||
* @param {{ date?: Date }} [options] one date for every entry, so the same input gives the same archive
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
function zip(files, options) {
|
||||
const { time, day } = dosTime(options && options.date);
|
||||
const parts = [];
|
||||
const central = [];
|
||||
let offset = 0;
|
||||
const seen = new Set();
|
||||
for (const f of files) {
|
||||
if (!f.name || f.name.startsWith('/') || f.name.includes('\\') || f.name.split('/').includes('..')) throw new Error('bad name in archive: ' + f.name);
|
||||
if (seen.has(f.name)) throw new Error('twice in archive: ' + f.name);
|
||||
seen.add(f.name);
|
||||
const name = Buffer.from(f.name, 'utf8');
|
||||
const data = Buffer.isBuffer(f.data) ? f.data : Buffer.from(f.data);
|
||||
const packed = zlib.deflateRawSync(data, { level: 9 });
|
||||
const stored = packed.length >= data.length;
|
||||
const body = stored ? data : packed;
|
||||
const crc = crc32(data);
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4); // version needed
|
||||
local.writeUInt16LE(0x0800, 6); // names are UTF-8
|
||||
local.writeUInt16LE(stored ? 0 : 8, 8);
|
||||
local.writeUInt16LE(time, 10);
|
||||
local.writeUInt16LE(day, 12);
|
||||
local.writeUInt32LE(crc, 14);
|
||||
local.writeUInt32LE(body.length, 18);
|
||||
local.writeUInt32LE(data.length, 22);
|
||||
local.writeUInt16LE(name.length, 26);
|
||||
local.writeUInt16LE(0, 28);
|
||||
parts.push(local, name, body);
|
||||
const entry = Buffer.alloc(46);
|
||||
entry.writeUInt32LE(0x02014b50, 0);
|
||||
entry.writeUInt16LE(20, 4); // made by
|
||||
entry.writeUInt16LE(20, 6);
|
||||
entry.writeUInt16LE(0x0800, 8);
|
||||
entry.writeUInt16LE(stored ? 0 : 8, 10);
|
||||
entry.writeUInt16LE(time, 12);
|
||||
entry.writeUInt16LE(day, 14);
|
||||
entry.writeUInt32LE(crc, 16);
|
||||
entry.writeUInt32LE(body.length, 20);
|
||||
entry.writeUInt32LE(data.length, 24);
|
||||
entry.writeUInt16LE(name.length, 28);
|
||||
entry.writeUInt32LE(offset, 42);
|
||||
central.push(entry, name);
|
||||
offset += local.length + name.length + body.length;
|
||||
}
|
||||
const dir = Buffer.concat(central);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(files.length, 8);
|
||||
end.writeUInt16LE(files.length, 10);
|
||||
end.writeUInt32LE(dir.length, 12);
|
||||
end.writeUInt32LE(offset, 16);
|
||||
return Buffer.concat([...parts, dir, end]);
|
||||
}
|
||||
|
||||
/** The entries of an archive, each checked against its checksum. */
|
||||
function unzip(buf) {
|
||||
let end = -1;
|
||||
for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) {
|
||||
if (buf.readUInt32LE(i) === 0x06054b50) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (end < 0) throw new Error('not a zip archive');
|
||||
const count = buf.readUInt16LE(end + 10);
|
||||
let at = buf.readUInt32LE(end + 16);
|
||||
const out = [];
|
||||
for (let n = 0; n < count; n++) {
|
||||
if (buf.readUInt32LE(at) !== 0x02014b50) throw new Error('damaged archive directory');
|
||||
const method = buf.readUInt16LE(at + 10);
|
||||
const crc = buf.readUInt32LE(at + 16);
|
||||
const packedSize = buf.readUInt32LE(at + 20);
|
||||
const size = buf.readUInt32LE(at + 24);
|
||||
const nameLength = buf.readUInt16LE(at + 28);
|
||||
const extra = buf.readUInt16LE(at + 30);
|
||||
const comment = buf.readUInt16LE(at + 32);
|
||||
const local = buf.readUInt32LE(at + 42);
|
||||
const name = buf.toString('utf8', at + 46, at + 46 + nameLength);
|
||||
if (buf.readUInt32LE(local) !== 0x04034b50) throw new Error('damaged entry: ' + name);
|
||||
const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
|
||||
const body = buf.subarray(start, start + packedSize);
|
||||
const data = method === 0 ? Buffer.from(body) : zlib.inflateRawSync(body);
|
||||
if (data.length !== size || crc32(data) !== crc) throw new Error('checksum of ' + name + ' differs');
|
||||
out.push({ name, data });
|
||||
at += 46 + nameLength + extra + comment;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = { zip, unzip, crc32 };
|
||||
Reference in new issue
Block a user