1use agent::ContextServerRegistry;
2use agent_client_protocol as acp;
3use anyhow::{Context as _, Result, anyhow, bail};
4use client::proto::LspWorkProgress;
5use futures::channel::mpsc;
6use futures::future::Shared;
7use futures::{FutureExt as _, StreamExt as _, future};
8use gpui::{App, AppContext as _, AsyncApp, Entity, Task};
9use handlebars::Handlebars;
10use language::{Buffer, DiagnosticSeverity, OffsetRangeExt as _};
11use language_model::{
12 LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
13 LanguageModelRequestMessage, LanguageModelToolResultContent, MessageContent, Role, TokenUsage,
14};
15use project::{DiagnosticSummary, Project, ProjectPath, lsp_store::OpenLspBufferHandle};
16use prompt_store::{ProjectContext, WorktreeContext};
17use rand::{distr, prelude::*};
18use serde::{Deserialize, Serialize};
19use std::{
20 fmt::Write as _,
21 fs::{self, File},
22 io::Write as _,
23 path::{Path, PathBuf},
24 rc::Rc,
25 sync::{Arc, Mutex},
26 time::Duration,
27};
28use unindent::Unindent as _;
29use util::{ResultExt as _, command::new_smol_command, markdown::MarkdownCodeBlock};
30
31use crate::{
32 AgentAppState, ToolMetrics,
33 assertions::{AssertionsReport, RanAssertion, RanAssertionResult},
34 example::{Example, ExampleContext, FailedAssertion, JudgeAssertion},
35};
36
37pub const ZED_REPO_URL: &str = "https://github.com/zed-industries/zed.git";
38
39#[derive(Clone)]
40pub struct ExampleInstance {
41 pub thread: Rc<dyn Example>,
42 pub name: String,
43 pub run_directory: PathBuf,
44 pub log_prefix: String,
45 /// The repetition number for this example (0-based)
46 /// When running multiple repetitions of the same example, each instance is assigned a unique repetition number.
47 /// This affects the worktree path and log prefix to avoid clobbering results between runs.
48 pub repetition: usize,
49 pub repo_path: PathBuf,
50 /// Path to the directory containing the requests and responses for the agentic loop
51 worktrees_dir: PathBuf,
52}
53
54#[derive(Debug, Serialize, Clone)]
55pub struct RunOutput {
56 pub repository_diff: String,
57 pub diagnostic_summary_before: DiagnosticSummary,
58 pub diagnostic_summary_after: DiagnosticSummary,
59 pub diagnostics_before: Option<String>,
60 pub diagnostics_after: Option<String>,
61 pub token_usage: TokenUsage,
62 pub tool_metrics: ToolMetrics,
63 pub thread_markdown: 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;
94 let run_directory = run_dir.join(&name).join(repetition.to_string());
95
96 let repo_path = repo_path_for_url(repos_dir, &thread.meta().url);
97
98 Self {
99 name,
100 thread,
101 log_prefix: String::new(),
102 run_directory,
103 repetition,
104 repo_path,
105 worktrees_dir: worktrees_dir.to_path_buf(),
106 }
107 }
108
109 pub fn repo_url(&self) -> String {
110 self.thread.meta().url
111 }
112
113 pub fn revision(&self) -> String {
114 self.thread.meta().revision
115 }
116
117 pub fn worktree_name(&self) -> String {
118 format!("{}-{}", self.name, self.repetition)
119 }
120
121 pub fn set_log_prefix_style(&mut self, color: &str, name_width: usize) {
122 self.log_prefix = format!(
123 "{}{:<width$}\x1b[0m | ",
124 color,
125 self.worktree_name(),
126 width = name_width
127 );
128 }
129
130 /// Set up the example by checking out the specified Git revision
131 pub async fn fetch(&mut self) -> Result<()> {
132 let meta = self.thread.meta();
133
134 let revision_exists = run_git(
135 &self.repo_path,
136 &["rev-parse", &format!("{}^{{commit}}", &meta.revision)],
137 )
138 .await
139 .is_ok();
140
141 if !revision_exists {
142 println!("{}Fetching revision {}", self.log_prefix, &meta.revision);
143 run_git(
144 &self.repo_path,
145 &["fetch", "--depth", "1", "origin", &meta.revision],
146 )
147 .await?;
148 }
149 Ok(())
150 }
151
152 /// Set up the example by checking out the specified Git revision
153 pub async fn setup(&mut self) -> Result<()> {
154 let worktree_path = self.worktree_path();
155 let meta = self.thread.meta();
156 if worktree_path.is_dir() {
157 println!("{}Resetting existing worktree", self.log_prefix);
158
159 // TODO: consider including "-x" to remove ignored files. The downside of this is that
160 // it will also remove build artifacts, and so prevent incremental reuse there.
161 run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
162 run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
163 run_git(&worktree_path, &["checkout", &meta.revision]).await?;
164 } else {
165 println!("{}Creating worktree", self.log_prefix);
166
167 let worktree_path_string = worktree_path.to_string_lossy().into_owned();
168
169 run_git(
170 &self.repo_path,
171 &[
172 "worktree",
173 "add",
174 "-f",
175 &worktree_path_string,
176 &meta.revision,
177 ],
178 )
179 .await?;
180 }
181
182 if meta.url == ZED_REPO_URL {
183 std::fs::write(worktree_path.join(".rules"), std::fs::read(".rules")?)?;
184 }
185
186 std::fs::create_dir_all(&self.run_directory)?;
187
188 Ok(())
189 }
190
191 pub fn worktree_path(&self) -> PathBuf {
192 self.worktrees_dir
193 .join(self.worktree_name())
194 .join(self.thread.meta().repo_name())
195 }
196
197 pub fn run(&self, app_state: Arc<AgentAppState>, cx: &mut App) -> Task<Result<RunOutput>> {
198 let project = Project::local(
199 app_state.client.clone(),
200 app_state.node_runtime.clone(),
201 app_state.user_store.clone(),
202 app_state.languages.clone(),
203 app_state.fs.clone(),
204 None,
205 project::LocalProjectFlags {
206 init_worktree_trust: false,
207 ..Default::default()
208 },
209 cx,
210 );
211
212 let worktree = project.update(cx, |project, cx| {
213 project.create_worktree(self.worktree_path(), true, cx)
214 });
215
216 let meta = self.thread.meta();
217 let this = self.clone();
218
219 cx.spawn(async move |cx| {
220 let worktree = worktree.await?;
221
222 // Wait for worktree scan to finish before choosing a file to open.
223 worktree
224 .update(cx, |worktree, _cx| {
225 worktree.as_local().unwrap().scan_complete()
226 })
227 .await;
228
229 struct LanguageServerState {
230 _lsp_open_handle: OpenLspBufferHandle,
231 language_file_buffer: Entity<Buffer>,
232 }
233
234 let mut diagnostics_before = None;
235 let mut diagnostic_summary_before = DiagnosticSummary::default();
236
237 let lsp = if let Some(language_server) = &meta.language_server {
238 // Open a file that matches the language to cause LSP to start.
239 let language_file = worktree
240 .read_with(cx, |worktree, _cx| {
241 worktree
242 .files(false, 0)
243 .find_map(|e| {
244 if e.path.clone().extension()
245 == Some(&language_server.file_extension)
246 {
247 Some(ProjectPath {
248 worktree_id: worktree.id(),
249 path: e.path.clone(),
250 })
251 } else {
252 None
253 }
254 })
255 .context("Failed to find a file for example language")
256 })?;
257
258 let open_language_file_buffer_task = project.update(cx, |project, cx| {
259 project.open_buffer(language_file.clone(), cx)
260 });
261
262 let language_file_buffer = open_language_file_buffer_task.await?;
263
264 let lsp_open_handle = project.update(cx, |project, cx| {
265 project.register_buffer_with_language_servers(&language_file_buffer, cx)
266 });
267
268 wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
269
270 diagnostic_summary_before = project.read_with(cx, |project, cx| {
271 project.diagnostic_summary(false, cx)
272 });
273
274 diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
275 if diagnostics_before.is_some() && language_server.allow_preexisting_diagnostics {
276 anyhow::bail!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`");
277 }
278
279 Some(LanguageServerState {
280 _lsp_open_handle: lsp_open_handle,
281 language_file_buffer,
282 })
283 } else {
284 None
285 };
286
287 anyhow::ensure!(std::env::var("ZED_EVAL_SETUP_ONLY").is_err(), "Setup only mode");
288
289 let last_diff_file_path = this.run_directory.join("last.diff");
290
291 // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
292 // history using undo/redo.
293 std::fs::write(&last_diff_file_path, "")?;
294
295 let thread = cx.update(|cx| {
296 //todo: Do we want to load rules files here?
297 let worktrees = project.read(cx).visible_worktrees(cx).map(|worktree| {
298 let root_name = worktree.read(cx).root_name_str().into();
299 let abs_path = worktree.read(cx).abs_path();
300
301 WorktreeContext {
302 root_name,
303 abs_path,
304 rules_file: None,
305 }
306 }).collect::<Vec<_>>();
307 let project_context = cx.new(|_cx| ProjectContext::new(worktrees, vec![]));
308 let context_server_registry = cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
309
310 let thread = if let Some(json) = &meta.existing_thread_json {
311 let session_id = acp::SessionId::new(
312 rand::rng()
313 .sample_iter(&distr::Alphanumeric)
314 .take(7)
315 .map(char::from)
316 .collect::<String>(),
317 );
318
319 let db_thread = agent::DbThread::from_json(json.as_bytes()).expect("Can't read serialized thread");
320 cx.new(|cx| agent::Thread::from_db(session_id, db_thread, project.clone(), project_context, context_server_registry, agent::Templates::new(), cx))
321 } else {
322 cx.new(|cx| agent::Thread::new(project.clone(), project_context, context_server_registry, agent::Templates::new(), None, cx))
323 };
324
325 thread.update(cx, |thread, cx| {
326 thread.add_default_tools(Rc::new(EvalThreadEnvironment {
327 project: project.clone(),
328 }), cx);
329 thread.set_profile(meta.profile_id.clone(), cx);
330 thread.set_model(
331 LanguageModelInterceptor::new(
332 LanguageModelRegistry::read_global(cx).default_model().expect("Missing model").model.clone(),
333 this.run_directory.clone(),
334 last_diff_file_path.clone(),
335 this.run_directory.join("last.messages.json"),
336 this.worktree_path(),
337 this.repo_url(),
338 ),
339 cx,
340 );
341 });
342
343 thread
344 });
345
346 let mut example_cx = ExampleContext::new(
347 meta.clone(),
348 this.log_prefix.clone(),
349 thread.clone(),
350 cx.clone(),
351 );
352 let result = this.thread.conversation(&mut example_cx).await;
353
354 if let Err(err) = result
355 && !err.is::<FailedAssertion>() {
356 return Err(err);
357 }
358
359 println!("{}Stopped", this.log_prefix);
360
361 println!("{}Getting repository diff", this.log_prefix);
362 let repository_diff = Self::repository_diff(this.worktree_path(), &this.repo_url()).await?;
363
364 std::fs::write(last_diff_file_path, &repository_diff)?;
365
366
367 let mut diagnostics_after = None;
368 let mut diagnostic_summary_after = Default::default();
369
370 if let Some(language_server_state) = lsp {
371 wait_for_lang_server(&project, &language_server_state.language_file_buffer, this.log_prefix.clone(), cx).await?;
372
373 println!("{}Getting diagnostics", this.log_prefix);
374 diagnostics_after = cx
375 .update(|cx| {
376 let project = project.clone();
377 cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
378 })
379 .await?;
380 println!("{}Got diagnostics", this.log_prefix);
381
382 diagnostic_summary_after = project.read_with(cx, |project, cx| {
383 project.diagnostic_summary(false, cx)
384 });
385
386 }
387
388 if let Some(diagnostics_before) = &diagnostics_before {
389 fs::write(this.run_directory.join("diagnostics_before.txt"), diagnostics_before)?;
390 }
391
392 if let Some(diagnostics_after) = &diagnostics_after {
393 fs::write(this.run_directory.join("diagnostics_after.txt"), diagnostics_after)?;
394 }
395
396 Ok(thread.update(cx, |thread, _cx| {
397 RunOutput {
398 repository_diff,
399 diagnostic_summary_before,
400 diagnostic_summary_after,
401 diagnostics_before,
402 diagnostics_after,
403 token_usage: thread.latest_request_token_usage().unwrap(),
404 tool_metrics: example_cx.tool_metrics.lock().unwrap().clone(),
405 thread_markdown: thread.to_markdown(),
406 programmatic_assertions: example_cx.assertions,
407 }
408 }))
409 })
410 }
411
412 async fn repository_diff(repository_path: PathBuf, repository_url: &str) -> Result<String> {
413 run_git(&repository_path, &["add", "."]).await?;
414 let mut diff_args = vec!["diff", "--staged"];
415 if repository_url == ZED_REPO_URL {
416 diff_args.push(":(exclude).rules");
417 }
418 run_git(&repository_path, &diff_args).await
419 }
420
421 pub async fn judge(
422 &self,
423 model: Arc<dyn LanguageModel>,
424 run_output: &RunOutput,
425 cx: &AsyncApp,
426 ) -> JudgeOutput {
427 let mut output_file =
428 File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
429
430 let diff_task = self.judge_diff(model.clone(), run_output, cx);
431 let thread_task = self.judge_thread(model.clone(), run_output, cx);
432
433 let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
434
435 let (diff_response, diff_output) = diff_result;
436 let (thread_response, thread_output) = thread_result;
437
438 writeln!(
439 &mut output_file,
440 "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
441 )
442 .log_err();
443
444 JudgeOutput {
445 thread: thread_output,
446 diff: diff_output,
447 }
448 }
449
450 async fn judge_diff(
451 &self,
452 model: Arc<dyn LanguageModel>,
453 run_output: &RunOutput,
454 cx: &AsyncApp,
455 ) -> (String, AssertionsReport) {
456 let diff_assertions = self.thread.diff_assertions();
457
458 if diff_assertions.is_empty() {
459 return (
460 "No diff assertions".to_string(),
461 AssertionsReport::default(),
462 );
463 }
464
465 println!("{}Running diff judge", self.log_prefix);
466
467 let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
468 let judge_diff_prompt_name = "judge_diff_prompt";
469 let mut hbs = Handlebars::new();
470 hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)
471 .unwrap();
472
473 let to_prompt = |assertion: String| {
474 hbs.render(
475 judge_diff_prompt_name,
476 &JudgeDiffInput {
477 repository_diff: run_output.repository_diff.clone(),
478 assertion,
479 },
480 )
481 .unwrap()
482 };
483
484 let (responses, report) = self
485 .judge_assertions(model, diff_assertions, to_prompt, cx)
486 .await;
487
488 println!(
489 "{}Judge - Diff score: {}%",
490 self.log_prefix,
491 report.passed_percentage()
492 );
493
494 (responses, report)
495 }
496
497 async fn judge_thread(
498 &self,
499 model: Arc<dyn LanguageModel>,
500 run_output: &RunOutput,
501 cx: &AsyncApp,
502 ) -> (String, AssertionsReport) {
503 let thread_assertions = self.thread.thread_assertions();
504
505 if thread_assertions.is_empty() {
506 return (
507 "No thread assertions".to_string(),
508 AssertionsReport::default(),
509 );
510 }
511
512 let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
513 let judge_thread_prompt_name = "judge_thread_prompt";
514 let mut hbs = Handlebars::new();
515 hbs.register_template_string(judge_thread_prompt_name, judge_thread_prompt)
516 .unwrap();
517
518 let complete_messages = &run_output.thread_markdown;
519 let to_prompt = |assertion: String| {
520 hbs.render(
521 judge_thread_prompt_name,
522 &JudgeThreadInput {
523 messages: complete_messages.clone(),
524 assertion,
525 },
526 )
527 .unwrap()
528 };
529
530 let (responses, report) = self
531 .judge_assertions(model, thread_assertions, to_prompt, cx)
532 .await;
533
534 println!(
535 "{}Judge - Thread score: {}%",
536 self.log_prefix,
537 report.passed_percentage()
538 );
539
540 (responses, report)
541 }
542
543 async fn judge_assertions(
544 &self,
545 model: Arc<dyn LanguageModel>,
546 assertions: Vec<JudgeAssertion>,
547 to_prompt: impl Fn(String) -> String,
548 cx: &AsyncApp,
549 ) -> (String, AssertionsReport) {
550 let assertions = assertions.into_iter().map(|assertion| {
551 let request = LanguageModelRequest {
552 thread_id: None,
553 prompt_id: None,
554 intent: None,
555 messages: vec![LanguageModelRequestMessage {
556 role: Role::User,
557 content: vec![MessageContent::Text(to_prompt(assertion.description))],
558 cache: false,
559 reasoning_details: None,
560 }],
561 temperature: None,
562 tools: Vec::new(),
563 tool_choice: None,
564 stop: Vec::new(),
565 thinking_allowed: true,
566 };
567
568 let model = model.clone();
569 let log_prefix = self.log_prefix.clone();
570 async move {
571 let response = send_language_model_request(model, request, cx).await;
572
573 let (response, result) = match response {
574 Ok(response) => (
575 response.clone(),
576 parse_assertion_result(&response).map_err(|err| err.to_string()),
577 ),
578 Err(err) => (err.to_string(), Err(err.to_string())),
579 };
580
581 if result.is_ok() {
582 println!("{}✅ {}", log_prefix, assertion.id);
583 } else {
584 println!("{}❌ {}", log_prefix, assertion.id);
585 }
586
587 (
588 response,
589 RanAssertion {
590 id: assertion.id,
591 result,
592 },
593 )
594 }
595 });
596
597 let mut responses = String::new();
598 let mut report = AssertionsReport::default();
599
600 for (response, assertion) in future::join_all(assertions).await {
601 writeln!(&mut responses, "# {}", assertion.id).unwrap();
602 writeln!(&mut responses, "{}\n\n", response).unwrap();
603 report.ran.push(assertion);
604 }
605
606 (responses, report)
607 }
608}
609
610struct EvalThreadEnvironment {
611 project: Entity<Project>,
612}
613
614struct EvalTerminalHandle {
615 terminal: Entity<acp_thread::Terminal>,
616}
617
618impl agent::TerminalHandle for EvalTerminalHandle {
619 fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
620 Ok(self.terminal.read_with(cx, |term, _cx| term.id().clone()))
621 }
622
623 fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
624 Ok(self
625 .terminal
626 .read_with(cx, |term, _cx| term.wait_for_exit()))
627 }
628
629 fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
630 Ok(self
631 .terminal
632 .read_with(cx, |term, cx| term.current_output(cx)))
633 }
634
635 fn kill(&self, cx: &AsyncApp) -> Result<()> {
636 cx.update(|cx| {
637 self.terminal.update(cx, |terminal, cx| {
638 terminal.kill(cx);
639 });
640 });
641 Ok(())
642 }
643
644 fn was_stopped_by_user(&self, cx: &AsyncApp) -> Result<bool> {
645 Ok(self
646 .terminal
647 .read_with(cx, |term, _cx| term.was_stopped_by_user()))
648 }
649}
650
651impl agent::ThreadEnvironment for EvalThreadEnvironment {
652 fn create_terminal(
653 &self,
654 command: String,
655 cwd: Option<PathBuf>,
656 output_byte_limit: Option<u64>,
657 cx: &mut AsyncApp,
658 ) -> Task<Result<Rc<dyn agent::TerminalHandle>>> {
659 let project = self.project.clone();
660 cx.spawn(async move |cx| {
661 let language_registry =
662 project.read_with(cx, |project, _cx| project.languages().clone());
663 let id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
664 let terminal =
665 acp_thread::create_terminal_entity(command, &[], vec![], cwd.clone(), &project, cx)
666 .await?;
667 let terminal = cx.new(|cx| {
668 acp_thread::Terminal::new(
669 id,
670 "",
671 cwd,
672 output_byte_limit.map(|limit| limit as usize),
673 terminal,
674 language_registry,
675 cx,
676 )
677 });
678 Ok(Rc::new(EvalTerminalHandle { terminal }) as Rc<dyn agent::TerminalHandle>)
679 })
680 }
681}
682
683struct LanguageModelInterceptor {
684 model: Arc<dyn LanguageModel>,
685 request_count: Arc<Mutex<usize>>,
686 previous_diff: Arc<Mutex<String>>,
687 example_output_dir: PathBuf,
688 last_diff_file_path: PathBuf,
689 messages_json_file_path: PathBuf,
690 repository_path: PathBuf,
691 repository_url: String,
692}
693
694impl LanguageModelInterceptor {
695 fn new(
696 model: Arc<dyn LanguageModel>,
697 example_output_dir: PathBuf,
698 last_diff_file_path: PathBuf,
699 messages_json_file_path: PathBuf,
700 repository_path: PathBuf,
701 repository_url: String,
702 ) -> Arc<Self> {
703 Arc::new(Self {
704 model,
705 request_count: Arc::new(Mutex::new(0)),
706 previous_diff: Arc::new(Mutex::new("".to_string())),
707 example_output_dir,
708 last_diff_file_path,
709 messages_json_file_path,
710 repository_path,
711 repository_url,
712 })
713 }
714}
715
716impl language_model::LanguageModel for LanguageModelInterceptor {
717 fn id(&self) -> language_model::LanguageModelId {
718 self.model.id()
719 }
720
721 fn name(&self) -> language_model::LanguageModelName {
722 self.model.name()
723 }
724
725 fn provider_id(&self) -> language_model::LanguageModelProviderId {
726 self.model.provider_id()
727 }
728
729 fn provider_name(&self) -> language_model::LanguageModelProviderName {
730 self.model.provider_name()
731 }
732
733 fn telemetry_id(&self) -> String {
734 self.model.telemetry_id()
735 }
736
737 fn supports_images(&self) -> bool {
738 self.model.supports_images()
739 }
740
741 fn supports_tools(&self) -> bool {
742 self.model.supports_tools()
743 }
744
745 fn supports_tool_choice(&self, choice: language_model::LanguageModelToolChoice) -> bool {
746 self.model.supports_tool_choice(choice)
747 }
748
749 fn max_token_count(&self) -> u64 {
750 self.model.max_token_count()
751 }
752
753 fn count_tokens(
754 &self,
755 request: LanguageModelRequest,
756 cx: &App,
757 ) -> future::BoxFuture<'static, Result<u64>> {
758 self.model.count_tokens(request, cx)
759 }
760
761 fn stream_completion(
762 &self,
763 request: LanguageModelRequest,
764 cx: &AsyncApp,
765 ) -> future::BoxFuture<
766 'static,
767 Result<
768 futures::stream::BoxStream<
769 'static,
770 Result<LanguageModelCompletionEvent, language_model::LanguageModelCompletionError>,
771 >,
772 language_model::LanguageModelCompletionError,
773 >,
774 > {
775 let stream = self.model.stream_completion(request.clone(), cx);
776 let request_count = self.request_count.clone();
777 let previous_diff = self.previous_diff.clone();
778 let example_output_dir = self.example_output_dir.clone();
779 let last_diff_file_path = self.last_diff_file_path.clone();
780 let messages_json_file_path = self.messages_json_file_path.clone();
781 let repository_path = self.repository_path.clone();
782 let repository_url = self.repository_url.clone();
783
784 Box::pin(async move {
785 let stream = stream.await?;
786
787 let response_events = Arc::new(Mutex::new(Vec::new()));
788 let request_clone = request.clone();
789
790 let wrapped_stream = stream.then(move |event| {
791 let response_events = response_events.clone();
792 let request = request_clone.clone();
793 let request_count = request_count.clone();
794 let previous_diff = previous_diff.clone();
795 let example_output_dir = example_output_dir.clone();
796 let last_diff_file_path = last_diff_file_path.clone();
797 let messages_json_file_path = messages_json_file_path.clone();
798 let repository_path = repository_path.clone();
799 let repository_url = repository_url.clone();
800
801 async move {
802 let event_result = match &event {
803 Ok(ev) => Ok(ev.clone()),
804 Err(err) => Err(err.to_string()),
805 };
806 response_events.lock().unwrap().push(event_result);
807
808 let should_execute = matches!(
809 &event,
810 Ok(LanguageModelCompletionEvent::Stop { .. }) | Err(_)
811 );
812
813 if should_execute {
814 let current_request_count = {
815 let mut count = request_count.lock().unwrap();
816 *count += 1;
817 *count
818 };
819
820 let messages_file_path =
821 example_output_dir.join(format!("{current_request_count}.messages.md"));
822 let diff_file_path =
823 example_output_dir.join(format!("{current_request_count}.diff"));
824 let last_messages_file_path = example_output_dir.join("last.messages.md");
825
826 let collected_events = response_events.lock().unwrap().clone();
827 let request_markdown = RequestMarkdown::new(&request);
828 let response_events_markdown =
829 response_events_to_markdown(&collected_events);
830 let dialog = ThreadDialog::new(&request, &collected_events);
831 let dialog_json =
832 serde_json::to_string_pretty(&dialog.to_combined_request())
833 .unwrap_or_default();
834
835 let messages = format!(
836 "{}\n\n{}",
837 request_markdown.messages, response_events_markdown
838 );
839 fs::write(&messages_file_path, messages.clone())
840 .expect("failed to write messages file");
841 fs::write(&last_messages_file_path, messages)
842 .expect("failed to write last messages file");
843 fs::write(&messages_json_file_path, dialog_json)
844 .expect("failed to write last.messages.json");
845
846 // Get repository diff
847 let diff_result =
848 ExampleInstance::repository_diff(repository_path, &repository_url)
849 .await;
850
851 match diff_result {
852 Ok(diff) => {
853 let prev_diff = previous_diff.lock().unwrap().clone();
854 if diff != prev_diff {
855 fs::write(&diff_file_path, &diff)
856 .expect("failed to write diff file");
857 fs::write(&last_diff_file_path, &diff)
858 .expect("failed to write last diff file");
859 *previous_diff.lock().unwrap() = diff;
860 }
861 }
862 Err(err) => {
863 let error_message = format!("{err:?}");
864 fs::write(&diff_file_path, &error_message)
865 .expect("failed to write diff error to file");
866 fs::write(&last_diff_file_path, &error_message)
867 .expect("failed to write last diff file");
868 }
869 }
870
871 if current_request_count == 1 {
872 let tools_file_path = example_output_dir.join("tools.md");
873 fs::write(tools_file_path, request_markdown.tools)
874 .expect("failed to write tools file");
875 }
876 }
877
878 event
879 }
880 });
881
882 Ok(Box::pin(wrapped_stream)
883 as futures::stream::BoxStream<
884 'static,
885 Result<
886 LanguageModelCompletionEvent,
887 language_model::LanguageModelCompletionError,
888 >,
889 >)
890 })
891 }
892}
893
894pub fn wait_for_lang_server(
895 project: &Entity<Project>,
896 buffer: &Entity<Buffer>,
897 log_prefix: String,
898 cx: &mut AsyncApp,
899) -> Task<Result<()>> {
900 if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
901 return Task::ready(Ok(()));
902 }
903
904 println!("{}⏵ Waiting for language server", log_prefix);
905
906 let (mut tx, mut rx) = mpsc::channel(1);
907
908 let lsp_store = project.read_with(cx, |project, _| project.lsp_store());
909
910 let has_lang_server = buffer.update(cx, |buffer, cx| {
911 lsp_store.update(cx, |lsp_store, cx| {
912 lsp_store
913 .running_language_servers_for_local_buffer(buffer, cx)
914 .next()
915 .is_some()
916 })
917 });
918
919 if has_lang_server {
920 project
921 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
922 .detach();
923 }
924
925 let subscriptions =
926 [
927 cx.subscribe(&lsp_store, {
928 let log_prefix = log_prefix.clone();
929 move |_, event, _| {
930 if let project::LspStoreEvent::LanguageServerUpdate {
931 message:
932 client::proto::update_language_server::Variant::WorkProgress(
933 LspWorkProgress {
934 message: Some(message),
935 ..
936 },
937 ),
938 ..
939 } = event
940 {
941 println!("{}⟲ {message}", log_prefix)
942 }
943 }
944 }),
945 cx.subscribe(project, {
946 let buffer = buffer.clone();
947 move |project, event, cx| match event {
948 project::Event::LanguageServerAdded(_, _, _) => {
949 let buffer = buffer.clone();
950 project
951 .update(cx, |project, cx| project.save_buffer(buffer, cx))
952 .detach();
953 }
954 project::Event::DiskBasedDiagnosticsFinished { .. } => {
955 tx.try_send(()).ok();
956 }
957 _ => {}
958 }
959 }),
960 ];
961
962 cx.spawn(async move |cx| {
963 let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
964 let result = futures::select! {
965 _ = rx.next() => {
966 println!("{}⚑ Language server idle", log_prefix);
967 anyhow::Ok(())
968 },
969 _ = timeout.fuse() => {
970 anyhow::bail!("LSP wait timed out after 5 minutes");
971 }
972 };
973 drop(subscriptions);
974 result
975 })
976}
977
978pub async fn query_lsp_diagnostics(
979 project: Entity<Project>,
980 cx: &mut AsyncApp,
981) -> Result<Option<String>> {
982 let paths_with_diagnostics = project.update(cx, |project, cx| {
983 project
984 .diagnostic_summaries(true, cx)
985 .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
986 .map(|(project_path, _, _)| project_path)
987 .collect::<Vec<_>>()
988 });
989
990 if paths_with_diagnostics.is_empty() {
991 return Ok(None);
992 }
993
994 let mut output = String::new();
995 for project_path in paths_with_diagnostics {
996 let buffer = project
997 .update(cx, |project, cx| project.open_buffer(project_path, cx))
998 .await?;
999 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot());
1000
1001 for (_, group) in snapshot.diagnostic_groups(None) {
1002 let entry = &group.entries[group.primary_ix];
1003 let range = entry.range.to_point(&snapshot);
1004 let severity = match entry.diagnostic.severity {
1005 DiagnosticSeverity::ERROR => "error",
1006 DiagnosticSeverity::WARNING => "warning",
1007 _ => continue,
1008 };
1009
1010 writeln!(
1011 output,
1012 "{} at line {}: {}",
1013 severity,
1014 range.start.row + 1,
1015 entry.diagnostic.message
1016 )?;
1017 }
1018 }
1019 anyhow::Ok(Some(output))
1020}
1021
1022fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
1023 let analysis = get_tag("analysis", response)?;
1024 let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
1025 "true" => true,
1026 "false" => false,
1027 value @ _ => bail!("invalid judge `passed` tag: {value}"),
1028 };
1029 Ok(RanAssertionResult {
1030 analysis: Some(analysis),
1031 passed,
1032 })
1033}
1034
1035fn get_tag(name: &'static str, response: &str) -> Result<String> {
1036 let start_tag = format!("<{}>", name);
1037 let end_tag = format!("</{}>", name);
1038
1039 let start_ix = response
1040 .find(&start_tag)
1041 .context(format!("{} start tag not found", name))?;
1042 let content_start_ix = start_ix + start_tag.len();
1043
1044 let end_ix = content_start_ix
1045 + response[content_start_ix..]
1046 .find(&end_tag)
1047 .context(format!("{} end tag not found", name))?;
1048
1049 let content = response[content_start_ix..end_ix].trim().unindent();
1050
1051 anyhow::Ok(content)
1052}
1053
1054pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
1055 let repo_name = repo_url
1056 .trim_start_matches("https://")
1057 .replace(|c: char| !c.is_alphanumeric(), "-");
1058 Path::new(repos_dir).join(repo_name)
1059}
1060
1061pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
1062 let output = new_smol_command("git")
1063 .current_dir(repo_path)
1064 .args(args)
1065 .output()
1066 .await?;
1067
1068 anyhow::ensure!(
1069 output.status.success(),
1070 "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
1071 args.join(" "),
1072 repo_path.display(),
1073 output.status,
1074 String::from_utf8_lossy(&output.stderr),
1075 String::from_utf8_lossy(&output.stdout),
1076 );
1077 Ok(String::from_utf8(output.stdout)?.trim().to_string())
1078}
1079
1080fn push_role(role: &Role, buf: &mut String, assistant_message_number: &mut u32) {
1081 match role {
1082 Role::System => buf.push_str("# ⚙️ SYSTEM\n\n"),
1083 Role::User => buf.push_str("# 👤 USER\n\n"),
1084 Role::Assistant => {
1085 buf.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
1086 *assistant_message_number = *assistant_message_number + 1;
1087 }
1088 }
1089}
1090
1091pub async fn send_language_model_request(
1092 model: Arc<dyn LanguageModel>,
1093 request: LanguageModelRequest,
1094 cx: &AsyncApp,
1095) -> anyhow::Result<String> {
1096 match model.stream_completion_text(request, cx).await {
1097 Ok(mut stream) => {
1098 let mut full_response = String::new();
1099 while let Some(chunk_result) = stream.stream.next().await {
1100 match chunk_result {
1101 Ok(chunk_str) => {
1102 full_response.push_str(&chunk_str);
1103 }
1104 Err(err) => {
1105 anyhow::bail!("Error receiving response from language model: {err}");
1106 }
1107 }
1108 }
1109 Ok(full_response)
1110 }
1111 Err(err) => Err(anyhow!(
1112 "Failed to get response from language model. Error was: {err}"
1113 )),
1114 }
1115}
1116
1117pub struct RequestMarkdown {
1118 pub tools: String,
1119 pub messages: String,
1120}
1121
1122impl RequestMarkdown {
1123 pub fn new(request: &LanguageModelRequest) -> Self {
1124 let mut tools = String::new();
1125 let mut messages = String::new();
1126 let mut assistant_message_number: u32 = 1;
1127
1128 // Print the tools
1129 if !request.tools.is_empty() {
1130 for tool in &request.tools {
1131 write!(&mut tools, "# {}\n\n", tool.name).unwrap();
1132 write!(&mut tools, "{}\n\n", tool.description).unwrap();
1133 writeln!(
1134 &mut tools,
1135 "{}",
1136 MarkdownCodeBlock {
1137 tag: "json",
1138 text: &format!("{:#}", tool.input_schema)
1139 }
1140 )
1141 .unwrap();
1142 }
1143 }
1144
1145 // Print the messages
1146 for message in &request.messages {
1147 push_role(&message.role, &mut messages, &mut assistant_message_number);
1148
1149 for content in &message.content {
1150 match content {
1151 MessageContent::Text(text) => {
1152 messages.push_str(text);
1153 messages.push_str("\n\n");
1154 }
1155 MessageContent::Image(_) => {
1156 messages.push_str("[IMAGE DATA]\n\n");
1157 }
1158 MessageContent::Thinking { text, signature } => {
1159 messages.push_str("**Thinking**:\n\n");
1160 if let Some(sig) = signature {
1161 messages.push_str(&format!("Signature: {}\n\n", sig));
1162 }
1163 messages.push_str(text);
1164 messages.push_str("\n");
1165 }
1166 MessageContent::RedactedThinking(items) => {
1167 messages.push_str(&format!(
1168 "**Redacted Thinking**: {} item(s)\n\n",
1169 items.len()
1170 ));
1171 }
1172 MessageContent::ToolUse(tool_use) => {
1173 messages.push_str(&format!(
1174 "**Tool Use**: {} (ID: {})\n",
1175 tool_use.name, tool_use.id
1176 ));
1177 messages.push_str(&format!(
1178 "{}\n",
1179 MarkdownCodeBlock {
1180 tag: "json",
1181 text: &format!("{:#}", tool_use.input)
1182 }
1183 ));
1184 }
1185 MessageContent::ToolResult(tool_result) => {
1186 messages.push_str(&format!(
1187 "**Tool Result**: {} (ID: {})\n\n",
1188 tool_result.tool_name, tool_result.tool_use_id
1189 ));
1190 if tool_result.is_error {
1191 messages.push_str("**ERROR:**\n");
1192 }
1193
1194 match &tool_result.content {
1195 LanguageModelToolResultContent::Text(text) => {
1196 writeln!(messages, "{text}\n").ok();
1197 }
1198 LanguageModelToolResultContent::Image(image) => {
1199 writeln!(messages, "\n", image.source).ok();
1200 }
1201 }
1202
1203 if let Some(output) = tool_result.output.as_ref() {
1204 writeln!(
1205 messages,
1206 "**Debug Output**:\n\n```json\n{}\n```\n",
1207 serde_json::to_string_pretty(output).unwrap()
1208 )
1209 .unwrap();
1210 }
1211 }
1212 }
1213 }
1214 }
1215
1216 Self { tools, messages }
1217 }
1218}
1219
1220pub fn response_events_to_markdown(
1221 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1222) -> String {
1223 let mut response = String::new();
1224 // Print the response events if any
1225 response.push_str("# Response\n\n");
1226 let mut text_buffer = String::new();
1227 let mut thinking_buffer = String::new();
1228
1229 let flush_buffers =
1230 |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
1231 if !text_buffer.is_empty() {
1232 output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
1233 text_buffer.clear();
1234 }
1235 if !thinking_buffer.is_empty() {
1236 output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
1237 thinking_buffer.clear();
1238 }
1239 };
1240
1241 for event in response_events {
1242 match event {
1243 Ok(LanguageModelCompletionEvent::Text(text)) => {
1244 text_buffer.push_str(text);
1245 }
1246 Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
1247 thinking_buffer.push_str(text);
1248 }
1249 Ok(LanguageModelCompletionEvent::RedactedThinking { .. }) => {}
1250 Ok(LanguageModelCompletionEvent::Stop(reason)) => {
1251 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1252 response.push_str(&format!("**Stop**: {:?}\n\n", reason));
1253 }
1254 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1255 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1256 response.push_str(&format!(
1257 "**Tool Use**: {} (ID: {})\n",
1258 tool_use.name, tool_use.id
1259 ));
1260 response.push_str(&format!(
1261 "{}\n",
1262 MarkdownCodeBlock {
1263 tag: "json",
1264 text: &format!("{:#}", tool_use.input)
1265 }
1266 ));
1267 }
1268 Ok(
1269 LanguageModelCompletionEvent::UsageUpdate(_)
1270 | LanguageModelCompletionEvent::StartMessage { .. }
1271 | LanguageModelCompletionEvent::Queued { .. }
1272 | LanguageModelCompletionEvent::Started
1273 | LanguageModelCompletionEvent::ReasoningDetails(_),
1274 ) => {}
1275 Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
1276 json_parse_error, ..
1277 }) => {
1278 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1279 response.push_str(&format!(
1280 "**Error**: parse error in tool use JSON: {}\n\n",
1281 json_parse_error
1282 ));
1283 }
1284 Err(error) => {
1285 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1286 response.push_str(&format!("**Error**: {}\n\n", error));
1287 }
1288 }
1289 }
1290
1291 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1292
1293 response
1294}
1295
1296#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1297pub struct ThreadDialog {
1298 pub request: LanguageModelRequest,
1299 pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1300}
1301
1302impl ThreadDialog {
1303 pub fn new(
1304 request: &LanguageModelRequest,
1305 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1306 ) -> Self {
1307 Self {
1308 request: request.clone(),
1309 response_events: response_events.to_vec(),
1310 }
1311 }
1312
1313 /// Represents all request and response messages in a unified format.
1314 ///
1315 /// Specifically, it appends the assistant's response (derived from response events)
1316 /// as a new message to existing messages in the request.
1317 pub fn to_combined_request(&self) -> LanguageModelRequest {
1318 let mut request = self.request.clone();
1319 if let Some(assistant_message) = self.response_events_to_message() {
1320 request.messages.push(assistant_message);
1321 }
1322 request
1323 }
1324 fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1325 let response_events = &self.response_events;
1326 let mut content: Vec<MessageContent> = Vec::new();
1327 let mut current_text = String::new();
1328
1329 let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1330 if !text.is_empty() {
1331 content.push(MessageContent::Text(std::mem::take(text)));
1332 }
1333 };
1334
1335 for event in response_events {
1336 match event {
1337 Ok(LanguageModelCompletionEvent::Text(text)) => {
1338 current_text.push_str(text);
1339 }
1340
1341 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1342 flush_text(&mut current_text, &mut content);
1343 if tool_use.is_input_complete {
1344 content.push(MessageContent::ToolUse(tool_use.clone()));
1345 }
1346 }
1347 Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1348 flush_text(&mut current_text, &mut content);
1349 content.push(MessageContent::Thinking {
1350 text: text.clone(),
1351 signature: signature.clone(),
1352 });
1353 }
1354
1355 // Skip these
1356 Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1357 | Ok(LanguageModelCompletionEvent::RedactedThinking { .. })
1358 | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1359 | Ok(LanguageModelCompletionEvent::ReasoningDetails(_))
1360 | Ok(LanguageModelCompletionEvent::Stop(_))
1361 | Ok(LanguageModelCompletionEvent::Queued { .. })
1362 | Ok(LanguageModelCompletionEvent::Started) => {}
1363
1364 Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
1365 json_parse_error,
1366 ..
1367 }) => {
1368 flush_text(&mut current_text, &mut content);
1369 content.push(MessageContent::Text(format!(
1370 "ERROR: parse error in tool use JSON: {}",
1371 json_parse_error
1372 )));
1373 }
1374
1375 Err(error) => {
1376 flush_text(&mut current_text, &mut content);
1377 content.push(MessageContent::Text(format!("ERROR: {}", error)));
1378 }
1379 }
1380 }
1381
1382 flush_text(&mut current_text, &mut content);
1383
1384 if !content.is_empty() {
1385 Some(LanguageModelRequestMessage {
1386 role: Role::Assistant,
1387 content,
1388 cache: false,
1389 reasoning_details: None,
1390 })
1391 } else {
1392 None
1393 }
1394 }
1395}
1396
1397#[cfg(test)]
1398mod test {
1399 use super::*;
1400
1401 #[test]
1402 fn test_parse_judge_output() {
1403 let response = r#"
1404 <analysis>The model did a good job but there were still compilations errors.</analysis>
1405 <passed>true</passed>
1406 "#
1407 .unindent();
1408
1409 let output = parse_assertion_result(&response).unwrap();
1410 assert_eq!(
1411 output.analysis,
1412 Some("The model did a good job but there were still compilations errors.".into())
1413 );
1414 assert!(output.passed);
1415
1416 let response = r#"
1417 Text around ignored
1418
1419 <analysis>
1420 Failed to compile:
1421 - Error 1
1422 - Error 2
1423 </analysis>
1424
1425 <passed>false</passed>
1426 "#
1427 .unindent();
1428
1429 let output = parse_assertion_result(&response).unwrap();
1430 assert_eq!(
1431 output.analysis,
1432 Some("Failed to compile:\n- Error 1\n- Error 2".into())
1433 );
1434 assert!(!output.passed);
1435 }
1436}