repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

wezterm/bugabinga/ai_shell.lua

Raw
File outline
local wezterm = require 'wezterm'
local system_prompt = require 'bugabinga.ai_system_prompt'

local M = {}

local API_URL = 'https://api.z.ai/api/coding/paas/v4/chat/completions'
local MODEL = 'glm-5-turbo'
local MAX_SCROLLBACK_LINES = 300

local ai_state = {}

local function get_ai_state(window)
  local id = window:window_id()
  if not ai_state[id] then
    ai_state[id] = {
      status = 'idle',
    }
  end
  return ai_state[id]
end

function M.trigger_ai_shell(window, pane, question)
  local state = get_ai_state(window)
  state.status = 'loading'

  local scrollback = pane:get_lines_as_text(MAX_SCROLLBACK_LINES)

  local api_key = os.getenv 'ZAI_WEZTERM_API_KEY' or ''
  wezterm.log_info('ai_shell: ZAI_WEZTERM_API_KEY present: ' .. (api_key ~= '' and 'yes' or 'NO - check WezTerm env vars'))

  local user_content = 'RECENT SCROLLBACK:\n' .. scrollback .. '\n\n---\n\nUSER QUESTION: ' .. question

  local json_payload = wezterm.json_encode({
    model = MODEL,
    messages = {
      { role = 'system', content = system_prompt.prompt },
      { role = 'user', content = user_content },
    },
    thinking = { type = 'disabled' },
    stream = false,
    max_tokens = 4096,
    temperature = 0.6,
  })

  wezterm.log_info('ai_shell: requesting z.ai API')

  local success, stdout, stderr = wezterm.run_child_process({
    'curl', '-s', '-X', 'POST', API_URL,
    '-H', 'Content-Type: application/json',
    '-H', 'Authorization: Bearer ' .. api_key,
    '-d', json_payload,
  })

  if not success or stdout == '' then
    wezterm.log_error('ai_shell: curl failed or empty response: ' .. stderr)
    state.status = 'offline'
    wezterm.time.call_after(2, function()
      state.status = 'idle'
    end)
    return
  end

  local ok, response = pcall(function()
    return wezterm.json_parse(stdout)
  end)

  if not ok or not response or not response.choices or not response.choices[1] or not response.choices[1].message then
    wezterm.log_error('ai_shell: API error: ' .. tostring(stdout))
    state.status = 'error'
    state.status = 'error'
    wezterm.time.call_after(2, function()
      state.status = 'idle'
    end)
    return
  end

  local command = M.strip_markdown(response.choices[1].message.content)
  command = command:match('^%s*(.-)%s*$')
  wezterm.log_info('ai_shell: executing: ' .. command)

  pane:send_text(command)

  state.status = 'success'
  wezterm.time.call_after(1.5, function()
    state.status = 'idle'
  end)
end

function M.strip_markdown(text)
  local lines = {}
  for line in text:gmatch('[^\r\n]+') do
    table.insert(lines, line)
  end

  if #lines > 0 and (lines[1]:match('^```%w*$') or lines[1] == '```') then
    table.remove(lines, 1)
  end

  if #lines > 0 and lines[#lines] == '```' then
    table.remove(lines, #lines)
  end

  local filtered = {}
  for _, line in ipairs(lines) do
    if line ~= '```' then
      table.insert(filtered, line)
    end
  end

  return table.concat(filtered, '\n')
end

function M.get_status_icon(window)
  local state = get_ai_state(window)

  local icon, color, label

  if state.status == 'loading' then
    icon = wezterm.nerdfonts.md_robot_confused
    color = 'Yellow'
    label = 'loading...'
  elseif state.status == 'success' then
    icon = wezterm.nerdfonts.md_robot_excited
    color = 'Green'
    label = 'done'
  elseif state.status == 'error' then
    icon = wezterm.nerdfonts.md_robot_dead
    color = 'Red'
    label = 'error'
  elseif state.status == 'offline' then
    icon = wezterm.nerdfonts.md_robot_off
    color = 'Gray'
    label = 'offline'
  else
    icon = wezterm.nerdfonts.md_robot
    color = nil
    label = nil
  end

  return icon, color, label
end

function M.get_status(window)
  local icon, color, label = M.get_status_icon(window)
  local parts = {}
  if icon then
    if color then
      table.insert(parts, { Foreground = { AnsiColor = color } })
    end
    table.insert(parts, { Text = icon })
  end
  if label then
    if color then
      table.insert(parts, { Foreground = { AnsiColor = color } })
    end
    table.insert(parts, { Text = ' ' .. label })
  end
  return wezterm.format(parts)
end

function M.trigger_prompt(window, pane)
  window:perform_action(
    wezterm.action.PromptInputLine({
      description = wezterm.format({
        { Attribute = { Intensity = 'Bold' } },
        { Foreground = { AnsiColor = 'Fuchsia' } },
        { Text = '󰚩 Ask AI for Nushell command' },
        { Text = '\n' },
        { Attribute = { Intensity = 'Normal' } },
        { Foreground = { AnsiColor = 'Silver' } },
        { Text = 'e.g. "list only directories"' },
      }),
      prompt = wezterm.format({
        { Foreground = { AnsiColor = 'Green' } },
        { Text = '> ' },
      }),
      action = wezterm.action_callback(function(win, p, line)
        if line and line ~= '' then
          M.trigger_ai_shell(win, p, line)
        end
      end),
    }),
    pane
  )
end

return M