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