file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
crates/avante-html2md/src/lib.rs
Rust
use htmd::HtmlToMarkdown; use mlua::prelude::*; use std::error::Error; #[derive(Debug)] enum MyError { HtmlToMd(String), Request(String), } impl std::fmt::Display for MyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { MyError::HtmlToMd(e) => write!(f, "HTML to Markdown error: {e}"), MyError::Request(e) => write!(f, "Request error: {e}"), } } } impl Error for MyError {} fn do_html2md(html: &str) -> Result<String, MyError> { let converter = HtmlToMarkdown::builder() .skip_tags(vec!["script", "style", "header", "footer"]) .build(); let md = converter .convert(html) .map_err(|e| MyError::HtmlToMd(e.to_string()))?; Ok(md) } fn do_fetch_md(url: &str) -> Result<String, MyError> { let mut headers = reqwest::header::HeaderMap::new(); headers.insert( reqwest::header::USER_AGENT, reqwest::header::HeaderValue::from_static("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"), ); let client = reqwest::blocking::Client::builder() .default_headers(headers) .build() .map_err(|e| MyError::Request(e.to_string()))?; let response = client .get(url) .send() .map_err(|e| MyError::Request(e.to_string()))?; let body = response .text() .map_err(|e| MyError::Request(e.to_string()))?; let html = body.trim().to_string(); let md = do_html2md(&html)?; Ok(md) } #[mlua::lua_module] fn avante_html2md(lua: &Lua) -> LuaResult<LuaTable> { let exports = lua.create_table()?; exports.set( "fetch_md", lua.create_function(move |_, url: String| -> LuaResult<String> { do_fetch_md(&url).map_err(|e| mlua::Error::RuntimeError(e.to_string())) })?, )?; exports.set( "html2md", lua.create_function(move |_, html: String| -> LuaResult<String> { do_html2md(&html).map_err(|e| mlua::Error::RuntimeError(e.to_string())) })?, )?; Ok(exports) } #[cfg(test)] mod tests { use super::*; #[test] fn test_fetch_md() { let md = do_fetch_md("https://github.com/yetone/avante.nvim").unwrap(); println!("{md}"); } }
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-c-defs.scm
Scheme
;; Capture extern functions, variables, public classes, and methods (function_definition (storage_class_specifier) @extern ) @function (struct_specifier) @struct (struct_specifier body: (field_declaration_list (field_declaration declarator: (field_identifier))? @class_variable ) ) (declaration (storage_class_specifier) @extern ) @variable
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-c-sharp-defs.scm
Scheme
(class_declaration name: (identifier) @class (parameter_list)? @method) ;; Primary constructor (record_declaration name: (identifier) @class (parameter_list)? @method) ;; Primary constructor (interface_declaration name: (identifier) @class) (method_declaration) @method (constructor_declaration) @method (property_declaration) @class_variable (field_declaration (variable_declaration (variable_declarator))) @class_variable (enum_declaration body: (enum_member_declaration_list (enum_member_declaration) @enum_item))
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-cpp-defs.scm
Scheme
;; Capture functions, variables, nammespaces, classes, methods, and enums (namespace_definition) @namespace (function_definition) @function (class_specifier) @class (class_specifier body: (field_declaration_list (declaration declarator: (function_declarator))? @method (field_declaration declarator: (function_declarator))? @method (function_definition)? @method (function_declarator)? @method (field_declaration declarator: (field_identifier))? @class_variable ) ) (struct_specifier) @struct (struct_specifier body: (field_declaration_list (declaration declarator: (function_declarator))? @method (field_declaration declarator: (function_declarator))? @method (function_definition)? @method (function_declarator)? @method (field_declaration declarator: (field_identifier))? @class_variable ) ) ((declaration type: (_))) @variable (enumerator_list ((enumerator) @enum_item))
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-elixir-defs.scm
Scheme
; * modules and protocols (call target: (identifier) @ignore (arguments (alias) @class) (#match? @ignore "^(defmodule|defprotocol)$")) ; * functions (call target: (identifier) @ignore (arguments [ ; zero-arity functions with no parentheses (identifier) @method ; regular function clause (call target: (identifier) @method) ; function clause with a guard clause (binary_operator left: (call target: (identifier) @method) operator: "when") ]) (#match? @ignore "^(def|defdelegate|defguard|defn)$"))
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-go-defs.scm
Scheme
;; Capture top-level functions and struct definitions (source_file (var_declaration (var_spec) @variable ) ) (source_file (const_declaration (const_spec) @variable ) ) (source_file (function_declaration) @function ) (source_file (type_declaration (type_spec (struct_type)) @class ) ) (source_file (type_declaration (type_spec (struct_type (field_declaration_list (field_declaration) @class_variable))) ) ) (source_file (method_declaration) @method )
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-java-defs.scm
Scheme
;; Capture exported functions, arrow functions, variables, classes, and method definitions (class_declaration name: (identifier) @class) (interface_declaration name: (identifier) @class) (enum_declaration name: (identifier) @enum) (enum_constant name: (identifier) @enum_item) (class_body (field_declaration) @class_variable) (class_body (constructor_declaration) @method) (class_body (method_declaration) @method) (interface_body (method_declaration) @method)
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-javascript-defs.scm
Scheme
;; Capture exported functions, arrow functions, variables, classes, and method definitions (export_statement declaration: (lexical_declaration (variable_declarator) @variable ) ) (export_statement declaration: (function_declaration) @function ) (export_statement declaration: (class_declaration body: (class_body (field_definition) @class_variable ) ) ) (export_statement declaration: (class_declaration body: (class_body (method_definition) @method ) ) )
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-lua-defs.scm
Scheme
;; Capture function and method definitions (variable_list) @variable (function_declaration) @function
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-php-defs.scm
Scheme
;; Capture exported functions, arrow functions, variables, classes, and method definitions (class_declaration) @class (interface_declaration) @class (function_definition) @function (assignment_expression) @assignment (const_declaration (const_element (name) @variable)) (_ body: (declaration_list (property_declaration) @class_variable)) (_ body: (declaration_list (method_declaration) @method))
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-python-defs.scm
Scheme
;; Capture top-level functions, class, and method definitions (module (expression_statement (assignment) @assignment ) ) (module (function_definition) @function ) (module (class_definition body: (block (expression_statement (assignment) @class_assignment ) ) ) ) (module (class_definition body: (block (function_definition) @method ) ) )
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-ruby-defs.scm
Scheme
;; Capture top-level methods, class definitions, and methods within classes (class (body_statement (call)? @class_call (assignment)? @class_assignment (method)? @method ) ) @class (program (method) @function ) (program (assignment) @assignment ) (module) @module (module (body_statement (call)? @class_call (assignment)? @class_assignment (method)? @method ) )
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-rust-defs.scm
Scheme
;; Capture public functions, structs, methods, and variable definitions (function_item) @function (impl_item body: (declaration_list (function_item) @method ) ) (struct_item) @class (struct_item body: (field_declaration_list (field_declaration) @class_variable ) ) (enum_item body: (enum_variant_list (enum_variant) @enum_item ) ) (const_item) @variable (static_item) @variable
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-scala-defs.scm
Scheme
(class_definition name: (identifier) @class) (object_definition name: (identifier) @class) (trait_definition name: (identifier) @class) (simple_enum_case name: (identifier) @enum_item) (full_enum_case name: (identifier) @enum_item) (template_body (function_definition) @method ) (template_body (function_declaration) @method ) (template_body (val_definition) @class_variable ) (template_body (val_declaration) @class_variable ) (template_body (var_definition) @class_variable ) (template_body (var_declaration) @class_variable ) (compilation_unit (function_definition) @function ) (compilation_unit (val_definition) @variable ) (compilation_unit (var_definition) @variable )
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-swift-defs.scm
Scheme
(property_declaration) @variable (function_declaration) @function (class_declaration _? [ "struct" "class" ]) @class (class_declaration _? "enum" ) @enum (class_body (property_declaration) @class_variable) (class_body (function_declaration) @method) (class_body (init_declaration) @method) (protocol_declaration body: (protocol_body (protocol_function_declaration) @function)) (protocol_declaration body: (protocol_body (protocol_property_declaration) @class_variable)) (class_declaration body: (enum_class_body (enum_entry) @enum_item))
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-typescript-defs.scm
Scheme
;; Capture exported functions, arrow functions, variables, classes, and method definitions (export_statement declaration: (lexical_declaration (variable_declarator) @variable ) ) (export_statement declaration: (function_declaration) @function ) (export_statement declaration: (class_declaration body: (class_body (public_field_definition) @class_variable ) ) ) (interface_declaration body: (interface_body (property_signature) @class_variable ) ) (type_alias_declaration value: (object_type (property_signature) @class_variable ) ) (export_statement declaration: (class_declaration body: (class_body (method_definition) @method ) ) )
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/queries/tree-sitter-zig-defs.scm
Scheme
;; Capture functions, structs, methods, variable definitions, and unions in Zig (variable_declaration (identifier) (struct_declaration (container_field) @class_variable)) (variable_declaration (identifier) (struct_declaration (function_declaration name: (identifier) @method))) (variable_declaration (identifier) (enum_declaration (container_field type: (identifier) @enum_item))) (variable_declaration (identifier) (union_declaration (container_field name: (identifier) @union_item))) (source_file (function_declaration) @function) (source_file (variable_declaration (identifier) @variable))
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-repo-map/src/lib.rs
Rust
#![allow(clippy::unnecessary_map_or)] use mlua::prelude::*; use std::cell::RefCell; use std::collections::BTreeMap; use tree_sitter::{Node, Parser, Query, QueryCursor}; use tree_sitter_language::LanguageFn; #[derive(Debug, Clone)] pub struct Func { pub name: String, pub params: String, pub return_type: String, pub accessibility_modifier: Option<String>, } #[derive(Debug, Clone)] pub struct Class { pub type_name: String, pub name: String, pub methods: Vec<Func>, pub properties: Vec<Variable>, pub visibility_modifier: Option<String>, } #[derive(Debug, Clone)] pub struct Enum { pub name: String, pub items: Vec<Variable>, } #[derive(Debug, Clone)] pub struct Union { pub name: String, pub items: Vec<Variable>, } #[derive(Debug, Clone)] pub struct Variable { pub name: String, pub value_type: String, } #[derive(Debug, Clone)] pub enum Definition { Func(Func), Class(Class), Module(Class), Enum(Enum), Variable(Variable), Union(Union), // TODO: Namespace support } fn get_ts_language(language: &str) -> Option<LanguageFn> { match language { "rust" => Some(tree_sitter_rust::LANGUAGE), "python" => Some(tree_sitter_python::LANGUAGE), "php" => Some(tree_sitter_php::LANGUAGE_PHP), "java" => Some(tree_sitter_java::LANGUAGE), "javascript" => Some(tree_sitter_javascript::LANGUAGE), "typescript" => Some(tree_sitter_typescript::LANGUAGE_TSX), "go" => Some(tree_sitter_go::LANGUAGE), "c" => Some(tree_sitter_c::LANGUAGE), "cpp" => Some(tree_sitter_cpp::LANGUAGE), "lua" => Some(tree_sitter_lua::LANGUAGE), "ruby" => Some(tree_sitter_ruby::LANGUAGE), "zig" => Some(tree_sitter_zig::LANGUAGE), "scala" => Some(tree_sitter_scala::LANGUAGE), "swift" => Some(tree_sitter_swift::LANGUAGE), "elixir" => Some(tree_sitter_elixir::LANGUAGE), "csharp" => Some(tree_sitter_c_sharp::LANGUAGE), _ => None, } } const C_QUERY: &str = include_str!("../queries/tree-sitter-c-defs.scm"); const CPP_QUERY: &str = include_str!("../queries/tree-sitter-cpp-defs.scm"); const GO_QUERY: &str = include_str!("../queries/tree-sitter-go-defs.scm"); const JAVA_QUERY: &str = include_str!("../queries/tree-sitter-java-defs.scm"); const JAVASCRIPT_QUERY: &str = include_str!("../queries/tree-sitter-javascript-defs.scm"); const LUA_QUERY: &str = include_str!("../queries/tree-sitter-lua-defs.scm"); const PYTHON_QUERY: &str = include_str!("../queries/tree-sitter-python-defs.scm"); const PHP_QUERY: &str = include_str!("../queries/tree-sitter-php-defs.scm"); const RUST_QUERY: &str = include_str!("../queries/tree-sitter-rust-defs.scm"); const ZIG_QUERY: &str = include_str!("../queries/tree-sitter-zig-defs.scm"); const TYPESCRIPT_QUERY: &str = include_str!("../queries/tree-sitter-typescript-defs.scm"); const RUBY_QUERY: &str = include_str!("../queries/tree-sitter-ruby-defs.scm"); const SCALA_QUERY: &str = include_str!("../queries/tree-sitter-scala-defs.scm"); const SWIFT_QUERY: &str = include_str!("../queries/tree-sitter-swift-defs.scm"); const ELIXIR_QUERY: &str = include_str!("../queries/tree-sitter-elixir-defs.scm"); const CSHARP_QUERY: &str = include_str!("../queries/tree-sitter-c-sharp-defs.scm"); fn get_definitions_query(language: &str) -> Result<Query, String> { let ts_language = get_ts_language(language); if ts_language.is_none() { return Err(format!("Unsupported language: {language}")); } let ts_language = ts_language.unwrap(); let contents = match language { "c" => C_QUERY, "cpp" => CPP_QUERY, "go" => GO_QUERY, "java" => JAVA_QUERY, "javascript" => JAVASCRIPT_QUERY, "lua" => LUA_QUERY, "php" => PHP_QUERY, "python" => PYTHON_QUERY, "rust" => RUST_QUERY, "zig" => ZIG_QUERY, "typescript" => TYPESCRIPT_QUERY, "ruby" => RUBY_QUERY, "scala" => SCALA_QUERY, "swift" => SWIFT_QUERY, "elixir" => ELIXIR_QUERY, "csharp" => CSHARP_QUERY, _ => return Err(format!("Unsupported language: {language}")), }; let query = Query::new(&ts_language.into(), contents) .unwrap_or_else(|e| panic!("Failed to parse query for {language}: {e}")); Ok(query) } fn get_closest_ancestor_name(node: &Node, source: &str) -> String { let mut parent = node.parent(); while let Some(parent_node) = parent { let name_node = parent_node.child_by_field_name("name"); if let Some(name_node) = name_node { return get_node_text(&name_node, source.as_bytes()).to_string(); } parent = parent_node.parent(); } String::new() } fn find_ancestor_by_type<'a>(node: &'a Node, parent_type: &str) -> Option<Node<'a>> { let mut parent = node.parent(); while let Some(parent_node) = parent { if parent_node.kind() == parent_type { return Some(parent_node); } parent = parent_node.parent(); } None } fn find_first_ancestor_by_types<'a>( node: &'a Node, possible_parent_types: &[&str], ) -> Option<Node<'a>> { let mut parent = node.parent(); while let Some(parent_node) = parent { if possible_parent_types.contains(&parent_node.kind()) { return Some(parent_node); } parent = parent_node.parent(); } None } fn find_descendant_by_type<'a>(node: &'a Node, child_type: &str) -> Option<Node<'a>> { let mut cursor = node.walk(); for i in 0..node.descendant_count() { cursor.goto_descendant(i); let node = cursor.node(); if node.kind() == child_type { return Some(node); } } None } fn ruby_method_is_private<'a>(node: &'a Node, source: &'a [u8]) -> bool { let mut prev_sibling = node.prev_sibling(); while let Some(prev_sibling_node) = prev_sibling { if prev_sibling_node.kind() == "identifier" { let text = prev_sibling_node.utf8_text(source).unwrap_or_default(); if text == "private" { return true; } else if text == "public" || text == "protected" { return false; } } else if prev_sibling_node.kind() == "class" || prev_sibling_node.kind() == "module" { return false; } prev_sibling = prev_sibling_node.prev_sibling(); } false } fn find_child_by_type<'a>(node: &'a Node, child_type: &str) -> Option<Node<'a>> { node.children(&mut node.walk()) .find(|child| child.kind() == child_type) } // Zig-specific function to find the parent variable declaration fn zig_find_parent_variable_declaration_name<'a>( node: &'a Node, source: &'a [u8], ) -> Option<String> { let vardec = find_ancestor_by_type(node, "variable_declaration"); if let Some(vardec) = vardec { // Find the identifier child node, which represents the class name let identifier_node = find_child_by_type(&vardec, "identifier"); if let Some(identifier_node) = identifier_node { return Some(get_node_text(&identifier_node, source)); } } None } fn zig_is_declaration_public<'a>(node: &'a Node, declaration_type: &str, source: &'a [u8]) -> bool { let declaration = find_ancestor_by_type(node, declaration_type); if let Some(declaration) = declaration { let declaration_text = get_node_text(&declaration, source); return declaration_text.starts_with("pub"); } false } fn zig_is_variable_declaration_public<'a>(node: &'a Node, source: &'a [u8]) -> bool { zig_is_declaration_public(node, "variable_declaration", source) } fn zig_is_function_declaration_public<'a>(node: &'a Node, source: &'a [u8]) -> bool { zig_is_declaration_public(node, "function_declaration", source) } fn zig_find_type_in_parent<'a>(node: &'a Node, source: &'a [u8]) -> Option<String> { // First go to the parent and then get the child_by_field_name "type" if let Some(parent) = node.parent() { if let Some(type_node) = parent.child_by_field_name("type") { return Some(get_node_text(&type_node, source)); } } None } fn csharp_is_primary_constructor(node: &Node) -> bool { node.kind() == "parameter_list" && node.parent().map_or(false, |n| { n.kind() == "class_declaration" || n.kind() == "record_declaration" }) } fn csharp_find_parent_type_node<'a>(node: &'a Node) -> Option<Node<'a>> { find_first_ancestor_by_types(node, &["class_declaration", "record_declaration"]) } fn ex_find_parent_module_declaration_name<'a>(node: &'a Node, source: &'a [u8]) -> Option<String> { let mut parent = node.parent(); while let Some(parent_node) = parent { if parent_node.kind() == "call" { let text = get_node_text(&parent_node, source); if text.starts_with("defmodule ") { let arguments_node = find_child_by_type(&parent_node, "arguments"); if let Some(arguments_node) = arguments_node { return Some(get_node_text(&arguments_node, source)); } } } parent = parent_node.parent(); } None } fn ruby_find_parent_module_declaration_name<'a>( node: &'a Node, source: &'a [u8], ) -> Option<String> { let mut path_parts = Vec::new(); let mut current = Some(*node); while let Some(current_node) = current { if current_node.kind() == "module" || current_node.kind() == "class" { if let Some(name_node) = current_node.child_by_field_name("name") { path_parts.push(get_node_text(&name_node, source)); } } current = current_node.parent(); } if path_parts.is_empty() { None } else { path_parts.reverse(); Some(path_parts.join("::")) } } fn get_node_text<'a>(node: &'a Node, source: &'a [u8]) -> String { node.utf8_text(source).unwrap_or_default().to_string() } fn get_node_type<'a>(node: &'a Node, source: &'a [u8]) -> String { let predefined_type_node = find_descendant_by_type(node, "predefined_type"); if let Some(type_node) = predefined_type_node { return type_node.utf8_text(source).unwrap().to_string(); } let value_type_node = node.child_by_field_name("type"); value_type_node .map(|n| n.utf8_text(source).unwrap().to_string()) .unwrap_or_default() } fn is_first_letter_uppercase(name: &str) -> bool { if name.is_empty() { return false; } name.chars().next().unwrap().is_uppercase() } // Given a language, parse the given source code and return exported definitions fn extract_definitions(language: &str, source: &str) -> Result<Vec<Definition>, String> { let ts_language = get_ts_language(language); if ts_language.is_none() { return Ok(vec![]); } let ts_language = ts_language.unwrap(); let mut definitions = Vec::new(); let mut parser = Parser::new(); parser .set_language(&ts_language.into()) .unwrap_or_else(|_| panic!("Failed to set language for {language}")); let tree = parser .parse(source, None) .unwrap_or_else(|| panic!("Failed to parse source code for {language}")); let root_node = tree.root_node(); let query = get_definitions_query(language)?; let mut query_cursor = QueryCursor::new(); let captures = query_cursor.captures(&query, root_node, source.as_bytes()); let mut class_def_map: BTreeMap<String, RefCell<Class>> = BTreeMap::new(); let mut enum_def_map: BTreeMap<String, RefCell<Enum>> = BTreeMap::new(); let mut union_def_map: BTreeMap<String, RefCell<Union>> = BTreeMap::new(); let ensure_class_def = |language: &str, name: &str, class_def_map: &mut BTreeMap<String, RefCell<Class>>| { let mut type_name = "class"; if language == "elixir" { type_name = "module"; } class_def_map.entry(name.to_string()).or_insert_with(|| { RefCell::new(Class { type_name: type_name.to_string(), name: name.to_string(), methods: vec![], properties: vec![], visibility_modifier: None, }) }); }; let ensure_module_def = |name: &str, class_def_map: &mut BTreeMap<String, RefCell<Class>>| { class_def_map.entry(name.to_string()).or_insert_with(|| { RefCell::new(Class { name: name.to_string(), type_name: "module".to_string(), methods: vec![], properties: vec![], visibility_modifier: None, }) }); }; let ensure_enum_def = |name: &str, enum_def_map: &mut BTreeMap<String, RefCell<Enum>>| { enum_def_map.entry(name.to_string()).or_insert_with(|| { RefCell::new(Enum { name: name.to_string(), items: vec![], }) }); }; let ensure_union_def = |name: &str, union_def_map: &mut BTreeMap<String, RefCell<Union>>| { union_def_map.entry(name.to_string()).or_insert_with(|| { RefCell::new(Union { name: name.to_string(), items: vec![], }) }); }; // Sometimes, multiple queries capture the same node with the same capture name. // We need to ensure that we only add the node to the definition map once. let mut captured_nodes: BTreeMap<String, Vec<usize>> = BTreeMap::new(); for (m, _) in captures { for capture in m.captures { let capture_name = &query.capture_names()[capture.index as usize]; let node = capture.node; let node_text = node.utf8_text(source.as_bytes()).unwrap(); let node_id = node.id(); if captured_nodes .get(*capture_name) .map_or(false, |v| v.contains(&node_id)) { continue; } captured_nodes .entry(String::from(*capture_name)) .or_default() .push(node_id); let name = match language { "cpp" => { if *capture_name == "class" { node.child_by_field_name("name") .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(node_text) .to_string() } else { let ident = find_descendant_by_type(&node, "field_identifier") .or_else(|| find_descendant_by_type(&node, "operator_name")) .or_else(|| find_descendant_by_type(&node, "identifier")) .map(|n| n.utf8_text(source.as_bytes()).unwrap()); if let Some(ident) = ident { let scope = node .child_by_field_name("declarator") .and_then(|n| n.child_by_field_name("declarator")) .and_then(|n| n.child_by_field_name("scope")); if let Some(scope_node) = scope { format!( "{}::{}", scope_node.utf8_text(source.as_bytes()).unwrap(), ident ) } else { ident.to_string() } } else { node_text.to_string() } } } "scala" => node .child_by_field_name("name") .or_else(|| node.child_by_field_name("pattern")) .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(node_text) .to_string(), "csharp" => { let mut identifier = node; // Handle primary constructors (they are direct children of *_declaration) if *capture_name == "method" && csharp_is_primary_constructor(&node) { identifier = node.parent().unwrap_or(node); } else if *capture_name == "class_variable" { identifier = find_descendant_by_type(&node, "variable_declarator").unwrap_or(node); } identifier .child_by_field_name("name") .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(node_text) .to_string() } "ruby" => { let name = node .child_by_field_name("name") .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(node_text) .to_string(); if *capture_name == "class" || *capture_name == "module" { ruby_find_parent_module_declaration_name(&node, source.as_bytes()) .unwrap_or(name) } else { name } } _ => node .child_by_field_name("name") .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(node_text) .to_string(), }; match *capture_name { "class" => { if !name.is_empty() { if language == "go" && !is_first_letter_uppercase(&name) { continue; } ensure_class_def(language, &name, &mut class_def_map); let visibility_modifier_node = find_child_by_type(&node, "visibility_modifier"); let visibility_modifier = visibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); let class_def = class_def_map.get_mut(&name).unwrap(); class_def.borrow_mut().visibility_modifier = if visibility_modifier.is_empty() { None } else { Some(visibility_modifier.to_string()) }; } } "module" => { if !name.is_empty() { ensure_module_def(&name, &mut class_def_map); } } "enum_item" => { let visibility_modifier_node = find_descendant_by_type(&node, "visibility_modifier"); let visibility_modifier = visibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); if language == "rust" && !visibility_modifier.contains("pub") { continue; } if language == "zig" && !zig_is_variable_declaration_public(&node, source.as_bytes()) { continue; } let mut enum_name = get_closest_ancestor_name(&node, source); if language == "zig" { enum_name = zig_find_parent_variable_declaration_name(&node, source.as_bytes()) .unwrap_or_default(); } if language == "scala" { if let Some(enum_node) = find_ancestor_by_type(&node, "enum_definition") { if let Some(name_node) = enum_node.child_by_field_name("name") { enum_name = name_node.utf8_text(source.as_bytes()).unwrap().to_string(); } } } if !enum_name.is_empty() && language == "go" && !is_first_letter_uppercase(&enum_name) { continue; } ensure_enum_def(&enum_name, &mut enum_def_map); let enum_def = enum_def_map.get_mut(&enum_name).unwrap(); let enum_type_node = find_descendant_by_type(&node, "type_identifier"); let enum_type = enum_type_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); let variable = Variable { name: name.to_string(), value_type: enum_type.to_string(), }; enum_def.borrow_mut().items.push(variable); } "union_item" => { if language != "zig" { continue; } if !zig_is_variable_declaration_public(&node, source.as_bytes()) { continue; } let union_name = zig_find_parent_variable_declaration_name(&node, source.as_bytes()) .unwrap_or_default(); ensure_union_def(&union_name, &mut union_def_map); let union_def = union_def_map.get_mut(&union_name).unwrap(); let union_type_node = find_descendant_by_type(&node, "type_identifier"); let union_type = union_type_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); let variable = Variable { name: name.to_string(), value_type: union_type.to_string(), }; union_def.borrow_mut().items.push(variable); } "method" => { // TODO: C++: Skip private/protected class/struct methods let visibility_modifier_node = find_descendant_by_type(&node, "visibility_modifier"); let visibility_modifier = visibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); if language == "swift" { if visibility_modifier.contains("private") { continue; } } if language == "java" { let modifier_node = find_descendant_by_type(&node, "modifiers"); if modifier_node.is_some() { let modifier_text = modifier_node.unwrap().utf8_text(source.as_bytes()).unwrap(); if modifier_text.contains("private") { continue; } } } if language == "rust" && !visibility_modifier.contains("pub") { continue; } if language == "zig" && !(zig_is_function_declaration_public(&node, source.as_bytes()) && zig_is_variable_declaration_public(&node, source.as_bytes())) { continue; } if language == "cpp" && find_descendant_by_type(&node, "destructor_name").is_some() { continue; } if !name.is_empty() && language == "go" && !is_first_letter_uppercase(&name) { continue; } if language == "csharp" { let csharp_visibility = find_descendant_by_type(&node, "modifier"); if csharp_visibility.is_none() && !csharp_is_primary_constructor(&node) { continue; } if csharp_visibility.is_some() { let csharp_visibility_text = csharp_visibility .unwrap() .utf8_text(source.as_bytes()) .unwrap(); if csharp_visibility_text == "private" { continue; } } } let mut params_node = node .child_by_field_name("parameters") .or_else(|| find_descendant_by_type(&node, "parameter_list")); let zig_function_node = find_ancestor_by_type(&node, "function_declaration"); if language == "zig" { params_node = zig_function_node .as_ref() .and_then(|n| find_child_by_type(n, "parameters")); } let ex_function_node = find_ancestor_by_type(&node, "call"); if language == "elixir" { params_node = ex_function_node .as_ref() .and_then(|n| find_child_by_type(n, "arguments")); } let params = params_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or("()"); let mut return_type_node = match language { "cpp" => node.child_by_field_name("type"), "csharp" => node.child_by_field_name("returns"), _ => node.child_by_field_name("return_type"), }; if language == "cpp" { let class_specifier_node = find_ancestor_by_type(&node, "class_specifier"); let type_identifier_node = class_specifier_node.and_then(|n| n.child_by_field_name("name")); if let Some(type_identifier_node) = type_identifier_node { let type_identifier_text = type_identifier_node.utf8_text(source.as_bytes()).unwrap(); if name == type_identifier_text { return_type_node = Some(type_identifier_node); } } } if language == "csharp" { let type_specifier_node = csharp_find_parent_type_node(&node); let type_identifier_node = type_specifier_node.and_then(|n| n.child_by_field_name("name")); if let Some(type_identifier_node) = type_identifier_node { let type_identifier_text = type_identifier_node.utf8_text(source.as_bytes()).unwrap(); if name == type_identifier_text { return_type_node = Some(type_identifier_node); } } } if return_type_node.is_none() { return_type_node = node.child_by_field_name("result"); } let mut return_type = "void".to_string(); if language == "elixir" { return_type = String::new(); } if return_type_node.is_some() { return_type = get_node_type(&return_type_node.unwrap(), source.as_bytes()); if return_type.is_empty() { return_type = return_type_node .unwrap() .utf8_text(source.as_bytes()) .unwrap_or("void") .to_string(); } } let impl_item_node = find_ancestor_by_type(&node, "impl_item"); let receiver_node = node.child_by_field_name("receiver"); let class_name = if language == "zig" { zig_find_parent_variable_declaration_name(&node, source.as_bytes()) .unwrap_or_default() } else if language == "elixir" { ex_find_parent_module_declaration_name(&node, source.as_bytes()) .unwrap_or_default() } else if language == "cpp" { find_ancestor_by_type(&node, "class_specifier") .or_else(|| find_ancestor_by_type(&node, "struct_specifier")) .and_then(|n| n.child_by_field_name("name")) .and_then(|n| n.utf8_text(source.as_bytes()).ok()) .unwrap_or("") .to_string() } else if language == "csharp" { csharp_find_parent_type_node(&node) .and_then(|n| n.child_by_field_name("name")) .and_then(|n| n.utf8_text(source.as_bytes()).ok()) .unwrap_or("") .to_string() } else if language == "ruby" { ruby_find_parent_module_declaration_name(&node, source.as_bytes()) .unwrap_or_default() } else if let Some(impl_item) = impl_item_node { let impl_type_node = impl_item.child_by_field_name("type"); impl_type_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or("") .to_string() } else if let Some(receiver) = receiver_node { let type_identifier_node = find_descendant_by_type(&receiver, "type_identifier"); type_identifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or("") .to_string() } else { get_closest_ancestor_name(&node, source).to_string() }; if language == "go" && !is_first_letter_uppercase(&class_name) { continue; } ensure_class_def(language, &class_name, &mut class_def_map); let class_def = class_def_map.get_mut(&class_name).unwrap(); let accessibility_modifier_node = find_descendant_by_type(&node, "accessibility_modifier"); let accessibility_modifier = if language == "ruby" { if ruby_method_is_private(&node, source.as_bytes()) { "private" } else { "" } } else { accessibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or("") }; let func = Func { name: name.to_string(), params: params.to_string(), return_type: return_type.to_string(), accessibility_modifier: if accessibility_modifier.is_empty() { None } else { Some(accessibility_modifier.to_string()) }, }; class_def.borrow_mut().methods.push(func); } "class_assignment" => { let visibility_modifier_node = find_descendant_by_type(&node, "visibility_modifier"); let visibility_modifier = visibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); if language == "swift" || language == "java" { if visibility_modifier.contains("private") { continue; } } if language == "java" { let modifier_node = find_descendant_by_type(&node, "modifiers"); if modifier_node.is_some() { let modifier_text = modifier_node.unwrap().utf8_text(source.as_bytes()).unwrap(); if modifier_text.contains("private") { continue; } } } if language == "rust" && !visibility_modifier.contains("pub") { continue; } let left_node = node.child_by_field_name("left"); let left = left_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); let value_type = get_node_type(&node, source.as_bytes()); let mut class_name = get_closest_ancestor_name(&node, source); if !class_name.is_empty() { if language == "ruby" { if let Some(namespaced_name) = ruby_find_parent_module_declaration_name(&node, source.as_bytes()) { class_name = namespaced_name; } } else if language == "go" && !is_first_letter_uppercase(&class_name) { continue; } } if class_name.is_empty() { continue; } ensure_class_def(language, &class_name, &mut class_def_map); let class_def = class_def_map.get_mut(&class_name).unwrap(); let variable = Variable { name: left.to_string(), value_type: value_type.to_string(), }; class_def.borrow_mut().properties.push(variable); } "class_variable" => { // TODO: C++: Skip private/protected class/struct variables let visibility_modifier_node = find_descendant_by_type(&node, "visibility_modifier"); let visibility_modifier = visibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); if language == "rust" && !visibility_modifier.contains("pub") { continue; } if language == "swift" || language == "java" { if visibility_modifier.contains("private") { continue; } } if language == "java" { let modifier_node = find_descendant_by_type(&node, "modifiers"); if modifier_node.is_some() { let modifier_text = modifier_node.unwrap().utf8_text(source.as_bytes()).unwrap(); if modifier_text.contains("private") { continue; } } } let value_type = get_node_type(&node, source.as_bytes()); if language == "zig" { // when top level class is not public, skip if !zig_is_variable_declaration_public(&node, source.as_bytes()) { continue; } } let mut class_name = get_closest_ancestor_name(&node, source); if language == "cpp" { class_name = find_ancestor_by_type(&node, "class_specifier") .or_else(|| find_ancestor_by_type(&node, "struct_specifier")) .and_then(|n| n.child_by_field_name("name")) .and_then(|n| n.utf8_text(source.as_bytes()).ok()) .unwrap_or("") .to_string(); } if language == "csharp" { let csharp_visibility = find_descendant_by_type(&node, "modifier"); if csharp_visibility.is_none() { continue; } let csharp_visibility_text = csharp_visibility .unwrap() .utf8_text(source.as_bytes()) .unwrap(); if csharp_visibility_text == "private" { continue; } } if language == "zig" { class_name = zig_find_parent_variable_declaration_name(&node, source.as_bytes()) .unwrap_or_default(); } if !class_name.is_empty() && language == "go" && !is_first_letter_uppercase(&class_name) { continue; } if class_name.is_empty() { continue; } if !name.is_empty() && language == "go" && !is_first_letter_uppercase(&name) { continue; } ensure_class_def(language, &class_name, &mut class_def_map); let class_def = class_def_map.get_mut(&class_name).unwrap(); let variable = Variable { name: name.to_string(), value_type: value_type.to_string(), }; class_def.borrow_mut().properties.push(variable); } "function" | "arrow_function" => { let visibility_modifier_node = find_descendant_by_type(&node, "visibility_modifier"); let visibility_modifier = visibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); if language == "swift" || language == "java" { if visibility_modifier.contains("private") { continue; } if node.parent().is_some() { continue; } } if language == "java" { let modifier_node = find_descendant_by_type(&node, "modifiers"); if modifier_node.is_some() { let modifier_text = modifier_node.unwrap().utf8_text(source.as_bytes()).unwrap(); if modifier_text.contains("private") { continue; } } } if language == "rust" && !visibility_modifier.contains("pub") { continue; } if language == "zig" { let variable_declaration_text = node.utf8_text(source.as_bytes()).unwrap_or(""); if !variable_declaration_text.contains("pub") { continue; } } if !name.is_empty() && language == "go" && !is_first_letter_uppercase(&name) { continue; } let impl_item_node = find_ancestor_by_type(&node, "impl_item"); if impl_item_node.is_some() { continue; } let class_specifier_node = find_ancestor_by_type(&node, "class_specifier"); if class_specifier_node.is_some() { continue; } let struct_specifier_node = find_ancestor_by_type(&node, "struct_specifier"); if struct_specifier_node.is_some() { continue; } let function_node = find_ancestor_by_type(&node, "function_declaration") .or_else(|| find_ancestor_by_type(&node, "function_definition")); if function_node.is_some() { continue; } let params_node = node .child_by_field_name("parameters") .or_else(|| find_descendant_by_type(&node, "parameter_list")); let params = params_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or("()"); let mut return_type = "void".to_string(); let return_type_node = match language { "cpp" => node.child_by_field_name("type"), _ => node .child_by_field_name("return_type") .or_else(|| node.child_by_field_name("result")), }; if return_type_node.is_some() { return_type = get_node_type(&return_type_node.unwrap(), source.as_bytes()); if return_type.is_empty() { return_type = return_type_node .unwrap() .utf8_text(source.as_bytes()) .unwrap_or("void") .to_string(); } } let accessibility_modifier_node = find_descendant_by_type(&node, "accessibility_modifier"); let accessibility_modifier = accessibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); let func = Func { name: name.to_string(), params: params.to_string(), return_type: return_type.to_string(), accessibility_modifier: if accessibility_modifier.is_empty() { None } else { Some(accessibility_modifier.to_string()) }, }; definitions.push(Definition::Func(func)); } "assignment" => { let visibility_modifier_node = find_descendant_by_type(&node, "visibility_modifier"); let visibility_modifier = visibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); if language == "swift" || language == "java" { if visibility_modifier.contains("private") { continue; } } if language == "java" { let modifier_node = find_descendant_by_type(&node, "modifiers"); if modifier_node.is_some() { let modifier_text = modifier_node.unwrap().utf8_text(source.as_bytes()).unwrap(); if modifier_text.contains("private") { continue; } } } if language == "rust" && !visibility_modifier.contains("pub") { continue; } let impl_item_node = find_ancestor_by_type(&node, "impl_item") .or_else(|| find_ancestor_by_type(&node, "class_declaration")) .or_else(|| find_ancestor_by_type(&node, "class_definition")); if impl_item_node.is_some() { continue; } let function_node = find_ancestor_by_type(&node, "function_declaration") .or_else(|| find_ancestor_by_type(&node, "function_definition")); if function_node.is_some() { continue; } let left_node = node.child_by_field_name("left"); let left = left_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); if !left.is_empty() && language == "go" && !is_first_letter_uppercase(left) { continue; } let value_type = get_node_type(&node, source.as_bytes()); let variable = Variable { name: left.to_string(), value_type: value_type.to_string(), }; definitions.push(Definition::Variable(variable)); } "variable" => { let visibility_modifier_node = find_descendant_by_type(&node, "visibility_modifier"); let visibility_modifier = visibility_modifier_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or(""); if language == "swift" { if visibility_modifier.contains("private") { continue; } } if language == "java" { let modifier_node = find_descendant_by_type(&node, "modifiers"); if modifier_node.is_some() { let modifier_text = modifier_node.unwrap().utf8_text(source.as_bytes()).unwrap(); if modifier_text.contains("private") { continue; } } } if language == "rust" && !visibility_modifier.contains("pub") { continue; } if language == "zig" && !zig_is_variable_declaration_public(&node, source.as_bytes()) { continue; } let impl_item_node = find_ancestor_by_type(&node, "impl_item") .or_else(|| find_ancestor_by_type(&node, "class_declaration")) .or_else(|| find_ancestor_by_type(&node, "class_definition")); if impl_item_node.is_some() { continue; } let function_node = find_ancestor_by_type(&node, "function_declaration") .or_else(|| find_ancestor_by_type(&node, "function_definition")); if function_node.is_some() { continue; } let value_node = node.child_by_field_name("value"); if value_node.is_some() { let value_type = value_node.unwrap().kind(); if value_type == "arrow_function" { let params_node = value_node.unwrap().child_by_field_name("parameters"); let params = params_node .map(|n| n.utf8_text(source.as_bytes()).unwrap()) .unwrap_or("()"); let mut return_type = "void".to_string(); let return_type_node = value_node.unwrap().child_by_field_name("return_type"); if return_type_node.is_some() { return_type = get_node_type(&return_type_node.unwrap(), source.as_bytes()); } let func = Func { name: name.to_string(), params: params.to_string(), return_type, accessibility_modifier: None, }; definitions.push(Definition::Func(func)); continue; } } let mut value_type = get_node_type(&node, source.as_bytes()); if language == "zig" { if let Some(zig_type) = zig_find_type_in_parent(&node, source.as_bytes()) { value_type = zig_type; } else { continue; }; } if !name.is_empty() && language == "go" && !is_first_letter_uppercase(&name) { continue; } let variable = Variable { name: name.to_string(), value_type: value_type.to_string(), }; definitions.push(Definition::Variable(variable)); } _ => {} } } } for (_, def) in class_def_map { let class_def = def.into_inner(); if language == "rust" { if let Some(visibility_modifier) = &class_def.visibility_modifier { if visibility_modifier.contains("pub") { definitions.push(Definition::Class(class_def)); } } } else { definitions.push(Definition::Class(class_def)); } } for (_, def) in enum_def_map { definitions.push(Definition::Enum(def.into_inner())); } for (_, def) in union_def_map { definitions.push(Definition::Union(def.into_inner())); } Ok(definitions) } fn stringify_function(func: &Func) -> String { let mut res = format!("func {}", func.name); if func.params.is_empty() { res = format!("{res}()"); } else { res = format!("{res}{}", func.params); } if !func.return_type.is_empty() { res = format!("{res} -> {}", func.return_type); } if let Some(modifier) = &func.accessibility_modifier { res = format!("{modifier} {res}"); } format!("{res};") } fn stringify_variable(variable: &Variable) -> String { let mut res = format!("var {}", variable.name); if !variable.value_type.is_empty() { res = format!("{res}:{}", variable.value_type); } format!("{res};") } fn stringify_enum_item(item: &Variable) -> String { let mut res = item.name.clone(); if !item.value_type.is_empty() { res = format!("{res}:{}", item.value_type); } format!("{res};") } fn stringify_union_item(item: &Variable) -> String { let mut res = item.name.clone(); if !item.value_type.is_empty() { res = format!("{res}:{}", item.value_type); } format!("{res};") } fn stringify_class(class: &Class) -> String { let mut res = format!("{} {}{{", class.type_name, class.name); for method in &class.methods { let method_str = stringify_function(method); res = format!("{res}{method_str}"); } for property in &class.properties { let property_str = stringify_variable(property); res = format!("{res}{property_str}"); } format!("{res}}};") } fn stringify_enum(enum_def: &Enum) -> String { let mut res = format!("enum {}{{", enum_def.name); for item in &enum_def.items { let item_str = stringify_enum_item(item); res = format!("{res}{item_str}"); } format!("{res}}};") } fn stringify_union(union_def: &Union) -> String { let mut res = format!("union {}{{", union_def.name); for item in &union_def.items { let item_str = stringify_union_item(item); res = format!("{res}{item_str}"); } format!("{res}}};") } fn stringify_definitions(definitions: &Vec<Definition>) -> String { let mut res = String::new(); for definition in definitions { match definition { Definition::Class(class) => res = format!("{res}{}", stringify_class(class)), Definition::Module(module) => res = format!("{res}{}", stringify_class(module)), Definition::Enum(enum_def) => res = format!("{res}{}", stringify_enum(enum_def)), Definition::Union(union_def) => res = format!("{res}{}", stringify_union(union_def)), Definition::Func(func) => res = format!("{res}{}", stringify_function(func)), Definition::Variable(variable) => { let variable_str = stringify_variable(variable); res = format!("{res}{variable_str}"); } } } res } pub fn get_definitions_string(language: &str, source: &str) -> LuaResult<String> { let definitions = extract_definitions(language, source).map_err(|e| LuaError::RuntimeError(e.to_string()))?; let stringified = stringify_definitions(&definitions); Ok(stringified) } #[mlua::lua_module] fn avante_repo_map(lua: &Lua) -> LuaResult<LuaTable> { let exports = lua.create_table()?; exports.set( "stringify_definitions", lua.create_function(move |_, (language, source): (String, String)| { get_definitions_string(language.as_str(), source.as_str()) })?, )?; Ok(exports) } #[cfg(test)] mod tests { use super::*; #[test] fn test_rust() { let source = r#" // This is a test comment pub const TEST_CONST: u32 = 1; pub static TEST_STATIC: u32 = 2; const INNER_TEST_CONST: u32 = 3; static INNER_TEST_STATIC: u32 = 4; pub(crate) struct TestStruct { pub test_field: String, inner_test_field: String, } impl TestStruct { pub fn test_method(&self, a: u32, b: u32) -> u32 { a + b } fn inner_test_method(&self, a: u32, b: u32) -> u32 { a + b } } struct InnerTestStruct { pub test_field: String, inner_test_field: String, } impl InnerTestStruct { pub fn test_method(&self, a: u32, b: u32) -> u32 { a + b } fn inner_test_method(&self, a: u32, b: u32) -> u32 { a + b } } pub enum TestEnum { TestEnumField1, TestEnumField2, } enum InnerTestEnum { InnerTestEnumField1, InnerTestEnumField2, } pub fn test_fn(a: u32, b: u32) -> u32 { let inner_var_in_func = 1; struct InnerStructInFunc { c: u32, } a + b + c } fn inner_test_fn(a: u32, b: u32) -> u32 { a + b } "#; let definitions = extract_definitions("rust", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var TEST_CONST:u32;var TEST_STATIC:u32;func test_fn(a: u32, b: u32) -> u32;class TestStruct{func test_method(&self, a: u32, b: u32) -> u32;var test_field:String;};"; assert_eq!(stringified, expected); } #[test] fn test_zig() { let source = r#" // This is a test comment pub const TEST_CONST: u32 = 1; pub var TEST_VAR: u32 = 2; const INNER_TEST_CONST: u32 = 3; var INNER_TEST_VAR: u32 = 4; pub const TestStruct = struct { test_field: []const u8, test_field2: u64, pub fn test_method(_: *TestStruct, a: u32, b: u32) u32 { return a + b; } fn inner_test_method(_: *TestStruct, a: u32, b: u32) u32 { return a + b; } }; const InnerTestStruct = struct { test_field: []const u8, test_field2: u64, pub fn test_method(_: *InnerTestStruct, a: u32, b: u32) u32 { return a + b; } fn inner_test_method(_: *InnerTestStruct, a: u32, b: u32) u32 { return a + b; } }; pub const TestEnum = enum { TestEnumField1, TestEnumField2, }; const InnerTestEnum = enum { InnerTestEnumField1, InnerTestEnumField2, }; pub const TestUnion = union { TestUnionField1: u32, TestUnionField2: u64, }; const InnerTestUnion = union { InnerTestUnionField1: u32, InnerTestUnionField2: u64, }; pub fn test_fn(a: u32, b: u32) u32 { const inner_var_in_func = 1; const InnerStructInFunc = struct { c: u32, }; _ = InnerStructInFunc; return a + b + inner_var_in_func; } fn inner_test_fn(a: u32, b: u32) u32 { return a + b; } "#; let definitions = extract_definitions("zig", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var TEST_CONST:u32;var TEST_VAR:u32;func test_fn() -> void;class TestStruct{func test_method(_: *TestStruct, a: u32, b: u32) -> void;var test_field:[]const u8;var test_field2:u64;};enum TestEnum{TestEnumField1;TestEnumField2;};union TestUnion{TestUnionField1;TestUnionField2;};"; assert_eq!(stringified, expected); } #[test] fn test_go() { let source = r#" // This is a test comment package main import "fmt" const TestConst string = "test" const innerTestConst string = "test" var TestVar string var innerTestVar string type TestStruct struct { TestField string innerTestField string } func (t *TestStruct) TestMethod(a int, b int) (int, error) { var InnerVarInFunc int = 1 type InnerStructInFunc struct { C int } return a + b, nil } func (t *TestStruct) innerTestMethod(a int, b int) (int, error) { return a + b, nil } type innerTestStruct struct { innerTestField string } func (t *innerTestStruct) testMethod(a int, b int) (int, error) { return a + b, nil } func (t *innerTestStruct) innerTestMethod(a int, b int) (int, error) { return a + b, nil } func TestFunc(a int, b int) (int, error) { return a + b, nil } func innerTestFunc(a int, b int) (int, error) { return a + b, nil } "#; let definitions = extract_definitions("go", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var TestConst:string;var TestVar:string;func TestFunc(a int, b int) -> (int, error);class TestStruct{func TestMethod(a int, b int) -> (int, error);var TestField:string;};"; assert_eq!(stringified, expected); } #[test] fn test_python() { let source = r#" # This is a test comment test_var: str = "test" class TestClass: def __init__(self, a, b): self.a = a self.b = b def test_method(self, a: int, b: int) -> int: inner_var_in_method: int = 1 return a + b def test_func(a: int, b: int) -> int: inner_var_in_func: str = "test" class InnerClassInFunc: def __init__(self, a, b): self.a = a self.b = b def test_method(self, a: int, b: int) -> int: return a + b def inne_func_in_func(a: int, b: int) -> int: return a + b return a + b "#; let definitions = extract_definitions("python", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var test_var:str;func test_func(a: int, b: int) -> int;class TestClass{func __init__(self, a, b) -> void;func test_method(self, a: int, b: int) -> int;};"; assert_eq!(stringified, expected); } #[test] fn test_typescript() { let source = r#" // This is a test comment export const testVar: string = "test"; const innerTestVar: string = "test"; export class TestClass { a: number; b: number; constructor(a: number, b: number) { this.a = a; this.b = b; } testMethod(a: number, b: number): number { const innerConstInMethod: number = 1; function innerFuncInMethod(a: number, b: number): number { return a + b; } return a + b; } } class InnerTestClass { a: number; b: number; } export function testFunc(a: number, b: number) { const innerConstInFunc: number = 1; function innerFuncInFunc(a: number, b: number): number { return a + b; } return a + b; } export const testFunc2 = (a: number, b: number) => { return a + b; } export const testFunc3 = (a: number, b: number): number => { return a + b; } function innerTestFunc(a: number, b: number) { return a + b; } "#; let definitions = extract_definitions("typescript", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var testVar:string;func testFunc(a: number, b: number) -> void;func testFunc2(a: number, b: number) -> void;func testFunc3(a: number, b: number) -> number;class TestClass{func constructor(a: number, b: number) -> void;func testMethod(a: number, b: number) -> number;var a:number;var b:number;};" ; assert_eq!(stringified, expected); } #[test] fn test_javascript() { let source = r#" // This is a test comment export const testVar = "test"; const innerTestVar = "test"; export class TestClass { constructor(a, b) { this.a = a; this.b = b; } testMethod(a, b) { const innerConstInMethod = 1; function innerFuncInMethod(a, b) { return a + b; } return a + b; } } class InnerTestClass { constructor(a, b) { this.a = a; this.b = b; } } export const testFunc = function(a, b) { const innerConstInFunc = 1; function innerFuncInFunc(a, b) { return a + b; } return a + b; } export const testFunc2 = (a, b) => { return a + b; } export const testFunc3 = (a, b) => a + b; function innerTestFunc(a, b) { return a + b; } "#; let definitions = extract_definitions("javascript", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var testVar;var testFunc;func testFunc2(a, b) -> void;func testFunc3(a, b) -> void;class TestClass{func constructor(a, b) -> void;func testMethod(a, b) -> void;};"; assert_eq!(stringified, expected); } #[test] fn test_ruby() { let source = r#" # This is a test comment test_var = "test" def test_func(a, b) inner_var_in_func = "test" class InnerClassInFunc attr_accessor :a, :b def initialize(a, b) @a = a @b = b end def test_method(a, b) return a + b end end return a + b end class TestClass attr_accessor :a, :b def initialize(a, b) @a = a @b = b end def test_method(a, b) inner_var_in_method = 1 def inner_func_in_method(a, b) return a + b end return a + b end end "#; let definitions = extract_definitions("ruby", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); // FIXME: let expected = "var test_var;func test_func(a, b) -> void;class InnerClassInFunc{func initialize(a, b) -> void;func test_method(a, b) -> void;};class TestClass{func initialize(a, b) -> void;func test_method(a, b) -> void;};"; assert_eq!(stringified, expected); } #[test] fn test_ruby2() { let source = r#" # frozen_string_literal: true require('jwt') top_level_var = 1 def top_level_func inner_var_in_func = 2 end module A module B @module_var = :foo def module_method @module_var end class C < Base TEST_CONST = 1 @class_var = :bar attr_accessor :a, :b def initialize(a, b) @a = a @b = b super end def bar inner_var_in_method = 1 true end private def baz(request, params) auth_header = request.headers['Authorization'] parts = auth_header.try(:split, /\s+/) JWT.decode(parts.last) end end end end "#; let definitions = extract_definitions("ruby", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var top_level_var;func top_level_func() -> void;module A{};module A::B{func module_method() -> void;var @module_var;};class A::B::C{func initialize(a, b) -> void;func bar() -> void;private func baz(request, params) -> void;var TEST_CONST;var @class_var;};"; assert_eq!(stringified, expected); } #[test] fn test_lua() { let source = r#" -- This is a test comment local test_var = "test" function test_func(a, b) local inner_var_in_func = 1 function inner_func_in_func(a, b) return a + b end return a + b end "#; let definitions = extract_definitions("lua", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var test_var;func test_func(a, b) -> void;"; assert_eq!(stringified, expected); } #[test] fn test_c() { let source = r#" #include <stdio.h> int test_var = 2; extern int extern_test_var; int TestFunc(bool b) { return b ? 42 : -1; } extern void ExternTestFunc(); struct Foo { int a; int b; }; typedef int my_int; "#; let definitions = extract_definitions("c", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var extern int extern_test_var;:int;var extern void ExternTestFunc();:void;class Foo{var int a;:int;var int b;:int;};"; assert_eq!(stringified, expected); } #[test] fn test_cpp() { let source = r#" // This is a test comment #include <iostream> namespace { constexpr int TEST_CONSTEXPR = 1; const int TEST_CONST = 1; }; // namespace int test_var = 2; int TestFunc(bool b) { return b ? 42 : -1; } template <typename T> class TestClass { public: TestClass(); TestClass(T a, T b); ~TestClass(); bool operator==(const TestClass &other); T testMethod(T x, T y) { return x + y; } T c; private: void privateMethod(); T a = 0; T b; }; struct TestStruct { public: TestStruct(int a, int b); ~TestStruct(); bool operator==(const TestStruct &other); int testMethod(int x, int y) { return x + y; } static int c; private: int a = 0; int b; }; bool TestStruct::operator==(const TestStruct &other) { return true; } int TestStruct::c = 0; int testFunction(int a, int b) { return a + b; } namespace TestNamespace { class InnerClass { public: bool innerMethod(int a) const; }; bool InnerClass::innerMethod(int a) const { return doSomething(a * 2); } } // namespace TestNamespace enum TestEnum { ENUM_VALUE_1, ENUM_VALUE_2 }; "#; let definitions = extract_definitions("cpp", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{}", stringified); let expected = "var TEST_CONSTEXPR:int;var TEST_CONST:int;var test_var:int;func TestFunc(bool b) -> int;func TestStruct::operator==(const TestStruct &other) -> bool;var TestStruct::c:int;func testFunction(int a, int b) -> int;func InnerClass::innerMethod(int a) -> bool;class InnerClass{func innerMethod(int a) -> bool;};class TestClass{func TestClass() -> TestClass;func operator==(const TestClass &other) -> bool;func testMethod(T x, T y) -> T;func privateMethod() -> void;func TestClass(T a, T b) -> TestClass;var c:T;var a:T;var b:T;};class TestStruct{func TestStruct(int a, int b) -> void;func operator==(const TestStruct &other) -> bool;func testMethod(int x, int y) -> int;var c:int;var a:int;var b:int;};enum TestEnum{ENUM_VALUE_1;ENUM_VALUE_2;};"; assert_eq!(stringified, expected); } #[test] fn test_scala() { let source = r#" object Main { def main(args: Array[String]): Unit = { println("Hello, World!") } } class TestClass { val testVal: String = "test" var testVar = 42 def testMethod(a: Int, b: Int): Int = { a + b } } // braceless syntax is also supported trait TestTrait: def abstractMethod(x: Int): Int def concreteMethod(y: Int): Int = y * 2 case class TestCaseClass(name: String, age: Int) enum TestEnum { case First, Second, Third } val foo: TestClass = ??? "#; let definitions = extract_definitions("scala", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var foo:TestClass;class Main{func main(args: Array[String]) -> Unit;};class TestCaseClass{};class TestClass{func testMethod(a: Int, b: Int) -> Int;var testVal:String;var testVar;};class TestTrait{func abstractMethod(x: Int) -> Int;func concreteMethod(y: Int) -> Int;};enum TestEnum{First;Second;Third;};"; assert_eq!(stringified, expected); } #[test] fn test_elixir() { let source = r#" defmodule TestModule do @moduledoc """ This is a test module """ @test_const "test" @other_const 123 def test_func(a, b) do a + b end defp private_func(x) do x * 2 end defmacro test_macro(expr) do quote do unquote(expr) end end end defmodule AnotherModule do def another_func() do :ok end end "#; let definitions = extract_definitions("elixir", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "module AnotherModule{func another_func();};module TestModule{func test_func(a, b);};"; assert_eq!(stringified, expected); } #[test] fn test_csharp() { let source = r#" using System; namespace TestNamespace; public class TestClass(TestDependency m) { private int PrivateTestProperty { get; set; } private int _privateTestField; public int TestProperty { get; set; } public string TestField; public TestClass() { TestProperty = 0; } public void TestMethod(int a, int b) { var innerVarInMethod = 1; return a + b; } public int TestMethod(int a, int b, int c) => a + b + c; private void PrivateMethod() { return; } public class MyInnerClass(InnerClassDependency m) {} public record MyInnerRecord(int a); } public record TestRecord(int a, int b); public enum TestEnum { Value1, Value2 } "#; let definitions = extract_definitions("csharp", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "class MyInnerClass{func MyInnerClass(InnerClassDependency m) -> MyInnerClass;};class MyInnerRecord{func MyInnerRecord(int a) -> MyInnerRecord;};class TestClass{func TestClass(TestDependency m) -> TestClass;func TestClass() -> TestClass;func TestMethod(int a, int b) -> void;func TestMethod(int a, int b, int c) -> int;var TestProperty:int;var TestField:string;};class TestRecord{func TestRecord(int a, int b) -> TestRecord;};enum TestEnum{Value1;Value2;};"; assert_eq!(stringified, expected); } #[test] fn test_swift() { let source = r#" import Foundation private var myVariable = 0 public var myPublicVariable = 0 struct MyStruct { public var myPublicVariable = 0 private var myPrivateVariable = 0 func myPublicMethod(with parameter: Int) -> { } private func myPrivateMethod(with parameter: Int) -> { } } class MyClass { public var myPublicVariable = 0 private var myPrivateVariable = 0 init(myParameter: Int, myOtherParameter: Int) { } func myPublicMethod(with parameter: Int) -> { } private func myPrivateMethod(with parameter: Int) -> { } func myMethod() { print("Hello, world!") } } "#; let definitions = extract_definitions("swift", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "var myPublicVariable;class MyClass{func init() -> void;func myPublicMethod() -> void;func myMethod() -> void;var myPublicVariable;};class MyStruct{func myPublicMethod() -> void;var myPublicVariable;};"; assert_eq!(stringified, expected); } #[test] fn test_php() { let source = r#" <?php class MyClass { public $myPublicVariable = 0; private $myPrivateVariable = 0; public function myPublicMethod($parameter) { } private function myPrivateMethod($parameter) { } function myMethod() { echo "Hello, world!"; } } ?> "#; let definitions = extract_definitions("php", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "class MyClass{func myPublicMethod($parameter) -> void;func myPrivateMethod($parameter) -> void;func myMethod() -> void;var public $myPublicVariable = 0;;var private $myPrivateVariable = 0;;};"; assert_eq!(stringified, expected); } #[test] fn test_java() { let source = r#" public class MyClass { public void myPublicMethod(String parameter) { System.out.println("Hello, world!"); } private void myPrivateMethod(String parameter) { System.out.println("Hello, world!"); } void myMethod() { System.out.println("Hello, world!"); } } "#; let definitions = extract_definitions("java", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = "class MyClass{func myPublicMethod(String parameter) -> void;func myMethod() -> void;};"; assert_eq!(stringified, expected); } #[test] fn test_unsupported_language() { let source = "print('Hello, world!')"; let definitions = extract_definitions("unknown", source).unwrap(); let stringified = stringify_definitions(&definitions); println!("{stringified}"); let expected = ""; assert_eq!(stringified, expected); } }
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-templates/src/lib.rs
Rust
use minijinja::{context, Environment}; use mlua::prelude::*; use serde::{Deserialize, Serialize}; use std::path::Path; use std::sync::{Arc, Mutex}; struct State<'a> { environment: Mutex<Option<Environment<'a>>>, } impl State<'_> { fn new() -> Self { State { environment: Mutex::new(None), } } } #[derive(Debug, Serialize, Deserialize)] struct SelectedCode { path: String, content: Option<String>, file_type: String, } #[derive(Debug, Serialize, Deserialize)] struct SelectedFile { path: String, content: Option<String>, file_type: String, } #[derive(Debug, Serialize, Deserialize)] struct TemplateContext { ask: bool, code_lang: String, selected_files: Option<Vec<SelectedFile>>, selected_code: Option<SelectedCode>, recently_viewed_files: Option<Vec<String>>, relevant_files: Option<Vec<String>>, project_context: Option<String>, diagnostics: Option<String>, system_info: Option<String>, model_name: Option<String>, memory: Option<String>, todos: Option<String>, enable_fastapply: Option<bool>, use_react_prompt: Option<bool>, } // Given the file name registered after add, the context table in Lua, resulted in a formatted // Lua string #[allow(clippy::needless_pass_by_value)] fn render(state: &State, template: &str, context: TemplateContext) -> LuaResult<String> { let environment = state.environment.lock().unwrap(); match environment.as_ref() { Some(environment) => { let jinja_template = environment .get_template(template) .map_err(LuaError::external) .unwrap(); Ok(jinja_template .render(context! { ask => context.ask, code_lang => context.code_lang, selected_files => context.selected_files, selected_code => context.selected_code, recently_viewed_files => context.recently_viewed_files, relevant_files => context.relevant_files, project_context => context.project_context, diagnostics => context.diagnostics, system_info => context.system_info, model_name => context.model_name, memory => context.memory, todos => context.todos, enable_fastapply => context.enable_fastapply, use_react_prompt => context.use_react_prompt, }) .map_err(LuaError::external) .unwrap()) } None => Err(LuaError::RuntimeError( "Environment not initialized".to_string(), )), } } fn initialize(state: &State, cache_directory: String, project_directory: String) { let mut environment_mutex = state.environment.lock().unwrap(); let mut env = Environment::new(); // Create a custom loader that searches both cache and project directories let cache_dir = cache_directory.clone(); let project_dir = project_directory.clone(); env.set_loader( move |name: &str| -> Result<Option<String>, minijinja::Error> { // First try the cache directory (for built-in templates) let cache_path = Path::new(&cache_dir).join(name); if cache_path.exists() { match std::fs::read_to_string(&cache_path) { Ok(content) => return Ok(Some(content)), Err(_) => {} // Continue to try project directory } } // Then try the project directory (for custom includes) let project_path = Path::new(&project_dir).join(name); if project_path.exists() { match std::fs::read_to_string(&project_path) { Ok(content) => return Ok(Some(content)), Err(_) => {} // File not found or read error } } // Template not found in either directory Ok(None) }, ); *environment_mutex = Some(env); } #[mlua::lua_module] fn avante_templates(lua: &Lua) -> LuaResult<LuaTable> { let core = State::new(); let state = Arc::new(core); let state_clone = Arc::clone(&state); let exports = lua.create_table()?; exports.set( "initialize", lua.create_function( move |_, (cache_directory, project_directory): (String, String)| { initialize(&state, cache_directory, project_directory); Ok(()) }, )?, )?; exports.set( "render", lua.create_function_mut(move |lua, (template, context): (String, LuaValue)| { let ctx = lua.from_value(context)?; render(&state_clone, template.as_str(), ctx) })?, )?; Ok(exports) }
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
crates/avante-tokenizers/src/lib.rs
Rust
use hf_hub::{api::sync::ApiBuilder, Repo, RepoType}; use mlua::prelude::*; use regex::Regex; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use tiktoken_rs::{get_bpe_from_model, CoreBPE}; use tokenizers::Tokenizer; struct Tiktoken { bpe: CoreBPE, } impl Tiktoken { fn new(model: &str) -> Self { let bpe = get_bpe_from_model(model).unwrap(); Self { bpe } } fn encode(&self, text: &str) -> (Vec<u32>, usize, usize) { let tokens = self.bpe.encode_with_special_tokens(text); let num_tokens = tokens.len(); let num_chars = text.chars().count(); (tokens, num_tokens, num_chars) } } struct HuggingFaceTokenizer { tokenizer: Tokenizer, } fn is_valid_url(url: &str) -> bool { let url_regex = Regex::new(r"^https?://[^\s/$.?#].[^\s]*$").unwrap(); url_regex.is_match(url) } impl HuggingFaceTokenizer { fn new(model: &str) -> Self { let tokenizer_path = if is_valid_url(model) { Self::get_cached_tokenizer(model) } else { // Use existing HuggingFace Hub logic for model names let identifier = model.to_string(); let api = ApiBuilder::new().with_progress(false).build().unwrap(); let repo = Repo::new(identifier, RepoType::Model); let api = api.repo(repo); api.get("tokenizer.json").unwrap() }; let tokenizer = Tokenizer::from_file(tokenizer_path).unwrap(); Self { tokenizer } } fn encode(&self, text: &str) -> (Vec<u32>, usize, usize) { let encoding = self.tokenizer.encode(text, false).unwrap(); let tokens = encoding.get_ids().to_vec(); let num_tokens = tokens.len(); let num_chars = encoding.get_offsets().last().unwrap().1; (tokens, num_tokens, num_chars) } fn get_cached_tokenizer(url: &str) -> PathBuf { let cache_dir = dirs::home_dir() .map(|h| h.join(".cache").join("avante")) .unwrap(); std::fs::create_dir_all(&cache_dir).unwrap(); // Extract filename from URL let filename = url.split('/').last().unwrap(); let cached_path = cache_dir.join(filename); if !cached_path.exists() { let response = ureq::get(url).call().unwrap(); let mut file = std::fs::File::create(&cached_path).unwrap(); let mut reader = response.into_reader(); std::io::copy(&mut reader, &mut file).unwrap(); } cached_path } } enum TokenizerType { Tiktoken(Tiktoken), HuggingFace(Box<HuggingFaceTokenizer>), } struct State { tokenizer: Mutex<Option<TokenizerType>>, } impl State { fn new() -> Self { State { tokenizer: Mutex::new(None), } } } fn encode(state: &State, text: &str) -> LuaResult<(Vec<u32>, usize, usize)> { let tokenizer = state.tokenizer.lock().unwrap(); match tokenizer.as_ref() { Some(TokenizerType::Tiktoken(tokenizer)) => Ok(tokenizer.encode(text)), Some(TokenizerType::HuggingFace(tokenizer)) => Ok(tokenizer.encode(text)), None => Err(LuaError::RuntimeError( "Tokenizer not initialized".to_string(), )), } } fn from_pretrained(state: &State, model: &str) { let mut tokenizer_mutex = state.tokenizer.lock().unwrap(); *tokenizer_mutex = Some(match model { "gpt-4o" => TokenizerType::Tiktoken(Tiktoken::new(model)), _ => TokenizerType::HuggingFace(Box::new(HuggingFaceTokenizer::new(model))), }); } #[mlua::lua_module] fn avante_tokenizers(lua: &Lua) -> LuaResult<LuaTable> { let core = State::new(); let state = Arc::new(core); let state_clone = Arc::clone(&state); let exports = lua.create_table()?; exports.set( "from_pretrained", lua.create_function(move |_, model: String| { from_pretrained(&state, model.as_str()); Ok(()) })?, )?; exports.set( "encode", lua.create_function(move |_, text: String| encode(&state_clone, text.as_str()))?, )?; Ok(exports) } #[cfg(test)] mod tests { use super::*; #[test] fn test_tiktoken() { let model = "gpt-4o"; let source = "Hello, world!"; let tokenizer = Tiktoken::new(model); let (tokens, num_tokens, num_chars) = tokenizer.encode(source); assert_eq!(tokens, vec![13225, 11, 2375, 0]); assert_eq!(num_tokens, 4); assert_eq!(num_chars, source.chars().count()); } #[test] fn test_hf() { let model = "gpt2"; let source = "Hello, world!"; let tokenizer = HuggingFaceTokenizer::new(model); let (tokens, num_tokens, num_chars) = tokenizer.encode(source); assert_eq!(tokens, vec![15496, 11, 995, 0]); assert_eq!(num_tokens, 4); assert_eq!(num_chars, source.chars().count()); } #[test] fn test_roundtrip() { let state = State::new(); let source = "Hello, world!"; let model = "gpt2"; from_pretrained(&state, model); let (tokens, num_tokens, num_chars) = encode(&state, "Hello, world!").unwrap(); assert_eq!(tokens, vec![15496, 11, 995, 0]); assert_eq!(num_tokens, 4); assert_eq!(num_chars, source.chars().count()); } // For example: https://storage.googleapis.com/cohere-public/tokenizers/command-r-08-2024.json // Disable testing on GitHub Actions to avoid rate limiting and file size limits #[test] fn test_public_url() { if std::env::var("GITHUB_ACTIONS").is_ok() { return; } let state = State::new(); let source = "Hello, world!"; let model = "https://storage.googleapis.com/cohere-public/tokenizers/command-r-08-2024.json"; from_pretrained(&state, model); let (tokens, num_tokens, num_chars) = encode(&state, "Hello, world!").unwrap(); assert_eq!(tokens, vec![28339, 19, 3845, 8]); assert_eq!(num_tokens, 4); assert_eq!(num_chars, source.chars().count()); } }
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/api.lua
Lua
local Config = require("avante.config") local Utils = require("avante.utils") local PromptInput = require("avante.ui.prompt_input") ---@class avante.ApiToggle ---@operator call(): boolean ---@field debug ToggleBind.wrap ---@field hint ToggleBind.wrap ---@class avante.Api ---@field toggle avante.ApiToggle local M = {} ---@param target_provider avante.SelectorProvider function M.switch_selector_provider(target_provider) require("avante.config").override({ selector = { provider = target_provider, }, }) end ---@param target_provider avante.InputProvider function M.switch_input_provider(target_provider) require("avante.config").override({ input = { provider = target_provider, }, }) end ---@param target avante.ProviderName function M.switch_provider(target) require("avante.providers").refresh(target) end ---@param path string local function to_windows_path(path) local winpath = path:gsub("/", "\\") if winpath:match("^%a:") then winpath = winpath:sub(1, 2):upper() .. winpath:sub(3) end winpath = winpath:gsub("\\$", "") return winpath end ---@param opts? {source: boolean} function M.build(opts) opts = opts or { source = true } local dirname = Utils.trim(string.sub(debug.getinfo(1).source, 2, #"/init.lua" * -1), { suffix = "/" }) local git_root = vim.fs.find(".git", { path = dirname, upward = true })[1] local build_directory = git_root and vim.fn.fnamemodify(git_root, ":h") or (dirname .. "/../../") if opts.source and not vim.fn.executable("cargo") then error("Building avante.nvim requires cargo to be installed.", 2) end ---@type string[] local cmd local os_name = Utils.get_os_name() if vim.tbl_contains({ "linux", "darwin" }, os_name) then cmd = { "sh", "-c", string.format("make BUILD_FROM_SOURCE=%s -C %s", opts.source == true and "true" or "false", build_directory), } elseif os_name == "windows" then build_directory = to_windows_path(build_directory) cmd = { "powershell", "-ExecutionPolicy", "Bypass", "-File", string.format("%s\\Build.ps1", build_directory), "-WorkingDirectory", build_directory, "-BuildFromSource", string.format("%s", opts.source == true and "true" or "false"), } else error("Unsupported operating system: " .. os_name, 2) end ---@type integer local pid local exit_code = { 0 } local ok, job_or_err = pcall(vim.system, cmd, { text = true }, function(obj) local stderr = obj.stderr and vim.split(obj.stderr, "\n") or {} local stdout = obj.stdout and vim.split(obj.stdout, "\n") or {} if vim.tbl_contains(exit_code, obj.code) then local output = stdout if #output == 0 then table.insert(output, "") Utils.debug("build output:", output) else Utils.debug("build error:", stderr) end end end) if not ok then Utils.error("Failed to build the command: " .. cmd .. "\n" .. job_or_err, { once = true }) end pid = job_or_err.pid return pid end ---@class AskOptions ---@field question? string optional questions ---@field win? table<string, any> windows options similar to |nvim_open_win()| ---@field ask? boolean ---@field floating? boolean whether to open a floating input to enter the question ---@field new_chat? boolean whether to open a new chat ---@field without_selection? boolean whether to open a new chat without selection ---@field sidebar_pre_render? fun(sidebar: avante.Sidebar) ---@field sidebar_post_render? fun(sidebar: avante.Sidebar) ---@field project_root? string optional project root ---@field show_logo? boolean whether to show the logo function M.full_view_ask() M.ask({ show_logo = true, sidebar_post_render = function(sidebar) sidebar:toggle_code_window() -- vim.wo[sidebar.containers.result.winid].number = true -- vim.wo[sidebar.containers.result.winid].relativenumber = true end, }) end M.zen_mode = M.full_view_ask ---@param opts? AskOptions function M.ask(opts) opts = opts or {} Config.ask_opts = opts if type(opts) == "string" then Utils.warn("passing 'ask' as string is deprecated, do {question = '...'} instead", { once = true }) opts = { question = opts } end local has_question = opts.question ~= nil and opts.question ~= "" local new_chat = opts.new_chat == true if Utils.is_sidebar_buffer(0) and not has_question and not new_chat then require("avante").close_sidebar() return false end opts = vim.tbl_extend("force", { selection = Utils.get_visual_selection_and_range() }, opts) ---@param input string | nil local function ask(input) if input == nil or input == "" then input = opts.question end local sidebar = require("avante").get() if sidebar and sidebar:is_open() and sidebar.code.bufnr ~= vim.api.nvim_get_current_buf() then sidebar:close({ goto_code_win = false }) end require("avante").open_sidebar(opts) sidebar = require("avante").get() if new_chat then sidebar:new_chat() end if opts.without_selection then sidebar.code.selection = nil sidebar.file_selector:reset() if sidebar.containers.selected_files then sidebar.containers.selected_files:unmount() end end if input == nil or input == "" then return true end vim.api.nvim_exec_autocmds("User", { pattern = "AvanteInputSubmitted", data = { request = input } }) return true end if opts.floating == true or (Config.windows.ask.floating == true and not has_question and opts.floating == nil) then local prompt_input = PromptInput:new({ submit_callback = function(input) ask(input) end, close_on_submit = true, win_opts = { border = Config.windows.ask.border, title = { { "Avante Ask", "FloatTitle" } }, }, start_insert = Config.windows.ask.start_insert, default_value = opts.question, }) prompt_input:open() return true end return ask() end ---@param request? string ---@param line1? integer ---@param line2? integer function M.edit(request, line1, line2) local _, selection = require("avante").get() if not selection then require("avante")._init(vim.api.nvim_get_current_tabpage()) end _, selection = require("avante").get() if not selection then return end selection:create_editing_input(request, line1, line2) if request ~= nil and request ~= "" then vim.api.nvim_exec_autocmds("User", { pattern = "AvanteEditSubmitted", data = { request = request } }) end end ---@return avante.Suggestion | nil function M.get_suggestion() local _, _, suggestion = require("avante").get() return suggestion end ---@param opts? AskOptions function M.refresh(opts) opts = opts or {} local sidebar = require("avante").get() if not sidebar then return end if not sidebar:is_open() then return end local curbuf = vim.api.nvim_get_current_buf() local focused = sidebar.containers.result.bufnr == curbuf or sidebar.containers.input.bufnr == curbuf if focused or not sidebar:is_open() then return end local listed = vim.api.nvim_get_option_value("buflisted", { buf = curbuf }) if Utils.is_sidebar_buffer(curbuf) or not listed then return end local curwin = vim.api.nvim_get_current_win() sidebar:close() sidebar.code.winid = curwin sidebar.code.bufnr = curbuf sidebar:render(opts) end ---@param opts? AskOptions function M.focus(opts) opts = opts or {} local sidebar = require("avante").get() if not sidebar then return end local curbuf = vim.api.nvim_get_current_buf() local curwin = vim.api.nvim_get_current_win() if sidebar:is_open() then if curbuf == sidebar.containers.input.bufnr then if sidebar.code.winid and sidebar.code.winid ~= curwin then vim.api.nvim_set_current_win(sidebar.code.winid) end elseif curbuf == sidebar.containers.result.bufnr then if sidebar.code.winid and sidebar.code.winid ~= curwin then vim.api.nvim_set_current_win(sidebar.code.winid) end else if sidebar.containers.input.winid and sidebar.containers.input.winid ~= curwin then vim.api.nvim_set_current_win(sidebar.containers.input.winid) end end else if sidebar.code.winid then vim.api.nvim_set_current_win(sidebar.code.winid) end ---@cast opts SidebarOpenOptions sidebar:open(opts) if sidebar.containers.input.winid then vim.api.nvim_set_current_win(sidebar.containers.input.winid) end end end function M.select_model() require("avante.model_selector").open() end function M.select_history() local buf = vim.api.nvim_get_current_buf() require("avante.history_selector").open(buf, function(filename) vim.api.nvim_buf_call(buf, function() if not require("avante").is_sidebar_open() then require("avante").open_sidebar({}) end local Path = require("avante.path") Path.history.save_latest_filename(buf, filename) local sidebar = require("avante").get() sidebar:update_content_with_history() sidebar:create_todos_container() sidebar:initialize_token_count() vim.schedule(function() sidebar:focus_input() end) end) end) end function M.add_buffer_files() local sidebar = require("avante").get() if not sidebar then require("avante.api").ask() sidebar = require("avante").get() end if not sidebar:is_open() then sidebar:open({}) end sidebar.file_selector:add_buffer_files() end function M.add_selected_file(filepath) local rel_path = Utils.uniform_path(filepath) local sidebar = require("avante").get() if not sidebar then require("avante.api").ask() sidebar = require("avante").get() end if not sidebar:is_open() then sidebar:open({}) end sidebar.file_selector:add_selected_file(rel_path) end function M.remove_selected_file(filepath) ---@diagnostic disable-next-line: undefined-field local stat = vim.uv.fs_stat(filepath) local files if stat and stat.type == "directory" then files = Utils.scan_directory({ directory = filepath, add_dirs = true }) else files = { filepath } end local sidebar = require("avante").get() if not sidebar then require("avante.api").ask() sidebar = require("avante").get() end if not sidebar:is_open() then sidebar:open({}) end for _, file in ipairs(files) do local rel_path = Utils.uniform_path(file) sidebar.file_selector:remove_selected_file(rel_path) end end function M.stop() require("avante.llm").cancel_inflight_request() end return setmetatable(M, { __index = function(t, k) local module = require("avante") ---@class AvailableApi: ApiCaller ---@field api? boolean local has = module[k] if type(has) ~= "table" or not has.api then Utils.warn(k .. " is not a valid avante's API method", { once = true }) return end t[k] = has return t[k] end, }) --[[@as avante.Api]]
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/auth/pkce.lua
Lua
local M = {} ---Generates a random N number of bytes using crypto lib over ffi, falling back to urandom ---@param n integer number of bytes to generate ---@return string|nil bytes string of bytes generated, or nil if all methods fail ---@return string|nil error error message if generation failed local function get_random_bytes(n) local ok, ffi = pcall(require, "ffi") if ok then -- Try OpenSSL first (cross-platform) local lib_ok, lib = pcall(ffi.load, "crypto") if lib_ok then local cdef_ok = pcall( ffi.cdef, [[ int RAND_bytes(unsigned char *buf, int num); ]] ) if cdef_ok then local buf = ffi.new("unsigned char[?]", n) if lib.RAND_bytes(buf, n) == 1 then return ffi.string(buf, n), nil end end return nil, "OpenSSL RAND_bytes failed - OpenSSL may not be properly installed" end return nil, "Failed to load OpenSSL crypto library - please install OpenSSL" end -- Fallback local f = io.open("/dev/urandom", "rb") if f then local bytes = f:read(n) f:close() return bytes, nil end return nil, "FFI not available and /dev/urandom is not accessible - cannot generate secure random bytes" end --- URL-safe base64 --- @param data string value to base64 encode --- @return string base64String base64 encoded string local function base64url_encode(data) local b64 = vim.base64.encode(data) local b64_string, _ = b64:gsub("+", "-"):gsub("/", "_"):gsub("=", "") return b64_string end -- Generate code_verifier (43-128 characters) --- @return string|nil verifier String representing pkce verifier or nil if generation fails --- @return string|nil error error message if generation failed function M.generate_verifier() local bytes, err = get_random_bytes(32) -- 256 bits if bytes then return base64url_encode(bytes), nil end return nil, err or "Failed to generate random bytes" end -- Generate code_challenge (S256 method) ---@return string|nil challenge String representing pkce challenge or nil if generation fails ---@return string|nil error error message if generation failed function M.generate_challenge(verifier) local ok, ffi = pcall(require, "ffi") if ok then local lib_ok, lib = pcall(ffi.load, "crypto") if lib_ok then local cdef_ok = pcall( ffi.cdef, [[ typedef unsigned char SHA256_DIGEST[32]; void SHA256(const unsigned char *d, size_t n, SHA256_DIGEST md); ]] ) if cdef_ok then local digest = ffi.new("SHA256_DIGEST") lib.SHA256(verifier, #verifier, digest) return base64url_encode(ffi.string(digest, 32)), nil end return nil, "Failed to define SHA256 function - OpenSSL may not be properly configured" end return nil, "Failed to load OpenSSL crypto library - please install OpenSSL" end return nil, "FFI not available - LuaJIT is required for PKCE authentication" end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/clipboard.lua
Lua
---NOTE: this module is inspired by https://github.com/HakonHarnes/img-clip.nvim/tree/main ---@see https://github.com/ekickx/clipboard-image.nvim/blob/main/lua/clipboard-image/paste.lua local Path = require("plenary.path") local Utils = require("avante.utils") local Config = require("avante.config") ---@module "img-clip" local ImgClip = nil ---@class AvanteClipboard ---@field get_base64_content fun(filepath: string): string | nil --- ---@class avante.Clipboard: AvanteClipboard local M = {} ---@type Path local paste_directory = nil ---@return Path local function get_paste_directory() if paste_directory then return paste_directory end paste_directory = Path:new(Config.history.storage_path):joinpath("pasted_images") return paste_directory end M.support_paste_image = Config.support_paste_image function M.setup() get_paste_directory() if not paste_directory:exists() then paste_directory:mkdir({ parent = true }) end if M.support_paste_image() and ImgClip == nil then ImgClip = require("img-clip") end end ---@param line? string function M.paste_image(line) line = line or nil if not Config.support_paste_image() then return false end local opts = { dir_path = paste_directory:absolute(), prompt_for_file_name = false, filetypes = { AvanteInput = Config.img_paste, }, } if vim.fn.has("wsl") > 0 or vim.fn.has("win32") > 0 then opts.use_absolute_path = true end ---@diagnostic disable-next-line: need-check-nil, undefined-field return ImgClip.paste_image(opts, line) end ---@param filepath string function M.get_base64_content(filepath) local os_mapping = Utils.get_os_name() ---@type vim.SystemCompleted local output if os_mapping == "darwin" or os_mapping == "linux" then output = Utils.shell_run(("cat %s | base64 | tr -d '\n'"):format(filepath)) else output = Utils.shell_run(("([Convert]::ToBase64String([IO.File]::ReadAllBytes('%s')) -replace '`r`n')"):format(filepath)) end if output.code == 0 then return output.stdout else error("Failed to convert image to base64") end end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/config.lua
Lua
---NOTE: user will be merged with defaults and ---we add a default var_accessor for this table to config values. ---@alias WebSearchEngineProviderResponseBodyFormatter fun(body: table): (string, string?) ---@alias avante.InputProvider "native" | "dressing" | "snacks" | fun(input: avante.ui.Input): nil local Utils = require("avante.utils") local function copilot_use_response_api(opts) local model = opts and opts.model return type(model) == "string" and model:match("gpt%-5%-codex") ~= nil end ---@class avante.file_selector.IParams ---@field public title string ---@field public filepaths string[] ---@field public handler fun(filepaths: string[]|nil): nil ---@class avante.file_selector.opts.IGetFilepathsParams ---@field public cwd string ---@field public selected_filepaths string[] ---@class avante.CoreConfig: avante.Config local M = {} --- Default configuration for project-specific instruction file M.instructions_file = "avante.md" ---@class avante.Config M._defaults = { debug = false, ---@alias avante.Mode "agentic" | "legacy" ---@type avante.Mode mode = "agentic", ---@alias avante.ProviderName "claude" | "openai" | "azure" | "gemini" | "vertex" | "cohere" | "copilot" | "bedrock" | "ollama" | "watsonx_code_assistant" | "mistral" | string ---@type avante.ProviderName provider = "claude", -- WARNING: Since auto-suggestions are a high-frequency operation and therefore expensive, -- currently designating it as `copilot` provider is dangerous because: https://github.com/yetone/avante.nvim/issues/1048 -- Of course, you can reduce the request frequency by increasing `suggestion.debounce`. auto_suggestions_provider = nil, memory_summary_provider = nil, ---@alias Tokenizer "tiktoken" | "hf" ---@type Tokenizer -- Used for counting tokens and encoding text. -- By default, we will use tiktoken. -- For most providers that we support we will determine this automatically. -- If you wish to use a given implementation, then you can override it here. tokenizer = "tiktoken", ---@type string | fun(): string | nil system_prompt = nil, ---@type string | fun(): string | nil override_prompt_dir = nil, rules = { project_dir = nil, ---@type string | nil (could be relative dirpath) global_dir = nil, ---@type string | nil (absolute dirpath) }, rag_service = { -- RAG service configuration enabled = false, -- Enables the RAG service host_mount = os.getenv("HOME"), -- Host mount path for the RAG service (Docker will mount this path) runner = "docker", -- The runner for the RAG service (can use docker or nix) -- The image to use to run the rag service if runner is docker image = "quay.io/yetoneful/avante-rag-service:0.0.11", llm = { -- Configuration for the Language Model (LLM) used by the RAG service provider = "openai", -- The LLM provider endpoint = "https://api.openai.com/v1", -- The LLM API endpoint api_key = "OPENAI_API_KEY", -- The environment variable name for the LLM API key model = "gpt-4o-mini", -- The LLM model name extra = nil, -- Extra configuration options for the LLM }, embed = { -- Configuration for the Embedding model used by the RAG service provider = "openai", -- The embedding provider endpoint = "https://api.openai.com/v1", -- The embedding API endpoint api_key = "OPENAI_API_KEY", -- The environment variable name for the embedding API key model = "text-embedding-3-large", -- The embedding model name extra = nil, -- Extra configuration options for the embedding model }, docker_extra_args = "", -- Extra arguments to pass to the docker command }, web_search_engine = { provider = "tavily", proxy = nil, providers = { tavily = { api_key_name = "TAVILY_API_KEY", extra_request_body = { include_answer = "basic", }, ---@type WebSearchEngineProviderResponseBodyFormatter format_response_body = function(body) return body.answer, nil end, }, serpapi = { api_key_name = "SERPAPI_API_KEY", extra_request_body = { engine = "google", google_domain = "google.com", }, ---@type WebSearchEngineProviderResponseBodyFormatter format_response_body = function(body) if body.answer_box ~= nil and body.answer_box.result ~= nil then return body.answer_box.result, nil end if body.organic_results ~= nil then local jsn = vim .iter(body.organic_results) :map( function(result) return { title = result.title, link = result.link, snippet = result.snippet, date = result.date, } end ) :take(10) :totable() return vim.json.encode(jsn), nil end return "", nil end, }, searchapi = { api_key_name = "SEARCHAPI_API_KEY", extra_request_body = { engine = "google", }, ---@type WebSearchEngineProviderResponseBodyFormatter format_response_body = function(body) if body.answer_box ~= nil then return body.answer_box.result, nil end if body.organic_results ~= nil then local jsn = vim .iter(body.organic_results) :map( function(result) return { title = result.title, link = result.link, snippet = result.snippet, date = result.date, } end ) :take(10) :totable() return vim.json.encode(jsn), nil end return "", nil end, }, google = { api_key_name = "GOOGLE_SEARCH_API_KEY", engine_id_name = "GOOGLE_SEARCH_ENGINE_ID", extra_request_body = {}, ---@type WebSearchEngineProviderResponseBodyFormatter format_response_body = function(body) if body.items ~= nil then local jsn = vim .iter(body.items) :map( function(result) return { title = result.title, link = result.link, snippet = result.snippet, } end ) :take(10) :totable() return vim.json.encode(jsn), nil end return "", nil end, }, kagi = { api_key_name = "KAGI_API_KEY", extra_request_body = { limit = "10", }, ---@type WebSearchEngineProviderResponseBodyFormatter format_response_body = function(body) if body.data ~= nil then local jsn = vim .iter(body.data) -- search results only :filter(function(result) return result.t == 0 end) :map( function(result) return { title = result.title, url = result.url, snippet = result.snippet, } end ) :take(10) :totable() return vim.json.encode(jsn), nil end return "", nil end, }, brave = { api_key_name = "BRAVE_API_KEY", extra_request_body = { count = "10", result_filter = "web", }, format_response_body = function(body) if body.web == nil then return "", nil end local jsn = vim.iter(body.web.results):map( function(result) return { title = result.title, url = result.url, snippet = result.description, } end ) return vim.json.encode(jsn), nil end, }, searxng = { api_url_name = "SEARXNG_API_URL", extra_request_body = { format = "json", }, ---@type WebSearchEngineProviderResponseBodyFormatter format_response_body = function(body) if body.results == nil then return "", nil end local jsn = vim.iter(body.results):map( function(result) return { title = result.title, url = result.url, snippet = result.content, } end ) return vim.json.encode(jsn), nil end, }, }, }, acp_providers = { ["gemini-cli"] = { command = "gemini", args = { "--experimental-acp" }, env = { NODE_NO_WARNINGS = "1", GEMINI_API_KEY = os.getenv("GEMINI_API_KEY"), }, auth_method = "gemini-api-key", }, ["claude-code"] = { command = "npx", args = { "-y", "-g", "@zed-industries/claude-code-acp" }, env = { NODE_NO_WARNINGS = "1", ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY"), ANTHROPIC_BASE_URL = os.getenv("ANTHROPIC_BASE_URL"), ACP_PATH_TO_CLAUDE_CODE_EXECUTABLE = vim.fn.exepath("claude"), ACP_PERMISSION_MODE = "bypassPermissions", }, }, ["goose"] = { command = "goose", args = { "acp" }, }, ["codex"] = { command = "npx", args = { "-y", "-g", "@zed-industries/codex-acp" }, env = { NODE_NO_WARNINGS = "1", HOME = os.getenv("HOME"), PATH = os.getenv("PATH"), OPENAI_API_KEY = os.getenv("OPENAI_API_KEY"), }, }, ["opencode"] = { command = "opencode", args = { "acp" }, }, ["kimi-cli"] = { command = "kimi", args = { "--acp" }, }, }, ---To add support for custom provider, follow the format below ---See https://github.com/yetone/avante.nvim/wiki#custom-providers for more details ---@type {[string]: AvanteProvider} providers = { ---@type AvanteSupportedProvider openai = { endpoint = "https://api.openai.com/v1", model = "gpt-4o", timeout = 30000, -- Timeout in milliseconds, increase this for reasoning models context_window = 128000, -- Number of tokens to send to the model for context use_response_api = copilot_use_response_api, -- Automatically switch to Response API for GPT-5 Codex models support_previous_response_id = true, -- OpenAI Response API supports previous_response_id for stateful conversations -- NOTE: Response API automatically manages conversation state using previous_response_id for tool calling extra_request_body = { temperature = 0.75, max_completion_tokens = 16384, -- Increase this to include reasoning tokens (for reasoning models). For Response API, will be converted to max_output_tokens reasoning_effort = "medium", -- low|medium|high, only used for reasoning models. For Response API, this will be converted to reasoning.effort -- background = false, -- Response API only: set to true to start a background task -- NOTE: previous_response_id is automatically managed by the provider for tool calling - don't set manually }, }, ---@type AvanteSupportedProvider copilot = { endpoint = "https://api.githubcopilot.com", model = "gpt-4o-2024-11-20", proxy = nil, -- [protocol://]host[:port] Use this proxy allow_insecure = false, -- Allow insecure server connections timeout = 30000, -- Timeout in milliseconds context_window = 64000, -- Number of tokens to send to the model for context use_response_api = copilot_use_response_api, -- Automatically switch to Response API for GPT-5 Codex models support_previous_response_id = false, -- Copilot doesn't support previous_response_id, must send full history -- NOTE: Copilot doesn't support previous_response_id, always sends full conversation history including tool_calls -- NOTE: Response API doesn't support some parameters like top_p, frequency_penalty, presence_penalty extra_request_body = { -- temperature is not supported by Response API for reasoning models max_tokens = 20480, }, }, ---@type AvanteAzureProvider azure = { endpoint = "", -- example: "https://<your-resource-name>.openai.azure.com" deployment = "", -- Azure deployment name (e.g., "gpt-4o", "my-gpt-4o-deployment") api_version = "2024-12-01-preview", timeout = 30000, -- Timeout in milliseconds, increase this for reasoning models extra_request_body = { temperature = 0.75, max_completion_tokens = 16384, -- Increase this toinclude reasoning tokens (for reasoning models); but too large default value will not fit for some models (e.g. gpt-5-chat supports at most 16384 completion tokens) reasoning_effort = "medium", -- low|medium|high, only used for reasoning models }, }, ---@type AvanteAnthropicProvider claude = { endpoint = "https://api.anthropic.com", auth_type = "api", model = "claude-sonnet-4-5-20250929", timeout = 30000, -- Timeout in milliseconds context_window = 200000, extra_request_body = { temperature = 0.75, max_tokens = 64000, }, }, ---@type AvanteSupportedProvider bedrock = { model = "us.anthropic.claude-3-7-sonnet-20250219-v1:0", model_names = { "anthropic.claude-3-5-sonnet-20241022-v2:0", "us.anthropic.claude-3-7-sonnet-20250219-v1:0", "us.anthropic.claude-opus-4-20250514-v1:0", "us.anthropic.claude-opus-4-1-20250805-v1:0", "us.anthropic.claude-sonnet-4-20250514-v1:0", }, timeout = 30000, -- Timeout in milliseconds extra_request_body = { temperature = 0.75, max_tokens = 20480, }, aws_region = "", -- AWS region to use for authentication and bedrock API aws_profile = "", -- AWS profile to use for authentication, if unspecified uses default credentials chain }, ---@type AvanteSupportedProvider gemini = { endpoint = "https://generativelanguage.googleapis.com/v1beta/models", model = "gemini-2.0-flash", timeout = 30000, -- Timeout in milliseconds context_window = 1048576, use_ReAct_prompt = true, extra_request_body = { generationConfig = { temperature = 0.75, }, }, }, ---@type AvanteSupportedProvider vertex = { endpoint = "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models", model = "gemini-1.5-flash-002", timeout = 30000, -- Timeout in milliseconds context_window = 1048576, use_ReAct_prompt = true, extra_request_body = { generationConfig = { temperature = 0.75, }, }, }, ---@type AvanteSupportedProvider cohere = { endpoint = "https://api.cohere.com/v2", model = "command-r-plus-08-2024", timeout = 30000, -- Timeout in milliseconds extra_request_body = { temperature = 0.75, max_tokens = 20480, }, }, ---@type AvanteSupportedProvider ollama = { endpoint = "http://127.0.0.1:11434", timeout = 30000, -- Timeout in milliseconds use_ReAct_prompt = true, extra_request_body = { options = { temperature = 0.75, num_ctx = 20480, keep_alive = "5m", }, }, }, ---@type AvanteSupportedProvider watsonx_code_assistant = { endpoint = "https://api.dataplatform.cloud.ibm.com/v2/wca/core/chat/text/generation", model = "granite-8b-code-instruct", timeout = 30000, -- Timeout in milliseconds extra_request_body = { -- Additional watsonx-specific parameters can be added here }, }, ---@type AvanteSupportedProvider vertex_claude = { endpoint = "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/anthropic/models", model = "claude-3-5-sonnet-v2@20241022", timeout = 30000, -- Timeout in milliseconds extra_request_body = { temperature = 0.75, max_tokens = 20480, }, }, ---@type AvanteSupportedProvider ["claude-haiku"] = { __inherited_from = "claude", model = "claude-3-5-haiku-20241022", timeout = 30000, -- Timeout in milliseconds extra_request_body = { temperature = 0.75, max_tokens = 8192, }, }, ---@type AvanteSupportedProvider ["claude-opus"] = { __inherited_from = "claude", model = "claude-3-opus-20240229", timeout = 30000, -- Timeout in milliseconds extra_request_body = { temperature = 0.75, max_tokens = 20480, }, }, ["openai-gpt-4o-mini"] = { __inherited_from = "openai", model = "gpt-4o-mini", }, aihubmix = { __inherited_from = "openai", endpoint = "https://aihubmix.com/v1", model = "gpt-4o-2024-11-20", api_key_name = "AIHUBMIX_API_KEY", }, ["aihubmix-claude"] = { __inherited_from = "claude", endpoint = "https://aihubmix.com", model = "claude-3-7-sonnet-20250219", api_key_name = "AIHUBMIX_API_KEY", }, morph = { __inherited_from = "openai", endpoint = "https://api.morphllm.com/v1", model = "auto", api_key_name = "MORPH_API_KEY", }, moonshot = { __inherited_from = "openai", endpoint = "https://api.moonshot.ai/v1", model = "kimi-k2-0711-preview", api_key_name = "MOONSHOT_API_KEY", }, xai = { __inherited_from = "openai", endpoint = "https://api.x.ai/v1", model = "grok-code-fast-1", api_key_name = "XAI_API_KEY", }, glm = { __inherited_from = "openai", endpoint = "https://open.bigmodel.cn/api/coding/paas/v4", model = "GLM-4.7", api_key_name = "GLM_API_KEY", }, qwen = { __inherited_from = "openai", endpoint = "https://dashscope.aliyuncs.com/compatible-mode/v1", model = "qwen3-coder-plus", api_key_name = "DASHSCOPE_API_KEY", }, mistral = { __inherited_from = "openai", endpoint = "https://api.mistral.ai/v1", model = "mistral-large-latest", api_key_name = "MISTRAL_API_KEY", extra_request_body = { max_tokens = 4096, -- to avoid using the unsupported max_completion_tokens }, }, }, ---Specify the special dual_boost mode ---1. enabled: Whether to enable dual_boost mode. Default to false. ---2. first_provider: The first provider to generate response. Default to "openai". ---3. second_provider: The second provider to generate response. Default to "claude". ---4. prompt: The prompt to generate response based on the two reference outputs. ---5. timeout: Timeout in milliseconds. Default to 60000. ---How it works: --- When dual_boost is enabled, avante will generate two responses from the first_provider and second_provider respectively. Then use the response from the first_provider as provider1_output and the response from the second_provider as provider2_output. Finally, avante will generate a response based on the prompt and the two reference outputs, with the default Provider as normal. ---Note: This is an experimental feature and may not work as expected. dual_boost = { enabled = false, first_provider = "openai", second_provider = "claude", prompt = "Based on the two reference outputs below, generate a response that incorporates elements from both but reflects your own judgment and unique perspective. Do not provide any explanation, just give the response directly. Reference Output 1: [{{provider1_output}}], Reference Output 2: [{{provider2_output}}]", timeout = 60000, -- Timeout in milliseconds }, ---Specify the behaviour of avante.nvim ---1. auto_focus_sidebar : Whether to automatically focus the sidebar when opening avante.nvim. Default to true. ---2. auto_suggestions = false, -- Whether to enable auto suggestions. Default to false. ---3. auto_apply_diff_after_generation: Whether to automatically apply diff after LLM response. --- This would simulate similar behaviour to cursor. Default to false. ---4. auto_set_keymaps : Whether to automatically set the keymap for the current line. Default to true. --- Note that avante will safely set these keymap. See https://github.com/yetone/avante.nvim/wiki#keymaps-and-api-i-guess for more details. ---5. auto_set_highlight_group : Whether to automatically set the highlight group for the current line. Default to true. ---6. jump_result_buffer_on_finish = false, -- Whether to automatically jump to the result buffer after generation ---7. support_paste_from_clipboard : Whether to support pasting image from clipboard. This will be determined automatically based whether img-clip is available or not. ---8. minimize_diff : Whether to remove unchanged lines when applying a code block ---9. enable_token_counting : Whether to enable token counting. Default to true. ---10. auto_add_current_file : Whether to automatically add the current file when opening a new chat. Default to true. behaviour = { auto_focus_sidebar = true, auto_suggestions = false, -- Experimental stage auto_suggestions_respect_ignore = false, auto_set_highlight_group = true, auto_set_keymaps = true, auto_apply_diff_after_generation = false, jump_result_buffer_on_finish = false, support_paste_from_clipboard = false, minimize_diff = true, enable_token_counting = true, use_cwd_as_project_root = false, auto_focus_on_diff_view = false, ---@type boolean | string[] -- true: auto-approve all tools, false: normal prompts, string[]: auto-approve specific tools by name auto_approve_tool_permissions = true, -- Default: auto-approve all tools (no prompts) auto_check_diagnostics = true, allow_access_to_git_ignored_files = false, enable_fastapply = false, include_generated_by_commit_line = false, -- Controls if 'Generated-by: <provider/model>' line is added to git commit message auto_add_current_file = true, -- Whether to automatically add the current file when opening a new chat --- popup is the original yes,all,no in a floating window --- inline_buttons is the new inline buttons in the sidebar ---@type "popup" | "inline_buttons" confirmation_ui_style = "inline_buttons", --- Whether to automatically open files and navigate to lines when ACP agent makes edits ---@type boolean acp_follow_agent_locations = true, }, prompt_logger = { -- logs prompts to disk (timestamped, for replay/debugging) enabled = true, -- toggle logging entirely log_dir = vim.fn.stdpath("cache"), -- directory where logs are saved max_entries = 100, -- the uplimit of entries that can be sotred next_prompt = { normal = "<C-n>", -- load the next (newer) prompt log in normal mode insert = "<C-n>", }, prev_prompt = { normal = "<C-p>", -- load the previous (older) prompt log in normal mode insert = "<C-p>", }, }, history = { max_tokens = 4096, carried_entry_count = nil, storage_path = Utils.join_paths(vim.fn.stdpath("state"), "avante"), paste = { extension = "png", filename = "pasted-%Y-%m-%d-%H-%M-%S", }, }, highlights = { diff = { current = nil, incoming = nil, }, }, img_paste = { url_encode_path = true, template = "\nimage: $FILE_PATH\n", }, mappings = { ---@class AvanteConflictMappings diff = { ours = "co", theirs = "ct", all_theirs = "ca", both = "cb", cursor = "cc", next = "]x", prev = "[x", }, suggestion = { accept = "<M-l>", next = "<M-]>", prev = "<M-[>", dismiss = "<C-]>", }, jump = { next = "]]", prev = "[[", }, submit = { normal = "<CR>", insert = "<C-s>", }, cancel = { normal = { "<C-c>", "<Esc>", "q" }, insert = { "<C-c>" }, }, -- NOTE: The following will be safely set by avante.nvim ask = "<leader>aa", new_ask = "<leader>an", zen_mode = "<leader>az", edit = "<leader>ae", refresh = "<leader>ar", focus = "<leader>af", stop = "<leader>aS", toggle = { default = "<leader>at", debug = "<leader>ad", selection = "<leader>aC", suggestion = "<leader>as", repomap = "<leader>aR", }, sidebar = { expand_tool_use = "<S-Tab>", next_prompt = "]p", prev_prompt = "[p", apply_all = "A", apply_cursor = "a", retry_user_request = "r", edit_user_request = "e", switch_windows = "<Tab>", reverse_switch_windows = "<S-Tab>", toggle_code_window = "x", remove_file = "d", add_file = "@", close = { "q" }, ---@alias AvanteCloseFromInput { normal: string | nil, insert: string | nil } ---@type AvanteCloseFromInput | nil close_from_input = nil, -- e.g., { normal = "<Esc>", insert = "<C-d>" } ---@alias AvanteToggleCodeWindowFromInput { normal: string | nil, insert: string | nil } ---@type AvanteToggleCodeWindowFromInput | nil toggle_code_window_from_input = nil, -- e.g., { normal = "x", insert = "<C-;>" } }, files = { add_current = "<leader>ac", -- Add current buffer to selected files add_all_buffers = "<leader>aB", -- Add all buffer files to selected files }, select_model = "<leader>a?", -- Select model command select_history = "<leader>ah", -- Select history command confirm = { focus_window = "<C-w>f", code = "c", resp = "r", input = "i", }, }, windows = { ---@alias AvantePosition "right" | "left" | "top" | "bottom" | "smart" ---@type AvantePosition position = "right", fillchars = "eob: ", wrap = true, -- similar to vim.o.wrap width = 30, -- default % based on available width in vertical layout height = 30, -- default % based on available height in horizontal layout sidebar_header = { enabled = true, -- true, false to enable/disable the header align = "center", -- left, center, right for title rounded = true, }, spinner = { editing = { "⡀", "⠄", "⠂", "⠁", "⠈", "⠐", "⠠", "⢀", "⣀", "⢄", "⢂", "⢁", "⢈", "⢐", "⢠", "⣠", "⢤", "⢢", "⢡", "⢨", "⢰", "⣰", "⢴", "⢲", "⢱", "⢸", "⣸", "⢼", "⢺", "⢹", "⣹", "⢽", "⢻", "⣻", "⢿", "⣿", }, generating = { "·", "✢", "✳", "∗", "✻", "✽" }, thinking = { "🤯", "🙄" }, }, input = { prefix = "> ", height = 8, -- Height of the input window in vertical layout }, selected_files = { height = 6, -- Maximum height of the selected files window }, edit = { border = { " ", " ", " ", " ", " ", " ", " ", " " }, start_insert = true, -- Start insert mode when opening the edit window }, ask = { floating = false, -- Open the 'AvanteAsk' prompt in a floating window border = { " ", " ", " ", " ", " ", " ", " ", " " }, start_insert = true, -- Start insert mode when opening the ask window ---@alias AvanteInitialDiff "ours" | "theirs" ---@type AvanteInitialDiff focus_on_apply = "ours", -- which diff to focus after applying }, }, --- @class AvanteConflictConfig diff = { autojump = true, --- Override the 'timeoutlen' setting while hovering over a diff (see :help timeoutlen). --- Helps to avoid entering operator-pending mode with diff mappings starting with `c`. --- Disable by setting to -1. override_timeoutlen = 500, }, --- Allows selecting code or other data in a buffer and ask LLM questions about it or --- to perform edits/transformations. --- @class AvanteSelectionConfig --- @field enabled boolean --- @field hint_display "delayed" | "immediate" | "none" When to show key map hints. selection = { enabled = true, hint_display = "delayed", }, --- @class AvanteRepoMapConfig repo_map = { ignore_patterns = { "%.git", "%.worktree", "__pycache__", "node_modules" }, -- ignore files matching these negate_patterns = {}, -- negate ignore files matching these. }, --- @class AvanteFileSelectorConfig file_selector = { provider = nil, -- Options override for custom providers provider_opts = {}, }, selector = { ---@alias avante.SelectorProvider "native" | "fzf_lua" | "mini_pick" | "snacks" | "telescope" | fun(selector: avante.ui.Selector): nil ---@type avante.SelectorProvider provider = "native", provider_opts = {}, exclude_auto_select = {}, -- List of items to exclude from auto selection }, input = { provider = "native", provider_opts = {}, }, suggestion = { debounce = 600, throttle = 600, }, disabled_tools = {}, ---@type string[] ---@type AvanteLLMToolPublic[] | fun(): AvanteLLMToolPublic[] custom_tools = {}, ---@type AvanteSlashCommand[] slash_commands = {}, ---@type AvanteShortcut[] shortcuts = {}, ---@type AskOptions ask_opts = {}, } ---@type avante.Config ---@diagnostic disable-next-line: missing-fields M._options = {} local function get_config_dir_path() return Utils.join_paths(vim.fn.expand("~"), ".config", "avante.nvim") end local function get_config_file_path() return Utils.join_paths(get_config_dir_path(), "config.json") end --- Function to save the last used model ---@param model_name string function M.save_last_model(model_name, provider_name) local config_dir = get_config_dir_path() local storage_path = get_config_file_path() if not Utils.path_exists(config_dir) then vim.fn.mkdir(config_dir, "p") end local Providers = require("avante.providers") local provider = Providers[provider_name] local provider_model = provider and provider.model local file = io.open(storage_path, "w") if file then file:write( vim.json.encode({ last_model = model_name, last_provider = provider_name, provider_model = provider_model }) ) file:close() end end --- Retrieves names of the last used model and provider. May remove saved config if it is deemed invalid ---@param known_providers table<string, AvanteSupportedProvider> ---@return string|nil Model name ---@return string|nil Provider name function M.get_last_used_model(known_providers) local storage_path = get_config_file_path() local file = io.open(storage_path, "r") if file then local content = file:read("*a") file:close() if not content or content == "" then Utils.warn("Last used model file is empty: " .. storage_path) -- Remove to not have repeated warnings os.remove(storage_path) end local success, data = pcall(vim.json.decode, content) if not success or not data or not data.last_model or data.last_model == "" or data.last_provider == "" then Utils.warn("Invalid or corrupt JSON in last used model file: " .. storage_path) -- Rename instead of deleting so user can examine contents os.rename(storage_path, storage_path .. ".bad") return end if data.last_provider then local provider = known_providers[data.last_provider] if not provider then Utils.warn( "Provider " .. data.last_provider .. " is no longer a valid provider, falling back to default configuration" ) os.remove(storage_path) return end if data.provider_model and provider.model and provider.model ~= data.provider_model then return provider.model, data.last_provider end end return data.last_model, data.last_provider end end ---Applies given model and provider to the config ---@param config avante.Config ---@param model_name string ---@param provider_name? string local function apply_model_selection(config, model_name, provider_name) local provider_list = config.providers or {} local current_provider_name = config.provider if config.acp_providers[current_provider_name] then return end local target_provider_name = provider_name or current_provider_name local target_provider = provider_list[target_provider_name] if not target_provider then return end local current_provider_data = provider_list[current_provider_name] local current_model_name = current_provider_data and current_provider_data.model if target_provider_name ~= current_provider_name or model_name ~= current_model_name then config.provider = target_provider_name target_provider.model = model_name if not target_provider.model_names then target_provider.model_names = {} end for _, model_name_ in ipairs({ model_name, current_model_name }) do if not vim.tbl_contains(target_provider.model_names, model_name_) then table.insert(target_provider.model_names, model_name_) end end Utils.info(string.format("Using previously selected model: %s/%s", target_provider_name, model_name)) end end ---@param opts table<string, any>|nil -- Optional table parameter for configuration settings function M.setup(opts) opts = opts or {} -- Ensure `opts` is defined with a default table if vim.fn.has("nvim-0.11") == 1 then vim.validate("opts", opts, "table", true) else vim.validate({ opts = { opts, "table", true } }) end opts = opts or {} local migration_url = "https://github.com/yetone/avante.nvim/wiki/Provider-configuration-migration-guide" if opts.providers ~= nil then for k, v in pairs(opts.providers) do local extra_request_body if type(v) == "table" then if M._defaults.providers[k] ~= nil then extra_request_body = M._defaults.providers[k].extra_request_body elseif v.__inherited_from ~= nil then if M._defaults.providers[v.__inherited_from] ~= nil then extra_request_body = M._defaults.providers[v.__inherited_from].extra_request_body end end end if extra_request_body ~= nil then for k_, v_ in pairs(v) do if extra_request_body[k_] ~= nil then opts.providers[k].extra_request_body = opts.providers[k].extra_request_body or {} opts.providers[k].extra_request_body[k_] = v_ Utils.warn( string.format( "[DEPRECATED] The configuration of `providers.%s.%s` should be placed in `providers.%s.extra_request_body.%s`; for detailed migration instructions, please visit: %s", k, k_, k, k_, migration_url ), { title = "Avante" } ) end end end end end for k, v in pairs(opts) do if M._defaults.providers[k] ~= nil then opts.providers = opts.providers or {} opts.providers[k] = v Utils.warn( string.format( "[DEPRECATED] The configuration of `%s` should be placed in `providers.%s`. For detailed migration instructions, please visit: %s", k, k, migration_url ), { title = "Avante" } ) local extra_request_body = M._defaults.providers[k].extra_request_body if type(v) == "table" and extra_request_body ~= nil then for k_, v_ in pairs(v) do if extra_request_body[k_] ~= nil then opts.providers[k].extra_request_body = opts.providers[k].extra_request_body or {} opts.providers[k].extra_request_body[k_] = v_ Utils.warn( string.format( "[DEPRECATED] The configuration of `%s.%s` should be placed in `providers.%s.extra_request_body.%s`; for detailed migration instructions, please visit: %s", k, k_, k, k_, migration_url ), { title = "Avante" } ) end end end end if k == "vendors" and v ~= nil then for k2, v2 in pairs(v) do opts.providers = opts.providers or {} opts.providers[k2] = v2 Utils.warn( string.format( "[DEPRECATED] The configuration of `vendors.%s` should be placed in `providers.%s`. For detailed migration instructions, please visit: %s", k2, k2, migration_url ), { title = "Avante" } ) if type(v2) == "table" and v2.__inherited_from ~= nil and M._defaults.providers[v2.__inherited_from] ~= nil then local extra_request_body = M._defaults.providers[v2.__inherited_from].extra_request_body if extra_request_body ~= nil then for k2_, v2_ in pairs(v2) do if extra_request_body[k2_] ~= nil then opts.providers[k2].extra_request_body = opts.providers[k2].extra_request_body or {} opts.providers[k2].extra_request_body[k2_] = v2_ Utils.warn( string.format( "[DEPRECATED] The configuration of `vendors.%s.%s` should be placed in `providers.%s.extra_request_body.%s`; for detailed migration instructions, please visit: %s", k2, k2_, k2, k2_, migration_url ), { title = "Avante" } ) end end end end end end end local merged = vim.tbl_deep_extend( "force", M._defaults, opts, ---@type avante.Config { behaviour = { support_paste_from_clipboard = M.support_paste_image(), }, } ) local last_model, last_provider = M.get_last_used_model(merged.providers or {}) if last_model then apply_model_selection(merged, last_model, last_provider) end M._options = merged ---@diagnostic disable-next-line: undefined-field if M._options.disable_tools ~= nil then Utils.warn( "`disable_tools` is provider-scoped, not globally scoped. Therefore, you cannot set `disable_tools` at the top level. It should be set under a provider, for example: `openai.disable_tools = true`", { title = "Avante" } ) end if type(M._options.disabled_tools) == "boolean" then Utils.warn( '`disabled_tools` must be a list, not a boolean. Please change it to `disabled_tools = { "tool1", "tool2" }`. Note the difference between `disabled_tools` and `disable_tools`.', { title = "Avante" } ) end if vim.fn.has("nvim-0.11") == 1 then vim.validate("provider", M._options.provider, "string", false) else vim.validate({ provider = { M._options.provider, "string", false } }) end for k, v in pairs(M._options.providers) do M._options.providers[k] = type(v) == "function" and v() or v end end ---@param opts table<string, any> function M.override(opts) if vim.fn.has("nvim-0.11") == 1 then vim.validate("opts", opts, "table", true) else vim.validate({ opts = { opts, "table", true } }) end M._options = vim.tbl_deep_extend("force", M._options, opts or {}) for k, v in pairs(M._options.providers) do M._options.providers[k] = type(v) == "function" and v() or v end end M = setmetatable(M, { __index = function(_, k) if M._options[k] then return M._options[k] end end, }) function M.support_paste_image() return Utils.has("img-clip.nvim") or Utils.has("img-clip") end function M.get_window_width() return math.ceil(vim.o.columns * (M.windows.width / 100)) end ---get supported providers ---@param provider_name avante.ProviderName function M.get_provider_config(provider_name) local found = false local config = {} if M.providers[provider_name] ~= nil then found = true config = vim.tbl_deep_extend("force", config, vim.deepcopy(M.providers[provider_name], true)) end if not found then error("Failed to find provider: " .. provider_name, 2) end return config end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/diff.lua
Lua
local api = vim.api local Config = require("avante.config") local Utils = require("avante.utils") local Highlights = require("avante.highlights") local H = {} local M = {} -----------------------------------------------------------------------------// -- REFERENCES: -----------------------------------------------------------------------------// -- Detecting the state of a git repository based on files in the .git directory. -- https://stackoverflow.com/questions/49774200/how-to-tell-if-my-git-repo-is-in-a-conflict -- git diff commands to git a list of conflicted files -- https://stackoverflow.com/questions/3065650/whats-the-simplest-way-to-list-conflicted-files-in-git -- how to show a full path for files in a git diff command -- https://stackoverflow.com/questions/10459374/making-git-diff-stat-show-full-file-path -- Advanced merging -- https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging -----------------------------------------------------------------------------// -- Types -----------------------------------------------------------------------------// ---@alias ConflictSide "'ours'"|"'theirs'"|"'all_theirs'"|"'both'"|"'cursor'"|"'base'"|"'none'" --- @class AvanteConflictHighlights --- @field current string --- @field incoming string ---@class RangeMark ---@field label integer ---@field content string --- @class PositionMarks --- @field current RangeMark --- @field incoming RangeMark --- @class Range --- @field range_start integer --- @field range_end integer --- @field content_start integer --- @field content_end integer --- @class ConflictPosition --- @field incoming Range --- @field middle Range --- @field current Range --- @field marks PositionMarks --- @class ConflictBufferCache --- @field lines table<integer, boolean> map of conflicted line numbers --- @field positions ConflictPosition[] --- @field tick integer --- @field bufnr integer -----------------------------------------------------------------------------// -- Constants -----------------------------------------------------------------------------// ---@enum AvanteConflictSides local SIDES = { OURS = "ours", THEIRS = "theirs", ALL_THEIRS = "all_theirs", BOTH = "both", NONE = "none", CURSOR = "cursor", } -- A mapping between the internal names and the display names local name_map = { ours = "current", theirs = "incoming", both = "both", none = "none", cursor = "cursor", } local CURRENT_HL = Highlights.CURRENT local INCOMING_HL = Highlights.INCOMING local CURRENT_LABEL_HL = Highlights.CURRENT_LABEL local INCOMING_LABEL_HL = Highlights.INCOMING_LABEL local PRIORITY = (vim.hl or vim.highlight).priorities.user local NAMESPACE = api.nvim_create_namespace("avante-conflict") local KEYBINDING_NAMESPACE = api.nvim_create_namespace("avante-conflict-keybinding") local AUGROUP_NAME = "avante_conflicts" local conflict_start = "^<<<<<<<" local conflict_middle = "^=======" local conflict_end = "^>>>>>>>" -----------------------------------------------------------------------------// --- @return table<string, ConflictBufferCache> local function create_visited_buffers() return setmetatable({}, { __index = function(t, k) if type(k) == "number" then return t[api.nvim_buf_get_name(k)] end end, }) end --- A list of buffers that have conflicts in them. This is derived from --- git using the diff command, and updated at intervals local visited_buffers = create_visited_buffers() -----------------------------------------------------------------------------// ---Add the positions to the buffer in our in memory buffer list ---positions are keyed by a list of range start and end for each mark ---@param buf integer ---@param positions ConflictPosition[] local function update_visited_buffers(buf, positions) if not buf or not api.nvim_buf_is_valid(buf) then return end local name = api.nvim_buf_get_name(buf) -- If this buffer is not in the list if not visited_buffers[name] then return end visited_buffers[name].bufnr = buf visited_buffers[name].tick = vim.b[buf].changedtick visited_buffers[name].positions = positions end function M.add_visited_buffer(bufnr) local name = api.nvim_buf_get_name(bufnr) visited_buffers[name] = visited_buffers[name] or {} end ---Set an extmark for each section of the git conflict ---@param bufnr integer ---@param hl string ---@param range_start integer ---@param range_end integer ---@return integer? extmark_id local function hl_range(bufnr, hl, range_start, range_end) if not range_start or not range_end then return end return api.nvim_buf_set_extmark(bufnr, NAMESPACE, range_start, 0, { hl_group = hl, hl_eol = true, hl_mode = "combine", end_row = range_end, priority = PRIORITY, }) end ---Add highlights and additional data to each section heading of the conflict marker ---These works by covering the underlying text with an extmark that contains the same information ---with some extra detail appended. ---TODO: ideally this could be done by using virtual text at the EOL and highlighting the ---background but this doesn't work and currently this is done by filling the rest of the line with ---empty space and overlaying the line content ---@param bufnr integer ---@param hl_group string ---@param label string ---@param lnum integer ---@return integer extmark id local function draw_section_label(bufnr, hl_group, label, lnum) local remaining_space = api.nvim_win_get_width(0) - api.nvim_strwidth(label) return api.nvim_buf_set_extmark(bufnr, NAMESPACE, lnum, 0, { hl_group = hl_group, virt_text = { { label .. string.rep(" ", remaining_space), hl_group } }, virt_text_pos = "overlay", priority = PRIORITY, }) end ---Highlight each part of a git conflict i.e. the incoming changes vs the current/HEAD changes ---TODO: should extmarks be ephemeral? or is it less expensive to save them and only re-apply ---them when a buffer changes since otherwise we have to reparse the whole buffer constantly ---@param bufnr integer ---@param positions table ---@param lines string[] local function highlight_conflicts(bufnr, positions, lines) M.clear(bufnr) for _, position in ipairs(positions) do local current_start = position.current.range_start local current_end = position.current.range_end local incoming_start = position.incoming.range_start local incoming_end = position.incoming.range_end -- Add one since the index access in lines is 1 based local current_label = lines[current_start + 1] .. " (Current changes)" local incoming_label = lines[incoming_end + 1] .. " (Incoming changes)" local curr_label_id = draw_section_label(bufnr, CURRENT_LABEL_HL, current_label, current_start) local curr_id = hl_range(bufnr, CURRENT_HL, current_start, current_end + 1) local inc_id = hl_range(bufnr, INCOMING_HL, incoming_start, incoming_end + 1) local inc_label_id = draw_section_label(bufnr, INCOMING_LABEL_HL, incoming_label, incoming_end) position.marks = { current = { label = curr_label_id, content = curr_id }, incoming = { label = inc_label_id, content = inc_id }, } end end ---Iterate through the buffer line by line checking there is a matching conflict marker ---when we find a starting mark we collect the position details and add it to a list of positions ---@param lines string[] ---@return boolean ---@return ConflictPosition[] local function detect_conflicts(lines) local positions = {} local position, has_middle = nil, false for index, line in ipairs(lines) do local lnum = index - 1 if line:match(conflict_start) then position = { current = { range_start = lnum, content_start = lnum + 1 }, middle = {}, incoming = {}, } end if position ~= nil and line:match(conflict_middle) then has_middle = true position.current.range_end = lnum - 1 position.current.content_end = lnum - 1 position.middle.range_start = lnum position.middle.range_end = lnum + 1 position.incoming.range_start = lnum + 1 position.incoming.content_start = lnum + 1 end if position ~= nil and has_middle and line:match(conflict_end) then position.incoming.range_end = lnum position.incoming.content_end = lnum - 1 positions[#positions + 1] = position position, has_middle = nil, false end end return #positions > 0, positions end ---Helper function to find a conflict position based on a comparator function ---@param bufnr integer ---@param comparator fun(string, integer): boolean ---@param opts table? ---@return ConflictPosition? local function find_position(bufnr, comparator, opts) local match = visited_buffers[bufnr] if not match then return end local line = Utils.get_cursor_pos() line = line - 1 -- Convert to 0-based for position comparison if opts and opts.reverse then for i = #match.positions, 1, -1 do local position = match.positions[i] if comparator(line, position) then return position end end return nil end for _, position in ipairs(match.positions) do if comparator(line, position) then return position end end return nil end ---Retrieves a conflict marker position by checking the visited buffers for a supported range ---@param bufnr integer ---@return ConflictPosition? local function get_current_position(bufnr) return find_position( bufnr, function(line, position) return position.current.range_start <= line and position.incoming.range_end >= line end ) end ---@param position ConflictPosition? ---@param side ConflictSide local function set_cursor(position, side) if not position then return end local target = side == SIDES.OURS and position.current or position.incoming api.nvim_win_set_cursor(0, { target.range_start + 1, 0 }) vim.cmd("normal! zz") end local show_keybinding_hint_extmark_id = nil local function register_cursor_move_events(bufnr) local function show_keybinding_hint(lnum) if show_keybinding_hint_extmark_id then api.nvim_buf_del_extmark(bufnr, KEYBINDING_NAMESPACE, show_keybinding_hint_extmark_id) end local hint = string.format( "[<%s>: OURS, <%s>: THEIRS, <%s>: CURSOR, <%s>: ALL THEIRS, <%s>: PREV, <%s>: NEXT]", Config.mappings.diff.ours, Config.mappings.diff.theirs, Config.mappings.diff.cursor, Config.mappings.diff.all_theirs, Config.mappings.diff.prev, Config.mappings.diff.next ) show_keybinding_hint_extmark_id = api.nvim_buf_set_extmark(bufnr, KEYBINDING_NAMESPACE, lnum - 1, -1, { hl_group = "AvanteInlineHint", virt_text = { { hint, "AvanteInlineHint" } }, virt_text_pos = "right_align", priority = PRIORITY, }) end api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI", "WinLeave" }, { buffer = bufnr, callback = function(event) local position = get_current_position(bufnr) if (event.event == "CursorMoved" or event.event == "CursorMovedI") and position then show_keybinding_hint(position.current.range_start + 1) M.override_timeoutlen(bufnr) else api.nvim_buf_clear_namespace(bufnr, KEYBINDING_NAMESPACE, 0, -1) M.restore_timeoutlen(bufnr) end end, }) end ---Get the conflict marker positions for a buffer if any and update the buffers state ---@param bufnr integer ---@param range_start? integer ---@param range_end? integer local function parse_buffer(bufnr, range_start, range_end) local lines = Utils.get_buf_lines(range_start or 0, range_end or -1, bufnr) local prev_conflicts = visited_buffers[bufnr].positions ~= nil and #visited_buffers[bufnr].positions > 0 local has_conflict, positions = detect_conflicts(lines) update_visited_buffers(bufnr, positions) if has_conflict then register_cursor_move_events(bufnr) highlight_conflicts(bufnr, positions, lines) else M.clear(bufnr) end if prev_conflicts ~= has_conflict or not vim.b[bufnr].avante_conflict_mappings_set then local pattern = has_conflict and "AvanteConflictDetected" or "AvanteConflictResolved" api.nvim_exec_autocmds("User", { pattern = pattern }) end end ---Process a buffer if the changed tick has changed ---@param bufnr integer ---@param range_start integer? ---@param range_end integer? function M.process(bufnr, range_start, range_end) bufnr = bufnr if visited_buffers[bufnr] and visited_buffers[bufnr].tick == vim.b[bufnr].changedtick then return end parse_buffer(bufnr, range_start, range_end) end -----------------------------------------------------------------------------// -- Mappings -----------------------------------------------------------------------------// ---@param bufnr integer given buffer id function H.setup_buffer_mappings(bufnr) ---@param desc string local function opts(desc) return { silent = true, buffer = bufnr, desc = "avante(conflict): " .. desc } end vim.keymap.set({ "n", "v" }, Config.mappings.diff.ours, function() M.choose("ours") end, opts("choose ours")) vim.keymap.set({ "n", "v" }, Config.mappings.diff.both, function() M.choose("both") end, opts("choose both")) vim.keymap.set({ "n", "v" }, Config.mappings.diff.theirs, function() M.choose("theirs") end, opts("choose theirs")) vim.keymap.set( { "n", "v" }, Config.mappings.diff.all_theirs, function() M.choose("all_theirs") end, opts("choose all theirs") ) vim.keymap.set("n", Config.mappings.diff.cursor, function() M.choose("cursor") end, opts("choose under cursor")) vim.keymap.set("n", Config.mappings.diff.prev, function() M.find_prev("ours") end, opts("previous conflict")) vim.keymap.set("n", Config.mappings.diff.next, function() M.find_next("ours") end, opts("next conflict")) vim.b[bufnr].avante_conflict_mappings_set = true end ---@param bufnr integer function H.clear_buffer_mappings(bufnr) if not bufnr or not vim.b[bufnr].avante_conflict_mappings_set then return end for _, diff_mapping in pairs(Config.mappings.diff) do pcall(vim.api.nvim_buf_del_keymap, bufnr, "n", diff_mapping) end vim.b[bufnr].avante_conflict_mappings_set = false M.restore_timeoutlen(bufnr) end ---@param bufnr integer function M.override_timeoutlen(bufnr) if vim.b[bufnr].avante_original_timeoutlen then return end if Config.diff.override_timeoutlen > 0 then vim.b[bufnr].avante_original_timeoutlen = vim.o.timeoutlen vim.o.timeoutlen = Config.diff.override_timeoutlen end end ---@param bufnr integer function M.restore_timeoutlen(bufnr) if vim.b[bufnr].avante_original_timeoutlen then vim.o.timeoutlen = vim.b[bufnr].avante_original_timeoutlen vim.b[bufnr].avante_original_timeoutlen = nil end end M.augroup = api.nvim_create_augroup(AUGROUP_NAME, { clear = true }) function M.setup() local previous_inlay_enabled = nil api.nvim_create_autocmd("User", { group = M.augroup, pattern = "AvanteConflictDetected", callback = function(ev) vim.diagnostic.enable(false, { bufnr = ev.buf }) if vim.lsp.inlay_hint then previous_inlay_enabled = vim.lsp.inlay_hint.is_enabled({ bufnr = ev.buf }) vim.lsp.inlay_hint.enable(false, { bufnr = ev.buf }) end H.setup_buffer_mappings(ev.buf) end, }) api.nvim_create_autocmd("User", { group = M.augroup, pattern = "AvanteConflictResolved", callback = function(ev) vim.diagnostic.enable(true, { bufnr = ev.buf }) if vim.lsp.inlay_hint and previous_inlay_enabled ~= nil then vim.lsp.inlay_hint.enable(previous_inlay_enabled, { bufnr = ev.buf }) previous_inlay_enabled = nil end H.clear_buffer_mappings(ev.buf) end, }) api.nvim_set_decoration_provider(NAMESPACE, { on_win = function(_, _, bufnr, _, _) if visited_buffers[bufnr] then M.process(bufnr) end end, }) end --- Add additional metadata to a quickfix entry if we have already visited the buffer and have that --- information ---@param item table<string, integer|string> ---@param items table<string, integer|string>[] ---@param visited_buf ConflictBufferCache local function quickfix_items_from_positions(item, items, visited_buf) if vim.tbl_isempty(visited_buf.positions) then return end for _, pos in ipairs(visited_buf.positions) do for key, value in pairs(pos) do if vim.tbl_contains({ name_map.ours, name_map.theirs, name_map.base }, key) and not vim.tbl_isempty(value) then local lnum = value.range_start + 1 local next_item = vim.deepcopy(item) next_item.text = string.format("%s change", key, lnum) next_item.lnum = lnum next_item.col = 0 table.insert(items, next_item) end end end end --- Convert the conflicts detected via get conflicted files into a list of quickfix entries. ---@param callback fun(files: table<string, integer[]>) function M.conflicts_to_qf_items(callback) local items = {} for filename, visited_buf in pairs(visited_buffers) do local item = { filename = filename, pattern = conflict_start, text = "git conflict", type = "E", valid = 1, } if visited_buf and next(visited_buf) then quickfix_items_from_positions(item, items, visited_buf) else table.insert(items, item) end end callback(items) end ---@param bufnr integer? function M.clear(bufnr) if bufnr and not api.nvim_buf_is_valid(bufnr) then return end bufnr = bufnr or 0 api.nvim_buf_clear_namespace(bufnr, NAMESPACE, 0, -1) api.nvim_buf_clear_namespace(bufnr, KEYBINDING_NAMESPACE, 0, -1) end ---@param side ConflictSide function M.find_next(side) local pos = find_position( 0, function(line, position) return position.current.range_start > line and position.incoming.range_end > line end ) set_cursor(pos, side) end ---@param side ConflictSide function M.find_prev(side) local pos = find_position( 0, function(line, position) return position.current.range_start <= line and position.incoming.range_end <= line end, { reverse = true } ) set_cursor(pos, side) end ---Select the changes to keep ---@param side ConflictSide function M.choose(side) local bufnr = api.nvim_get_current_buf() if vim.fn.mode() == "v" or vim.fn.mode() == "V" or vim.fn.mode() == "" then vim.cmd("noautocmd stopinsert") -- have to defer so that the < and > marks are set vim.defer_fn(function() local start = api.nvim_buf_get_mark(0, "<")[1] local finish = api.nvim_buf_get_mark(0, ">")[1] local position = find_position(bufnr, function(_, pos) local left = pos.current.range_start >= start - 1 local right = pos.incoming.range_end <= finish + 1 return left and right end) while position ~= nil do M.process_position(bufnr, side, position, false) position = find_position(bufnr, function(_, pos) local left = pos.current.range_start >= start - 1 local right = pos.incoming.range_end <= finish + 1 return left and right end) end end, 50) if Config.diff.autojump then M.find_next(side) vim.cmd([[normal! zz]]) end return end local position = get_current_position(bufnr) if not position then return end if side == SIDES.ALL_THEIRS then ---@diagnostic disable-next-line: unused-local local pos = find_position(bufnr, function(line, pos) return true end) while pos ~= nil do M.process_position(bufnr, "theirs", pos, false) ---@diagnostic disable-next-line: unused-local pos = find_position(bufnr, function(line, pos_) return true end) end else M.process_position(bufnr, side, position, true) end end ---@param side ConflictSide ---@param position ConflictPosition ---@param enable_autojump boolean function M.process_position(bufnr, side, position, enable_autojump) local lines = {} if vim.tbl_contains({ SIDES.OURS, SIDES.THEIRS }, side) then local data = position[name_map[side]] lines = Utils.get_buf_lines(data.content_start, data.content_end + 1) elseif side == SIDES.BOTH then local first = Utils.get_buf_lines(position.current.content_start, position.current.content_end + 1) local second = Utils.get_buf_lines(position.incoming.content_start, position.incoming.content_end + 1) lines = vim.list_extend(first, second) elseif side == SIDES.NONE then lines = {} elseif side == SIDES.CURSOR then local cursor_line = Utils.get_cursor_pos() for _, pos in ipairs({ SIDES.OURS, SIDES.THEIRS }) do local data = position[name_map[pos]] or {} if data.range_start and data.range_start + 1 <= cursor_line and data.range_end + 1 >= cursor_line then side = pos lines = Utils.get_buf_lines(data.content_start, data.content_end + 1) break end end if side == SIDES.CURSOR then return end else return end local pos_start = position.current.range_start < 0 and 0 or position.current.range_start local pos_end = position.incoming.range_end + 1 api.nvim_buf_set_lines(0, pos_start, pos_end, false, lines) api.nvim_buf_del_extmark(0, NAMESPACE, position.marks.incoming.label) api.nvim_buf_del_extmark(0, NAMESPACE, position.marks.current.label) parse_buffer(bufnr) if enable_autojump and Config.diff.autojump then M.find_next(side) vim.cmd([[normal! zz]]) end end function M.conflict_count(bufnr) if bufnr and not api.nvim_buf_is_valid(bufnr) then return 0 end bufnr = bufnr or 0 local name = api.nvim_buf_get_name(bufnr) if not visited_buffers[name] then return 0 end return #visited_buffers[name].positions end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/extensions/init.lua
Lua
---@class avante.extensions local M = {} setmetatable(M, { __index = function(t, k) ---@diagnostic disable-next-line: no-unknown t[k] = require("avante.extensions." .. k) return t[k] end, })
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/extensions/nvim_tree.lua
Lua
local Api = require("avante.api") --- @class avante.extensions.nvim_tree local M = {} --- Adds the currently selected file in NvimTree to the selection via Api.add_selected_file. -- Notifies the user if not invoked within NvimTree or if errors occur. --- @return nil function M.add_file() if vim.bo.filetype ~= "NvimTree" then vim.notify("This action can only be used inside NvimTree.", vim.log.levels.WARN) return end local ok, nvim_tree_api = pcall(require, "nvim-tree.api") if not ok then vim.notify("nvim-tree needed", vim.log.levels.ERROR) return end local success, node = pcall(function() return nvim_tree_api.tree.get_node_under_cursor() end) if not success then vim.notify("Error getting node: " .. tostring(node), vim.log.levels.ERROR) return end local filepath = node.absolute_path Api.add_selected_file(filepath) end --- Removes the currently selected file in NvimTree from the selection via Api.remove_selected_file. -- Notifies the user if not invoked within NvimTree or if errors occur. --- @return nil function M.remove_file() if vim.bo.filetype ~= "NvimTree" then vim.notify("This action can only be used inside NvimTree.", vim.log.levels.WARN) return end local ok, nvim_tree_api = pcall(require, "nvim-tree.api") if not ok then vim.notify("nvim-tree needed", vim.log.levels.ERROR) return end local success, node = pcall(function() return nvim_tree_api.tree.get_node_under_cursor() end) if not success then vim.notify("Error getting node: " .. tostring(node), vim.log.levels.ERROR) return end local filepath = node.absolute_path Api.remove_selected_file(filepath) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/file_selector.lua
Lua
local Utils = require("avante.utils") local Config = require("avante.config") local Selector = require("avante.ui.selector") local PROMPT_TITLE = "(Avante) Add a file" --- @class FileSelector local FileSelector = {} --- @class FileSelector --- @field id integer --- @field selected_filepaths string[] Absolute paths --- @field event_handlers table<string, function[]> ---@alias FileSelectorHandler fun(self: FileSelector, on_select: fun(filepaths: string[] | nil)): nil local function has_scheme(path) return path:find("^(?!term://)%w+://") ~= nil end function FileSelector:process_directory(absolute_path) if absolute_path:sub(-1) == Utils.path_sep then absolute_path = absolute_path:sub(1, -2) end local files = Utils.scan_directory({ directory = absolute_path, add_dirs = false }) for _, file in ipairs(files) do local abs_path = Utils.to_absolute_path(file) if not vim.tbl_contains(self.selected_filepaths, abs_path) then table.insert(self.selected_filepaths, abs_path) end end self:emit("update") end ---@param selected_paths string[] | nil ---@return nil function FileSelector:handle_path_selection(selected_paths) if not selected_paths then return end for _, selected_path in ipairs(selected_paths) do local absolute_path = Utils.to_absolute_path(selected_path) if vim.fn.isdirectory(absolute_path) == 1 then self:process_directory(absolute_path) else local abs_path = Utils.to_absolute_path(selected_path) if Config.file_selector.provider == "native" then table.insert(self.selected_filepaths, abs_path) else if not vim.tbl_contains(self.selected_filepaths, abs_path) then table.insert(self.selected_filepaths, abs_path) end end end end self:emit("update") end ---Scans a given directory and produces a list of files/directories with absolute paths ---@param excluded_paths_set? table<string, boolean> Optional set of absolute paths to exclude ---@return { path: string, is_dir: boolean }[] local function get_project_filepaths(excluded_paths_set) excluded_paths_set = excluded_paths_set or {} local project_root = Utils.get_project_root() local files = Utils.scan_directory({ directory = project_root, add_dirs = true }) return vim .iter(files) :filter(function(path) return not excluded_paths_set[path] end) :map(function(path) local is_dir = vim.fn.isdirectory(path) == 1 return { path = path, is_dir = is_dir } end) :totable() end ---@param id integer ---@return FileSelector function FileSelector:new(id) return setmetatable({ id = id, selected_filepaths = {}, event_handlers = {}, }, { __index = self }) end function FileSelector:reset() self.selected_filepaths = {} self.event_handlers = {} self:emit("update") end function FileSelector:add_selected_file(filepath) if not filepath or filepath == "" or has_scheme(filepath) then return end if filepath:match("^oil:") then filepath = filepath:gsub("^oil:", "") end local absolute_path = Utils.to_absolute_path(filepath) if vim.fn.isdirectory(absolute_path) == 1 then self:process_directory(absolute_path) return end -- Avoid duplicates if not vim.tbl_contains(self.selected_filepaths, absolute_path) then table.insert(self.selected_filepaths, absolute_path) self:emit("update") end end function FileSelector:add_current_buffer() local current_buf = vim.api.nvim_get_current_buf() local filepath = vim.api.nvim_buf_get_name(current_buf) if filepath and filepath ~= "" and not has_scheme(filepath) then local absolute_path = Utils.to_absolute_path(filepath) for i, path in ipairs(self.selected_filepaths) do if path == absolute_path then table.remove(self.selected_filepaths, i) self:emit("update") return true end end self:add_selected_file(absolute_path) return true end return false end function FileSelector:on(event, callback) local handlers = self.event_handlers[event] if not handlers then handlers = {} self.event_handlers[event] = handlers end table.insert(handlers, callback) end function FileSelector:emit(event, ...) local handlers = self.event_handlers[event] if not handlers then return end for _, handler in ipairs(handlers) do handler(...) end end function FileSelector:off(event, callback) if not callback then self.event_handlers[event] = {} return end local handlers = self.event_handlers[event] if not handlers then return end for i, handler in ipairs(handlers) do if handler == callback then table.remove(handlers, i) break end end end function FileSelector:open() self:show_selector_ui() end function FileSelector:get_filepaths() if type(Config.file_selector.provider_opts.get_filepaths) == "function" then ---@type avante.file_selector.opts.IGetFilepathsParams local params = { cwd = Utils.get_project_root(), selected_filepaths = self.selected_filepaths, } return Config.file_selector.provider_opts.get_filepaths(params) end local selected_filepaths_set = {} for _, abs_path in ipairs(self.selected_filepaths) do selected_filepaths_set[abs_path] = true end local project_root = Utils.get_project_root() local file_info = get_project_filepaths(selected_filepaths_set) table.sort(file_info, function(a, b) -- Sort alphabetically with directories being first if a.is_dir and not b.is_dir then return true elseif not a.is_dir and b.is_dir then return false else return a.path < b.path end end) return vim .iter(file_info) :map(function(info) local rel_path = Utils.make_relative_path(info.path, project_root) if info.is_dir then rel_path = rel_path .. "/" end return rel_path end) :totable() end ---@return nil function FileSelector:show_selector_ui() local function handler(selected_paths) self:handle_path_selection(selected_paths) end vim.schedule(function() if Config.file_selector.provider ~= nil then Utils.warn("config.file_selector is deprecated, please use config.selector instead!") if type(Config.file_selector.provider) == "function" then local title = string.format("%s:", PROMPT_TITLE) ---@type string local filepaths = self:get_filepaths() ---@type string[] local params = { title = title, filepaths = filepaths, handler = handler } ---@type avante.file_selector.IParams Config.file_selector.provider(params) else ---@type avante.SelectorProvider local provider = "native" if Config.file_selector.provider == "native" then provider = "native" elseif Config.file_selector.provider == "fzf" then provider = "fzf_lua" elseif Config.file_selector.provider == "mini.pick" then provider = "mini_pick" elseif Config.file_selector.provider == "snacks" then provider = "snacks" elseif Config.file_selector.provider == "telescope" then provider = "telescope" elseif type(Config.file_selector.provider) == "function" then provider = Config.file_selector.provider end ---@cast provider avante.SelectorProvider local selector = Selector:new({ provider = provider, title = PROMPT_TITLE, items = vim.tbl_map(function(filepath) return { id = filepath, title = filepath } end, self:get_filepaths()), default_item_id = self.selected_filepaths[1], selected_item_ids = self.selected_filepaths, provider_opts = Config.file_selector.provider_opts, on_select = function(item_ids) self:handle_path_selection(item_ids) end, get_preview_content = function(item_id) local content = Utils.read_file_from_buf_or_disk(item_id) local filetype = Utils.get_filetype(item_id) return table.concat(content or {}, "\n"), filetype end, }) selector:open() end else local selector = Selector:new({ provider = Config.selector.provider, title = PROMPT_TITLE, items = vim.tbl_map(function(filepath) return { id = filepath, title = filepath } end, self:get_filepaths()), default_item_id = self.selected_filepaths[1], selected_item_ids = self.selected_filepaths, provider_opts = Config.selector.provider_opts, on_select = function(item_ids) self:handle_path_selection(item_ids) end, get_preview_content = function(item_id) local content = Utils.read_file_from_buf_or_disk(item_id) local filetype = Utils.get_filetype(item_id) return table.concat(content or {}, "\n"), filetype end, }) selector:open() end end) -- unlist the current buffer as vim.ui.select will be listed local winid = vim.api.nvim_get_current_win() local bufnr = vim.api.nvim_win_get_buf(winid) vim.api.nvim_set_option_value("buflisted", false, { buf = bufnr }) vim.api.nvim_set_option_value("bufhidden", "wipe", { buf = bufnr }) end ---@param idx integer ---@return boolean function FileSelector:remove_selected_filepaths_with_index(idx) if idx > 0 and idx <= #self.selected_filepaths then table.remove(self.selected_filepaths, idx) self:emit("update") return true end return false end function FileSelector:remove_selected_file(rel_path) local abs_path = Utils.to_absolute_path(rel_path) local idx = Utils.tbl_indexof(self.selected_filepaths, abs_path) if idx then self:remove_selected_filepaths_with_index(idx) end end ---@return { path: string, content: string, file_type: string }[] function FileSelector:get_selected_files_contents() local contents = {} for _, filepath in ipairs(self.selected_filepaths) do local lines, error = Utils.read_file_from_buf_or_disk(filepath) lines = lines or {} local filetype = Utils.get_filetype(filepath) if error ~= nil then Utils.error("error reading file: " .. error) else local content = table.concat(lines, "\n") table.insert(contents, { path = filepath, content = content, file_type = filetype }) end end return contents end function FileSelector:get_selected_filepaths() return vim.deepcopy(self.selected_filepaths) end ---@return nil function FileSelector:add_quickfix_files() local quickfix_files = vim .iter(vim.fn.getqflist({ items = 0 }).items) :filter(function(item) return item.bufnr ~= 0 end) :map(function(item) return Utils.to_absolute_path(vim.api.nvim_buf_get_name(item.bufnr)) end) :totable() for _, filepath in ipairs(quickfix_files) do self:add_selected_file(filepath) end end ---@return nil function FileSelector:add_buffer_files() local buffers = vim.api.nvim_list_bufs() for _, bufnr in ipairs(buffers) do -- Skip invalid or unlisted buffers if vim.api.nvim_buf_is_valid(bufnr) and vim.bo[bufnr].buflisted then local filepath = vim.api.nvim_buf_get_name(bufnr) -- Skip empty paths and special buffers (like terminals) if filepath ~= "" and not has_scheme(filepath) then local absolute_path = Utils.to_absolute_path(filepath) self:add_selected_file(absolute_path) end end end end return FileSelector
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/health.lua
Lua
local M = {} local H = require("vim.health") local Utils = require("avante.utils") local Config = require("avante.config") function M.check() H.start("avante.nvim") -- Required dependencies with their module names local required_plugins = { ["plenary.nvim"] = { path = "nvim-lua/plenary.nvim", module = "plenary", }, ["nui.nvim"] = { path = "MunifTanjim/nui.nvim", module = "nui.popup", }, } for name, plugin in pairs(required_plugins) do if Utils.has(name) or Utils.has(plugin.module) then H.ok(string.format("Found required plugin: %s", plugin.path)) else H.error(string.format("Missing required plugin: %s", plugin.path)) end end -- Optional dependencies if Utils.icons_enabled() then H.ok("Found icons plugin (nvim-web-devicons or mini.icons)") else H.warn("No icons plugin found (nvim-web-devicons or mini.icons). Icons will not be displayed") end -- Check input UI provider local input_provider = Config.input and Config.input.provider or "native" if input_provider == "dressing" then if Utils.has("dressing.nvim") or Utils.has("dressing") then H.ok("Found configured input provider: dressing.nvim") else H.error("Input provider is set to 'dressing' but dressing.nvim is not installed") end elseif input_provider == "snacks" then if Utils.has("snacks.nvim") or Utils.has("snacks") then H.ok("Found configured input provider: snacks.nvim") else H.error("Input provider is set to 'snacks' but snacks.nvim is not installed") end else H.ok("Using native input provider (no additional dependencies required)") end -- Check Copilot if configured if Config.provider and Config.provider == "copilot" then if Utils.has("copilot.lua") or Utils.has("copilot.vim") or Utils.has("copilot") then H.ok("Found Copilot plugin") else H.error("Copilot provider is configured but neither copilot.lua nor copilot.vim is installed") end end -- Check TreeSitter dependencies M.check_treesitter() end -- Check TreeSitter functionality and parsers function M.check_treesitter() H.start("TreeSitter Dependencies") -- List of important parsers for avante.nvim local essential_parsers = { "markdown", } local missing_parsers = {} ---@type string[] for _, parser_name in ipairs(essential_parsers) do local loaded_parser = vim.treesitter.language.add(parser_name) if not loaded_parser then missing_parsers[#missing_parsers + 1] = parser_name end end if #missing_parsers == 0 then H.ok("All essential TreeSitter parsers are installed") else H.warn( string.format( "Missing recommended parsers: %s. Install with :TSInstall %s", table.concat(missing_parsers, ", "), table.concat(missing_parsers, " ") ) ) end -- Check TreeSitter highlight local _, highlighter = pcall(require, "vim.treesitter.highlighter") if not highlighter then H.warn("TreeSitter highlighter not available. Syntax highlighting might be limited") else H.ok("TreeSitter highlighter is available") end end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/highlights.lua
Lua
local api = vim.api local Config = require("avante.config") local Utils = require("avante.utils") local bit = require("bit") local rshift, band = bit.rshift, bit.band local Highlights = { TITLE = { name = "AvanteTitle", fg = "#1e222a", bg = "#98c379" }, REVERSED_TITLE = { name = "AvanteReversedTitle", fg = "#98c379", bg_link = "NormalFloat" }, SUBTITLE = { name = "AvanteSubtitle", fg = "#1e222a", bg = "#56b6c2" }, REVERSED_SUBTITLE = { name = "AvanteReversedSubtitle", fg = "#56b6c2", bg_link = "NormalFloat" }, THIRD_TITLE = { name = "AvanteThirdTitle", fg = "#ABB2BF", bg = "#353B45" }, REVERSED_THIRD_TITLE = { name = "AvanteReversedThirdTitle", fg = "#353B45", bg_link = "NormalFloat" }, SUGGESTION = { name = "AvanteSuggestion", link = "Comment" }, ANNOTATION = { name = "AvanteAnnotation", link = "Comment" }, POPUP_HINT = { name = "AvantePopupHint", link = "NormalFloat" }, INLINE_HINT = { name = "AvanteInlineHint", link = "Keyword" }, TO_BE_DELETED = { name = "AvanteToBeDeleted", bg = "#ffcccc", strikethrough = true }, TO_BE_DELETED_WITHOUT_STRIKETHROUGH = { name = "AvanteToBeDeletedWOStrikethrough", bg = "#562C30" }, CONFIRM_TITLE = { name = "AvanteConfirmTitle", fg = "#1e222a", bg = "#e06c75" }, BUTTON_DEFAULT = { name = "AvanteButtonDefault", fg = "#1e222a", bg = "#ABB2BF" }, BUTTON_DEFAULT_HOVER = { name = "AvanteButtonDefaultHover", fg = "#1e222a", bg = "#a9cf8a" }, BUTTON_PRIMARY = { name = "AvanteButtonPrimary", fg = "#1e222a", bg = "#ABB2BF" }, BUTTON_PRIMARY_HOVER = { name = "AvanteButtonPrimaryHover", fg = "#1e222a", bg = "#56b6c2" }, BUTTON_DANGER = { name = "AvanteButtonDanger", fg = "#1e222a", bg = "#ABB2BF" }, BUTTON_DANGER_HOVER = { name = "AvanteButtonDangerHover", fg = "#1e222a", bg = "#e06c75" }, AVANTE_PROMPT_INPUT = { name = "AvantePromptInput" }, AVANTE_PROMPT_INPUT_BORDER = { name = "AvantePromptInputBorder", link = "NormalFloat" }, AVANTE_SIDEBAR_WIN_SEPARATOR = { name = "AvanteSidebarWinSeparator", fg_link_bg = "NormalFloat", bg_link = "NormalFloat", }, AVANTE_SIDEBAR_WIN_HORIZONTAL_SEPARATOR = { name = "AvanteSidebarWinHorizontalSeparator", fg_link = "WinSeparator", bg_link = "NormalFloat", }, AVANTE_SIDEBAR_NORMAL = { name = "AvanteSidebarNormal", link = "NormalFloat" }, AVANTE_COMMENT_FG = { name = "AvanteCommentFg", fg_link = "Comment" }, AVANTE_REVERSED_NORMAL = { name = "AvanteReversedNormal", fg_link_bg = "Normal", bg_link_fg = "Normal" }, AVANTE_STATE_SPINNER_GENERATING = { name = "AvanteStateSpinnerGenerating", fg = "#1e222a", bg = "#ab9df2" }, AVANTE_STATE_SPINNER_TOOL_CALLING = { name = "AvanteStateSpinnerToolCalling", fg = "#1e222a", bg = "#56b6c2" }, AVANTE_STATE_SPINNER_FAILED = { name = "AvanteStateSpinnerFailed", fg = "#1e222a", bg = "#e06c75" }, AVANTE_STATE_SPINNER_SUCCEEDED = { name = "AvanteStateSpinnerSucceeded", fg = "#1e222a", bg = "#98c379" }, AVANTE_STATE_SPINNER_SEARCHING = { name = "AvanteStateSpinnerSearching", fg = "#1e222a", bg = "#c678dd" }, AVANTE_STATE_SPINNER_THINKING = { name = "AvanteStateSpinnerThinking", fg = "#1e222a", bg = "#c678dd" }, AVANTE_STATE_SPINNER_COMPACTING = { name = "AvanteStateSpinnerCompacting", fg = "#1e222a", bg = "#c678dd" }, AVANTE_TASK_RUNNING = { name = "AvanteTaskRunning", fg = "#c678dd", bg_link = "Normal" }, AVANTE_TASK_COMPLETED = { name = "AvanteTaskCompleted", fg = "#98c379", bg_link = "Normal" }, AVANTE_TASK_FAILED = { name = "AvanteTaskFailed", fg = "#e06c75", bg_link = "Normal" }, AVANTE_THINKING = { name = "AvanteThinking", fg = "#c678dd", bg_link = "Normal" }, -- Gradient logo highlights AVANTE_LOGO_LINE_1 = { name = "AvanteLogoLine1", fg = "#f5f5f5" }, AVANTE_LOGO_LINE_2 = { name = "AvanteLogoLine2", fg = "#e8e8e8" }, AVANTE_LOGO_LINE_3 = { name = "AvanteLogoLine3", fg = "#dbdbdb" }, AVANTE_LOGO_LINE_4 = { name = "AvanteLogoLine4", fg = "#cfcfcf" }, AVANTE_LOGO_LINE_5 = { name = "AvanteLogoLine5", fg = "#c2c2c2" }, AVANTE_LOGO_LINE_6 = { name = "AvanteLogoLine6", fg = "#b5b5b5" }, AVANTE_LOGO_LINE_7 = { name = "AvanteLogoLine7", fg = "#a8a8a8" }, AVANTE_LOGO_LINE_8 = { name = "AvanteLogoLine8", fg = "#9b9b9b" }, AVANTE_LOGO_LINE_9 = { name = "AvanteLogoLine9", fg = "#8e8e8e" }, AVANTE_LOGO_LINE_10 = { name = "AvanteLogoLine10", fg = "#818181" }, AVANTE_LOGO_LINE_11 = { name = "AvanteLogoLine11", fg = "#747474" }, AVANTE_LOGO_LINE_12 = { name = "AvanteLogoLine12", fg = "#676767" }, AVANTE_LOGO_LINE_13 = { name = "AvanteLogoLine13", fg = "#5a5a5a" }, AVANTE_LOGO_LINE_14 = { name = "AvanteLogoLine14", fg = "#4d4d4d" }, } Highlights.conflict = { CURRENT = { name = "AvanteConflictCurrent", bg = "#562C30", bold = true }, CURRENT_LABEL = { name = "AvanteConflictCurrentLabel", shade_link = "AvanteConflictCurrent", shade = 30 }, INCOMING = { name = "AvanteConflictIncoming", bg = 3229523, bold = true }, -- #314753 INCOMING_LABEL = { name = "AvanteConflictIncomingLabel", shade_link = "AvanteConflictIncoming", shade = 30 }, } --- helper local H = {} local M = {} local function has_set_colors(hl_group) return next(Utils.get_hl(hl_group)) ~= nil end local first_setup = true local already_set_highlights = {} function M.setup() if Config.behaviour.auto_set_highlight_group then vim .iter(Highlights) :filter(function(k, _) -- return all uppercase key with underscore or fully uppercase key return k:match("^%u+_") or k:match("^%u+$") end) :each(function(_, hl) if first_setup and has_set_colors(hl.name) then already_set_highlights[hl.name] = true end if not already_set_highlights[hl.name] then local bg = hl.bg local fg = hl.fg if hl.bg_link ~= nil then bg = Utils.get_hl(hl.bg_link).bg end if hl.fg_link ~= nil then fg = Utils.get_hl(hl.fg_link).fg end if hl.bg_link_fg ~= nil then bg = Utils.get_hl(hl.bg_link_fg).fg end if hl.fg_link_bg ~= nil then fg = Utils.get_hl(hl.fg_link_bg).bg end api.nvim_set_hl( 0, hl.name, { fg = fg or nil, bg = bg or nil, link = hl.link or nil, strikethrough = hl.strikethrough } ) end end) end if first_setup then vim.iter(Highlights.conflict):each(function(_, hl) if hl.name and has_set_colors(hl.name) then already_set_highlights[hl.name] = true end end) end first_setup = false M.setup_conflict_highlights() end function M.setup_conflict_highlights() local custom_hls = Config.highlights.diff ---@return number | nil local function get_bg(hl_name) return Utils.get_hl(hl_name).bg end local function get_bold(hl_name) return Utils.get_hl(hl_name).bold end vim.iter(Highlights.conflict):each(function(key, hl) --- set none shade linked highlights first if hl.shade_link ~= nil and hl.shade ~= nil then return end if already_set_highlights[hl.name] then return end local bg = hl.bg local bold = hl.bold local custom_hl_name = custom_hls[key:lower()] if custom_hl_name ~= nil then bg = get_bg(custom_hl_name) or hl.bg bold = get_bold(custom_hl_name) or hl.bold end api.nvim_set_hl(0, hl.name, { bg = bg, default = true, bold = bold }) end) vim.iter(Highlights.conflict):each(function(key, hl) --- only set shade linked highlights if hl.shade_link == nil or hl.shade == nil then return end if already_set_highlights[hl.name] then return end local bg local bold = hl.bold local custom_hl_name = custom_hls[key:lower()] if custom_hl_name ~= nil then bg = get_bg(custom_hl_name) bold = get_bold(custom_hl_name) or hl.bold else local link_bg = get_bg(hl.shade_link) if link_bg == nil then Utils.warn(string.format("highlights %s don't have bg, use fallback", hl.shade_link)) link_bg = 3229523 end bg = H.shade_color(link_bg, hl.shade) end api.nvim_set_hl(0, hl.name, { bg = bg, default = true, bold = bold }) end) end setmetatable(M, { __index = function(t, k) if Highlights[k] ~= nil then return Highlights[k].name elseif Highlights.conflict[k] ~= nil then return Highlights.conflict[k].name end return t[k] end, }) --- Returns a table containing the RGB values encoded inside 24 least --- significant bits of the number @rgb_24bit --- ---@param rgb_24bit number 24-bit RGB value ---@return {r: integer, g: integer, b: integer} with keys 'r', 'g', 'b' in [0,255] function H.decode_24bit_rgb(rgb_24bit) if vim.fn.has("nvim-0.11") == 1 then vim.validate("rgb_24bit", rgb_24bit, "number", true) else vim.validate({ rgb_24bit = { rgb_24bit, "number", true } }) end local r = band(rshift(rgb_24bit, 16), 255) local g = band(rshift(rgb_24bit, 8), 255) local b = band(rgb_24bit, 255) return { r = r, g = g, b = b } end ---@param attr integer ---@param percent integer function H.alter(attr, percent) return math.floor(attr * (100 + percent) / 100) end ---@source https://stackoverflow.com/q/5560248 ---@see https://stackoverflow.com/a/37797380 ---Lighten a specified hex color ---@param color number ---@param percent number ---@return string function H.shade_color(color, percent) percent = vim.opt.background:get() == "light" and percent / 5 or percent local rgb = H.decode_24bit_rgb(color) if not rgb.r or not rgb.g or not rgb.b then return "NONE" end local r, g, b = H.alter(rgb.r, percent), H.alter(rgb.g, percent), H.alter(rgb.b, percent) r, g, b = math.min(r, 255), math.min(g, 255), math.min(b, 255) return string.format("#%02x%02x%02x", r, g, b) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/history/helpers.lua
Lua
local Utils = require("avante.utils") local M = {} ---If message is a text message return the text. ---@param message avante.HistoryMessage ---@return string | nil function M.get_text_data(message) local content = message.message.content if type(content) == "table" then assert(#content == 1, "more than one entry in message content") local item = content[1] if type(item) == "string" then return item elseif type(item) == "table" and item.type == "text" then return item.content end elseif type(content) == "string" then return content end end ---If message is a "tool use" message returns information about the tool invocation. ---@param message avante.HistoryMessage ---@return AvanteLLMToolUse | nil function M.get_tool_use_data(message) local content = message.message.content if type(content) == "table" then assert(#content == 1, "more than one entry in message content") local item = content[1] if item.type == "tool_use" then ---@cast item AvanteLLMToolUse return item end end end ---If message is a "tool result" message returns results of the tool invocation. ---@param message avante.HistoryMessage ---@return AvanteLLMToolResult | nil function M.get_tool_result_data(message) local content = message.message.content if type(content) == "table" then assert(#content == 1, "more than one entry in message content") local item = content[1] if item.type == "tool_result" then ---@cast item AvanteLLMToolResult return item end end end ---Attempts to locate result of a tool execution given tool invocation ID ---@param id string ---@param messages avante.HistoryMessage[] ---@return AvanteLLMToolResult | nil function M.get_tool_result(id, messages) for idx = #messages, 1, -1 do local msg = messages[idx] local result = M.get_tool_result_data(msg) if result and result.tool_use_id == id then return result end end end ---Given a tool invocation ID locate corresponding tool use message ---@param id string ---@param messages avante.HistoryMessage[] ---@return avante.HistoryMessage | nil function M.get_tool_use_message(id, messages) for idx = #messages, 1, -1 do local msg = messages[idx] local use = M.get_tool_use_data(msg) if use and use.id == id then return msg end end end ---Given a tool invocation ID locate corresponding tool result message ---@param id string ---@param messages avante.HistoryMessage[] ---@return avante.HistoryMessage | nil function M.get_tool_result_message(id, messages) for idx = #messages, 1, -1 do local msg = messages[idx] local result = M.get_tool_result_data(msg) if result and result.tool_use_id == id then return msg end end end ---@param message avante.HistoryMessage ---@return boolean function M.is_thinking_message(message) local content = message.message.content return type(content) == "table" and (content[1].type == "thinking" or content[1].type == "redacted_thinking") end ---@param message avante.HistoryMessage ---@return boolean function M.is_tool_result_message(message) return M.get_tool_result_data(message) ~= nil end ---@param message avante.HistoryMessage ---@return boolean function M.is_tool_use_message(message) return M.get_tool_use_data(message) ~= nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/history/init.lua
Lua
local Helpers = require("avante.history.helpers") local Message = require("avante.history.message") local Utils = require("avante.utils") local M = {} M.Helpers = Helpers M.Message = Message ---@param history avante.ChatHistory ---@return avante.HistoryMessage[] function M.get_history_messages(history) if history.messages then return history.messages end local messages = {} for _, entry in ipairs(history.entries or {}) do if entry.request and entry.request ~= "" then local message = Message:new("user", entry.request, { timestamp = entry.timestamp, is_user_submission = true, visible = entry.visible, selected_filepaths = entry.selected_filepaths, selected_code = entry.selected_code, }) table.insert(messages, message) end if entry.response and entry.response ~= "" then local message = Message:new("assistant", entry.response, { timestamp = entry.timestamp, visible = entry.visible, }) table.insert(messages, message) end end history.messages = messages return messages end ---Represents information about tool use: invocation, result, affected file (for "view" or "edit" tools). ---@class HistoryToolInfo ---@field kind "edit" | "view" | "other" ---@field use AvanteLLMToolUse ---@field result? AvanteLLMToolResult ---@field result_message? avante.HistoryMessage Complete result message ---@field path? string Uniform (normalized) path of the affected file ---@class HistoryFileInfo ---@field last_tool_id? string ID of the tool with most up-to-date state of the file ---@field edit_tool_id? string ID of the last tool done edit on the file ---Collects information about all uses of tools in the history: their invocations, results, and affected files. ---@param messages avante.HistoryMessage[] ---@return table<string, HistoryToolInfo> ---@return table<string, HistoryFileInfo> local function collect_tool_info(messages) ---@type table<string, HistoryToolInfo> Maps tool ID to tool information local tools = {} ---@type table<string, HistoryFileInfo> Maps file path to file information local files = {} -- Collect invocations of all tools, and also build a list of viewed or edited files. for _, message in ipairs(messages) do local use = Helpers.get_tool_use_data(message) if use then if use.name == "view" or Utils.is_edit_tool_use(use) then if use.input.path then local path = Utils.uniform_path(use.input.path) if use.id then tools[use.id] = { kind = use.name == "view" and "view" or "edit", use = use, path = path } end end else if use.id then tools[use.id] = { kind = "other", use = use } end end goto continue end local result = Helpers.get_tool_result_data(message) if result then -- We assume that "result" entries always come after corresponding "use" entries. local info = tools[result.tool_use_id] if info then info.result = result info.result_message = message if info.path then local f = files[info.path] if not f then f = {} files[info.path] = f end f.last_tool_id = result.tool_use_id if info.kind == "edit" and not (result.is_error or result.is_user_declined) then f.edit_tool_id = result.tool_use_id end end end end ::continue:: end return tools, files end ---Converts a tool invocation (use + result) into a simple request/response pair of text messages ---@param tool_info HistoryToolInfo ---@return avante.HistoryMessage[] local function convert_tool_to_text(tool_info) return { Message:new_assistant_synthetic( string.format("Tool use %s(%s)", tool_info.use.name, vim.json.encode(tool_info.use.input)) ), Message:new_user_synthetic({ type = "text", text = string.format( "Tool use [%s] is successful: %s", tool_info.use.name, tostring(not tool_info.result.is_error) ), }), } end ---Generates a fake file "content" telling LLM to look further for up-to-date data ---@param path string ---@return string local function stale_view_content(path) return string.format("The file %s has been updated. Please use the latest `view` tool result!", path) end ---Updates the result of "view" tool invocation with latest contents of a buffer or file, ---or a stub message if this result will be superseded by another one. ---@param tool_info HistoryToolInfo ---@param stale_view boolean local function update_view_result(tool_info, stale_view) local use = tool_info.use local result = tool_info.result if stale_view then result.content = stale_view_content(tool_info.path) else local view_result, view_error = require("avante.llm_tools.view").func( { path = tool_info.path, start_line = use.input.start_line, end_line = use.input.end_line }, {} ) result.content = view_error and ("Error: " .. view_error) or view_result result.is_error = view_error ~= nil end end ---Generates synthetic "view" tool invocation to tell LLM to refresh its view of a file after editing ---@param tool_use AvanteLLMToolUse ---@param path any ---@param stale_view any ---@return avante.HistoryMessage[] local function generate_view_messages(tool_use, path, stale_view) local view_result, view_error if stale_view then view_result = stale_view_content(path) else view_result, view_error = require("avante.llm_tools.view").func({ path = path }, {}) end if view_error then view_result = "Error: " .. view_error end local view_tool_use_id = Utils.uuid() local view_tool_name = "view" local view_tool_input = { path = path } if tool_use.name == "str_replace_editor" and tool_use.input.command == "str_replace" then view_tool_name = "str_replace_editor" view_tool_input.command = "view" elseif tool_use.name == "str_replace_based_edit_tool" and tool_use.input.command == "str_replace" then view_tool_name = "str_replace_based_edit_tool" view_tool_input.command = "view" end return { Message:new_assistant_synthetic(string.format("Viewing file %s to get the latest content", path)), Message:new_assistant_synthetic({ type = "tool_use", id = view_tool_use_id, name = view_tool_name, input = view_tool_input, }), Message:new_user_synthetic({ type = "tool_result", tool_use_id = view_tool_use_id, content = view_result, is_error = view_error ~= nil, is_user_declined = false, }), } end ---Generates "diagnostic" for a file after it has been edited to help catching errors ---@param path string ---@return avante.HistoryMessage[] local function generate_diagnostic_messages(path) local get_diagnostics_tool_use_id = Utils.uuid() local diagnostics = Utils.lsp.get_diagnostics_from_filepath(path) return { Message:new_assistant_synthetic( string.format("The file %s has been modified, let me check if there are any errors in the changes.", path) ), Message:new_assistant_synthetic({ type = "tool_use", id = get_diagnostics_tool_use_id, name = "get_diagnostics", input = { path = path }, }), Message:new_user_synthetic({ type = "tool_result", tool_use_id = get_diagnostics_tool_use_id, content = vim.json.encode(diagnostics), is_error = false, is_user_declined = false, }), } end ---Iterate through history messages and generate a new list containing updated history ---that has up-to-date file contents and potentially updated diagnostic for modified ---files. ---@param messages avante.HistoryMessage[] ---@param tools HistoryToolInfo[] ---@param files HistoryFileInfo[] ---@param add_diagnostic boolean Whether to generate and add diagnostic info to "edit" invocations ---@param tools_to_text integer Number of tool invocations to be converted to simple text ---@return avante.HistoryMessage[] local function refresh_history(messages, tools, files, add_diagnostic, tools_to_text) ---@type avante.HistoryMessage[] local updated_messages = {} local tool_count = 0 for _, message in ipairs(messages) do local use = Helpers.get_tool_use_data(message) if use then -- This is a tool invocation message. We will be handling both use and result together. local tool_info = tools[use.id] if not tool_info then goto continue end if not tool_info.result then goto continue end if tool_count < tools_to_text then local text_msgs = convert_tool_to_text(tool_info) Utils.debug("Converted", use.name, "invocation to", #text_msgs, "messages") updated_messages = vim.list_extend(updated_messages, text_msgs) else table.insert(updated_messages, message) table.insert(updated_messages, tool_info.result_message) tool_count = tool_count + 1 if tool_info.kind == "view" then local path = tool_info.path assert(path, "encountered 'view' tool invocation without path") update_view_result(tool_info, use.id ~= files[tool_info.path].last_tool_id) end end if tool_info.kind == "edit" then local path = tool_info.path assert(path, "encountered 'edit' tool invocation without path") local file_info = files[path] -- If this is the last operation for this file, generate synthetic "view" -- invocation to provide the up-to-date file contents. if not tool_info.result.is_error then local view_msgs = generate_view_messages(use, path, use.id == file_info.last_tool_id) Utils.debug("Added", #view_msgs, "'view' tool messages for", path) updated_messages = vim.list_extend(updated_messages, view_msgs) tool_count = tool_count + 1 end if add_diagnostic and use.id == file_info.edit_tool_id then local diag_msgs = generate_diagnostic_messages(path) Utils.debug("Added", #diag_msgs, "'diagnostics' tool messages for", path) updated_messages = vim.list_extend(updated_messages, diag_msgs) tool_count = tool_count + 1 end end elseif not Helpers.get_tool_result_data(message) then -- Skip the tool result messages (since we process them together with their "use"s. -- All other (non-tool-related) messages we simply keep. table.insert(updated_messages, message) end ::continue:: end return updated_messages end ---Analyzes the history looking for tool invocations, drops incomplete invocations, ---and updates complete ones with the latest data available. ---@param messages avante.HistoryMessage[] ---@param max_tool_use integer | nil Maximum number of tool invocations to keep ---@param add_diagnostic boolean Mix in LSP diagnostic info for affected files ---@return avante.HistoryMessage[] M.update_tool_invocation_history = function(messages, max_tool_use, add_diagnostic) local tools, files = collect_tool_info(messages) -- Figure number of tool invocations that should be converted to simple "text" -- messages to reduce prompt costs. local tools_to_text = 0 if max_tool_use then local n_edits = vim.iter(files):fold( 0, ---@param count integer ---@param file_info HistoryFileInfo function(count, file_info) if file_info.edit_tool_id then count = count + 1 end return count end ) -- Each valid "edit" invocation will result in synthetic "view" and also -- in "diagnostic" if it is requested by the caller. local expected = #tools + n_edits + (add_diagnostic and n_edits or 0) tools_to_text = expected - max_tool_use end return refresh_history(messages, tools, files, add_diagnostic, tools_to_text) end ---Scans message history backwards, looking for tool invocations that have not been executed yet ---@param messages avante.HistoryMessage[] ---@return AvantePartialLLMToolUse[] ---@return avante.HistoryMessage[] function M.get_pending_tools(messages) local last_turn_id = nil if #messages > 0 then last_turn_id = messages[#messages].turn_id end local pending_tool_uses = {} ---@type AvantePartialLLMToolUse[] local pending_tool_uses_messages = {} ---@type avante.HistoryMessage[] local tool_result_seen = {} for idx = #messages, 1, -1 do local message = messages[idx] if last_turn_id and message.turn_id ~= last_turn_id then break end local use = Helpers.get_tool_use_data(message) if use then if not tool_result_seen[use.id] then local partial_tool_use = { name = use.name, id = use.id, input = use.input, state = message.state, } table.insert(pending_tool_uses, 1, partial_tool_use) table.insert(pending_tool_uses_messages, 1, message) end goto continue end local result = Helpers.get_tool_result_data(message) if result then tool_result_seen[result.tool_use_id] = true end ::continue:: end return pending_tool_uses, pending_tool_uses_messages end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/history/message.lua
Lua
local Utils = require("avante.utils") ---@class avante.HistoryMessage local M = {} M.__index = M ---@class avante.HistoryMessage.Opts ---@field uuid? string ---@field turn_id? string ---@field state? avante.HistoryMessageState ---@field displayed_content? string ---@field original_content? AvanteLLMMessageContent ---@field selected_code? AvanteSelectedCode ---@field selected_filepaths? string[] ---@field is_calling? boolean ---@field is_dummy? boolean ---@field is_user_submission? boolean ---@field just_for_display? boolean ---@field visible? boolean --- ---@param role "user" | "assistant" ---@param content AvanteLLMMessageContentItem ---@param opts? avante.HistoryMessage.Opts ---@return avante.HistoryMessage function M:new(role, content, opts) ---@type AvanteLLMMessage local message = { role = role, content = type(content) == "string" and content or { content } } local obj = { message = message, uuid = Utils.uuid(), state = "generated", timestamp = Utils.get_timestamp(), is_user_submission = false, visible = true, } obj = vim.tbl_extend("force", obj, opts or {}) return setmetatable(obj, M) end ---Creates a new instance of synthetic (dummy) history message ---@param role "assistant" | "user" ---@param item AvanteLLMMessageContentItem ---@return avante.HistoryMessage function M:new_synthetic(role, item) return M:new(role, item, { is_dummy = true }) end ---Creates a new instance of synthetic (dummy) history message attributed to the assistant ---@param item AvanteLLMMessageContentItem ---@return avante.HistoryMessage function M:new_assistant_synthetic(item) return M:new_synthetic("assistant", item) end ---Creates a new instance of synthetic (dummy) history message attributed to the user ---@param item AvanteLLMMessageContentItem ---@return avante.HistoryMessage function M:new_user_synthetic(item) return M:new_synthetic("user", item) end ---Updates content of a message as long as it is a simple text (or empty). ---@param new_content string function M:update_content(new_content) assert(type(self.message.content) == "string", "can only update content of simple string messages") self.message.content = new_content end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/history/render.lua
Lua
local Helpers = require("avante.history.helpers") local Line = require("avante.ui.line") local Utils = require("avante.utils") local Highlights = require("avante.highlights") local M = {} ---@diagnostic disable-next-line: deprecated local islist = vim.islist or vim.tbl_islist ---Converts text into format suitable for UI ---@param text string ---@param decoration string | nil ---@param filter? fun(text_line: string, idx: integer, len: integer): boolean ---@return avante.ui.Line[] local function text_to_lines(text, decoration, filter) local text_lines = vim.split(text, "\n") local lines = {} for idx, text_line in ipairs(text_lines) do if filter and not filter(text_line, idx, #text_lines) then goto continue end if decoration then table.insert(lines, Line:new({ { decoration }, { text_line } })) else table.insert(lines, Line:new({ { text_line } })) end ::continue:: end return lines end ---Converts text into format suitable for UI ---@param text string ---@param decoration string | nil ---@param truncate boolean | nil ---@return avante.ui.Line[] local function text_to_truncated_lines(text, decoration, truncate) local text_lines = vim.split(text, "\n") local lines = {} for _, text_line in ipairs(text_lines) do if truncate and #lines > 3 then table.insert( lines, Line:new({ { decoration }, { string.format("... (Result truncated, remaining %d lines not shown)", #text_lines - #lines + 1), Highlights.AVANTE_COMMENT_FG, }, }) ) break end table.insert(lines, Line:new({ { decoration }, { text_line } })) end return lines end ---@param lines avante.ui.Line[] ---@param decoration string | nil ---@param truncate boolean | nil ---@return avante.ui.Line[] local function lines_to_truncated_lines(lines, decoration, truncate) local truncated_lines = {} for idx, line in ipairs(lines) do if truncate and #truncated_lines > 3 then table.insert( truncated_lines, Line:new({ { decoration }, { string.format("... (Result truncated, remaining %d lines not shown)", #lines - idx + 1), Highlights.AVANTE_COMMENT_FG, }, }) ) break end table.insert(truncated_lines, line) end return truncated_lines end ---Converts "thinking" item into format suitable for UI ---@param item AvanteLLMMessageContentItem ---@return avante.ui.Line[] local function thinking_to_lines(item) local text = item.thinking or item.data or "" local text_lines = vim.split(text, "\n") --- trim prefix empty lines while #text_lines > 0 and text_lines[1] == "" do table.remove(text_lines, 1) end --- trim suffix empty lines while #text_lines > 0 and text_lines[#text_lines] == "" do table.remove(text_lines, #text_lines) end local ui_lines = {} table.insert(ui_lines, Line:new({ { Utils.icon("🤔 ") .. "Thought content:" } })) table.insert(ui_lines, Line:new({ { "" } })) for _, text_line in ipairs(text_lines) do table.insert(ui_lines, Line:new({ { "> " .. text_line } })) end return ui_lines end ---Converts logs generated by a tool during execution into format suitable for UI ---@param tool_name string ---@param logs string[] ---@return avante.ui.Line[] function M.tool_logs_to_lines(tool_name, logs) local ui_lines = {} local num_logs = #logs for log_idx = 1, num_logs do local log_lines = vim.split(logs[log_idx]:gsub("^%[" .. tool_name .. "%]: ", "", 1), "\n") local num_lines = #log_lines for line_idx = 1, num_lines do local decoration = "│ " table.insert(ui_lines, Line:new({ { decoration }, { " " .. log_lines[line_idx] } })) end end return ui_lines end local STATE_TO_HL = { generating = "AvanteStateSpinnerToolCalling", failed = "AvanteStateSpinnerFailed", succeeded = "AvanteStateSpinnerSucceeded", } function M.get_diff_lines(old_str, new_str, decoration, truncate) local lines = {} local line_count = 0 local old_lines = vim.split(old_str, "\n") local new_lines = vim.split(new_str, "\n") ---@diagnostic disable-next-line: assign-type-mismatch, missing-fields local patch = vim.diff(old_str, new_str, { ---@type integer[][] algorithm = "histogram", result_type = "indices", ctxlen = vim.o.scrolloff, }) local prev_start_a = 0 local truncated_lines = 0 for _, hunk in ipairs(patch) do local start_a, count_a, start_b, count_b = unpack(hunk) local no_change_lines = vim.list_slice(old_lines, prev_start_a, start_a - 1) if truncate then local last_three_no_change_lines = vim.list_slice(no_change_lines, #no_change_lines - 3) truncated_lines = truncated_lines + #no_change_lines - #last_three_no_change_lines if #no_change_lines > 4 then table.insert(lines, Line:new({ { decoration }, { "...", Highlights.AVANTE_COMMENT_FG } })) end no_change_lines = last_three_no_change_lines end for idx, line in ipairs(no_change_lines) do if truncate and line_count > 10 then truncated_lines = truncated_lines + #no_change_lines - idx break end line_count = line_count + 1 table.insert(lines, Line:new({ { decoration }, { line } })) end prev_start_a = start_a + count_a if count_a > 0 then local delete_lines = vim.list_slice(old_lines, start_a, start_a + count_a - 1) for idx, line in ipairs(delete_lines) do if truncate and line_count > 10 then truncated_lines = truncated_lines + #delete_lines - idx break end line_count = line_count + 1 table.insert(lines, Line:new({ { decoration }, { line, Highlights.TO_BE_DELETED_WITHOUT_STRIKETHROUGH } })) end end if count_b > 0 then local create_lines = vim.list_slice(new_lines, start_b, start_b + count_b - 1) for idx, line in ipairs(create_lines) do if truncate and line_count > 10 then truncated_lines = truncated_lines + #create_lines - idx break end line_count = line_count + 1 table.insert(lines, Line:new({ { decoration }, { line, Highlights.INCOMING } })) end end end if prev_start_a < #old_lines then -- Append remaining old_lines local no_change_lines = vim.list_slice(old_lines, prev_start_a, #old_lines) local first_three_no_change_lines = vim.list_slice(no_change_lines, 1, 3) for idx, line in ipairs(first_three_no_change_lines) do if truncate and line_count > 10 then truncated_lines = truncated_lines + #first_three_no_change_lines - idx break end line_count = line_count + 1 table.insert(lines, Line:new({ { decoration }, { line } })) end end if truncate and truncated_lines > 0 then table.insert( lines, Line:new({ { decoration }, { string.format("... (Result truncated, remaining %d lines not shown)", truncated_lines), Highlights.AVANTE_COMMENT_FG, }, }) ) end return lines end ---@param content any ---@param decoration string | nil ---@param truncate boolean | nil function M.get_content_lines(content, decoration, truncate) local lines = {} local content_obj = content if type(content) == "string" then local ok, content_obj_ = pcall(vim.json.decode, content) if ok then content_obj = content_obj_ end end if type(content_obj) == "table" then if islist(content_obj) then local all_lines = {} for _, content_item in ipairs(content_obj) do if type(content_item) == "string" then local lines_ = text_to_lines(content_item, decoration) all_lines = vim.list_extend(all_lines, lines_) end end local lines_ = lines_to_truncated_lines(all_lines, decoration, truncate) lines = vim.list_extend(lines, lines_) end if type(content_obj.content) == "string" then local lines_ = text_to_truncated_lines(content_obj.content, decoration, truncate) lines = vim.list_extend(lines, lines_) end if islist(content_obj.content) then local all_lines = {} for _, content_item in ipairs(content_obj.content) do if type(content_item) == "string" then local lines_ = text_to_lines(content_item, decoration) all_lines = vim.list_extend(all_lines, lines_) end end local lines_ = lines_to_truncated_lines(all_lines, decoration, truncate) lines = vim.list_extend(lines, lines_) end if islist(content_obj.matches) then local all_lines = {} for _, content_item in ipairs(content_obj.matches) do if type(content_item) == "string" then local lines_ = text_to_lines(content_item, decoration) all_lines = vim.list_extend(all_lines, lines_) end end local lines_ = lines_to_truncated_lines(all_lines, decoration, truncate) lines = vim.list_extend(lines, lines_) end end if type(content_obj) == "string" then local lines_ = text_to_lines(content_obj, decoration) local line_count = 0 for idx, line in ipairs(lines_) do if truncate and line_count > 3 then table.insert( lines, Line:new({ { decoration }, { string.format("... (Result truncated, remaining %d lines not shown)", #lines_ - idx + 1), Highlights.AVANTE_COMMENT_FG, }, }) ) break end line_count = line_count + 1 table.insert(lines, line) end end if type(content_obj) == "number" then table.insert(lines, Line:new({ { decoration }, { tostring(content_obj) } })) end if islist(content) then for _, content_item in ipairs(content) do local line_count = 0 if content_item.type == "content" then if content_item.content.type == "text" then local lines_ = text_to_lines(content_item.content.text, decoration, function(text_line, idx, len) if idx == 1 and text_line:match("^%s*```%s*$") then return false end if idx == len and text_line:match("^%s*```%s*$") then return false end return true end) for idx, line in ipairs(lines_) do if truncate and line_count > 3 then table.insert( lines, Line:new({ { decoration }, { string.format("... (Result truncated, remaining %d lines not shown)", #lines_ - idx + 1), Highlights.AVANTE_COMMENT_FG, }, }) ) break end line_count = line_count + 1 table.insert(lines, line) end end elseif content_item.type == "diff" and content_item.oldText ~= nil and content_item.newText ~= nil and content_item.oldText ~= vim.NIL and content_item.newText ~= vim.NIL then local relative_path = Utils.relative_path(content_item.path) table.insert(lines, Line:new({ { decoration }, { "Path: " .. relative_path } })) local lines_ = M.get_diff_lines(content_item.oldText, content_item.newText, decoration, truncate) lines = vim.list_extend(lines, lines_) end end end return lines end ---@param message avante.HistoryMessage ---@return string tool_name ---@return string | nil error function M.get_tool_display_name(message) local content = message.message.content if type(content) ~= "table" then return "", "expected message content to be a table" end ---@cast content AvanteLLMMessageContentItem[] if not islist(content) then return "", "expected message content to be a list" end local item = message.message.content[1] local native_tool_name = item.name if native_tool_name == "other" and message.acp_tool_call then native_tool_name = message.acp_tool_call.title or "Other" end if message.acp_tool_call and message.acp_tool_call.title then native_tool_name = message.acp_tool_call.title end local tool_name = native_tool_name if message.displayed_tool_name then tool_name = message.displayed_tool_name else local param if item.input and type(item.input) == "table" then local path if type(item.input.path) == "string" then path = item.input.path end if type(item.input.rel_path) == "string" then path = item.input.rel_path end if type(item.input.filepath) == "string" then path = item.input.filepath end if type(item.input.file_path) == "string" then path = item.input.file_path end if type(item.input.query) == "string" then param = item.input.query end if type(item.input.pattern) == "string" then param = item.input.pattern end if type(item.input.command) == "string" then param = item.input.command local pieces = vim.split(param, "\n") if #pieces > 1 then param = pieces[1] .. "..." end end if native_tool_name == "execute" and not param then if message.acp_tool_call and message.acp_tool_call.title then param = message.acp_tool_call.title end end if not param and path then local relative_path = Utils.relative_path(path) param = relative_path end end if not param and message.acp_tool_call then if message.acp_tool_call.locations then for _, location in ipairs(message.acp_tool_call.locations) do if location.path then local relative_path = Utils.relative_path(location.path) param = relative_path break end end end end if not param and message.acp_tool_call and message.acp_tool_call.rawInput and message.acp_tool_call.rawInput.command then param = message.acp_tool_call.rawInput.command pcall(function() local project_root = Utils.root.get() param = param:gsub(project_root .. "/?", "") end) end if param then tool_name = native_tool_name .. "(" .. vim.inspect(param) .. ")" end end ---@cast tool_name string return tool_name, nil end ---Converts a tool invocation into format suitable for UI ---@param item AvanteLLMMessageContentItem ---@param message avante.HistoryMessage ---@param messages avante.HistoryMessage[] ---@param expanded boolean | nil ---@return avante.ui.Line[] local function tool_to_lines(item, message, messages, expanded) -- local logs = message.tool_use_logs local lines = {} local tool_name, error = M.get_tool_display_name(message) if error then table.insert(lines, Line:new({ { "❌ " }, { error } })) return lines end local rest_input_text_lines = {} local result = Helpers.get_tool_result(item.id, messages) local state if not result then state = "generating" elseif result.is_error then state = "failed" else state = "succeeded" end table.insert( lines, Line:new({ { "╭─ " }, { " " .. tool_name .. " ", STATE_TO_HL[state] }, { " " .. state }, }) ) -- if logs then vim.list_extend(lines, tool_logs_to_lines(item.name, logs)) end local decoration = "│ " if rest_input_text_lines and #rest_input_text_lines > 0 then local lines_ = text_to_lines(table.concat(rest_input_text_lines, "\n"), decoration) local line_count = 0 for idx, line in ipairs(lines_) do if not expanded and line_count > 3 then table.insert( lines, Line:new({ { decoration }, { string.format("... (Input truncated, remaining %d lines not shown)", #lines_ - idx + 1), Highlights.AVANTE_COMMENT_FG, }, }) ) break end line_count = line_count + 1 table.insert(lines, line) end table.insert(lines, Line:new({ { decoration }, { "" } })) end local add_diff_lines = false if item.input and type(item.input) == "table" then if type(item.input.old_str) == "string" and type(item.input.new_str) == "string" then local diff_lines = M.get_diff_lines(item.input.old_str, item.input.new_str, decoration, not expanded) add_diff_lines = true vim.list_extend(lines, diff_lines) end end if not add_diff_lines and message.acp_tool_call and message.acp_tool_call.rawInput and message.acp_tool_call.rawInput.oldString then local diff_lines = M.get_diff_lines( message.acp_tool_call.rawInput.oldString, message.acp_tool_call.rawInput.newString, decoration, not expanded ) vim.list_extend(lines, diff_lines) end if message.acp_tool_call and message.acp_tool_call.rawOutput and message.acp_tool_call.rawOutput.metadata and message.acp_tool_call.rawOutput.metadata.preview then local preview = message.acp_tool_call.rawOutput.metadata.preview if preview then local content_lines = M.get_content_lines(preview, decoration, not expanded) vim.list_extend(lines, content_lines) end else if message.acp_tool_call and message.acp_tool_call.content then local content = message.acp_tool_call.content if content then local content_lines = M.get_content_lines(content, decoration, not expanded) vim.list_extend(lines, content_lines) end else if result and result.content then local result_content = result.content if result_content then local content_lines = M.get_content_lines(result_content, decoration, not expanded) vim.list_extend(lines, content_lines) end end end end if #lines <= 1 then if state == "generating" then table.insert(lines, Line:new({ { decoration }, { "...", Highlights.AVANTE_COMMENT_FG } })) else table.insert(lines, Line:new({ { decoration }, { "completed" } })) end end --- remove last empty lines while #lines > 0 and lines[#lines].sections[2] and lines[#lines].sections[2][1] == "" do table.remove(lines, #lines) end local last_line = lines[#lines] last_line.sections[1][1] = "╰─ " return lines end ---Converts a message item into representation suitable for UI ---@param item AvanteLLMMessageContentItem ---@param message avante.HistoryMessage ---@param messages avante.HistoryMessage[] ---@param expanded boolean | nil ---@return avante.ui.Line[] local function message_content_item_to_lines(item, message, messages, expanded) if type(item) == "string" then return text_to_lines(item) elseif type(item) == "table" then if item.type == "thinking" or item.type == "redacted_thinking" then return thinking_to_lines(item) elseif item.type == "text" then return text_to_lines(item.text) elseif item.type == "image" then return { Line:new({ { "![image](" .. item.source.media_type .. ": " .. item.source.data .. ")" } }) } elseif item.type == "tool_use" and item.name then local ok, llm_tool = pcall(require, "avante.llm_tools." .. item.name) if ok then local tool_result_message = Helpers.get_tool_result_message(item.id, messages) ---@cast llm_tool AvanteLLMTool if llm_tool.on_render then return llm_tool.on_render(item.input, { logs = message.tool_use_logs, state = message.state, store = message.tool_use_store, result_message = tool_result_message, }) end end local lines = tool_to_lines(item, message, messages, expanded) if message.tool_use_log_lines then lines = vim.list_extend(lines, message.tool_use_log_lines) end return lines end end return {} end ---Converts a message into representation suitable for UI ---@param message avante.HistoryMessage ---@param messages avante.HistoryMessage[] ---@param expanded boolean | nil ---@return avante.ui.Line[] function M.message_to_lines(message, messages, expanded) if message.displayed_content then return text_to_lines(message.displayed_content) end local content = message.message.content if type(content) == "string" then return text_to_lines(content) end if islist(content) then local lines = {} for _, item in ipairs(content) do local item_lines = message_content_item_to_lines(item, message, messages, expanded) lines = vim.list_extend(lines, item_lines) end return lines end return {} end ---Converts a message item into text representation ---@param item AvanteLLMMessageContentItem ---@param message avante.HistoryMessage ---@param messages avante.HistoryMessage[] ---@return string local function message_content_item_to_text(item, message, messages) local lines = message_content_item_to_lines(item, message, messages) return vim.iter(lines):map(function(line) return tostring(line) end):join("\n") end ---Converts a message into text representation ---@param message avante.HistoryMessage ---@param messages avante.HistoryMessage[] ---@return string function M.message_to_text(message, messages) local content = message.message.content if type(content) == "string" then return content end if islist(content) then return vim .iter(content) :map(function(item) return message_content_item_to_text(item, message, messages) end) :filter(function(text) return text ~= "" end) :join("\n") end return "" end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/history_selector.lua
Lua
local History = require("avante.history") local Utils = require("avante.utils") local Path = require("avante.path") local Config = require("avante.config") local Selector = require("avante.ui.selector") ---@class avante.HistorySelector local M = {} ---@param history avante.ChatHistory ---@return table? local function to_selector_item(history) local messages = History.get_history_messages(history) local timestamp = #messages > 0 and messages[#messages].timestamp or history.timestamp local name = history.title .. " - " .. timestamp .. " (" .. #messages .. ")" name = name:gsub("\n", "\\n") return { name = name, filename = history.filename, } end ---@param bufnr integer ---@param cb fun(filename: string) function M.open(bufnr, cb) local selector_items = {} local histories = Path.history.list(bufnr) for _, history in ipairs(histories) do table.insert(selector_items, to_selector_item(history)) end if #selector_items == 0 then Utils.warn("No history items found.") return end local current_selector -- To be able to close it from the keymap current_selector = Selector:new({ provider = Config.selector.provider, -- This should be 'native' for the current setup title = "Avante History (Select, then choose action)", -- Updated title items = vim .iter(selector_items) :map( function(item) return { id = item.filename, title = item.name, } end ) :totable(), on_select = function(item_ids) if not item_ids then return end if #item_ids == 0 then return end cb(item_ids[1]) end, get_preview_content = function(item_id) local history = Path.history.load(vim.api.nvim_get_current_buf(), item_id) local Sidebar = require("avante.sidebar") local content = Sidebar.render_history_content(history) return content, "markdown" end, on_delete_item = function(item_id_to_delete) if not item_id_to_delete then Utils.warn("No item ID provided for deletion.") return end Path.history.delete(bufnr, item_id_to_delete) -- bufnr from M.open's scope end, on_open = function() M.open(bufnr, cb) end, }) current_selector:open() end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/html2md.lua
Lua
---@class AvanteHtml2Md ---@field fetch_md fun(url: string): string local _html2md_lib = nil local M = {} ---@return AvanteHtml2Md|nil function M._init_html2md_lib() if _html2md_lib ~= nil then return _html2md_lib end local ok, core = pcall(require, "avante_html2md") if not ok then return nil end _html2md_lib = core return _html2md_lib end function M.setup() vim.defer_fn(M._init_html2md_lib, 1000) end function M.fetch_md(url) local html2md_lib = M._init_html2md_lib() if not html2md_lib then return nil, "Failed to load avante_html2md" end local ok, res = pcall(html2md_lib.fetch_md, url) if not ok then return nil, res end return res, nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/init.lua
Lua
local api = vim.api local Utils = require("avante.utils") local Sidebar = require("avante.sidebar") local Selection = require("avante.selection") local Suggestion = require("avante.suggestion") local Config = require("avante.config") local Diff = require("avante.diff") local RagService = require("avante.rag_service") ---@class Avante local M = { ---@type avante.Sidebar[] we use this to track chat command across tabs sidebars = {}, ---@type avante.Selection[] selections = {}, ---@type avante.Suggestion[] suggestions = {}, ---@type {sidebar?: avante.Sidebar, selection?: avante.Selection, suggestion?: avante.Suggestion} current = { sidebar = nil, selection = nil, suggestion = nil }, ---@type table<string, any> Global ACP client registry for cleanup on exit acp_clients = {}, } M.did_setup = false -- ACP Client Management Functions ---Register an ACP client for cleanup on exit ---@param client_id string Unique identifier for the client ---@param client any ACP client instance function M.register_acp_client(client_id, client) M.acp_clients[client_id] = client Utils.debug("Registered ACP client: " .. client_id) end ---Unregister an ACP client ---@param client_id string Unique identifier for the client function M.unregister_acp_client(client_id) M.acp_clients[client_id] = nil Utils.debug("Unregistered ACP client: " .. client_id) end ---Cleanup all registered ACP clients function M.cleanup_all_acp_clients() Utils.debug("Cleaning up all ACP clients...") for client_id, client in pairs(M.acp_clients) do if client and client.stop then Utils.debug("Stopping ACP client: " .. client_id) pcall(function() client:stop() end) end end M.acp_clients = {} Utils.debug("All ACP clients cleaned up") end local H = {} function H.load_path() local ok, LazyConfig = pcall(require, "lazy.core.config") if ok then Utils.debug("LazyConfig loaded") local name = "avante.nvim" local function load_path() require("avante_lib").load() end if LazyConfig.plugins[name] and LazyConfig.plugins[name]._.loaded then vim.schedule(load_path) else api.nvim_create_autocmd("User", { pattern = "LazyLoad", callback = function(event) if event.data == name then load_path() return true end end, }) end api.nvim_create_autocmd("User", { pattern = "VeryLazy", callback = load_path, }) else require("avante_lib").load() end end function H.keymaps() vim.keymap.set({ "n", "v" }, "<Plug>(AvanteAsk)", function() require("avante.api").ask() end, { noremap = true }) vim.keymap.set( { "n", "v" }, "<Plug>(AvanteAskNew)", function() require("avante.api").ask({ new_chat = true }) end, { noremap = true } ) vim.keymap.set( { "n", "v" }, "<Plug>(AvanteChat)", function() require("avante.api").ask({ ask = false }) end, { noremap = true } ) vim.keymap.set("v", "<Plug>(AvanteEdit)", function() require("avante.api").edit() end, { noremap = true }) vim.keymap.set("n", "<Plug>(AvanteRefresh)", function() require("avante.api").refresh() end, { noremap = true }) vim.keymap.set("n", "<Plug>(AvanteFocus)", function() require("avante.api").focus() end, { noremap = true }) vim.keymap.set("n", "<Plug>(AvanteBuild)", function() require("avante.api").build() end, { noremap = true }) vim.keymap.set("n", "<Plug>(AvanteToggle)", function() M.toggle() end, { noremap = true }) vim.keymap.set("n", "<Plug>(AvanteToggleDebug)", function() M.toggle.debug() end) vim.keymap.set("n", "<Plug>(AvanteToggleSelection)", function() M.toggle.selection() end) vim.keymap.set("n", "<Plug>(AvanteToggleSuggestion)", function() M.toggle.suggestion() end) vim.keymap.set({ "n", "v" }, "<Plug>(AvanteConflictOurs)", function() Diff.choose("ours") end) vim.keymap.set({ "n", "v" }, "<Plug>(AvanteConflictBoth)", function() Diff.choose("both") end) vim.keymap.set({ "n", "v" }, "<Plug>(AvanteConflictTheirs)", function() Diff.choose("theirs") end) vim.keymap.set({ "n", "v" }, "<Plug>(AvanteConflictAllTheirs)", function() Diff.choose("all_theirs") end) vim.keymap.set({ "n", "v" }, "<Plug>(AvanteConflictCursor)", function() Diff.choose("cursor") end) vim.keymap.set("n", "<Plug>(AvanteConflictNextConflict)", function() Diff.find_next("ours") end) vim.keymap.set("n", "<Plug>(AvanteConflictPrevConflict)", function() Diff.find_prev("ours") end) vim.keymap.set("n", "<Plug>(AvanteSelectModel)", function() require("avante.api").select_model() end) if Config.behaviour.auto_set_keymaps then Utils.safe_keymap_set( { "n", "v" }, Config.mappings.ask, function() require("avante.api").ask() end, { desc = "avante: ask" } ) Utils.safe_keymap_set( { "n", "v" }, Config.mappings.zen_mode, function() require("avante.api").zen_mode() end, { desc = "avante: toggle Zen Mode" } ) Utils.safe_keymap_set( { "n", "v" }, Config.mappings.new_ask, function() require("avante.api").ask({ new_chat = true }) end, { desc = "avante: create new ask" } ) Utils.safe_keymap_set( "v", Config.mappings.edit, function() require("avante.api").edit() end, { desc = "avante: edit" } ) Utils.safe_keymap_set( "n", Config.mappings.stop, function() require("avante.api").stop() end, { desc = "avante: stop" } ) Utils.safe_keymap_set( "n", Config.mappings.refresh, function() require("avante.api").refresh() end, { desc = "avante: refresh" } ) Utils.safe_keymap_set( "n", Config.mappings.focus, function() require("avante.api").focus() end, { desc = "avante: focus" } ) Utils.safe_keymap_set("n", Config.mappings.toggle.default, function() M.toggle() end, { desc = "avante: toggle" }) Utils.safe_keymap_set( "n", Config.mappings.toggle.debug, function() M.toggle.debug() end, { desc = "avante: toggle debug" } ) Utils.safe_keymap_set( "n", Config.mappings.toggle.selection, function() M.toggle.hint() end, { desc = "avante: toggle selection" } ) Utils.safe_keymap_set( "n", Config.mappings.toggle.suggestion, function() M.toggle.suggestion() end, { desc = "avante: toggle suggestion" } ) Utils.safe_keymap_set("n", Config.mappings.toggle.repomap, function() require("avante.repo_map").show() end, { desc = "avante: display repo map", noremap = true, silent = true, }) Utils.safe_keymap_set( "n", Config.mappings.select_model, function() require("avante.api").select_model() end, { desc = "avante: select model" } ) Utils.safe_keymap_set( "n", Config.mappings.select_history, function() require("avante.api").select_history() end, { desc = "avante: select history" } ) Utils.safe_keymap_set( "n", Config.mappings.files.add_all_buffers, function() require("avante.api").add_buffer_files() end, { desc = "avante: add all open buffers" } ) end if Config.behaviour.auto_suggestions then Utils.safe_keymap_set("i", Config.mappings.suggestion.accept, function() local _, _, sg = M.get() sg:accept() end, { desc = "avante: accept suggestion", noremap = true, silent = true, }) Utils.safe_keymap_set("i", Config.mappings.suggestion.dismiss, function() local _, _, sg = M.get() if sg:is_visible() then sg:dismiss() end end, { desc = "avante: dismiss suggestion", noremap = true, silent = true, }) Utils.safe_keymap_set("i", Config.mappings.suggestion.next, function() local _, _, sg = M.get() sg:next() end, { desc = "avante: next suggestion", noremap = true, silent = true, }) Utils.safe_keymap_set("i", Config.mappings.suggestion.prev, function() local _, _, sg = M.get() sg:prev() end, { desc = "avante: previous suggestion", noremap = true, silent = true, }) end end ---@class ApiCaller ---@operator call(...): any function H.api(fun) return setmetatable({ api = true }, { __call = function(...) return fun(...) end, }) --[[@as ApiCaller]] end function H.signs() vim.fn.sign_define("AvanteInputPromptSign", { text = Config.windows.input.prefix }) end H.augroup = api.nvim_create_augroup("avante_autocmds", { clear = true }) function H.autocmds() api.nvim_create_autocmd("TabEnter", { group = H.augroup, pattern = "*", once = true, callback = function(ev) local tab = tonumber(ev.file) M._init(tab or api.nvim_get_current_tabpage()) if Config.selection.enabled and not M.current.selection.did_setup then M.current.selection:setup_autocmds() end end, }) api.nvim_create_autocmd("VimResized", { group = H.augroup, callback = function() local sidebar = M.get() if not sidebar then return end if not sidebar:is_open() then return end sidebar:resize() end, }) api.nvim_create_autocmd("QuitPre", { group = H.augroup, callback = function() local current_buf = vim.api.nvim_get_current_buf() if Utils.is_sidebar_buffer(current_buf) then return end local non_sidebar_wins = 0 local sidebar_wins = {} for _, win in ipairs(vim.api.nvim_list_wins()) do if vim.api.nvim_win_is_valid(win) then local win_buf = vim.api.nvim_win_get_buf(win) if Utils.is_sidebar_buffer(win_buf) then table.insert(sidebar_wins, win) else non_sidebar_wins = non_sidebar_wins + 1 end end end if non_sidebar_wins <= 1 then for _, win in ipairs(sidebar_wins) do pcall(vim.api.nvim_win_close, win, false) end end end, nested = true, }) api.nvim_create_autocmd("TabClosed", { group = H.augroup, pattern = "*", callback = function(ev) local tab = tonumber(ev.file) local s = M.sidebars[tab] local sl = M.selections[tab] if s then s:reset() end if sl then sl:delete_autocmds() end if tab ~= nil then M.sidebars[tab] = nil end end, }) -- Fix Issue #2749: Cleanup ACP processes on Neovim exit api.nvim_create_autocmd("VimLeavePre", { group = H.augroup, desc = "Cleanup all ACP processes before Neovim exits", callback = function() Utils.debug("VimLeavePre: Starting ACP cleanup...") -- Cancel any inflight requests first local ok, Llm = pcall(require, "avante.llm") if ok then pcall(function() Llm.cancel_inflight_request() end) end -- Cleanup all registered ACP clients M.cleanup_all_acp_clients() Utils.debug("VimLeavePre: ACP cleanup completed") end, }) vim.schedule(function() M._init(api.nvim_get_current_tabpage()) if Config.selection.enabled then M.current.selection:setup_autocmds() end end) local function setup_colors() Utils.debug("Setting up avante colors") require("avante.highlights").setup() end api.nvim_create_autocmd("ColorSchemePre", { group = H.augroup, callback = function() vim.schedule(function() setup_colors() end) end, }) api.nvim_create_autocmd("ColorScheme", { group = H.augroup, callback = function() vim.schedule(function() setup_colors() end) end, }) -- automatically setup Avante filetype to markdown vim.treesitter.language.register("markdown", "Avante") vim.filetype.add({ extension = { ["avanterules"] = "jinja", }, pattern = { ["%.avanterules%.[%w_.-]+"] = "jinja", }, }) end ---@param current boolean? false to disable setting current, otherwise use this to track across tabs. ---@return avante.Sidebar, avante.Selection, avante.Suggestion function M.get(current) local tab = api.nvim_get_current_tabpage() local sidebar = M.sidebars[tab] local selection = M.selections[tab] local suggestion = M.suggestions[tab] if current ~= false then M.current.sidebar = sidebar M.current.selection = selection M.current.suggestion = suggestion end return sidebar, selection, suggestion end ---@param id integer function M._init(id) local sidebar = M.sidebars[id] local selection = M.selections[id] local suggestion = M.suggestions[id] if not sidebar then sidebar = Sidebar:new(id) M.sidebars[id] = sidebar end if not selection then selection = Selection:new(id) M.selections[id] = selection end if not suggestion then suggestion = Suggestion:new(id) M.suggestions[id] = suggestion end M.current = { sidebar = sidebar, selection = selection, suggestion = suggestion } return M end M.toggle = { api = true } ---@param opts? AskOptions function M.toggle_sidebar(opts) opts = opts or {} if opts.ask == nil then opts.ask = true end local sidebar = M.get() if not sidebar then M._init(api.nvim_get_current_tabpage()) ---@cast opts SidebarOpenOptions M.current.sidebar:open(opts) return true end return sidebar:toggle(opts) end function M.is_sidebar_open() local sidebar = M.get() if not sidebar then return false end return sidebar:is_open() end ---@param opts? AskOptions function M.open_sidebar(opts) opts = opts or {} if opts.ask == nil then opts.ask = true end local sidebar = M.get() if not sidebar then M._init(api.nvim_get_current_tabpage()) end ---@cast opts SidebarOpenOptions M.current.sidebar:open(opts) end function M.close_sidebar() local sidebar = M.get() if not sidebar then return end sidebar:close() end M.toggle.debug = H.api(Utils.toggle_wrap({ name = "debug", get = function() return Config.debug end, set = function(state) Config.override({ debug = state }) end, })) M.toggle.selection = H.api(Utils.toggle_wrap({ name = "selection", get = function() return Config.selection.enabled end, set = function(state) Config.override({ selection = { enabled = state } }) end, })) M.toggle.suggestion = H.api(Utils.toggle_wrap({ name = "suggestion", get = function() return Config.behaviour.auto_suggestions end, set = function(state) Config.override({ behaviour = { auto_suggestions = state } }) local _, _, sg = M.get() if state ~= false then if sg then sg:setup_autocmds() end H.keymaps() else if sg then sg:delete_autocmds() end end end, })) setmetatable(M.toggle, { __index = M.toggle, __call = function() M.toggle_sidebar() end, }) M.slash_commands_id = nil ---@param opts? avante.Config function M.setup(opts) ---PERF: we can still allow running require("avante").setup() multiple times to override config if users wish to ---but most of the other functionality will only be called once from lazy.nvim Config.setup(opts) if M.did_setup then return end H.load_path() require("avante.html2md").setup() require("avante.repo_map").setup() require("avante.path").setup() require("avante.highlights").setup() require("avante.diff").setup() require("avante.providers").setup() require("avante.clipboard").setup() -- setup helpers H.autocmds() H.keymaps() H.signs() M.did_setup = true local function run_rag_service() local started_at = os.time() local add_resource_with_delay local function add_resource() local is_ready = RagService.is_ready() if not is_ready then local elapsed = os.time() - started_at if elapsed > 1000 * 60 * 15 then Utils.warn("Rag Service is not ready, giving up") return end add_resource_with_delay() return end vim.defer_fn(function() Utils.info("Adding project root to Rag Service ...") local uri = "file://" .. Utils.get_project_root() if uri:sub(-1) ~= "/" then uri = uri .. "/" end RagService.add_resource(uri) end, 5000) end add_resource_with_delay = function() vim.defer_fn(function() add_resource() end, 5000) end vim.schedule(function() Utils.info("Starting Rag Service ...") RagService.launch_rag_service(add_resource_with_delay) end) end if Config.rag_service.enabled then run_rag_service() end local has_cmp, cmp = pcall(require, "cmp") if has_cmp then M.slash_commands_id = cmp.register_source("avante_commands", require("cmp_avante.commands"):new()) cmp.register_source("avante_mentions", require("cmp_avante.mentions"):new(Utils.get_chat_mentions)) cmp.register_source("avante_prompt_mentions", require("cmp_avante.mentions"):new(Utils.get_mentions)) cmp.register_source("avante_shortcuts", require("cmp_avante.shortcuts"):new()) cmp.setup.filetype({ "AvanteInput" }, { enabled = true, sources = { { name = "avante_commands" }, { name = "avante_mentions" }, { name = "avante_shortcuts" }, { name = "avante_files" }, }, }) cmp.setup.filetype({ "AvantePromptInput" }, { enabled = true, sources = { { name = "avante_prompt_mentions" }, }, }) end end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/libs/ReAct_parser.lua
Lua
local M = {} -- Helper function to parse a parameter tag like <param_name>value</param_name> -- Returns {name = string, value = string, next_pos = number} or nil if incomplete local function parse_parameter(text, start_pos) local i = start_pos local len = #text -- Skip whitespace while i <= len and string.match(string.sub(text, i, i), "%s") do i = i + 1 end if i > len or string.sub(text, i, i) ~= "<" then return nil end -- Find parameter name local param_name_start = i + 1 local param_name_end = string.find(text, ">", param_name_start) if not param_name_end then return nil -- Incomplete parameter tag end local param_name = string.sub(text, param_name_start, param_name_end - 1) i = param_name_end + 1 -- Find parameter value (everything until closing tag) local param_close_tag = "</" .. param_name .. ">" local param_value_start = i local param_close_pos = string.find(text, param_close_tag, i, true) if not param_close_pos then -- Incomplete parameter value, return what we have local param_value = string.sub(text, param_value_start) return { name = param_name, value = param_value, next_pos = len + 1, } end local param_value = string.sub(text, param_value_start, param_close_pos - 1) i = param_close_pos + #param_close_tag return { name = param_name, value = param_value, next_pos = i, } end -- Helper function to parse tool use content starting after <tool_use> -- Returns {content = ToolUseContent, next_pos = number} or nil if incomplete local function parse_tool_use(text, start_pos) local i = start_pos local len = #text -- Skip whitespace while i <= len and string.match(string.sub(text, i, i), "%s") do i = i + 1 end if i > len then return nil -- No content after <tool_use> end -- Check if we have opening tag for tool name if string.sub(text, i, i) ~= "<" then return nil -- Invalid format end -- Find tool name local tool_name_start = i + 1 local tool_name_end = string.find(text, ">", tool_name_start) if not tool_name_end then return nil -- Incomplete tool name tag end local tool_name = string.sub(text, tool_name_start, tool_name_end - 1) i = tool_name_end + 1 -- Parse tool parameters local tool_input = {} local partial = false -- Look for tool closing tag or </tool_use> local tool_close_tag = "</" .. tool_name .. ">" local tool_use_close_tag = "</tool_use>" while i <= len do -- Skip whitespace before checking for closing tags while i <= len and string.match(string.sub(text, i, i), "%s") do i = i + 1 end if i > len then partial = true break end -- Check for tool closing tag first local tool_close_pos = string.find(text, tool_close_tag, i, true) local tool_use_close_pos = string.find(text, tool_use_close_tag, i, true) if tool_close_pos and tool_close_pos == i then -- Found tool closing tag i = tool_close_pos + #tool_close_tag -- Skip whitespace while i <= len and string.match(string.sub(text, i, i), "%s") do i = i + 1 end -- Check for </tool_use> if i <= len and string.find(text, tool_use_close_tag, i, true) == i then i = i + #tool_use_close_tag partial = false else partial = true end break elseif tool_use_close_pos and tool_use_close_pos == i then -- Found </tool_use> without tool closing tag (malformed, but handle it) i = tool_use_close_pos + #tool_use_close_tag partial = false break else -- Parse parameter tag local param_result = parse_parameter(text, i) if param_result then tool_input[param_result.name] = param_result.value i = param_result.next_pos else -- Incomplete parameter, mark as partial partial = true break end end end -- If we reached end of text without proper closing, it's partial if i > len then partial = true end return { content = { type = "tool_use", tool_name = tool_name, tool_input = tool_input, partial = partial, }, next_pos = i, } end --- Parse the text into a list of TextContent and ToolUseContent --- The text is a string. --- For example: --- parse("Hello, world!") --- returns --- { --- { --- type = "text", --- text = "Hello, world!", --- partial = false, --- }, --- } --- --- parse("Hello, world! I am a tool.<tool_use><write><path>path/to/file.txt</path><content>foo</content></write></tool_use>") --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "foo", --- }, --- partial = false, --- }, --- } --- --- parse("Hello, world! I am a tool.<tool_use><write><path>path/to/file.txt</path><content>foo</content></write></tool_use>I am another tool.<tool_use><write><path>path/to/file.txt</path><content>bar</content></write></tool_use>hello") --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "foo", --- }, --- partial = false, --- }, --- { --- type = "text", --- text = "I am another tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "bar", --- }, --- partial = false, --- }, --- { --- type = "text", --- text = "hello", --- partial = false, --- }, --- } --- --- parse("Hello, world! I am a tool.<tool_use><write") --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- } --- } --- --- parse("Hello, world! I am a tool.<tool_use><write>") --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = {}, --- partial = true, --- }, --- } --- --- parse("Hello, world! I am a tool.<tool_use><write><path>path/to/file.txt") --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- }, --- partial = true, --- }, --- } --- --- parse("Hello, world! I am a tool.<tool_use><write><path>path/to/file.txt</path><content>foo bar") --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "foo bar", --- }, --- partial = true, --- }, --- } --- --- parse("Hello, world! I am a tool.<write><path>path/to/file.txt</path><content>foo bar") --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.<write><path>path/to/file.txt</path><content>foo bar", --- partial = false, --- } --- } --- --- parse("Hello, world! I am a tool.<tool_use><write><path>path/to/file.txt</path><content><button>foo</button></content></write></tool_use>") --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "<button>foo</button>", --- }, --- partial = false, --- }, --- } --- --- parse("Hello, world! I am a tool.<tool_use><write><path>path/to/file.txt</path><content><button>foo") --- returns --- { --- { --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "<button>foo", --- }, --- partial = true, --- }, --- } --- ---@param text string ---@return (avante.TextContent|avante.ToolUseContent)[] function M.parse(text) local result = {} local current_text = "" local i = 1 local len = #text -- Helper function to add text content to result local function add_text_content() if current_text ~= "" then table.insert(result, { type = "text", text = current_text, partial = false, }) current_text = "" end end -- Helper function to find the next occurrence of a pattern local function find_pattern(pattern, start_pos) return string.find(text, pattern, start_pos, true) end while i <= len do -- Check for <tool_use> tag local tool_use_start = find_pattern("<tool_use>", i) if tool_use_start and tool_use_start == i then -- Found <tool_use> at current position add_text_content() i = i + 10 -- Skip "<tool_use>" -- Parse tool use content local tool_use_result = parse_tool_use(text, i) if tool_use_result then table.insert(result, tool_use_result.content) i = tool_use_result.next_pos else -- Incomplete tool_use, break break end else -- Regular text character if tool_use_start then -- There's a <tool_use> ahead, add text up to that point current_text = current_text .. string.sub(text, i, tool_use_start - 1) i = tool_use_start else -- No more <tool_use> tags, add rest of text current_text = current_text .. string.sub(text, i) break end end end -- Add any remaining text add_text_content() return result end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/libs/ReAct_parser2.lua
Lua
local JsonParser = require("avante.libs.jsonparser") ---@class avante.TextContent ---@field type "text" ---@field text string ---@field partial boolean --- ---@class avante.ToolUseContent ---@field type "tool_use" ---@field tool_name string ---@field tool_input table ---@field partial boolean local M = {} --- Parse the text into a list of TextContent and ToolUseContent --- The text is a string. --- For example: --- parse([[Hello, world!]]) --- returns --- { --- { --- type = "text", --- text = "Hello, world!", --- partial = false, --- }, --- } --- --- parse([[Hello, world! I am a tool.<tool_use>{"name": "write", "input": {"path": "path/to/file.txt", "content": "foo"}}</tool_use>]]) --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "foo", --- }, --- partial = false, --- }, --- } --- --- parse([[Hello, world! I am a tool.<tool_use>{"name": "write", "input": {"path": "path/to/file.txt", "content": "foo"}}</tool_use>I am another tool.<tool_use>{"name": "write", "input": {"path": "path/to/file.txt", "content": "bar"}}</tool_use>hello]]) --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "foo", --- }, --- partial = false, --- }, --- { --- type = "text", --- text = "I am another tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "bar", --- }, --- partial = false, --- }, --- { --- type = "text", --- text = "hello", --- partial = false, --- }, --- } --- --- parse([[Hello, world! I am a tool.<tool_use>{"name"]]) --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- } --- } --- --- parse([[Hello, world! I am a tool.<tool_use>{"name": "write"]]) --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = {}, --- partial = true, --- }, --- } --- --- parse([[Hello, world! I am a tool.<tool_use>{"name": "write", "input": {"path": "path/to/file.txt"]]) --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- }, --- partial = true, --- }, --- } --- --- parse([[Hello, world! I am a tool.<tool_use>{"name": "write", "input": {"path": "path/to/file.txt", "content": "foo bar]]) --- returns --- { --- { --- type = "text", --- text = "Hello, world! I am a tool.", --- partial = false, --- }, --- { --- type = "tool_use", --- tool_name = "write", --- tool_input = { --- path = "path/to/file.txt", --- content = "foo bar", --- }, --- partial = true, --- }, --- } --- --- parse([[Hello, world! I am a tool.{"name": "write", "input": {"path": "path/to/file.txt", "content": foo bar]]) --- returns --- { --- { --- type = "text", --- text = [[Hello, world! I am a tool.{"name": "write", "input": {"path": "path/to/file.txt", "content": foo bar]], --- partial = false, --- } --- } --- ---@param text string ---@return (avante.TextContent|avante.ToolUseContent)[] function M.parse(text) local result = {} local pos = 1 local len = #text while pos <= len do local tool_start = text:find("<tool_use>", pos, true) if not tool_start then -- No more tool_use tags, add remaining text if any if pos <= len then local remaining_text = text:sub(pos) if remaining_text ~= "" then table.insert(result, { type = "text", text = remaining_text, partial = false, }) end end break end -- Add text before tool_use tag if any if tool_start > pos then local text_content = text:sub(pos, tool_start - 1) if text_content ~= "" then table.insert(result, { type = "text", text = text_content, partial = false, }) end end -- Find the closing tag local json_start = tool_start + 10 -- length of "<tool_use>" local tool_end = text:find("</tool_use>", json_start, true) if not tool_end then -- No closing tag found, treat as partial tool_use local json_text = text:sub(json_start) json_text = json_text:gsub("^\n+", "") json_text = json_text:gsub("\n+$", "") json_text = json_text:gsub("^%s+", "") json_text = json_text:gsub("%s+$", "") -- Try to parse complete JSON first local success, json_data = pcall(function() return vim.json.decode(json_text) end) if success and json_data and json_data.name then table.insert(result, { type = "tool_use", tool_name = json_data.name, tool_input = json_data.input or {}, partial = true, }) else local jsn = JsonParser.parse(json_text) if jsn and jsn.name then table.insert(result, { type = "tool_use", tool_name = jsn.name, tool_input = jsn.input or {}, partial = true, }) end end break end -- Extract JSON content local json_text = text:sub(json_start, tool_end - 1) local success, json_data = pcall(function() return vim.json.decode(json_text) end) if success and json_data and json_data.name then table.insert(result, { type = "tool_use", tool_name = json_data.name, tool_input = json_data.input or {}, partial = false, }) pos = tool_end + 11 -- length of "</tool_use>" else -- Invalid JSON, treat the whole thing as text local invalid_text = text:sub(tool_start, tool_end + 10) table.insert(result, { type = "text", text = invalid_text, partial = false, }) pos = tool_end + 11 end end return result end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/libs/acp_client.lua
Lua
local Config = require("avante.config") local Utils = require("avante.utils") ---@class avante.acp.ClientCapabilities ---@field fs avante.acp.FileSystemCapability ---@class avante.acp.FileSystemCapability ---@field readTextFile boolean ---@field writeTextFile boolean ---@class avante.acp.AgentCapabilities ---@field loadSession boolean ---@field promptCapabilities avante.acp.PromptCapabilities ---@class avante.acp.PromptCapabilities ---@field image boolean ---@field audio boolean ---@field embeddedContext boolean ---@class avante.acp.AuthMethod ---@field id string ---@field name string ---@field description string|nil ---@class avante.acp.McpServer ---@field name string ---@field command string ---@field args string[] ---@field env avante.acp.EnvVariable[] ---@class avante.acp.EnvVariable ---@field name string ---@field value string ---@alias ACPStopReason "end_turn" | "max_tokens" | "max_turn_requests" | "refusal" | "cancelled" ---@alias ACPToolKind "read" | "edit" | "delete" | "move" | "search" | "execute" | "think" | "fetch" | "other" ---@alias ACPToolCallStatus "pending" | "in_progress" | "completed" | "failed" ---@alias ACPPlanEntryStatus "pending" | "in_progress" | "completed" ---@alias ACPPlanEntryPriority "high" | "medium" | "low" ---@class avante.acp.BaseContent ---@field type "text" | "image" | "audio" | "resource_link" | "resource" ---@field annotations avante.acp.Annotations|nil ---@class avante.acp.TextContent : avante.acp.BaseContent ---@field type "text" ---@field text string ---@class avante.acp.ImageContent : avante.acp.BaseContent ---@field type "image" ---@field data string ---@field mimeType string ---@field uri string|nil ---@class avante.acp.AudioContent : avante.acp.BaseContent ---@field type "audio" ---@field data string ---@field mimeType string ---@class avante.acp.ResourceLinkContent : avante.acp.BaseContent ---@field type "resource_link" ---@field uri string ---@field name string ---@field description string|nil ---@field mimeType string|nil ---@field size number|nil ---@field title string|nil ---@class avante.acp.ResourceContent : avante.acp.BaseContent ---@field type "resource" ---@field resource avante.acp.EmbeddedResource ---@class avante.acp.EmbeddedResource ---@field uri string ---@field text string|nil ---@field blob string|nil ---@field mimeType string|nil ---@class avante.acp.Annotations ---@field audience any[]|nil ---@field lastModified string|nil ---@field priority number|nil ---@alias ACPContent avante.acp.TextContent | avante.acp.ImageContent | avante.acp.AudioContent | avante.acp.ResourceLinkContent | avante.acp.ResourceContent ---@class avante.acp.ToolCall ---@field toolCallId string ---@field title string ---@field kind ACPToolKind ---@field status ACPToolCallStatus ---@field content ACPToolCallContent[] ---@field locations avante.acp.ToolCallLocation[] ---@field rawInput table ---@field rawOutput table ---@class avante.acp.BaseToolCallContent ---@field type "content" | "diff" ---@class avante.acp.ToolCallRegularContent : avante.acp.BaseToolCallContent ---@field type "content" ---@field content ACPContent ---@class avante.acp.ToolCallDiffContent : avante.acp.BaseToolCallContent ---@field type "diff" ---@field path string ---@field oldText string|nil ---@field newText string ---@alias ACPToolCallContent avante.acp.ToolCallRegularContent | avante.acp.ToolCallDiffContent ---@class avante.acp.ToolCallLocation ---@field path string ---@field line number|nil ---@class avante.acp.PlanEntry ---@field content string ---@field priority ACPPlanEntryPriority ---@field status ACPPlanEntryStatus ---@class avante.acp.Plan ---@field entries avante.acp.PlanEntry[] ---@class avante.acp.AvailableCommand ---@field name string ---@field description string ---@field input? table<string, any> ---@class avante.acp.BaseSessionUpdate ---@field sessionUpdate "user_message_chunk" | "agent_message_chunk" | "agent_thought_chunk" | "tool_call" | "tool_call_update" | "plan" | "available_commands_update" ---@class avante.acp.UserMessageChunk : avante.acp.BaseSessionUpdate ---@field sessionUpdate "user_message_chunk" ---@field content ACPContent ---@class avante.acp.AgentMessageChunk : avante.acp.BaseSessionUpdate ---@field sessionUpdate "agent_message_chunk" ---@field content ACPContent ---@class avante.acp.AgentThoughtChunk : avante.acp.BaseSessionUpdate ---@field sessionUpdate "agent_thought_chunk" ---@field content ACPContent ---@class avante.acp.ToolCallUpdate : avante.acp.BaseSessionUpdate ---@field sessionUpdate "tool_call" | "tool_call_update" ---@field toolCallId string ---@field title string|nil ---@field kind ACPToolKind|nil ---@field status ACPToolCallStatus|nil ---@field content ACPToolCallContent[]|nil ---@field locations avante.acp.ToolCallLocation[]|nil ---@field rawInput table|nil ---@field rawOutput table|nil ---@class avante.acp.PlanUpdate : avante.acp.BaseSessionUpdate ---@field sessionUpdate "plan" ---@field entries avante.acp.PlanEntry[] ---@class avante.acp.AvailableCommandsUpdate : avante.acp.BaseSessionUpdate ---@field sessionUpdate "available_commands_update" ---@field availableCommands avante.acp.AvailableCommand[] ---@class avante.acp.PermissionOption ---@field optionId string ---@field name string ---@field kind "allow_once" | "allow_always" | "reject_once" | "reject_always" ---@class avante.acp.RequestPermissionOutcome ---@field outcome "cancelled" | "selected" ---@field optionId string|nil ---@class avante.acp.ACPTransport ---@field send function ---@field start function ---@field stop function ---@alias ACPConnectionState "disconnected" | "connecting" | "connected" | "initializing" | "ready" | "error" ---@class avante.acp.ACPError ---@field code number ---@field message string ---@field data any|nil ---@class avante.acp.ACPClient ---@field protocol_version number ---@field capabilities avante.acp.ClientCapabilities ---@field agent_capabilities avante.acp.AgentCapabilities|nil ---@field config ACPConfig ---@field callbacks table<number, fun(result: table|nil, err: avante.acp.ACPError|nil)> ---@field debug_log_file file*|nil local ACPClient = {} -- ACP Error codes ACPClient.ERROR_CODES = { -- JSON-RPC 2.0 PARSE_ERROR = -32700, INVALID_REQUEST = -32600, METHOD_NOT_FOUND = -32601, INVALID_PARAMS = -32602, INTERNAL_ERROR = -32603, -- ACP AUTH_REQUIRED = -32000, RESOURCE_NOT_FOUND = -32002, } ---@class ACPHandlers ---@field on_session_update? fun(update: avante.acp.UserMessageChunk | avante.acp.AgentMessageChunk | avante.acp.AgentThoughtChunk | avante.acp.ToolCallUpdate | avante.acp.PlanUpdate | avante.acp.AvailableCommandsUpdate) ---@field on_request_permission? fun(tool_call: table, options: table[], callback: fun(option_id: string | nil)): nil ---@field on_read_file? fun(path: string, line: integer | nil, limit: integer | nil, callback: fun(content: string), error_callback: fun(message: string, code: integer|nil)): nil ---@field on_write_file? fun(path: string, content: string, callback: fun(error: string|nil)): nil ---@field on_error? fun(error: table) ---@class ACPConfig ---@field transport_type "stdio" | "websocket" | "tcp" ---@field command? string Command to spawn agent (for stdio) ---@field args? string[] Arguments for agent command ---@field env? table Environment variables ---@field host? string Host for tcp/websocket ---@field port? number Port for tcp/websocket ---@field timeout? number Request timeout in milliseconds ---@field reconnect? boolean Enable auto-reconnect ---@field max_reconnect_attempts? number Maximum reconnection attempts ---@field heartbeat_interval? number Heartbeat interval in milliseconds ---@field auth_method? string Authentication method ---@field handlers? ACPHandlers ---@field on_state_change? fun(new_state: ACPConnectionState, old_state: ACPConnectionState) ---Create a new ACP client instance ---@param config ACPConfig ---@return avante.acp.ACPClient function ACPClient:new(config) local client = setmetatable({ id_counter = 0, protocol_version = 1, capabilities = { fs = { readTextFile = true, writeTextFile = true, }, }, debug_log_file = nil, callbacks = {}, transport = nil, config = config or {}, state = "disconnected", reconnect_count = 0, heartbeat_timer = nil, }, { __index = self }) client:_setup_transport() return client end ---Write debug log message ---@param message string function ACPClient:_debug_log(message) if not Config.debug then self:_close_debug_log() return end -- Open file if needed if not self.debug_log_file then self.debug_log_file = io.open("/tmp/avante-acp-session.log", "a") end if self.debug_log_file then self.debug_log_file:write(message) self.debug_log_file:flush() end end ---Close debug log file function ACPClient:_close_debug_log() if self.debug_log_file then self.debug_log_file:close() self.debug_log_file = nil end end ---Setup transport layer function ACPClient:_setup_transport() local transport_type = self.config.transport_type or "stdio" if transport_type == "stdio" then self.transport = self:_create_stdio_transport() elseif transport_type == "websocket" then self.transport = self:_create_websocket_transport() elseif transport_type == "tcp" then self.transport = self:_create_tcp_transport() else error("Unsupported transport type: " .. transport_type) end end ---Set connection state ---@param state ACPConnectionState function ACPClient:_set_state(state) local old_state = self.state self.state = state if self.config.on_state_change then self.config.on_state_change(state, old_state) end end ---Create error object ---@param code number ---@param message string ---@param data any? ---@return avante.acp.ACPError function ACPClient:_create_error(code, message, data) return { code = code, message = message, data = data, } end ---Create stdio transport layer function ACPClient:_create_stdio_transport() local uv = vim.uv or vim.loop --- @class avante.acp.ACPTransportInstance local transport = { --- @type uv.uv_pipe_t|nil stdin = nil, --- @type uv.uv_pipe_t|nil stdout = nil, --- @type uv.uv_process_t|nil process = nil, } --- @param transport_self avante.acp.ACPTransportInstance --- @param data string function transport.send(transport_self, data) if transport_self.stdin and not transport_self.stdin:is_closing() then transport_self.stdin:write(data .. "\n") return true end return false end --- @param transport_self avante.acp.ACPTransportInstance --- @param on_message fun(message: any) function transport.start(transport_self, on_message) self:_set_state("connecting") local stdin = uv.new_pipe(false) local stdout = uv.new_pipe(false) local stderr = uv.new_pipe(false) if not stdin or not stdout or not stderr then self:_set_state("error") error("Failed to create pipes for ACP agent") end local args = vim.deepcopy(self.config.args or {}) local env = self.config.env -- Start with system environment and override with config env local final_env = {} local path = vim.fn.getenv("PATH") if path then final_env[#final_env + 1] = "PATH=" .. path end if env then for k, v in pairs(env) do final_env[#final_env + 1] = k .. "=" .. v end end ---@diagnostic disable-next-line: missing-fields local handle, pid = uv.spawn(self.config.command, { args = args, env = final_env, stdio = { stdin, stdout, stderr }, }, function(code, signal) Utils.debug("ACP agent exited with code " .. code .. " and signal " .. signal) self:_set_state("disconnected") if transport_self.process then transport_self.process:close() transport_self.process = nil end -- Handle auto-reconnect if self.config.reconnect and self.reconnect_count < (self.config.max_reconnect_attempts or 3) then self.reconnect_count = self.reconnect_count + 1 vim.defer_fn(function() if self.state == "disconnected" then self:connect(function(_err) end) end end, 2000) -- Wait 2 seconds before reconnecting end end) Utils.debug("Spawned ACP agent process with PID " .. tostring(pid)) if not handle then self:_set_state("error") error("Failed to spawn ACP agent process") end transport_self.process = handle transport_self.stdin = stdin transport_self.stdout = stdout self:_set_state("connected") -- Read stdout local buffer = "" stdout:read_start(function(err, data) if err then vim.notify("ACP stdout error: " .. err, vim.log.levels.ERROR) self:_set_state("error") return end if data then buffer = buffer .. data -- Split on newlines and process complete JSON-RPC messages local lines = vim.split(buffer, "\n", { plain = true }) buffer = lines[#lines] -- Keep incomplete line in buffer for i = 1, #lines - 1 do local line = vim.trim(lines[i]) if line ~= "" then local ok, message = pcall(vim.json.decode, line) if ok then on_message(message) else vim.schedule( function() vim.notify("Failed to parse JSON-RPC message: " .. line, vim.log.levels.WARN) end ) end end end end end) -- Read stderr for debugging stderr:read_start(function(_, data) -- if data then -- -- Filter out common session recovery error messages to avoid user confusion -- if not (data:match("Session not found") or data:match("session/prompt")) then -- vim.schedule(function() vim.notify("ACP stderr: " .. data, vim.log.levels.DEBUG) end) -- end -- end end) end --- @param transport_self avante.acp.ACPTransportInstance function transport.stop(transport_self) if transport_self.process and not transport_self.process:is_closing() then local process = transport_self.process transport_self.process = nil if not process then return end -- Try to terminate gracefully pcall(function() process:kill(15) end) -- then force kill, it'll fail harmlessly if already exited pcall(function() process:kill(9) end) process:close() end if transport_self.stdin then transport_self.stdin:close() transport_self.stdin = nil end if transport_self.stdout then transport_self.stdout:close() transport_self.stdout = nil end self:_set_state("disconnected") end return transport end ---Create WebSocket transport layer (placeholder) function ACPClient:_create_websocket_transport() error("WebSocket transport not implemented yet") end ---Create TCP transport layer (placeholder) function ACPClient:_create_tcp_transport() error("TCP transport not implemented yet") end ---Generate next request ID ---@return number function ACPClient:_next_id() self.id_counter = self.id_counter + 1 return self.id_counter end ---Send JSON-RPC request ---@param method string ---@param params table? ---@param callback fun(result: table|nil, err: avante.acp.ACPError|nil) function ACPClient:_send_request(method, params, callback) local id = self:_next_id() local message = { jsonrpc = "2.0", id = id, method = method, params = params or {}, } self.callbacks[id] = callback local data = vim.json.encode(message) self:_debug_log("request: " .. data .. string.rep("=", 100) .. "\n") self.transport:send(data) end ---Send JSON-RPC notification ---@param method string ---@param params table? function ACPClient:_send_notification(method, params) local message = { jsonrpc = "2.0", method = method, params = params or {}, } local data = vim.json.encode(message) self:_debug_log("notification: " .. data .. string.rep("=", 100) .. "\n") self.transport:send(data) end ---Send JSON-RPC result ---@param id number ---@param result table | string | vim.NIL | nil ---@return nil function ACPClient:_send_result(id, result) local message = { jsonrpc = "2.0", id = id, result = result } local data = vim.json.encode(message) self:_debug_log("request: " .. data .. "\n" .. string.rep("=", 100) .. "\n") self.transport:send(data) end ---Send JSON-RPC error ---@param id number ---@param message string ---@param code? number ---@return nil function ACPClient:_send_error(id, message, code) code = code or self.ERROR_CODES.INTERNAL_ERROR local msg = { jsonrpc = "2.0", id = id, error = { code = code, message = message } } local data = vim.json.encode(msg) self.transport:send(data) end ---Handle received message ---@param message table function ACPClient:_handle_message(message) -- Check if this is a notification (has method but no id, or has both method and id for notifications) if message.method and not message.result and not message.error then -- This is a notification self:_handle_notification(message.id, message.method, message.params) elseif message.id and (message.result or message.error) then self:_debug_log("response: " .. vim.inspect(message) .. "\n" .. string.rep("=", 100) .. "\n") local callback = self.callbacks[message.id] if callback then callback(message.result, message.error) self.callbacks[message.id] = nil end else -- Unknown message type vim.notify("Unknown message type: " .. vim.inspect(message), vim.log.levels.WARN) end end ---Handle notification ---@param method string ---@param params table function ACPClient:_handle_notification(message_id, method, params) self:_debug_log("method: " .. method .. "\n") self:_debug_log(vim.inspect(params) .. "\n" .. string.rep("=", 100) .. "\n") if method == "session/update" then self:_handle_session_update(params) elseif method == "session/request_permission" then self:_handle_request_permission(message_id, params) elseif method == "fs/read_text_file" then self:_handle_read_text_file(message_id, params) elseif method == "fs/write_text_file" then self:_handle_write_text_file(message_id, params) else vim.notify("Unknown notification method: " .. method, vim.log.levels.WARN) end end ---Handle session update notification ---@param params table function ACPClient:_handle_session_update(params) local session_id = params.sessionId local update = params.update if not session_id then vim.notify("Received session/update without sessionId", vim.log.levels.WARN) return end if not update then vim.notify("Received session/update without update data", vim.log.levels.WARN) return end if self.config.handlers and self.config.handlers.on_session_update then vim.schedule(function() self.config.handlers.on_session_update(update) end) end end ---Handle permission request notification ---@param message_id number ---@param params table function ACPClient:_handle_request_permission(message_id, params) local session_id = params.sessionId local tool_call = params.toolCall local options = params.options if not session_id or not tool_call then return end if self.config.handlers and self.config.handlers.on_request_permission then vim.schedule(function() self.config.handlers.on_request_permission( tool_call, options, function(option_id) self:_send_result(message_id, { outcome = { outcome = "selected", optionId = option_id, }, }) end ) end) end end ---Handle fs/read_text_file requests ---@param message_id number ---@param params table function ACPClient:_handle_read_text_file(message_id, params) local session_id = params.sessionId local path = params.path if not session_id or not path then self:_send_error(message_id, "Invalid fs/read_text_file params", ACPClient.ERROR_CODES.INVALID_PARAMS) return end if self.config.handlers and self.config.handlers.on_read_file then vim.schedule(function() self.config.handlers.on_read_file( path, params.line ~= vim.NIL and params.line or nil, params.limit ~= vim.NIL and params.limit or nil, function(content) self:_send_result(message_id, { content = content }) end, function(err, code) self:_send_error(message_id, err or "Failed to read file", code) end ) end) else self:_send_error(message_id, "fs/read_text_file handler not configured", ACPClient.ERROR_CODES.METHOD_NOT_FOUND) end end ---Handle fs/write_text_file requests ---@param message_id number ---@param params table function ACPClient:_handle_write_text_file(message_id, params) local session_id = params.sessionId local path = params.path local content = params.content if not session_id or not path or not content then self:_send_error(message_id, "Invalid fs/write_text_file params", ACPClient.ERROR_CODES.INVALID_PARAMS) return end if self.config.handlers and self.config.handlers.on_write_file then vim.schedule(function() self.config.handlers.on_write_file( path, content, function(error) self:_send_result(message_id, error == nil and vim.NIL or error) end ) end) else self:_send_error(message_id, "fs/write_text_file handler not configured", ACPClient.ERROR_CODES.METHOD_NOT_FOUND) end end ---Start client ---@param callback fun(err: avante.acp.ACPError|nil) function ACPClient:connect(callback) callback = callback or function() end if self.state ~= "disconnected" then callback(nil) return end self.transport:start(vim.schedule_wrap(function(message) self:_handle_message(message) end)) self:initialize(callback) end ---Stop client function ACPClient:stop() self.transport:stop() self:_close_debug_log() self.reconnect_count = 0 end ---Initialize protocol connection ---@param callback fun(err: avante.acp.ACPError|nil) function ACPClient:initialize(callback) callback = callback or function() end if self.state ~= "connected" then local error = self:_create_error(self.ERROR_CODES.PROTOCOL_ERROR, "Cannot initialize: client not connected") callback(error) return end self:_set_state("initializing") self:_send_request("initialize", { protocolVersion = self.protocol_version, clientCapabilities = self.capabilities, }, function(result, err) if err or not result then self:_set_state("error") vim.schedule(function() vim.notify("Failed to initialize", vim.log.levels.ERROR) end) callback(err or self:_create_error(self.ERROR_CODES.PROTOCOL_ERROR, "Failed to initialize: missing result")) return end -- Update protocol version and capabilities self.protocol_version = result.protocolVersion self.agent_capabilities = result.agentCapabilities self.auth_methods = result.authMethods or {} -- Check if we need to authenticate local auth_method = self.config.auth_method if auth_method then Utils.debug("Authenticating with method " .. auth_method) self:authenticate(auth_method, function(auth_err) if auth_err then callback(auth_err) else self:_set_state("ready") callback(nil) end end) else Utils.debug("No authentication method found or specified") self:_set_state("ready") callback(nil) end end) end ---Authentication (if required) ---@param method_id string ---@param callback fun(err: avante.acp.ACPError|nil) function ACPClient:authenticate(method_id, callback) callback = callback or function() end self:_send_request("authenticate", { methodId = method_id, }, function(result, err) callback(err) end) end ---Create new session ---@param cwd string ---@param mcp_servers table[]? ---@param callback fun(session_id: string|nil, err: avante.acp.ACPError|nil) function ACPClient:create_session(cwd, mcp_servers, callback) callback = callback or function() end self:_send_request("session/new", { cwd = cwd, mcpServers = mcp_servers or {}, }, function(result, err) if err then vim.schedule(function() vim.notify("Failed to create session: " .. err.message, vim.log.levels.ERROR) end) callback(nil, err) return end if not result then local error = self:_create_error(self.ERROR_CODES.PROTOCOL_ERROR, "Failed to create session: missing result") callback(nil, error) return end callback(result.sessionId, nil) end) end ---Load existing session ---@param session_id string ---@param cwd string ---@param mcp_servers table[]? ---@param callback fun(result: table|nil, err: avante.acp.ACPError|nil) function ACPClient:load_session(session_id, cwd, mcp_servers, callback) callback = callback or function() end if not self.agent_capabilities or not self.agent_capabilities.loadSession then vim.schedule(function() vim.notify("Agent does not support loading sessions", vim.log.levels.WARN) end) local err = self:_create_error(self.ERROR_CODES.PROTOCOL_ERROR, "Agent does not support loading sessions") callback(nil, err) return end self:_send_request("session/load", { sessionId = session_id, cwd = cwd, mcpServers = mcp_servers or {}, }, callback) end ---Send prompt ---@param session_id string ---@param prompt table[] ---@param callback fun(result: table|nil, err: avante.acp.ACPError|nil) function ACPClient:send_prompt(session_id, prompt, callback) local params = { sessionId = session_id, prompt = prompt, } return self:_send_request("session/prompt", params, callback) end ---Cancel session ---@param session_id string function ACPClient:cancel_session(session_id) self:_send_notification("session/cancel", { sessionId = session_id, }) end ---Helper function: Create text content block ---@param text string ---@param annotations table? ---@return table function ACPClient:create_text_content(text, annotations) return { type = "text", text = text, annotations = annotations, } end ---Helper function: Create image content block ---@param data string Base64 encoded image data ---@param mime_type string ---@param uri string? ---@param annotations table? ---@return table function ACPClient:create_image_content(data, mime_type, uri, annotations) return { type = "image", data = data, mimeType = mime_type, uri = uri, annotations = annotations, } end ---Helper function: Create audio content block ---@param data string Base64 encoded audio data ---@param mime_type string ---@param annotations table? ---@return table function ACPClient:create_audio_content(data, mime_type, annotations) return { type = "audio", data = data, mimeType = mime_type, annotations = annotations, } end ---Helper function: Create resource link content block ---@param uri string ---@param name string ---@param description string? ---@param mime_type string? ---@param size number? ---@param title string? ---@param annotations table? ---@return table function ACPClient:create_resource_link_content(uri, name, description, mime_type, size, title, annotations) return { type = "resource_link", uri = uri, name = name, description = description, mimeType = mime_type, size = size, title = title, annotations = annotations, } end ---Helper function: Create embedded resource content block ---@param resource table ---@param annotations table? ---@return table function ACPClient:create_resource_content(resource, annotations) return { type = "resource", resource = resource, annotations = annotations, } end ---Helper function: Create text resource ---@param uri string ---@param text string ---@param mime_type string? ---@return table function ACPClient:create_text_resource(uri, text, mime_type) return { uri = uri, text = text, mimeType = mime_type, } end ---Helper function: Create binary resource ---@param uri string ---@param blob string Base64 encoded binary data ---@param mime_type string? ---@return table function ACPClient:create_blob_resource(uri, blob, mime_type) return { uri = uri, blob = blob, mimeType = mime_type, } end ---Convenience method: Check if client is ready ---@return boolean function ACPClient:is_ready() return self.state == "ready" end ---Convenience method: Check if client is connected ---@return boolean function ACPClient:is_connected() return self.state ~= "disconnected" and self.state ~= "error" end ---Convenience method: Get current state ---@return ACPConnectionState function ACPClient:get_state() return self.state end ---Convenience method: Wait for client to be ready ---@param callback function ---@param timeout number? Timeout in milliseconds function ACPClient:wait_ready(callback, timeout) if self:is_ready() then callback(nil) return end local timeout_ms = timeout or 10000 -- 10 seconds default local start_time = vim.loop.now() local function check_ready() if self:is_ready() then callback(nil) elseif self.state == "error" then callback(self:_create_error(self.ERROR_CODES.PROTOCOL_ERROR, "Client entered error state while waiting")) elseif vim.loop.now() - start_time > timeout_ms then callback(self:_create_error(self.ERROR_CODES.TIMEOUT_ERROR, "Timeout waiting for client to be ready")) else vim.defer_fn(check_ready, 100) -- Check every 100ms end end check_ready() end ---Convenience method: Send simple text prompt ---@param session_id string ---@param text string ---@param callback fun(result: table|nil, err: avante.acp.ACPError|nil) function ACPClient:send_text_prompt(session_id, text, callback) local prompt = { self:create_text_content(text) } self:send_prompt(session_id, prompt, callback) end return ACPClient
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/libs/jsonparser.lua
Lua
-- JSON Streaming Parser for Lua local JsonParser = {} -- 流式解析器状态 local StreamParser = {} StreamParser.__index = StreamParser -- JSON 解析状态枚举 local PARSE_STATE = { READY = "ready", PARSING = "parsing", INCOMPLETE = "incomplete", ERROR = "error", OBJECT_START = "object_start", OBJECT_KEY = "object_key", OBJECT_VALUE = "object_value", ARRAY_START = "array_start", ARRAY_VALUE = "array_value", STRING = "string", NUMBER = "number", LITERAL = "literal", } -- 创建新的流式解析器实例 function StreamParser.new() local parser = { buffer = "", -- 缓冲区存储未处理的内容 position = 1, -- 当前解析位置 state = PARSE_STATE.READY, -- 解析状态 stack = {}, -- 解析栈,存储嵌套的对象和数组 results = {}, -- 已完成的 JSON 对象列表 current = nil, -- 当前正在构建的对象 current_key = nil, -- 当前对象的键 escape_next = false, -- 下一个字符是否被转义 string_delimiter = nil, -- 字符串分隔符 (' 或 ") last_error = nil, -- 最后的错误信息 incomplete_string = "", -- 未完成的字符串内容 incomplete_number = "", -- 未完成的数字内容 incomplete_literal = "", -- 未完成的字面量内容 depth = 0, -- 当前嵌套深度 } setmetatable(parser, StreamParser) return parser end -- 重置解析器状态 function StreamParser:reset() self.buffer = "" self.position = 1 self.state = PARSE_STATE.READY self.stack = {} self.results = {} self.current = nil self.current_key = nil self.escape_next = false self.string_delimiter = nil self.last_error = nil self.incomplete_string = "" self.incomplete_number = "" self.incomplete_literal = "" self.depth = 0 end -- 获取解析器状态信息 function StreamParser:getStatus() return { state = self.state, completed_objects = #self.results, stack_depth = #self.stack, buffer_size = #self.buffer, current_depth = self.depth, last_error = self.last_error, has_incomplete = self.state == PARSE_STATE.INCOMPLETE, position = self.position, } end -- 辅助函数:检查字符是否为空白字符 local function isWhitespace(char) return char == " " or char == "\t" or char == "\n" or char == "\r" end -- 辅助函数:检查字符是否为数字开始字符 local function isNumberStart(char) return char == "-" or (char >= "0" and char <= "9") end -- 辅助函数:检查字符是否为数字字符 local function isNumberChar(char) return (char >= "0" and char <= "9") or char == "." or char == "e" or char == "E" or char == "+" or char == "-" end -- 辅助函数:解析 JSON 字符串转义 local function unescapeJsonString(str) local result = str:gsub("\\(.)", function(char) if char == "n" then return "\n" elseif char == "r" then return "\r" elseif char == "t" then return "\t" elseif char == "b" then return "\b" elseif char == "f" then return "\f" elseif char == "\\" then return "\\" elseif char == "/" then return "/" elseif char == '"' then return '"' else return "\\" .. char -- 保持未知转义序列 end end) -- 处理 Unicode 转义序列 \uXXXX result = result:gsub("\\u(%x%x%x%x)", function(hex) local codepoint = tonumber(hex, 16) if codepoint then -- 简单的 UTF-8 编码(仅支持基本多文种平面) if codepoint < 0x80 then return string.char(codepoint) elseif codepoint < 0x800 then return string.char(0xC0 + math.floor(codepoint / 0x40), 0x80 + (codepoint % 0x40)) else return string.char( 0xE0 + math.floor(codepoint / 0x1000), 0x80 + math.floor((codepoint % 0x1000) / 0x40), 0x80 + (codepoint % 0x40) ) end end return "\\u" .. hex -- 保持原样如果解析失败 end) return result end -- 辅助函数:解析数字 local function parseNumber(str) local num = tonumber(str) if num then return num end return nil end -- 辅助函数:解析字面量(true, false, null) local function parseLiteral(str) if str == "true" then return true elseif str == "false" then return false elseif str == "null" then return nil else return nil, "Invalid literal: " .. str end end -- 跳过空白字符 function StreamParser:skipWhitespace() while self.position <= #self.buffer and isWhitespace(self.buffer:sub(self.position, self.position)) do self.position = self.position + 1 end end -- 获取当前字符 function StreamParser:getCurrentChar() if self.position <= #self.buffer then return self.buffer:sub(self.position, self.position) end return nil end -- 前进一个字符位置 function StreamParser:advance() self.position = self.position + 1 end -- 设置错误状态 function StreamParser:setError(message) self.state = PARSE_STATE.ERROR self.last_error = message end -- 推入栈 function StreamParser:pushStack(value, type) -- Save the current key when pushing to stack table.insert(self.stack, { value = value, type = type, key = self.current_key }) self.current_key = nil -- Reset for the new context self.depth = self.depth + 1 end -- 弹出栈 function StreamParser:popStack() if #self.stack > 0 then local item = table.remove(self.stack) self.depth = self.depth - 1 return item end return nil end -- 获取栈顶元素 function StreamParser:peekStack() if #self.stack > 0 then return self.stack[#self.stack] end return nil end -- 添加值到当前容器 function StreamParser:addValue(value) local parent = self:peekStack() if not parent then -- 顶层值,直接添加到结果 table.insert(self.results, value) self.current = nil elseif parent.type == "object" then -- 添加到对象 if self.current_key then parent.value[self.current_key] = value self.current_key = nil else self:setError("Object value without key") return false end elseif parent.type == "array" then -- 添加到数组 table.insert(parent.value, value) else self:setError("Invalid parent type: " .. tostring(parent.type)) return false end return true end -- 解析字符串 function StreamParser:parseString() local delimiter = self:getCurrentChar() if delimiter ~= '"' and delimiter ~= "'" then self:setError("Expected string delimiter") return nil end self.string_delimiter = delimiter self:advance() -- 跳过开始引号 local content = self.incomplete_string while self.position <= #self.buffer do local char = self:getCurrentChar() if self.escape_next then content = content .. char self.escape_next = false self:advance() elseif char == "\\" then content = content .. char self.escape_next = true self:advance() elseif char == delimiter then -- 字符串结束 self:advance() -- 跳过结束引号 local unescaped = unescapeJsonString(content) self.incomplete_string = "" self.string_delimiter = nil self.escape_next = false return unescaped else content = content .. char self:advance() end end -- 字符串未完成 self.incomplete_string = content self.state = PARSE_STATE.INCOMPLETE return nil end -- 继续解析未完成的字符串 function StreamParser:continueStringParsing() local content = self.incomplete_string local delimiter = self.string_delimiter while self.position <= #self.buffer do local char = self:getCurrentChar() if self.escape_next then content = content .. char self.escape_next = false self:advance() elseif char == "\\" then content = content .. char self.escape_next = true self:advance() elseif char == delimiter then -- 字符串结束 self:advance() -- 跳过结束引号 local unescaped = unescapeJsonString(content) self.incomplete_string = "" self.string_delimiter = nil self.escape_next = false return unescaped else content = content .. char self:advance() end end -- 字符串仍未完成 self.incomplete_string = content self.state = PARSE_STATE.INCOMPLETE return nil end -- 解析数字 function StreamParser:parseNumber() local content = self.incomplete_number while self.position <= #self.buffer do local char = self:getCurrentChar() if isNumberChar(char) then content = content .. char self:advance() else -- 数字结束 local number = parseNumber(content) if number then self.incomplete_number = "" return number else self:setError("Invalid number format: " .. content) return nil end end end -- 数字可能未完成,但也可能已经是有效数字 local number = parseNumber(content) if number then self.incomplete_number = "" return number else -- 数字未完成 self.incomplete_number = content self.state = PARSE_STATE.INCOMPLETE return nil end end -- 解析字面量 function StreamParser:parseLiteral() local content = self.incomplete_literal while self.position <= #self.buffer do local char = self:getCurrentChar() if char and char:match("[%w]") then content = content .. char self:advance() else -- 字面量结束 local value, err = parseLiteral(content) if err then self:setError(err) return nil end self.incomplete_literal = "" return value end end -- 检查当前内容是否已经是完整的字面量 local value, err = parseLiteral(content) if not err then self.incomplete_literal = "" return value end -- 字面量未完成 self.incomplete_literal = content self.state = PARSE_STATE.INCOMPLETE return nil end -- 流式解析器方法:添加数据到缓冲区并解析 function StreamParser:addData(data) if not data or data == "" then return end self.buffer = self.buffer .. data self:parseBuffer() end -- 解析缓冲区中的数据 function StreamParser:parseBuffer() -- 如果当前状态是不完整,先尝试继续之前的解析 if self.state == PARSE_STATE.INCOMPLETE then if self.incomplete_string ~= "" and self.string_delimiter then -- Continue parsing the incomplete string local str = self:continueStringParsing() if str then local parent = self:peekStack() if parent and parent.type == "object" and not self.current_key then self.current_key = str else if not self:addValue(str) then return end end elseif self.state == PARSE_STATE.ERROR then return elseif self.state == PARSE_STATE.INCOMPLETE then return end elseif self.incomplete_number ~= "" then local num = self:parseNumber() if num then if not self:addValue(num) then return end elseif self.state == PARSE_STATE.ERROR then return elseif self.state == PARSE_STATE.INCOMPLETE then return end elseif self.incomplete_literal ~= "" then local value = self:parseLiteral() if value ~= nil or self.incomplete_literal == "null" then if not self:addValue(value) then return end elseif self.state == PARSE_STATE.ERROR then return elseif self.state == PARSE_STATE.INCOMPLETE then return end end end self.state = PARSE_STATE.PARSING while self.position <= #self.buffer and self.state == PARSE_STATE.PARSING do self:skipWhitespace() if self.position > #self.buffer then break end local char = self:getCurrentChar() if not char then break end -- 根据当前状态和字符进行解析 if char == "{" then -- 对象开始 local obj = {} self:pushStack(obj, "object") self.current = obj -- Reset current_key for the new object context self.current_key = nil self:advance() elseif char == "}" then -- 对象结束 local parent = self:popStack() if not parent or parent.type ~= "object" then self:setError("Unexpected }") return end -- Restore the key context from when this object was pushed self.current_key = parent.key if not self:addValue(parent.value) then return end self:advance() elseif char == "[" then -- 数组开始 local arr = {} self:pushStack(arr, "array") self.current = arr self:advance() elseif char == "]" then -- 数组结束 local parent = self:popStack() if not parent or parent.type ~= "array" then self:setError("Unexpected ]") return end -- Restore the key context from when this array was pushed self.current_key = parent.key if not self:addValue(parent.value) then return end self:advance() elseif char == '"' then -- 字符串(只支持双引号,这是标准JSON) local str = self:parseString() if self.state == PARSE_STATE.INCOMPLETE then return elseif self.state == PARSE_STATE.ERROR then return end local parent = self:peekStack() -- Check if we're directly inside an object and need a key if parent and parent.type == "object" and not self.current_key then -- 对象的键 self.current_key = str else -- 值 if not self:addValue(str) then return end end elseif char == ":" then -- 键值分隔符 if not self.current_key then self:setError("Unexpected :") return end self:advance() elseif char == "," then -- 值分隔符 self:advance() elseif isNumberStart(char) then -- 数字 local num = self:parseNumber() if self.state == PARSE_STATE.INCOMPLETE then return elseif self.state == PARSE_STATE.ERROR then return end if num ~= nil and not self:addValue(num) then return end elseif char:match("[%a]") then -- 字面量 (true, false, null) local value = self:parseLiteral() if self.state == PARSE_STATE.INCOMPLETE then return elseif self.state == PARSE_STATE.ERROR then return end if not self:addValue(value) then return end else self:setError("Unexpected character: " .. char .. " at position " .. self.position) return end end -- 如果解析完成且没有错误,设置为就绪状态 if self.state == PARSE_STATE.PARSING and #self.stack == 0 then self.state = PARSE_STATE.READY elseif self.state == PARSE_STATE.PARSING and #self.stack > 0 then self.state = PARSE_STATE.INCOMPLETE end end -- 获取所有已完成的 JSON 对象 function StreamParser:getAllObjects() -- 如果有不完整的数据,自动完成解析 if self.state == PARSE_STATE.INCOMPLETE or self.incomplete_string ~= "" or self.incomplete_number ~= "" or self.incomplete_literal ~= "" or #self.stack > 0 then self:finalize() end return self.results end -- 获取已完成的对象(保留向后兼容性) function StreamParser:getCompletedObjects() return self.results end -- 获取当前未完成的对象(保留向后兼容性) function StreamParser:getCurrentObject() if #self.stack > 0 then return self.stack[1].value end return self.current end -- 强制完成解析(将未完成的内容标记为不完整但仍然返回) function StreamParser:finalize() -- 如果有未完成的字符串、数字或字面量,尝试解析 if self.incomplete_string ~= "" or self.string_delimiter then -- 未完成的字符串,进行转义处理以便用户使用 -- 虽然字符串不完整,但用户需要使用转义后的内容 local unescaped = unescapeJsonString(self.incomplete_string) local parent = self:peekStack() if parent and parent.type == "object" and not self.current_key then self.current_key = unescaped else self:addValue(unescaped) end self.incomplete_string = "" self.string_delimiter = nil self.escape_next = false end if self.incomplete_number ~= "" then -- 未完成的数字,尝试解析当前内容 local number = parseNumber(self.incomplete_number) if number then self:addValue(number) self.incomplete_number = "" end end if self.incomplete_literal ~= "" then -- 未完成的字面量,尝试解析当前内容 local value, err = parseLiteral(self.incomplete_literal) if not err then self:addValue(value) self.incomplete_literal = "" end end -- 将栈中的所有未完成对象标记为不完整并添加到结果 -- 从栈底开始处理,确保正确的嵌套结构 local stack_items = {} while #self.stack > 0 do local item = self:popStack() table.insert(stack_items, 1, item) -- 插入到开头,保持原始顺序 end -- 重新构建嵌套结构 local root_object = nil for i, item in ipairs(stack_items) do if item and item.value then -- 标记为不完整 if type(item.value) == "table" then item.value._incomplete = true end if i == 1 then -- 第一个(最外层)对象 root_object = item.value else -- 嵌套对象,需要添加到父对象中 local parent_item = stack_items[i - 1] if parent_item and parent_item.value then if parent_item.type == "object" and item.key then parent_item.value[item.key] = item.value elseif parent_item.type == "array" then table.insert(parent_item.value, item.value) end end end end end -- 只添加根对象到结果 if root_object then table.insert(self.results, root_object) end self.current = nil self.current_key = nil self.state = PARSE_STATE.READY end -- 获取当前解析深度 function StreamParser:getCurrentDepth() return self.depth end -- 检查是否有错误 function StreamParser:hasError() return self.state == PARSE_STATE.ERROR end -- 获取错误信息 function StreamParser:getError() return self.last_error end -- 创建流式解析器实例 function JsonParser.createStreamParser() return StreamParser.new() end -- 简单的一次性解析函数(非流式) function JsonParser.parse(jsonString) local parser = StreamParser.new() parser:addData(jsonString) parser:finalize() if parser:hasError() then return nil, parser:getError() end local results = parser:getAllObjects() if #results == 1 then return results[1] elseif #results > 1 then return results else return nil, "No valid JSON found" end end return JsonParser
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/libs/xmlparser.lua
Lua
-- XML Parser for Lua local XmlParser = {} -- 流式解析器状态 local StreamParser = {} StreamParser.__index = StreamParser -- 创建新的流式解析器实例 function StreamParser.new() local parser = { buffer = "", -- 缓冲区存储未处理的内容 stack = {}, -- 标签栈 results = {}, -- 已完成的元素列表 current = nil, -- 当前正在处理的元素 root = nil, -- 当前根元素 position = 1, -- 当前解析位置 state = "ready", -- 解析状态: ready, parsing, incomplete, error incomplete_tag = nil, -- 未完成的标签信息 last_error = nil, -- 最后的错误信息 inside_tool_use = false, -- 是否在 tool_use 标签内 tool_use_depth = 0, -- tool_use 标签嵌套深度 tool_use_stack = {}, -- tool_use 标签栈 } setmetatable(parser, StreamParser) return parser end -- 重置解析器状态 function StreamParser:reset() self.buffer = "" self.stack = {} self.results = {} self.current = nil self.root = nil self.position = 1 self.state = "ready" self.incomplete_tag = nil self.last_error = nil self.inside_tool_use = false self.tool_use_depth = 0 self.tool_use_stack = {} end -- 获取解析器状态信息 function StreamParser:getStatus() return { state = self.state, completed_elements = #self.results, stack_depth = #self.stack, buffer_size = #self.buffer, incomplete_tag = self.incomplete_tag, last_error = self.last_error, has_incomplete = self.state == "incomplete" or self.incomplete_tag ~= nil, inside_tool_use = self.inside_tool_use, tool_use_depth = self.tool_use_depth, tool_use_stack_size = #self.tool_use_stack, } end -- 辅助函数:去除字符串首尾空白 local function trim(s) return s:match("^%s*(.-)%s*$") end -- 辅助函数:解析属性 local function parseAttributes(attrStr) local attrs = {} if not attrStr or attrStr == "" then return attrs end -- 匹配属性模式:name="value" 或 name='value' for name, value in attrStr:gmatch("([_%w]+)%s*=%s*[\"']([^\"']*)[\"']") do attrs[name] = value end return attrs end -- 辅助函数:HTML实体解码 local function decodeEntities(str) local entities = { ["&lt;"] = "<", ["&gt;"] = ">", ["&amp;"] = "&", ["&quot;"] = '"', ["&apos;"] = "'", } for entity, char in pairs(entities) do str = str:gsub(entity, char) end -- 处理数字实体 &#123; 和 &#x1A; str = str:gsub("&#(%d+);", function(n) local num = tonumber(n) return num and string.char(num) or "" end) str = str:gsub("&#x(%x+);", function(n) local num = tonumber(n, 16) return num and string.char(num) or "" end) return str end -- 检查是否为有效的XML标签 local function isValidXmlTag(tag, xmlContent, tagStart) -- 排除明显不是XML标签的内容,比如数学表达式 < 或 > -- 检查标签是否包含合理的XML标签格式 if not tag:match("^<[^<>]*>$") then return false end -- 检查是否是合法的标签格式 if tag:match("^</[_%w]+>$") then return true end -- 结束标签 if tag:match("^<[_%w]+[^>]*/>$") then return true end -- 自闭合标签 if tag:match("^<[_%w]+[^>]*>$") then -- 对于开始标签,进行额外的上下文检查 local tagName = tag:match("^<([_%w]+)") -- 检查是否存在对应的结束标签 local closingTag = "</" .. tagName .. ">" local hasClosingTag = xmlContent:find(closingTag, tagStart) -- 如果是单个标签且没有结束标签,可能是文本中的引用 if not hasClosingTag then -- 检查前后文本,如果像是在描述而不是实际的XML结构,则不认为是有效标签 local beforeText = xmlContent:sub(math.max(1, tagStart - 50), tagStart - 1) local afterText = xmlContent:sub(tagStart + #tag, math.min(#xmlContent, tagStart + #tag + 50)) -- 如果前面有"provided in the"、"in the"等描述性文字,可能是文本引用 if beforeText:match("provided in the%s*$") or beforeText:match("in the%s*$") or beforeText:match("see the%s*$") or beforeText:match("use the%s*$") then return false end -- 如果后面紧跟着"tag"等描述性词汇,可能是文本引用 if afterText:match("^%s*tag") then return false end end return true end return false end -- 流式解析器方法:添加数据到缓冲区并解析 function StreamParser:addData(data) if not data or data == "" then return end self.buffer = self.buffer .. data self:parseBuffer() end -- 获取当前解析深度 function StreamParser:getCurrentDepth() return #self.stack end -- 解析缓冲区中的数据 function StreamParser:parseBuffer() self.state = "parsing" while self.position <= #self.buffer do local remaining = self.buffer:sub(self.position) -- 首先检查是否有 tool_use 标签 local tool_use_start = remaining:find("<tool_use>") local tool_use_end = remaining:find("</tool_use>") -- 如果当前不在 tool_use 内,且找到了 tool_use 开始标签 if not self.inside_tool_use and tool_use_start then -- 处理 tool_use 标签前的文本作为普通文本 if tool_use_start > 1 then local precedingText = remaining:sub(1, tool_use_start - 1) if precedingText ~= "" then local textElement = { _name = "_text", _text = precedingText, } table.insert(self.results, textElement) end end -- 进入 tool_use 模式 self.inside_tool_use = true self.tool_use_depth = 1 table.insert(self.tool_use_stack, { start_pos = self.position + tool_use_start - 1 }) self.position = self.position + tool_use_start + 10 -- 跳过 "<tool_use>" goto continue end -- 如果在 tool_use 内,检查是否遇到结束标签 if self.inside_tool_use and tool_use_end then self.tool_use_depth = self.tool_use_depth - 1 if self.tool_use_depth == 0 then -- 退出 tool_use 模式 self.inside_tool_use = false table.remove(self.tool_use_stack) self.position = self.position + tool_use_end + 11 -- 跳过 "</tool_use>" goto continue end end -- 如果不在 tool_use 内,将所有内容作为普通文本处理 if not self.inside_tool_use then -- 查找下一个可能的 tool_use 标签 local next_tool_use = remaining:find("<tool_use>") if next_tool_use then -- 处理到下一个 tool_use 标签之前的文本 local text = remaining:sub(1, next_tool_use - 1) if text ~= "" then local textElement = { _name = "_text", _text = text, } table.insert(self.results, textElement) end self.position = self.position + next_tool_use - 1 else -- 没有更多 tool_use 标签,处理剩余的所有文本 if remaining ~= "" then local textElement = { _name = "_text", _text = remaining, } table.insert(self.results, textElement) end self.position = #self.buffer + 1 break end goto continue end -- 查找下一个标签(只有在 tool_use 内才进行 XML 解析) local tagStart, tagEnd = remaining:find("</?[%w_]+>") if not tagStart then -- 检查是否有未完成的开始标签(以<开始但没有>结束) local incompleteStart = remaining:find("<[%w_]+$") if incompleteStart then local incompleteContent = remaining:sub(incompleteStart) -- 确保这确实是一个未完成的标签,而不是文本中的<符号 if incompleteContent:match("^<[%w_]") then -- 尝试解析未完成的开始标签 local tagName = incompleteContent:match("^<([%w_]+)") if tagName then -- 处理未完成标签前的文本 if incompleteStart > 1 then local precedingText = trim(remaining:sub(1, incompleteStart - 1)) if precedingText ~= "" then if self.current then -- 如果当前在某个标签内,添加到该标签的文本内容 precedingText = decodeEntities(precedingText) if self.current._text then self.current._text = self.current._text .. precedingText else self.current._text = precedingText end else -- 如果是顶层文本,作为独立元素添加 local textElement = { _name = "_text", _text = decodeEntities(precedingText), } table.insert(self.results, textElement) end end end -- 创建未完成的元素 local element = { _name = tagName, _attr = {}, _state = "incomplete_start_tag", } if not self.root then self.root = element self.current = element elseif self.current then table.insert(self.stack, self.current) if not self.current[tagName] then self.current[tagName] = {} end table.insert(self.current[tagName], element) self.current = element end self.incomplete_tag = { start_pos = self.position + incompleteStart - 1, content = incompleteContent, element = element, } self.state = "incomplete" return end end end -- 处理剩余的文本内容 if remaining ~= "" then if self.current then -- 检查当前深度,如果在第一层子元素中,保持原始文本 local currentDepth = #self.stack if currentDepth >= 1 then -- 在第一层子元素中,保持原始文本不变 if self.current._text then self.current._text = self.current._text .. remaining else self.current._text = remaining end else -- 在根级别,进行正常的文本处理 local text = trim(remaining) if text ~= "" then text = decodeEntities(text) if self.current._text then self.current._text = self.current._text .. text else self.current._text = text end end end else -- 如果是顶层文本,作为独立元素添加 local text = trim(remaining) if text ~= "" then local textElement = { _name = "_text", _text = decodeEntities(text), } table.insert(self.results, textElement) end end end self.position = #self.buffer + 1 break end local tag = remaining:sub(tagStart, tagEnd) local actualTagStart = self.position + tagStart - 1 local actualTagEnd = self.position + tagEnd - 1 -- 检查是否为有效的XML标签 if not isValidXmlTag(tag, self.buffer, actualTagStart) then -- 如果不是有效标签,将其作为普通文本处理 local text = remaining:sub(1, tagEnd) if text ~= "" then if self.current then -- 检查当前深度,如果在第一层子元素中,保持原始文本 local currentDepth = #self.stack if currentDepth >= 1 then -- 在第一层子元素中,保持原始文本不变 if self.current._text then self.current._text = self.current._text .. text else self.current._text = text end else -- 在根级别,进行正常的文本处理 text = trim(text) if text ~= "" then text = decodeEntities(text) if self.current._text then self.current._text = self.current._text .. text else self.current._text = text end end end else -- 顶层文本作为独立元素 text = trim(text) if text ~= "" then local textElement = { _name = "_text", _text = decodeEntities(text), } table.insert(self.results, textElement) end end end self.position = actualTagEnd + 1 goto continue end -- 处理标签前的文本内容 if tagStart > 1 then local precedingText = remaining:sub(1, tagStart - 1) if precedingText ~= "" then if self.current then -- 如果当前在某个标签内,添加到该标签的文本内容 -- 检查当前深度,如果在第一层子元素中,不要进行实体解码和trim local currentDepth = #self.stack if currentDepth >= 1 then -- 在第一层子元素中,保持原始文本不变 if self.current._text then self.current._text = self.current._text .. precedingText else self.current._text = precedingText end else -- 在根级别,进行正常的文本处理 precedingText = trim(precedingText) if precedingText ~= "" then precedingText = decodeEntities(precedingText) if self.current._text then self.current._text = self.current._text .. precedingText else self.current._text = precedingText end end end else -- 如果是顶层文本,作为独立元素添加 precedingText = trim(precedingText) if precedingText ~= "" then local textElement = { _name = "_text", _text = decodeEntities(precedingText), } table.insert(self.results, textElement) end end end end -- 检查当前深度,如果已经在第一层子元素中,将所有标签作为文本处理 local currentDepth = #self.stack if currentDepth >= 1 then -- 检查是否是当前元素的结束标签 if tag:match("^</[_%w]+>$") and self.current then local tagName = tag:match("^</([_%w]+)>$") if self.current._name == tagName then -- 这是当前元素的结束标签,正常处理 if not self:processTag(tag) then self.state = "error" return end else -- 不是当前元素的结束标签,作为文本处理 if self.current._text then self.current._text = self.current._text .. tag else self.current._text = tag end end else -- 在第一层子元素中,将标签作为文本处理 if self.current then if self.current._text then self.current._text = self.current._text .. tag else self.current._text = tag end end end else -- 处理标签 if not self:processTag(tag) then self.state = "error" return end end self.position = actualTagEnd + 1 ::continue:: end -- 检查当前是否有未关闭的元素 if self.current and self.current._state ~= "complete" then self.current._state = "incomplete_unclosed" self.state = "incomplete" elseif self.state ~= "incomplete" and self.state ~= "error" then self.state = "ready" end end -- 处理单个标签 function StreamParser:processTag(tag) if tag:match("^</[_%w]+>$") then -- 结束标签 local tagName = tag:match("^</([_%w]+)>$") if self.current and self.current._name == tagName then -- 标记当前元素为完成状态 self.current._state = "complete" self.current = table.remove(self.stack) -- 只有当栈为空且当前元素也为空时,说明完成了一个根级元素 if #self.stack == 0 and not self.current and self.root then table.insert(self.results, self.root) self.root = nil end else self.last_error = "Mismatched closing tag: " .. tagName return false end elseif tag:match("^<[_%w]+[^>]*/>$") then -- 自闭合标签 local tagName, attrs = tag:match("^<([_%w]+)([^>]*)/>") local element = { _name = tagName, _attr = parseAttributes(attrs), _state = "complete", children = {}, } if not self.root then -- 直接作为根级元素添加到结果中 table.insert(self.results, element) elseif self.current then if not self.current.children then self.current.children = {} end table.insert(self.current.children, element) end elseif tag:match("^<[_%w]+[^>]*>$") then -- 开始标签 local tagName, attrs = tag:match("^<([_%w]+)([^>]*)>") local element = { _name = tagName, _attr = parseAttributes(attrs), _state = "incomplete_open", -- 标记为未完成(等待结束标签) children = {}, } if not self.root then self.root = element self.current = element elseif self.current then table.insert(self.stack, self.current) if not self.current.children then self.current.children = {} end table.insert(self.current.children, element) self.current = element end end return true end -- 获取所有元素(已完成的和当前正在处理的) function StreamParser:getAllElements() local all_elements = {} -- 添加所有已完成的元素 for _, element in ipairs(self.results) do table.insert(all_elements, element) end -- 如果有当前正在处理的元素,也添加进去 if self.root then table.insert(all_elements, self.root) end return all_elements end -- 获取已完成的元素(保留向后兼容性) function StreamParser:getCompletedElements() return self.results end -- 获取当前未完成的元素(保留向后兼容性) function StreamParser:getCurrentElement() return self.root end -- 强制完成解析(将未完成的内容作为已完成处理) function StreamParser:finalize() -- 首先处理当前正在解析的元素 if self.current then -- 递归设置所有未完成元素的状态 local function markIncompleteElements(element) if element._state and element._state:match("incomplete") then element._state = "incomplete_unclosed" end -- 处理 children 数组中的子元素 if element.children and type(element.children) == "table" then for _, child in ipairs(element.children) do if type(child) == "table" and child._name then markIncompleteElements(child) end end end end -- 标记当前元素及其所有子元素为未完成状态,但保持层次结构 markIncompleteElements(self.current) -- 向上遍历栈,标记所有祖先元素 for i = #self.stack, 1, -1 do local ancestor = self.stack[i] if ancestor._state and ancestor._state:match("incomplete") then ancestor._state = "incomplete_unclosed" end end end -- 只有当存在根元素时才添加到结果中 if self.root then table.insert(self.results, self.root) self.root = nil end self.current = nil self.stack = {} self.state = "ready" self.incomplete_tag = nil end -- 创建流式解析器实例 function XmlParser.createStreamParser() return StreamParser.new() end return XmlParser
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm.lua
Lua
local api = vim.api local fn = vim.fn local uv = vim.uv local curl = require("plenary.curl") local ACPClient = require("avante.libs.acp_client") local Utils = require("avante.utils") local Prompts = require("avante.utils.prompts") local Config = require("avante.config") local Path = require("avante.path") local PPath = require("plenary.path") local Providers = require("avante.providers") local LLMToolHelpers = require("avante.llm_tools.helpers") local LLMTools = require("avante.llm_tools") local History = require("avante.history") local HistoryRender = require("avante.history.render") local ACPConfirmAdapter = require("avante.ui.acp_confirm_adapter") ---@class avante.LLM local M = {} M.CANCEL_PATTERN = "AvanteLLMEscape" ------------------------------Prompt and type------------------------------ local group = api.nvim_create_augroup("avante_llm", { clear = true }) ---@param prev_memory string | nil ---@param history_messages avante.HistoryMessage[] ---@param cb fun(memory: avante.ChatMemory | nil): nil function M.summarize_memory(prev_memory, history_messages, cb) local system_prompt = [[You are an expert coding assistant. Your goal is to generate a concise, structured summary of the conversation below that captures all essential information needed to continue development after context replacement. Include tasks performed, code areas modified or reviewed, key decisions or assumptions, test results or errors, and outstanding tasks or next steps.]] if #history_messages == 0 then cb(nil) return end local latest_timestamp = nil local latest_message_uuid = nil for idx = #history_messages, 1, -1 do local message = history_messages[idx] if not message.is_dummy then latest_timestamp = message.timestamp latest_message_uuid = message.uuid break end end if not latest_timestamp or not latest_message_uuid then cb(nil) return end local conversation_items = vim .iter(history_messages) :map(function(msg) return msg.message.role .. ": " .. HistoryRender.message_to_text(msg, history_messages) end) :totable() local conversation_text = table.concat(conversation_items, "\n") local user_prompt = "Here is the conversation so far:\n" .. conversation_text .. "\n\nPlease summarize this conversation, covering:\n1. Tasks performed and outcomes\n2. Code files, modules, or functions modified or examined\n3. Important decisions or assumptions made\n4. Errors encountered and test or build results\n5. Remaining tasks, open questions, or next steps\nProvide the summary in a clear, concise format." if prev_memory then user_prompt = user_prompt .. "\n\nThe previous summary is:\n\n" .. prev_memory end local messages = { { role = "user", content = user_prompt, }, } local response_content = "" local provider = Providers.get_memory_summary_provider() M.curl({ provider = provider, prompt_opts = { system_prompt = system_prompt, messages = messages, }, handler_opts = { on_start = function(_) end, on_chunk = function(chunk) if not chunk then return end response_content = response_content .. chunk end, on_stop = function(stop_opts) if stop_opts.error ~= nil then Utils.error(string.format("summarize memory failed: %s", vim.inspect(stop_opts.error))) return end if stop_opts.reason == "complete" then response_content = Utils.trim_think_content(response_content) local memory = { content = response_content, last_summarized_timestamp = latest_timestamp, last_message_uuid = latest_message_uuid, } cb(memory) else cb(nil) end end, }, }) end ---@param user_input string ---@param cb fun(error: string | nil): nil function M.generate_todos(user_input, cb) local system_prompt = [[You are an expert coding assistant. Please generate a todo list to complete the task based on the user input and pass the todo list to the write_todos tool.]] local messages = { { role = "user", content = user_input }, } local provider = Providers[Config.provider] local tools = { require("avante.llm_tools.write_todos"), } local history_messages = {} cb = Utils.call_once(cb) M.curl({ provider = provider, prompt_opts = { system_prompt = system_prompt, messages = messages, tools = tools, }, handler_opts = { on_start = function() end, on_chunk = function() end, on_messages_add = function(msgs) msgs = vim.islist(msgs) and msgs or { msgs } for _, msg in ipairs(msgs) do if not msg.uuid then msg.uuid = Utils.uuid() end local idx = nil for i, m in ipairs(history_messages) do if m.uuid == msg.uuid then idx = i break end end if idx ~= nil then history_messages[idx] = msg else table.insert(history_messages, msg) end end end, on_stop = function(stop_opts) if stop_opts.error ~= nil then Utils.error(string.format("generate todos failed: %s", vim.inspect(stop_opts.error))) return end if stop_opts.reason == "tool_use" then local pending_tools = History.get_pending_tools(history_messages) for _, pending_tool in ipairs(pending_tools) do if pending_tool.state == "generated" and pending_tool.name == "write_todos" then local result = LLMTools.process_tool_use(tools, pending_tool, { session_ctx = {}, on_complete = function() cb() end, tool_use_id = pending_tool.id, }) if result ~= nil then cb() end end end else cb() end end, }, }) end ---@class avante.AgentLoopOptions ---@field system_prompt string ---@field user_input string ---@field tools AvanteLLMTool[] ---@field on_complete fun(error: string | nil): nil ---@field session_ctx? table ---@field on_tool_log? fun(tool_id: string, tool_name: string, log: string, state: AvanteLLMToolUseState): nil ---@field on_start? fun(): nil ---@field on_chunk? fun(chunk: string): nil ---@field on_messages_add? fun(messages: avante.HistoryMessage[]): nil ---@param opts avante.AgentLoopOptions function M.agent_loop(opts) local messages = {} table.insert(messages, { role = "user", content = "<task>" .. opts.user_input .. "</task>" }) local memory_content = nil local history_messages = {} local function no_op() end local session_ctx = opts.session_ctx or {} local stream_options = { ask = true, memory = memory_content, code_lang = "unknown", provider = Providers[Config.provider], get_history_messages = function() return history_messages end, on_tool_log = opts.on_tool_log or no_op, on_messages_add = function(msgs) msgs = vim.islist(msgs) and msgs or { msgs } for _, msg in ipairs(msgs) do local idx = nil for i, m in ipairs(history_messages) do if m.uuid == msg.uuid then idx = i break end end if idx ~= nil then history_messages[idx] = msg else table.insert(history_messages, msg) end end if opts.on_messages_add then opts.on_messages_add(msgs) end end, session_ctx = session_ctx, prompt_opts = { system_prompt = opts.system_prompt, tools = opts.tools, messages = messages, }, on_start = opts.on_start or no_op, on_chunk = opts.on_chunk or no_op, on_stop = function(stop_opts) if stop_opts.error ~= nil then local err = string.format("dispatch_agent failed: %s", vim.inspect(stop_opts.error)) opts.on_complete(err) return end opts.on_complete(nil) end, } local function on_memory_summarize(pending_compaction_history_messages) local compaction_history_message_uuids = {} for _, msg in ipairs(pending_compaction_history_messages or {}) do compaction_history_message_uuids[msg.uuid] = true end M.summarize_memory(memory_content, pending_compaction_history_messages or {}, function(memory) if memory then stream_options.memory = memory.content end local new_history_messages = {} for _, msg in ipairs(history_messages) do if not compaction_history_message_uuids[msg.uuid] then table.insert(new_history_messages, msg) end end history_messages = new_history_messages M._stream(stream_options) end) end stream_options.on_memory_summarize = on_memory_summarize M._stream(stream_options) end ---@param opts AvanteGeneratePromptsOptions ---@return AvantePromptOptions function M.generate_prompts(opts) local project_instruction_file = Config.instructions_file or "avante.md" local project_root = Utils.root.get() local instruction_file_path = PPath:new(project_root, project_instruction_file) if instruction_file_path:exists() then local lines = Utils.read_file_from_buf_or_disk(instruction_file_path:absolute()) local instruction_content = lines and table.concat(lines, "\n") or "" if instruction_content then opts.instructions = (opts.instructions or "") .. "\n" .. instruction_content end end local mode = opts.mode or Config.mode -- Check if the instructions contains an image path local image_paths = {} if opts.prompt_opts and opts.prompt_opts.image_paths then image_paths = vim.list_extend(image_paths, opts.prompt_opts.image_paths) end Path.prompts.initialize(Path.prompts.get_templates_dir(project_root), project_root) local system_info = Utils.get_system_info() local selected_files = opts.selected_files or {} if opts.selected_filepaths then for _, filepath in ipairs(opts.selected_filepaths) do local lines, error = Utils.read_file_from_buf_or_disk(filepath) if error ~= nil then Utils.error("error reading file: " .. error) else local content = table.concat(lines or {}, "\n") local filetype = Utils.get_filetype(filepath) table.insert(selected_files, { path = filepath, content = content, file_type = filetype }) end end end local viewed_files = {} if opts.history_messages then for _, message in ipairs(opts.history_messages) do local use = History.Helpers.get_tool_use_data(message) if use and use.name == "view" and use.input.path then local uniform_path = Utils.uniform_path(use.input.path) viewed_files[uniform_path] = use.id end end end selected_files = vim.iter(selected_files):filter(function(file) return viewed_files[file.path] == nil end):totable() local is_acp_provider = false if not opts.provider then is_acp_provider = Config.acp_providers[Config.provider] ~= nil end local model_name = "unknown" local context_window = nil local use_react_prompt = false if not is_acp_provider then local provider = opts.provider or Providers[Config.provider] model_name = provider.model or "unknown" local provider_conf = Providers.parse_config(provider) use_react_prompt = provider_conf.use_ReAct_prompt context_window = provider.context_window end local template_opts = { ask = opts.ask, -- TODO: add mode without ask instruction code_lang = opts.code_lang, selected_files = selected_files, selected_code = opts.selected_code, recently_viewed_files = opts.recently_viewed_files, project_context = opts.project_context, diagnostics = opts.diagnostics, system_info = system_info, model_name = model_name, memory = opts.memory, enable_fastapply = Config.behaviour.enable_fastapply, use_react_prompt = use_react_prompt, } -- Removed the original todos processing logic, now handled in context_messages local system_prompt if opts.prompt_opts and opts.prompt_opts.system_prompt then system_prompt = opts.prompt_opts.system_prompt else system_prompt = Path.prompts.render_mode(mode, template_opts) end if Config.system_prompt ~= nil then local custom_system_prompt if type(Config.system_prompt) == "function" then custom_system_prompt = Config.system_prompt() end if type(Config.system_prompt) == "string" then custom_system_prompt = Config.system_prompt end if custom_system_prompt ~= nil and custom_system_prompt ~= "" and custom_system_prompt ~= "null" then system_prompt = system_prompt .. "\n\n" .. custom_system_prompt end end ---@type AvanteLLMMessage[] local context_messages = {} if opts.prompt_opts and opts.prompt_opts.messages then context_messages = vim.list_extend(context_messages, opts.prompt_opts.messages) end if opts.project_context ~= nil and opts.project_context ~= "" and opts.project_context ~= "null" then local project_context = Path.prompts.render_file("_project.avanterules", template_opts) if project_context ~= "" then table.insert(context_messages, { role = "user", content = project_context, visible = false, is_context = true }) end end if opts.diagnostics ~= nil and opts.diagnostics ~= "" and opts.diagnostics ~= "null" then local diagnostics = Path.prompts.render_file("_diagnostics.avanterules", template_opts) if diagnostics ~= "" then table.insert(context_messages, { role = "user", content = diagnostics, visible = false, is_context = true }) end end if #selected_files > 0 or opts.selected_code ~= nil then local code_context = Path.prompts.render_file("_context.avanterules", template_opts) if code_context ~= "" then table.insert(context_messages, { role = "user", content = code_context, visible = false, is_context = true }) end end if opts.memory ~= nil and opts.memory ~= "" and opts.memory ~= "null" then local memory = Path.prompts.render_file("_memory.avanterules", template_opts) if memory ~= "" then table.insert(context_messages, { role = "user", content = memory, visible = false, is_context = true }) end end local pending_compaction_history_messages = {} if opts.prompt_opts and opts.prompt_opts.pending_compaction_history_messages then pending_compaction_history_messages = vim.list_extend(pending_compaction_history_messages, opts.prompt_opts.pending_compaction_history_messages) end if context_window and context_window > 0 then Utils.debug("Context window", context_window) if opts.get_tokens_usage then local tokens_usage = opts.get_tokens_usage() if tokens_usage and tokens_usage.prompt_tokens ~= nil and tokens_usage.completion_tokens ~= nil then local target_tokens = context_window * 0.9 local tokens_count = tokens_usage.prompt_tokens + tokens_usage.completion_tokens Utils.debug("Tokens count", tokens_count) if tokens_count > target_tokens then pending_compaction_history_messages = opts.history_messages end end end end ---@type AvanteLLMMessage[] local messages = vim.deepcopy(context_messages) for _, msg in ipairs(opts.history_messages or {}) do local message = msg.message if msg.is_user_submission then message = vim.deepcopy(message) local content = message.content if Config.mode == "agentic" then if type(content) == "string" then message.content = "<task>" .. content .. "</task>" elseif type(content) == "table" then for idx, item in ipairs(content) do if type(item) == "string" then item = "<task>" .. item .. "</task>" content[idx] = item elseif type(item) == "table" and item.type == "text" then item.content = "<task>" .. item.content .. "</task>" content[idx] = item end end end end end table.insert(messages, message) end messages = vim .iter(messages) :filter(function(msg) return type(msg.content) ~= "string" or msg.content ~= "" end) :totable() if opts.instructions ~= nil and opts.instructions ~= "" then messages = vim.list_extend(messages, { { role = "user", content = opts.instructions } }) end opts.session_ctx = opts.session_ctx or {} opts.session_ctx.system_prompt = system_prompt opts.session_ctx.messages = messages local tools = {} if opts.tools then tools = vim.list_extend(tools, opts.tools) end if opts.prompt_opts and opts.prompt_opts.tools then tools = vim.list_extend(tools, opts.prompt_opts.tools) end -- Set tools to nil if empty to avoid sending empty arrays to APIs that require -- tools to be either non-existent or have at least one item if #tools == 0 then tools = nil end local agents_rules = Prompts.get_agents_rules_prompt() if agents_rules then system_prompt = system_prompt .. "\n\n" .. agents_rules end local cursor_rules = Prompts.get_cursor_rules_prompt(selected_files) if cursor_rules then system_prompt = system_prompt .. "\n\n" .. cursor_rules end ---@type AvantePromptOptions return { system_prompt = system_prompt, messages = messages, image_paths = image_paths, tools = tools, pending_compaction_history_messages = pending_compaction_history_messages, } end ---@param opts AvanteGeneratePromptsOptions ---@return integer function M.calculate_tokens(opts) if Config.acp_providers[Config.provider] then return 0 end local prompt_opts = M.generate_prompts(opts) local tokens = Utils.tokens.calculate_tokens(prompt_opts.system_prompt) for _, message in ipairs(prompt_opts.messages) do tokens = tokens + Utils.tokens.calculate_tokens(message.content) end return tokens end local parse_headers = function(headers_file) local headers = {} local file = io.open(headers_file, "r") if file then for line in file:lines() do line = line:gsub("\r$", "") local key, value = line:match("^%s*(.-)%s*:%s*(.*)$") if key and value then headers[key] = value end end if Config.debug then -- Original header file was deleted by plenary.nvim -- see https://github.com/nvim-lua/plenary.nvim/blob/b9fd5226c2f76c951fc8ed5923d85e4de065e509/lua/plenary/curl.lua#L268 local debug_headers_file = headers_file .. ".log" Utils.debug("curl response headers file:", debug_headers_file) local debug_file = io.open(debug_headers_file, "a") if debug_file then file:seek("set") debug_file:write(file:read("*all")) debug_file:close() end end file:close() end return headers end ---@param opts avante.CurlOpts function M.curl(opts) local provider = opts.provider local prompt_opts = opts.prompt_opts local handler_opts = opts.handler_opts local orig_on_stop = handler_opts.on_stop local stopped = false ---@param stop_opts AvanteLLMStopCallbackOptions handler_opts.on_stop = function(stop_opts) if stop_opts and not stop_opts.streaming_tool_use then if stopped then return end stopped = true end if orig_on_stop then return orig_on_stop(stop_opts) end end local spec = provider:parse_curl_args(prompt_opts) if not spec then handler_opts.on_stop({ reason = "error", error = "Provider configuration error" }) return end ---@type string local current_event_state = nil local turn_ctx = {} turn_ctx.turn_id = Utils.uuid() local response_body = "" ---@param line string local function parse_stream_data(line) local event = line:match("^event:%s*(.+)$") if event then current_event_state = event return end local data_match = line:match("^data:%s*(.+)$") if data_match then response_body = "" provider:parse_response(turn_ctx, data_match, current_event_state, handler_opts) else response_body = response_body .. line local ok, jsn = pcall(vim.json.decode, response_body) if ok then if jsn.error then handler_opts.on_stop({ reason = "error", error = jsn.error }) else provider:parse_response(turn_ctx, response_body, current_event_state, handler_opts) end response_body = "" end end end local function parse_response_without_stream(data) provider:parse_response_without_stream(data, current_event_state, handler_opts) end local completed = false local active_job ---@type Job|nil local temp_file = fn.tempname() local curl_body_file = temp_file .. "-request-body.json" local resp_body_file = temp_file .. "-response-body.txt" local headers_file = temp_file .. "-response-headers.txt" -- Check if this is a multipart form request (specifically for watsonx) local is_multipart_form = spec.headers and spec.headers["Content-Type"] == "multipart/form-data" local curl_options if is_multipart_form then -- For multipart form data, use the form parameter -- spec.body should be a table with form field data curl_options = { headers = spec.headers, proxy = spec.proxy, insecure = spec.insecure, form = spec.body, raw = spec.rawArgs, } else -- For regular JSON requests, encode as JSON and write to file local json_content = vim.json.encode(spec.body) fn.writefile(vim.split(json_content, "\n"), curl_body_file) curl_options = { headers = spec.headers, proxy = spec.proxy, insecure = spec.insecure, body = curl_body_file, raw = spec.rawArgs, } end Utils.debug("curl request body file:", curl_body_file) Utils.debug("curl response body file:", resp_body_file) local function cleanup() if Config.debug then return end vim.schedule(function() fn.delete(curl_body_file) pcall(fn.delete, resp_body_file) end) end local headers_reported = false local started_job, new_active_job = pcall( curl.post, spec.url, vim.tbl_extend("force", curl_options, { dump = { "-D", headers_file }, stream = function(err, data, _) if not headers_reported and opts.on_response_headers then headers_reported = true opts.on_response_headers(parse_headers(headers_file)) end if err then completed = true handler_opts.on_stop({ reason = "error", error = err }) return end if not data then return end if Config.debug then if type(data) == "string" then local file = io.open(resp_body_file, "a") if file then file:write(data .. "\n") file:close() end end end vim.schedule(function() if provider.parse_stream_data ~= nil then provider:parse_stream_data(turn_ctx, data, handler_opts) else parse_stream_data(data) end end) end, on_error = function(err) if err.exit == 23 then local xdg_runtime_dir = os.getenv("XDG_RUNTIME_DIR") if not xdg_runtime_dir or fn.isdirectory(xdg_runtime_dir) == 0 then Utils.error( "$XDG_RUNTIME_DIR=" .. xdg_runtime_dir .. " is set but does not exist. curl could not write output. Please make sure it exists, or unset.", { title = "Avante" } ) elseif not uv.fs_access(xdg_runtime_dir, "w") then Utils.error( "$XDG_RUNTIME_DIR=" .. xdg_runtime_dir .. " exists but is not writable. curl could not write output. Please make sure it is writable, or unset.", { title = "Avante" } ) end end active_job = nil if not completed then completed = true cleanup() handler_opts.on_stop({ reason = "error", error = err }) end end, callback = function(result) active_job = nil cleanup() local headers_map = vim.iter(result.headers):fold({}, function(acc, value) local pieces = vim.split(value, ":") local key = pieces[1] local remain = vim.list_slice(pieces, 2) if not remain then return acc end local val = Utils.trim_spaces(table.concat(remain, ":")) acc[key] = val return acc end) if result.status >= 400 then if provider.on_error then provider.on_error(result) else Utils.error("API request failed with status " .. result.status, { once = true, title = "Avante" }) end local retry_after = 10 if headers_map["retry-after"] then retry_after = tonumber(headers_map["retry-after"]) or 10 end if result.status == 429 then handler_opts.on_stop({ reason = "rate_limit", retry_after = retry_after }) return end vim.schedule(function() if not completed then completed = true handler_opts.on_stop({ reason = "error", error = "API request failed with status " .. result.status .. ". Body: " .. vim.inspect(result.body), }) end end) end -- If stream is not enabled, then handle the response here if provider:is_disable_stream() and result.status == 200 then vim.schedule(function() completed = true parse_response_without_stream(result.body) end) end if result.status == 200 and spec.url:match("https://openrouter.ai") then local content_type = headers_map["content-type"] if content_type and content_type:match("text/html") then handler_opts.on_stop({ reason = "error", error = "Your openrouter endpoint setting is incorrect, please set it to https://openrouter.ai/api/v1", }) end end end, }) ) if not started_job then local error_msg = vim.inspect(new_active_job) Utils.error("Failed to make LLM request: " .. error_msg) handler_opts.on_stop({ reason = "error", error = error_msg }) return end active_job = new_active_job api.nvim_create_autocmd("User", { group = group, pattern = M.CANCEL_PATTERN, once = true, callback = function() -- Error: cannot resume dead coroutine if active_job then -- Mark as completed first to prevent error handler from running completed = true -- 检查 active_job 的状态 local job_is_alive = pcall(function() return active_job:is_closing() == false end) -- 只有当 job 仍然活跃时才尝试关闭它 if job_is_alive then -- Attempt to shutdown the active job, but ignore any errors xpcall(function() active_job:shutdown() end, function(err) Utils.debug("Ignored error during job shutdown: " .. vim.inspect(err)) return err end) else Utils.debug("Job already closed, skipping shutdown") end Utils.debug("LLM request cancelled") active_job = nil -- Clean up and notify of cancellation cleanup() vim.schedule(function() handler_opts.on_stop({ reason = "cancelled" }) end) end end, }) return active_job end local retry_timer = nil local abort_retry_timer = false local function stop_retry_timer() if retry_timer then retry_timer:stop() pcall(function() retry_timer:close() end) retry_timer = nil end end -- Intelligently truncate chat history for session recovery to avoid token limits ---@param history_messages table[] ---@return table[] local function truncate_history_for_recovery(history_messages) if not history_messages or #history_messages == 0 then return {} end -- Get configuration parameters with validation and sensible defaults local recovery_config = Config.session_recovery or {} local MAX_RECOVERY_MESSAGES = math.max(1, math.min(recovery_config.max_history_messages or 20, 50)) -- Increased from 10 to 20 local MAX_MESSAGE_LENGTH = math.max(100, math.min(recovery_config.max_message_length or 1000, 10000)) -- Keep recent messages starting from the newest local truncated = {} local count = 0 -- CRITICAL: For session recovery, prioritize keeping conversation pairs (user+assistant) -- This preserves the full context of recent interactions local conversation_pairs = {} local last_user_message = nil for i = #history_messages, 1, -1 do local message = history_messages[i] if message and message.message and message.message.content then local role = message.message.role -- Build conversation pairs for better context preservation if role == "user" then last_user_message = message elseif role == "assistant" and last_user_message then -- Found a complete conversation pair table.insert(conversation_pairs, 1, { user = last_user_message, assistant = message }) last_user_message = nil end end end -- Add complete conversation pairs first (better context preservation) for _, pair in ipairs(conversation_pairs) do if count >= MAX_RECOVERY_MESSAGES then break end -- Add user message table.insert(truncated, 1, pair.user) count = count + 1 if count < MAX_RECOVERY_MESSAGES then -- Add assistant response table.insert(truncated, 1, pair.assistant) count = count + 1 end end -- Add remaining individual messages if space allows for i = #history_messages, 1, -1 do if count >= MAX_RECOVERY_MESSAGES then break end local message = history_messages[i] if message and message.message and message.message.content then -- Skip if already added as part of conversation pair local already_added = false for _, added_msg in ipairs(truncated) do if added_msg.uuid == message.uuid then already_added = true break end end if not already_added then -- Prioritize user messages and important assistant replies, skip verbose tool call results local content = message.message.content local role = message.message.role -- Skip overly verbose tool call results with multiple code blocks if role == "assistant" and type(content) == "string" and content:match("```.*```.*```") and #content > MAX_MESSAGE_LENGTH * 2 then goto continue end -- Handle string content if type(content) == "string" then if #content > MAX_MESSAGE_LENGTH then -- Truncate overly long messages local truncated_message = vim.deepcopy(message) truncated_message.message.content = content:sub(1, MAX_MESSAGE_LENGTH) .. "...[truncated]" table.insert(truncated, 1, truncated_message) else table.insert(truncated, 1, message) end -- Handle table content (multimodal messages) elseif type(content) == "table" then local truncated_message = vim.deepcopy(message) -- Safely handle table content if truncated_message.message.content and type(truncated_message.message.content) == "table" then for j, item in ipairs(truncated_message.message.content) do -- Handle various content item types if type(item) == "string" and #item > MAX_MESSAGE_LENGTH then truncated_message.message.content[j] = item:sub(1, MAX_MESSAGE_LENGTH) .. "...[truncated]" elseif type(item) == "table" and item.text and type(item.text) == "string" and #item.text > MAX_MESSAGE_LENGTH then -- Handle {type="text", text="..."} format item.text = item.text:sub(1, MAX_MESSAGE_LENGTH) .. "...[truncated]" end end end table.insert(truncated, 1, truncated_message) else table.insert(truncated, 1, message) end count = count + 1 end end ::continue:: end return truncated end ---@param opts AvanteLLMStreamOptions function M._stream_acp(opts) Utils.debug("use ACP", Config.provider) ---@type table<string, avante.HistoryMessage> local tool_call_messages = {} ---@type avante.HistoryMessage local last_tool_call_message = nil local acp_provider = Config.acp_providers[Config.provider] local prev_text_message_content = "" local history_messages = {} local get_history_messages = function() if opts.get_history_messages then return opts.get_history_messages() end return history_messages end local on_messages_add = function(messages) if opts.on_chunk then for _, message in ipairs(messages) do if message.message.role == "assistant" and type(message.message.content) == "string" then local chunk = message.message.content:sub(#prev_text_message_content + 1) opts.on_chunk(chunk) prev_text_message_content = message.message.content end end end if opts.on_messages_add then opts.on_messages_add(messages) else for _, message in ipairs(messages) do local idx = nil for i, m in ipairs(history_messages) do if m.uuid == message.uuid then idx = i break end end if idx ~= nil then history_messages[idx] = message else table.insert(history_messages, message) end end end end local function add_tool_call_message(update) local message = History.Message:new("assistant", { type = "tool_use", id = update.toolCallId, name = update.kind or update.title, input = update.rawInput or {}, }, { uuid = update.toolCallId, }) last_tool_call_message = message message.acp_tool_call = update if update.status == "pending" or update.status == "in_progress" then message.is_calling = true end tool_call_messages[update.toolCallId] = message if update.rawInput then local description = update.rawInput.description if description then message.tool_use_logs = message.tool_use_logs or {} table.insert(message.tool_use_logs, description) end end on_messages_add({ message }) return message end local acp_client = opts.acp_client local session_id = opts.acp_session_id if not acp_client then local acp_config = vim.tbl_deep_extend("force", acp_provider, { ---@type ACPHandlers handlers = { on_session_update = function(update) if update.sessionUpdate == "plan" then local todos = {} for idx, entry in ipairs(update.entries) do local status = "todo" if entry.status == "in_progress" then status = "doing" end if entry.status == "completed" then status = "done" end ---@type avante.TODO local todo = { id = tostring(idx), content = entry.content, status = status, priority = entry.priority, } table.insert(todos, todo) end vim.schedule(function() if opts.update_todos then opts.update_todos(todos) end end) return end if update.sessionUpdate == "agent_message_chunk" then if update.content.type == "text" then local messages = get_history_messages() local last_message = messages[#messages] if last_message and last_message.message.role == "assistant" then local has_text = false local content = last_message.message.content if type(content) == "string" then last_message.message.content = last_message.message.content .. update.content.text has_text = true elseif type(content) == "table" then for idx, item in ipairs(content) do if type(item) == "string" then content[idx] = item .. update.content.text has_text = true end if type(item) == "table" and item.type == "text" then item.text = item.text .. update.content.text has_text = true end end end if has_text then on_messages_add({ last_message }) return end end local message = History.Message:new("assistant", update.content.text) on_messages_add({ message }) end end if update.sessionUpdate == "agent_thought_chunk" then if update.content.type == "text" then local messages = get_history_messages() local last_message = messages[#messages] if last_message and last_message.message.role == "assistant" then local is_thinking = false local content = last_message.message.content if type(content) == "table" then for idx, item in ipairs(content) do if type(item) == "table" and item.type == "thinking" then is_thinking = true content[idx].thinking = content[idx].thinking .. update.content.text end end end if is_thinking then on_messages_add({ last_message }) return end end local message = History.Message:new("assistant", { type = "thinking", thinking = update.content.text, }) on_messages_add({ message }) end end if update.sessionUpdate == "tool_call" then add_tool_call_message(update) local sidebar = require("avante").get() if Config.behaviour.acp_follow_agent_locations and sidebar and not sidebar.is_in_full_view -- don't follow when in Zen mode and update.kind == "edit" -- to avoid entering more than once and update.locations and #update.locations > 0 then vim.schedule(function() if not sidebar:is_open() then return end -- Find a valid code window (non-sidebar window) local code_winid = nil if sidebar.code.winid and sidebar.code.winid ~= 0 and api.nvim_win_is_valid(sidebar.code.winid) then code_winid = sidebar.code.winid else -- Find first non-sidebar window in the current tab local all_wins = api.nvim_tabpage_list_wins(0) for _, winid in ipairs(all_wins) do if api.nvim_win_is_valid(winid) and not sidebar:is_sidebar_winid(winid) then code_winid = winid break end end end if not code_winid then return end local now = uv.now() local last_auto_nav = vim.g.avante_last_auto_nav or 0 local grace_period = 2000 -- Check if user navigated manually recently if now - last_auto_nav < grace_period then return end -- Only follow first location to avoid rapid jumping local location = update.locations[1] if not location or not location.path then return end local abs_path = Utils.join_paths(Utils.get_project_root(), location.path) local bufnr = vim.fn.bufnr(abs_path, true) if not bufnr or bufnr == -1 then return end if not api.nvim_buf_is_loaded(bufnr) then pcall(vim.fn.bufload, bufnr) end local ok = pcall(api.nvim_win_set_buf, code_winid, bufnr) if not ok then return end local line = location.line or 1 local line_count = api.nvim_buf_line_count(bufnr) local target_line = math.min(line, line_count) pcall(api.nvim_win_set_cursor, code_winid, { target_line, 0 }) pcall(api.nvim_win_call, code_winid, function() vim.cmd("normal! zz") -- Center line in viewport end) vim.g.avante_last_auto_nav = now end) end end if update.sessionUpdate == "tool_call_update" then local tool_call_message = tool_call_messages[update.toolCallId] if not tool_call_message then tool_call_message = History.Message:new("assistant", { type = "tool_use", id = update.toolCallId, name = "", }) tool_call_messages[update.toolCallId] = tool_call_message tool_call_message.acp_tool_call = update end if tool_call_message.acp_tool_call then if update.content and next(update.content) == nil then update.content = nil end tool_call_message.acp_tool_call = vim.tbl_deep_extend("force", tool_call_message.acp_tool_call, update) end tool_call_message.tool_use_logs = tool_call_message.tool_use_logs or {} tool_call_message.tool_use_log_lines = tool_call_message.tool_use_log_lines or {} local tool_result_message if update.status == "pending" or update.status == "in_progress" then tool_call_message.is_calling = true tool_call_message.state = "generating" elseif update.status == "completed" or update.status == "failed" then tool_call_message.is_calling = false tool_call_message.state = "generated" tool_result_message = History.Message:new("assistant", { type = "tool_result", tool_use_id = update.toolCallId, content = nil, is_error = update.status == "failed", is_user_declined = update.status == "cancelled", }) end local messages = { tool_call_message } if tool_result_message then table.insert(messages, tool_result_message) end on_messages_add(messages) end if update.sessionUpdate == "available_commands_update" then local commands = update.availableCommands local has_cmp, cmp = pcall(require, "cmp") if has_cmp then local slash_commands_id = require("avante").slash_commands_id if slash_commands_id ~= nil then cmp.unregister_source(slash_commands_id) end for _, command in ipairs(commands) do local exists = false for _, command_ in ipairs(Config.slash_commands) do if command_.name == command.name then exists = true break end end if not exists then table.insert(Config.slash_commands, { name = command.name, description = command.description, details = command.description, }) end end local avante = require("avante") avante.slash_commands_id = cmp.register_source("avante_commands", require("cmp_avante.commands"):new()) end end end, on_request_permission = function(tool_call, options, callback) local sidebar = require("avante").get() if not sidebar then Utils.error("Avante sidebar not found") return end ---@cast tool_call avante.acp.ToolCall local message = tool_call_messages[tool_call.toolCallId] if not message then message = add_tool_call_message(tool_call) else if message.acp_tool_call then if tool_call.content and next(tool_call.content) == nil then tool_call.content = nil end message.acp_tool_call = vim.tbl_deep_extend("force", message.acp_tool_call, tool_call) end end on_messages_add({ message }) local description = HistoryRender.get_tool_display_name(message) LLMToolHelpers.confirm(description, function(ok) local acp_mapped_options = ACPConfirmAdapter.map_acp_options(options) if ok and opts.session_ctx and opts.session_ctx.always_yes then callback(acp_mapped_options.all) elseif ok then callback(acp_mapped_options.yes) else callback(acp_mapped_options.no) end sidebar.scroll = true sidebar._history_cache_invalidated = true sidebar:update_content("") end, { focus = true, skip_reject_prompt = true, permission_options = options, }, opts.session_ctx, tool_call.kind) end, on_read_file = function(path, line, limit, callback, error_callback) local abs_path = Utils.to_absolute_path(path) local lines, err, errname = Utils.read_file_from_buf_or_disk(abs_path) if err then if error_callback then local code = errname == "ENOENT" and ACPClient.ERROR_CODES.RESOURCE_NOT_FOUND or nil error_callback(err, code) end return end lines = lines or {} if line ~= nil and limit ~= nil then lines = vim.list_slice(lines, line, line + limit) end local content = table.concat(lines, "\n") if last_tool_call_message and last_tool_call_message.acp_tool_call and last_tool_call_message.acp_tool_call.kind == "read" then if last_tool_call_message.acp_tool_call.content and next(last_tool_call_message.acp_tool_call.content) == nil then last_tool_call_message.acp_tool_call.content = { { type = "content", content = { type = "text", text = content, }, }, } end end callback(content) end, on_write_file = function(path, content, callback) local abs_path = Utils.to_absolute_path(path) local file = io.open(abs_path, "w") if file then file:write(content) file:close() local buffers = vim.tbl_filter( function(bufnr) return vim.api.nvim_buf_is_valid(bufnr) and vim.fn.fnamemodify(vim.api.nvim_buf_get_name(bufnr), ":p") == vim.fn.fnamemodify(abs_path, ":p") end, vim.api.nvim_list_bufs() ) for _, buf in ipairs(buffers) do vim.api.nvim_buf_call(buf, function() vim.cmd("edit") end) end callback(nil) return end callback("Failed to write file: " .. abs_path) end, }, }) acp_client = ACPClient:new(acp_config) acp_client:connect(function(conn_err) if conn_err then opts.on_stop({ reason = "error", error = conn_err }) return end -- Register ACP client for global cleanup on exit (Fix Issue #2749) local client_id = "acp_" .. tostring(acp_client) .. "_" .. os.time() local ok, Avante = pcall(require, "avante") if ok and Avante.register_acp_client then Avante.register_acp_client(client_id, acp_client) end -- If we create a new client and it does not support sesion loading, -- remove the old session if not acp_client.agent_capabilities.loadSession then opts.acp_session_id = nil end if opts.on_save_acp_client then opts.on_save_acp_client(acp_client) end session_id = opts.acp_session_id if not session_id then M._create_acp_session_and_continue(opts, acp_client) else M._load_acp_session_and_continue(opts, acp_client, session_id) end end) return elseif not session_id then M._create_acp_session_and_continue(opts, acp_client) return end if opts.just_connect_acp_client then return end M._continue_stream_acp(opts, acp_client, session_id) end ---@param opts AvanteLLMStreamOptions ---@param acp_client avante.acp.ACPClient function M._create_acp_session_and_continue(opts, acp_client) local project_root = Utils.root.get() local acp_provider = Config.acp_providers[Config.provider] or {} local mcp_servers = acp_provider.mcp_servers or {} acp_client:create_session(project_root, mcp_servers, function(session_id_, err) if err then opts.on_stop({ reason = "error", error = err }) return end if not session_id_ then opts.on_stop({ reason = "error", error = "Failed to create session" }) return end opts.acp_session_id = session_id_ if opts.on_save_acp_session_id then opts.on_save_acp_session_id(session_id_) end if opts.just_connect_acp_client then return end M._continue_stream_acp(opts, acp_client, session_id_) end) end ---@param opts AvanteLLMStreamOptions ---@param acp_client avante.acp.ACPClient ---@param session_id string function M._load_acp_session_and_continue(opts, acp_client, session_id) local project_root = Utils.root.get() acp_client:load_session(session_id, project_root, {}, function(_, err) if err then -- Failed to load session, create a new one. It happens after switching acp providers M._create_acp_session_and_continue(opts, acp_client) return end if opts.just_connect_acp_client then return end M._continue_stream_acp(opts, acp_client, session_id) end) end ---@param opts AvanteLLMStreamOptions ---@param acp_client avante.acp.ACPClient ---@param session_id string function M._continue_stream_acp(opts, acp_client, session_id) local prompt = {} local donot_use_builtin_system_prompt = opts.history_messages ~= nil and #opts.history_messages > 0 if donot_use_builtin_system_prompt then if opts.selected_filepaths then for _, filepath in ipairs(opts.selected_filepaths) do local abs_path = Utils.to_absolute_path(filepath) local file_name = vim.fn.fnamemodify(abs_path, ":t") local prompt_item = acp_client:create_resource_link_content("file://" .. abs_path, file_name) table.insert(prompt, prompt_item) end end if opts.selected_code then local prompt_item = { type = "text", text = string.format( "<selected_code>\n<path>%s</path>\n<snippet>%s</snippet>\n</selected_code>", opts.selected_code.path, opts.selected_code.content ), } table.insert(prompt, prompt_item) end end local history_messages = opts.history_messages or {} -- DEBUG: Log history message details Utils.debug("ACP history messages count: " .. #history_messages) for i, msg in ipairs(history_messages) do if msg and msg.message then Utils.debug( "History msg " .. i .. ": role=" .. (msg.message.role or "unknown") .. ", has_content=" .. tostring(msg.message.content ~= nil) ) if msg.message.role == "assistant" then Utils.debug("Found assistant message " .. i .. ": " .. tostring(msg.message.content):sub(1, 100)) end end end -- DEBUG: Log session recovery state Utils.debug( "Session recovery state: _is_session_recovery=" .. tostring(rawget(opts, "_is_session_recovery")) .. ", acp_session_id=" .. tostring(opts.acp_session_id) ) -- CRITICAL: Enhanced session recovery with full context preservation if rawget(opts, "_is_session_recovery") and opts.acp_session_id then -- For session recovery, preserve full conversation context Utils.info("ACP session recovery: preserving full conversation context") -- Add all recent messages (both user and assistant) for better context local recent_messages = {} local recovery_config = Config.session_recovery or {} local include_history_count = recovery_config.include_history_count or 15 -- Default to 15 for better context -- Get recent messages from truncated history local start_idx = math.max(1, #history_messages - include_history_count + 1) Utils.debug("Including history from index " .. start_idx .. " to " .. #history_messages) for i = start_idx, #history_messages do local message = history_messages[i] if message and message.message then table.insert(recent_messages, message) Utils.debug("Adding message " .. i .. " to recent_messages: role=" .. (message.message.role or "unknown")) end end Utils.info("ACP recovery: including " .. #recent_messages .. " recent messages") -- DEBUG: Log what we're about to add to prompt for i, msg in ipairs(recent_messages) do if msg and msg.message then Utils.debug("Adding to prompt: " .. i .. " role=" .. (msg.message.role or "unknown")) end end -- CRITICAL: Add all recent messages to prompt for complete context for _, message in ipairs(recent_messages) do local role = message.message.role local content = message.message.content Utils.debug("Processing message: role=" .. (role or "unknown") .. ", content_type=" .. type(content)) -- Format based on role local role_tag = role == "user" and "previous_user_message" or "previous_assistant_message" if type(content) == "table" then for _, item in ipairs(content) do if type(item) == "string" then table.insert(prompt, { type = "text", text = "<" .. role_tag .. ">" .. item .. "</" .. role_tag .. ">", }) Utils.debug("Added assistant table content: " .. item:sub(1, 50) .. "...") elseif type(item) == "table" and item.type == "text" then table.insert(prompt, { type = "text", text = "<" .. role_tag .. ">" .. item.text .. "</" .. role_tag .. ">", }) Utils.debug("Added assistant text content: " .. item.text:sub(1, 50) .. "...") end end else table.insert(prompt, { type = "text", text = "<" .. role_tag .. ">" .. content .. "</" .. role_tag .. ">", }) if role == "assistant" then Utils.debug("Added assistant content: " .. tostring(content):sub(1, 50) .. "...") end end end -- Add context about session recovery with more detail if #recent_messages > 0 then table.insert(prompt, { type = "text", text = "<system_context>Continuing from previous ACP session with " .. #recent_messages .. " recent messages preserved for context</system_context>", }) end elseif opts.acp_session_id then -- Original logic for non-recovery session continuation local recovery_config = Config.session_recovery or {} local include_history_count = recovery_config.include_history_count or 5 local user_messages_added = 0 for i = #history_messages, 1, -1 do local message = history_messages[i] if message.message.role == "user" and user_messages_added < include_history_count then local content = message.message.content if type(content) == "table" then for _, item in ipairs(content) do if type(item) == "string" then table.insert(prompt, { type = "text", text = "<previous_user_message>" .. item .. "</previous_user_message>", }) elseif type(item) == "table" and item.type == "text" then table.insert(prompt, { type = "text", text = "<previous_user_message>" .. item.text .. "</previous_user_message>", }) end end elseif type(content) == "string" then table.insert(prompt, { type = "text", text = "<previous_user_message>" .. content .. "</previous_user_message>", }) end user_messages_added = user_messages_added + 1 end end -- Add context about session recovery if user_messages_added > 0 then table.insert(prompt, { type = "text", text = "<system_context>Continuing from previous session with " .. user_messages_added .. " recent user messages</system_context>", }) end else if donot_use_builtin_system_prompt then -- Include all user messages for better context preservation for _, message in ipairs(history_messages) do if message.message.role == "user" then local content = message.message.content if type(content) == "table" then for _, item in ipairs(content) do if type(item) == "string" then table.insert(prompt, { type = "text", text = item, }) elseif type(item) == "table" and item.type == "text" then table.insert(prompt, { type = "text", text = item.text, }) end end else table.insert(prompt, { type = "text", text = content, }) end end end else local prompt_opts = M.generate_prompts(opts) table.insert(prompt, { type = "text", text = prompt_opts.system_prompt, }) for _, message in ipairs(prompt_opts.messages) do if message.role == "user" then table.insert(prompt, { type = "text", text = message.content, }) end end end end local cancelled = false local stop_cmd_id = api.nvim_create_autocmd("User", { group = group, pattern = M.CANCEL_PATTERN, once = true, callback = function() cancelled = true local cancelled_text = "\n*[Request cancelled by user.]*\n" if opts.on_chunk then opts.on_chunk(cancelled_text) end if opts.on_messages_add then local message = History.Message:new("assistant", cancelled_text, { just_for_display = true, }) opts.on_messages_add({ message }) end acp_client:cancel_session(session_id) opts.on_stop({ reason = "cancelled" }) end, }) acp_client:send_prompt(session_id, prompt, function(_, err_) if cancelled then return end vim.schedule(function() api.nvim_del_autocmd(stop_cmd_id) end) if err_ then -- ACP-specific session recovery: Check for session not found error -- Check for session recovery conditions local recovery_config = Config.session_recovery or {} local recovery_enabled = recovery_config.enabled ~= false -- Default enabled unless explicitly disabled local is_session_not_found = false if err_.code == -32603 and err_.data and err_.data.details then local details = err_.data.details -- Support both Claude format ("Session not found") and Gemini-CLI format ("Session not found: session-id") is_session_not_found = details == "Session not found" or details:match("^Session not found:") end if recovery_enabled and is_session_not_found and not rawget(opts, "_session_recovery_attempted") then -- Mark recovery attempt to prevent infinite loops rawset(opts, "_session_recovery_attempted", true) -- DEBUG: Log recovery attempt Utils.debug("Session recovery attempt detected, setting _session_recovery_attempted flag") -- Clear invalid session ID if opts.on_save_acp_session_id then opts.on_save_acp_session_id("") -- Use empty string instead of nil end -- Clear invalid session for recovery - let global cleanup handle ACP processes vim.schedule(function() opts.acp_client = nil opts.acp_session_id = nil end) -- CRITICAL: Preserve full history for better context retention -- Only truncate if explicitly configured to do so, otherwise keep full history local original_history = opts.history_messages or {} local truncated_history -- Check if history truncation is explicitly enabled local should_truncate = recovery_config.truncate_history ~= false -- Default to true for backward compatibility -- DEBUG: Log original history details Utils.debug("Original history for recovery: " .. #original_history .. " messages") for i, msg in ipairs(original_history) do if msg and msg.message then Utils.debug("Original history " .. i .. ": role=" .. (msg.message.role or "unknown")) end end if should_truncate and #original_history > 20 then -- Only truncate if history is long enough (20条) -- Safely call truncation function local ok, result = pcall(truncate_history_for_recovery, original_history) if ok then truncated_history = result Utils.info( "History truncated from " .. #original_history .. " to " .. #truncated_history .. " messages for recovery" ) else Utils.warn("Failed to truncate history for recovery: " .. tostring(result)) truncated_history = original_history -- Use full history as fallback end else -- Use full history for better context retention truncated_history = original_history Utils.debug("Using full history for session recovery: " .. #truncated_history .. " messages") end -- DEBUG: Log truncated history details Utils.debug("Truncated history for recovery: " .. #truncated_history .. " messages") for i, msg in ipairs(truncated_history) do if msg and msg.message then Utils.debug("Truncated history " .. i .. ": role=" .. (msg.message.role or "unknown")) end end opts.history_messages = truncated_history Utils.info( string.format( "Session expired, recovering with %d recent messages (from %d total)...", #truncated_history, #original_history ) ) -- CRITICAL: Use vim.schedule to move recovery out of fast event context -- This prevents E5560 errors by avoiding vim.fn calls in fast event context vim.schedule(function() Utils.debug("Session recovery: clearing old session ID and retrying...") -- Clean up recovery flags for fresh session state management rawset(opts, "_session_recovery_attempted", nil) -- Mark this as a recovery attempt to preserve history context rawset(opts, "_is_session_recovery", true) -- Update UI state if available if opts.on_state_change then opts.on_state_change("generating") end -- CRITICAL: Ensure history messages are preserved in recovery Utils.info("Session recovery retry with " .. #(opts.history_messages or {}) .. " history messages") -- DEBUG: Log recovery history details local recovery_history = opts.history_messages or {} Utils.debug("Recovery history messages: " .. #recovery_history) for i, msg in ipairs(recovery_history) do if msg and msg.message then Utils.debug("Recovery msg " .. i .. ": role=" .. (msg.message.role or "unknown")) if msg.message.role == "assistant" then Utils.debug("Recovery assistant content: " .. tostring(msg.message.content):sub(1, 100)) end end end -- Retry with truncated history to rebuild context in new session M._stream_acp(opts) end) -- CRITICAL: Return immediately to prevent further processing in fast event context return end opts.on_stop({ reason = "error", error = err_ }) return end opts.on_stop({ reason = "complete" }) end) end ---@param opts AvanteLLMStreamOptions function M._stream(opts) -- Reset the cancellation flag at the start of a new request if LLMToolHelpers then LLMToolHelpers.is_cancelled = false end local acp_provider = Config.acp_providers[Config.provider] if acp_provider then return M._stream_acp(opts) end local provider = opts.provider or Providers[Config.provider] opts.session_ctx = opts.session_ctx or {} if not opts.session_ctx.on_messages_add then opts.session_ctx.on_messages_add = opts.on_messages_add end if not opts.session_ctx.on_state_change then opts.session_ctx.on_state_change = opts.on_state_change end if not opts.session_ctx.on_start then opts.session_ctx.on_start = opts.on_start end if not opts.session_ctx.on_chunk then opts.session_ctx.on_chunk = opts.on_chunk end if not opts.session_ctx.on_stop then opts.session_ctx.on_stop = opts.on_stop end if not opts.session_ctx.on_tool_log then opts.session_ctx.on_tool_log = opts.on_tool_log end if not opts.session_ctx.get_history_messages then opts.session_ctx.get_history_messages = opts.get_history_messages end ---@cast provider AvanteProviderFunctor local prompt_opts = M.generate_prompts(opts) if prompt_opts.pending_compaction_history_messages and #prompt_opts.pending_compaction_history_messages > 0 and opts.on_memory_summarize then opts.on_memory_summarize(prompt_opts.pending_compaction_history_messages) return end local resp_headers = {} local function dispatch_cancel_message() local cancelled_text = "\n*[Request cancelled by user.]*\n" if opts.on_chunk then opts.on_chunk(cancelled_text) end if opts.on_messages_add then local message = History.Message:new("assistant", cancelled_text, { just_for_display = true, }) opts.on_messages_add({ message }) end return opts.on_stop({ reason = "cancelled" }) end ---@type AvanteHandlerOptions local handler_opts = { on_messages_add = opts.on_messages_add, on_state_change = opts.on_state_change, update_tokens_usage = opts.update_tokens_usage, on_start = opts.on_start, on_chunk = opts.on_chunk, on_stop = function(stop_opts) if stop_opts.usage and opts.update_tokens_usage then opts.update_tokens_usage(stop_opts.usage) end ---@param tool_uses AvantePartialLLMToolUse[] ---@param tool_use_index integer ---@param tool_results AvanteLLMToolResult[] local function handle_next_tool_use( tool_uses, tool_use_messages, tool_use_index, tool_results, streaming_tool_use ) if tool_use_index > #tool_uses then ---@type avante.HistoryMessage[] local messages = {} for _, tool_result in ipairs(tool_results) do messages[#messages + 1] = History.Message:new("user", { type = "tool_result", tool_use_id = tool_result.tool_use_id, content = tool_result.content, is_error = tool_result.is_error, is_user_declined = tool_result.is_user_declined, }) end if opts.on_messages_add then opts.on_messages_add(messages) end local the_last_tool_use = tool_uses[#tool_uses] if the_last_tool_use and the_last_tool_use.name == "attempt_completion" then opts.on_stop({ reason = "complete" }) return end local new_opts = vim.tbl_deep_extend("force", opts, { history_messages = opts.get_history_messages and opts.get_history_messages() or {}, }) if provider.get_rate_limit_sleep_time then local sleep_time = provider:get_rate_limit_sleep_time(resp_headers) if sleep_time and sleep_time > 0 then Utils.info("Rate limit reached. Sleeping for " .. sleep_time .. " seconds ...") vim.defer_fn(function() M._stream(new_opts) end, sleep_time * 1000) return end end if not streaming_tool_use then M._stream(new_opts) end return end local partial_tool_use = tool_uses[tool_use_index] local partial_tool_use_message = tool_use_messages[tool_use_index] ---@param result string | nil ---@param error string | nil local function handle_tool_result(result, error) partial_tool_use_message.is_calling = false if opts.on_messages_add then opts.on_messages_add({ partial_tool_use_message }) end -- Special handling for cancellation signal from tools if error == LLMToolHelpers.CANCEL_TOKEN then Utils.debug("Tool execution was cancelled by user") local cancelled_text = "\n*[Request cancelled by user during tool execution.]*\n" if opts.on_chunk then opts.on_chunk(cancelled_text) end if opts.on_messages_add then local message = History.Message:new("assistant", cancelled_text, { just_for_display = true, }) opts.on_messages_add({ message }) end return opts.on_stop({ reason = "cancelled" }) end local is_user_declined = error and error:match("^User declined") local tool_result = { tool_use_id = partial_tool_use.id, content = error ~= nil and error or result, is_error = error ~= nil, -- Keep this as error to prevent processing as success is_user_declined = is_user_declined ~= nil, } table.insert(tool_results, tool_result) return handle_next_tool_use(tool_uses, tool_use_messages, tool_use_index + 1, tool_results) end local is_edit_tool_use = Utils.is_edit_tool_use(partial_tool_use) local support_streaming = false local llm_tool = vim.iter(prompt_opts.tools):find(function(tool) return tool.name == partial_tool_use.name end) if llm_tool then support_streaming = llm_tool.support_streaming == true end ---@type AvanteLLMToolFuncOpts local tool_use_opts = { session_ctx = opts.session_ctx, tool_use_id = partial_tool_use.id, streaming = partial_tool_use.state == "generating", on_complete = function() end, } if partial_tool_use.state == "generating" then if not is_edit_tool_use and not support_streaming then return end if type(partial_tool_use.input) == "table" then LLMTools.process_tool_use(prompt_opts.tools, partial_tool_use, tool_use_opts) end return end if streaming_tool_use then return end partial_tool_use_message.is_calling = true if opts.on_messages_add then opts.on_messages_add({ partial_tool_use_message }) end -- Either on_complete handles the tool result asynchronously or we receive the result and error synchronously when either is not nil local result, error = LLMTools.process_tool_use(prompt_opts.tools, partial_tool_use, { session_ctx = opts.session_ctx, on_log = opts.on_tool_log, set_tool_use_store = opts.set_tool_use_store, on_complete = handle_tool_result, tool_use_id = partial_tool_use.id, }) if result ~= nil or error ~= nil then return handle_tool_result(result, error) end end if stop_opts.reason == "cancelled" then dispatch_cancel_message() end local history_messages = opts.get_history_messages and opts.get_history_messages({ all = true }) or {} local pending_tools, pending_tool_use_messages = History.get_pending_tools(history_messages) if stop_opts.reason == "complete" and Config.mode == "agentic" then local completed_attempt_completion_tool_use = nil for idx = #history_messages, 1, -1 do local message = history_messages[idx] if message.is_user_submission then break end local use = History.Helpers.get_tool_use_data(message) if use and use.name == "attempt_completion" then completed_attempt_completion_tool_use = message break end end local unfinished_todos = {} if opts.get_todos then local todos = opts.get_todos() unfinished_todos = vim.tbl_filter( function(todo) return todo.status ~= "done" and todo.status ~= "cancelled" end, todos ) end local user_reminder_count = opts.session_ctx.user_reminder_count or 0 if not completed_attempt_completion_tool_use and opts.on_messages_add and (user_reminder_count < 3 or #unfinished_todos > 0) then opts.session_ctx.user_reminder_count = user_reminder_count + 1 Utils.debug("user reminder count", user_reminder_count) local message if #unfinished_todos > 0 then message = History.Message:new( "user", "<system-reminder>You should use tool calls to answer the question, for example, use write_todos if the task step is done or cancelled.</system-reminder>", { visible = false, } ) else message = History.Message:new( "user", "<system-reminder>You should use tool calls to answer the question, for example, use attempt_completion if the job is done.</system-reminder>", { visible = false, } ) end opts.on_messages_add({ message }) local new_opts = vim.tbl_deep_extend("force", opts, { history_messages = opts.get_history_messages(), }) if provider.get_rate_limit_sleep_time then local sleep_time = provider:get_rate_limit_sleep_time(resp_headers) if sleep_time and sleep_time > 0 then Utils.info("Rate limit reached. Sleeping for " .. sleep_time .. " seconds ...") vim.defer_fn(function() M._stream(new_opts) end, sleep_time * 1000) return end end M._stream(new_opts) return end end if stop_opts.reason == "tool_use" then opts.session_ctx.user_reminder_count = 0 return handle_next_tool_use(pending_tools, pending_tool_use_messages, 1, {}, stop_opts.streaming_tool_use) end if stop_opts.reason == "rate_limit" then local message = opts.on_messages_add and History.Message:new( "assistant", "", -- Actual content will be set below { just_for_display = true, } ) local retry_count = stop_opts.retry_after Utils.info("Rate limit reached. Retrying in " .. retry_count .. " seconds", { title = "Avante" }) local function countdown() if abort_retry_timer then Utils.info("Retry aborted due to user requested cancellation.") stop_retry_timer() dispatch_cancel_message() return end local msg_content = "*[Rate limit reached. Retrying in " .. retry_count .. " seconds ...]*" if opts.on_chunk then -- Use ANSI escape codes to clear line and move cursor up only for subsequent updates local prefix = "" if retry_count < stop_opts.retry_after then prefix = [[\033[1A\033[K]] end opts.on_chunk(prefix .. "\n" .. msg_content .. "\n") end if opts.on_messages_add and message then message:update_content("\n\n" .. msg_content) opts.on_messages_add({ message }) end if retry_count <= 0 then stop_retry_timer() Utils.info("Restarting stream after rate limit pause") M._stream(opts) else retry_count = retry_count - 1 end end stop_retry_timer() retry_timer = uv.new_timer() if retry_timer then retry_timer:start(0, 1000, vim.schedule_wrap(function() countdown() end)) end return end return opts.on_stop(stop_opts) end, } return M.curl({ provider = provider, prompt_opts = prompt_opts, handler_opts = handler_opts, on_response_headers = function(headers) resp_headers = headers end, }) end local function _merge_response(first_response, second_response, opts) local prompt = "\n" .. Config.dual_boost.prompt prompt = prompt :gsub("{{[%s]*provider1_output[%s]*}}", function() return first_response end) :gsub("{{[%s]*provider2_output[%s]*}}", function() return second_response end) prompt = prompt .. "\n" if opts.instructions == nil then opts.instructions = "" end -- append this reference prompt to the prompt_opts messages at last opts.instructions = opts.instructions .. prompt M._stream(opts) end local function _collector_process_responses(collector, opts) if not collector[1] or not collector[2] then Utils.error("One or both responses failed to complete") return end _merge_response(collector[1], collector[2], opts) end local function _collector_add_response(collector, index, response, opts) collector[index] = response collector.count = collector.count + 1 if collector.count == 2 then collector.timer:stop() _collector_process_responses(collector, opts) end end function M._dual_boost_stream(opts, Provider1, Provider2) Utils.debug("Starting Dual Boost Stream") local collector = { count = 0, responses = {}, timer = uv.new_timer(), timeout_ms = Config.dual_boost.timeout, } -- Setup timeout collector.timer:start( collector.timeout_ms, 0, vim.schedule_wrap(function() if collector.count < 2 then Utils.warn("Dual boost stream timeout reached") collector.timer:stop() -- Process whatever responses we have _collector_process_responses(collector, opts) end end) ) -- Create options for both streams local function create_stream_opts(index) local response = "" return vim.tbl_extend("force", opts, { on_chunk = function(chunk) if chunk then response = response .. chunk end end, on_stop = function(stop_opts) if stop_opts.error then Utils.error(string.format("Stream %d failed: %s", index, stop_opts.error)) return end Utils.debug(string.format("Response %d completed", index)) _collector_add_response(collector, index, response, opts) end, }) end -- Start both streams local success, err = xpcall(function() local opts1 = create_stream_opts(1) opts1.provider = Provider1 M._stream(opts1) local opts2 = create_stream_opts(2) opts2.provider = Provider2 M._stream(opts2) end, function(err) return err end) if not success then Utils.error("Failed to start dual_boost streams: " .. tostring(err)) end end ---@param opts AvanteLLMStreamOptions function M.stream(opts) local is_completed = false if opts.on_tool_log ~= nil then local original_on_tool_log = opts.on_tool_log opts.on_tool_log = vim.schedule_wrap(function(...) if not original_on_tool_log then return end return original_on_tool_log(...) end) end if opts.set_tool_use_store ~= nil then local original_set_tool_use_store = opts.set_tool_use_store opts.set_tool_use_store = vim.schedule_wrap(function(...) if not original_set_tool_use_store then return end return original_set_tool_use_store(...) end) end if opts.on_chunk ~= nil then local original_on_chunk = opts.on_chunk opts.on_chunk = vim.schedule_wrap(function(chunk) if is_completed then return end if original_on_chunk then return original_on_chunk(chunk) end end) end if opts.on_stop ~= nil then local original_on_stop = opts.on_stop opts.on_stop = vim.schedule_wrap(function(stop_opts) if is_completed then return end if stop_opts.reason == "complete" or stop_opts.reason == "error" or stop_opts.reason == "cancelled" then is_completed = true end return original_on_stop(stop_opts) end) end local valid_dual_boost_modes = { legacy = true, } opts.mode = opts.mode or Config.mode abort_retry_timer = false if Config.dual_boost.enabled and valid_dual_boost_modes[opts.mode] then M._dual_boost_stream( opts, Providers[Config.dual_boost.first_provider], Providers[Config.dual_boost.second_provider] ) else M._stream(opts) end end function M.cancel_inflight_request() if LLMToolHelpers.is_cancelled ~= nil then LLMToolHelpers.is_cancelled = true end if LLMToolHelpers.confirm_popup ~= nil then LLMToolHelpers.confirm_popup:cancel() LLMToolHelpers.confirm_popup = nil end abort_retry_timer = true api.nvim_exec_autocmds("User", { pattern = M.CANCEL_PATTERN }) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/attempt_completion.lua
Lua
local Base = require("avante.llm_tools.base") local Config = require("avante.config") local Highlights = require("avante.highlights") local Line = require("avante.ui.line") ---@alias AttemptCompletionInput {result: string, command?: string} ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "attempt_completion" M.description = [[ After each tool use, the user will respond with the result of that tool use, i.e. if it succeeded or failed, along with any reasons for failure. Once you've received the results of tool uses and can confirm that the task is complete, use this tool to present the result of your work to the user. Optionally you may provide a CLI command to showcase the result of your work. The user may respond with feedback if they are not satisfied with the result, which you can use to make improvements and try again. IMPORTANT NOTE: This tool CANNOT be used until you've confirmed from the user that any previous tool uses were successful. Failure to do so will result in code corruption and system failure. Before using this tool, you must ask yourself in `think` tool calling if you've confirmed from the user that any previous tool uses were successful. If not, then DO NOT use this tool. ]] M.support_streaming = true M.enabled = function() return Config.mode == "agentic" end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "result", description = "The result of the task. Formulate this result in a way that is final and does not require further input from the user. Don't end your result with questions or offers for further assistance.", type = "string", }, { name = "command", description = [[A CLI command to execute to show a live demo of the result to the user. For example, use \`open index.html\` to display a created html website, or \`open localhost:3000\` to display a locally running development server. But DO NOT use commands like \`echo\` or \`cat\` that merely print text. This command should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.]], type = "string", optional = true, }, }, usage = { result = "The result of the task. Formulate this result in a way that is final and does not require further input from the user. Don't end your result with questions or offers for further assistance.", command = "A CLI command to execute to show a live demo of the result to the user. For example, use `open index.html` to display a created html website, or `open localhost:3000` to display a locally running development server. But DO NOT use commands like `echo` or `cat` that merely print text. This command should be valid for the current operating system. Ensure the command is properly formatted and does not contain any harmful instructions.", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "Whether the task was completed successfully", type = "boolean", }, { name = "error", description = "Error message if the file was not read successfully", type = "string", optional = true, }, } ---@type avante.LLMToolOnRender<AttemptCompletionInput> function M.on_render(input) local lines = {} table.insert(lines, Line:new({ { "✓ Task Completed", Highlights.AVANTE_TASK_COMPLETED } })) table.insert(lines, Line:new({ { "" } })) local result = input.result or "" local text_lines = vim.split(result, "\n") for _, text_line in ipairs(text_lines) do table.insert(lines, Line:new({ { text_line } })) end return lines end ---@type AvanteLLMToolFunc<AttemptCompletionInput> function M.func(input, opts) if not opts.on_complete then return false, "on_complete not provided" end local sidebar = require("avante").get() if not sidebar then return false, "Avante sidebar not found" end local is_streaming = opts.streaming or false if is_streaming then -- wait for stream completion as command may not be complete yet return end opts.session_ctx.attempt_completion_is_called = true if input.command and input.command ~= vim.NIL and input.command ~= "" and not vim.startswith(input.command, "open ") then opts.session_ctx.always_yes = false require("avante.llm_tools.bash").func({ command = input.command }, opts) else opts.on_complete(true, nil) end end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/base.lua
Lua
local M = {} function M:__call(opts, on_log, on_complete) return self.func(opts, on_log, on_complete) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/bash.lua
Lua
local Path = require("plenary.path") local Utils = require("avante.utils") local Helpers = require("avante.llm_tools.helpers") local Base = require("avante.llm_tools.base") local Config = require("avante.config") local Providers = require("avante.providers") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "bash" local banned_commands = { "alias", "curl", "curlie", "wget", "axel", "aria2c", "nc", "telnet", "lynx", "w3m", "links", "httpie", "xh", "http-prompt", "chrome", "firefox", "safari", } M.get_description = function() local provider = Providers[Config.provider] if Config.provider:match("copilot") and provider.model and provider.model:match("gpt") then return [[Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures. Do not use bash command to read or modify files, or you will be fired!]] end local res = ([[Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures. Do not use bash command to read or modify files, or you will be fired! Before executing the command, please follow these steps: 1. Directory Verification: - If the command will create new directories or files, first use the LS tool to verify the parent directory exists and is the correct location - For example, before running "mkdir foo/bar", first use LS to check that "foo" exists and is the intended parent directory 2. Security Check: - For security and to limit the threat of a prompt injection attack, some commands are limited or banned. If you use a disallowed command, you will receive an error message explaining the restriction. Explain the error to the User. - Verify that the command is not one of the banned commands: ${BANNED_COMMANDS}. 3. Command Execution: - After ensuring proper quoting, execute the command. - Capture the output of the command. 4. Output Processing: - If the output exceeds ${MAX_OUTPUT_LENGTH} characters, output will be truncated before being returned to you. - Prepare the output for display to the user. 5. Return Result: - Provide the processed output of the command. - If any errors occurred during execution, include those in the output. Usage notes: - The command argument is required. - You can specify an optional timeout in milliseconds (up to 600000ms / 10 minutes). If not specified, commands will timeout after 30 minutes. - VERY IMPORTANT: You MUST avoid using search commands like \`find\` and \`grep\`. Instead use ${GrepTool.name}, ${GlobTool.name}, or ${AgentTool.name} to search. You MUST avoid read tools like \`cat\`, \`head\`, \`tail\`, and \`ls\`, and use ${FileReadTool.name} and ${LSTool.name} to read files. - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings). - IMPORTANT: All commands share the same shell session. Shell state (environment variables, virtual environments, current directory, etc.) persist between commands. For example, if you set an environment variable as part of a command, the environment variable will persist for subsequent commands. - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of \`cd\`. You may use \`cd\` if the User explicitly requests it. <good-example> pytest /foo/bar/tests </good-example> <bad-example> cd /foo/bar && pytest tests </bad-example> # Committing changes with git When the user asks you to create a new git commit, follow these steps carefully: 1. Start with a single message that contains exactly three tool_use blocks that do the following (it is VERY IMPORTANT that you send these tool_use blocks in a single message, otherwise it will feel slow to the user!): - Run a git status command to see all untracked files. - Run a git diff command to see both staged and unstaged changes that will be committed. - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style. 2. Use the git context at the start of this conversation to determine which files are relevant to your commit. Add relevant untracked files to the staging area. Do not commit files that were already modified at the start of this conversation, if they are not relevant to your commit. 3. Analyze all staged changes (both previously staged and newly added) and draft a commit message. Wrap your analysis process in <commit_analysis> tags: <commit_analysis> - List the files that have been changed or added - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.) - Brainstorm the purpose or motivation behind these changes - Do not use tools to explore code, beyond what is available in the git context - Assess the impact of these changes on the overall project - Check for any sensitive information that shouldn't be committed - Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what" - Ensure your language is clear, concise, and to the point - Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.) - Ensure the message is not generic (avoid words like "Update" or "Fix" without context) - Review the draft message to ensure it accurately reflects the changes and their purpose </commit_analysis> - In order to ensure good formatting, ALWAYS pass the commit message via a HEREDOC, a la this example: <example> git commit -m "$(cat <<'EOF' Commit message here. EOF )" </example> 5. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them. 6. Finally, run git status to make sure the commit succeeded. Important notes: - When possible, combine the "git add" and "git commit" commands into a single "git commit -am" command, to speed things up - However, be careful not to stage files (e.g. with \`git add .\`) for commits that aren't part of the change, they may have untracked files they want to keep around, but not commit. - NEVER update the git config - DO NOT push to the remote repository - IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported. - If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit - Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them. - Return an empty response - the user will see the git output directly # Creating pull requests Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed. IMPORTANT: When the user asks you to create a pull request, follow these steps carefully: 1. Understand the current state of the branch. Remember to send a single message that contains multiple tool_use blocks (it is VERY IMPORTANT that you do this in a single message, otherwise it will feel slow to the user!): - Run a git status command to see all untracked files. - Run a git diff command to see both staged and unstaged changes that will be committed. - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote - Run a git log command and \`git diff main...HEAD\` to understand the full commit history for the current branch (from the time it diverged from the \`main\` branch.) 2. Create new branch if needed 3. Commit changes if needed 4. Push to remote with -u flag if needed 5. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (not just the latest commit, but all commits that will be included in the pull request!), and draft a pull request summary. Wrap your analysis process in <pr_analysis> tags: <pr_analysis> - List the commits since diverging from the main branch - Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.) - Brainstorm the purpose or motivation behind these changes - Assess the impact of these changes on the overall project - Do not use tools to explore code, beyond what is available in the git context - Check for any sensitive information that shouldn't be committed - Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what" - Ensure the summary accurately reflects all changes since diverging from the main branch - Ensure your language is clear, concise, and to the point - Ensure the summary accurately reflects the changes and their purpose (ie. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.) - Ensure the summary is not generic (avoid words like "Update" or "Fix" without context) - Review the draft summary to ensure it accurately reflects the changes and their purpose </pr_analysis> 6. Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting. <example> gh pr create --title "the pr title" --body "$(cat <<'EOF' ## Summary <1-3 bullet points> ## Test plan [Checklist of TODOs for testing the pull request...] EOF )" </example> Important: - Return an empty response - the user will see the gh output directly - Never update git config]]):gsub("${BANNED_COMMANDS}", table.concat(banned_commands, ", ")) return res end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "Relative path to the project directory, as cwd", type = "string", }, { name = "command", description = "Command to run", type = "string", }, }, usage = { path = "Relative path to the project directory, as cwd", command = "Command to run", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "stdout", description = "Output of the command", type = "string", }, { name = "error", description = "Error message if the command was not run successfully", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, command: string }> function M.func(input, opts) local is_streaming = opts.streaming or false if is_streaming then -- wait for stream completion as command may not be complete yet return end local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return false, "Path not found: " .. abs_path end if not input.command then return false, "Command is required" end if opts.on_log then opts.on_log("command: " .. input.command) end ---change cwd to abs_path ---@param output string ---@param exit_code integer ---@return string | boolean | nil result ---@return string | nil error local function handle_result(output, exit_code) if exit_code ~= 0 then if output then return false, "Error: " .. output .. "; Error code: " .. tostring(exit_code) end return false, "Error code: " .. tostring(exit_code) end return output, nil end if not opts.on_complete then return false, "on_complete not provided" end Helpers.confirm( "Are you sure you want to run the command: `" .. input.command .. "` in the directory: " .. abs_path, function(ok, reason) if not ok then opts.on_complete(false, "User declined, reason: " .. (reason and reason or "unknown")) return end Utils.shell_run_async(input.command, "bash -c", function(output, exit_code) local result, err = handle_result(output, exit_code) opts.on_complete(result, err) end, abs_path, 1000 * 60 * 2) end, { focus = true }, opts.session_ctx, M.name -- Pass the tool name for permission checking ) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/create.lua
Lua
local Path = require("plenary.path") local Utils = require("avante.utils") local Base = require("avante.llm_tools.base") local Helpers = require("avante.llm_tools.helpers") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "create" M.description = "The create tool allows you to create a new file with specified content." function M.enabled() return require("avante.config").mode == "agentic" and not require("avante.config").behaviour.enable_fastapply end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "The path where the new file should be created", type = "string", }, { name = "file_text", description = "The content to write to the new file", type = "string", }, }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "Whether the file was created successfully", type = "boolean", }, { name = "error", description = "Error message if the file was not created successfully", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, file_text: string }> function M.func(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local session_ctx = opts.session_ctx if not on_complete then return false, "on_complete not provided" end if on_log then on_log("path: " .. input.path) end if Helpers.already_in_context(input.path) then on_complete(nil, "Ooooops! This file is already in the context! Why you are trying to create it again?") return end local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if input.file_text == nil then return false, "file_text not provided" end if Path:new(abs_path):exists() then return false, "File already exists: " .. abs_path end local lines = vim.split(input.file_text, "\n") if #lines == 1 and input.file_text:match("\\n") then local text = Utils.trim_escapes(input.file_text) lines = vim.split(text, "\n") end local bufnr, err = Helpers.get_bufnr(abs_path) if err then return false, err end vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines) Helpers.confirm("Are you sure you want to create this file?", function(ok, reason) if not ok then -- close the buffer vim.api.nvim_buf_delete(bufnr, { force = true }) on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end -- save the file Path:new(abs_path):parent():mkdir({ parents = true, exists_ok = true }) local current_winid = vim.api.nvim_get_current_win() local winid = Utils.get_winid(bufnr) vim.api.nvim_set_current_win(winid) vim.cmd("noautocmd write") vim.api.nvim_set_current_win(current_winid) on_complete(true, nil) end, { focus = true }, session_ctx, M.name) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/delete_tool_use_messages.lua
Lua
local Base = require("avante.llm_tools.base") local History = require("avante.history") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "delete_tool_use_messages" M.description = "Since many tool use messages are useless for completing subsequent tasks and may cause excessive token consumption or even prevent task completion, you need to decide whether to invoke this tool to delete the useless tool use messages." ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "tool_use_id", description = "The tool use id", type = "string", }, }, usage = { tool_use_id = "The tool use id", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "True if the deletion was successful, false otherwise", type = "boolean", }, { name = "error", description = "Error message", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ tool_use_id: string }> function M.func(input, opts) local sidebar = require("avante").get() if not sidebar then return false, "Avante sidebar not found" end local history_messages = History.get_history_messages(sidebar.chat_history) local the_deleted_message_uuids = {} for _, msg in ipairs(history_messages) do local use = History.Helpers.get_tool_use_data(msg) if use then if use.id == input.tool_use_id then table.insert(the_deleted_message_uuids, msg.uuid) end goto continue end local result = History.Helpers.get_tool_result_data(msg) if result then if result.tool_use_id == input.tool_use_id then table.insert(the_deleted_message_uuids, msg.uuid) end end ::continue:: end sidebar:delete_history_messages(the_deleted_message_uuids) return true, nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/dispatch_agent.lua
Lua
local Providers = require("avante.providers") local Config = require("avante.config") local Utils = require("avante.utils") local Base = require("avante.llm_tools.base") local History = require("avante.history") local Line = require("avante.ui.line") local Highlights = require("avante.highlights") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "dispatch_agent" M.get_description = function() local provider = Providers[Config.provider] if Config.provider:match("copilot") and provider.model and provider.model:match("gpt") then return [[Launch a new agent that has access to the following tools: `glob`, `grep`, `ls`, `view`, `attempt_completion`. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you.]] end return [[Launch a new agent that has access to the following tools: `glob`, `grep`, `ls`, `view`, `attempt_completion`. When you are searching for a keyword or file and are not confident that you will find the right match on the first try, use the Agent tool to perform the search for you. For example: - If you are searching for a keyword like "config" or "logger", the Agent tool is appropriate - If you want to read a specific file path, use the `view` or `glob` tool instead of the `dispatch_agent` tool, to find the match more quickly - If you are searching for a specific class definition like "class Foo", use the `glob` tool instead, to find the match more quickly RULES: - Do not ask for more information than necessary. Use the tools provided to accomplish the user's request efficiently and effectively. When you've completed your task, you must use the attempt_completion tool to present the result to the user. The user may provide feedback, which you can use to make improvements and try again. - NEVER end attempt_completion result with a question or request to engage in further conversation! Formulate the end of your result in a way that is final and does not require further input from the user. OBJECTIVE: 1. Analyze the user's task and set clear, achievable goals to accomplish it. Prioritize these goals in a logical order. 2. Work through these goals sequentially, utilizing available tools one at a time as necessary. Each goal should correspond to a distinct step in your problem-solving process. You will be informed on the work completed and what's remaining as you go. 3. Once you've completed the user's task, you must use the attempt_completion tool to present the result of the task to the user. You may also provide a CLI command to showcase the result of your task; this can be particularly useful for web development tasks, where you can run e.g. \`open index.html\` to show the website you've built. Usage notes: 1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses 2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result. 3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you. 4. The agent's outputs should generally be trusted 5. IMPORTANT: The agent can not use `bash`, `write`, `str_replace`, so can not modify files. If you want to use these tools, use them directly instead of going through the agent.]] end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "prompt", description = "The task for the agent to perform", type = "string", }, }, required = { "prompt" }, usage = { prompt = "The task for the agent to perform", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "result", description = "The result of the agent", type = "string", }, { name = "error", description = "The error message if the agent fails", type = "string", optional = true, }, } local function get_available_tools() return { require("avante.llm_tools.ls"), require("avante.llm_tools.grep"), require("avante.llm_tools.glob"), require("avante.llm_tools.view"), require("avante.llm_tools.attempt_completion"), } end ---@class avante.DispatchAgentInput ---@field prompt string ---@type avante.LLMToolOnRender<avante.DispatchAgentInput> function M.on_render(input, opts) local result_message = opts.result_message local store = opts.store or {} local messages = store.messages or {} local tool_use_summary = {} for _, msg in ipairs(messages) do local summary local tool_use = History.Helpers.get_tool_use_data(msg) if tool_use then local tool_result = History.Helpers.get_tool_result(tool_use.id, messages) if tool_result then if tool_use.name == "ls" then local path = tool_use.input.path if tool_result.is_error then summary = string.format("Ls %s: failed", path) else local ok, filepaths = pcall(vim.json.decode, tool_result.content) if ok then summary = string.format("Ls %s: %d paths", path, #filepaths) end end elseif tool_use.name == "grep" then local path = tool_use.input.path local query = tool_use.input.query if tool_result.is_error then summary = string.format("Grep %s in %s: failed", query, path) else local ok, filepaths = pcall(vim.json.decode, tool_result.content) if ok then summary = string.format("Grep %s in %s: %d paths", query, path, #filepaths) end end elseif tool_use.name == "glob" then local path = tool_use.input.path local pattern = tool_use.input.pattern if tool_result.is_error then summary = string.format("Glob %s in %s: failed", pattern, path) else local ok, result = pcall(vim.json.decode, tool_result.content) if ok then local matches = result.matches if matches then summary = string.format("Glob %s in %s: %d matches", pattern, path, #matches) end end end elseif tool_use.name == "view" then local path = tool_use.input.path if tool_result.is_error then summary = string.format("View %s: failed", path) else local ok, result = pcall(vim.json.decode, tool_result.content) if ok and type(result) == "table" and type(result.content) == "string" then local lines = vim.split(result.content, "\n") summary = string.format("View %s: %d lines", path, #lines) end end end end if summary then summary = " " .. Utils.icon("🛠️ ") .. summary end else summary = History.Helpers.get_text_data(msg) end if summary then table.insert(tool_use_summary, summary) end end local state = "running" local icon = Utils.icon("🔄 ") local hl = Highlights.AVANTE_TASK_RUNNING if result_message then local result = History.Helpers.get_tool_result_data(result_message) if result then if result.is_error then state = "failed" icon = Utils.icon("❌ ") hl = Highlights.AVANTE_TASK_FAILED else state = "completed" icon = Utils.icon("✅ ") hl = Highlights.AVANTE_TASK_COMPLETED end end end local lines = {} table.insert(lines, Line:new({ { icon .. "Subtask " .. state, hl } })) table.insert(lines, Line:new({ { "" } })) table.insert(lines, Line:new({ { " Task:" } })) local prompt_lines = vim.split(input.prompt or "", "\n") for _, line in ipairs(prompt_lines) do table.insert(lines, Line:new({ { " " .. line } })) end table.insert(lines, Line:new({ { "" } })) table.insert(lines, Line:new({ { " Task summary:" } })) for _, summary in ipairs(tool_use_summary) do local summary_lines = vim.split(summary, "\n") for _, line in ipairs(summary_lines) do table.insert(lines, Line:new({ { " " .. line } })) end end return lines end ---@type AvanteLLMToolFunc<avante.DispatchAgentInput> function M.func(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local session_ctx = opts.session_ctx local Llm = require("avante.llm") if not on_complete then return false, "on_complete not provided" end local prompt = input.prompt local tools = get_available_tools() local start_time = Utils.get_timestamp() if on_log then on_log("prompt: " .. prompt) end local system_prompt = ([[You are a helpful assistant with access to various tools. Your task is to help the user with their request: "${prompt}" Be thorough and use the tools available to you to find the most relevant information. When you're done, provide a clear and concise summary of what you found.]]):gsub("${prompt}", prompt) local history_messages = {} local tool_use_messages = {} local total_tokens = 0 local result = "" ---@type avante.AgentLoopOptions local agent_loop_options = { system_prompt = system_prompt, user_input = "start", tools = tools, on_tool_log = session_ctx.on_tool_log, on_messages_add = function(msgs) msgs = vim.islist(msgs) and msgs or { msgs } for _, msg in ipairs(msgs) do local idx = nil for i, m in ipairs(history_messages) do if m.uuid == msg.uuid then idx = i break end end if idx ~= nil then history_messages[idx] = msg else table.insert(history_messages, msg) end end if opts.set_store then opts.set_store("messages", history_messages) end for _, msg in ipairs(msgs) do local tool_use = History.Helpers.get_tool_use_data(msg) if tool_use then tool_use_messages[msg.uuid] = true if tool_use.name == "attempt_completion" and tool_use.input and tool_use.input.result then result = tool_use.input.result end end end end, session_ctx = session_ctx, on_start = session_ctx.on_start, on_chunk = function(chunk) if not chunk then return end total_tokens = total_tokens + (#vim.split(chunk, " ") * 1.3) end, on_complete = function(err) if err ~= nil then err = string.format("dispatch_agent failed: %s", vim.inspect(err)) on_complete(err, nil) return end local end_time = Utils.get_timestamp() local elapsed_time = Utils.datetime_diff(start_time, end_time) local tool_use_count = vim.tbl_count(tool_use_messages) local summary = "dispatch_agent Done (" .. (tool_use_count <= 1 and "1 tool use" or tool_use_count .. " tool uses") .. " · " .. math.ceil(total_tokens) .. " tokens · " .. elapsed_time .. "s)" if session_ctx.on_messages_add then local message = History.Message:new("assistant", "\n\n" .. summary, { just_for_display = true, }) session_ctx.on_messages_add({ message }) end on_complete(result, nil) end, } Llm.agent_loop(agent_loop_options) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/edit_file.lua
Lua
local Base = require("avante.llm_tools.base") local Providers = require("avante.providers") local Utils = require("avante.utils") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "edit_file" M.enabled = function() return require("avante.config").mode == "agentic" and require("avante.config").behaviour.enable_fastapply end M.description = "Use this tool to propose an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\nWhen writing the edit, you should specify each edit in sequence, with the special comment // ... existing code ... to represent unchanged code in between edited lines.\n\nFor example:\n\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\nDO NOT omit spans of pre-existing code (or comments) without using the // ... existing code ... comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\nIf you plan on deleting a section, you must provide context before and after to delete it. If the initial code is ```code \\n Block 1 \\n Block 2 \\n Block 3 \\n code```, and you want to remove Block 2, you would output ```// ... existing code ... \\n Block 1 \\n Block 3 \\n // ... existing code ...```.\nMake sure it is clear what the edit should be, and where it should be applied.\nALWAYS make all edits to a file in a single edit_file instead of multiple edit_file calls to the same file. The apply model can handle many distinct edits at once." ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "The target file path to modify.", type = "string", }, { name = "instructions", type = "string", description = "A single sentence instruction describing what you are going to do for the sketched edit. This is used to assist the less intelligent model in applying the edit. Use the first person to describe what you are going to do. Use it to disambiguate uncertainty in the edit.", }, { name = "code_edit", type = "string", description = "Specify ONLY the precise lines of code that you wish to edit. NEVER specify or write out unchanged code. Instead, represent all unchanged code using the comment of the language you're editing in - example: // ... existing code ...", }, }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "Whether the file was edited successfully", type = "boolean", }, { name = "error", description = "Error message if the file could not be edited", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, instructions: string, code_edit: string }> M.func = vim.schedule_wrap(function(input, opts) if opts.streaming then return false, "streaming not supported" end if not input.path then return false, "path not provided" end if not input.instructions then input.instructions = "" end if not input.code_edit then return false, "code_edit not provided" end local on_complete = opts.on_complete if not on_complete then return false, "on_complete not provided" end local provider = Providers["morph"] if not provider then return false, "morph provider not found" end if not provider.is_env_set() then return false, "morph provider not set" end if not input.path then return false, "path not provided" end --- if input.path is a directory, return false if vim.fn.isdirectory(input.path) == 1 then return false, "path is a directory" end local ok, lines = pcall(Utils.read_file_from_buf_or_disk, input.path) if not ok then local f = io.open(input.path, "r") if f then local original_code = f:read("*all") f:close() lines = vim.split(original_code, "\n") end end if lines and #lines > 0 then if lines[#lines] == "" then lines = vim.list_slice(lines, 0, #lines - 1) end end local original_code = table.concat(lines or {}, "\n") local provider_conf = Providers.parse_config(provider) local body = { model = provider_conf.model, messages = { { role = "user", content = "<instructions>" .. input.instructions .. "</instructions>\n<code>" .. original_code .. "</code>\n<update>" .. input.code_edit .. "</update>", }, }, } local temp_file = vim.fn.tempname() local curl_body_file = temp_file .. "-request-body.json" local json_content = vim.json.encode(body) vim.fn.writefile(vim.split(json_content, "\n"), curl_body_file) -- Construct curl command with additional debugging and error handling local curl_cmd = { "curl", "-X", "POST", "-H", "Content-Type: application/json", "-d", "@" .. curl_body_file, "--fail", -- Return error for HTTP status codes >= 400 "--show-error", -- Show error messages "--verbose", -- Enable verbose output for better debugging "--connect-timeout", "30", -- Connection timeout in seconds "--max-time", "120", -- Maximum operation time Utils.url_join(provider_conf.endpoint, "/chat/completions"), } -- Add authorization header if available if Providers.env.require_api_key(provider_conf) then local api_key = provider.parse_api_key() table.insert(curl_cmd, 4, "-H") table.insert(curl_cmd, 5, "Authorization: Bearer " .. api_key) end vim.system( curl_cmd, { text = true, }, vim.schedule_wrap(function(result) -- Clean up temporary file vim.fn.delete(curl_body_file) if result.code ~= 0 then local error_msg = result.stderr if not error_msg or error_msg == "" then error_msg = result.stdout end if not error_msg or error_msg == "" then error_msg = "No detailed error message available" end -- 检查curl常见的错误码 local curl_error_map = { [1] = "Unsupported protocol (curl error 1)", [2] = "Failed to initialize (curl error 2)", [3] = "URL malformed (curl error 3)", [4] = "Requested FTP action not supported (curl error 4)", [5] = "Failed to resolve proxy (curl error 5)", [6] = "Could not resolve host (DNS resolution failed)", [7] = "Failed to connect to host (connection refused)", [28] = "Operation timeout (connection timed out)", [35] = "SSL connection error (handshake failed)", [52] = "Empty reply from server", [56] = "Failure in receiving network data", [60] = "SSL certificate problem (certificate verification failed)", [77] = "Problem with reading SSL CA certificate", } local curl_cmd_str = table.concat(curl_cmd, " ") local error_hint = curl_error_map[result.code] or ("curl exited with code " .. result.code) local full_error = "curl command failed: " .. error_hint .. "\n" .. "Command: " .. curl_cmd_str .. "\n" .. "Exit code: " .. result.code if error_msg and error_msg ~= "" then full_error = full_error .. "\nError details: " .. error_msg end if provider_conf.endpoint and provider_conf.model then full_error = full_error .. "\nEndpoint: " .. provider_conf.endpoint .. "/chat/completions" .. "\nModel: " .. provider_conf.model end on_complete(false, full_error) return end local response_body = result.stdout or "" if response_body == "" then on_complete(false, "Empty response from server") return end local ok_, jsn = pcall(vim.json.decode, response_body) if not ok_ then on_complete(false, "Failed to parse JSON response: " .. response_body) return end if jsn.error then if type(jsn.error) == "table" and jsn.error.message then on_complete(false, jsn.error.message or vim.inspect(jsn.error)) else on_complete(false, vim.inspect(jsn.error)) end return end if not jsn.choices or not jsn.choices[1] or not jsn.choices[1].message then on_complete(false, "Invalid response format") return end local str_replace = require("avante.llm_tools.str_replace") local new_input = { path = input.path, old_str = original_code, new_str = jsn.choices[1].message.content, } str_replace.func(new_input, opts) end) ) end) return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/get_diagnostics.lua
Lua
local Base = require("avante.llm_tools.base") local Helpers = require("avante.llm_tools.helpers") local Utils = require("avante.utils") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "get_diagnostics" M.description = "Get diagnostics from a specific file" ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "The path to the file in the current project scope", type = "string", }, }, usage = { path = "The path to the file in the current project scope", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "diagnostics", description = "The diagnostics for the file", type = "string", }, { name = "error", description = "Error message if the replacement failed", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, diff: string }> function M.func(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete if not input.path then return false, "pathf are required" end if on_log then on_log("path: " .. input.path) end local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if not on_complete then return false, "on_complete is required" end local diagnostics = Utils.lsp.get_diagnostics_from_filepath(abs_path) local jsn_str = vim.json.encode(diagnostics) on_complete(jsn_str, nil) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/glob.lua
Lua
local Helpers = require("avante.llm_tools.helpers") local Base = require("avante.llm_tools.base") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "glob" M.description = 'Fast file pattern matching using glob patterns like "**/*.js", in current project scope' ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "pattern", description = "Glob pattern", type = "string", }, { name = "path", description = "Relative path to the project directory, as cwd", type = "string", }, }, usage = { pattern = "Glob pattern", path = "Relative path to the project directory, as cwd", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "matches", description = "List of matched files", type = "string", }, { name = "err", description = "Error message", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, pattern: string }> function M.func(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return "", "No permission to access path: " .. abs_path end if on_log then on_log("path: " .. abs_path) end if on_log then on_log("pattern: " .. input.pattern) end local files = vim.fn.glob(abs_path .. "/" .. input.pattern, true, true) local truncated_files = {} local is_truncated = false local size = 0 for _, file in ipairs(files) do size = size + #file if size > 1024 * 10 then is_truncated = true break end table.insert(truncated_files, file) end local result = vim.json.encode({ matches = truncated_files, is_truncated = is_truncated, }) if not on_complete then return result, nil end on_complete(result, nil) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/grep.lua
Lua
local Path = require("plenary.path") local Utils = require("avante.utils") local Helpers = require("avante.llm_tools.helpers") local Base = require("avante.llm_tools.base") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "grep" M.description = "Search for a keyword in a directory using grep in current project scope" ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "Relative path to the project directory", type = "string", }, { name = "query", description = "Query to search for", type = "string", }, { name = "case_sensitive", description = "Whether to search case sensitively", type = "boolean", default = false, optional = true, }, { name = "include_pattern", description = "Glob pattern to include files", type = "string", optional = true, }, { name = "exclude_pattern", description = "Glob pattern to exclude files", type = "string", optional = true, }, }, usage = { path = "Relative path to the project directory", query = "Query to search for", case_sensitive = "Whether to search case sensitively", include_pattern = "Glob pattern to include files", exclude_pattern = "Glob pattern to exclude files", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "files", description = "List of files that match the keyword", type = "string", }, { name = "error", description = "Error message if the directory was not searched successfully", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, query: string, case_sensitive?: boolean, include_pattern?: string, exclude_pattern?: string }> function M.func(input, opts) local on_log = opts.on_log local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return "", "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return "", "No such file or directory: " .. abs_path end ---check if any search cmd is available local search_cmd = vim.fn.exepath("rg") if search_cmd == "" then search_cmd = vim.fn.exepath("ag") end if search_cmd == "" then search_cmd = vim.fn.exepath("ack") end if search_cmd == "" then search_cmd = vim.fn.exepath("grep") end if search_cmd == "" then return "", "No search command found" end ---execute the search command local cmd = {} if search_cmd:find("rg") then cmd = { search_cmd, "--files-with-matches", "--hidden" } if input.case_sensitive then table.insert(cmd, "--case-sensitive") else table.insert(cmd, "--ignore-case") end if input.include_pattern then table.insert(cmd, "--glob") table.insert(cmd, input.include_pattern) end if input.exclude_pattern then table.insert(cmd, "--glob") table.insert(cmd, "!" .. input.exclude_pattern) end table.insert(cmd, input.query) table.insert(cmd, abs_path) elseif search_cmd:find("ag") then cmd = { search_cmd, "--nocolor", "--nogroup", "--hidden" } if input.case_sensitive then table.insert(cmd, "--case-sensitive") end if input.include_pattern then table.insert(cmd, "--ignore") table.insert(cmd, "!" .. input.include_pattern) end if input.exclude_pattern then table.insert(cmd, "--ignore") table.insert(cmd, input.exclude_pattern) end table.insert(cmd, input.query) table.insert(cmd, abs_path) elseif search_cmd:find("ack") then cmd = { search_cmd, "--nocolor", "--nogroup", "--hidden" } if input.case_sensitive then table.insert(cmd, "--smart-case") end if input.exclude_pattern then table.insert(cmd, "--ignore-dir") table.insert(cmd, input.exclude_pattern) end table.insert(cmd, input.query) table.insert(cmd, abs_path) elseif search_cmd:find("grep") then local files = vim.system({ "git", "-C", abs_path, "ls-files", "-co", "--exclude-standard" }, { text = true }):wait().stdout cmd = { "grep", "-rH" } if not input.case_sensitive then table.insert(cmd, "-i") end if input.include_pattern then table.insert(cmd, "--include") table.insert(cmd, input.include_pattern) end if input.exclude_pattern then table.insert(cmd, "--exclude") table.insert(cmd, input.exclude_pattern) end table.insert(cmd, input.query) if files ~= "" then for _, path in ipairs(vim.split(files, "\n")) do if not path:match("^%s*$") then table.insert(cmd, vim.fs.joinpath(abs_path, path)) end end else table.insert(cmd, abs_path) end end Utils.debug("cmd", table.concat(cmd, " ")) if on_log then on_log("Running command: " .. table.concat(cmd, " ")) end local result = vim.system(cmd, { text = true }):wait().stdout or "" local filepaths = vim.split(result, "\n") return vim.json.encode(filepaths), nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/helpers.lua
Lua
local Utils = require("avante.utils") local Path = require("plenary.path") local Config = require("avante.config") local ACPConfirmAdapter = require("avante.ui.acp_confirm_adapter") local M = {} M.CANCEL_TOKEN = "__CANCELLED__" -- Track cancellation state M.is_cancelled = false ---@type avante.ui.Confirm M.confirm_popup = nil ---@param rel_path string ---@return string function M.get_abs_path(rel_path) local project_root = Utils.get_project_root() local p = Utils.join_paths(project_root, rel_path) if p:sub(-2) == "/." then p = p:sub(1, -3) end return p end ---@type avante.acp.PermissionOption[] local default_permission_options = { { optionId = "allow_always", name = "Allow Always", kind = "allow_always" }, { optionId = "allow_once", name = "Allow", kind = "allow_once" }, { optionId = "reject_once", name = "Reject", kind = "reject_once" }, } ---@param callback fun(option_id: string) ---@param confirm_opts avante.ui.ConfirmOptions function M.confirm_inline(callback, confirm_opts) local sidebar = require("avante").get() local items = ACPConfirmAdapter.generate_buttons_for_acp_options(confirm_opts.permission_options or default_permission_options) sidebar.permission_button_options = items sidebar.permission_handler = function(id) callback(id) sidebar.scroll = true sidebar.permission_button_options = nil sidebar.permission_handler = nil sidebar._history_cache_invalidated = true sidebar:update_content("") end end ---@param message string ---@param callback fun(response: boolean, reason?: string) ---@param confirm_opts? avante.ui.ConfirmOptions ---@param session_ctx? table ---@param tool_name? string -- Optional tool name to check against tool_permissions config ---@return avante.ui.Confirm | nil function M.confirm(message, callback, confirm_opts, session_ctx, tool_name) callback = vim.schedule_wrap(callback) if session_ctx and session_ctx.always_yes then callback(true) return end -- Check behaviour.auto_approve_tool_permissions config for auto-approval local auto_approve = Config.behaviour.auto_approve_tool_permissions -- If auto_approve is true, auto-approve all tools if auto_approve == true then callback(true) return end -- If auto_approve is a table (array of tool names), check if this tool is in the list if type(auto_approve) == "table" and vim.tbl_contains(auto_approve, tool_name) then callback(true) return end if Config.behaviour.confirmation_ui_style == "inline_buttons" then M.confirm_inline(function(option_id) if option_id == "allow" or option_id == "allow_once" or option_id == "allow_always" then if option_id == "allow_always" and session_ctx then session_ctx.always_yes = true end callback(true) else callback(false, option_id) end end, confirm_opts or {}) return end local Confirm = require("avante.ui.confirm") local sidebar = require("avante").get() if not sidebar or not sidebar.containers.input or not sidebar.containers.input.winid then Utils.error("Avante sidebar not found", { title = "Avante" }) callback(false) return end confirm_opts = vim.tbl_deep_extend("force", { container_winid = sidebar.containers.input.winid }, confirm_opts or {}) if M.confirm_popup then M.confirm_popup:close() end M.confirm_popup = Confirm:new(message, function(type, reason) if type == "yes" then callback(true) elseif type == "all" then if session_ctx then session_ctx.always_yes = true end callback(true) elseif type == "no" then callback(false, reason) end M.confirm_popup = nil end, confirm_opts) M.confirm_popup:open() return M.confirm_popup end ---@param abs_path string ---@return boolean local function old_is_ignored(abs_path) local project_root = Utils.get_project_root() local gitignore_path = project_root .. "/.gitignore" local gitignore_patterns, gitignore_negate_patterns = Utils.parse_gitignore(gitignore_path) -- The checker should only take care of the path inside the project root -- Specifically, it should not check the project root itself -- Otherwise if the binary is named the same as the project root (such as Go binary), any paths -- insde the project root will be ignored local rel_path = Utils.make_relative_path(abs_path, project_root) return Utils.is_ignored(rel_path, gitignore_patterns, gitignore_negate_patterns) end ---@param abs_path string ---@return boolean function M.is_ignored(abs_path) local project_root = Utils.get_project_root() local exit_code = vim.system({ "git", "-C", project_root, "check-ignore", abs_path }, { text = true }):wait().code -- If command failed or git is not available or not a git repository, fall back to old method if exit_code ~= 0 and exit_code ~= 1 then return old_is_ignored(abs_path) end -- git check-ignore returns: -- - exit code 0 and outputs the path to stdout if the file is ignored -- - exit code 1 and no output to stdout if the file is not ignored -- - exit code 128 and outputs the error info to stderr not stdout return exit_code == 0 end ---@param abs_path string ---@return boolean function M.has_permission_to_access(abs_path) if not Path:new(abs_path):is_absolute() then return false end local project_root = Utils.get_project_root() -- allow if inside project root OR inside user config dir local config_dir = vim.fn.stdpath("config") local in_project = abs_path:sub(1, #project_root) == project_root local in_config = abs_path:sub(1, #config_dir) == config_dir local bypass_ignore = Config.behaviour and Config.behaviour.allow_access_to_git_ignored_files if not in_project and not in_config then return false end return bypass_ignore or not M.is_ignored(abs_path) end ---@param path string ---@return boolean function M.already_in_context(path) local sidebar = require("avante").get() if sidebar and sidebar.file_selector then local rel_path = Utils.uniform_path(path) return vim.tbl_contains(sidebar.file_selector.selected_filepaths, rel_path) end return false end ---@param path string ---@param session_ctx table ---@return boolean function M.already_viewed(path, session_ctx) local view_history = session_ctx.view_history or {} local uniform_path = Utils.uniform_path(path) if view_history[uniform_path] then return true end return false end ---@param path string ---@param session_ctx table function M.mark_as_viewed(path, session_ctx) local view_history = session_ctx.view_history or {} local uniform_path = Utils.uniform_path(path) view_history[uniform_path] = true session_ctx.view_history = view_history end function M.mark_as_not_viewed(path, session_ctx) local view_history = session_ctx.view_history or {} local uniform_path = Utils.uniform_path(path) view_history[uniform_path] = nil session_ctx.view_history = view_history end ---@param abs_path string ---@return integer bufnr ---@return string | nil error function M.get_bufnr(abs_path) local sidebar = require("avante").get() if not sidebar then return 0, "Avante sidebar not found" end local bufnr ---@type integer vim.api.nvim_win_call(sidebar.code.winid, function() ---@diagnostic disable-next-line: param-type-mismatch pcall(vim.cmd, "edit " .. abs_path) bufnr = vim.api.nvim_get_current_buf() end) return bufnr, nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/init.lua
Lua
local curl = require("plenary.curl") local Utils = require("avante.utils") local Path = require("plenary.path") local Config = require("avante.config") local RagService = require("avante.rag_service") local Helpers = require("avante.llm_tools.helpers") local M = {} ---@type AvanteLLMToolFunc<{ path: string }> function M.read_file_toplevel_symbols(input, opts) local on_log = opts.on_log local RepoMap = require("avante.repo_map") local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return "", "No permission to access path: " .. abs_path end if on_log then on_log("path: " .. abs_path) end if not Path:new(abs_path):exists() then return "", "File does not exists: " .. abs_path end local filetype = RepoMap.get_ts_lang(abs_path) local repo_map_lib = RepoMap._init_repo_map_lib() if not repo_map_lib then return "", "Failed to load avante_repo_map" end local lines = Utils.read_file_from_buf_or_disk(abs_path) local content = lines and table.concat(lines, "\n") or "" local definitions = filetype and repo_map_lib.stringify_definitions(filetype, content) or "" return definitions, nil end ---@type AvanteLLMToolFunc<{ command: "view" | "str_replace" | "create" | "insert" | "undo_edit", path: string, old_str?: string, new_str?: string, file_text?: string, insert_line?: integer, new_str?: string, view_range?: integer[] }> function M.str_replace_editor(input, opts) if input.command == "undo_edit" then return require("avante.llm_tools.undo_edit").func(input, opts) end ---@cast input any return M.str_replace_based_edit_tool(input, opts) end ---@type AvanteLLMToolFunc<{ command: "view" | "str_replace" | "create" | "insert", path: string, old_str?: string, new_str?: string, file_text?: string, insert_line?: integer, new_str?: string, view_range?: integer[] }> function M.str_replace_based_edit_tool(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete if not input.command then return false, "command not provided" end if on_log then on_log("command: " .. input.command) end if not on_complete then return false, "on_complete not provided" end local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if input.command == "view" then local view = require("avante.llm_tools.view") local input_ = { path = input.path } if input.view_range then local start_line, end_line = unpack(input.view_range) input_.start_line = start_line input_.end_line = end_line end return view(input_, opts) end if input.command == "str_replace" then if input.new_str == nil and input.file_text ~= nil then input.new_str = input.file_text input.file_text = nil end return require("avante.llm_tools.str_replace").func(input, opts) end if input.command == "create" then return require("avante.llm_tools.create").func(input, opts) end if input.command == "insert" then return require("avante.llm_tools.insert").func(input, opts) end return false, "Unknown command: " .. input.command end ---@type AvanteLLMToolFunc<{ abs_path: string }> function M.read_global_file(input, opts) local on_log = opts.on_log local abs_path = Helpers.get_abs_path(input.abs_path) if Helpers.is_ignored(abs_path) then return "", "This file is ignored: " .. abs_path end if on_log then on_log("path: " .. abs_path) end local file = io.open(abs_path, "r") if not file then return "", "file not found: " .. abs_path end local content = file:read("*a") file:close() return content, nil end ---@type AvanteLLMToolFunc<{ abs_path: string, content: string }> function M.write_global_file(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local abs_path = Helpers.get_abs_path(input.abs_path) if Helpers.is_ignored(abs_path) then return false, "This file is ignored: " .. abs_path end if on_log then on_log("path: " .. abs_path) end if on_log then on_log("content: " .. input.content) end if not on_complete then return false, "on_complete not provided" end Helpers.confirm("Are you sure you want to write to the file: " .. abs_path, function(ok) if not ok then on_complete(false, "User canceled") return end local file = io.open(abs_path, "w") if not file then on_complete(false, "file not found: " .. abs_path) return end file:write(input.content) file:close() on_complete(true, nil) end, nil, opts.session_ctx, "write_global_file") end ---@type AvanteLLMToolFunc<{ source_path: string, destination_path: string }> function M.move_path(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local abs_path = Helpers.get_abs_path(input.source_path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return false, "The source path not found: " .. abs_path end local new_abs_path = Helpers.get_abs_path(input.destination_path) if on_log then on_log(abs_path .. " -> " .. new_abs_path) end if not Helpers.has_permission_to_access(new_abs_path) then return false, "No permission to access path: " .. new_abs_path end if Path:new(new_abs_path):exists() then return false, "The destination path already exists: " .. new_abs_path end if not on_complete then return false, "on_complete not provided" end Helpers.confirm( "Are you sure you want to move the path: " .. abs_path .. " to: " .. new_abs_path, function(ok, reason) if not ok then on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end os.rename(abs_path, new_abs_path) on_complete(true, nil) end, nil, opts.session_ctx, "move_path" ) end ---@type AvanteLLMToolFunc<{ source_path: string, destination_path: string }> function M.copy_path(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local abs_path = Helpers.get_abs_path(input.source_path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return false, "The source path not found: " .. abs_path end local new_abs_path = Helpers.get_abs_path(input.destination_path) if not Helpers.has_permission_to_access(new_abs_path) then return false, "No permission to access path: " .. new_abs_path end if Path:new(new_abs_path):exists() then return false, "The destination path already exists: " .. new_abs_path end if not on_complete then return false, "on_complete not provided" end Helpers.confirm( "Are you sure you want to copy the path: " .. abs_path .. " to: " .. new_abs_path, function(ok, reason) if not ok then on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end if on_log then on_log("Copying path: " .. abs_path .. " to " .. new_abs_path) end if Path:new(abs_path):is_dir() then Path:new(new_abs_path):mkdir({ parents = true }) for _, entry in ipairs(Path:new(abs_path):list()) do local new_entry_path = Path:new(new_abs_path):joinpath(entry) if entry:match("^%.") then goto continue end if Path:new(new_entry_path):exists() then if Path:new(new_entry_path):is_dir() then Path:new(new_entry_path):rmdir() else Path:new(new_entry_path):unlink() end end vim.fn.mkdir(new_entry_path, "p") Path:new(new_entry_path):write(Path:new(abs_path):joinpath(entry):read(), "w") ::continue:: end else Path:new(new_abs_path):write(Path:new(abs_path):read(), "w") end on_complete(true, nil) end, nil, opts.session_ctx, "copy_path" ) end ---@type AvanteLLMToolFunc<{ path: string }> function M.delete_path(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return false, "Path not found: " .. abs_path end if not on_complete then return false, "on_complete not provided" end Helpers.confirm("Are you sure you want to delete the path: " .. abs_path, function(ok, reason) if not ok then on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end if on_log then on_log("Deleting path: " .. abs_path) end os.remove(abs_path) on_complete(true, nil) end, nil, opts.session_ctx, "delete_path") end ---@type AvanteLLMToolFunc<{ path: string }> function M.create_dir(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if Path:new(abs_path):exists() then return false, "Directory already exists: " .. abs_path end if not on_complete then return false, "on_complete not provided" end Helpers.confirm("Are you sure you want to create the directory: " .. abs_path, function(ok, reason) if not ok then on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end if on_log then on_log("Creating directory: " .. abs_path) end Path:new(abs_path):mkdir({ parents = true }) on_complete(true, nil) end, nil, opts.session_ctx, "create_dir") end ---@type AvanteLLMToolFunc<{ query: string }> function M.web_search(input, opts) local on_log = opts.on_log local provider_type = Config.web_search_engine.provider local proxy = Config.web_search_engine.proxy if provider_type == nil then return nil, "Search engine provider is not set" end if on_log then on_log("provider: " .. provider_type) end if on_log then on_log("query: " .. input.query) end local search_engine = Config.web_search_engine.providers[provider_type] if search_engine == nil then return nil, "No search engine found: " .. provider_type end if provider_type ~= "searxng" and search_engine.api_key_name == "" then return nil, "No API key provided" end local api_key = provider_type ~= "searxng" and Utils.environment.parse(search_engine.api_key_name) or nil if provider_type ~= "searxng" and api_key == nil or api_key == "" then return nil, "Environment variable " .. search_engine.api_key_name .. " is not set" end if provider_type == "tavily" then local curl_opts = { headers = { ["Content-Type"] = "application/json", ["Authorization"] = "Bearer " .. api_key, }, body = vim.json.encode(vim.tbl_deep_extend("force", { query = input.query, }, search_engine.extra_request_body)), } if proxy then curl_opts.proxy = proxy end local resp = curl.post("https://api.tavily.com/search", curl_opts) if resp.status ~= 200 then return nil, "Error: " .. resp.body end local jsn = vim.json.decode(resp.body) return search_engine.format_response_body(jsn) elseif provider_type == "serpapi" then local query_params = vim.tbl_deep_extend("force", { api_key = api_key, q = input.query, }, search_engine.extra_request_body) local query_string = "" for key, value in pairs(query_params) do query_string = query_string .. key .. "=" .. vim.uri_encode(value) .. "&" end local curl_opts = { headers = { ["Content-Type"] = "application/json", }, } if proxy then curl_opts.proxy = proxy end local resp = curl.get("https://serpapi.com/search?" .. query_string, curl_opts) if resp.status ~= 200 then return nil, "Error: " .. resp.body end local jsn = vim.json.decode(resp.body) return search_engine.format_response_body(jsn) elseif provider_type == "searchapi" then local query_params = vim.tbl_deep_extend("force", { api_key = api_key, q = input.query, }, search_engine.extra_request_body) local query_string = "" for key, value in pairs(query_params) do query_string = query_string .. key .. "=" .. vim.uri_encode(value) .. "&" end local curl_opts = { headers = { ["Content-Type"] = "application/json", }, } if proxy then curl_opts.proxy = proxy end local resp = curl.get("https://searchapi.io/api/v1/search?" .. query_string, curl_opts) if resp.status ~= 200 then return nil, "Error: " .. resp.body end local jsn = vim.json.decode(resp.body) return search_engine.format_response_body(jsn) elseif provider_type == "google" then local engine_id = Utils.environment.parse(search_engine.engine_id_name) if engine_id == nil or engine_id == "" then return nil, "Environment variable " .. search_engine.engine_id_name .. " is not set" end local query_params = vim.tbl_deep_extend("force", { key = api_key, cx = engine_id, q = input.query, }, search_engine.extra_request_body) local query_string = "" for key, value in pairs(query_params) do query_string = query_string .. key .. "=" .. vim.uri_encode(value) .. "&" end local curl_opts = { headers = { ["Content-Type"] = "application/json", }, } if proxy then curl_opts.proxy = proxy end local resp = curl.get("https://www.googleapis.com/customsearch/v1?" .. query_string, curl_opts) if resp.status ~= 200 then return nil, "Error: " .. resp.body end local jsn = vim.json.decode(resp.body) return search_engine.format_response_body(jsn) elseif provider_type == "kagi" then local query_params = vim.tbl_deep_extend("force", { q = input.query, }, search_engine.extra_request_body) local query_string = "" for key, value in pairs(query_params) do query_string = query_string .. key .. "=" .. vim.uri_encode(value) .. "&" end local curl_opts = { headers = { ["Authorization"] = "Bot " .. api_key, ["Content-Type"] = "application/json", }, } if proxy then curl_opts.proxy = proxy end local resp = curl.get("https://kagi.com/api/v0/search?" .. query_string, curl_opts) if resp.status ~= 200 then return nil, "Error: " .. resp.body end local jsn = vim.json.decode(resp.body) return search_engine.format_response_body(jsn) elseif provider_type == "brave" then local query_params = vim.tbl_deep_extend("force", { q = input.query, }, search_engine.extra_request_body) local query_string = "" for key, value in pairs(query_params) do query_string = query_string .. key .. "=" .. vim.uri_encode(value) .. "&" end local curl_opts = { headers = { ["Content-Type"] = "application/json", ["X-Subscription-Token"] = api_key, }, } if proxy then curl_opts.proxy = proxy end local resp = curl.get("https://api.search.brave.com/res/v1/web/search?" .. query_string, curl_opts) if resp.status ~= 200 then return nil, "Error: " .. resp.body end local jsn = vim.json.decode(resp.body) return search_engine.format_response_body(jsn) elseif provider_type == "searxng" then local searxng_api_url = Utils.environment.parse(search_engine.api_url_name) if searxng_api_url == nil or searxng_api_url == "" then return nil, "Environment variable " .. search_engine.api_url_name .. " is not set" end local query_params = vim.tbl_deep_extend("force", { q = input.query, }, search_engine.extra_request_body) local query_string = "" for key, value in pairs(query_params) do query_string = query_string .. key .. "=" .. vim.uri_encode(value) .. "&" end local resp = curl.get(searxng_api_url .. "?" .. query_string, { headers = { ["Content-Type"] = "application/json", }, }) if resp.status ~= 200 then return nil, "Error: " .. resp.body end local jsn = vim.json.decode(resp.body) return search_engine.format_response_body(jsn) end return nil, "Error: No search engine found" end ---@type AvanteLLMToolFunc<{ url: string }> function M.fetch(input, opts) local on_log = opts.on_log if on_log then on_log("url: " .. input.url) end local Html2Md = require("avante.html2md") local res, err = Html2Md.fetch_md(input.url) if err then return nil, err end return res, nil end ---@type AvanteLLMToolFunc<{ scope?: string }> function M.git_diff(input, opts) local on_log = opts.on_log local git_cmd = vim.fn.exepath("git") if git_cmd == "" then return nil, "Git command not found" end local project_root = Utils.get_project_root() if not project_root then return nil, "Not in a git repository" end -- Check if we're in a git repository local git_dir = vim.system({ "git", "rev-parse", "--git-dir" }, { text = true }):wait().stdout:gsub("\n", "") if git_dir == "" then return nil, "Not a git repository" end -- Get the diff local scope = input.scope or "" local cmd = { "git", "diff", "--cached", scope } if on_log then on_log("Running command: " .. table.concat(cmd, " ")) end local diff = vim.system(cmd, { text = true }):wait().stdout if diff == "" then -- If there's no staged changes, get unstaged changes cmd = { "git", "diff", scope } if on_log then on_log("No staged changes. Running command: " .. table.concat(cmd, " ")) end diff = vim.system(cmd, { text = true }):wait().stdout end if diff == "" then return nil, "No changes detected" end return diff, nil end ---@type AvanteLLMToolFunc<{ message: string, scope?: string }> function M.git_commit(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local git_cmd = vim.fn.exepath("git") if git_cmd == "" then return false, "Git command not found" end local project_root = Utils.get_project_root() if not project_root then return false, "Not in a git repository" end -- Check if we're in a git repository local git_dir = vim.system({ "git", "rev-parse", "--git-dir" }, { text = true }):wait().stdout:gsub("\n", "") if git_dir == "" then return false, "Not a git repository" end -- First check if there are any changes to commit local status = vim.system({ "git", "status", "--porcelain" }, { text = true }):wait().stdout if status == "" then return false, "No changes to commit" end -- Get git user name and email local git_user = vim.system({ "git", "config", "user.name" }, { text = true }):wait().stdout:gsub("\n", "") local git_email = vim.system({ "git", "config", "user.email" }, { text = true }):wait().stdout:gsub("\n", "") -- Check if GPG signing is available and configured local has_gpg = false local signing_key = vim .system({ "git", "config", "--get", "user.signingkey" }, { text = true }) :wait().stdout :gsub("\n", "") if signing_key ~= "" then -- Try to find gpg executable based on OS local gpg_cmd if vim.fn.has("win32") == 1 then -- Check common Windows GPG paths gpg_cmd = vim.fn.exepath("gpg.exe") ~= "" and vim.fn.exepath("gpg.exe") or vim.fn.exepath("gpg2.exe") else -- Unix-like systems (Linux/MacOS) gpg_cmd = vim.fn.exepath("gpg") ~= "" and vim.fn.exepath("gpg") or vim.fn.exepath("gpg2") end if gpg_cmd ~= "" then -- Verify GPG is working has_gpg = vim.system({ gpg_cmd, "--version" }, { text = true }):wait().code == 0 end end if on_log then on_log(string.format("GPG signing %s", has_gpg and "enabled" or "disabled")) end -- Prepare commit message local commit_msg_lines = {} for line in input.message:gmatch("[^\r\n]+") do commit_msg_lines[#commit_msg_lines + 1] = line:gsub('"', '\\"') end commit_msg_lines[#commit_msg_lines + 1] = "" -- add Generated-by line using provider and model name if Config.behaviour and Config.behaviour.include_generated_by_commit_line then local provider_name = Config.provider or "unknown" local model_name = (Config.providers and Config.providers[provider_name] and Config.providers[provider_name].model) or "unknown" commit_msg_lines[#commit_msg_lines + 1] = string.format("Generated-by: %s/%s", provider_name, model_name) end if git_user ~= "" and git_email ~= "" then commit_msg_lines[#commit_msg_lines + 1] = string.format("Signed-off-by: %s <%s>", git_user, git_email) end -- Construct full commit message for confirmation local full_commit_msg = table.concat(commit_msg_lines, "\n") if not on_complete then return false, "on_complete not provided" end -- Confirm with user Helpers.confirm("Are you sure you want to commit with message:\n" .. full_commit_msg, function(ok, reason) if not ok then on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end -- Stage changes if scope is provided if input.scope then local stage_cmd = { "git", "add", input.scope } if on_log then on_log("Staging files: " .. table.concat(stage_cmd, " ")) end local stage_result = vim.system(stage_cmd, { text = true }):wait() if stage_result.code ~= 0 then on_complete(false, "Failed to stage files: " .. stage_result.stderr) return end end -- Construct git commit command local cmd_parts = { "git", "commit" } -- Only add -S flag if GPG is available if has_gpg then table.insert(cmd_parts, "-S") end for _, line in ipairs(commit_msg_lines) do table.insert(cmd_parts, "-m") table.insert(cmd_parts, line) end local cmd = table.concat(cmd_parts, " ") -- Execute git commit if on_log then on_log("Running command: " .. cmd) end local result = vim.system(cmd_parts, { text = true }):wait() if result.code ~= 0 then on_complete(false, "Failed to commit: " .. result.stderr) return end on_complete(true, nil) end, nil, opts.session_ctx, "git_commit") end ---@type AvanteLLMToolFunc<{ query: string }> function M.rag_search(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete if not on_complete then return nil, "on_complete not provided" end if not Config.rag_service.enabled then return nil, "Rag service is not enabled" end if not input.query then return nil, "No query provided" end if on_log then on_log("query: " .. input.query) end local root = Utils.get_project_root() local uri = "file://" .. root if uri:sub(-1) ~= "/" then uri = uri .. "/" end RagService.retrieve( uri, input.query, vim.schedule_wrap(function(resp, err) if err then on_complete(nil, err) return end on_complete(vim.json.encode(resp), nil) end) ) end ---@type AvanteLLMToolFunc<{ code: string, path: string, container_image?: string }> function M.python(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return nil, "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return nil, "Path not found: " .. abs_path end if on_log then on_log("cwd: " .. abs_path) end if on_log then on_log("code:\n" .. input.code) end local container_image = input.container_image or "python:3.11-slim-bookworm" if not on_complete then return nil, "on_complete not provided" end Helpers.confirm( "Are you sure you want to run the following python code in the `" .. container_image .. "` container, in the directory: `" .. abs_path .. "`?\n" .. input.code, function(ok, reason) if not ok then on_complete(nil, "User declined, reason: " .. (reason or "unknown")) return end if vim.fn.executable("docker") == 0 then on_complete(nil, "Python tool is not available to execute any code") return end local function handle_result(result) ---@param result vim.SystemCompleted if result.code ~= 0 then return nil, "Error: " .. (result.stderr or "Unknown error") end Utils.debug("output", result.stdout) return result.stdout, nil end vim.system( { "docker", "run", "--rm", "-v", abs_path .. ":" .. abs_path, "-w", abs_path, container_image, "python", "-c", input.code, }, { text = true, cwd = abs_path, }, vim.schedule_wrap(function(result) if not on_complete then return end local output, err = handle_result(result) on_complete(output, err) end) ) end, nil, opts.session_ctx, "python" ) end ---@param user_input string ---@param history_messages AvanteLLMMessage[] ---@return AvanteLLMTool[] function M.get_tools(user_input, history_messages) local custom_tools = Config.custom_tools if type(custom_tools) == "function" then custom_tools = custom_tools() end ---@type AvanteLLMTool[] local unfiltered_tools = vim.list_extend(vim.list_extend({}, M._tools), custom_tools) return vim .iter(unfiltered_tools) :filter(function(tool) ---@param tool AvanteLLMTool -- Always disable tools that are explicitly disabled if vim.tbl_contains(Config.disabled_tools, tool.name) then return false end if tool.enabled == nil then return true else return tool.enabled({ user_input = user_input, history_messages = history_messages }) end end) :totable() end function M.get_tool_names() local custom_tools = Config.custom_tools if type(custom_tools) == "function" then custom_tools = custom_tools() end ---@type AvanteLLMTool[] local unfiltered_tools = vim.list_extend(vim.list_extend({}, M._tools), custom_tools) local tool_names = {} for _, tool in ipairs(unfiltered_tools) do table.insert(tool_names, tool.name) end return tool_names end ---@type AvanteLLMTool[] M._tools = { require("avante.llm_tools.dispatch_agent"), require("avante.llm_tools.glob"), { name = "rag_search", enabled = function() return Config.rag_service.enabled and RagService.is_ready() end, description = "Use Retrieval-Augmented Generation (RAG) to search for relevant information from an external knowledge base or documents. This tool retrieves relevant context from a large dataset and integrates it into the response generation process, improving accuracy and relevance. Use it when answering questions that require factual knowledge beyond what the model has been trained on.", param = { type = "table", fields = { { name = "query", description = "Query to search", type = "string", }, }, usage = { query = "Query to search", }, }, returns = { { name = "result", description = "Result of the search", type = "string", }, { name = "error", description = "Error message if the search was not successful", type = "string", optional = true, }, }, }, { name = "run_python", description = "Run python code in current project scope. Can't use it to read files or modify files.", param = { type = "table", fields = { { name = "code", description = "Python code to run", type = "string", }, { name = "path", description = "Relative path to the project directory, as cwd", type = "string", }, }, usage = { code = "Python code to run", path = "Relative path to the project directory, as cwd", }, }, returns = { { name = "result", description = "Python output", type = "string", }, { name = "error", description = "Error message if the python code failed", type = "string", optional = true, }, }, }, { name = "git_diff", description = "Get git diff for generating commit message in current project scope", param = { type = "table", fields = { { name = "scope", description = "Scope for the git diff (e.g. specific files or directories)", type = "string", }, }, usage = { scope = "Scope for the git diff (e.g. specific files or directories)", }, }, returns = { { name = "result", description = "Git diff output to be used for generating commit message", type = "string", }, { name = "error", description = "Error message if the diff generation failed", type = "string", optional = true, }, }, }, { name = "git_commit", description = "Commit changes with the given commit message in current project scope", param = { type = "table", fields = { { name = "message", description = "Commit message to use", type = "string", }, { name = "scope", description = "Scope for staging files (e.g. specific files or directories)", type = "string", optional = true, }, }, usage = { message = "Commit message to use", scope = "Scope for staging files (e.g. specific files or directories)", }, }, returns = { { name = "success", description = "True if the commit was successful, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the commit failed", type = "string", optional = true, }, }, }, require("avante.llm_tools.ls"), require("avante.llm_tools.grep"), require("avante.llm_tools.delete_tool_use_messages"), require("avante.llm_tools.read_todos"), require("avante.llm_tools.write_todos"), { name = "read_file_toplevel_symbols", description = [[Read the top-level symbols of a file in current project scope. This tool is useful for understanding the structure of a file and extracting information about its contents. It can be used to extract information about functions, types, constants, and other symbols that are defined at the top level of a file. <example> Given the following file: a.py: ```python a = 1 class A: pass def foo(): return "bar" def baz(): return "qux" ``` The top-level symbols of "a.py": [ "a", "A", "foo", "baz" ] Then you can use the "read_definitions" tool to retrieve the source code definitions of these symbols. </example>]], param = { type = "table", fields = { { name = "path", description = "Relative path to the file in current project scope", type = "string", }, }, usage = { path = "Relative path to the file in current project scope", }, }, returns = { { name = "definitions", description = "Top-level symbols of the file", type = "string", }, { name = "error", description = "Error message if the file was not read successfully", type = "string", optional = true, }, }, }, require("avante.llm_tools.str_replace"), require("avante.llm_tools.view"), require("avante.llm_tools.write_to_file"), require("avante.llm_tools.insert"), require("avante.llm_tools.undo_edit"), { name = "read_global_file", description = "Read the contents of a file in the global scope. If the file content is already in the context, do not use this tool.", enabled = function(opts) if opts.user_input:match("@read_global_file") then return true end for _, message in ipairs(opts.history_messages) do if message.role == "user" then local content = message.content if type(content) == "string" and content:match("@read_global_file") then return true end if type(content) == "table" then for _, item in ipairs(content) do if type(item) == "string" and item:match("@read_global_file") then return true end end end end end return false end, param = { type = "table", fields = { { name = "abs_path", description = "Absolute path to the file in global scope", type = "string", }, }, usage = { abs_path = "Absolute path to the file in global scope", }, }, returns = { { name = "content", description = "Contents of the file", type = "string", }, { name = "error", description = "Error message if the file was not read successfully", type = "string", optional = true, }, }, }, { name = "write_global_file", description = "Write to a file in the global scope", enabled = function(opts) if opts.user_input:match("@write_global_file") then return true end for _, message in ipairs(opts.history_messages) do if message.role == "user" then local content = message.content if type(content) == "string" and content:match("@write_global_file") then return true end if type(content) == "table" then for _, item in ipairs(content) do if type(item) == "string" and item:match("@write_global_file") then return true end end end end end return false end, param = { type = "table", fields = { { name = "abs_path", description = "Absolute path to the file in global scope", type = "string", }, { name = "content", description = "Content to write to the file", type = "string", }, }, usage = { abs_path = "The path to the file in the current project scope", content = "The content to write to the file", }, }, returns = { { name = "success", description = "True if the file was written successfully, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the file was not written successfully", type = "string", optional = true, }, }, }, { name = "move_path", description = [[Moves or rename a file or directory in the project, and returns confirmation that the move succeeded. If the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move. This tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.]], param = { type = "table", fields = { { name = "source_path", description = [[The source path of the file or directory to move/rename. <example> If the project has the following files: - directory1/a/something.txt - directory2/a/things.txt - directory3/a/other.txt You can move the first file by providing a source_path of "directory1/a/something.txt" </example>]], type = "string", }, { name = "destination_path", description = [[The destination path where the file or directory should be moved/renamed to. If the paths are the same except for the filename, then this will be a rename. <example> To move "directory1/a/something.txt" to "directory2/b/renamed.txt", provide a destination_path of "directory2/b/renamed.txt" </example>]], type = "string", }, }, usage = { source_path = "The source path of the file or directory to move/rename", destination_path = "The destination path where the file or directory should be moved/renamed to", }, }, returns = { { name = "success", description = "True if the file was renamed successfully, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the file was not renamed successfully", type = "string", optional = true, }, }, }, { name = "copy_path", description = [[Copies a file or directory from the project to a new location, and returns confirmation that the copy succeeded. This tool should be used when it's desirable to copy a file or directory without changing its contents at all.]], param = { type = "table", fields = { { name = "source_path", description = [[The source path of the file or directory to copy. <example> If the project has the following files: - directory1/a/something.txt - directory2/a/things.txt - directory3/a/other.txt You can copy the first file by providing a source_path of "directory1/a/something.txt" </example>]], type = "string", }, { name = "destination_path", description = [[The destination path where the file or directory should be copied to. <example> To copy "directory1/a/something.txt" to "directory2/b/copied.txt", provide a destination_path of "directory2/b/copied.txt" </example>]], type = "string", }, }, usage = { source_path = "The source path of the file or directory to copy", destination_path = "The destination path where the file or directory should be copied to", }, }, returns = { { name = "success", description = "True if the file was copied successfully, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the file was not copied successfully", type = "string", optional = true, }, }, }, { name = "delete_path", description = "Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.", param = { type = "table", fields = { { name = "path", description = [[The path of the file or directory to delete. <example> If the project has the following files: - directory1/a/something.txt - directory2/a/things.txt - directory3/a/other.txt You can delete the first file by providing a path of "directory1/a/something.txt" </example> ]], type = "string", }, }, usage = { path = "Relative path to the file or directory in the current project scope", }, }, returns = { { name = "success", description = "True if the file was deleted successfully, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the file was not deleted successfully", type = "string", optional = true, }, }, }, { name = "create_dir", description = "Create a new directory in current project scope", param = { type = "table", fields = { { name = "path", description = "Relative path to the project directory", type = "string", }, }, usage = { path = "Relative path to the project directory", }, }, returns = { { name = "success", description = "True if the directory was created successfully, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the directory was not created successfully", type = "string", optional = true, }, }, }, require("avante.llm_tools.think"), require("avante.llm_tools.get_diagnostics"), require("avante.llm_tools.bash"), require("avante.llm_tools.attempt_completion"), require("avante.llm_tools.edit_file"), { name = "web_search", description = "Search the web", param = { type = "table", fields = { { name = "query", description = "Query to search", type = "string", }, }, usage = { query = "Query to search", }, }, returns = { { name = "result", description = "Result of the search", type = "string", }, { name = "error", description = "Error message if the search was not successful", type = "string", optional = true, }, }, }, { name = "fetch", description = "Fetch markdown from a url", param = { type = "table", fields = { { name = "url", description = "Url to fetch markdown from", type = "string", }, }, usage = { url = "Url to fetch markdown from", }, }, returns = { { name = "result", description = "Result of the fetch", type = "string", }, { name = "error", description = "Error message if the fetch was not successful", type = "string", optional = true, }, }, }, { name = "read_definitions", description = "Retrieves the complete source code definitions of any symbol (function, type, constant, etc.) from your codebase.", param = { type = "table", fields = { { name = "symbol_name", description = "The name of the symbol to retrieve the definition for", type = "string", }, { name = "show_line_numbers", description = "Whether to show line numbers in the definitions", type = "boolean", default = false, }, }, usage = { symbol_name = "The name of the symbol to retrieve the definition for, example: fibonacci", show_line_numbers = "true or false", }, }, returns = { { name = "definitions", description = "The source code definitions of the symbol", type = "string[]", }, { name = "error", description = "Error message if the definition retrieval failed", type = "string", optional = true, }, }, func = function(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local symbol_name = input.symbol_name local show_line_numbers = input.show_line_numbers if on_log then on_log("symbol_name: " .. vim.inspect(symbol_name)) end if on_log then on_log("show_line_numbers: " .. vim.inspect(show_line_numbers)) end if not symbol_name then return nil, "No symbol name provided" end local sidebar = require("avante").get() if not sidebar then return nil, "No sidebar" end local bufnr = sidebar.code.bufnr if not bufnr then return nil, "No bufnr" end if not vim.api.nvim_buf_is_valid(bufnr) then return nil, "Invalid bufnr" end if on_log then on_log("bufnr: " .. vim.inspect(bufnr)) end Utils.lsp.read_definitions(bufnr, symbol_name, show_line_numbers, function(definitions, error) local encoded_defs = vim.json.encode(definitions) on_complete(encoded_defs, error) end) return nil, nil end, }, } --- compatibility alias for old calls & tests M.run_python = M.python ---@class avante.ProcessToolUseOpts ---@field session_ctx table ---@field on_log? fun(tool_id: string, tool_name: string, log: string, state: AvanteLLMToolUseState): nil ---@field set_tool_use_store? fun(tool_id: string, key: string, value: any): nil ---@field on_complete? fun(result: string | nil, error: string | nil): nil ---@param tools AvanteLLMTool[] ---@param tool_use AvanteLLMToolUse ---@return string | nil result ---@return string | nil error function M.process_tool_use(tools, tool_use, opts) local on_log = opts.on_log local on_complete = opts.on_complete -- Check if execution is already cancelled if Helpers.is_cancelled then Utils.debug("Tool execution cancelled before starting: " .. tool_use.name) if on_complete then on_complete(nil, Helpers.CANCEL_TOKEN) return end return nil, Helpers.CANCEL_TOKEN end local func if tool_use.name == "str_replace_editor" then func = M.str_replace_editor elseif tool_use.name == "str_replace_based_edit_tool" then func = M.str_replace_based_edit_tool else ---@type AvanteLLMTool? local tool = vim.iter(tools):find(function(tool) return tool.name == tool_use.name end) ---@param tool AvanteLLMTool if tool == nil then return nil, "This tool is not provided: " .. vim.inspect(tool_use.name) end func = tool.func or M[tool.name] end local input_json = tool_use.input if not func then return nil, "Tool not found: " .. tool_use.name end if on_log then on_log(tool_use.id, tool_use.name, "running tool", "running") end -- Set up a timer to periodically check for cancellation local cancel_timer if on_complete then cancel_timer = vim.uv.new_timer() if cancel_timer then cancel_timer:start( 100, 100, vim.schedule_wrap(function() if Helpers.is_cancelled then Utils.debug("Tool execution cancelled during execution: " .. tool_use.name) if cancel_timer and not cancel_timer:is_closing() then cancel_timer:stop() cancel_timer:close() end Helpers.is_cancelled = false on_complete(nil, Helpers.CANCEL_TOKEN) end end) ) end end ---@param result string | nil | boolean ---@param err string | nil local function handle_result(result, err) -- Stop the cancellation timer if it exists if cancel_timer and not cancel_timer:is_closing() then cancel_timer:stop() cancel_timer:close() end -- Check for cancellation one more time before processing result if Helpers.is_cancelled then if on_log then on_log(tool_use.id, tool_use.name, "cancelled during result handling", "failed") end return nil, Helpers.CANCEL_TOKEN end if err ~= nil then if on_log then on_log(tool_use.id, tool_use.name, "Error: " .. err, "failed") end else if on_log then on_log(tool_use.id, tool_use.name, "tool finished", "succeeded") end end local result_str ---@type string? if type(result) == "string" then result_str = result elseif result ~= nil then result_str = vim.json.encode(result) end return result_str, err end local result, err = func(input_json, { session_ctx = opts.session_ctx or {}, on_log = function(log) -- Check for cancellation during logging if Helpers.is_cancelled then return end if on_log then on_log(tool_use.id, tool_use.name, log, "running") end end, set_store = function(key, value) if opts.set_tool_use_store then opts.set_tool_use_store(tool_use.id, key, value) end end, on_complete = function(result, err) -- Check for cancellation before completing if Helpers.is_cancelled then Helpers.is_cancelled = false if on_complete then on_complete(nil, Helpers.CANCEL_TOKEN) end return end result, err = handle_result(result, err) if on_complete == nil then Utils.error("asynchronous tool " .. tool_use.name .. " result not handled") return end on_complete(result, err) end, streaming = opts.streaming, tool_use_id = opts.tool_use_id, }) -- Result and error being nil means that the tool was executed asynchronously if result == nil and err == nil and on_complete then return end return handle_result(result, err) end ---@param tool_use AvanteLLMToolUse ---@return string function M.stringify_tool_use(tool_use) local s = string.format("`%s`", tool_use.name) return s end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/insert.lua
Lua
local Path = require("plenary.path") local Base = require("avante.llm_tools.base") local Helpers = require("avante.llm_tools.helpers") local Highlights = require("avante.highlights") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "insert" M.description = "The insert tool allows you to insert text at a specific location in a file." function M.enabled() return require("avante.config").mode == "agentic" and not require("avante.config").behaviour.enable_fastapply end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "The path to the file to modify", type = "string", }, { name = "insert_line", description = "The line number after which to insert the text (0 for beginning of file)", type = "integer", }, { name = "new_str", description = "The text to insert", type = "string", }, }, usage = { path = "The path to the file to modify", insert_line = "The line number after which to insert the text (0 for beginning of file)", new_str = "The text to insert", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "True if the text was inserted successfully, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the text was not inserted successfully", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, insert_line: integer, new_str: string }> function M.func(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local session_ctx = opts.session_ctx if not on_complete then return false, "on_complete not provided" end if on_log then on_log("path: " .. input.path) end local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return false, "File not found: " .. abs_path end if not Path:new(abs_path):is_file() then return false, "Path is not a file: " .. abs_path end if input.insert_line == nil then return false, "insert_line not provided" end if input.new_str == nil then return false, "new_str not provided" end local ns_id = vim.api.nvim_create_namespace("avante_insert_diff") local bufnr, err = Helpers.get_bufnr(abs_path) if err then return false, err end local function clear_highlights() vim.api.nvim_buf_clear_namespace(bufnr, ns_id, 0, -1) end local new_lines = vim.split(input.new_str, "\n") local max_col = vim.o.columns local virt_lines = vim .iter(new_lines) :map(function(line) --- append spaces to the end of the line local line_ = line .. string.rep(" ", max_col - #line) return { { line_, Highlights.INCOMING } } end) :totable() local line_count = vim.api.nvim_buf_line_count(bufnr) if input.insert_line > line_count - 1 then input.insert_line = line_count - 1 end vim.api.nvim_buf_set_extmark(bufnr, ns_id, input.insert_line, 0, { virt_lines = virt_lines, hl_eol = true, hl_mode = "combine", }) Helpers.confirm("Are you sure you want to insert these lines?", function(ok, reason) clear_highlights() if not ok then on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end vim.api.nvim_buf_set_lines(bufnr, input.insert_line, input.insert_line, false, new_lines) vim.api.nvim_buf_call(bufnr, function() vim.cmd("noautocmd write") end) if session_ctx then Helpers.mark_as_not_viewed(input.path, session_ctx) end on_complete(true, nil) end, { focus = true }, session_ctx, M.name) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/ls.lua
Lua
local Utils = require("avante.utils") local Helpers = require("avante.llm_tools.helpers") local Base = require("avante.llm_tools.base") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "ls" M.description = "List files and directories in a given path in current project scope" ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "Relative path to the project directory", type = "string", }, { name = "max_depth", description = "Maximum depth of the directory", type = "integer", }, }, usage = { path = "Relative path to the project directory", max_depth = "Maximum depth of the directory", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "entries", description = "List of file paths and directorie paths in the given directory", type = "string[]", }, { name = "error", description = "Error message if the directory was not listed successfully", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, max_depth?: integer }> function M.func(input, opts) local on_log = opts.on_log local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return "", "No permission to access path: " .. abs_path end if on_log then on_log("path: " .. abs_path) end if on_log then on_log("max depth: " .. tostring(input.max_depth)) end local files = Utils.scan_directory({ directory = abs_path, add_dirs = true, max_depth = input.max_depth, }) local filepaths = {} for _, file in ipairs(files) do local uniform_path = Utils.uniform_path(file) table.insert(filepaths, uniform_path) end return vim.json.encode(filepaths), nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/read_todos.lua
Lua
local Base = require("avante.llm_tools.base") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "read_todos" M.description = "Read TODOs from the current task" ---@type AvanteLLMToolParam M.param = { type = "table", fields = {}, usage = {}, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "todos", description = "The TODOs from the current task", type = "array", }, } M.on_render = function() return {} end function M.func(input, opts) local on_complete = opts.on_complete local sidebar = require("avante").get() if not sidebar then return false, "Avante sidebar not found" end local todos = sidebar.chat_history.todos or {} if on_complete then on_complete(vim.json.encode(todos), nil) return nil, nil end return todos, nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/replace_in_file.lua
Lua
local Base = require("avante.llm_tools.base") local Helpers = require("avante.llm_tools.helpers") local Utils = require("avante.utils") local Highlights = require("avante.highlights") local Config = require("avante.config") local PRIORITY = (vim.hl or vim.highlight).priorities.user local NAMESPACE = vim.api.nvim_create_namespace("avante-diff") local KEYBINDING_NAMESPACE = vim.api.nvim_create_namespace("avante-diff-keybinding") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "replace_in_file" M.description = "Request to replace sections of content in an existing file using SEARCH/REPLACE blocks that define exact changes to specific parts of the file. This tool should be used when you need to make targeted changes to specific parts of a file." M.support_streaming = true function M.enabled() return false end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "The path to the file in the current project scope", type = "string", }, { --- IMPORTANT: Using "the_diff" instead of "diff" is to avoid LLM streaming generating function parameters in alphabetical order, which would result in generating "path" after "diff", making it impossible to achieve a streaming diff view. name = "the_diff", description = [[ One or more SEARCH/REPLACE blocks following this exact format: ``` ------- SEARCH [exact content to find] ======= [new content to replace with] +++++++ REPLACE ``` Example: ``` ------- SEARCH func my_function(param1, param2) { // This is a comment console.log(param1); } ======= func my_function(param1, param2) { // This is a modified comment console.log(param2); } +++++++ REPLACE ``` Critical rules: 1. SEARCH content must match the associated file section to find EXACTLY: * Do not refer to the `diff` argument of the previous `replace_in_file` function call for SEARCH content matching, as it may have been modified. Always match from the latest file content in <selected_files> or from the `view` function call result. * Match character-for-character including whitespace, indentation, line endings * Include all comments, docstrings, etc. 2. SEARCH/REPLACE blocks will ONLY replace the first match occurrence. * Including multiple unique SEARCH/REPLACE blocks if you need to make multiple changes. * Include *just* enough lines in each SEARCH section to uniquely match each set of lines that need to change. * When using multiple SEARCH/REPLACE blocks, list them in the order they appear in the file. 3. Keep SEARCH/REPLACE blocks concise: * Break large SEARCH/REPLACE blocks into a series of smaller blocks that each change a small portion of the file. * Include just the changing lines, and a few surrounding lines if needed for uniqueness. * Do not include long runs of unchanging lines in SEARCH/REPLACE blocks. * Each line must be complete. Never truncate lines mid-way through as this can cause matching failures. 4. Special operations: * To move code: Use two SEARCH/REPLACE blocks (one to delete from original + one to insert at new location) * To delete code: Use empty REPLACE section ]], type = "string", }, }, usage = { path = "File path here", the_diff = "Search and replace blocks here", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "True if the replacement was successful, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the replacement failed", type = "string", optional = true, }, } --- IMPORTANT: Using "the_diff" instead of "diff" is to avoid LLM streaming generating function parameters in alphabetical order, which would result in generating "path" after "diff", making it impossible to achieve a streaming diff view. ---@type AvanteLLMToolFunc<{ path: string, the_diff?: string }> function M.func(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local session_ctx = opts.session_ctx if not on_complete then return false, "on_complete not provided" end if not input.path or not input.the_diff then return false, "path and the_diff are required " .. vim.inspect(input) end if on_log then on_log("path: " .. input.path) end local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end local is_streaming = opts.streaming or false session_ctx.prev_streaming_diff_timestamp_map = session_ctx.prev_streaming_diff_timestamp_map or {} local current_timestamp = os.time() if is_streaming then local prev_streaming_diff_timestamp = session_ctx.prev_streaming_diff_timestamp_map[opts.tool_use_id] if prev_streaming_diff_timestamp ~= nil then if current_timestamp - prev_streaming_diff_timestamp < 2 then return false, "Diff hasn't changed in the last 2 seconds" end end local streaming_diff_lines_count = Utils.count_lines(input.the_diff) session_ctx.streaming_diff_lines_count_history = session_ctx.streaming_diff_lines_count_history or {} local prev_streaming_diff_lines_count = session_ctx.streaming_diff_lines_count_history[opts.tool_use_id] if streaming_diff_lines_count == prev_streaming_diff_lines_count then return false, "Diff lines count hasn't changed" end session_ctx.streaming_diff_lines_count_history[opts.tool_use_id] = streaming_diff_lines_count end local diff = Utils.fix_diff(input.the_diff) if on_log and diff ~= input.the_diff then on_log("diff fixed") end local diff_lines = vim.split(diff, "\n") local is_searching = false local is_replacing = false local current_old_lines = {} local current_new_lines = {} local rough_diff_blocks = {} for _, line in ipairs(diff_lines) do if line:match("^%s*-------* SEARCH") then is_searching = true is_replacing = false current_old_lines = {} elseif line:match("^%s*=======*") and is_searching then is_searching = false is_replacing = true current_new_lines = {} elseif line:match("^%s*+++++++* REPLACE") and is_replacing then is_replacing = false table.insert(rough_diff_blocks, { old_lines = current_old_lines, new_lines = current_new_lines }) elseif is_searching then table.insert(current_old_lines, line) elseif is_replacing then -- Remove trailing spaces from each line before adding to new_lines table.insert(current_new_lines, (line:gsub("%s+$", ""))) end end -- Handle streaming mode: if we're still in replace mode at the end, include the partial block if is_streaming and is_replacing and #current_old_lines > 0 then if #current_old_lines > #current_new_lines then current_old_lines = vim.list_slice(current_old_lines, 1, #current_new_lines) end table.insert( rough_diff_blocks, { old_lines = current_old_lines, new_lines = current_new_lines, is_replacing = true } ) end if #rough_diff_blocks == 0 then -- Utils.debug("opts.diff", opts.diff) -- Utils.debug("diff", diff) local err = [[No diff blocks found. Please make sure the diff is formatted correctly, and that the SEARCH/REPLACE blocks are in the correct order.]] return false, err end session_ctx.prev_streaming_diff_timestamp_map[opts.tool_use_id] = current_timestamp local bufnr, err = Helpers.get_bufnr(abs_path) if err then return false, err end session_ctx.undo_joined = session_ctx.undo_joined or {} local undo_joined = session_ctx.undo_joined[opts.tool_use_id] if not undo_joined then pcall(vim.cmd.undojoin) session_ctx.undo_joined[opts.tool_use_id] = true end local original_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) local sidebar = require("avante").get() if not sidebar then return false, "Avante sidebar not found" end --- add line numbers to rough_diff_block local function complete_rough_diff_block(rough_diff_block) local old_lines = rough_diff_block.old_lines local new_lines = rough_diff_block.new_lines local start_line, end_line = Utils.fuzzy_match(original_lines, old_lines) if start_line == nil or end_line == nil then local old_string = table.concat(old_lines, "\n") return "Failed to find the old string:\n" .. old_string end local original_indentation = Utils.get_indentation(original_lines[start_line]) if original_indentation ~= Utils.get_indentation(old_lines[1]) then old_lines = vim.tbl_map(function(line) return original_indentation .. line end, old_lines) new_lines = vim.tbl_map(function(line) return original_indentation .. line end, new_lines) end rough_diff_block.old_lines = old_lines rough_diff_block.new_lines = new_lines rough_diff_block.start_line = start_line rough_diff_block.end_line = end_line return nil end session_ctx.rough_diff_blocks_to_diff_blocks_cache_map = session_ctx.rough_diff_blocks_to_diff_blocks_cache_map or {} local rough_diff_blocks_to_diff_blocks_cache = session_ctx.rough_diff_blocks_to_diff_blocks_cache_map[opts.tool_use_id] if not rough_diff_blocks_to_diff_blocks_cache then rough_diff_blocks_to_diff_blocks_cache = {} session_ctx.rough_diff_blocks_to_diff_blocks_cache_map[opts.tool_use_id] = rough_diff_blocks_to_diff_blocks_cache end local function rough_diff_blocks_to_diff_blocks(rough_diff_blocks_) local res = {} local base_line_ = 0 for idx, rough_diff_block in ipairs(rough_diff_blocks_) do local cache_key = string.format("%s:%s", idx, #rough_diff_block.new_lines) local cached_diff_blocks = rough_diff_blocks_to_diff_blocks_cache[cache_key] if cached_diff_blocks then res = vim.list_extend(res, cached_diff_blocks.diff_blocks) base_line_ = cached_diff_blocks.base_line goto continue end local old_lines = rough_diff_block.old_lines local new_lines = rough_diff_block.new_lines if rough_diff_block.is_replacing then new_lines = vim.list_slice(new_lines, 1, #new_lines - 1) old_lines = vim.list_slice(old_lines, 1, #new_lines) end local old_string = table.concat(old_lines, "\n") local new_string = table.concat(new_lines, "\n") local patch if Config.behaviour.minimize_diff then ---@diagnostic disable-next-line: assign-type-mismatch, missing-fields patch = vim.diff(old_string, new_string, { ---@type integer[][] algorithm = "histogram", result_type = "indices", ctxlen = vim.o.scrolloff, }) else patch = { { 1, #old_lines, 1, #new_lines } } end local diff_blocks_ = {} for _, hunk in ipairs(patch) do local start_a, count_a, start_b, count_b = unpack(hunk) local diff_block = {} if count_a > 0 then diff_block.old_lines = vim.list_slice(rough_diff_block.old_lines, start_a, start_a + count_a - 1) else diff_block.old_lines = {} end if count_b > 0 then diff_block.new_lines = vim.list_slice(rough_diff_block.new_lines, start_b, start_b + count_b - 1) else diff_block.new_lines = {} end if count_a > 0 then diff_block.start_line = base_line_ + rough_diff_block.start_line + start_a - 1 else diff_block.start_line = base_line_ + rough_diff_block.start_line + start_a end diff_block.end_line = base_line_ + rough_diff_block.start_line + start_a + math.max(count_a, 1) - 2 table.insert(diff_blocks_, diff_block) end local distance = 0 for _, hunk in ipairs(patch) do local _, count_a, _, count_b = unpack(hunk) distance = distance + count_b - count_a end local old_distance = #rough_diff_block.new_lines - #rough_diff_block.old_lines base_line_ = base_line_ + distance - old_distance if not rough_diff_block.is_replacing then rough_diff_blocks_to_diff_blocks_cache[cache_key] = { diff_blocks = diff_blocks_, base_line = base_line_ } end res = vim.list_extend(res, diff_blocks_) ::continue:: end return res end for _, rough_diff_block in ipairs(rough_diff_blocks) do local error = complete_rough_diff_block(rough_diff_block) if error then on_complete(false, error) return end end local diff_blocks = rough_diff_blocks_to_diff_blocks(rough_diff_blocks) table.sort(diff_blocks, function(a, b) return a.start_line < b.start_line end) local base_line = 0 for _, diff_block in ipairs(diff_blocks) do diff_block.new_start_line = diff_block.start_line + base_line diff_block.new_end_line = diff_block.new_start_line + #diff_block.new_lines - 1 base_line = base_line + #diff_block.new_lines - #diff_block.old_lines end local function remove_diff_block(removed_idx, use_new_lines) local new_diff_blocks = {} local distance = 0 for idx, diff_block in ipairs(diff_blocks) do if idx == removed_idx then if not use_new_lines then distance = #diff_block.old_lines - #diff_block.new_lines end goto continue end if idx > removed_idx then diff_block.new_start_line = diff_block.new_start_line + distance diff_block.new_end_line = diff_block.new_end_line + distance end table.insert(new_diff_blocks, diff_block) ::continue:: end diff_blocks = new_diff_blocks end local function get_current_diff_block() local winid = Utils.get_winid(bufnr) local cursor_line = Utils.get_cursor_pos(winid) for idx, diff_block in ipairs(diff_blocks) do if cursor_line >= diff_block.new_start_line and cursor_line <= diff_block.new_end_line then return diff_block, idx end end return nil, nil end local function get_prev_diff_block() local winid = Utils.get_winid(bufnr) local cursor_line = Utils.get_cursor_pos(winid) local distance = nil local idx = nil for i, diff_block in ipairs(diff_blocks) do if cursor_line >= diff_block.new_start_line and cursor_line <= diff_block.new_end_line then local new_i = i - 1 if new_i < 1 then return diff_blocks[#diff_blocks] end return diff_blocks[new_i] end if diff_block.new_start_line < cursor_line then local distance_ = cursor_line - diff_block.new_start_line if distance == nil or distance_ < distance then distance = distance_ idx = i end end end if idx ~= nil then return diff_blocks[idx] end if #diff_blocks > 0 then return diff_blocks[#diff_blocks] end return nil end local function get_next_diff_block() local winid = Utils.get_winid(bufnr) local cursor_line = Utils.get_cursor_pos(winid) local distance = nil local idx = nil for i, diff_block in ipairs(diff_blocks) do if cursor_line >= diff_block.new_start_line and cursor_line <= diff_block.new_end_line then local new_i = i + 1 if new_i > #diff_blocks then return diff_blocks[1] end return diff_blocks[new_i] end if diff_block.new_start_line > cursor_line then local distance_ = diff_block.new_start_line - cursor_line if distance == nil or distance_ < distance then distance = distance_ idx = i end end end if idx ~= nil then return diff_blocks[idx] end if #diff_blocks > 0 then return diff_blocks[1] end return nil end local show_keybinding_hint_extmark_id = nil local augroup = vim.api.nvim_create_augroup("avante_replace_in_file", { clear = true }) local function register_cursor_move_events() local function show_keybinding_hint(lnum) if show_keybinding_hint_extmark_id then vim.api.nvim_buf_del_extmark(bufnr, KEYBINDING_NAMESPACE, show_keybinding_hint_extmark_id) end local hint = string.format( "[<%s>: OURS, <%s>: THEIRS, <%s>: PREV, <%s>: NEXT]", Config.mappings.diff.ours, Config.mappings.diff.theirs, Config.mappings.diff.prev, Config.mappings.diff.next ) show_keybinding_hint_extmark_id = vim.api.nvim_buf_set_extmark(bufnr, KEYBINDING_NAMESPACE, lnum - 1, -1, { hl_group = "AvanteInlineHint", virt_text = { { hint, "AvanteInlineHint" } }, virt_text_pos = "right_align", priority = PRIORITY, }) end vim.api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI", "WinLeave" }, { buffer = bufnr, group = augroup, callback = function(event) local diff_block = get_current_diff_block() if (event.event == "CursorMoved" or event.event == "CursorMovedI") and diff_block then show_keybinding_hint(diff_block.new_start_line) else vim.api.nvim_buf_clear_namespace(bufnr, KEYBINDING_NAMESPACE, 0, -1) end end, }) end local confirm local has_rejected = false local function register_buf_write_events() vim.api.nvim_create_autocmd({ "BufWritePost" }, { buffer = bufnr, group = augroup, callback = function() if #diff_blocks ~= 0 then return end pcall(vim.api.nvim_del_augroup_by_id, augroup) if confirm then confirm:close() end if has_rejected then on_complete(false, "User canceled") return end if session_ctx then Helpers.mark_as_not_viewed(input.path, session_ctx) end on_complete(true, nil) end, }) end local function register_keybinding_events() local keymap_opts = { buffer = bufnr } vim.keymap.set({ "n", "v" }, Config.mappings.diff.ours, function() if show_keybinding_hint_extmark_id then vim.api.nvim_buf_del_extmark(bufnr, KEYBINDING_NAMESPACE, show_keybinding_hint_extmark_id) end local diff_block, idx = get_current_diff_block() if not diff_block then return end pcall(vim.api.nvim_buf_del_extmark, bufnr, NAMESPACE, diff_block.delete_extmark_id) pcall(vim.api.nvim_buf_del_extmark, bufnr, NAMESPACE, diff_block.incoming_extmark_id) vim.api.nvim_buf_set_lines( bufnr, diff_block.new_start_line - 1, diff_block.new_end_line, false, diff_block.old_lines ) diff_block.incoming_extmark_id = nil diff_block.delete_extmark_id = nil remove_diff_block(idx, false) local next_diff_block = get_next_diff_block() if next_diff_block then local winnr = Utils.get_winid(bufnr) vim.api.nvim_win_set_cursor(winnr, { next_diff_block.new_start_line, 0 }) vim.api.nvim_win_call(winnr, function() vim.cmd("normal! zz") end) end has_rejected = true end, keymap_opts) vim.keymap.set({ "n", "v" }, Config.mappings.diff.theirs, function() if show_keybinding_hint_extmark_id then vim.api.nvim_buf_del_extmark(bufnr, KEYBINDING_NAMESPACE, show_keybinding_hint_extmark_id) end local diff_block, idx = get_current_diff_block() if not diff_block then return end pcall(vim.api.nvim_buf_del_extmark, bufnr, NAMESPACE, diff_block.incoming_extmark_id) pcall(vim.api.nvim_buf_del_extmark, bufnr, NAMESPACE, diff_block.delete_extmark_id) diff_block.incoming_extmark_id = nil diff_block.delete_extmark_id = nil remove_diff_block(idx, true) local next_diff_block = get_next_diff_block() if next_diff_block then local winnr = Utils.get_winid(bufnr) vim.api.nvim_win_set_cursor(winnr, { next_diff_block.new_start_line, 0 }) vim.api.nvim_win_call(winnr, function() vim.cmd("normal! zz") end) end end, keymap_opts) vim.keymap.set({ "n", "v" }, Config.mappings.diff.next, function() if show_keybinding_hint_extmark_id then vim.api.nvim_buf_del_extmark(bufnr, KEYBINDING_NAMESPACE, show_keybinding_hint_extmark_id) end local diff_block = get_next_diff_block() if not diff_block then return end local winnr = Utils.get_winid(bufnr) vim.api.nvim_win_set_cursor(winnr, { diff_block.new_start_line, 0 }) vim.api.nvim_win_call(winnr, function() vim.cmd("normal! zz") end) end, keymap_opts) vim.keymap.set({ "n", "v" }, Config.mappings.diff.prev, function() if show_keybinding_hint_extmark_id then vim.api.nvim_buf_del_extmark(bufnr, KEYBINDING_NAMESPACE, show_keybinding_hint_extmark_id) end local diff_block = get_prev_diff_block() if not diff_block then return end local winnr = Utils.get_winid(bufnr) vim.api.nvim_win_set_cursor(winnr, { diff_block.new_start_line, 0 }) vim.api.nvim_win_call(winnr, function() vim.cmd("normal! zz") end) end, keymap_opts) end local function unregister_keybinding_events() pcall(vim.api.nvim_buf_del_keymap, bufnr, "n", Config.mappings.diff.ours) pcall(vim.api.nvim_buf_del_keymap, bufnr, "n", Config.mappings.diff.theirs) pcall(vim.api.nvim_buf_del_keymap, bufnr, "n", Config.mappings.diff.next) pcall(vim.api.nvim_buf_del_keymap, bufnr, "n", Config.mappings.diff.prev) pcall(vim.api.nvim_buf_del_keymap, bufnr, "v", Config.mappings.diff.ours) pcall(vim.api.nvim_buf_del_keymap, bufnr, "v", Config.mappings.diff.theirs) pcall(vim.api.nvim_buf_del_keymap, bufnr, "v", Config.mappings.diff.next) pcall(vim.api.nvim_buf_del_keymap, bufnr, "v", Config.mappings.diff.prev) end local function clear() if bufnr and not vim.api.nvim_buf_is_valid(bufnr) then return end vim.api.nvim_buf_clear_namespace(bufnr, NAMESPACE, 0, -1) vim.api.nvim_buf_clear_namespace(bufnr, KEYBINDING_NAMESPACE, 0, -1) unregister_keybinding_events() pcall(vim.api.nvim_del_augroup_by_id, augroup) end local function insert_diff_blocks_new_lines() local base_line_ = 0 for _, diff_block in ipairs(diff_blocks) do local start_line = diff_block.start_line + base_line_ local end_line = diff_block.end_line + base_line_ base_line_ = base_line_ + #diff_block.new_lines - #diff_block.old_lines vim.api.nvim_buf_set_lines(bufnr, start_line - 1, end_line, false, diff_block.new_lines) end end local function highlight_diff_blocks() local line_count = vim.api.nvim_buf_line_count(bufnr) vim.api.nvim_buf_clear_namespace(bufnr, NAMESPACE, 0, -1) local base_line_ = 0 local max_col = vim.o.columns for _, diff_block in ipairs(diff_blocks) do local start_line = diff_block.start_line + base_line_ base_line_ = base_line_ + #diff_block.new_lines - #diff_block.old_lines local deleted_virt_lines = vim .iter(diff_block.old_lines) :map(function(line) --- append spaces to the end of the line local line_ = line .. string.rep(" ", max_col - #line) return { { line_, Highlights.TO_BE_DELETED_WITHOUT_STRIKETHROUGH } } end) :totable() local end_row = start_line + #diff_block.new_lines - 1 local delete_extmark_id = vim.api.nvim_buf_set_extmark(bufnr, NAMESPACE, math.min(math.max(end_row - 1, 0), line_count - 1), 0, { virt_lines = deleted_virt_lines, hl_eol = true, hl_mode = "combine", }) local incoming_extmark_id = vim.api.nvim_buf_set_extmark(bufnr, NAMESPACE, math.min(math.max(start_line - 1, 0), line_count - 1), 0, { hl_group = Highlights.INCOMING, hl_eol = true, hl_mode = "combine", end_row = end_row, }) diff_block.delete_extmark_id = delete_extmark_id diff_block.incoming_extmark_id = incoming_extmark_id end end session_ctx.extmark_id_map = session_ctx.extmark_id_map or {} local extmark_id_map = session_ctx.extmark_id_map[opts.tool_use_id] if not extmark_id_map then extmark_id_map = {} session_ctx.extmark_id_map[opts.tool_use_id] = extmark_id_map end session_ctx.virt_lines_map = session_ctx.virt_lines_map or {} local virt_lines_map = session_ctx.virt_lines_map[opts.tool_use_id] if not virt_lines_map then virt_lines_map = {} session_ctx.virt_lines_map[opts.tool_use_id] = virt_lines_map end session_ctx.last_orig_diff_end_line_map = session_ctx.last_orig_diff_end_line_map or {} local last_orig_diff_end_line = session_ctx.last_orig_diff_end_line_map[opts.tool_use_id] if not last_orig_diff_end_line then last_orig_diff_end_line = 1 session_ctx.last_orig_diff_end_line_map[opts.tool_use_id] = last_orig_diff_end_line end session_ctx.last_resp_diff_end_line_map = session_ctx.last_resp_diff_end_line_map or {} local last_resp_diff_end_line = session_ctx.last_resp_diff_end_line_map[opts.tool_use_id] if not last_resp_diff_end_line then last_resp_diff_end_line = 1 session_ctx.last_resp_diff_end_line_map[opts.tool_use_id] = last_resp_diff_end_line end session_ctx.prev_diff_blocks_map = session_ctx.prev_diff_blocks_map or {} local prev_diff_blocks = session_ctx.prev_diff_blocks_map[opts.tool_use_id] if not prev_diff_blocks then prev_diff_blocks = {} session_ctx.prev_diff_blocks_map[opts.tool_use_id] = prev_diff_blocks end local function get_unstable_diff_blocks(diff_blocks_) local new_diff_blocks = {} for _, diff_block in ipairs(diff_blocks_) do local has = vim.iter(prev_diff_blocks):find(function(prev_diff_block) if prev_diff_block.start_line ~= diff_block.start_line then return false end if prev_diff_block.end_line ~= diff_block.end_line then return false end if #prev_diff_block.old_lines ~= #diff_block.old_lines then return false end if #prev_diff_block.new_lines ~= #diff_block.new_lines then return false end return true end) if has == nil then table.insert(new_diff_blocks, diff_block) end end return new_diff_blocks end local function highlight_streaming_diff_blocks() local unstable_diff_blocks = get_unstable_diff_blocks(diff_blocks) session_ctx.prev_diff_blocks_map[opts.tool_use_id] = diff_blocks local max_col = vim.o.columns for _, diff_block in ipairs(unstable_diff_blocks) do local new_lines = diff_block.new_lines local start_line = diff_block.start_line if #diff_block.old_lines > 0 then vim.api.nvim_buf_set_extmark(bufnr, NAMESPACE, start_line - 1, 0, { hl_group = Highlights.TO_BE_DELETED_WITHOUT_STRIKETHROUGH, hl_eol = true, hl_mode = "combine", end_row = start_line + #diff_block.old_lines - 1, }) end if #new_lines == 0 then goto continue end local virt_lines = vim .iter(new_lines) :map(function(line) --- append spaces to the end of the line local line_ = line .. string.rep(" ", max_col - #line) return { { line_, Highlights.INCOMING } } end) :totable() local extmark_line if #diff_block.old_lines > 0 then extmark_line = math.max(0, start_line - 2 + #diff_block.old_lines) else extmark_line = math.max(0, start_line - 1 + #diff_block.old_lines) end -- Utils.debug("extmark_line", extmark_line, "idx", idx, "start_line", diff_block.start_line, "old_lines", table.concat(diff_block.old_lines, "\n")) local old_extmark_id = extmark_id_map[start_line] if old_extmark_id then vim.api.nvim_buf_del_extmark(bufnr, NAMESPACE, old_extmark_id) end local extmark_id = vim.api.nvim_buf_set_extmark(bufnr, NAMESPACE, extmark_line, 0, { virt_lines = virt_lines, hl_eol = true, hl_mode = "combine", }) extmark_id_map[start_line] = extmark_id ::continue:: end end if not is_streaming then insert_diff_blocks_new_lines() highlight_diff_blocks() register_cursor_move_events() register_keybinding_events() register_buf_write_events() else highlight_streaming_diff_blocks() end if diff_blocks[1] then if not vim.api.nvim_buf_is_valid(bufnr) then return false, "Code buffer is not valid" end local line_count = vim.api.nvim_buf_line_count(bufnr) local winnr = Utils.get_winid(bufnr) if is_streaming then -- In streaming mode, focus on the last diff block local last_diff_block = diff_blocks[#diff_blocks] vim.api.nvim_win_set_cursor(winnr, { math.min(last_diff_block.start_line, line_count), 0 }) vim.api.nvim_win_call(winnr, function() vim.cmd("normal! zz") end) else -- In normal mode, focus on the first diff block vim.api.nvim_win_set_cursor(winnr, { math.min(diff_blocks[1].new_start_line, line_count), 0 }) vim.api.nvim_win_call(winnr, function() vim.cmd("normal! zz") end) end end if is_streaming then -- In streaming mode, don't show confirmation dialog, just apply changes return end pcall(vim.cmd.undojoin) confirm = Helpers.confirm("Are you sure you want to apply this modification?", function(ok, reason) clear() if not ok then vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, original_lines) on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end local parent_dir = vim.fn.fnamemodify(abs_path, ":h") --- check if the parent dir is exists, if not, create it if vim.fn.isdirectory(parent_dir) == 0 then vim.fn.mkdir(parent_dir, "p") end if not vim.api.nvim_buf_is_valid(bufnr) then on_complete(false, "Code buffer is not valid") return end vim.api.nvim_buf_call(bufnr, function() vim.cmd("noautocmd write!") end) if session_ctx then Helpers.mark_as_not_viewed(input.path, session_ctx) end on_complete(true, nil) end, { focus = not Config.behaviour.auto_focus_on_diff_view }, session_ctx, M.name) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/str_replace.lua
Lua
local Base = require("avante.llm_tools.base") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "str_replace" M.description = "The str_replace tool allows you to replace a specific string in a file with a new string. This is used for making precise edits." function M.enabled() return require("avante.config").mode == "agentic" and not require("avante.config").behaviour.enable_fastapply end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "The path to the file in the current project scope", type = "string", }, { name = "old_str", description = "The text to replace (must match exactly, including whitespace and indentation)", type = "string", }, { name = "new_str", description = "The new text to insert in place of the old text", type = "string", }, }, usage = { path = "File path here", old_str = "old str here", new_str = "new str here", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "True if the replacement was successful, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the replacement failed", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, old_str: string, new_str: string }> function M.func(input, opts) local replace_in_file = require("avante.llm_tools.replace_in_file") local Utils = require("avante.utils") if input.new_str == nil then input.new_str = "" end if input.old_str == nil then input.old_str = "" end -- Remove trailing spaces from the new string input.new_str = Utils.remove_trailing_spaces(input.new_str) local diff = "------- SEARCH\n" .. input.old_str .. "\n=======\n" .. input.new_str if not opts.streaming then diff = diff .. "\n+++++++ REPLACE" end local new_input = { path = input.path, the_diff = diff, } return replace_in_file.func(new_input, opts) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/think.lua
Lua
local Line = require("avante.ui.line") local Base = require("avante.llm_tools.base") local Highlights = require("avante.highlights") local Utils = require("avante.utils") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "think" function M.enabled() local Providers = require("avante.providers") local Config = require("avante.config") local acp_provider = Config.acp_providers[Config.provider] if acp_provider then return true end local provider = Providers[Config.provider] local model = provider.model if model and model:match("gpt%-5") then return false end return true end M.description = [[Use the tool to think about something. It will not obtain new information or make any changes to the repository, but just log the thought. Use it when complex reasoning or brainstorming is needed. For example, if you explore the repo and discover the source of a bug, call this tool to brainstorm several unique ways of fixing the bug, and assess which change(s) are likely to be simplest and most effective. Alternatively, if you receive some test results, call this tool to brainstorm ways to fix the failing tests. RULES: - Remember to frequently use the `think` tool to resolve tasks, especially before each tool call. ]] M.support_streaming = true ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "thought", description = "Your thoughts.", type = "string", }, }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "Whether the task was completed successfully", type = "string", }, { name = "thoughts", description = "The thoughts that guided the solution", type = "string", }, } ---@class ThinkingInput ---@field thought string ---@type avante.LLMToolOnRender<ThinkingInput> function M.on_render(input, opts) local state = opts.state local lines = {} local text = state == "generating" and "Thinking" or "Thoughts" table.insert(lines, Line:new({ { Utils.icon("🤔 ") .. text, Highlights.AVANTE_THINKING } })) table.insert(lines, Line:new({ { "" } })) local content = input.thought or "" local text_lines = vim.split(content, "\n") for _, text_line in ipairs(text_lines) do table.insert(lines, Line:new({ { "> " .. text_line } })) end return lines end ---@type AvanteLLMToolFunc<ThinkingInput> function M.func(input, opts) local on_complete = opts.on_complete if not on_complete then return false, "on_complete not provided" end on_complete(true, nil) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/undo_edit.lua
Lua
local Path = require("plenary.path") local Base = require("avante.llm_tools.base") local Helpers = require("avante.llm_tools.helpers") local Utils = require("avante.utils") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "undo_edit" M.description = "The undo_edit tool allows you to revert the last edit made to a file." function M.enabled() return require("avante.config").mode == "agentic" end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = "The path to the file whose last edit should be undone", type = "string", }, }, usage = { path = "The path to the file whose last edit should be undone", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "True if the edit was undone successfully, false otherwise", type = "boolean", }, { name = "error", description = "Error message if the edit was not undone successfully", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string }> function M.func(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete local session_ctx = opts.session_ctx if not on_complete then return false, "on_complete not provided" end if on_log then on_log("path: " .. input.path) end local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return false, "File not found: " .. abs_path end if not Path:new(abs_path):is_file() then return false, "Path is not a file: " .. abs_path end local bufnr, err = Helpers.get_bufnr(abs_path) if err then return false, err end local winid = Utils.get_winid(bufnr) Helpers.confirm("Are you sure you want to undo edit this file?", function(ok, reason) if not ok then on_complete(false, "User declined, reason: " .. (reason or "unknown")) return end vim.api.nvim_win_call(winid, function() vim.cmd("noautocmd undo") end) vim.api.nvim_buf_call(bufnr, function() vim.cmd("noautocmd write") end) if session_ctx then Helpers.mark_as_not_viewed(input.path, session_ctx) end on_complete(true, nil) end, { focus = true }, session_ctx, M.name) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/view.lua
Lua
local Path = require("plenary.path") local Utils = require("avante.utils") local Base = require("avante.llm_tools.base") local Helpers = require("avante.llm_tools.helpers") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "view" M.description = [[Reads the content of the given file in the project. - Never attempt to read a path that hasn't been previously mentioned. IMPORTANT NOTE: If the file content exceeds a certain size, the returned content will be truncated, and `is_truncated` will be set to true. If `is_truncated` is true, please use the `start_line` parameter and `end_line` parameter to call this `view` tool again. ]] M.enabled = function(opts) if opts.user_input:match("@read_global_file") then return false end for _, message in ipairs(opts.history_messages) do if message.role == "user" then local content = message.content if type(content) == "string" and content:match("@read_global_file") then return false end if type(content) == "table" then for _, item in ipairs(content) do if type(item) == "string" and item:match("@read_global_file") then return false end end end end end return true end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", description = [[The relative path of the file to read. This path should never be absolute, and the first component of the path should always be a root directory in a project. <example> If the project has the following root directories: - directory1 - directory2 If you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`. If you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`. </example>]], type = "string", }, { name = "start_line", description = "Optional line number to start reading on (1-based index)", type = "integer", optional = true, }, { name = "end_line", description = "Optional line number to end reading on (1-based index, inclusive)", type = "integer", optional = true, }, }, usage = { path = "The path to the file in the current project scope", start_line = "The start line of the view range, 1-indexed", end_line = "The end line of the view range, 1-indexed, and -1 for the end line means read to the end of the file", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "content", description = "Contents of the file", type = "string", }, { name = "error", description = "Error message if the file was not read successfully", type = "string", optional = true, }, } ---@type AvanteLLMToolFunc<{ path: string, start_line?: integer, end_line?: integer }> function M.func(input, opts) local on_log = opts.on_log local on_complete = opts.on_complete if not input.path then return false, "path is required" end if on_log then on_log("path: " .. input.path) end local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if not Path:new(abs_path):exists() then return false, "Path not found: " .. abs_path end if Path:new(abs_path):is_dir() then return false, "Path is a directory: " .. abs_path end local file = io.open(abs_path, "r") if not file then return false, "file not found: " .. abs_path end local lines = Utils.read_file_from_buf_or_disk(abs_path) local start_line = input.start_line local end_line = input.end_line if start_line and end_line and lines then lines = vim.list_slice(lines, start_line, end_line) end local truncated_lines = {} local is_truncated = false local size = 0 for _, line in ipairs(lines or {}) do size = size + #line if size > 2048 * 100 then is_truncated = true break end table.insert(truncated_lines, line) end local total_line_count = lines and #lines or 0 local content = truncated_lines and table.concat(truncated_lines, "\n") or "" local result = vim.json.encode({ content = content, total_line_count = total_line_count, is_truncated = is_truncated, }) if not on_complete then return result, nil end on_complete(result, nil) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/write_to_file.lua
Lua
local Utils = require("avante.utils") local Base = require("avante.llm_tools.base") local Helpers = require("avante.llm_tools.helpers") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "write_to_file" M.description = "Request to write content to a file at the specified path. If the file exists, it will be overwritten with the provided content. If the file doesn't exist, it will be created. This tool will automatically create any directories needed to write the file." M.support_streaming = false function M.enabled() return require("avante.config").mode == "agentic" and not require("avante.config").behaviour.enable_fastapply end ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "path", get_description = function() local res = ("The path of the file to write to (relative to the current working directory {{cwd}})"):gsub( "{{cwd}}", Utils.get_project_root() ) return res end, type = "string", }, { --- IMPORTANT: Using "the_content" instead of "content" is to avoid LLM streaming generating function parameters in alphabetical order, which would result in generating "path" after "content", making it impossible to achieve a stream diff view. name = "the_content", description = "The content to write to the file. ALWAYS provide the COMPLETE intended content of the file, without any truncation or omissions. You MUST include ALL parts of the file, even if they haven't been modified.", type = "string", }, }, usage = { path = "File path here", the_content = "File content here", }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "Whether the file was created successfully", type = "boolean", }, { name = "error", description = "Error message if the file was not created successfully", type = "string", optional = true, }, } --- IMPORTANT: Using "the_content" instead of "content" is to avoid LLM streaming generating function parameters in alphabetical order, which would result in generating "path" after "content", making it impossible to achieve a stream diff view. ---@type AvanteLLMToolFunc<{ path: string, the_content?: string }> function M.func(input, opts) local abs_path = Helpers.get_abs_path(input.path) if not Helpers.has_permission_to_access(abs_path) then return false, "No permission to access path: " .. abs_path end if input.the_content == nil then return false, "the_content not provided" end if type(input.the_content) ~= "string" then input.the_content = vim.json.encode(input.the_content) end if Utils.count_lines(input.the_content) == 1 then Utils.debug("Trimming escapes from content") input.the_content = Utils.trim_escapes(input.the_content) end -- Remove trailing spaces from each line input.the_content = Utils.remove_trailing_spaces(input.the_content) local old_lines = Utils.read_file_from_buf_or_disk(abs_path) local old_content = table.concat(old_lines or {}, "\n") local str_replace = require("avante.llm_tools.str_replace") local new_input = { path = input.path, old_str = old_content, new_str = input.the_content, } return str_replace.func(new_input, opts) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/llm_tools/write_todos.lua
Lua
local Base = require("avante.llm_tools.base") ---@class AvanteLLMTool local M = setmetatable({}, Base) M.name = "write_todos" M.description = "Write TODOs to the current task" ---@type AvanteLLMToolParam M.param = { type = "table", fields = { { name = "todos", description = "The entire TODOs array to write", type = "array", items = { name = "items", type = "object", fields = { { name = "id", description = "The ID of the TODO", type = "string", }, { name = "content", description = "The content of the TODO", type = "string", }, { name = "status", description = "The status of the TODO", type = "string", choices = { "todo", "doing", "done", "cancelled" }, }, { name = "priority", description = "The priority of the TODO", type = "string", choices = { "low", "medium", "high" }, }, }, }, }, }, } ---@type AvanteLLMToolReturn[] M.returns = { { name = "success", description = "Whether the TODOs were added successfully", type = "boolean", }, { name = "error", description = "Error message if the TODOs could not be updated", type = "string", optional = true, }, } M.on_render = function() return {} end ---@type AvanteLLMToolFunc<{ todos: avante.TODO[] }> function M.func(input, opts) local on_complete = opts.on_complete local sidebar = require("avante").get() if not sidebar then return false, "Avante sidebar not found" end local todos = input.todos if not todos or #todos == 0 then return false, "No todos provided" end sidebar:update_todos(todos) if on_complete then on_complete(true, nil) return nil, nil end return true, nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/model_selector.lua
Lua
local Utils = require("avante.utils") local Providers = require("avante.providers") local Config = require("avante.config") local Selector = require("avante.ui.selector") ---@class avante.ModelSelector local M = {} M.list_models_invoked = {} M.list_models_returned = {} local list_models_cached_result = {} ---@param provider_name string ---@param provider_cfg table ---@return table local function create_model_entries(provider_name, provider_cfg) local res = {} if provider_cfg.list_models and provider_cfg.__inherited_from == nil then local models if type(provider_cfg.list_models) == "function" then if M.list_models_invoked[provider_cfg.list_models] then return {} end M.list_models_invoked[provider_cfg.list_models] = true local cached_result = list_models_cached_result[provider_cfg.list_models] if cached_result then models = cached_result else models = provider_cfg:list_models() list_models_cached_result[provider_cfg.list_models] = models end else if M.list_models_returned[provider_cfg.list_models] then return {} end M.list_models_returned[provider_cfg.list_models] = true models = provider_cfg.list_models end if models then -- If list_models is defined, use it to create entries res = vim .iter(models) :map( function(model) return { name = model.name or model.id, display_name = model.display_name or model.name or model.id, provider_name = provider_name, model = model.id, } end ) :totable() end end if provider_cfg.model then local seen = vim.iter(res):find(function(item) return item.model == provider_cfg.model end) if not seen then table.insert(res, { name = provider_cfg.display_name or (provider_name .. "/" .. provider_cfg.model), display_name = provider_cfg.display_name or (provider_name .. "/" .. provider_cfg.model), provider_name = provider_name, model = provider_cfg.model, }) end end if provider_cfg.model_names then for _, model_name in ipairs(provider_cfg.model_names) do local seen = vim.iter(res):find(function(item) return item.model == model_name end) if not seen then table.insert(res, { name = provider_cfg.display_name or (provider_name .. "/" .. model_name), display_name = provider_cfg.display_name or (provider_name .. "/" .. model_name), provider_name = provider_name, model = model_name, }) end end end return res end function M.open() M.list_models_invoked = {} M.list_models_returned = {} local models = {} -- Collect models from providers for provider_name, _ in pairs(Config.providers) do local provider_cfg = Providers[provider_name] if provider_cfg.hide_in_model_selector then goto continue end if not provider_cfg.is_env_set() then goto continue end local entries = create_model_entries(provider_name, provider_cfg) models = vim.list_extend(models, entries) ::continue:: end -- Sort models by name for stable display table.sort(models, function(a, b) return (a.name or "") < (b.name or "") end) if #models == 0 then Utils.warn("No models available in config") return end local items = vim .iter(models) :map(function(item) return { id = item.name, title = item.name, } end) :totable() local current_model = Config.providers[Config.provider].model local default_item = vim.iter(models):find( function(item) return item.model == current_model and item.provider_name == Config.provider end ) local function on_select(item_ids) if not item_ids then return end local choice = vim.iter(models):find(function(item) return item.name == item_ids[1] end) if not choice then return end -- Switch provider if needed if choice.provider_name ~= Config.provider then require("avante.providers").refresh(choice.provider_name) end -- Update config with new model Config.override({ providers = { [choice.provider_name] = vim.tbl_deep_extend( "force", Config.get_provider_config(choice.provider_name), { model = choice.model } ), }, }) local provider_cfg = Providers[choice.provider_name] if provider_cfg then provider_cfg.model = choice.model end Utils.info("Switched to model: " .. choice.name) -- Persist last used provider and model Config.save_last_model(choice.model, choice.provider_name) end local selector = Selector:new({ title = "Select Avante Model", items = items, default_item_id = default_item and default_item.name or nil, provider = Config.selector.provider, provider_opts = Config.selector.provider_opts, on_select = on_select, get_preview_content = function(item_id) local model = vim.iter(models):find(function(item) return item.name == item_id end) if not model then return "", "markdown" end return model.name, "markdown" end, }) selector:open() end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/path.lua
Lua
local fn = vim.fn local Utils = require("avante.utils") local Path = require("plenary.path") local Scan = require("plenary.scandir") local Config = require("avante.config") ---@class avante.Path ---@field history_path Path ---@field cache_path Path ---@field data_path Path local P = {} ---@param bufnr integer | nil ---@return string dirname local function generate_project_dirname_in_storage(bufnr) local project_root = Utils.root.get({ buf = bufnr, }) -- Replace path separators with double underscores local path_with_separators = string.gsub(project_root, "/", "__") -- Replace other non-alphanumeric characters with single underscores local dirname = string.gsub(path_with_separators, "[^A-Za-z0-9._]", "_") return tostring(Path:new("projects"):joinpath(dirname)) end local function filepath_to_filename(filepath) return tostring(filepath):sub(tostring(filepath:parent()):len() + 2) end -- History path local History = {} function History.get_history_dir(bufnr) local dirname = generate_project_dirname_in_storage(bufnr) local history_dir = Path:new(Config.history.storage_path):joinpath(dirname):joinpath("history") if not history_dir:exists() then history_dir:mkdir({ parents = true }) local metadata_filepath = history_dir:joinpath("metadata.json") local metadata = { project_root = Utils.root.get({ buf = bufnr, }), } metadata_filepath:write(vim.json.encode(metadata), "w") end return history_dir end ---@return avante.ChatHistory[] function History.list(bufnr) local history_dir = History.get_history_dir(bufnr) local files = vim.fn.glob(tostring(history_dir:joinpath("*.json")), true, true) local latest_filename = History.get_latest_filename(bufnr, false) local res = {} for _, filename in ipairs(files) do if not filename:match("metadata.json") then local filepath = Path:new(filename) local history = History.from_file(filepath) if history then table.insert(res, history) end end end --- sort by timestamp --- sort by latest_filename table.sort(res, function(a, b) local H = require("avante.history") if a.filename == latest_filename then return true end if b.filename == latest_filename then return false end local a_messages = H.get_history_messages(a) local b_messages = H.get_history_messages(b) local timestamp_a = #a_messages > 0 and a_messages[#a_messages].timestamp or a.timestamp local timestamp_b = #b_messages > 0 and b_messages[#b_messages].timestamp or b.timestamp return timestamp_a > timestamp_b end) return res end -- Get a chat history file name given a buffer ---@param bufnr integer ---@param new boolean ---@return Path function History.get_latest_filepath(bufnr, new) local history_dir = History.get_history_dir(bufnr) local filename = History.get_latest_filename(bufnr, new) return history_dir:joinpath(filename) end function History.get_filepath(bufnr, filename) local history_dir = History.get_history_dir(bufnr) return history_dir:joinpath(filename) end function History.get_metadata_filepath(bufnr) local history_dir = History.get_history_dir(bufnr) return history_dir:joinpath("metadata.json") end function History.get_latest_filename(bufnr, new) local history_dir = History.get_history_dir(bufnr) local filename local metadata_filepath = History.get_metadata_filepath(bufnr) if metadata_filepath:exists() and not new then local metadata_content = metadata_filepath:read() local metadata = vim.json.decode(metadata_content) filename = metadata.latest_filename end if not filename or filename == "" then local pattern = tostring(history_dir:joinpath("*.json")) local files = vim.fn.glob(pattern, true, true) filename = #files .. ".json" if #files > 0 and not new then filename = (#files - 1) .. ".json" end end return filename end function History.save_latest_filename(bufnr, filename) local metadata_filepath = History.get_metadata_filepath(bufnr) local metadata = {} if metadata_filepath:exists() then local metadata_content = metadata_filepath:read() metadata = vim.json.decode(metadata_content) end if metadata.project_root == nil then metadata.project_root = Utils.root.get({ buf = bufnr, }) end metadata.latest_filename = filename metadata_filepath:write(vim.json.encode(metadata), "w") end ---@param bufnr integer function History.new(bufnr) local filepath = History.get_latest_filepath(bufnr, true) ---@type avante.ChatHistory local history = { title = "untitled", timestamp = Utils.get_timestamp(), entries = {}, messages = {}, todos = {}, filename = filepath_to_filename(filepath), } return history end ---Attempts to load chat history from a given file ---@param filepath Path ---@return avante.ChatHistory|nil function History.from_file(filepath) if filepath:exists() then local content = filepath:read() if content ~= nil then local decode_ok, history = pcall(vim.json.decode, content) if decode_ok and type(history) == "table" then if not history.title or type(history.title) ~= "string" then history.title = "untitled" end if not history.timestamp or history.timestamp ~= "string" then history.timestamp = Utils.get_timestamp() end -- TODO: sanitize individual entries of the lists below as well. if not vim.islist(history.entries) then history.entries = {} end if not vim.islist(history.messages) then history.messages = {} end if not vim.islist(history.todos) then history.todos = {} end ---@cast history avante.ChatHistory history.filename = filepath_to_filename(filepath) return history end end end end -- Loads the chat history for the given buffer. ---@param bufnr integer ---@param filename string? ---@return avante.ChatHistory function History.load(bufnr, filename) local history_filepath = filename and History.get_filepath(bufnr, filename) or History.get_latest_filepath(bufnr, false) return History.from_file(history_filepath) or History.new(bufnr) end -- Saves the chat history for the given buffer. ---@param bufnr integer ---@param history avante.ChatHistory function History.save(bufnr, history) local history_filepath = History.get_filepath(bufnr, history.filename) history_filepath:write(vim.json.encode(history), "w") History.save_latest_filename(bufnr, history.filename) end --- Deletes a specific chat history file. ---@param bufnr integer ---@param filename string function History.delete(bufnr, filename) local history_filepath = History.get_filepath(bufnr, filename) if history_filepath:exists() then local was_latest = (filename == History.get_latest_filename(bufnr, false)) history_filepath:rm() if was_latest then local remaining_histories = History.list(bufnr) -- This list is sorted by recency if #remaining_histories > 0 then History.save_latest_filename(bufnr, remaining_histories[1].filename) else -- No histories left, clear the latest_filename from metadata local metadata_filepath = History.get_metadata_filepath(bufnr) if metadata_filepath:exists() then local metadata_content = metadata_filepath:read() local metadata = vim.json.decode(metadata_content) metadata.latest_filename = nil -- Or "", depending on desired behavior for an empty latest metadata_filepath:write(vim.json.encode(metadata), "w") end end end else Utils.warn("History file not found: " .. tostring(history_filepath)) end end P.history = History ---@return table[] List of projects with their information function P.list_projects() local projects_dir = Path:new(Config.history.storage_path):joinpath("projects") if not projects_dir:exists() then return {} end local projects = {} local dirs = Scan.scan_dir(tostring(projects_dir), { depth = 1, add_dirs = true, only_dirs = true }) for _, dir_path in ipairs(dirs) do local project_dir = Path:new(dir_path) local history_dir = project_dir:joinpath("history") local metadata_file = history_dir:joinpath("metadata.json") local project_root = "" if metadata_file:exists() then local content = metadata_file:read() if content then local metadata = vim.json.decode(content) if metadata and metadata.project_root then project_root = metadata.project_root end end end -- Skip if project_root is empty if project_root == "" then goto continue end -- Count history files local history_count = 0 if history_dir:exists() then local history_files = vim.fn.glob(tostring(history_dir:joinpath("*.json")), true, true) for _, file in ipairs(history_files) do if not file:match("metadata.json") then history_count = history_count + 1 end end end table.insert(projects, { name = filepath_to_filename(project_dir), root = project_root, history_count = history_count, directory = tostring(project_dir), }) ::continue:: end -- Sort by history count (most active projects first) table.sort(projects, function(a, b) return a.history_count > b.history_count end) return projects end -- Prompt path local Prompt = {} -- Given a mode, return the file name for the custom prompt. ---@param mode AvanteLlmMode ---@return string function Prompt.get_custom_prompts_filepath(mode) return string.format("custom.%s.avanterules", mode) end function Prompt.get_builtin_prompts_filepath(mode) return string.format("%s.avanterules", mode) end ---@class AvanteTemplates ---@field initialize fun(cache_directory: string, project_directory: string): nil ---@field render fun(template: string, context: AvanteTemplateOptions): string local _templates_lib = nil Prompt.custom_modes = { agentic = true, legacy = true, editing = true, suggesting = true, } Prompt.custom_prompts_contents = {} ---@param project_root string ---@return string templates_dir function Prompt.get_templates_dir(project_root) if not P.available() then error("Make sure to build avante (missing avante_templates)", 2) end -- get root directory of given bufnr local directory = Path:new(project_root) if Utils.get_os_name() == "windows" then directory = Path:new(directory:absolute():gsub("^%a:", "")[1]) end ---@cast directory Path ---@type Path local cache_prompt_dir = P.cache_path:joinpath(directory) if not cache_prompt_dir:exists() then cache_prompt_dir:mkdir({ parents = true }) end local function find_rules(dir) if not dir then return end if vim.fn.isdirectory(dir) ~= 1 then return end local scanner = Scan.scan_dir(dir, { depth = 1, add_dirs = true }) for _, entry in ipairs(scanner) do local file = Path:new(entry) if file:is_file() then local pieces = vim.split(entry, "/") local piece = pieces[#pieces] local mode = piece:match("([^.]+)%.avanterules$") if not mode or not Prompt.custom_modes[mode] then goto continue end if Prompt.custom_prompts_contents[mode] == nil then Utils.info(string.format("Using %s as %s system prompt", entry, mode)) Prompt.custom_prompts_contents[mode] = file:read() end end ::continue:: end end if Config.rules.project_dir then local project_rules_path = Path:new(Config.rules.project_dir) if not project_rules_path:is_absolute() then project_rules_path = directory:joinpath(project_rules_path) end find_rules(tostring(project_rules_path)) end find_rules(Config.rules.global_dir) find_rules(directory:absolute()) local source_dir = Path:new(debug.getinfo(1).source:match("@?(.*/)"):gsub("/lua/avante/path.lua$", "") .. "templates") -- Copy built-in templates to cache directory (only if not overridden by user templates) source_dir:copy({ destination = cache_prompt_dir, recursive = true, override = true, }) -- Check for override prompt local override_prompt_dir = Config.override_prompt_dir if override_prompt_dir then -- Handle the case where override_prompt_dir is a function if type(override_prompt_dir) == "function" then local ok, result = pcall(override_prompt_dir) if ok and result then override_prompt_dir = result end end if override_prompt_dir then local user_template_path = Path:new(override_prompt_dir) if user_template_path:exists() then local user_scanner = Scan.scan_dir(user_template_path:absolute(), { depth = 1, add_dirs = false }) for _, entry in ipairs(user_scanner) do local file = Path:new(entry) if file:is_file() then local pieces = vim.split(entry, "/") local piece = pieces[#pieces] if piece == "base.avanterules" then local content = file:read() if not content:match("{%% block extra_prompt %%}[%s,\\n]*{%% endblock %%}") then file:write("{% block extra_prompt %}\n", "a") file:write("{% endblock %}\n", "a") end if not content:match("{%% block custom_prompt %%}[%s,\\n]*{%% endblock %%}") then file:write("{% block custom_prompt %}\n", "a") file:write("{% endblock %}", "a") end end file:copy({ destination = cache_prompt_dir:joinpath(piece) }) end end end end end vim.iter(Prompt.custom_prompts_contents):filter(function(_, v) return v ~= nil end):each(function(k, v) local orig_file = cache_prompt_dir:joinpath(Prompt.get_builtin_prompts_filepath(k)) local orig_content = orig_file:read() local f = cache_prompt_dir:joinpath(Prompt.get_custom_prompts_filepath(k)) f:write(orig_content, "w") f:write("{% block custom_prompt -%}\n", "a") f:write(v, "a") f:write("\n{%- endblock %}", "a") end) local dir = cache_prompt_dir:absolute() return dir end ---@param mode AvanteLlmMode ---@return string function Prompt.get_filepath(mode) if Prompt.custom_prompts_contents[mode] ~= nil then return Prompt.get_custom_prompts_filepath(mode) end return Prompt.get_builtin_prompts_filepath(mode) end ---@param path string ---@param opts AvanteTemplateOptions function Prompt.render_file(path, opts) return _templates_lib.render(path, opts) end ---@param mode AvanteLlmMode ---@param opts AvanteTemplateOptions function Prompt.render_mode(mode, opts) local filepath = Prompt.get_filepath(mode) return _templates_lib.render(filepath, opts) end function Prompt.initialize(cache_directory, project_directory) _templates_lib.initialize(cache_directory, project_directory) end P.prompts = Prompt local RepoMap = {} -- Get a chat history file name given a buffer ---@param project_root string ---@param ext string ---@return string function RepoMap.filename(project_root, ext) -- Replace path separators with double underscores local path_with_separators = fn.substitute(project_root, "/", "__", "g") -- Replace other non-alphanumeric characters with single underscores return fn.substitute(path_with_separators, "[^A-Za-z0-9._]", "_", "g") .. "." .. ext .. ".repo_map.json" end function RepoMap.get(project_root, ext) return Path:new(P.data_path):joinpath(RepoMap.filename(project_root, ext)) end function RepoMap.save(project_root, ext, data) local file = RepoMap.get(project_root, ext) file:write(vim.json.encode(data), "w") end function RepoMap.load(project_root, ext) local file = RepoMap.get(project_root, ext) if file:exists() then local content = file:read() return content ~= nil and vim.json.decode(content) or {} end return nil end P.repo_map = RepoMap ---@return AvanteTemplates|nil function P._init_templates_lib() if _templates_lib ~= nil then return _templates_lib end local ok, module = pcall(require, "avante_templates") ---@cast module AvanteTemplates ---@cast ok boolean if not ok then return nil end _templates_lib = module return _templates_lib end function P.setup() local history_path = Path:new(Config.history.storage_path) if not history_path:exists() then history_path:mkdir({ parents = true }) end P.history_path = history_path local cache_path = Path:new(Utils.join_paths(vim.fn.stdpath("cache"), "avante")) if not cache_path:exists() then cache_path:mkdir({ parents = true }) end P.cache_path = cache_path local data_path = Path:new(Utils.join_paths(vim.fn.stdpath("data"), "avante")) if not data_path:exists() then data_path:mkdir({ parents = true }) end P.data_path = data_path vim.defer_fn(P._init_templates_lib, 1000) end function P.available() return P._init_templates_lib() ~= nil end function P.clear() P.cache_path:rm({ recursive = true }) P.history_path:rm({ recursive = true }) if not P.cache_path:exists() then P.cache_path:mkdir({ parents = true }) end if not P.history_path:exists() then P.history_path:mkdir({ parents = true }) end end return P
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/azure.lua
Lua
---@class AvanteAzureExtraRequestBody ---@field temperature number ---@field max_completion_tokens number ---@field reasoning_effort? string ---@class AvanteAzureProvider: AvanteDefaultBaseProvider ---@field deployment string ---@field api_version string ---@field extra_request_body AvanteAzureExtraRequestBody local Utils = require("avante.utils") local P = require("avante.providers") local O = require("avante.providers").openai ---@class AvanteProviderFunctor local M = {} M.api_key_name = "AZURE_OPENAI_API_KEY" -- Inherit from OpenAI class setmetatable(M, { __index = O }) ---@param prompt_opts AvantePromptOptions ---@return AvanteCurlOutput|nil function M:parse_curl_args(prompt_opts) local provider_conf, request_body = P.parse_config(self) local disable_tools = provider_conf.disable_tools or false local headers = { ["Content-Type"] = "application/json", } if P.env.require_api_key(provider_conf) then local api_key = self.parse_api_key() if not api_key then Utils.error("Azure: API key is not set. Please set " .. M.api_key_name) return nil end if provider_conf.entra then headers["Authorization"] = "Bearer " .. api_key else headers["api-key"] = api_key end end self.set_allowed_params(provider_conf, request_body) local tools = nil if not disable_tools and prompt_opts.tools then tools = {} for _, tool in ipairs(prompt_opts.tools) do table.insert(tools, self:transform_tool(tool)) end end return { url = Utils.url_join( provider_conf.endpoint, "/openai/deployments/" ---@diagnostic disable-next-line: undefined-field .. provider_conf.deployment .. "/chat/completions?api-version=" ---@diagnostic disable-next-line: undefined-field .. provider_conf.api_version ), proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, headers = Utils.tbl_override(headers, self.extra_headers), body = vim.tbl_deep_extend("force", { messages = self:parse_messages(prompt_opts), stream = true, tools = tools, }, request_body), } end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/bedrock.lua
Lua
local Utils = require("avante.utils") local P = require("avante.providers") ---@class AvanteBedrockProviderFunctor local M = {} M.api_key_name = "BEDROCK_KEYS" ---@class AWSCreds ---@field access_key_id string ---@field secret_access_key string ---@field session_token string local AWSCreds = {} M = setmetatable(M, { __index = function(_, k) local model_handler = M.load_model_handler() return model_handler[k] end, }) function M.setup() -- Check if curl supports AWS signature v4 if not M.check_curl_supports_aws_sig() then Utils.error( "Your curl version doesn't support AWS signature v4 properly. Please upgrade to curl 8.10.0 or newer.", { once = true, title = "Avante Bedrock" } ) return false end return true end --- Detect the model type from model ID or ARN ---@param model string The model ID or inference profile ARN ---@return string The detected model type (e.g., "claude") local function detect_model_type(model) -- Check for Claude/Anthropic models if model:match("anthropic") or model:match("claude") then return "claude" end -- For inference profile ARNs, default to claude -- as it's the most common use case for Bedrock inference profiles if model:match("^arn:aws:bedrock:") then return "claude" end return model end function M.load_model_handler() local provider_conf, _ = P.parse_config(P["bedrock"]) local bedrock_model = detect_model_type(provider_conf.model) local ok, model_module = pcall(require, "avante.providers.bedrock." .. bedrock_model) if ok then return model_module end local error_msg = "Bedrock model handler not found: " .. bedrock_model error(error_msg) end function M.is_env_set() local provider_conf, _ = P.parse_config(P["bedrock"]) ---@diagnostic disable-next-line: undefined-field local profile = provider_conf.aws_profile if profile ~= nil and profile ~= "" then -- AWS CLI is only needed if aws_profile is used for authoriztion if not M.check_aws_cli_installed() then Utils.error( "AWS CLI not found. Please install it to use the Bedrock provider: https://aws.amazon.com/cli/", { once = true, title = "Avante Bedrock" } ) return false end return true end local value = Utils.environment.parse(M.api_key_name) return value ~= nil end function M:parse_messages(prompt_opts) local model_handler = M.load_model_handler() return model_handler.parse_messages(self, prompt_opts) end function M:parse_response(ctx, data_stream, event_state, opts) local model_handler = M.load_model_handler() return model_handler.parse_response(self, ctx, data_stream, event_state, opts) end function M:transform_tool(tool) local model_handler = M.load_model_handler() return model_handler.transform_tool(self, tool) end function M:build_bedrock_payload(prompt_opts, request_body) local model_handler = M.load_model_handler() return model_handler.build_bedrock_payload(self, prompt_opts, request_body) end local function parse_exception(data) local exceptions_found = {} local bedrock_match = data:gmatch("exception(%b{})") for bedrock_data_match in bedrock_match do local jsn = vim.json.decode(bedrock_data_match) table.insert(exceptions_found, "- " .. jsn.message) end return exceptions_found end function M:parse_stream_data(ctx, data, opts) -- @NOTE: Decode and process Bedrock response -- Each response contains a Base64-encoded `bytes` field, which is decoded into JSON. -- The `type` field in the decoded JSON determines how the response is handled. local bedrock_match = data:gmatch("event(%b{})") for bedrock_data_match in bedrock_match do local jsn = vim.json.decode(bedrock_data_match) local data_stream = vim.base64.decode(jsn.bytes) local json = vim.json.decode(data_stream) self:parse_response(ctx, data_stream, json.type, opts) end local exceptions = parse_exception(data) if #exceptions > 0 then Utils.debug("Bedrock exceptions: ", vim.fn.json_encode(exceptions)) if opts.on_chunk then opts.on_chunk("\n**Exception caught**\n\n") opts.on_chunk(table.concat(exceptions, "\n")) end vim.schedule(function() opts.on_stop({ reason = "error" }) end) end end function M:parse_response_without_stream(data, event_state, opts) if opts.on_chunk == nil then return end local exceptions = parse_exception(data) if #exceptions > 0 then opts.on_chunk("\n**Exception caught**\n\n") opts.on_chunk(table.concat(exceptions, "\n")) end vim.schedule(function() opts.on_stop({ reason = "complete" }) end) end ---@param prompt_opts AvantePromptOptions ---@return AvanteCurlOutput|nil function M:parse_curl_args(prompt_opts) local provider_conf, request_body = P.parse_config(self) local access_key_id, secret_access_key, session_token, region ---@diagnostic disable-next-line: undefined-field local profile = provider_conf.aws_profile if profile ~= nil and profile ~= "" then ---@diagnostic disable-next-line: undefined-field region = provider_conf.aws_region if not region or region == "" then Utils.error("Bedrock: no aws_region specified in bedrock config") return nil end local awsCreds = M:get_aws_credentials(region, profile) access_key_id = awsCreds.access_key_id secret_access_key = awsCreds.secret_access_key session_token = awsCreds.session_token else -- try to parse credentials from api key local api_key = self.parse_api_key() if api_key ~= nil then local parts = vim.split(api_key, ",") access_key_id = parts[1] secret_access_key = parts[2] region = parts[3] session_token = parts[4] else Utils.error("Bedrock: API key not set correctly") return nil end end local endpoint if provider_conf.endpoint then -- Use custom endpoint if provided endpoint = provider_conf.endpoint else -- URL encode the model ID (required for ARNs which contain colons and slashes) local encoded_model = provider_conf.model:gsub( "([^%w%-_.~])", function(c) return string.format("%%%02X", string.byte(c)) end ) -- Default to AWS Bedrock endpoint endpoint = string.format( "https://bedrock-runtime.%s.amazonaws.com/model/%s/invoke-with-response-stream", region, encoded_model ) end local headers = { ["Content-Type"] = "application/json", } if session_token and session_token ~= "" then headers["x-amz-security-token"] = session_token end local body_payload = self:build_bedrock_payload(prompt_opts, request_body) local rawArgs = { "--aws-sigv4", string.format("aws:amz:%s:bedrock", region), "--user", string.format("%s:%s", access_key_id, secret_access_key), } return { url = endpoint, proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, headers = Utils.tbl_override(headers, self.extra_headers), body = body_payload, rawArgs = rawArgs, } end function M.on_error(result) if not result.body then return Utils.error("API request failed with status " .. result.status, { once = true, title = "Avante" }) end local ok, body = pcall(vim.json.decode, result.body) if not (ok and body and body.error) then return Utils.error("Failed to parse error response", { once = true, title = "Avante" }) end local error_msg = body.error.message Utils.error(error_msg, { once = true, title = "Avante" }) end --- Run a command and capture its output. Time out after 10 seconds ---@param ... string Command and its arguments ---@return string stdout ---@return integer exit code (0 for success, 124 for timeout, etc) local function run_command(...) local args = { ... } local result = vim.system(args, { text = true }):wait(10000) -- Wait up to 10 seconds -- result.code will be 124 if the command times out. return result.stdout, result.code end --- get_aws_credentials returns aws credentials using the aws cli ---@param region string ---@param profile string ---@return AWSCreds function M:get_aws_credentials(region, profile) local awsCreds = { access_key_id = "", secret_access_key = "", session_token = "", } local args = { "aws", "configure", "export-credentials" } if profile and profile ~= "" then table.insert(args, "--profile") table.insert(args, profile) end if region and region ~= "" then table.insert(args, "--region") table.insert(args, region) end -- run aws configure export-credentials and capture the json output local start_time = vim.uv.hrtime() local output, exit_code = run_command(unpack(args)) if exit_code == 0 then local credentials = vim.json.decode(output) awsCreds.access_key_id = credentials.AccessKeyId awsCreds.secret_access_key = credentials.SecretAccessKey awsCreds.session_token = credentials.SessionToken else print("Failed to run AWS command") end local end_time = vim.uv.hrtime() local duration_ms = (end_time - start_time) / 1000000 Utils.debug(string.format("AWS credentials fetch took %.2f ms", duration_ms)) return awsCreds end --- check_aws_cli_installed returns true when the aws cli is installed --- @return boolean function M.check_aws_cli_installed() local _, exit_code = run_command("aws", "--version") return exit_code == 0 end --- check_curl_version_supports_aws_sig checks if the given curl version supports aws sigv4 correctly --- we require at least version 8.10.0 because it contains critical fixes for aws sigv4 support --- https://curl.se/ch/8.10.0.html --- @param version_string string The curl version string to check --- @return boolean function M.check_curl_version_supports_aws_sig(version_string) -- Extract the version number local major, minor = version_string:match("curl (%d+)%.(%d+)") if major and minor then major = tonumber(major) minor = tonumber(minor) -- Check if the version is at least 8.10 if major > 8 or (major == 8 and minor >= 10) then return true end end return false end --- check_curl_supports_aws_sig returns true when the installed curl version supports aws sigv4 --- @return boolean function M.check_curl_supports_aws_sig() local output, exit_code = run_command("curl", "--version") if exit_code ~= 0 then return false end -- Get first line of output which contains version info local version_string = output:match("^[^\n]+") return M.check_curl_version_supports_aws_sig(version_string) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/bedrock/claude.lua
Lua
---@class AvanteBedrockClaudeTextMessage ---@field type "text" ---@field text string --- ---@class AvanteBedrockClaudeMessage ---@field role "user" | "assistant" ---@field content [AvanteBedrockClaudeTextMessage][] local P = require("avante.providers") local Claude = require("avante.providers.claude") ---@class AvanteBedrockModelHandler local M = {} M.support_prompt_caching = false M.role_map = { user = "user", assistant = "assistant", } M.is_disable_stream = Claude.is_disable_stream M.parse_messages = Claude.parse_messages M.parse_response = Claude.parse_response M.transform_tool = Claude.transform_tool M.transform_anthropic_usage = Claude.transform_anthropic_usage ---@param provider AvanteProviderFunctor ---@param prompt_opts AvantePromptOptions ---@param request_body table ---@return table function M.build_bedrock_payload(provider, prompt_opts, request_body) local system_prompt = prompt_opts.system_prompt or "" local messages = provider:parse_messages(prompt_opts) local max_tokens = request_body.max_tokens or 2000 local provider_conf, _ = P.parse_config(provider) local disable_tools = provider_conf.disable_tools or false local tools = {} if not disable_tools and prompt_opts.tools then for _, tool in ipairs(prompt_opts.tools) do table.insert(tools, provider:transform_tool(tool)) end end local payload = { anthropic_version = "bedrock-2023-05-31", max_tokens = max_tokens, messages = messages, tools = tools, system = system_prompt, } return vim.tbl_deep_extend("force", payload, request_body or {}) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/claude.lua
Lua
local Utils = require("avante.utils") local Clipboard = require("avante.clipboard") local P = require("avante.providers") local HistoryMessage = require("avante.history.message") local JsonParser = require("avante.libs.jsonparser") local Config = require("avante.config") local Path = require("plenary.path") local pkce = require("avante.auth.pkce") local curl = require("plenary.curl") ---@class AvanteAnthropicProvider : AvanteDefaultBaseProvider ---@field auth_type "api" | "max" ---@class ClaudeAuthToken ---@field access_token string ---@field refresh_token string ---@field expires_at integer ---@class AvanteProviderFunctor local M = {} local claude_path = vim.fn.stdpath("data") .. "/avante/claude-auth.json" local lockfile_path = vim.fn.stdpath("data") .. "/avante/claude-timer.lock" local auth_endpoint = "https://claude.ai/oauth/authorize" local token_endpoint = "https://console.anthropic.com/v1/oauth/token" local client_id = "9d1c250a-e61b-44d9-88ed-5944d1962f5e" local claude_code_spoof_prompt = "You are Claude Code, Anthropic's official CLI for Claude." ---@private ---@class AvanteAnthropicState ---@field claude_token ClaudeAuthToken? M.state = nil M.api_key_name = "ANTHROPIC_API_KEY" M.support_prompt_caching = true M.tokenizer_id = "gpt-4o" M.role_map = { user = "user", assistant = "assistant", } M._is_setup = false M._refresh_timer = nil -- Token validation helper ---@param token ClaudeAuthToken? ---@return boolean local function is_valid_token(token) return token ~= nil and type(token.access_token) == "string" and type(token.refresh_token) == "string" and type(token.expires_at) == "number" and token.access_token ~= "" and token.refresh_token ~= "" end -- Lockfile management local function is_process_running(pid) local result = vim.uv.kill(pid, 0) if result ~= nil and result == 0 then return true else return false end end local function try_acquire_claude_timer_lock() local lockfile = Path:new(lockfile_path) local tmp_lockfile = lockfile_path .. ".tmp." .. vim.fn.getpid() Path:new(tmp_lockfile):write(tostring(vim.fn.getpid()), "w") -- Check existing lock if lockfile:exists() then local content = lockfile:read() local pid = tonumber(content) if pid and is_process_running(pid) then os.remove(tmp_lockfile) return false -- Another instance is already managing end end -- Attempt to take ownership local success = os.rename(tmp_lockfile, lockfile_path) if not success then os.remove(tmp_lockfile) return false end return true end local function start_manager_check_timer() if M._manager_check_timer then M._manager_check_timer:stop() M._manager_check_timer:close() end M._manager_check_timer = vim.uv.new_timer() M._manager_check_timer:start( 30000, 30000, vim.schedule_wrap(function() if not M._refresh_timer and try_acquire_claude_timer_lock() then M.setup_claude_timer() end end) ) end function M.setup_claude_file_watcher() if M._file_watcher then return end local claude_token_file = Path:new(claude_path) M._file_watcher = vim.uv.new_fs_event() M._file_watcher:start( claude_path, {}, vim.schedule_wrap(function() -- Reload token from file if claude_token_file:exists() then local ok, token = pcall(vim.json.decode, claude_token_file:read()) if ok then M.state.claude_token = token end end end) ) end -- Common token management setup (timer, file watcher, tokenizer) local function setup_token_management() -- Setup timer management local timer_lock_acquired = try_acquire_claude_timer_lock() if timer_lock_acquired then M.setup_claude_timer() else vim.schedule(function() if M._is_setup then M.refresh_token(true, false) end end) end M.setup_claude_file_watcher() start_manager_check_timer() require("avante.tokenizers").setup(M.tokenizer_id) vim.g.avante_login = true end function M.setup() local claude_token_file = Path:new(claude_path) local auth_type = P[Config.provider].auth_type if auth_type == "api" then require("avante.tokenizers").setup(M.tokenizer_id) M._is_setup = true return end M.api_key_name = "" if not M.state then M.state = { claude_token = nil, } end if claude_token_file:exists() then local ok, token = pcall(vim.json.decode, claude_token_file:read()) -- Note: We don't check expiration here because refresh logic needs the refresh_token field -- from the existing token. Expired tokens will be refreshed automatically on next use. if ok and is_valid_token(token) then M.state.claude_token = token elseif ok and not is_valid_token(token) then -- Token file exists but is malformed - delete and re-authenticate Utils.warn("Claude token file is corrupted or invalid, re-authenticating...", { title = "Avante" }) vim.schedule(function() pcall(claude_token_file.rm, claude_token_file) end) M.authenticate() elseif not ok then -- JSON decode failed - file is corrupted Utils.warn( "Failed to parse Claude token file: " .. tostring(token) .. ", re-authenticating...", { title = "Avante" } ) vim.schedule(function() pcall(claude_token_file.rm, claude_token_file) end) M.authenticate() end setup_token_management() M._is_setup = true else M.authenticate() setup_token_management() -- Note: M._is_setup is NOT set to true here because authenticate() is async -- and may fail. The flag indicates setup was attempted, not that it succeeded. end end function M.setup_claude_timer() if M._refresh_timer then M._refresh_timer:stop() M._refresh_timer:close() end -- Calculate time until token expires local now = math.floor(os.time()) local expires_at = M.state.claude_token and M.state.claude_token.expires_at or now local time_until_expiry = math.max(0, expires_at - now) -- Refresh 2 minutes before expiration local initial_interval = math.max(0, (time_until_expiry - 120) * 1000) -- Regular interval of 28 minutes after the first refresh -- local repeat_interval = 28 * 60 * 1000 local repeat_interval = 0 -- Try 0 as we should know exactly when the refresh is needed, rather than repeating M._refresh_timer = vim.uv.new_timer() M._refresh_timer:start( initial_interval, repeat_interval, vim.schedule_wrap(function() if M._is_setup then M.refresh_token(true, true) end end) ) end ---@param headers table<string, string> ---@return integer|nil function M:get_rate_limit_sleep_time(headers) local remaining_tokens = tonumber(headers["anthropic-ratelimit-tokens-remaining"]) if remaining_tokens == nil then return end if remaining_tokens > 10000 then return end local reset_dt_str = headers["anthropic-ratelimit-tokens-reset"] if remaining_tokens ~= 0 then reset_dt_str = reset_dt_str or headers["anthropic-ratelimit-requests-reset"] end local reset_dt, err = Utils.parse_iso8601_date(reset_dt_str) if err then Utils.warn(err) return end local now = Utils.utc_now() return Utils.datetime_diff(tostring(now), tostring(reset_dt)) end ---@param tool AvanteLLMTool ---@return AvanteClaudeTool function M:transform_tool(tool) local input_schema_properties, required = Utils.llm_tool_param_fields_to_json_schema(tool.param.fields) return { name = tool.name, description = tool.get_description and tool.get_description() or tool.description, input_schema = { type = "object", properties = input_schema_properties, required = required, }, } end function M:is_disable_stream() return false end ---@return AvanteClaudeMessage[] function M:parse_messages(opts) ---@type AvanteClaudeMessage[] local messages = {} local provider_conf, _ = P.parse_config(self) ---@type {idx: integer, length: integer}[] local messages_with_length = {} for idx, message in ipairs(opts.messages) do table.insert(messages_with_length, { idx = idx, length = Utils.tokens.calculate_tokens(message.content) }) end table.sort(messages_with_length, function(a, b) return a.length > b.length end) local has_tool_use = false for _, message in ipairs(opts.messages) do local content_items = message.content local message_content = {} if type(content_items) == "string" then if message.role == "assistant" then content_items = content_items:gsub("%s+$", "") end if content_items ~= "" then table.insert(message_content, { type = "text", text = content_items, }) end elseif type(content_items) == "table" then ---@cast content_items AvanteLLMMessageContentItem[] for _, item in ipairs(content_items) do if type(item) == "string" then if message.role == "assistant" then item = item:gsub("%s+$", "") end table.insert(message_content, { type = "text", text = item }) elseif type(item) == "table" and item.type == "text" then table.insert(message_content, { type = "text", text = item.text }) elseif type(item) == "table" and item.type == "image" then table.insert(message_content, { type = "image", source = item.source }) elseif not provider_conf.disable_tools and type(item) == "table" and item.type == "tool_use" then has_tool_use = true table.insert(message_content, { type = "tool_use", name = item.name, id = item.id, input = item.input }) elseif not provider_conf.disable_tools and type(item) == "table" and item.type == "tool_result" and has_tool_use then table.insert( message_content, { type = "tool_result", tool_use_id = item.tool_use_id, content = item.content, is_error = item.is_error } ) elseif type(item) == "table" and item.type == "thinking" then table.insert(message_content, { type = "thinking", thinking = item.thinking, signature = item.signature }) elseif type(item) == "table" and item.type == "redacted_thinking" then table.insert(message_content, { type = "redacted_thinking", data = item.data }) end end end if #message_content > 0 then table.insert(messages, { role = self.role_map[message.role], content = message_content, }) end end if Clipboard.support_paste_image() and opts.image_paths and #opts.image_paths > 0 then local message_content = messages[#messages].content for _, image_path in ipairs(opts.image_paths) do table.insert(message_content, { type = "image", source = { type = "base64", media_type = "image/png", data = Clipboard.get_base64_content(image_path), }, }) end messages[#messages].content = message_content end return messages end ---@param usage avante.AnthropicTokenUsage | nil ---@return avante.LLMTokenUsage | nil function M.transform_anthropic_usage(usage) if not usage then return nil end ---@type avante.LLMTokenUsage local res = { prompt_tokens = usage.cache_creation_input_tokens and (usage.input_tokens + usage.cache_creation_input_tokens) or usage.input_tokens, completion_tokens = usage.cache_read_input_tokens and (usage.output_tokens + usage.cache_read_input_tokens) or usage.output_tokens, } return res end function M:parse_response(ctx, data_stream, event_state, opts) if event_state == nil then if data_stream:match('"message_start"') then event_state = "message_start" elseif data_stream:match('"message_delta"') then event_state = "message_delta" elseif data_stream:match('"message_stop"') then event_state = "message_stop" elseif data_stream:match('"content_block_start"') then event_state = "content_block_start" elseif data_stream:match('"content_block_delta"') then event_state = "content_block_delta" elseif data_stream:match('"content_block_stop"') then event_state = "content_block_stop" end end if ctx.content_blocks == nil then ctx.content_blocks = {} end ---@param content AvanteLLMMessageContentItem ---@param uuid? string ---@return avante.HistoryMessage local function new_assistant_message(content, uuid) assert( event_state == "content_block_start" or event_state == "content_block_delta" or event_state == "content_block_stop", "called with unexpected event_state: " .. event_state ) return HistoryMessage:new("assistant", content, { state = event_state == "content_block_stop" and "generated" or "generating", turn_id = ctx.turn_id, uuid = uuid, }) end if event_state == "message_start" then local ok, jsn = pcall(vim.json.decode, data_stream) if not ok then return end ctx.usage = jsn.message.usage elseif event_state == "content_block_start" then local ok, jsn = pcall(vim.json.decode, data_stream) if not ok then return end local content_block = jsn.content_block content_block.stoppped = false ctx.content_blocks[jsn.index + 1] = content_block if content_block.type == "text" then local msg = new_assistant_message(content_block.text) content_block.uuid = msg.uuid if opts.on_messages_add then opts.on_messages_add({ msg }) end elseif content_block.type == "thinking" then if opts.on_chunk then opts.on_chunk("<think>\n") end if opts.on_messages_add then local msg = new_assistant_message({ type = "thinking", thinking = content_block.thinking, signature = content_block.signature, }) content_block.uuid = msg.uuid opts.on_messages_add({ msg }) end elseif content_block.type == "tool_use" then if opts.on_messages_add then local incomplete_json = JsonParser.parse(content_block.input_json) local msg = new_assistant_message({ type = "tool_use", name = content_block.name, id = content_block.id, input = incomplete_json or { dummy = "" }, }) content_block.uuid = msg.uuid opts.on_messages_add({ msg }) -- opts.on_stop({ reason = "tool_use", streaming_tool_use = true }) end end elseif event_state == "content_block_delta" then local ok, jsn = pcall(vim.json.decode, data_stream) if not ok then return end local content_block = ctx.content_blocks[jsn.index + 1] if jsn.delta.type == "input_json_delta" then if not content_block.input_json then content_block.input_json = "" end content_block.input_json = content_block.input_json .. jsn.delta.partial_json return elseif jsn.delta.type == "thinking_delta" then content_block.thinking = content_block.thinking .. jsn.delta.thinking if opts.on_chunk then opts.on_chunk(jsn.delta.thinking) end if opts.on_messages_add then local msg = new_assistant_message({ type = "thinking", thinking = content_block.thinking, signature = content_block.signature, }, content_block.uuid) opts.on_messages_add({ msg }) end elseif jsn.delta.type == "text_delta" then content_block.text = content_block.text .. jsn.delta.text if opts.on_chunk then opts.on_chunk(jsn.delta.text) end if opts.on_messages_add then local msg = new_assistant_message(content_block.text, content_block.uuid) opts.on_messages_add({ msg }) end elseif jsn.delta.type == "signature_delta" then if ctx.content_blocks[jsn.index + 1].signature == nil then ctx.content_blocks[jsn.index + 1].signature = "" end ctx.content_blocks[jsn.index + 1].signature = ctx.content_blocks[jsn.index + 1].signature .. jsn.delta.signature end elseif event_state == "content_block_stop" then local ok, jsn = pcall(vim.json.decode, data_stream) if not ok then return end local content_block = ctx.content_blocks[jsn.index + 1] content_block.stoppped = true if content_block.type == "text" then if opts.on_messages_add then local msg = new_assistant_message(content_block.text, content_block.uuid) opts.on_messages_add({ msg }) end elseif content_block.type == "thinking" then if opts.on_chunk then if content_block.thinking and content_block.thinking ~= vim.NIL and content_block.thinking:sub(-1) ~= "\n" then opts.on_chunk("\n</think>\n\n") else opts.on_chunk("</think>\n\n") end end if opts.on_messages_add then local msg = new_assistant_message({ type = "thinking", thinking = content_block.thinking, signature = content_block.signature, }, content_block.uuid) opts.on_messages_add({ msg }) end elseif content_block.type == "tool_use" then if opts.on_messages_add then local ok_, complete_json = pcall(vim.json.decode, content_block.input_json) if not ok_ then complete_json = nil end local msg = new_assistant_message({ type = "tool_use", name = content_block.name, id = content_block.id, input = complete_json or { dummy = "" }, }, content_block.uuid) opts.on_messages_add({ msg }) end end elseif event_state == "message_delta" then local ok, jsn = pcall(vim.json.decode, data_stream) if not ok then return end if jsn.usage and ctx.usage then ctx.usage.output_tokens = ctx.usage.output_tokens + jsn.usage.output_tokens end if jsn.delta.stop_reason == "end_turn" then opts.on_stop({ reason = "complete", usage = M.transform_anthropic_usage(ctx.usage) }) elseif jsn.delta.stop_reason == "max_tokens" then opts.on_stop({ reason = "max_tokens", usage = M.transform_anthropic_usage(ctx.usage) }) elseif jsn.delta.stop_reason == "tool_use" then opts.on_stop({ reason = "tool_use", usage = M.transform_anthropic_usage(ctx.usage), }) end return elseif event_state == "error" then opts.on_stop({ reason = "error", error = vim.json.decode(data_stream) }) end end ---@param prompt_opts AvantePromptOptions ---@return AvanteCurlOutput|nil function M:parse_curl_args(prompt_opts) -- refresh token synchronously, only if it has expired -- (this should rarely happen, as we refresh the token in the background) M.refresh_token(false, false) local provider_conf, request_body = P.parse_config(self) ---@cast provider_conf AvanteAnthropicProvider local disable_tools = provider_conf.disable_tools or false local headers = { ["Content-Type"] = "application/json", ["anthropic-version"] = "2023-06-01", } if provider_conf.auth_type == "max" then local api_key = M.state.claude_token.access_token headers["authorization"] = string.format("Bearer %s", api_key) headers["anthropic-beta"] = "oauth-2025-04-20,claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14,prompt-caching-2024-07-31" else if P.env.require_api_key(provider_conf) then local api_key = self.parse_api_key() if not api_key then Utils.error("Claude: API key is not set. Please set " .. M.api_key_name) return nil end headers["x-api-key"] = api_key headers["anthropic-beta"] = "prompt-caching-2024-07-31" end end local messages = self:parse_messages(prompt_opts) local tools = {} if not disable_tools and prompt_opts.tools then for _, tool in ipairs(prompt_opts.tools) do if Config.mode == "agentic" then if tool.name == "create_file" then goto continue end if tool.name == "view" then goto continue end if tool.name == "str_replace" then goto continue end if tool.name == "create" then goto continue end if tool.name == "insert" then goto continue end if tool.name == "undo_edit" then goto continue end if tool.name == "replace_in_file" then goto continue end end table.insert(tools, self:transform_tool(tool)) ::continue:: end end if prompt_opts.tools and #prompt_opts.tools > 0 and Config.mode == "agentic" then if provider_conf.model:match("claude%-sonnet%-4%-5") then table.insert(tools, { type = "text_editor_20250728", name = "str_replace_based_edit_tool", }) elseif provider_conf.model:match("claude%-sonnet%-4") then table.insert(tools, { type = "text_editor_20250429", name = "str_replace_based_edit_tool", }) elseif provider_conf.model:match("claude%-3%-7%-sonnet") then table.insert(tools, { type = "text_editor_20250124", name = "str_replace_editor", }) elseif provider_conf.model:match("claude%-3%-5%-sonnet") then table.insert(tools, { type = "text_editor_20250124", name = "str_replace_editor", }) end end if self.support_prompt_caching then if #messages > 0 then local found = false for i = #messages, 1, -1 do local message = messages[i] message = vim.deepcopy(message) ---@cast message AvanteClaudeMessage local content = message.content ---@cast content AvanteClaudeMessageContentTextItem[] for j = #content, 1, -1 do local item = content[j] if item.type == "text" then item.cache_control = { type = "ephemeral" } found = true break end end if found then messages[i] = message break end end end if #tools > 0 then local last_tool = vim.deepcopy(tools[#tools]) last_tool.cache_control = { type = "ephemeral" } tools[#tools] = last_tool end end local system = {} if provider_conf.auth_type == "max" then table.insert(system, { type = "text", text = claude_code_spoof_prompt, }) end table.insert(system, { type = "text", text = prompt_opts.system_prompt, cache_control = self.support_prompt_caching and { type = "ephemeral" } or nil, }) return { url = Utils.url_join(provider_conf.endpoint, "/v1/messages"), proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, headers = Utils.tbl_override(headers, self.extra_headers), body = vim.tbl_deep_extend("force", { model = provider_conf.model, system = system, messages = messages, tools = tools, stream = true, }, request_body), } end function M.on_error(result) if result.status == 429 then return end if not result.body then return Utils.error("API request failed with status " .. result.status, { once = true, title = "Avante" }) end local ok, body = pcall(vim.json.decode, result.body) if not (ok and body and body.error) then return Utils.error("Failed to parse error response", { once = true, title = "Avante" }) end local error_msg = body.error.message local error_type = body.error.type if error_type == "insufficient_quota" then error_msg = "You don't have any credits or have exceeded your quota. Please check your plan and billing details." elseif error_type == "invalid_request_error" and error_msg:match("temperature") then error_msg = "Invalid temperature value. Please ensure it's between 0 and 1." end Utils.error(error_msg, { once = true, title = "Avante" }) end function M.authenticate() local verifier, verifier_err = pkce.generate_verifier() if not verifier then vim.schedule( function() vim.notify("Failed to generate PKCE verifier: " .. (verifier_err or "Unknown error"), vim.log.levels.ERROR) end ) return end local challenge, challenge_err = pkce.generate_challenge(verifier) if not challenge then vim.schedule( function() vim.notify("Failed to generate PKCE challenge: " .. (challenge_err or "Unknown error"), vim.log.levels.ERROR) end ) return end local state, state_err = pkce.generate_verifier() if not state then vim.schedule( function() vim.notify("Failed to generate PKCE state: " .. (state_err or "Unknown error"), vim.log.levels.ERROR) end ) return end local auth_url = string.format( "%s?client_id=%s&response_type=code&redirect_uri=%s&scope=%s&state=%s&code_challenge=%s&code_challenge_method=S256", auth_endpoint, client_id, vim.uri_encode("https://console.anthropic.com/oauth/code/callback"), vim.uri_encode("org:create_api_key user:profile user:inference"), state, challenge ) -- Open browser to begin authentication vim.schedule(function() local open_success = pcall(vim.ui.open, auth_url) if not open_success then vim.fn.setreg("+", auth_url) vim.notify("Copied URL to Clipboard, please open this URL in your browser:\n" .. auth_url, vim.log.levels.WARN) end end) local function on_submit(input) if input then local splits = vim.split(input, "#") local response = curl.post(token_endpoint, { body = vim.json.encode({ grant_type = "authorization_code", client_id = client_id, code = splits[1], state = splits[2], redirect_uri = "https://console.anthropic.com/oauth/code/callback", code_verifier = verifier, }), headers = { ["Content-Type"] = "application/json", }, }) if response.status >= 400 then vim.schedule( function() vim.notify(string.format("HTTP %d: %s", response.status, response.body), vim.log.levels.ERROR) end ) return end local ok, tokens = pcall(vim.json.decode, response.body) if ok then M.store_tokens(tokens) vim.schedule(function() vim.notify("✓ Authentication successful!", vim.log.levels.INFO) end) M._is_setup = true else vim.schedule(function() vim.notify("Failed to decode JSON", vim.log.levels.ERROR) end) end else vim.schedule(function() vim.notify("Failed to parse code, authentication failed!", vim.log.levels.ERROR) end) end end local Input = require("avante.ui.input") local input = Input:new({ provider = Config.input.provider, title = "Enter Auth Key: ", default = "", conceal = false, -- Key input should be concealed provider_opts = Config.input.provider_opts, on_submit = on_submit, }) input:open() end --- Function to refresh an expired claude auth token ---@param async boolean whether to refresh the token asynchronously ---@param force boolean whether to force the refresh function M.refresh_token(async, force) if not M.state or not M.state.claude_token then return false end -- Exit early if no state async = async == nil and true or async force = force or false -- Do not refresh token if not forced or not expired if not force and M.state.claude_token and M.state.claude_token.expires_at and M.state.claude_token.expires_at > math.floor(os.time()) then return false end local base_url = "https://console.anthropic.com/v1/oauth/token" local body = { grant_type = "refresh_token", client_id = client_id, refresh_token = M.state.claude_token.refresh_token, } local curl_opts = { body = vim.json.encode(body), headers = { ["Content-Type"] = "application/json", }, } local function handle_response(response) if response.status >= 400 then vim.schedule( function() vim.notify( string.format("[%s]Failed to refresh access token: %s", response.status, response.body), vim.log.levels.ERROR ) end ) return false else local ok, tokens = pcall(vim.json.decode, response.body) if ok then M.store_tokens(tokens) return true else return false end end end if async then curl.post( base_url, vim.tbl_deep_extend("force", { callback = handle_response, }, curl_opts) ) else local response = curl.post(base_url, curl_opts) handle_response(response) end end function M.store_tokens(tokens) local json = { access_token = tokens["access_token"], refresh_token = tokens["refresh_token"], expires_at = os.time() + tokens["expires_in"], } M.state.claude_token = json vim.schedule(function() local data_path = vim.fn.stdpath("data") .. "/avante/claude-auth.json" -- Safely encode JSON local ok, json_str = pcall(vim.json.encode, json) if not ok then Utils.error("Failed to encode token data: " .. tostring(json_str), { once = true, title = "Avante" }) return end -- Open file for writing local file, open_err = io.open(data_path, "w") if not file then Utils.error("Failed to save token file: " .. tostring(open_err), { once = true, title = "Avante" }) return end -- Write token data local write_ok, write_err = pcall(file.write, file, json_str) file:close() if not write_ok then Utils.error("Failed to write token file: " .. tostring(write_err), { once = true, title = "Avante" }) return end -- Set file permissions (Unix only) if vim.fn.has("unix") == 1 then local chmod_ok = vim.loop.fs_chmod(data_path, 384) -- 0600 in decimal if not chmod_ok then Utils.warn("Failed to set token file permissions", { once = true, title = "Avante" }) end end end) end function M.cleanup_claude() -- Cleanup refresh timer if M._refresh_timer then M._refresh_timer:stop() M._refresh_timer:close() M._refresh_timer = nil -- Remove lockfile if we were the manager local lockfile = Path:new(lockfile_path) if lockfile:exists() then local content = lockfile:read() local pid = tonumber(content) if pid and pid == vim.fn.getpid() then lockfile:rm() end end end -- Cleanup manager check timer if M._manager_check_timer then M._manager_check_timer:stop() M._manager_check_timer:close() M._manager_check_timer = nil end -- Cleanup file watcher if M._file_watcher then ---@diagnostic disable-next-line: param-type-mismatch M._file_watcher:stop() M._file_watcher = nil end end -- Register cleanup on Neovim exit vim.api.nvim_create_autocmd("VimLeavePre", { callback = function() M.cleanup_claude() end, }) return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/cohere.lua
Lua
local Utils = require("avante.utils") local P = require("avante.providers") ---@alias CohereFinishReason "COMPLETE" | "LENGTH" | "ERROR" ---@alias CohereStreamType "message-start" | "content-start" | "content-delta" | "content-end" | "message-end" --- ---@class CohereChatContent ---@field type? CohereStreamType ---@field text string --- ---@class CohereChatMessage ---@field content CohereChatContent --- ---@class CohereChatStreamBase ---@field type CohereStreamType ---@field index integer --- ---@class CohereChatContentDelta: CohereChatStreamBase ---@field type "content-delta" | "content-start" | "content-end" ---@field delta? { message: CohereChatMessage } --- ---@class CohereChatMessageStart: CohereChatStreamBase ---@field type "message-start" ---@field delta { message: { role: "assistant" } } --- ---@class CohereChatMessageEnd: CohereChatStreamBase ---@field type "message-end" ---@field delta { finish_reason: CohereFinishReason, usage: CohereChatUsage } --- ---@class CohereChatUsage ---@field billed_units { input_tokens: integer, output_tokens: integer } ---@field tokens { input_tokens: integer, output_tokens: integer } --- ---@alias CohereChatResponse CohereChatContentDelta | CohereChatMessageStart | CohereChatMessageEnd --- ---@class CohereMessage ---@field type "text" ---@field text string --- ---@class AvanteProviderFunctor local M = {} M.api_key_name = "CO_API_KEY" M.tokenizer_id = "https://storage.googleapis.com/cohere-public/tokenizers/command-r-08-2024.json" M.role_map = { user = "user", assistant = "assistant", } function M:is_disable_stream() return false end function M:parse_messages(opts) local messages = { { role = "system", content = opts.system_prompt }, } vim .iter(opts.messages) :each(function(msg) table.insert(messages, { role = M.role_map[msg.role], content = msg.content }) end) return { messages = messages } end function M:parse_stream_data(ctx, data, opts) ---@type CohereChatResponse local json = vim.json.decode(data) if json.type ~= nil then if json.type == "message-end" and json.delta.finish_reason == "COMPLETE" then P.openai:finish_pending_messages(ctx, opts) opts.on_stop({ reason = "complete" }) return end if json.type == "content-delta" then local content = json.delta.message.content.text P.openai:add_text_message(ctx, content, "generating", opts) if content and content ~= "" and opts.on_chunk then opts.on_chunk(content) end end end end ---@param prompt_opts AvantePromptOptions ---@return AvanteCurlOutput|nil function M:parse_curl_args(prompt_opts) local provider_conf, request_body = P.parse_config(self) local headers = { ["Accept"] = "application/json", ["Content-Type"] = "application/json", ["X-Client-Name"] = "avante.nvim/Neovim/" .. vim.version().major .. "." .. vim.version().minor .. "." .. vim.version().patch, } if P.env.require_api_key(provider_conf) then local api_key = self.parse_api_key() if not api_key then Utils.error("Cohere: API key is not set. Please set " .. M.api_key_name) return nil end headers["Authorization"] = "Bearer " .. api_key end return { url = Utils.url_join(provider_conf.endpoint, "/chat"), proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, headers = Utils.tbl_override(headers, self.extra_headers), body = vim.tbl_deep_extend("force", { model = provider_conf.model, stream = true, }, self:parse_messages(prompt_opts), request_body), } end function M.setup() P.env.parse_envvar(M) require("avante.tokenizers").setup(M.tokenizer_id, false) vim.g.avante_login = true end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/copilot.lua
Lua
---Reference implementation: ---https://github.com/zbirenbaum/copilot.lua/blob/master/lua/copilot/auth.lua config file ---https://github.com/zed-industries/zed/blob/ad43bbbf5eda59eba65309735472e0be58b4f7dd/crates/copilot/src/copilot_chat.rs#L272 for authorization --- ---@class CopilotToken ---@field annotations_enabled boolean ---@field chat_enabled boolean ---@field chat_jetbrains_enabled boolean ---@field code_quote_enabled boolean ---@field codesearch boolean ---@field copilotignore_enabled boolean ---@field endpoints {api: string, ["origin-tracker"]: string, proxy: string, telemetry: string} ---@field expires_at integer ---@field individual boolean ---@field nes_enabled boolean ---@field prompt_8k boolean ---@field public_suggestions string ---@field refresh_in integer ---@field sku string ---@field snippy_load_test_enabled boolean ---@field telemetry string ---@field token string ---@field tracking_id string ---@field vsc_electron_fetcher boolean ---@field xcode boolean ---@field xcode_chat boolean local curl = require("plenary.curl") local Path = require("plenary.path") local Utils = require("avante.utils") local Providers = require("avante.providers") local OpenAI = require("avante.providers").openai local H = {} ---@class AvanteProviderFunctor local M = {} local copilot_path = vim.fn.stdpath("data") .. "/avante/github-copilot.json" local lockfile_path = vim.fn.stdpath("data") .. "/avante/copilot-timer.lock" -- Lockfile management local function is_process_running(pid) local result = vim.uv.kill(pid, 0) if result ~= nil and result == 0 then return true else return false end end local function try_acquire_timer_lock() local lockfile = Path:new(lockfile_path) local tmp_lockfile = lockfile_path .. ".tmp." .. vim.fn.getpid() Path:new(tmp_lockfile):write(tostring(vim.fn.getpid()), "w") -- Check existing lock if lockfile:exists() then local content = lockfile:read() local pid = tonumber(content) if pid and is_process_running(pid) then os.remove(tmp_lockfile) return false -- Another instance is already managing end end -- Attempt to take ownership local success = os.rename(tmp_lockfile, lockfile_path) if not success then os.remove(tmp_lockfile) return false end return true end local function start_manager_check_timer() if M._manager_check_timer then M._manager_check_timer:stop() M._manager_check_timer:close() end M._manager_check_timer = vim.uv.new_timer() M._manager_check_timer:start( 30000, 30000, vim.schedule_wrap(function() if not M._refresh_timer and try_acquire_timer_lock() then M.setup_timer() end end) ) end ---@class OAuthToken ---@field user string ---@field oauth_token string --- ---@return string function H.get_oauth_token() local xdg_config = vim.fn.expand("$XDG_CONFIG_HOME") local os_name = Utils.get_os_name() ---@type string local config_dir if xdg_config and vim.fn.isdirectory(xdg_config) > 0 then config_dir = xdg_config elseif vim.tbl_contains({ "linux", "darwin" }, os_name) then config_dir = vim.fn.expand("~/.config") else config_dir = vim.fn.expand("~/AppData/Local") end --- hosts.json (copilot.lua), apps.json (copilot.vim) ---@type Path[] local paths = vim.iter({ "hosts.json", "apps.json" }):fold({}, function(acc, path) local yason = Path:new(config_dir):joinpath("github-copilot", path) if yason:exists() then table.insert(acc, yason) end return acc end) if #paths == 0 then error("You must setup copilot with either copilot.lua or copilot.vim", 2) end local yason = paths[1] return vim .iter( ---@type table<string, OAuthToken> ---@diagnostic disable-next-line: param-type-mismatch vim.json.decode(yason:read()) ) :filter(function(k, _) return k:match("github.com") end) ---@param acc {oauth_token: string} :fold({}, function(acc, _, v) acc.oauth_token = v.oauth_token return acc end) .oauth_token end H.chat_auth_url = "https://api.github.com/copilot_internal/v2/token" function H.chat_completion_url(base_url) return Utils.url_join(base_url, "/chat/completions") end function H.response_url(base_url) return Utils.url_join(base_url, "/responses") end function H.refresh_token(async, force) if not M.state then error("internal initialization error") end async = async == nil and true or async force = force or false -- Do not refresh token if not forced or not expired if not force and M.state.github_token and M.state.github_token.expires_at and M.state.github_token.expires_at > math.floor(os.time()) then return false end local provider_conf = Providers.get_config("copilot") local curl_opts = { headers = { ["Authorization"] = "token " .. M.state.oauth_token, ["Accept"] = "application/json", }, timeout = provider_conf.timeout, proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, } local function handle_response(response) if response.status == 200 then M.state.github_token = vim.json.decode(response.body) local file = Path:new(copilot_path) file:write(vim.json.encode(M.state.github_token), "w") if not vim.g.avante_login then vim.g.avante_login = true end -- If triggered synchronously, reset timer if not async and M._refresh_timer then M.setup_timer() end return true else error("Failed to get success response: " .. vim.inspect(response)) return false end end if async then curl.get( H.chat_auth_url, vim.tbl_deep_extend("force", { callback = handle_response, }, curl_opts) ) else local response = curl.get(H.chat_auth_url, curl_opts) handle_response(response) end end ---@private ---@class AvanteCopilotState ---@field oauth_token string ---@field github_token CopilotToken? M.state = nil M.api_key_name = "" M.tokenizer_id = "gpt-4o" M.role_map = { user = "user", assistant = "assistant", } function M:is_disable_stream() return false end setmetatable(M, { __index = OpenAI }) function M:list_models() if M._model_list_cache then return M._model_list_cache end if not M._is_setup then M.setup() end -- refresh token synchronously, only if it has expired -- (this should rarely happen, as we refresh the token in the background) H.refresh_token(false, false) local provider_conf = Providers.parse_config(self) local headers = self:build_headers() local curl_opts = { headers = Utils.tbl_override(headers, self.extra_headers), timeout = provider_conf.timeout, proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, } local function handle_response(response) if response.status == 200 then local body = vim.json.decode(response.body) -- ref: https://github.com/CopilotC-Nvim/CopilotChat.nvim/blob/16d897fd43d07e3b54478ccdb2f8a16e4df4f45a/lua/CopilotChat/config/providers.lua#L171-L187 local models = vim .iter(body.data) :filter(function(model) return model.capabilities.type == "chat" and not vim.endswith(model.id, "paygo") end) :map( function(model) return { id = model.id, display_name = model.name, name = "copilot/" .. model.name .. " (" .. model.id .. ")", provider_name = "copilot", tokenizer = model.capabilities.tokenizer, max_input_tokens = model.capabilities.limits.max_prompt_tokens, max_output_tokens = model.capabilities.limits.max_output_tokens, policy = not model["policy"] or model["policy"]["state"] == "enabled", version = model.version, } end ) :totable() M._model_list_cache = models return models else error("Failed to get success response: " .. vim.inspect(response)) return {} end end local response = curl.get((M.state.github_token.endpoints.api or "") .. "/models", curl_opts) return handle_response(response) end function M:build_headers() return { ["Authorization"] = "Bearer " .. M.state.github_token.token, ["User-Agent"] = "GitHubCopilotChat/0.26.7", ["Editor-Version"] = "vscode/1.105.1", ["Editor-Plugin-Version"] = "copilot-chat/0.26.7", ["Copilot-Integration-Id"] = "vscode-chat", ["Openai-Intent"] = "conversation-edits", } end function M:parse_curl_args(prompt_opts) -- refresh token synchronously, only if it has expired -- (this should rarely happen, as we refresh the token in the background) H.refresh_token(false, false) local provider_conf, request_body = Providers.parse_config(self) local use_response_api = Providers.resolve_use_response_api(provider_conf, prompt_opts) local disable_tools = provider_conf.disable_tools or false -- Apply OpenAI's set_allowed_params for Response API compatibility OpenAI.set_allowed_params(provider_conf, request_body) local use_ReAct_prompt = provider_conf.use_ReAct_prompt == true local tools = nil if not disable_tools and prompt_opts.tools and not use_ReAct_prompt then tools = {} for _, tool in ipairs(prompt_opts.tools) do local transformed_tool = OpenAI:transform_tool(tool) -- Response API uses flattened tool structure if use_response_api then if transformed_tool.type == "function" and transformed_tool["function"] then transformed_tool = { type = "function", name = transformed_tool["function"].name, description = transformed_tool["function"].description, parameters = transformed_tool["function"].parameters, } end end table.insert(tools, transformed_tool) end end local headers = self:build_headers() if prompt_opts.messages and #prompt_opts.messages > 0 then local last_message = prompt_opts.messages[#prompt_opts.messages] local initiator = last_message.role == "user" and "user" or "agent" headers["X-Initiator"] = initiator end local parsed_messages = self:parse_messages(prompt_opts) -- Build base body local base_body = { model = provider_conf.model, stream = true, tools = tools, } -- Response API uses 'input' instead of 'messages' -- NOTE: Copilot doesn't support previous_response_id, always send full history if use_response_api then base_body.input = parsed_messages -- Response API uses max_output_tokens instead of max_tokens/max_completion_tokens if request_body.max_completion_tokens then request_body.max_output_tokens = request_body.max_completion_tokens request_body.max_completion_tokens = nil end if request_body.max_tokens then request_body.max_output_tokens = request_body.max_tokens request_body.max_tokens = nil end -- Response API doesn't use stream_options base_body.stream_options = nil base_body.include = { "reasoning.encrypted_content" } base_body.reasoning = { summary = "detailed", } base_body.truncation = "disabled" else base_body.messages = parsed_messages base_body.stream_options = { include_usage = true, } end local base_url = M.state.github_token.endpoints.api or provider_conf.endpoint local build_url = use_response_api and H.response_url or H.chat_completion_url return { url = build_url(base_url), timeout = provider_conf.timeout, proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, headers = Utils.tbl_override(headers, self.extra_headers), body = vim.tbl_deep_extend("force", base_body, request_body), } end M._refresh_timer = nil function M.setup_timer() if M._refresh_timer then M._refresh_timer:stop() M._refresh_timer:close() end -- Calculate time until token expires local now = math.floor(os.time()) local expires_at = M.state.github_token and M.state.github_token.expires_at or now local time_until_expiry = math.max(0, expires_at - now) -- Refresh 2 minutes before expiration local initial_interval = math.max(0, (time_until_expiry - 120) * 1000) -- Regular interval of 28 minutes after the first refresh local repeat_interval = 28 * 60 * 1000 M._refresh_timer = vim.uv.new_timer() M._refresh_timer:start( initial_interval, repeat_interval, vim.schedule_wrap(function() H.refresh_token(true, true) end) ) end function M.setup_file_watcher() if M._file_watcher then return end local copilot_token_file = Path:new(copilot_path) M._file_watcher = vim.uv.new_fs_event() M._file_watcher:start( copilot_path, {}, vim.schedule_wrap(function() -- Reload token from file if copilot_token_file:exists() then local ok, token = pcall(vim.json.decode, copilot_token_file:read()) if ok then M.state.github_token = token end end end) ) end M._is_setup = false function M.is_env_set() local ok = pcall(function() H.get_oauth_token() end) return ok end function M.setup() local copilot_token_file = Path:new(copilot_path) if not M.state then M.state = { github_token = nil, oauth_token = H.get_oauth_token(), } end -- Load and validate existing token if copilot_token_file:exists() then local ok, token = pcall(vim.json.decode, copilot_token_file:read()) if ok and token.expires_at and token.expires_at > math.floor(os.time()) then M.state.github_token = token end end -- Setup timer management local timer_lock_acquired = try_acquire_timer_lock() if timer_lock_acquired then M.setup_timer() else vim.schedule(function() H.refresh_token(true, false) end) end M.setup_file_watcher() start_manager_check_timer() require("avante.tokenizers").setup(M.tokenizer_id) vim.g.avante_login = true M._is_setup = true end function M.cleanup() -- Cleanup refresh timer if M._refresh_timer then M._refresh_timer:stop() M._refresh_timer:close() M._refresh_timer = nil -- Remove lockfile if we were the manager local lockfile = Path:new(lockfile_path) if lockfile:exists() then local content = lockfile:read() local pid = tonumber(content) if pid and pid == vim.fn.getpid() then lockfile:rm() end end end -- Cleanup manager check timer if M._manager_check_timer then M._manager_check_timer:stop() M._manager_check_timer:close() M._manager_check_timer = nil end -- Cleanup file watcher if M._file_watcher then ---@diagnostic disable-next-line: param-type-mismatch M._file_watcher:stop() M._file_watcher = nil end end -- Register cleanup on Neovim exit vim.api.nvim_create_autocmd("VimLeavePre", { callback = function() M.cleanup() end, }) return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/gemini.lua
Lua
local Utils = require("avante.utils") local Providers = require("avante.providers") local Clipboard = require("avante.clipboard") local OpenAI = require("avante.providers").openai local Prompts = require("avante.utils.prompts") ---@class AvanteProviderFunctor local M = {} M.api_key_name = "GEMINI_API_KEY" M.role_map = { user = "user", assistant = "model", } function M:is_disable_stream() return false end ---@param tool AvanteLLMTool function M:transform_to_function_declaration(tool) local input_schema_properties, required = Utils.llm_tool_param_fields_to_json_schema(tool.param.fields) local parameters = nil if not vim.tbl_isempty(input_schema_properties) then parameters = { type = "object", properties = input_schema_properties, required = required, } end return { name = tool.name, description = tool.get_description and tool.get_description() or tool.description, parameters = parameters, } end function M:parse_messages(opts) local provider_conf, _ = Providers.parse_config(self) local use_ReAct_prompt = provider_conf.use_ReAct_prompt == true local contents = {} local prev_role = nil local tool_id_to_name = {} vim.iter(opts.messages):each(function(message) local role = message.role if role == prev_role then if role == M.role_map["user"] then table.insert( contents, { role = M.role_map["assistant"], parts = { { text = "Ok, I understand." }, } } ) else table.insert(contents, { role = M.role_map["user"], parts = { { text = "Ok" }, } }) end end prev_role = role local parts = {} local content_items = message.content if type(content_items) == "string" then table.insert(parts, { text = content_items }) elseif type(content_items) == "table" then ---@cast content_items AvanteLLMMessageContentItem[] for _, item in ipairs(content_items) do if type(item) == "string" then table.insert(parts, { text = item }) elseif type(item) == "table" and item.type == "text" then table.insert(parts, { text = item.text }) elseif type(item) == "table" and item.type == "image" then table.insert(parts, { inline_data = { mime_type = "image/png", data = item.source.data, }, }) elseif type(item) == "table" and item.type == "tool_use" and not use_ReAct_prompt then tool_id_to_name[item.id] = item.name role = "model" table.insert(parts, { functionCall = { name = item.name, args = item.input, }, }) elseif type(item) == "table" and item.type == "tool_result" and not use_ReAct_prompt then role = "function" local ok, content = pcall(vim.json.decode, item.content) if not ok then content = item.content end -- item.name here refers to the name of the tool that was called, -- which is available in the tool_result content item prepared by llm.lua local tool_name = item.name if not tool_name then -- Fallback, though item.name should ideally always be present for tool_result tool_name = tool_id_to_name[item.tool_use_id] end table.insert(parts, { functionResponse = { name = tool_name, response = { name = tool_name, -- Gemini API requires the name in the response object as well content = content, }, }, }) elseif type(item) == "table" and item.type == "thinking" then table.insert(parts, { text = item.thinking }) elseif type(item) == "table" and item.type == "redacted_thinking" then table.insert(parts, { text = item.data }) end end if not provider_conf.disable_tools and use_ReAct_prompt then if content_items[1].type == "tool_result" then local tool_use_msg = nil for _, msg_ in ipairs(opts.messages) do if type(msg_.content) == "table" and #msg_.content > 0 then if msg_.content[1].type == "tool_use" and msg_.content[1].id == content_items[1].tool_use_id then tool_use_msg = msg_ break end end end if tool_use_msg then table.insert(contents, { role = "model", parts = { { text = Utils.tool_use_to_xml(tool_use_msg.content[1]) }, }, }) role = "user" table.insert(parts, { text = "The result of tool use " .. Utils.tool_use_to_xml(tool_use_msg.content[1]) .. " is:\n", }) table.insert(parts, { text = content_items[1].content, }) end end end end if #parts > 0 then table.insert(contents, { role = M.role_map[role] or role, parts = parts }) end end) if Clipboard.support_paste_image() and opts.image_paths then for _, image_path in ipairs(opts.image_paths) do local image_data = { inline_data = { mime_type = "image/png", data = Clipboard.get_base64_content(image_path), }, } table.insert(contents[#contents].parts, image_data) end end local system_prompt = opts.system_prompt if use_ReAct_prompt then system_prompt = Prompts.get_ReAct_system_prompt(provider_conf, opts) end return { systemInstruction = { role = "user", parts = { { text = system_prompt, }, }, }, contents = contents, } end --- Prepares the main request body for Gemini-like APIs. ---@param provider_instance AvanteProviderFunctor The provider instance (self). ---@param prompt_opts AvantePromptOptions Prompt options including messages, tools, system_prompt. ---@param provider_conf table Provider configuration from config.lua (e.g., model, top-level temperature/max_tokens). ---@param request_body_ table Request-specific overrides, typically from provider_conf.request_config_overrides. ---@return table The fully constructed request body. function M.prepare_request_body(provider_instance, prompt_opts, provider_conf, request_body_) local request_body = {} request_body.generationConfig = request_body_.generationConfig or {} local use_ReAct_prompt = provider_conf.use_ReAct_prompt == true if use_ReAct_prompt then request_body.generationConfig.stopSequences = { "</tool_use>" } end local disable_tools = provider_conf.disable_tools or false if not use_ReAct_prompt and not disable_tools and prompt_opts.tools then local function_declarations = {} for _, tool in ipairs(prompt_opts.tools) do table.insert(function_declarations, provider_instance:transform_to_function_declaration(tool)) end if #function_declarations > 0 then request_body.tools = { { functionDeclarations = function_declarations, }, } end end return vim.tbl_deep_extend("force", {}, provider_instance:parse_messages(prompt_opts), request_body) end ---@param usage avante.GeminiTokenUsage | nil ---@return avante.LLMTokenUsage | nil function M.transform_gemini_usage(usage) if not usage then return nil end ---@type avante.LLMTokenUsage local res = { prompt_tokens = usage.promptTokenCount, completion_tokens = usage.candidatesTokenCount, } return res end function M:parse_response(ctx, data_stream, _, opts) local ok, jsn = pcall(vim.json.decode, data_stream) if not ok then opts.on_stop({ reason = "error", error = "Failed to parse JSON response: " .. tostring(jsn) }) return end if opts.update_tokens_usage and jsn.usageMetadata and jsn.usageMetadata ~= nil then local usage = M.transform_gemini_usage(jsn.usageMetadata) if usage ~= nil then opts.update_tokens_usage(usage) end end -- Handle prompt feedback first, as it might indicate an overall issue with the prompt if jsn.promptFeedback and jsn.promptFeedback.blockReason then local feedback = jsn.promptFeedback OpenAI:finish_pending_messages(ctx, opts) -- Ensure any pending messages are cleared opts.on_stop({ reason = "error", error = "Prompt blocked or filtered. Reason: " .. feedback.blockReason, details = feedback, }) return end if jsn.candidates and #jsn.candidates > 0 then local candidate = jsn.candidates[1] ---@type AvanteLLMToolUse[] ctx.tool_use_list = ctx.tool_use_list or {} -- Check if candidate.content and candidate.content.parts exist before iterating if candidate.content and candidate.content.parts then for _, part in ipairs(candidate.content.parts) do if part.text then if opts.on_chunk then opts.on_chunk(part.text) end OpenAI:add_text_message(ctx, part.text, "generating", opts) elseif part.functionCall then if not ctx.function_call_id then ctx.function_call_id = 0 end ctx.function_call_id = ctx.function_call_id + 1 local tool_use = { id = ctx.turn_id .. "-" .. tostring(ctx.function_call_id), name = part.functionCall.name, input_json = vim.json.encode(part.functionCall.args), } table.insert(ctx.tool_use_list, tool_use) OpenAI:add_tool_use_message(ctx, tool_use, "generated", opts) end end end -- Check for finishReason to determine if this candidate's stream is done. if candidate.finishReason then OpenAI:finish_pending_messages(ctx, opts) local reason_str = candidate.finishReason local stop_details = { finish_reason = reason_str } stop_details.usage = M.transform_gemini_usage(jsn.usageMetadata) if reason_str == "TOOL_CODE" then -- Model indicates a tool-related stop. -- The tool_use list is added to the table in llm.lua opts.on_stop(vim.tbl_deep_extend("force", { reason = "tool_use" }, stop_details)) elseif reason_str == "STOP" then if ctx.tool_use_list and #ctx.tool_use_list > 0 then -- Natural stop, but tools were found in this final chunk. opts.on_stop(vim.tbl_deep_extend("force", { reason = "tool_use" }, stop_details)) else -- Natural stop, no tools in this final chunk. -- llm.lua will check its accumulated tools if tool_choice was active. opts.on_stop(vim.tbl_deep_extend("force", { reason = "complete" }, stop_details)) end elseif reason_str == "MAX_TOKENS" then opts.on_stop(vim.tbl_deep_extend("force", { reason = "max_tokens" }, stop_details)) elseif reason_str == "SAFETY" or reason_str == "RECITATION" then opts.on_stop( vim.tbl_deep_extend( "force", { reason = "error", error = "Generation stopped: " .. reason_str }, stop_details ) ) else -- OTHER, FINISH_REASON_UNSPECIFIED, or any other unhandled reason. opts.on_stop( vim.tbl_deep_extend( "force", { reason = "error", error = "Generation stopped with unhandled reason: " .. reason_str }, stop_details ) ) end end -- If no finishReason, it's an intermediate chunk; do not call on_stop. end end ---@param prompt_opts AvantePromptOptions ---@return AvanteCurlOutput|nil function M:parse_curl_args(prompt_opts) local provider_conf, request_body = Providers.parse_config(self) local api_key = self:parse_api_key() if api_key == nil then Utils.error("Gemini: API key is not set. Please set " .. M.api_key_name) return nil end return { url = Utils.url_join( provider_conf.endpoint, provider_conf.model .. ":streamGenerateContent?alt=sse&key=" .. api_key ), proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, headers = Utils.tbl_override({ ["Content-Type"] = "application/json" }, self.extra_headers), body = M.prepare_request_body(self, prompt_opts, provider_conf, request_body), } end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/init.lua
Lua
local api, fn = vim.api, vim.fn local Config = require("avante.config") local Utils = require("avante.utils") ---@class avante.Providers ---@field azure AvanteProviderFunctor ---@field bedrock AvanteBedrockProviderFunctor ---@field claude AvanteProviderFunctor ---@field cohere AvanteProviderFunctor ---@field copilot AvanteProviderFunctor ---@field gemini AvanteProviderFunctor ---@field mistral AvanteProviderFunctor ---@field ollama AvanteProviderFunctor ---@field openai AvanteProviderFunctor ---@field vertex_claude AvanteProviderFunctor ---@field watsonx_code_assistant AvanteProviderFunctor local M = {} ---@class EnvironmentHandler local E = {} ---@private ---@type table<string, string> E.cache = {} ---@param Opts AvanteSupportedProvider | AvanteProviderFunctor | AvanteBedrockProviderFunctor ---@return string | nil function E.parse_envvar(Opts) -- First try the scoped version (e.g., AVANTE_ANTHROPIC_API_KEY) local scoped_key_name = nil if Opts.api_key_name and type(Opts.api_key_name) == "string" and Opts.api_key_name ~= "" then -- Only add AVANTE_ prefix if it's a regular environment variable (not a cmd: or already prefixed) if not Opts.api_key_name:match("^cmd:") and not Opts.api_key_name:match("^AVANTE_") then scoped_key_name = "AVANTE_" .. Opts.api_key_name end end -- Try scoped key first if available if scoped_key_name then local scoped_value = Utils.environment.parse(scoped_key_name, Opts._shellenv) if scoped_value ~= nil then vim.g.avante_login = true return scoped_value end end -- Fall back to the original global key local value = Utils.environment.parse(Opts.api_key_name, Opts._shellenv) if value ~= nil then vim.g.avante_login = true return value end return nil end --- initialize the environment variable for current neovim session. --- This will only run once and spawn a UI for users to input the envvar. ---@param opts {refresh: boolean, provider: AvanteProviderFunctor | AvanteBedrockProviderFunctor} ---@private function E.setup(opts) opts.provider.setup() local var = opts.provider.api_key_name if var == nil or var == "" then vim.g.avante_login = true return end if type(var) ~= "table" and vim.env[var] ~= nil then vim.g.avante_login = true return end -- check if var is a all caps string if type(var) == "table" or var:match("^cmd:(.*)") then return end local refresh = opts.refresh or false ---@param value string ---@return nil local function on_confirm(value) if value then vim.fn.setenv(var, value) vim.g.avante_login = true else if not opts.provider.is_env_set() then Utils.warn("Failed to set " .. var .. ". Avante won't work as expected", { once = true }) end end end local function mount_input_ui() vim.defer_fn(function() -- only mount if given buffer is not of buftype ministarter, dashboard, alpha, qf local exclude_filetypes = { "NvimTree", "Outline", "help", "dashboard", "alpha", "qf", "ministarter", "TelescopePrompt", "gitcommit", "gitrebase", "DressingInput", "snacks_input", "noice", } if not vim.tbl_contains(exclude_filetypes, vim.bo.filetype) and not opts.provider.is_env_set() then local Input = require("avante.ui.input") local input = Input:new({ provider = Config.input.provider, title = "Enter " .. var .. ": ", default = "", conceal = true, -- Password input should be concealed provider_opts = Config.input.provider_opts, on_submit = on_confirm, }) input:open() end end, 200) end if refresh then return mount_input_ui() end api.nvim_create_autocmd("User", { pattern = E.REQUEST_LOGIN_PATTERN, callback = mount_input_ui, }) end E.REQUEST_LOGIN_PATTERN = "AvanteRequestLogin" ---@param provider AvanteDefaultBaseProvider function E.require_api_key(provider) return provider.api_key_name ~= nil and provider.api_key_name ~= "" end M.env = E M = setmetatable(M, { ---@param t avante.Providers ---@param k avante.ProviderName __index = function(t, k) if Config.providers[k] == nil then error("Failed to find provider: " .. k, 2) end local provider_config = M.get_config(k) if provider_config.__inherited_from ~= nil then local base_provider_config = M.get_config(provider_config.__inherited_from) local ok, module = pcall(require, "avante.providers." .. provider_config.__inherited_from) if not ok then error("Failed to load provider: " .. provider_config.__inherited_from, 2) end provider_config = Utils.deep_extend_with_metatable("force", module, base_provider_config, provider_config) else local ok, module = pcall(require, "avante.providers." .. k) if ok then provider_config = Utils.deep_extend_with_metatable("force", module, provider_config) elseif provider_config.parse_curl_args == nil then error( string.format( 'The configuration of your provider "%s" is incorrect, missing the `__inherited_from` attribute or a custom `parse_curl_args` function. Please fix your provider configuration. For more details, see: https://github.com/yetone/avante.nvim/wiki/Custom-providers', k ) ) end end t[k] = provider_config if rawget(t[k], "parse_api_key") == nil then t[k].parse_api_key = function() return E.parse_envvar(t[k]) end end -- default to gpt-4o as tokenizer if t[k].tokenizer_id == nil then t[k].tokenizer_id = "gpt-4o" end if rawget(t[k], "is_env_set") == nil then t[k].is_env_set = function() if not E.require_api_key(t[k]) then return true end if type(t[k].api_key_name) == "string" and t[k].api_key_name:match("^cmd:") then return true end local ok, result = pcall(t[k].parse_api_key) if not ok then return false end return result ~= nil end end if rawget(t[k], "setup") == nil then local provider_conf = M.parse_config(t[k]) t[k].setup = function() if E.require_api_key(provider_conf) then if not (type(provider_conf.api_key_name) == "string" and provider_conf.api_key_name:match("^cmd:")) then t[k].parse_api_key() end end require("avante.tokenizers").setup(t[k].tokenizer_id) end end return t[k] end, }) function M.setup() vim.g.avante_login = false if Config.acp_providers[Config.provider] then return end ---@type AvanteProviderFunctor | AvanteBedrockProviderFunctor local provider = M[Config.provider] E.setup({ provider = provider }) if Config.auto_suggestions_provider then local auto_suggestions_provider = M[Config.auto_suggestions_provider] if auto_suggestions_provider and auto_suggestions_provider ~= provider then E.setup({ provider = auto_suggestions_provider }) end end if Config.memory_summary_provider then local memory_summary_provider = M[Config.memory_summary_provider] if memory_summary_provider and memory_summary_provider ~= provider then E.setup({ provider = memory_summary_provider }) end end end ---@param provider_name avante.ProviderName function M.refresh(provider_name) require("avante.config").override({ provider = provider_name }) if Config.acp_providers[provider_name] then Config.provider = provider_name else ---@type AvanteProviderFunctor | AvanteBedrockProviderFunctor local p = M[Config.provider] E.setup({ provider = p, refresh = true }) end Utils.info("Switch to provider: " .. provider_name, { once = true, title = "Avante" }) end ---@param opts AvanteProvider | AvanteSupportedProvider | AvanteAnthropicProvider | AvanteProviderFunctor | AvanteBedrockProviderFunctor ---@return AvanteDefaultBaseProvider provider_opts ---@return table<string, any> request_body function M.parse_config(opts) ---@type AvanteDefaultBaseProvider local provider_opts = {} for key, value in pairs(opts) do if key ~= "extra_request_body" then provider_opts[key] = value end end ---@type table<string, any> local request_body = opts.extra_request_body or {} return provider_opts, request_body end ---@param provider_conf table | nil ---@param ctx any ---@return boolean function M.resolve_use_response_api(provider_conf, ctx) if not provider_conf then return false end local value = provider_conf.use_response_api if type(value) ~= "function" then value = provider_conf._use_response_api_resolver or value end if type(value) == "function" then provider_conf._use_response_api_resolver = value local ok, result = pcall(value, provider_conf, ctx) if not ok then error("Failed to evaluate use_response_api: " .. result, 2) end return result == true end return value == true end ---@param provider_name avante.ProviderName function M.get_config(provider_name) provider_name = provider_name or Config.provider local cur = Config.get_provider_config(provider_name) return type(cur) == "function" and cur() or cur end function M.get_memory_summary_provider() local provider_name = Config.memory_summary_provider if provider_name == nil then provider_name = Config.provider end return M[provider_name] end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/ollama.lua
Lua
local Utils = require("avante.utils") local Providers = require("avante.providers") local Config = require("avante.config") local Clipboard = require("avante.clipboard") local HistoryMessage = require("avante.history.message") local Prompts = require("avante.utils.prompts") ---@class AvanteProviderFunctor local M = {} setmetatable(M, { __index = function(_, k) -- Filter out OpenAI's default models because everyone uses their own ones with Ollama if k == "model" or k == "model_names" then return nil end return Providers.openai[k] end, }) M.api_key_name = "" -- Ollama typically doesn't require API keys for local use M.role_map = { user = "user", assistant = "assistant", } -- Ollama is disabled by default. Users should override is_env_set() -- implementation in their configs to enable it. There is a helper -- check_endpoint_alive() that can be used to test if configured -- endpoint is alive that can be used in place of is_env_set(). function M.is_env_set() return false end function M:parse_messages(opts) local messages = {} local provider_conf, _ = Providers.parse_config(self) local system_prompt = Prompts.get_ReAct_system_prompt(provider_conf, opts) if self.is_reasoning_model(provider_conf.model) then table.insert(messages, { role = "developer", content = system_prompt }) else table.insert(messages, { role = "system", content = system_prompt }) end vim.iter(opts.messages):each(function(msg) if type(msg.content) == "string" then table.insert(messages, { role = self.role_map[msg.role], content = msg.content }) elseif type(msg.content) == "table" then local content = {} for _, item in ipairs(msg.content) do if type(item) == "string" then table.insert(content, { type = "text", text = item }) elseif item.type == "text" then table.insert(content, { type = "text", text = item.text }) elseif item.type == "image" then table.insert(content, { type = "image_url", image_url = { url = "data:" .. item.source.media_type .. ";" .. item.source.type .. "," .. item.source.data, }, }) end end if not provider_conf.disable_tools then if msg.content[1].type == "tool_result" then local tool_use = nil for _, msg_ in ipairs(opts.messages) do if type(msg_.content) == "table" and #msg_.content > 0 then if msg_.content[1].type == "tool_use" and msg_.content[1].id == msg.content[1].tool_use_id then tool_use = msg_ break end end end if tool_use then msg.role = "user" table.insert(content, { type = "text", text = "[" .. tool_use.content[1].name .. " for '" .. (tool_use.content[1].input.path or tool_use.content[1].input.rel_path or "") .. "'] Result:", }) table.insert(content, { type = "text", text = msg.content[1].content, }) end end end if #content > 0 then local text_content = {} for _, item in ipairs(content) do if type(item) == "table" and item.type == "text" then table.insert(text_content, item.text) end end table.insert(messages, { role = self.role_map[msg.role], content = table.concat(text_content, "\n\n") }) end end end) if Config.behaviour.support_paste_from_clipboard and opts.image_paths and #opts.image_paths > 0 then local message_content = messages[#messages].content if type(message_content) ~= "table" or message_content[1] == nil then message_content = { { type = "text", text = message_content } } end for _, image_path in ipairs(opts.image_paths) do table.insert(message_content, { type = "image_url", image_url = { url = "data:image/png;base64," .. Clipboard.get_base64_content(image_path), }, }) end messages[#messages].content = message_content end local final_messages = {} local prev_role = nil vim.iter(messages):each(function(message) local role = message.role if role == prev_role and role ~= "tool" then if role == self.role_map["assistant"] then table.insert(final_messages, { role = self.role_map["user"], content = "Ok" }) else table.insert(final_messages, { role = self.role_map["assistant"], content = "Ok, I understand." }) end end prev_role = role table.insert(final_messages, message) end) return final_messages end function M:is_disable_stream() return false end ---@class avante.OllamaFunction ---@field name string ---@field arguments table ---@class avante.OllamaToolCall ---@field function avante.OllamaFunction ---@param tool_calls avante.OllamaToolCall[] ---@param opts AvanteLLMStreamOptions function M:add_tool_use_messages(tool_calls, opts) if opts.on_messages_add then local msgs = {} for _, tool_call in ipairs(tool_calls) do local id = Utils.uuid() local func = tool_call["function"] local msg = HistoryMessage:new("assistant", { type = "tool_use", name = func.name, id = id, input = func.arguments, }, { state = "generated", uuid = id, }) table.insert(msgs, msg) end opts.on_messages_add(msgs) end end function M:parse_stream_data(ctx, data, opts) local ok, jsn = pcall(vim.json.decode, data) if not ok or not jsn then -- Add debug logging Utils.debug("Failed to parse JSON", data) return end if jsn.message then if jsn.message.content then local content = jsn.message.content if content and content ~= "" then Providers.openai:add_text_message(ctx, content, "generating", opts) if opts.on_chunk then opts.on_chunk(content) end end end if jsn.message.tool_calls then ctx.has_tool_use = true local tool_calls = jsn.message.tool_calls self:add_tool_use_messages(tool_calls, opts) end end if jsn.done then Providers.openai:finish_pending_messages(ctx, opts) if ctx.has_tool_use or (ctx.tool_use_list and #ctx.tool_use_list > 0) then opts.on_stop({ reason = "tool_use" }) else opts.on_stop({ reason = "complete" }) end return end end ---@param prompt_opts AvantePromptOptions ---@return AvanteCurlOutput|nil function M:parse_curl_args(prompt_opts) local provider_conf, request_body = Providers.parse_config(self) local keep_alive = provider_conf.keep_alive or "5m" if not provider_conf.model or provider_conf.model == "" then Utils.error("Ollama: model must be specified in config") return nil end if not provider_conf.endpoint then Utils.error("Ollama: endpoint must be specified in config") return nil end local headers = { ["Content-Type"] = "application/json", ["Accept"] = "application/json", } if Providers.env.require_api_key(provider_conf) then local api_key = self.parse_api_key() if api_key and api_key ~= "" then headers["Authorization"] = "Bearer " .. api_key else Utils.info((Config.provider or "Provider") .. ": API key not set, continuing without authentication") end end return { url = Utils.url_join(provider_conf.endpoint, "/api/chat"), headers = Utils.tbl_override(headers, self.extra_headers), body = vim.tbl_deep_extend("force", { model = provider_conf.model, messages = self:parse_messages(prompt_opts), stream = true, keep_alive = keep_alive, }, request_body), } end ---@param result table M.on_error = function(result) local error_msg = "Ollama API error" if result.body then local ok, body = pcall(vim.json.decode, result.body) if ok and body.error then error_msg = body.error end end Utils.error(error_msg, { title = "Ollama" }) end local curl_errors = { [1] = "Unsupported protocol", [3] = "URL malformed", [5] = "Could not resolve proxy", [6] = "Could not resolve host", [7] = "Failed to connect to host", [23] = "Failed writing received data to disk", [28] = "Operation timed out", [35] = "SSL/TLS connection error", [47] = "Too many redirects", [52] = "Server returned empty response", [56] = "Failure in receiving network data", [60] = "Peer certificate cannot be authenticated with known CA certificates (SSL cert issue)", } ---Queries configured endpoint for the list of available models ---@param opts AvanteProviderFunctor Provider settings ---@param timeout? integer Timeout in milliseconds ---@return table[]|nil models List of available models ---@return string|nil error Error message in case of failure local function query_models(opts, timeout) -- Parse provider config and construct tags endpoint URL local provider_conf = Providers.parse_config(opts) if not provider_conf.endpoint then return nil, "Ollama requires endpoint configuration" end local curl = require("plenary.curl") local tags_url = Utils.url_join(provider_conf.endpoint, "/api/tags") local base_headers = { ["Content-Type"] = "application/json", ["Accept"] = "application/json", } local headers = Utils.tbl_override(base_headers, opts.extra_headers) -- Request the model tags from Ollama local response = {} local job = curl.get(tags_url, { headers = headers, callback = function(output) response = output end, on_error = function(err) response = { exit = err.exit } end, }) local job_ok, error = pcall(job.wait, job, timeout or 10000) if not job_ok then return nil, "Ollama: curl command invocation failed: " .. error elseif response.exit ~= 0 then local err_msg = curl_errors[response.exit] or ("curl returned error: " .. response.exit) return nil, "Ollama: " .. err_msg elseif response.status ~= 200 then return nil, "Failed to fetch Ollama models: " .. (response.body or response.status) end -- Parse the response body local ok, res_body = pcall(vim.json.decode, response.body) if not ok then return nil, "Failed to parse model list query response" end return res_body.models or {} end -- List available models using Ollama's tags API function M:list_models() -- Return cached models if available if self._model_list_cache then return self._model_list_cache end local result, error = query_models(self) if not result then assert(error) Utils.error(error) return {} end -- Helper to format model display string from its details local function format_display_name(details) local parts = {} for _, key in ipairs({ "family", "parameter_size", "quantization_level" }) do if details[key] then table.insert(parts, details[key]) end end return table.concat(parts, ", ") end -- Format the models list local models = {} for _, model in ipairs(result) do local details = model.details or {} local display = format_display_name(details) table.insert(models, { id = model.name, name = string.format("ollama/%s (%s)", model.name, display), display_name = model.name, provider_name = "ollama", version = model.digest, }) end self._model_list_cache = models return models end function M.check_endpoint_alive() local result = query_models(Providers.ollama, 1000) return result ~= nil end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/openai.lua
Lua
local Utils = require("avante.utils") local Config = require("avante.config") local Clipboard = require("avante.clipboard") local Providers = require("avante.providers") local HistoryMessage = require("avante.history.message") local ReActParser = require("avante.libs.ReAct_parser2") local JsonParser = require("avante.libs.jsonparser") local Prompts = require("avante.utils.prompts") local LlmTools = require("avante.llm_tools") ---@class AvanteProviderFunctor local M = {} M.api_key_name = "OPENAI_API_KEY" M.role_map = { user = "user", assistant = "assistant", } function M:is_disable_stream() return false end ---@param tool AvanteLLMTool ---@return AvanteOpenAITool function M:transform_tool(tool) local input_schema_properties, required = Utils.llm_tool_param_fields_to_json_schema(tool.param.fields) ---@type AvanteOpenAIToolFunctionParameters local parameters = { type = "object", properties = input_schema_properties, required = required, additionalProperties = false, } ---@type AvanteOpenAITool local res = { type = "function", ["function"] = { name = tool.name, description = tool.get_description and tool.get_description() or tool.description, parameters = parameters, }, } return res end function M.is_openrouter(url) return url:match("^https://openrouter%.ai/") end function M.is_mistral(url) return url:match("^https://api%.mistral%.ai/") end ---@param opts AvantePromptOptions function M.get_user_message(opts) vim.deprecate("get_user_message", "parse_messages", "0.1.0", "avante.nvim") return table.concat( vim .iter(opts.messages) :filter(function(_, value) return value == nil or value.role ~= "user" end) :fold({}, function(acc, value) acc = vim.list_extend({}, acc) acc = vim.list_extend(acc, { value.content }) return acc end), "\n" ) end function M.is_reasoning_model(model) return model and (string.match(model, "^o%d+") ~= nil or (string.match(model, "gpt%-5") ~= nil and model ~= "gpt-5-chat")) end function M.set_allowed_params(provider_conf, request_body) local use_response_api = Providers.resolve_use_response_api(provider_conf, nil) if M.is_reasoning_model(provider_conf.model) then -- Reasoning models have specific parameter requirements request_body.temperature = 1 -- Response API doesn't support temperature for reasoning models if use_response_api then request_body.temperature = nil end else request_body.reasoning_effort = nil request_body.reasoning = nil end -- If max_tokens is set in config, unset max_completion_tokens if request_body.max_tokens then request_body.max_completion_tokens = nil end -- Handle Response API specific parameters if use_response_api then -- Convert reasoning_effort to reasoning object for Response API if request_body.reasoning_effort then request_body.reasoning = { effort = request_body.reasoning_effort, } request_body.reasoning_effort = nil end -- Response API doesn't support some parameters -- Remove unsupported parameters for Response API local unsupported_params = { "top_p", "frequency_penalty", "presence_penalty", "logit_bias", "logprobs", "top_logprobs", "n", } for _, param in ipairs(unsupported_params) do request_body[param] = nil end end end function M:parse_messages(opts) local messages = {} local provider_conf, _ = Providers.parse_config(self) local use_response_api = Providers.resolve_use_response_api(provider_conf, opts) local use_ReAct_prompt = provider_conf.use_ReAct_prompt == true local system_prompt = opts.system_prompt if use_ReAct_prompt then system_prompt = Prompts.get_ReAct_system_prompt(provider_conf, opts) end if self.is_reasoning_model(provider_conf.model) then table.insert(messages, { role = "developer", content = system_prompt }) else table.insert(messages, { role = "system", content = system_prompt }) end local has_tool_use = false vim.iter(opts.messages):each(function(msg) if type(msg.content) == "string" then table.insert(messages, { role = self.role_map[msg.role], content = msg.content }) elseif type(msg.content) == "table" then -- Check if this is a reasoning message (object with type "reasoning") if msg.content.type == "reasoning" then -- Add reasoning message directly (for Response API) table.insert(messages, { type = "reasoning", id = msg.content.id, encrypted_content = msg.content.encrypted_content, summary = msg.content.summary, }) return end local content = {} local tool_calls = {} local tool_results = {} for _, item in ipairs(msg.content) do if type(item) == "string" then table.insert(content, { type = "text", text = item }) elseif item.type == "text" then table.insert(content, { type = "text", text = item.text }) elseif item.type == "image" then table.insert(content, { type = "image_url", image_url = { url = "data:" .. item.source.media_type .. ";" .. item.source.type .. "," .. item.source.data, }, }) elseif item.type == "reasoning" then -- Add reasoning message directly (for Response API) table.insert(messages, { type = "reasoning", id = item.id, encrypted_content = item.encrypted_content, summary = item.summary, }) elseif item.type == "tool_use" and not use_ReAct_prompt then has_tool_use = true table.insert(tool_calls, { id = item.id, type = "function", ["function"] = { name = item.name, arguments = vim.json.encode(item.input) }, }) elseif item.type == "tool_result" and has_tool_use and not use_ReAct_prompt then table.insert( tool_results, { tool_call_id = item.tool_use_id, content = item.is_error and "Error: " .. item.content or item.content } ) end end if not provider_conf.disable_tools and use_ReAct_prompt then if msg.content[1].type == "tool_result" then local tool_use_msg = nil for _, msg_ in ipairs(opts.messages) do if type(msg_.content) == "table" and #msg_.content > 0 then if msg_.content[1].type == "tool_use" and msg_.content[1].id == msg.content[1].tool_use_id then tool_use_msg = msg_ break end end end if tool_use_msg then msg.role = "user" table.insert(content, { type = "text", text = "The result of tool use " .. Utils.tool_use_to_xml(tool_use_msg.content[1]) .. " is:\n", }) table.insert(content, { type = "text", text = msg.content[1].content, }) end end end if #content > 0 then table.insert(messages, { role = self.role_map[msg.role], content = content }) end if not provider_conf.disable_tools and not use_ReAct_prompt then if #tool_calls > 0 then -- Only skip tool_calls if using Response API with previous_response_id support -- Copilot uses Response API format but doesn't support previous_response_id local should_include_tool_calls = not use_response_api or not provider_conf.support_previous_response_id if should_include_tool_calls then -- For Response API without previous_response_id support (like Copilot), -- convert tool_calls to function_call items in input if use_response_api then for _, tool_call in ipairs(tool_calls) do table.insert(messages, { type = "function_call", call_id = tool_call.id, name = tool_call["function"].name, arguments = tool_call["function"].arguments, }) end else -- Chat Completions API format local last_message = messages[#messages] if last_message and last_message.role == self.role_map["assistant"] and last_message.tool_calls then last_message.tool_calls = vim.list_extend(last_message.tool_calls, tool_calls) if not last_message.content then last_message.content = "" end else table.insert(messages, { role = self.role_map["assistant"], tool_calls = tool_calls, content = "" }) end end end -- If support_previous_response_id is true, Response API manages function call history -- So we can skip adding tool_calls to input messages end if #tool_results > 0 then for _, tool_result in ipairs(tool_results) do -- Response API uses different format for function outputs if use_response_api then table.insert(messages, { type = "function_call_output", call_id = tool_result.tool_call_id, output = tool_result.content or "", }) else table.insert( messages, { role = "tool", tool_call_id = tool_result.tool_call_id, content = tool_result.content or "" } ) end end end end end end) if Config.behaviour.support_paste_from_clipboard and opts.image_paths and #opts.image_paths > 0 then local message_content = messages[#messages].content if type(message_content) ~= "table" or message_content[1] == nil then message_content = { { type = "text", text = message_content } } end for _, image_path in ipairs(opts.image_paths) do table.insert(message_content, { type = "image_url", image_url = { url = "data:image/png;base64," .. Clipboard.get_base64_content(image_path), }, }) end messages[#messages].content = message_content end local final_messages = {} local prev_role = nil local prev_type = nil vim.iter(messages):each(function(message) local role = message.role if role == prev_role and role ~= "tool" and prev_type ~= "function_call" and prev_type ~= "function_call_output" then if role == self.role_map["assistant"] then table.insert(final_messages, { role = self.role_map["user"], content = "Ok" }) else table.insert(final_messages, { role = self.role_map["assistant"], content = "Ok, I understand." }) end else if role == "user" and prev_role == "tool" and M.is_mistral(provider_conf.endpoint) then table.insert(final_messages, { role = self.role_map["assistant"], content = "Ok, I understand." }) end end prev_role = role prev_type = message.type table.insert(final_messages, message) end) return final_messages end function M:finish_pending_messages(ctx, opts) if ctx.content ~= nil and ctx.content ~= "" then self:add_text_message(ctx, "", "generated", opts) end if ctx.tool_use_map then for _, tool_use in pairs(ctx.tool_use_map) do if tool_use.state == "generating" then self:add_tool_use_message(ctx, tool_use, "generated", opts) end end end end local llm_tool_names = nil function M:add_text_message(ctx, text, state, opts) if llm_tool_names == nil then llm_tool_names = LlmTools.get_tool_names() end if ctx.content == nil then ctx.content = "" end ctx.content = ctx.content .. text local content = ctx.content:gsub("<tool_code>", ""):gsub("</tool_code>", ""):gsub("<tool_call>", ""):gsub("</tool_call>", "") ctx.content = content local msg = HistoryMessage:new("assistant", ctx.content, { state = state, uuid = ctx.content_uuid, original_content = ctx.content, }) ctx.content_uuid = msg.uuid local msgs = { msg } local xml_content = ctx.content local xml_lines = vim.split(xml_content, "\n") local cleaned_xml_lines = {} local prev_tool_name = nil for _, line in ipairs(xml_lines) do if line:match("<tool_name>") then local tool_name = line:match("<tool_name>(.*)</tool_name>") if tool_name then prev_tool_name = tool_name end elseif line:match("<parameters>") then if prev_tool_name then table.insert(cleaned_xml_lines, "<" .. prev_tool_name .. ">") end goto continue elseif line:match("</parameters>") then if prev_tool_name then table.insert(cleaned_xml_lines, "</" .. prev_tool_name .. ">") end goto continue end table.insert(cleaned_xml_lines, line) ::continue:: end local cleaned_xml_content = table.concat(cleaned_xml_lines, "\n") local xml = ReActParser.parse(cleaned_xml_content) if xml and #xml > 0 then local new_content_list = {} local xml_md_openned = false for idx, item in ipairs(xml) do if item.type == "text" then local cleaned_lines = {} local lines = vim.split(item.text, "\n") for _, line in ipairs(lines) do if line:match("^```xml") or line:match("^```tool_code") or line:match("^```tool_use") then xml_md_openned = true elseif line:match("^```$") then if xml_md_openned then xml_md_openned = false else table.insert(cleaned_lines, line) end else table.insert(cleaned_lines, line) end end table.insert(new_content_list, table.concat(cleaned_lines, "\n")) goto continue end if not vim.tbl_contains(llm_tool_names, item.tool_name) then goto continue end local input = {} for k, v in pairs(item.tool_input or {}) do local ok, jsn = pcall(vim.json.decode, v) if ok and jsn then input[k] = jsn else input[k] = v end end if next(input) ~= nil then local msg_uuid = ctx.content_uuid .. "-" .. idx local tool_use_id = msg_uuid local tool_message_state = item.partial and "generating" or "generated" local msg_ = HistoryMessage:new("assistant", { type = "tool_use", name = item.tool_name, id = tool_use_id, input = input, }, { state = tool_message_state, uuid = msg_uuid, turn_id = ctx.turn_id, }) msgs[#msgs + 1] = msg_ ctx.tool_use_map = ctx.tool_use_map or {} local input_json = type(input) == "string" and input or vim.json.encode(input) local exists = false for _, tool_use in pairs(ctx.tool_use_map) do if tool_use.id == tool_use_id then tool_use.input_json = input_json exists = true end end if not exists then local tool_key = tostring(vim.tbl_count(ctx.tool_use_map)) ctx.tool_use_map[tool_key] = { uuid = tool_use_id, id = tool_use_id, name = item.tool_name, input_json = input_json, state = "generating", } end opts.on_stop({ reason = "tool_use", streaming_tool_use = item.partial }) end ::continue:: end msg.message.content = table.concat(new_content_list, "\n"):gsub("\n+$", "\n") end if opts.on_messages_add then opts.on_messages_add(msgs) end end function M:add_thinking_message(ctx, text, state, opts) if ctx.reasonging_content == nil then ctx.reasonging_content = "" end ctx.reasonging_content = ctx.reasonging_content .. text local msg = HistoryMessage:new("assistant", { type = "thinking", thinking = ctx.reasonging_content, signature = "", }, { state = state, uuid = ctx.reasonging_content_uuid, turn_id = ctx.turn_id, }) ctx.reasonging_content_uuid = msg.uuid if opts.on_messages_add then opts.on_messages_add({ msg }) end end function M:add_tool_use_message(ctx, tool_use, state, opts) local jsn = JsonParser.parse(tool_use.input_json) -- Fix: Ensure empty arguments are encoded as {} (object) not [] (array) if jsn == nil or (type(jsn) == "table" and vim.tbl_isempty(jsn)) then jsn = vim.empty_dict() end local msg = HistoryMessage:new("assistant", { type = "tool_use", name = tool_use.name, id = tool_use.id, input = jsn, }, { state = state, uuid = tool_use.uuid, turn_id = ctx.turn_id, }) tool_use.uuid = msg.uuid tool_use.state = state if opts.on_messages_add then opts.on_messages_add({ msg }) end if state == "generating" then opts.on_stop({ reason = "tool_use", streaming_tool_use = true }) end end function M:add_reasoning_message(ctx, reasoning_item, opts) local msg = HistoryMessage:new("assistant", { type = "reasoning", id = reasoning_item.id, encrypted_content = reasoning_item.encrypted_content, summary = reasoning_item.summary, }, { state = "generated", uuid = Utils.uuid(), turn_id = ctx.turn_id, }) if opts.on_messages_add then opts.on_messages_add({ msg }) end end ---@param usage avante.OpenAITokenUsage | nil ---@return avante.LLMTokenUsage | nil function M.transform_openai_usage(usage) if not usage then return nil end if usage == vim.NIL then return nil end ---@type avante.LLMTokenUsage local res = { prompt_tokens = usage.prompt_tokens, completion_tokens = usage.completion_tokens, } return res end function M:parse_response(ctx, data_stream, _, opts) if data_stream:match('"%[DONE%]":') or data_stream == "[DONE]" then self:finish_pending_messages(ctx, opts) if ctx.tool_use_map and vim.tbl_count(ctx.tool_use_map) > 0 then ctx.tool_use_map = {} opts.on_stop({ reason = "tool_use" }) else opts.on_stop({ reason = "complete" }) end return end local jsn = vim.json.decode(data_stream) -- Check if this is a Response API event (has 'type' field) if jsn.type and type(jsn.type) == "string" then -- Response API event-driven format if jsn.type == "response.output_text.delta" then -- Text content delta if jsn.delta and jsn.delta ~= vim.NIL and jsn.delta ~= "" then if opts.on_chunk then opts.on_chunk(jsn.delta) end self:add_text_message(ctx, jsn.delta, "generating", opts) end elseif jsn.type == "response.reasoning_summary_text.delta" then -- Reasoning summary delta if jsn.delta and jsn.delta ~= vim.NIL and jsn.delta ~= "" then if ctx.returned_think_start_tag == nil or not ctx.returned_think_start_tag then ctx.returned_think_start_tag = true if opts.on_chunk then opts.on_chunk("<think>\n") end end ctx.last_think_content = jsn.delta self:add_thinking_message(ctx, jsn.delta, "generating", opts) if opts.on_chunk then opts.on_chunk(jsn.delta) end end elseif jsn.type == "response.function_call_arguments.delta" then -- Function call arguments delta if jsn.delta and jsn.delta ~= vim.NIL and jsn.delta ~= "" then if not ctx.tool_use_map then ctx.tool_use_map = {} end local tool_key = tostring(jsn.output_index or 0) if not ctx.tool_use_map[tool_key] then ctx.tool_use_map[tool_key] = { name = jsn.name or "", id = jsn.call_id or "", input_json = jsn.delta, } else ctx.tool_use_map[tool_key].input_json = ctx.tool_use_map[tool_key].input_json .. jsn.delta end end elseif jsn.type == "response.output_item.added" then -- Output item added (could be function call or reasoning) if jsn.item and jsn.item.type == "function_call" then local tool_key = tostring(jsn.output_index or 0) if not ctx.tool_use_map then ctx.tool_use_map = {} end ctx.tool_use_map[tool_key] = { name = jsn.item.name or "", id = jsn.item.call_id or jsn.item.id or "", input_json = "", } self:add_tool_use_message(ctx, ctx.tool_use_map[tool_key], "generating", opts) elseif jsn.item and jsn.item.type == "reasoning" then -- Add reasoning item to history self:add_reasoning_message(ctx, jsn.item, opts) end elseif jsn.type == "response.output_item.done" then -- Output item done (finalize function call) if jsn.item and jsn.item.type == "function_call" then local tool_key = tostring(jsn.output_index or 0) if ctx.tool_use_map and ctx.tool_use_map[tool_key] then local tool_use = ctx.tool_use_map[tool_key] if jsn.item.arguments then tool_use.input_json = jsn.item.arguments end self:add_tool_use_message(ctx, tool_use, "generated", opts) end end elseif jsn.type == "response.completed" or jsn.type == "response.done" then -- Response completed - save response.id for future requests if jsn.response and jsn.response.id then ctx.last_response_id = jsn.response.id -- Store in provider for next request self.last_response_id = jsn.response.id end if ctx.returned_think_start_tag ~= nil and (ctx.returned_think_end_tag == nil or not ctx.returned_think_end_tag) then ctx.returned_think_end_tag = true if opts.on_chunk then if ctx.last_think_content and ctx.last_think_content ~= vim.NIL and ctx.last_think_content:sub(-1) ~= "\n" then opts.on_chunk("\n</think>\n") else opts.on_chunk("</think>\n") end end self:add_thinking_message(ctx, "", "generated", opts) end self:finish_pending_messages(ctx, opts) local usage = nil if jsn.response and jsn.response.usage then usage = self.transform_openai_usage(jsn.response.usage) end if ctx.tool_use_map and vim.tbl_count(ctx.tool_use_map) > 0 then opts.on_stop({ reason = "tool_use", usage = usage }) else opts.on_stop({ reason = "complete", usage = usage }) end elseif jsn.type == "error" then -- Error event local error_msg = jsn.error and vim.inspect(jsn.error) or "Unknown error" opts.on_stop({ reason = "error", error = error_msg }) end return end -- Chat Completions API format (original code) if jsn.usage and jsn.usage ~= vim.NIL then if opts.update_tokens_usage then local usage = self.transform_openai_usage(jsn.usage) if usage then opts.update_tokens_usage(usage) end end end if jsn.error and jsn.error ~= vim.NIL then opts.on_stop({ reason = "error", error = vim.inspect(jsn.error) }) return end ---@cast jsn AvanteOpenAIChatResponse if not jsn.choices then return end local choice = jsn.choices[1] if not choice then return end local delta = choice.delta if not delta then local provider_conf = Providers.parse_config(self) if provider_conf.model:match("o1") then delta = choice.message end end if not delta then return end if delta.reasoning_content and delta.reasoning_content ~= vim.NIL and delta.reasoning_content ~= "" then if ctx.returned_think_start_tag == nil or not ctx.returned_think_start_tag then ctx.returned_think_start_tag = true if opts.on_chunk then opts.on_chunk("<think>\n") end end ctx.last_think_content = delta.reasoning_content self:add_thinking_message(ctx, delta.reasoning_content, "generating", opts) if opts.on_chunk then opts.on_chunk(delta.reasoning_content) end elseif delta.reasoning and delta.reasoning ~= vim.NIL then if ctx.returned_think_start_tag == nil or not ctx.returned_think_start_tag then ctx.returned_think_start_tag = true if opts.on_chunk then opts.on_chunk("<think>\n") end end ctx.last_think_content = delta.reasoning self:add_thinking_message(ctx, delta.reasoning, "generating", opts) if opts.on_chunk then opts.on_chunk(delta.reasoning) end elseif delta.tool_calls and delta.tool_calls ~= vim.NIL then local choice_index = choice.index or 0 for idx, tool_call in ipairs(delta.tool_calls) do --- In Gemini's so-called OpenAI Compatible API, tool_call.index is nil, which is quite absurd! Therefore, a compatibility fix is needed here. if tool_call.index == nil then tool_call.index = choice_index + idx - 1 end if not ctx.tool_use_map then ctx.tool_use_map = {} end local tool_key = tostring(tool_call.index) local prev_tool_key = tostring(tool_call.index - 1) if not ctx.tool_use_map[tool_key] then local prev_tool_use = ctx.tool_use_map[prev_tool_key] if tool_call.index > 0 and prev_tool_use then self:add_tool_use_message(ctx, prev_tool_use, "generated", opts) end local tool_use = { name = tool_call["function"].name, id = tool_call.id, input_json = type(tool_call["function"].arguments) == "string" and tool_call["function"].arguments or "", } ctx.tool_use_map[tool_key] = tool_use self:add_tool_use_message(ctx, tool_use, "generating", opts) else local tool_use = ctx.tool_use_map[tool_key] if tool_call["function"].arguments == vim.NIL then tool_call["function"].arguments = "" end tool_use.input_json = tool_use.input_json .. tool_call["function"].arguments -- self:add_tool_use_message(ctx, tool_use, "generating", opts) end end elseif delta.content then if ctx.returned_think_start_tag ~= nil and (ctx.returned_think_end_tag == nil or not ctx.returned_think_end_tag) then ctx.returned_think_end_tag = true if opts.on_chunk then if ctx.last_think_content and ctx.last_think_content ~= vim.NIL and ctx.last_think_content:sub(-1) ~= "\n" then opts.on_chunk("\n</think>\n") else opts.on_chunk("</think>\n") end end self:add_thinking_message(ctx, "", "generated", opts) end if delta.content ~= vim.NIL then if opts.on_chunk then opts.on_chunk(delta.content) end self:add_text_message(ctx, delta.content, "generating", opts) end end if choice.finish_reason == "stop" or choice.finish_reason == "eos_token" or choice.finish_reason == "length" then self:finish_pending_messages(ctx, opts) if ctx.tool_use_map and vim.tbl_count(ctx.tool_use_map) > 0 then opts.on_stop({ reason = "tool_use", usage = self.transform_openai_usage(jsn.usage) }) else opts.on_stop({ reason = "complete", usage = self.transform_openai_usage(jsn.usage) }) end end if choice.finish_reason == "tool_calls" then self:finish_pending_messages(ctx, opts) opts.on_stop({ reason = "tool_use", usage = self.transform_openai_usage(jsn.usage), }) end end function M:parse_response_without_stream(data, _, opts) ---@type AvanteOpenAIChatResponse local json = vim.json.decode(data) if json.choices and json.choices[1] then local choice = json.choices[1] if choice.message and choice.message.content then if opts.on_chunk then opts.on_chunk(choice.message.content) end self:add_text_message({}, choice.message.content, "generated", opts) vim.schedule(function() opts.on_stop({ reason = "complete" }) end) end end end ---@param prompt_opts AvantePromptOptions ---@return AvanteCurlOutput|nil function M:parse_curl_args(prompt_opts) local provider_conf, request_body = Providers.parse_config(self) local disable_tools = provider_conf.disable_tools or false local headers = { ["Content-Type"] = "application/json", } if Providers.env.require_api_key(provider_conf) then local api_key = self.parse_api_key() if api_key == nil then Utils.error(Config.provider .. ": API key is not set, please set it in your environment variable or config file") return nil end headers["Authorization"] = "Bearer " .. api_key end if M.is_openrouter(provider_conf.endpoint) then headers["HTTP-Referer"] = "https://github.com/yetone/avante.nvim" headers["X-Title"] = "Avante.nvim" request_body.include_reasoning = true end self.set_allowed_params(provider_conf, request_body) local use_response_api = Providers.resolve_use_response_api(provider_conf, prompt_opts) local use_ReAct_prompt = provider_conf.use_ReAct_prompt == true local tools = nil if not disable_tools and prompt_opts.tools and not use_ReAct_prompt then tools = {} for _, tool in ipairs(prompt_opts.tools) do local transformed_tool = self:transform_tool(tool) -- Response API uses flattened tool structure if use_response_api then -- Convert from {type: "function", function: {name, description, parameters}} -- to {type: "function", name, description, parameters} if transformed_tool.type == "function" and transformed_tool["function"] then transformed_tool = { type = "function", name = transformed_tool["function"].name, description = transformed_tool["function"].description, parameters = transformed_tool["function"].parameters, } end end table.insert(tools, transformed_tool) end end Utils.debug("endpoint", provider_conf.endpoint) Utils.debug("model", provider_conf.model) local stop = nil if use_ReAct_prompt then stop = { "</tool_use>" } end -- Determine endpoint path based on use_response_api local endpoint_path = use_response_api and "/responses" or "/chat/completions" local parsed_messages = self:parse_messages(prompt_opts) -- Build base body local base_body = { model = provider_conf.model, stop = stop, stream = true, tools = tools, } -- Response API uses 'input' instead of 'messages' if use_response_api then -- Check if we have tool results - if so, use previous_response_id local has_function_outputs = false for _, msg in ipairs(parsed_messages) do if msg.type == "function_call_output" then has_function_outputs = true break end end if has_function_outputs and self.last_response_id then -- When sending function outputs, use previous_response_id base_body.previous_response_id = self.last_response_id -- Only send the function outputs, not the full history local function_outputs = {} for _, msg in ipairs(parsed_messages) do if msg.type == "function_call_output" then table.insert(function_outputs, msg) end end base_body.input = function_outputs -- Clear the stored response_id after using it self.last_response_id = nil else -- Normal request without tool results base_body.input = parsed_messages end -- Response API uses max_output_tokens instead of max_tokens/max_completion_tokens if request_body.max_completion_tokens then request_body.max_output_tokens = request_body.max_completion_tokens request_body.max_completion_tokens = nil end if request_body.max_tokens then request_body.max_output_tokens = request_body.max_tokens request_body.max_tokens = nil end -- Response API doesn't use stream_options base_body.stream_options = nil else base_body.messages = parsed_messages base_body.stream_options = not M.is_mistral(provider_conf.endpoint) and { include_usage = true, } or nil end return { url = Utils.url_join(provider_conf.endpoint, endpoint_path), proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, headers = Utils.tbl_override(headers, self.extra_headers), body = vim.tbl_deep_extend("force", base_body, request_body), } end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/vertex.lua
Lua
local P = require("avante.providers") local Utils = require("avante.utils") local Gemini = require("avante.providers.gemini") ---@class AvanteProviderFunctor local M = {} M.api_key_name = "cmd:gcloud auth application-default print-access-token" M.role_map = { user = "user", assistant = "model", } M.is_disable_stream = Gemini.is_disable_stream M.parse_messages = Gemini.parse_messages M.parse_response = Gemini.parse_response M.transform_to_function_declaration = Gemini.transform_to_function_declaration local function execute_command(command) local handle = io.popen(command .. " 2>/dev/null") if not handle then error("Failed to execute command: " .. command) end local result = handle:read("*a") handle:close() return result:match("^%s*(.-)%s*$") end local function parse_cmd(cmd_input, error_msg) if not cmd_input:match("^cmd:") then if not error_msg then error("Invalid cmd: Expected 'cmd:<command>' format, got '" .. cmd_input .. "'") else error(error_msg) end end local command = cmd_input:sub(5) local direct_output = execute_command(command) return direct_output end function M.parse_api_key() return parse_cmd( M.api_key_name, "Invalid api_key_name: Expected 'cmd:<command>' format, got '" .. M.api_key_name .. "'" ) end function M:parse_curl_args(prompt_opts) local provider_conf, request_body = P.parse_config(self) local model_id = provider_conf.model or "default-model-id" local project_id = vim.fn.getenv("GOOGLE_CLOUD_PROJECT") or parse_cmd("cmd:gcloud config get-value project") local location = vim.fn.getenv("GOOGLE_CLOUD_LOCATION") -- same as gemini-cli if project_id == nil or project_id == vim.NIL then project_id = "default-project-id" end if location == nil or location == vim.NIL then location = "global" end local url = provider_conf.endpoint:gsub("LOCATION", location):gsub("PROJECT_ID", project_id) url = string.format("%s/%s:streamGenerateContent?alt=sse", url, model_id) local bearer_token = M.parse_api_key() return { url = url, headers = Utils.tbl_override({ ["Authorization"] = "Bearer " .. bearer_token, ["Content-Type"] = "application/json; charset=utf-8", }, self.extra_headers), proxy = provider_conf.proxy, insecure = provider_conf.allow_insecure, body = Gemini.prepare_request_body(self, prompt_opts, provider_conf, request_body), } end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/vertex_claude.lua
Lua
local P = require("avante.providers") local Utils = require("avante.utils") local Vertex = require("avante.providers.vertex") ---@class AvanteProviderFunctor local M = {} M.role_map = { user = "user", assistant = "assistant", } M.is_disable_stream = P.claude.is_disable_stream M.parse_messages = P.claude.parse_messages M.parse_response = P.claude.parse_response M.parse_api_key = Vertex.parse_api_key M.on_error = Vertex.on_error M.transform_anthropic_usage = P.claude.transform_anthropic_usage Vertex.api_key_name = "cmd:gcloud auth print-access-token" ---@param prompt_opts AvantePromptOptions function M:parse_curl_args(prompt_opts) local provider_conf, request_body = P.parse_config(self) local disable_tools = provider_conf.disable_tools or false local location = vim.fn.getenv("LOCATION") local project_id = vim.fn.getenv("PROJECT_ID") local model_id = provider_conf.model or "default-model-id" if location == nil or location == vim.NIL then location = "default-location" end if project_id == nil or project_id == vim.NIL then project_id = "default-project-id" end local url = provider_conf.endpoint:gsub("LOCATION", location):gsub("PROJECT_ID", project_id) url = string.format("%s/%s:streamRawPredict", url, model_id) local system_prompt = prompt_opts.system_prompt or "" local messages = self:parse_messages(prompt_opts) local tools = {} if not disable_tools and prompt_opts.tools then for _, tool in ipairs(prompt_opts.tools) do table.insert(tools, P.claude:transform_tool(tool)) end end if self.support_prompt_caching and #tools > 0 then local last_tool = vim.deepcopy(tools[#tools]) last_tool.cache_control = { type = "ephemeral" } tools[#tools] = last_tool end request_body = vim.tbl_deep_extend("force", request_body, { anthropic_version = "vertex-2023-10-16", temperature = 0.75, max_tokens = 4096, stream = true, messages = messages, system = { { type = "text", text = system_prompt, cache_control = { type = "ephemeral" }, }, }, tools = tools, }) return { url = url, headers = Utils.tbl_override({ ["Authorization"] = "Bearer " .. Vertex.parse_api_key(), ["Content-Type"] = "application/json; charset=utf-8", }, self.extra_headers), body = vim.tbl_deep_extend("force", {}, request_body), } end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/providers/watsonx_code_assistant.lua
Lua
-- Documentation for setting up IBM Watsonx Code Assistant --- Generating an access token: https://www.ibm.com/products/watsonx-code-assistant or https://github.ibm.com/code-assistant/wca-api local P = require("avante.providers") local Utils = require("avante.utils") local curl = require("plenary.curl") local Config = require("avante.config") local Llm = require("avante.llm") local ts_utils = pcall(require, "nvim-treesitter.ts_utils") and require("nvim-treesitter.ts_utils") or { get_node_at_cursor = function() return nil end, } local OpenAI = require("avante.providers.openai") ---@class AvanteProviderFunctor local M = {} M.api_key_name = "WCA_API_KEY" -- The name of the environment variable that contains the API key M.role_map = { user = "USER", assistant = "ASSISTANT", system = "SYSTEM", } M.last_iam_token_time = nil M.iam_bearer_token = "" function M:is_disable_stream() return true end ---@type fun(self: AvanteProviderFunctor, opts: AvantePromptOptions): table function M:parse_messages(opts) if opts == nil then return {} end local messages if opts.system_prompt == "WCA_COMMAND" then messages = {} else messages = { { content = opts.system_prompt, role = "SYSTEM" }, } end vim .iter(opts.messages) :each(function(msg) table.insert(messages, { content = msg.content, role = M.role_map[msg.role] }) end) return messages end --- This function will be used to parse incoming SSE stream --- It takes in the data stream as the first argument, followed by SSE event state, and opts --- retrieved from given buffer. --- This opts include: --- - on_chunk: (fun(chunk: string): any) this is invoked on parsing correct delta chunk --- - on_complete: (fun(err: string|nil): any) this is invoked on either complete call or error chunk local function parse_response_wo_stream(self, data, _, opts) if Utils.debug then Utils.debug("WCA parse_response_without_stream called with opts: " .. vim.inspect(opts)) end local json = vim.json.decode(data) if Utils.debug then Utils.debug("WCA Response: " .. vim.inspect(json)) end if json.error ~= nil and json.error ~= vim.NIL then Utils.warn("WCA Error " .. tostring(json.error.code) .. ": " .. tostring(json.error.message)) end if json.response and json.response.message and json.response.message.content then local content = json.response.message.content if Utils.debug then Utils.debug("WCA Original Content: " .. tostring(content)) end -- Clean up the content by removing XML-like tags that are not part of the actual response -- These tags appear to be internal formatting from watsonx that should not be shown to users -- Use more careful patterns to avoid removing too much content content = content:gsub("<file>\n?", "") content = content:gsub("\n?</file>", "") content = content:gsub("\n?<memory>.-</memory>\n?", "") content = content:gsub("\n?<write_todos>.-</write_todos>\n?", "") content = content:gsub("\n?<attempt_completion>.-</attempt_completion>\n?", "") -- Trim excessive whitespace but preserve structure content = content:gsub("^\n+", ""):gsub("\n+$", "") if Utils.debug then Utils.debug("WCA Cleaned Content: " .. tostring(content)) end -- Ensure we still have content after cleaning if content and content ~= "" then if opts.on_chunk then opts.on_chunk(content) end -- Add the text message for UI display (similar to OpenAI provider) OpenAI:add_text_message({}, content, "generated", opts) else Utils.warn("WCA: Content became empty after cleaning") if opts.on_chunk then opts.on_chunk(json.response.message.content) -- Fallback to original content end -- Add the original content as fallback OpenAI:add_text_message({}, json.response.message.content, "generated", opts) end vim.schedule(function() if opts.on_stop then opts.on_stop({ reason = "complete" }) end end) elseif json.error and json.error ~= vim.NIL then vim.schedule(function() if opts.on_stop then opts.on_stop({ reason = "error", error = "WCA Error " .. tostring(json.error.code) .. ": " .. tostring(json.error.message), }) end end) else -- Handle case where there's no response content and no explicit error if Utils.debug then Utils.debug("WCA: No content found in response, treating as empty response") end vim.schedule(function() if opts.on_stop then opts.on_stop({ reason = "complete" }) end end) end end M.parse_response_without_stream = parse_response_wo_stream -- Needs to be language specific for each function and methods. local get_function_name_under_cursor = function() local current_node = ts_utils.get_node_at_cursor() if not current_node then return "" end local expr = current_node while expr do if expr:type() == "function_definition" or expr:type() == "method_declaration" then break end expr = expr:parent() end if not expr then return "" end local result = (ts_utils.get_node_text(expr:child(1)))[1] return result end --- It takes in the provider options as the first argument, followed by code_opts retrieved from given buffer. ---@type fun(command_name: string): nil M.method_command = function(command_name) if command_name ~= "document" and command_name ~= "unit-test" and command_name ~= "explain" and command_name:find("translate", 1, true) == 0 then Utils.warn("Invalid command name" .. command_name) end local current_buffer = vim.api.nvim_get_current_buf() local file_path = vim.api.nvim_buf_get_name(current_buffer) -- Use file name for now. For proper extraction of method names, a lang specific TreeSitter querry is need -- local method_name = get_function_name_under_cursor() -- use whole file if we cannot get the method local method_name = "" if method_name == "" then local path_splits = vim.split(file_path, "/") method_name = path_splits[#path_splits] end local sidebar = require("avante").get() if not sidebar then require("avante.api").ask() sidebar = require("avante").get() end if not sidebar:is_open() then sidebar:open({}) end sidebar.file_selector:add_current_buffer() local response_content = "" local provider = P[Config.provider] local content = "/" .. command_name .. " @" .. method_name Llm.curl({ provider = provider, prompt_opts = { system_prompt = "WCA_COMMAND", messages = { { content = content, role = "user" }, }, selected_files = sidebar.file_selector:get_selected_files_contents(), }, handler_opts = { on_start = function(_) end, on_chunk = function(chunk) if not chunk then return end response_content = response_content .. chunk end, on_stop = function(stop_opts) if stop_opts.error ~= nil then Utils.error(string.format("WCA Command " .. command_name .. " failed: %s", vim.inspect(stop_opts.error))) return end if stop_opts.reason == "complete" then if not sidebar:is_open() then sidebar:open({}) end sidebar:update_content(response_content, { focus = true }) end end, }, }) end local function get_iam_bearer_token(provider) if M.last_iam_token_time ~= nil and os.time() - M.last_iam_token_time <= 3550 then return M.iam_bearer_token end local api_key = provider.parse_api_key() if api_key == nil then -- if no api key is available, make a request with a empty api key. api_key = "" end local url = "https://iam.cloud.ibm.com/identity/token" local header = { ["Content-Type"] = "application/x-www-form-urlencoded" } local body = "grant_type=urn:ibm:params:oauth:grant-type:apikey&apikey=" .. api_key local response = curl.post(url, { headers = header, body = body }) if response.status == 200 then -- select first key value pair local access_token_field = vim.split(response.body, ",")[1] -- get value local token = vim.split(access_token_field, ":")[2] -- remove quotes M.iam_bearer_token = (token:gsub("^%p(.*)%p$", "%1")) M.last_iam_token_time = os.time() else Utils.error( "Failed to retrieve IAM token: " .. response.status .. ": " .. vim.inspect(response.body), { title = "Avante WCA" } ) M.iam_bearer_token = "" end return M.iam_bearer_token end local random = math.random math.randomseed(os.time()) local function uuid() local template = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx" return string.gsub(template, "[xy]", function(c) local v = (c == "x") and random(0, 0xf) or random(8, 0xb) return string.format("%x", v) end) end --- This function below will be used to parse in cURL arguments. --- It takes in the provider options as the first argument, followed by code_opts retrieved from given buffer. --- This code_opts include: --- - question: Input from the users --- - code_lang: the language of given code buffer --- - code_content: content of code buffer --- - selected_code_content: (optional) If given code content is selected in visual mode as context. ---@type fun(opts: AvanteProvider, code_opts: AvantePromptOptions): AvanteCurlOutput ---@param provider AvanteProviderFunctor ---@param code_opts AvantePromptOptions ---@return table M.parse_curl_args = function(provider, code_opts) local base, _ = P.parse_config(provider) local headers = { ["Content-Type"] = "multipart/form-data", ["Authorization"] = "Bearer " .. get_iam_bearer_token(provider), ["Request-ID"] = uuid(), } -- Create the message_payload structure as required by WCA API local message_payload = { message_payload = { chat_session_id = uuid(), -- Required for granite-3-8b-instruct model messages = M:parse_messages(code_opts), }, } -- Base64 encode the message payload as required by watsonx API local json_content = vim.json.encode(message_payload) local encoded_json_content = vim.base64.encode(json_content) -- Return form data structure - the message field contains the base64-encoded JSON local body = { message = encoded_json_content, } return { url = base.endpoint, timeout = base.timeout, insecure = false, headers = headers, body = body, } end --- The following function SHOULD only be used when providers doesn't follow SSE spec [ADVANCED] --- this is mutually exclusive with parse_response_data return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/rag_service.lua
Lua
local curl = require("plenary.curl") local Path = require("plenary.path") local Config = require("avante.config") local Utils = require("avante.utils") local M = {} local container_name = "avante-rag-service" local service_path = "/tmp/" .. container_name function M.get_rag_service_image() if Config.rag_service and Config.rag_service.image then return Config.rag_service.image else return "quay.io/yetoneful/avante-rag-service:0.0.11" end end function M.get_rag_service_port() return 20250 end function M.get_rag_service_url() return string.format("http://localhost:%d", M.get_rag_service_port()) end function M.get_data_path() local p = Path:new(vim.fn.stdpath("data")):joinpath("avante/rag_service") if not p:exists() then p:mkdir({ parents = true }) end return p end function M.get_current_image() local cmd = { "docker", "inspect", "--format", "{{.Config.Image}}", container_name } local result = vim.system(cmd, { text = true }):wait() if result.code ~= 0 or result.stdout == "" then return nil end return result.stdout end function M.get_rag_service_runner() return (Config.rag_service and Config.rag_service.runner) or "docker" end ---@param cb fun() function M.launch_rag_service(cb) --- If Config.rag_service.llm.api_key is nil or empty, llm_api_key will be an empty string. local llm_api_key = "" if Config.rag_service and Config.rag_service.llm and Config.rag_service.llm.api_key and Config.rag_service.llm.api_key ~= "" then llm_api_key = os.getenv(Config.rag_service.llm.api_key) or "" if llm_api_key == nil or llm_api_key == "" then error(string.format("cannot launch avante rag service, %s is not set", Config.rag_service.llm.api_key)) return end end --- If Config.rag_service.embed.api_key is nil or empty, embed_api_key will be an empty string. local embed_api_key = "" if Config.rag_service and Config.rag_service.embed and Config.rag_service.embed.api_key and Config.rag_service.embed.api_key ~= "" then embed_api_key = os.getenv(Config.rag_service.embed.api_key) or "" if embed_api_key == nil or embed_api_key == "" then error(string.format("cannot launch avante rag service, %s is not set", Config.rag_service.embed.api_key)) return end end local embed_extra = "{}" -- Default to empty JSON object string if Config.rag_service and Config.rag_service.embed and Config.rag_service.embed.extra then embed_extra = string.format("%q", vim.json.encode(Config.rag_service.embed.extra)) end local llm_extra = "{}" -- Default to empty JSON object string if Config.rag_service and Config.rag_service.llm and Config.rag_service.llm.extra then llm_extra = string.format("%q", vim.json.encode(Config.rag_service.llm.extra)) end local port = M.get_rag_service_port() if M.get_rag_service_runner() == "docker" then local image = M.get_rag_service_image() local data_path = M.get_data_path() local cmd = { "docker", "inspect", "--format", "{{.State.Status}}", container_name } local result = vim.system(cmd, { text = true }):wait() if result.code ~= 0 then Utils.debug(string.format("cmd: %s execution error", table.concat(cmd, " "))) end if result.stdout == "" then Utils.debug(string.format("container %s not found, starting...", container_name)) elseif result.stdout == "running" then Utils.debug(string.format("container %s already running", container_name)) local current_image = M.get_current_image() if current_image == image then cb() return end Utils.debug( string.format( "container %s is running with different image: %s != %s, stopping...", container_name, current_image, image ) ) M.stop_rag_service() end if result.stdout ~= "running" then Utils.info(string.format("container %s already started but not running, stopping...", container_name)) M.stop_rag_service() end local cmd_ = string.format( "docker run --platform=linux/amd64 -d -p 0.0.0.0:%d:%d --name %s -v %s:/data -v %s:/host:ro -e ALLOW_RESET=TRUE -e DATA_DIR=/data -e RAG_EMBED_PROVIDER=%s -e RAG_EMBED_ENDPOINT=%s -e RAG_EMBED_API_KEY=%s -e RAG_EMBED_MODEL=%s -e RAG_EMBED_EXTRA=%s -e RAG_LLM_PROVIDER=%s -e RAG_LLM_ENDPOINT=%s -e RAG_LLM_API_KEY=%s -e RAG_LLM_MODEL=%s -e RAG_LLM_EXTRA=%s %s %s", M.get_rag_service_port(), M.get_rag_service_port(), container_name, data_path, Config.rag_service.host_mount, Config.rag_service.embed.provider, Config.rag_service.embed.endpoint, embed_api_key, Config.rag_service.embed.model, embed_extra, Config.rag_service.llm.provider, Config.rag_service.llm.endpoint, llm_api_key, Config.rag_service.llm.model, llm_extra, Config.rag_service.docker_extra_args, image ) vim.fn.jobstart(cmd_, { detach = true, on_exit = function(_, exit_code) if exit_code ~= 0 then Utils.error(string.format("container %s failed to start, exit code: %d", container_name, exit_code)) else Utils.debug(string.format("container %s started", container_name)) cb() end end, }) elseif M.get_rag_service_runner() == "nix" then -- Check if service is already running local check_cmd = { "pgrep", "-f", service_path } local check_result = vim.system(check_cmd, { text = true }):wait().stdout if check_result ~= "" then Utils.debug(string.format("RAG service already running at %s", service_path)) cb() return end local dirname = Utils.trim(string.sub(debug.getinfo(1).source, 2, #"/lua/avante/rag_service.lua" * -1), { suffix = "/" }) local rag_service_dir = dirname .. "/py/rag-service" Utils.debug(string.format("launching %s with nix...", container_name)) vim.system({ "sh", "run.sh", service_path }, { detach = true, cwd = rag_service_dir, env = { ALLOW_RESET = "TRUE", PORT = port, DATA_DIR = service_path, RAG_EMBED_PROVIDER = Config.rag_service.embed.provider, RAG_EMBED_ENDPOINT = Config.rag_service.embed.endpoint, RAG_EMBED_API_KEY = embed_api_key, RAG_EMBED_MODEL = Config.rag_service.embed.model, RAG_EMBED_EXTRA = embed_extra, RAG_LLM_PROVIDER = Config.rag_service.llm.provider, RAG_LLM_ENDPOINT = Config.rag_service.llm.endpoint, RAG_LLM_API_KEY = llm_api_key, RAG_LLM_MODEL = Config.rag_service.llm.model, RAG_LLM_EXTRA = llm_extra, }, }, function(res) if res.code ~= 0 then Utils.error(string.format("service %s failed to start, exit code: %d", container_name, res.code)) else Utils.debug(string.format("service %s started", container_name)) cb() end end) end end function M.stop_rag_service() if M.get_rag_service_runner() == "docker" then local cmd = { "docker", "inspect", "--format", "{{.State.Status}}", container_name } local result = vim.system(cmd, { text = true }):wait().stdout if result ~= "" then vim.system({ "docker", "rm", "-fv", container_name }):wait() end else local pid = vim.system({ "pgrep", "-f", service_path }, { text = true }):wait().stdout if pid ~= "" then vim.system({ "kill", "-9", pid }):wait() Utils.debug(string.format("Attempted to kill processes related to %s", service_path)) end end end function M.get_rag_service_status() if M.get_rag_service_runner() == "docker" then local cmd = { "docker", "inspect", "--format", "{{.State.Status}}", container_name } local result = vim.system(cmd, { text = true }):wait().stdout if result ~= "running" then return "stopped" else return "running" end elseif M.get_rag_service_runner() == "nix" then local cmd = { "pgrep", "-f", service_path } local result = vim.system(cmd, { text = true }):wait().stdout if result == "" then return "stopped" else return "running" end end end function M.get_scheme(uri) local scheme = uri:match("^(%w+)://") if scheme == nil then return "unknown" end return scheme end function M.to_container_uri(uri) local runner = M.get_rag_service_runner() if runner == "nix" then return uri end local scheme = M.get_scheme(uri) if scheme == "file" then local path = uri:match("^file://(.*)$") local host_dir = Config.rag_service.host_mount if path:sub(1, #host_dir) == host_dir then path = "/host" .. path:sub(#host_dir + 1) end uri = string.format("file://%s", path) end return uri end function M.to_local_uri(uri) local scheme = M.get_scheme(uri) local path = uri:match("^file:///host(.*)$") if scheme == "file" and path ~= nil then local host_dir = Config.rag_service.host_mount local full_path = Path:new(host_dir):joinpath(path:sub(2)):absolute() uri = string.format("file://%s", full_path) end return uri end function M.is_ready() return vim .system( { "curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", M.get_rag_service_url() .. "/api/health" }, { text = true } ) :wait().code == 0 end ---@class AvanteRagServiceAddResourceResponse ---@field status string ---@field message string ---@param uri string function M.add_resource(uri) uri = M.to_container_uri(uri) local resource_name = uri:match("([^/]+)/$") local resources_resp = M.get_resources() if resources_resp == nil then Utils.error("Failed to get resources") return nil end local already_added = false for _, resource in ipairs(resources_resp.resources) do if resource.uri == uri then already_added = true resource_name = resource.name break end end if not already_added then local names_map = {} for _, resource in ipairs(resources_resp.resources) do names_map[resource.name] = true end if names_map[resource_name] then for i = 1, 100 do local resource_name_ = string.format("%s-%d", resource_name, i) if not names_map[resource_name_] then resource_name = resource_name_ break end end if names_map[resource_name] then Utils.error(string.format("Failed to add resource, name conflict: %s", resource_name)) return nil end end end local cmd = { "curl", "-X", "POST", M.get_rag_service_url() .. "/api/v1/add_resource", "-H", "Content-Type: application/json", "-d", vim.json.encode({ name = resource_name, uri = uri }), } vim.system(cmd, { text = true }, function(output) if output.code == 0 then Utils.debug(string.format("Added resource: %s", uri)) else Utils.error(string.format("Failed to add resource: %s; output: %s", uri, output.stderr)) end end) end function M.remove_resource(uri) uri = M.to_container_uri(uri) local resp = curl.post(M.get_rag_service_url() .. "/api/v1/remove_resource", { headers = { ["Content-Type"] = "application/json", }, body = vim.json.encode({ uri = uri, }), }) if resp.status ~= 200 then Utils.error("failed to remove resource: " .. resp.body) return end return vim.json.decode(resp.body) end ---@class AvanteRagServiceRetrieveSource ---@field uri string ---@field content string ---@class AvanteRagServiceRetrieveResponse ---@field response string ---@field sources AvanteRagServiceRetrieveSource[] ---@param base_uri string ---@param query string ---@param on_complete fun(resp: AvanteRagServiceRetrieveResponse | nil, error: string | nil): nil function M.retrieve(base_uri, query, on_complete) base_uri = M.to_container_uri(base_uri) curl.post(M.get_rag_service_url() .. "/api/v1/retrieve", { headers = { ["Content-Type"] = "application/json", }, body = vim.json.encode({ base_uri = base_uri, query = query, top_k = 10, }), timeout = 100000, callback = function(resp) if resp.status ~= 200 then Utils.error("failed to retrieve: " .. resp.body) on_complete(nil, resp.body) return end local jsn = vim.json.decode(resp.body) jsn.sources = vim .iter(jsn.sources) :map(function(source) local uri = M.to_local_uri(source.uri) return vim.tbl_deep_extend("force", source, { uri = uri }) end) :totable() on_complete(jsn, nil) end, }) end ---@class AvanteRagServiceIndexingStatusSummary ---@field indexing integer ---@field completed integer ---@field failed integer ---@class AvanteRagServiceIndexingStatusResponse ---@field uri string ---@field is_watched boolean ---@field total_files integer ---@field status_summary AvanteRagServiceIndexingStatusSummary ---@param uri string ---@return AvanteRagServiceIndexingStatusResponse | nil function M.indexing_status(uri) uri = M.to_container_uri(uri) local resp = curl.post(M.get_rag_service_url() .. "/api/v1/indexing_status", { headers = { ["Content-Type"] = "application/json", }, body = vim.json.encode({ uri = uri, }), }) if resp.status ~= 200 then Utils.error("Failed to get indexing status: " .. resp.body) return end local jsn = vim.json.decode(resp.body) jsn.uri = M.to_local_uri(jsn.uri) return jsn end ---@class AvanteRagServiceResource ---@field name string ---@field uri string ---@field type string ---@field status string ---@field indexing_status string ---@field created_at string ---@field indexing_started_at string | nil ---@field last_indexed_at string | nil ---@class AvanteRagServiceResourceListResponse ---@field resources AvanteRagServiceResource[] ---@field total_count number ---@return AvanteRagServiceResourceListResponse | nil function M.get_resources() local resp = curl.get(M.get_rag_service_url() .. "/api/v1/resources", { headers = { ["Content-Type"] = "application/json", }, }) if resp.status ~= 200 then Utils.error("Failed to get resources: " .. resp.body) return end local jsn = vim.json.decode(resp.body) jsn.resources = vim .iter(jsn.resources) :map(function(resource) local uri = M.to_local_uri(resource.uri) return vim.tbl_deep_extend("force", resource, { uri = uri }) end) :totable() return jsn end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/range.lua
Lua
---@class avante.Range ---@field start avante.RangeSelection start point ---@field finish avante.RangeSelection Selection end point local Range = {} Range.__index = Range ---@class avante.RangeSelection: table<string, integer> ---@field lnum number ---@field col number ---Create a selection range ---@param start avante.RangeSelection Selection start point ---@param finish avante.RangeSelection Selection end point function Range:new(start, finish) local instance = setmetatable({}, Range) instance.start = start instance.finish = finish return instance end ---Check if the line and column are within the range ---@param lnum number Line number ---@param col number Column number ---@return boolean function Range:contains(lnum, col) local start = self.start local finish = self.finish if lnum < start.lnum or lnum > finish.lnum then return false end if lnum == start.lnum and col < start.col then return false end if lnum == finish.lnum and col > finish.col then return false end return true end return Range
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/repo_map.lua
Lua
local Popup = require("nui.popup") local Utils = require("avante.utils") local event = require("nui.utils.autocmd").event local filetype_map = { ["javascriptreact"] = "javascript", ["typescriptreact"] = "typescript", ["cs"] = "csharp", } ---@class AvanteRepoMap ---@field stringify_definitions fun(lang: string, source: string): string local repo_map_lib = nil local RepoMap = {} ---@return AvanteRepoMap|nil function RepoMap._init_repo_map_lib() if repo_map_lib ~= nil then return repo_map_lib end local ok, core = pcall(require, "avante_repo_map") if not ok then return nil end repo_map_lib = core return repo_map_lib end function RepoMap.setup() vim.defer_fn(RepoMap._init_repo_map_lib, 1000) end function RepoMap.get_ts_lang(filepath) local filetype = Utils.get_filetype(filepath) return filetype_map[filetype] or filetype end function RepoMap._build_repo_map(project_root, file_ext) local output = {} local filepaths = Utils.scan_directory({ directory = project_root, }) if filepaths and not RepoMap._init_repo_map_lib() then -- or just throw an error if we don't want to execute request without codebase Utils.error("Failed to load avante_repo_map") return end vim.iter(filepaths):each(function(filepath) if not Utils.is_same_file_ext(file_ext, filepath) then return end local filetype = RepoMap.get_ts_lang(filepath) local lines = Utils.read_file_from_buf_or_disk(filepath) local content = lines and table.concat(lines, "\n") or "" local definitions = filetype and repo_map_lib.stringify_definitions(filetype, content) or "" if definitions == "" then return end table.insert(output, { path = Utils.relative_path(filepath), lang = Utils.get_filetype(filepath), defs = definitions, }) end) return output end local cache = {} function RepoMap.get_repo_map(file_ext) -- Add safety check for file_ext if not file_ext then Utils.warn("No file extension available - please open a file first") return {} end local repo_map = RepoMap._get_repo_map(file_ext) or {} if not repo_map or next(repo_map) == nil then Utils.warn("The repo map is empty. Maybe do not support this language: " .. file_ext) end return repo_map end function RepoMap._get_repo_map(file_ext) -- Add safety check at the start of the function if not file_ext then local current_buf = vim.api.nvim_get_current_buf() local buf_name = vim.api.nvim_buf_get_name(current_buf) if buf_name and buf_name ~= "" then file_ext = vim.fn.fnamemodify(buf_name, ":e") end if not file_ext or file_ext == "" then return {} end end local project_root = Utils.root.get() local cache_key = project_root .. "." .. file_ext local cached = cache[cache_key] if cached then return cached end local PPath = require("plenary.path") local Path = require("avante.path") local repo_map local function build_and_save() repo_map = RepoMap._build_repo_map(project_root, file_ext) cache[cache_key] = repo_map Path.repo_map.save(project_root, file_ext, repo_map) end repo_map = Path.repo_map.load(project_root, file_ext) if not repo_map or next(repo_map) == nil then build_and_save() if not repo_map then return end else local timer = vim.uv.new_timer() if timer then timer:start( 0, 0, vim.schedule_wrap(function() build_and_save() timer:close() end) ) end end local update_repo_map = vim.schedule_wrap(function(rel_filepath) if rel_filepath and Utils.is_same_file_ext(file_ext, rel_filepath) then local abs_filepath = PPath:new(project_root):joinpath(rel_filepath):absolute() local lines = Utils.read_file_from_buf_or_disk(abs_filepath) local content = lines and table.concat(lines, "\n") or "" local definitions = repo_map_lib.stringify_definitions(RepoMap.get_ts_lang(abs_filepath), content) if definitions == "" then return end local found = false for _, m in ipairs(repo_map) do if m.path == rel_filepath then m.defs = definitions found = true break end end if not found then table.insert(repo_map, { path = Utils.relative_path(abs_filepath), lang = Utils.get_filetype(abs_filepath), defs = definitions, }) end cache[cache_key] = repo_map Path.repo_map.save(project_root, file_ext, repo_map) end end) local handle = vim.uv.new_fs_event() if handle then handle:start(project_root, { recursive = true }, function(err, rel_filepath) if err then print("Error watching directory " .. project_root .. ":", err) return end if rel_filepath then update_repo_map(rel_filepath) end end) end vim.api.nvim_create_autocmd({ "BufReadPost", "BufNewFile" }, { callback = function(ev) vim.defer_fn(function() local ok, filepath = pcall(vim.api.nvim_buf_get_name, ev.buf) if not ok or not filepath then return end if not vim.startswith(filepath, project_root) then return end local rel_filepath = Utils.relative_path(filepath) update_repo_map(rel_filepath) end, 0) end, }) return repo_map end function RepoMap.show() local file_ext = vim.fn.expand("%:e") local repo_map = RepoMap.get_repo_map(file_ext) if not repo_map or next(repo_map) == nil then Utils.warn("The repo map is empty or not supported for this language: " .. file_ext) return end local popup = Popup({ position = "50%", enter = true, focusable = true, border = { style = "rounded", padding = { 1, 1 }, text = { top = " Avante Repo Map ", top_align = "center", }, }, size = { width = math.floor(vim.o.columns * 0.8), height = math.floor(vim.o.lines * 0.8), }, }) popup:mount() popup:map("n", "q", function() popup:unmount() end, { noremap = true, silent = true }) popup:on(event.BufLeave, function() popup:unmount() end) -- Format the repo map for display local lines = {} for _, entry in ipairs(repo_map) do table.insert(lines, string.format("Path: %s", entry.path)) table.insert(lines, string.format("Lang: %s", entry.lang)) table.insert(lines, "Defs:") for def_line in entry.defs:gmatch("[^\r\n]+") do table.insert(lines, def_line) end table.insert(lines, "") -- Add an empty line between entries end -- Set the buffer content vim.api.nvim_buf_set_lines(popup.bufnr, 0, -1, false, lines) end return RepoMap
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/selection.lua
Lua
local Utils = require("avante.utils") local Config = require("avante.config") local Llm = require("avante.llm") local Provider = require("avante.providers") local RepoMap = require("avante.repo_map") local PromptInput = require("avante.ui.prompt_input") local SelectionResult = require("avante.selection_result") local Range = require("avante.range") local api = vim.api local fn = vim.fn local NAMESPACE = api.nvim_create_namespace("avante_selection") local SELECTED_CODE_NAMESPACE = api.nvim_create_namespace("avante_selected_code") local PRIORITY = (vim.hl or vim.highlight).priorities.user ---@class avante.Selection ---@field id integer ---@field selection avante.SelectionResult | nil ---@field cursor_pos table | nil ---@field shortcuts_extmark_id integer | nil ---@field shortcuts_hint_timer? uv.uv_timer_t ---@field selected_code_extmark_id integer | nil ---@field augroup integer | nil ---@field visual_mode_augroup integer | nil ---@field code_winid integer | nil ---@field code_bufnr integer | nil ---@field prompt_input avante.ui.PromptInput | nil local Selection = {} Selection.__index = Selection Selection.did_setup = false ---@param id integer the tabpage id retrieved from api.nvim_get_current_tabpage() function Selection:new(id) return setmetatable({ id = id, shortcuts_extmark_id = nil, selected_code_extmark_id = nil, augroup = api.nvim_create_augroup("avante_selection_" .. id, { clear = true }), selection = nil, cursor_pos = nil, code_winid = nil, code_bufnr = nil, prompt_input = nil, }, Selection) end function Selection:get_virt_text_line() local current_pos = fn.getpos(".") -- Get the current and start position line numbers local current_line = current_pos[2] - 1 -- 0-indexed -- Ensure line numbers are not negative and don't exceed buffer range local total_lines = api.nvim_buf_line_count(0) if current_line < 0 then current_line = 0 end if current_line >= total_lines then current_line = total_lines - 1 end -- Take the first line of the selection to ensure virt_text is always in the top right corner return current_line end function Selection:show_shortcuts_hints_popup() local virt_text_line = self:get_virt_text_line() if self.shortcuts_extmark_id then local extmark = vim.api.nvim_buf_get_extmark_by_id(0, NAMESPACE, self.shortcuts_extmark_id, {}) if extmark and extmark[1] == virt_text_line then -- The hint text is already where it is supposed to be return end self:close_shortcuts_hints_popup() end local hint_text = string.format(" [%s: ask, %s: edit] ", Config.mappings.ask, Config.mappings.edit) self.shortcuts_extmark_id = api.nvim_buf_set_extmark(0, NAMESPACE, virt_text_line, -1, { virt_text = { { hint_text, "AvanteInlineHint" } }, virt_text_pos = "eol", priority = PRIORITY, }) end function Selection:close_shortcuts_hints_popup() if self.shortcuts_extmark_id then api.nvim_buf_del_extmark(0, NAMESPACE, self.shortcuts_extmark_id) self.shortcuts_extmark_id = nil end end function Selection:close_editing_input() if self.prompt_input then self.prompt_input:close() self.prompt_input = nil end Llm.cancel_inflight_request() if self.code_winid and api.nvim_win_is_valid(self.code_winid) then local code_bufnr = api.nvim_win_get_buf(self.code_winid) api.nvim_buf_clear_namespace(code_bufnr, SELECTED_CODE_NAMESPACE, 0, -1) if self.selected_code_extmark_id then api.nvim_buf_del_extmark(code_bufnr, SELECTED_CODE_NAMESPACE, self.selected_code_extmark_id) self.selected_code_extmark_id = nil end end if self.cursor_pos and self.code_winid and api.nvim_win_is_valid(self.code_winid) then vim.schedule(function() local bufnr = api.nvim_win_get_buf(self.code_winid) local line_count = api.nvim_buf_line_count(bufnr) local row = math.min(self.cursor_pos[1], line_count) local line = api.nvim_buf_get_lines(bufnr, row - 1, row, true)[1] or "" local col = math.min(self.cursor_pos[2], #line) api.nvim_win_set_cursor(self.code_winid, { row, col }) end) end end function Selection:submit_input(input) if not input then Utils.error("No input provided", { once = true, title = "Avante" }) return end if self.prompt_input and self.prompt_input.spinner_active then Utils.error( "Please wait for the previous request to finish before submitting another", { once = true, title = "Avante" } ) return end local code_lines = api.nvim_buf_get_lines(self.code_bufnr, 0, -1, false) local code_content = table.concat(code_lines, "\n") local full_response = "" local start_line = self.selection.range.start.lnum local finish_line = self.selection.range.finish.lnum local original_first_line_indentation = Utils.get_indentation(code_lines[self.selection.range.start.lnum]) local need_prepend_indentation = false if self.prompt_input then self.prompt_input:start_spinner() end ---@type AvanteLLMStartCallback local function on_start(_) end ---@type AvanteLLMChunkCallback local function on_chunk(chunk) full_response = full_response .. chunk local response_lines_ = vim.split(full_response, "\n") local response_lines = {} local in_code_block = false for _, line in ipairs(response_lines_) do if line:match("^<code>") then in_code_block = true line = line:gsub("^<code>", ""):gsub("</code>.*$", "") if line ~= "" then table.insert(response_lines, line) end elseif line:match("</code>") then in_code_block = false line = line:gsub("</code>.*$", "") if line ~= "" then table.insert(response_lines, line) end elseif in_code_block then table.insert(response_lines, line) end end if #response_lines == 1 then local first_line = response_lines[1] local first_line_indentation = Utils.get_indentation(first_line) need_prepend_indentation = first_line_indentation ~= original_first_line_indentation end if need_prepend_indentation then for i, line in ipairs(response_lines) do response_lines[i] = original_first_line_indentation .. line end end pcall(function() api.nvim_buf_set_lines(self.code_bufnr, start_line - 1, finish_line, true, response_lines) end) finish_line = start_line + #response_lines - 1 end ---@type AvanteLLMStopCallback local function on_stop(stop_opts) if stop_opts.error then -- NOTE: in Ubuntu 22.04+ you will see this ignorable error from ~/.local/share/nvim/lazy/avante.nvim/lua/avante/llm.lua `on_error = function(err)`, check to avoid showing this error. if type(stop_opts.error) == "table" and stop_opts.error.exit == nil and stop_opts.error.stderr == "{}" then return end Utils.error( "Error occurred while processing the response: " .. vim.inspect(stop_opts.error), { once = true, title = "Avante" } ) return end if self.prompt_input then self.prompt_input:stop_spinner() end vim.defer_fn(function() self:close_editing_input() end, 0) Utils.debug("full response:", full_response) end local filetype = api.nvim_get_option_value("filetype", { buf = self.code_bufnr }) local file_ext = api.nvim_buf_get_name(self.code_bufnr):match("^.+%.(.+)$") local mentions = Utils.extract_mentions(input) input = mentions.new_content local project_context = mentions.enable_project_context and RepoMap.get_repo_map(file_ext) or nil local diagnostics = Utils.lsp.get_current_selection_diagnostics(self.code_bufnr, self.selection) ---@type AvanteSelectedCode | nil local selected_code = nil if self.selection then selected_code = { content = self.selection.content, file_type = self.selection.filetype, path = self.selection.filepath, } end local instructions = "Do not call any tools and just response the request: " .. input Llm.stream({ ask = true, project_context = vim.json.encode(project_context), diagnostics = vim.json.encode(diagnostics), selected_files = { { content = code_content, file_type = filetype, path = "" } }, code_lang = filetype, selected_code = selected_code, instructions = instructions, mode = "editing", on_start = on_start, on_chunk = on_chunk, on_stop = on_stop, }) end ---@param request? string ---@param line1? integer ---@param line2? integer function Selection:create_editing_input(request, line1, line2) self:close_editing_input() if not vim.g.avante_login or vim.g.avante_login == false then api.nvim_exec_autocmds("User", { pattern = Provider.env.REQUEST_LOGIN_PATTERN }) vim.g.avante_login = true end self.code_bufnr = api.nvim_get_current_buf() self.code_winid = api.nvim_get_current_win() self.cursor_pos = api.nvim_win_get_cursor(self.code_winid) local code_lines = api.nvim_buf_get_lines(self.code_bufnr, 0, -1, false) if line1 ~= nil and line2 ~= nil then local filepath = vim.fn.expand("%:p") local filetype = Utils.get_filetype(filepath) local content_lines = vim.list_slice(code_lines, line1, line2) local content = table.concat(content_lines, "\n") local range = Range:new( { lnum = line1, col = #content_lines[1] }, { lnum = line2, col = #content_lines[#content_lines] } ) self.selection = SelectionResult:new(filepath, filetype, content, range) else self.selection = Utils.get_visual_selection_and_range() end if self.selection == nil then Utils.error("No visual selection found", { once = true, title = "Avante" }) return end local start_row local start_col local end_row local end_col if vim.fn.mode() == "V" then start_row = self.selection.range.start.lnum - 1 start_col = 0 end_row = self.selection.range.finish.lnum - 1 end_col = #code_lines[self.selection.range.finish.lnum] else start_row = self.selection.range.start.lnum - 1 start_col = self.selection.range.start.col - 1 end_row = self.selection.range.finish.lnum - 1 end_col = math.min(self.selection.range.finish.col, #code_lines[self.selection.range.finish.lnum]) end self.selected_code_extmark_id = api.nvim_buf_set_extmark(self.code_bufnr, SELECTED_CODE_NAMESPACE, start_row, start_col, { hl_group = "Visual", hl_mode = "combine", end_row = end_row, end_col = end_col, priority = PRIORITY, }) local prompt_input = PromptInput:new({ default_value = request, submit_callback = function(input) self:submit_input(input) end, cancel_callback = function() self:close_editing_input() end, win_opts = { border = Config.windows.edit.border, height = Config.windows.edit.height, width = Config.windows.edit.width, title = { { "Avante edit selected block", "FloatTitle" } }, }, start_insert = Config.windows.edit.start_insert, }) self.prompt_input = prompt_input prompt_input:open() end ---Show the hints virtual line and set up autocommands to update it or stop showing it when exiting visual mode ---@param bufnr integer function Selection:on_entering_visual_mode(bufnr) if Config.selection.hint_display == "none" then return end if vim.bo[bufnr].buftype == "terminal" or Utils.is_sidebar_buffer(bufnr) then return end self:show_shortcuts_hints_popup() self.visual_mode_augroup = api.nvim_create_augroup("avante_selection_visual_" .. self.id, { clear = true }) if Config.selection.hint_display == "delayed" then local deferred_show_shortcut_hints_popup = Utils.debounce(function() self:show_shortcuts_hints_popup() self.shortcuts_hint_timer = nil end, vim.o.updatetime) api.nvim_create_autocmd({ "CursorMoved" }, { group = self.visual_mode_augroup, buffer = bufnr, callback = function() self:close_shortcuts_hints_popup() self.shortcuts_hint_timer = deferred_show_shortcut_hints_popup() end, }) else self:show_shortcuts_hints_popup() api.nvim_create_autocmd({ "CursorMoved" }, { group = self.visual_mode_augroup, buffer = bufnr, callback = function() self:show_shortcuts_hints_popup() end, }) end api.nvim_create_autocmd({ "ModeChanged" }, { group = self.visual_mode_augroup, buffer = bufnr, callback = function(ev) -- Check if exiting visual mode. Autocommand pattern matching does not work -- with buffer-local autocommands so need to test explicitly if ev.match:match("[vV]:[^vV]") then self:on_exiting_visual_mode() end end, }) api.nvim_create_autocmd({ "BufLeave" }, { group = self.visual_mode_augroup, buffer = bufnr, callback = function() self:on_exiting_visual_mode() end, }) end function Selection:on_exiting_visual_mode() self:close_shortcuts_hints_popup() if self.shortcuts_hint_timer then self.shortcuts_hint_timer:stop() self.shortcuts_hint_timer:close() self.shortcuts_hint_timer = nil end api.nvim_del_augroup_by_id(self.visual_mode_augroup) self.visual_mode_augroup = nil end function Selection:setup_autocmds() self.did_setup = true api.nvim_create_autocmd("User", { group = self.augroup, pattern = "AvanteEditSubmitted", callback = function(ev) self:submit_input(ev.data.request) end, }) api.nvim_create_autocmd({ "ModeChanged" }, { group = self.augroup, pattern = { "n:v", "n:V", "n:" }, -- Entering Visual mode from Normal mode callback = function(ev) self:on_entering_visual_mode(ev.buf) end, }) end function Selection:delete_autocmds() if self.augroup then api.nvim_del_augroup_by_id(self.augroup) self.augroup = nil end self.did_setup = false end return Selection
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/selection_result.lua
Lua
---@class avante.SelectionResult ---@field filepath string Filepath of the selected content ---@field filetype string Filetype of the selected content ---@field content string Selected content ---@field range avante.Range Selection range local SelectionResult = {} SelectionResult.__index = SelectionResult -- Create a selection content and range ---@param filepath string Filepath of the selected content ---@param filetype string Filetype of the selected content ---@param content string Selected content ---@param range avante.Range Selection range function SelectionResult:new(filepath, filetype, content, range) local instance = setmetatable({}, self) instance.filepath = filepath instance.filetype = filetype instance.content = content instance.range = range return instance end return SelectionResult
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/sidebar.lua
Lua
local api = vim.api local fn = vim.fn local Split = require("nui.split") local event = require("nui.utils.autocmd").event local PPath = require("plenary.path") local Providers = require("avante.providers") local Path = require("avante.path") local Config = require("avante.config") local Diff = require("avante.diff") local Llm = require("avante.llm") local Utils = require("avante.utils") local PromptLogger = require("avante.utils.promptLogger") local Highlights = require("avante.highlights") local RepoMap = require("avante.repo_map") local FileSelector = require("avante.file_selector") local LLMTools = require("avante.llm_tools") local History = require("avante.history") local Render = require("avante.history.render") local Line = require("avante.ui.line") local LRUCache = require("avante.utils.lru_cache") local logo = require("avante.utils.logo") local ButtonGroupLine = require("avante.ui.button_group_line") local RESULT_BUF_NAME = "AVANTE_RESULT" local VIEW_BUFFER_UPDATED_PATTERN = "AvanteViewBufferUpdated" local CODEBLOCK_KEYBINDING_NAMESPACE = api.nvim_create_namespace("AVANTE_CODEBLOCK_KEYBINDING") local TOOL_MESSAGE_KEYBINDING_NAMESPACE = api.nvim_create_namespace("AVANTE_TOOL_MESSAGE_KEYBINDING") local USER_REQUEST_BLOCK_KEYBINDING_NAMESPACE = api.nvim_create_namespace("AVANTE_USER_REQUEST_BLOCK_KEYBINDING") local SELECTED_FILES_HINT_NAMESPACE = api.nvim_create_namespace("AVANTE_SELECTED_FILES_HINT") local SELECTED_FILES_ICON_NAMESPACE = api.nvim_create_namespace("AVANTE_SELECTED_FILES_ICON") local INPUT_HINT_NAMESPACE = api.nvim_create_namespace("AVANTE_INPUT_HINT") local STATE_NAMESPACE = api.nvim_create_namespace("AVANTE_STATE") local RESULT_BUF_HL_NAMESPACE = api.nvim_create_namespace("AVANTE_RESULT_BUF_HL") local PRIORITY = (vim.hl or vim.highlight).priorities.user local RESP_SEPARATOR = "-------" ---This is a list of known sidebar containers or sub-windows. They are listed in ---the order they appear in the sidebar, from top to bottom. local SIDEBAR_CONTAINERS = { "result", "selected_code", "selected_files", "todos", "input", } ---@class avante.Sidebar local Sidebar = {} Sidebar.__index = Sidebar ---@class avante.CodeState ---@field winid integer ---@field bufnr integer ---@field selection avante.SelectionResult | nil ---@field old_winhl string | nil ---@field win_width integer | nil ---@class avante.Sidebar ---@field id integer ---@field augroup integer ---@field code avante.CodeState ---@field containers { result?: NuiSplit, todos?: NuiSplit, selected_code?: NuiSplit, selected_files?: NuiSplit, input?: NuiSplit } ---@field file_selector FileSelector ---@field chat_history avante.ChatHistory | nil ---@field current_state avante.GenerateState | nil ---@field state_timer table | nil ---@field state_spinner_chars string[] ---@field thinking_spinner_chars string[] ---@field state_spinner_idx integer ---@field state_extmark_id integer | nil ---@field scroll boolean ---@field input_hint_window integer | nil ---@field old_result_lines avante.ui.Line[] ---@field token_count integer | nil ---@field acp_client avante.acp.ACPClient | nil ---@field post_render? fun(sidebar: avante.Sidebar) ---@field permission_handler fun(id: string) | nil ---@field permission_button_options ({ id: string, icon: string|nil, name: string }[]) | nil ---@field expanded_message_uuids table<string, boolean> ---@field tool_message_positions table<string, [integer, integer]> ---@field skip_line_count integer | nil ---@field current_tool_use_extmark_id integer | nil ---@field private win_size_store table<integer, {width: integer, height: integer}> ---@field is_in_full_view boolean ---@param id integer the tabpage id retrieved from api.nvim_get_current_tabpage() function Sidebar:new(id) return setmetatable({ id = id, code = { bufnr = 0, winid = 0, selection = nil, old_winhl = nil }, winids = { result_container = 0, todos_container = 0, selected_files_container = 0, selected_code_container = 0, input_container = 0, }, containers = {}, file_selector = FileSelector:new(id), is_generating = false, chat_history = nil, current_state = nil, state_timer = nil, state_spinner_chars = Config.windows.spinner.generating, thinking_spinner_chars = Config.windows.spinner.thinking, state_spinner_idx = 1, state_extmark_id = nil, scroll = true, input_hint_window = nil, old_result_lines = {}, token_count = nil, -- Cache-related fields _cached_history_lines = nil, _history_cache_invalidated = true, post_render = nil, tool_message_positions = {}, expanded_message_ids = {}, current_tool_use_extmark_id = nil, win_width_store = {}, is_in_full_view = false, }, Sidebar) end function Sidebar:delete_autocmds() if self.augroup then api.nvim_del_augroup_by_id(self.augroup) end self.augroup = nil end function Sidebar:delete_containers() for _, container in pairs(self.containers) do container:unmount() end self.containers = {} end function Sidebar:reset() -- clean up event handlers if self.augroup then api.nvim_del_augroup_by_id(self.augroup) self.augroup = nil end -- clean up keymaps self:unbind_apply_key() self:unbind_sidebar_keys() -- clean up file selector events if self.file_selector then self.file_selector:off("update") end self:delete_containers() self.code = { bufnr = 0, winid = 0, selection = nil } self.scroll = true self.old_result_lines = {} self.token_count = nil self.tool_message_positions = {} self.expanded_message_uuids = {} self.current_tool_use_extmark_id = nil self.win_size_store = {} self.is_in_full_view = false end ---@class SidebarOpenOptions: AskOptions ---@field selection? avante.SelectionResult ---@param opts SidebarOpenOptions function Sidebar:open(opts) opts = opts or {} self.show_logo = opts.show_logo local in_visual_mode = Utils.in_visual_mode() and self:in_code_win() if not self:is_open() then self:reset() self:initialize() if opts.selection then self.code.selection = opts.selection end self:render(opts) self:focus() else if in_visual_mode or opts.selection then self:close() self:reset() self:initialize() if opts.selection then self.code.selection = opts.selection end self:render(opts) return self end self:focus() end if not vim.g.avante_login or vim.g.avante_login == false then api.nvim_exec_autocmds("User", { pattern = Providers.env.REQUEST_LOGIN_PATTERN }) vim.g.avante_login = true end local acp_provider = Config.acp_providers[Config.provider] if acp_provider then self:handle_submit("") end return self end function Sidebar:setup_colors() self:set_code_winhl() vim.api.nvim_create_autocmd("WinNew", { group = self.augroup, callback = function(env) if Utils.is_floating_window(env.id) then Utils.debug("WinNew ignore floating window") return end for _, winid in ipairs(vim.api.nvim_tabpage_list_wins(self.id)) do if not vim.api.nvim_win_is_valid(winid) or self:is_sidebar_winid(winid) then goto continue end local winhl = vim.wo[winid].winhl if winhl:find("WinSeparator:" .. Highlights.AVANTE_SIDEBAR_WIN_SEPARATOR) and not (vim.api.nvim_win_is_valid(self.code.winid) and Utils.should_hidden_border(self.code.winid, winid)) then vim.wo[winid].winhl = self.code.old_winhl or "" end ::continue:: end self:set_code_winhl() end, }) end function Sidebar:set_code_winhl() if not self.code.winid or not api.nvim_win_is_valid(self.code.winid) then return end if not Utils.is_valid_container(self.containers.result, true) then return end if Utils.should_hidden_border(self.code.winid, self.containers.result.winid) then local old_winhl = vim.wo[self.code.winid].winhl if self.code.old_winhl == nil then self.code.old_winhl = old_winhl else old_winhl = self.code.old_winhl end local pieces = vim.split(old_winhl or "", ",") local new_pieces = {} for _, piece in ipairs(pieces) do if not piece:find("WinSeparator:") and piece ~= "" then table.insert(new_pieces, piece) end end table.insert(new_pieces, "WinSeparator:" .. Highlights.AVANTE_SIDEBAR_WIN_SEPARATOR) local new_winhl = table.concat(new_pieces, ",") vim.wo[self.code.winid].winhl = new_winhl end end function Sidebar:recover_code_winhl() if self.code.old_winhl ~= nil then if self.code.winid and api.nvim_win_is_valid(self.code.winid) then vim.wo[self.code.winid].winhl = self.code.old_winhl end self.code.old_winhl = nil end end ---@class SidebarCloseOptions ---@field goto_code_win? boolean ---@param opts? SidebarCloseOptions function Sidebar:close(opts) opts = vim.tbl_extend("force", { goto_code_win = true }, opts or {}) -- If sidebar was maximized make it normal size so that other windows -- will not be left minimized. if self.is_in_full_view then self:toggle_code_window() end self:delete_autocmds() self:delete_containers() self.old_result_lines = {} if opts.goto_code_win and self.code and self.code.winid and api.nvim_win_is_valid(self.code.winid) then fn.win_gotoid(self.code.winid) end self:recover_code_winhl() self:close_input_hint() end function Sidebar:shutdown() Llm.cancel_inflight_request() self:close() vim.cmd("noautocmd stopinsert") end ---@return boolean function Sidebar:focus() if self:is_open() then fn.win_gotoid(self.containers.result.winid) return true end return false end function Sidebar:focus_input() if Utils.is_valid_container(self.containers.input, true) then api.nvim_set_current_win(self.containers.input.winid) self:show_input_hint() end end function Sidebar:is_open() return Utils.is_valid_container(self.containers.result, true) end function Sidebar:in_code_win() return self.code.winid == api.nvim_get_current_win() end ---@param opts AskOptions function Sidebar:toggle(opts) local in_visual_mode = Utils.in_visual_mode() and self:in_code_win() if self:is_open() and not in_visual_mode then self:close() return false else ---@cast opts SidebarOpenOptions self:open(opts) return true end end ---@class AvanteReplacementResult ---@field content string ---@field current_filepath string ---@field is_searching boolean ---@field is_replacing boolean ---@field is_thinking boolean ---@field waiting_for_breakline boolean ---@field last_search_tag_start_line integer ---@field last_replace_tag_start_line integer ---@field last_think_tag_start_line integer ---@field last_think_tag_end_line integer ---@param result_content string ---@param prev_filepath string ---@return AvanteReplacementResult local function transform_result_content(result_content, prev_filepath) local transformed_lines = {} local result_lines = vim.split(result_content, "\n") local is_searching = false local is_replacing = false local is_thinking = false local last_search_tag_start_line = 0 local last_replace_tag_start_line = 0 local last_think_tag_start_line = 0 local last_think_tag_end_line = 0 local search_start = 0 local current_filepath local waiting_for_breakline = false local i = 1 while true do if i > #result_lines then break end local line_content = result_lines[i] local matched_filepath = line_content:match("<[Ff][Ii][Ll][Ee][Pp][Aa][Tt][Hh]>(.+)</[Ff][Ii][Ll][Ee][Pp][Aa][Tt][Hh]>") if matched_filepath then if i > 1 then local prev_line = result_lines[i - 1] if prev_line and prev_line:match("^%s*```%w+$") then transformed_lines = vim.list_slice(transformed_lines, 1, #transformed_lines - 1) end end current_filepath = matched_filepath table.insert(transformed_lines, string.format("Filepath: %s", matched_filepath)) goto continue end if line_content:match("^%s*<[Ss][Ee][Aa][Rr][Cc][Hh]>") then is_searching = true if not line_content:match("^%s*<[Ss][Ee][Aa][Rr][Cc][Hh]>%s*$") then local search_start_line = line_content:match("<[Ss][Ee][Aa][Rr][Cc][Hh]>(.+)$") line_content = "<SEARCH>" result_lines[i] = line_content if search_start_line and search_start_line ~= "" then table.insert(result_lines, i + 1, search_start_line) end end line_content = "<SEARCH>" local prev_line = result_lines[i - 1] if prev_line and prev_filepath and not prev_line:match("Filepath:.+") and not prev_line:match("<[Ff][Ii][Ll][Ee][Pp][Aa][Tt][Hh]>.+</[Ff][Ii][Ll][Ee][Pp][Aa][Tt][Hh]>") then table.insert(transformed_lines, string.format("Filepath: %s", prev_filepath)) end local next_line = result_lines[i + 1] if next_line and next_line:match("^%s*```%w+$") then i = i + 1 end search_start = i + 1 last_search_tag_start_line = i elseif line_content:match("</[Ss][Ee][Aa][Rr][Cc][Hh]>%s*$") then if is_replacing then result_lines[i] = line_content:gsub("</[Ss][Ee][Aa][Rr][Cc][Hh]>", "</REPLACE>") goto continue_without_increment end -- Handle case where </SEARCH> is a suffix if not line_content:match("^%s*</[Ss][Ee][Aa][Rr][Cc][Hh]>%s*$") then local search_end_line = line_content:match("^(.+)</[Ss][Ee][Aa][Rr][Cc][Hh]>") line_content = "</SEARCH>" result_lines[i] = line_content if search_end_line and search_end_line ~= "" then table.insert(result_lines, i, search_end_line) goto continue_without_increment end end is_searching = false local search_end = i local prev_line = result_lines[i - 1] if prev_line and prev_line:match("^%s*```$") then search_end = i - 1 end local match_filetype = nil local filepath = current_filepath or prev_filepath or "" if filepath == "" then goto continue end local file_content_lines = Utils.read_file_from_buf_or_disk(filepath) or {} local file_type = Utils.get_filetype(filepath) local search_lines = vim.list_slice(result_lines, search_start, search_end - 1) local start_line, end_line = Utils.fuzzy_match(file_content_lines, search_lines) if start_line ~= nil and end_line ~= nil then match_filetype = file_type else start_line = 0 end_line = 0 end -- when the filetype isn't detected, fallback to matching based on filepath. -- can happen if the llm tries to edit or create a file outside of it's context. if not match_filetype then local snippet_file_path = current_filepath or prev_filepath match_filetype = Utils.get_filetype(snippet_file_path) end local search_start_tag_idx_in_transformed_lines = 0 for j = 1, #transformed_lines do if transformed_lines[j] == "<SEARCH>" then search_start_tag_idx_in_transformed_lines = j break end end if search_start_tag_idx_in_transformed_lines > 0 then transformed_lines = vim.list_slice(transformed_lines, 1, search_start_tag_idx_in_transformed_lines - 1) end waiting_for_breakline = true vim.list_extend(transformed_lines, { string.format("Replace lines: %d-%d", start_line, end_line), string.format("```%s", match_filetype), }) goto continue elseif line_content:match("^%s*<[Rr][Ee][Pp][Ll][Aa][Cc][Ee]>") then is_replacing = true if not line_content:match("^%s*<[Rr][Ee][Pp][Ll][Aa][Cc][Ee]>%s*$") then local replace_first_line = line_content:match("<[Rr][Ee][Pp][Ll][Aa][Cc][Ee]>(.+)$") line_content = "<REPLACE>" result_lines[i] = line_content if replace_first_line and replace_first_line ~= "" then table.insert(result_lines, i + 1, replace_first_line) end end local next_line = result_lines[i + 1] if next_line and next_line:match("^%s*```%w+$") then i = i + 1 end last_replace_tag_start_line = i goto continue elseif line_content:match("</[Rr][Ee][Pp][Ll][Aa][Cc][Ee]>%s*$") then -- Handle case where </REPLACE> is a suffix if not line_content:match("^%s*</[Rr][Ee][Pp][Ll][Aa][Cc][Ee]>%s*$") then local replace_end_line = line_content:match("^(.+)</[Rr][Ee][Pp][Ll][Aa][Cc][Ee]>") line_content = "</REPLACE>" result_lines[i] = line_content if replace_end_line and replace_end_line ~= "" then table.insert(result_lines, i, replace_end_line) goto continue_without_increment end end is_replacing = false local prev_line = result_lines[i - 1] if not (prev_line and prev_line:match("^%s*```$")) then table.insert(transformed_lines, "```") end local next_line = result_lines[i + 1] if next_line and next_line:match("^%s*```%s*$") then i = i + 1 end goto continue elseif line_content == "<think>" then is_thinking = true last_think_tag_start_line = i last_think_tag_end_line = 0 elseif line_content == "</think>" then is_thinking = false last_think_tag_end_line = i elseif line_content:match("^%s*```%s*$") then local prev_line = result_lines[i - 1] if prev_line and prev_line:match("^%s*```$") then goto continue end end waiting_for_breakline = false table.insert(transformed_lines, line_content) ::continue:: i = i + 1 ::continue_without_increment:: end return { current_filepath = current_filepath, content = table.concat(transformed_lines, "\n"), waiting_for_breakline = waiting_for_breakline, is_searching = is_searching, is_replacing = is_replacing, is_thinking = is_thinking, last_search_tag_start_line = last_search_tag_start_line, last_replace_tag_start_line = last_replace_tag_start_line, last_think_tag_start_line = last_think_tag_start_line, last_think_tag_end_line = last_think_tag_end_line, } end ---@param replacement AvanteReplacementResult ---@return string local function generate_display_content(replacement) if replacement.is_searching then return table.concat( vim.list_slice(vim.split(replacement.content, "\n"), 1, replacement.last_search_tag_start_line - 1), "\n" ) end if replacement.last_think_tag_start_line > 0 then local lines = vim.split(replacement.content, "\n") local last_think_tag_end_line = replacement.last_think_tag_end_line if last_think_tag_end_line == 0 then last_think_tag_end_line = #lines + 1 end local thinking_content_lines = vim.list_slice(lines, replacement.last_think_tag_start_line + 2, last_think_tag_end_line - 1) local formatted_thinking_content_lines = vim .iter(thinking_content_lines) :map(function(line) if Utils.trim_spaces(line) == "" then return line end return string.format(" > %s", line) end) :totable() local result_lines = vim.list_extend( vim.list_slice(lines, 1, replacement.last_search_tag_start_line), { Utils.icon("🤔 ") .. "Thought content:" } ) result_lines = vim.list_extend(result_lines, formatted_thinking_content_lines) result_lines = vim.list_extend(result_lines, vim.list_slice(lines, last_think_tag_end_line + 1)) return table.concat(result_lines, "\n") end return replacement.content end ---@class AvanteCodeSnippet ---@field range integer[] ---@field content string ---@field lang string ---@field explanation string ---@field start_line_in_response_buf integer ---@field end_line_in_response_buf integer ---@field filepath string ---@param source string|integer ---@return TSNode[] local function tree_sitter_markdown_parse_code_blocks(source) local query = require("vim.treesitter.query") local parser if type(source) == "string" then parser = vim.treesitter.get_string_parser(source, "markdown") else parser = vim.treesitter.get_parser(source, "markdown") end if parser == nil then Utils.warn("Failed to get markdown parser") return {} end local tree = parser:parse()[1] local root = tree:root() local code_block_query = query.parse( "markdown", [[ (fenced_code_block (info_string (language) @language)? (block_continuation) @code_start (fenced_code_block_delimiter) @code_end) ]] ) local nodes = {} for _, node in code_block_query:iter_captures(root, source) do table.insert(nodes, node) end return nodes end ---@param response_content string ---@return table<string, AvanteCodeSnippet[]> local function extract_code_snippets_map(response_content) local snippets = {} local lines = vim.split(response_content, "\n") -- use tree-sitter-markdown to parse all code blocks in response_content local lang = "text" local start_line, end_line local start_line_in_response_buf, end_line_in_response_buf local explanation_start_line = 0 for _, node in ipairs(tree_sitter_markdown_parse_code_blocks(response_content)) do if node:type() == "language" then lang = vim.treesitter.get_node_text(node, response_content) elseif node:type() == "block_continuation" and node:start() > 1 then start_line_in_response_buf = node:start() local number_line = lines[start_line_in_response_buf - 1] local _, start_line_str, end_line_str = number_line:match("^%s*(%d*)[%.%)%s]*[Aa]?n?d?%s*[Rr]eplace%s+[Ll]ines:?%s*(%d+)%-(%d+)") if start_line_str ~= nil and end_line_str ~= nil then start_line = tonumber(start_line_str) end_line = tonumber(end_line_str) else _, start_line_str = number_line:match("^%s*(%d*)[%.%)%s]*[Aa]?n?d?%s*[Rr]eplace%s+[Ll]ine:?%s*(%d+)") if start_line_str ~= nil then start_line = tonumber(start_line_str) end_line = tonumber(start_line_str) else start_line_str = number_line:match("[Aa]fter%s+[Ll]ine:?%s*(%d+)") if start_line_str ~= nil then start_line = tonumber(start_line_str) + 1 end_line = tonumber(start_line_str) + 1 end end end elseif node:type() == "fenced_code_block_delimiter" and start_line_in_response_buf ~= nil and node:start() >= start_line_in_response_buf then end_line_in_response_buf, _ = node:start() if start_line ~= nil and end_line ~= nil then local filepath = lines[start_line_in_response_buf - 2] if filepath:match("^[Ff]ilepath:") then filepath = filepath:match("^[Ff]ilepath:%s*(.+)") end local content = table.concat(vim.list_slice(lines, start_line_in_response_buf + 1, end_line_in_response_buf), "\n") local explanation = "" if start_line_in_response_buf > explanation_start_line + 2 then explanation = table.concat(vim.list_slice(lines, explanation_start_line, start_line_in_response_buf - 3), "\n") end local snippet = { range = { start_line, end_line }, content = content, lang = lang, explanation = explanation, start_line_in_response_buf = start_line_in_response_buf, end_line_in_response_buf = end_line_in_response_buf + 1, filepath = filepath, } table.insert(snippets, snippet) end lang = "text" explanation_start_line = end_line_in_response_buf + 2 end end local snippets_map = {} for _, snippet in ipairs(snippets) do if snippet.filepath == "" then goto continue end snippets_map[snippet.filepath] = snippets_map[snippet.filepath] or {} table.insert(snippets_map[snippet.filepath], snippet) ::continue:: end return snippets_map end local function insert_conflict_contents(bufnr, snippets) -- sort snippets by start_line table.sort(snippets, function(a, b) return a.range[1] < b.range[1] end) local lines = Utils.get_buf_lines(0, -1, bufnr) local offset = 0 for _, snippet in ipairs(snippets) do local start_line, end_line = unpack(snippet.range) local first_line_content = lines[start_line] local old_first_line_indentation = "" if first_line_content then old_first_line_indentation = Utils.get_indentation(first_line_content) end local result = {} table.insert(result, "<<<<<<< HEAD") for i = start_line, end_line do table.insert(result, lines[i]) end table.insert(result, "=======") local snippet_lines = vim.split(snippet.content, "\n") if #snippet_lines > 0 then local new_first_line_indentation = Utils.get_indentation(snippet_lines[1]) if #old_first_line_indentation > #new_first_line_indentation then local line_indentation = old_first_line_indentation:sub(#new_first_line_indentation + 1) snippet_lines = vim.iter(snippet_lines):map(function(line) return line_indentation .. line end):totable() end end vim.list_extend(result, snippet_lines) table.insert(result, ">>>>>>> Snippet") api.nvim_buf_set_lines(bufnr, offset + start_line - 1, offset + end_line, false, result) offset = offset + #snippet_lines + 3 end end ---@param codeblocks table<integer, any> local function is_cursor_in_codeblock(codeblocks) local cursor_line, _ = Utils.get_cursor_pos() for _, block in ipairs(codeblocks) do if cursor_line >= block.start_line and cursor_line <= block.end_line then return block end end return nil end ---@class AvanteRespUserRequestBlock ---@field start_line number 1-indexed ---@field end_line number 1-indexed ---@field content string ---@param position? integer ---@return AvanteRespUserRequestBlock | nil function Sidebar:get_current_user_request_block(position) local current_resp_content, current_resp_start_line = self:get_content_between_separators(position) if current_resp_content == nil then return nil end if current_resp_content == "" then return nil end local lines = vim.split(current_resp_content, "\n") local start_line = nil local end_line = nil local content_lines = {} for i = 1, #lines do local line = lines[i] local m = line:match("^>%s+(.+)$") if m then if start_line == nil then start_line = i end table.insert(content_lines, m) end_line = i elseif start_line ~= nil then break end end if start_line == nil then return nil end content_lines = vim.list_slice(content_lines, 1, #content_lines - 1) local content = table.concat(content_lines, "\n") return { start_line = current_resp_start_line + start_line - 1, end_line = current_resp_start_line + end_line - 1, content = content, } end function Sidebar:is_cursor_in_user_request_block() local block = self:get_current_user_request_block() if block == nil then return false end local cursor_line = api.nvim_win_get_cursor(self.containers.result.winid)[1] return cursor_line >= block.start_line and cursor_line <= block.end_line end function Sidebar:get_current_tool_use_message_uuid() local skip_line_count = self.skip_line_count or 0 local cursor_line = api.nvim_win_get_cursor(self.containers.result.winid)[1] for message_uuid, positions in pairs(self.tool_message_positions) do if skip_line_count + positions[1] + 1 <= cursor_line and cursor_line <= skip_line_count + positions[2] then return message_uuid, positions end end end ---@class AvanteCodeblock ---@field start_line integer 1-indexed ---@field end_line integer 1-indexed ---@field lang string ---@param buf integer ---@return AvanteCodeblock[] local function parse_codeblocks(buf) local codeblocks = {} local lines = Utils.get_buf_lines(0, -1, buf) local lang, start_line, valid for _, node in ipairs(tree_sitter_markdown_parse_code_blocks(buf)) do if node:type() == "language" then lang = vim.treesitter.get_node_text(node, buf) elseif node:type() == "block_continuation" then start_line, _ = node:start() elseif node:type() == "fenced_code_block_delimiter" and start_line ~= nil and node:start() >= start_line then local end_line, _ = node:start() valid = lines[start_line - 1]:match("^%s*(%d*)[%.%)%s]*[Aa]?n?d?%s*[Rr]eplace%s+[Ll]ines:?%s*(%d+)%-(%d+)") ~= nil if valid then table.insert(codeblocks, { start_line = start_line, end_line = end_line + 1, lang = lang }) end end end return codeblocks end ---@param original_lines string[] ---@param snippet AvanteCodeSnippet ---@return AvanteCodeSnippet[] local function minimize_snippet(original_lines, snippet) local start_line = snippet.range[1] local end_line = snippet.range[2] local original_snippet_lines = vim.list_slice(original_lines, start_line, end_line) local original_snippet_content = table.concat(original_snippet_lines, "\n") local snippet_content = snippet.content local snippet_lines = vim.split(snippet_content, "\n") ---@diagnostic disable-next-line: assign-type-mismatch local patch = vim.diff( ---@type integer[][] original_snippet_content, snippet_content, ---@diagnostic disable-next-line: missing-fields { algorithm = "histogram", result_type = "indices", ctxlen = vim.o.scrolloff } ) ---@type AvanteCodeSnippet[] local new_snippets = {} for _, hunk in ipairs(patch) do local start_a, count_a, start_b, count_b = unpack(hunk) ---@type AvanteCodeSnippet local new_snippet = { range = { count_a > 0 and start_line + start_a - 1 or start_line + start_a, start_line + start_a + math.max(count_a, 1) - 2, }, content = table.concat(vim.list_slice(snippet_lines, start_b, start_b + count_b - 1), "\n"), lang = snippet.lang, explanation = snippet.explanation, start_line_in_response_buf = snippet.start_line_in_response_buf, end_line_in_response_buf = snippet.end_line_in_response_buf, filepath = snippet.filepath, } table.insert(new_snippets, new_snippet) end return new_snippets end ---@param filepath string ---@param snippets AvanteCodeSnippet[] ---@return table<string, AvanteCodeSnippet[]> function Sidebar:minimize_snippets(filepath, snippets) local original_lines = {} local original_lines_ = Utils.read_file_from_buf_or_disk(filepath) if original_lines_ then original_lines = original_lines_ end local results = {} for _, snippet in ipairs(snippets) do local new_snippets = minimize_snippet(original_lines, snippet) if new_snippets then for _, new_snippet in ipairs(new_snippets) do table.insert(results, new_snippet) end end end return results end function Sidebar:retry_user_request() local block = self:get_current_user_request_block() if not block then return end self:handle_submit(block.content) end function Sidebar:handle_expand_message(message_uuid, expanded) Utils.debug("handle_expand_message", message_uuid, expanded) self.expanded_message_uuids[message_uuid] = expanded self._history_cache_invalidated = true local old_scroll = self.scroll self.scroll = false self:update_content("") self.scroll = old_scroll vim.defer_fn(function() local cursor_line = api.nvim_win_get_cursor(self.containers.result.winid)[1] local positions = self.tool_message_positions[message_uuid] if positions then local skip_line_count = self.skip_line_count or 0 if cursor_line > positions[2] + skip_line_count then api.nvim_win_set_cursor(self.containers.result.winid, { positions[2] + skip_line_count, 0 }) end end end, 100) end function Sidebar:edit_user_request() local block = self:get_current_user_request_block() if not block then return end if Utils.is_valid_container(self.containers.input) then local lines = vim.split(block.content, "\n") api.nvim_buf_set_lines(self.containers.input.bufnr, 0, -1, false, lines) api.nvim_set_current_win(self.containers.input.winid) api.nvim_win_set_cursor(self.containers.input.winid, { 1, #lines > 0 and #lines[1] or 0 }) end end ---@param current_cursor boolean function Sidebar:apply(current_cursor) local response, response_start_line = self:get_content_between_separators() local all_snippets_map = extract_code_snippets_map(response) local selected_snippets_map = {} if current_cursor then if self.containers.result and self.containers.result.winid then local cursor_line = Utils.get_cursor_pos(self.containers.result.winid) for filepath, snippets in pairs(all_snippets_map) do for _, snippet in ipairs(snippets) do if cursor_line >= snippet.start_line_in_response_buf + response_start_line - 1 and cursor_line <= snippet.end_line_in_response_buf + response_start_line - 1 then selected_snippets_map[filepath] = { snippet } break end end end end else selected_snippets_map = all_snippets_map end vim.defer_fn(function() api.nvim_set_current_win(self.code.winid) for filepath, snippets in pairs(selected_snippets_map) do if Config.behaviour.minimize_diff then snippets = self:minimize_snippets(filepath, snippets) end local bufnr = Utils.open_buffer(filepath) local path_ = PPath:new(Utils.is_win() and filepath:gsub("/", "\\") or filepath) path_:parent():mkdir({ parents = true, exists_ok = true }) insert_conflict_contents(bufnr, snippets) local function process(winid) api.nvim_set_current_win(winid) vim.cmd("noautocmd stopinsert") Diff.add_visited_buffer(bufnr) Diff.process(bufnr) api.nvim_win_set_cursor(winid, { 1, 0 }) vim.defer_fn(function() Diff.find_next(Config.windows.ask.focus_on_apply) vim.cmd("normal! zz") end, 100) end local winid = Utils.get_winid(bufnr) if winid then process(winid) else api.nvim_create_autocmd("BufWinEnter", { group = self.augroup, buffer = bufnr, once = true, callback = function() local winid_ = Utils.get_winid(bufnr) if winid_ then process(winid_) end end, }) end end end, 10) end local buf_options = { modifiable = false, swapfile = false, buftype = "nofile", } local base_win_options = { winfixbuf = true, spell = false, signcolumn = "no", foldcolumn = "0", number = false, relativenumber = false, winfixwidth = true, list = false, linebreak = true, breakindent = true, wrap = false, cursorline = false, fillchars = "eob: ", winhighlight = "CursorLine:Normal,CursorColumn:Normal,WinSeparator:" .. Highlights.AVANTE_SIDEBAR_WIN_SEPARATOR .. ",Normal:" .. Highlights.AVANTE_SIDEBAR_NORMAL, winbar = "", statusline = vim.o.laststatus == 0 and " " or "", } function Sidebar:render_header(winid, bufnr, header_text, hl, reverse_hl) if not Config.windows.sidebar_header.enabled then return end if not bufnr or not api.nvim_buf_is_valid(bufnr) then return end local function format_segment(text, highlight) return "%#" .. highlight .. "#" .. text end if Config.windows.sidebar_header.rounded then header_text = format_segment(Utils.icon("", "『"), reverse_hl) .. format_segment(header_text, hl) .. format_segment(Utils.icon("", "』"), reverse_hl) else header_text = format_segment(" " .. header_text .. " ", hl) end local winbar_text if Config.windows.sidebar_header.align == "left" then winbar_text = header_text .. "%=" .. format_segment("", Highlights.AVANTE_SIDEBAR_WIN_HORIZONTAL_SEPARATOR) elseif Config.windows.sidebar_header.align == "center" then winbar_text = format_segment("%=", Highlights.AVANTE_SIDEBAR_WIN_HORIZONTAL_SEPARATOR) .. header_text .. format_segment("%=", Highlights.AVANTE_SIDEBAR_WIN_HORIZONTAL_SEPARATOR) elseif Config.windows.sidebar_header.align == "right" then winbar_text = format_segment("%=", Highlights.AVANTE_SIDEBAR_WIN_HORIZONTAL_SEPARATOR) .. header_text end api.nvim_set_option_value("winbar", winbar_text, { win = winid }) end function Sidebar:render_result() if not Utils.is_valid_container(self.containers.result) then return end local header_text = Utils.icon("󰭻 ") .. "Avante" self:render_header( self.containers.result.winid, self.containers.result.bufnr, header_text, Highlights.TITLE, Highlights.REVERSED_TITLE ) end ---@param ask? boolean function Sidebar:render_input(ask) if ask == nil then ask = true end if not Utils.is_valid_container(self.containers.input) then return end local header_text = string.format( "%s%s (" .. Config.mappings.sidebar.switch_windows .. ": switch focus)", Utils.icon("󱜸 "), ask and "Ask" or "Chat with" ) if self.code.selection ~= nil then header_text = string.format( "%s%s (%d:%d) (%s: switch focus)", Utils.icon("󱜸 "), ask and "Ask" or "Chat with", self.code.selection.range.start.lnum, self.code.selection.range.finish.lnum, Config.mappings.sidebar.switch_windows ) end self:render_header( self.containers.input.winid, self.containers.input.bufnr, header_text, Highlights.THIRD_TITLE, Highlights.REVERSED_THIRD_TITLE ) end function Sidebar:render_selected_code() if not self.code.selection then return end if not Utils.is_valid_container(self.containers.selected_code) then return end local count = Utils.count_lines(self.code.selection.content) local max_shown = api.nvim_win_get_height(self.containers.selected_code.winid) if Config.windows.sidebar_header.enabled then max_shown = max_shown - 1 end local header_text = Utils.icon(" ") .. "Selected Code" if max_shown < count then header_text = string.format("%s (%d/%d lines)", header_text, max_shown, count) end self:render_header( self.containers.selected_code.winid, self.containers.selected_code.bufnr, header_text, Highlights.SUBTITLE, Highlights.REVERSED_SUBTITLE ) end function Sidebar:bind_apply_key() if self.containers.result then vim.keymap.set( "n", Config.mappings.sidebar.apply_cursor, function() self:apply(true) end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) end end function Sidebar:unbind_apply_key() if self.containers.result then pcall(vim.keymap.del, "n", Config.mappings.sidebar.apply_cursor, { buffer = self.containers.result.bufnr }) end end function Sidebar:bind_retry_user_request_key() if self.containers.result then vim.keymap.set( "n", Config.mappings.sidebar.retry_user_request, function() self:retry_user_request() end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) end end function Sidebar:unbind_retry_user_request_key() if self.containers.result then pcall(vim.keymap.del, "n", Config.mappings.sidebar.retry_user_request, { buffer = self.containers.result.bufnr }) end end function Sidebar:bind_expand_tool_use_key(message_uuid) if self.containers.result then local expanded = self.expanded_message_uuids[message_uuid] vim.keymap.set( "n", Config.mappings.sidebar.expand_tool_use, function() self:handle_expand_message(message_uuid, not expanded) end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) end end function Sidebar:unbind_expand_tool_use_key() if self.containers.result then pcall(vim.keymap.del, "n", Config.mappings.sidebar.expand_tool_use, { buffer = self.containers.result.bufnr }) end end function Sidebar:bind_edit_user_request_key() if self.containers.result then vim.keymap.set( "n", Config.mappings.sidebar.edit_user_request, function() self:edit_user_request() end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) end end function Sidebar:unbind_edit_user_request_key() if self.containers.result then pcall(vim.keymap.del, "n", Config.mappings.sidebar.edit_user_request, { buffer = self.containers.result.bufnr }) end end function Sidebar:render_tool_use_control_buttons() local function show_current_tool_use_control_buttons() if self.current_tool_use_extmark_id then api.nvim_buf_del_extmark( self.containers.result.bufnr, TOOL_MESSAGE_KEYBINDING_NAMESPACE, self.current_tool_use_extmark_id ) end local message_uuid, positions = self:get_current_tool_use_message_uuid() if not message_uuid then return end local expanded = self.expanded_message_uuids[message_uuid] local skip_line_count = self.skip_line_count or 0 self.current_tool_use_extmark_id = api.nvim_buf_set_extmark( self.containers.result.bufnr, TOOL_MESSAGE_KEYBINDING_NAMESPACE, skip_line_count + positions[1] + 2, -1, { virt_text = { { string.format(" [%s: %s] ", Config.mappings.sidebar.expand_tool_use, expanded and "Collapse" or "Expand"), "AvanteInlineHint", }, }, virt_text_pos = "right_align", hl_group = "AvanteInlineHint", priority = PRIORITY, } ) end local current_tool_use_message_uuid = self:get_current_tool_use_message_uuid() if current_tool_use_message_uuid then show_current_tool_use_control_buttons() self:bind_expand_tool_use_key(current_tool_use_message_uuid) else api.nvim_buf_clear_namespace(self.containers.result.bufnr, TOOL_MESSAGE_KEYBINDING_NAMESPACE, 0, -1) self:unbind_expand_tool_use_key() end end function Sidebar:bind_sidebar_keys(codeblocks) ---@param direction "next" | "prev" local function jump_to_codeblock(direction) local cursor_line = api.nvim_win_get_cursor(self.containers.result.winid)[1] ---@type AvanteCodeblock local target_block if direction == "next" then for _, block in ipairs(codeblocks) do if block.start_line > cursor_line then target_block = block break end end if not target_block and #codeblocks > 0 then target_block = codeblocks[1] end elseif direction == "prev" then for i = #codeblocks, 1, -1 do if codeblocks[i].end_line < cursor_line then target_block = codeblocks[i] break end end if not target_block and #codeblocks > 0 then target_block = codeblocks[#codeblocks] end end if target_block then api.nvim_win_set_cursor(self.containers.result.winid, { target_block.start_line, 0 }) vim.cmd("normal! zz") else Utils.error("No codeblock found") end end ---@param direction "next" | "prev" local function jump_to_prompt(direction) local current_request_block = self:get_current_user_request_block() local current_line = Utils.get_cursor_pos(self.containers.result.winid) if not current_request_block then Utils.error("No prompt found") return end if (current_request_block.start_line > current_line and direction == "next") or (current_request_block.end_line < current_line and direction == "prev") then api.nvim_win_set_cursor(self.containers.result.winid, { current_request_block.start_line, 0 }) return end local start_search_line = current_line local result_lines = Utils.get_buf_lines(0, -1, self.containers.result.bufnr) local end_search_line = direction == "next" and #result_lines or 1 local step = direction == "next" and 1 or -1 local query_pos ---@type integer|nil for i = start_search_line, end_search_line, step do local result_line = result_lines[i] if result_line == RESP_SEPARATOR then query_pos = direction == "next" and i + 1 or i - 1 break end end if not query_pos then Utils.error("No other prompt found " .. (direction == "next" and "below" or "above")) return end current_request_block = self:get_current_user_request_block(query_pos) if not current_request_block then Utils.error("No prompt found") return end api.nvim_win_set_cursor(self.containers.result.winid, { current_request_block.start_line, 0 }) end vim.keymap.set( "n", Config.mappings.sidebar.apply_all, function() self:apply(false) end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) vim.keymap.set( "n", Config.mappings.jump.next, function() jump_to_codeblock("next") end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) vim.keymap.set( "n", Config.mappings.jump.prev, function() jump_to_codeblock("prev") end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) vim.keymap.set( "n", Config.mappings.sidebar.next_prompt, function() jump_to_prompt("next") end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) vim.keymap.set( "n", Config.mappings.sidebar.prev_prompt, function() jump_to_prompt("prev") end, { buffer = self.containers.result.bufnr, noremap = true, silent = true } ) end function Sidebar:unbind_sidebar_keys() if Utils.is_valid_container(self.containers.result) then pcall(vim.keymap.del, "n", Config.mappings.sidebar.apply_all, { buffer = self.containers.result.bufnr }) pcall(vim.keymap.del, "n", Config.mappings.jump.next, { buffer = self.containers.result.bufnr }) pcall(vim.keymap.del, "n", Config.mappings.jump.prev, { buffer = self.containers.result.bufnr }) end end ---@param opts AskOptions function Sidebar:on_mount(opts) self:setup_window_navigation(self.containers.result) -- Add keymap to add current buffer while sidebar is open if Config.behaviour.auto_set_keymaps and Config.mappings.files and Config.mappings.files.add_current then vim.keymap.set("n", Config.mappings.files.add_current, function() if self:is_open() and self.file_selector:add_current_buffer() then vim.notify("Added current buffer to file selector", vim.log.levels.DEBUG, { title = "Avante" }) else vim.notify("Failed to add current buffer", vim.log.levels.WARN, { title = "Avante" }) end end, { desc = "avante: add current buffer to file selector", noremap = true, silent = true, }) end api.nvim_set_option_value("wrap", Config.windows.wrap, { win = self.containers.result.winid }) local current_apply_extmark_id = nil ---@param block AvanteCodeblock local function show_apply_button(block) if current_apply_extmark_id then api.nvim_buf_del_extmark(self.containers.result.bufnr, CODEBLOCK_KEYBINDING_NAMESPACE, current_apply_extmark_id) end current_apply_extmark_id = api.nvim_buf_set_extmark( self.containers.result.bufnr, CODEBLOCK_KEYBINDING_NAMESPACE, block.start_line - 1, -1, { virt_text = { { string.format( " [<%s>: apply this, <%s>: apply all] ", Config.mappings.sidebar.apply_cursor, Config.mappings.sidebar.apply_all ), "AvanteInlineHint", }, }, virt_text_pos = "right_align", hl_group = "AvanteInlineHint", priority = PRIORITY, } ) end local current_user_request_block_extmark_id = nil local function show_user_request_block_control_buttons() if current_user_request_block_extmark_id then api.nvim_buf_del_extmark( self.containers.result.bufnr, USER_REQUEST_BLOCK_KEYBINDING_NAMESPACE, current_user_request_block_extmark_id ) end local block = self:get_current_user_request_block() if not block then return end current_user_request_block_extmark_id = api.nvim_buf_set_extmark( self.containers.result.bufnr, USER_REQUEST_BLOCK_KEYBINDING_NAMESPACE, block.start_line - 1, -1, { virt_text = { { string.format( " [<%s>: retry, <%s>: edit] ", Config.mappings.sidebar.retry_user_request, Config.mappings.sidebar.edit_user_request ), "AvanteInlineHint", }, }, virt_text_pos = "right_align", hl_group = "AvanteInlineHint", priority = PRIORITY, } ) end ---@type AvanteCodeblock[] local codeblocks = {} api.nvim_create_autocmd({ "CursorMoved", "CursorMovedI" }, { group = self.augroup, buffer = self.containers.result.bufnr, callback = function(ev) self:render_tool_use_control_buttons() local in_codeblock = is_cursor_in_codeblock(codeblocks) if in_codeblock then show_apply_button(in_codeblock) self:bind_apply_key() else api.nvim_buf_clear_namespace(ev.buf, CODEBLOCK_KEYBINDING_NAMESPACE, 0, -1) self:unbind_apply_key() end local in_user_request_block = self:is_cursor_in_user_request_block() if in_user_request_block then show_user_request_block_control_buttons() self:bind_retry_user_request_key() self:bind_edit_user_request_key() else api.nvim_buf_clear_namespace(ev.buf, USER_REQUEST_BLOCK_KEYBINDING_NAMESPACE, 0, -1) self:unbind_retry_user_request_key() self:unbind_edit_user_request_key() end end, }) if self.code.bufnr and api.nvim_buf_is_valid(self.code.bufnr) then api.nvim_create_autocmd({ "BufEnter", "BufWritePost" }, { group = self.augroup, buffer = self.containers.result.bufnr, callback = function(ev) codeblocks = parse_codeblocks(ev.buf) self:bind_sidebar_keys(codeblocks) end, }) api.nvim_create_autocmd("User", { group = self.augroup, pattern = VIEW_BUFFER_UPDATED_PATTERN, callback = function() if not Utils.is_valid_container(self.containers.result) then return end codeblocks = parse_codeblocks(self.containers.result.bufnr) self:bind_sidebar_keys(codeblocks) end, }) end api.nvim_create_autocmd("BufLeave", { group = self.augroup, buffer = self.containers.result.bufnr, callback = function() self:unbind_sidebar_keys() end, }) self:render_result() self:render_input(opts.ask) self:render_selected_code() if self.containers.selected_code ~= nil then local selected_code_buf = self.containers.selected_code.bufnr if selected_code_buf ~= nil then if self.code.selection ~= nil then Utils.unlock_buf(selected_code_buf) local lines = vim.split(self.code.selection.content, "\n") api.nvim_buf_set_lines(selected_code_buf, 0, -1, false, lines) Utils.lock_buf(selected_code_buf) end if self.code.bufnr and api.nvim_buf_is_valid(self.code.bufnr) then local ts_ok, ts_highlighter = pcall(require, "vim.treesitter.highlighter") if ts_ok and ts_highlighter.active[self.code.bufnr] then -- Treesitter highlighting is active in the code buffer, activate it -- it in code selection buffer as well. local filetype = vim.bo[self.code.bufnr].filetype local lang = vim.treesitter.language.get_lang(filetype or "") if lang and lang ~= "" then vim.treesitter.start(selected_code_buf, lang) end end -- Try the old syntax highlighting local syntax = api.nvim_get_option_value("syntax", { buf = self.code.bufnr }) if syntax and syntax ~= "" then api.nvim_set_option_value("syntax", syntax, { buf = selected_code_buf }) end end end end api.nvim_create_autocmd("BufEnter", { group = self.augroup, buffer = self.containers.result.bufnr, callback = function() if Config.behaviour.auto_focus_sidebar then self:focus() if Utils.is_valid_container(self.containers.input, true) then api.nvim_set_current_win(self.containers.input.winid) vim.defer_fn(function() if Config.windows.ask.start_insert then vim.cmd("noautocmd startinsert!") end end, 300) end end return true end, }) for _, container in pairs(self.containers) do if container.mount and container.bufnr and api.nvim_buf_is_valid(container.bufnr) then Utils.mark_as_sidebar_buffer(container.bufnr) end end end --- Given a desired container name, returns the window ID of the first valid container --- situated above it in the sidebar's order. --- @param container_name string The name of the container to start searching from. --- @return integer|nil The window ID of the previous valid container, or nil. function Sidebar:get_split_candidate(container_name) local start_index = 0 for i, name in ipairs(SIDEBAR_CONTAINERS) do if name == container_name then start_index = i break end end if start_index > 1 then for i = start_index - 1, 1, -1 do local container = self.containers[SIDEBAR_CONTAINERS[i]] if Utils.is_valid_container(container, true) then return container.winid end end end return nil end ---Cycles focus over sidebar components. ---@param direction "next" | "previous" function Sidebar:switch_window_focus(direction) local current_winid = vim.api.nvim_get_current_win() local current_index = nil local ordered_winids = {} for _, name in ipairs(SIDEBAR_CONTAINERS) do local container = self.containers[name] if container and container.winid then table.insert(ordered_winids, container.winid) if container.winid == current_winid then current_index = #ordered_winids end end end if current_index and #ordered_winids > 1 then local next_index if direction == "next" then next_index = (current_index % #ordered_winids) + 1 elseif direction == "previous" then next_index = current_index - 1 if next_index < 1 then next_index = #ordered_winids end else error("Invalid 'direction' parameter: " .. direction) end vim.api.nvim_set_current_win(ordered_winids[next_index]) end end ---Sets up focus switching shortcuts for a sidebar component ---@param container NuiSplit function Sidebar:setup_window_navigation(container) local buf = api.nvim_win_get_buf(container.winid) Utils.safe_keymap_set( { "n", "i" }, Config.mappings.sidebar.switch_windows, function() self:switch_window_focus("next") end, { buffer = buf, noremap = true, silent = true, nowait = true } ) Utils.safe_keymap_set( { "n", "i" }, Config.mappings.sidebar.reverse_switch_windows, function() self:switch_window_focus("previous") end, { buffer = buf, noremap = true, silent = true, nowait = true } ) end function Sidebar:resize() for _, container in pairs(self.containers) do if container.winid and api.nvim_win_is_valid(container.winid) then if self.is_in_full_view then api.nvim_win_set_width(container.winid, vim.o.columns - 1) else api.nvim_win_set_width(container.winid, Config.get_window_width()) end end end self:render_result() self:render_input() self:render_selected_code() vim.defer_fn(function() vim.cmd("AvanteRefresh") end, 200) end function Sidebar:render_logo() local logo_lines = vim.split(logo, "\n") local max_width = 30 --- get editor width local editor_width = vim.api.nvim_win_get_width(self.containers.result.winid) local padding = math.floor((editor_width - max_width) / 2) Utils.unlock_buf(self.containers.result.bufnr) for i, line in ipairs(logo_lines) do --- center logo line = vim.trim(line) vim.api.nvim_buf_set_lines(self.containers.result.bufnr, i - 1, i, false, { string.rep(" ", padding) .. line }) --- apply gradient color if line ~= "" then local hl_group = "AvanteLogoLine" .. i vim.api.nvim_buf_set_extmark(self.containers.result.bufnr, RESULT_BUF_HL_NAMESPACE, i - 1, padding, { end_col = padding + #line, hl_group = hl_group, }) end end Utils.lock_buf(self.containers.result.bufnr) return #logo_lines end function Sidebar:toggle_code_window() -- Collect all windows that do not belong to the sidebar local winids = vim .iter(api.nvim_tabpage_list_wins(self.id)) :filter(function(winid) return not self:is_sidebar_winid(winid) end) :totable() if self.is_in_full_view then -- Transitioning to normal view: restore sizes of all non-sidebar windows for _, winid in ipairs(winids) do local old_size = self.win_size_store[winid] if old_size then api.nvim_win_set_width(winid, old_size.width) api.nvim_win_set_height(winid, old_size.height) end end else -- Transitioning to full view: hide all non-sidebar windows -- We need do this in 2 phases: first phase is to collect window sizes -- and 2nd phase is to actually maximize the sidebar. If we attempt to do -- everything is one pass sizes of windows may change in the process and -- we'll end up with a mess. self.win_size_store = {} for _, winid in ipairs(winids) do if Utils.is_floating_window(winid) then api.nvim_win_close(winid, true) else self.win_size_store[winid] = { width = api.nvim_win_get_width(winid), height = api.nvim_win_get_height(winid) } end end if self:get_layout() == "vertical" then api.nvim_win_set_width(self.code.winid, 0) api.nvim_win_set_width(self.containers.result.winid, vim.o.columns - 1) else api.nvim_win_set_height(self.containers.result.winid, vim.o.lines) end end self.is_in_full_view = not self.is_in_full_view end --- Initialize the sidebar instance. --- @return avante.Sidebar The Sidebar instance. function Sidebar:initialize() self.code.winid = api.nvim_get_current_win() self.code.bufnr = api.nvim_get_current_buf() self.code.selection = Utils.get_visual_selection_and_range() if not self.code.bufnr or not api.nvim_buf_is_valid(self.code.bufnr) then return self end -- check if the filetype of self.code.bufnr is disabled local buf_ft = api.nvim_get_option_value("filetype", { buf = self.code.bufnr }) if vim.list_contains(Config.selector.exclude_auto_select, buf_ft) then return self end self.file_selector:reset() -- Only auto-add current file if configured to do so if Config.behaviour.auto_add_current_file then local buf_path = api.nvim_buf_get_name(self.code.bufnr) -- if the filepath is outside of the current working directory then we want the absolute path local filepath = Utils.file.is_in_project(buf_path) and Utils.relative_path(buf_path) or buf_path Utils.debug("Sidebar:initialize adding buffer to file selector", buf_path) local stat = vim.uv.fs_stat(filepath) if stat == nil or stat.type == "file" then self.file_selector:add_selected_file(filepath) end end self:reload_chat_history() return self end function Sidebar:is_focused_on_result() return self:is_open() and self.containers.result and self.containers.result.winid == api.nvim_get_current_win() end ---Locates container object by its window ID ---@param winid integer ---@return NuiSplit|nil function Sidebar:get_sidebar_window(winid) for _, container in pairs(self.containers) do if container.winid == winid then return container end end end ---Checks if a window with given ID belongs to the sidebar ---@param winid integer ---@return boolean function Sidebar:is_sidebar_winid(winid) return self:get_sidebar_window(winid) ~= nil end ---@return boolean function Sidebar:should_auto_scroll() if not self.containers.result or not self.containers.result.winid then return false end if not api.nvim_win_is_valid(self.containers.result.winid) then return false end local win_height = api.nvim_win_get_height(self.containers.result.winid) local total_lines = api.nvim_buf_line_count(self.containers.result.bufnr) local topline = vim.fn.line("w0", self.containers.result.winid) local last_visible_line = topline + win_height - 1 local is_scrolled_to_bottom = last_visible_line >= total_lines - 1 return is_scrolled_to_bottom end Sidebar.throttled_update_content = Utils.throttle(function(self, ...) local args = { ... } self:update_content(unpack(args)) end, 50) ---@param content string concatenated content of the buffer ---@param opts? {focus?: boolean, scroll?: boolean, backspace?: integer, callback?: fun(): nil} whether to focus the result view function Sidebar:update_content(content, opts) if not Utils.is_valid_container(self.containers.result) then return end local should_auto_scroll = self:should_auto_scroll() opts = vim.tbl_deep_extend( "force", { focus = false, scroll = should_auto_scroll and self.scroll, callback = nil }, opts or {} ) local history_lines local tool_message_positions if not self._cached_history_lines or self._history_cache_invalidated then history_lines, tool_message_positions = self:get_history_lines(self.chat_history, self.show_logo) self.tool_message_positions = tool_message_positions self._cached_history_lines = history_lines self._history_cache_invalidated = false else history_lines = vim.deepcopy(self._cached_history_lines) end if content ~= nil and content ~= "" then table.insert(history_lines, Line:new({ { "" } })) for _, line in ipairs(vim.split(content, "\n")) do table.insert(history_lines, Line:new({ { line } })) end end if not Utils.is_valid_container(self.containers.result) then return end self:clear_state() local skip_line_count = 0 if self.show_logo then skip_line_count = self:render_logo() self.skip_line_count = skip_line_count end local bufnr = self.containers.result.bufnr Utils.unlock_buf(bufnr) Utils.update_buffer_lines(RESULT_BUF_HL_NAMESPACE, bufnr, self.old_result_lines, history_lines, skip_line_count) self.old_result_lines = history_lines api.nvim_set_option_value("filetype", "Avante", { buf = bufnr }) Utils.lock_buf(bufnr) vim.defer_fn(function() if self.permission_button_options and self.permission_handler then local cur_winid = api.nvim_get_current_win() if cur_winid == self.containers.result.winid then local line_count = api.nvim_buf_line_count(bufnr) api.nvim_win_set_cursor(cur_winid, { line_count - 3, 0 }) end end end, 100) if opts.focus and not self:is_focused_on_result() then xpcall(function() api.nvim_set_current_win(self.containers.result.winid) end, function(err) Utils.debug("Failed to set current win:", err) return err end) end if opts.scroll then Utils.buf_scroll_to_end(bufnr) end if opts.callback then vim.schedule(opts.callback) end vim.schedule(function() self:render_state() self:render_tool_use_control_buttons() vim.defer_fn(function() vim.cmd("redraw") end, 10) end) return self end ---@param timestamp string|osdate ---@param provider string ---@param model string ---@param request string ---@param selected_filepaths string[] ---@param selected_code AvanteSelectedCode? ---@return string local function render_chat_record_prefix(timestamp, provider, model, request, selected_filepaths, selected_code) local res local acp_provider = Config.acp_providers[provider] if acp_provider then res = "- Datetime: " .. timestamp .. "\n" .. "- ACP: " .. provider else provider = provider or "unknown" model = model or "unknown" res = "- Datetime: " .. timestamp .. "\n" .. "- Model: " .. provider .. "/" .. model end if selected_filepaths ~= nil and #selected_filepaths > 0 then res = res .. "\n- Selected files:" for _, path in ipairs(selected_filepaths) do res = res .. "\n - " .. path end end if selected_code ~= nil then res = res .. "\n\n- Selected code: " .. "\n\n```" .. (selected_code.file_type or "") .. (selected_code.path and " " .. selected_code.path or "") .. "\n" .. selected_code.content .. "\n```" end return res .. "\n\n> " .. request:gsub("\n", "\n> "):gsub("([%w-_]+)%b[]", "`%0`") end local function calculate_config_window_position() local position = Config.windows.position if position == "smart" then -- get editor width local editor_width = vim.o.columns -- get editor height local editor_height = vim.o.lines * 3 if editor_width > editor_height then position = "right" else position = "bottom" end end ---@cast position -"smart", -string return position end function Sidebar:get_layout() return vim.tbl_contains({ "left", "right" }, calculate_config_window_position()) and "vertical" or "horizontal" end ---@param ctx table ---@param message avante.HistoryMessage ---@param messages avante.HistoryMessage[] ---@param ignore_record_prefix boolean | nil ---@return avante.ui.Line[] function Sidebar:_get_message_lines(ctx, message, messages, ignore_record_prefix) local expanded = self.expanded_message_uuids[message.uuid] if message.visible == false then return {} end local lines = Render.message_to_lines(message, messages, expanded) if message.is_user_submission and not ignore_record_prefix then ctx.selected_filepaths = message.selected_filepaths local text = table.concat(vim.tbl_map(function(line) return tostring(line) end, lines), "\n") local prefix = render_chat_record_prefix( message.timestamp, message.provider, message.model, text, message.selected_filepaths, message.selected_code ) local res = {} for _, line_ in ipairs(vim.split(prefix, "\n")) do table.insert(res, Line:new({ { line_ } })) end return res end if message.message.role == "user" then local res = {} for _, line_ in ipairs(lines) do local sections = { { "> " } } sections = vim.list_extend(sections, line_.sections) table.insert(res, Line:new(sections)) end return res end if message.message.role == "assistant" then if History.Helpers.is_tool_use_message(message) then return lines end local text = table.concat(vim.tbl_map(function(line) return tostring(line) end, lines), "\n") local transformed = transform_result_content(text, ctx.prev_filepath) ctx.prev_filepath = transformed.current_filepath local displayed_content = generate_display_content(transformed) local res = {} for _, line_ in ipairs(vim.split(displayed_content, "\n")) do table.insert(res, Line:new({ { line_ } })) end return res end return lines end local _message_to_lines_lru_cache = LRUCache:new(100) ---@param ctx table ---@param message avante.HistoryMessage ---@param messages avante.HistoryMessage[] ---@param ignore_record_prefix boolean | nil ---@return avante.ui.Line[] function Sidebar:get_message_lines(ctx, message, messages, ignore_record_prefix) local expanded = self.expanded_message_uuids[message.uuid] if message.state == "generating" or message.is_calling then local lines = self:_get_message_lines(ctx, message, messages, ignore_record_prefix) if self.permission_handler and self.permission_button_options then local button_group_line = ButtonGroupLine:new(self.permission_button_options, { on_click = self.permission_handler, group_label = "Waiting for Confirmation... ", }) table.insert(lines, Line:new({ { "" } })) table.insert(lines, button_group_line) end return lines end local text_len = 0 local content = message.message.content if type(content) == "table" then for _, item in ipairs(content) do if type(item) == "string" then text_len = text_len + #item else for _, subitem in pairs(item) do if type(subitem) == "string" then text_len = text_len + #subitem end end end end elseif type(content) == "string" then text_len = #content end local cache_key = message.uuid .. ":" .. message.state .. ":" .. tostring(text_len) .. ":" .. tostring(expanded == true) local cached_lines = _message_to_lines_lru_cache:get(cache_key) if cached_lines then return cached_lines end local lines = self:_get_message_lines(ctx, message, messages, ignore_record_prefix) --- trim suffix empty lines while #lines > 0 and tostring(lines[#lines]) == "" do table.remove(lines) end _message_to_lines_lru_cache:set(cache_key, lines) return lines end ---@param history avante.ChatHistory ---@param ignore_record_prefix boolean | nil ---@return avante.ui.Line[] history_lines ---@return table<string, [integer, integer]> tool_message_positions function Sidebar:get_history_lines(history, ignore_record_prefix) local history_messages = History.get_history_messages(history) local ctx = {} ---@type avante.ui.Line[] local res = {} local tool_message_positions = {} local is_first_user_submission = true for _, message in ipairs(history_messages) do local lines = self:get_message_lines(ctx, message, history_messages, ignore_record_prefix) if #lines == 0 then goto continue end if message.is_user_submission then if not is_first_user_submission then if ignore_record_prefix then res = vim.list_extend(res, { Line:new({ { "" } }), Line:new({ { "" } }) }) else res = vim.list_extend(res, { Line:new({ { "" } }), Line:new({ { RESP_SEPARATOR } }), Line:new({ { "" } }) }) end end is_first_user_submission = false end if message.message.role == "assistant" and not message.just_for_display and tostring(lines[1]) ~= "" then table.insert(lines, 1, Line:new({ { "" } })) table.insert(lines, 1, Line:new({ { "" } })) end if History.Helpers.is_tool_use_message(message) then tool_message_positions[message.uuid] = { #res, #res + #lines } end res = vim.list_extend(res, lines) ::continue:: end table.insert(res, Line:new({ { "" } })) table.insert(res, Line:new({ { "" } })) table.insert(res, Line:new({ { "" } })) return res, tool_message_positions end ---@param message avante.HistoryMessage ---@param messages avante.HistoryMessage[] ---@param ctx table ---@return string | nil local function render_message(message, messages, ctx) if message.visible == false then return nil end local text = Render.message_to_text(message, messages) if text == "" then return nil end if message.is_user_submission then ctx.selected_filepaths = message.selected_filepaths local prefix = render_chat_record_prefix( message.timestamp, message.provider, message.model, text, message.selected_filepaths, message.selected_code ) return prefix end if message.message.role == "user" then local lines = vim.split(text, "\n") lines = vim.iter(lines):map(function(line) return "> " .. line end):totable() text = table.concat(lines, "\n") return text end if message.message.role == "assistant" then local transformed = transform_result_content(text, ctx.prev_filepath) ctx.prev_filepath = transformed.current_filepath local displayed_content = generate_display_content(transformed) return displayed_content end return "" end ---@param history avante.ChatHistory ---@return string function Sidebar.render_history_content(history) local history_messages = History.get_history_messages(history) local ctx = {} local group = {} for _, message in ipairs(history_messages) do local text = render_message(message, history_messages, ctx) if text == nil then goto continue end if message.is_user_submission then table.insert(group, {}) end local last_item = group[#group] if last_item == nil then table.insert(group, {}) last_item = group[#group] end if message.message.role == "assistant" and not message.just_for_display and text:sub(1, 2) ~= "\n\n" then text = "\n\n" .. text end table.insert(last_item, text) ::continue:: end local pieces = {} for _, item in ipairs(group) do table.insert(pieces, table.concat(item, "")) end return table.concat(pieces, "\n\n" .. RESP_SEPARATOR .. "\n\n") .. "\n\n" end function Sidebar:update_content_with_history() self:reload_chat_history() self:update_content("") end ---@param position? integer ---@return string, integer function Sidebar:get_content_between_separators(position) local separator = RESP_SEPARATOR local cursor_line = position or Utils.get_cursor_pos() local lines = Utils.get_buf_lines(0, -1, self.containers.result.bufnr) local start_line, end_line for i = cursor_line, 1, -1 do if lines[i] == separator then start_line = i + 1 break end end start_line = start_line or 1 for i = cursor_line, #lines do if lines[i] == separator then end_line = i - 1 break end end end_line = end_line or #lines if lines[cursor_line] == separator then if cursor_line > 1 and lines[cursor_line - 1] ~= separator then end_line = cursor_line - 1 elseif cursor_line < #lines and lines[cursor_line + 1] ~= separator then start_line = cursor_line + 1 end end local content = table.concat(vim.list_slice(lines, start_line, end_line), "\n") return content, start_line end function Sidebar:clear_history(args, cb) self.current_state = nil if next(self.chat_history) ~= nil then self.chat_history.messages = {} self.chat_history.entries = {} Path.history.save(self.code.bufnr, self.chat_history) self._history_cache_invalidated = true self:reload_chat_history() self:update_content_with_history() self:update_content( "Chat history cleared", { focus = false, scroll = false, callback = function() self:focus_input() end } ) if cb then cb(args) end else self:update_content( "Chat history is already empty", { focus = false, scroll = false, callback = function() self:focus_input() end } ) end end function Sidebar:clear_state() if self.state_extmark_id and self.containers.result then pcall(api.nvim_buf_del_extmark, self.containers.result.bufnr, STATE_NAMESPACE, self.state_extmark_id) end self.state_extmark_id = nil self.state_spinner_idx = 1 if self.state_timer then self.state_timer:stop() end end function Sidebar:render_state() if not Utils.is_valid_container(self.containers.result) then return end if not self.current_state then return end local lines = vim.api.nvim_buf_get_lines(self.containers.result.bufnr, 0, -1, false) if self.state_extmark_id then api.nvim_buf_del_extmark(self.containers.result.bufnr, STATE_NAMESPACE, self.state_extmark_id) end local spinner_chars = self.state_spinner_chars if self.current_state == "thinking" then spinner_chars = self.thinking_spinner_chars end local hl = "AvanteStateSpinnerGenerating" if self.current_state == "tool calling" then hl = "AvanteStateSpinnerToolCalling" end if self.current_state == "failed" then hl = "AvanteStateSpinnerFailed" end if self.current_state == "succeeded" then hl = "AvanteStateSpinnerSucceeded" end if self.current_state == "searching" then hl = "AvanteStateSpinnerSearching" end if self.current_state == "thinking" then hl = "AvanteStateSpinnerThinking" end if self.current_state == "compacting" then hl = "AvanteStateSpinnerCompacting" end local spinner_char = spinner_chars[self.state_spinner_idx] if not spinner_char then spinner_char = spinner_chars[1] end self.state_spinner_idx = (self.state_spinner_idx % #spinner_chars) + 1 if self.current_state ~= "generating" and self.current_state ~= "tool calling" and self.current_state ~= "thinking" and self.current_state ~= "compacting" then spinner_char = "" end local virt_line if spinner_char == "" then virt_line = " " .. self.current_state .. " " else virt_line = " " .. spinner_char .. " " .. self.current_state .. " " end local win_width = api.nvim_win_get_width(self.containers.result.winid) local padding = math.floor((win_width - vim.fn.strdisplaywidth(virt_line)) / 2) local centered_virt_lines = { { { string.rep(" ", padding) }, { virt_line, hl } }, } local line_num = math.max(0, #lines - 2) self.state_extmark_id = api.nvim_buf_set_extmark(self.containers.result.bufnr, STATE_NAMESPACE, line_num, 0, { virt_lines = centered_virt_lines, hl_eol = true, hl_mode = "combine", }) self.state_timer = vim.defer_fn(function() self:render_state() end, 160) end function Sidebar:init_current_project(args, cb) local user_input = [[ You are a responsible senior development engineer, and you are about to leave your position. Please carefully analyze the entire project and generate a handover document to be stored in the AGENTS.md file, so that subsequent developers can quickly get up to speed. The requirements are as follows: - If there is an AGENTS.md file in the project root directory, combine it with the existing AGENTS.md content to generate a new AGENTS.md. - If the existing AGENTS.md content conflicts with the newly generated content, replace the conflicting old parts with the new content. - If there is no AGENTS.md file in the project root directory, create a new AGENTS.md file and write the new content in it.]] self:new_chat(args, cb) self.code.selection = nil self.file_selector:reset() if self.containers.selected_files then self.containers.selected_files:unmount() end vim.api.nvim_exec_autocmds("User", { pattern = "AvanteInputSubmitted", data = { request = user_input } }) end function Sidebar:compact_history_messages(args, cb) local history_memory = self.chat_history.memory local messages = History.get_history_messages(self.chat_history) self.current_state = "compacting" self:render_state() self:update_content( "compacting history messsages", { focus = false, scroll = true, callback = function() self:focus_input() end } ) Llm.summarize_memory(history_memory and history_memory.content, messages, function(memory) if memory then self.chat_history.memory = memory Path.history.save(self.code.bufnr, self.chat_history) end self:update_content("compacted!", { focus = false, scroll = true, callback = function() self:focus_input() end }) self.current_state = "compacted" self:clear_state() if cb then cb(args) end end) end function Sidebar:new_chat(args, cb) local history = Path.history.new(self.code.bufnr) Path.history.save(self.code.bufnr, history) self:reload_chat_history() self.current_state = nil self.expanded_message_uuids = {} self.tool_message_positions = {} self.current_tool_use_extmark_id = nil self:update_content("New chat", { focus = false, scroll = false, callback = function() self:focus_input() end }) --- goto first line then go to last line vim.schedule(function() vim.api.nvim_win_call(self.containers.result.winid, function() vim.cmd("normal! ggG") end) end) if cb then cb(args) end vim.schedule(function() self:create_todos_container() end) end local debounced_save_history = Utils.debounce( function(self) Path.history.save(self.code.bufnr, self.chat_history) end, 1000 ) function Sidebar:save_history() debounced_save_history(self) end ---@param uuids string[] function Sidebar:delete_history_messages(uuids) local history_messages = History.get_history_messages(self.chat_history) for _, msg in ipairs(history_messages) do if vim.list_contains(uuids, msg.uuid) then msg.is_deleted = true end end Path.history.save(self.code.bufnr, self.chat_history) end ---@param todos avante.TODO[] function Sidebar:update_todos(todos) if self.chat_history == nil then self:reload_chat_history() end if self.chat_history == nil then return end self.chat_history.todos = todos Path.history.save(self.code.bufnr, self.chat_history) self:create_todos_container() end ---@param messages avante.HistoryMessage | avante.HistoryMessage[] ---@param opts? {eager_update?: boolean} function Sidebar:add_history_messages(messages, opts) local history_messages = History.get_history_messages(self.chat_history) messages = vim.islist(messages) and messages or { messages } for _, message in ipairs(messages) do if message.is_user_submission then message.provider = Config.provider if not Config.acp_providers[Config.provider] then message.model = Config.get_provider_config(Config.provider).model end end local idx = nil for idx_, message_ in ipairs(history_messages) do if message_.uuid == message.uuid then idx = idx_ break end end if idx ~= nil then history_messages[idx] = message else table.insert(history_messages, message) end end self.chat_history.messages = history_messages self._history_cache_invalidated = true self:save_history() if self.chat_history.title == "untitled" and #messages > 0 and messages[1].just_for_display ~= true and messages[1].state == "generated" then local first_msg_text = Render.message_to_text(messages[1], messages) local lines_ = vim.iter(vim.split(first_msg_text, "\n")):filter(function(line) return line ~= "" end):totable() if #lines_ > 0 then self.chat_history.title = lines_[1] self:save_history() end end local last_message = messages[#messages] if last_message then if History.Helpers.is_tool_use_message(last_message) then self.current_state = "tool calling" elseif History.Helpers.is_thinking_message(last_message) then self.current_state = "thinking" else self.current_state = "generating" end end if opts and opts.eager_update then pcall(function() self:update_content("") end) return end xpcall(function() self:throttled_update_content("") end, function(err) Utils.debug("Failed to update content:", err) return nil end) end -- FIXME: this is used by external plugin users ---@param messages AvanteLLMMessage | AvanteLLMMessage[] ---@param options {visible?: boolean} function Sidebar:add_chat_history(messages, options) options = options or {} messages = vim.islist(messages) and messages or { messages } local is_first_user = true local history_messages = {} for _, message in ipairs(messages) do local role = message.role if role == "system" and type(message.content) == "string" then self.chat_history.system_prompt = message.content --[[@as string]] else ---@type AvanteLLMMessageContentItem local content = type(message.content) ~= "table" and message.content or message.content[1] local msg_opts = { visible = options.visible } if role == "user" and is_first_user then msg_opts.is_user_submission = true is_first_user = false end table.insert(history_messages, History.Message:new(role, content, msg_opts)) end end self:add_history_messages(history_messages) end function Sidebar:create_selected_code_container() if self.containers.selected_code ~= nil then self.containers.selected_code:unmount() self.containers.selected_code = nil end local height = self:get_selected_code_container_height() if self.code.selection ~= nil then self.containers.selected_code = Split({ enter = false, relative = { type = "win", winid = self:get_split_candidate("selected_code"), }, buf_options = vim.tbl_deep_extend("force", buf_options, { filetype = "AvanteSelectedCode" }), win_options = vim.tbl_deep_extend("force", base_win_options, {}), size = { height = height, }, position = "bottom", }) self.containers.selected_code:mount() self:adjust_layout() self:setup_window_navigation(self.containers.selected_code) end end function Sidebar:close_input_hint() if self.input_hint_window and api.nvim_win_is_valid(self.input_hint_window) then local buf = api.nvim_win_get_buf(self.input_hint_window) if INPUT_HINT_NAMESPACE then api.nvim_buf_clear_namespace(buf, INPUT_HINT_NAMESPACE, 0, -1) end api.nvim_win_close(self.input_hint_window, true) api.nvim_buf_delete(buf, { force = true }) self.input_hint_window = nil end end function Sidebar:get_input_float_window_row() local win_height = api.nvim_win_get_height(self.containers.input.winid) local winline = Utils.winline(self.containers.input.winid) if winline >= win_height - 1 then return 0 end return winline end -- Create a floating window as a hint function Sidebar:show_input_hint() self:close_input_hint() -- Close the existing hint window local hint_text = (fn.mode() ~= "i" and Config.mappings.submit.normal or Config.mappings.submit.insert) .. ": submit" if Config.behaviour.enable_token_counting then local input_value = table.concat(api.nvim_buf_get_lines(self.containers.input.bufnr, 0, -1, false), "\n") if self.token_count == nil then self:initialize_token_count() end local tokens = self.token_count + Utils.tokens.calculate_tokens(input_value) hint_text = "Tokens: " .. tostring(tokens) .. "; " .. hint_text end local buf = api.nvim_create_buf(false, true) api.nvim_buf_set_lines(buf, 0, -1, false, { hint_text }) api.nvim_buf_set_extmark(buf, INPUT_HINT_NAMESPACE, 0, 0, { hl_group = "AvantePopupHint", end_col = #hint_text }) -- Get the current window size local win_width = api.nvim_win_get_width(self.containers.input.winid) local width = #hint_text -- Create the floating window self.input_hint_window = api.nvim_open_win(buf, false, { relative = "win", win = self.containers.input.winid, width = width, height = 1, row = self:get_input_float_window_row(), col = math.max(win_width - width, 0), -- Display in the bottom right corner style = "minimal", border = "none", focusable = false, zindex = 100, }) end function Sidebar:close_selected_files_hint() if self.containers.selected_files and api.nvim_win_is_valid(self.containers.selected_files.winid) then pcall(api.nvim_buf_clear_namespace, self.containers.selected_files.bufnr, SELECTED_FILES_HINT_NAMESPACE, 0, -1) end end function Sidebar:show_selected_files_hint() self:close_selected_files_hint() local cursor_pos = api.nvim_win_get_cursor(self.containers.selected_files.winid) local line_number = cursor_pos[1] local col_number = cursor_pos[2] local selected_filepaths_ = self.file_selector:get_selected_filepaths() local hint if #selected_filepaths_ == 0 then hint = string.format(" [%s: add] ", Config.mappings.sidebar.add_file) else hint = string.format(" [%s: delete, %s: add] ", Config.mappings.sidebar.remove_file, Config.mappings.sidebar.add_file) end api.nvim_buf_set_extmark( self.containers.selected_files.bufnr, SELECTED_FILES_HINT_NAMESPACE, line_number - 1, col_number, { virt_text = { { hint, "AvanteInlineHint" } }, virt_text_pos = "right_align", hl_group = "AvanteInlineHint", priority = PRIORITY, } ) end function Sidebar:reload_chat_history() self.token_count = nil if not self.code.bufnr or not api.nvim_buf_is_valid(self.code.bufnr) then return end self.chat_history = Path.history.load(self.code.bufnr) self._history_cache_invalidated = true end ---@param opts? {all?: boolean} ---@return avante.HistoryMessage[] function Sidebar:get_history_messages_for_api(opts) opts = opts or {} local messages = History.get_history_messages(self.chat_history) -- Scan the initial set of messages, filtering out "uninteresting" ones, but also -- check if the last message mentioned in the chat memory is actually present. local last_message = self.chat_history.memory and self.chat_history.memory.last_message_uuid local last_message_present = false messages = vim .iter(messages) :filter(function(message) if message.just_for_display or message.is_compacted then return false end if not opts.all then if message.state == "generating" then return false end if last_message and message.uuid == last_message then last_message_present = true end end return true end) :totable() if not opts.all then if last_message and last_message_present then -- Drop all old messages preceding the "last" one from the memory local last_message_seen = false messages = vim .iter(messages) :filter(function(message) if not last_message_seen then if message.uuid == last_message then last_message_seen = true end return false end return true end) :totable() end if not Config.acp_providers[Config.provider] then local provider = Providers[Config.provider] local use_response_api = Providers.resolve_use_response_api(provider, nil) local tool_limit if provider.use_ReAct_prompt or use_response_api then tool_limit = nil else tool_limit = 25 end messages = History.update_tool_invocation_history(messages, tool_limit, Config.behaviour.auto_check_diagnostics) end end return messages end ---@param request string ---@param cb? fun(opts: AvanteGeneratePromptsOptions): nil function Sidebar:get_generate_prompts_options(request, cb) local filetype = api.nvim_get_option_value("filetype", { buf = self.code.bufnr }) local file_ext = nil -- Get file extension safely local buf_name = api.nvim_buf_get_name(self.code.bufnr) if buf_name and buf_name ~= "" then file_ext = vim.fn.fnamemodify(buf_name, ":e") end ---@type AvanteSelectedCode | nil local selected_code = nil if self.code.selection ~= nil then selected_code = { path = self.code.selection.filepath, file_type = self.code.selection.filetype, content = self.code.selection.content, } end local mentions = Utils.extract_mentions(request) request = mentions.new_content local project_context = mentions.enable_project_context and file_ext and RepoMap.get_repo_map(file_ext) or nil local diagnostics = nil if mentions.enable_diagnostics then if self.code ~= nil and self.code.bufnr ~= nil and self.code.selection ~= nil then diagnostics = Utils.lsp.get_current_selection_diagnostics(self.code.bufnr, self.code.selection) else diagnostics = Utils.lsp.get_diagnostics(self.code.bufnr) end end local history_messages = self:get_history_messages_for_api() local tools = vim.deepcopy(LLMTools.get_tools(request, history_messages)) table.insert(tools, { name = "add_file_to_context", description = "Add a file to the context", ---@type AvanteLLMToolFunc<{ rel_path: string }> func = function(input) self.file_selector:add_selected_file(input.rel_path) return "Added file to context", nil end, param = { type = "table", fields = { { name = "rel_path", description = "Relative path to the file", type = "string" } }, }, returns = {}, }) table.insert(tools, { name = "remove_file_from_context", description = "Remove a file from the context", ---@type AvanteLLMToolFunc<{ rel_path: string }> func = function(input) self.file_selector:remove_selected_file(input.rel_path) return "Removed file from context", nil end, param = { type = "table", fields = { { name = "rel_path", description = "Relative path to the file", type = "string" } }, }, returns = {}, }) local selected_filepaths = self.file_selector.selected_filepaths or {} local ask = Config.ask_opts.ask if ask == nil then ask = true end ---@type AvanteGeneratePromptsOptions local prompts_opts = { ask = ask, project_context = vim.json.encode(project_context), selected_filepaths = selected_filepaths, recently_viewed_files = Utils.get_recent_filepaths(), diagnostics = vim.json.encode(diagnostics), history_messages = history_messages, code_lang = filetype, selected_code = selected_code, tools = tools, } if self.chat_history.system_prompt then prompts_opts.prompt_opts = { system_prompt = self.chat_history.system_prompt, messages = history_messages, } end if self.chat_history.memory then prompts_opts.memory = self.chat_history.memory.content end if Config.behaviour.enable_token_counting then self.token_count = Llm.calculate_tokens(prompts_opts) end if cb then cb(prompts_opts) end end function Sidebar:submit_input() if not vim.g.avante_login then Utils.warn("Sending message to fast!, API key is not yet set", { title = "Avante" }) return end if not Utils.is_valid_container(self.containers.input) then return end local lines = api.nvim_buf_get_lines(self.containers.input.bufnr, 0, -1, false) local request = table.concat(lines, "\n") if request == "" then return end api.nvim_buf_set_lines(self.containers.input.bufnr, 0, -1, false, {}) api.nvim_win_set_cursor(self.containers.input.winid, { 1, 0 }) self:handle_submit(request) end ---@param request string function Sidebar:handle_submit(request) if Config.prompt_logger.enabled then PromptLogger.log_prompt(request) end if self.is_generating then self:add_history_messages({ History.Message:new("user", request) }) return end if request:match("@codebase") and not vim.fn.expand("%:e") then self:update_content("Please open a file first before using @codebase", { focus = false, scroll = false }) return end if request:sub(1, 1) == "/" then local command, args = request:match("^/(%S+)%s*(.*)") if command == nil then self:update_content("Invalid command", { focus = false, scroll = false }) return end local cmds = Utils.get_commands() ---@type AvanteSlashCommand local cmd = vim.iter(cmds):filter(function(cmd) return cmd.name == command end):totable()[1] if cmd then if cmd.callback then if command == "lines" then cmd.callback(self, args, function(args_) local _, _, question = args_:match("(%d+)-(%d+)%s+(.*)") request = question end) elseif command == "commit" then cmd.callback(self, args, function(question) request = question end) else cmd.callback(self, args) return end end else self:update_content("Unknown command: " .. command, { focus = false, scroll = false }) return end end -- Process shortcut replacements local new_content, has_shortcuts = Utils.extract_shortcuts(request) if has_shortcuts then request = new_content end local selected_filepaths = self.file_selector:get_selected_filepaths() ---@type AvanteSelectedCode | nil local selected_code = self.code.selection and { path = self.code.selection.filepath, file_type = self.code.selection.filetype, content = self.code.selection.content, } if request ~= "" then --- HACK: we need to set focus to true and scroll to false to --- prevent the cursor from jumping to the bottom of the --- buffer at the beginning self:update_content("", { focus = true, scroll = false }) end ---stop scroll when user presses j/k keys local function on_j() self.scroll = false ---perform scroll vim.cmd("normal! j") end local function on_k() self.scroll = false ---perform scroll vim.cmd("normal! k") end local function on_G() self.scroll = true ---perform scroll vim.cmd("normal! G") end vim.keymap.set("n", "j", on_j, { buffer = self.containers.result.bufnr }) vim.keymap.set("n", "k", on_k, { buffer = self.containers.result.bufnr }) vim.keymap.set("n", "G", on_G, { buffer = self.containers.result.bufnr }) ---@type AvanteLLMStartCallback local function on_start(_) end ---@param messages avante.HistoryMessage[] local function on_messages_add(messages) self:add_history_messages(messages) end ---@param state avante.GenerateState local function on_state_change(state) self:clear_state() self.current_state = state self:render_state() end ---@param tool_id string ---@param tool_name string ---@param log string ---@param state AvanteLLMToolUseState local function on_tool_log(tool_id, tool_name, log, state) if state == "generating" then on_state_change("tool calling") end local tool_use_message = History.Helpers.get_tool_use_message(tool_id, self.chat_history.messages) if not tool_use_message then -- Utils.debug("tool_use message not found", tool_id, tool_name) return end local tool_use_logs = tool_use_message.tool_use_logs or {} local content = string.format("[%s]: %s", tool_name, log) table.insert(tool_use_logs, content) tool_use_message.tool_use_logs = tool_use_logs local orig_is_calling = tool_use_message.is_calling tool_use_message.is_calling = true self:update_content("") tool_use_message.is_calling = orig_is_calling self:save_history() end local function set_tool_use_store(tool_id, key, value) local tool_use_message = History.Helpers.get_tool_use_message(tool_id, self.chat_history.messages) if tool_use_message then local tool_use_store = tool_use_message.tool_use_store or {} tool_use_store[key] = value tool_use_message.tool_use_store = tool_use_store self:save_history() end end ---@type AvanteLLMStopCallback local function on_stop(stop_opts) self.is_generating = false pcall(function() ---remove keymaps vim.keymap.del("n", "j", { buffer = self.containers.result.bufnr }) vim.keymap.del("n", "k", { buffer = self.containers.result.bufnr }) vim.keymap.del("n", "G", { buffer = self.containers.result.bufnr }) end) if stop_opts.error ~= nil and stop_opts.error ~= vim.NIL then local msg_content = stop_opts.error if type(msg_content) ~= "string" then msg_content = vim.inspect(msg_content) end self:add_history_messages({ History.Message:new("assistant", "\n\nError: " .. msg_content, { just_for_display = true, }), }) on_state_change("failed") return end if stop_opts.reason == "cancelled" then on_state_change("cancelled") else on_state_change("succeeded") end self:update_content("", { callback = function() api.nvim_exec_autocmds("User", { pattern = VIEW_BUFFER_UPDATED_PATTERN }) end, }) vim.defer_fn(function() if Utils.is_valid_container(self.containers.result, true) and Config.behaviour.jump_result_buffer_on_finish then api.nvim_set_current_win(self.containers.result.winid) end if Config.behaviour.auto_apply_diff_after_generation then self:apply(false) end end, 0) Path.history.save(self.code.bufnr, self.chat_history) end if request and request ~= "" then self:add_history_messages({ History.Message:new("user", request, { is_user_submission = true, selected_filepaths = selected_filepaths, selected_code = selected_code, }), }) end self:get_generate_prompts_options(request, function(generate_prompts_options) ---@type AvanteLLMStreamOptions ---@diagnostic disable-next-line: assign-type-mismatch local stream_options = vim.tbl_deep_extend("force", generate_prompts_options, { just_connect_acp_client = request == "", on_start = on_start, on_stop = on_stop, on_tool_log = on_tool_log, on_messages_add = on_messages_add, on_state_change = on_state_change, acp_client = self.acp_client, on_save_acp_client = function(client) self.acp_client = client end, acp_session_id = self.chat_history.acp_session_id, on_save_acp_session_id = function(session_id) self.chat_history.acp_session_id = session_id Path.history.save(self.code.bufnr, self.chat_history) end, set_tool_use_store = set_tool_use_store, get_history_messages = function(opts) return self:get_history_messages_for_api(opts) end, get_todos = function() local history = Path.history.load(self.code.bufnr) return history.todos end, update_todos = function(todos) self:update_todos(todos) end, session_ctx = {}, ---@param usage avante.LLMTokenUsage update_tokens_usage = function(usage) if not usage then return end if usage.completion_tokens == nil then return end if usage.prompt_tokens == nil then return end self.chat_history.tokens_usage = usage self:save_history() end, get_tokens_usage = function() return self.chat_history.tokens_usage end, }) ---@param pending_compaction_history_messages avante.HistoryMessage[] local function on_memory_summarize(pending_compaction_history_messages) local history_memory = self.chat_history.memory Llm.summarize_memory( history_memory and history_memory.content, pending_compaction_history_messages, function(memory) if memory then self.chat_history.memory = memory Path.history.save(self.code.bufnr, self.chat_history) stream_options.memory = memory.content end stream_options.history_messages = self:get_history_messages_for_api() Llm.stream(stream_options) end ) end stream_options.on_memory_summarize = on_memory_summarize if request ~= "" then on_state_change("generating") end Llm.stream(stream_options) end) end function Sidebar:initialize_token_count() if Config.behaviour.enable_token_counting then self:get_generate_prompts_options("") end end function Sidebar:create_input_container() if self.containers.input then self.containers.input:unmount() end if not self.code.bufnr or not api.nvim_buf_is_valid(self.code.bufnr) then return end if self.chat_history == nil then self:reload_chat_history() end local function get_position() if self:get_layout() == "vertical" then return "bottom" end return "right" end local function get_size() if self:get_layout() == "vertical" then return { height = Config.windows.input.height, } end local selected_code_container_height = self:get_selected_code_container_height() return { width = "40%", height = math.max(1, api.nvim_win_get_height(self.containers.result.winid) - selected_code_container_height), } end self.containers.input = Split({ enter = false, relative = { type = "win", winid = self.containers.result.winid, }, buf_options = { swapfile = false, buftype = "nofile", }, win_options = vim.tbl_deep_extend("force", base_win_options, { signcolumn = "yes", wrap = Config.windows.wrap }), position = get_position(), size = get_size(), }) local function on_submit() self:submit_input() end self.containers.input:mount() PromptLogger.init() local function place_sign_at_first_line(bufnr) local group = "avante_input_prompt_group" fn.sign_unplace(group, { buffer = bufnr }) fn.sign_place(0, group, "AvanteInputPromptSign", bufnr, { lnum = 1 }) end place_sign_at_first_line(self.containers.input.bufnr) if Utils.in_visual_mode() then -- Exit visual mode. Unfortunately there is no appropriate command -- so we have to simulate keystrokes. local esc_key = api.nvim_replace_termcodes("<Esc>", true, false, true) vim.api.nvim_feedkeys(esc_key, "n", false) end self:setup_window_navigation(self.containers.input) self.containers.input:map("n", Config.mappings.submit.normal, on_submit) self.containers.input:map("i", Config.mappings.submit.insert, on_submit) if Config.prompt_logger.next_prompt.normal then self.containers.input:map("n", Config.prompt_logger.next_prompt.normal, PromptLogger.on_log_retrieve(-1)) end if Config.prompt_logger.next_prompt.insert then self.containers.input:map("i", Config.prompt_logger.next_prompt.insert, PromptLogger.on_log_retrieve(-1)) end if Config.prompt_logger.prev_prompt.normal then self.containers.input:map("n", Config.prompt_logger.prev_prompt.normal, PromptLogger.on_log_retrieve(1)) end if Config.prompt_logger.prev_prompt.insert then self.containers.input:map("i", Config.prompt_logger.prev_prompt.insert, PromptLogger.on_log_retrieve(1)) end if Config.mappings.sidebar.close_from_input ~= nil then if Config.mappings.sidebar.close_from_input.normal ~= nil then self.containers.input:map("n", Config.mappings.sidebar.close_from_input.normal, function() self:shutdown() end) end if Config.mappings.sidebar.close_from_input.insert ~= nil then self.containers.input:map("i", Config.mappings.sidebar.close_from_input.insert, function() self:shutdown() end) end end if Config.mappings.sidebar.toggle_code_window_from_input ~= nil then if Config.mappings.sidebar.toggle_code_window_from_input.normal ~= nil then self.containers.input:map( "n", Config.mappings.sidebar.toggle_code_window_from_input.normal, function() self:toggle_code_window() end ) end if Config.mappings.sidebar.toggle_code_window_from_input.insert ~= nil then self.containers.input:map( "i", Config.mappings.sidebar.toggle_code_window_from_input.insert, function() self:toggle_code_window() end ) end end api.nvim_set_option_value("filetype", "AvanteInput", { buf = self.containers.input.bufnr }) -- Setup completion api.nvim_create_autocmd("InsertEnter", { group = self.augroup, buffer = self.containers.input.bufnr, once = true, desc = "Setup the completion of helpers in the input buffer", callback = function() end, }) local debounced_show_input_hint = Utils.debounce(function() if vim.api.nvim_win_is_valid(self.containers.input.winid) then self:show_input_hint() end end, 200) api.nvim_create_autocmd({ "TextChanged", "TextChangedI", "VimResized" }, { group = self.augroup, buffer = self.containers.input.bufnr, callback = function() debounced_show_input_hint() place_sign_at_first_line(self.containers.input.bufnr) end, }) api.nvim_create_autocmd("QuitPre", { group = self.augroup, buffer = self.containers.input.bufnr, callback = function() self:close_input_hint() end, }) api.nvim_create_autocmd("WinClosed", { group = self.augroup, pattern = tostring(self.containers.input.winid), callback = function() self:close_input_hint() end, }) api.nvim_create_autocmd("BufEnter", { group = self.augroup, buffer = self.containers.input.bufnr, callback = function() if Config.windows.ask.start_insert then vim.cmd("noautocmd startinsert!") end end, }) api.nvim_create_autocmd("BufLeave", { group = self.augroup, buffer = self.containers.input.bufnr, callback = function() vim.cmd("noautocmd stopinsert") self:close_input_hint() end, }) -- Update hint on mode change as submit key sequence may be different api.nvim_create_autocmd("ModeChanged", { group = self.augroup, buffer = self.containers.input.bufnr, callback = function() self:show_input_hint() end, }) api.nvim_create_autocmd("WinEnter", { group = self.augroup, callback = function() local cur_win = api.nvim_get_current_win() if self.containers.input and cur_win == self.containers.input.winid then self:show_input_hint() else self:close_input_hint() end end, }) end -- FIXME: this is used by external plugin users ---@param value string function Sidebar:set_input_value(value) if not self.containers.input then return end if not value then return end api.nvim_buf_set_lines(self.containers.input.bufnr, 0, -1, false, vim.split(value, "\n")) end ---@return string function Sidebar:get_input_value() if not self.containers.input then return "" end local lines = api.nvim_buf_get_lines(self.containers.input.bufnr, 0, -1, false) return table.concat(lines, "\n") end function Sidebar:get_selected_code_container_height() if not self.code.selection then return 0 end local max_height = 5 local count = Utils.count_lines(self.code.selection.content) if Config.windows.sidebar_header.enabled then count = count + 1 end return math.min(count, max_height) end function Sidebar:get_todos_container_height() local history = Path.history.load(self.code.bufnr) if #history.todos == 0 then return 0 end return 3 end function Sidebar:get_result_container_height() local todos_container_height = self:get_todos_container_height() local selected_code_container_height = self:get_selected_code_container_height() local selected_files_container_height = self:get_selected_files_container_height() if self:get_layout() == "horizontal" then return math.floor(Config.windows.height / 100 * vim.o.lines) end return math.max( 1, api.nvim_get_option_value("lines", {}) - selected_files_container_height - selected_code_container_height - todos_container_height - Config.windows.input.height ) end function Sidebar:get_result_container_width() if self:get_layout() == "vertical" then return math.floor(Config.windows.width / 100 * vim.o.columns) end return math.max(1, api.nvim_win_get_width(self.code.winid)) end function Sidebar:adjust_result_container_layout() local width = self:get_result_container_width() local height = self:get_result_container_height() if self.is_in_full_view then width = vim.o.columns - 1 end api.nvim_win_set_width(self.containers.result.winid, width) api.nvim_win_set_height(self.containers.result.winid, height) end ---@param opts AskOptions function Sidebar:render(opts) self.augroup = api.nvim_create_augroup("avante_sidebar_" .. self.id, { clear = true }) -- This autocommand needs to be registered first, before NuiSplit -- registers their own handlers for WinClosed events that will set -- container.winid to nil, which will cause Sidebar:get_sidebar_window() -- to fail. api.nvim_create_autocmd("WinClosed", { group = self.augroup, callback = function(args) local closed_winid = tonumber(args.match) if closed_winid then local container = self:get_sidebar_window(closed_winid) -- Ignore closing selected files and todos windows because they can disappear during normal operation if container and container ~= self.containers.selected_files and container ~= self.containers.todos then self:close() end end end, }) if opts.sidebar_pre_render then opts.sidebar_pre_render(self) end local function get_position() return (opts and opts.win and opts.win.position) and opts.win.position or calculate_config_window_position() end self.containers.result = Split({ enter = false, relative = "editor", position = get_position(), buf_options = vim.tbl_deep_extend("force", buf_options, { modifiable = false, swapfile = false, buftype = "nofile", bufhidden = "wipe", filetype = "Avante", }), win_options = vim.tbl_deep_extend("force", base_win_options, { wrap = Config.windows.wrap, fillchars = Config.windows.fillchars, }), size = { width = self:get_result_container_width(), height = self:get_result_container_height(), }, }) self.containers.result:mount() self.containers.result:on(event.BufWinEnter, function() xpcall(function() api.nvim_buf_set_name(self.containers.result.bufnr, RESULT_BUF_NAME) end, function(_) end) end) self.containers.result:map("n", Config.mappings.sidebar.close, function() self:shutdown() end) self.containers.result:map("n", Config.mappings.sidebar.toggle_code_window, function() self:toggle_code_window() end) self:create_input_container() self:create_selected_files_container() if self.code.bufnr and api.nvim_buf_is_valid(self.code.bufnr) then -- reset states when buffer is closed api.nvim_buf_attach(self.code.bufnr, false, { on_detach = function(_, _) vim.schedule(function() if not self.code.winid or not api.nvim_win_is_valid(self.code.winid) then return end local bufnr = api.nvim_win_get_buf(self.code.winid) self.code.bufnr = bufnr self:reload_chat_history() end) end, }) end self:create_selected_code_container() self:create_todos_container() self:on_mount(opts) self:setup_colors() if opts.sidebar_post_render then self.post_render = opts.sidebar_post_render vim.defer_fn(function() opts.sidebar_post_render(self) self:update_content_with_history() end, 100) else self:update_content_with_history() end api.nvim_create_autocmd("User", { group = self.augroup, pattern = "AvanteInputSubmitted", callback = function(ev) if ev.data and ev.data.request then self:handle_submit(ev.data.request) end end, }) return self end function Sidebar:get_selected_files_container_height() local selected_filepaths_ = self.file_selector:get_selected_filepaths() return math.min(Config.windows.selected_files.height, #selected_filepaths_ + 1) end function Sidebar:adjust_selected_files_container_layout() if not Utils.is_valid_container(self.containers.selected_files, true) then return end local win_height = self:get_selected_files_container_height() api.nvim_win_set_height(self.containers.selected_files.winid, win_height) end function Sidebar:adjust_selected_code_container_layout() if not Utils.is_valid_container(self.containers.selected_code, true) then return end local win_height = self:get_selected_code_container_height() api.nvim_win_set_height(self.containers.selected_code.winid, win_height) end function Sidebar:adjust_todos_container_layout() if not Utils.is_valid_container(self.containers.todos, true) then return end local win_height = self:get_todos_container_height() api.nvim_win_set_height(self.containers.todos.winid, win_height) end function Sidebar:create_selected_files_container() if self.containers.selected_files then self.containers.selected_files:unmount() end local selected_filepaths = self.file_selector:get_selected_filepaths() if #selected_filepaths == 0 then self.file_selector:off("update") self.file_selector:on("update", function() self:create_selected_files_container() end) return end self.containers.selected_files = Split({ enter = false, relative = { type = "win", winid = self:get_split_candidate("selected_files"), }, buf_options = vim.tbl_deep_extend("force", buf_options, { modifiable = false, swapfile = false, buftype = "nofile", bufhidden = "wipe", filetype = "AvanteSelectedFiles", }), win_options = vim.tbl_deep_extend("force", base_win_options, { fillchars = Config.windows.fillchars, }), position = "bottom", size = { height = 2, }, }) self.containers.selected_files:mount() local function render() local selected_filepaths_ = self.file_selector:get_selected_filepaths() if #selected_filepaths_ == 0 then if Utils.is_valid_container(self.containers.selected_files) then self.containers.selected_files:unmount() end return end if not Utils.is_valid_container(self.containers.selected_files, true) then self:create_selected_files_container() if not Utils.is_valid_container(self.containers.selected_files, true) then Utils.warn("Failed to create or find selected files container window.") return end end local lines_to_set = {} local highlights_to_apply = {} local project_path = Utils.root.get() for i, filepath in ipairs(selected_filepaths_) do local icon, hl = Utils.file.get_file_icon(filepath) local renderpath = PPath:new(filepath):normalize(project_path) local formatted_line = string.format("%s %s", icon, renderpath) table.insert(lines_to_set, formatted_line) if hl and hl ~= "" then table.insert(highlights_to_apply, { line_nr = i, icon = icon, hl = hl }) end end local selected_files_count = #lines_to_set ---@type integer local selected_files_buf = api.nvim_win_get_buf(self.containers.selected_files.winid) Utils.unlock_buf(selected_files_buf) api.nvim_buf_clear_namespace(selected_files_buf, SELECTED_FILES_ICON_NAMESPACE, 0, -1) api.nvim_buf_set_lines(selected_files_buf, 0, -1, true, lines_to_set) for _, highlight_info in ipairs(highlights_to_apply) do local line_idx = highlight_info.line_nr - 1 local icon_bytes = #highlight_info.icon pcall(api.nvim_buf_set_extmark, selected_files_buf, SELECTED_FILES_ICON_NAMESPACE, line_idx, 0, { end_col = icon_bytes, hl_group = highlight_info.hl, priority = PRIORITY, }) end Utils.lock_buf(selected_files_buf) local win_height = self:get_selected_files_container_height() api.nvim_win_set_height(self.containers.selected_files.winid, win_height) self:render_header( self.containers.selected_files.winid, selected_files_buf, string.format( "%sSelected (%d file%s)", Utils.icon(" "), selected_files_count, selected_files_count > 1 and "s" or "" ), Highlights.SUBTITLE, Highlights.REVERSED_SUBTITLE ) self:adjust_layout() end self.file_selector:on("update", render) local function remove_file(line_number) self.file_selector:remove_selected_filepaths_with_index(line_number) end -- Set up keybinding to remove files self.containers.selected_files:map("n", Config.mappings.sidebar.remove_file, function() local line_number = api.nvim_win_get_cursor(self.containers.selected_files.winid)[1] remove_file(line_number) end, { noremap = true, silent = true }) self.containers.selected_files:map("x", Config.mappings.sidebar.remove_file, function() vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Esc>", true, false, true), "n", false) local start_line = math.min(vim.fn.line("v"), vim.fn.line(".")) local end_line = math.max(vim.fn.line("v"), vim.fn.line(".")) for _ = start_line, end_line do remove_file(start_line) end end, { noremap = true, silent = true }) self.containers.selected_files:map( "n", Config.mappings.sidebar.add_file, function() self.file_selector:open() end, { noremap = true, silent = true } ) -- Set up autocmd to show hint on cursor move self.containers.selected_files:on({ event.CursorMoved }, function() self:show_selected_files_hint() end, {}) -- Clear hint when leaving the window self.containers.selected_files:on(event.BufLeave, function() self:close_selected_files_hint() end, {}) self:setup_window_navigation(self.containers.selected_files) render() end function Sidebar:create_todos_container() local history = Path.history.load(self.code.bufnr) if #history.todos == 0 then if self.containers.todos and Utils.is_valid_container(self.containers.todos) then self.containers.todos:unmount() end self.containers.todos = nil self:adjust_layout() return end -- Calculate safe height to prevent "Not enough room" error local safe_height = math.min(3, math.max(1, vim.o.lines - 5)) if not Utils.is_valid_container(self.containers.todos, true) then self.containers.todos = Split({ enter = false, relative = { type = "win", winid = self:get_split_candidate("todos"), }, buf_options = vim.tbl_deep_extend("force", buf_options, { modifiable = false, swapfile = false, buftype = "nofile", bufhidden = "wipe", filetype = "AvanteTodos", }), win_options = vim.tbl_deep_extend("force", base_win_options, { fillchars = Config.windows.fillchars, }), position = "bottom", size = { height = safe_height, }, }) local ok, err = pcall(function() self.containers.todos:mount() self:setup_window_navigation(self.containers.todos) end) if not ok then Utils.debug("Failed to create todos container:", err) self.containers.todos = nil return end end local done_count = 0 local total_count = #history.todos local focused_idx = 1 local todos_content_lines = {} for idx, todo in ipairs(history.todos) do local status_content = "[ ]" if todo.status == "done" then done_count = done_count + 1 status_content = "[x]" end if todo.status == "doing" then status_content = "[-]" end local line = string.format("%s %d. %s", status_content, idx, todo.content) if todo.status == "cancelled" then line = "~~" .. line .. "~~" end if todo.status ~= "todo" then focused_idx = idx + 1 end table.insert(todos_content_lines, line) end if focused_idx > #todos_content_lines then focused_idx = #todos_content_lines end local todos_buf = api.nvim_win_get_buf(self.containers.todos.winid) Utils.unlock_buf(todos_buf) api.nvim_buf_set_lines(todos_buf, 0, -1, false, todos_content_lines) pcall(function() api.nvim_win_set_cursor(self.containers.todos.winid, { focused_idx, 0 }) end) Utils.lock_buf(todos_buf) self:render_header( self.containers.todos.winid, todos_buf, Utils.icon(" ") .. "Todos" .. " (" .. done_count .. "/" .. total_count .. ")", Highlights.SUBTITLE, Highlights.REVERSED_SUBTITLE ) local ok, err = pcall(function() self:adjust_layout() end) if not ok then Utils.debug("Failed to adjust layout after todos creation:", err) end end function Sidebar:adjust_layout() self:adjust_result_container_layout() self:adjust_todos_container_layout() self:adjust_selected_code_container_layout() self:adjust_selected_files_container_layout() end return Sidebar
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/suggestion.lua
Lua
local Utils = require("avante.utils") local Llm = require("avante.llm") local Highlights = require("avante.highlights") local Config = require("avante.config") local Providers = require("avante.providers") local HistoryMessage = require("avante.history.message") local api = vim.api local fn = vim.fn local SUGGESTION_NS = api.nvim_create_namespace("avante_suggestion") ---Represents contents of a single code block that can be placed between start and end rows ---@class avante.SuggestionItem ---@field id integer ---@field content string ---@field start_row integer ---@field end_row integer ---@field original_start_row integer ---A list of code blocks that form a complete set of edits to implement a recommended change ---@alias avante.SuggestionSet avante.SuggestionItem[] ---@class avante.SuggestionContext ---@field suggestions_list avante.SuggestionSet[] ---@field current_suggestion_idx number ---@field prev_doc? table ---@class avante.Suggestion ---@field id number ---@field augroup integer ---@field ignore_patterns table ---@field negate_patterns table ---@field _timer? uv.uv_timer_t ---@field _contexts table ---@field is_on_throttle boolean local Suggestion = {} Suggestion.__index = Suggestion ---@param id number ---@return avante.Suggestion function Suggestion:new(id) local instance = setmetatable({}, self) local gitignore_path = Utils.get_project_root() .. "/.gitignore" local gitignore_patterns, gitignore_negate_patterns = Utils.parse_gitignore(gitignore_path) instance.id = id instance._timer = nil instance._contexts = {} instance.ignore_patterns = gitignore_patterns instance.negate_patterns = gitignore_negate_patterns instance.is_on_throttle = false if Config.behaviour.auto_suggestions then if not vim.g.avante_login or vim.g.avante_login == false then api.nvim_exec_autocmds("User", { pattern = Providers.env.REQUEST_LOGIN_PATTERN }) vim.g.avante_login = true end instance:setup_autocmds() end return instance end function Suggestion:destroy() self:stop_timer() self:reset() self:delete_autocmds() end ---Validates a potential suggestion item, ensuring that it has all needed data ---@param item table The suggestion item to validate. ---@return boolean `true` if valid, otherwise `false`. local function validate_suggestion_item(item) return not not ( item.content and type(item.content) == "string" and item.start_row and type(item.start_row) == "number" and item.end_row and type(item.end_row) == "number" and item.start_row <= item.end_row ) end ---Validates incoming raw suggestion data and builds a suggestion set, minimizing content ---@param raw_suggestions table[] ---@param current_content string[] ---@return avante.SuggestionSet local function build_suggestion_set(raw_suggestions, current_content) ---@type avante.SuggestionSet local items = vim .iter(raw_suggestions) :map(function(s) --- 's' is a table generated from parsing json, it may not have --- all the expected keys or they may have bad values. if not validate_suggestion_item(s) then Utils.error("Provider returned malformed or invalid suggestion data", { once = true }) return end local lines = vim.split(s.content, "\n") local new_start_row = s.start_row for i = s.start_row, s.start_row + #lines - 1 do if current_content[i] ~= lines[i - s.start_row + 1] then break end new_start_row = i + 1 end local new_content_lines = new_start_row ~= s.start_row and vim.list_slice(lines, new_start_row - s.start_row + 1) or lines if #new_content_lines == 0 then return nil end new_content_lines = Utils.trim_line_numbers(new_content_lines) return { id = s.start_row, original_start_row = s.start_row, start_row = new_start_row, end_row = s.end_row, content = table.concat(new_content_lines, "\n"), } end) :filter(function(s) return s ~= nil end) :totable() --- sort the suggestions by start_row table.sort(items, function(a, b) return a.start_row < b.start_row end) return items end ---Parses provider response and builds a list of suggestions ---@param full_response string ---@param bufnr integer ---@return avante.SuggestionSet[] | nil local function build_suggestion_list(full_response, bufnr) -- Clean up markdown code blocks full_response = Utils.trim_think_content(full_response) full_response = full_response:gsub("<suggestions>\n(.-)\n</suggestions>", "%1") full_response = full_response:gsub("^```%w*\n(.-)\n```$", "%1") full_response = full_response:gsub("(.-)\n```\n?$", "%1") -- Remove everything before the first '[' to ensure we get just the JSON array full_response = full_response:gsub("^.-(%[.*)", "%1") -- Remove everything after the last ']' to ensure we get just the JSON array full_response = full_response:gsub("(.*%]).-$", "%1") local ok, suggestions_list = pcall(vim.json.decode, full_response) if not ok then Utils.error("Error while decoding suggestions: " .. full_response, { once = true, title = "Avante" }) return end if not suggestions_list then Utils.info("No suggestions found", { once = true, title = "Avante" }) return end if #suggestions_list ~= 0 and not vim.islist(suggestions_list[1]) then suggestions_list = { suggestions_list } end local current_lines = Utils.get_buf_lines(0, -1, bufnr) return vim .iter(suggestions_list) :map(function(suggestions) return build_suggestion_set(suggestions, current_lines) end) :totable() end function Suggestion:suggest() Utils.debug("suggesting") local ctx = self:ctx() local doc = Utils.get_doc() ctx.prev_doc = doc local bufnr = api.nvim_get_current_buf() local filetype = api.nvim_get_option_value("filetype", { buf = bufnr }) local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) table.insert(lines, "") table.insert(lines, "") local code_content = table.concat(Utils.prepend_line_numbers(lines), "\n") local full_response = "" local provider = Providers[Config.auto_suggestions_provider or Config.provider] ---@type AvanteLLMMessage[] local llm_messages = { { role = "user", content = [[ <filepath>a.py</filepath> <code> L1: def fib L2: L3: if __name__ == "__main__": L4: # just pass L5: pass </code> ]], }, { role = "assistant", content = "ok", }, { role = "user", content = '{"insertSpaces":true,"tabSize":4,"indentSize":4,"position":{"row":1,"col":7}}', }, { role = "assistant", content = [[ <suggestions> [ [ { "start_row": 1, "end_row": 1, "content": "def fib(n):\n if n < 2:\n return n\n return fib(n - 1) + fib(n - 2)" }, { "start_row": 4, "end_row": 5, "content": " fib(int(input()))" }, ], [ { "start_row": 1, "end_row": 1, "content": "def fib(n):\n a, b = 0, 1\n for _ in range(n):\n yield a\n a, b = b, a + b" }, { "start_row": 4, "end_row": 5, "content": " list(fib(int(input())))" }, ] ] </suggestions> ]], }, } local history_messages = vim .iter(llm_messages) :map(function(msg) return HistoryMessage:new(msg.role, msg.content) end) :totable() local diagnostics = Utils.lsp.get_diagnostics(bufnr) Llm.stream({ provider = provider, ask = true, diagnostics = vim.json.encode(diagnostics), selected_files = { { content = code_content, file_type = filetype, path = "" } }, code_lang = filetype, history_messages = history_messages, instructions = vim.json.encode(doc), mode = "suggesting", on_start = function(_) end, on_chunk = function(chunk) full_response = full_response .. chunk end, on_stop = function(stop_opts) local err = stop_opts.error if err then Utils.error("Error while suggesting: " .. vim.inspect(err), { once = true, title = "Avante" }) return end Utils.debug("full_response:", full_response) vim.schedule(function() local cursor_row, cursor_col = Utils.get_cursor_pos() if cursor_row ~= doc.position.row or cursor_col ~= doc.position.col then return end ctx.suggestions_list = build_suggestion_list(full_response, bufnr) ctx.current_suggestions_idx = 1 self:show() end) end, }) end function Suggestion:show() Utils.debug("showing suggestions, mode:", fn.mode()) self:hide() if not fn.mode():match("^[iR]") then return end local ctx = self:ctx() local bufnr = api.nvim_get_current_buf() local suggestions = ctx.suggestions_list and ctx.suggestions_list[ctx.current_suggestions_idx] or nil Utils.debug("show suggestions", suggestions) if not suggestions then return end for _, suggestion in ipairs(suggestions) do local start_row = suggestion.start_row local end_row = suggestion.end_row local content = suggestion.content local lines = vim.split(content, "\n") local current_lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) local virt_text_win_col = 0 local cursor_row, _ = Utils.get_cursor_pos() if start_row == end_row and start_row == cursor_row and current_lines[start_row] and #lines > 0 then if vim.startswith(lines[1], current_lines[start_row]) then virt_text_win_col = #current_lines[start_row] lines[1] = string.sub(lines[1], #current_lines[start_row] + 1) else local patch = vim.diff( current_lines[start_row], lines[1], ---@diagnostic disable-next-line: missing-fields { algorithm = "histogram", result_type = "indices", ctxlen = vim.o.scrolloff } ) Utils.debug("patch", patch) if patch and #patch > 0 then virt_text_win_col = patch[1][3] lines[1] = string.sub(lines[1], patch[1][3] + 1) end end end local virt_lines = {} for _, line in ipairs(lines) do table.insert(virt_lines, { { line, Highlights.SUGGESTION } }) end local extmark = { id = suggestion.id, virt_text_win_col = virt_text_win_col, virt_lines = virt_lines, } if virt_text_win_col > 0 then extmark.virt_text = { { lines[1], Highlights.SUGGESTION } } extmark.virt_lines = vim.list_slice(virt_lines, 2) end extmark.hl_mode = "combine" local buf_lines = Utils.get_buf_lines(0, -1, bufnr) local buf_lines_count = #buf_lines while buf_lines_count < end_row do api.nvim_buf_set_lines(bufnr, buf_lines_count, -1, false, { "" }) buf_lines_count = buf_lines_count + 1 end if virt_text_win_col > 0 or start_row - 2 < 0 then api.nvim_buf_set_extmark(bufnr, SUGGESTION_NS, start_row - 1, 0, extmark) else api.nvim_buf_set_extmark(bufnr, SUGGESTION_NS, start_row - 2, 0, extmark) end for i = start_row, end_row do if i == start_row and start_row == cursor_row and virt_text_win_col > 0 then goto continue end Utils.debug("add highlight", i - 1) local old_line = current_lines[i] api.nvim_buf_set_extmark( bufnr, SUGGESTION_NS, i - 1, 0, { hl_group = Highlights.TO_BE_DELETED, end_row = i - 1, end_col = #old_line } ) ::continue:: end end end function Suggestion:is_visible() local extmarks = api.nvim_buf_get_extmarks(0, SUGGESTION_NS, 0, -1, { details = false }) return #extmarks > 0 end function Suggestion:hide() api.nvim_buf_clear_namespace(0, SUGGESTION_NS, 0, -1) end function Suggestion:ctx() local bufnr = api.nvim_get_current_buf() local ctx = self._contexts[bufnr] if not ctx then ctx = { suggestions_list = {}, current_suggestions_idx = 0, prev_doc = {}, internal_move = false, } self._contexts[bufnr] = ctx end return ctx end function Suggestion:reset() self._timer = nil local bufnr = api.nvim_get_current_buf() self._contexts[bufnr] = nil end function Suggestion:stop_timer() if self._timer then pcall(function() self._timer:stop() self._timer:close() end) self._timer = nil end end function Suggestion:next() local ctx = self:ctx() if #ctx.suggestions_list == 0 then return end ctx.current_suggestions_idx = (ctx.current_suggestions_idx % #ctx.suggestions_list) + 1 self:show() end function Suggestion:prev() local ctx = self:ctx() if #ctx.suggestions_list == 0 then return end ctx.current_suggestions_idx = ((ctx.current_suggestions_idx - 2 + #ctx.suggestions_list) % #ctx.suggestions_list) + 1 self:show() end function Suggestion:dismiss() self:stop_timer() self:hide() self:reset() end function Suggestion:get_current_suggestion() local ctx = self:ctx() local suggestions = ctx.suggestions_list and ctx.suggestions_list[ctx.current_suggestions_idx] or nil if not suggestions then return nil end local cursor_row, _ = Utils.get_cursor_pos(0) Utils.debug("cursor row", cursor_row) for _, suggestion in ipairs(suggestions) do if suggestion.original_start_row - 1 <= cursor_row and suggestion.end_row >= cursor_row then return suggestion end end end function Suggestion:get_next_suggestion() local ctx = self:ctx() local suggestions = ctx.suggestions_list and ctx.suggestions_list[ctx.current_suggestions_idx] or nil if not suggestions then return nil end local cursor_row, _ = Utils.get_cursor_pos() local new_suggestions = {} for _, suggestion in ipairs(suggestions) do table.insert(new_suggestions, suggestion) end --- sort the suggestions by cursor distance table.sort( new_suggestions, function(a, b) return math.abs(a.start_row - cursor_row) < math.abs(b.start_row - cursor_row) end ) --- get the closest suggestion to the cursor return new_suggestions[1] end function Suggestion:accept() local ctx = self:ctx() local suggestions = ctx.suggestions_list and ctx.suggestions_list[ctx.current_suggestions_idx] or nil Utils.debug("suggestions", suggestions) if not suggestions then if Config.mappings.suggestion and Config.mappings.suggestion.accept == "<Tab>" then api.nvim_feedkeys(api.nvim_replace_termcodes("<Tab>", true, false, true), "n", true) end return end local suggestion = self:get_current_suggestion() Utils.debug("current suggestion", suggestion) if not suggestion then suggestion = self:get_next_suggestion() if suggestion then Utils.debug("next suggestion", suggestion) local lines = api.nvim_buf_get_lines(0, 0, -1, false) local first_line_row = suggestion.start_row if first_line_row > 1 then first_line_row = first_line_row - 1 end local line = lines[first_line_row] local col = 0 if line ~= nil then col = #line end self:set_internal_move(true) api.nvim_win_set_cursor(0, { first_line_row, col }) vim.cmd("normal! zz") vim.cmd("noautocmd startinsert") self:set_internal_move(false) return end end if not suggestion then return end api.nvim_buf_del_extmark(0, SUGGESTION_NS, suggestion.id) local bufnr = api.nvim_get_current_buf() local start_row = suggestion.start_row local end_row = suggestion.end_row local content = suggestion.content local lines = vim.split(content, "\n") local cursor_row, _ = Utils.get_cursor_pos() local replaced_line_count = end_row - start_row + 1 if replaced_line_count > #lines then Utils.debug("delete lines") api.nvim_buf_set_lines(bufnr, start_row + #lines - 1, end_row, false, {}) api.nvim_buf_set_lines(bufnr, start_row - 1, start_row + #lines, false, lines) else local start_line = start_row - 1 local end_line = end_row if end_line < start_line then end_line = start_line end Utils.debug("replace lines", start_line, end_line, lines) api.nvim_buf_set_lines(bufnr, start_line, end_line, false, lines) end local row_diff = #lines - replaced_line_count ctx.suggestions_list[ctx.current_suggestions_idx] = vim .iter(suggestions) :filter(function(s) return s.start_row ~= suggestion.start_row end) :map(function(s) if s.start_row > suggestion.start_row then s.original_start_row = s.original_start_row + row_diff s.start_row = s.start_row + row_diff s.end_row = s.end_row + row_diff end return s end) :totable() local line_count = #lines local down_count = line_count - 1 if start_row > cursor_row then down_count = down_count + 1 end local cursor_keys = string.rep("<Down>", down_count) .. "<End>" suggestions = ctx.suggestions_list and ctx.suggestions_list[ctx.current_suggestions_idx] or {} if #suggestions > 0 then self:set_internal_move(true) end api.nvim_feedkeys(api.nvim_replace_termcodes(cursor_keys, true, false, true), "n", false) if #suggestions > 0 then self:set_internal_move(false) end end function Suggestion:is_internal_move() local ctx = self:ctx() Utils.debug("is internal move", ctx and ctx.internal_move) return ctx and ctx.internal_move end function Suggestion:set_internal_move(internal_move) local ctx = self:ctx() if not internal_move then vim.schedule(function() Utils.debug("set internal move", internal_move) ctx.internal_move = internal_move end) else Utils.debug("set internal move", internal_move) ctx.internal_move = internal_move end end function Suggestion:setup_autocmds() self.augroup = api.nvim_create_augroup("avante_suggestion_" .. self.id, { clear = true }) local last_cursor_pos = {} local check_for_suggestion = Utils.debounce(function() if self.is_on_throttle then return end local current_cursor_pos = api.nvim_win_get_cursor(0) if last_cursor_pos[1] == current_cursor_pos[1] and last_cursor_pos[2] == current_cursor_pos[2] then self.is_on_throttle = true vim.defer_fn(function() self.is_on_throttle = false end, Config.suggestion.throttle) self:suggest() end end, Config.suggestion.debounce) local function suggest_callback() if self.is_on_throttle then return end if self:is_internal_move() then return end if not vim.bo.buflisted then return end if vim.bo.buftype ~= "" then return end local full_path = api.nvim_buf_get_name(0) if Config.behaviour.auto_suggestions_respect_ignore and Utils.is_ignored(full_path, self.ignore_patterns, self.negate_patterns) then return end local ctx = self:ctx() if ctx.prev_doc and vim.deep_equal(ctx.prev_doc, Utils.get_doc()) then return end self:hide() last_cursor_pos = api.nvim_win_get_cursor(0) self._timer = check_for_suggestion() end api.nvim_create_autocmd("InsertEnter", { group = self.augroup, callback = suggest_callback, }) api.nvim_create_autocmd("BufEnter", { group = self.augroup, callback = function() if fn.mode():match("^[iR]") then suggest_callback() end end, }) api.nvim_create_autocmd("CursorMovedI", { group = self.augroup, callback = suggest_callback, }) api.nvim_create_autocmd("InsertLeave", { group = self.augroup, callback = function() last_cursor_pos = {} self:hide() self:reset() end, }) end function Suggestion:delete_autocmds() if self.augroup then api.nvim_del_augroup_by_id(self.augroup) end self.augroup = nil end return Suggestion
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/tokenizers.lua
Lua
local Utils = require("avante.utils") ---@class AvanteTokenizer ---@field from_pretrained fun(model: string): nil ---@field encode fun(string): integer[] local tokenizers = nil ---@type "gpt-4o" | string local current_model = "gpt-4o" local M = {} ---@param model "gpt-4o" | string ---@return AvanteTokenizer|nil function M._init_tokenizers_lib(model) if tokenizers ~= nil then return tokenizers end local ok, core = pcall(require, "avante_tokenizers") if not ok then return nil end ---@cast core AvanteTokenizer tokenizers = core core.from_pretrained(model) return tokenizers end ---@param model "gpt-4o" | string ---@param warning? boolean function M.setup(model, warning) current_model = model warning = warning or true vim.defer_fn(function() M._init_tokenizers_lib(model) end, 1000) if warning then local HF_TOKEN = os.getenv("HF_TOKEN") if HF_TOKEN == nil and model ~= "gpt-4o" then Utils.warn( "Please set HF_TOKEN environment variable to use HuggingFace tokenizer if " .. model .. " is gated", { once = true } ) end end end function M.available() return M._init_tokenizers_lib(current_model) ~= nil end ---@param prompt string function M.encode(prompt) if not M.available() then return nil end if not prompt or prompt == "" then return nil end if type(prompt) ~= "string" then error("Prompt is not type string", 2) end local success, result = pcall(tokenizers.encode, prompt) -- Some output like terminal command output might not be utf-8 encoded, which will cause an error here if not success then Utils.warn("Failed to encode prompt: " .. result) return nil end return result end ---@param prompt string function M.count(prompt) if not M.available() then return math.ceil(#prompt * 0.5) end local tokens = M.encode(prompt) if not tokens then return 0 end return #tokens end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/types.lua
Lua
---@meta ---@class vim.api.create_autocmd.callback.args ---@field id number ---@field event string ---@field group number? ---@field match string ---@field buf number ---@field file string ---@field data any ---@class vim.api.keyset.create_autocmd.opts: vim.api.keyset.create_autocmd ---@field callback? fun(ev:vim.api.create_autocmd.callback.args):boolean? ---@param event string | string[] (string|array) Event(s) that will trigger the handler ---@param opts vim.api.keyset.create_autocmd.opts ---@return integer function vim.api.nvim_create_autocmd(event, opts) end ---@class vim.api.keyset.user_command.callback_opts ---@field name string ---@field args string ---@field fargs string[] ---@field nargs? integer | string ---@field bang? boolean ---@field line1? integer ---@field line2? integer ---@field range? integer ---@field count? integer ---@field reg? string ---@field mods? string ---@field smods? UserCommandSmods ---@class UserCommandSmods ---@field browse boolean ---@field confirm boolean ---@field emsg_silent boolean ---@field hide boolean ---@field horizontal boolean ---@field keepalt boolean ---@field keepjumps boolean ---@field keepmarks boolean ---@field keeppatterns boolean ---@field lockmarks boolean ---@field noautocmd boolean ---@field noswapfile boolean ---@field sandbox boolean ---@field silent boolean ---@field split string ---@field tab integer ---@field unsilent boolean ---@field verbose integer ---@field vertical boolean ---@class vim.api.keyset.user_command.opts: vim.api.keyset.user_command ---@field nargs? integer | string ---@field range? integer ---@field bang? boolean ---@field desc? string ---@field force? boolean ---@field complete? fun(prefix: string, line: string, pos?: integer): string[] ---@field preview? fun(opts: vim.api.keyset.user_command.callback_opts, ns: integer, buf: integer): nil ---@alias vim.api.keyset.user_command.callback fun(opts?: vim.api.keyset.user_command.callback_opts):nil ---@param name string ---@param command vim.api.keyset.user_command.callback ---@param opts? vim.api.keyset.user_command.opts function vim.api.nvim_create_user_command(name, command, opts) end ---@type boolean vim.g.avante_login = vim.g.avante_login ---@class AvanteHandlerOptions: table<[string], string> ---@field on_start AvanteLLMStartCallback ---@field on_chunk AvanteLLMChunkCallback ---@field on_stop AvanteLLMStopCallback ---@field on_messages_add? fun(messages: avante.HistoryMessage[]): nil ---@field on_state_change? fun(state: avante.GenerateState): nil ---@field update_tokens_usage? fun(usage: avante.LLMTokenUsage): nil --- ---@alias AvanteLLMMessageContentItem string | { type: "text", text: string, cache_control: { type: string } | nil } | { type: "image", source: { type: "base64", media_type: string, data: string } } | { type: "tool_use", name: string, id: string, input: any } | { type: "tool_result", tool_use_id: string, content: string, is_error?: boolean, is_user_declined?: boolean } | { type: "thinking", thinking: string, signature: string } | { type: "redacted_thinking", data: string } ---@alias AvanteLLMMessageContent AvanteLLMMessageContentItem[] | string ---@class AvanteLLMMessage ---@field role "user" | "assistant" ---@field content AvanteLLMMessageContent ---@class avante.TODO ---@field id string ---@field content string ---@field status "todo" | "doing" | "done" | "cancelled" ---@field priority "low" | "medium" | "high" ---@class avante.HistoryMessage ---@field message AvanteLLMMessage ---@field timestamp string ---@field state avante.HistoryMessageState ---@field uuid string | nil ---@field displayed_tool_name string | nil ---@field displayed_content string | nil ---@field visible boolean | nil ---@field is_context boolean | nil ---@field is_user_submission boolean | nil ---@field provider string | nil ---@field model string | nil ---@field selected_code AvanteSelectedCode | nil ---@field selected_filepaths string[] | nil ---@field tool_use_logs string[] | nil ---@field tool_use_log_lines avante.ui.Line[] | nil ---@field tool_use_store table | nil ---@field just_for_display boolean | nil ---@field is_dummy boolean | nil ---@field is_compacted boolean | nil ---@field is_deleted boolean | nil ---@field turn_id string | nil ---@field is_calling boolean | nil ---@field original_content AvanteLLMMessageContent | nil ---@field acp_tool_call? avante.acp.ToolCall ---@class AvanteLLMToolResult ---@field tool_name string ---@field tool_use_id string ---@field content string ---@field is_error? boolean ---@field is_user_declined? boolean ---@class AvantePromptOptions: table<[string], string> ---@field system_prompt string ---@field messages AvanteLLMMessage[] ---@field image_paths? string[] ---@field tools? AvanteLLMTool[] ---@field pending_compaction_history_messages? AvanteLLMMessage[] --- ---@class AvanteGeminiMessage ---@field role "user" ---@field parts { text: string }[] --- ---@class AvanteClaudeMessageContentBaseItem ---@field cache_control {type: "ephemeral"}? --- ---@class AvanteClaudeMessageContentTextItem: AvanteClaudeMessageContentBaseItem ---@field type "text" ---@field text string --- ---@class AvanteClaudeMessageCotnentImageItem: AvanteClaudeMessageContentBaseItem ---@field type "image" ---@field source {type: "base64", media_type: string, data: string} --- ---@class AvanteClaudeMessage ---@field role "user" | "assistant" ---@field content [AvanteClaudeMessageContentTextItem | AvanteClaudeMessageCotnentImageItem][] ---@class AvanteClaudeTool ---@field name string ---@field description string ---@field input_schema AvanteClaudeToolInputSchema ---@class AvanteClaudeToolInputSchema ---@field type "object" ---@field properties table<string, AvanteClaudeToolInputSchemaProperty> ---@field required string[] ---@class AvanteClaudeToolInputSchemaProperty ---@field type "string" | "number" | "boolean" ---@field description string ---@field enum? string[] --- ---@class AvanteOpenAIChatResponse ---@field id string ---@field object "chat.completion" | "chat.completion.chunk" ---@field created integer ---@field model string ---@field system_fingerprint string ---@field choices? AvanteOpenAIResponseChoice[] | AvanteOpenAIResponseChoiceComplete[] ---@field usage {prompt_tokens: integer, completion_tokens: integer, total_tokens: integer} --- ---@class AvanteOpenAIResponseChoice ---@field index integer ---@field delta AvanteOpenAIMessage ---@field logprobs? integer ---@field finish_reason? "stop" | "length" --- ---@class AvanteOpenAIResponseChoiceComplete ---@field message AvanteOpenAIMessage ---@field finish_reason "stop" | "length" | "eos_token" ---@field index integer ---@field logprobs integer --- ---@class AvanteOpenAIMessageToolCallFunction ---@field name string ---@field arguments string --- ---@class AvanteOpenAIMessageToolCall ---@field index integer ---@field id string ---@field type "function" ---@field function AvanteOpenAIMessageToolCallFunction --- ---@class AvanteOpenAIMessage ---@field role? "user" | "system" | "assistant" ---@field content? string ---@field reasoning_content? string ---@field reasoning? string ---@field tool_calls? AvanteOpenAIMessageToolCall[] ---@field type? "reasoning" | "function_call" | "function_call_output" ---@field id? string ---@field encrypted_content? string ---@field summary? string ---@field call_id? string ---@field name? string ---@field arguments? string ---@field output? string --- ---@class AvanteOpenAITool ---@field type "function" ---@field function? AvanteOpenAIToolFunction ---@field name? string ---@field description? string | nil ---@field parameters? AvanteOpenAIToolFunctionParameters | nil ---@field strict? boolean | nil --- ---@class AvanteOpenAIToolFunction ---@field name string ---@field description string | nil ---@field parameters AvanteOpenAIToolFunctionParameters | nil ---@field strict boolean | nil --- ---@class AvanteOpenAIToolFunctionParameters ---@field type "object" ---@field properties table<string, AvanteOpenAIToolFunctionParameterProperty> ---@field required string[] ---@field additionalProperties boolean --- ---@class AvanteOpenAIToolFunctionParameterProperty ---@field type string ---@field description string --- ---@alias AvanteChatMessage AvanteClaudeMessage | AvanteOpenAIMessage | AvanteGeminiMessage --- ---@alias AvanteMessagesParser fun(self: AvanteProviderFunctor, opts: AvantePromptOptions): AvanteChatMessage[] --- ---@class AvanteCurlOutput: {url: string, proxy: string, insecure: boolean, body: table<string, any> | string, headers: table<string, string>, rawArgs: string[] | nil} ---@alias AvanteCurlArgsParser fun(self: AvanteProviderFunctor, prompt_opts: AvantePromptOptions): (AvanteCurlOutput | nil) --- ---@alias AvanteResponseParser fun(self: AvanteProviderFunctor, ctx: any, data_stream: string, event_state: string, opts: AvanteHandlerOptions): nil --- ---@class AvanteDefaultBaseProvider: table<string, any> ---@field endpoint? string ---@field extra_request_body? table<string, any> ---@field model? string ---@field model_names? string[] ---@field local? boolean ---@field proxy? string ---@field keep_alive? string ---@field timeout? integer ---@field allow_insecure? boolean ---@field api_key_name? string ---@field _shellenv? string ---@field disable_tools? boolean ---@field entra? boolean ---@field hide_in_model_selector? boolean ---@field use_ReAct_prompt? boolean ---@field context_window? integer ---@field use_response_api? boolean | fun(provider: AvanteDefaultBaseProvider, ctx?: any): boolean ---@field support_previous_response_id? boolean --- ---@class AvanteSupportedProvider: AvanteDefaultBaseProvider ---@field __inherited_from? string ---@field display_name? string --- ---@class avante.OpenAITokenUsage ---@field total_tokens number ---@field prompt_tokens number ---@field completion_tokens number ---@field prompt_tokens_details {cached_tokens: number} --- ---@class avante.AnthropicTokenUsage ---@field input_tokens number ---@field cache_creation_input_tokens number ---@field cache_read_input_tokens number ---@field output_tokens number --- ---@class avante.GeminiTokenUsage ---@field promptTokenCount number ---@field candidatesTokenCount number --- ---@class avante.LLMTokenUsage ---@field prompt_tokens number ---@field completion_tokens number --- ---@class AvanteLLMThinkingBlock ---@field thinking string ---@field signature string --- ---@class AvanteLLMRedactedThinkingBlock ---@field data string --- ---@alias avante.HistoryMessageState "generating" | "generated" --- ---@class AvanteLLMToolUse ---@field name string ---@field id string ---@field input any --- ---@class AvantePartialLLMToolUse : AvanteLLMToolUse ---@field state avante.HistoryMessageState --- ---@class AvanteLLMStartCallbackOptions ---@field usage? avante.LLMTokenUsage --- ---@class AvanteLLMStopCallbackOptions ---@field reason "complete" | "tool_use" | "error" | "rate_limit" | "cancelled" | "max_tokens" | "usage" ---@field error? string | table ---@field usage? avante.LLMTokenUsage ---@field retry_after? integer ---@field headers? table<string, string> ---@field streaming_tool_use? boolean --- ---@alias AvanteStreamParser fun(self: AvanteProviderFunctor, ctx: any, line: string, handler_opts: AvanteHandlerOptions): nil ---@alias AvanteLLMStartCallback fun(opts: AvanteLLMStartCallbackOptions): nil ---@alias AvanteLLMChunkCallback fun(chunk: string): any ---@alias AvanteLLMStopCallback fun(opts: AvanteLLMStopCallbackOptions): nil ---@alias AvanteLLMConfigHandler fun(opts: AvanteSupportedProvider): AvanteDefaultBaseProvider, table<string, any> --- ---@class AvanteProviderModel ---@field id string ---@field name string ---@field display_name string ---@field provider_name string ---@field version string ---@field tokenizer? string ---@field max_input_tokens? integer ---@field max_output_tokens? integer ---@field policy? boolean --- ---@alias AvanteProviderModelList AvanteProviderModel[] --- ---@class AvanteProvider: AvanteSupportedProvider ---@field parse_curl_args? AvanteCurlArgsParser ---@field parse_stream_data? AvanteStreamParser ---@field parse_api_key? fun(): string | nil --- ---@class AvanteProviderFunctor ---@field _model_list_cache table ---@field extra_headers fun(table): table | table | nil ---@field support_prompt_caching boolean | nil ---@field role_map table<"user" | "assistant", string> ---@field parse_messages AvanteMessagesParser ---@field parse_response AvanteResponseParser ---@field parse_curl_args AvanteCurlArgsParser ---@field is_disable_stream fun(self: AvanteProviderFunctor): boolean ---@field setup fun(): nil ---@field is_env_set fun(): boolean ---@field api_key_name string ---@field tokenizer_id string | "gpt-4o" ---@field model? string ---@field context_window? integer ---@field parse_api_key fun(): string | nil ---@field parse_stream_data? AvanteStreamParser ---@field on_error? fun(result: table<string, any>): nil ---@field transform_tool? fun(self: AvanteProviderFunctor, tool: AvanteLLMTool): AvanteOpenAITool | AvanteClaudeTool ---@field get_rate_limit_sleep_time? fun(self: AvanteProviderFunctor, headers: table<string, string>): integer | nil ---@field list_models? fun(self): AvanteProviderModelList | nil --- ---@alias AvanteBedrockPayloadBuilder fun(self: AvanteBedrockModelHandler | AvanteBedrockProviderFunctor, prompt_opts: AvantePromptOptions, request_body: table<string, any>): table<string, any> --- ---@class AvanteBedrockProviderFunctor: AvanteProviderFunctor ---@field load_model_handler fun(): AvanteBedrockModelHandler ---@field build_bedrock_payload? AvanteBedrockPayloadBuilder --- ---@class AvanteBedrockModelHandler : AvanteProviderFunctor ---@field role_map table<"user" | "assistant", string> ---@field parse_messages AvanteMessagesParser ---@field parse_response AvanteResponseParser ---@field build_bedrock_payload AvanteBedrockPayloadBuilder --- ---@class AvanteACPProvider ---@field command string ---@field args string[] ---@field env table<string, string> ---@field auth_method string --- ---@alias AvanteLlmMode avante.Mode | "editing" | "suggesting" --- ---@class AvanteSelectedCode ---@field path string ---@field content string ---@field file_type string --- ---@class AvanteSelectedFile ---@field path string ---@field content string ---@field file_type string --- ---@class AvanteTemplateOptions ---@field ask boolean ---@field code_lang string ---@field recently_viewed_files string[] | nil ---@field selected_code AvanteSelectedCode | nil ---@field project_context string | nil ---@field selected_files AvanteSelectedFile[] | nil ---@field selected_filepaths string[] | nil ---@field diagnostics string | nil ---@field history_messages avante.HistoryMessage[] | nil ---@field get_todos? fun(): avante.TODO[] ---@field update_todos? fun(todos: avante.TODO[]): nil ---@field memory string | nil ---@field get_tokens_usage? fun(): avante.LLMTokenUsage | nil --- ---@class AvanteGeneratePromptsOptions: AvanteTemplateOptions ---@field instructions? string ---@field mode? AvanteLlmMode ---@field provider AvanteProviderFunctor | AvanteBedrockProviderFunctor | nil ---@field tools? AvanteLLMTool[] ---@field original_code? string ---@field update_snippets? string[] ---@field prompt_opts? AvantePromptOptions ---@field session_ctx? table --- ---@class AvanteLLMToolHistory ---@field tool_result? AvanteLLMToolResult ---@field tool_use? AvanteLLMToolUse --- ---@alias AvanteLLMMemorySummarizeCallback fun(pending_compaction_history_messages: avante.HistoryMessage[]): nil --- ---@alias AvanteLLMToolUseState "generating" | "generated" | "running" | "succeeded" | "failed" ---@alias avante.GenerateState "generating" | "tool calling" | "failed" | "succeeded" | "cancelled" | "searching" | "thinking" | "compacting" | "compacted" | "initializing" | "initialized" --- ---@class AvanteLLMStreamOptions: AvanteGeneratePromptsOptions ---@field acp_client? avante.acp.ACPClient ---@field on_save_acp_client? fun(client: avante.acp.ACPClient): nil ---@field just_connect_acp_client? boolean ---@field acp_session_id? string ---@field on_save_acp_session_id? fun(session_id: string): nil ---@field on_start AvanteLLMStartCallback ---@field on_chunk? AvanteLLMChunkCallback ---@field on_stop AvanteLLMStopCallback ---@field on_memory_summarize? AvanteLLMMemorySummarizeCallback ---@field on_tool_log? fun(tool_id: string, tool_name: string, log: string, state: AvanteLLMToolUseState): nil ---@field set_tool_use_store? fun(tool_id: string, key: string, value: any): nil ---@field get_history_messages? fun(opts?: { all?: boolean }): avante.HistoryMessage[] ---@field on_messages_add? fun(messages: avante.HistoryMessage[]): nil ---@field on_state_change? fun(state: avante.GenerateState): nil ---@field update_tokens_usage? fun(usage: avante.LLMTokenUsage): nil --- ---@class AvanteLLMToolFuncOpts ---@field session_ctx table ---@field on_complete? fun(result: boolean | string | nil, error: string | nil): nil ---@field on_log? fun(log: string): nil ---@field set_store? fun(key: string, value: any): nil ---@field tool_use_id? string ---@field streaming? boolean --- ---@alias AvanteLLMToolFunc<T> fun( --- input: T, --- opts: AvanteLLMToolFuncOpts) --- : (boolean | string | nil, string | nil) --- ---@class avante.LLMToolOnRenderOpts ---@field logs string[] ---@field state avante.HistoryMessageState ---@field store table | nil ---@field result_message avante.HistoryMessage | nil --- --- @alias avante.LLMToolOnRender<T> fun(input: T, opts: avante.LLMToolOnRenderOpts): avante.ui.Line[] --- ---@class AvanteLLMTool ---@field name string ---@field description? string ---@field get_description? fun(): string ---@field func? AvanteLLMToolFunc ---@field param AvanteLLMToolParam ---@field returns AvanteLLMToolReturn[] ---@field enabled? fun(opts: { user_input: string, history_messages: AvanteLLMMessage[] }): boolean ---@field on_render? avante.LLMToolOnRender ---@field support_streaming? boolean ---@class AvanteLLMToolPublic : AvanteLLMTool ---@field func AvanteLLMToolFunc ---@class AvanteLLMToolParam ---@field type 'table' ---@field fields AvanteLLMToolParamField[] ---@field usage? table ---@class AvanteLLMToolParamField ---@field name string ---@field description? string ---@field get_description? fun(): string ---@field type 'string' | 'integer' | 'boolean' | 'object' | 'array' ---@field fields? AvanteLLMToolParamField[] ---@field items? AvanteLLMToolParamField ---@field choices? string[] ---@field optional? boolean ---@class AvanteLLMToolReturn ---@field name string ---@field description string ---@field type 'string' | 'string[]' | 'boolean' | 'array' ---@field optional? boolean --- ---@class avante.ChatHistoryEntry ---@field timestamp string ---@field provider string ---@field model string ---@field request string ---@field response string ---@field original_response string ---@field selected_file {filepath: string}? ---@field selected_code AvanteSelectedCode | nil ---@field selected_filepaths string[] | nil ---@field visible boolean? --- ---@class avante.ChatHistory ---@field title string ---@field timestamp string ---@field messages avante.HistoryMessage[] ---@field entries avante.ChatHistoryEntry[] ---@field todos avante.TODO[] ---@field memory avante.ChatMemory | nil ---@field filename string ---@field system_prompt string | nil ---@field tokens_usage avante.LLMTokenUsage | nil ---@field acp_session_id string | nil --- ---@class avante.ChatMemory ---@field content string ---@field last_summarized_timestamp string ---@field last_message_uuid string | nil --- ---@class avante.CurlOpts ---@field provider AvanteProviderFunctor ---@field prompt_opts AvantePromptOptions ---@field handler_opts AvanteHandlerOptions ---@field on_response_headers? fun(headers: table<string, string>): nil --- ---@class avante.lsp.Definition ---@field content string ---@field uri string --- ---@alias AvanteSlashCommandBuiltInName "clear" | "help" | "lines" | "commit" | "new" ---@alias AvanteSlashCommandCallback fun(self: avante.Sidebar, args: string, cb?: fun(args: string): nil): nil ---@class AvanteSlashCommand ---@field name AvanteSlashCommandBuiltInName | string ---@field description string ---@field details string ---@field shorthelp? string ---@field callback? AvanteSlashCommandCallback ---@alias AvanteMentions "codebase" | "diagnostics" | "file" | "quickfix" | "buffers" ---@alias AvanteMentionCallback fun(args: string, cb?: fun(args: string): nil): nil ---@alias AvanteMention {description: string, command: AvanteMentions, details: string, shorthelp?: string, callback?: AvanteMentionCallback} ---@class AvanteShortcut ---@field name string ---@field details string ---@field description string ---@field prompt string
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/acp_confirm_adapter.lua
Lua
local Highlights = require("avante.highlights") ---@class avante.ui.ConfirmAdapter local M = {} ---@class avante.ui.ACPConfirmAdapter.ACPMappedOptions ---@field yes? string ---@field all? string ---@field no? string ---Converts the ACP permission options to confirmation popup-compatible format (yes/all/no) ---@param options avante.acp.PermissionOption[] ---@return avante.ui.ACPConfirmAdapter.ACPMappedOptions function M.map_acp_options(options) local option_map = { yes = nil, all = nil, no = nil } for _, opt in ipairs(options) do if opt.kind == "allow_once" then option_map.yes = opt.optionId elseif opt.kind == "allow_always" then option_map.all = opt.optionId elseif opt.kind == "reject_once" then option_map.no = opt.optionId -- elseif opt.kind == "reject_always" then -- ignore, no 4th option in the confirm popup yet end end return option_map end ---@class avante.ui.ACPConfirmAdapter.ButtonOption ---@field id string ---@field icon string ---@field name string ---@field hl? string ---@param options avante.acp.PermissionOption[] ---@return avante.ui.ACPConfirmAdapter.ButtonOption[] function M.generate_buttons_for_acp_options(options) local items = vim .iter(options) :map(function(item) ---@cast item avante.acp.PermissionOption local icon = item.kind == "allow_once" and "" or "" if item.kind == "allow_always" then icon = "" end local hl = nil if item.kind == "reject_once" or item.kind == "reject_always" then hl = Highlights.BUTTON_DANGER_HOVER end ---@type avante.ui.ACPConfirmAdapter.ButtonOption local button = { id = item.optionId, name = item.name, icon = icon, hl = hl, } return button end) :totable() -- Sort to have "allow" first, then "allow always", then "reject" table.sort(items, function(a, b) return a.name < b.name end) return items end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/button_group_line.lua
Lua
local Highlights = require("avante.highlights") local Line = require("avante.ui.line") local Utils = require("avante.utils") ---@class avante.ui.ButtonGroupLine ---@field _line avante.ui.Line ---@field _button_options { id: string, icon?: string, name: string, hl?: string }[] ---@field _focus_index integer ---@field _group_label string|nil ---@field _start_col integer ---@field _button_pos integer[][] ---@field _ns_id integer|nil ---@field _bufnr integer|nil ---@field _line_1b integer|nil ---@field on_click? fun(id: string) local ButtonGroupLine = {} ButtonGroupLine.__index = ButtonGroupLine -- per-buffer registry for dispatching shared keymaps/autocmds local registry ---@type table<integer, { lines: table<integer, avante.ui.ButtonGroupLine>, mapped: boolean, autocmd: integer|nil }> registry = {} local function ensure_dispatch(bufnr) local entry = registry[bufnr] if not entry then entry = { lines = {}, mapped = false, autocmd = nil } registry[bufnr] = entry end if not entry.mapped then -- Tab: next button if on a group line; otherwise fall back to sidebar switch_windows vim.keymap.set("n", "<Tab>", function() local row, _ = unpack(vim.api.nvim_win_get_cursor(0)) local group = entry.lines[row] if not group then local ok, sidebar = pcall(require, "avante") if ok and sidebar and sidebar.get then local sb = sidebar.get() if sb and sb.switch_window_focus then sb:switch_window_focus("next") return end end -- Fallback to raw <Tab> if sidebar is unavailable vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<Tab>", true, false, true), "n", true) return end group._focus_index = group._focus_index + 1 if group._focus_index > #group._button_options then group._focus_index = 1 end group:_refresh_highlights() group:_move_cursor_to_focus() end, { buffer = bufnr, nowait = true }) vim.keymap.set("n", "<S-Tab>", function() local row, _ = unpack(vim.api.nvim_win_get_cursor(0)) local group = entry.lines[row] if not group then local ok, sidebar = pcall(require, "avante") if ok and sidebar and sidebar.get then local sb = sidebar.get() if sb and sb.switch_window_focus then sb:switch_window_focus("previous") return end end -- Fallback to raw <S-Tab> if sidebar is unavailable vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<S-Tab>", true, false, true), "n", true) return end group._focus_index = group._focus_index - 1 if group._focus_index < 1 then group._focus_index = #group._button_options end group:_refresh_highlights() group:_move_cursor_to_focus() end, { buffer = bufnr, nowait = true }) vim.keymap.set("n", "<CR>", function() local row, _ = unpack(vim.api.nvim_win_get_cursor(0)) local group = entry.lines[row] if not group then vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes("<CR>", true, false, true), "n", true) return end group:_click_focused() end, { buffer = bufnr, nowait = true }) -- Mouse click to activate vim.api.nvim_buf_set_keymap(bufnr, "n", "<LeftMouse>", "", { callback = function() local pos = vim.fn.getmousepos() local row, col = pos.winrow, pos.wincol local group = entry.lines[row] if not group then return end group:_update_focus_by_col(col) group:_click_focused() end, noremap = true, silent = true, }) -- CursorMoved hover highlight entry.autocmd = vim.api.nvim_create_autocmd("CursorMoved", { buffer = bufnr, callback = function() local row, col = unpack(vim.api.nvim_win_get_cursor(0)) local group = entry.lines[row] if not group then return end group:_update_focus_by_col(col) end, }) entry.mapped = true end end local function cleanup_dispatch_if_empty(bufnr) local entry = registry[bufnr] if not entry then return end -- Do not delete keymaps when no button lines remain. -- Deleting buffer-local mappings would not restore any previous mapping, -- which breaks the original Tab behavior in the sidebar. -- We intentionally keep the keymaps and autocmds; they safely no-op or -- fall back when not on a button group line. end ---@param button_options { id: string, icon: string|nil, name: string, hl?: string }[] ---@param opts? { on_click: fun(id: string), start_col?: integer, group_label?: string } function ButtonGroupLine:new(button_options, opts) opts = opts or {} local o = setmetatable({}, ButtonGroupLine) o._button_options = vim.deepcopy(button_options) o._focus_index = 1 o._start_col = opts.start_col or 0 o._group_label = opts.group_label local BUTTON_NORMAL = Highlights.BUTTON_DEFAULT local BUTTON_FOCUS = Highlights.BUTTON_DEFAULT_HOVER local sections = {} if o._group_label and #o._group_label > 0 then table.insert(sections, { o._group_label .. " " }) end local btn_sep = " " for i, opt in ipairs(o._button_options) do local label if opt.icon and #opt.icon > 0 then label = string.format(" %s %s ", opt.icon, opt.name) else label = string.format(" %s ", opt.name) end local focus_hl = opt.hl or BUTTON_FOCUS table.insert(sections, { label, function() return (o._focus_index == i) and focus_hl or BUTTON_NORMAL end }) if i < #o._button_options then table.insert(sections, { btn_sep }) end end o._line = Line:new(sections) -- precalc positions for quick hover/click checks o._button_pos = {} local sec_idx = (o._group_label and #o._group_label > 0) and 2 or 1 for i = 1, #o._button_options do local start_end = o._line:get_section_pos(sec_idx, o._start_col) o._button_pos[i] = { start_end[1], start_end[2] } if i < #o._button_options then sec_idx = sec_idx + 2 else sec_idx = sec_idx + 1 end end if opts.on_click then o.on_click = opts.on_click end return o end function ButtonGroupLine:__tostring() return string.rep(" ", self._start_col) .. tostring(self._line) end ---@param ns_id integer ---@param bufnr integer ---@param line_0b integer ---@param _offset integer|nil -- ignored; offset handled in __tostring and pos precalc function ButtonGroupLine:set_highlights(ns_id, bufnr, line_0b, _offset) _offset = _offset or 0 self._ns_id = ns_id self._bufnr = bufnr self._line_1b = line_0b + 1 self._line:set_highlights(ns_id, bufnr, line_0b, self._start_col + _offset) end -- called by utils.update_buffer_lines after content is written ---@param _ns_id integer ---@param bufnr integer ---@param line_1b integer function ButtonGroupLine:bind_events(_ns_id, bufnr, line_1b) self._bufnr = bufnr self._line_1b = line_1b ensure_dispatch(bufnr) local entry = registry[bufnr] entry.lines[line_1b] = self end ---@param bufnr integer ---@param line_1b integer function ButtonGroupLine:unbind_events(bufnr, line_1b) local entry = registry[bufnr] if not entry then return end entry.lines[line_1b] = nil cleanup_dispatch_if_empty(bufnr) end function ButtonGroupLine:_refresh_highlights() if not (self._ns_id and self._bufnr and self._line_1b) then return end --- refresh content Utils.unlock_buf(self._bufnr) vim.api.nvim_buf_set_lines(self._bufnr, self._line_1b - 1, self._line_1b, false, { tostring(self) }) Utils.lock_buf(self._bufnr) self._line:set_highlights(self._ns_id, self._bufnr, self._line_1b - 1, self._start_col) end function ButtonGroupLine:_move_cursor_to_focus() local pos = self._button_pos[self._focus_index] if not pos then return end local winid = require("avante.utils").get_winid(self._bufnr) if winid and vim.api.nvim_win_is_valid(winid) then vim.api.nvim_win_set_cursor(winid, { self._line_1b, pos[1] }) end end ---@param col integer 0-based column function ButtonGroupLine:_update_focus_by_col(col) for i, rng in ipairs(self._button_pos) do if col >= rng[1] and col <= rng[2] then if self._focus_index ~= i then self._focus_index = i self:_refresh_highlights() end return end end end function ButtonGroupLine:_click_focused() local opt = self._button_options[self._focus_index] if not opt then return end if self.on_click then pcall(self.on_click, opt.id) end end return ButtonGroupLine
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/confirm.lua
Lua
local Popup = require("nui.popup") local NuiText = require("nui.text") local Highlights = require("avante.highlights") local Utils = require("avante.utils") local Line = require("avante.ui.line") local PromptInput = require("avante.ui.prompt_input") local Config = require("avante.config") ---@class avante.ui.Confirm ---@field message string ---@field callback fun(type: "yes" | "all" | "no", reason?: string) ---@field _container_winid number ---@field _focus boolean | nil ---@field _group number | nil ---@field _popup NuiPopup | nil ---@field _prev_winid number | nil ---@field _ns_id number | nil ---@field _skip_reject_prompt boolean | nil local M = {} M.__index = M ---@class avante.ui.ConfirmOptions ---@field container_winid? number ---@field focus? boolean | nil ---@field skip_reject_prompt? boolean ACP doesn't support reject reason ---@field permission_options? avante.acp.PermissionOption[] ACP permission options to show in the confirm popup ---@param message string ---@param callback fun(type: "yes" | "all" | "no", reason?: string) ---@param opts avante.ui.ConfirmOptions ---@return avante.ui.Confirm function M:new(message, callback, opts) local this = setmetatable({}, M) this.message = message or "" this.callback = callback this._container_winid = opts.container_winid or vim.api.nvim_get_current_win() this._focus = opts.focus this._skip_reject_prompt = opts.skip_reject_prompt this._ns_id = vim.api.nvim_create_namespace("avante_confirm") return this end function M:open() if self._popup then return end self._prev_winid = vim.api.nvim_get_current_win() local message = self.message or "" local callback = self.callback local win_width = 60 local focus_index = 1 -- 1 = Yes, 2 = All Yes, 3 = No local BUTTON_NORMAL = Highlights.BUTTON_DEFAULT local BUTTON_FOCUS = Highlights.BUTTON_DEFAULT_HOVER local commentfg = Highlights.AVANTE_COMMENT_FG local keybindings_line = Line:new({ { " " .. Config.mappings.confirm.focus_window .. " ", "visual" }, { " - focus ", commentfg }, { " " }, { " " .. Config.mappings.confirm.code .. " ", "visual" }, { " - code ", commentfg }, { " " }, { " " .. Config.mappings.confirm.resp .. " ", "visual" }, { " - resp ", commentfg }, { " " }, { " " .. Config.mappings.confirm.input .. " ", "visual" }, { " - input ", commentfg }, { " " }, }) local buttons_line = Line:new({ { "  [Y]es ", function() return focus_index == 1 and BUTTON_FOCUS or BUTTON_NORMAL end }, { " " }, { "  [A]ll yes ", function() return focus_index == 2 and BUTTON_FOCUS or BUTTON_NORMAL end }, { " " }, { "  [N]o ", function() return focus_index == 3 and BUTTON_FOCUS or BUTTON_NORMAL end }, }) local buttons_content = tostring(buttons_line) local buttons_start_col = math.floor((win_width - #buttons_content) / 2) local yes_button_pos = buttons_line:get_section_pos(1, buttons_start_col) local all_button_pos = buttons_line:get_section_pos(3, buttons_start_col) local no_button_pos = buttons_line:get_section_pos(5, buttons_start_col) local buttons_line_content = string.rep(" ", buttons_start_col) .. buttons_content local keybindings_line_num = 5 + #vim.split(message, "\n") local buttons_line_num = 2 + #vim.split(message, "\n") local content = vim .iter({ "", vim.tbl_map(function(line) return " " .. line end, vim.split(message, "\n")), "", buttons_line_content, "", "", tostring(keybindings_line), }) :flatten() :totable() local win_height = #content for _, line in ipairs(vim.split(message, "\n")) do win_height = win_height + math.floor(#line / (win_width - 2)) end local button_row = buttons_line_num + 1 local container_winid = self._container_winid local container_width = vim.api.nvim_win_get_width(container_winid) local popup = Popup({ relative = { type = "win", winid = container_winid, }, position = { row = vim.o.lines - win_height, col = math.floor((container_width - win_width) / 2), }, size = { width = win_width, height = win_height }, enter = self._focus ~= false, focusable = true, border = { padding = { 0, 1 }, text = { top = NuiText(" Confirmation ", Highlights.CONFIRM_TITLE) }, style = { " ", " ", " ", " ", " ", " ", " ", " " }, }, buf_options = { filetype = "AvanteConfirm", modifiable = false, readonly = true, buftype = "nofile", }, win_options = { winfixbuf = true, cursorline = false, winblend = 5, winhighlight = "NormalFloat:Normal,FloatBorder:Comment", }, }) local function focus_button() if focus_index == 1 then vim.api.nvim_win_set_cursor(popup.winid, { button_row, yes_button_pos[1] }) elseif focus_index == 2 then vim.api.nvim_win_set_cursor(popup.winid, { button_row, all_button_pos[1] }) else vim.api.nvim_win_set_cursor(popup.winid, { button_row, no_button_pos[1] }) end end local function render_content() Utils.unlock_buf(popup.bufnr) vim.api.nvim_buf_set_lines(popup.bufnr, 0, -1, false, content) Utils.lock_buf(popup.bufnr) buttons_line:set_highlights(self._ns_id, popup.bufnr, buttons_line_num, buttons_start_col) keybindings_line:set_highlights(self._ns_id, popup.bufnr, keybindings_line_num) focus_button() end local function click_button() if focus_index == 1 then self:close() callback("yes") return end if focus_index == 2 then self:close() callback("all") return end if self._skip_reject_prompt then self:close() callback("no") return end local prompt_input = PromptInput:new({ submit_callback = function(input) self:close() callback("no", input ~= "" and input or nil) end, close_on_submit = true, win_opts = { relative = "win", win = self._container_winid, border = Config.windows.ask.border, title = { { "Reject reason", "FloatTitle" } }, }, start_insert = Config.windows.ask.start_insert, }) prompt_input:open() end vim.keymap.set("n", Config.mappings.confirm.code, function() local sidebar = require("avante").get() if not sidebar then return end if sidebar.code.winid and vim.api.nvim_win_is_valid(sidebar.code.winid) then vim.api.nvim_set_current_win(sidebar.code.winid) end end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", Config.mappings.confirm.resp, function() local sidebar = require("avante").get() if sidebar and sidebar.containers.result and vim.api.nvim_win_is_valid(sidebar.containers.result.winid) then vim.api.nvim_set_current_win(sidebar.containers.result.winid) end end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", Config.mappings.confirm.input, function() local sidebar = require("avante").get() if sidebar and sidebar.containers.input and vim.api.nvim_win_is_valid(sidebar.containers.input.winid) then vim.api.nvim_set_current_win(sidebar.containers.input.winid) end end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", "y", function() focus_index = 1 render_content() click_button() end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", "Y", function() focus_index = 1 render_content() click_button() end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", "a", function() focus_index = 2 render_content() click_button() end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", "A", function() focus_index = 2 render_content() click_button() end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", "n", function() focus_index = 3 render_content() click_button() end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", "N", function() focus_index = 3 render_content() click_button() end, { buffer = popup.bufnr, nowait = true }) vim.keymap.set("n", "<Left>", function() focus_index = focus_index - 1 if focus_index < 1 then focus_index = 3 end focus_button() end, { buffer = popup.bufnr }) vim.keymap.set("n", "<Right>", function() focus_index = focus_index + 1 if focus_index > 3 then focus_index = 1 end focus_button() end, { buffer = popup.bufnr }) vim.keymap.set("n", "h", function() focus_index = 1 focus_button() end, { buffer = popup.bufnr }) vim.keymap.set("n", "l", function() focus_index = 2 focus_button() end, { buffer = popup.bufnr }) vim.keymap.set("n", "<Tab>", function() focus_index = focus_index + 1 if focus_index > 3 then focus_index = 1 end focus_button() end, { buffer = popup.bufnr }) vim.keymap.set("n", "<S-Tab>", function() focus_index = focus_index - 1 if focus_index < 1 then focus_index = 3 end focus_button() end, { buffer = popup.bufnr }) vim.keymap.set("n", "<CR>", function() click_button() end, { buffer = popup.bufnr }) vim.api.nvim_buf_set_keymap(popup.bufnr, "n", "<LeftMouse>", "", { callback = function() local pos = vim.fn.getmousepos() local row, col = pos["winrow"], pos["wincol"] if row == button_row then if col >= yes_button_pos[1] and col <= yes_button_pos[2] then focus_index = 1 elseif col >= all_button_pos[1] and col <= all_button_pos[2] then focus_index = 2 elseif col >= no_button_pos[1] and col <= no_button_pos[2] then focus_index = 3 end render_content() click_button() end end, noremap = true, silent = true, }) vim.api.nvim_create_autocmd("CursorMoved", { buffer = popup.bufnr, callback = function() local row, col = unpack(vim.api.nvim_win_get_cursor(0)) if row ~= button_row then vim.api.nvim_win_set_cursor(self._popup.winid, { button_row, buttons_start_col }) end if col >= yes_button_pos[1] and col <= yes_button_pos[2] then focus_index = 1 render_content() elseif col >= all_button_pos[1] and col <= all_button_pos[2] then focus_index = 2 render_content() elseif col >= no_button_pos[1] and col <= no_button_pos[2] then focus_index = 3 render_content() end end, }) self._group = self._group and self._group or vim.api.nvim_create_augroup("AvanteConfirm", { clear = true }) vim.api.nvim_create_autocmd("WinClosed", { group = self._group, callback = function() local winids = vim.api.nvim_list_wins() if not vim.list_contains(winids, self._container_winid) then self:close() end end, }) popup:mount() render_content() self._popup = popup self:bind_window_focus_keymaps() end function M:window_focus_handler() local current_winid = vim.api.nvim_get_current_win() if current_winid == self._popup.winid and current_winid ~= self._prev_winid and vim.api.nvim_win_is_valid(self._prev_winid) then vim.api.nvim_set_current_win(self._prev_winid) return end self._prev_winid = current_winid vim.api.nvim_set_current_win(self._popup.winid) end function M:bind_window_focus_keymaps() vim.keymap.set({ "n", "i" }, Config.mappings.confirm.focus_window, function() self:window_focus_handler() end) end function M:unbind_window_focus_keymaps() pcall(vim.keymap.del, { "n", "i" }, Config.mappings.confirm.focus_window) end function M:cancel() self.callback("no", "cancel") return self:close() end function M:close() self:unbind_window_focus_keymaps() if self._group then pcall(vim.api.nvim_del_augroup_by_id, self._group) self._group = nil end if self._popup then self._popup:unmount() self._popup = nil return true end return false end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/input/init.lua
Lua
local Utils = require("avante.utils") ---@class avante.ui.InputOption ---@field provider avante.InputProvider ---@field title string ---@field default string | nil ---@field completion string | nil ---@field provider_opts table | nil ---@field on_submit fun(result: string | nil) ---@field conceal boolean | nil -- Whether to conceal input (for passwords) ---@class avante.ui.Input ---@field provider avante.InputProvider ---@field title string ---@field default string | nil ---@field completion string | nil ---@field provider_opts table | nil ---@field on_submit fun(result: string | nil) ---@field conceal boolean | nil local Input = {} Input.__index = Input ---@param opts avante.ui.InputOption function Input:new(opts) local o = {} setmetatable(o, Input) o.provider = opts.provider o.title = opts.title o.default = opts.default or "" o.completion = opts.completion o.provider_opts = opts.provider_opts or {} o.on_submit = opts.on_submit o.conceal = opts.conceal or false return o end function Input:open() if type(self.provider) == "function" then self.provider(self) return end local ok, provider = pcall(require, "avante.ui.input.providers." .. self.provider) if not ok then Utils.error("Unknown input provider: " .. self.provider) end provider.show(self) end return Input
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/input/providers/dressing.lua
Lua
local api = vim.api local fn = vim.fn local M = {} ---@param input avante.ui.Input function M.show(input) local ok, dressing_input = pcall(require, "dressing.input") if not ok then vim.notify("dressing.nvim not found, falling back to native input", vim.log.levels.WARN) require("avante.ui.input.providers.native").show(input) return end -- Store state for concealing functionality local state = { winid = nil, input_winid = nil, input_bufnr = nil } local function setup_concealing() if not input.conceal then return end vim.defer_fn(function() -- Find the dressing input window for _, winid in ipairs(api.nvim_list_wins()) do local bufnr = api.nvim_win_get_buf(winid) if vim.bo[bufnr].filetype == "DressingInput" then state.input_winid = winid state.input_bufnr = bufnr vim.wo[winid].conceallevel = 2 vim.wo[winid].concealcursor = "nvi" -- Set up concealing syntax local prompt_length = api.nvim_strwidth(fn.prompt_getprompt(state.input_bufnr)) api.nvim_buf_call( state.input_bufnr, function() vim.cmd(string.format( [[ syn region SecretValue start=/^/ms=s+%s end=/$/ contains=SecretChar syn match SecretChar /./ contained conceal cchar=* ]], prompt_length )) end ) break end end end, 50) end -- Enhanced functionality for concealed input vim.ui.input({ prompt = input.title, default = input.default, completion = input.completion, }, function(result) input.on_submit(result) -- Close the dressing input window after submission if we have concealing if input.conceal then pcall(dressing_input.close) end end) -- Set up concealing if needed setup_concealing() end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/input/providers/native.lua
Lua
local M = {} ---@param input avante.ui.Input function M.show(input) local opts = { prompt = input.title, default = input.default, completion = input.completion, } -- Note: Native vim.ui.input doesn't support concealing -- For password input, users should use dressing or snacks providers if input.conceal then vim.notify_once( "Native input provider doesn't support concealed input. Consider using 'dressing' or 'snacks' provider for password input.", vim.log.levels.WARN ) end vim.ui.input(opts, input.on_submit) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/input/providers/snacks.lua
Lua
local M = {} ---@param input avante.ui.Input function M.show(input) local ok, snacks_input = pcall(require, "snacks.input") if not ok then vim.notify("snacks.nvim not found, falling back to native input", vim.log.levels.WARN) require("avante.ui.input.providers.native").show(input) return end local opts = vim.tbl_deep_extend("force", { prompt = input.title, default = input.default, }, input.provider_opts) -- Add concealing support if needed if input.conceal then opts.password = true end snacks_input(opts, input.on_submit) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/line.lua
Lua
---@alias avante.ui.LineSection table --- ---@class avante.ui.Line ---@field sections avante.ui.LineSection[] local M = {} M.__index = M ---@param sections avante.ui.LineSection[] function M:new(sections) local this = setmetatable({}, M) this.sections = sections return this end ---@param ns_id number ---@param bufnr number ---@param line number ---@param offset number | nil function M:set_highlights(ns_id, bufnr, line, offset) if not vim.api.nvim_buf_is_valid(bufnr) then return end local col_start = offset or 0 for _, section in ipairs(self.sections) do local text = section[1] local highlight = section[2] if type(highlight) == "function" then highlight = highlight() end if highlight then vim.highlight.range(bufnr, ns_id, highlight, { line, col_start }, { line, col_start + #text }) end col_start = col_start + #text end end ---@param section_index number ---@param offset number | nil ---@return number[] function M:get_section_pos(section_index, offset) offset = offset or 0 local col_start = 0 for i = 1, section_index - 1 do if i == section_index then break end local section = self.sections[i] local text = type(section) == "table" and section[1] or section col_start = col_start + #text end local current = self.sections[section_index] local text = type(current) == "table" and current[1] or current return { offset + col_start, offset + col_start + #text } end function M:__tostring() local content = {} for _, section in ipairs(self.sections) do local text = section[1] table.insert(content, text) end return table.concat(content, "") end function M:__eq(other) if not other or type(other) ~= "table" or not other.sections then return false end return vim.deep_equal(self.sections, other.sections) end function M:bind_events(ns_id, bufnr, line) end function M:unbind_events(bufnr, line) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/prompt_input.lua
Lua
local api = vim.api local fn = vim.fn local Config = require("avante.config") local Utils = require("avante.utils") ---@class avante.ui.PromptInput ---@field bufnr integer | nil ---@field winid integer | nil ---@field win_opts table ---@field shortcuts_hints_winid integer | nil ---@field augroup integer | nil ---@field start_insert boolean ---@field submit_callback function | nil ---@field cancel_callback function | nil ---@field close_on_submit boolean ---@field spinner_chars table ---@field spinner_index integer ---@field spinner_timer uv.uv_timer_t | nil ---@field spinner_active boolean ---@field default_value string | nil ---@field popup_hint_id integer | nil local PromptInput = {} PromptInput.__index = PromptInput ---@class avante.ui.PromptInputOptions ---@field start_insert? boolean ---@field submit_callback? fun(input: string):nil ---@field cancel_callback? fun():nil ---@field close_on_submit? boolean ---@field win_opts? table ---@field default_value? string ---@param opts? avante.ui.PromptInputOptions function PromptInput:new(opts) opts = opts or {} local obj = setmetatable({}, PromptInput) obj.bufnr = nil obj.winid = nil obj.shortcuts_hints_winid = nil obj.augroup = api.nvim_create_augroup("PromptInput", { clear = true }) obj.start_insert = opts.start_insert or false obj.submit_callback = opts.submit_callback obj.cancel_callback = opts.cancel_callback obj.close_on_submit = opts.close_on_submit or false obj.win_opts = opts.win_opts obj.default_value = opts.default_value obj.spinner_chars = Config.windows.spinner.editing obj.spinner_index = 1 obj.spinner_timer = nil obj.spinner_active = false obj.popup_hint_id = vim.api.nvim_create_namespace("avante_prompt_input_hint") return obj end function PromptInput:open() self:close() local bufnr = api.nvim_create_buf(false, true) self.bufnr = bufnr vim.bo[bufnr].filetype = "AvantePromptInput" Utils.mark_as_sidebar_buffer(bufnr) local win_opts = vim.tbl_extend("force", { relative = "cursor", width = 40, height = 2, row = 1, col = 0, style = "minimal", border = Config.windows.edit.border, title = { { "Input", "FloatTitle" } }, title_pos = "center", }, self.win_opts) local winid = api.nvim_open_win(bufnr, true, win_opts) self.winid = winid api.nvim_set_option_value("wrap", false, { win = winid }) api.nvim_set_option_value("winblend", 5, { win = winid }) api.nvim_set_option_value( "winhighlight", "FloatBorder:AvantePromptInputBorder,Normal:AvantePromptInput", { win = winid } ) api.nvim_set_option_value("cursorline", true, { win = winid }) api.nvim_set_option_value("modifiable", true, { buf = bufnr }) local default_value_lines = {} if self.default_value then default_value_lines = vim.split(self.default_value, "\n") end if #default_value_lines > 0 then vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, default_value_lines) api.nvim_win_set_cursor(winid, { #default_value_lines, #default_value_lines[#default_value_lines] }) end self:show_shortcuts_hints() self:setup_keymaps() self:setup_autocmds() if self.start_insert then vim.cmd("noautocmd startinsert!") end end function PromptInput:close() if not self.bufnr then return end self:stop_spinner() self:close_shortcuts_hints() if api.nvim_get_mode().mode == "i" then vim.cmd("noautocmd stopinsert") end if self.winid and api.nvim_win_is_valid(self.winid) then api.nvim_win_close(self.winid, true) self.winid = nil end if self.bufnr and api.nvim_buf_is_valid(self.bufnr) then api.nvim_buf_delete(self.bufnr, { force = true }) self.bufnr = nil end if self.augroup then api.nvim_del_augroup_by_id(self.augroup) self.augroup = nil end end function PromptInput:cancel() self:close() if self.cancel_callback then self.cancel_callback() end end function PromptInput:submit(input) if self.close_on_submit then self:close() end if self.submit_callback then self.submit_callback(input) end end function PromptInput:show_shortcuts_hints() self:close_shortcuts_hints() if not self.winid or not api.nvim_win_is_valid(self.winid) then return end local win_width = api.nvim_win_get_width(self.winid) local win_height = api.nvim_win_get_height(self.winid) local buf_height = api.nvim_buf_line_count(self.bufnr) local hint_text = (vim.fn.mode() ~= "i" and Config.mappings.submit.normal or Config.mappings.submit.insert) .. ": submit" local display_text = hint_text if self.spinner_active then local spinner = self.spinner_chars[self.spinner_index] display_text = spinner .. " " .. hint_text end local buf = api.nvim_create_buf(false, true) api.nvim_buf_set_lines(buf, 0, -1, false, { display_text }) api.nvim_buf_set_extmark(buf, self.popup_hint_id, 0, 0, { end_row = 0, end_col = #display_text, hl_group = "AvantePopupHint", priority = 100, }) local width = fn.strdisplaywidth(display_text) local opts = { relative = "win", win = self.winid, width = width, height = 1, row = win_height, col = math.max(win_width - width, 0), style = "minimal", border = "none", focusable = false, zindex = 100, } self.shortcuts_hints_winid = api.nvim_open_win(buf, false, opts) api.nvim_set_option_value("winblend", 10, { win = self.shortcuts_hints_winid }) end function PromptInput:close_shortcuts_hints() if self.shortcuts_hints_winid and api.nvim_win_is_valid(self.shortcuts_hints_winid) then local buf = api.nvim_win_get_buf(self.shortcuts_hints_winid) if self.popup_hint_id then api.nvim_buf_clear_namespace(buf, self.popup_hint_id, 0, -1) end api.nvim_win_close(self.shortcuts_hints_winid, true) api.nvim_buf_delete(buf, { force = true }) self.shortcuts_hints_winid = nil end end function PromptInput:start_spinner() self.spinner_active = true self.spinner_index = 1 if self.spinner_timer then self.spinner_timer:stop() self.spinner_timer:close() self.spinner_timer = nil end self.spinner_timer = vim.uv.new_timer() local spinner_timer = self.spinner_timer if self.spinner_timer then self.spinner_timer:start(0, 100, function() vim.schedule(function() if not self.spinner_active or spinner_timer ~= self.spinner_timer then return end self.spinner_index = (self.spinner_index % #self.spinner_chars) + 1 self:show_shortcuts_hints() end) end) end end function PromptInput:stop_spinner() self.spinner_active = false if self.spinner_timer then self.spinner_timer:stop() self.spinner_timer:close() self.spinner_timer = nil end self:show_shortcuts_hints() end function PromptInput:setup_keymaps() local bufnr = self.bufnr local function get_input() if not bufnr or not api.nvim_buf_is_valid(bufnr) then return "" end local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) return lines[1] or "" end vim.keymap.set( "i", Config.mappings.submit.insert, function() self:submit(get_input()) end, { buffer = bufnr, noremap = true, silent = true } ) vim.keymap.set( "n", Config.mappings.submit.normal, function() self:submit(get_input()) end, { buffer = bufnr, noremap = true, silent = true } ) for _, key in ipairs(Config.mappings.cancel.normal) do vim.keymap.set("n", key, function() self:cancel() end, { buffer = bufnr }) end for _, key in ipairs(Config.mappings.cancel.insert) do vim.keymap.set("i", key, function() self:cancel() end, { buffer = bufnr }) end end function PromptInput:setup_autocmds() local bufnr = self.bufnr local group = self.augroup api.nvim_create_autocmd({ "TextChanged", "TextChangedI" }, { group = group, buffer = bufnr, callback = function() self:show_shortcuts_hints() end, }) api.nvim_create_autocmd("ModeChanged", { group = group, pattern = { "i:*", "*:i" }, callback = function() local cur_buf = api.nvim_get_current_buf() if cur_buf == bufnr then self:show_shortcuts_hints() end end, }) api.nvim_create_autocmd("QuitPre", { group = group, buffer = bufnr, once = true, nested = true, callback = function() self:cancel() end, }) api.nvim_create_autocmd("WinLeave", { group = group, buffer = bufnr, callback = function() self:cancel() end, }) end return PromptInput
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/selector/init.lua
Lua
local Utils = require("avante.utils") ---@class avante.ui.SelectorItem ---@field id string ---@field title string ---@class avante.ui.SelectorOption ---@field provider avante.SelectorProvider ---@field title string ---@field items avante.ui.SelectorItem[] ---@field default_item_id string | nil ---@field selected_item_ids string[] | nil ---@field provider_opts table | nil ---@field on_select fun(item_ids: string[] | nil) ---@field get_preview_content fun(item_id: string): (string, string) | nil ---@field on_delete_item fun(item_id: string): (nil) | nil ---@field on_open fun(): (nil) | nil ---@class avante.ui.Selector ---@field provider avante.SelectorProvider ---@field title string ---@field items avante.ui.SelectorItem[] ---@field default_item_id string | nil ---@field provider_opts table | nil ---@field on_select fun(item_ids: string[] | nil) ---@field selected_item_ids string[] | nil ---@field get_preview_content fun(item_id: string): (string, string) | nil ---@field on_delete_item fun(item_id: string): (nil) | nil ---@field on_open fun(): (nil) | nil local Selector = {} Selector.__index = Selector ---@param opts avante.ui.SelectorOption function Selector:new(opts) local o = {} setmetatable(o, Selector) o.provider = opts.provider o.title = opts.title o.items = vim .iter(opts.items) :map(function(item) local new_item = vim.deepcopy(item) new_item.title = new_item.title:gsub("\n", " ") return new_item end) :totable() o.default_item_id = opts.default_item_id o.provider_opts = opts.provider_opts or {} o.on_select = opts.on_select o.selected_item_ids = opts.selected_item_ids or {} o.get_preview_content = opts.get_preview_content o.on_delete_item = opts.on_delete_item o.on_open = opts.on_open return o end function Selector:open() if type(self.provider) == "function" then self.provider(self) return end local ok, provider = pcall(require, "avante.ui.selector.providers." .. self.provider) if not ok then Utils.error("Unknown file selector provider: " .. self.provider) end provider.show(self) end return Selector
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform
lua/avante/ui/selector/providers/fzf_lua.lua
Lua
local Utils = require("avante.utils") local M = {} ---@param selector avante.ui.Selector function M.show(selector) local success, fzf_lua = pcall(require, "fzf-lua") if not success then Utils.error("fzf-lua is not installed. Please install fzf-lua to use it as a file selector.") return end local title_to_id = {} for _, item in ipairs(selector.items) do title_to_id[item.title] = item.id end local function close_action() selector.on_select(nil) end fzf_lua.fzf_live( function(args) local query = args[1] or "" local items = {} for _, item in ipairs(vim.iter(selector.items):map(function(item) return item.title end):totable()) do if query == "" or item:match(query:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")) then table.insert(items, item) end end return items end, vim.tbl_deep_extend("force", { prompt = selector.title, preview = selector.get_preview_content and function(item) local id = title_to_id[item[1]] local content = selector.get_preview_content(id) return content end or nil, fzf_opts = { ["--multi"] = true }, git_icons = false, actions = { ["default"] = function(selected) if not selected or #selected == 0 then return close_action() end ---@type string[] local selections = {} for _, entry in ipairs(selected) do local id = title_to_id[entry] if id then table.insert(selections, id) end end selector.on_select(selections) end, ["esc"] = close_action, ["ctrl-c"] = close_action, ["ctrl-delete"] = { fn = function(selected) if not selected or #selected == 0 then return close_action() end local selections = selected vim.ui.input({ prompt = "Remove·selection?·(" .. #selections .. " items) [y/N]" }, function(input) if input and input:lower() == "y" then for _, selection in ipairs(selections) do selector.on_delete_item(title_to_id[selection]) for i, item in ipairs(selector.items) do if item.id == title_to_id[selection] then table.remove(selector.items, i) end end end end end) end, reload = true, }, }, }, selector.provider_opts) ) end return M
yetone/avante.nvim
17,366
Use your Neovim like using Cursor AI IDE!
Lua
yetone
yetone
Isoform