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