instance.rs

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