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