feat(neovim): let pivi run commands, name files, and reach pi capabilities
0634d896386563498c8ee4250e34d872f8e70c71
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
- Parent 1: 19e84617e2bd
bugabingas dorkfiles
0634d896386563498c8ee4250e34d872f8e70c71
Oliver Krylow <o.krylow@isp-insoft.de> ·
SSH signature · not checked
+743 / −9 text lines
+9 / −1 text lines
29. **A picker filters the text it is shown.** Formatting an item as `name description` makes every description compete with the name; show the name alone.30. **Contract tests guard assumptions,** not features. They skip unless `pi` is on `PATH` and opt-in is set. When Pi changes behavior, they fail before users do.30. **A written prompt is not always a prompt.** `bugabinga.pivi.compose` decides: a leading bang is a shell command through pi's `bash`, which accepts `excludeFromContext` even though `rpc.md` does not document it, and `@name` is expanded client-side because pi has no server-side `@` over this channel. Expansion reuses `edit.read`, so a named file is sent as its buffer content when it is open and unsaved; anything else would contradict every other pivi read. The wire shape is pi's own: `<file name="ABSOLUTE">content</file>`, images as `images[]`.31. **A local in Lua is not visible before its declaration.** Two functions have now been used above their definition and resolved to `nil` at runtime; if a helper is called from an earlier function, define it earlier.32. **Contract tests guard assumptions,** not features. They skip unless `pi` is on `PATH` and opt-in is set. When Pi changes behavior, they fail before users do.+261 / −0 text lines
local compose = require 'bugabinga.pivi.compose'--- What `@` can refer to: what is open first, then what is nearby.--- A buffer is what the user is actually looking at, so it outranks a path--- that merely exists.local references = function( cwd ) local found, seen = {}, {} for _, bufnr in ipairs( vim.api.nvim_list_bufs() ) do if vim.api.nvim_buf_is_loaded( bufnr ) and vim.bo[bufnr].buftype == '' then local name = vim.api.nvim_buf_get_name( bufnr ) if name ~= '' then local shown = vim.fn.fnamemodify( name, ':.' ) if not seen[shown] then seen[shown] = true table.insert( found, { path = shown, open = true, modified = vim.bo[bufnr].modified, } ) end end end end local ok, listed = pcall( vim.fn.systemlist, { 'git', '-C', cwd, 'ls-files', } ) if ok and vim.v.shell_error == 0 then for _, path in ipairs( listed ) do if not seen[path] then seen[path] = true table.insert( found, { path = path, open = false, } ) end end end return foundendlocal pick_reference = function( current, on_pick ) local choices = references( current.cwd or vim.uv.cwd() ) if #choices == 0 then notify( 'nothing to refer to', vim.log.levels.WARN ) return end vim.ui.select( choices, { prompt = 'refer to', format_item = function( choice ) return choice.path end, }, function( choice ) if choice then on_pick( choice.path ) end end )end -- `@` names a file, as it does in pi itself. It only takes over when it -- starts a word, so an address or a decorator can still be typed. vim.keymap.set( 'i', '@', function() local line = vim.api.nvim_get_current_line() local column = vim.api.nvim_win_get_cursor( 0 )[2] local before = column > 0 and line:sub( column, column ) or '' if before ~= '' and not before:match '%s' then return '@' end vim.schedule( function() pick_reference( current, function( path ) vim.api.nvim_put( { '@' .. path .. ' ', }, 'c', true, true ) vim.cmd.startinsert { bang = true, } end ) end ) return '' end, { buffer = bufnr, expr = true, desc = 'pivi refer to a file', } )--- Runs a shell command through pi, so its output joins the conversation.subcommands.bang = function( arguments ) local current = require_session() if not current then return end if arguments == '' then notify( 'bang needs a command', vim.log.levels.WARN ) return end local accepted, rejection = current.bash( arguments, false ) if not accepted then notify( rejection, vim.log.levels.WARN ) return end transcript.show( current.buffer )end--- The same, kept out of the conversation.subcommands['bang!'] = function( arguments ) local current = require_session() if not current then return end if arguments == '' then notify( 'bang needs a command', vim.log.levels.WARN ) return end local accepted, rejection = current.bash( arguments, true ) if not accepted then notify( rejection, vim.log.levels.WARN ) return end transcript.show( current.buffer )end--- Switches thinking level, the other capability `/thinking` cannot reach here.subcommands.thinking = function( arguments ) local current = require_session() if not current then return end current.request( { type = 'get_available_thinking_levels', }, function( response ) local levels = response.success and response.data and response.data.levels or {} if #levels == 0 then notify( 'this model offers no thinking levels', vim.log.levels.WARN ) return end local choose = function( level ) current.request( { type = 'set_thinking_level', level = level, }, function( answer ) if answer.success then notify( 'thinking ' .. level ) else notify( answer.error or 'pi refused the level', vim.log.levels.ERROR ) end end ) end if arguments ~= '' then if vim.list_contains( levels, arguments ) then choose( arguments ) else notify( 'no such level: ' .. arguments, vim.log.levels.WARN ) end return end vim.ui.select( levels, { prompt = 'thinking', }, function( level ) if level then choose( level ) end end ) end )end--- Compacts the conversation, optionally saying what to keep.subcommands.compact = function( arguments ) local current = require_session() if not current then return end local request = { type = 'compact', } if arguments ~= '' then request.customInstructions = arguments end notify 'compacting' current.request( request, function( response ) if not response.success then notify( response.error or 'compaction failed', vim.log.levels.ERROR ) return end local data = response.data or {} notify( ( 'compacted %s to about %s tokens' ):format( tostring( data.tokensBefore or '?' ), tostring( data.estimatedTokensAfter or '?' ) ) ) end )end--- Turns automatic compaction on or off.subcommands.autocompact = function( arguments ) local current = require_session() if not current then return end local wanted = arguments ~= 'off' current.request( { type = 'set_auto_compaction', enabled = wanted, }, function( response ) if response.success then notify( 'automatic compaction ' .. ( wanted and 'on' or 'off' ) ) else notify( response.error or 'pi refused', vim.log.levels.ERROR ) end end )end--- What this session has cost so far.subcommands.session = function() local current = require_session() if not current then return end current.request( { type = 'get_session_stats', }, function( response ) if not response.success or not response.data then notify( 'pi did not report session statistics', vim.log.levels.WARN ) return end local data = response.data local tokens = data.tokens or {} local usage = data.contextUsage or {} local told = { 'session ' .. tostring( data.sessionId or current.name ), ( 'messages %s, tool calls %s' ):format( tostring( data.totalMessages or '?' ), tostring( data.toolCalls or '?' ) ), ( 'tokens %s in, %s out, %s total' ):format( tostring( tokens.input or 0 ), tostring( tokens.output or 0 ), tostring( tokens.total or 0 ) ), ( 'cost %s' ):format( tostring( data.cost or 0 ) ), } if usage.percent then table.insert( told, ( 'context %s%% of %s' ):format( tostring( usage.percent ), tostring( usage.contextWindow ) ) ) end notify( table.concat( told, '\n' ) ) end )end--- Names the session, so it can be recognised when resumed.subcommands.name = function( arguments ) local current = require_session() if not current then return end if arguments == '' then notify( 'name needs a name', vim.log.levels.WARN ) return end current.request( { type = 'set_session_name', name = arguments, }, function( response ) if response.success then notify( 'named ' .. arguments ) else notify( response.error or 'pi refused the name', vim.log.levels.ERROR ) end end )end--- Starts a fresh conversation in the process that is already running.--- `start` spawns another pi; this one does not.subcommands.new = function() local current = require_session() if not current then return end current.request( { type = 'new_session', }, function( response ) if not response.success then notify( response.error or 'pi refused a new session', vim.log.levels.ERROR ) return end if response.data and response.data.cancelled then notify( 'an extension cancelled the new session', vim.log.levels.WARN ) return end transcript.clear( current.buffer ) notify 'new conversation' end )end--- Writes the conversation out as it is.subcommands.export = function( arguments ) local current = require_session() if not current then return end local request = { type = 'export_html', } if arguments ~= '' then request.outputPath = vim.fn.expand( arguments ) end current.request( request, function( response ) if response.success and response.data then notify( 'exported to ' .. tostring( response.data.path ) ) else notify( response.error or 'export failed', vim.log.levels.ERROR ) end end )end if subcommand == 'stop' or subcommand == 'sessions' then return matching( session.list() ) end if subcommand == 'autocompact' then return matching { 'on', 'off', } endnew file mode 100644+124 / −0 text lines
local edit = require 'bugabinga.pivi.edit'local IMAGES = { png = 'image/png', jpg = 'image/jpeg', jpeg = 'image/jpeg', gif = 'image/gif', webp = 'image/webp',}--- What a written prompt turns out to mean.--- Pi reads a leading bang as a shell command rather than something said, and--- doubles it to keep the output out of the conversation.--- @param text string--- @return table action kind, and what that kind needslocal parse = function( text ) vim.validate( 'text', text, 'string' ) local written = vim.trim( text ) local quiet = written:match '^!!%s*(.*)$' if quiet then return { kind = 'bash', command = vim.trim( quiet ), exclude = true, } end local loud = written:match '^!%s*(.*)$' if loud then return { kind = 'bash', command = vim.trim( loud ), exclude = false, } end return { kind = 'prompt', message = written, }endlocal image_type = function( path ) local suffix = path:match '%.([%a%d]+)$' if not suffix then return nil end return IMAGES[suffix:lower()]endlocal absolute = function( path, cwd ) local expanded = vim.fn.expand( path ) if expanded:match '^/' or expanded:match '^%a:' then return vim.fs.normalize( expanded ) end return vim.fs.normalize( ( cwd or vim.uv.cwd() ) .. '/' .. expanded )end--- Reads a file for the model.--- A loaded buffer wins over what is on disk, because that is what the user is--- looking at and what every other pivi read already answers with.local contents = function( path ) local text = edit.read( path ) return textendlocal encode_image = function( path ) local read = io.open( path, 'rb' ) if not read then return nil end local bytes = read:read '*a' read:close() if not bytes or bytes == '' then return nil end local ok, encoded = pcall( vim.base64.encode, bytes ) if not ok then return nil end return encodedend--- Replaces every file reference with the file itself.--- The shape matches what Pi builds for the same reference elsewhere, so a--- model sees one convention rather than two.--- @param text string--- @param options table? cwd--- @return string message--- @return table images--- @return string[] missing references that could not be readlocal expand = function( text, options ) vim.validate( 'text', text, 'string' ) options = options or {} local images = {} local missing = {} local attached = {} local message = text:gsub( '@([%w%._%-~/\\:]+)', function( reference ) local path = absolute( reference, options.cwd ) local mime = image_type( path ) if mime then local data = encode_image( path ) if not data then table.insert( missing, reference ) return '@' .. reference end table.insert( images, { type = 'image', data = data, mimeType = mime, } ) return ( '<file name="%s"></file>' ):format( path ) end local body = contents( path ) if not body then table.insert( missing, reference ) return '@' .. reference end if attached[path] then return ( '<file name="%s"></file>' ):format( path ) end attached[path] = true return ( '<file name="%s">\n%s\n</file>' ):format( path, body ) end ) return message, images, missingend--- Every reference a written prompt names.local references = function( text ) local found = {} for reference in ( text or '' ):gmatch '@([%w%._%-~/\\:]+)' do table.insert( found, reference ) end return foundendreturn { image_types = IMAGES, parse = parse, expand = expand, references = references, absolute = absolute,}+53 / −2 text lines
local compose = require 'bugabinga.pivi.compose'--- Runs a shell command through Pi.--- Pi keeps the output in the conversation unless asked not to, which is what--- doubling the bang means.local run_bash = function( self, command, exclude, callback ) vim.validate( 'command', command, 'string' ) if command == '' then return false, 'nothing to run' end local id = begin( self, 'tool', { tool = exclude and 'bang!' or 'bang', args = { command = command, }, cwd = self.cwd, } ) entry.line( self.buffer, id, tool.headline( entry.meta( self.buffer, id ) ) ) self.client.request( { type = 'bash', command = command, excludeFromContext = exclude == true, }, function( response ) local data = response.data or {} entry.annotate( self.buffer, id, { result = { content = { { type = 'text', text = data.output or '', }, }, }, failed = response.success ~= true or ( data.exitCode ~= nil and data.exitCode ~= 0 ), exit = data.exitCode, } ) entry.rewrite( self.buffer, id, tool.body( entry.meta( self.buffer, id ) ) ) seal( self ) if callback then callback( response ) end end ) return true, nilend local message = text local expanded, images, missing = text, nil, {} if options.compose ~= false then expanded, images, missing = compose.expand( text, { cwd = self.cwd, } ) for _, reference in ipairs( missing ) do vim.notify( 'pivi: cannot read @' .. reference, vim.log.levels.WARN ) end end local message = expanded message = context.render( snapshot ) .. text message = context.render( snapshot ) .. expanded if images and #images > 0 then command.images = images end self.bash = function( command, exclude, callback ) return run_bash( self, command, exclude, callback ) end+13 / −1 text lines
In the prompt, `<c-y>` accepts: the completion when one is offered, the prompt otherwise. `<CR>` in normal mode sends it too, so both work. The prompt opens in insert mode, so keys behind a leader need `<Esc>` first; `vim.g.pivi_start_insert = false` opens it in normal mode instead.`/model` and other terminal-only commands are not offered over this channel and are refused rather than said to the model; `:Pi model` switches model natively.`/model` and other terminal-only commands are not offered over this channel and are refused rather than said to the model; `:Pi model` and `:Pi thinking` reach the same capability natively.In a prompt, a leading `!` runs the rest as a shell command through pi and keeps the output in the conversation; `!!` runs it and keeps the output out. `@` names a file: it opens a picker when it starts a word, and stays an ordinary character inside one. A named file is sent as its buffer content when it is open and unsaved, because that is what every other pivi read answers with; an image is attached rather than inlined.pivi chooses none of these. It publishes `<Plug>(pivi-goto-location)`, `<Plug>(pivi-inspect-entry)`, `<Plug>(pivi-next-entry)`, `<Plug>(pivi-previous-entry)`, `<Plug>(pivi-next-tool)`, `<Plug>(pivi-previous-tool)`, `<Plug>(pivi-compare-change)`, `<Plug>(pivi-toggle-entry)`, `<Plug>(pivi-guide)`, `<Plug>(pivi-submit)` and `<Plug>(pivi-accept)`, and the configuration decides the keys. A key is only reused where the local behaviour is the same idea as the global one.| `:Pi bang {cmd}` | run a shell command through pi, output joins the conversation || `:Pi bang! {cmd}` | the same, kept out of the conversation || `:Pi model [name]` | switch model || `:Pi thinking [level]` | switch thinking level || `:Pi compact [instructions]` | compact the conversation || `:Pi autocompact on\|off` | automatic compaction || `:Pi session` | tokens, cost and context so far || `:Pi name {name}` | name the session || `:Pi new` | fresh conversation in the running process || `:Pi export [path]` | write the conversation out |new file mode 100644+129 / −0 text lines
---@diagnostic disable: duplicate-set-field, need-check-nil, param-type-mismatch, assign-type-mismatch, redundant-parameterlocal compose = require 'bugabinga.pivi.compose'local temp_file = function( lines, suffix ) local path = vim.fs.normalize( vim.fn.tempname() .. ( suffix or '.lua' ) ) vim.fn.writefile( lines, path ) return pathenddescribe( 'pivi compose', function() after_each( function() vim.cmd 'silent! %bwipeout!' end ) describe( 'what was written', function() it( 'reads a leading bang as a command to run', function() local intent = compose.parse '!just test' assert.equal( 'bash', intent.kind ) assert.equal( 'just test', intent.command ) assert.is_false( intent.exclude ) end ) it( 'reads a doubled bang as a command kept out of the conversation', function() local intent = compose.parse '!!git status' assert.equal( 'bash', intent.kind ) assert.equal( 'git status', intent.command ) assert.is_true( intent.exclude ) end ) it( 'tolerates space after the bang', function() assert.equal( 'ls -la', compose.parse( '! ls -la' ).command ) assert.equal( 'ls', compose.parse( ' !! ls ' ).command ) end ) it( 'reads anything else as something said', function() local intent = compose.parse 'rename greet to hail' assert.equal( 'prompt', intent.kind ) assert.equal( 'rename greet to hail', intent.message ) end ) it( 'does not mistake a bang inside a sentence for a command', function() assert.equal( 'prompt', compose.parse( 'fix this!' ).kind ) assert.equal( 'prompt', compose.parse( 'why not use !! here' ).kind ) end ) end ) describe( 'what was referred to', function() it( 'names every reference', function() assert.same( { 'a.lua', 'src/b.lua', }, compose.references 'compare @a.lua with @src/b.lua' ) assert.same( {}, compose.references 'nothing here' ) end ) it( 'replaces a reference with the file itself', function() local path = temp_file { 'local value = 1', } local message, images, missing = compose.expand( 'look at @' .. path ) assert.same( {}, missing ) assert.same( {}, images ) assert.is_true( message:find( '<file name="' .. path .. '">', 1, true ) ~= nil ) assert.is_true( message:find( 'local value = 1', 1, true ) ~= nil ) assert.is_true( message:find( '</file>', 1, true ) ~= nil ) end ) it( 'prefers what the buffer holds over what the file holds', function() local path = temp_file { 'on disk', } vim.cmd( 'edit! ' .. vim.fn.fnameescape( path ) ) vim.api.nvim_buf_set_lines( 0, 0, -1, false, { 'not saved yet', } ) local message = compose.expand( 'read @' .. path ) assert.is_true( message:find( 'not saved yet', 1, true ) ~= nil ) assert.is_nil( message:find( 'on disk', 1, true ) ) end ) it( 'resolves a relative reference against the session directory', function() local path = temp_file { 'relative', } local directory = vim.fs.dirname( path ) local message = compose.expand( '@' .. vim.fs.basename( path ), { cwd = directory, } ) assert.is_true( message:find( 'relative', 1, true ) ~= nil ) end ) it( 'attaches an image rather than inlining it', function() local path = vim.fs.normalize( vim.fn.tempname() .. '.png' ) local write = io.open( path, 'wb' ) write:write '\137PNG\r\n\26\n fake but binary' write:close() local message, images = compose.expand( 'see @' .. path ) assert.equal( 1, #images ) assert.equal( 'image/png', images[1].mimeType ) assert.equal( 'image', images[1].type ) assert.is_true( #images[1].data > 0 ) assert.is_true( message:find( '<file name="' .. path .. '"></file>', 1, true ) ~= nil ) end ) it( 'reports a reference it cannot read and leaves it written', function() local absent = vim.fn.tempname() .. '-absent.lua' local message, _, missing = compose.expand( 'read @' .. absent ) assert.equal( 1, #missing ) assert.is_true( message:find( '@' .. absent, 1, true ) ~= nil ) end ) it( 'includes a file once however often it is named', function() local path = temp_file { 'once', } local message = compose.expand( ( '@%s and @%s' ):format( path, path ) ) local count = select( 2, message:gsub( 'once', '' ) ) assert.equal( 1, count ) end ) it( 'leaves text without references alone', function() local message, images, missing = compose.expand 'just words' assert.equal( 'just words', message ) assert.same( {}, images ) assert.same( {}, missing ) end ) end )end )+51 / −5 text lines
it( 'claims no key of its own in a prompt, beyond slash-command entry', function() it( 'claims no key of its own in a prompt, beyond naming a command or a file', function() it( 'still types a literal @ inside a word', function() -- Naming a file opens a picker, which this test is not exercising. local original = vim.ui.select vim.ui.select = function( _, _, on_choice ) on_choice( nil ) end local channel = fake.new() local current = session.create { spawn = channel.spawn, name = 'typing', extension = false, skill = false, executable = 'pi', env = {}, } local bufnr = command.open_prompt( current ) vim.cmd.stopinsert() local at for _, mapping in ipairs( vim.api.nvim_buf_get_keymap( bufnr, 'i' ) ) do if mapping.lhs == '@' then at = mapping end end assert.is_table( at ) local win = vim.fn.bufwinid( bufnr ) assert.is_true( win > 0 ) vim.api.nvim_set_current_win( win ) -- Normal mode cannot place the cursor past the last character, so both -- positions below sit inside the line. -- Inside a word it is just a character. vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { 'mail me', } ) vim.api.nvim_win_set_cursor( win, { 1, 4, } ) assert.equal( '@', at.callback() ) -- Starting a word it names a file. vim.api.nvim_buf_set_lines( bufnr, 0, -1, false, { 'look at x', } ) vim.api.nvim_win_set_cursor( win, { 1, 8, } ) assert.equal( '', at.callback() ) vim.wait( 50, function() return false end ) vim.ui.select = original end )+103 / −0 text lines
it( 'runs a banged prompt as a command instead of saying it', function() local channel = fake.new() local current = create( channel ) assert.is_true( current.submit( '!just test', { capture = false, } ) ) local ran for _, sent in ipairs( channel.commands ) do if sent.type == 'bash' then ran = sent end assert.is_not.equal( 'prompt', sent.type ) end assert.is_table( ran ) assert.equal( 'just test', ran.command ) assert.is_false( ran.excludeFromContext ) end ) it( 'keeps a doubly banged command out of the conversation', function() local channel = fake.new() local current = create( channel ) current.submit( '!!git status', { capture = false, } ) local ran for _, sent in ipairs( channel.commands ) do if sent.type == 'bash' then ran = sent end end assert.is_table( ran ) assert.equal( 'git status', ran.command ) assert.is_true( ran.excludeFromContext ) end ) it( 'shows what a command produced inside its own entry', function() local channel = fake.new() local current = create( channel ) current.submit( '!echo hi', { capture = false, } ) local ran for _, sent in ipairs( channel.commands ) do if sent.type == 'bash' then ran = sent end end channel.frame { id = ran.id, type = 'response', command = 'bash', success = true, data = { output = 'hi', exitCode = 0, }, } channel.flush() local item = entry.list( current.buffer )[1] local lines = transcript.lines( current.buffer ) assert.equal( 'tool', item.kind ) assert.equal( 'bang', item.meta.tool ) assert.is_true( vim.list_contains( lines, 'hi' ) ) assert.is_false( item.meta.failed ) end ) it( 'marks a command that exited badly', function() local channel = fake.new() local current = create( channel ) current.submit( '!false', { capture = false, } ) local ran for _, sent in ipairs( channel.commands ) do if sent.type == 'bash' then ran = sent end end channel.frame { id = ran.id, type = 'response', command = 'bash', success = true, data = { output = '', exitCode = 1, }, } channel.flush() assert.is_true( entry.list( current.buffer )[1].meta.failed ) end ) it( 'sends a referenced file with what was said', function() local path = vim.fs.normalize( vim.fn.tempname() .. '.lua' ) vim.fn.writefile( { 'local referenced = true', }, path ) local channel = fake.new() local current = create( channel ) current.submit( 'explain @' .. path, { capture = false, } ) local sent = commands_of( channel, 'prompt' )[1] assert.is_table( sent ) assert.is_true( sent.message:find( 'local referenced = true', 1, true ) ~= nil ) assert.is_true( sent.message:find( '<file name=', 1, true ) ~= nil ) -- The transcript still shows what the user actually wrote. local prompt = entry.list( current.buffer )[1] local lines = transcript.lines( current.buffer ) assert.equal( 'explain @' .. path, lines[prompt.first] ) end )