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(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                intent: None,
 582                messages: vec![LanguageModelRequestMessage {
 583                    role: Role::User,
 584                    content: vec![MessageContent::Text(to_prompt(assertion.description))],
 585                    cache: false,
 586                }],
 587                temperature: None,
 588                tools: Vec::new(),
 589                tool_choice: None,
 590                stop: Vec::new(),
 591            };
 592
 593            let model = model.clone();
 594            let log_prefix = self.log_prefix.clone();
 595            async move {
 596                let response = send_language_model_request(model, request, cx).await;
 597
 598                let (response, result) = match response {
 599                    Ok(response) => (
 600                        response.clone(),
 601                        parse_assertion_result(&response).map_err(|err| err.to_string()),
 602                    ),
 603                    Err(err) => (err.to_string(), Err(err.to_string())),
 604                };
 605
 606                if result.is_ok() {
 607                    println!("{}{}", log_prefix, assertion.id);
 608                } else {
 609                    println!("{}{}", log_prefix, assertion.id);
 610                }
 611
 612                (
 613                    response,
 614                    RanAssertion {
 615                        id: assertion.id,
 616                        result,
 617                    },
 618                )
 619            }
 620        });
 621
 622        let mut responses = String::new();
 623        let mut report = AssertionsReport::default();
 624
 625        for (response, assertion) in future::join_all(assertions).await {
 626            writeln!(&mut responses, "# {}", assertion.id).unwrap();
 627            writeln!(&mut responses, "{}\n\n", response).unwrap();
 628            report.ran.push(assertion);
 629        }
 630
 631        (responses, report)
 632    }
 633}
 634
 635pub fn wait_for_lang_server(
 636    project: &Entity<Project>,
 637    buffer: &Entity<Buffer>,
 638    log_prefix: String,
 639    cx: &mut AsyncApp,
 640) -> Task<Result<()>> {
 641    if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
 642        return Task::ready(Ok(()));
 643    }
 644
 645    println!("{}⏵ Waiting for language server", log_prefix);
 646
 647    let (mut tx, mut rx) = mpsc::channel(1);
 648
 649    let lsp_store = project
 650        .read_with(cx, |project, _| project.lsp_store())
 651        .unwrap();
 652
 653    let has_lang_server = buffer
 654        .update(cx, |buffer, cx| {
 655            lsp_store.update(cx, |lsp_store, cx| {
 656                lsp_store
 657                    .language_servers_for_local_buffer(&buffer, cx)
 658                    .next()
 659                    .is_some()
 660            })
 661        })
 662        .unwrap_or(false);
 663
 664    if has_lang_server {
 665        project
 666            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 667            .unwrap()
 668            .detach();
 669    }
 670
 671    let subscriptions =
 672        [
 673            cx.subscribe(&lsp_store, {
 674                let log_prefix = log_prefix.clone();
 675                move |_, event, _| match event {
 676                    project::LspStoreEvent::LanguageServerUpdate {
 677                        message:
 678                            client::proto::update_language_server::Variant::WorkProgress(
 679                                LspWorkProgress {
 680                                    message: Some(message),
 681                                    ..
 682                                },
 683                            ),
 684                        ..
 685                    } => println!("{}{message}", log_prefix),
 686                    _ => {}
 687                }
 688            }),
 689            cx.subscribe(&project, {
 690                let buffer = buffer.clone();
 691                move |project, event, cx| match event {
 692                    project::Event::LanguageServerAdded(_, _, _) => {
 693                        let buffer = buffer.clone();
 694                        project
 695                            .update(cx, |project, cx| project.save_buffer(buffer, cx))
 696                            .detach();
 697                    }
 698                    project::Event::DiskBasedDiagnosticsFinished { .. } => {
 699                        tx.try_send(()).ok();
 700                    }
 701                    _ => {}
 702                }
 703            }),
 704        ];
 705
 706    cx.spawn(async move |cx| {
 707        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 708        let result = futures::select! {
 709            _ = rx.next() => {
 710                println!("{}⚑ Language server idle", log_prefix);
 711                anyhow::Ok(())
 712            },
 713            _ = timeout.fuse() => {
 714                anyhow::bail!("LSP wait timed out after 5 minutes");
 715            }
 716        };
 717        drop(subscriptions);
 718        result
 719    })
 720}
 721
 722pub async fn query_lsp_diagnostics(
 723    project: Entity<Project>,
 724    cx: &mut AsyncApp,
 725) -> Result<Option<String>> {
 726    let paths_with_diagnostics = project.update(cx, |project, cx| {
 727        project
 728            .diagnostic_summaries(true, cx)
 729            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 730            .map(|(project_path, _, _)| project_path)
 731            .collect::<Vec<_>>()
 732    })?;
 733
 734    if paths_with_diagnostics.is_empty() {
 735        return Ok(None);
 736    }
 737
 738    let mut output = String::new();
 739    for project_path in paths_with_diagnostics {
 740        let buffer = project
 741            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 742            .await?;
 743        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 744
 745        for (_, group) in snapshot.diagnostic_groups(None) {
 746            let entry = &group.entries[group.primary_ix];
 747            let range = entry.range.to_point(&snapshot);
 748            let severity = match entry.diagnostic.severity {
 749                DiagnosticSeverity::ERROR => "error",
 750                DiagnosticSeverity::WARNING => "warning",
 751                _ => continue,
 752            };
 753
 754            writeln!(
 755                output,
 756                "{} at line {}: {}",
 757                severity,
 758                range.start.row + 1,
 759                entry.diagnostic.message
 760            )?;
 761        }
 762    }
 763    anyhow::Ok(Some(output))
 764}
 765
 766fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
 767    let analysis = get_tag("analysis", response)?.to_string();
 768    let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
 769        "true" => true,
 770        "false" => false,
 771        value @ _ => bail!("invalid judge `passed` tag: {value}"),
 772    };
 773    Ok(RanAssertionResult {
 774        analysis: Some(analysis),
 775        passed,
 776    })
 777}
 778
 779fn get_tag(name: &'static str, response: &str) -> Result<String> {
 780    let start_tag = format!("<{}>", name);
 781    let end_tag = format!("</{}>", name);
 782
 783    let start_ix = response
 784        .find(&start_tag)
 785        .context(format!("{} start tag not found", name))?;
 786    let content_start_ix = start_ix + start_tag.len();
 787
 788    let end_ix = content_start_ix
 789        + response[content_start_ix..]
 790            .find(&end_tag)
 791            .context(format!("{} end tag not found", name))?;
 792
 793    let content = response[content_start_ix..end_ix].trim().unindent();
 794
 795    anyhow::Ok(content)
 796}
 797
 798pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
 799    let repo_name = repo_url
 800        .trim_start_matches("https://")
 801        .replace(|c: char| !c.is_alphanumeric(), "-");
 802    Path::new(repos_dir).join(repo_name)
 803}
 804
 805pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
 806    let output = new_smol_command("git")
 807        .current_dir(repo_path)
 808        .args(args)
 809        .output()
 810        .await?;
 811
 812    anyhow::ensure!(
 813        output.status.success(),
 814        "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
 815        args.join(" "),
 816        repo_path.display(),
 817        output.status,
 818        String::from_utf8_lossy(&output.stderr),
 819        String::from_utf8_lossy(&output.stdout),
 820    );
 821    Ok(String::from_utf8(output.stdout)?.trim().to_string())
 822}
 823
 824fn messages_to_markdown<'a>(message_iter: impl IntoIterator<Item = &'a Message>) -> String {
 825    let mut messages = String::new();
 826    let mut assistant_message_number: u32 = 1;
 827
 828    for message in message_iter {
 829        push_role(&message.role, &mut messages, &mut assistant_message_number);
 830
 831        for segment in &message.segments {
 832            match segment {
 833                MessageSegment::Text(text) => {
 834                    messages.push_str(&text);
 835                    messages.push_str("\n\n");
 836                }
 837                MessageSegment::Thinking { text, signature } => {
 838                    messages.push_str("**Thinking**:\n\n");
 839                    if let Some(sig) = signature {
 840                        messages.push_str(&format!("Signature: {}\n\n", sig));
 841                    }
 842                    messages.push_str(&text);
 843                    messages.push_str("\n");
 844                }
 845                MessageSegment::RedactedThinking(items) => {
 846                    messages.push_str(&format!(
 847                        "**Redacted Thinking**: {} item(s)\n\n",
 848                        items.len()
 849                    ));
 850                }
 851            }
 852        }
 853    }
 854
 855    messages
 856}
 857
 858fn push_role(role: &Role, buf: &mut String, assistant_message_number: &mut u32) {
 859    match role {
 860        Role::System => buf.push_str("# ⚙️ SYSTEM\n\n"),
 861        Role::User => buf.push_str("# 👤 USER\n\n"),
 862        Role::Assistant => {
 863            buf.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
 864            *assistant_message_number = *assistant_message_number + 1;
 865        }
 866    }
 867}
 868
 869pub async fn send_language_model_request(
 870    model: Arc<dyn LanguageModel>,
 871    request: LanguageModelRequest,
 872    cx: &AsyncApp,
 873) -> anyhow::Result<String> {
 874    match model.stream_completion_text(request, &cx).await {
 875        Ok(mut stream) => {
 876            let mut full_response = String::new();
 877            while let Some(chunk_result) = stream.stream.next().await {
 878                match chunk_result {
 879                    Ok(chunk_str) => {
 880                        full_response.push_str(&chunk_str);
 881                    }
 882                    Err(err) => {
 883                        anyhow::bail!("Error receiving response from language model: {err}");
 884                    }
 885                }
 886            }
 887            Ok(full_response)
 888        }
 889        Err(err) => Err(anyhow!(
 890            "Failed to get response from language model. Error was: {err}"
 891        )),
 892    }
 893}
 894
 895pub struct RequestMarkdown {
 896    pub tools: String,
 897    pub messages: String,
 898}
 899
 900impl RequestMarkdown {
 901    pub fn new(request: &LanguageModelRequest) -> Self {
 902        let mut tools = String::new();
 903        let mut messages = String::new();
 904        let mut assistant_message_number: u32 = 1;
 905
 906        // Print the tools
 907        if !request.tools.is_empty() {
 908            for tool in &request.tools {
 909                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
 910                write!(&mut tools, "{}\n\n", tool.description).unwrap();
 911                write!(
 912                    &mut tools,
 913                    "{}\n",
 914                    MarkdownCodeBlock {
 915                        tag: "json",
 916                        text: &format!("{:#}", tool.input_schema)
 917                    }
 918                )
 919                .unwrap();
 920            }
 921        }
 922
 923        // Print the messages
 924        for message in &request.messages {
 925            push_role(&message.role, &mut messages, &mut assistant_message_number);
 926
 927            for content in &message.content {
 928                match content {
 929                    MessageContent::Text(text) => {
 930                        messages.push_str(text);
 931                        messages.push_str("\n\n");
 932                    }
 933                    MessageContent::Image(_) => {
 934                        messages.push_str("[IMAGE DATA]\n\n");
 935                    }
 936                    MessageContent::Thinking { text, signature } => {
 937                        messages.push_str("**Thinking**:\n\n");
 938                        if let Some(sig) = signature {
 939                            messages.push_str(&format!("Signature: {}\n\n", sig));
 940                        }
 941                        messages.push_str(text);
 942                        messages.push_str("\n");
 943                    }
 944                    MessageContent::RedactedThinking(items) => {
 945                        messages.push_str(&format!(
 946                            "**Redacted Thinking**: {} item(s)\n\n",
 947                            items.len()
 948                        ));
 949                    }
 950                    MessageContent::ToolUse(tool_use) => {
 951                        messages.push_str(&format!(
 952                            "**Tool Use**: {} (ID: {})\n",
 953                            tool_use.name, tool_use.id
 954                        ));
 955                        messages.push_str(&format!(
 956                            "{}\n",
 957                            MarkdownCodeBlock {
 958                                tag: "json",
 959                                text: &format!("{:#}", tool_use.input)
 960                            }
 961                        ));
 962                    }
 963                    MessageContent::ToolResult(tool_result) => {
 964                        messages.push_str(&format!(
 965                            "**Tool Result**: {} (ID: {})\n\n",
 966                            tool_result.tool_name, tool_result.tool_use_id
 967                        ));
 968                        if tool_result.is_error {
 969                            messages.push_str("**ERROR:**\n");
 970                        }
 971
 972                        match &tool_result.content {
 973                            LanguageModelToolResultContent::Text(text) => {
 974                                writeln!(messages, "{text}\n").ok();
 975                            }
 976                            LanguageModelToolResultContent::Image(image) => {
 977                                writeln!(messages, "![Image](data:base64,{})\n", image.source).ok();
 978                            }
 979                        }
 980
 981                        if let Some(output) = tool_result.output.as_ref() {
 982                            writeln!(
 983                                messages,
 984                                "**Debug Output**:\n\n```json\n{}\n```\n",
 985                                serde_json::to_string_pretty(output).unwrap()
 986                            )
 987                            .unwrap();
 988                        }
 989                    }
 990                }
 991            }
 992        }
 993
 994        Self { tools, messages }
 995    }
 996}
 997
 998pub fn response_events_to_markdown(
 999    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1000) -> String {
1001    let mut response = String::new();
1002    // Print the response events if any
1003    response.push_str("# Response\n\n");
1004    let mut text_buffer = String::new();
1005    let mut thinking_buffer = String::new();
1006
1007    let flush_buffers =
1008        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
1009            if !text_buffer.is_empty() {
1010                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
1011                text_buffer.clear();
1012            }
1013            if !thinking_buffer.is_empty() {
1014                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
1015                thinking_buffer.clear();
1016            }
1017        };
1018
1019    for event in response_events {
1020        match event {
1021            Ok(LanguageModelCompletionEvent::Text(text)) => {
1022                text_buffer.push_str(text);
1023            }
1024            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
1025                thinking_buffer.push_str(text);
1026            }
1027            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
1028                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1029                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
1030            }
1031            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1032                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1033                response.push_str(&format!(
1034                    "**Tool Use**: {} (ID: {})\n",
1035                    tool_use.name, tool_use.id
1036                ));
1037                response.push_str(&format!(
1038                    "{}\n",
1039                    MarkdownCodeBlock {
1040                        tag: "json",
1041                        text: &format!("{:#}", tool_use.input)
1042                    }
1043                ));
1044            }
1045            Ok(
1046                LanguageModelCompletionEvent::UsageUpdate(_)
1047                | LanguageModelCompletionEvent::StartMessage { .. }
1048                | LanguageModelCompletionEvent::StatusUpdate { .. },
1049            ) => {}
1050            Err(error) => {
1051                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1052                response.push_str(&format!("**Error**: {}\n\n", error));
1053            }
1054        }
1055    }
1056
1057    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1058
1059    response
1060}
1061
1062#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1063pub struct ThreadDialog {
1064    pub request: LanguageModelRequest,
1065    pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1066}
1067
1068impl ThreadDialog {
1069    pub fn new(
1070        request: &LanguageModelRequest,
1071        response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1072    ) -> Self {
1073        Self {
1074            request: request.clone(),
1075            response_events: response_events.to_vec(),
1076        }
1077    }
1078
1079    /// Represents all request and response messages in a unified format.
1080    ///
1081    /// Specifically, it appends the assistant's response (derived from response events)
1082    /// as a new message to existing messages in the request.
1083    pub fn to_combined_request(&self) -> LanguageModelRequest {
1084        let mut request = self.request.clone();
1085        if let Some(assistant_message) = self.response_events_to_message() {
1086            request.messages.push(assistant_message);
1087        }
1088        request
1089    }
1090    fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1091        let response_events = &self.response_events;
1092        let mut content: Vec<MessageContent> = Vec::new();
1093        let mut current_text = String::new();
1094
1095        let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1096            if !text.is_empty() {
1097                content.push(MessageContent::Text(std::mem::take(text)));
1098            }
1099        };
1100
1101        for event in response_events {
1102            match event {
1103                Ok(LanguageModelCompletionEvent::Text(text)) => {
1104                    current_text.push_str(text);
1105                }
1106
1107                Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1108                    flush_text(&mut current_text, &mut content);
1109                    if tool_use.is_input_complete {
1110                        content.push(MessageContent::ToolUse(tool_use.clone()));
1111                    }
1112                }
1113                Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1114                    flush_text(&mut current_text, &mut content);
1115                    content.push(MessageContent::Thinking {
1116                        text: text.clone(),
1117                        signature: signature.clone(),
1118                    });
1119                }
1120
1121                // Skip these
1122                Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1123                | Ok(LanguageModelCompletionEvent::StatusUpdate { .. })
1124                | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1125                | Ok(LanguageModelCompletionEvent::Stop(_)) => {}
1126
1127                Err(error) => {
1128                    flush_text(&mut current_text, &mut content);
1129                    content.push(MessageContent::Text(format!("ERROR: {}", error)));
1130                }
1131            }
1132        }
1133
1134        flush_text(&mut current_text, &mut content);
1135
1136        if !content.is_empty() {
1137            Some(LanguageModelRequestMessage {
1138                role: Role::Assistant,
1139                content,
1140                cache: false,
1141            })
1142        } else {
1143            None
1144        }
1145    }
1146}
1147
1148#[cfg(test)]
1149mod test {
1150    use super::*;
1151
1152    #[test]
1153    fn test_parse_judge_output() {
1154        let response = r#"
1155            <analysis>The model did a good job but there were still compilations errors.</analysis>
1156            <passed>true</passed>
1157        "#
1158        .unindent();
1159
1160        let output = parse_assertion_result(&response).unwrap();
1161        assert_eq!(
1162            output.analysis,
1163            Some("The model did a good job but there were still compilations errors.".into())
1164        );
1165        assert_eq!(output.passed, true);
1166
1167        let response = r#"
1168            Text around ignored
1169
1170            <analysis>
1171                Failed to compile:
1172                - Error 1
1173                - Error 2
1174            </analysis>
1175
1176            <passed>false</passed>
1177        "#
1178        .unindent();
1179
1180        let output = parse_assertion_result(&response).unwrap();
1181        assert_eq!(
1182            output.analysis,
1183            Some("Failed to compile:\n- Error 1\n- Error 2".into())
1184        );
1185        assert_eq!(output.passed, false);
1186    }
1187}