local rpc = require 'bugabinga.pivi.rpc' local transcript = require 'bugabinga.pivi.transcript' local BUFFER_NAME = 'help' local ORIENTATION = table.concat( { 'You answer one short question about Neovim or about pivi, the native Neovim integration for Pi.', 'pivi runs Pi as a JSONL RPC child process and presents sessions, edits, and findings through native Neovim surfaces.', 'Answer directly and briefly. Do not modify files.', }, ' ' ) local executable = function() return vim.g.pivi_executable or 'pi' end local build_command = function( options ) local command = { executable(), '--mode', 'rpc', '--no-session', '--no-tools', '--append-system-prompt', ORIENTATION, } if options.model then table.insert( command, '--model' ) table.insert( command, options.model ) end for _, argument in ipairs( options.arguments or {} ) do table.insert( command, argument ) end return command end --- Answers a question in an independent ephemeral run. --- It owns its own process, buffer, and lifetime, so no working session's --- history, queue, or status is touched. --- @param question string --- @param options table? model, arguments, spawn, on_done local ask = function( question, options ) vim.validate( 'question', question, 'string' ) options = options or {} local bufnr = transcript.ensure( BUFFER_NAME ) transcript.clear( bufnr ) transcript.line( bufnr, '? ' .. question ) transcript.line( bufnr, '' ) local run = { buffer = bufnr, done = false, answer = '', } run.client = rpc.start { command = build_command( options ), cwd = options.cwd or vim.uv.cwd(), spawn = options.spawn, on_event = function( event ) if event.type == 'message_update' then local delta = event.assistantMessageEvent or {} if delta.type == 'text_delta' then run.answer = run.answer .. ( delta.delta or '' ) transcript.append( bufnr, delta.delta or '' ) end elseif event.type == 'message_end' and event.message and event.message.errorMessage then transcript.line( bufnr, '! ' .. tostring( event.message.errorMessage ) ) elseif event.type == 'agent_settled' then run.done = true run.client.stop() if options.on_done then options.on_done( run ) end end end, on_exit = function() run.done = true end, } run.client.request( { type = 'prompt', message = question, }, function( response ) if response.success then return end transcript.line( bufnr, '! ' .. tostring( response.error or 'help run rejected' ) ) run.done = true run.client.stop() if options.on_done then options.on_done( run ) end end ) transcript.show( bufnr ) return run end return { buffer_name = BUFFER_NAME, orientation = ORIENTATION, build_command = build_command, ask = ask, }