Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63d705c76c
|
||
|
|
3438c290ba
|
No files matched your search
@@ -1,5 +1,42 @@
|
||||
# Changelog
|
||||
|
||||
## [1.0.0-beta.5] — 2026-11-27
|
||||
|
||||
### Fixed (VS Code / VSCodium)
|
||||
|
||||
- **Chat input pinned to the bottom of the side panel.** Wrapped the header, collapsible Tune drawer, and subagent strip inside a single `.chrome` container and restored a 3-row `body` grid (`auto minmax(0, 1fr) auto`) with `height: 100vh`. Previously, `hidden` (`display: none`) siblings shifted `<main id="log">` and `<footer>` onto `auto` tracks above an empty `1fr` track, floating the chat composer near the top with empty space beneath it.
|
||||
|
||||
## [1.0.0-beta.4] — 2026-11-27
|
||||
|
||||
### Fixed (VS Code / VSCodium & Neovim)
|
||||
|
||||
- **Protocol compatibility with LLeMbas CLI 2.0:**
|
||||
- `_lembas/files/search`: read `{ path, kind }` objects returned by the CLI (with string fallback) so `@file` search, `:LLeMbasFiles`, and *Add File / Open File* work reliably and distinguish files from directories while escaping spaces and `#`.
|
||||
- `_lembas/sessions/resume`: replay the CLI's `historyTurns` shape (`role: "user" | "assistant"`, tool calls with outputs, thinking blocks, attachments, and harness turns), fixing empty transcripts on session resume.
|
||||
- `_lembas/question`: send spec-compliant `Answer` objects (`{ kind: "options", labels }`, `{ kind: "custom", text }`, `{ kind: "skipped" }`) so answers are accepted instead of silently treated as dismissed; support `recommended` markers and multi-select in Neovim too.
|
||||
- `_lembas/plan`: send `{ outcome: "dismissed" }` on dismissal.
|
||||
- **Neovim `:LLeMbasFix` & editor context:** include buffer error/warning diagnostics and open file paths in `_meta.lembas.editor` even when no visual range is selected, and read cursor position from the buffer's own window.
|
||||
- **VS Code `llembas.generate`:** guard against concurrent rewrites on the same file, show streaming progress with cancellation (`_lembas/edit/cancel`), and report when nothing changed or the document edited meanwhile.
|
||||
- **Neovim robustness:** cap JSON-RPC line buffer memory in `rpc.lua`, disable undo history on the read-only transcript buffer, reset session metadata (`title`, `progress`, `usage`, `team`, `attached`, `shown`) on `:LLeMbasNew`, handle `_lembas/permission/settled` and transient autocomplete errors cleanly, and read `M.version` directly from `VERSION`.
|
||||
|
||||
### Added & Improved (VS Code / VSCodium)
|
||||
|
||||
- **Redesigned chat sidebar UI & visual polish:**
|
||||
- Two-row branded header with the LLeMbas pixel-leaf icon, live connection/working dot, mode indicator dot, session title, and compact action bar.
|
||||
- Welcome empty state (*"Waybread for the code ahead."*) with quick-action starter buttons (`Explain selection`, `Fix file problems`, `Add @file`, `Resume session`) and shortcut hints.
|
||||
- **Autocomplete Tune drawer** in the sidebar with an interactive **Max Tokens slider** (`0`..`4096`), quick length presets (`Default`, `Words`, `Line`, `Block`, `File`), **Prediction scope** selector (`llembas.complete.length`), **Autocomplete instructions** input (`llembas.complete.instructions`), and live toggles for *Suggest as you type* and *Show thinking*.
|
||||
- Real **GFM Markdown tables** inside horizontally scrollable wrappers with column alignment and inline formatting, plus `~~strikethrough~~` and task list checkboxes (`- [x]` / `- [ ]`).
|
||||
- **Fenced code block toolbars** with one-click **Copy** and **Insert at cursor** buttons.
|
||||
- **Collapsible Thinking blocks** and **expandable tool call outputs** with semantic status icons, tool kind tags, execution duration (`ms`), and clickable file chips.
|
||||
- Visual `<progress>` bar on live Plan cards, rich Markdown rendering inside Plan approval cards, live subagent team strip, session token usage indicator (`↑`/`↓`), auto-growing prompt input, and upgraded status bar item.
|
||||
- New commands: `LLeMbas: Compact Session Context` (`llembas.compact`) and `LLeMbas: Toggle Autocomplete as You Type` (`llembas.toggleAutocomplete`).
|
||||
|
||||
### Added & Improved (Neovim)
|
||||
|
||||
- **Dedicated `LLeMbas*` highlight groups & visual design (`lua/llembas/ui.lua`):** colorscheme-aware highlights re-applied on `ColorScheme`, branded transcript winbar with session title/mode/model/token usage/phase, empty-state virtual-text welcome banner, section dividers, visual plan progress bar + task list, inline diff hint & gutter highlights, and floating preview windows.
|
||||
- **Autocomplete length, tokens & word-by-word accept:** `:LLeMbasAutocompleteTokens [N|auto|words|line|block|file]` and `:LLeMbasAutocompleteInstructions [text|-]`, plus `<M-Right>` (`accept_word`) to accept suggestions one word at a time.
|
||||
- **New commands & panel keys:** `:LLeMbasGenerate`, `:LLeMbasCompact`, `:LLeMbasCommands`, `:LLeMbasToggleThoughts`, `:LLeMbasCancelEdit`, `:LLeMbasNextHunk` / `:LLeMbasPrevHunk` (`]h`/`[h`), `:LLeMbasStatus`, `:LLeMbasHelp` (`g?`), `require("llembas").statusline()`, plus `K` (inspect tool output in a float), `y` (yank code block under cursor), `i` (jump to prompt), `<C-x><C-f>` (`@file`), `<C-x><C-o>` (`/command`), and configurable panel `position` (`right`, `left`, `bottom`, `float`).
|
||||
|
||||
## [1.0.0-beta.3] — 2026-11-26
|
||||
|
||||
### Fixed (VS Code / VSCodium)
|
||||
|
||||
@@ -32,30 +32,39 @@ vim-plug: `Plug 'LLeMbas/LLeMbas-IDE', { 'branch': 'dev', 'rtp': 'nvim' }`
|
||||
|
||||
| Command | What it does |
|
||||
|---|---|
|
||||
| `:LLeMbas` | open or close the chat panel |
|
||||
| `:LLeMbas` | open or close the chat panel (`right`, `left`, `bottom`, or `float`) |
|
||||
| `:'<,'>LLeMbasAsk [question]` | ask about the selected lines; without a question they go with the next message |
|
||||
| `:'<,'>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) |
|
||||
| `:'<,'>LLeMbasExplain` | explain the selected lines |
|
||||
| `:'<,'>LLeMbasEdit [instruction]` | rewrite the selected lines as inline hunks (`ga`/`gr`, `gA`/`gR`, `]h`/`[h`) |
|
||||
| `:LLeMbasGenerate [instruction]` | generate code at the cursor as inline hunks |
|
||||
| `:LLeMbasCancelEdit` | cancel an in-flight rewrite or generation |
|
||||
| `:LLeMbasFix` | send the current buffer's diagnostics to the agent to fix |
|
||||
| `:LLeMbasAccept[!]`, `:LLeMbasReject[!]` | accept or reject proposed changes (`!`: all) |
|
||||
| `:LLeMbasNextHunk`, `:LLeMbasPrevHunk` | jump between proposed changes (`]h`, `[h`) |
|
||||
| `:LLeMbasAutocomplete [on\|off]` | toggle suggestions as you type |
|
||||
| `:LLeMbasAutocompleteTokens [N\|auto\|words\|line\|block\|file]` | tune autocomplete max tokens and prediction length preset |
|
||||
| `:LLeMbasAutocompleteInstructions [text\|-]` | set or clear custom instructions sent with autocomplete |
|
||||
| `:LLeMbasAutocompleteModel[!] [model]` | the model that writes suggestions (`!`: this editor only; `-`: back to default) |
|
||||
| `:LLeMbasMainModel [model]` | the model for chat and rewriting, saved in your account (`?` shows both) |
|
||||
| `:LLeMbasFiles[!] [query]` | search project index and insert `@path` (`!`: open file in editor) |
|
||||
| `:LLeMbasOpenFile [query]` | open a file from the project index |
|
||||
| `:LLeMbasCommands` | pick a session `/command` or skill |
|
||||
| `:LLeMbasSessions` | list and resume a previous session with its history |
|
||||
| `:LLeMbasCompact` | compact the session context |
|
||||
| `:LLeMbasToggleThoughts` | show or hide model thinking |
|
||||
| `:LLeMbasOpen` | open the file the agent showed last |
|
||||
| `:LLeMbasStop` | stop the running turn |
|
||||
| `:LLeMbasNew` | start a new session |
|
||||
| `:LLeMbasMode [mode]` | change the mode |
|
||||
| `:LLeMbasModel [model]` | show or change the model |
|
||||
| `:LLeMbasNew[!]` | start a new session (`!` ends a hung turn) |
|
||||
| `:LLeMbasMode [mode]` | change the mode (works live mid-turn) |
|
||||
| `:LLeMbasModel [model]` | pick or change the session's model |
|
||||
| `:LLeMbasStatus`, `:LLeMbasHelp` | floating status overview / commands & keys card |
|
||||
|
||||
In the prompt: Enter (normal mode) or Ctrl-S sends, Ctrl-C stops the turn, `q` closes the panel.
|
||||
In the prompt: `<CR>` (normal mode) or `<C-s>` sends (or steers mid-turn), `<C-c>` stops the turn, `<C-x><C-f>` inserts `@file`, `<C-x><C-o>` inserts `/command`, `q` closes, `g?` opens help.
|
||||
In the transcript: `<CR>` / `gf` opens `file:line`, `K` inspects tool output in a float, `y` yanks the fenced code block under the cursor, `i` jumps to the prompt, `q` closes.
|
||||
|
||||
While typing, `<Tab>` accepts a suggestion, `<M-Right>` accepts the next word, and `<M-\>` triggers one manually; all keys and `LLeMbas*` highlight groups can be customized. `require("llembas").statusline()` provides a compact statusline component.
|
||||
Help: `:help llembas`.
|
||||
|
||||
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
|
||||
@@ -66,9 +75,11 @@ scripts/package-vscode.sh # writes dist/llemba
|
||||
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).
|
||||
Includes a redesigned sidebar chat with interactive approval, question and plan cards, real GFM
|
||||
tables, code-block Copy/Insert toolbars, collapsible thinking and tool output, session resume and
|
||||
compaction, `@file` and `/command` popups, inline diff rewrites and generation, inline autocomplete
|
||||
with a **Tune** drawer (max-tokens slider, length presets, and custom instructions), and shown
|
||||
media. Commands, keys, and settings: [`vscode/README.md`](vscode/README.md).
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
+71
-10
@@ -8,27 +8,53 @@ COMMANDS *llembas-commands*
|
||||
|
||||
:LLeMbas *:LLeMbas*
|
||||
Open or close the chat panel: the transcript, and the prompt under it.
|
||||
In the prompt, <CR> in normal mode or <C-s> sends, <C-c> stops the turn,
|
||||
q closes the panel.
|
||||
In the prompt, <CR> in normal mode or <C-s> sends (or steers while busy),
|
||||
<C-c> stops the turn, <C-x><C-f> inserts @file, <C-x><C-o> inserts a
|
||||
/command, q closes the panel, g? opens help.
|
||||
In the transcript, <CR> or gf opens file:line under the cursor, K inspects
|
||||
tool output in a float, y yanks the fenced code block under the cursor, i
|
||||
jumps into the prompt, q closes.
|
||||
|
||||
:[range]LLeMbasAsk [question] *:LLeMbasAsk*
|
||||
Ask about the lines of [range]. They are sent as the buffer has them,
|
||||
saved or not, with the file, the line numbers and the diagnostics on them.
|
||||
Without a question the lines are attached to the next message you type.
|
||||
|
||||
:[range]LLeMbasExplain *:LLeMbasExplain*
|
||||
Ask the agent to explain the selected lines concisely.
|
||||
|
||||
:LLeMbasFix *:LLeMbasFix*
|
||||
Send the current buffer's reported diagnostics to the agent to fix.
|
||||
|
||||
:[range]LLeMbasEdit [instruction] *:LLeMbasEdit*
|
||||
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.)
|
||||
gA and gR do all, ]h and [h jump between changes.
|
||||
|
||||
:LLeMbasGenerate [instruction] *:LLeMbasGenerate*
|
||||
Generate code at the cursor line and show it as inline proposed hunks.
|
||||
|
||||
:LLeMbasCancelEdit *:LLeMbasCancelEdit*
|
||||
Cancel an in-flight rewrite or generation in the current buffer.
|
||||
|
||||
:LLeMbasAccept[!] :LLeMbasReject[!] *:LLeMbasAccept* *:LLeMbasReject*
|
||||
Accept or reject the change under the cursor; with ! all of them.
|
||||
|
||||
:LLeMbasNextHunk :LLeMbasPrevHunk *:LLeMbasNextHunk* *:LLeMbasPrevHunk*
|
||||
Jump to the next or previous proposed change in the current buffer.
|
||||
|
||||
:LLeMbasAutocomplete [on|off] *:LLeMbasAutocomplete*
|
||||
Suggestions as you type. While typing, <Tab> accepts a shown suggestion
|
||||
and <M-\> asks for one now.
|
||||
Suggestions as you type. While typing, <Tab> accepts a shown suggestion,
|
||||
<M-Right> accepts the next word, and <M-\> asks for one now.
|
||||
|
||||
:LLeMbasAutocompleteTokens [N|auto|words|line|block|file] *:LLeMbasAutocompleteTokens*
|
||||
Configure how much autocomplete predicts (max tokens up to 4096 and/or a
|
||||
length preset: auto, words, line, block, file). Without an argument, opens
|
||||
a picker with presets and a custom token count input.
|
||||
|
||||
:LLeMbasAutocompleteInstructions [text|-] *:LLeMbasAutocompleteInstructions*
|
||||
Set custom instructions sent with autocomplete requests ("-" clears them).
|
||||
|
||||
:LLeMbasAutocompleteModel[!] [model] *:LLeMbasAutocompleteModel*
|
||||
The model that writes suggestions, saved in your account; without a name,
|
||||
@@ -39,27 +65,52 @@ COMMANDS *llembas-commands*
|
||||
The model for chat and rewriting, saved in your account. "?" shows both
|
||||
settings.
|
||||
|
||||
:LLeMbasFiles[!] [query] *:LLeMbasFiles*
|
||||
Search the project file index and insert @path into the prompt (! opens
|
||||
the chosen file directly in the editing window).
|
||||
|
||||
:LLeMbasOpenFile [query] *:LLeMbasOpenFile*
|
||||
Open a file from the project index.
|
||||
|
||||
:LLeMbasCommands *:LLeMbasCommands*
|
||||
Pick an available /command or skill and insert it into the prompt.
|
||||
|
||||
:LLeMbasSessions *:LLeMbasSessions*
|
||||
List previous sessions in this directory and resume one with its history.
|
||||
|
||||
:LLeMbasCompact *:LLeMbasCompact*
|
||||
Compact the active session's conversation context.
|
||||
|
||||
:LLeMbasToggleThoughts *:LLeMbasToggleThoughts*
|
||||
Toggle showing model thinking in the transcript.
|
||||
|
||||
:LLeMbasOpen *:LLeMbasOpen*
|
||||
Open the file the agent showed last with the system's viewer.
|
||||
|
||||
:LLeMbasStop *:LLeMbasStop*
|
||||
Stop the running turn.
|
||||
|
||||
:LLeMbasNew *:LLeMbasNew*
|
||||
Start a new session. The old one stays in the CLI's store.
|
||||
:LLeMbasNew[!] *:LLeMbasNew*
|
||||
Start a new session (! ends a hung turn). Old sessions stay in the CLI.
|
||||
|
||||
:LLeMbasMode [mode] *:LLeMbasMode*
|
||||
Change the session's mode; without an argument, pick from a list.
|
||||
Change the session's mode (works live mid-turn); without an arg, pick.
|
||||
|
||||
:LLeMbasModel [model] *:LLeMbasModel*
|
||||
Show the session's model, or change it to one your server serves.
|
||||
Pick or change the session's model.
|
||||
|
||||
:LLeMbasStatus :LLeMbasHelp *:LLeMbasStatus* *:LLeMbasHelp*
|
||||
Open floating status overview or commands & keymaps reference.
|
||||
|
||||
==============================================================================
|
||||
SETUP *llembas-setup*
|
||||
>lua
|
||||
require("llembas").setup({
|
||||
cmd = { "lembas", "serve", "--stdio" }, -- the agent
|
||||
position = "right", -- "right" | "left" | "bottom" | "float"
|
||||
width = 64, -- the panel's columns
|
||||
prompt_height = 5, -- the prompt window's rows
|
||||
border = "rounded", -- border style for floating windows
|
||||
mode = nil, -- the mode a session starts in
|
||||
model = nil, -- the model a session starts on
|
||||
show_thoughts = false, -- the model's thinking in the transcript
|
||||
@@ -68,11 +119,21 @@ SETUP *llembas-setup*
|
||||
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
|
||||
max_tokens = nil, -- max tokens to predict (nil: server default)
|
||||
length = "auto", -- "auto" | "words" | "line" | "block" | "file"
|
||||
instructions = "", -- custom autocomplete instructions
|
||||
accept = "<Tab>", -- accepts a shown suggestion
|
||||
accept_word = "<M-Right>", -- accepts next word of suggestion
|
||||
trigger = "<M-\\>", -- asks for a suggestion now
|
||||
},
|
||||
})
|
||||
<
|
||||
Statusline component: `require("llembas").statusline()`.
|
||||
Highlights: `LLeMbasBrand`, `LLeMbasUserHeader`, `LLeMbasAgentHeader`,
|
||||
`LLeMbasThought`, `LLeMbasToolPending`, `LLeMbasToolDone`, `LLeMbasToolFail`,
|
||||
`LLeMbasToolDenied`, `LLeMbasPlanHeader`, `LLeMbasDiffAdd`, `LLeMbasDiffDelete`,
|
||||
`LLeMbasDiffHint`, `LLeMbasGhost`, `LLeMbasSeparator` (all `default = true`).
|
||||
|
||||
What the model writes is shown as text. It is never run, and the panel's
|
||||
buffers read no modeline.
|
||||
|
||||
|
||||
+218
-53
@@ -1,7 +1,14 @@
|
||||
-- The chat panel: a transcript nobody types in and a prompt under it. What the model writes is put
|
||||
-- there as text and nothing else: it is never run, and modelines are off in both buffers.
|
||||
local M = { tbuf = nil, ibuf = nil, marks = {}, on_send = nil, on_stop = nil }
|
||||
local ui = require("llembas.ui")
|
||||
|
||||
local M = {
|
||||
tbuf = nil, ibuf = nil, marks = {}, details = {},
|
||||
on_send = nil, on_stop = nil, on_help = nil, on_files = nil, on_commands = nil,
|
||||
}
|
||||
local ns = vim.api.nvim_create_namespace("llembas")
|
||||
local ns_hl = vim.api.nvim_create_namespace("llembas-hl")
|
||||
local ns_welcome = vim.api.nvim_create_namespace("llembas-welcome")
|
||||
|
||||
local function valid(b) return b and vim.api.nvim_buf_is_valid(b) end
|
||||
|
||||
@@ -12,25 +19,127 @@ local function win_of(buf)
|
||||
end
|
||||
end
|
||||
|
||||
local function scratch(name, ft)
|
||||
local function is_empty_buf(buf)
|
||||
local n = vim.api.nvim_buf_line_count(buf)
|
||||
if n ~= 1 then return false end
|
||||
return (vim.api.nvim_buf_get_lines(buf, 0, 1, false)[1] or "") == ""
|
||||
end
|
||||
|
||||
local function sync_welcome()
|
||||
if not valid(M.tbuf) then return end
|
||||
vim.api.nvim_buf_clear_namespace(M.tbuf, ns_welcome, 0, -1)
|
||||
if is_empty_buf(M.tbuf) then
|
||||
vim.api.nvim_buf_set_extmark(M.tbuf, ns_welcome, 0, 0, {
|
||||
virt_lines = ui.welcome_virt_lines(),
|
||||
virt_lines_above = false,
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
local function scratch(name, ft, readonly)
|
||||
local b = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[b].buftype = "nofile"
|
||||
vim.bo[b].bufhidden = "hide"
|
||||
vim.bo[b].swapfile = false
|
||||
vim.bo[b].modeline = false
|
||||
vim.bo[b].filetype = ft
|
||||
if readonly then vim.bo[b].undolevels = -1 end
|
||||
pcall(vim.api.nvim_buf_set_name, b, name)
|
||||
return b
|
||||
end
|
||||
|
||||
local function open_at_cursor()
|
||||
local token = vim.fn.expand("<cWORD>")
|
||||
if not token or token == "" then return end
|
||||
token = token:gsub("^[`\"'(%[<]+", ""):gsub("[`\"')%]>.,;:]+$", "")
|
||||
local path, line = token:match("^([%w%._%-%/]+%.[%w]+):(%d+)")
|
||||
if not path then path, line = token:match("^([%w%._%-%/]+%.[%w]+)#L(%d+)") end
|
||||
if not path then path = token:match("^([%w%._%-%/]+%.[%w]+)$") end
|
||||
if not path then return end
|
||||
local full = path:match("^/") and path or (vim.fn.getcwd() .. "/" .. path)
|
||||
if vim.fn.filereadable(full) == 0 then return end
|
||||
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_set_current_win(target)
|
||||
pcall(vim.cmd, "edit " .. vim.fn.fnameescape(full))
|
||||
if tonumber(line) then pcall(vim.api.nvim_win_set_cursor, 0, { tonumber(line), 0 }) end
|
||||
end
|
||||
end
|
||||
|
||||
local function inspect_line()
|
||||
if not valid(M.tbuf) then return end
|
||||
local row = vim.api.nvim_win_get_cursor(0)[1] - 1
|
||||
for id, mark in pairs(M.marks) do
|
||||
local pos = vim.api.nvim_buf_get_extmark_by_id(M.tbuf, ns, mark, {})
|
||||
if pos[1] == row and M.details[id] and M.details[id] ~= "" then
|
||||
local lines = vim.split(M.details[id], "\n", { plain = true })
|
||||
ui.float("Tool output", lines)
|
||||
return
|
||||
end
|
||||
end
|
||||
vim.notify("LLeMbas: no tool output on this line", vim.log.levels.INFO)
|
||||
end
|
||||
|
||||
local function yank_code_block()
|
||||
if not valid(M.tbuf) then return end
|
||||
local cur = vim.api.nvim_win_get_cursor(0)[1]
|
||||
local lines = vim.api.nvim_buf_get_lines(M.tbuf, 0, -1, false)
|
||||
local open_row, close_row, fence
|
||||
for i = cur, 1, -1 do
|
||||
local m = lines[i]:match("^%s*(`%`%`+)") or lines[i]:match("^%s*(~~~+)")
|
||||
if m then
|
||||
if i == cur then
|
||||
-- Cursor on fence line: check whether it opens or closes
|
||||
open_row, fence = i, m
|
||||
else
|
||||
open_row, fence = i, m
|
||||
end
|
||||
break
|
||||
end
|
||||
end
|
||||
if not open_row then return vim.notify("LLeMbas: cursor is not inside a code block", vim.log.levels.INFO) end
|
||||
local ch = fence:sub(1, 1)
|
||||
for j = open_row + 1, #lines do
|
||||
local trimmed = vim.trim(lines[j])
|
||||
if trimmed:sub(1, #fence) == fence and trimmed:match("^" .. ch .. "+$") then
|
||||
close_row = j
|
||||
break
|
||||
end
|
||||
end
|
||||
if not close_row or cur > close_row then
|
||||
return vim.notify("LLeMbas: cursor is not inside a code block", vim.log.levels.INFO)
|
||||
end
|
||||
local block = vim.list_slice(lines, open_row + 1, close_row - 1)
|
||||
local text = table.concat(block, "\n")
|
||||
vim.fn.setreg('"', text)
|
||||
pcall(vim.fn.setreg, "+", text)
|
||||
vim.notify(("LLeMbas: yanked %d line%s of code"):format(#block, #block == 1 and "" or "s"), vim.log.levels.INFO)
|
||||
end
|
||||
|
||||
local function buffers()
|
||||
if not valid(M.tbuf) then
|
||||
M.tbuf = scratch("llembas://chat", "markdown")
|
||||
M.tbuf = scratch("llembas://chat", "markdown", true)
|
||||
vim.bo[M.tbuf].modifiable = false
|
||||
M.marks = {}
|
||||
M.details = {}
|
||||
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" })
|
||||
vim.keymap.set("n", "<C-c>", function() if M.on_stop then M.on_stop() end end, { buffer = M.tbuf, desc = "LLeMbas: stop the turn" })
|
||||
vim.keymap.set("n", "<CR>", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" })
|
||||
vim.keymap.set("n", "gf", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" })
|
||||
vim.keymap.set("n", "K", inspect_line, { buffer = M.tbuf, desc = "LLeMbas: inspect tool output" })
|
||||
vim.keymap.set("n", "y", yank_code_block, { buffer = M.tbuf, desc = "LLeMbas: yank code block under cursor" })
|
||||
vim.keymap.set("n", "g?", function() if M.on_help then M.on_help() end end, { buffer = M.tbuf, desc = "LLeMbas: help" })
|
||||
vim.keymap.set("n", "i", function()
|
||||
local iw = win_of(M.ibuf)
|
||||
if iw then vim.api.nvim_set_current_win(iw); pcall(vim.cmd, "startinsert") end
|
||||
end, { buffer = M.tbuf, desc = "LLeMbas: jump to prompt" })
|
||||
sync_welcome()
|
||||
end
|
||||
if not valid(M.ibuf) then
|
||||
M.ibuf = scratch("llembas://prompt", "markdown")
|
||||
M.ibuf = scratch("llembas://prompt", "markdown", false)
|
||||
local function send()
|
||||
local text = table.concat(vim.api.nvim_buf_get_lines(M.ibuf, 0, -1, false), "\n")
|
||||
if not text:match("%S") then return end
|
||||
@@ -38,60 +147,82 @@ local function buffers()
|
||||
end
|
||||
vim.keymap.set("n", "<CR>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
|
||||
vim.keymap.set({ "n", "i" }, "<C-s>", send, { buffer = M.ibuf, desc = "LLeMbas: send" })
|
||||
vim.keymap.set("n", "<C-c>", function() if M.on_stop then M.on_stop() end end, { buffer = M.ibuf, desc = "LLeMbas: stop the turn" })
|
||||
vim.keymap.set({ "n", "i" }, "<C-c>", function() if M.on_stop then M.on_stop() end end, { buffer = M.ibuf, desc = "LLeMbas: stop the turn" })
|
||||
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.ibuf, desc = "LLeMbas: close the panel" })
|
||||
vim.keymap.set("n", "q", function() M.close() end, { buffer = M.tbuf, desc = "LLeMbas: close the panel" })
|
||||
local function open_at_cursor()
|
||||
local token = vim.fn.expand("<cWORD>")
|
||||
if not token or token == "" then return end
|
||||
token = token:gsub("^[`\"'(%[<]+", ""):gsub("[`\"')%]>.,;:]+$", "")
|
||||
local path, line = token:match("^([%w%._%-%/]+%.[%w]+):(%d+)")
|
||||
if not path then path = token:match("^([%w%._%-%/]+%.[%w]+)$") end
|
||||
if not path then return end
|
||||
local full = path:match("^/") and path or (vim.fn.getcwd() .. "/" .. path)
|
||||
if vim.fn.filereadable(full) == 0 then return end
|
||||
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_set_current_win(target)
|
||||
pcall(vim.cmd, "edit " .. vim.fn.fnameescape(full))
|
||||
if tonumber(line) then pcall(vim.api.nvim_win_set_cursor, 0, { tonumber(line), 0 }) end
|
||||
end
|
||||
end
|
||||
vim.keymap.set("n", "<CR>", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" })
|
||||
vim.keymap.set("n", "gf", open_at_cursor, { buffer = M.tbuf, desc = "LLeMbas: open file:line under cursor" })
|
||||
vim.keymap.set("n", "g?", function() if M.on_help then M.on_help() end end, { buffer = M.ibuf, desc = "LLeMbas: help" })
|
||||
vim.keymap.set("n", "<C-k>", function()
|
||||
local tw = win_of(M.tbuf)
|
||||
if tw then vim.api.nvim_set_current_win(tw) end
|
||||
end, { buffer = M.ibuf, desc = "LLeMbas: focus transcript" })
|
||||
vim.keymap.set("i", "<C-x><C-f>", function() if M.on_files then M.on_files() end end, { buffer = M.ibuf, desc = "LLeMbas: insert @file" })
|
||||
vim.keymap.set("i", "<C-x><C-o>", function() if M.on_commands then M.on_commands() end end, { buffer = M.ibuf, desc = "LLeMbas: insert /command" })
|
||||
end
|
||||
end
|
||||
|
||||
function M.is_open() return win_of(M.tbuf) ~= nil end
|
||||
|
||||
--- Open the panel (a column on the right: the transcript, and the prompt under it).
|
||||
function M.open(width, focus)
|
||||
--- Open the panel (`opts` may be a width number or `{ width, position, prompt_height, border }`).
|
||||
function M.open(opts, focus)
|
||||
buffers()
|
||||
local width = type(opts) == "number" and opts or (opts and opts.width) or 64
|
||||
local position = type(opts) == "table" and opts.position or "right"
|
||||
local prompt_h = type(opts) == "table" and opts.prompt_height or 5
|
||||
local border = type(opts) == "table" and opts.border or "rounded"
|
||||
local back = vim.api.nvim_get_current_win()
|
||||
local tw = win_of(M.tbuf)
|
||||
if not tw then
|
||||
vim.cmd("botright vertical " .. width .. "split")
|
||||
tw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(tw, M.tbuf)
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = true }) do
|
||||
vim.wo[tw][k] = v
|
||||
end
|
||||
end
|
||||
local iw = win_of(M.ibuf)
|
||||
if not iw then
|
||||
vim.api.nvim_set_current_win(tw)
|
||||
vim.cmd("belowright 5split")
|
||||
iw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(iw, M.ibuf)
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true }) do
|
||||
vim.wo[iw][k] = v
|
||||
|
||||
if position == "float" then
|
||||
local u = vim.api.nvim_list_uis()[1]
|
||||
local cols = (u and u.width) or vim.o.columns or 120
|
||||
local rows = (u and u.height) or vim.o.lines or 36
|
||||
local w = math.min(math.max(width, 48), math.floor(cols * 0.85))
|
||||
local total_h = math.max(14, math.floor(rows * 0.8))
|
||||
local th = math.max(8, total_h - prompt_h - 3)
|
||||
local col = math.max(1, math.floor((cols - w) / 2))
|
||||
local row = math.max(1, math.floor((rows - total_h) / 2))
|
||||
if not tw then
|
||||
tw = vim.api.nvim_open_win(M.tbuf, true, {
|
||||
relative = "editor", width = w, height = th, row = row, col = col,
|
||||
style = "minimal", border = border, title = " ◈ LLeMbas ", title_pos = "center",
|
||||
})
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no" }) do
|
||||
vim.wo[tw][k] = v
|
||||
end
|
||||
end
|
||||
if not iw then
|
||||
iw = vim.api.nvim_open_win(M.ibuf, true, {
|
||||
relative = "editor", width = w, height = prompt_h, row = row + th + 2, col = col,
|
||||
style = "minimal", border = border, title = " Prompt (<CR>/<C-s> send · q close) ", title_pos = "left",
|
||||
})
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no" }) do
|
||||
vim.wo[iw][k] = v
|
||||
end
|
||||
end
|
||||
else
|
||||
if not tw then
|
||||
if position == "left" then vim.cmd("topleft vertical " .. width .. "split")
|
||||
elseif position == "bottom" then vim.cmd("botright " .. math.max(12, math.floor(vim.o.lines * 0.35)) .. "split")
|
||||
else vim.cmd("botright vertical " .. width .. "split") end
|
||||
tw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(tw, M.tbuf)
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixwidth = position ~= "bottom" }) do
|
||||
vim.wo[tw][k] = v
|
||||
end
|
||||
end
|
||||
if not iw then
|
||||
vim.api.nvim_set_current_win(tw)
|
||||
vim.cmd("belowright " .. prompt_h .. "split")
|
||||
iw = vim.api.nvim_get_current_win()
|
||||
vim.api.nvim_win_set_buf(iw, M.ibuf)
|
||||
for k, v in pairs({ wrap = true, linebreak = true, number = false, relativenumber = false, signcolumn = "no", winfixheight = true }) do
|
||||
vim.wo[iw][k] = v
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
if focus == false and vim.api.nvim_win_is_valid(back) then vim.api.nvim_set_current_win(back)
|
||||
else vim.api.nvim_set_current_win(iw) end
|
||||
elseif iw and vim.api.nvim_win_is_valid(iw) then vim.api.nvim_set_current_win(iw) end
|
||||
end
|
||||
|
||||
function M.close()
|
||||
@@ -101,6 +232,12 @@ function M.close()
|
||||
end
|
||||
end
|
||||
|
||||
--- The header line above the transcript: brand, session title, mode, model, usage.
|
||||
function M.header(text)
|
||||
local w = win_of(M.tbuf)
|
||||
if w then vim.wo[w].winbar = (text or ""):gsub("%%", "%%%%") end
|
||||
end
|
||||
|
||||
--- The line above the prompt: what the next message carries, the mode, the model.
|
||||
function M.status(text)
|
||||
local w = win_of(M.ibuf)
|
||||
@@ -115,21 +252,35 @@ local function edit(fn)
|
||||
vim.bo[M.tbuf].modifiable = true
|
||||
local ok, err = pcall(fn)
|
||||
vim.bo[M.tbuf].modifiable = false
|
||||
sync_welcome()
|
||||
if follow and tw and vim.api.nvim_win_is_valid(tw) then
|
||||
pcall(vim.api.nvim_win_set_cursor, tw, { vim.api.nvim_buf_line_count(M.tbuf), 0 })
|
||||
end
|
||||
if not ok then error(err, 0) end
|
||||
end
|
||||
|
||||
--- Add text at the end, continuing the last line.
|
||||
function M.append(text)
|
||||
local function highlight_lines(from_row, to_row, hl)
|
||||
if not hl or not valid(M.tbuf) then return end
|
||||
for r = from_row, to_row do
|
||||
pcall(vim.api.nvim_buf_set_extmark, M.tbuf, ns_hl, r, 0, { line_hl_group = hl })
|
||||
end
|
||||
end
|
||||
|
||||
--- Add text at the end, continuing the last line. Optional `hl` highlights appended lines.
|
||||
function M.append(text, hl)
|
||||
if not text or text == "" then return end
|
||||
edit(function()
|
||||
-- Inserted at the very end, so a line that is rewritten later keeps its mark.
|
||||
local parts = vim.split(text, "\n", { plain = true })
|
||||
local n = vim.api.nvim_buf_line_count(M.tbuf)
|
||||
local tail = vim.api.nvim_buf_get_lines(M.tbuf, n - 1, n, false)[1] or ""
|
||||
vim.api.nvim_buf_set_text(M.tbuf, n - 1, #tail, n - 1, #tail, parts)
|
||||
local start_row = n - 1
|
||||
vim.api.nvim_buf_set_text(M.tbuf, start_row, #tail, start_row, #tail, parts)
|
||||
if hl then
|
||||
local end_row = start_row + #parts - 1
|
||||
if parts[#parts] == "" and end_row > start_row then end_row = end_row - 1 end
|
||||
highlight_lines(start_row, end_row, hl)
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
@@ -145,22 +296,31 @@ function M.newline()
|
||||
if tail ~= "" then M.append("\n") elseif n == 1 then return end
|
||||
end
|
||||
|
||||
function M.section(title)
|
||||
function M.section(title, hl)
|
||||
buffers()
|
||||
local n, tail = last_line()
|
||||
if not (n == 1 and tail == "") then
|
||||
local first = (n == 1 and tail == "")
|
||||
if not first then
|
||||
M.newline()
|
||||
local _, t = last_line()
|
||||
local prev = vim.api.nvim_buf_get_lines(M.tbuf, -3, -2, false)[1]
|
||||
if t == "" and prev ~= "" then M.append("\n") end
|
||||
end
|
||||
M.append("## " .. title .. "\n\n")
|
||||
local header_row = vim.api.nvim_buf_line_count(M.tbuf) - 1
|
||||
M.append("## " .. title .. "\n\n", hl)
|
||||
if not first and valid(M.tbuf) then
|
||||
pcall(vim.api.nvim_buf_set_extmark, M.tbuf, ns_hl, header_row, 0, {
|
||||
virt_lines = { { { "────────────────────────────────────────", "LLeMbasSeparator" } } },
|
||||
virt_lines_above = true,
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
--- One line that is rewritten later under the same `id` (a tool call, the plan).
|
||||
function M.line(id, text)
|
||||
function M.line(id, text, hl, detail)
|
||||
buffers()
|
||||
text = (text:gsub("[\r\n]+", " "))
|
||||
if detail ~= nil then M.details[id] = detail end
|
||||
local mark = M.marks[id]
|
||||
if mark then
|
||||
local pos = vim.api.nvim_buf_get_extmark_by_id(M.tbuf, ns, mark, {})
|
||||
@@ -168,12 +328,14 @@ function M.line(id, text)
|
||||
edit(function()
|
||||
local old = vim.api.nvim_buf_get_lines(M.tbuf, pos[1], pos[1] + 1, false)[1] or ""
|
||||
vim.api.nvim_buf_set_text(M.tbuf, pos[1], 0, pos[1], #old, { text })
|
||||
vim.api.nvim_buf_clear_namespace(M.tbuf, ns_hl, pos[1], pos[1] + 1)
|
||||
if hl then highlight_lines(pos[1], pos[1], hl) end
|
||||
end)
|
||||
return
|
||||
end
|
||||
end
|
||||
M.newline()
|
||||
M.append(text)
|
||||
M.append(text, hl)
|
||||
local n = vim.api.nvim_buf_line_count(M.tbuf)
|
||||
M.marks[id] = vim.api.nvim_buf_set_extmark(M.tbuf, ns, n - 1, 0, { right_gravity = false })
|
||||
M.append("\n")
|
||||
@@ -182,10 +344,13 @@ end
|
||||
function M.clear()
|
||||
buffers()
|
||||
M.marks = {}
|
||||
M.details = {}
|
||||
vim.bo[M.tbuf].modifiable = true
|
||||
vim.api.nvim_buf_clear_namespace(M.tbuf, ns, 0, -1)
|
||||
vim.api.nvim_buf_clear_namespace(M.tbuf, ns_hl, 0, -1)
|
||||
vim.api.nvim_buf_set_lines(M.tbuf, 0, -1, false, {})
|
||||
vim.bo[M.tbuf].modifiable = false
|
||||
sync_welcome()
|
||||
end
|
||||
|
||||
function M.insert_prompt(text)
|
||||
|
||||
+113
-23
@@ -4,23 +4,58 @@
|
||||
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 }
|
||||
local st = { timer = nil, seq = 0, asked = nil, shown = nil, off = nil, said = false, last_warm = nil, installed = false }
|
||||
|
||||
local PREFIX_MAX, SUFFIX_MAX = 16000, 4000
|
||||
local REFUSALS = { no_model = true, not_allowed = true, not_logged_in = true, unsupported = true }
|
||||
|
||||
local LENGTH_PRESETS = {
|
||||
auto = { tokens = nil, instruction = "" },
|
||||
words = {
|
||||
tokens = 24,
|
||||
instruction = "Predict only a few words to finish the current expression or identifier. Stop immediately once the current token or phrase is complete.",
|
||||
},
|
||||
line = {
|
||||
tokens = 64,
|
||||
instruction = "Predict at most the remainder of the current line. Do not start a new line.",
|
||||
},
|
||||
block = {
|
||||
tokens = 256,
|
||||
instruction = "Predict a complete statement, block, or function body fitting the surrounding code.",
|
||||
},
|
||||
file = {
|
||||
tokens = 2048,
|
||||
instruction = "Predict a comprehensive continuation, up to a full multi-function section or file implementation when appropriate.",
|
||||
},
|
||||
}
|
||||
|
||||
local function L() return require("llembas") end
|
||||
|
||||
local function resolve_prediction()
|
||||
local c = L().config.complete or {}
|
||||
local preset = LENGTH_PRESETS[c.length or "auto"] or LENGTH_PRESETS.auto
|
||||
local explicit = tonumber(c.max_tokens)
|
||||
local max_tokens = (explicit and explicit > 0) and math.floor(explicit) or preset.tokens
|
||||
local parts = {}
|
||||
if preset.instruction ~= "" then parts[#parts + 1] = preset.instruction end
|
||||
if type(c.instructions) == "string" and c.instructions:match("%S") then parts[#parts + 1] = vim.trim(c.instructions) end
|
||||
local guidance = table.concat(parts, "\n")
|
||||
return max_tokens, guidance ~= "" and guidance or nil
|
||||
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.
|
||||
--- The accept keys are ours only while a suggestion is on the screen: buffer mappings 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
|
||||
if not s or not s.maps then return end
|
||||
for _, m in ipairs(s.maps) do
|
||||
pcall(vim.keymap.del, "i", m.key, { buffer = s.buf })
|
||||
if m.before and next(m.before) and m.before.buffer == 1 then pcall(vim.fn.mapset, "i", false, m.before) end
|
||||
end
|
||||
end
|
||||
|
||||
function M.clear()
|
||||
@@ -40,19 +75,25 @@ local function cancel()
|
||||
end
|
||||
|
||||
local function show(buf, row, col, text)
|
||||
require("llembas.ui").setup_highlights()
|
||||
M.clear()
|
||||
local lines = vim.split(text, "\n", { plain = true })
|
||||
local opts = { virt_text = { { lines[1], "Comment" } }, virt_text_pos = "inline" }
|
||||
local opts = { virt_text = { { lines[1], "LLeMbasGhost" } }, 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
|
||||
for i = 2, #lines do opts.virt_lines[#opts.virt_lines + 1] = { { lines[i], "LLeMbasGhost" } } 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
|
||||
st.shown = { buf = buf, text = text, mark = vim.api.nvim_buf_set_extmark(buf, ns, row, col, opts), maps = {} }
|
||||
local c = L().config.complete
|
||||
local function bind(key, fn, desc)
|
||||
if not key or key == "" then return end
|
||||
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" })
|
||||
st.shown.maps[#st.shown.maps + 1] = { key = key, before = before }
|
||||
vim.keymap.set("i", key, fn, { buffer = buf, nowait = true, desc = desc })
|
||||
end
|
||||
bind(c.accept, function() M.accept() end, "LLeMbas: accept the suggestion")
|
||||
if c.accept_word and c.accept_word ~= "" and c.accept_word ~= c.accept then
|
||||
bind(c.accept_word, function() M.accept_word() end, "LLeMbas: accept next word of suggestion")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -133,25 +174,40 @@ function M.request(manual)
|
||||
local id = ("c%d"):format(seq)
|
||||
st.asked = id
|
||||
local name = vim.api.nvim_buf_get_name(buf)
|
||||
conn:request("_lembas/complete", {
|
||||
local max_tokens, guidance = resolve_prediction()
|
||||
local params = {
|
||||
id = id, prefix = prefix, suffix = suffix, path = name ~= "" and name or nil,
|
||||
language = vim.bo[buf].filetype ~= "" and vim.bo[buf].filetype or nil,
|
||||
cwd = vim.fn.getcwd(),
|
||||
sessionId = L()._state.session,
|
||||
open = open_snippets(buf),
|
||||
model = L().config.complete.model,
|
||||
}, function(err, r)
|
||||
max_tokens = max_tokens,
|
||||
}
|
||||
if guidance then
|
||||
params.context = { { path = "llembas:autocomplete-instructions", text = guidance } }
|
||||
end
|
||||
conn:request("_lembas/complete", params, 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)
|
||||
local reason = (type(err.data) == "table" and type(err.data.reason) == "string") and err.data.reason or ""
|
||||
local msg = tostring(err.message or "completion failed")
|
||||
if REFUSALS[reason] or reason == "" then
|
||||
-- Permanent refusal (e.g. no model): said once, stops asking until a model is chosen.
|
||||
st.off = msg
|
||||
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
|
||||
else
|
||||
-- Transient server failure: pause briefly instead of shutting off permanently.
|
||||
st.wait_until = vim.uv.now() + 15000
|
||||
if manual then vim.notify("LLeMbas: " .. msg, vim.log.levels.WARN) end
|
||||
end
|
||||
return
|
||||
end
|
||||
if manual and st.off then st.off, st.said = nil, false end
|
||||
if not r or r.cancelled or type(r.text) ~= "string" or r.text == "" then return end
|
||||
if vim.api.nvim_get_current_buf() ~= buf or not M._typing() then return end
|
||||
local now = vim.api.nvim_win_get_cursor(0)
|
||||
@@ -179,18 +235,51 @@ function M.accept()
|
||||
return true
|
||||
end
|
||||
|
||||
--- Accept only the next word (or line break) of the shown suggestion, keeping the rest visible.
|
||||
function M.accept_word()
|
||||
local s = st.shown
|
||||
if not s or s.buf ~= vim.api.nvim_get_current_buf() then return false end
|
||||
local pos = vim.api.nvim_buf_get_extmark_by_id(s.buf, ns, s.mark, {})
|
||||
if not pos[1] then M.clear(); return false end
|
||||
local chunk = s.text:match("^%s*[%w_]+") or s.text:match("^%s*[^\n%s]") or s.text:match("^\n[ \t]*") or s.text
|
||||
if chunk == s.text then return M.accept() end
|
||||
local rest = s.text:sub(#chunk + 1)
|
||||
local buf = s.buf
|
||||
M.clear()
|
||||
st.seq = st.seq + 1
|
||||
local at_row, at_col = pos[1], pos[2]
|
||||
local lines = vim.split(chunk, "\n", { plain = true })
|
||||
vim.api.nvim_buf_set_text(buf, at_row, at_col, at_row, at_col, lines)
|
||||
local new_row = at_row + #lines
|
||||
local new_col = #lines == 1 and (at_col + #lines[1]) or #lines[#lines]
|
||||
vim.api.nvim_win_set_cursor(0, { new_row, new_col })
|
||||
if rest ~= "" then show(buf, new_row - 1, new_col, rest) end
|
||||
return true
|
||||
end
|
||||
|
||||
function M.dismiss()
|
||||
M.clear()
|
||||
cancel()
|
||||
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
|
||||
if c.auto then
|
||||
if not st.installed then M.setup() end
|
||||
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, st.last_warm = nil, false, nil end
|
||||
--- A model or token/instruction setting was chosen: ask again.
|
||||
function M.reset() st.off, st.said, st.last_warm, st.wait_until = nil, false, nil, nil end
|
||||
|
||||
local function typed()
|
||||
M.clear()
|
||||
@@ -205,6 +294,7 @@ local function typed()
|
||||
end
|
||||
|
||||
function M.setup()
|
||||
st.installed = true
|
||||
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 })
|
||||
|
||||
@@ -27,12 +27,13 @@ function M.selection(buf, first, last)
|
||||
return blocks
|
||||
end
|
||||
|
||||
--- The diagnostics on lines `first..last`, as one text; nil when there are none.
|
||||
--- The diagnostics on lines `first..last` (or the whole buffer when nil), as one text; nil when none.
|
||||
function M.diagnostics(buf, first, last)
|
||||
local out = {}
|
||||
for _, d in ipairs(vim.diagnostic.get(buf)) do
|
||||
local l = d.lnum + 1
|
||||
if l >= first and l <= last and #out < 30 then
|
||||
local in_range = (not first or not last) or (l >= first and l <= last)
|
||||
if in_range and #out < 30 then
|
||||
local sev = vim.diagnostic.severity[d.severity] or "INFO"
|
||||
out[#out + 1] = ("- line %d, %s%s: %s"):format(l, sev:lower(), d.source and (" (" .. d.source .. ")") or "", (d.message:gsub("%s+", " ")))
|
||||
end
|
||||
@@ -45,13 +46,15 @@ end
|
||||
function M.file(buf)
|
||||
local _, name = uri_of(buf)
|
||||
if not name then return nil end
|
||||
local row = vim.api.nvim_win_get_cursor(0)[1]
|
||||
local win = vim.fn.bufwinid(buf)
|
||||
local row = win ~= -1 and vim.api.nvim_win_get_cursor(win)[1] or 1
|
||||
return { type = "text", text = ("Open in the editor: %s, cursor on line %d%s."):format(
|
||||
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.
|
||||
--- The same as data, for an agent that takes it so (`_meta.lembas.editor`): the file, the cursor,
|
||||
--- diagnostics (selected lines, or buffer errors/warnings when nothing is selected), and open files.
|
||||
--- Lines are 1-based, inclusive.
|
||||
function M.editor(buf, first, last)
|
||||
local _, name = uri_of(buf)
|
||||
local out = {}
|
||||
@@ -61,16 +64,41 @@ function M.editor(buf, first, last)
|
||||
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
|
||||
local raw = vim.diagnostic.get(buf)
|
||||
table.sort(raw, function(a, b)
|
||||
if (a.severity or 9) ~= (b.severity or 9) then return (a.severity or 9) < (b.severity or 9) end
|
||||
return (a.lnum or 0) < (b.lnum or 0)
|
||||
end)
|
||||
local diags = {}
|
||||
for _, d in ipairs(raw) do
|
||||
local l = d.lnum + 1
|
||||
local keep
|
||||
if first and last then
|
||||
keep = l >= first and l <= last
|
||||
else
|
||||
keep = (d.severity or vim.diagnostic.severity.INFO) <= vim.diagnostic.severity.WARN
|
||||
end
|
||||
if keep and #diags < 20 then
|
||||
diags[#diags + 1] = { path = name, line = l, severity = (vim.diagnostic.severity[d.severity] or "INFO"):lower(),
|
||||
message = (d.message:gsub("%s+", " ")):sub(1, 300), source = d.source }
|
||||
end
|
||||
end
|
||||
if #diags > 0 then out.diagnostics = diags end
|
||||
local open = {}
|
||||
local seen = {}
|
||||
if name then seen[name] = true end
|
||||
for _, b in ipairs(vim.api.nvim_list_bufs()) do
|
||||
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
|
||||
seen[p] = true
|
||||
open[#open + 1] = p
|
||||
end
|
||||
end
|
||||
if #diags > 0 then out.diagnostics = diags end
|
||||
end
|
||||
if #open > 0 then out.open = open end
|
||||
if next(out) == nil then return nil end
|
||||
return out
|
||||
end
|
||||
|
||||
+108
-16
@@ -4,11 +4,14 @@
|
||||
local M = {}
|
||||
local ns = vim.api.nvim_create_namespace("llembas-diff")
|
||||
|
||||
local proposals = {} -- buf -> list of pending hunks { mark, old_count, new, above }
|
||||
local proposals = {} -- buf -> list of pending hunks { mark, mark2, hint, old_count, new, above }
|
||||
local rewriting = {} -- buf -> active request id
|
||||
local req_seq = 0
|
||||
local written_by_id = {}
|
||||
|
||||
local function count(buf) return #(proposals[buf] or {}) end
|
||||
|
||||
local KEYS = { "ga", "gr", "gA", "gR" }
|
||||
local KEYS = { "ga", "gr", "gA", "gR", "]h", "[h" }
|
||||
local saved = {} -- buf -> the buffer mappings these keys had before
|
||||
|
||||
local function unmap(buf)
|
||||
@@ -20,6 +23,7 @@ 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
|
||||
if hunk.hint then pcall(vim.api.nvim_buf_del_extmark, buf, ns, hunk.hint) 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
|
||||
@@ -68,6 +72,40 @@ local function nearest(buf)
|
||||
return best or list[#list]
|
||||
end
|
||||
|
||||
function M.next_hunk()
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
local list = proposals[buf] or {}
|
||||
if #list == 0 then return end
|
||||
local rows = {}
|
||||
for _, h in ipairs(list) do
|
||||
local r = row_of(buf, h)
|
||||
if r then rows[#rows + 1] = r end
|
||||
end
|
||||
table.sort(rows)
|
||||
local cur = vim.api.nvim_win_get_cursor(0)[1] - 1
|
||||
for _, r in ipairs(rows) do
|
||||
if r > cur then return pcall(vim.api.nvim_win_set_cursor, 0, { r + 1, 0 }) end
|
||||
end
|
||||
if rows[1] then pcall(vim.api.nvim_win_set_cursor, 0, { rows[1] + 1, 0 }) end
|
||||
end
|
||||
|
||||
function M.prev_hunk()
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
local list = proposals[buf] or {}
|
||||
if #list == 0 then return end
|
||||
local rows = {}
|
||||
for _, h in ipairs(list) do
|
||||
local r = row_of(buf, h)
|
||||
if r then rows[#rows + 1] = r end
|
||||
end
|
||||
table.sort(rows)
|
||||
local cur = vim.api.nvim_win_get_cursor(0)[1] - 1
|
||||
for i = #rows, 1, -1 do
|
||||
if rows[i] < cur then return pcall(vim.api.nvim_win_set_cursor, 0, { rows[i] + 1, 0 }) end
|
||||
end
|
||||
if rows[#rows] then pcall(vim.api.nvim_win_set_cursor, 0, { rows[#rows] + 1, 0 }) end
|
||||
end
|
||||
|
||||
function M.accept(all)
|
||||
local buf = vim.api.nvim_get_current_buf()
|
||||
if all then
|
||||
@@ -95,25 +133,28 @@ 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
|
||||
for _, l in ipairs(lines) do out[#out + 1] = { { l == "" and " " or l, "LLeMbasDiffAdd" } } 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)
|
||||
require("llembas.ui").setup_highlights()
|
||||
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
|
||||
for i, 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 }
|
||||
local hint_row
|
||||
if a_count > 0 then
|
||||
local row = first - 1 + a_start - 1
|
||||
hint_row = row
|
||||
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 })
|
||||
end_row = row + a_count, hl_group = "LLeMbasDiffDelete", 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
|
||||
@@ -123,9 +164,19 @@ function M.propose(buf, first, last, new)
|
||||
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))
|
||||
hint_row = row
|
||||
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
|
||||
if i == 1 and hint_row then
|
||||
local label = #hunks > 1
|
||||
and (" ◈ LLeMbas (%d changes): ga accept · gr reject · gA/gR all · ]h/[h jump"):format(#hunks)
|
||||
or " ◈ LLeMbas: ga accept · gr reject"
|
||||
hunk.hint = vim.api.nvim_buf_set_extmark(buf, ns, hint_row, 0, {
|
||||
virt_text = { { label, "LLeMbasDiffHint" } },
|
||||
virt_text_pos = "eol",
|
||||
})
|
||||
end
|
||||
table.insert(proposals[buf], hunk)
|
||||
end
|
||||
if not saved[buf] then
|
||||
@@ -140,6 +191,8 @@ function M.propose(buf, first, last, new)
|
||||
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")
|
||||
map("]h", function() M.next_hunk() end, "LLeMbas: next proposed change")
|
||||
map("[h", function() M.prev_hunk() end, "LLeMbas: previous proposed change")
|
||||
return #hunks
|
||||
end
|
||||
|
||||
@@ -148,36 +201,63 @@ 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, {})
|
||||
local id = (params and params.id) or "default"
|
||||
written_by_id[id] = (written_by_id[id] or 0) + #((params and params.delta) or "")
|
||||
vim.api.nvim_echo({ { ("LLeMbas is rewriting… %d characters"):format(written_by_id[id]), "Comment" } }, false, {})
|
||||
end
|
||||
|
||||
--- Have lines `first..last` rewritten as `instruction` says, and show the result as hunks.
|
||||
function M.rewrite(buf, first, last, instruction)
|
||||
--- Cancel an in-flight rewrite or generation in the current buffer.
|
||||
function M.cancel(buf)
|
||||
buf = buf or vim.api.nvim_get_current_buf()
|
||||
local id = rewriting[buf]
|
||||
if not id then return false end
|
||||
rewriting[buf] = nil
|
||||
written_by_id[id] = nil
|
||||
local conn = require("llembas")._state.conn
|
||||
if conn then conn:notify("_lembas/edit/cancel", { id = id }) end
|
||||
vim.api.nvim_echo({ { "" } }, false, {})
|
||||
vim.notify("LLeMbas: cancelled the rewrite", vim.log.levels.INFO)
|
||||
return true
|
||||
end
|
||||
|
||||
local function run_edit(buf, first, last, instruction, verb)
|
||||
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
|
||||
if rewriting[buf] then
|
||||
return vim.notify("LLeMbas: a rewrite of this buffer is already running (:LLeMbasCancelEdit cancels it)", 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, {})
|
||||
req_seq = req_seq + 1
|
||||
local id = ("e%d"):format(req_seq)
|
||||
rewriting[buf] = id
|
||||
written_by_id[id] = 0
|
||||
vim.api.nvim_echo({ { "LLeMbas is " .. verb .. "…", "Comment" } }, false, {})
|
||||
L._connect(function(conn)
|
||||
if not conn then return vim.notify("LLeMbas: the agent did not start", vim.log.levels.ERROR) end
|
||||
if not conn then
|
||||
rewriting[buf] = nil
|
||||
written_by_id[id] = nil
|
||||
return vim.notify("LLeMbas: the agent did not start", vim.log.levels.ERROR)
|
||||
end
|
||||
local body_text = table.concat(text, "\n")
|
||||
if body_text == "" then body_text = " " 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"),
|
||||
id = id, cwd = vim.fn.getcwd(), sessionId = L._state.session, path = name ~= "" and name or nil,
|
||||
text = body_text, before = table.concat(before, "\n"), after = table.concat(after, "\n"),
|
||||
language = vim.bo[buf].filetype, instruction = instruction, model = L.config.model,
|
||||
}, function(err, r)
|
||||
if rewriting[buf] == id then rewriting[buf] = nil end
|
||||
written_by_id[id] = nil
|
||||
vim.api.nvim_echo({ { "" } }, false, {})
|
||||
if err then return vim.notify("LLeMbas: " .. tostring(err.message), vim.log.levels.ERROR) end
|
||||
if not vim.api.nvim_buf_is_valid(buf) then return end
|
||||
if not r or r.cancelled or not vim.api.nvim_buf_is_valid(buf) then return end
|
||||
if vim.api.nvim_buf_get_changedtick(buf) ~= tick then
|
||||
return vim.notify("LLeMbas: the buffer changed while the rewrite was written; nothing is shown. Ask again.", vim.log.levels.WARN)
|
||||
end
|
||||
@@ -190,6 +270,16 @@ function M.rewrite(buf, first, last, instruction)
|
||||
end)
|
||||
end
|
||||
|
||||
--- Have lines `first..last` rewritten as `instruction` says, and show the result as hunks.
|
||||
function M.rewrite(buf, first, last, instruction)
|
||||
run_edit(buf, first, last, instruction, "rewriting")
|
||||
end
|
||||
|
||||
--- Generate code at 1-based `row` as `instruction` says, and show the result as hunks.
|
||||
function M.generate(buf, row, instruction)
|
||||
run_edit(buf, row, row, "At this line, " .. instruction, "generating")
|
||||
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)
|
||||
@@ -205,11 +295,13 @@ function M.preview(content)
|
||||
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.bo[b].undolevels = -1
|
||||
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)
|
||||
vim.wo[w].winbar = " ◈ LLeMbas proposed diff "
|
||||
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
|
||||
|
||||
+642
-120
File diff suppressed because it is too large.
Load diff
@@ -2,6 +2,8 @@
|
||||
local M = {}
|
||||
M.__index = M
|
||||
|
||||
local MAX_BUF_BYTES = 64 * 1024 * 1024 -- 64 MB cap against an unbounded unterminated stream
|
||||
|
||||
--- Start `cmd` and speak JSON-RPC with it. `on.request(method, params, reply)` and
|
||||
--- `on.notify(method, params)` run on the main loop; `on.exit(code, stderr)` when the process ends.
|
||||
function M.start(cmd, on, opts)
|
||||
@@ -32,6 +34,11 @@ function M.start(cmd, on, opts)
|
||||
end
|
||||
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
-- Visual design, highlights, floating cards and formatting helpers for llembas.nvim.
|
||||
-- Every colour links to standard Neovim highlight groups with `default = true`, so any
|
||||
-- colorscheme looks cohesive and users can override individual `LLeMbas*` groups.
|
||||
local M = {}
|
||||
|
||||
local HIGHLIGHTS = {
|
||||
LLeMbasBrand = { link = "Special" },
|
||||
LLeMbasUserHeader = { link = "Title" },
|
||||
LLeMbasAgentHeader = { link = "Function" },
|
||||
LLeMbasThoughtHeader = { link = "Comment" },
|
||||
LLeMbasThought = { link = "Comment" },
|
||||
LLeMbasToolPending = { link = "DiagnosticWarn" },
|
||||
LLeMbasToolDone = { link = "DiagnosticOk" },
|
||||
LLeMbasToolFail = { link = "DiagnosticError" },
|
||||
LLeMbasToolDenied = { link = "DiagnosticWarn" },
|
||||
LLeMbasToolKind = { link = "Tag" },
|
||||
LLeMbasToolMeta = { link = "Comment" },
|
||||
LLeMbasPlanHeader = { link = "Title" },
|
||||
LLeMbasPlanBar = { link = "DiagnosticOk" },
|
||||
LLeMbasPlanDone = { link = "DiagnosticOk" },
|
||||
LLeMbasPlanActive = { link = "DiagnosticInfo" },
|
||||
LLeMbasPlanPending = { link = "Comment" },
|
||||
LLeMbasNote = { link = "Comment" },
|
||||
LLeMbasWarn = { link = "DiagnosticWarn" },
|
||||
LLeMbasError = { link = "DiagnosticError" },
|
||||
LLeMbasDiffAdd = { link = "DiffAdd" },
|
||||
LLeMbasDiffDelete = { link = "DiffDelete" },
|
||||
LLeMbasDiffHint = { link = "DiagnosticVirtualTextInfo" },
|
||||
LLeMbasGhost = { link = "Comment" },
|
||||
LLeMbasSeparator = { link = "WinSeparator" },
|
||||
LLeMbasStatusBrand = { link = "Special" },
|
||||
LLeMbasStatusMode = { link = "DiagnosticInfo" },
|
||||
LLeMbasStatusModel = { link = "Comment" },
|
||||
LLeMbasStatusBusy = { link = "DiagnosticWarn" },
|
||||
LLeMbasStatusAttach = { link = "DiagnosticHint" },
|
||||
}
|
||||
|
||||
local hi_installed = false
|
||||
|
||||
function M.setup_highlights()
|
||||
for name, spec in pairs(HIGHLIGHTS) do
|
||||
vim.api.nvim_set_hl(0, name, vim.tbl_extend("force", { default = true }, spec))
|
||||
end
|
||||
if not hi_installed then
|
||||
hi_installed = true
|
||||
local group = vim.api.nvim_create_augroup("llembas-highlights", { clear = true })
|
||||
vim.api.nvim_create_autocmd("ColorScheme", {
|
||||
group = group,
|
||||
callback = function()
|
||||
for name, spec in pairs(HIGHLIGHTS) do
|
||||
vim.api.nvim_set_hl(0, name, vim.tbl_extend("force", { default = true }, spec))
|
||||
end
|
||||
end,
|
||||
})
|
||||
end
|
||||
end
|
||||
|
||||
function M.format_tokens(n)
|
||||
local v = tonumber(n) or 0
|
||||
if v >= 1000000 then return ("%.1fM"):format(v / 1000000) end
|
||||
if v >= 1000 then return ("%.1fk"):format(v / 1000) end
|
||||
return tostring(math.floor(v))
|
||||
end
|
||||
|
||||
function M.format_ms(ms)
|
||||
local v = tonumber(ms)
|
||||
if not v or v < 0 then return "" end
|
||||
if v < 1000 then return ("%dms"):format(math.floor(v + 0.5)) end
|
||||
return ("%.1fs"):format(v / 1000)
|
||||
end
|
||||
|
||||
function M.progress_bar(done, total, width)
|
||||
width = width or 12
|
||||
if not total or total <= 0 then return "" end
|
||||
local ratio = math.max(0, math.min(1, done / total))
|
||||
local filled = math.floor(ratio * width + 0.5)
|
||||
return "[" .. string.rep("█", filled) .. string.rep("░", width - filled) .. "]"
|
||||
end
|
||||
|
||||
--- Welcome virtual lines shown in an empty transcript (never written to the buffer text).
|
||||
function M.welcome_virt_lines()
|
||||
return {
|
||||
{ { "", "Normal" } },
|
||||
{ { " ◈ ", "LLeMbasBrand" }, { "LLeMbas", "LLeMbasUserHeader" }, { " · Waybread for the code ahead.", "LLeMbasNote" } },
|
||||
{ { " ────────────────────────────────────────────", "LLeMbasSeparator" } },
|
||||
{ { " Prompt: ", "LLeMbasNote" }, { "<CR>/<C-s>", "LLeMbasToolKind" }, { " send ", "LLeMbasNote" }, { "<C-c>", "LLeMbasToolKind" }, { " stop ", "LLeMbasNote" }, { "q", "LLeMbasToolKind" }, { " close", "LLeMbasNote" } },
|
||||
{ { " Chat: ", "LLeMbasNote" }, { "<CR>/gf", "LLeMbasToolKind" }, { " open file ", "LLeMbasNote" }, { "K", "LLeMbasToolKind" }, { " output ", "LLeMbasNote" }, { "y", "LLeMbasToolKind" }, { " yank code ", "LLeMbasNote" }, { "g?", "LLeMbasToolKind" }, { " help", "LLeMbasNote" } },
|
||||
{ { " Tools: ", "LLeMbasNote" }, { ":LLeMbasAsk", "LLeMbasAgentHeader" }, { " ", "Normal" }, { ":LLeMbasEdit", "LLeMbasAgentHeader" }, { " ", "Normal" }, { ":LLeMbasGenerate", "LLeMbasAgentHeader" }, { " ", "Normal" }, { ":LLeMbasFiles", "LLeMbasAgentHeader" } },
|
||||
{ { " Models: ", "LLeMbasNote" }, { ":LLeMbasAutocompleteTokens", "LLeMbasAgentHeader" }, { " ", "Normal" }, { ":LLeMbasSessions", "LLeMbasAgentHeader" } },
|
||||
}
|
||||
end
|
||||
|
||||
--- Open a read-only floating window with rounded borders (`q` or `<Esc>` closes).
|
||||
function M.float(title, lines, opts)
|
||||
opts = opts or {}
|
||||
local b = vim.api.nvim_create_buf(false, true)
|
||||
vim.bo[b].buftype = "nofile"
|
||||
vim.bo[b].bufhidden = "wipe"
|
||||
vim.bo[b].swapfile = false
|
||||
vim.bo[b].modeline = false
|
||||
vim.bo[b].undolevels = -1
|
||||
vim.api.nvim_buf_set_lines(b, 0, -1, false, lines)
|
||||
if opts.filetype then vim.bo[b].filetype = opts.filetype end
|
||||
vim.bo[b].modifiable = false
|
||||
|
||||
local max_w = 0
|
||||
for _, l in ipairs(lines) do
|
||||
local w = vim.fn.strdisplaywidth(l)
|
||||
if w > max_w then max_w = w end
|
||||
end
|
||||
local ui = vim.api.nvim_list_uis()[1]
|
||||
local cols = (ui and ui.width) or vim.o.columns or 100
|
||||
local rows = (ui and ui.height) or vim.o.lines or 30
|
||||
local width = math.min(math.max(max_w + 4, 44), math.max(44, math.floor(cols * 0.8)))
|
||||
local height = math.min(math.max(#lines, 4), math.max(6, math.floor(rows * 0.7)))
|
||||
local win = vim.api.nvim_open_win(b, opts.enter ~= false, {
|
||||
relative = "editor",
|
||||
width = width,
|
||||
height = height,
|
||||
row = math.max(1, math.floor((rows - height) / 2) - 1),
|
||||
col = math.max(1, math.floor((cols - width) / 2)),
|
||||
style = "minimal",
|
||||
border = opts.border or "rounded",
|
||||
title = title and (" " .. title .. " ") or nil,
|
||||
title_pos = title and "center" or nil,
|
||||
})
|
||||
vim.wo[win].wrap = true
|
||||
vim.wo[win].linebreak = true
|
||||
local function close()
|
||||
if vim.api.nvim_win_is_valid(win) then pcall(vim.api.nvim_win_close, win, true) end
|
||||
end
|
||||
vim.keymap.set("n", "q", close, { buffer = b, nowait = true, desc = "LLeMbas: close window" })
|
||||
vim.keymap.set("n", "<Esc>", close, { buffer = b, nowait = true, desc = "LLeMbas: close window" })
|
||||
return win, close
|
||||
end
|
||||
|
||||
return M
|
||||
@@ -13,17 +13,29 @@ cmd("LLeMbasAsk", function(o) L().ask(o.line1, o.line2, o.args) end,
|
||||
{ range = true, nargs = "*", desc = "LLeMbas: ask about the selected lines" })
|
||||
cmd("LLeMbasEdit", function(o) L().edit(o.line1, o.line2, o.args) end,
|
||||
{ range = true, nargs = "*", desc = "LLeMbas: have the selected lines rewritten" })
|
||||
cmd("LLeMbasGenerate", function(o) L().generate(o.args) end,
|
||||
{ nargs = "*", desc = "LLeMbas: generate code at the cursor" })
|
||||
cmd("LLeMbasCancelEdit", function() require("llembas.diff").cancel() end,
|
||||
{ desc = "LLeMbas: cancel an in-flight rewrite or generation" })
|
||||
cmd("LLeMbasStop", function() L().stop() end, { desc = "LLeMbas: stop the running turn" })
|
||||
cmd("LLeMbasNew", function(o) L().new(o.bang) end, { bang = true, desc = "LLeMbas: start a new session (! also while a turn hangs)" })
|
||||
cmd("LLeMbasCompact", function() L().compact() end, { desc = "LLeMbas: compact session context" })
|
||||
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("LLeMbasNextHunk", function() require("llembas.diff").next_hunk() end, { desc = "LLeMbas: jump to next proposed change" })
|
||||
cmd("LLeMbasPrevHunk", function() require("llembas.diff").prev_hunk() end, { desc = "LLeMbas: jump to previous proposed change" })
|
||||
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("LLeMbasAutocompleteTokens", function(o) L().autocomplete_tokens(o.args) end,
|
||||
{ nargs = "?", complete = function() return { "auto", "words", "line", "block", "file", "24", "64", "256", "1024", "2048" } end,
|
||||
desc = "LLeMbas: set autocomplete max tokens or prediction length preset" })
|
||||
cmd("LLeMbasAutocompleteInstructions", function(o) L().autocomplete_instructions(o.args) end,
|
||||
{ nargs = "*", desc = "LLeMbas: set custom instructions for autocomplete (- clears)" })
|
||||
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,
|
||||
@@ -33,7 +45,11 @@ 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" })
|
||||
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,
|
||||
{ range = true, desc = "LLeMbas: explain the selected lines" })
|
||||
cmd("LLeMbasFix", function() L().fix() end, { desc = "LLeMbas: fix diagnostics in the current buffer" })
|
||||
cmd("LLeMbasToggleThoughts", function() L().toggle_thoughts() end, { desc = "LLeMbas: toggle showing model thinking" })
|
||||
cmd("LLeMbasStatus", function() L().status_popup() end, { desc = "LLeMbas: show agent, session and autocomplete status" })
|
||||
cmd("LLeMbasHelp", function() L().help() end, { desc = "LLeMbas: show commands and keymaps" })
|
||||
@@ -165,7 +165,7 @@ def main():
|
||||
elif method == "initialize":
|
||||
result = {"protocolVersion": 1, "agentCapabilities": {}}
|
||||
if EDITOR:
|
||||
result["_meta"] = {"lembas": {"capabilities": ["editor", "media", "files", "steer", "sessions", "ask", "plan"]}}
|
||||
result["_meta"] = {"lembas": {"capabilities": ["editor", "media", "files", "commands", "steer", "sessions", "ask", "plan", "compact"]}}
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": result})
|
||||
elif method == "_lembas/complete":
|
||||
threading.Thread(target=complete, args=(msg,), daemon=True).start()
|
||||
@@ -175,17 +175,25 @@ def main():
|
||||
pass
|
||||
elif method == "_lembas/files/search":
|
||||
q = str((msg.get("params") or {}).get("query") or "").lower()
|
||||
sample = ["sample.py", "other.py"]
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"files": [f for f in sample if not q or q in f.lower()]}})
|
||||
sample = [{"path": "sample.py", "kind": "file"}, {"path": "other.py", "kind": "file"}, {"path": "sub", "kind": "dir"}]
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"root": os.getcwd(), "files": [f for f in sample if not q or q in f["path"].lower()]}})
|
||||
elif method == "_lembas/commands":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"commands": [{"name": "review", "description": "Review changes", "_meta": {"lembas": {"kind": "builtin"}}}]}})
|
||||
elif method == "_lembas/session/compact":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"summary": "Compacted 1 turn."}})
|
||||
elif method == "_lembas/steer":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"queued": True}})
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"queued": 1}})
|
||||
elif method == "_lembas/sessions/list":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {"sessions": [{"id": "ses_prev", "title": "Previous run", "model": "example/model-a"}]}})
|
||||
elif method == "_lembas/sessions/resume":
|
||||
out({"jsonrpc": "2.0", "id": msg["id"], "result": {
|
||||
"sessionId": "ses_prev",
|
||||
"title": "Previous run",
|
||||
"modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]},
|
||||
"turns": [{"user": "old prompt", "assistant": "old reply", "tools": []}],
|
||||
"turns": [
|
||||
{"role": "user", "text": "old prompt"},
|
||||
{"role": "assistant", "text": "old reply", "reasoning": "", "tools": [{"id": "h1", "name": "read", "args": "{}", "output": "file text"}]},
|
||||
],
|
||||
"_meta": {"lembas": {"model": "example/model-a", "mode": "edit"}},
|
||||
}})
|
||||
elif method == "_lembas/edit":
|
||||
|
||||
+55
-3
@@ -415,16 +415,68 @@ vim.ui.select = function(items, opts, cb)
|
||||
return cb(items[1])
|
||||
end
|
||||
type_and_send("QUESTION")
|
||||
check("question: interactive answer reaches agent", idle() and chat.text():find("SQLite", 1, true) ~= nil, chat.text())
|
||||
check("question: interactive spec-compliant Answer reaches agent",
|
||||
idle() and chat.text():find('"kind": "options"', 1, true) ~= nil and chat.text():find("SQLite", 1, true) ~= nil, chat.text())
|
||||
type_and_send("PLANCARD")
|
||||
check("plan: interactive approval reaches agent", idle() and chat.text():find("approve", 1, true) ~= nil, chat.text())
|
||||
vim.cmd("LLeMbasFiles other")
|
||||
check("files: attaches @path into prompt",
|
||||
check("files: attaches @path from real CLI {path, kind} entries",
|
||||
wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("@other.py", 1, true) ~= nil end))
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
|
||||
vim.cmd("LLeMbasCommands")
|
||||
check("commands: picks and inserts /command into prompt",
|
||||
wait(function() return table.concat(vim.api.nvim_buf_get_lines(chat.ibuf, 0, -1, false), ""):find("/review", 1, true) ~= nil end))
|
||||
vim.api.nvim_buf_set_lines(chat.ibuf, 0, -1, false, {})
|
||||
vim.cmd("LLeMbasSessions")
|
||||
check("sessions: resumes previous session and replays history",
|
||||
check("sessions: resumes previous session and replays real CLI historyTurns",
|
||||
wait(function() return L._state.session == "ses_prev" and chat.text():find("old reply", 1, true) ~= nil end), chat.text())
|
||||
vim.cmd("LLeMbasCompact")
|
||||
check("compact: compacts session and prints summary note",
|
||||
wait(function() return chat.text():find("Compacted 1 turn", 1, true) ~= nil end), chat.text())
|
||||
|
||||
-- Autocomplete tokens preset, custom instructions & word-by-word acceptance.
|
||||
vim.cmd("LLeMbasAutocompleteTokens block")
|
||||
check("autocomplete tokens: preset sets scope and token cap",
|
||||
L.config.complete.length == "block" and L.config.complete.max_tokens == 256)
|
||||
vim.cmd("LLeMbasAutocompleteInstructions Keep it concise")
|
||||
check("autocomplete instructions: sets custom instructions",
|
||||
L.config.complete.instructions == "Keep it concise")
|
||||
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)
|
||||
local c_last = calls("_lembas/complete")
|
||||
local req = c_last[#c_last]
|
||||
check("autocomplete tuning: max_tokens and instructions context reach _lembas/complete",
|
||||
req and req.max_tokens == 256 and req.context and req.context[1].path == "llembas:autocomplete-instructions"
|
||||
and req.context[1].text:find("Keep it concise", 1, true) ~= nil, vim.inspect(req))
|
||||
check("autocomplete accept_word: inserts first word and keeps remaining ghost text",
|
||||
C.accept_word() and vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1] == "def TWOtail" and ghost(obuf) ~= nil,
|
||||
vim.inspect({ vim.api.nvim_buf_get_lines(obuf, 0, 1, false)[1], ghost(obuf) }))
|
||||
C.clear()
|
||||
|
||||
-- :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" } })
|
||||
vim.cmd("LLeMbasFix")
|
||||
idle()
|
||||
all = sent()
|
||||
for i = #all, 1, -1 do if all[i].method == "session/prompt" then pr = all[i].params break end end
|
||||
check("fix: buffer diagnostics reach agent in _meta.lembas.editor.diagnostics",
|
||||
pr and pr._meta and pr._meta.lembas and pr._meta.lembas.editor and pr._meta.lembas.editor.diagnostics
|
||||
and pr._meta.lembas.editor.diagnostics[1].message == "broken syntax", vim.inspect(pr))
|
||||
vim.diagnostic.reset(d_ns, obuf)
|
||||
|
||||
-- :LLeMbasGenerate & statusline.
|
||||
vim.api.nvim_set_current_win(vim.fn.bufwinid(obuf))
|
||||
vim.api.nvim_buf_set_lines(obuf, 0, -1, false, { "x = 1" })
|
||||
vim.api.nvim_win_set_cursor(0, { 1, 0 })
|
||||
vim.cmd("LLeMbasGenerate write helper")
|
||||
check("generate: proposes inline diff hunks at cursor", wait(function() return D.pending(obuf) > 0 end))
|
||||
check("statusline: reports pending changes", L.statusline():find("change", 1, true) ~= nil, L.statusline())
|
||||
vim.cmd("LLeMbasReject!")
|
||||
check("statusline: reports active session mode and model", L.statusline():find("edit", 1, true) ~= nil, L.statusline())
|
||||
|
||||
vim.notify = notify
|
||||
|
||||
|
||||
+58
-79
@@ -1,16 +1,14 @@
|
||||
# LLeMbas for VS Code and VSCodium
|
||||
|
||||
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.
|
||||
LLeMbas in the editor: an agentic chat beside your files, questions and plans as interactive cards,
|
||||
rewriting and generating code as inline diffs, session resume, `@file` and `/command` completion,
|
||||
and tunable inline 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.
|
||||
@@ -44,74 +42,67 @@ 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.
|
||||
**Chat.** The LLeMbas icon in the activity bar opens the chat. The header shows the connection
|
||||
status, session title, mode (switchable live mid-turn), session model, **Tune** (autocomplete
|
||||
settings drawer), **Compact**, **History** (resume previous sessions), and **New**. Enter sends
|
||||
(or steers mid-run), Shift+Enter starts a new line, `@` searches project files and folders, and `/`
|
||||
completes slash commands and skills. Approval cards open edited files in the diff view first;
|
||||
question cards support single/multi-select, recommended markers, custom answers, and skip; plan
|
||||
cards render formatted Markdown with Approve (Edit/Manual), Revise, and Dismiss actions.
|
||||
|
||||
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.
|
||||
What a model writes is drawn as text through the extension's own Markdown reader: paragraphs,
|
||||
headings, lists, task checklists, quotes, real GFM tables (in horizontally scrollable wrappers),
|
||||
strikethrough, fenced code blocks with **Copy** and **Insert** buttons, and clickable `file:line`
|
||||
references. HTML in a reply stays text, pictures in a reply are not loaded, and links open only for
|
||||
`http`, `https` and `mailto`. Replies over 400,000 characters are shown as written. Tool calls show
|
||||
status, kind, duration, clickable changed files, and expandable output; thinking blocks collapse
|
||||
cleanly.
|
||||
|
||||
**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*).
|
||||
**Ask, Explain, Fix, Generate & Rewrite.** Ask about or explain a selection, fix reported warnings
|
||||
and errors in the active file, generate code at the cursor, or rewrite selected lines as proposed
|
||||
hunks with *Accept* / *Reject* CodeLenses and a side-by-side diff view. Nothing is written until you
|
||||
accept, and hunks whose lines you edited meanwhile are dropped safely.
|
||||
|
||||
**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.
|
||||
**Tunable Autocomplete.** Inline suggestions appear as you type and on `Alt+\` (Tab accepts, Escape
|
||||
dismisses). Use the **Tune** drawer in the chat header (or Settings) to slide **Max Tokens** from a
|
||||
few words up to a full file (`0`..`4096`), pick a prediction scope preset (`Auto`, `Few words`,
|
||||
`Single line`, `Function / block`, `Large / file`), and add custom **Autocomplete instructions**.
|
||||
|
||||
**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.
|
||||
status bar — shows both the **autocomplete** model and the **main** model (chat and rewriting), saved
|
||||
in your account or switched for this window only.
|
||||
|
||||
**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.
|
||||
**Files the agent shows.** Pictures appear inline in the chat. Other files appear with *Open* (only
|
||||
for display-only kinds whose bytes match their filename) or *Show in folder* for anything else. Files
|
||||
over 64 MB are refused (`llembas.media.maxMegabytes`).
|
||||
|
||||
**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.
|
||||
**Unsaved text.** The agent reads open files from your editor buffers (saved or not), and writes
|
||||
open files back through the document so undo and disk stay in sync.
|
||||
|
||||
## 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: Ask About the Selection | `Ctrl+Alt+K` | also in editor context menu |
|
||||
| LLeMbas: Explain the Selection | | editor context menu |
|
||||
| LLeMbas: Fix Problems in This File | | editor context menu |
|
||||
| LLeMbas: Generate Code at Cursor | | editor context menu |
|
||||
| LLeMbas: Rewrite the Selection | `Ctrl+Alt+E` | also in editor context menu |
|
||||
| LLeMbas: Suggest a Completion Here | `Alt+\` | |
|
||||
| LLeMbas: Toggle Autocomplete as You Type | | |
|
||||
| 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: Accept / Reject the Proposed Change at the Cursor | | or CodeLenses 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: Open File from Project Index / Add File to Chat | | |
|
||||
| LLeMbas: New Session / Resume a Previous Session | | |
|
||||
| LLeMbas: Compact Session Context | | |
|
||||
| LLeMbas: Stop the Running Turn | | |
|
||||
| LLeMbas: Choose the Mode | | |
|
||||
| LLeMbas: Choose This Session's Model | | |
|
||||
| LLeMbas: Models (Autocomplete and Main) | | |
|
||||
| LLeMbas: Choose the Mode / Choose This Session's Model | | |
|
||||
| LLeMbas: Models (Autocomplete and Main) | | also status bar item |
|
||||
| LLeMbas: Choose the Autocomplete Model / the Main Model | | |
|
||||
| LLeMbas: Stop the Agent | | it starts again when needed |
|
||||
| LLeMbas: Stop the Agent | | starts again when needed |
|
||||
|
||||
On macOS the keys use `Cmd` in place of `Ctrl`.
|
||||
|
||||
@@ -119,45 +110,33 @@ On macOS the keys use `Cmd` in place of `Ctrl`.
|
||||
|
||||
| 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.command` | `lembas` | the LLeMbas CLI, or its full path (machine-scoped) |
|
||||
| `llembas.chat.sendEditorContext` | on | send active file, cursor, selection, diagnostics and open files |
|
||||
| `llembas.chat.showThinking` | off | show collapsible model thinking blocks |
|
||||
| `llembas.chat.startMode` | | initial mode for a new session (machine-scoped) |
|
||||
| `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 |
|
||||
| `llembas.complete.debounce` | 250 | pause in milliseconds before requesting a completion |
|
||||
| `llembas.complete.maxTokens` | 0 | max tokens to predict (`0`: server default or preset; up to `4096`) |
|
||||
| `llembas.complete.length` | `auto` | prediction scope preset (`auto`, `words`, `line`, `block`, `file`) |
|
||||
| `llembas.complete.instructions` | `""` | custom instructions sent with autocomplete requests |
|
||||
| `llembas.rewrite.openDiff` | on | open diff view beside the file when a rewrite is proposed |
|
||||
| `llembas.media.maxMegabytes` | 64 | largest shown file accepted from the agent |
|
||||
|
||||
## 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.
|
||||
- Sound, video, PDF and 3D files are not rendered inline in the chat: they appear with *Open*.
|
||||
- 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.
|
||||
without one. The chat page (`media/chat.js`) builds elements with `createElement` and `textContent`
|
||||
only, under a strict Content-Security-Policy; every colour comes from VS Code'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.
|
||||
+205
-55
@@ -104,6 +104,9 @@ class Proposals {
|
||||
this.removed = vscode.window.createTextEditorDecorationType({
|
||||
isWholeLine: true,
|
||||
backgroundColor: new vscode.ThemeColor('diffEditor.removedLineBackground'),
|
||||
borderWidth: '0 0 0 3px',
|
||||
borderStyle: 'solid',
|
||||
borderColor: new vscode.ThemeColor('editorOverviewRuler.deletedForeground'),
|
||||
overviewRulerColor: new vscode.ThemeColor('editorOverviewRuler.modifiedForeground'),
|
||||
overviewRulerLane: vscode.OverviewRulerLane.Left,
|
||||
});
|
||||
@@ -334,6 +337,7 @@ class ChatView {
|
||||
nonce: crypto.randomBytes(18).toString('base64url'),
|
||||
scriptUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'chat.js')).toString(),
|
||||
styleUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'chat.css')).toString(),
|
||||
logoUri: webview.asWebviewUri(vscode.Uri.joinPath(this.context.extensionUri, 'media', 'logo.png')).toString(),
|
||||
});
|
||||
webview.onDidReceiveMessage((m) => this.receive(m));
|
||||
view.onDidDispose(() => {
|
||||
@@ -352,6 +356,10 @@ class ChatView {
|
||||
if (!growing) this.reading.set(item.id, (growing = new markdown.Growing()));
|
||||
return { id: item.id, kind: 'agent', ast: growing.update(item.text) };
|
||||
}
|
||||
if (item.kind === 'plancard') {
|
||||
const { text, ...rest } = item;
|
||||
return { ...rest, ast: text ? markdown.parse(text) : [] };
|
||||
}
|
||||
if (item.kind === 'media') {
|
||||
const entry = this.shown.get(item.key);
|
||||
const src = item.picture && entry && entry.file && this.view ? this.view.webview.asWebviewUri(vscode.Uri.file(entry.file)).toString() : '';
|
||||
@@ -385,6 +393,7 @@ class ChatView {
|
||||
type: 'reset',
|
||||
items: this.chat.items.map((i) => this.present(i)),
|
||||
state: this.chat.state(),
|
||||
settings: this.actions.uiSettings ? this.actions.uiSettings() : undefined,
|
||||
attached: this.attached ? this.attached.label : '',
|
||||
});
|
||||
}
|
||||
@@ -418,10 +427,27 @@ class ChatView {
|
||||
return this.chat.stop();
|
||||
case 'new':
|
||||
return a.newSession();
|
||||
case 'compact':
|
||||
return a.guard(a.compact());
|
||||
case 'sessions':
|
||||
return a.guard(a.resumeSession());
|
||||
case 'explain':
|
||||
return a.guard(a.explain());
|
||||
case 'fix':
|
||||
return a.guard(a.fixProblems());
|
||||
case 'addFile':
|
||||
return a.guard(a.addFile());
|
||||
case 'copyCode':
|
||||
if (typeof m.text === 'string' && vscode.env && vscode.env.clipboard && typeof vscode.env.clipboard.writeText === 'function') {
|
||||
vscode.env.clipboard.writeText(m.text).then(undefined, () => {});
|
||||
}
|
||||
return undefined;
|
||||
case 'insertCode':
|
||||
if (typeof m.text === 'string') a.guard(a.insertCode(m.text));
|
||||
return undefined;
|
||||
case 'updateSettings':
|
||||
if (m.settings && typeof m.settings === 'object') a.guard(a.updateSettings(m.settings));
|
||||
return undefined;
|
||||
case 'searchFiles':
|
||||
if (typeof m.query === 'string') {
|
||||
const seq = m.seq;
|
||||
@@ -660,38 +686,46 @@ function activate(context) {
|
||||
const fromAgent = await chat.searchFiles(query, 40).catch(() => []);
|
||||
if (fromAgent.length) return fromAgent;
|
||||
const root = workingDirectory();
|
||||
const seenPaths = new Set();
|
||||
const openRel = [];
|
||||
for (const d of vscode.workspace.textDocuments) {
|
||||
if (d.uri.scheme !== 'file') continue;
|
||||
const rel = path.relative(root, d.uri.fsPath).replace(/\\/g, '/');
|
||||
if (rel && !rel.startsWith('..') && (!query || rel.toLowerCase().includes(query.toLowerCase()))) openRel.push(rel);
|
||||
if (rel && !rel.startsWith('..') && !seenPaths.has(rel) && (!query || rel.toLowerCase().includes(query.toLowerCase()))) {
|
||||
seenPaths.add(rel);
|
||||
openRel.push({ path: rel, kind: 'file' });
|
||||
}
|
||||
}
|
||||
return [...new Set(openRel)];
|
||||
return openRel;
|
||||
}
|
||||
|
||||
async function pickProjectFile(title) {
|
||||
const files = await searchProjectFiles('');
|
||||
async function pickProjectFile(title, allowDirs) {
|
||||
const files = (await searchProjectFiles('')).filter((f) => allowDirs || f.kind !== 'dir');
|
||||
if (!files.length) {
|
||||
vscode.window.showInformationMessage('LLeMbas: no files found in the project index.');
|
||||
return undefined;
|
||||
}
|
||||
const picked = await vscode.window.showQuickPick(
|
||||
files.map((f) => ({ label: f })),
|
||||
files.map((f) => ({
|
||||
label: (f.kind === 'dir' ? '$(folder) ' : '$(file) ') + f.path + (f.kind === 'dir' ? '/' : ''),
|
||||
entry: f,
|
||||
})),
|
||||
{ title, placeHolder: 'Type to filter project files' },
|
||||
);
|
||||
return picked ? picked.label : undefined;
|
||||
return picked ? picked.entry : undefined;
|
||||
}
|
||||
|
||||
async function openIndexedFile() {
|
||||
const rel = await pickProjectFile('LLeMbas: open file from project index');
|
||||
if (rel) await openFileAt(rel);
|
||||
const entry = await pickProjectFile('LLeMbas: open file from project index', false);
|
||||
if (entry) await openFileAt(entry.path);
|
||||
}
|
||||
|
||||
async function addFileToChat() {
|
||||
const rel = await pickProjectFile('LLeMbas: add file to chat');
|
||||
if (!rel) return;
|
||||
const entry = await pickProjectFile('LLeMbas: add file to chat', true);
|
||||
if (!entry) return;
|
||||
await view.reveal(true);
|
||||
view.post({ type: 'insertText', text: `@${rel} ` });
|
||||
const escaped = entry.path.replace(/([ #])/g, '\\$1') + (entry.kind === 'dir' ? '/' : '');
|
||||
view.post({ type: 'insertText', text: `@${escaped} ` });
|
||||
}
|
||||
|
||||
async function resumeSession() {
|
||||
@@ -717,6 +751,69 @@ function activate(context) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function uiSettings() {
|
||||
const c = config();
|
||||
return {
|
||||
auto: !!c.get('complete.auto'),
|
||||
maxTokens: Number(c.get('complete.maxTokens')) || 0,
|
||||
length: String(c.get('complete.length') || 'auto'),
|
||||
instructions: String(c.get('complete.instructions') || ''),
|
||||
showThinking: !!c.get('chat.showThinking'),
|
||||
};
|
||||
}
|
||||
|
||||
async function updateSettings(patch) {
|
||||
const c = config();
|
||||
if (typeof c.update !== 'function') return;
|
||||
const target = vscode.ConfigurationTarget ? vscode.ConfigurationTarget.Global : true;
|
||||
const tasks = [];
|
||||
if (typeof patch.auto === 'boolean') tasks.push(c.update('complete.auto', patch.auto, target));
|
||||
if (typeof patch.maxTokens === 'number' && Number.isFinite(patch.maxTokens)) {
|
||||
const clamped = Math.max(0, Math.min(4096, Math.round(patch.maxTokens)));
|
||||
tasks.push(c.update('complete.maxTokens', clamped, target));
|
||||
}
|
||||
if (typeof patch.length === 'string' && ['auto', 'words', 'line', 'block', 'file'].includes(patch.length)) {
|
||||
tasks.push(c.update('complete.length', patch.length, target));
|
||||
}
|
||||
if (typeof patch.instructions === 'string') {
|
||||
tasks.push(c.update('complete.instructions', patch.instructions.slice(0, 2000), target));
|
||||
}
|
||||
if (typeof patch.showThinking === 'boolean') tasks.push(c.update('chat.showThinking', patch.showThinking, target));
|
||||
await Promise.all(tasks);
|
||||
view.post({ type: 'settings', settings: uiSettings() });
|
||||
showStatus();
|
||||
}
|
||||
|
||||
async function insertCode(text) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor) return vscode.window.showInformationMessage('LLeMbas: open an editor to insert code.');
|
||||
const doc = editor.document;
|
||||
const eol = doc.eol === vscode.EndOfLine.CRLF ? '\r\n' : '\n';
|
||||
const edit = new vscode.WorkspaceEdit();
|
||||
edit.replace(doc.uri, editor.selection, String(text).replace(/\r\n/g, '\n').replace(/\n/g, eol));
|
||||
await vscode.workspace.applyEdit(edit);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function compactSession() {
|
||||
if (chat.busy) return vscode.window.showWarningMessage('LLeMbas is working. Stop it first.');
|
||||
if (!chat.session) return vscode.window.showInformationMessage('LLeMbas: start a session first.');
|
||||
await chat.compact();
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async function toggleAutocomplete() {
|
||||
const c = config();
|
||||
const next = !c.get('complete.auto');
|
||||
if (typeof c.update === 'function') {
|
||||
const target = vscode.ConfigurationTarget ? vscode.ConfigurationTarget.Global : true;
|
||||
await c.update('complete.auto', next, target);
|
||||
}
|
||||
view.post({ type: 'settings', settings: uiSettings() });
|
||||
showStatus();
|
||||
vscode.window.showInformationMessage(`LLeMbas: autocomplete as you type is ${next ? 'on' : 'off'}.`);
|
||||
}
|
||||
|
||||
const actions = {
|
||||
mediaDir,
|
||||
guard,
|
||||
@@ -724,6 +821,12 @@ function activate(context) {
|
||||
searchFiles: searchProjectFiles,
|
||||
resumeSession,
|
||||
addFile: addFileToChat,
|
||||
compact: compactSession,
|
||||
explain: () => explain(),
|
||||
fixProblems: () => fixProblems(),
|
||||
insertCode,
|
||||
uiSettings,
|
||||
updateSettings,
|
||||
async sendTyped(text) {
|
||||
if (chat.busy) {
|
||||
if (chat.has('steer')) return chat.steer(text);
|
||||
@@ -806,49 +909,76 @@ function activate(context) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (!editor) return vscode.window.showInformationMessage('LLeMbas: open an editor first.');
|
||||
const doc = editor.document;
|
||||
const line = editor.selection.active.line;
|
||||
const instruction = await vscode.window.showInputBox({
|
||||
title: 'Generate code at cursor',
|
||||
placeHolder: 'Describe the code to write here',
|
||||
});
|
||||
if (!instruction || !instruction.trim()) return undefined;
|
||||
const key = doc.uri.toString();
|
||||
if (proposals.pending(doc)) return vscode.window.showWarningMessage('LLeMbas: accept or reject the changes shown in this file first.');
|
||||
if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start'));
|
||||
if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite/generate yet. Update the CLI.');
|
||||
const lines = (from, to) => {
|
||||
const out = [];
|
||||
for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text);
|
||||
return out;
|
||||
};
|
||||
const old = [doc.lineAt(line).text];
|
||||
const versionThen = doc.version;
|
||||
const id = 'e' + ++rewrites;
|
||||
const params = {
|
||||
id,
|
||||
cwd: workingDirectory(),
|
||||
text: old.join('\n') || ' ',
|
||||
before: lines(line - 40, line - 1).join('\n'),
|
||||
after: lines(line + 1, line + 40).join('\n'),
|
||||
language: doc.languageId,
|
||||
instruction: `At this line, ${instruction.trim()}`,
|
||||
};
|
||||
if (doc.uri.scheme === 'file') params.path = doc.uri.fsPath;
|
||||
if (chat.session) params.sessionId = chat.session;
|
||||
if (windowModel.main) params.model = windowModel.main;
|
||||
let r;
|
||||
if (rewriting.has(key)) return vscode.window.showWarningMessage('LLeMbas: a rewrite of this file is still being written.');
|
||||
rewriting.add(key);
|
||||
try {
|
||||
r = await chat.request('_lembas/edit', params);
|
||||
} catch (e) {
|
||||
return vscode.window.showErrorMessage(say(e));
|
||||
const line = editor.selection.active.line;
|
||||
const instruction = await vscode.window.showInputBox({
|
||||
title: 'Generate code at cursor',
|
||||
placeHolder: 'Describe the code to write here',
|
||||
});
|
||||
if (!instruction || !instruction.trim()) return undefined;
|
||||
if (!(await chat.connect(false))) return vscode.window.showErrorMessage(say(chat.startError || 'the agent did not start'));
|
||||
if (!chat.has('editor')) return vscode.window.showWarningMessage('LLeMbas: this LLeMbas CLI cannot rewrite/generate yet. Update the CLI.');
|
||||
const lines = (from, to) => {
|
||||
const out = [];
|
||||
for (let i = Math.max(0, from); i <= Math.min(doc.lineCount - 1, to); i++) out.push(doc.lineAt(i).text);
|
||||
return out;
|
||||
};
|
||||
const old = [doc.lineAt(line).text];
|
||||
const versionThen = doc.version;
|
||||
const id = 'e' + ++rewrites;
|
||||
const params = {
|
||||
id,
|
||||
cwd: workingDirectory(),
|
||||
text: old.join('\n') || ' ',
|
||||
before: lines(line - 40, line - 1).join('\n'),
|
||||
after: lines(line + 1, line + 40).join('\n'),
|
||||
language: doc.languageId,
|
||||
instruction: `At this line, ${instruction.trim()}`,
|
||||
};
|
||||
if (doc.uri.scheme === 'file') params.path = doc.uri.fsPath;
|
||||
if (chat.session) params.sessionId = chat.session;
|
||||
if (windowModel.main) params.model = windowModel.main;
|
||||
let r;
|
||||
try {
|
||||
r = await vscode.window.withProgress(
|
||||
{ location: vscode.ProgressLocation.Notification, title: 'LLeMbas is generating…', cancellable: true },
|
||||
async (progress, token) => {
|
||||
let written = 0;
|
||||
const onDelta = (p) => {
|
||||
if (!p || p.id !== id || typeof p.delta !== 'string') return;
|
||||
written += p.delta.length;
|
||||
progress.report({ message: `${written} characters` });
|
||||
};
|
||||
chat.on('editDelta', onDelta);
|
||||
token.onCancellationRequested(() => chat.notify('_lembas/edit/cancel', { id }));
|
||||
try {
|
||||
return await chat.request('_lembas/edit', params);
|
||||
} finally {
|
||||
chat.off('editDelta', onDelta);
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
return vscode.window.showErrorMessage(say(e));
|
||||
}
|
||||
if (!r || r.cancelled || typeof r.text !== 'string' || doc.isClosed) return undefined;
|
||||
if (doc.version !== versionThen) {
|
||||
return vscode.window.showWarningMessage('LLeMbas: the file changed while the code was generated, so nothing is shown. Ask again.');
|
||||
}
|
||||
const fresh = hunksOf.splitLines(r.text);
|
||||
if (fresh.length > 1 && fresh[fresh.length - 1] === '') fresh.pop();
|
||||
const hunks = hunksOf.propose(line, old, fresh);
|
||||
if (!hunks.length) return vscode.window.showInformationMessage('LLeMbas: nothing to insert.');
|
||||
proposals.set(doc, hunks);
|
||||
if (config().get('rewrite.openDiff')) proposals.showDiff(doc).then(undefined, () => {});
|
||||
return undefined;
|
||||
} finally {
|
||||
rewriting.delete(key);
|
||||
}
|
||||
if (!r || r.cancelled || typeof r.text !== 'string' || doc.isClosed || doc.version !== versionThen) return undefined;
|
||||
const fresh = hunksOf.splitLines(r.text);
|
||||
if (fresh.length > 1 && fresh[fresh.length - 1] === '') fresh.pop();
|
||||
const hunks = hunksOf.propose(line, old, fresh);
|
||||
if (!hunks.length) return undefined;
|
||||
proposals.set(doc, hunks);
|
||||
if (config().get('rewrite.openDiff')) proposals.showDiff(doc).then(undefined, () => {});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ---- rewrite a selection ----
|
||||
@@ -964,6 +1094,8 @@ function activate(context) {
|
||||
debounceMs: () => Number(config().get('complete.debounce')),
|
||||
model: () => windowModel.autocomplete,
|
||||
maxTokens: () => Number(config().get('complete.maxTokens')) || undefined,
|
||||
length: () => String(config().get('complete.length') || 'auto'),
|
||||
instructions: () => String(config().get('complete.instructions') || ''),
|
||||
onRefusal(reason, message) {
|
||||
if (reason === 'no_model' || reason === 'not_allowed') {
|
||||
const text = reason === 'no_model' ? message || 'No autocomplete model is chosen.' : message || 'That model is not allowed for autocomplete.';
|
||||
@@ -1051,10 +1183,22 @@ function activate(context) {
|
||||
function showStatus() {
|
||||
const saved = chat.settings && chat.settings.autocomplete && chat.settings.autocomplete.model;
|
||||
const model = windowModel.autocomplete || saved;
|
||||
status.text = 'LLeMbas' + (model ? ': ' + String(model).split('/').pop() : '');
|
||||
status.tooltip = model
|
||||
? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}. Click to change the models.`
|
||||
: 'LLeMbas: choose the models';
|
||||
const autoOn = !!config().get('complete.auto');
|
||||
const maxTok = Number(config().get('complete.maxTokens')) || 0;
|
||||
const len = String(config().get('complete.length') || 'auto');
|
||||
const icon = chat.busy ? '$(sync~spin) ' : '$(sparkle) ';
|
||||
const suffix = model ? ': ' + String(model).split('/').pop() : '';
|
||||
status.text = icon + 'LLeMbas' + suffix + (autoOn ? '' : ' (off)');
|
||||
const lines = [
|
||||
model
|
||||
? `Autocomplete model: ${model}${windowModel.autocomplete ? ' (this window only)' : ''}`
|
||||
: 'Autocomplete model: not chosen',
|
||||
`Autocomplete: ${autoOn ? 'on' : 'off'} · scope: ${len}${maxTok ? ` · max ${maxTok} tokens` : ''}`,
|
||||
];
|
||||
if (chat.mode) lines.push(`Session mode: ${chat.mode}`);
|
||||
if (chat.model) lines.push(`Session model: ${chat.model}`);
|
||||
lines.push('Click to change models.');
|
||||
status.tooltip = lines.join('\n');
|
||||
status.show();
|
||||
}
|
||||
showStatus();
|
||||
@@ -1155,6 +1299,7 @@ function activate(context) {
|
||||
command('llembas.open', () => view.reveal(true));
|
||||
command('llembas.newSession', actions.newSession);
|
||||
command('llembas.resumeSession', resumeSession);
|
||||
command('llembas.compact', compactSession);
|
||||
command('llembas.stop', () => chat.stop());
|
||||
command('llembas.restart', () => chat.stopAgent());
|
||||
command('llembas.ask', ask);
|
||||
@@ -1163,6 +1308,7 @@ function activate(context) {
|
||||
command('llembas.generate', generateAtCursor);
|
||||
command('llembas.rewrite', rewrite);
|
||||
command('llembas.complete', () => vscode.commands.executeCommand('editor.action.inlineSuggest.trigger'));
|
||||
command('llembas.toggleAutocomplete', toggleAutocomplete);
|
||||
command('llembas.openFile', openIndexedFile);
|
||||
command('llembas.addFile', addFileToChat);
|
||||
command('llembas.chooseMode', chooseMode);
|
||||
@@ -1207,6 +1353,10 @@ function activate(context) {
|
||||
vscode.workspace.onDidChangeConfiguration((ev) => {
|
||||
// Another command for the agent: the running one is stopped, and the next request starts the new one.
|
||||
if (ev.affectsConfiguration('llembas.command')) chat.stopAgent();
|
||||
if (ev.affectsConfiguration('llembas.complete') || ev.affectsConfiguration('llembas.chat.showThinking')) {
|
||||
view.post({ type: 'settings', settings: uiSettings() });
|
||||
showStatus();
|
||||
}
|
||||
}),
|
||||
proposals.removed,
|
||||
proposals.added,
|
||||
|
||||
+673
-80
@@ -1,33 +1,110 @@
|
||||
/* Every colour is one of the editor's theme variables. */
|
||||
html, body { height: 100%; }
|
||||
html, body { height: 100%; overflow: hidden; }
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100vh;
|
||||
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;
|
||||
line-height: 1.5;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
.chrome { min-width: 0; }
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
/* ---- Header bar ------------------------------------------------------------------------ */
|
||||
|
||||
.bar {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto auto;
|
||||
grid-template-rows: auto auto;
|
||||
gap: 6px;
|
||||
padding: 6px 8px;
|
||||
padding: 8px 10px;
|
||||
background: var(--vscode-sideBarSectionHeader-background, var(--vscode-sideBar-background));
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
}
|
||||
.bar-top {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
.brand-logo {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border-radius: 3px;
|
||||
flex: none;
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
.brand-title {
|
||||
font-weight: 600;
|
||||
font-size: 0.95em;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.bar-btns {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.bar-controls {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 0.85fr) minmax(0, 1.15fr);
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
.select-wrap {
|
||||
display: grid;
|
||||
grid-template-columns: 8px minmax(0, 1fr);
|
||||
gap: 5px;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 99px;
|
||||
background: var(--vscode-descriptionForeground);
|
||||
flex: none;
|
||||
}
|
||||
.dot.is-ok { background: var(--vscode-testing-iconPassed, var(--vscode-charts-green)); }
|
||||
.dot.is-busy {
|
||||
background: var(--vscode-progressBar-background, var(--vscode-charts-blue));
|
||||
animation: llembas-pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
.mode-dot.mode-plan { background: var(--vscode-charts-purple, var(--vscode-editorInfo-foreground)); }
|
||||
.mode-dot.mode-manual { background: var(--vscode-charts-yellow, var(--vscode-editorWarning-foreground)); }
|
||||
.mode-dot.mode-edit { background: var(--vscode-charts-blue, var(--vscode-editorInfo-foreground)); }
|
||||
.mode-dot.mode-auto { background: var(--vscode-charts-green, var(--vscode-testing-iconPassed)); }
|
||||
|
||||
@keyframes llembas-pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.35; }
|
||||
}
|
||||
|
||||
select, button, textarea, input { font: inherit; }
|
||||
select {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 26px;
|
||||
padding: 0 6px;
|
||||
color: var(--vscode-dropdown-foreground);
|
||||
background: var(--vscode-dropdown-background);
|
||||
border: 1px solid var(--vscode-dropdown-border);
|
||||
border-radius: 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
button {
|
||||
height: 26px;
|
||||
@@ -35,7 +112,7 @@ button {
|
||||
color: var(--vscode-button-foreground);
|
||||
background: var(--vscode-button-background);
|
||||
border: 1px solid var(--vscode-button-border, transparent);
|
||||
border-radius: 2px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -45,6 +122,24 @@ button.second {
|
||||
background: var(--vscode-button-secondaryBackground);
|
||||
}
|
||||
button.second:hover { background: var(--vscode-button-secondaryHoverBackground); }
|
||||
button.icon-btn {
|
||||
height: 24px;
|
||||
padding: 0 8px;
|
||||
font-size: 0.88em;
|
||||
}
|
||||
button.mini {
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
font-size: 0.82em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
background: transparent;
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 3px;
|
||||
}
|
||||
button.mini:hover {
|
||||
color: var(--vscode-foreground);
|
||||
background: var(--vscode-toolbar-hoverBackground);
|
||||
}
|
||||
button.plain {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
@@ -54,79 +149,477 @@ button.plain {
|
||||
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, input:focus, .link:focus-visible {
|
||||
button:disabled, select:disabled { opacity: 0.55; cursor: default; }
|
||||
select:focus, button:focus-visible, textarea:focus, input:focus, .link:focus-visible, .file-chip:focus-visible {
|
||||
outline: 1px solid var(--vscode-focusBorder);
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
#log {
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 8px;
|
||||
/* ---- Settings / Autocomplete Tune Drawer ----------------------------------------------- */
|
||||
|
||||
.settings-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 8px 10px;
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background));
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.item { margin: 0 0 10px; overflow-wrap: anywhere; }
|
||||
.who {
|
||||
margin: 0 0 2px;
|
||||
font-size: 0.85em;
|
||||
.sp-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.sp-label {
|
||||
font-size: 0.88em;
|
||||
font-weight: 600;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.sp-val {
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.86em;
|
||||
padding: 0 6px;
|
||||
border-radius: 99px;
|
||||
background: var(--vscode-badge-background);
|
||||
color: var(--vscode-badge-foreground);
|
||||
}
|
||||
.sp-slider {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
accent-color: var(--vscode-button-background);
|
||||
cursor: pointer;
|
||||
}
|
||||
.sp-presets {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
.preset-btn.active {
|
||||
color: var(--vscode-button-foreground);
|
||||
background: var(--vscode-button-background);
|
||||
border-color: var(--vscode-button-background);
|
||||
}
|
||||
.sp-grid {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
.sp-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.sp-checks {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.sp-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 0.88em;
|
||||
color: var(--vscode-foreground);
|
||||
cursor: pointer;
|
||||
}
|
||||
.sp-check input {
|
||||
margin: 0;
|
||||
accent-color: var(--vscode-button-background);
|
||||
}
|
||||
|
||||
/* ---- Subagent / Team strip ------------------------------------------------------------- */
|
||||
|
||||
.team-bar {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 5px 10px;
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background));
|
||||
font-size: 0.85em;
|
||||
}
|
||||
.team-label {
|
||||
font-weight: 600;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
.team-chip {
|
||||
padding: 1px 6px;
|
||||
border-radius: 99px;
|
||||
background: var(--vscode-badge-background);
|
||||
color: var(--vscode-badge-foreground);
|
||||
}
|
||||
|
||||
/* ---- Transcript & Empty State ---------------------------------------------------------- */
|
||||
|
||||
#log {
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
gap: 14px;
|
||||
min-height: 100%;
|
||||
padding: 16px 8px;
|
||||
}
|
||||
.hero {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.hero-logo {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
.hero-title {
|
||||
font-size: 1.15em;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
.hero-sub {
|
||||
font-size: 0.9em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.starter-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 6px;
|
||||
width: 100%;
|
||||
max-width: 300px;
|
||||
}
|
||||
button.starter {
|
||||
height: auto;
|
||||
min-height: 30px;
|
||||
padding: 5px 8px;
|
||||
white-space: normal;
|
||||
font-size: 0.88em;
|
||||
color: var(--vscode-foreground);
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-input-background));
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 6px;
|
||||
}
|
||||
button.starter:hover {
|
||||
background: var(--vscode-list-hoverBackground, var(--vscode-toolbar-hoverBackground));
|
||||
border-color: var(--vscode-focusBorder);
|
||||
}
|
||||
.hero-hints {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.hint-pill {
|
||||
padding: 1px 7px;
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.82em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
background: var(--vscode-textCodeBlock-background);
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 99px;
|
||||
}
|
||||
|
||||
/* ---- Items ----------------------------------------------------------------------------- */
|
||||
|
||||
.item { margin: 0 0 12px; overflow-wrap: anywhere; }
|
||||
.who-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin: 0 0 3px;
|
||||
}
|
||||
.who {
|
||||
margin: 0 0 3px;
|
||||
font-size: 0.82em;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-transform: uppercase;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.who-row .who { margin: 0; }
|
||||
.badge {
|
||||
padding: 0 6px;
|
||||
border-radius: 99px;
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.8em;
|
||||
color: var(--vscode-badge-foreground);
|
||||
background: var(--vscode-badge-background);
|
||||
}
|
||||
|
||||
.user .text, .thought .text, .note { white-space: pre-wrap; }
|
||||
.user .body {
|
||||
padding: 6px 8px;
|
||||
padding: 8px 10px;
|
||||
background: var(--vscode-input-background);
|
||||
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
|
||||
border-radius: 3px;
|
||||
border-left: 3px solid var(--vscode-button-background);
|
||||
border-radius: 6px;
|
||||
}
|
||||
.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);
|
||||
.agent {
|
||||
padding-bottom: 4px;
|
||||
}
|
||||
|
||||
.thought-box {
|
||||
padding: 5px 8px;
|
||||
border-left: 2px solid var(--vscode-panel-border);
|
||||
background: var(--vscode-editorWidget-background, transparent);
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
.thought-summary {
|
||||
cursor: pointer;
|
||||
font-size: 0.85em;
|
||||
font-weight: 600;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
user-select: none;
|
||||
}
|
||||
.thought-box .text {
|
||||
margin-top: 6px;
|
||||
font-size: 0.92em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.note {
|
||||
padding: 5px 8px;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-size: 0.9em;
|
||||
border-left: 2px solid var(--vscode-panel-border);
|
||||
}
|
||||
.note.warn {
|
||||
color: var(--vscode-editorWarning-foreground);
|
||||
border-left-color: var(--vscode-editorWarning-foreground);
|
||||
}
|
||||
.note.error {
|
||||
color: var(--vscode-errorForeground);
|
||||
border-left-color: var(--vscode-errorForeground);
|
||||
}
|
||||
|
||||
/* ---- Tool calls & Plans ---------------------------------------------------------------- */
|
||||
|
||||
.tool {
|
||||
display: grid;
|
||||
grid-template-columns: 1.5em minmax(0, 1fr);
|
||||
gap: 2px;
|
||||
padding: 5px 8px;
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-input-background));
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 6px;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.tool .mark { font-weight: 700; text-align: center; }
|
||||
.tool.completed .mark { color: var(--vscode-testing-iconPassed, var(--vscode-charts-green)); }
|
||||
.tool.failed .mark { color: var(--vscode-testing-iconFailed, var(--vscode-errorForeground)); }
|
||||
.tool.denied .mark { color: var(--vscode-editorWarning-foreground); }
|
||||
.tool.running .mark {
|
||||
color: var(--vscode-progressBar-background, var(--vscode-charts-blue));
|
||||
animation: llembas-pulse 1.1s ease-in-out infinite;
|
||||
}
|
||||
.tool-main { min-width: 0; }
|
||||
.tool-head {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
.tool-kind {
|
||||
padding: 0 5px;
|
||||
border-radius: 3px;
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.8em;
|
||||
text-transform: uppercase;
|
||||
color: var(--vscode-badge-foreground);
|
||||
background: var(--vscode-badge-background);
|
||||
}
|
||||
.tool .title { color: var(--vscode-foreground); }
|
||||
.tool-ms {
|
||||
margin-left: auto;
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.82em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.tool .files {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
.file-chip {
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.85em;
|
||||
color: var(--vscode-textLink-foreground);
|
||||
background: var(--vscode-textCodeBlock-background);
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
cursor: pointer;
|
||||
}
|
||||
.file-chip:hover {
|
||||
color: var(--vscode-textLink-activeForeground);
|
||||
border-color: var(--vscode-textLink-foreground);
|
||||
}
|
||||
.tool-output { margin-top: 5px; }
|
||||
.tool-output-summary {
|
||||
cursor: pointer;
|
||||
font-size: 0.85em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
user-select: none;
|
||||
}
|
||||
.tool-output pre {
|
||||
margin-top: 4px;
|
||||
max-height: 14em;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.plan {
|
||||
padding: 8px 10px;
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-input-background));
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-left: 3px solid var(--vscode-charts-blue, var(--vscode-editorInfo-foreground));
|
||||
border-radius: 6px;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
.tool.failed .mark { color: var(--vscode-errorForeground); }
|
||||
.tool .files, .plan .plan-entries { grid-column: 2; }
|
||||
.plan-entries { margin-top: 4px; display: flex; flex-direction: column; gap: 2px; }
|
||||
.plan-entry { display: grid; grid-template-columns: 1.2em minmax(0, 1fr); gap: 2px; }
|
||||
.plan-entry.completed { opacity: 0.7; }
|
||||
.plan-entry.in_progress { color: var(--vscode-foreground); font-weight: 500; }
|
||||
.plan-head {
|
||||
display: grid;
|
||||
grid-template-columns: 1.4em minmax(0, 1fr);
|
||||
align-items: center;
|
||||
font-weight: 600;
|
||||
}
|
||||
.plan-progress {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 5px;
|
||||
margin: 6px 0;
|
||||
accent-color: var(--vscode-progressBar-background);
|
||||
}
|
||||
.plan-entries { margin-top: 4px; display: flex; flex-direction: column; gap: 3px; }
|
||||
.plan-entry { display: grid; grid-template-columns: 1.3em minmax(0, 1fr); gap: 3px; color: var(--vscode-descriptionForeground); }
|
||||
.plan-entry.completed { opacity: 0.72; }
|
||||
.plan-entry.completed .pmark { color: var(--vscode-testing-iconPassed, var(--vscode-charts-green)); }
|
||||
.plan-entry.in_progress { color: var(--vscode-foreground); font-weight: 600; }
|
||||
.plan-entry.in_progress .pmark { color: var(--vscode-charts-blue, var(--vscode-editorInfo-foreground)); }
|
||||
|
||||
.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; }
|
||||
/* ---- Markdown content ------------------------------------------------------------------ */
|
||||
|
||||
.md p, .md ul, .md ol, .md pre, .md .code-block, .md .table-wrap, .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 h1, .md h2, .md h3, .md h4, .md h5, .md h6 { font-size: 1em; font-weight: 700; margin-top: 10px; }
|
||||
.md h1 { font-size: 1.2em; padding-bottom: 3px; border-bottom: 1px solid var(--vscode-panel-border); }
|
||||
.md h2 { font-size: 1.1em; }
|
||||
.md ul, .md ol { padding-left: 1.5em; }
|
||||
.md li { margin-bottom: 2px; }
|
||||
.md li.task-item { list-style: none; margin-left: -1.2em; }
|
||||
.md li.task-item.checked { color: var(--vscode-descriptionForeground); }
|
||||
.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;
|
||||
padding: 4px 8px;
|
||||
border-left: 3px solid var(--vscode-textBlockQuote-border);
|
||||
background: var(--vscode-textBlockQuote-background);
|
||||
border-radius: 0 4px 4px 0;
|
||||
}
|
||||
.md hr { border: 0; border-top: 1px solid var(--vscode-panel-border); margin: 8px 0; }
|
||||
.md hr { border: 0; border-top: 1px solid var(--vscode-panel-border); margin: 10px 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; cursor: pointer; }
|
||||
.md code {
|
||||
background: var(--vscode-textCodeBlock-background);
|
||||
padding: 1px 4px;
|
||||
border-radius: 3px;
|
||||
}
|
||||
.md code.file-ref {
|
||||
color: var(--vscode-textLink-foreground);
|
||||
cursor: pointer;
|
||||
}
|
||||
.md code.file-ref:hover { text-decoration: underline; }
|
||||
|
||||
.code-block {
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
background: var(--vscode-textCodeBlock-background);
|
||||
}
|
||||
.code-head {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 8px;
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-sideBar-background));
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
}
|
||||
.code-lang {
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.8em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
text-transform: lowercase;
|
||||
}
|
||||
.code-tools { display: flex; gap: 4px; }
|
||||
.code-block pre {
|
||||
margin: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
pre {
|
||||
margin: 0;
|
||||
padding: 6px 8px;
|
||||
padding: 8px 10px;
|
||||
overflow-x: auto; /* a wide line scrolls here, never the view */
|
||||
white-space: pre;
|
||||
background: var(--vscode-textCodeBlock-background);
|
||||
border-radius: 3px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
.md pre code { background: transparent; padding: 0; cursor: text; }
|
||||
.md pre code { background: transparent; padding: 0; cursor: text; color: inherit; }
|
||||
|
||||
/* ---- GFM Tables ------------------------------------------------------------------------ */
|
||||
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 5px;
|
||||
}
|
||||
.table-wrap table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
.table-wrap th, .table-wrap td {
|
||||
padding: 5px 8px;
|
||||
border-bottom: 1px solid var(--vscode-panel-border);
|
||||
border-right: 1px solid var(--vscode-panel-border);
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
}
|
||||
.table-wrap th:last-child, .table-wrap td:last-child { border-right: 0; }
|
||||
.table-wrap tr:last-child td { border-bottom: 0; }
|
||||
.table-wrap thead th {
|
||||
font-weight: 600;
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-textCodeBlock-background));
|
||||
}
|
||||
.table-wrap .align-center { text-align: center; }
|
||||
.table-wrap .align-right { text-align: right; }
|
||||
|
||||
.link {
|
||||
color: var(--vscode-textLink-foreground);
|
||||
text-decoration: underline;
|
||||
@@ -134,44 +627,69 @@ pre {
|
||||
}
|
||||
.link:hover { color: var(--vscode-textLink-activeForeground); }
|
||||
|
||||
/* ---- Interactive Cards (Approval, Question, Plan) -------------------------------------- */
|
||||
|
||||
.card {
|
||||
padding: 8px;
|
||||
padding: 10px;
|
||||
border: 1px solid var(--vscode-inputValidation-warningBorder, var(--vscode-panel-border));
|
||||
background: var(--vscode-inputValidation-warningBackground, var(--vscode-input-background));
|
||||
border-radius: 3px;
|
||||
border-left: 3px solid var(--vscode-inputValidation-warningBorder, var(--vscode-editorWarning-foreground));
|
||||
background: var(--vscode-inputValidation-warningBackground, var(--vscode-editorWidget-background));
|
||||
border-radius: 6px;
|
||||
}
|
||||
.card.info-card {
|
||||
border-color: var(--vscode-inputValidation-infoBorder, var(--vscode-panel-border));
|
||||
border-left-color: var(--vscode-editorInfo-foreground, var(--vscode-charts-blue));
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-input-background));
|
||||
}
|
||||
.card.plan-approval {
|
||||
border-color: var(--vscode-panel-border);
|
||||
border-left-color: var(--vscode-testing-iconPassed, var(--vscode-charts-green));
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-input-background));
|
||||
}
|
||||
.card.closed {
|
||||
border-color: var(--vscode-panel-border);
|
||||
border-left-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 .title { white-space: pre-wrap; font-family: var(--vscode-editor-font-family); font-weight: 600; margin: 2px 0 4px; }
|
||||
.card .reason { font-size: 0.9em; margin: 0 0 6px; color: var(--vscode-descriptionForeground); }
|
||||
.card pre { margin: 0 0 6px; max-height: 16em; overflow: auto; }
|
||||
.card .buttons { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
|
||||
.q-block { margin: 0 0 8px; }
|
||||
.q-header { font-size: 0.85em; font-weight: 600; color: var(--vscode-descriptionForeground); }
|
||||
.q-options { display: flex; flex-wrap: wrap; gap: 4px; margin: 4px 0 6px; }
|
||||
.q-opt { height: auto; min-height: 24px; padding: 2px 8px; white-space: normal; text-align: left; }
|
||||
.card .plan-md {
|
||||
max-height: 22em;
|
||||
overflow: auto;
|
||||
padding: 8px;
|
||||
margin: 4px 0 8px;
|
||||
background: var(--vscode-editor-background, var(--vscode-sideBar-background));
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 5px;
|
||||
}
|
||||
.card .buttons { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
|
||||
.q-block { margin: 0 0 10px; }
|
||||
.q-header { font-size: 0.82em; font-weight: 600; text-transform: uppercase; letter-spacing: 0.03em; color: var(--vscode-descriptionForeground); }
|
||||
.q-options { display: flex; flex-wrap: wrap; gap: 5px; margin: 5px 0 6px; }
|
||||
.q-opt { height: auto; min-height: 26px; padding: 3px 9px; white-space: normal; text-align: left; }
|
||||
.q-input {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 26px;
|
||||
padding: 2px 6px;
|
||||
height: 28px;
|
||||
padding: 2px 8px;
|
||||
margin-top: 4px;
|
||||
color: var(--vscode-input-foreground);
|
||||
background: var(--vscode-input-background);
|
||||
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
|
||||
border-radius: 2px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
/* ---- Media ----------------------------------------------------------------------------- */
|
||||
|
||||
.media img {
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
max-height: 60vh;
|
||||
height: auto;
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
border-radius: 3px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.media .caption {
|
||||
@@ -181,73 +699,148 @@ pre {
|
||||
align-items: center;
|
||||
min-height: 26px;
|
||||
margin-top: 4px;
|
||||
font-size: 0.92em;
|
||||
font-size: 0.9em;
|
||||
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); position: relative; }
|
||||
/* ---- Composer Footer ------------------------------------------------------------------- */
|
||||
|
||||
footer {
|
||||
padding: 8px 10px 10px;
|
||||
border-top: 1px solid var(--vscode-panel-border);
|
||||
background: var(--vscode-sideBar-background);
|
||||
position: relative;
|
||||
}
|
||||
.popup {
|
||||
max-height: 180px;
|
||||
max-height: 190px;
|
||||
overflow-y: auto;
|
||||
margin-bottom: 4px;
|
||||
margin-bottom: 6px;
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
background: var(--vscode-editorSuggestWidget-background, var(--vscode-input-background));
|
||||
border-radius: 2px;
|
||||
background: var(--vscode-editorSuggestWidget-background, var(--vscode-editorWidget-background));
|
||||
border-radius: 5px;
|
||||
}
|
||||
.popup-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 8px;
|
||||
padding: 3px 6px;
|
||||
align-items: center;
|
||||
padding: 4px 8px;
|
||||
cursor: pointer;
|
||||
font-size: 0.92em;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.popup-row.active, .popup-row:hover {
|
||||
background: var(--vscode-list-activeSelectionBackground);
|
||||
color: var(--vscode-list-activeSelectionForeground);
|
||||
}
|
||||
.popup-label { font-family: var(--vscode-editor-font-family); white-space: nowrap; }
|
||||
.popup-detail { opacity: 0.8; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.popup-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
.popup-badge {
|
||||
padding: 0 4px;
|
||||
border-radius: 3px;
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.78em;
|
||||
text-transform: uppercase;
|
||||
background: var(--vscode-badge-background);
|
||||
color: var(--vscode-badge-foreground);
|
||||
flex: none;
|
||||
}
|
||||
.popup-label {
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.popup-detail {
|
||||
opacity: 0.8;
|
||||
font-size: 0.88em;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 140px;
|
||||
}
|
||||
|
||||
.attached {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 22px;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
padding: 2px 4px 2px 8px;
|
||||
margin-bottom: 6px;
|
||||
border: 1px solid var(--vscode-panel-border);
|
||||
background: var(--vscode-editorWidget-background, var(--vscode-input-background));
|
||||
border-radius: 4px;
|
||||
font-size: 0.88em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
}
|
||||
.attached-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.composer {
|
||||
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
|
||||
background: var(--vscode-input-background);
|
||||
border-radius: 6px;
|
||||
padding: 6px;
|
||||
}
|
||||
.composer:focus-within {
|
||||
border-color: var(--vscode-focusBorder);
|
||||
}
|
||||
textarea {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 5.2em;
|
||||
resize: none;
|
||||
padding: 5px 6px;
|
||||
padding: 2px 4px;
|
||||
color: var(--vscode-input-foreground);
|
||||
background: var(--vscode-input-background);
|
||||
border: 1px solid var(--vscode-input-border, var(--vscode-panel-border));
|
||||
border-radius: 2px;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
}
|
||||
textarea:focus { outline: none; }
|
||||
textarea::placeholder { color: var(--vscode-input-placeholderForeground); }
|
||||
|
||||
.send {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
min-height: 26px;
|
||||
margin-top: 6px;
|
||||
padding-top: 6px;
|
||||
border-top: 1px solid var(--vscode-panel-border);
|
||||
}
|
||||
.left-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.attached {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, auto) 22px;
|
||||
gap: 2px;
|
||||
.working {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: start;
|
||||
height: 26px;
|
||||
font-size: 0.92em;
|
||||
gap: 5px;
|
||||
font-size: 0.88em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
}
|
||||
.attached-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.working { font-size: 0.92em; color: var(--vscode-descriptionForeground); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 160px; }
|
||||
.pulse-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 99px;
|
||||
background: var(--vscode-progressBar-background, var(--vscode-charts-blue));
|
||||
animation: llembas-pulse 1.1s ease-in-out infinite;
|
||||
flex: none;
|
||||
}
|
||||
.usage {
|
||||
font-family: var(--vscode-editor-font-family);
|
||||
font-size: 0.8em;
|
||||
color: var(--vscode-descriptionForeground);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.actions { display: flex; gap: 4px; }
|
||||
[hidden] { display: none !important; }
|
||||
+397
-49
@@ -4,9 +4,10 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var MARKS = { pending: '…', in_progress: '…', completed: '✓', failed: '✗' };
|
||||
var MARKS = { pending: '…', in_progress: '◐', completed: '✓', failed: '✗' };
|
||||
var PLAN_MARKS = { pending: '☐', in_progress: '▸', completed: '✓' };
|
||||
var MAX_DEPTH = 8;
|
||||
var FILE_REF_RE = /^([A-Za-z0-9_.\-/]+\.[A-Za-z0-9]{1,10})(?::(\d+)(?:-\d+)?)?$/;
|
||||
|
||||
function el(doc, tag, cls, text) {
|
||||
var e = doc.createElement(tag);
|
||||
@@ -15,6 +16,24 @@
|
||||
return e;
|
||||
}
|
||||
|
||||
function formatTokens(n) {
|
||||
var v = Number(n) || 0;
|
||||
if (v >= 1000000) return (v / 1000000).toFixed(1) + 'M';
|
||||
if (v >= 1000) return (v / 1000).toFixed(1) + 'k';
|
||||
return String(v);
|
||||
}
|
||||
|
||||
function formatMs(ms) {
|
||||
var v = Number(ms);
|
||||
if (!Number.isFinite(v) || v < 0) return '';
|
||||
if (v < 1000) return Math.round(v) + ' ms';
|
||||
return (v / 1000).toFixed(1) + ' s';
|
||||
}
|
||||
|
||||
function escapeAtPath(p) {
|
||||
return String(p || '').replace(/([ #])/g, '\\$1');
|
||||
}
|
||||
|
||||
function buildInline(doc, nodes, parent, depth) {
|
||||
if (!Array.isArray(nodes) || depth > MAX_DEPTH) return;
|
||||
for (var i = 0; i < nodes.length; i++) {
|
||||
@@ -22,9 +41,14 @@
|
||||
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');
|
||||
else if (n.t === 'code') {
|
||||
var raw = String(n.v || '');
|
||||
var isRef = FILE_REF_RE.test(raw.trim());
|
||||
var code = el(doc, 'code', isRef ? 'file-ref' : '', raw);
|
||||
if (isRef) code.setAttribute('title', 'Open ' + raw.trim());
|
||||
parent.appendChild(code);
|
||||
} else if (n.t === 'b' || n.t === 'i' || n.t === 'del') {
|
||||
var e = doc.createElement(n.t === 'b' ? 'strong' : n.t === 'i' ? 'em' : 'del');
|
||||
buildInline(doc, n.c, e, depth + 1);
|
||||
parent.appendChild(e);
|
||||
} else if (n.t === 'a') {
|
||||
@@ -41,7 +65,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
function buildBlocks(doc, blocks, parent, depth) {
|
||||
function buildBlocks(doc, blocks, parent, depth, post) {
|
||||
if (!Array.isArray(blocks) || depth > MAX_DEPTH) return;
|
||||
for (var i = 0; i < blocks.length; i++) {
|
||||
var b = blocks[i];
|
||||
@@ -55,8 +79,64 @@
|
||||
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));
|
||||
var pre = doc.createElement('pre');
|
||||
pre.appendChild(el(doc, 'code', '', b.v));
|
||||
if (post) {
|
||||
e = el(doc, 'div', 'code-block');
|
||||
var head = el(doc, 'div', 'code-head');
|
||||
head.appendChild(el(doc, 'span', 'code-lang', b.lang || 'code'));
|
||||
var tools = el(doc, 'div', 'code-tools');
|
||||
(function (codeText) {
|
||||
var copyBtn = button(doc, 'Copy', 'mini', function () {
|
||||
post({ type: 'copyCode', text: codeText });
|
||||
copyBtn.textContent = 'Copied';
|
||||
setTimeout(function () {
|
||||
copyBtn.textContent = 'Copy';
|
||||
}, 1200);
|
||||
});
|
||||
var insBtn = button(doc, 'Insert', 'mini', function () {
|
||||
post({ type: 'insertCode', text: codeText });
|
||||
});
|
||||
tools.appendChild(copyBtn);
|
||||
tools.appendChild(insBtn);
|
||||
})(String(b.v || ''));
|
||||
head.appendChild(tools);
|
||||
e.appendChild(head);
|
||||
e.appendChild(pre);
|
||||
} else {
|
||||
e = pre;
|
||||
}
|
||||
} else if (b.t === 'table') {
|
||||
e = el(doc, 'div', 'table-wrap');
|
||||
var table = doc.createElement('table');
|
||||
var align = Array.isArray(b.align) ? b.align : [];
|
||||
if (Array.isArray(b.head) && b.head.length) {
|
||||
var thead = doc.createElement('thead');
|
||||
var htr = doc.createElement('tr');
|
||||
for (var c = 0; c < b.head.length; c++) {
|
||||
var th = el(doc, 'th', align[c] ? 'align-' + align[c] : '');
|
||||
buildInline(doc, b.head[c], th, 0);
|
||||
htr.appendChild(th);
|
||||
}
|
||||
thead.appendChild(htr);
|
||||
table.appendChild(thead);
|
||||
}
|
||||
var rows = Array.isArray(b.rows) ? b.rows : [];
|
||||
if (rows.length) {
|
||||
var tbody = doc.createElement('tbody');
|
||||
for (var r = 0; r < rows.length; r++) {
|
||||
var tr = doc.createElement('tr');
|
||||
var cells = Array.isArray(rows[r]) ? rows[r] : [];
|
||||
for (var k = 0; k < cells.length; k++) {
|
||||
var td = el(doc, 'td', align[k] ? 'align-' + align[k] : '');
|
||||
buildInline(doc, cells[k], td, 0);
|
||||
tr.appendChild(td);
|
||||
}
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
table.appendChild(tbody);
|
||||
}
|
||||
e.appendChild(table);
|
||||
} 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);
|
||||
@@ -64,14 +144,20 @@
|
||||
e = doc.createElement('hr');
|
||||
} else if (b.t === 'quote') {
|
||||
e = doc.createElement('blockquote');
|
||||
buildBlocks(doc, b.c, e, depth + 1);
|
||||
buildBlocks(doc, b.c, e, depth + 1, post);
|
||||
} 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);
|
||||
var it = items[j] || {};
|
||||
var d = Math.max(0, Math.min(5, Number(it.d) || 0));
|
||||
var liCls = d ? 'depth-' + d : '';
|
||||
if (typeof it.checked === 'boolean') liCls = (liCls ? liCls + ' ' : '') + 'task-item' + (it.checked ? ' checked' : '');
|
||||
var li = el(doc, 'li', liCls);
|
||||
if (typeof it.checked === 'boolean') {
|
||||
li.appendChild(el(doc, 'span', 'task-box', it.checked ? '☑ ' : '☐ '));
|
||||
}
|
||||
buildInline(doc, it.c, li, 0);
|
||||
e.appendChild(li);
|
||||
}
|
||||
} else {
|
||||
@@ -89,51 +175,89 @@
|
||||
}
|
||||
|
||||
/** One item of the transcript as an element. `post` sends a message to the extension. */
|
||||
function renderItem(doc, item, post) {
|
||||
function renderItem(doc, item, post, uiState) {
|
||||
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 uHead = el(doc, 'div', 'who-row');
|
||||
uHead.appendChild(el(doc, 'span', 'who', 'You'));
|
||||
if (item.label) uHead.appendChild(el(doc, 'span', 'badge', '[' + item.label + ']'));
|
||||
root.appendChild(uHead);
|
||||
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);
|
||||
if (Array.isArray(item.ast)) buildBlocks(doc, item.ast, md, 0, post);
|
||||
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));
|
||||
var details = el(doc, 'details', 'thought-box');
|
||||
if (uiState && uiState.openDetails && uiState.openDetails[item.id]) details.open = true;
|
||||
details.addEventListener('toggle', function () {
|
||||
if (uiState && uiState.openDetails) uiState.openDetails[item.id] = !!details.open;
|
||||
});
|
||||
var txt = String(item.text || '');
|
||||
details.appendChild(el(doc, 'summary', 'thought-summary', 'Thinking · ' + txt.length + ' chars'));
|
||||
details.appendChild(el(doc, 'div', 'text', txt));
|
||||
root.appendChild(details);
|
||||
} else if (item.kind === 'note') {
|
||||
if (item.level === 'error' || item.level === 'warn') root.className += ' ' + item.level;
|
||||
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 stCls = item.denied ? 'denied' : item.status === 'failed' ? 'failed' : item.status === 'completed' ? 'completed' : 'running';
|
||||
root.className += ' ' + stCls;
|
||||
var markTxt = item.denied ? '⊘' : MARKS[item.status] || '…';
|
||||
root.appendChild(el(doc, 'span', 'mark', markTxt));
|
||||
var main = el(doc, 'div', 'tool-main');
|
||||
var headRow = el(doc, 'div', 'tool-head');
|
||||
if (item.toolKind) headRow.appendChild(el(doc, 'span', 'tool-kind', item.toolKind));
|
||||
headRow.appendChild(el(doc, 'span', 'title', String(item.title) + (item.denied ? ' (not allowed)' : '')));
|
||||
if (typeof item.ms === 'number') headRow.appendChild(el(doc, 'span', 'tool-ms', formatMs(item.ms)));
|
||||
main.appendChild(headRow);
|
||||
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());
|
||||
files.slice(0, 20).forEach(function (path) {
|
||||
var f = el(doc, 'span', 'file-chip', 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);
|
||||
main.appendChild(list);
|
||||
}
|
||||
if (item.output && typeof item.output === 'string' && item.output.trim()) {
|
||||
var outDet = el(doc, 'details', 'tool-output');
|
||||
if (uiState && uiState.openDetails && uiState.openDetails[item.id]) outDet.open = true;
|
||||
outDet.addEventListener('toggle', function () {
|
||||
if (uiState && uiState.openDetails) uiState.openDetails[item.id] = !!outDet.open;
|
||||
});
|
||||
outDet.appendChild(el(doc, 'summary', 'tool-output-summary', item.status === 'failed' ? 'Error output' : 'Output'));
|
||||
outDet.appendChild(el(doc, 'pre', '', item.output));
|
||||
main.appendChild(outDet);
|
||||
}
|
||||
root.appendChild(main);
|
||||
} 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'));
|
||||
var done = Number(item.done) || 0;
|
||||
var all = Number(item.all) || 0;
|
||||
var pHead = el(doc, 'div', 'plan-head');
|
||||
pHead.appendChild(el(doc, 'span', 'mark', all > 0 && done >= all ? '✓' : '▸'));
|
||||
pHead.appendChild(el(doc, 'span', 'title', (item.title ? item.title + ' — ' : 'Plan: ') + done + ' of ' + all + ' done'));
|
||||
root.appendChild(pHead);
|
||||
if (all > 0) {
|
||||
var bar = doc.createElement('progress');
|
||||
bar.className = 'plan-progress';
|
||||
bar.setAttribute('value', String(done));
|
||||
bar.setAttribute('max', String(all));
|
||||
root.appendChild(bar);
|
||||
}
|
||||
var entries = Array.isArray(item.entries) ? item.entries : [];
|
||||
if (entries.length) {
|
||||
var plist = el(doc, 'div', 'plan-entries');
|
||||
entries.slice(0, 20).forEach(function (ent) {
|
||||
entries.slice(0, 24).forEach(function (ent) {
|
||||
var row = el(doc, 'div', 'plan-entry ' + String(ent.status || 'pending').replace(/[^a-z_]/g, ''));
|
||||
row.appendChild(el(doc, 'span', 'pmark', PLAN_MARKS[ent.status] || '☐'));
|
||||
row.appendChild(el(doc, 'span', 'ptext', String(ent.content || '')));
|
||||
@@ -144,7 +268,9 @@
|
||||
} 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'));
|
||||
var who = open ? 'LLeMbas asks' + (item.tool ? ' (' + item.tool + ')' : '') : 'Asked';
|
||||
if (item.subagent) who += ' · ' + item.subagent;
|
||||
root.appendChild(el(doc, 'div', 'who', who));
|
||||
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));
|
||||
@@ -167,7 +293,7 @@
|
||||
}
|
||||
} else if (item.kind === 'question') {
|
||||
var qOpen = item.state === 'open';
|
||||
root.className += ' card' + (qOpen ? '' : ' closed');
|
||||
root.className += ' card info-card' + (qOpen ? '' : ' closed');
|
||||
root.appendChild(el(doc, 'div', 'who', qOpen ? 'LLeMbas asks a question' : 'Question'));
|
||||
if (item.why) root.appendChild(el(doc, 'div', 'reason', item.why));
|
||||
var qs = Array.isArray(item.questions) ? item.questions : [];
|
||||
@@ -176,14 +302,15 @@
|
||||
var inputs = [];
|
||||
qs.forEach(function (q, qi) {
|
||||
var blk = el(doc, 'div', 'q-block');
|
||||
if (q.header) blk.appendChild(el(doc, 'div', 'q-header', q.header));
|
||||
if (q.header) blk.appendChild(el(doc, 'div', 'q-header', q.header + (q.multiple ? ' (choose any)' : '')));
|
||||
blk.appendChild(el(doc, 'div', 'title', q.question));
|
||||
var opts = Array.isArray(q.options) ? q.options : [];
|
||||
if (opts.length) {
|
||||
var optWrap = el(doc, 'div', 'q-options');
|
||||
var btns = [];
|
||||
opts.forEach(function (o) {
|
||||
var b = button(doc, o.label + (o.description ? ' — ' + o.description : ''), 'second q-opt', function () {
|
||||
var labelTxt = o.label + (o.recommended ? ' ★' : '') + (o.description ? ' — ' + o.description : '');
|
||||
var b = button(doc, labelTxt, 'second q-opt', function () {
|
||||
if (q.multiple) {
|
||||
var idx = chosen[qi].indexOf(o.label);
|
||||
if (idx >= 0) {
|
||||
@@ -216,9 +343,10 @@
|
||||
var answers = qs.map(function (q, qi) {
|
||||
var typed = (inputs[qi] && typeof inputs[qi].value === 'string' ? inputs[qi].value.trim() : '');
|
||||
var list = chosen[qi].slice();
|
||||
if (typed) list.push(typed);
|
||||
if (!list.length && q.options && q.options[0]) list.push(q.options[0].label);
|
||||
return list;
|
||||
if (typed && !list.length) return { kind: 'custom', text: typed };
|
||||
if (typed && list.length) return { kind: 'custom', text: list.join(', ') + ' — ' + typed };
|
||||
if (list.length) return { kind: 'options', labels: list };
|
||||
return { kind: 'skipped' };
|
||||
});
|
||||
post({ type: 'answerQuestion', card: item.id, answers: answers });
|
||||
}));
|
||||
@@ -231,11 +359,17 @@
|
||||
}
|
||||
} else if (item.kind === 'plancard') {
|
||||
var pOpen = item.state === 'open';
|
||||
root.className += ' card' + (pOpen ? '' : ' closed');
|
||||
root.className += ' card plan-approval' + (pOpen ? '' : ' closed');
|
||||
root.appendChild(el(doc, 'div', 'who', pOpen ? 'Plan ready for approval' : 'Plan'));
|
||||
root.appendChild(el(doc, 'div', 'title', item.title || 'Plan'));
|
||||
if (pOpen && item.text) root.appendChild(el(doc, 'pre', '', item.text));
|
||||
if (pOpen) {
|
||||
if (Array.isArray(item.ast) && item.ast.length) {
|
||||
var pmd = el(doc, 'div', 'md plan-md');
|
||||
buildBlocks(doc, item.ast, pmd, 0, post);
|
||||
root.appendChild(pmd);
|
||||
} else if (item.text) {
|
||||
root.appendChild(el(doc, 'pre', '', item.text));
|
||||
}
|
||||
var fb = el(doc, 'input', 'q-input');
|
||||
fb.setAttribute('type', 'text');
|
||||
fb.setAttribute('placeholder', 'Optional feedback to revise the plan…');
|
||||
@@ -251,7 +385,7 @@
|
||||
post({ type: 'answerPlan', card: item.id, outcome: 'revise', value: fb.value || '' });
|
||||
}));
|
||||
pRow.appendChild(button(doc, 'Dismiss', 'second', function () {
|
||||
post({ type: 'answerPlan', card: item.id, outcome: 'dismiss', value: '' });
|
||||
post({ type: 'answerPlan', card: item.id, outcome: 'dismissed', value: '' });
|
||||
}));
|
||||
root.appendChild(pRow);
|
||||
} else {
|
||||
@@ -287,6 +421,20 @@
|
||||
var vscode = acquireVsCodeApi();
|
||||
var doc = document;
|
||||
var log = doc.getElementById('log');
|
||||
var empty = doc.getElementById('empty');
|
||||
var teamBar = doc.getElementById('team-bar');
|
||||
var connDot = doc.getElementById('conn-dot');
|
||||
var modeDot = doc.getElementById('mode-dot');
|
||||
var sessionTitle = doc.getElementById('session-title');
|
||||
var compactBtn = doc.getElementById('compact');
|
||||
var settingsToggle = doc.getElementById('settings-toggle');
|
||||
var settingsPanel = doc.getElementById('settings-panel');
|
||||
var acTokens = doc.getElementById('ac-tokens');
|
||||
var acTokensVal = doc.getElementById('ac-tokens-val');
|
||||
var acLength = doc.getElementById('ac-length');
|
||||
var acInstructions = doc.getElementById('ac-instructions');
|
||||
var acAuto = doc.getElementById('ac-auto');
|
||||
var chatThinking = doc.getElementById('chat-thinking');
|
||||
var prompt = doc.getElementById('prompt');
|
||||
var send = doc.getElementById('send');
|
||||
var stopBtn = doc.getElementById('stop');
|
||||
@@ -295,9 +443,12 @@
|
||||
var attached = doc.getElementById('attached');
|
||||
var attachedLabel = doc.getElementById('attached-label');
|
||||
var working = doc.getElementById('working');
|
||||
var workingText = doc.getElementById('working-text');
|
||||
var usageEl = doc.getElementById('usage');
|
||||
var popup = doc.getElementById('popup');
|
||||
var state = { busy: false, modes: [], models: [], mode: null, model: null, commands: [], progress: '', canSteer: false };
|
||||
var state = { busy: false, connected: false, modes: [], models: [], mode: null, model: null, commands: [], progress: '', canSteer: false, canCompact: false, title: '', usage: null, team: null };
|
||||
var nodes = {};
|
||||
var uiState = { openDetails: {} };
|
||||
var popupState = { kind: '', tokenStart: 0, tokenEnd: 0, items: [], index: 0 };
|
||||
var fileSearchSeq = 0;
|
||||
|
||||
@@ -309,20 +460,36 @@
|
||||
return log.scrollHeight - log.scrollTop - log.clientHeight < 40;
|
||||
}
|
||||
|
||||
function syncEmpty() {
|
||||
if (!empty) return;
|
||||
empty.hidden = Object.keys(nodes).length > 0;
|
||||
}
|
||||
|
||||
function autoRows() {
|
||||
var lines = (prompt.value || '').split('\n').length;
|
||||
prompt.setAttribute('rows', String(Math.max(3, Math.min(8, lines))));
|
||||
}
|
||||
|
||||
function upsert(item) {
|
||||
var stick = atBottom();
|
||||
var fresh = renderItem(doc, item, post);
|
||||
var fresh = renderItem(doc, item, post, uiState);
|
||||
var old = nodes[item.id];
|
||||
if (old && old.parentNode === log) log.replaceChild(fresh, old);
|
||||
else log.appendChild(fresh);
|
||||
nodes[item.id] = fresh;
|
||||
syncEmpty();
|
||||
if (stick) log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function reset(items) {
|
||||
while (log.firstChild) log.removeChild(log.firstChild);
|
||||
var children = Array.prototype.slice.call(log.childNodes);
|
||||
children.forEach(function (ch) {
|
||||
if (ch !== empty) log.removeChild(ch);
|
||||
});
|
||||
nodes = {};
|
||||
uiState.openDetails = {};
|
||||
(items || []).forEach(upsert);
|
||||
syncEmpty();
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
@@ -347,14 +514,58 @@
|
||||
select.disabled = options.length === 0;
|
||||
}
|
||||
|
||||
function renderTeam(tree) {
|
||||
if (!teamBar) return;
|
||||
while (teamBar.firstChild) teamBar.removeChild(teamBar.firstChild);
|
||||
var members = [];
|
||||
function walk(node) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (node.id && node.name) members.push(node);
|
||||
var kids = Array.isArray(node.children) ? node.children : Array.isArray(node.agents) ? node.agents : [];
|
||||
kids.forEach(walk);
|
||||
}
|
||||
if (Array.isArray(tree)) tree.forEach(walk);
|
||||
else walk(tree);
|
||||
if (!members.length) {
|
||||
teamBar.hidden = true;
|
||||
return;
|
||||
}
|
||||
teamBar.appendChild(el(doc, 'span', 'team-label', 'Agents'));
|
||||
members.slice(0, 8).forEach(function (m) {
|
||||
var chip = el(doc, 'span', 'team-chip ' + String(m.state || '').replace(/[^a-z]/g, ''));
|
||||
chip.textContent = String(m.name) + (m.state ? ' · ' + m.state : '');
|
||||
teamBar.appendChild(chip);
|
||||
});
|
||||
teamBar.hidden = false;
|
||||
}
|
||||
|
||||
function showState(s) {
|
||||
state = s;
|
||||
fill(mode, s.modes || [], s.mode, 'Mode');
|
||||
fill(model, s.models || [], s.model, 'Model');
|
||||
if (stopBtn) stopBtn.hidden = !s.busy;
|
||||
send.textContent = s.busy ? (s.canSteer ? 'Steer' : 'Stop') : 'Send';
|
||||
working.hidden = !s.busy;
|
||||
working.textContent = s.progress || 'Working…';
|
||||
if (working) working.hidden = !s.busy;
|
||||
if (workingText) workingText.textContent = s.progress || 'Working…';
|
||||
if (connDot) {
|
||||
connDot.className = 'dot' + (s.busy ? ' is-busy' : s.connected ? ' is-ok' : '');
|
||||
connDot.setAttribute('title', s.busy ? 'Working' : s.connected ? 'Connected' : 'Ready');
|
||||
}
|
||||
if (modeDot) {
|
||||
var mCls = String(s.mode || '').replace(/[^a-z]/g, '');
|
||||
modeDot.className = 'dot mode-dot' + (mCls ? ' mode-' + mCls : '');
|
||||
}
|
||||
if (sessionTitle) sessionTitle.textContent = s.title || 'LLeMbas';
|
||||
if (compactBtn) compactBtn.hidden = !s.canCompact;
|
||||
if (usageEl) {
|
||||
if (s.usage && (s.usage.input || s.usage.output)) {
|
||||
usageEl.textContent = '↑' + formatTokens(s.usage.input) + ' ↓' + formatTokens(s.usage.output);
|
||||
usageEl.hidden = false;
|
||||
} else {
|
||||
usageEl.hidden = true;
|
||||
}
|
||||
}
|
||||
renderTeam(s.team);
|
||||
// Mode can be switched live mid-run (Edit <-> Auto, etc.).
|
||||
mode.disabled = (s.modes || []).length === 0;
|
||||
model.disabled = model.disabled || !!s.busy;
|
||||
@@ -376,7 +587,10 @@
|
||||
popupState.items.forEach(function (it, idx) {
|
||||
var row = el(doc, 'div', 'popup-row' + (idx === popupState.index ? ' active' : ''));
|
||||
row.setAttribute('role', 'option');
|
||||
row.appendChild(el(doc, 'span', 'popup-label', it.label));
|
||||
var left = el(doc, 'span', 'popup-left');
|
||||
if (it.badge) left.appendChild(el(doc, 'span', 'popup-badge', it.badge));
|
||||
left.appendChild(el(doc, 'span', 'popup-label', it.label));
|
||||
row.appendChild(left);
|
||||
if (it.detail) row.appendChild(el(doc, 'span', 'popup-detail', it.detail));
|
||||
row.addEventListener('mousedown', function (ev) {
|
||||
ev.preventDefault();
|
||||
@@ -397,6 +611,7 @@
|
||||
var pos = (before + inserted).length;
|
||||
prompt.setSelectionRange(pos, pos);
|
||||
vscode.setState({ draft: prompt.value });
|
||||
autoRows();
|
||||
hidePopup();
|
||||
prompt.focus();
|
||||
}
|
||||
@@ -410,7 +625,14 @@
|
||||
var matches = (state.commands || [])
|
||||
.filter(function (c) { return !q || c.name.toLowerCase().indexOf(q) >= 0; })
|
||||
.slice(0, 12)
|
||||
.map(function (c) { return { label: '/' + c.name, detail: c.description || '', insert: '/' + c.name }; });
|
||||
.map(function (c) {
|
||||
return {
|
||||
badge: c.kind || 'cmd',
|
||||
label: '/' + c.name + (c.hint ? ' ' + c.hint : ''),
|
||||
detail: c.description || '',
|
||||
insert: '/' + c.name,
|
||||
};
|
||||
});
|
||||
popupState = { kind: 'command', tokenStart: 0, tokenEnd: pos, items: matches, index: 0 };
|
||||
renderPopup();
|
||||
return;
|
||||
@@ -432,6 +654,7 @@
|
||||
if (state.canSteer && text.trim()) {
|
||||
post({ type: 'steer', text: text });
|
||||
prompt.value = '';
|
||||
autoRows();
|
||||
vscode.setState({ draft: '' });
|
||||
hidePopup();
|
||||
return;
|
||||
@@ -442,6 +665,7 @@
|
||||
if (!text.trim()) return;
|
||||
post({ type: 'send', text: text });
|
||||
prompt.value = '';
|
||||
autoRows();
|
||||
vscode.setState({ draft: '' });
|
||||
hidePopup();
|
||||
}
|
||||
@@ -452,6 +676,24 @@
|
||||
post({ type: 'stop' });
|
||||
});
|
||||
}
|
||||
if (compactBtn) {
|
||||
compactBtn.addEventListener('click', function () {
|
||||
post({ type: 'compact' });
|
||||
});
|
||||
}
|
||||
if (empty) {
|
||||
empty.addEventListener('click', function (ev) {
|
||||
var btn = ev.target;
|
||||
while (btn && btn !== empty) {
|
||||
var act = btn.getAttribute && btn.getAttribute('data-action');
|
||||
if (act) {
|
||||
post({ type: act });
|
||||
return;
|
||||
}
|
||||
btn = btn.parentNode;
|
||||
}
|
||||
});
|
||||
}
|
||||
prompt.addEventListener('keydown', function (ev) {
|
||||
if (popup && !popup.hidden && popupState.items.length) {
|
||||
if (ev.key === 'ArrowDown') {
|
||||
@@ -479,6 +721,7 @@
|
||||
}
|
||||
});
|
||||
prompt.addEventListener('input', function () {
|
||||
autoRows();
|
||||
vscode.setState({ draft: prompt.value });
|
||||
checkPopup();
|
||||
});
|
||||
@@ -517,7 +760,7 @@
|
||||
}
|
||||
if (t.tagName === 'CODE' && (!t.parentNode || t.parentNode.tagName !== 'PRE')) {
|
||||
var raw = (t.textContent || '').trim();
|
||||
var fm = /^([A-Za-z0-9_.\-\/]+\.[A-Za-z0-9]{1,10})(?::(\d+)(?:-\d+)?)?$/.exec(raw);
|
||||
var fm = FILE_REF_RE.exec(raw);
|
||||
if (fm) {
|
||||
return post({ type: 'openFile', path: fm[1], line: fm[2] ? Number(fm[2]) : undefined, soft: true });
|
||||
}
|
||||
@@ -532,6 +775,94 @@
|
||||
if (ev.key === 'Enter') follow(ev.target);
|
||||
});
|
||||
|
||||
function formatTokenReadout(n) {
|
||||
var v = Number(n) || 0;
|
||||
return v <= 0 ? 'Default' : v + ' tokens';
|
||||
}
|
||||
|
||||
function applySettingsUi(cfg) {
|
||||
if (!cfg || typeof cfg !== 'object') return;
|
||||
var tokens = Math.max(0, Math.min(4096, Number(cfg.maxTokens) || 0));
|
||||
var len = typeof cfg.length === 'string' ? cfg.length : 'auto';
|
||||
if (acTokens) acTokens.value = String(tokens);
|
||||
if (acTokensVal) acTokensVal.textContent = formatTokenReadout(tokens);
|
||||
if (acLength) acLength.value = len;
|
||||
if (acInstructions && doc.activeElement !== acInstructions) acInstructions.value = String(cfg.instructions || '');
|
||||
if (acAuto) acAuto.checked = cfg.auto !== false;
|
||||
if (chatThinking) chatThinking.checked = !!cfg.showThinking;
|
||||
if (settingsPanel) {
|
||||
var btns = settingsPanel.querySelectorAll('.preset-btn');
|
||||
for (var i = 0; i < btns.length; i++) {
|
||||
var b = btns[i];
|
||||
var match = b.getAttribute('data-length') === len && Number(b.getAttribute('data-tokens')) === tokens;
|
||||
b.className = 'mini preset-btn' + (match ? ' active' : '');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function pushSettings(patch) {
|
||||
post({ type: 'updateSettings', settings: patch });
|
||||
}
|
||||
|
||||
if (settingsToggle && settingsPanel) {
|
||||
settingsToggle.addEventListener('click', function () {
|
||||
var open = settingsPanel.hidden;
|
||||
settingsPanel.hidden = !open;
|
||||
settingsToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||||
});
|
||||
settingsPanel.addEventListener('click', function (ev) {
|
||||
var btn = ev.target;
|
||||
if (btn && btn.className && String(btn.className).indexOf('preset-btn') >= 0) {
|
||||
var len = btn.getAttribute('data-length') || 'auto';
|
||||
var toks = Number(btn.getAttribute('data-tokens')) || 0;
|
||||
applySettingsUi({
|
||||
maxTokens: toks,
|
||||
length: len,
|
||||
instructions: acInstructions ? acInstructions.value : '',
|
||||
auto: acAuto ? acAuto.checked : true,
|
||||
showThinking: chatThinking ? chatThinking.checked : false,
|
||||
});
|
||||
pushSettings({ maxTokens: toks, length: len });
|
||||
}
|
||||
});
|
||||
}
|
||||
if (acTokens) {
|
||||
acTokens.addEventListener('input', function () {
|
||||
if (acTokensVal) acTokensVal.textContent = formatTokenReadout(acTokens.value);
|
||||
});
|
||||
acTokens.addEventListener('change', function () {
|
||||
pushSettings({ maxTokens: Number(acTokens.value) || 0 });
|
||||
});
|
||||
}
|
||||
if (acLength) {
|
||||
acLength.addEventListener('change', function () {
|
||||
pushSettings({ length: acLength.value });
|
||||
});
|
||||
}
|
||||
var instrTimer = null;
|
||||
if (acInstructions) {
|
||||
acInstructions.addEventListener('input', function () {
|
||||
if (instrTimer) clearTimeout(instrTimer);
|
||||
instrTimer = setTimeout(function () {
|
||||
pushSettings({ instructions: acInstructions.value });
|
||||
}, 300);
|
||||
});
|
||||
acInstructions.addEventListener('change', function () {
|
||||
if (instrTimer) clearTimeout(instrTimer);
|
||||
pushSettings({ instructions: acInstructions.value });
|
||||
});
|
||||
}
|
||||
if (acAuto) {
|
||||
acAuto.addEventListener('change', function () {
|
||||
pushSettings({ auto: !!acAuto.checked });
|
||||
});
|
||||
}
|
||||
if (chatThinking) {
|
||||
chatThinking.addEventListener('change', function () {
|
||||
pushSettings({ showThinking: !!chatThinking.checked });
|
||||
});
|
||||
}
|
||||
|
||||
window.addEventListener('message', function (ev) {
|
||||
var m = ev.data;
|
||||
if (!m || typeof m !== 'object') return;
|
||||
@@ -539,18 +870,32 @@
|
||||
reset(m.items);
|
||||
showState(m.state);
|
||||
showAttached(m.attached);
|
||||
if (m.settings) applySettingsUi(m.settings);
|
||||
} else if (m.type === 'item') upsert(m.item);
|
||||
else if (m.type === 'state') showState(m.state);
|
||||
else if (m.type === 'settings') applySettingsUi(m.settings);
|
||||
else if (m.type === 'attached') showAttached(m.label);
|
||||
else if (m.type === 'focus') prompt.focus();
|
||||
else if (m.type === 'insertText' && typeof m.text === 'string') {
|
||||
var cur = prompt.value;
|
||||
prompt.value = cur && !/\s$/.test(cur) ? cur + ' ' + m.text : cur + m.text;
|
||||
autoRows();
|
||||
vscode.setState({ draft: prompt.value });
|
||||
prompt.focus();
|
||||
} else if (m.type === 'files' && m.seq === fileSearchSeq && popupState.kind === 'file') {
|
||||
popupState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 14).map(function (f) {
|
||||
return { label: f, detail: '', insert: '@' + f };
|
||||
popupState.items = (Array.isArray(m.files) ? m.files : []).slice(0, 14).map(function (entry) {
|
||||
var p = typeof entry === 'string' ? entry : String((entry && entry.path) || '');
|
||||
var isDir = typeof entry === 'object' && entry && entry.kind === 'dir';
|
||||
var slashIdx = p.lastIndexOf('/');
|
||||
var base = slashIdx >= 0 ? p.slice(slashIdx + 1) : p;
|
||||
var dir = slashIdx >= 0 ? p.slice(0, slashIdx) : '';
|
||||
var insertPath = escapeAtPath(p) + (isDir ? '/' : '');
|
||||
return {
|
||||
badge: isDir ? 'dir' : 'file',
|
||||
label: base + (isDir ? '/' : ''),
|
||||
detail: dir,
|
||||
insert: '@' + insertPath,
|
||||
};
|
||||
});
|
||||
popupState.index = 0;
|
||||
renderPopup();
|
||||
@@ -559,10 +904,13 @@
|
||||
|
||||
function showAttached(label) {
|
||||
attached.hidden = !label;
|
||||
attachedLabel.textContent = label ? 'With ' + label : '';
|
||||
attachedLabel.textContent = label ? 'Selection: ' + label : '';
|
||||
}
|
||||
|
||||
var saved = vscode.getState();
|
||||
if (saved && typeof saved.draft === 'string') prompt.value = saved.draft;
|
||||
if (saved && typeof saved.draft === 'string') {
|
||||
prompt.value = saved.draft;
|
||||
autoRows();
|
||||
}
|
||||
post({ type: 'ready' });
|
||||
})();
|
||||
+22
-2
@@ -34,6 +34,7 @@
|
||||
{ "command": "llembas.open", "title": "Open the Chat", "category": "LLeMbas" },
|
||||
{ "command": "llembas.newSession", "title": "New Session", "category": "LLeMbas" },
|
||||
{ "command": "llembas.resumeSession", "title": "Resume a Previous Session", "category": "LLeMbas" },
|
||||
{ "command": "llembas.compact", "title": "Compact Session Context", "category": "LLeMbas" },
|
||||
{ "command": "llembas.stop", "title": "Stop the Running Turn", "category": "LLeMbas" },
|
||||
{ "command": "llembas.ask", "title": "Ask About the Selection", "category": "LLeMbas" },
|
||||
{ "command": "llembas.explain", "title": "Explain the Selection", "category": "LLeMbas" },
|
||||
@@ -41,6 +42,7 @@
|
||||
{ "command": "llembas.generate", "title": "Generate Code at Cursor", "category": "LLeMbas" },
|
||||
{ "command": "llembas.rewrite", "title": "Rewrite the Selection", "category": "LLeMbas" },
|
||||
{ "command": "llembas.complete", "title": "Suggest a Completion Here", "category": "LLeMbas" },
|
||||
{ "command": "llembas.toggleAutocomplete", "title": "Toggle Autocomplete as You Type", "category": "LLeMbas" },
|
||||
{ "command": "llembas.openFile", "title": "Open File from Project Index", "category": "LLeMbas" },
|
||||
{ "command": "llembas.addFile", "title": "Add File to Chat", "category": "LLeMbas" },
|
||||
{ "command": "llembas.acceptChange", "title": "Accept the Proposed Change at the Cursor", "category": "LLeMbas" },
|
||||
@@ -127,8 +129,26 @@
|
||||
"type": "number",
|
||||
"default": 0,
|
||||
"minimum": 0,
|
||||
"maximum": 512,
|
||||
"description": "The longest completion to ask for, in tokens. 0: the server's own number."
|
||||
"maximum": 4096,
|
||||
"description": "Maximum tokens to predict for autocomplete (0: server default or preset; e.g. 24 for a few words, 256 for a block, 2048 for a large file section)."
|
||||
},
|
||||
"llembas.complete.length": {
|
||||
"type": "string",
|
||||
"default": "auto",
|
||||
"enum": ["auto", "words", "line", "block", "file"],
|
||||
"enumDescriptions": [
|
||||
"Use the server's default prediction length",
|
||||
"Few words — finish the current expression or identifier (~24 tokens)",
|
||||
"Single line — finish the current line (~64 tokens)",
|
||||
"Function / block — complete a block or function (~256 tokens)",
|
||||
"Large / file — predict a large multi-block or full-file continuation (~2048 tokens)"
|
||||
],
|
||||
"description": "How much code autocomplete should aim to predict, paired with guidance instructions."
|
||||
},
|
||||
"llembas.complete.instructions": {
|
||||
"type": "string",
|
||||
"default": "",
|
||||
"description": "Custom instructions sent with autocomplete requests (e.g. style, brevity, or scope guidance)."
|
||||
},
|
||||
"llembas.rewrite.openDiff": {
|
||||
"type": "boolean",
|
||||
|
||||
+190
-35
@@ -12,13 +12,69 @@ function sentence(text) {
|
||||
return s ? s[0].toUpperCase() + s.slice(1) + (/[.!?…]$/.test(s) ? '' : '.') : '';
|
||||
}
|
||||
|
||||
/** Normalize an entry from `_lembas/files/search` (`{ path, kind }` or plain string). */
|
||||
function normalizeFileEntry(entry) {
|
||||
if (typeof entry === 'string') {
|
||||
const clean = entry.replace(/\/$/, '');
|
||||
return clean ? { path: clean, kind: entry.endsWith('/') ? 'dir' : 'file' } : null;
|
||||
}
|
||||
if (entry && typeof entry === 'object' && typeof entry.path === 'string' && entry.path) {
|
||||
return { path: entry.path.replace(/\/$/, ''), kind: entry.kind === 'dir' ? 'dir' : 'file' };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Normalize one answer for `_lembas/question` to the harness spec's Answer shape. */
|
||||
function normalizeAnswer(a, question) {
|
||||
if (a === null || a === undefined) return { kind: 'skipped' };
|
||||
if (typeof a === 'object' && !Array.isArray(a) && typeof a.kind === 'string') {
|
||||
if (a.kind === 'options' && Array.isArray(a.labels)) {
|
||||
const labels = a.labels.map(String).filter(Boolean);
|
||||
return labels.length ? { kind: 'options', labels } : { kind: 'skipped' };
|
||||
}
|
||||
if ((a.kind === 'custom' || a.kind === 'back') && typeof a.text === 'string') {
|
||||
const text = a.text.trim();
|
||||
return text ? { kind: a.kind, text } : { kind: 'skipped' };
|
||||
}
|
||||
if (a.kind === 'skipped') return { kind: 'skipped' };
|
||||
}
|
||||
if (Array.isArray(a)) {
|
||||
const items = a.map(String).map((s) => s.trim()).filter(Boolean);
|
||||
if (!items.length) return { kind: 'skipped' };
|
||||
const known = new Set(((question && question.options) || []).map((o) => o.label));
|
||||
if (known.size && items.every((l) => known.has(l))) return { kind: 'options', labels: items };
|
||||
if (items.length === 1 && !known.has(items[0])) return { kind: 'custom', text: items[0] };
|
||||
return { kind: 'options', labels: items };
|
||||
}
|
||||
const text = String(a).trim();
|
||||
if (!text) return { kind: 'skipped' };
|
||||
const known = new Set(((question && question.options) || []).map((o) => o.label));
|
||||
if (known.has(text)) return { kind: 'options', labels: [text] };
|
||||
return { kind: 'custom', text };
|
||||
}
|
||||
|
||||
function summarizeAnswer(a) {
|
||||
if (!a || a.kind === 'skipped') return 'Skipped';
|
||||
if (a.kind === 'options') return (a.labels || []).join(', ');
|
||||
if (a.kind === 'custom' || a.kind === 'back') return a.text || '';
|
||||
return '';
|
||||
}
|
||||
|
||||
function extractTextContent(content) {
|
||||
return (Array.isArray(content) ? 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');
|
||||
}
|
||||
|
||||
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 },
|
||||
* hooks?: { readTextFile?: Function, writeTextFile?: 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)`.
|
||||
*/
|
||||
@@ -43,7 +99,10 @@ class Chat extends EventEmitter {
|
||||
this.modes = [];
|
||||
this.mode = null;
|
||||
this.model = null;
|
||||
this.title = '';
|
||||
this.progress = '';
|
||||
this.usage = null;
|
||||
this.team = null;
|
||||
this.commands = [];
|
||||
this.said = null;
|
||||
this.planItem = null;
|
||||
@@ -70,22 +129,29 @@ class Chat extends EventEmitter {
|
||||
this.emit('item', item);
|
||||
}
|
||||
|
||||
note(text) {
|
||||
note(text, level) {
|
||||
this.said = null;
|
||||
return this.add({ kind: 'note', text: String(text) });
|
||||
const item = { kind: 'note', text: String(text) };
|
||||
if (level && level !== 'info') item.level = String(level);
|
||||
return this.add(item);
|
||||
}
|
||||
|
||||
/** What the view needs besides the items. */
|
||||
state() {
|
||||
return {
|
||||
busy: this.busy,
|
||||
connected: !!(this.agent && this.agent.ready && !this.agent.stopped),
|
||||
session: !!this.session,
|
||||
title: this.title,
|
||||
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) })),
|
||||
progress: this.progress,
|
||||
usage: this.usage,
|
||||
team: this.team,
|
||||
canSteer: !!(this.session && this.has('steer')),
|
||||
canCompact: !!(this.session && !this.busy && this.has('compact')),
|
||||
commands: this.commands,
|
||||
};
|
||||
}
|
||||
@@ -116,12 +182,13 @@ class Chat extends EventEmitter {
|
||||
this.failedAt = 0;
|
||||
this.startError = null;
|
||||
this.emit('connected', agent);
|
||||
this.emit('state');
|
||||
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));
|
||||
if (!quiet) this.note(sentence(e.message), 'error');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -139,7 +206,7 @@ class Chat extends EventEmitter {
|
||||
for (const q of [...this.questions.values()]) this._settleQuestion(q, 'The agent stopped before this was answered.');
|
||||
for (const pl of [...this.planCards.values()]) this._settlePlan(pl, '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 : '.'}`);
|
||||
if (e && e.started && had) this.note(`The agent stopped (${e.signal || 'exit ' + e.code})${e.last ? ': ' + e.last : '.'}`, 'error');
|
||||
else if (!e && had) this.note('The agent was stopped. The next message starts a new session.');
|
||||
this.emit('stopped');
|
||||
this.emit('state');
|
||||
@@ -183,7 +250,7 @@ class Chat extends EventEmitter {
|
||||
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));
|
||||
if (this.agent === agent) this.note('No session: ' + sentence(e.message), 'error');
|
||||
return false;
|
||||
}
|
||||
if (this.agent !== agent || !r || typeof r.sessionId !== 'string') return false;
|
||||
@@ -224,11 +291,12 @@ class Chat extends EventEmitter {
|
||||
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 (typeof lembas.summary === 'string' && lembas.summary) this.note('Compacted: ' + lembas.summary);
|
||||
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));
|
||||
if (this.agent === agent) this.note('The turn failed: ' + sentence(e.message), 'error');
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
@@ -249,6 +317,15 @@ class Chat extends EventEmitter {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Compact the session's conversation history (`_lembas/session/compact`). */
|
||||
async compact() {
|
||||
if (this.busy || !this.agent || !this.session) return false;
|
||||
const r = await this.agent.request('_lembas/session/compact', { sessionId: this.session });
|
||||
const summary = r && typeof r.summary === 'string' ? r.summary.trim() : '';
|
||||
this.note(summary ? 'Session compacted: ' + summary : 'Session compacted.');
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Stop the running turn. Cards still open are answered as cancelled, as ACP asks. */
|
||||
stop() {
|
||||
if (!this.agent || !this.session || !this.busy) return;
|
||||
@@ -310,22 +387,25 @@ class Chat extends EventEmitter {
|
||||
const list = r && Array.isArray(r.commands) ? r.commands : [];
|
||||
this.commands = list
|
||||
.filter((c) => c && typeof c.name === 'string')
|
||||
.map((c) => ({ name: String(c.name), description: String(c.description || ''), source: String(c.source || '') }));
|
||||
.map((c) => ({
|
||||
name: String(c.name),
|
||||
description: String(c.description || ''),
|
||||
hint: String((c.input && c.input.hint) || ''),
|
||||
kind: String((c._meta && c._meta.lembas && c._meta.lembas.kind) || c.source || ''),
|
||||
}));
|
||||
this.emit('state');
|
||||
return this.commands;
|
||||
}
|
||||
|
||||
/** Search the project's file index (`_lembas/files/search`). */
|
||||
/** Search the project's file index (`_lembas/files/search`). Returns `{ path, kind }[]`. */
|
||||
async searchFiles(query, limit) {
|
||||
const agent = await this.connect(true);
|
||||
if (!agent || !agent.has('files')) return [];
|
||||
if (!this.session && !(await this.ensureSession())) return [];
|
||||
const r = await agent.request('_lembas/files/search', {
|
||||
sessionId: this.session,
|
||||
query: String(query || ''),
|
||||
limit: limit || 30,
|
||||
});
|
||||
return r && Array.isArray(r.files) ? r.files.filter((f) => typeof f === 'string') : [];
|
||||
const params = { query: String(query || ''), limit: limit || 30 };
|
||||
if (this.session) params.sessionId = this.session;
|
||||
else params.cwd = this.io.cwd();
|
||||
const r = await agent.request('_lembas/files/search', params);
|
||||
return (r && Array.isArray(r.files) ? r.files : []).map(normalizeFileEntry).filter(Boolean);
|
||||
}
|
||||
|
||||
/** List previous sessions in this project (`_lembas/sessions/list`). */
|
||||
@@ -346,27 +426,64 @@ class Chat extends EventEmitter {
|
||||
this.agent = agent;
|
||||
this.models = models;
|
||||
this.session = r.sessionId;
|
||||
this.title = typeof r.title === 'string' ? r.title : '';
|
||||
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.items = [];
|
||||
const showThoughts = !!this.options().showThoughts;
|
||||
for (const turn of Array.isArray(r.turns) ? r.turns : []) {
|
||||
if (turn && typeof turn.user === 'string' && turn.user.trim()) {
|
||||
if (!turn || typeof turn !== 'object') continue;
|
||||
if (turn.role === 'user') {
|
||||
const att = Array.isArray(turn.attachments) && turn.attachments.length ? turn.attachments.map((a) => a.name).filter(Boolean).join(', ') : '';
|
||||
const label = turn.machine ? 'harness' : att;
|
||||
if ((typeof turn.text === 'string' && turn.text.trim()) || label) {
|
||||
this.items.push({ id: 'i' + this.nextItem++, kind: 'user', text: String(turn.text || ''), label });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (turn.role === 'assistant') {
|
||||
if (showThoughts && typeof turn.reasoning === 'string' && turn.reasoning.trim()) {
|
||||
this.items.push({ id: 'i' + this.nextItem++, kind: 'thought', text: turn.reasoning });
|
||||
}
|
||||
for (const t of Array.isArray(turn.tools) ? turn.tools : []) {
|
||||
const out = typeof t.output === 'string' ? t.output : '';
|
||||
this.items.push({
|
||||
id: 'i' + this.nextItem++,
|
||||
kind: 'tool',
|
||||
toolCallId: String(t.id || 'h' + this.nextItem),
|
||||
title: String(t.title || t.name || 'tool'),
|
||||
toolKind: String(t.kind || ''),
|
||||
status: t.isError ? 'failed' : 'completed',
|
||||
output: out.length > DETAIL_MAX ? out.slice(0, DETAIL_MAX) + '\n…' : out,
|
||||
files: [],
|
||||
denied: false,
|
||||
});
|
||||
}
|
||||
if (typeof turn.text === 'string' && turn.text.trim()) {
|
||||
this.items.push({ id: 'i' + this.nextItem++, kind: 'agent', text: turn.text });
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Legacy combined shape fallback ({ user, assistant, tools })
|
||||
if (typeof turn.user === 'string' && turn.user.trim()) {
|
||||
this.items.push({ id: 'i' + this.nextItem++, kind: 'user', text: turn.user, label: '' });
|
||||
}
|
||||
for (const t of Array.isArray(turn && turn.tools) ? turn.tools : []) {
|
||||
for (const t of Array.isArray(turn.tools) ? turn.tools : []) {
|
||||
this.items.push({
|
||||
id: 'i' + this.nextItem++,
|
||||
kind: 'tool',
|
||||
toolCallId: String(t.id || 'h' + this.nextItem),
|
||||
title: String(t.title || t.name || 'tool'),
|
||||
toolKind: String(t.kind || ''),
|
||||
status: t.isError ? 'failed' : 'completed',
|
||||
output: typeof t.output === 'string' ? t.output.slice(0, DETAIL_MAX) : '',
|
||||
files: [],
|
||||
denied: false,
|
||||
});
|
||||
}
|
||||
if (turn && typeof turn.assistant === 'string' && turn.assistant.trim()) {
|
||||
if (typeof turn.assistant === 'string' && turn.assistant.trim()) {
|
||||
this.items.push({ id: 'i' + this.nextItem++, kind: 'agent', text: turn.assistant });
|
||||
}
|
||||
}
|
||||
@@ -411,10 +528,36 @@ class Chat extends EventEmitter {
|
||||
} else if (ev.type === 'mode' && typeof ev.mode === 'string') {
|
||||
this.mode = ev.mode;
|
||||
this.emit('state');
|
||||
} else if (ev.type === 'title' && typeof ev.title === 'string') {
|
||||
this.title = ev.title;
|
||||
this.emit('state');
|
||||
} else if (ev.type === 'phase') {
|
||||
const p = ev.progress;
|
||||
this.progress = p && typeof p.phase === 'string' ? p.phase.replace(/_/g, ' ') + (p.detail ? ': ' + p.detail : '') : '';
|
||||
this.emit('state');
|
||||
} else if (ev.type === 'usage') {
|
||||
const input = Number(ev.input_tokens ?? ev.input ?? ev.tokens_in ?? 0) || 0;
|
||||
const output = Number(ev.output_tokens ?? ev.output ?? ev.tokens_out ?? 0) || 0;
|
||||
if (input || output) {
|
||||
this.usage = {
|
||||
input: (this.usage ? this.usage.input : 0) + input,
|
||||
output: (this.usage ? this.usage.output : 0) + output,
|
||||
};
|
||||
this.emit('state');
|
||||
}
|
||||
} else if (ev.type === 'tool_end' && typeof ev.id === 'string' && typeof ev.ms === 'number') {
|
||||
const item = this.tools.get(ev.id);
|
||||
if (item) {
|
||||
item.ms = Math.max(0, Math.round(ev.ms));
|
||||
this.changed(item);
|
||||
}
|
||||
} else if (ev.type === 'notice' && typeof ev.message === 'string' && ev.message.trim()) {
|
||||
this.note(ev.message, ev.level || 'info');
|
||||
} else if (ev.type === 'compacted' && typeof ev.summary === 'string' && ev.summary.trim()) {
|
||||
this.note('Context compacted: ' + ev.summary);
|
||||
} else if (ev.type === 'team') {
|
||||
this.team = ev.tree || null;
|
||||
this.emit('state');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -437,29 +580,35 @@ class Chat extends EventEmitter {
|
||||
let item = this.tools.get(id);
|
||||
const fresh = !item;
|
||||
if (!item) {
|
||||
item = { kind: 'tool', toolCallId: id, title: 'tool', status: 'pending', files: [], denied: false };
|
||||
item = { kind: 'tool', toolCallId: id, title: 'tool', toolKind: '', status: 'pending', files: [], output: '', denied: false };
|
||||
this.tools.set(id, item);
|
||||
}
|
||||
if (typeof u.title === 'string' && u.title) item.title = u.title;
|
||||
if (typeof u.kind === 'string' && u.kind) item.toolKind = u.kind;
|
||||
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)];
|
||||
const textOut = extractTextContent(u.content);
|
||||
if (textOut) item.output = textOut.length > DETAIL_MAX ? textOut.slice(0, DETAIL_MAX) + '\n…' : textOut;
|
||||
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 structured = (u._meta && u._meta.lembas && u._meta.lembas.plan) || null;
|
||||
if (!entries.length && !structured) return;
|
||||
const done = entries.filter((e) => e && e.status === 'completed').length;
|
||||
const mapped = entries.map((e) => ({
|
||||
content: String((e && e.content) || ''),
|
||||
status: String((e && e.status) || 'pending'),
|
||||
}));
|
||||
const title = structured && typeof structured.title === 'string' ? structured.title : '';
|
||||
if (!this.planItem || !this.items.includes(this.planItem)) {
|
||||
this.planItem = this.add({ kind: 'plan', done, all: entries.length, entries: mapped });
|
||||
this.planItem = this.add({ kind: 'plan', title, done, all: entries.length, entries: mapped });
|
||||
} else {
|
||||
this.planItem.title = title;
|
||||
this.planItem.done = done;
|
||||
this.planItem.all = entries.length;
|
||||
this.planItem.entries = mapped;
|
||||
@@ -473,7 +622,12 @@ class Chat extends EventEmitter {
|
||||
const list = Array.isArray(u.availableCommands) ? u.availableCommands : [];
|
||||
this.commands = list
|
||||
.filter((c) => c && typeof c.name === 'string')
|
||||
.map((c) => ({ name: String(c.name), description: String(c.description || ''), source: '' }));
|
||||
.map((c) => ({
|
||||
name: String(c.name),
|
||||
description: String(c.description || ''),
|
||||
hint: String((c.input && c.input.hint) || ''),
|
||||
kind: String((c._meta && c._meta.lembas && c._meta.lembas.kind) || ''),
|
||||
}));
|
||||
this.emit('state');
|
||||
}
|
||||
}
|
||||
@@ -502,15 +656,14 @@ class Chat extends EventEmitter {
|
||||
.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 text = extractTextContent(call.content);
|
||||
const subagent = lembas.subagent && typeof lembas.subagent.name === 'string' ? lembas.subagent.name : '';
|
||||
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 : '',
|
||||
subagent,
|
||||
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),
|
||||
@@ -540,6 +693,7 @@ class Chat extends EventEmitter {
|
||||
options: (Array.isArray(q && q.options) ? q.options : []).map((o) => ({
|
||||
label: String((o && o.label) || ''),
|
||||
description: String((o && o.description) || ''),
|
||||
recommended: !!(o && o.recommended),
|
||||
})),
|
||||
}));
|
||||
const item = this.add({
|
||||
@@ -560,9 +714,10 @@ class Chat extends EventEmitter {
|
||||
const q = this.questions.get(cardId);
|
||||
if (!q) return false;
|
||||
this.questions.delete(cardId);
|
||||
const list = Array.isArray(answers) ? answers.map((a) => (Array.isArray(a) ? a.map(String) : [String(a)])) : [];
|
||||
const qs = q.item.questions || [];
|
||||
const list = (Array.isArray(answers) ? answers : []).map((a, i) => normalizeAnswer(a, qs[i]));
|
||||
q.item.state = 'answered';
|
||||
q.item.answer = list.map((a) => a.join(', ')).filter(Boolean).join(' · ') || 'Answered';
|
||||
q.item.answer = list.map(summarizeAnswer).filter(Boolean).join(' · ') || 'Answered';
|
||||
this.changed(q.item);
|
||||
q.resolve({ outcome: 'answered', answers: list });
|
||||
return true;
|
||||
@@ -616,10 +771,10 @@ class Chat extends EventEmitter {
|
||||
reply = { outcome: 'revise', feedback };
|
||||
label = feedback ? 'Revision requested: ' + feedback : 'Revision requested';
|
||||
} else {
|
||||
reply = { outcome: 'dismiss' };
|
||||
reply = { outcome: 'dismissed' };
|
||||
label = 'Dismissed';
|
||||
}
|
||||
pl.item.state = outcome === 'dismiss' ? 'settled' : 'answered';
|
||||
pl.item.state = outcome === 'dismiss' || outcome === 'dismissed' ? 'settled' : 'answered';
|
||||
pl.item.answer = label;
|
||||
this.changed(pl.item);
|
||||
pl.resolve(reply);
|
||||
@@ -631,7 +786,7 @@ class Chat extends EventEmitter {
|
||||
pl.item.state = 'settled';
|
||||
pl.item.answer = why;
|
||||
this.changed(pl.item);
|
||||
pl.resolve({ outcome: 'dismiss' });
|
||||
pl.resolve({ outcome: 'dismissed' });
|
||||
}
|
||||
|
||||
/** The person's answer to a card. */
|
||||
@@ -677,7 +832,7 @@ class Chat extends EventEmitter {
|
||||
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}`);
|
||||
this.note(`${(got && got.name) || 'A file'} was not shown: ${reason}`, 'warn');
|
||||
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 });
|
||||
@@ -715,4 +870,4 @@ function diffItems(content) {
|
||||
return out;
|
||||
}
|
||||
|
||||
module.exports = { Chat, diffItems };
|
||||
module.exports = { Chat, diffItems, normalizeFileEntry, normalizeAnswer };
|
||||
@@ -4,6 +4,40 @@
|
||||
|
||||
const REFUSALS = new Set(['no_model', 'not_allowed', 'not_logged_in', 'unsupported']);
|
||||
|
||||
const LENGTH_PRESETS = {
|
||||
auto: { tokens: 0, instruction: '' },
|
||||
words: {
|
||||
tokens: 24,
|
||||
instruction: 'Predict only a few words to finish the current expression or identifier. Stop immediately once the current token or phrase is complete.',
|
||||
},
|
||||
line: {
|
||||
tokens: 64,
|
||||
instruction: 'Predict at most the remainder of the current line. Do not start a new line.',
|
||||
},
|
||||
block: {
|
||||
tokens: 256,
|
||||
instruction: 'Predict a complete statement, block, or function body fitting the surrounding code.',
|
||||
},
|
||||
file: {
|
||||
tokens: 2048,
|
||||
instruction: 'Predict a comprehensive continuation, up to a full multi-function section or file implementation when appropriate.',
|
||||
},
|
||||
};
|
||||
|
||||
/** Resolve effective `max_tokens` and guidance instruction from user settings. */
|
||||
function resolvePrediction(o) {
|
||||
const opts = o || {};
|
||||
const mode = typeof opts.length === 'string' && Object.prototype.hasOwnProperty.call(LENGTH_PRESETS, opts.length) ? opts.length : 'auto';
|
||||
const preset = LENGTH_PRESETS[mode];
|
||||
const explicitTokens = Number.isFinite(Number(opts.maxTokens)) && Number(opts.maxTokens) > 0 ? Math.floor(Number(opts.maxTokens)) : 0;
|
||||
const maxTokens = explicitTokens || preset.tokens || undefined;
|
||||
const parts = [];
|
||||
if (preset.instruction) parts.push(preset.instruction);
|
||||
if (typeof opts.instructions === 'string' && opts.instructions.trim()) parts.push(opts.instructions.trim());
|
||||
const guidance = parts.join('\n');
|
||||
return { mode, maxTokens, guidance };
|
||||
}
|
||||
|
||||
/** The text around the cursor that is sent: a window, not the file. */
|
||||
function windowAround(text, offset, limits) {
|
||||
const prefixMax = (limits && limits.prefixMax) || 12000;
|
||||
@@ -28,6 +62,8 @@ class Completer {
|
||||
* debounceMs?: () => number,
|
||||
* model?: () => string | undefined,
|
||||
* maxTokens?: () => number | undefined,
|
||||
* length?: () => string | undefined,
|
||||
* instructions?: () => string | undefined,
|
||||
* onRefusal?: (reason: string, message: string, manual: boolean) => void,
|
||||
* onError?: (message: string, manual: boolean) => void,
|
||||
* setTimeout?: Function, clearTimeout?: Function, now?: () => number }} io
|
||||
@@ -84,11 +120,17 @@ class Completer {
|
||||
if (what.cwd) params.cwd = what.cwd;
|
||||
if (what.sessionId) params.sessionId = what.sessionId;
|
||||
if (Array.isArray(what.open) && what.open.length) params.open = what.open;
|
||||
if (Array.isArray(what.context) && what.context.length) params.context = what.context;
|
||||
const pred = resolvePrediction({
|
||||
maxTokens: this.io.maxTokens ? this.io.maxTokens() : undefined,
|
||||
length: this.io.length ? this.io.length() : undefined,
|
||||
instructions: this.io.instructions ? this.io.instructions() : undefined,
|
||||
});
|
||||
const ctx = Array.isArray(what.context) ? what.context.slice() : [];
|
||||
if (pred.guidance) ctx.unshift({ path: 'llembas:autocomplete-instructions', text: pred.guidance });
|
||||
if (ctx.length) params.context = ctx;
|
||||
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;
|
||||
if (pred.maxTokens) params.max_tokens = pred.maxTokens;
|
||||
let asked;
|
||||
try {
|
||||
asked = Promise.resolve(this.io.request('_lembas/complete', params));
|
||||
@@ -155,4 +197,4 @@ class Completer {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { Completer, windowAround, REFUSALS };
|
||||
module.exports = { Completer, windowAround, resolvePrediction, LENGTH_PRESETS, REFUSALS };
|
||||
+101
-5
@@ -5,8 +5,9 @@
|
||||
// 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: 'quote', c: blocks } { t: 'ul' | 'ol', items: [{ d, checked?, c }] }
|
||||
// { t: 'table', align: string[], head: Inline[][], rows: Inline[][][] } { t: 'plain', v }
|
||||
// Inline: { t: 'text', v } { t: 'code', v } { t: 'b', c } { t: 'i', c } { t: 'del', c }
|
||||
// { t: 'a', href, c } { t: 'br' }
|
||||
|
||||
const MAX_DEPTH = 6;
|
||||
@@ -19,6 +20,7 @@ const MAX_CHARS = 400000;
|
||||
const MAX_LINE = 4000;
|
||||
const BUDGET = 400000;
|
||||
const LABEL_MAX = 1000;
|
||||
const MAX_TABLE_COLS = 24;
|
||||
|
||||
/** A link the chat may offer to open: http, https or mailto, and nothing else. */
|
||||
function safeHref(url) {
|
||||
@@ -114,6 +116,20 @@ function parseInline(s, depth, budget) {
|
||||
i += n;
|
||||
continue;
|
||||
}
|
||||
if (!deep && ch === '~' && s[i + 1] === '~') {
|
||||
const next = s[i + 2];
|
||||
if (next !== undefined && !/\s/.test(next)) {
|
||||
const close = findClosing(s, i + 2, '~~', work);
|
||||
if (close > 0) {
|
||||
out.push({ t: 'del', c: parseInline(s.slice(i + 2, close), (depth || 0) + 1, work) });
|
||||
i = close + 2;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
pushText(out, '~~');
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (!deep && (ch === '*' || ch === '_')) {
|
||||
const double = s[i + 1] === ch;
|
||||
const marker = double ? ch + ch : ch;
|
||||
@@ -199,7 +215,50 @@ 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 TASK = /^\[([ xX])\]\s+(.*)$/;
|
||||
const QUOTE = /^ {0,3}>\s?(.*)$/;
|
||||
const TABLE_SEP_CELL = /^:?-{1,}:?$/;
|
||||
|
||||
function splitTableCells(line) {
|
||||
let s = line.trim();
|
||||
if (s.startsWith('|')) s = s.slice(1);
|
||||
if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1);
|
||||
const cells = [];
|
||||
let cur = '';
|
||||
let inCode = false;
|
||||
for (let i = 0; i < s.length; i++) {
|
||||
const ch = s[i];
|
||||
if (ch === '\\' && i + 1 < s.length && s[i + 1] === '|') {
|
||||
cur += '|';
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '`') inCode = !inCode;
|
||||
if (ch === '|' && !inCode) {
|
||||
cells.push(cur.trim());
|
||||
cur = '';
|
||||
if (cells.length >= MAX_TABLE_COLS) break;
|
||||
continue;
|
||||
}
|
||||
cur += ch;
|
||||
}
|
||||
if (cells.length < MAX_TABLE_COLS) cells.push(cur.trim());
|
||||
return cells;
|
||||
}
|
||||
|
||||
function parseTableAlign(line) {
|
||||
if (!line || line.length > MAX_LINE || !line.includes('|')) return null;
|
||||
const cells = splitTableCells(line);
|
||||
if (!cells.length) return null;
|
||||
const align = [];
|
||||
for (const c of cells) {
|
||||
if (!TABLE_SEP_CELL.test(c)) return null;
|
||||
const left = c.startsWith(':');
|
||||
const right = c.endsWith(':');
|
||||
align.push(left && right ? 'center' : right ? 'right' : left ? 'left' : '');
|
||||
}
|
||||
return align;
|
||||
}
|
||||
|
||||
/** A heading's text without the closing run of # some write after it. */
|
||||
function headingText(text) {
|
||||
@@ -286,8 +345,29 @@ function read(src, depth, budget) {
|
||||
i = j - 1;
|
||||
continue;
|
||||
}
|
||||
if (line.includes('|') && i + 1 < lines.length) {
|
||||
const align = parseTableAlign(lines[i + 1]);
|
||||
if (align) {
|
||||
const headRaw = splitTableCells(line);
|
||||
if (headRaw.length === align.length) {
|
||||
flush();
|
||||
const cols = align.length;
|
||||
const head = headRaw.map((c) => parseInline(c, 0, work));
|
||||
const rows = [];
|
||||
let j = i + 2;
|
||||
for (; j < lines.length && lines[j].length <= MAX_LINE && lines[j].trim() !== '' && lines[j].includes('|'); j++) {
|
||||
const cells = splitTableCells(lines[j]);
|
||||
while (cells.length < cols) cells.push('');
|
||||
rows.push(cells.slice(0, cols).map((c) => parseInline(c, 0, work)));
|
||||
}
|
||||
blocks.push({ t: 'table', align, head, rows });
|
||||
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.
|
||||
// Pipe lines without a valid separator row stay in a fixed-width block.
|
||||
flush();
|
||||
const body = [];
|
||||
let j = i;
|
||||
@@ -307,14 +387,30 @@ function read(src, depth, budget) {
|
||||
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]] });
|
||||
let bodyText = m[3];
|
||||
let checked = null;
|
||||
if (!ordered) {
|
||||
const tm = TASK.exec(bodyText);
|
||||
if (tm) {
|
||||
checked = tm[1].toLowerCase() === 'x';
|
||||
bodyText = tm[2];
|
||||
}
|
||||
}
|
||||
items.push({ d, checked, text: [bodyText] });
|
||||
} 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) })) });
|
||||
blocks.push({
|
||||
t: ordered ? 'ol' : 'ul',
|
||||
items: items.map((it) => {
|
||||
const node = { d: it.d, c: parseInline(it.text.join('\n'), 0, work) };
|
||||
if (it.checked !== null) node.checked = it.checked;
|
||||
return node;
|
||||
}),
|
||||
});
|
||||
i = j - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
+96
-19
@@ -4,7 +4,7 @@
|
||||
// with `textContent`. No `vscode` here.
|
||||
|
||||
/**
|
||||
* @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string }} o
|
||||
* @param {{ cspSource: string, nonce: string, scriptUri: string, styleUri: string, logoUri?: string }} o
|
||||
*/
|
||||
function chatHtml(o) {
|
||||
// VS Code / VSCodium's `webview.cspSource` may list multiple space-separated origins
|
||||
@@ -12,7 +12,9 @@ function chatHtml(o) {
|
||||
if (typeof o.cspSource !== 'string' || !o.cspSource.trim() || /["<>;\r\n]/.test(o.cspSource)) {
|
||||
throw new Error('unsafe cspSource for the chat page');
|
||||
}
|
||||
for (const v of [o.nonce, o.scriptUri, o.styleUri]) {
|
||||
const uris = [o.nonce, o.scriptUri, o.styleUri];
|
||||
if (o.logoUri !== undefined && o.logoUri !== '') uris.push(o.logoUri);
|
||||
for (const v of uris) {
|
||||
if (typeof v !== 'string' || !v || /["<>\s]/.test(v)) throw new Error('unsafe value for the chat page');
|
||||
}
|
||||
const csp = [
|
||||
@@ -23,6 +25,8 @@ function chatHtml(o) {
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
].join('; ');
|
||||
const brandImg = o.logoUri ? `<img class="brand-logo" src="${o.logoUri}" alt="" width="18" height="18">` : '';
|
||||
const heroImg = o.logoUri ? `<img class="hero-logo" src="${o.logoUri}" alt="LLeMbas IDE" width="44" height="44">` : '';
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
@@ -33,28 +37,101 @@ function chatHtml(o) {
|
||||
<title>LLeMbas</title>
|
||||
</head>
|
||||
<body>
|
||||
<div class="chrome">
|
||||
<header class="bar">
|
||||
<select id="mode" title="Mode (can be changed mid-turn)" aria-label="Mode"></select>
|
||||
<select id="model" title="This session's model" aria-label="Model"></select>
|
||||
<button id="sessions" type="button" class="second" title="Resume a previous session">History</button>
|
||||
<button id="new" type="button" title="Start a new session">New</button>
|
||||
<div class="bar-top">
|
||||
<div class="brand">
|
||||
${brandImg}
|
||||
<span id="conn-dot" class="dot" title="Agent status" aria-hidden="true"></span>
|
||||
<span id="session-title" class="brand-title">LLeMbas</span>
|
||||
</div>
|
||||
<div class="bar-btns">
|
||||
<button id="compact" type="button" class="second icon-btn" title="Compact session context" hidden>Compact</button>
|
||||
<button id="settings-toggle" type="button" class="second icon-btn" title="Autocomplete length, tokens & instructions" aria-expanded="false">Tune</button>
|
||||
<button id="sessions" type="button" class="second icon-btn" title="Resume a previous session">History</button>
|
||||
<button id="new" type="button" class="icon-btn" title="Start a new session">New</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="bar-controls">
|
||||
<div class="select-wrap">
|
||||
<span id="mode-dot" class="dot mode-dot" aria-hidden="true"></span>
|
||||
<select id="mode" title="Mode (can be changed mid-turn)" aria-label="Mode"></select>
|
||||
</div>
|
||||
<select id="model" title="This session's model" aria-label="Model"></select>
|
||||
</div>
|
||||
</header>
|
||||
<main id="log" aria-live="polite"></main>
|
||||
<section id="settings-panel" class="settings-panel" hidden aria-label="Autocomplete settings">
|
||||
<div class="sp-row">
|
||||
<label class="sp-label" for="ac-tokens">Autocomplete max tokens</label>
|
||||
<span id="ac-tokens-val" class="sp-val">Default</span>
|
||||
</div>
|
||||
<input id="ac-tokens" class="sp-slider" type="range" min="0" max="4096" step="16" value="0" aria-label="Autocomplete maximum tokens">
|
||||
<div class="sp-presets">
|
||||
<button type="button" class="mini preset-btn" data-length="auto" data-tokens="0">Default</button>
|
||||
<button type="button" class="mini preset-btn" data-length="words" data-tokens="24">Words</button>
|
||||
<button type="button" class="mini preset-btn" data-length="line" data-tokens="64">Line</button>
|
||||
<button type="button" class="mini preset-btn" data-length="block" data-tokens="256">Block</button>
|
||||
<button type="button" class="mini preset-btn" data-length="file" data-tokens="2048">File</button>
|
||||
</div>
|
||||
<div class="sp-grid">
|
||||
<label class="sp-label" for="ac-length">Prediction scope</label>
|
||||
<select id="ac-length" aria-label="Autocomplete prediction scope">
|
||||
<option value="auto">Auto (server default)</option>
|
||||
<option value="words">Few words</option>
|
||||
<option value="line">Single line</option>
|
||||
<option value="block">Function / block</option>
|
||||
<option value="file">Large / full file</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="sp-field">
|
||||
<label class="sp-label" for="ac-instructions">Autocomplete instructions</label>
|
||||
<input id="ac-instructions" class="q-input" type="text" placeholder="Optional guidance (e.g. concise idiomatic code, no comments)">
|
||||
</div>
|
||||
<div class="sp-checks">
|
||||
<label class="sp-check"><input id="ac-auto" type="checkbox"> Suggest as you type</label>
|
||||
<label class="sp-check"><input id="chat-thinking" type="checkbox"> Show thinking</label>
|
||||
</div>
|
||||
</section>
|
||||
<div id="team-bar" class="team-bar" hidden aria-live="polite"></div>
|
||||
</div>
|
||||
<main id="log" aria-live="polite">
|
||||
<section id="empty" class="empty">
|
||||
<div class="hero">
|
||||
${heroImg}
|
||||
<div class="hero-title">LLeMbas</div>
|
||||
<div class="hero-sub">Waybread for the code ahead.</div>
|
||||
</div>
|
||||
<div class="starter-grid">
|
||||
<button type="button" class="starter" data-action="explain">Explain selection</button>
|
||||
<button type="button" class="starter" data-action="fix">Fix file problems</button>
|
||||
<button type="button" class="starter" data-action="addFile">Add @file</button>
|
||||
<button type="button" class="starter" data-action="sessions">Resume session</button>
|
||||
</div>
|
||||
<div class="hero-hints">
|
||||
<span class="hint-pill">@file</span>
|
||||
<span class="hint-pill">/command</span>
|
||||
<span class="hint-pill">Alt+\ complete</span>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<footer>
|
||||
<div id="popup" class="popup" hidden role="listbox" aria-label="Suggestions"></div>
|
||||
<textarea id="prompt" rows="3" placeholder="Ask LLeMbas (@file, /command, Enter sends, Shift+Enter newline)" aria-label="Message"></textarea>
|
||||
<div class="send">
|
||||
<div class="left-controls">
|
||||
<button id="add-file" type="button" class="second" title="Add a file from the project index (@file)">@ File</button>
|
||||
<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 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>
|
||||
<div class="composer">
|
||||
<textarea id="prompt" rows="3" placeholder="Ask LLeMbas (@file, /command, Enter sends, Shift+Enter newline)" aria-label="Message"></textarea>
|
||||
<div class="send">
|
||||
<div class="left-controls">
|
||||
<button id="add-file" type="button" class="second" title="Add a file from the project index (@file)">@ File</button>
|
||||
<span id="working" class="working" hidden><span class="pulse-dot" aria-hidden="true"></span><span id="working-text">Working…</span></span>
|
||||
<span id="usage" class="usage" hidden></span>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<button id="stop" type="button" class="second" hidden>Stop</button>
|
||||
<button id="send" type="button">Send</button>
|
||||
</div>
|
||||
</div>
|
||||
<span id="working" class="working" hidden>Working…</span>
|
||||
<div class="actions">
|
||||
<button id="stop" type="button" class="second" hidden>Stop</button>
|
||||
<button id="send" type="button">Send</button>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -440,3 +440,36 @@ test('a text file the agent shows goes to the hook that opens it', async (t) =>
|
||||
assert.equal(opened[0].text, '<script>alert(1)</script>');
|
||||
assert.match(text(chat), /> Shown: page\.html/);
|
||||
});
|
||||
|
||||
test('real CLI shapes: files/search objects, historyTurns resume, question Answer[], plan dismissed, and compact', async (t) => {
|
||||
const { chat } = fakeChat(t);
|
||||
const files = await chat.searchFiles('src');
|
||||
assert.deepEqual(files, [
|
||||
{ path: 'src/app.py', kind: 'file' },
|
||||
{ path: 'src/utils.py', kind: 'file' },
|
||||
{ path: 'src', kind: 'dir' },
|
||||
]);
|
||||
|
||||
assert.equal(await chat.resumeSession('ses_prev'), true);
|
||||
assert.equal(chat.title, 'Earlier work');
|
||||
assert.ok(chat.items.some((i) => i.kind === 'user' && i.text === 'earlier question'));
|
||||
assert.ok(chat.items.some((i) => i.kind === 'tool' && i.title === 'read' && i.output === 'ok'));
|
||||
assert.ok(chat.items.some((i) => i.kind === 'agent' && i.text === 'earlier answer'));
|
||||
|
||||
const qTurn = chat.send('QUESTION');
|
||||
await until(() => chat.questions.size === 1);
|
||||
const qItem = chat.items.find((i) => i.kind === 'question');
|
||||
chat.answerQuestion(qItem.id, [{ kind: 'options', labels: ['SQLite'] }]);
|
||||
await qTurn;
|
||||
assert.match(text(chat), /"kind": "options".*"SQLite"/);
|
||||
|
||||
const pTurn = chat.send('PLANCARD');
|
||||
await until(() => chat.planCards.size === 1);
|
||||
const pItem = chat.items.find((i) => i.kind === 'plancard');
|
||||
chat.answerPlan(pItem.id, 'dismissed');
|
||||
await pTurn;
|
||||
assert.match(text(chat), /"outcome": "dismissed"/);
|
||||
|
||||
assert.equal(await chat.compact(), true);
|
||||
assert.match(text(chat), /> Session compacted: Compacted 2 turns\./);
|
||||
});
|
||||
@@ -271,3 +271,31 @@ test('agent: a model not allowed for autocomplete is a refusal of its own', asyn
|
||||
assert.equal(await completer.ask({ prefix: 'a' }), null);
|
||||
assert.equal(refusals[0].reason, 'not_allowed');
|
||||
});
|
||||
|
||||
test('prediction tokens slider, length presets and custom instructions flow into _lembas/complete', async () => {
|
||||
const { resolvePrediction } = require('../src/completion');
|
||||
assert.deepEqual(resolvePrediction({ length: 'auto', maxTokens: 0, instructions: '' }), { mode: 'auto', maxTokens: undefined, guidance: '' });
|
||||
const words = resolvePrediction({ length: 'words' });
|
||||
assert.equal(words.maxTokens, 24);
|
||||
assert.match(words.guidance, /few words/i);
|
||||
const fileOverride = resolvePrediction({ length: 'file', maxTokens: 1536, instructions: 'Use TypeScript types' });
|
||||
assert.equal(fileOverride.maxTokens, 1536);
|
||||
assert.match(fileOverride.guidance, /comprehensive continuation/i);
|
||||
assert.match(fileOverride.guidance, /Use TypeScript types/);
|
||||
|
||||
const sent = [];
|
||||
const c = new Completer({
|
||||
request: (method, params) => {
|
||||
sent.push({ method, params });
|
||||
return Promise.resolve({ text: 'ok' });
|
||||
},
|
||||
notify: () => {},
|
||||
maxTokens: () => 512,
|
||||
length: () => 'block',
|
||||
instructions: () => 'Keep code concise',
|
||||
});
|
||||
assert.equal(await c.ask({ prefix: 'function f() {' }, { manual: true }), 'ok');
|
||||
assert.equal(sent[0].params.max_tokens, 512);
|
||||
assert.equal(sent[0].params.context[0].path, 'llembas:autocomplete-instructions');
|
||||
assert.match(sent[0].params.context[0].text, /Keep code concise/);
|
||||
});
|
||||
@@ -70,7 +70,7 @@ test('activation registers the view, every command of the manifest, the provider
|
||||
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].text, '$(sparkle) LLeMbas');
|
||||
assert.equal(s.statusItems[0].command, 'llembas.modelSettings');
|
||||
assert.equal(view.webview.options.enableScripts, true);
|
||||
assert.equal(view.webview.options.enableCommandUris, false);
|
||||
@@ -79,7 +79,11 @@ test('activation registers the view, every command of the manifest, the provider
|
||||
assert.deepEqual(view.posted[0], {
|
||||
type: 'reset',
|
||||
items: [],
|
||||
state: { busy: false, session: false, mode: null, modes: [], model: null, models: [], progress: '', canSteer: false, commands: [] },
|
||||
state: {
|
||||
busy: false, connected: false, session: false, title: '', mode: null, modes: [], model: null, models: [],
|
||||
progress: '', usage: null, team: null, canSteer: false, canCompact: false, commands: [],
|
||||
},
|
||||
settings: { auto: true, maxTokens: 0, length: 'auto', instructions: '', showThinking: false },
|
||||
attached: '',
|
||||
});
|
||||
});
|
||||
@@ -316,7 +320,7 @@ test('autocomplete without a model: said once with a button, quiet until one is
|
||||
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');
|
||||
await until(() => s.statusItems[0].text === '$(sparkle) LLeMbas: model-b');
|
||||
assert.match(s.statusItems[0].tooltip, /example\/model-b \(this window only\)/);
|
||||
assert.equal(s.messages.length, 1);
|
||||
|
||||
@@ -354,7 +358,7 @@ test('the two model settings: read, and saved in the account through the agent',
|
||||
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');
|
||||
assert.equal(s.statusItems[0].text, '$(sparkle) LLeMbas: model-b');
|
||||
|
||||
s.picks.push((items) => items[items.length - 1]);
|
||||
await run('llembas.chooseAutocompleteModel');
|
||||
@@ -651,44 +655,71 @@ test('a command that is not installed is said in the chat, and autocomplete stay
|
||||
});
|
||||
|
||||
test('full agentic features: question & plan cards, session resume, @file search, open file:line, and mid-run steer', async (t) => {
|
||||
const { view, sent, run, items, state, idle, dir, s } = host(t);
|
||||
const { vscode, view, sent, run, items, state, idle, dir, s } = host(t);
|
||||
fs.writeFileSync(path.join(dir, 'README.md'), 'line 1\nline 2\nline 3\n');
|
||||
|
||||
// 1. Question card
|
||||
// 1. Question card (real CLI Answer[] shape)
|
||||
view.say({ type: 'send', text: 'QUESTION' });
|
||||
await until(() => items().some((i) => i.kind === 'question' && i.state === 'open'));
|
||||
const qCard = items().find((i) => i.kind === 'question');
|
||||
view.say({ type: 'answerQuestion', card: qCard.id, answers: [['SQLite']] });
|
||||
view.say({ type: 'answerQuestion', card: qCard.id, answers: [{ kind: 'options', labels: ['SQLite'] }] });
|
||||
await idle();
|
||||
const qReply = items().filter((i) => i.kind === 'agent').pop();
|
||||
assert.ok(JSON.stringify(qReply.ast).includes('SQLite'));
|
||||
assert.ok(JSON.stringify(qReply.ast).includes('options'));
|
||||
|
||||
// 2. Plan approval card
|
||||
// 2. Plan approval card (rendered as safe Markdown AST)
|
||||
view.say({ type: 'send', text: 'PLANCARD' });
|
||||
await until(() => items().some((i) => i.kind === 'plancard' && i.state === 'open'));
|
||||
const pCard = items().find((i) => i.kind === 'plancard');
|
||||
assert.ok(Array.isArray(pCard.ast) && pCard.ast.length > 0);
|
||||
view.say({ type: 'answerPlan', card: pCard.id, outcome: 'approve', value: 'edit' });
|
||||
await idle();
|
||||
const pReply = items().filter((i) => i.kind === 'agent').pop();
|
||||
assert.ok(JSON.stringify(pReply.ast).includes('approve'));
|
||||
|
||||
// 3. @file index search & bringing up a specific file at a line
|
||||
// 3. @file index search ({ path, kind } real CLI shape) & bringing up a specific file at a line
|
||||
view.say({ type: 'searchFiles', query: 'app', seq: 7 });
|
||||
await until(() => view.posted.some((m) => m.type === 'files' && m.seq === 7));
|
||||
const found = view.posted.find((m) => m.type === 'files' && m.seq === 7);
|
||||
assert.deepEqual(found.files, ['src/app.py']);
|
||||
assert.deepEqual(found.files, [{ path: 'src/app.py', kind: 'file' }]);
|
||||
|
||||
view.say({ type: 'openFile', path: 'README.md', line: 2, soft: true });
|
||||
await until(() => s.executed.some((e) => e[0] === 'showTextDocument'));
|
||||
|
||||
// 4. Session resume replays history
|
||||
// 4. Session resume replays history (real CLI role-based historyTurns)
|
||||
s.picks.push((list) => list.find((x) => x.id === 'ses_prev'));
|
||||
await run('llembas.resumeSession');
|
||||
assert.equal(state().mode, 'edit');
|
||||
assert.equal(state().title, 'Earlier work');
|
||||
assert.ok(items().some((i) => i.kind === 'user' && i.text === 'earlier question'));
|
||||
assert.ok(items().some((i) => i.kind === 'agent'));
|
||||
|
||||
// 5. Mid-run steer & live mode switch while busy
|
||||
// 5. Compact session & webview settings drawer (autocomplete tokens slider + length + instructions)
|
||||
await run('llembas.compact');
|
||||
await until(() => items().some((i) => i.kind === 'note' && i.text.includes('Compacted 2 turns')));
|
||||
|
||||
view.say({ type: 'updateSettings', settings: { maxTokens: 512, length: 'block', instructions: 'Use strict types' } });
|
||||
await until(() => s.config['llembas.complete.maxTokens'] === 512);
|
||||
assert.equal(s.config['llembas.complete.length'], 'block');
|
||||
assert.equal(s.config['llembas.complete.instructions'], 'Use strict types');
|
||||
|
||||
// Verify updated tokens + instructions actually go out on _lembas/complete
|
||||
s.config['llembas.complete.debounce'] = 5;
|
||||
const ed = vscode.__.open(path.join(dir, 'tune.py'), 'def f():\n ', new vscode.Selection(1, 4, 1, 4), 'python');
|
||||
await s.inlineProviders[0].provideInlineCompletionItems(ed.document, new vscode.Position(1, 4), { triggerKind: 0 }, { isCancellationRequested: false, onCancellationRequested: () => ({ dispose() {} }) });
|
||||
const compCall = sent().filter((m) => m.method === '_lembas/complete').pop();
|
||||
assert.equal(compCall.params.max_tokens, 512);
|
||||
assert.equal(compCall.params.context[0].path, 'llembas:autocomplete-instructions');
|
||||
assert.match(compCall.params.context[0].text, /Use strict types/);
|
||||
|
||||
// 6. Toggle autocomplete & copyCode
|
||||
await run('llembas.toggleAutocomplete');
|
||||
assert.equal(s.config['llembas.complete.auto'], false);
|
||||
view.say({ type: 'copyCode', text: 'const x = 1;' });
|
||||
await until(() => s.copied === 'const x = 1;');
|
||||
|
||||
// 7. Mid-run steer & live mode switch while busy
|
||||
view.say({ type: 'send', text: 'SLOW' });
|
||||
await until(() => state().busy === true);
|
||||
view.say({ type: 'steer', text: 'focus on tests' });
|
||||
|
||||
@@ -327,7 +327,7 @@ def main():
|
||||
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", "files", "commands", "steer", "sessions", "ask", "plan"]}}
|
||||
"capabilities": ["configure", "show", "editor", "media", "files", "commands", "steer", "sessions", "ask", "plan", "compact"]}}
|
||||
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")
|
||||
@@ -374,20 +374,31 @@ def main():
|
||||
pass
|
||||
elif method == "_lembas/files/search":
|
||||
q = str((msg.get("params") or {}).get("query") or "").lower()
|
||||
sample = ["src/app.py", "src/utils.py", "README.md"]
|
||||
result(msg, {"files": [f for f in sample if not q or q in f.lower()]})
|
||||
sample = [
|
||||
{"path": "src/app.py", "kind": "file"},
|
||||
{"path": "src/utils.py", "kind": "file"},
|
||||
{"path": "src", "kind": "dir"},
|
||||
{"path": "README.md", "kind": "file"},
|
||||
]
|
||||
result(msg, {"root": os.getcwd(), "files": [f for f in sample if not q or q in f["path"].lower()]})
|
||||
elif method == "_lembas/commands":
|
||||
result(msg, {"commands": [{"name": "compact", "description": "Compact context", "source": "builtin"}]})
|
||||
result(msg, {"commands": [{"name": "compact", "description": "Compact context", "_meta": {"lembas": {"kind": "builtin"}}}]})
|
||||
elif method == "_lembas/session/compact":
|
||||
result(msg, {"summary": "Compacted 2 turns."})
|
||||
elif method == "_lembas/steer":
|
||||
result(msg, {"queued": True})
|
||||
result(msg, {"queued": 1})
|
||||
elif method == "_lembas/sessions/list":
|
||||
result(msg, {"sessions": [{"id": "ses_prev", "title": "Earlier work", "model": "example/model-a", "updated": 1700000000000}]})
|
||||
elif method == "_lembas/sessions/resume":
|
||||
sid = (msg.get("params") or {}).get("sessionId") or "ses_prev"
|
||||
result(msg, {
|
||||
"sessionId": sid,
|
||||
"title": "Earlier work",
|
||||
"modes": {"currentModeId": "edit", "availableModes": [{"id": "ask", "name": "Ask"}, {"id": "edit", "name": "Edit"}]},
|
||||
"turns": [{"user": "earlier question", "assistant": "earlier answer", "tools": []}],
|
||||
"turns": [
|
||||
{"role": "user", "text": "earlier question"},
|
||||
{"role": "assistant", "text": "earlier answer", "reasoning": "", "tools": [{"id": "t1", "name": "read", "args": "{}", "output": "ok"}]},
|
||||
],
|
||||
"_meta": {"lembas": {"model": session_model[0], "mode": "edit"}},
|
||||
})
|
||||
elif "id" in msg:
|
||||
|
||||
@@ -55,7 +55,7 @@ function render(src) {
|
||||
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']);
|
||||
const ALLOWED = new Set(['#text', 'div', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'code', 'hr', 'blockquote', 'ul', 'ol', 'li', 'strong', 'em', 'del', 'span', 'br', 'table', 'thead', 'tbody', 'tr', 'th', 'td']);
|
||||
|
||||
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"))');
|
||||
@@ -81,8 +81,39 @@ test('a fenced block is text as written, and one still being written is a block
|
||||
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('a GFM table is rendered as a table inside a scrollable wrapper, with alignment and inline formatting', () => {
|
||||
assert.equal(render('| a | b |\n|---|---|\n| 1 | 2 |').show(), 'div(div(table(thead(tr(th("a") th("b"))) tbody(tr(td("1") td("2"))))))');
|
||||
const aligned = render('| Left | Mid | Right |\n|:---|:---:|---:|\n| **x** | `y` | ~~z~~ |');
|
||||
const ths = aligned.all().filter((n) => n.tag === 'th');
|
||||
assert.deepEqual(ths.map((n) => n.className), ['align-left', 'align-center', 'align-right']);
|
||||
assert.ok(aligned.all().some((n) => n.tag === 'strong' && n.textContent === 'x'));
|
||||
assert.ok(aligned.all().some((n) => n.tag === 'del' && n.textContent === 'z'));
|
||||
// Pipe lines without a separator row fall back to a preformatted block.
|
||||
assert.equal(render('| just | pipes |').show(), 'div(pre(code("| just | pipes |")))');
|
||||
});
|
||||
|
||||
test('task list checkboxes and strikethrough inline markup', () => {
|
||||
const out = render('- [x] done\n- [ ] todo\n\n~~old~~ text');
|
||||
const lis = out.all().filter((n) => n.tag === 'li');
|
||||
assert.equal(lis.length, 2);
|
||||
assert.ok(lis[0].className.includes('checked'));
|
||||
assert.ok(lis[0].textContent.includes('done'));
|
||||
assert.ok(!lis[1].className.includes('checked'));
|
||||
assert.ok(out.all().some((n) => n.tag === 'del' && n.textContent === 'old'));
|
||||
});
|
||||
|
||||
test('fenced code block with post handler renders copy and insert toolbar buttons', () => {
|
||||
const posted = [];
|
||||
const root = new Node('div');
|
||||
page.buildBlocks(doc, parse('```python\nprint(1)\n```'), root, 0, (m) => posted.push(m));
|
||||
const buttons = root.all().filter((n) => n.tag === 'button');
|
||||
assert.deepEqual(buttons.map((b) => b.textContent), ['Copy', 'Insert']);
|
||||
buttons[0].listeners.click();
|
||||
buttons[1].listeners.click();
|
||||
assert.deepEqual(posted, [
|
||||
{ type: 'copyCode', text: 'print(1)' },
|
||||
{ type: 'insertCode', text: 'print(1)' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('markup a model writes is text, never elements', () => {
|
||||
@@ -296,6 +327,12 @@ test('the page: a strict policy, one script with a nonce, nothing from elsewhere
|
||||
});
|
||||
assert.ok(multi.includes('style-src vscode-resource: https://file+.vscode-resource.vscode-cdn.net;'));
|
||||
assert.throws(() => chatHtml({ cspSource: "https://a.example; script-src 'unsafe-inline'", nonce: 'abc', scriptUri: 's', styleUri: 't' }));
|
||||
// Layout invariant: body has exactly 3 visible top-level grid children (.chrome, #log, footer)
|
||||
// so hiding collapsible drawers inside .chrome never shifts #log or footer off their grid tracks.
|
||||
const body = /<body>([\s\S]*)<\/body>/.exec(html)[1];
|
||||
assert.match(body, /^\s*<div class="chrome">[\s\S]*<\/div>\s*<main id="log"[\s\S]*<\/main>\s*<footer>[\s\S]*<\/footer>\s*<script\b/);
|
||||
const css = fs.readFileSync(path.join(__dirname, '..', 'media', 'chat.css'), 'utf8');
|
||||
assert.match(css, /grid-template-rows:\s*auto minmax\(0,\s*1fr\) auto;/);
|
||||
});
|
||||
|
||||
test('the stylesheet takes every colour from the editor\'s theme', () => {
|
||||
@@ -303,7 +340,7 @@ test('the stylesheet takes every colour from the editor\'s theme', () => {
|
||||
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)) {
|
||||
for (const m of css.matchAll(/(?:^|[;{\s])(color|background|background-color|border(?:-(?!collapse|spacing|radius|style|width)[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();
|
||||
|
||||
@@ -233,6 +233,7 @@ function make(pkg) {
|
||||
ViewColumn: { Beside: -2 },
|
||||
InlineCompletionTriggerKind: { Invoke: 0, Automatic: 1 },
|
||||
DiagnosticSeverity: { Error: 0, Warning: 1, Information: 2, Hint: 3 },
|
||||
ConfigurationTarget: { Global: 1, Workspace: 2, WorkspaceFolder: 3 },
|
||||
workspace: {
|
||||
workspaceFolders: undefined,
|
||||
textDocuments: [],
|
||||
@@ -242,6 +243,11 @@ function make(pkg) {
|
||||
if (!(full in defaults)) throw new Error('a setting that is not declared: ' + full);
|
||||
return full in state.config ? state.config[full] : defaults[full];
|
||||
},
|
||||
update: async (key, value) => {
|
||||
const full = `${section}.${key}`;
|
||||
if (!(full in defaults)) throw new Error('a setting that is not declared: ' + full);
|
||||
state.config[full] = value;
|
||||
},
|
||||
}),
|
||||
registerTextDocumentContentProvider: (scheme, provider) => {
|
||||
state.contentProviders.set(scheme, provider);
|
||||
@@ -351,6 +357,11 @@ function make(pkg) {
|
||||
getDiagnostics: (uri) => state.diagnostics.get(uri.toString()) || [],
|
||||
},
|
||||
env: {
|
||||
clipboard: {
|
||||
writeText: async (text) => {
|
||||
state.copied = text;
|
||||
},
|
||||
},
|
||||
openExternal: async (uri) => {
|
||||
state.external.push(uri.toString());
|
||||
return true;
|
||||
|
||||
Reference in new issue
Block a user