diff --git a/nvim/doc/llembas.txt b/nvim/doc/llembas.txt index 27143f2..b289ba9 100644 --- a/nvim/doc/llembas.txt +++ b/nvim/doc/llembas.txt @@ -97,7 +97,7 @@ COMMANDS *llembas-commands* a picker with presets and a custom token count input. :LLeMbasAutocompleteInstructions [text|-] *:LLeMbasAutocompleteInstructions* - Set custom instructions sent with autocomplete requests ("-" clears them). + Your own instructions for suggestions ("-" clears them). :LLeMbasAutocompleteModel[!] [model] *:LLeMbasAutocompleteModel* The model that writes suggestions, saved in your account; without a name, @@ -129,13 +129,17 @@ COMMANDS *llembas-commands* Toggle showing model thinking in the transcript. :LLeMbasOpen *:LLeMbasOpen* - Open the file the agent showed last with the system's viewer. + Open the file the agent showed last. Only a picture, a PDF, sound, video + or plain text, and only when the file's first bytes are what its name + says: plain text opens here (read-only), the rest in the system's + viewer. Anything else is named and left alone. :LLeMbasStop *:LLeMbasStop* Stop the running turn. :LLeMbasNew[!] *:LLeMbasNew* - Start a new session (! ends a hung turn). Old sessions stay in the CLI. + Start a new session (! also ends the agent when a turn hangs). Old + sessions stay in the CLI. :LLeMbasMode [mode] *:LLeMbasMode* Change the session's mode (works live mid-turn); without an arg, pick. @@ -303,6 +307,11 @@ require("llembas").prompt({opts}) *llembas.prompt() |:LLeMbasPrompt|: `intent`, `first`, `last`, `attach = false`. require("llembas").intent([{name}]) *llembas.intent()* Set, and return, what in the prompt will do. +require("llembas").cli() *llembas.cli()* + The command that starts the agent, as a list, or nil and why: `cmd` as + set, and a bare `lembas` that is not on this editor's PATH where the + CLI's installer puts it (~/.local/bin). The one place that decides + whether the LLeMbas CLI is installed. require("llembas").effort([{level}]) .ai([{on}]) .autocomplete([{on}]) require("llembas").cycle_mode() .menu() As the commands of those names. @@ -328,6 +337,51 @@ What is remembered *llembas-remembered* autocomplete and main model are your account's (|:LLeMbasAutocompleteModel|, |:LLeMbasMainModel|). + After |:cd| the new directory's own hold: the mode and the effort a + session starts with, LLeMbas and suggestions on or off. + +============================================================================== +WHAT IS SENT *llembas-privacy* + +Everything goes to the LLeMbas CLI on this computer, and from there to your +LLeMbas server: nowhere else. + +What you send the message you type; lines you ask about, have + explained or rewritten; a file you name with @. +With a message the name of the file you are in, the cursor's line, the + lines that came along, the diagnostics on them, and the + NAMES (not the text) of the other open files + (`send_open_file = false`: none of this). +With a suggestion the text around the cursor (up to 400 lines before it + and 100 after), the file's name and type, and the TEXT + of up to six other open files (the first 400 lines of + each), of which the CLI puts pieces beside it. + +What goes along without your pointing at it — the other files' names and +text — is held to three rules: + +1. Only files inside the working directory (|:pwd|). +2. Never a file that looks like it holds secrets, by its name or its place: + `.env` and `.env.*` (but not `.env.example`, `.env.sample`, + `.env.template`), `*.env`, `*.pem`, `*.key`, `*.p12`, `*.pfx`, `*.jks`, + `*.keystore`, `*.ppk`, `*.kdbx`, `id_rsa*`, `id_ed25519*`, `id_ecdsa*`, + `id_dsa*`, `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`, + `.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and + anything under `.ssh/`, `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or + `.azure/`. +3. Never a file the project's .gitignore leaves out (git is asked, once a + file; a file git has not answered for yet is left out). + +In a file that looks like it holds secrets no suggestion is asked for at +all, so nothing of it is sent; that is said once. A file the project +ignores, or one outside the working directory, still gets suggestions while +you type in it: its own text around the cursor is what a suggestion is made +from. + +The agent itself reads and writes files as a turn needs them, under the +CLI's permissions; that is the CLI's to allow or ask about, and is not +limited by the rules above. |:LLeMbasAI| off sends nothing at all. + ============================================================================== WHEN SOMETHING IS WRONG *llembas-trouble* diff --git a/nvim/lua/llembas/complete.lua b/nvim/lua/llembas/complete.lua index 0b0b9c8..4a67a86 100644 --- a/nvim/lua/llembas/complete.lua +++ b/nvim/lua/llembas/complete.lua @@ -4,7 +4,7 @@ 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, last_warm = nil, installed = false } +local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil, installed = false, said_private = {} } local PREFIX_MAX, SUFFIX_MAX = 16000, 4000 -- Refusals that stay true until something is changed: said once, and typing asks no more. @@ -136,15 +136,25 @@ local function usable(buf) return vim.bo[buf].buftype == "" and vim.bo[buf].modifiable end ---- Collect up to 6 other loaded file buffers' text so the CLI can prefer unsaved open buffers ---- for session-aware autocomplete context. +--- Whether `buf` is a file that looks like it holds secrets: no suggestion is asked for in it, +--- so that nothing of it is sent. +function M.private(buf) + local name = vim.api.nvim_buf_get_name(buf) + return name ~= "" and require("llembas.private").looks_secret(name) +end + +--- The text of up to six other open files (the first 400 lines of each), which the CLI may put +--- pieces of beside the text around the cursor. Only files of this project, and never one that +--- looks like it holds secrets or that the project's .gitignore leaves out (|llembas-privacy|). local function open_snippets(exclude_buf) + local private = require("llembas.private") + local roots = private.roots() local out = {} for _, b in ipairs(vim.api.nvim_list_bufs()) do if #out >= 6 then break end if b ~= exclude_buf and vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then local name = vim.api.nvim_buf_get_name(b) - if name ~= "" then + if name ~= "" and private.may_send(name, roots) then local text = table.concat(vim.api.nvim_buf_get_lines(b, 0, 400, false), "\n") if #text > 0 and #text <= 32768 then out[#out + 1] = { path = name, text = text } @@ -162,7 +172,7 @@ function M.warm(buf) local conn = L()._state.conn if not conn or not L()._state.ready or not L()._state.caps.editor then return end local name = vim.api.nvim_buf_get_name(buf) - if name == "" then return end + if name == "" or require("llembas.private").looks_secret(name) then return end local cwd = vim.fn.getcwd() local key = (L()._state.session or "") .. "|" .. cwd .. "|" .. name if st.last_warm == key then return end @@ -184,6 +194,14 @@ function M.request(manual) if manual then say("no suggestion: LLeMbas is off", true) end return end + if M.private(buf) then + -- Said once a file, and again when it is asked for by hand. + if manual or not st.said_private[buf] then + st.said_private[buf] = true + say("no suggestions in this file: its name says it may hold secrets, so nothing of it is sent", true) + end + 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] @@ -209,7 +227,7 @@ function M.request(manual) return end if not L()._state.caps.editor then - st.off = "this LLeMbas CLI has no autocomplete yet. Update the CLI." + st.off = L()._words.too_old st.why = st.off if manual or not st.said then st.said = true @@ -337,8 +355,14 @@ local function typed() M.clear() local c = L().config.complete if not c.auto or st.off or L()._state.ai == false 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 + local buf = vim.api.nvim_get_current_buf() + if not usable(buf) then return end cancel() + -- A file that is never sent asks for nothing; that is said once, when typing in it begins. + if M.private(buf) then + if not st.said_private[buf] then M.request(false) end + return + end 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 diff --git a/nvim/lua/llembas/context.lua b/nvim/lua/llembas/context.lua index 69c8e5e..51a28fc 100644 --- a/nvim/lua/llembas/context.lua +++ b/nvim/lua/llembas/context.lua @@ -85,6 +85,10 @@ function M.editor(buf, first, last) end end if #diags > 0 then out.diagnostics = diags end + -- The other open files, by name: only files of this project, never one that looks like it + -- holds secrets or that the project's .gitignore leaves out (|llembas-privacy|). + local private = require("llembas.private") + local roots = private.roots() local open = {} local seen = {} if name then seen[name] = true end @@ -92,7 +96,7 @@ function M.editor(buf, first, last) if #open >= 30 then break end if b ~= buf and vim.api.nvim_buf_is_loaded(b) and vim.bo[b].buftype == "" then local p = vim.api.nvim_buf_get_name(b) - if p ~= "" and not seen[p] then + if p ~= "" and not seen[p] and private.may_send(p, roots) then seen[p] = true open[#open + 1] = p end diff --git a/nvim/lua/llembas/init.lua b/nvim/lua/llembas/init.lua index 4032c61..51531e5 100644 --- a/nvim/lua/llembas/init.lua +++ b/nvim/lua/llembas/init.lua @@ -56,10 +56,17 @@ end --- A version as numbers: `2.0.0-beta.10` is newer than `2.0.0-beta.9`, and `2.0.0` newer than both. local function version_key(v) - local core, pre = tostring(v or ""):gsub("%+.*$", ""):match("^v?([%d%.]+)%-?(.*)$") - if not core then return nil end + -- Digits and dots, then perhaps `-` and a pre-release name, then perhaps `+` and build words: + -- anything else ("1.2.3junk") is no version. The VS Code extension reads it the same way + -- (vscode/src/words.js); tests/rules/versions.json holds the cases both must answer alike. + local s = vim.trim(tostring(v == nil and "" or v)):gsub("^v", "", 1):gsub("%+.*$", "", 1) + local core, pre = s:match("^(%d[%d%.]*)%-([%w%.%-]+)$") + if not core then core, pre = s:match("^(%d[%d%.]*)$"), "" end + if not core or core:find("..", 1, true) or core:sub(-1) == "." then return nil end local key = {} - for n in core:gmatch("%d+") do key[#key + 1] = tonumber(n) end + for n in core:gmatch("%d+") do + if #key < 3 then key[#key + 1] = tonumber(n) end + end while #key < 3 do key[#key + 1] = 0 end -- A release is above its pre-releases; among those the name (alpha, beta, rc) then the number. key[4] = pre == "" and 1 or 0 @@ -95,6 +102,9 @@ local WORDS = { client_too_old = "The LLeMbas server needs a newer LLeMbas CLI; update the CLI (lembas update)", not_allowed = "The server does not allow that", busy = "The server is busy; try again in a moment", + -- Said by the editor itself, in one wording wherever it applies. + working = "LLeMbas is still working. Stop it first (:LLeMbasStop).", + too_old = "This LLeMbas CLI is too old for that. Update it: lembas update", } local WHOLE = { not_logged_in = true, signed_out = true } local SERVER_SAYS = { not_allowed = true, busy = true } @@ -553,8 +563,8 @@ local function on_plan(p, reply) pcall(vim.cmd, "stopinsert") local actions = { { id = "dismiss", label = "Dismiss" }, - { id = "approve_edit", label = "Approve (edit mode)" }, - { id = "approve_manual", label = "Approve (manual mode)" }, + { id = "approve_edit", label = "Approve: edit without asking" }, + { id = "approve_manual", label = "Approve: ask before each edit" }, { id = "revise", label = "Revise with feedback" }, } vim.ui.select(actions, { @@ -569,11 +579,11 @@ local function on_plan(p, reply) return reply({ outcome = "dismissed" }) end if choice.id == "approve_edit" then - chat.line(id, "- ✓ plan approved (edit mode)", "LLeMbasToolDone") + chat.line(id, "- ✓ plan approved: edits without asking", "LLeMbasToolDone") return reply({ outcome = "approve", mode = "edit" }) end if choice.id == "approve_manual" then - chat.line(id, "- ✓ plan approved (manual mode)", "LLeMbasToolDone") + chat.line(id, "- ✓ plan approved: asks before each edit", "LLeMbasToolDone") return reply({ outcome = "approve", mode = "manual" }) end vim.ui.input({ prompt = "Plan revision feedback: " }, function(fb) @@ -618,8 +628,11 @@ local function stopped(code, stderr, signal) status() end ---- The command that starts the agent: as set; a bare `lembas` that is not on this editor's PATH is ---- looked for where the CLI's installer puts it. Returns the command, or nil and why. +--- The command that starts the agent, as a list: `cmd` as set; a bare `lembas` that is not on +--- this editor's PATH is looked for where the CLI's installer puts it (`~/.local/bin`). Returns +--- the command, or nil and why. This is the one place that decides whether the LLeMbas CLI is +--- installed: `require("llembas").cli()` is what a configuration asks (LLeMbas IDE does), and +--- the IDE's launcher keeps the same rule in shell (scripts/test-ide.sh holds the two together). local function agent_command() local cmd = vim.list_slice(M.config.cmd) local exe = cmd[1] @@ -850,12 +863,15 @@ local function send(blocks, shown, meta) status() ensure(function(ok) if not ok then S.busy = false; status(); return end - S.conn:request("session/prompt", { sessionId = S.session, prompt = blocks, _meta = meta }, function(err, r) + local conn = S.conn + conn:request("session/prompt", { sessionId = S.session, prompt = blocks, _meta = meta }, function(err, r) + -- An agent that was replaced meanwhile (a new session, a restart) answers into nothing: + -- the turn that may be running now is its successor's, and is not ended by this. + if S.conn ~= conn then return end S.busy = false S.progress = nil if err then - -- An agent that stopped has said so itself; anything else is the turn's own failure. - if S.conn then note("The turn failed: " .. words(err), "error") end + note("The turn failed: " .. words(err), "error") else local lm = (r and r._meta and r._meta.lembas) or {} -- The failure as the answer carries it, unless the event has said it already. @@ -960,14 +976,14 @@ local function send_typed(text) if S.intent ~= "ask" and not text:match("^/") then return send_intent(text) end if S.busy then if S.conn and S.session and S.caps.steer then - chat.section("You (while working)", "LLeMbasUserHeader") + chat.section("You (sent while working)", "LLeMbasUserHeader") chat.append(text .. "\n") S.conn:request("_lembas/steer", { sessionId = S.session, text = text }, function(err) if err then note("Not sent to the running turn: " .. words(err), "error") end end, 15000) return true end - vim.notify("LLeMbas is still working on the last message (:LLeMbasStop stops it)", vim.log.levels.WARN) + vim.notify(WORDS.working, vim.log.levels.WARN) return false end if not S.ai then @@ -1127,9 +1143,7 @@ function M.edit(first, last, instruction) 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 + if S.busy then return vim.notify(WORDS.working, 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 " @@ -1154,7 +1168,7 @@ function M.generate(instruction) return connect(function(ok) if ok then M.generate(instruction) end end) end if not S.caps.editor then - return vim.notify("LLeMbas: this LLeMbas CLI does not support inline generation yet", vim.log.levels.WARN) + return vim.notify("LLeMbas: " .. WORDS.too_old, vim.log.levels.WARN) end local row = vim.api.nvim_win_get_cursor(0)[1] require("llembas.diff").generate(buf, row, instruction) @@ -1201,7 +1215,7 @@ end --- A new session; the old one stays in the CLI's store. 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) + return vim.notify(WORDS.working .. " :LLeMbasNew! ends the agent instead.", vim.log.levels.WARN) end S.busy = false local conn = S.conn @@ -1219,7 +1233,7 @@ function M.new(force) end function M.compact() - if S.busy then return vim.notify("LLeMbas is working; wait for the turn to finish", vim.log.levels.WARN) end + if S.busy then return vim.notify(WORDS.working, vim.log.levels.WARN) end if not S.session or not S.conn then return vim.notify("LLeMbas: no active session to compact", vim.log.levels.INFO) end S.conn:request("_lembas/session/compact", { sessionId = S.session }, function(err, r) if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end @@ -1344,7 +1358,7 @@ function M.commands() pick_cmd(out) end, 30000) else - vim.notify("LLeMbas: this CLI does not list slash commands", vim.log.levels.INFO) + vim.notify("LLeMbas: " .. WORDS.too_old, vim.log.levels.INFO) end end) end @@ -1387,14 +1401,14 @@ end --- List previous sessions in this project and resume one with its history (`_lembas/sessions/list` & `resume`). function M.sessions() - if S.busy then return vim.notify("LLeMbas is working; stop it first (:LLeMbasStop)", vim.log.levels.WARN) end + if S.busy then return vim.notify(WORDS.working, vim.log.levels.WARN) end connect(function(ok) if not ok then return end - if not S.caps.sessions then return vim.notify("LLeMbas: this LLeMbas CLI cannot list its sessions here yet. Update the CLI.", vim.log.levels.WARN) end + if not S.caps.sessions then return vim.notify("LLeMbas: " .. WORDS.too_old, vim.log.levels.WARN) end local conn = S.conn conn:request("_lembas/sessions/list", { cwd = S.cwd or vim.fn.getcwd(), limit = 40 }, function(err, r) if err then - if err.code == -32601 then return vim.notify("LLeMbas: this LLeMbas CLI cannot list its sessions here yet. Update the CLI.", vim.log.levels.WARN) end + if err.code == -32601 then return vim.notify("LLeMbas: " .. WORDS.too_old, vim.log.levels.WARN) end return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end local list = (r and r.sessions) or {} @@ -1463,7 +1477,7 @@ 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 + if not S.caps.editor then return vim.notify("LLeMbas: " .. WORDS.too_old, 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: " .. words(err), vim.log.levels.ERROR) end cb(r or {}) @@ -1474,7 +1488,7 @@ end local function pick(which, cb) connect(function(ok) if not ok then return end - if not S.caps.editor then return vim.notify("LLeMbas: this LLeMbas CLI does not list models yet", vim.log.levels.WARN) end + if not S.caps.editor then return vim.notify("LLeMbas: " .. WORDS.too_old, vim.log.levels.WARN) end S.conn:request("_lembas/models", vim.empty_dict(), function(err, r) if err then return vim.notify("LLeMbas: " .. words(err), vim.log.levels.ERROR) end local items = {} @@ -1581,26 +1595,32 @@ function M._show(p, reply) 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 - +--- Open the file the agent showed last. Only files that are merely looked at or listened to +--- (pictures, PDF, sound, video, plain text), and only when the file's first bytes are what its +--- name says (|llembas.shown|, the rule the VS Code extension keeps too): plain text opens here, +--- the rest in the system's viewer. Anything else — a script, a page, a shortcut, a document +--- that can carry macros, a name the bytes do not back — is named and left alone. 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) + local shown = require("llembas.shown") + local kind = shown.openable(shown.head(S.shown), S.shown) + if not kind then + return vim.notify("LLeMbas: not opened. Only pictures, PDF, sound, video and plain text are, and only when the file is what its name says: " + .. S.shown, vim.log.levels.WARN) + end + if kind == "text" then + local target = editing_win() + if target then + return vim.api.nvim_win_call(target, function() pcall(vim.cmd, "keepalt view " .. vim.fn.fnameescape(S.shown)) end) + end end vim.ui.open(S.shown) 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) + vim.notify(("LLeMbas: the autocomplete model is %s%s; the chat and rewrite model is %s"):format(a.model or "not chosen", + a.source and (" (" .. a.source .. ")") or "", m.model or "the one a session starts on"), vim.log.levels.INFO) end --- The model that writes suggestions. No name: pick from the list. `quick`: for this editor only, @@ -1627,24 +1647,22 @@ function M.main_model(name) pick("main", set) end ---- Configure autocomplete max tokens & length scope preset interactively or by argument. +--- How much a suggestion writes: a length, or a number of tokens; picked from a list without an argument. function M.autocomplete_tokens(arg) local complete = require("llembas.complete") local presets = { - { id = "auto", tokens = 0, label = "Server default (auto)" }, - { id = "words", tokens = 24, label = "Few words — ~24 tokens (current expression)" }, - { id = "line", tokens = 64, label = "Single line — ~64 tokens (finish current line)" }, - { id = "block", tokens = 256, label = "Function / block — ~256 tokens" }, - { id = "file", tokens = 2048, label = "Large / full file — ~2048 tokens" }, - { id = "custom", tokens = nil, label = "Custom max tokens number…" }, + { id = "auto", tokens = 0, label = "As the server sets it" }, + { id = "words", tokens = 24, label = "A few words (about 24 tokens)" }, + { id = "line", tokens = 64, label = "One line (about 64 tokens)" }, + { id = "block", tokens = 256, label = "A function or block (about 256 tokens)" }, + { id = "file", tokens = 2048, label = "A long passage (about 2048 tokens)" }, + { id = "custom", tokens = nil, label = "A number of tokens of your own…" }, } local function apply(length, tokens) if length then M.config.complete.length = length end M.config.complete.max_tokens = (tokens and tokens > 0) and math.min(4096, math.floor(tokens)) or nil complete.reset() - vim.notify(("LLeMbas: autocomplete scope=%s, max_tokens=%s"):format( - M.config.complete.length or "auto", - M.config.complete.max_tokens and tostring(M.config.complete.max_tokens) or "default"), vim.log.levels.INFO) + vim.notify("LLeMbas: suggestions: " .. M._length_words(), vim.log.levels.INFO) end if arg and arg ~= "" then local n = tonumber(arg) @@ -1652,16 +1670,15 @@ function M.autocomplete_tokens(arg) for _, p in ipairs(presets) do if p.id == arg and p.id ~= "custom" then return apply(p.id, p.tokens) end end - return vim.notify("LLeMbas: use a number (0..4096) or auto|words|line|block|file", vim.log.levels.WARN) + return vim.notify("LLeMbas: a number of tokens (0 to 4096), or one of auto, words, line, block, file", vim.log.levels.WARN) end vim.ui.select(presets, { - prompt = ("LLeMbas autocomplete length (now: %s, %s tokens)"):format( - M.config.complete.length or "auto", M.config.complete.max_tokens or "default"), + prompt = ("LLeMbas: how much a suggestion writes (now: %s)"):format(M._length_words()), format_item = function(p) return p.label end, }, function(choice) if not choice then return end if choice.id == "custom" then - return vim.ui.input({ prompt = "Max tokens (0 for server default, up to 4096): " }, function(val) + return vim.ui.input({ prompt = "At most how many tokens (0: as the length says; up to 4096): " }, function(val) local n = tonumber(val or "") if n then apply(nil, n) end end) @@ -1670,25 +1687,32 @@ function M.autocomplete_tokens(arg) end) end ---- Configure custom autocomplete instructions (or "-" to clear). +--- Your own instructions for suggestions ("-" clears them). function M.autocomplete_instructions(arg) local function apply(text) M.config.complete.instructions = (text == "-" or not text) and "" or vim.trim(text) require("llembas.complete").reset() - vim.notify("LLeMbas: autocomplete instructions " .. (M.config.complete.instructions ~= "" and ("set: " .. M.config.complete.instructions) or "cleared"), vim.log.levels.INFO) + vim.notify("LLeMbas: your instructions for suggestions are " .. (M.config.complete.instructions ~= "" and ("now: " .. M.config.complete.instructions) or "cleared"), vim.log.levels.INFO) end if arg and arg ~= "" then return apply(arg) end - vim.ui.input({ prompt = "Autocomplete instructions (empty or '-' to clear): ", default = M.config.complete.instructions or "" }, function(val) + vim.ui.input({ prompt = "Your instructions for suggestions (empty or '-' clears them): ", default = M.config.complete.instructions or "" }, function(val) if val ~= nil then apply(val) end end) end +--- How much a suggestion writes, in words: "one line, at most 64 tokens". +function M._length_words() + local c = M.config.complete + local names = { auto = "as the server sets it", words = "a few words", line = "one line", block = "a function or block", file = "a long passage" } + local text = names[c.length or "auto"] or tostring(c.length) + if c.max_tokens then text = text .. ", at most " .. tostring(c.max_tokens) .. " tokens" end + return text +end + --- Floating status overview card (`:LLeMbasStatus`). function M.status_popup() ui.setup_highlights() local c = M.config.complete - local caps = vim.tbl_keys(S.caps) - table.sort(caps) local lines = { "◈ LLeMbas " .. M.version, "──────────────────────────────────────────", @@ -1700,15 +1724,14 @@ function M.status_popup() "Mode: " .. (S.mode or "—"), "Model: " .. (S.model or "—"), "Busy: " .. (S.busy and (S.progress or "working") or "no"), - "Usage: " .. (S.usage and ("↑" .. ui.format_tokens(S.usage.input) .. " ↓" .. ui.format_tokens(S.usage.output)) or "—"), + "Tokens: " .. (S.usage and (ui.format_tokens(S.usage.input) .. " sent, " .. ui.format_tokens(S.usage.output) + .. " received (every request of this session added up)") or "—"), "", - "Autocomplete: " .. (c.auto and "on" or "off") .. " (debounce " .. tostring(c.debounce_ms) .. "ms)" + "Autocomplete: " .. (c.auto and "on" or "off") .. " (after a pause of " .. tostring(c.debounce_ms) .. " ms)" .. (require("llembas.complete").why() and ("\n no suggestions: " .. require("llembas.complete").why()) or ""), - "Scope / Cap: " .. (c.length or "auto") .. " · " .. (c.max_tokens and (tostring(c.max_tokens) .. " tokens") or "server default"), + "Length: " .. M._length_words(), "Instructions: " .. ((c.instructions and c.instructions ~= "") and c.instructions or "(none)"), - "Window model: " .. (c.model or "(account default)"), - "", - "Capabilities: " .. (#caps > 0 and table.concat(caps, ", ") or "(not connected yet)"), + "Model here only: " .. (c.model or "(none: the one saved in your account)"), } ui.float("LLeMbas Status", lines, { border = M.config.border }) end @@ -1717,11 +1740,11 @@ end function M.help() ui.setup_highlights() local lines = { - "◈ LLeMbas IDE — Commands & Keys", + "◈ LLeMbas — commands and keys", "───────────────────────────────────────────────", "Panel:", " :LLeMbas Toggle chat panel", - " :LLeMbasNew[!] New session (! kills hung turn)", + " :LLeMbasNew[!] New session (! also ends the agent)", " :LLeMbasSessions Resume a previous session", " :LLeMbasCompact Compact session context", " :LLeMbasStop Stop running turn", @@ -1918,7 +1941,7 @@ function M.choices(id, cb) if id == "model" then return connect(function(ok) if not ok then return cb(nil, S.start_error or "the agent did not start") end - if not S.caps.editor then return cb(nil, "this LLeMbas CLI does not list models") end + if not S.caps.editor then return cb(nil, WORDS.too_old) end S.conn:request("_lembas/models", vim.empty_dict(), function(err, r) if err then return cb(nil, words(err)) end local out = {} @@ -2003,6 +2026,7 @@ function M.setup(opts) store.enabled = M.config.remember ~= false kept = nil -- What was switched off here before stays off; what the settings switch off is never switched on. + S.auto_set = M.config.complete.auto == true local r = remembered() if r.ai == false then S.ai = false end if r.autocomplete ~= nil and M.config.complete.auto then M.config.complete.auto = r.autocomplete end @@ -2042,6 +2066,7 @@ M._status = status M._state = S -- for the tests M._words = WORDS M._say = words +M.cli = agent_command M._command = agent_command vim.api.nvim_create_autocmd("VimLeavePre", { @@ -2059,7 +2084,46 @@ vim.api.nvim_create_autocmd({ "FileChangedShellPost", "BufReadPost" }, { }) 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, + callback = function(ev) + if vim.bo[ev.buf].buftype ~= "" then return end + S.last_buf = ev.buf + -- Whether the project's .gitignore leaves this file out is asked now, so that it is known by + -- the time something would send the file's name or a piece of it along (|llembas-privacy|). + local name = vim.api.nvim_buf_get_name(ev.buf) + local private = require("llembas.private") + if name ~= "" and private.inside(name, private.roots()) and not private.looks_secret(name) then private.ignored(name) end + end, +}) +vim.api.nvim_create_autocmd("BufWritePost", { + group = "llembas", + pattern = ".gitignore", + callback = function() require("llembas.private").forget() end, +}) +-- Another working directory: what is remembered is per directory, so it is read again — the +-- mode and the effort a session starts with, and LLeMbas and suggestions on or off. +vim.api.nvim_create_autocmd("DirChanged", { + group = "llembas", + callback = function() + if vim.v.event.scope ~= "global" then return end + require("llembas.private").forget() + kept = nil + local r = remembered() + local ai = r.ai ~= false + if ai ~= S.ai then + S.ai = ai + if not ai then + pcall(function() require("llembas.complete").dismiss() end) + pcall(function() require("llembas.diff").cancel() end) + M.restart(true) + end + end + -- What the settings switch off is never switched on. + if S.auto_set then + local auto = r.autocomplete ~= false + if auto ~= (M.config.complete.auto == true) then require("llembas.complete").auto(auto) end + end + status() + end, }) return M diff --git a/nvim/lua/llembas/login.lua b/nvim/lua/llembas/login.lua index 32ac538..2fc9418 100644 --- a/nvim/lua/llembas/login.lua +++ b/nvim/lua/llembas/login.lua @@ -23,6 +23,34 @@ local function events_of(text) end M._events_of = events_of +--- A reader of `lembas login --json`'s output as it arrives: `feed(data)` takes the pieces, and +--- `on_event(ev)` is called for every event on a line that has ended. A line cut in two by the +--- pipe is one line; what has no line break yet is not read. The same reading as the VS Code +--- extension's (vscode/src/login.js); tests/rules/login_events.json holds the cases. +local function reader(on_event) + local buf = "" + return function(data) + if not data or data == "" then return end + buf = buf .. data + while true do + local nl = buf:find("\n", 1, true) + if not nl then break end + local line = buf:sub(1, nl - 1) + buf = buf:sub(nl + 1) + for _, ev in ipairs(events_of(line)) do on_event(ev) end + end + end +end +M._reader = reader + +--- A server's address as the person typed it, fit to be one argument of `lembas login`: one +--- word, and never something the program would read as an option. The address, or nil. +function M.address(text) + local s = type(text) == "string" and vim.trim(text) or "" + if s == "" or #s > 2048 or s:find("[%s%c]") or s:sub(1, 1) == "-" then return nil end + return s +end + local function last_line(text) local last = "" for line in tostring(text or ""):gmatch("[^\r\n]+") do if line:match("%S") then last = line end end @@ -50,20 +78,21 @@ function M.current(exe, cb) done = true vim.schedule(function() cb(v) end) end + -- Read by lines, as the sign-in itself is: a `done` cut in two by the pipe must not read as + -- "not signed in", which would let another sign-in replace this one without the question. + local feed = reader(function(ev) + -- A sign-in the server no longer takes is begun anew by the CLI: that it asks for a code + -- says there was one. It is not gone through with here. + if ev.event == "code" and type(ev.instance) == "table" then + finish(ev.instance.base_url) + kill(proc) + elseif ev.event == "done" then finish(ev.base_url) + end + end) local ok ok, proc = pcall(vim.system, { exe, "login", "--json" }, { text = true, - stdout = function(_, data) - -- A sign-in the server no longer takes is begun anew by the CLI: that it asks for a code - -- says there was one. It is not gone through with here. - for _, ev in ipairs(events_of(data)) do - if ev.event == "code" and type(ev.instance) == "table" then - finish(ev.instance.base_url) - kill(proc) - elseif ev.event == "done" then finish(ev.base_url) - end - end - end, + stdout = function(_, data) feed(data) end, timeout = 15000, }, function() finish(nil) end) if not ok then finish(nil) end @@ -86,12 +115,11 @@ local function run(exe, address, ca) if ca and ca ~= "" then vim.list_extend(argv, { "--ca", vim.fn.expand(ca) }) end local me = { cancelled = false } local settled = false - local buf = "" local function on_event(ev) if ev.event == "code" then local where = type(ev.instance) == "table" and (ev.instance.name or ev.instance.base_url) or address local url = ev.verification_uri_complete or ev.verification_uri - L()._note(("To sign in to %s, approve the code %s at %s — the page is being opened in your browser. :LLeMbasLoginCancel stops waiting.") + L()._note(("To sign in to %s, approve the code %s at %s. The page is opened in your browser where there is one; if none opens, go to that address yourself. :LLeMbasLoginCancel stops waiting.") :format(tostring(where), tostring(ev.user_code), tostring(ev.verification_uri))) -- Only a web address is handed to the system, whatever the program printed. if type(url) == "string" and url:match("^https?://[^%s]+$") and vim.ui.open then pcall(vim.ui.open, url) end @@ -110,19 +138,10 @@ local function run(exe, address, ca) L()._note("Not signed in: " .. L()._say({ message = ev.message, code = ev.code }), "error") end end + local feed = reader(function(ev) vim.schedule(function() on_event(ev) end) end) local ok, proc = pcall(vim.system, argv, { text = true, - stdout = function(_, data) - if not data then return end - buf = buf .. data - while true do - local nl = buf:find("\n", 1, true) - if not nl then break end - local line = buf:sub(1, nl - 1) - buf = buf:sub(nl + 1) - for _, ev in ipairs(events_of(line)) do vim.schedule(function() on_event(ev) end) end - end - end, + stdout = function(_, data) feed(data) end, }, function(res) vim.schedule(function() if running == me then running = nil end @@ -150,7 +169,11 @@ function M.login(address, ca) if text and text:match("%S") then M.login(vim.trim(text), ca) end end) end - address = vim.trim(address) + local typed = address + address = M.address(address) + if not address then + return vim.notify(("LLeMbas: %q is not a server's address: one word, such as ai.example.org, and not an option"):format(vim.trim(typed)), vim.log.levels.WARN) + end ca = ca or (L().config.login or {}).ca M.current(exe, function(now) -- The same server again, without a certificate: the CLI reads its login anew and replaces nothing. diff --git a/nvim/lua/llembas/private.lua b/nvim/lua/llembas/private.lua new file mode 100644 index 0000000..44bb40d --- /dev/null +++ b/nvim/lua/llembas/private.lua @@ -0,0 +1,119 @@ +-- What is never sent along by itself: files that look like they hold secrets, files outside the +-- project, and files the project's .gitignore leaves out. Used for what goes with a request +-- without the person having pointed at it: pieces of other open files with a suggestion, and the +-- names of the other open files with a message. The same rules as the VS Code extension's +-- (vscode/src/private.js); tests/rules/private_files.json holds the cases both must answer alike. +local M = {} + +local ENV_EXAMPLES = { [".env.example"] = true, [".env.sample"] = true, [".env.template"] = true } +local NAMES = { + [".netrc"] = true, ["_netrc"] = true, [".npmrc"] = true, [".pypirc"] = true, [".pgpass"] = true, + [".htpasswd"] = true, [".git-credentials"] = true, +} +local ENDINGS = { pem = true, key = true, p12 = true, pfx = true, jks = true, keystore = true, ppk = true, kdbx = true, env = true } +local KEY_NAMES = { "id_rsa", "id_ed25519", "id_ecdsa", "id_dsa" } +local DIRECTORIES = { [".ssh"] = true, [".gnupg"] = true, [".aws"] = true, [".kube"] = true, [".docker"] = true, [".azure"] = true } + +local function parts_of(path) + local out = {} + for part in (tostring(path or ""):gsub("\\", "/")):gmatch("[^/]+") do out[#out + 1] = part:lower() end + return out +end + +--- Whether a file's name or place says it may hold secrets: `.env` and `.env.*` (not the +--- `.example`, `.sample` and `.template` ones), `*.env`, key and certificate stores (`*.pem`, +--- `*.key`, `*.p12`, `*.pfx`, `*.jks`, `*.keystore`, `*.ppk`, `*.kdbx`), SSH key names (`id_rsa*`, +--- `id_ed25519*`, `id_ecdsa*`, `id_dsa*`), `.netrc`, `.npmrc`, `.pypirc`, `.pgpass`, `.htpasswd`, +--- `.git-credentials`, `credentials*`, `secrets.*`, `secret.*`, and anything under `.ssh/`, +--- `.gnupg/`, `.aws/`, `.kube/`, `.docker/` or `.azure/`. +function M.looks_secret(path) + local parts = parts_of(path) + local base = parts[#parts] + if not base then return false end + for i = 1, #parts - 1 do + if DIRECTORIES[parts[i]] then return true end + end + if base == ".env" or (base:sub(1, 5) == ".env." and not ENV_EXAMPLES[base]) then return true end + if NAMES[base] then return true end + local ending = base:match("%.([^.]+)$") + if ending and ENDINGS[ending] then return true end + for _, k in ipairs(KEY_NAMES) do + if base:sub(1, #k) == k then return true end + end + if base:sub(1, 11) == "credentials" then return true end + if base:sub(1, 8) == "secrets." or base:sub(1, 7) == "secret." then return true end + return false +end + +--- A path with `.` and `..` worked out and one kind of slash, or nil when it is not absolute. +local function absolute(path) + local p = tostring(path or ""):gsub("\\", "/") + local drive = p:match("^(%a:)/") or "" + if drive ~= "" then p = p:sub(3) end + if p:sub(1, 1) ~= "/" then return nil end + local out = {} + for part in p:gmatch("[^/]+") do + if part == ".." then table.remove(out) + elseif part ~= "." then out[#out + 1] = part end + end + return drive:lower() .. "/" .. table.concat(out, "/") +end + +--- Whether `path` is a file inside one of the folders `roots` (never a folder itself, and never +--- "inside" the root of the disk). +function M.inside(path, roots) + local p = absolute(path) + if not p then return false end + for _, root in ipairs(roots or {}) do + local r = absolute(root) + if r and r ~= "/" and not r:match("^%a:/$") and p:sub(1, #r + 1) == r .. "/" then return true end + end + return false +end + +local ignored = {} -- path -> true | false | "asking" + +--- Whether the project's .gitignore leaves `path` out: true or false once git has answered, nil +--- while it has not (the question is then on its way; `cb(answer)` is called with it). Without +--- git, or outside a repository, nothing is ignored. Asked once a file. +function M.ignored(path, cb) + local known = ignored[path] + if known == true or known == false then + if cb then cb(known) end + return known + end + if known == "asking" then return nil end + if vim.fn.executable("git") == 0 then + ignored[path] = false + if cb then cb(false) end + return false + end + ignored[path] = "asking" + local ok = pcall(vim.system, { "git", "-C", vim.fs.dirname(path), "check-ignore", "-q", "--", path }, + { text = true, timeout = 5000, env = { GIT_OPTIONAL_LOCKS = "0" } }, function(res) + -- 0: ignored. 1: not. Anything else: no repository there, or git failed. + ignored[path] = res.code == 0 + if cb then vim.schedule(function() cb(ignored[path]) end) end + end) + if not ok then + ignored[path] = false + if cb then cb(false) end + return false + end + return nil +end + +--- A .gitignore changed, or the directory did: what git said before is asked again. +function M.forget() ignored = {} end + +--- The folders that are the project here: the working directory. +function M.roots() return { vim.fn.getcwd() } end + +--- Whether a file other than the one being worked on may go along by itself: inside the +--- project, not secret by its name, and known not to be ignored by the project's .gitignore. +function M.may_send(path, roots) + if not M.inside(path, roots or M.roots()) or M.looks_secret(path) then return false end + return M.ignored(path) == false +end + +return M diff --git a/nvim/lua/llembas/rpc.lua b/nvim/lua/llembas/rpc.lua index aa15f34..6106ad1 100644 --- a/nvim/lua/llembas/rpc.lua +++ b/nvim/lua/llembas/rpc.lua @@ -2,7 +2,7 @@ local M = {} M.__index = M -local MAX_BUF_BYTES = 64 * 1024 * 1024 -- 64 MB cap against an unbounded unterminated stream +local MAX_LINE_BYTES = 64 * 1024 * 1024 -- a line that never ends is dropped, not kept local MAX_ERR_BYTES = 64 * 1024 -- what is kept of the agent's stderr: its end M.KILL_AFTER_MS = 5000 @@ -39,19 +39,25 @@ function M.start(cmd, on, opts) return self end +--- Bytes from the agent. A line longer than the reader keeps is dropped whole: what was read of +--- it, and the rest of it up to its line break — never a message that merely follows it. The +--- same reading as the VS Code extension's (vscode/src/rpc.js); tests/rules/rpc_lines.json. function M:_feed(data) - if #self.buf + #data > MAX_BUF_BYTES then - -- Drop oversized unterminated line rather than exhausting editor memory. - self.buf = "" - return - end self.buf = self.buf .. data while true do local nl = self.buf:find("\n", 1, true) - if not nl then break end + if not nl then + if #self.buf > (self.max_line or MAX_LINE_BYTES) then + self.buf = "" + self.dropping = true -- the rest of that line, when its end comes, is not a message + end + break + end local line = self.buf:sub(1, nl - 1) self.buf = self.buf:sub(nl + 1) - if line:match("%S") then + if self.dropping then + self.dropping = false + elseif line:match("%S") then local ok, msg = pcall(vim.json.decode, line, { luanil = { object = true, array = true } }) if ok and type(msg) == "table" then vim.schedule(function() self:_message(msg) end) @@ -76,7 +82,11 @@ function M:_message(msg) local ok, e = pcall(self.on.request, msg.method, msg.params or {}, reply) if not ok then reply(nil, { code = -32603, message = tostring(e) }) end elseif self.on.notify then - pcall(self.on.notify, msg.method, msg.params or {}) + -- A notification has nobody to tell when it fails here: said where the agent's own words are kept. + local ok, e = pcall(self.on.notify, msg.method, msg.params or {}) + if not ok then + self.err = (self.err .. "[editor] " .. tostring(msg.method) .. " was not taken in: " .. tostring(e):sub(1, 300) .. "\n"):sub(-MAX_ERR_BYTES) + end end elseif msg.id ~= nil then local cb = self.waiting[msg.id] diff --git a/nvim/lua/llembas/shown.lua b/nvim/lua/llembas/shown.lua new file mode 100644 index 0000000..f055966 --- /dev/null +++ b/nvim/lua/llembas/shown.lua @@ -0,0 +1,112 @@ +-- Which files the agent showed may be opened: only kinds that are merely looked at or listened +-- to, and only when the file's first bytes are that kind and its name ends as that kind does (the +-- system picks its program by the name, so a name the bytes do not back is never handed to it). +-- The same rule as the VS Code extension's (vscode/src/media.js); tests/rules/openable.json holds +-- the cases both must answer alike. +local M = {} + +local TEXT_ENDINGS = {} +for _, e in ipairs({ "txt", "text", "log", "md", "markdown", "csv", "tsv", "json", "jsonl", "yaml", "yml", "toml", "ini", "diff", "patch" }) do + TEXT_ENDINGS[e] = true +end + +local function has(list, v) return vim.tbl_contains(list, v) end + +local function picture(b) + if #b < 12 then return nil end + if b:sub(1, 6) == "\137PNG\r\n" then return { "png" } end + if b:sub(1, 3) == "\255\216\255" then return { "jpg", "jpeg" } end + if b:sub(1, 6) == "GIF87a" or b:sub(1, 6) == "GIF89a" then return { "gif" } end + if b:sub(1, 4) == "RIFF" and b:sub(9, 12) == "WEBP" then return { "webp" } end + if b:sub(5, 8) == "ftyp" and (b:sub(9, 12) == "avif" or b:sub(9, 12) == "avis") then return { "avif" } end + return nil +end + +local function brand(b) return b:sub(5, 8) == "ftyp" and b:sub(9, 12) or "" end +local function one_of(v, list) return has(list, v) end + +local KINDS = { + { "pdf", { "pdf" }, function(b) return b:sub(1, 5) == "%PDF-" end }, + { "audio", { "mp3" }, function(b) + return b:sub(1, 3) == "ID3" or (b:byte(1) == 0xff and bit.band(b:byte(2), 0xe6) == 0xe2) + end }, + { "audio", { "wav" }, function(b) return b:sub(1, 4) == "RIFF" and b:sub(9, 12) == "WAVE" end }, + { "audio", { "ogg", "oga", "opus" }, function(b) return b:sub(1, 4) == "OggS" end }, + { "audio", { "flac" }, function(b) return b:sub(1, 4) == "fLaC" end }, + { "audio", { "m4a" }, function(b) return one_of(brand(b), { "M4A ", "M4B ", "mp42", "isom" }) end }, + { "video", { "mp4", "m4v" }, function(b) + local br = brand(b) + return one_of(br, { "isom", "mp41", "mp42", "avc1", "M4V ", "dash" }) or br:match("^iso[2-9]$") ~= nil + end }, + { "video", { "mov" }, function(b) return brand(b) == "qt " end }, + { "video", { "webm", "mkv" }, function(b) return b:sub(1, 4) == "\26\69\223\163" end }, +} + +local function looks_like_text(b) + if #b == 0 then return false end + for i = 1, #b do + local c = b:byte(i) + if c == 0 or (c < 0x20 and c ~= 0x09 and c ~= 0x0a and c ~= 0x0d and c ~= 0x0c) then return false end + end + -- The window may end inside a character; up to three bytes are let go before judging. + for cut = 0, math.min(3, #b - 1) do + if M._valid_utf8(b:sub(1, #b - cut)) then return true end + end + return false +end + +--- Whether `s` is well-formed UTF-8. +function M._valid_utf8(s) + local i, n = 1, #s + while i <= n do + local c = s:byte(i) + local more, low + if c < 0x80 then more = 0 + elseif c >= 0xc2 and c <= 0xdf then more = 1 + elseif c >= 0xe0 and c <= 0xef then more = 2 + elseif c >= 0xf0 and c <= 0xf4 then more = 3 + else return false end + if i + more > n then return false end + for k = 1, more do + low = s:byte(i + k) + if low < 0x80 or low > 0xbf then return false end + end + -- No overlong forms, no surrogates, nothing past U+10FFFF. + local second = more > 0 and s:byte(i + 1) or 0 + if (c == 0xe0 and second < 0xa0) or (c == 0xed and second > 0x9f) or (c == 0xf0 and second < 0x90) or (c == 0xf4 and second > 0x8f) then + return false + end + i = i + more + 1 + end + return true +end + +--- What a shown file is, from its first bytes (`head`, a string) and its name: "image", "pdf", +--- "audio", "video" or "text" when it may be opened, nil when it may only be named. +function M.openable(head, name) + local ending = (tostring(name or ""):match("%.([%w]+)$") or ""):lower() + if type(head) ~= "string" or ending == "" then return nil end + local pic = picture(head) + if pic then return has(pic, ending) and "image" or nil end + local known = false + for _, k in ipairs(KINDS) do + if #head >= 12 and k[3](head) then + if has(k[2], ending) then return k[1] end + known = true + end + end + if known then return nil end -- the bytes are a kind the name does not say + if TEXT_ENDINGS[ending] and looks_like_text(head) then return "text" end + return nil +end + +--- The first bytes of the file at `path`, or nil. +function M.head(path) + local f = io.open(path, "rb") + if not f then return nil end + local b = f:read(4096) + f:close() + return b or "" +end + +return M diff --git a/nvim/plugin/llembas.lua b/nvim/plugin/llembas.lua index 81c9081..74d30ed 100644 --- a/nvim/plugin/llembas.lua +++ b/nvim/plugin/llembas.lua @@ -1,7 +1,7 @@ if vim.g.loaded_llembas then return end vim.g.loaded_llembas = true if vim.fn.has("nvim-0.10") == 0 then - vim.notify("llembas.nvim needs Neovim 0.10 or newer", vim.log.levels.WARN) + vim.notify("LLeMbas needs Neovim 0.10 or newer", vim.log.levels.WARN) return end @@ -63,7 +63,7 @@ cmd("LLeMbasOpen", function() L().open_shown() end, { desc = "LLeMbas: open the cmd("LLeMbasFiles", function(o) L().files(o.args, o.bang) end, { nargs = "?", bang = true, desc = "LLeMbas: search project files and attach @path (! opens file in editor)" }) cmd("LLeMbasOpenFile", function(o) L().files(o.args, true) end, - { nargs = "?", desc = "LLeMbas: open a file from the project index" }) + { nargs = "?", desc = "LLeMbas: open a file of this project" }) cmd("LLeMbasCommands", function() L().commands() end, { desc = "LLeMbas: pick a /command or skill" }) cmd("LLeMbasSessions", function() L().sessions() end, { desc = "LLeMbas: list and resume a previous session" }) cmd("LLeMbasExplain", function(o) L().explain(o.line1, o.line2) end, diff --git a/nvim/tests/child.lua b/nvim/tests/child.lua index 53e3703..4f2123f 100644 --- a/nvim/tests/child.lua +++ b/nvim/tests/child.lua @@ -57,6 +57,10 @@ vim.schedule(function() require("llembas.store").make_default() elseif step == "ai_off" then L.ai(false) + elseif step == "cd" then + -- Another working directory without a restart: what is remembered there holds. + vim.cmd("cd " .. vim.fn.fnameescape((assert(vim.env.CD_TO, "CD_TO")))) + vim.wait(50) end layout.remember_widths() local s, o = L.settings(), layout.options() diff --git a/nvim/tests/layout.lua b/nvim/tests/layout.lua index 4b3480c..a2b8681 100644 --- a/nvim/tests/layout.lua +++ b/nvim/tests/layout.lua @@ -696,6 +696,12 @@ local function run() r = step(dir_a, "ai_off") r = step(dir_a, "look") check("remember: AI off is remembered too", r.ai == false, r) + r = step(dir_b, "cd", { CD_TO = dir_a }) + check("remember: after :cd the new directory's choices hold — AI off, its mode, its suggestions", + r.ai == false and r.mode == "edit" and r.autocomplete == false, r) + r = step(dir_a, "cd", { CD_TO = dir_b }) + check("remember: and :cd back to a directory with AI on turns it on, with that directory's mode", + r.ai == true and r.mode == "plan", r) local f = io.open(state_home .. "/nvim/llembas/settings.json") local stored = f and vim.json.decode(f:read("*a")) or {} if f then f:close() end diff --git a/nvim/tests/rules.lua b/nvim/tests/rules.lua new file mode 100644 index 0000000..086119f --- /dev/null +++ b/nvim/tests/rules.lua @@ -0,0 +1,80 @@ +-- The rules both editors keep, against the cases in tests/rules/ (the VS Code extension reads the +-- same files in vscode/tests/rules.test.js). Run by scripts/test-nvim.sh: +-- nvim --headless -u NONE --cmd "set rtp+=nvim" -l nvim/tests/rules.lua +local here = vim.fn.fnamemodify(debug.getinfo(1, "S").source:sub(2), ":p:h") +local repo = vim.fs.normalize(here .. "/../..") +vim.opt.rtp:append(repo .. "/nvim") + +local failed, ran = 0, 0 +local function check(name, cond, extra) + ran = ran + 1 + if cond then print("ok " .. name) else + failed = failed + 1 + print("FAIL " .. name .. (extra and ("\n " .. tostring(extra)) or "")) + end +end +local function cases(name) + local f = assert(io.open(repo .. "/tests/rules/" .. name .. ".json", "rb")) + local text = f:read("*a") + f:close() + return vim.json.decode(text, { luanil = { object = true, array = true } }) +end +local function unhex(s) return (s:gsub("%x%x", function(h) return string.char(tonumber(h, 16)) end)) end + +local L = require("llembas") +local private = require("llembas.private") +local login = require("llembas.login") +local rpc = require("llembas.rpc") +local shown = require("llembas.shown") + +-- versions +local versions = cases("versions") +for _, c in ipairs(versions.compare) do + check(("versions: %q against %q is %d"):format(c[1], c[2], c[3]), L.compare_versions(c[1], c[2]) == c[3], vim.inspect(L.compare_versions(c[1], c[2]))) + check(("versions: and %q against %q is %d"):format(c[2], c[1], -c[3]), L.compare_versions(c[2], c[1]) == -c[3]) +end +for _, v in ipairs(versions.not_versions) do + check(("versions: %q is no version"):format(v), L.compare_versions(v, "1.0.0") == nil and L.compare_versions("1.0.0", v) == nil) +end + +-- files that are never sent along +local files = cases("private_files") +for _, p in ipairs(files.secret) do check("private: looks secret: " .. p, private.looks_secret(p) == true) end +for _, p in ipairs(files.plain) do check("private: does not look secret: " .. p, private.looks_secret(p) == false) end +for _, c in ipairs(files.inside) do + check(("private: %s inside %s: %s"):format(c[1], vim.inspect(c[2]), tostring(c[3])), private.inside(c[1], c[2]) == c[3]) +end + +-- the server's address +local addresses = cases("server_address") +for _, a in ipairs(addresses.ok) do check(("address: %q is taken"):format(a), login.address(a) == vim.trim(a)) end +for _, a in ipairs(addresses.refused) do check(("address: %q is refused"):format(a), login.address(a) == nil) end + +-- the sign-in's events, in whatever pieces they arrive +for i, c in ipairs(cases("login_events")) do + local got = {} + local feed = login._reader(function(ev) got[#got + 1] = ev.event end) + for _, chunk in ipairs(c.chunks) do feed(chunk) end + check(("login: case %d reads %s"):format(i, vim.inspect(c.events)), vim.deep_equal(got, c.events), vim.inspect(got)) +end + +-- a line longer than the reader keeps +local lines = cases("rpc_lines") +for i, c in ipairs(lines.cases) do + local got = {} + local reader = setmetatable({ buf = "", err = "", max_line = lines.max, on = {} }, rpc) + reader._message = function(_, msg) got[#got + 1] = msg.method end + for _, chunk in ipairs(c.chunks) do reader:_feed(chunk) end + vim.wait(500, function() return #got >= #c.methods end, 5) + vim.wait(20) + check(("rpc: case %d keeps %s"):format(i, vim.inspect(c.methods)), vim.deep_equal(got, c.methods), vim.inspect(got)) +end + +-- what may be opened +for _, c in ipairs(cases("openable")) do + local kind = shown.openable(unhex(c.head), c.name) + check(("open: %s is %s"):format(c.name, tostring(c.kind)), kind == c.kind, tostring(kind)) +end + +print(("RAN %d, failed %d"):format(ran, failed)) +vim.cmd(failed == 0 and "qall!" or "cquit!") diff --git a/nvim/tests/run.lua b/nvim/tests/run.lua index f30ee1b..b29958b 100644 --- a/nvim/tests/run.lua +++ b/nvim/tests/run.lua @@ -168,11 +168,26 @@ check("busy: the header says what the agent is doing", wait(function() return vi type_and_send("one more thing") check("busy: a message typed meanwhile is given to the running turn", wait(function() local s = last_call("_lembas/steer"); return s and s.text == "one more thing" and s.sessionId == L._state.session end) - and has("## You (while working)\n\none more thing"), chat.text()) + and has("## You (sent while working)\n\none more thing"), chat.text()) vim.cmd("LLeMbasStop") check("stop: the turn ends as stopped", idle() and has("> Stopped."), chat.text()) check("stop: the cancel names the session", last_call("session/cancel").sessionId == "ses_test") +-- An agent replaced while it works (:LLeMbasNew!) answers into nothing: the turn of the new one +-- is not ended by the old one's last words. +type_and_send("SLOW") +wait(function() return L._state.busy end) +local old_pid = L._state.conn.proc.pid +vim.cmd("LLeMbasNew!") +type_and_send("SLOW") +wait(function() return L._state.busy and L._state.conn and L._state.conn.proc.pid ~= old_pid end) +note_pid() +check("replaced: the old agent is gone", wait(function() return not alive(old_pid) end, 10000)) +vim.wait(300) +check("replaced: its last answer does not end the new turn", L._state.busy and not has("The turn failed"), chat.text()) +vim.cmd("LLeMbasStop") +check("replaced: the new turn stops as its own", idle() and has("> Stopped."), chat.text()) + -- Mode and model. check("mode: the CLI's own modes are offered", vim.deep_equal(L.mode_ids(), { "manual", "edit", "auto", "plan" }), vim.inspect(L.mode_ids())) vim.cmd("LLeMbasMode edit") @@ -699,6 +714,39 @@ check("autocomplete accept_word: inserts first word and keeps remaining ghost te vim.inspect({ vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1], ghost(obuf) })) C.clear() +-- What goes along by itself: other open files only from the project, never one that looks secret. +local outside_dir = tmp .. "-outside" +vim.fn.mkdir(outside_dir, "p") +local open_files = { inside = tmp .. "/helper.py", secret = tmp .. "/.env", outside = outside_dir .. "/far.py" } +for _, f in pairs(open_files) do + vim.fn.writefile({ "X = 1" }, f) + vim.fn.bufload(vim.fn.bufadd(f)) +end +require("llembas.private").ignored(open_files.inside) +wait(function() return require("llembas.private").ignored(open_files.inside) == false end) +vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf)) +vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "def TWO" }) +vim.api.nvim_win_set_cursor(0, { 1, 7 }) +C.request(true) +wait(function() return ghost(obuf) ~= nil end) +C.clear() +req = last_call("_lembas/complete") +local open_paths = {} +for _, o in ipairs(req and req.open or {}) do open_paths[o.path] = true end +check("privacy: a suggestion takes along an open file of the project, not a secret one, not one outside", + open_paths[open_files.inside] and not open_paths[open_files.secret] and not open_paths[open_files.outside], vim.inspect(req and req.open)) +local sbuf = vim.fn.bufnr(open_files.secret) +vim.api.nvim_win_set_buf(0, sbuf) +local n_before = #calls("_lembas/complete") +said_msgs = {} +C.request(true) +vim.wait(300) +check("privacy: in a file that looks secret no suggestion is asked for, and that is said", + #calls("_lembas/complete") == n_before and was_said("its name says it may hold secrets"), vim.inspect(said_msgs)) +vim.api.nvim_win_set_buf(0, obuf) +for _, f in pairs(open_files) do pcall(vim.cmd, "bwipeout! " .. vim.fn.bufnr(f)) end +vim.fn.delete(outside_dir, "rf") + -- :LLeMbasFix sends buffer diagnostics in _meta.lembas.editor.diagnostics. local d_ns = vim.api.nvim_create_namespace("test-diag") vim.diagnostic.set(d_ns, obuf, { { lnum = 0, col = 0, severity = vim.diagnostic.severity.ERROR, message = "broken syntax", source = "lint" } }) diff --git a/scripts/test-nvim.sh b/scripts/test-nvim.sh index 19c5ab8..ac72030 100755 --- a/scripts/test-nvim.sh +++ b/scripts/test-nvim.sh @@ -2,7 +2,8 @@ # The Neovim plugin's tests: headless, against the stand-in agent (tests/fake_agent.py) and, when its # source is at hand, the LLeMbas CLI itself. Needs nvim 0.10+ and python3. # -# scripts/test-nvim.sh both suites +# scripts/test-nvim.sh all of them +# scripts/test-nvim.sh rules the rules both editors keep, against tests/rules/ # scripts/test-nvim.sh plugin the plugin on its own: chat, rewrite, suggestions, sign-in # scripts/test-nvim.sh layout the bars: top, bottom, tree, right bar, keys, what is remembered # @@ -23,6 +24,10 @@ export TERM=dumb which="${1:-all}" status=0 +if [ "$which" = all ] || [ "$which" = rules ]; then + # The rules both editors keep, against the shared cases in tests/rules/. + nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/rules.lua || status=$? +fi if [ "$which" = all ] || [ "$which" = plugin ]; then nvim --headless -u NONE -i NONE --cmd "set rtp+=nvim" -l nvim/tests/run.lua || status=$? fi diff --git a/tests/fake_agent.py b/tests/fake_agent.py index 74b1d22..c804614 100755 --- a/tests/fake_agent.py +++ b/tests/fake_agent.py @@ -113,6 +113,7 @@ completion = [None] # (client id, Event) of the one completion under way complete_lock = threading.Lock() rewrites = {} # Event -> client id handles = {} # handle -> bytes +deleted = {} # ids of stored sessions that were deleted PREVIOUS = {"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000100000, "created": 1700000000000} @@ -335,10 +336,17 @@ def prompt(msg, s, text): turn = str((((p.get("_meta") or {}).get("lembas") or {}).get("turnId")) or uuid.uuid4()) done = {"turnId": turn} s["working"] = True + + def answer(value): + # The turn is over before its answer is on the wire: a request that follows the answer + # at once (a compact, a delete) must not find the session still working. + s["working"] = False + return result(msg, value) + try: if text.startswith("/compact"): event(sid, {"type": "compacted", "summary": "Compacted 2 turns."}) - return result(msg, {"stopReason": "end_turn", "_meta": {"lembas": {**done, "command": "compact", "summary": "Compacted 2 turns."}}}) + return answer({"stopReason": "end_turn", "_meta": {"lembas": {**done, "command": "compact", "summary": "Compacted 2 turns."}}}) event(sid, {"type": "prompt", "text": text, "turnId": turn}) event(sid, {"type": "task", "state": "start", "turnId": turn}) phase(sid, "waiting_for_model", model=s["model"]) @@ -360,11 +368,11 @@ def prompt(msg, s, text): phase(sid, "failed", reason=why) event(sid, {"type": "task", "state": "end", "turnId": turn}) event(sid, {"type": "done", "reason": "error"}) - return result(msg, {"stopReason": "end_turn", "_meta": {"lembas": {**done, "error": {"code": "unreachable", "message": why}}}}) + return answer({"stopReason": "end_turn", "_meta": {"lembas": {**done, "error": {"code": "unreachable", "message": why}}}}) phase(sid, None) event(sid, {"type": "task", "state": "end", "turnId": turn}) event(sid, {"type": "done", "reason": "cancelled" if stop == "cancelled" else "stop"}) - result(msg, {"stopReason": stop, "_meta": {"lembas": done}}) + answer({"stopReason": stop, "_meta": {"lembas": done}}) finally: s["working"] = False @@ -840,12 +848,12 @@ def handle(msg): if not LOGGED_IN: return result(msg, {"sessions": []}) cwd = p.get("cwd") if isinstance(p.get("cwd"), str) and os.path.isabs(p.get("cwd")) else "/" - return result(msg, {"sessions": [{**PREVIOUS, "root": cwd}]}) + return result(msg, {"sessions": [] if deleted.get(PREVIOUS["id"]) else [{**PREVIOUS, "root": cwd}]}) if method == "_lembas/sessions/resume": sid = str(p.get("sessionId") or "").strip() if not sid: raise Refusal(INVALID_PARAMS, "sessionId is required") - if sid != PREVIOUS["id"] and sid not in sessions: + if (sid != PREVIOUS["id"] or deleted.get(sid)) and sid not in sessions: raise Refusal(INVALID_PARAMS, "no such session") if not LOGGED_IN: raise Refusal(INVALID_PARAMS, NOT_LOGGED_IN_SESSION) @@ -858,6 +866,19 @@ def handle(msg): {"id": "call_2", "name": "bash", "args": "{\"command\":\"make\"}", "output": "make: no rule", "isError": True}]}, {"role": "user", "text": "⏎ the job is done", "turnId": "t2", "machine": True}, {"role": "assistant", "text": "noted", "reasoning": "", "tools": []}]})) + if method == "_lembas/session/delete": + # As the CLI answers it (src/acp/agent.ts `deleteSession`): `{deleted}`, false for a session + # it does not have; one that works is stopped first; nothing is notified on `serve --stdio` + # (`_lembas/session/deleted` goes to the LLeMbas link only). + sid = str(p.get("sessionId") or "") + s = sessions.pop(sid, None) + if s: + s["cancel"].set() + return result(msg, {"deleted": True}) + if sid == PREVIOUS["id"] and LOGGED_IN and not deleted.get(sid): + deleted[sid] = True + return result(msg, {"deleted": True}) + return result(msg, {"deleted": False}) if method.startswith("_lembas/") and not HAS_EDITOR and method.split("/")[1] in ("complete", "edit", "models", "editor", "show"): if is_request: raise Refusal(METHOD_NOT_FOUND, "Method not found: " + method) diff --git a/tests/rules/README.md b/tests/rules/README.md new file mode 100644 index 0000000..ec2786f --- /dev/null +++ b/tests/rules/README.md @@ -0,0 +1,15 @@ +# Rules both editors keep + +The Neovim plugin (Lua) and the VS Code extension (JavaScript) each carry their own copy of a few +small rules. These files are the cases both copies must answer the same way: data, read by +`nvim/tests/rules.lua` and `vscode/tests/rules.test.js`. A rule changed in one editor fails here +until the other follows. + +| File | The rule | +|---|---| +| `versions.json` | which of two versions is newer, and what is no version at all | +| `private_files.json` | which files look like they hold secrets, and what counts as inside a folder | +| `server_address.json` | what may be handed to `lembas login` as the server's address | +| `login_events.json` | the events of `lembas login --json`, whatever pieces its output arrives in | +| `rpc_lines.json` | which messages survive a line that is longer than the reader keeps | +| `openable.json` | which shown files may be opened, by their first bytes and their name | diff --git a/tests/rules/login_events.json b/tests/rules/login_events.json new file mode 100644 index 0000000..d9961f1 --- /dev/null +++ b/tests/rules/login_events.json @@ -0,0 +1,11 @@ +[ + { "chunks": ["{\"event\":\"done\",\"base_url\":\"https://ai.example.org\"}\n"], "events": ["done"] }, + { "chunks": ["{\"event\":\"done\",\"base_", "url\":\"https://ai.example.org\"}\n"], "events": ["done"] }, + { "chunks": ["{\"event\":\"code\",\"user_code\":\"ABCD\"}\n{\"event\":\"do", "ne\"}\n"], "events": ["code", "done"] }, + { "chunks": ["{\"event\":\"code\"}\r\n", "{\"event\":\"error\",\"message\":\"no\"}\r\n"], "events": ["code", "error"] }, + { "chunks": ["not json\n", "{\"event\":\"done\"}\n"], "events": ["done"] }, + { "chunks": ["{\"no_event\":1}\n[1,2]\n\"text\"\n{\"event\":7}\n"], "events": [] }, + { "chunks": ["{\"event\":\"done\"}"], "events": [] }, + { "chunks": ["{\"event\":\"code\"}\n{\"event\":\"done\"}"], "events": ["code"] }, + { "chunks": ["", "\n", "{\"event\":\"done\"}\n"], "events": ["done"] } +] diff --git a/tests/rules/openable.json b/tests/rules/openable.json new file mode 100644 index 0000000..7b22b03 --- /dev/null +++ b/tests/rules/openable.json @@ -0,0 +1,177 @@ +[ + { + "name": "picture.png", + "head": "89504e470d0a1a0a00000000000000000000000000000000", + "kind": "image" + }, + { + "name": "picture.PNG", + "head": "89504e470d0a1a0a00000000000000000000000000000000", + "kind": "image" + }, + { + "name": "photo.jpg", + "head": "ffd8ffe000000000000000000000000000000000", + "kind": "image" + }, + { + "name": "photo.jpeg", + "head": "ffd8ffe000000000000000000000000000000000", + "kind": "image" + }, + { + "name": "picture.jpg", + "head": "89504e470d0a1a0a00000000000000000000000000000000", + "kind": null + }, + { + "name": "picture.pdf", + "head": "89504e470d0a1a0a00000000000000000000000000000000", + "kind": null + }, + { + "name": "picture", + "head": "89504e470d0a1a0a00000000000000000000000000000000", + "kind": null + }, + { + "name": "paper.pdf", + "head": "255044462d312e370a256162636465666768", + "kind": "pdf" + }, + { + "name": "paper.txt", + "head": "255044462d312e370a256162636465666768", + "kind": null + }, + { + "name": "paper.pdf", + "head": "6e616d652c636f756e740a66697273742c310a", + "kind": null + }, + { + "name": "tune.mp3", + "head": "4944330300000000000000000000000000000000", + "kind": "audio" + }, + { + "name": "tune.wav", + "head": "524946460000000057415645666d7420", + "kind": "audio" + }, + { + "name": "tune.ogg", + "head": "4f67675300000000000000000000000000000000", + "kind": "audio" + }, + { + "name": "tune.mp3", + "head": "4f67675300000000000000000000000000000000", + "kind": null + }, + { + "name": "clip.mp4", + "head": "000000186674797069736f6d00000000", + "kind": "video" + }, + { + "name": "clip.webm", + "head": "1a45dfa300000000000000000000000000000000", + "kind": "video" + }, + { + "name": "clip.mkv", + "head": "1a45dfa300000000000000000000000000000000", + "kind": "video" + }, + { + "name": "clip.mp4", + "head": "1a45dfa300000000000000000000000000000000", + "kind": null + }, + { + "name": "table.csv", + "head": "6e616d652c636f756e740a66697273742c310a", + "kind": "text" + }, + { + "name": "notes.txt", + "head": "6e616d652c636f756e740a66697273742c310a", + "kind": "text" + }, + { + "name": "notes.md", + "head": "6e616d652c636f756e740a66697273742c310a", + "kind": "text" + }, + { + "name": "data.json", + "head": "6e616d652c636f756e740a66697273742c310a", + "kind": "text" + }, + { + "name": "run.sh", + "head": "23212f62696e2f73680a6563686f2068656c6c6f2074686572650a", + "kind": null + }, + { + "name": "run.txt", + "head": "23212f62696e2f73680a6563686f2068656c6c6f2074686572650a", + "kind": "text" + }, + { + "name": "page.html", + "head": "3c21646f63747970652068746d6c3e3c7363726970743e313c2f7363726970743e", + "kind": null + }, + { + "name": "page.svg", + "head": "3c21646f63747970652068746d6c3e3c7363726970743e313c2f7363726970743e", + "kind": null + }, + { + "name": "program", + "head": "7f454c4600000000000000000000000000000000", + "kind": null + }, + { + "name": "program.txt", + "head": "7f454c4600000000000000000000000000000000", + "kind": null + }, + { + "name": "program.png", + "head": "7f454c4600000000000000000000000000000000", + "kind": null + }, + { + "name": "program.exe", + "head": "7f454c4600000000000000000000000000000000", + "kind": null + }, + { + "name": "shortcut.desktop", + "head": "6e616d652c636f756e740a66697273742c310a", + "kind": null + }, + { + "name": "model.glb", + "head": "676c544600000000000000000000000000000000", + "kind": null + }, + { + "name": "model.obj", + "head": "6e616d652c636f756e740a66697273742c310a", + "kind": null + }, + { + "name": "macro.docm", + "head": "504b030400000000000000000000000000000000", + "kind": null + }, + { + "name": "empty.txt", + "head": "", + "kind": null + } +] \ No newline at end of file diff --git a/tests/rules/private_files.json b/tests/rules/private_files.json new file mode 100644 index 0000000..8aa4208 --- /dev/null +++ b/tests/rules/private_files.json @@ -0,0 +1,79 @@ +{ + "secret": [ + "/home/sam/app/.env", + "/home/sam/app/.env.local", + "/home/sam/app/.env.production", + "/home/sam/app/.ENV", + "/home/sam/app/prod.env", + "/home/sam/app/certs/server.pem", + "/home/sam/app/certs/server.KEY", + "/home/sam/app/store.p12", + "/home/sam/app/store.pfx", + "/home/sam/app/release.jks", + "/home/sam/app/release.keystore", + "/home/sam/app/putty.ppk", + "/home/sam/app/passwords.kdbx", + "/home/sam/app/id_rsa", + "/home/sam/app/id_rsa.pub", + "/home/sam/app/id_ed25519", + "/home/sam/app/id_ed25519_work", + "/home/sam/app/id_ecdsa", + "/home/sam/app/id_dsa", + "/home/sam/app/.netrc", + "/home/sam/app/_netrc", + "/home/sam/app/.npmrc", + "/home/sam/app/.pypirc", + "/home/sam/app/.pgpass", + "/home/sam/app/.htpasswd", + "/home/sam/app/.git-credentials", + "/home/sam/app/credentials", + "/home/sam/app/credentials.json", + "/home/sam/app/Credentials.yaml", + "/home/sam/app/secrets.yaml", + "/home/sam/app/secrets.toml", + "/home/sam/app/secret.json", + "/home/sam/.ssh/config", + "/home/sam/.ssh/known_hosts", + "/home/sam/app/.ssh/notes.txt", + "/home/sam/.gnupg/gpg.conf", + "/home/sam/.aws/config", + "/home/sam/.kube/config", + "/home/sam/.docker/config.json", + "/home/sam/.azure/profile.json", + "C:\\Users\\sam\\app\\.env", + "C:\\Users\\sam\\.ssh\\config" + ], + "plain": [ + "/home/sam/app/main.py", + "/home/sam/app/.env.example", + "/home/sam/app/.env.sample", + "/home/sam/app/.env.template", + "/home/sam/app/environment.ts", + "/home/sam/app/env.py", + "/home/sam/app/keyboard.rs", + "/home/sam/app/key.go", + "/home/sam/app/pem.rs", + "/home/sam/app/secretsanta.py", + "/home/sam/app/secrets/readme.md", + "/home/sam/app/src/credential_store.rs", + "/home/sam/app/ssh/client.go", + "/home/sam/app/aws/s3.py", + "/home/sam/app/README.md", + "/home/sam/app/.gitignore", + "/home/sam/app/package.json", + "/home/sam/app/identity.rs" + ], + "inside": [ + ["/home/sam/app/src/main.py", ["/home/sam/app"], true], + ["/home/sam/app/main.py", ["/home/sam/app/"], true], + ["/home/sam/app", ["/home/sam/app"], false], + ["/home/sam/application/main.py", ["/home/sam/app"], false], + ["/home/sam/other/main.py", ["/home/sam/app"], false], + ["/home/sam/other/main.py", ["/home/sam/app", "/home/sam/other"], true], + ["/home/sam/app/../other/main.py", ["/home/sam/app"], false], + ["/home/sam/app/main.py", [], false], + ["/etc/passwd", ["/home/sam/app"], false], + ["/etc/passwd", ["/"], false], + ["relative/main.py", ["/home/sam/app"], false] + ] +} diff --git a/tests/rules/rpc_lines.json b/tests/rules/rpc_lines.json new file mode 100644 index 0000000..1b6b124 --- /dev/null +++ b/tests/rules/rpc_lines.json @@ -0,0 +1,11 @@ +{ + "max": 64, + "cases": [ + { "chunks": ["{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["a", "b"] }, + { "chunks": ["{\"jsonrpc\":\"2.0\",\"me", "thod\":\"a\"}\n"], "methods": ["a"] }, + { "chunks": ["{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "tail of the long line\n{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["a", "b"] }, + { "chunks": ["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "{\"jsonrpc\":\"2.0\",\"method\":\"lost\"}\n", "{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["b"] }, + { "chunks": ["xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "\n", "{\"jsonrpc\":\"2.0\",\"method\":\"b\"}\n"], "methods": ["b"] }, + { "chunks": ["printed by mistake\n", "\n", "{\"jsonrpc\":\"2.0\",\"method\":\"a\"}\n"], "methods": ["a"] } + ] +} diff --git a/tests/rules/server_address.json b/tests/rules/server_address.json new file mode 100644 index 0000000..2f5a51b --- /dev/null +++ b/tests/rules/server_address.json @@ -0,0 +1,4 @@ +{ + "ok": ["ai.example.org", "https://ai.example.org", "http://localhost:8000", "https://ai.example.org/base/", " ai.example.org ", "[::1]:8000"], + "refused": ["", " ", "-h", "--ca", "--json", "ai.example.org --ca /tmp/x", "ai.example.org\n--ca", "a\tb", "-"] +} diff --git a/tests/rules/versions.json b/tests/rules/versions.json new file mode 100644 index 0000000..feaa2b2 --- /dev/null +++ b/tests/rules/versions.json @@ -0,0 +1,20 @@ +{ + "compare": [ + ["2.0.0-beta.9", "2.0.0-beta.10", -1], + ["2.0.0-beta.10", "2.0.0-beta.9", 1], + ["2.0.0-beta.16", "2.0.0-beta.16", 0], + ["2.0.0", "2.0.0-beta.99", 1], + ["2.0.0-alpha.3", "2.0.0-beta.1", -1], + ["2.0.0-beta.4", "2.0.0-rc.1", -1], + ["v2.0.0", "2.0.0", 0], + ["2.0", "2.0.0", 0], + ["2", "2.0.0", 0], + ["1.9.9", "2.0.0-beta.1", -1], + ["2.0.1", "2.0.0", 1], + ["2.0.0+build.7", "2.0.0", 0], + ["2.0.0-beta.3+build.7", "2.0.0-beta.3", 0], + [" 2.0.0 ", "2.0.0", 0], + ["10.0.0", "9.9.9", 1] + ], + "not_versions": ["", "latest", "1.2.3junk", "1.2.3 junk", "x1.2.3", "1.2.3-", "1..2", ".1.2", "1.2.", "-beta.1", "1.2.3-beta 4", "v"] +}