Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

neovim/lua/bugabinga/pivi/init.lua

Raw
local auto = require 'std.auto'
local map = require 'std.map'
local view = require 'bugabinga.pivi.view'
local connect = require 'bugabinga.pivi.transport'
local auth = require 'bugabinga.pivi.auth'
local review = require 'bugabinga.pivi.review'

local root = vim.fn.fnamemodify(debug.getinfo(1, 'S').source:sub(2), ':h:h:h:h') .. '/pivi'
local current

local function notify(message)
  vim.notify(tostring(message), vim.log.levels.ERROR, { title = 'pivi' })
end

local function request(state, method, params, done, settled)
  if not state.transport.running() then
    if settled then settled() end
    notify('Pivi is disconnected.')
    return
  end
  state.transport.request(method, params, function(ok, result)
    if settled then settled() end
    if not ok then
      notify(result)
    elseif done then
      done(result)
    end
  end)
end

local function menu(prompt, choices)
  vim.ui.select(choices, { prompt = prompt, format_item = function(choice) return choice[1] end }, function(choice)
    if choice then choice[2]() end
  end)
end

local function label(buffer)
  local name = vim.api.nvim_buf_get_name(buffer)
  return name ~= '' and vim.fn.fnamemodify(name, ':~:.') or '[No Name]'
end

local function is_workspace(buffer)
  return vim.api.nvim_buf_is_valid(buffer) and not vim.api.nvim_buf_get_name(buffer):match('^pivi://')
end

local function recent_buffer()
  local recent
  for _, info in ipairs(vim.fn.getbufinfo({ buflisted = 1 })) do
    local workspace = vim.bo[info.bufnr].buftype == '' and is_workspace(info.bufnr)
    if
      workspace
      and (
        not recent
        or info.lastused > recent.lastused
        or (info.lastused == recent.lastused and info.bufnr > recent.bufnr)
      )
    then
      recent = info
    end
  end
  return recent and recent.bufnr
end

local function editor_context()
  local buffer = recent_buffer()
  if not buffer then return ('[editor: cwd %s]'):format(vim.fn.getcwd()) end
  local window = vim.fn.bufwinid(buffer)
  local line = window ~= -1 and vim.api.nvim_win_get_cursor(window)[1] or vim.api.nvim_buf_get_mark(buffer, '"')[1]
  return ('[editor: cwd %s · buffer %d %s · line %d · %s]'):format(
    vim.fn.getcwd(),
    buffer,
    vim.api.nvim_buf_get_name(buffer),
    math.max(line, 1),
    vim.bo[buffer].modified and 'unsaved changes' or 'saved'
  )
end

local function select_attachment(state, prompt, done)
  vim.ui.select(
    state.attachments,
    { prompt = prompt, format_item = function(item) return item.label end },
    function(item)
      if item then done(item) end
    end
  )
end

local function attach(state)
  local function add(kind, buffer)
    if not buffer or not is_workspace(buffer) then
      notify('No workspace buffer to attach.')
      return
    end
    vim.fn.bufload(buffer)
    table.insert(state.attachments, { kind = kind, buffer = buffer, label = kind .. ': ' .. label(buffer) })
    view.winbar(state)
  end
  menu('Attach to draft', {
    {
      'Buffer',
      function()
        local buffers = vim.tbl_filter(
          function(buffer) return vim.bo[buffer].buflisted and is_workspace(buffer) end,
          vim.api.nvim_list_bufs()
        )
        local format = function(buffer) return buffer .. ': ' .. label(buffer) end
        vim.ui.select(buffers, { prompt = 'Buffer', format_item = format }, function(buffer)
          if buffer then add('buffer', buffer) end
        end)
      end,
    },
    {
      'File',
      function()
        vim.ui.input({ prompt = 'File: ', completion = 'file' }, function(path)
          if path and path ~= '' then add('file', vim.fn.bufadd(vim.fn.fnamemodify(path, ':p'))) end
        end)
      end,
    },
    { 'Diagnostics', function() add('diagnostics', recent_buffer()) end },
  })
end

local function detach(state)
  select_attachment(state, 'Remove attachment', function(selected)
    state.attachments = vim.tbl_filter(function(item) return item ~= selected end, state.attachments)
    view.winbar(state)
  end)
end

local function attachment_text(attachment)
  local buffer = attachment.buffer
  local name = vim.api.nvim_buf_get_name(buffer)
  if attachment.kind ~= 'diagnostics' then
    local content = table.concat(vim.api.nvim_buf_get_lines(buffer, 0, -1, false), '\n')
    return ('<buffer number="%d" name="%s">\n%s\n</buffer>'):format(buffer, name, content)
  end
  local lines = vim.tbl_map(function(diagnostic)
    local severity = vim.diagnostic.severity[diagnostic.severity]
    return ('%d:%d %s %s'):format(diagnostic.lnum + 1, diagnostic.col + 1, severity, diagnostic.message)
  end, vim.diagnostic.get(buffer))
  return ('<diagnostics buffer="%d" name="%s">\n%s\n</diagnostics>'):format(buffer, name, table.concat(lines, '\n'))
end

local function submit(state, mode)
  if state.submitting then return end
  local text = view.draft(state)
  if text:match('^%s*$') then
    notify('Draft is empty.')
    return
  end
  local sent = vim.list_slice(state.attachments)
  local parts = { editor_context() .. '\n' .. text }
  for _, attachment in ipairs(sent) do
    if not vim.api.nvim_buf_is_valid(attachment.buffer) then
      notify('Attached buffer no longer exists: ' .. attachment.label)
      return
    end
    parts[#parts + 1] = attachment_text(attachment)
  end
  state.submitting = true
  view.winbar(state)
  request(state, 'submit', { content = table.concat(parts, '\n\n'), mode = mode }, function()
    if view.draft(state) == text then view.set_draft(state, '') end
    state.attachments = vim.tbl_filter(function(item) return not vim.tbl_contains(sent, item) end, state.attachments)
    view.winbar(state)
    if vim.api.nvim_get_current_buf() == state.draft_buffer then
      vim.api.nvim_set_current_buf(state.buffer)
      view.follow(state)
    end
  end, function()
    state.submitting = false
    view.winbar(state)
  end)
end

local function fork(state, id)
  if not id then
    notify('Place cursor on a committed entry.')
    return
  end
  local previous, prompt
  for _, item in ipairs(state.view.items) do
    local entry = item.entry
    if entry and entry.id == id then
      local lines = view.entry_lines(state, id)
      if entry.kind == 'pi.user' then
        prompt = table.concat(lines, '\n', 2, #lines - 1):gsub('^%[editor: [^\n]*%]\n', '')
      end
      break
    end
    previous = entry and entry.id or previous
  end
  if not prompt then
    request(state, 'fork', { entry = id })
  elseif not view.draft(state):match('^%s*$') then
    notify('Draft is not empty. Submit or clear it before forking at a prompt.')
  else
    request(state, previous and 'fork' or 'new', { entry = previous }, function()
      view.set_draft(state, prompt)
      vim.api.nvim_set_current_buf(state.draft_buffer)
    end)
  end
end

local function inspect_entry(state, entry)
  if not entry then
    notify('No entry at cursor.')
    return
  end
  view.page('entry', view.entry_lines(state, entry))
end

local function open_attachment(state)
  if #state.attachments == 0 then
    notify('No attachments.')
    return
  end
  select_attachment(state, 'Open attachment', function(item)
    if vim.api.nvim_buf_is_valid(item.buffer) then vim.api.nvim_set_current_buf(item.buffer) end
  end)
end

local actions = {
  help = function(state) view.help(state, false) end,
  toggle = function(state)
    local draft = vim.api.nvim_get_current_buf() == state.draft_buffer
    vim.api.nvim_set_current_buf(draft and state.buffer or state.draft_buffer)
  end,
  submit = function(state) submit(state, 'submit') end,
  steer = function(state) submit(state, 'steer') end,
  followUp = function(state) submit(state, 'followUp') end,
  review = review,
  abort = function(state)
    if state.stopping then return end
    if not state.transport.running() then
      notify('Pivi is disconnected. Run :Pivi to reconnect before stopping retained work.')
      return
    end
    local inbox = state.view and state.view.docs['pi.inbox']
    local queued = {}
    for _, item in ipairs(inbox and inbox.items or {}) do
      if type(item.content) == 'string' then queued[#queued + 1] = (item.content:gsub('^%[editor: [^\n]*%]\n', '')) end
    end
    if not state.view then return end
    state.stopping = true
    view.render(state, state.view)
    state.transport.request('abort', nil, function(ok, failure)
      state.stopping = false
      view.render(state, state.view)
      if not ok then
        notify(failure)
      elseif #queued > 0 then
        local draft = view.draft(state)
        if not draft:match('^%s*$') then table.insert(queued, 1, draft) end
        view.set_draft(state, table.concat(queued, '\n\n'))
        vim.notify('Queued messages are back in the draft.', vim.log.levels.INFO, { title = 'pivi' })
      end
    end)
  end,
  fork = function(state) fork(state, view.entry(state)) end,
  inspect = function(state)
    if view.context(state) == 'draft' then
      open_attachment(state)
    else
      inspect_entry(state, view.entry(state))
    end
  end,
  actions = function(state)
    if view.context(state) ~= 'draft' then
      local entry = view.entry(state)
      menu('Pivi entry', {
        { 'Inspect entry', function() inspect_entry(state, entry) end },
        { 'Fork at entry', function() fork(state, entry) end },
      })
    elseif #state.attachments == 0 then
      attach(state)
    else
      menu('Pivi draft', {
        { 'Attach context', function() attach(state) end },
        { 'Open attachment', function() open_attachment(state) end },
        { 'Remove attachment', function() detach(state) end },
      })
    end
  end,
}

local function dispatch(state, action)
  if state ~= current then
    notify('This pivi buffer is not connected. Run :Pivi.')
    return
  end
  actions[action](state)
end

local function disconnected(state, message)
  view.disconnected(state, message)
end

local function stop()
  local state = current
  if not state then return end
  current = nil
  state.transport.close()
  disconnected(state)
end

local function start()
  if current and not (current.transport.running() and vim.api.nvim_buf_is_valid(current.buffer)) then stop() end
  if not current then
    if vim.fn.isdirectory(root .. '/node_modules') == 0 then
      notify('Pivi dependencies missing. Run `just pivi-install`.')
      return
    end
    local id = vim.g.PiviSession
    if type(id) ~= 'string' or not id:match('^[%w_-]+$') then
      id = vim.fn.sha256(vim.uv.hrtime() .. ':' .. vim.fn.getpid()):sub(1, 8)
      vim.g.PiviSession = id
    end
    vim.opt.sessionoptions:append('globals')
    local argv = {
      vim.g.pivi_node or 'node',
      root .. '/worker.mjs',
      vim.fn.stdpath('state') .. '/pivi/sessions/' .. id .. '/session.sqlite',
      vim.fn.stdpath('state') .. '/pivi/auth.json',
      vim.g.pivi_config,
    }
    local state = view.create(id, dispatch)
    local ok, transport = pcall(connect, argv, function(record)
      if current ~= state then return end
      if record.type == 'exit' then
        local message = (record.code ~= 0 or record.protocol_error or not state.ready)
            and ('Pivi worker exited (%d). %s'):format(record.code, record.error)
          or nil
        disconnected(state, message)
        if message then notify(message) end
      elseif record.type == 'view' then
        view.render(state, record.view)
      elseif record.type == 'ready' then
        state.ready = true
      elseif record.type == 'report' then
        notify(record.error)
      elseif record.type == 'notice' then
        vim.notify(record.message, vim.log.levels.INFO, { title = 'pivi' })
      else
        auth.receive(state, record)
      end
    end)
    if not ok then
      view.disconnected(state, tostring(transport))
      vim.api.nvim_set_current_buf(state.buffer)
      notify(transport)
      return
    end
    state.id, state.transport, state.ready = id, transport, false
    current = state
  end
  return current
end

local function show()
  local state = start()
  if state then vim.api.nvim_set_current_buf(state.buffer) end
end

local sign_in

local function choose_model(state, value, only)
  local function configure(provider, model)
    request(state, 'configure', { model = { provider = provider, modelId = model } })
  end
  if value ~= '' then
    local provider, model = value:match('^([^/]+)/(.+)$')
    if not provider then
      notify('Use provider/model-id.')
      return
    end
    configure(provider, model)
    return
  end
  request(state, 'models', nil, function(models)
    if only then models = vim.tbl_filter(function(item) return item.provider == only end, models) end
    if #models == 0 and only then
      notify('Signed in, but ' .. only .. ' offers no models.')
      return
    elseif #models == 0 then
      vim.notify('No usable models yet. Sign in to a provider first.', vim.log.levels.INFO, { title = 'pivi' })
      sign_in(state, '')
      return
    end
    local format = function(item) return item.provider .. '/' .. item.modelId end
    vim.ui.select(models, { prompt = 'Pivi model', format_item = format }, function(choice)
      if choice then configure(choice.provider, choice.modelId) end
    end)
  end)
end

sign_in = function(state, provider)
  auth.login(state, provider, function(signed_in)
    if state.model == 'no model' then choose_model(state, '', signed_in.id) end
  end)
end

local commands = {
  login = sign_in,
  logout = auth.logout,
  show = function(state) vim.api.nvim_set_current_buf(state.buffer) end,
  draft = function(state) vim.api.nvim_set_current_buf(state.draft_buffer) end,
  help = function(state) view.help(state, true) end,
  model = choose_model,
  attach = attach,
  fork = actions.fork,
  compact = function(state, instructions) request(state, 'compact', { instructions = instructions }) end,
  new = function(state) request(state, 'new') end,
  earlier = function(state) request(state, 'earlier') end,
  resume = function(state) request(state, 'resume') end,
  continue = function(state)
    if state.busy then
      notify('Work is still retained. Use :Pivi resume for suspended work, or :Pivi stop first.')
      return
    end
    if not (state.view and state.view.docs['pi.live'].runFailure) then
      notify('No stopped run to continue. Write a new draft instead.')
      return
    end
    menu('Continue from retained history? Existing edits stay; the model may repeat actions.', {
      { 'Keep stopped', function() end },
      { 'Continue run', function() request(state, 'continue') end },
    })
  end,
  review = review,
  stop = function(state) actions.abort(state) end,
}
local names = vim.tbl_keys(commands)
table.insert(names, 'close')
table.sort(names)

vim.api.nvim_create_user_command('Pivi', function(options)
  local name, argument = options.args:match('^(%S*)%s*(.*)$')
  if name == 'close' then
    stop()
    return
  end
  local command = commands[name == '' and 'show' or name]
  if not command then
    notify('Unknown Pivi command: ' .. name)
    return
  end
  local state = start()
  if state then command(state, argument) end
end, {
  nargs = '*',
  complete = function(lead)
    return vim.tbl_filter(function(name) return vim.startswith(name, lead) end, names)
  end,
  desc = 'Pivi: standalone Pi Durable harness',
})

map.normal { keys = view.prefix() .. 'p', description = 'Open pivi', category = 'pivi', command = show }

auto('pivi_lifecycle') {
  { events = 'VimLeavePre', command = stop },
  {
    events = 'BufModifiedSet',
    command = function()
      if current then view.winbar(current) end
    end,
  },
  {
    events = 'SessionLoadPost',
    command = function()
      if current and current.id ~= vim.g.PiviSession then stop() end
      if vim.api.nvim_buf_get_name(0):match('^pivi://') then show() end
    end,
  },
}

_G.BugabingaPivi = {
  show = show,
  close = stop,
  fold = view.fold,
  foldtext = view.foldtext,
  current = function() return current end,
}
return _G.BugabingaPivi