instance.rs

   1use agent::{Message, MessageSegment, ThreadStore};
   2use anyhow::{Context, Result, anyhow, bail};
   3use assistant_tool::ToolWorkingSet;
   4use client::proto::LspWorkProgress;
   5use futures::channel::mpsc;
   6use futures::{FutureExt as _, StreamExt as _, future};
   7use gpui::{App, AppContext as _, AsyncApp, Entity, Task};
   8use handlebars::Handlebars;
   9use language::{Buffer, DiagnosticSeverity, OffsetRangeExt as _};
  10use language_model::{
  11    LanguageModel, LanguageModelCompletionEvent, LanguageModelRequest, LanguageModelRequestMessage,
  12    MessageContent, Role, TokenUsage,
  13};
  14use project::lsp_store::OpenLspBufferHandle;
  15use project::{DiagnosticSummary, Project, ProjectPath};
  16use serde::{Deserialize, Serialize};
  17use std::cell::RefCell;
  18use std::fmt::Write as _;
  19use std::fs;
  20use std::fs::File;
  21use std::io::Write as _;
  22use std::path::Path;
  23use std::path::PathBuf;
  24use std::rc::Rc;
  25use std::sync::Arc;
  26use std::time::Duration;
  27use unindent::Unindent as _;
  28use util::ResultExt as _;
  29use util::command::new_smol_command;
  30use util::markdown::MarkdownCodeBlock;
  31
  32use crate::assertions::{AssertionsReport, RanAssertion, RanAssertionResult};
  33use crate::example::{Example, ExampleContext, FailedAssertion, JudgeAssertion};
  34use crate::{AgentAppState, ToolMetrics};
  35
  36pub const ZED_REPO_URL: &str = "https://github.com/zed-industries/zed.git";
  37
  38#[derive(Clone)]
  39pub struct ExampleInstance {
  40    pub thread: Rc<dyn Example>,
  41    pub name: String,
  42    pub run_directory: PathBuf,
  43    pub log_prefix: String,
  44    /// The repetition number for this example (0-based)
  45    /// When running multiple repetitions of the same example, each instance is assigned a unique repetition number.
  46    /// This affects the worktree path and log prefix to avoid clobbering results between runs.
  47    pub repetition: usize,
  48    pub repo_path: PathBuf,
  49    /// Path to the directory containing the requests and responses for the agentic loop
  50    worktrees_dir: PathBuf,
  51}
  52
  53#[derive(Debug, Serialize, Clone)]
  54pub struct RunOutput {
  55    pub repository_diff: String,
  56    pub diagnostic_summary_before: DiagnosticSummary,
  57    pub diagnostic_summary_after: DiagnosticSummary,
  58    pub diagnostics_before: Option<String>,
  59    pub diagnostics_after: Option<String>,
  60    pub response_count: usize,
  61    pub token_usage: TokenUsage,
  62    pub tool_metrics: ToolMetrics,
  63    pub all_messages: String,
  64    pub programmatic_assertions: AssertionsReport,
  65}
  66
  67#[derive(Debug, Clone, Serialize, Deserialize)]
  68pub struct JudgeDiffInput {
  69    pub repository_diff: String,
  70    pub assertion: String,
  71}
  72
  73#[derive(Debug, Clone, Serialize, Deserialize)]
  74pub struct JudgeThreadInput {
  75    pub messages: String,
  76    pub assertion: String,
  77}
  78
  79#[derive(Debug, Clone, Serialize, Deserialize)]
  80pub struct JudgeOutput {
  81    pub thread: AssertionsReport,
  82    pub diff: AssertionsReport,
  83}
  84
  85impl ExampleInstance {
  86    pub fn new(
  87        thread: Rc<dyn Example>,
  88        repos_dir: &Path,
  89        run_dir: &Path,
  90        worktrees_dir: &Path,
  91        repetition: usize,
  92    ) -> Self {
  93        let name = thread.meta().name.to_string();
  94        let run_directory = run_dir
  95            .join(&name)
  96            .join(repetition.to_string())
  97            .to_path_buf();
  98
  99        let repo_path = repo_path_for_url(repos_dir, &thread.meta().url);
 100
 101        Self {
 102            name,
 103            thread,
 104            log_prefix: String::new(),
 105            run_directory,
 106            repetition,
 107            repo_path,
 108            worktrees_dir: worktrees_dir.to_path_buf(),
 109        }
 110    }
 111
 112    pub fn repo_url(&self) -> String {
 113        self.thread.meta().url
 114    }
 115
 116    pub fn revision(&self) -> String {
 117        self.thread.meta().revision
 118    }
 119
 120    pub fn worktree_name(&self) -> String {
 121        format!("{}-{}", self.name, self.repetition)
 122    }
 123
 124    pub fn set_log_prefix_style(&mut self, color: &str, name_width: usize) {
 125        self.log_prefix = format!(
 126            "{}{:<width$}\x1b[0m | ",
 127            color,
 128            self.worktree_name(),
 129            width = name_width
 130        );
 131    }
 132
 133    /// Set up the example by checking out the specified Git revision
 134    pub async fn fetch(&mut self) -> Result<()> {
 135        let meta = self.thread.meta();
 136
 137        let revision_exists = run_git(
 138            &self.repo_path,
 139            &["rev-parse", &format!("{}^{{commit}}", &meta.revision)],
 140        )
 141        .await
 142        .is_ok();
 143
 144        if !revision_exists {
 145            println!("{}Fetching revision {}", self.log_prefix, &meta.revision);
 146            run_git(
 147                &self.repo_path,
 148                &["fetch", "--depth", "1", "origin", &meta.revision],
 149            )
 150            .await?;
 151        }
 152        Ok(())
 153    }
 154
 155    /// Set up the example by checking out the specified Git revision
 156    pub async fn setup(&mut self) -> Result<()> {
 157        let worktree_path = self.worktree_path();
 158        let meta = self.thread.meta();
 159        if worktree_path.is_dir() {
 160            println!("{}Resetting existing worktree", self.log_prefix);
 161
 162            // TODO: consider including "-x" to remove ignored files. The downside of this is that
 163            // it will also remove build artifacts, and so prevent incremental reuse there.
 164            run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
 165            run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
 166            run_git(&worktree_path, &["checkout", &meta.revision]).await?;
 167        } else {
 168            println!("{}Creating worktree", self.log_prefix);
 169
 170            let worktree_path_string = worktree_path.to_string_lossy().to_string();
 171
 172            run_git(
 173                &self.repo_path,
 174                &[
 175                    "worktree",
 176                    "add",
 177                    "-f",
 178                    &worktree_path_string,
 179                    &meta.revision,
 180                ],
 181            )
 182            .await?;
 183        }
 184
 185        if meta.url == ZED_REPO_URL {
 186            std::fs::write(worktree_path.join(".rules"), std::fs::read(".rules")?)?;
 187        }
 188
 189        std::fs::create_dir_all(&self.run_directory)?;
 190
 191        Ok(())
 192    }
 193
 194    pub fn worktree_path(&self) -> PathBuf {
 195        self.worktrees_dir
 196            .join(self.worktree_name())
 197            .join(self.thread.meta().repo_name())
 198    }
 199
 200    pub fn run(
 201        &self,
 202        model: Arc<dyn LanguageModel>,
 203        app_state: Arc<AgentAppState>,
 204        cx: &mut App,
 205    ) -> Task<Result<RunOutput>> {
 206        let project = Project::local(
 207            app_state.client.clone(),
 208            app_state.node_runtime.clone(),
 209            app_state.user_store.clone(),
 210            app_state.languages.clone(),
 211            app_state.fs.clone(),
 212            None,
 213            cx,
 214        );
 215
 216        let worktree = project.update(cx, |project, cx| {
 217            project.create_worktree(self.worktree_path(), true, cx)
 218        });
 219
 220        let tools = cx.new(|_| ToolWorkingSet::default());
 221        let prompt_store = None;
 222        let thread_store = ThreadStore::load(
 223            project.clone(),
 224            tools,
 225            prompt_store,
 226            app_state.prompt_builder.clone(),
 227            cx,
 228        );
 229        let meta = self.thread.meta();
 230        let this = self.clone();
 231
 232        cx.spawn(async move |cx| {
 233            let worktree = worktree.await?;
 234
 235            // Wait for worktree scan to finish before choosing a file to open.
 236            worktree
 237                .update(cx, |worktree, _cx| {
 238                    worktree.as_local().unwrap().scan_complete()
 239                })?
 240                .await;
 241
 242            struct LanguageServerState {
 243                _lsp_open_handle: OpenLspBufferHandle,
 244                language_file_buffer: Entity<Buffer>,
 245            }
 246
 247            let mut diagnostics_before = None;
 248            let mut diagnostic_summary_before = DiagnosticSummary::default();
 249
 250            let lsp = if let Some(language_server) = &meta.language_server {
 251                // Open a file that matches the language to cause LSP to start.
 252                let language_file = worktree.read_with(cx, |worktree, _cx| {
 253                    worktree
 254                        .files(false, 0)
 255                        .find_map(|e| {
 256                            if e.path.clone().extension().and_then(|ext| ext.to_str())
 257                                == Some(&language_server.file_extension)
 258                            {
 259                                Some(ProjectPath {
 260                                    worktree_id: worktree.id(),
 261                                    path: e.path.clone(),
 262                                })
 263                            } else {
 264                                None
 265                            }
 266                        })
 267                        .context("Failed to find a file for example language")
 268                })??;
 269
 270                let open_language_file_buffer_task = project.update(cx, |project, cx| {
 271                    project.open_buffer(language_file.clone(), cx)
 272                })?;
 273
 274                let language_file_buffer = open_language_file_buffer_task.await?;
 275
 276                let lsp_open_handle = project.update(cx, |project, cx| {
 277                    project.register_buffer_with_language_servers(&language_file_buffer, cx)
 278                })?;
 279
 280                wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
 281
 282                diagnostic_summary_before = project.read_with(cx, |project, cx| {
 283                      project.diagnostic_summary(false, cx)
 284                })?;
 285
 286                diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
 287                if diagnostics_before.is_some() && language_server.allow_preexisting_diagnostics {
 288                    return Err(anyhow!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`"));
 289                }
 290
 291                Some(LanguageServerState {
 292                    _lsp_open_handle: lsp_open_handle,
 293                    language_file_buffer,
 294                })
 295            } else {
 296                None
 297            };
 298
 299            if std::env::var("ZED_EVAL_SETUP_ONLY").is_ok() {
 300                return Err(anyhow!("Setup only mode"));
 301            }
 302
 303            let last_diff_file_path = this.run_directory.join("last.diff");
 304
 305            // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
 306            // history using undo/redo.
 307            std::fs::write(&last_diff_file_path, "")?;
 308
 309            let thread_store = thread_store.await?;
 310            let thread =
 311                thread_store.update(cx, |thread_store, cx| thread_store.create_thread(cx))?;
 312
 313            thread.update(cx, |thread, _cx| {
 314                let mut request_count = 0;
 315                let previous_diff = Rc::new(RefCell::new("".to_string()));
 316                let example_output_dir = this.run_directory.clone();
 317                let last_diff_file_path = last_diff_file_path.clone();
 318                let messages_json_file_path = example_output_dir.join("last.messages.json");
 319                let this = this.clone();
 320                thread.set_request_callback(move |request, response_events| {
 321                    request_count += 1;
 322                    let messages_file_path = example_output_dir.join(format!("{request_count}.messages.md"));
 323                    let diff_file_path = example_output_dir.join(format!("{request_count}.diff"));
 324                    let last_messages_file_path = example_output_dir.join("last.messages.md");
 325                    let request_markdown = RequestMarkdown::new(request);
 326                    let response_events_markdown = response_events_to_markdown(response_events);
 327                    let dialog = ThreadDialog::new(request, response_events);
 328                    let dialog_json = serde_json::to_string_pretty(&dialog.to_combined_request()).unwrap_or_default();
 329
 330                    let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
 331                    fs::write(&messages_file_path, messages.clone()).expect("failed to write messages file");
 332                    fs::write(&last_messages_file_path, messages).expect("failed to write last messages file");
 333                    fs::write(&messages_json_file_path, dialog_json).expect("failed to write last.messages.json");
 334
 335                    let diff_result = smol::block_on(this.repository_diff());
 336                    match diff_result {
 337                        Ok(diff) => {
 338                            if diff != previous_diff.borrow().clone() {
 339                                fs::write(&diff_file_path, &diff).expect("failed to write diff file");
 340                                fs::write(&last_diff_file_path, &diff).expect("failed to write last diff file");
 341                                *previous_diff.borrow_mut() = diff;
 342                            }
 343                        }
 344                        Err(err) => {
 345                            let error_message = format!("{err:?}");
 346                            fs::write(&diff_file_path, &error_message).expect("failed to write diff error to file");
 347                            fs::write(&last_diff_file_path, &error_message).expect("failed to write last diff file");
 348                        }
 349                    }
 350
 351                    if request_count == 1 {
 352                        let tools_file_path = example_output_dir.join("tools.md");
 353                        fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
 354                    }
 355                });
 356            })?;
 357
 358            let mut example_cx = ExampleContext::new(meta.clone(), this.log_prefix.clone(), thread.clone(), model.clone(), cx.clone());
 359            let result = this.thread.conversation(&mut example_cx).await;
 360
 361            if let Err(err) = result {
 362                if !err.is::<FailedAssertion>() {
 363                    return Err(err);
 364                }
 365            }
 366
 367            println!("{}Stopped", this.log_prefix);
 368
 369            println!("{}Getting repository diff", this.log_prefix);
 370            let repository_diff = this.repository_diff().await?;
 371
 372            std::fs::write(last_diff_file_path, &repository_diff)?;
 373
 374
 375            let mut diagnostics_after = None;
 376            let mut diagnostic_summary_after = Default::default();
 377
 378            if let Some(language_server_state) = lsp {
 379                wait_for_lang_server(&project, &language_server_state.language_file_buffer, this.log_prefix.clone(), cx).await?;
 380
 381                println!("{}Getting diagnostics", this.log_prefix);
 382                diagnostics_after = cx
 383                    .update(|cx| {
 384                        let project = project.clone();
 385                        cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
 386                    })?
 387                    .await?;
 388                println!("{}Got diagnostics", this.log_prefix);
 389
 390                diagnostic_summary_after = project.read_with(cx, |project, cx| {
 391                      project.diagnostic_summary(false, cx)
 392                })?;
 393
 394            }
 395
 396            if let Some(diagnostics_before) = &diagnostics_before {
 397                fs::write(this.run_directory.join("diagnostics_before.txt"), diagnostics_before)?;
 398            }
 399
 400            if let Some(diagnostics_after) = &diagnostics_after {
 401                fs::write(this.run_directory.join("diagnostics_after.txt"), diagnostics_after)?;
 402            }
 403
 404            thread.update(cx, |thread, _cx| {
 405                let response_count = thread
 406                    .messages()
 407                    .filter(|message| message.role == language_model::Role::Assistant)
 408                    .count();
 409                RunOutput {
 410                    repository_diff,
 411                    diagnostic_summary_before,
 412                    diagnostic_summary_after,
 413                    diagnostics_before,
 414                    diagnostics_after,
 415                    response_count,
 416                    token_usage: thread.cumulative_token_usage(),
 417                    tool_metrics: example_cx.tool_metrics.lock().unwrap().clone(),
 418                    all_messages: messages_to_markdown(thread.messages()),
 419                    programmatic_assertions: example_cx.assertions,
 420                }
 421            })
 422        })
 423    }
 424
 425    async fn repository_diff(&self) -> Result<String> {
 426        let worktree_path = self.worktree_path();
 427        run_git(&worktree_path, &["add", "."]).await?;
 428        let mut diff_args = vec!["diff", "--staged"];
 429        if self.thread.meta().url == ZED_REPO_URL {
 430            diff_args.push(":(exclude).rules");
 431        }
 432        run_git(&worktree_path, &diff_args).await
 433    }
 434
 435    pub async fn judge(
 436        &self,
 437        model: Arc<dyn LanguageModel>,
 438        run_output: &RunOutput,
 439        cx: &AsyncApp,
 440    ) -> JudgeOutput {
 441        let mut output_file =
 442            File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
 443
 444        let diff_task = self.judge_diff(model.clone(), &run_output, cx);
 445        let thread_task = self.judge_thread(model.clone(), &run_output, cx);
 446
 447        let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
 448
 449        let (diff_response, diff_output) = diff_result;
 450        let (thread_response, thread_output) = thread_result;
 451
 452        writeln!(
 453            &mut output_file,
 454            "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
 455        )
 456        .log_err();
 457
 458        JudgeOutput {
 459            thread: thread_output,
 460            diff: diff_output,
 461        }
 462    }
 463
 464    async fn judge_diff(
 465        &self,
 466        model: Arc<dyn LanguageModel>,
 467        run_output: &RunOutput,
 468        cx: &AsyncApp,
 469    ) -> (String, AssertionsReport) {
 470        let diff_assertions = self.thread.diff_assertions();
 471
 472        if diff_assertions.is_empty() {
 473            return (
 474                "No diff assertions".to_string(),
 475                AssertionsReport::default(),
 476            );
 477        }
 478
 479        println!("{}Running diff judge", self.log_prefix);
 480
 481        let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
 482        let judge_diff_prompt_name = "judge_diff_prompt";
 483        let mut hbs = Handlebars::new();
 484        hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)
 485            .unwrap();
 486
 487        let to_prompt = |assertion: String| {
 488            hbs.render(
 489                judge_diff_prompt_name,
 490                &JudgeDiffInput {
 491                    repository_diff: run_output.repository_diff.clone(),
 492                    assertion,
 493                },
 494            )
 495            .unwrap()
 496        };
 497
 498        let (responses, report) = self
 499            .judge_assertions(model, diff_assertions, to_prompt, cx)
 500            .await;
 501
 502        println!(
 503            "{}Judge - Diff score: {}%",
 504            self.log_prefix,
 505            report.passed_percentage()
 506        );
 507
 508        (responses, report)
 509    }
 510
 511    async fn judge_thread(
 512        &self,
 513        model: Arc<dyn LanguageModel>,
 514        run_output: &RunOutput,
 515        cx: &AsyncApp,
 516    ) -> (String, AssertionsReport) {
 517        let thread_assertions = self.thread.thread_assertions();
 518
 519        if thread_assertions.is_empty() {
 520            return (
 521                "No thread assertions".to_string(),
 522                AssertionsReport::default(),
 523            );
 524        }
 525
 526        let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
 527        let judge_thread_prompt_name = "judge_thread_prompt";
 528        let mut hbs = Handlebars::new();
 529        hbs.register_template_string(judge_thread_prompt_name, judge_thread_prompt)
 530            .unwrap();
 531
 532        let complete_messages = &run_output.all_messages;
 533        let to_prompt = |assertion: String| {
 534            hbs.render(
 535                judge_thread_prompt_name,
 536                &JudgeThreadInput {
 537                    messages: complete_messages.clone(),
 538                    assertion,
 539                },
 540            )
 541            .unwrap()
 542        };
 543
 544        let (responses, report) = self
 545            .judge_assertions(model, thread_assertions, to_prompt, cx)
 546            .await;
 547
 548        println!(
 549            "{}Judge - Thread score: {}%",
 550            self.log_prefix,
 551            report.passed_percentage()
 552        );
 553
 554        (responses, report)
 555    }
 556
 557    async fn judge_assertions(
 558        &self,
 559        model: Arc<dyn LanguageModel>,
 560        assertions: Vec<JudgeAssertion>,
 561        to_prompt: impl Fn(String) -> String,
 562        cx: &AsyncApp,
 563    ) -> (String, AssertionsReport) {
 564        let assertions = assertions.into_iter().map(|assertion| {
 565            let request = LanguageModelRequest {
 566                thread_id: None,
 567                prompt_id: None,
 568                mode: None,
 569                messages: vec![LanguageModelRequestMessage {
 570                    role: Role::User,
 571                    content: vec![MessageContent::Text(to_prompt(assertion.description))],
 572                    cache: false,
 573                }],
 574                temperature: None,
 575                tools: Vec::new(),
 576                stop: Vec::new(),
 577            };
 578
 579            let model = model.clone();
 580            let log_prefix = self.log_prefix.clone();
 581            async move {
 582                let response = send_language_model_request(model, request, cx).await;
 583
 584                let (response, result) = match response {
 585                    Ok(response) => (
 586                        response.clone(),
 587                        parse_assertion_result(&response).map_err(|err| err.to_string()),
 588                    ),
 589                    Err(err) => (err.to_string(), Err(err.to_string())),
 590                };
 591
 592                if result.is_ok() {
 593                    println!("{}{}", log_prefix, assertion.id);
 594                } else {
 595                    println!("{}{}", log_prefix, assertion.id);
 596                }
 597
 598                (
 599                    response,
 600                    RanAssertion {
 601                        id: assertion.id,
 602                        result,
 603                    },
 604                )
 605            }
 606        });
 607
 608        let mut responses = String::new();
 609        let mut report = AssertionsReport::default();
 610
 611        for (response, assertion) in future::join_all(assertions).await {
 612            writeln!(&mut responses, "# {}", assertion.id).unwrap();
 613            writeln!(&mut responses, "{}\n\n", response).unwrap();
 614            report.ran.push(assertion);
 615        }
 616
 617        (responses, report)
 618    }
 619}
 620
 621pub fn wait_for_lang_server(
 622    project: &Entity<Project>,
 623    buffer: &Entity<Buffer>,
 624    log_prefix: String,
 625    cx: &mut AsyncApp,
 626) -> Task<Result<()>> {
 627    if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
 628        return Task::ready(Ok(()));
 629    }
 630
 631    println!("{}⏵ Waiting for language server", log_prefix);
 632
 633    let (mut tx, mut rx) = mpsc::channel(1);
 634
 635    let lsp_store = project
 636        .update(cx, |project, _| project.lsp_store())
 637        .unwrap();
 638
 639    let has_lang_server = buffer
 640        .update(cx, |buffer, cx| {
 641            lsp_store.update(cx, |lsp_store, cx| {
 642                lsp_store
 643                    .language_servers_for_local_buffer(&buffer, cx)
 644                    .next()
 645                    .is_some()
 646            })
 647        })
 648        .unwrap_or(false);
 649
 650    if has_lang_server {
 651        project
 652            .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
 653            .unwrap()
 654            .detach();
 655    }
 656
 657    let subscriptions =
 658        [
 659            cx.subscribe(&lsp_store, {
 660                let log_prefix = log_prefix.clone();
 661                move |_, event, _| match event {
 662                    project::LspStoreEvent::LanguageServerUpdate {
 663                        message:
 664                            client::proto::update_language_server::Variant::WorkProgress(
 665                                LspWorkProgress {
 666                                    message: Some(message),
 667                                    ..
 668                                },
 669                            ),
 670                        ..
 671                    } => println!("{}{message}", log_prefix),
 672                    _ => {}
 673                }
 674            }),
 675            cx.subscribe(&project, {
 676                let buffer = buffer.clone();
 677                move |project, event, cx| match event {
 678                    project::Event::LanguageServerAdded(_, _, _) => {
 679                        let buffer = buffer.clone();
 680                        project
 681                            .update(cx, |project, cx| project.save_buffer(buffer, cx))
 682                            .detach();
 683                    }
 684                    project::Event::DiskBasedDiagnosticsFinished { .. } => {
 685                        tx.try_send(()).ok();
 686                    }
 687                    _ => {}
 688                }
 689            }),
 690        ];
 691
 692    cx.spawn(async move |cx| {
 693        let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
 694        let result = futures::select! {
 695            _ = rx.next() => {
 696                println!("{}⚑ Language server idle", log_prefix);
 697                anyhow::Ok(())
 698            },
 699            _ = timeout.fuse() => {
 700                Err(anyhow!("LSP wait timed out after 5 minutes"))
 701            }
 702        };
 703        drop(subscriptions);
 704        result
 705    })
 706}
 707
 708pub async fn query_lsp_diagnostics(
 709    project: Entity<Project>,
 710    cx: &mut AsyncApp,
 711) -> Result<Option<String>> {
 712    let paths_with_diagnostics = project.update(cx, |project, cx| {
 713        project
 714            .diagnostic_summaries(true, cx)
 715            .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
 716            .map(|(project_path, _, _)| project_path)
 717            .collect::<Vec<_>>()
 718    })?;
 719
 720    if paths_with_diagnostics.is_empty() {
 721        return Ok(None);
 722    }
 723
 724    let mut output = String::new();
 725    for project_path in paths_with_diagnostics {
 726        let buffer = project
 727            .update(cx, |project, cx| project.open_buffer(project_path, cx))?
 728            .await?;
 729        let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
 730
 731        for (_, group) in snapshot.diagnostic_groups(None) {
 732            let entry = &group.entries[group.primary_ix];
 733            let range = entry.range.to_point(&snapshot);
 734            let severity = match entry.diagnostic.severity {
 735                DiagnosticSeverity::ERROR => "error",
 736                DiagnosticSeverity::WARNING => "warning",
 737                _ => continue,
 738            };
 739
 740            writeln!(
 741                output,
 742                "{} at line {}: {}",
 743                severity,
 744                range.start.row + 1,
 745                entry.diagnostic.message
 746            )?;
 747        }
 748    }
 749    anyhow::Ok(Some(output))
 750}
 751
 752fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
 753    let analysis = get_tag("analysis", response)?.to_string();
 754    let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
 755        "true" => true,
 756        "false" => false,
 757        value @ _ => bail!("invalid judge `passed` tag: {value}"),
 758    };
 759    Ok(RanAssertionResult {
 760        analysis: Some(analysis),
 761        passed,
 762    })
 763}
 764
 765fn get_tag(name: &'static str, response: &str) -> Result<String> {
 766    let start_tag = format!("<{}>", name);
 767    let end_tag = format!("</{}>", name);
 768
 769    let start_ix = response
 770        .find(&start_tag)
 771        .context(format!("{} start tag not found", name))?;
 772    let content_start_ix = start_ix + start_tag.len();
 773
 774    let end_ix = content_start_ix
 775        + response[content_start_ix..]
 776            .find(&end_tag)
 777            .context(format!("{} end tag not found", name))?;
 778
 779    let content = response[content_start_ix..end_ix].trim().unindent();
 780
 781    anyhow::Ok(content)
 782}
 783
 784pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
 785    let repo_name = repo_url
 786        .trim_start_matches("https://")
 787        .replace(|c: char| !c.is_alphanumeric(), "-");
 788    Path::new(repos_dir).join(repo_name)
 789}
 790
 791pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
 792    let output = new_smol_command("git")
 793        .current_dir(repo_path)
 794        .args(args)
 795        .output()
 796        .await?;
 797
 798    if output.status.success() {
 799        Ok(String::from_utf8(output.stdout)?.trim().to_string())
 800    } else {
 801        Err(anyhow!(
 802            "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
 803            args.join(" "),
 804            repo_path.display(),
 805            output.status,
 806            String::from_utf8_lossy(&output.stderr),
 807            String::from_utf8_lossy(&output.stdout),
 808        ))
 809    }
 810}
 811
 812fn messages_to_markdown<'a>(message_iter: impl IntoIterator<Item = &'a Message>) -> String {
 813    let mut messages = String::new();
 814    let mut assistant_message_number: u32 = 1;
 815
 816    for message in message_iter {
 817        push_role(&message.role, &mut messages, &mut assistant_message_number);
 818
 819        for segment in &message.segments {
 820            match segment {
 821                MessageSegment::Text(text) => {
 822                    messages.push_str(&text);
 823                    messages.push_str("\n\n");
 824                }
 825                MessageSegment::Thinking { text, signature } => {
 826                    messages.push_str("**Thinking**:\n\n");
 827                    if let Some(sig) = signature {
 828                        messages.push_str(&format!("Signature: {}\n\n", sig));
 829                    }
 830                    messages.push_str(&text);
 831                    messages.push_str("\n");
 832                }
 833                MessageSegment::RedactedThinking(items) => {
 834                    messages.push_str(&format!(
 835                        "**Redacted Thinking**: {} item(s)\n\n",
 836                        items.len()
 837                    ));
 838                }
 839            }
 840        }
 841    }
 842
 843    messages
 844}
 845
 846fn push_role(role: &Role, buf: &mut String, assistant_message_number: &mut u32) {
 847    match role {
 848        Role::System => buf.push_str("# ⚙️ SYSTEM\n\n"),
 849        Role::User => buf.push_str("# 👤 USER\n\n"),
 850        Role::Assistant => {
 851            buf.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
 852            *assistant_message_number = *assistant_message_number + 1;
 853        }
 854    }
 855}
 856
 857pub async fn send_language_model_request(
 858    model: Arc<dyn LanguageModel>,
 859    request: LanguageModelRequest,
 860    cx: &AsyncApp,
 861) -> anyhow::Result<String> {
 862    match model.stream_completion_text(request, &cx).await {
 863        Ok(mut stream) => {
 864            let mut full_response = String::new();
 865            while let Some(chunk_result) = stream.stream.next().await {
 866                match chunk_result {
 867                    Ok(chunk_str) => {
 868                        full_response.push_str(&chunk_str);
 869                    }
 870                    Err(err) => {
 871                        return Err(anyhow!(
 872                            "Error receiving response from language model: {err}"
 873                        ));
 874                    }
 875                }
 876            }
 877            Ok(full_response)
 878        }
 879        Err(err) => Err(anyhow!(
 880            "Failed to get response from language model. Error was: {err}"
 881        )),
 882    }
 883}
 884
 885pub struct RequestMarkdown {
 886    pub tools: String,
 887    pub messages: String,
 888}
 889
 890impl RequestMarkdown {
 891    pub fn new(request: &LanguageModelRequest) -> Self {
 892        let mut tools = String::new();
 893        let mut messages = String::new();
 894        let mut assistant_message_number: u32 = 1;
 895
 896        // Print the tools
 897        if !request.tools.is_empty() {
 898            for tool in &request.tools {
 899                write!(&mut tools, "# {}\n\n", tool.name).unwrap();
 900                write!(&mut tools, "{}\n\n", tool.description).unwrap();
 901                write!(
 902                    &mut tools,
 903                    "{}\n",
 904                    MarkdownCodeBlock {
 905                        tag: "json",
 906                        text: &format!("{:#}", tool.input_schema)
 907                    }
 908                )
 909                .unwrap();
 910            }
 911        }
 912
 913        // Print the messages
 914        for message in &request.messages {
 915            push_role(&message.role, &mut messages, &mut assistant_message_number);
 916
 917            for content in &message.content {
 918                match content {
 919                    MessageContent::Text(text) => {
 920                        messages.push_str(text);
 921                        messages.push_str("\n\n");
 922                    }
 923                    MessageContent::Image(_) => {
 924                        messages.push_str("[IMAGE DATA]\n\n");
 925                    }
 926                    MessageContent::Thinking { text, signature } => {
 927                        messages.push_str("**Thinking**:\n\n");
 928                        if let Some(sig) = signature {
 929                            messages.push_str(&format!("Signature: {}\n\n", sig));
 930                        }
 931                        messages.push_str(text);
 932                        messages.push_str("\n");
 933                    }
 934                    MessageContent::RedactedThinking(items) => {
 935                        messages.push_str(&format!(
 936                            "**Redacted Thinking**: {} item(s)\n\n",
 937                            items.len()
 938                        ));
 939                    }
 940                    MessageContent::ToolUse(tool_use) => {
 941                        messages.push_str(&format!(
 942                            "**Tool Use**: {} (ID: {})\n",
 943                            tool_use.name, tool_use.id
 944                        ));
 945                        messages.push_str(&format!(
 946                            "{}\n",
 947                            MarkdownCodeBlock {
 948                                tag: "json",
 949                                text: &format!("{:#}", tool_use.input)
 950                            }
 951                        ));
 952                    }
 953                    MessageContent::ToolResult(tool_result) => {
 954                        messages.push_str(&format!(
 955                            "**Tool Result**: {} (ID: {})\n\n",
 956                            tool_result.tool_name, tool_result.tool_use_id
 957                        ));
 958                        if tool_result.is_error {
 959                            messages.push_str("**ERROR:**\n");
 960                        }
 961                        messages.push_str(&format!("{}\n\n", tool_result.content));
 962                    }
 963                }
 964            }
 965        }
 966
 967        Self { tools, messages }
 968    }
 969}
 970
 971pub fn response_events_to_markdown(
 972    response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
 973) -> String {
 974    let mut response = String::new();
 975    // Print the response events if any
 976    response.push_str("# Response\n\n");
 977    let mut text_buffer = String::new();
 978    let mut thinking_buffer = String::new();
 979
 980    let flush_buffers =
 981        |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
 982            if !text_buffer.is_empty() {
 983                output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
 984                text_buffer.clear();
 985            }
 986            if !thinking_buffer.is_empty() {
 987                output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
 988                thinking_buffer.clear();
 989            }
 990        };
 991
 992    for event in response_events {
 993        match event {
 994            Ok(LanguageModelCompletionEvent::Text(text)) => {
 995                text_buffer.push_str(text);
 996            }
 997            Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
 998                thinking_buffer.push_str(text);
 999            }
1000            Ok(LanguageModelCompletionEvent::Stop(reason)) => {
1001                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1002                response.push_str(&format!("**Stop**: {:?}\n\n", reason));
1003            }
1004            Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1005                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1006                response.push_str(&format!(
1007                    "**Tool Use**: {} (ID: {})\n",
1008                    tool_use.name, tool_use.id
1009                ));
1010                response.push_str(&format!(
1011                    "{}\n",
1012                    MarkdownCodeBlock {
1013                        tag: "json",
1014                        text: &format!("{:#}", tool_use.input)
1015                    }
1016                ));
1017            }
1018            Ok(
1019                LanguageModelCompletionEvent::UsageUpdate(_)
1020                | LanguageModelCompletionEvent::StartMessage { .. }
1021                | LanguageModelCompletionEvent::StatusUpdate { .. },
1022            ) => {}
1023            Err(error) => {
1024                flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1025                response.push_str(&format!("**Error**: {}\n\n", error));
1026            }
1027        }
1028    }
1029
1030    flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1031
1032    response
1033}
1034
1035#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1036pub struct ThreadDialog {
1037    pub request: LanguageModelRequest,
1038    pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1039}
1040
1041impl ThreadDialog {
1042    pub fn new(
1043        request: &LanguageModelRequest,
1044        response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1045    ) -> Self {
1046        Self {
1047            request: request.clone(),
1048            response_events: response_events.to_vec(),
1049        }
1050    }
1051
1052    /// Represents all request and response messages in a unified format.
1053    ///
1054    /// Specifically, it appends the assistant's response (derived from response events)
1055    /// as a new message to existing messages in the request.
1056    pub fn to_combined_request(&self) -> LanguageModelRequest {
1057        let mut request = self.request.clone();
1058        if let Some(assistant_message) = self.response_events_to_message() {
1059            request.messages.push(assistant_message);
1060        }
1061        request
1062    }
1063    fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1064        let response_events = &self.response_events;
1065        let mut content: Vec<MessageContent> = Vec::new();
1066        let mut current_text = String::new();
1067
1068        let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1069            if !text.is_empty() {
1070                content.push(MessageContent::Text(std::mem::take(text)));
1071            }
1072        };
1073
1074        for event in response_events {
1075            match event {
1076                Ok(LanguageModelCompletionEvent::Text(text)) => {
1077                    current_text.push_str(text);
1078                }
1079
1080                Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1081                    flush_text(&mut current_text, &mut content);
1082                    if tool_use.is_input_complete {
1083                        content.push(MessageContent::ToolUse(tool_use.clone()));
1084                    }
1085                }
1086                Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1087                    flush_text(&mut current_text, &mut content);
1088                    content.push(MessageContent::Thinking {
1089                        text: text.clone(),
1090                        signature: signature.clone(),
1091                    });
1092                }
1093
1094                // Skip these
1095                Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1096                | Ok(LanguageModelCompletionEvent::StatusUpdate { .. })
1097                | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1098                | Ok(LanguageModelCompletionEvent::Stop(_)) => {}
1099
1100                Err(error) => {
1101                    flush_text(&mut current_text, &mut content);
1102                    content.push(MessageContent::Text(format!("ERROR: {}", error)));
1103                }
1104            }
1105        }
1106
1107        flush_text(&mut current_text, &mut content);
1108
1109        if !content.is_empty() {
1110            Some(LanguageModelRequestMessage {
1111                role: Role::Assistant,
1112                content,
1113                cache: false,
1114            })
1115        } else {
1116            None
1117        }
1118    }
1119}
1120
1121#[cfg(test)]
1122mod test {
1123    use super::*;
1124
1125    #[test]
1126    fn test_parse_judge_output() {
1127        let response = r#"
1128            <analysis>The model did a good job but there were still compilations errors.</analysis>
1129            <passed>true</passed>
1130        "#
1131        .unindent();
1132
1133        let output = parse_assertion_result(&response).unwrap();
1134        assert_eq!(
1135            output.analysis,
1136            Some("The model did a good job but there were still compilations errors.".into())
1137        );
1138        assert_eq!(output.passed, true);
1139
1140        let response = r#"
1141            Text around ignored
1142
1143            <analysis>
1144                Failed to compile:
1145                - Error 1
1146                - Error 2
1147            </analysis>
1148
1149            <passed>false</passed>
1150        "#
1151        .unindent();
1152
1153        let output = parse_assertion_result(&response).unwrap();
1154        assert_eq!(
1155            output.analysis,
1156            Some("Failed to compile:\n- Error 1\n- Error 2".into())
1157        );
1158        assert_eq!(output.passed, false);
1159    }
1160}