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::MarkdownCodeBlock;
  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 prompt_store = None;
 222        let thread_store = ThreadStore::load(
 223            project.clone(),
 224            tools,
 225            prompt_store,
 226            app_state.prompt_builder.clone(),
 227            cx,
 228        );
 229        let meta = self.thread.meta();
 230        let this = self.clone();
 231
 232        cx.spawn(async move |cx| {
 233            let worktree = worktree.await?;
 234
 235            // Wait for worktree scan to finish before choosing a file to open.
 236            worktree
 237                .update(cx, |worktree, _cx| {
 238                    worktree.as_local().unwrap().scan_complete()
 239                })?
 240                .await;
 241
 242            struct LanguageServerState {
 243                _lsp_open_handle: OpenLspBufferHandle,
 244                language_file_buffer: Entity<Buffer>,
 245            }
 246
 247            let mut diagnostics_before = None;
 248            let mut diagnostic_summary_before = DiagnosticSummary::default();
 249
 250            let lsp = if let Some(language_server) = &meta.language_server {
 251                // Open a file that matches the language to cause LSP to start.
 252                let language_file = worktree.read_with(cx, |worktree, _cx| {
 253                    worktree
 254                        .files(false, 0)
 255                        .find_map(|e| {
 256                            if e.path.clone().extension().and_then(|ext| ext.to_str())
 257                                == Some(&language_server.file_extension)
 258                            {
 259                                Some(ProjectPath {
 260                                    worktree_id: worktree.id(),
 261                                    path: e.path.clone(),
 262                                })
 263                            } else {
 264                                None
 265                            }
 266                        })
 267                        .context("Failed to find a file for example language")
 268                })??;
 269
 270                let open_language_file_buffer_task = project.update(cx, |project, cx| {
 271                    project.open_buffer(language_file.clone(), cx)
 272                })?;
 273
 274                let language_file_buffer = open_language_file_buffer_task.await?;
 275
 276                let lsp_open_handle = project.update(cx, |project, cx| {
 277                    project.register_buffer_with_language_servers(&language_file_buffer, cx)
 278                })?;
 279
 280                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 281
 282                diagnostic_summary_before = project.read_with(cx, |project, cx| {
 283                      project.diagnostic_summary(false, cx)
 284                })?;
 285
 286                diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
 287                if diagnostics_before.is_some() && language_server.allow_preexisting_diagnostics {
 288                    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`"));
 289                }
 290
 291                Some(LanguageServerState {
 292                    _lsp_open_handle: lsp_open_handle,
 293                    language_file_buffer,
 294                })
 295            } else {
 296                None
 297            };
 298
 299            if std::env::var("ZED_EVAL_SETUP_ONLY").is_ok() {
 300                return Err(anyhow!("Setup only mode"));
 301            }
 302
 303            let last_diff_file_path = this.run_directory.join("last.diff");
 304
 305            // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
 306            // history using undo/redo.
 307            std::fs::write(&last_diff_file_path, "")?;
 308
 309            let thread_store = thread_store.await?;
 310            let thread =
 311                thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
 312            let last_request = Rc::new(RefCell::new(None));
 313
 314            thread.update(cx, |thread, _cx| {
 315                let mut request_count = 0;
 316                let last_request = Rc::clone(&last_request);
 317                let previous_diff = Rc::new(RefCell::new("".to_string()));
 318                let example_output_dir = this.run_directory.clone();
 319                let last_diff_file_path = last_diff_file_path.clone();
 320                let messages_json_file_path = example_output_dir.join("last.messages.json");
 321                let this = this.clone();
 322                thread.set_request_callback(move |request, response_events| {
 323                    *last_request.borrow_mut() = Some(request.clone());
 324
 325                    request_count += 1;
 326                    let messages_file_path = example_output_dir.join(format!("{request_count}.messages.md"));
 327                    let diff_file_path = example_output_dir.join(format!("{request_count}.diff"));
 328                    let last_messages_file_path = example_output_dir.join("last.messages.md");
 329                    let request_markdown = RequestMarkdown::new(request);
 330                    let response_events_markdown = response_events_to_markdown(response_events);
 331                    let dialog = ThreadDialog::new(request, response_events);
 332                    let dialog_json = serde_json::to_string_pretty(&dialog.to_combined_request()).unwrap_or_default();
 333
 334                    let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
 335                    fs::write(&messages_file_path, messages.clone()).expect("failed to write messages file");
 336                    fs::write(&last_messages_file_path, messages).expect("failed to write last messages file");
 337                    fs::write(&messages_json_file_path, dialog_json).expect("failed to write last.messages.json");
 338
 339                    let diff_result = smol::block_on(this.repository_diff());
 340                    match diff_result {
 341                        Ok(diff) => {
 342                            if diff != previous_diff.borrow().clone() {
 343                                fs::write(&diff_file_path, &diff).expect("failed to write diff file");
 344                                fs::write(&last_diff_file_path, &diff).expect("failed to write last diff file");
 345                                *previous_diff.borrow_mut() = diff;
 346                            }
 347                        }
 348                        Err(err) => {
 349                            let error_message = format!("{err:?}");
 350                            fs::write(&diff_file_path, &error_message).expect("failed to write diff error to file");
 351                            fs::write(&last_diff_file_path, &error_message).expect("failed to write last diff file");
 352                        }
 353                    }
 354
 355                    if request_count == 1 {
 356                        let tools_file_path = example_output_dir.join("tools.md");
 357                        fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
 358                    }
 359                });
 360            })?;
 361
 362            let mut example_cx = ExampleContext::new(meta.clone(), this.log_prefix.clone(), thread.clone(), model.clone(), cx.clone());
 363            let result = this.thread.conversation(&mut example_cx).await;
 364
 365            if let Err(err) = result {
 366                if !err.is::<FailedAssertion>() {
 367                    return Err(err);
 368                }
 369            }
 370
 371            println!("{}Stopped", this.log_prefix);
 372
 373            println!("{}Getting repository diff", this.log_prefix);
 374            let repository_diff = this.repository_diff().await?;
 375
 376            std::fs::write(last_diff_file_path, &repository_diff)?;
 377
 378
 379            let mut diagnostics_after = None;
 380            let mut diagnostic_summary_after = Default::default();
 381
 382            if let Some(language_server_state) = lsp {
 383                wait_for_lang_server(&project, &language_server_state.language_file_buffer, this.log_prefix.clone(), cx).await?;
 384
 385                println!("{}Getting diagnostics", this.log_prefix);
 386                diagnostics_after = cx
 387                    .update(|cx| {
 388                        let project = project.clone();
 389                        cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
 390                    })?
 391                    .await?;
 392                println!("{}Got diagnostics", this.log_prefix);
 393
 394                diagnostic_summary_after = project.read_with(cx, |project, cx| {
 395                      project.diagnostic_summary(false, cx)
 396                })?;
 397
 398            }
 399
 400            let Some(last_request) = last_request.borrow_mut().take() else {
 401                return Err(anyhow!("No requests ran."));
 402            };
 403
 404            if let Some(diagnostics_before) = &diagnostics_before {
 405                fs::write(this.run_directory.join("diagnostics_before.txt"), diagnostics_before)?;
 406            }
 407
 408            if let Some(diagnostics_after) = &diagnostics_after {
 409                fs::write(this.run_directory.join("diagnostics_after.txt"), diagnostics_after)?;
 410            }
 411
 412            thread.update(cx, |thread, _cx| {
 413                let response_count = thread
 414                    .messages()
 415                    .filter(|message| message.role == language_model::Role::Assistant)
 416                    .count();
 417                RunOutput {
 418                    repository_diff,
 419                    diagnostic_summary_before,
 420                    diagnostic_summary_after,
 421                    diagnostics_before,
 422                    diagnostics_after,
 423                    response_count,
 424                    token_usage: thread.cumulative_token_usage(),
 425                    tool_metrics: example_cx.tool_metrics.lock().unwrap().clone(),
 426                    last_request,
 427                    programmatic_assertions: example_cx.assertions,
 428                }
 429            })
 430        })
 431    }
 432
 433    async fn repository_diff(&self) -> Result<String> {
 434        let worktree_path = self.worktree_path();
 435        run_git(&worktree_path, &["add", "."]).await?;
 436        let mut diff_args = vec!["diff", "--staged"];
 437        if self.thread.meta().url == ZED_REPO_URL {
 438            diff_args.push(":(exclude).rules");
 439        }
 440        run_git(&worktree_path, &diff_args).await
 441    }
 442
 443    pub async fn judge(
 444        &self,
 445        model: Arc<dyn LanguageModel>,
 446        run_output: &RunOutput,
 447        cx: &AsyncApp,
 448    ) -> JudgeOutput {
 449        let mut output_file =
 450            File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
 451
 452        let diff_task = self.judge_diff(model.clone(), &run_output, cx);
 453        let thread_task = self.judge_thread(model.clone(), &run_output, cx);
 454
 455        let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
 456
 457        let (diff_response, diff_output) = diff_result;
 458        let (thread_response, thread_output) = thread_result;
 459
 460        writeln!(
 461            &mut output_file,
 462            "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
 463        )
 464        .log_err();
 465
 466        JudgeOutput {
 467            thread: thread_output,
 468            diff: diff_output,
 469        }
 470    }
 471
 472    async fn judge_diff(
 473        &self,
 474        model: Arc<dyn LanguageModel>,
 475        run_output: &RunOutput,
 476        cx: &AsyncApp,
 477    ) -> (String, AssertionsReport) {
 478        let diff_assertions = self.thread.diff_assertions();
 479
 480        if diff_assertions.is_empty() {
 481            return (
 482                "No diff assertions".to_string(),
 483                AssertionsReport::default(),
 484            );
 485        }
 486
 487        println!("{}Running diff judge", self.log_prefix);
 488
 489        let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
 490        let judge_diff_prompt_name = "judge_diff_prompt";
 491        let mut hbs = Handlebars::new();
 492        hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)
 493            .unwrap();
 494
 495        let to_prompt = |assertion: String| {
 496            hbs.render(
 497                judge_diff_prompt_name,
 498                &JudgeDiffInput {
 499                    repository_diff: run_output.repository_diff.clone(),
 500                    assertion,
 501                },
 502            )
 503            .unwrap()
 504        };
 505
 506        let (responses, report) = self
 507            .judge_assertions(model, diff_assertions, to_prompt, cx)
 508            .await;
 509
 510        println!(
 511            "{}Judge - Diff score: {}%",
 512            self.log_prefix,
 513            report.passed_percentage()
 514        );
 515
 516        (responses, report)
 517    }
 518
 519    async fn judge_thread(
 520        &self,
 521        model: Arc<dyn LanguageModel>,
 522        run_output: &RunOutput,
 523        cx: &AsyncApp,
 524    ) -> (String, AssertionsReport) {
 525        let thread_assertions = self.thread.thread_assertions();
 526
 527        if thread_assertions.is_empty() {
 528            return (
 529                "No diff assertions".to_string(),
 530                AssertionsReport::default(),
 531            );
 532        }
 533
 534        let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
 535        let judge_diff_prompt_name = "judge_thread_prompt";
 536        let mut hbs = Handlebars::new();
 537        hbs.register_template_string(judge_diff_prompt_name, judge_thread_prompt)
 538            .unwrap();
 539
 540        let request_markdown = RequestMarkdown::new(&run_output.last_request);
 541        let to_prompt = |assertion: String| {
 542            hbs.render(
 543                judge_diff_prompt_name,
 544                &JudgeThreadInput {
 545                    messages: request_markdown.messages.clone(),
 546                    assertion,
 547                },
 548            )
 549            .unwrap()
 550        };
 551
 552        let (responses, report) = self
 553            .judge_assertions(model, thread_assertions, to_prompt, cx)
 554            .await;
 555
 556        println!(
 557            "{}Judge - Thread score: {}%",
 558            self.log_prefix,
 559            report.passed_percentage()
 560        );
 561
 562        (responses, report)
 563    }
 564
 565    async fn judge_assertions(
 566        &self,
 567        model: Arc<dyn LanguageModel>,
 568        assertions: Vec<JudgeAssertion>,
 569        to_prompt: impl Fn(String) -> String,
 570        cx: &AsyncApp,
 571    ) -> (String, AssertionsReport) {
 572        let assertions = assertions.into_iter().map(|assertion| {
 573            let request = LanguageModelRequest {
 574                thread_id: None,
 575                prompt_id: None,
 576                messages: vec![LanguageModelRequestMessage {
 577                    role: Role::User,
 578                    content: vec![MessageContent::Text(to_prompt(assertion.description))],
 579                    cache: false,
 580                }],
 581                temperature: None,
 582                tools: Vec::new(),
 583                stop: Vec::new(),
 584            };
 585
 586            let model = model.clone();
 587            let log_prefix = self.log_prefix.clone();
 588            async move {
 589                let response = send_language_model_request(model, request, cx).await;
 590
 591                let (response, result) = match response {
 592                    Ok(response) => (
 593                        response.clone(),
 594                        parse_assertion_result(&response).map_err(|err| err.to_string()),
 595                    ),
 596                    Err(err) => (err.to_string(), Err(err.to_string())),
 597                };
 598
 599                if result.is_ok() {
 600                    println!("{}{}", log_prefix, assertion.id);
 601                } else {
 602                    println!("{}{}", log_prefix, assertion.id);
 603                }
 604
 605                (
 606                    response,
 607                    RanAssertion {
 608                        id: assertion.id,
 609                        result,
 610                    },
 611                )
 612            }
 613        });
 614
 615        let mut responses = String::new();
 616        let mut report = AssertionsReport::default();
 617
 618        for (response, assertion) in future::join_all(assertions).await {
 619            writeln!(&mut responses, "# {}", assertion.id).unwrap();
 620            writeln!(&mut responses, "{}\n\n", response).unwrap();
 621            report.ran.push(assertion);
 622        }
 623
 624        (responses, report)
 625    }
 626}
 627
 628pub fn wait_for_lang_server(
 629    project: &Entity<Project>,
 630    buffer: &Entity<Buffer>,
 631    log_prefix: String,
 632    cx: &mut AsyncApp,
 633) -> Task<Result<()>> {
 634    if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
 635        return Task::ready(Ok(()));
 636    }
 637
 638    println!("{}⏵ Waiting for language server", log_prefix);
 639
 640    let (mut tx, mut rx) = mpsc::channel(1);
 641
 642    let lsp_store = project
 643        .update(cx, |project, _| project.lsp_store())
 644        .unwrap();
 645
 646    let has_lang_server = buffer
 647        .update(cx, |buffer, cx| {
 648            lsp_store.update(cx, |lsp_store, cx| {
 649                lsp_store
 650                    .language_servers_for_local_buffer(&buffer, cx)
 651                    .next()
 652                    .is_some()
 653            })
 654        })
 655        .unwrap_or(false);
 656
 657    if has_lang_server {
 658        project
 659            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 660            .unwrap()
 661            .detach();
 662    }
 663
 664    let subscriptions =
 665        [
 666            cx.subscribe(&lsp_store, {
 667                let log_prefix = log_prefix.clone();
 668                move |_, event, _| match event {
 669                    project::LspStoreEvent::LanguageServerUpdate {
 670                        message:
 671                            client::proto::update_language_server::Variant::WorkProgress(
 672                                LspWorkProgress {
 673                                    message: Some(message),
 674                                    ..
 675                                },
 676                            ),
 677                        ..
 678                    } => println!("{}{message}", log_prefix),
 679                    _ => {}
 680                }
 681            }),
 682            cx.subscribe(&project, {
 683                let buffer = buffer.clone();
 684                move |project, event, cx| match event {
 685                    project::Event::LanguageServerAdded(_, _, _) => {
 686                        let buffer = buffer.clone();
 687                        project
 688                            .update(cx, |project, cx| project.save_buffer(buffer, cx))
 689                            .detach();
 690                    }
 691                    project::Event::DiskBasedDiagnosticsFinished { .. } => {
 692                        tx.try_send(()).ok();
 693                    }
 694                    _ => {}
 695                }
 696            }),
 697        ];
 698
 699    cx.spawn(async move |cx| {
 700        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 701        let result = futures::select! {
 702            _ = rx.next() => {
 703                println!("{}⚑ Language server idle", log_prefix);
 704                anyhow::Ok(())
 705            },
 706            _ = timeout.fuse() => {
 707                Err(anyhow!("LSP wait timed out after 5 minutes"))
 708            }
 709        };
 710        drop(subscriptions);
 711        result
 712    })
 713}
 714
 715pub async fn query_lsp_diagnostics(
 716    project: Entity<Project>,
 717    cx: &mut AsyncApp,
 718) -> Result<Option<String>> {
 719    let paths_with_diagnostics = project.update(cx, |project, cx| {
 720        project
 721            .diagnostic_summaries(true, cx)
 722            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 723            .map(|(project_path, _, _)| project_path)
 724            .collect::<Vec<_>>()
 725    })?;
 726
 727    if paths_with_diagnostics.is_empty() {
 728        return Ok(None);
 729    }
 730
 731    let mut output = String::new();
 732    for project_path in paths_with_diagnostics {
 733        let buffer = project
 734            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 735            .await?;
 736        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 737
 738        for (_, group) in snapshot.diagnostic_groups(None) {
 739            let entry = &group.entries[group.primary_ix];
 740            let range = entry.range.to_point(&snapshot);
 741            let severity = match entry.diagnostic.severity {
 742                DiagnosticSeverity::ERROR => "error",
 743                DiagnosticSeverity::WARNING => "warning",
 744                _ => continue,
 745            };
 746
 747            writeln!(
 748                output,
 749                "{} at line {}: {}",
 750                severity,
 751                range.start.row + 1,
 752                entry.diagnostic.message
 753            )?;
 754        }
 755    }
 756    anyhow::Ok(Some(output))
 757}
 758
 759fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
 760    let analysis = get_tag("analysis", response)?.to_string();
 761    let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
 762        "true" => true,
 763        "false" => false,
 764        value @ _ => bail!("invalid judge `passed` tag: {value}"),
 765    };
 766    Ok(RanAssertionResult {
 767        analysis: Some(analysis),
 768        passed,
 769    })
 770}
 771
 772fn get_tag(name: &'static str, response: &str) -> Result<String> {
 773    let start_tag = format!("<{}>", name);
 774    let end_tag = format!("</{}>", name);
 775
 776    let start_ix = response
 777        .find(&start_tag)
 778        .context(format!("{} start tag not found", name))?;
 779    let content_start_ix = start_ix + start_tag.len();
 780
 781    let end_ix = content_start_ix
 782        + response[content_start_ix..]
 783            .find(&end_tag)
 784            .context(format!("{} end tag not found", name))?;
 785
 786    let content = response[content_start_ix..end_ix].trim().unindent();
 787
 788    anyhow::Ok(content)
 789}
 790
 791pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
 792    let repo_name = repo_url
 793        .trim_start_matches("https://")
 794        .replace(|c: char| !c.is_alphanumeric(), "-");
 795    Path::new(repos_dir).join(repo_name)
 796}
 797
 798pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
 799    let output = new_smol_command("git")
 800        .current_dir(repo_path)
 801        .args(args)
 802        .output()
 803        .await?;
 804
 805    if output.status.success() {
 806        Ok(String::from_utf8(output.stdout)?.trim().to_string())
 807    } else {
 808        Err(anyhow!(
 809            "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
 810            args.join(" "),
 811            repo_path.display(),
 812            output.status,
 813            String::from_utf8_lossy(&output.stderr),
 814            String::from_utf8_lossy(&output.stdout),
 815        ))
 816    }
 817}
 818
 819pub async fn send_language_model_request(
 820    model: Arc<dyn LanguageModel>,
 821    request: LanguageModelRequest,
 822    cx: &AsyncApp,
 823) -> anyhow::Result<String> {
 824    match model.stream_completion_text(request, &cx).await {
 825        Ok(mut stream) => {
 826            let mut full_response = String::new();
 827            while let Some(chunk_result) = stream.stream.next().await {
 828                match chunk_result {
 829                    Ok(chunk_str) => {
 830                        full_response.push_str(&chunk_str);
 831                    }
 832                    Err(err) => {
 833                        return Err(anyhow!(
 834                            "Error receiving response from language model: {err}"
 835                        ));
 836                    }
 837                }
 838            }
 839            Ok(full_response)
 840        }
 841        Err(err) => Err(anyhow!(
 842            "Failed to get response from language model. Error was: {err}"
 843        )),
 844    }
 845}
 846
 847pub struct RequestMarkdown {
 848    pub tools: String,
 849    pub messages: String,
 850}
 851
 852impl RequestMarkdown {
 853    pub fn new(request: &LanguageModelRequest) -> Self {
 854        let mut tools = String::new();
 855        let mut messages = String::new();
 856        let mut assistant_message_number: u32 = 1;
 857
 858        // Print the tools
 859        if !request.tools.is_empty() {
 860            for tool in &request.tools {
 861                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
 862                write!(&mut tools, "{}\n\n", tool.description).unwrap();
 863                write!(
 864                    &mut tools,
 865                    "{}\n",
 866                    MarkdownCodeBlock {
 867                        tag: "json",
 868                        text: &format!("{:#}", tool.input_schema)
 869                    }
 870                )
 871                .unwrap();
 872            }
 873        }
 874
 875        // Print the messages
 876        for message in &request.messages {
 877            match message.role {
 878                Role::System => messages.push_str("# ⚙️ SYSTEM\n\n"),
 879                Role::User => messages.push_str("# 👤 USER\n\n"),
 880                Role::Assistant => {
 881                    messages.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
 882                    assistant_message_number += 1;
 883                }
 884            };
 885
 886            for content in &message.content {
 887                match content {
 888                    MessageContent::Text(text) => {
 889                        messages.push_str(text);
 890                        messages.push_str("\n\n");
 891                    }
 892                    MessageContent::Image(_) => {
 893                        messages.push_str("[IMAGE DATA]\n\n");
 894                    }
 895                    MessageContent::Thinking { text, signature } => {
 896                        messages.push_str("**Thinking**:\n\n");
 897                        if let Some(sig) = signature {
 898                            messages.push_str(&format!("Signature: {}\n\n", sig));
 899                        }
 900                        messages.push_str(text);
 901                        messages.push_str("\n");
 902                    }
 903                    MessageContent::RedactedThinking(items) => {
 904                        messages.push_str(&format!(
 905                            "**Redacted Thinking**: {} item(s)\n\n",
 906                            items.len()
 907                        ));
 908                    }
 909                    MessageContent::ToolUse(tool_use) => {
 910                        messages.push_str(&format!(
 911                            "**Tool Use**: {} (ID: {})\n",
 912                            tool_use.name, tool_use.id
 913                        ));
 914                        messages.push_str(&format!(
 915                            "{}\n",
 916                            MarkdownCodeBlock {
 917                                tag: "json",
 918                                text: &format!("{:#}", tool_use.input)
 919                            }
 920                        ));
 921                    }
 922                    MessageContent::ToolResult(tool_result) => {
 923                        messages.push_str(&format!(
 924                            "**Tool Result**: {} (ID: {})\n\n",
 925                            tool_result.tool_name, tool_result.tool_use_id
 926                        ));
 927                        if tool_result.is_error {
 928                            messages.push_str("**ERROR:**\n");
 929                        }
 930                        messages.push_str(&format!("{}\n\n", tool_result.content));
 931                    }
 932                }
 933            }
 934        }
 935
 936        Self { tools, messages }
 937    }
 938}
 939
 940pub fn response_events_to_markdown(
 941    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
 942) -> String {
 943    let mut response = String::new();
 944    // Print the response events if any
 945    response.push_str("# Response\n\n");
 946    let mut text_buffer = String::new();
 947    let mut thinking_buffer = String::new();
 948
 949    let flush_buffers =
 950        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
 951            if !text_buffer.is_empty() {
 952                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
 953                text_buffer.clear();
 954            }
 955            if !thinking_buffer.is_empty() {
 956                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
 957                thinking_buffer.clear();
 958            }
 959        };
 960
 961    for event in response_events {
 962        match event {
 963            Ok(LanguageModelCompletionEvent::Text(text)) => {
 964                text_buffer.push_str(text);
 965            }
 966            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
 967                thinking_buffer.push_str(text);
 968            }
 969            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
 970                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 971                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
 972            }
 973            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
 974                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 975                response.push_str(&format!(
 976                    "**Tool Use**: {} (ID: {})\n",
 977                    tool_use.name, tool_use.id
 978                ));
 979                response.push_str(&format!(
 980                    "{}\n",
 981                    MarkdownCodeBlock {
 982                        tag: "json",
 983                        text: &format!("{:#}", tool_use.input)
 984                    }
 985                ));
 986            }
 987            Ok(
 988                LanguageModelCompletionEvent::UsageUpdate(_)
 989                | LanguageModelCompletionEvent::StartMessage { .. },
 990            ) => {}
 991            Err(error) => {
 992                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 993                response.push_str(&format!("**Error**: {}\n\n", error));
 994            }
 995        }
 996    }
 997
 998    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
 999
1000    response
1001}
1002
1003#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1004pub struct ThreadDialog {
1005    pub request: LanguageModelRequest,
1006    pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1007}
1008
1009impl ThreadDialog {
1010    pub fn new(
1011        request: &LanguageModelRequest,
1012        response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1013    ) -> Self {
1014        Self {
1015            request: request.clone(),
1016            response_events: response_events.to_vec(),
1017        }
1018    }
1019
1020    /// Represents all request and response messages in a unified format.
1021    ///
1022    /// Specifically, it appends the assistant's response (derived from response events)
1023    /// as a new message to existing messages in the request.
1024    pub fn to_combined_request(&self) -> LanguageModelRequest {
1025        let mut request = self.request.clone();
1026        if let Some(assistant_message) = self.response_events_to_message() {
1027            request.messages.push(assistant_message);
1028        }
1029        request
1030    }
1031    fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1032        let response_events = &self.response_events;
1033        let mut content: Vec<MessageContent> = Vec::new();
1034        let mut current_text = String::new();
1035
1036        let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1037            if !text.is_empty() {
1038                content.push(MessageContent::Text(std::mem::take(text)));
1039            }
1040        };
1041
1042        for event in response_events {
1043            match event {
1044                Ok(LanguageModelCompletionEvent::Text(text)) => {
1045                    current_text.push_str(text);
1046                }
1047
1048                Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1049                    flush_text(&mut current_text, &mut content);
1050                    if tool_use.is_input_complete {
1051                        content.push(MessageContent::ToolUse(tool_use.clone()));
1052                    }
1053                }
1054                Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1055                    flush_text(&mut current_text, &mut content);
1056                    content.push(MessageContent::Thinking {
1057                        text: text.clone(),
1058                        signature: signature.clone(),
1059                    });
1060                }
1061
1062                // Skip these
1063                Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1064                | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1065                | Ok(LanguageModelCompletionEvent::Stop(_)) => {}
1066
1067                Err(error) => {
1068                    flush_text(&mut current_text, &mut content);
1069                    content.push(MessageContent::Text(format!("ERROR: {}", error)));
1070                }
1071            }
1072        }
1073
1074        flush_text(&mut current_text, &mut content);
1075
1076        if !content.is_empty() {
1077            Some(LanguageModelRequestMessage {
1078                role: Role::Assistant,
1079                content,
1080                cache: false,
1081            })
1082        } else {
1083            None
1084        }
1085    }
1086}
1087
1088#[cfg(test)]
1089mod test {
1090    use super::*;
1091
1092    #[test]
1093    fn test_parse_judge_output() {
1094        let response = r#"
1095            <analysis>The model did a good job but there were still compilations errors.</analysis>
1096            <passed>true</passed>
1097        "#
1098        .unindent();
1099
1100        let output = parse_assertion_result(&response).unwrap();
1101        assert_eq!(
1102            output.analysis,
1103            Some("The model did a good job but there were still compilations errors.".into())
1104        );
1105        assert_eq!(output.passed, true);
1106
1107        let response = r#"
1108            Text around ignored
1109
1110            <analysis>
1111                Failed to compile:
1112                - Error 1
1113                - Error 2
1114            </analysis>
1115
1116            <passed>false</passed>
1117        "#
1118        .unindent();
1119
1120        let output = parse_assertion_result(&response).unwrap();
1121        assert_eq!(
1122            output.analysis,
1123            Some("Failed to compile:\n- Error 1\n- Error 2".into())
1124        );
1125        assert_eq!(output.passed, false);
1126    }
1127}