instance.rs

   1use agent::ThreadStore;
   2use anyhow::{Context, Result, anyhow, bail};
   3use assistant_tool::ToolWorkingSet;
   4use client::proto::LspWorkProgress;
   5use futures::channel::mpsc;
   6use futures::{FutureExt as _, StreamExt as _, future};
   7use gpui::{App, AppContext as _, AsyncApp, Entity, Task};
   8use handlebars::Handlebars;
   9use language::{Buffer, DiagnosticSeverity, OffsetRangeExt as _};
  10use language_model::{
  11    LanguageModel, LanguageModelCompletionEvent, LanguageModelRequest, LanguageModelRequestMessage,
  12    MessageContent, Role, TokenUsage,
  13};
  14use project::lsp_store::OpenLspBufferHandle;
  15use project::{DiagnosticSummary, Project, ProjectPath};
  16use serde::{Deserialize, Serialize};
  17use std::cell::RefCell;
  18use std::fmt::Write as _;
  19use std::fs;
  20use std::fs::File;
  21use std::io::Write as _;
  22use std::path::Path;
  23use std::path::PathBuf;
  24use std::rc::Rc;
  25use std::sync::Arc;
  26use std::time::Duration;
  27use unindent::Unindent as _;
  28use util::ResultExt as _;
  29use util::command::new_smol_command;
  30use util::markdown::MarkdownString;
  31
  32use crate::assertions::{AssertionsReport, RanAssertion, RanAssertionResult};
  33use crate::example::{Example, ExampleContext, FailedAssertion, JudgeAssertion};
  34use crate::{AgentAppState, ToolMetrics};
  35
  36pub const ZED_REPO_URL: &str = "https://github.com/zed-industries/zed.git";
  37
  38#[derive(Clone)]
  39pub struct ExampleInstance {
  40    pub thread: Rc<dyn Example>,
  41    pub name: String,
  42    pub run_directory: PathBuf,
  43    pub log_prefix: String,
  44    /// The repetition number for this example (0-based)
  45    /// When running multiple repetitions of the same example, each instance is assigned a unique repetition number.
  46    /// This affects the worktree path and log prefix to avoid clobbering results between runs.
  47    pub repetition: usize,
  48    pub repo_path: PathBuf,
  49    /// Path to the directory containing the requests and responses for the agentic loop
  50    worktrees_dir: PathBuf,
  51}
  52
  53#[derive(Debug, Serialize, Clone)]
  54pub struct RunOutput {
  55    pub repository_diff: String,
  56    pub diagnostic_summary_before: DiagnosticSummary,
  57    pub diagnostic_summary_after: DiagnosticSummary,
  58    pub diagnostics_before: Option<String>,
  59    pub diagnostics_after: Option<String>,
  60    pub response_count: usize,
  61    pub token_usage: TokenUsage,
  62    pub tool_metrics: ToolMetrics,
  63    pub last_request: LanguageModelRequest,
  64    pub programmatic_assertions: AssertionsReport,
  65}
  66
  67#[derive(Debug, Clone, Serialize, Deserialize)]
  68pub struct JudgeDiffInput {
  69    pub repository_diff: String,
  70    pub assertion: String,
  71}
  72
  73#[derive(Debug, Clone, Serialize, Deserialize)]
  74pub struct JudgeThreadInput {
  75    pub messages: String,
  76    pub assertion: String,
  77}
  78
  79#[derive(Debug, Clone, Serialize, Deserialize)]
  80pub struct JudgeOutput {
  81    pub thread: AssertionsReport,
  82    pub diff: AssertionsReport,
  83}
  84
  85impl ExampleInstance {
  86    pub fn new(
  87        thread: Rc<dyn Example>,
  88        repos_dir: &Path,
  89        run_dir: &Path,
  90        worktrees_dir: &Path,
  91        repetition: usize,
  92    ) -> Self {
  93        let name = thread.meta().name.to_string();
  94        let run_directory = run_dir
  95            .join(&name)
  96            .join(repetition.to_string())
  97            .to_path_buf();
  98
  99        let repo_path = repo_path_for_url(repos_dir, &thread.meta().url);
 100
 101        Self {
 102            name,
 103            thread,
 104            log_prefix: String::new(),
 105            run_directory,
 106            repetition,
 107            repo_path,
 108            worktrees_dir: worktrees_dir.to_path_buf(),
 109        }
 110    }
 111
 112    pub fn repo_url(&self) -> String {
 113        self.thread.meta().url
 114    }
 115
 116    pub fn revision(&self) -> String {
 117        self.thread.meta().revision
 118    }
 119
 120    pub fn worktree_name(&self) -> String {
 121        format!("{}-{}", self.name, self.repetition)
 122    }
 123
 124    pub fn set_log_prefix_style(&mut self, color: &str, name_width: usize) {
 125        self.log_prefix = format!(
 126            "{}{:<width$}\x1b[0m | ",
 127            color,
 128            self.worktree_name(),
 129            width = name_width
 130        );
 131    }
 132
 133    /// Set up the example by checking out the specified Git revision
 134    pub async fn fetch(&mut self) -> Result<()> {
 135        let meta = self.thread.meta();
 136
 137        let revision_exists = run_git(
 138            &self.repo_path,
 139            &["rev-parse", &format!("{}^{{commit}}", &meta.revision)],
 140        )
 141        .await
 142        .is_ok();
 143
 144        if !revision_exists {
 145            println!("{}Fetching revision {}", self.log_prefix, &meta.revision);
 146            run_git(
 147                &self.repo_path,
 148                &["fetch", "--depth", "1", "origin", &meta.revision],
 149            )
 150            .await?;
 151        }
 152        Ok(())
 153    }
 154
 155    /// Set up the example by checking out the specified Git revision
 156    pub async fn setup(&mut self) -> Result<()> {
 157        let worktree_path = self.worktree_path();
 158        let meta = self.thread.meta();
 159        if worktree_path.is_dir() {
 160            println!("{}Resetting existing worktree", self.log_prefix);
 161
 162            // TODO: consider including "-x" to remove ignored files. The downside of this is that
 163            // it will also remove build artifacts, and so prevent incremental reuse there.
 164            run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
 165            run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
 166            run_git(&worktree_path, &["checkout", &meta.revision]).await?;
 167        } else {
 168            println!("{}Creating worktree", self.log_prefix);
 169
 170            let worktree_path_string = worktree_path.to_string_lossy().to_string();
 171
 172            run_git(
 173                &self.repo_path,
 174                &[
 175                    "worktree",
 176                    "add",
 177                    "-f",
 178                    &worktree_path_string,
 179                    &meta.revision,
 180                ],
 181            )
 182            .await?;
 183        }
 184
 185        if meta.url == ZED_REPO_URL {
 186            std::fs::write(worktree_path.join(".rules"), std::fs::read(".rules")?)?;
 187        }
 188
 189        std::fs::create_dir_all(&self.run_directory)?;
 190
 191        Ok(())
 192    }
 193
 194    pub fn worktree_path(&self) -> PathBuf {
 195        self.worktrees_dir
 196            .join(self.worktree_name())
 197            .join(self.thread.meta().repo_name())
 198    }
 199
 200    pub fn run(
 201        &self,
 202        model: Arc<dyn LanguageModel>,
 203        app_state: Arc<AgentAppState>,
 204        cx: &mut App,
 205    ) -> Task<Result<RunOutput>> {
 206        let project = Project::local(
 207            app_state.client.clone(),
 208            app_state.node_runtime.clone(),
 209            app_state.user_store.clone(),
 210            app_state.languages.clone(),
 211            app_state.fs.clone(),
 212            None,
 213            cx,
 214        );
 215
 216        let worktree = project.update(cx, |project, cx| {
 217            project.create_worktree(self.worktree_path(), true, cx)
 218        });
 219
 220        let tools = cx.new(|_| ToolWorkingSet::default());
 221        let thread_store =
 222            ThreadStore::load(project.clone(), tools, app_state.prompt_builder.clone(), cx);
 223        let meta = self.thread.meta();
 224        let this = self.clone();
 225
 226        cx.spawn(async move |cx| {
 227            let worktree = worktree.await?;
 228
 229            // Wait for worktree scan to finish before choosing a file to open.
 230            worktree
 231                .update(cx, |worktree, _cx| {
 232                    worktree.as_local().unwrap().scan_complete()
 233                })?
 234                .await;
 235
 236            struct LanguageServerState {
 237                _lsp_open_handle: OpenLspBufferHandle,
 238                language_file_buffer: Entity<Buffer>,
 239            }
 240
 241            let mut diagnostics_before = None;
 242            let mut diagnostic_summary_before = DiagnosticSummary::default();
 243
 244            let lsp = if let Some(language_server) = &meta.language_server {
 245                // Open a file that matches the language to cause LSP to start.
 246                let language_file = worktree.read_with(cx, |worktree, _cx| {
 247                    worktree
 248                        .files(false, 0)
 249                        .find_map(|e| {
 250                            if e.path.clone().extension().and_then(|ext| ext.to_str())
 251                                == Some(&language_server.file_extension)
 252                            {
 253                                Some(ProjectPath {
 254                                    worktree_id: worktree.id(),
 255                                    path: e.path.clone(),
 256                                })
 257                            } else {
 258                                None
 259                            }
 260                        })
 261                        .context("Failed to find a file for example language")
 262                })??;
 263
 264                let open_language_file_buffer_task = project.update(cx, |project, cx| {
 265                    project.open_buffer(language_file.clone(), cx)
 266                })?;
 267
 268                let language_file_buffer = open_language_file_buffer_task.await?;
 269
 270                let lsp_open_handle = project.update(cx, |project, cx| {
 271                    project.register_buffer_with_language_servers(&language_file_buffer, cx)
 272                })?;
 273
 274                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 275
 276                diagnostic_summary_before = project.read_with(cx, |project, cx| {
 277                      project.diagnostic_summary(false, cx)
 278                })?;
 279
 280                diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
 281                if diagnostics_before.is_some() && language_server.allow_preexisting_diagnostics {
 282                    return Err(anyhow!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`"));
 283                }
 284
 285                Some(LanguageServerState {
 286                    _lsp_open_handle: lsp_open_handle,
 287                    language_file_buffer,
 288                })
 289            } else {
 290                None
 291            };
 292
 293            if std::env::var("ZED_EVAL_SETUP_ONLY").is_ok() {
 294                return Err(anyhow!("Setup only mode"));
 295            }
 296
 297            let last_diff_file_path = this.run_directory.join("last.diff");
 298
 299            // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
 300            // history using undo/redo.
 301            std::fs::write(&last_diff_file_path, "")?;
 302
 303            let thread_store = thread_store.await?;
 304            let thread =
 305                thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
 306            let last_request = Rc::new(RefCell::new(None));
 307
 308            thread.update(cx, |thread, _cx| {
 309                let mut request_count = 0;
 310                let last_request = Rc::clone(&last_request);
 311                let previous_diff = Rc::new(RefCell::new("".to_string()));
 312                let example_output_dir = this.run_directory.clone();
 313                let last_diff_file_path = last_diff_file_path.clone();
 314                let this = this.clone();
 315                thread.set_request_callback(move |request, response_events| {
 316                    *last_request.borrow_mut() = Some(request.clone());
 317
 318                    request_count += 1;
 319                    let messages_file_path = example_output_dir.join(format!("{request_count}.messages.md"));
 320                    let diff_file_path = example_output_dir.join(format!("{request_count}.diff"));
 321                    let last_messages_file_path = example_output_dir.join("last.messages.md");
 322                    let request_markdown = RequestMarkdown::new(request);
 323                    let response_events_markdown = response_events_to_markdown(response_events);
 324
 325                    let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
 326                    fs::write(&messages_file_path, messages.clone()).expect("failed to write messages file");
 327                    fs::write(&last_messages_file_path, messages).expect("failed to write last messages file");
 328
 329                    let diff_result = smol::block_on(this.repository_diff());
 330                    match diff_result {
 331                        Ok(diff) => {
 332                            if diff != previous_diff.borrow().clone() {
 333                                fs::write(&diff_file_path, &diff).expect("failed to write diff file");
 334                                fs::write(&last_diff_file_path, &diff).expect("failed to write last diff file");
 335                                *previous_diff.borrow_mut() = diff;
 336                            }
 337                        }
 338                        Err(err) => {
 339                            let error_message = format!("{err:?}");
 340                            fs::write(&diff_file_path, &error_message).expect("failed to write diff error to file");
 341                            fs::write(&last_diff_file_path, &error_message).expect("failed to write last diff file");
 342                        }
 343                    }
 344
 345                    if request_count == 1 {
 346                        let tools_file_path = example_output_dir.join("tools.md");
 347                        fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
 348                    }
 349                });
 350            })?;
 351
 352            let mut example_cx = ExampleContext::new(meta.clone(), this.log_prefix.clone(), thread.clone(), model.clone(), cx.clone());
 353            let result = this.thread.conversation(&mut example_cx).await;
 354
 355            if let Err(err) = result {
 356                if !err.is::<FailedAssertion>() {
 357                    return Err(err);
 358                }
 359            }
 360
 361            println!("{}Stopped", this.log_prefix);
 362
 363            println!("{}Getting repository diff", this.log_prefix);
 364            let repository_diff = this.repository_diff().await?;
 365
 366            std::fs::write(last_diff_file_path, &repository_diff)?;
 367
 368
 369            let mut diagnostics_after = None;
 370            let mut diagnostic_summary_after = Default::default();
 371
 372            if let Some(language_server_state) = lsp {
 373                wait_for_lang_server(&project, &language_server_state.language_file_buffer, this.log_prefix.clone(), cx).await?;
 374
 375                println!("{}Getting diagnostics", this.log_prefix);
 376                diagnostics_after = cx
 377                    .update(|cx| {
 378                        let project = project.clone();
 379                        cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
 380                    })?
 381                    .await?;
 382                println!("{}Got diagnostics", this.log_prefix);
 383
 384                diagnostic_summary_after = project.read_with(cx, |project, cx| {
 385                      project.diagnostic_summary(false, cx)
 386                })?;
 387
 388            }
 389
 390            let Some(last_request) = last_request.borrow_mut().take() else {
 391                return Err(anyhow!("No requests ran."));
 392            };
 393
 394            if let Some(diagnostics_before) = &diagnostics_before {
 395                fs::write(this.run_directory.join("diagnostics_before.txt"), diagnostics_before)?;
 396            }
 397
 398            if let Some(diagnostics_after) = &diagnostics_after {
 399                fs::write(this.run_directory.join("diagnostics_after.txt"), diagnostics_after)?;
 400            }
 401
 402            thread.update(cx, |thread, _cx| {
 403                let response_count = thread
 404                    .messages()
 405                    .filter(|message| message.role == language_model::Role::Assistant)
 406                    .count();
 407                RunOutput {
 408                    repository_diff,
 409                    diagnostic_summary_before,
 410                    diagnostic_summary_after,
 411                    diagnostics_before,
 412                    diagnostics_after,
 413                    response_count,
 414                    token_usage: thread.cumulative_token_usage(),
 415                    tool_metrics: example_cx.tool_metrics.lock().unwrap().clone(),
 416                    last_request,
 417                    programmatic_assertions: example_cx.assertions,
 418                }
 419            })
 420        })
 421    }
 422
 423    async fn repository_diff(&self) -> Result<String> {
 424        let worktree_path = self.worktree_path();
 425        run_git(&worktree_path, &["add", "."]).await?;
 426        let mut diff_args = vec!["diff", "--staged"];
 427        if self.thread.meta().url == ZED_REPO_URL {
 428            diff_args.push(":(exclude).rules");
 429        }
 430        run_git(&worktree_path, &diff_args).await
 431    }
 432
 433    pub async fn judge(
 434        &self,
 435        model: Arc<dyn LanguageModel>,
 436        run_output: &RunOutput,
 437        cx: &AsyncApp,
 438    ) -> JudgeOutput {
 439        let mut output_file =
 440            File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
 441
 442        let diff_task = self.judge_diff(model.clone(), &run_output, cx);
 443        let thread_task = self.judge_thread(model.clone(), &run_output, cx);
 444
 445        let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
 446
 447        let (diff_response, diff_output) = diff_result;
 448        let (thread_response, thread_output) = thread_result;
 449
 450        writeln!(
 451            &mut output_file,
 452            "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
 453        )
 454        .log_err();
 455
 456        JudgeOutput {
 457            thread: thread_output,
 458            diff: diff_output,
 459        }
 460    }
 461
 462    async fn judge_diff(
 463        &self,
 464        model: Arc<dyn LanguageModel>,
 465        run_output: &RunOutput,
 466        cx: &AsyncApp,
 467    ) -> (String, AssertionsReport) {
 468        let diff_assertions = self.thread.diff_assertions();
 469
 470        if diff_assertions.is_empty() {
 471            return (
 472                "No diff assertions".to_string(),
 473                AssertionsReport::default(),
 474            );
 475        }
 476
 477        println!("{}Running diff judge", self.log_prefix);
 478
 479        let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
 480        let judge_diff_prompt_name = "judge_diff_prompt";
 481        let mut hbs = Handlebars::new();
 482        hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)
 483            .unwrap();
 484
 485        let to_prompt = |assertion: String| {
 486            hbs.render(
 487                judge_diff_prompt_name,
 488                &JudgeDiffInput {
 489                    repository_diff: run_output.repository_diff.clone(),
 490                    assertion,
 491                },
 492            )
 493            .unwrap()
 494        };
 495
 496        let (responses, report) = self
 497            .judge_assertions(model, diff_assertions, to_prompt, cx)
 498            .await;
 499
 500        println!(
 501            "{}Judge - Diff score: {}%",
 502            self.log_prefix,
 503            report.passed_percentage()
 504        );
 505
 506        (responses, report)
 507    }
 508
 509    async fn judge_thread(
 510        &self,
 511        model: Arc<dyn LanguageModel>,
 512        run_output: &RunOutput,
 513        cx: &AsyncApp,
 514    ) -> (String, AssertionsReport) {
 515        let thread_assertions = self.thread.thread_assertions();
 516
 517        if thread_assertions.is_empty() {
 518            return (
 519                "No diff assertions".to_string(),
 520                AssertionsReport::default(),
 521            );
 522        }
 523
 524        let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
 525        let judge_diff_prompt_name = "judge_thread_prompt";
 526        let mut hbs = Handlebars::new();
 527        hbs.register_template_string(judge_diff_prompt_name, judge_thread_prompt)
 528            .unwrap();
 529
 530        let request_markdown = RequestMarkdown::new(&run_output.last_request);
 531        let to_prompt = |assertion: String| {
 532            hbs.render(
 533                judge_diff_prompt_name,
 534                &JudgeThreadInput {
 535                    messages: request_markdown.messages.clone(),
 536                    assertion,
 537                },
 538            )
 539            .unwrap()
 540        };
 541
 542        let (responses, report) = self
 543            .judge_assertions(model, thread_assertions, to_prompt, cx)
 544            .await;
 545
 546        println!(
 547            "{}Judge - Thread score: {}%",
 548            self.log_prefix,
 549            report.passed_percentage()
 550        );
 551
 552        (responses, report)
 553    }
 554
 555    async fn judge_assertions(
 556        &self,
 557        model: Arc<dyn LanguageModel>,
 558        assertions: Vec<JudgeAssertion>,
 559        to_prompt: impl Fn(String) -> String,
 560        cx: &AsyncApp,
 561    ) -> (String, AssertionsReport) {
 562        let assertions = assertions.into_iter().map(|assertion| {
 563            let request = LanguageModelRequest {
 564                thread_id: None,
 565                prompt_id: None,
 566                messages: vec![LanguageModelRequestMessage {
 567                    role: Role::User,
 568                    content: vec![MessageContent::Text(to_prompt(assertion.description))],
 569                    cache: false,
 570                }],
 571                temperature: None,
 572                tools: Vec::new(),
 573                stop: Vec::new(),
 574            };
 575
 576            let model = model.clone();
 577            let log_prefix = self.log_prefix.clone();
 578            async move {
 579                let response = send_language_model_request(model, request, cx).await;
 580
 581                let (response, result) = match response {
 582                    Ok(response) => (
 583                        response.clone(),
 584                        parse_assertion_result(&response).map_err(|err| err.to_string()),
 585                    ),
 586                    Err(err) => (err.to_string(), Err(err.to_string())),
 587                };
 588
 589                if result.is_ok() {
 590                    println!("{}{}", log_prefix, assertion.id);
 591                } else {
 592                    println!("{}{}", log_prefix, assertion.id);
 593                }
 594
 595                (
 596                    response,
 597                    RanAssertion {
 598                        id: assertion.id,
 599                        result,
 600                    },
 601                )
 602            }
 603        });
 604
 605        let mut responses = String::new();
 606        let mut report = AssertionsReport::default();
 607
 608        for (response, assertion) in future::join_all(assertions).await {
 609            writeln!(&mut responses, "# {}", assertion.id).unwrap();
 610            writeln!(&mut responses, "{}\n\n", response).unwrap();
 611            report.ran.push(assertion);
 612        }
 613
 614        (responses, report)
 615    }
 616}
 617
 618pub fn wait_for_lang_server(
 619    project: &Entity<Project>,
 620    buffer: &Entity<Buffer>,
 621    log_prefix: String,
 622    cx: &mut AsyncApp,
 623) -> Task<Result<()>> {
 624    if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
 625        return Task::ready(Ok(()));
 626    }
 627
 628    println!("{}⏵ Waiting for language server", log_prefix);
 629
 630    let (mut tx, mut rx) = mpsc::channel(1);
 631
 632    let lsp_store = project
 633        .update(cx, |project, _| project.lsp_store())
 634        .unwrap();
 635
 636    let has_lang_server = buffer
 637        .update(cx, |buffer, cx| {
 638            lsp_store.update(cx, |lsp_store, cx| {
 639                lsp_store
 640                    .language_servers_for_local_buffer(&buffer, cx)
 641                    .next()
 642                    .is_some()
 643            })
 644        })
 645        .unwrap_or(false);
 646
 647    if has_lang_server {
 648        project
 649            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 650            .unwrap()
 651            .detach();
 652    }
 653
 654    let subscriptions =
 655        [
 656            cx.subscribe(&lsp_store, {
 657                let log_prefix = log_prefix.clone();
 658                move |_, event, _| match event {
 659                    project::LspStoreEvent::LanguageServerUpdate {
 660                        message:
 661                            client::proto::update_language_server::Variant::WorkProgress(
 662                                LspWorkProgress {
 663                                    message: Some(message),
 664                                    ..
 665                                },
 666                            ),
 667                        ..
 668                    } => println!("{}{message}", log_prefix),
 669                    _ => {}
 670                }
 671            }),
 672            cx.subscribe(&project, {
 673                let buffer = buffer.clone();
 674                move |project, event, cx| match event {
 675                    project::Event::LanguageServerAdded(_, _, _) => {
 676                        let buffer = buffer.clone();
 677                        project
 678                            .update(cx, |project, cx| project.save_buffer(buffer, cx))
 679                            .detach();
 680                    }
 681                    project::Event::DiskBasedDiagnosticsFinished { .. } => {
 682                        tx.try_send(()).ok();
 683                    }
 684                    _ => {}
 685                }
 686            }),
 687        ];
 688
 689    cx.spawn(async move |cx| {
 690        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 691        let result = futures::select! {
 692            _ = rx.next() => {
 693                println!("{}⚑ Language server idle", log_prefix);
 694                anyhow::Ok(())
 695            },
 696            _ = timeout.fuse() => {
 697                Err(anyhow!("LSP wait timed out after 5 minutes"))
 698            }
 699        };
 700        drop(subscriptions);
 701        result
 702    })
 703}
 704
 705pub async fn query_lsp_diagnostics(
 706    project: Entity<Project>,
 707    cx: &mut AsyncApp,
 708) -> Result<Option<String>> {
 709    let paths_with_diagnostics = project.update(cx, |project, cx| {
 710        project
 711            .diagnostic_summaries(true, cx)
 712            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 713            .map(|(project_path, _, _)| project_path)
 714            .collect::<Vec<_>>()
 715    })?;
 716
 717    if paths_with_diagnostics.is_empty() {
 718        return Ok(None);
 719    }
 720
 721    let mut output = String::new();
 722    for project_path in paths_with_diagnostics {
 723        let buffer = project
 724            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 725            .await?;
 726        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 727
 728        for (_, group) in snapshot.diagnostic_groups(None) {
 729            let entry = &group.entries[group.primary_ix];
 730            let range = entry.range.to_point(&snapshot);
 731            let severity = match entry.diagnostic.severity {
 732                DiagnosticSeverity::ERROR => "error",
 733                DiagnosticSeverity::WARNING => "warning",
 734                _ => continue,
 735            };
 736
 737            writeln!(
 738                output,
 739                "{} at line {}: {}",
 740                severity,
 741                range.start.row + 1,
 742                entry.diagnostic.message
 743            )?;
 744        }
 745    }
 746    anyhow::Ok(Some(output))
 747}
 748
 749fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
 750    let analysis = get_tag("analysis", response)?.to_string();
 751    let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
 752        "true" => true,
 753        "false" => false,
 754        value @ _ => bail!("invalid judge `passed` tag: {value}"),
 755    };
 756    Ok(RanAssertionResult {
 757        analysis: Some(analysis),
 758        passed,
 759    })
 760}
 761
 762fn get_tag(name: &'static str, response: &str) -> Result<String> {
 763    let start_tag = format!("<{}>", name);
 764    let end_tag = format!("</{}>", name);
 765
 766    let start_ix = response
 767        .find(&start_tag)
 768        .context(format!("{} start tag not found", name))?;
 769    let content_start_ix = start_ix + start_tag.len();
 770
 771    let end_ix = content_start_ix
 772        + response[content_start_ix..]
 773            .find(&end_tag)
 774            .context(format!("{} end tag not found", name))?;
 775
 776    let content = response[content_start_ix..end_ix].trim().unindent();
 777
 778    anyhow::Ok(content)
 779}
 780
 781pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
 782    let repo_name = repo_url
 783        .trim_start_matches("https://")
 784        .replace(|c: char| !c.is_alphanumeric(), "-");
 785    Path::new(repos_dir).join(repo_name)
 786}
 787
 788pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
 789    let output = new_smol_command("git")
 790        .current_dir(repo_path)
 791        .args(args)
 792        .output()
 793        .await?;
 794
 795    if output.status.success() {
 796        Ok(String::from_utf8(output.stdout)?.trim().to_string())
 797    } else {
 798        Err(anyhow!(
 799            "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
 800            args.join(" "),
 801            repo_path.display(),
 802            output.status,
 803            String::from_utf8_lossy(&output.stderr),
 804            String::from_utf8_lossy(&output.stdout),
 805        ))
 806    }
 807}
 808
 809pub async fn send_language_model_request(
 810    model: Arc<dyn LanguageModel>,
 811    request: LanguageModelRequest,
 812    cx: &AsyncApp,
 813) -> anyhow::Result<String> {
 814    match model.stream_completion_text(request, &cx).await {
 815        Ok(mut stream) => {
 816            let mut full_response = String::new();
 817            while let Some(chunk_result) = stream.stream.next().await {
 818                match chunk_result {
 819                    Ok(chunk_str) => {
 820                        full_response.push_str(&chunk_str);
 821                    }
 822                    Err(err) => {
 823                        return Err(anyhow!(
 824                            "Error receiving response from language model: {err}"
 825                        ));
 826                    }
 827                }
 828            }
 829            Ok(full_response)
 830        }
 831        Err(err) => Err(anyhow!(
 832            "Failed to get response from language model. Error was: {err}"
 833        )),
 834    }
 835}
 836
 837pub struct RequestMarkdown {
 838    pub tools: String,
 839    pub messages: String,
 840}
 841
 842impl RequestMarkdown {
 843    pub fn new(request: &LanguageModelRequest) -> Self {
 844        let mut tools = String::new();
 845        let mut messages = String::new();
 846        let mut assistant_message_number: u32 = 1;
 847
 848        // Print the tools
 849        if !request.tools.is_empty() {
 850            for tool in &request.tools {
 851                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
 852                write!(&mut tools, "{}\n\n", tool.description).unwrap();
 853                write!(
 854                    &mut tools,
 855                    "{}\n",
 856                    MarkdownString::code_block("json", &format!("{:#}", tool.input_schema))
 857                )
 858                .unwrap();
 859            }
 860        }
 861
 862        // Print the messages
 863        for message in &request.messages {
 864            match message.role {
 865                Role::System => messages.push_str("# ⚙️ SYSTEM\n\n"),
 866                Role::User => messages.push_str("# 👤 USER\n\n"),
 867                Role::Assistant => {
 868                    messages.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
 869                    assistant_message_number += 1;
 870                }
 871            };
 872
 873            for content in &message.content {
 874                match content {
 875                    MessageContent::Text(text) => {
 876                        messages.push_str(text);
 877                        messages.push_str("\n\n");
 878                    }
 879                    MessageContent::Image(_) => {
 880                        messages.push_str("[IMAGE DATA]\n\n");
 881                    }
 882                    MessageContent::Thinking { text, signature } => {
 883                        messages.push_str("**Thinking**:\n\n");
 884                        if let Some(sig) = signature {
 885                            messages.push_str(&format!("Signature: {}\n\n", sig));
 886                        }
 887                        messages.push_str(text);
 888                        messages.push_str("\n");
 889                    }
 890                    MessageContent::RedactedThinking(items) => {
 891                        messages.push_str(&format!(
 892                            "**Redacted Thinking**: {} item(s)\n\n",
 893                            items.len()
 894                        ));
 895                    }
 896                    MessageContent::ToolUse(tool_use) => {
 897                        messages.push_str(&format!(
 898                            "**Tool Use**: {} (ID: {})\n",
 899                            tool_use.name, tool_use.id
 900                        ));
 901                        messages.push_str(&format!(
 902                            "{}\n",
 903                            MarkdownString::code_block("json", &format!("{:#}", tool_use.input))
 904                        ));
 905                    }
 906                    MessageContent::ToolResult(tool_result) => {
 907                        messages.push_str(&format!(
 908                            "**Tool Result**: {} (ID: {})\n\n",
 909                            tool_result.tool_name, tool_result.tool_use_id
 910                        ));
 911                        if tool_result.is_error {
 912                            messages.push_str("**ERROR:**\n");
 913                        }
 914                        messages.push_str(&format!("{}\n\n", tool_result.content));
 915                    }
 916                }
 917            }
 918        }
 919
 920        Self { tools, messages }
 921    }
 922}
 923
 924pub fn response_events_to_markdown(
 925    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
 926) -> String {
 927    let mut response = String::new();
 928    // Print the response events if any
 929    response.push_str("# Response\n\n");
 930    let mut text_buffer = String::new();
 931    let mut thinking_buffer = String::new();
 932
 933    let flush_buffers =
 934        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
 935            if !text_buffer.is_empty() {
 936                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
 937                text_buffer.clear();
 938            }
 939            if !thinking_buffer.is_empty() {
 940                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
 941                thinking_buffer.clear();
 942            }
 943        };
 944
 945    for event in response_events {
 946        match event {
 947            Ok(LanguageModelCompletionEvent::Text(text)) => {
 948                text_buffer.push_str(text);
 949            }
 950            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
 951                thinking_buffer.push_str(text);
 952            }
 953            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
 954                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 955                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
 956            }
 957            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 958                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 959                response.push_str(&format!(
 960                    "**Tool Use**: {} (ID: {})\n",
 961                    tool_use.name, tool_use.id
 962                ));
 963                response.push_str(&format!(
 964                    "{}\n",
 965                    MarkdownString::code_block("json", &format!("{:#}", tool_use.input))
 966                ));
 967            }
 968            Ok(
 969                LanguageModelCompletionEvent::UsageUpdate(_)
 970                | LanguageModelCompletionEvent::StartMessage { .. },
 971            ) => {}
 972            Err(error) => {
 973                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 974                response.push_str(&format!("**Error**: {}\n\n", error));
 975            }
 976        }
 977    }
 978
 979    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 980
 981    response
 982}
 983
 984#[cfg(test)]
 985mod test {
 986    use super::*;
 987
 988    #[test]
 989    fn test_parse_judge_output() {
 990        let response = r#"
 991            <analysis>The model did a good job but there were still compilations errors.</analysis>
 992            <passed>true</passed>
 993        "#
 994        .unindent();
 995
 996        let output = parse_assertion_result(&response).unwrap();
 997        assert_eq!(
 998            output.analysis,
 999            Some("The model did a good job but there were still compilations errors.".into())
1000        );
1001        assert_eq!(output.passed, true);
1002
1003        let response = r#"
1004            Text around ignored
1005
1006            <analysis>
1007                Failed to compile:
1008                - Error 1
1009                - Error 2
1010            </analysis>
1011
1012            <passed>false</passed>
1013        "#
1014        .unindent();
1015
1016        let output = parse_assertion_result(&response).unwrap();
1017        assert_eq!(
1018            output.analysis,
1019            Some("Failed to compile:\n- Error 1\n- Error 2".into())
1020        );
1021        assert_eq!(output.passed, false);
1022    }
1023}