assistant_tool.rs

  1mod tool_registry;
  2mod tool_working_set;
  3
  4use anyhow::Result;
  5use collections::{HashMap, HashSet};
  6use gpui::{App, Context, Entity, SharedString, Task};
  7use language::Buffer;
  8use language_model::LanguageModelRequestMessage;
  9use project::Project;
 10use std::fmt::{self, Debug, Formatter};
 11use std::sync::Arc;
 12
 13pub use crate::tool_registry::*;
 14pub use crate::tool_working_set::*;
 15
 16pub fn init(cx: &mut App) {
 17    ToolRegistry::default_global(cx);
 18}
 19
 20#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
 21pub enum ToolSource {
 22    /// A native tool built-in to Zed.
 23    Native,
 24    /// A tool provided by a context server.
 25    ContextServer { id: SharedString },
 26}
 27
 28/// A tool that can be used by a language model.
 29pub trait Tool: 'static + Send + Sync {
 30    /// Returns the name of the tool.
 31    fn name(&self) -> String;
 32
 33    /// Returns the description of the tool.
 34    fn description(&self) -> String;
 35
 36    /// Returns the source of the tool.
 37    fn source(&self) -> ToolSource {
 38        ToolSource::Native
 39    }
 40
 41    /// Returns true iff the tool needs the users's confirmation
 42    /// before having permission to run.
 43    fn needs_confirmation(&self) -> bool;
 44
 45    /// Returns the JSON schema that describes the tool's input.
 46    fn input_schema(&self) -> serde_json::Value {
 47        serde_json::Value::Object(serde_json::Map::default())
 48    }
 49
 50    /// Returns markdown to be displayed in the UI for this tool.
 51    fn ui_text(&self, input: &serde_json::Value) -> String;
 52
 53    /// Runs the tool with the provided input.
 54    fn run(
 55        self: Arc<Self>,
 56        input: serde_json::Value,
 57        messages: &[LanguageModelRequestMessage],
 58        project: Entity<Project>,
 59        action_log: Entity<ActionLog>,
 60        cx: &mut App,
 61    ) -> Task<Result<String>>;
 62}
 63
 64impl Debug for dyn Tool {
 65    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
 66        f.debug_struct("Tool").field("name", &self.name()).finish()
 67    }
 68}
 69
 70/// Tracks actions performed by tools in a thread
 71#[derive(Debug)]
 72pub struct ActionLog {
 73    /// Buffers that user manually added to the context, and whose content has
 74    /// changed since the model last saw them.
 75    stale_buffers_in_context: HashSet<Entity<Buffer>>,
 76    /// Buffers that we want to notify the model about when they change.
 77    tracked_buffers: HashMap<Entity<Buffer>, TrackedBuffer>,
 78}
 79
 80#[derive(Debug, Default)]
 81struct TrackedBuffer {
 82    version: clock::Global,
 83}
 84
 85impl ActionLog {
 86    /// Creates a new, empty action log.
 87    pub fn new() -> Self {
 88        Self {
 89            stale_buffers_in_context: HashSet::default(),
 90            tracked_buffers: HashMap::default(),
 91        }
 92    }
 93
 94    /// Track a buffer as read, so we can notify the model about user edits.
 95    pub fn buffer_read(&mut self, buffer: Entity<Buffer>, cx: &mut Context<Self>) {
 96        let tracked_buffer = self.tracked_buffers.entry(buffer.clone()).or_default();
 97        tracked_buffer.version = buffer.read(cx).version();
 98    }
 99
100    /// Mark a buffer as edited, so we can refresh it in the context
101    pub fn buffer_edited(&mut self, buffers: HashSet<Entity<Buffer>>, cx: &mut Context<Self>) {
102        for buffer in &buffers {
103            let tracked_buffer = self.tracked_buffers.entry(buffer.clone()).or_default();
104            tracked_buffer.version = buffer.read(cx).version();
105        }
106
107        self.stale_buffers_in_context.extend(buffers);
108    }
109
110    /// Iterate over buffers changed since last read or edited by the model
111    pub fn stale_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a Entity<Buffer>> {
112        self.tracked_buffers
113            .iter()
114            .filter(|(buffer, tracked)| tracked.version != buffer.read(cx).version)
115            .map(|(buffer, _)| buffer)
116    }
117
118    /// Takes and returns the set of buffers pending refresh, clearing internal state.
119    pub fn take_stale_buffers_in_context(&mut self) -> HashSet<Entity<Buffer>> {
120        std::mem::take(&mut self.stale_buffers_in_context)
121    }
122}