refactor(wezterm): remove ai shell and simplify config
fc2a3baefa9af62c0a4fb1e845a99fa5f7fc1fcd
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 7a212d1e4305
bugabingas dorkfiles
fc2a3baefa9af62c0a4fb1e845a99fa5f7fc1fcd
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+100 / −560 text lines
deleted file mode 100644+0 / −187 text lines
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 = 300local 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]endfunction 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)endfunction 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')endfunction 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, labelendfunction 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)endfunction 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 )endreturn Mdeleted file mode 100644+0 / −182 text lines
local M = {}--[[ NUSHELL SYSTEM PROMPT ===================== This prompt instructs the AI to generate valid Nushell commands. Update this when Nushell syntax changes significantly. KEY CRAFTING PRINCIPLES: ------------------------- 1. Be explicit about Nushell version (0.110+) 2. List common Bash-to-Nushell equivalents 3. Emphasize: NO markdown, NO code fences, raw command only 4. Include examples of modern Nushell syntax (pipelines, $env, etc.) 5. Warn about common pitfalls (> is comparison, not redirection) RESOURCES FOR UPDATING: ----------------------- - https://www.nushell.sh/book/thinking_in_nu.html - https://www.nushell.sh/book/coming_from_bash.html - https://www.nushell.sh/book/cheat_sheet.html - https://www.nushell.sh/book/quick_tour.html TESTING UPDATES: ---------------- After updating, test with queries like: - "list files in current directory" - "find all .lua files recursively" - "show only directories in current folder" - "get the 5 largest files in current directory"]]M.prompt = [===[You are a Nushell (0.110+) expert. Generate ONLY raw shell commands valid in modern Nushell 0.110+.KEY NUSHELL CONCEPTS:- Nushell is NOT Bash. > is comparison operator, not redirection- Use pipeline syntax: "output | filter | transform"- Every command returns structured data (tables, lists, records), not plain text- Variables are immutable by default: use `let` not `=`. Use `mut` for mutable state- Command substitution / subexpression: use `(cmd)` NOT `cmd` or `$(cmd)`- String interpolation: $"text ($variable)"- Environment variables: $env.VAR (not $VAR). Set with: $env.VAR = value- $nu contains runtime info: config-path, env-path, current-exe, is-interactive- $env.config contains Nushell configuration- $in is current pipeline input- $it is current row/element in closures like `where` and `each`- Redirection: use `| save file` not `> file`. Use `out>` or `o>` for stdout where appropriate- External commands: prefix with ^ to run system command explicitly- Lists: [item1 item2], access with .index (not [index])- Records: {key: value}, access with .key- Tables: [[col1 col2]; [1 2]] or [{x: 1}, {x: 2}]- Conditionals/filters: use `where column == value` or `where $it =~ pattern` instead of grep- File globbing: **/*.rs; use `ls **/*.rs` for metadata table or `glob **/*.rs` for paths- Date handling: `date now`, `| into datetime`- Error handling: try/catch blocksBASH -> NUSHELL EQUIVALENTS:- $VAR -> $env.VAR- export VAR=val -> $env.VAR = val- echo $PATH -> $env.PATH- echo $? -> $env.LAST_EXIT_CODE- $(cmd) -> (cmd)- cd -> cd- ls -la -> ls --long --all or ls -la- cat file -> open --raw file- grep pattern -> where $it =~ pattern- find . -name "*.rs" -> ls **/*.rs or glob **/*.rs- [ -f file ] -> $file | path exists- basename path -> $path | path parse | get stem- > file -> | save file- >> file -> | save --append file- >/dev/null -> | ignore- 2>&1 -> o+e>| (external commands only)- sed/awk -> str replace, parse, split, each, reduce, select, update- && / || -> prefer `;`, `try/catch`, `if`, or inspect $env.LAST_EXIT_CODEPIPELINE PATTERNS:- Filter rows: ls | where size > 1mb- Filter dirs: ls | where type == dir- Regex filter: ls | where name =~ "^nu"- Select columns: ls | select name size- Insert computed column: ls | insert big {|row| $row.size > 1mb }- Update column: ls | update name { path parse | get stem }- Iterate list: [1 2 3] | each {|x| $x * 2 }- Filter list: [1 2 3] | where $it > 2- Reduce list: [1 2 3] | reduce {|val acc| $acc + $val }REDIRECTION:- Write file: "hello" | save output.txt- Append file: "hello" | save --append output.txt- Discard output: command | ignore- Redirect stderr from external command: ^external_cmd e>| ignore- Redirect stdout+stderr from external command: ^external_cmd o+e>| ignore- Redirect stdout+stderr to file from external command: ^external_cmd o+e>| error.log- e>| and o+e>| work for external commands only, not internal Nushell commands- For internal command errors, use try/catch instead of stderr redirectionVARIABLES:- Immutable: let x = 10- List: let items = [1 2 3]- Record: let cfg = {theme: dark}- Compile-time constant: const PI = 3.14159- Mutable: mut y = 0; $y = 5- Env path prepend: $env.PATH = ($env.PATH | prepend "/custom")- Do not assign immutable vars with `$x = ...` unless declared `mut`STRINGS:- Literal string: 'hello world'- Escaped string: "hello\nworld"- Interpolation: $"hello, ($name)!"- Raw/no escapes: $'raw string'#- Raw with quotes: r#'can have "quotes"'#DATA TYPES:- int: 42- float: 3.14- bool: true or false- nothing/null: null- list: [1 2 3]- record: {a: 1, b: 2}- table: [{x: 1}, {x: 2}]- filesize: 10mb, 1gb- duration: 5sec, 2min- inclusive range: 1..10- exclusive range: 1..<10FUNCTIONS AND ALIASES:- Custom command: def greet [name: string] { $"Hello, ($name)!" }- Typed args: def add [a: int, b: int] { $a + $b }- Rest args: def sum [...nums: int] { $nums | math sum }- Alias: alias name = cmdCONTROL FLOW:- If: if $cond { "yes" } else { "no" }- Match: match $val { 1 => "one", 2 => "two", _ => "other" }- For loop: for i in 1..10 { print $i }- While loop: while $condition { ... }- Try/catch: try { risky_operation } catch {|err| print $err.msg }- Error: error make "something failed"- Structured error: error make {msg: "failed", help: "try this"}- Catch error record commonly has msg, debug, json fields; no direct code fieldEXTERNAL COMMANDS:- Explicit external: ^ls -la- Explicit external echo: ^echo "hello"- Spread args: let args = ["-la" "*.nu"]; ^ls ...$args- Use ^ when command name may conflict with an internal Nushell commandMODULES:- Define module: module utils { export def add [a: int, b: int] { $a + $b } }- Use exported command: use utils add; add 5 3FILES:- Glob current dir: ls *.nu- Recursive glob: ls **/*.rs- Open parsed structured data: open file.json- Open raw text: open --raw file.txt- Check path exists: "/tmp" | path existsRUNNING NUSHELL:- Run script file: nu script.nu- Run one-liner: nu -c 'ls | where size > 1mb'COMMON MISTAKES TO AVOID:- Do NOT use Bash `2>&1`; use `o+e>|` for external commands- Do NOT use `$err.code`; use `$err.msg` or inspect `$err.json`- Do NOT write `ls | e>| ignore`; internal commands do not support stderr redirection- Do NOT use `$variable` for env vars; use `$env.variable`- Do NOT use `$(cmd)`; use `(cmd)`- Do NOT forget `^` before external commands when ambiguity is possible- Do NOT pipe structured data expecting plain strings; select/get columns explicitly- Do NOT use deprecated `$config`; use `$env.config`- Do NOT assign to immutable vars; use `mut` or `$env.var`- Do NOT use `test -f file`; use `$file | path exists`IMPORTANT:- Output ONLY the raw command. No markdown, no code fences, no backticks, no explanation.- If multiple commands are needed, separate with semicolons or newlines.- Prefer structured Nushell-native commands over Bash-style text processing.]===]return M+0 / −22 text lines
+6 / −2 text lines
+2 / −0 text lines
+0 / −11 text lines
+1 / −14 text lines
+1 / −7 text lines
+7 / −2 text lines
+48 / −42 text lines
---@param t1 table---@param t2 table---@return table tlocal function deep_merge_table( t1, t2 ) for k, v in pairs( t2 ) do if type( v ) == 'table' then if type( t1[k] or false ) == 'table' then deep_merge_table( t1[k] or {}, t2[k] or {} ) else t1[k] = v end else t1[k] = v end endlocal wez = require 'wezterm' return t1local presentation_active = falselocal presentation_prev_font_weightlocal presentation_prev_font_sizelocal function ensure_font_override( config, overrides ) if not overrides.font then overrides.font = deep_copy( config.font or {} ) end if not overrides.font.font then overrides.font.font = {} end if not overrides.font.font[1] and config.font and config.font.font then overrides.font.font[1] = deep_copy( config.font.font[1] ) end return overrides.font.font[1]end local id = win:window_id() local font = ensure_font_override( config, overrides ) presentation_active = true require 'wezterm'.emit( 'bugabinga.presentation.activate', win ) return overrides local overrides = win:get_config_overrides() or {} if presentation_active then overrides.font.font[1].weight = presentation_prev_font_weight overrides.font_size = presentation_prev_font_size win:toggle_fullscreen() presentation_active = false require 'wezterm'.emit( 'bugabinga.presentation.deactivate', win )+7 / −30 text lines
local last_palette_refresh = 0 -- Workspace contents change slowly, but update-status runs often for spinners. -- Cache the expensive mux-wide scan and keep animation work local to tabs. local current_time = now() if workspace_summary_cache.value and current_time - workspace_summary_cache.at < WORKSPACE_SUMMARY_TTL_SECONDS then return workspace_summary_cache.value end workspace_summary_cache = { at = current_time, value = summaries } local id = tab.tab_id or tab.tab_index or stable_tab_programs[id] badge, color = progress_badge( tab.active_pane.progress )+15 / −35 text lines
cfg.font = wez.font_with_fallback { 'JetBrains Mono', } cfg.font_rules = { -- the goal is to make comments in neovim look beautiful -- because comments are the true GOAT of code { italic = true, intensity = 'Bold', font = wez.font_with_fallback { { family = 'JetBrains Mono', weight = 'Bold', style = 'Italic', }, }, }, -- this gives string values in neovim a special touch { italic = true, intensity = 'Normal', font = wez.font_with_fallback { { family = 'JetBrains Mono', style = 'Italic', }, }, }, }+1 / −10 text lines
+12 / −16 text lines
wezterm.log_error( "Child process '" .. cmd .. "' failed with stderr: '" .. stderr .. "'" ) wezterm.log_error( "Child process '" .. table.concat( args, ' ' ) .. "' failed with stderr: '" .. stderr .. "'" ) local stdout = run_child_process( zoxide_path .. ' query -l ' ) local stdout = run_child_process { zoxide_path, 'query', '-l' } run_child_process( zoxide_path .. ' add ' .. path ) run_child_process { zoxide_path, 'add', path } local args = { 'wezterm', 'start', '--always-new-process', '--workspace', workspace } local args = { os.getenv 'WEZTERM_EXECUTABLE' or 'wezterm', 'start', '--always-new-process', '--workspace', workspace }