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