instance.rs

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