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 cx,
206 );
207
208 let worktree = project.update(cx, |project, cx| {
209 project.create_worktree(self.worktree_path(), true, cx)
210 });
211
212 let meta = self.thread.meta();
213 let this = self.clone();
214
215 cx.spawn(async move |cx| {
216 let worktree = worktree.await?;
217
218 // Wait for worktree scan to finish before choosing a file to open.
219 worktree
220 .update(cx, |worktree, _cx| {
221 worktree.as_local().unwrap().scan_complete()
222 })?
223 .await;
224
225 struct LanguageServerState {
226 _lsp_open_handle: OpenLspBufferHandle,
227 language_file_buffer: Entity<Buffer>,
228 }
229
230 let mut diagnostics_before = None;
231 let mut diagnostic_summary_before = DiagnosticSummary::default();
232
233 let lsp = if let Some(language_server) = &meta.language_server {
234 // Open a file that matches the language to cause LSP to start.
235 let language_file = worktree.read_with(cx, |worktree, _cx| {
236 worktree
237 .files(false, 0)
238 .find_map(|e| {
239 if e.path.clone().extension()
240 == Some(&language_server.file_extension)
241 {
242 Some(ProjectPath {
243 worktree_id: worktree.id(),
244 path: e.path.clone(),
245 })
246 } else {
247 None
248 }
249 })
250 .context("Failed to find a file for example language")
251 })??;
252
253 let open_language_file_buffer_task = project.update(cx, |project, cx| {
254 project.open_buffer(language_file.clone(), cx)
255 })?;
256
257 let language_file_buffer = open_language_file_buffer_task.await?;
258
259 let lsp_open_handle = project.update(cx, |project, cx| {
260 project.register_buffer_with_language_servers(&language_file_buffer, cx)
261 })?;
262
263 wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
264
265 diagnostic_summary_before = project.read_with(cx, |project, cx| {
266 project.diagnostic_summary(false, cx)
267 })?;
268
269 diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
270 if diagnostics_before.is_some() && language_server.allow_preexisting_diagnostics {
271 anyhow::bail!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`");
272 }
273
274 Some(LanguageServerState {
275 _lsp_open_handle: lsp_open_handle,
276 language_file_buffer,
277 })
278 } else {
279 None
280 };
281
282 anyhow::ensure!(std::env::var("ZED_EVAL_SETUP_ONLY").is_err(), "Setup only mode");
283
284 let last_diff_file_path = this.run_directory.join("last.diff");
285
286 // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
287 // history using undo/redo.
288 std::fs::write(&last_diff_file_path, "")?;
289
290 let thread = cx.update(|cx| {
291 //todo: Do we want to load rules files here?
292 let worktrees = project.read(cx).visible_worktrees(cx).map(|worktree| {
293 let root_name = worktree.read(cx).root_name_str().into();
294 let abs_path = worktree.read(cx).abs_path();
295
296 WorktreeContext {
297 root_name,
298 abs_path,
299 rules_file: None,
300 }
301 }).collect::<Vec<_>>();
302 let project_context = cx.new(|_cx| ProjectContext::new(worktrees, vec![]));
303 let context_server_registry = cx.new(|cx| ContextServerRegistry::new(project.read(cx).context_server_store(), cx));
304
305 let thread = if let Some(json) = &meta.existing_thread_json {
306 let session_id = acp::SessionId(
307 rand::rng()
308 .sample_iter(&distr::Alphanumeric)
309 .take(7)
310 .map(char::from)
311 .collect::<String>()
312 .into(),
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());
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 }],
557 temperature: None,
558 tools: Vec::new(),
559 tool_choice: None,
560 stop: Vec::new(),
561 thinking_allowed: true,
562 };
563
564 let model = model.clone();
565 let log_prefix = self.log_prefix.clone();
566 async move {
567 let response = send_language_model_request(model, request, cx).await;
568
569 let (response, result) = match response {
570 Ok(response) => (
571 response.clone(),
572 parse_assertion_result(&response).map_err(|err| err.to_string()),
573 ),
574 Err(err) => (err.to_string(), Err(err.to_string())),
575 };
576
577 if result.is_ok() {
578 println!("{}✅ {}", log_prefix, assertion.id);
579 } else {
580 println!("{}❌ {}", log_prefix, assertion.id);
581 }
582
583 (
584 response,
585 RanAssertion {
586 id: assertion.id,
587 result,
588 },
589 )
590 }
591 });
592
593 let mut responses = String::new();
594 let mut report = AssertionsReport::default();
595
596 for (response, assertion) in future::join_all(assertions).await {
597 writeln!(&mut responses, "# {}", assertion.id).unwrap();
598 writeln!(&mut responses, "{}\n\n", response).unwrap();
599 report.ran.push(assertion);
600 }
601
602 (responses, report)
603 }
604}
605
606struct EvalThreadEnvironment {
607 project: Entity<Project>,
608}
609
610struct EvalTerminalHandle {
611 terminal: Entity<acp_thread::Terminal>,
612}
613
614impl agent::TerminalHandle for EvalTerminalHandle {
615 fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
616 self.terminal.read_with(cx, |term, _cx| term.id().clone())
617 }
618
619 fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
620 self.terminal
621 .read_with(cx, |term, _cx| term.wait_for_exit())
622 }
623
624 fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
625 self.terminal
626 .read_with(cx, |term, cx| term.current_output(cx))
627 }
628}
629
630impl agent::ThreadEnvironment for EvalThreadEnvironment {
631 fn create_terminal(
632 &self,
633 command: String,
634 cwd: Option<PathBuf>,
635 output_byte_limit: Option<u64>,
636 cx: &mut AsyncApp,
637 ) -> Task<Result<Rc<dyn agent::TerminalHandle>>> {
638 let project = self.project.clone();
639 cx.spawn(async move |cx| {
640 let language_registry =
641 project.read_with(cx, |project, _cx| project.languages().clone())?;
642 let id = acp::TerminalId(uuid::Uuid::new_v4().to_string().into());
643 let terminal =
644 acp_thread::create_terminal_entity(command, &[], vec![], cwd.clone(), &project, cx)
645 .await?;
646 let terminal = cx.new(|cx| {
647 acp_thread::Terminal::new(
648 id,
649 "",
650 cwd,
651 output_byte_limit.map(|limit| limit as usize),
652 terminal,
653 language_registry,
654 cx,
655 )
656 })?;
657 Ok(Rc::new(EvalTerminalHandle { terminal }) as Rc<dyn agent::TerminalHandle>)
658 })
659 }
660}
661
662struct LanguageModelInterceptor {
663 model: Arc<dyn LanguageModel>,
664 request_count: Arc<Mutex<usize>>,
665 previous_diff: Arc<Mutex<String>>,
666 example_output_dir: PathBuf,
667 last_diff_file_path: PathBuf,
668 messages_json_file_path: PathBuf,
669 repository_path: PathBuf,
670 repository_url: String,
671}
672
673impl LanguageModelInterceptor {
674 fn new(
675 model: Arc<dyn LanguageModel>,
676 example_output_dir: PathBuf,
677 last_diff_file_path: PathBuf,
678 messages_json_file_path: PathBuf,
679 repository_path: PathBuf,
680 repository_url: String,
681 ) -> Arc<Self> {
682 Arc::new(Self {
683 model,
684 request_count: Arc::new(Mutex::new(0)),
685 previous_diff: Arc::new(Mutex::new("".to_string())),
686 example_output_dir,
687 last_diff_file_path,
688 messages_json_file_path,
689 repository_path,
690 repository_url,
691 })
692 }
693}
694
695impl language_model::LanguageModel for LanguageModelInterceptor {
696 fn id(&self) -> language_model::LanguageModelId {
697 self.model.id()
698 }
699
700 fn name(&self) -> language_model::LanguageModelName {
701 self.model.name()
702 }
703
704 fn provider_id(&self) -> language_model::LanguageModelProviderId {
705 self.model.provider_id()
706 }
707
708 fn provider_name(&self) -> language_model::LanguageModelProviderName {
709 self.model.provider_name()
710 }
711
712 fn telemetry_id(&self) -> String {
713 self.model.telemetry_id()
714 }
715
716 fn supports_images(&self) -> bool {
717 self.model.supports_images()
718 }
719
720 fn supports_tools(&self) -> bool {
721 self.model.supports_tools()
722 }
723
724 fn supports_tool_choice(&self, choice: language_model::LanguageModelToolChoice) -> bool {
725 self.model.supports_tool_choice(choice)
726 }
727
728 fn max_token_count(&self) -> u64 {
729 self.model.max_token_count()
730 }
731
732 fn count_tokens(
733 &self,
734 request: LanguageModelRequest,
735 cx: &App,
736 ) -> future::BoxFuture<'static, Result<u64>> {
737 self.model.count_tokens(request, cx)
738 }
739
740 fn stream_completion(
741 &self,
742 request: LanguageModelRequest,
743 cx: &AsyncApp,
744 ) -> future::BoxFuture<
745 'static,
746 Result<
747 futures::stream::BoxStream<
748 'static,
749 Result<LanguageModelCompletionEvent, language_model::LanguageModelCompletionError>,
750 >,
751 language_model::LanguageModelCompletionError,
752 >,
753 > {
754 let stream = self.model.stream_completion(request.clone(), cx);
755 let request_count = self.request_count.clone();
756 let previous_diff = self.previous_diff.clone();
757 let example_output_dir = self.example_output_dir.clone();
758 let last_diff_file_path = self.last_diff_file_path.clone();
759 let messages_json_file_path = self.messages_json_file_path.clone();
760 let repository_path = self.repository_path.clone();
761 let repository_url = self.repository_url.clone();
762
763 Box::pin(async move {
764 let stream = stream.await?;
765
766 let response_events = Arc::new(Mutex::new(Vec::new()));
767 let request_clone = request.clone();
768
769 let wrapped_stream = stream.then(move |event| {
770 let response_events = response_events.clone();
771 let request = request_clone.clone();
772 let request_count = request_count.clone();
773 let previous_diff = previous_diff.clone();
774 let example_output_dir = example_output_dir.clone();
775 let last_diff_file_path = last_diff_file_path.clone();
776 let messages_json_file_path = messages_json_file_path.clone();
777 let repository_path = repository_path.clone();
778 let repository_url = repository_url.clone();
779
780 async move {
781 let event_result = match &event {
782 Ok(ev) => Ok(ev.clone()),
783 Err(err) => Err(err.to_string()),
784 };
785 response_events.lock().unwrap().push(event_result);
786
787 let should_execute = matches!(
788 &event,
789 Ok(LanguageModelCompletionEvent::Stop { .. }) | Err(_)
790 );
791
792 if should_execute {
793 let current_request_count = {
794 let mut count = request_count.lock().unwrap();
795 *count += 1;
796 *count
797 };
798
799 let messages_file_path =
800 example_output_dir.join(format!("{current_request_count}.messages.md"));
801 let diff_file_path =
802 example_output_dir.join(format!("{current_request_count}.diff"));
803 let last_messages_file_path = example_output_dir.join("last.messages.md");
804
805 let collected_events = response_events.lock().unwrap().clone();
806 let request_markdown = RequestMarkdown::new(&request);
807 let response_events_markdown =
808 response_events_to_markdown(&collected_events);
809 let dialog = ThreadDialog::new(&request, &collected_events);
810 let dialog_json =
811 serde_json::to_string_pretty(&dialog.to_combined_request())
812 .unwrap_or_default();
813
814 let messages = format!(
815 "{}\n\n{}",
816 request_markdown.messages, response_events_markdown
817 );
818 fs::write(&messages_file_path, messages.clone())
819 .expect("failed to write messages file");
820 fs::write(&last_messages_file_path, messages)
821 .expect("failed to write last messages file");
822 fs::write(&messages_json_file_path, dialog_json)
823 .expect("failed to write last.messages.json");
824
825 // Get repository diff
826 let diff_result =
827 ExampleInstance::repository_diff(repository_path, &repository_url)
828 .await;
829
830 match diff_result {
831 Ok(diff) => {
832 let prev_diff = previous_diff.lock().unwrap().clone();
833 if diff != prev_diff {
834 fs::write(&diff_file_path, &diff)
835 .expect("failed to write diff file");
836 fs::write(&last_diff_file_path, &diff)
837 .expect("failed to write last diff file");
838 *previous_diff.lock().unwrap() = diff;
839 }
840 }
841 Err(err) => {
842 let error_message = format!("{err:?}");
843 fs::write(&diff_file_path, &error_message)
844 .expect("failed to write diff error to file");
845 fs::write(&last_diff_file_path, &error_message)
846 .expect("failed to write last diff file");
847 }
848 }
849
850 if current_request_count == 1 {
851 let tools_file_path = example_output_dir.join("tools.md");
852 fs::write(tools_file_path, request_markdown.tools)
853 .expect("failed to write tools file");
854 }
855 }
856
857 event
858 }
859 });
860
861 Ok(Box::pin(wrapped_stream)
862 as futures::stream::BoxStream<
863 'static,
864 Result<
865 LanguageModelCompletionEvent,
866 language_model::LanguageModelCompletionError,
867 >,
868 >)
869 })
870 }
871}
872
873pub fn wait_for_lang_server(
874 project: &Entity<Project>,
875 buffer: &Entity<Buffer>,
876 log_prefix: String,
877 cx: &mut AsyncApp,
878) -> Task<Result<()>> {
879 if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
880 return Task::ready(Ok(()));
881 }
882
883 println!("{}⏵ Waiting for language server", log_prefix);
884
885 let (mut tx, mut rx) = mpsc::channel(1);
886
887 let lsp_store = project
888 .read_with(cx, |project, _| project.lsp_store())
889 .unwrap();
890
891 let has_lang_server = buffer
892 .update(cx, |buffer, cx| {
893 lsp_store.update(cx, |lsp_store, cx| {
894 lsp_store
895 .language_servers_for_local_buffer(buffer, cx)
896 .next()
897 .is_some()
898 })
899 })
900 .unwrap_or(false);
901
902 if has_lang_server {
903 project
904 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
905 .unwrap()
906 .detach();
907 }
908
909 let subscriptions =
910 [
911 cx.subscribe(&lsp_store, {
912 let log_prefix = log_prefix.clone();
913 move |_, event, _| {
914 if let project::LspStoreEvent::LanguageServerUpdate {
915 message:
916 client::proto::update_language_server::Variant::WorkProgress(
917 LspWorkProgress {
918 message: Some(message),
919 ..
920 },
921 ),
922 ..
923 } = event
924 {
925 println!("{}⟲ {message}", log_prefix)
926 }
927 }
928 }),
929 cx.subscribe(project, {
930 let buffer = buffer.clone();
931 move |project, event, cx| match event {
932 project::Event::LanguageServerAdded(_, _, _) => {
933 let buffer = buffer.clone();
934 project
935 .update(cx, |project, cx| project.save_buffer(buffer, cx))
936 .detach();
937 }
938 project::Event::DiskBasedDiagnosticsFinished { .. } => {
939 tx.try_send(()).ok();
940 }
941 _ => {}
942 }
943 }),
944 ];
945
946 cx.spawn(async move |cx| {
947 let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
948 let result = futures::select! {
949 _ = rx.next() => {
950 println!("{}⚑ Language server idle", log_prefix);
951 anyhow::Ok(())
952 },
953 _ = timeout.fuse() => {
954 anyhow::bail!("LSP wait timed out after 5 minutes");
955 }
956 };
957 drop(subscriptions);
958 result
959 })
960}
961
962pub async fn query_lsp_diagnostics(
963 project: Entity<Project>,
964 cx: &mut AsyncApp,
965) -> Result<Option<String>> {
966 let paths_with_diagnostics = project.update(cx, |project, cx| {
967 project
968 .diagnostic_summaries(true, cx)
969 .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
970 .map(|(project_path, _, _)| project_path)
971 .collect::<Vec<_>>()
972 })?;
973
974 if paths_with_diagnostics.is_empty() {
975 return Ok(None);
976 }
977
978 let mut output = String::new();
979 for project_path in paths_with_diagnostics {
980 let buffer = project
981 .update(cx, |project, cx| project.open_buffer(project_path, cx))?
982 .await?;
983 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
984
985 for (_, group) in snapshot.diagnostic_groups(None) {
986 let entry = &group.entries[group.primary_ix];
987 let range = entry.range.to_point(&snapshot);
988 let severity = match entry.diagnostic.severity {
989 DiagnosticSeverity::ERROR => "error",
990 DiagnosticSeverity::WARNING => "warning",
991 _ => continue,
992 };
993
994 writeln!(
995 output,
996 "{} at line {}: {}",
997 severity,
998 range.start.row + 1,
999 entry.diagnostic.message
1000 )?;
1001 }
1002 }
1003 anyhow::Ok(Some(output))
1004}
1005
1006fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
1007 let analysis = get_tag("analysis", response)?;
1008 let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
1009 "true" => true,
1010 "false" => false,
1011 value @ _ => bail!("invalid judge `passed` tag: {value}"),
1012 };
1013 Ok(RanAssertionResult {
1014 analysis: Some(analysis),
1015 passed,
1016 })
1017}
1018
1019fn get_tag(name: &'static str, response: &str) -> Result<String> {
1020 let start_tag = format!("<{}>", name);
1021 let end_tag = format!("</{}>", name);
1022
1023 let start_ix = response
1024 .find(&start_tag)
1025 .context(format!("{} start tag not found", name))?;
1026 let content_start_ix = start_ix + start_tag.len();
1027
1028 let end_ix = content_start_ix
1029 + response[content_start_ix..]
1030 .find(&end_tag)
1031 .context(format!("{} end tag not found", name))?;
1032
1033 let content = response[content_start_ix..end_ix].trim().unindent();
1034
1035 anyhow::Ok(content)
1036}
1037
1038pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
1039 let repo_name = repo_url
1040 .trim_start_matches("https://")
1041 .replace(|c: char| !c.is_alphanumeric(), "-");
1042 Path::new(repos_dir).join(repo_name)
1043}
1044
1045pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
1046 let output = new_smol_command("git")
1047 .current_dir(repo_path)
1048 .args(args)
1049 .output()
1050 .await?;
1051
1052 anyhow::ensure!(
1053 output.status.success(),
1054 "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
1055 args.join(" "),
1056 repo_path.display(),
1057 output.status,
1058 String::from_utf8_lossy(&output.stderr),
1059 String::from_utf8_lossy(&output.stdout),
1060 );
1061 Ok(String::from_utf8(output.stdout)?.trim().to_string())
1062}
1063
1064fn push_role(role: &Role, buf: &mut String, assistant_message_number: &mut u32) {
1065 match role {
1066 Role::System => buf.push_str("# ⚙️ SYSTEM\n\n"),
1067 Role::User => buf.push_str("# 👤 USER\n\n"),
1068 Role::Assistant => {
1069 buf.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
1070 *assistant_message_number = *assistant_message_number + 1;
1071 }
1072 }
1073}
1074
1075pub async fn send_language_model_request(
1076 model: Arc<dyn LanguageModel>,
1077 request: LanguageModelRequest,
1078 cx: &AsyncApp,
1079) -> anyhow::Result<String> {
1080 match model.stream_completion_text(request, cx).await {
1081 Ok(mut stream) => {
1082 let mut full_response = String::new();
1083 while let Some(chunk_result) = stream.stream.next().await {
1084 match chunk_result {
1085 Ok(chunk_str) => {
1086 full_response.push_str(&chunk_str);
1087 }
1088 Err(err) => {
1089 anyhow::bail!("Error receiving response from language model: {err}");
1090 }
1091 }
1092 }
1093 Ok(full_response)
1094 }
1095 Err(err) => Err(anyhow!(
1096 "Failed to get response from language model. Error was: {err}"
1097 )),
1098 }
1099}
1100
1101pub struct RequestMarkdown {
1102 pub tools: String,
1103 pub messages: String,
1104}
1105
1106impl RequestMarkdown {
1107 pub fn new(request: &LanguageModelRequest) -> Self {
1108 let mut tools = String::new();
1109 let mut messages = String::new();
1110 let mut assistant_message_number: u32 = 1;
1111
1112 // Print the tools
1113 if !request.tools.is_empty() {
1114 for tool in &request.tools {
1115 write!(&mut tools, "# {}\n\n", tool.name).unwrap();
1116 write!(&mut tools, "{}\n\n", tool.description).unwrap();
1117 writeln!(
1118 &mut tools,
1119 "{}",
1120 MarkdownCodeBlock {
1121 tag: "json",
1122 text: &format!("{:#}", tool.input_schema)
1123 }
1124 )
1125 .unwrap();
1126 }
1127 }
1128
1129 // Print the messages
1130 for message in &request.messages {
1131 push_role(&message.role, &mut messages, &mut assistant_message_number);
1132
1133 for content in &message.content {
1134 match content {
1135 MessageContent::Text(text) => {
1136 messages.push_str(text);
1137 messages.push_str("\n\n");
1138 }
1139 MessageContent::Image(_) => {
1140 messages.push_str("[IMAGE DATA]\n\n");
1141 }
1142 MessageContent::Thinking { text, signature } => {
1143 messages.push_str("**Thinking**:\n\n");
1144 if let Some(sig) = signature {
1145 messages.push_str(&format!("Signature: {}\n\n", sig));
1146 }
1147 messages.push_str(text);
1148 messages.push_str("\n");
1149 }
1150 MessageContent::RedactedThinking(items) => {
1151 messages.push_str(&format!(
1152 "**Redacted Thinking**: {} item(s)\n\n",
1153 items.len()
1154 ));
1155 }
1156 MessageContent::ToolUse(tool_use) => {
1157 messages.push_str(&format!(
1158 "**Tool Use**: {} (ID: {})\n",
1159 tool_use.name, tool_use.id
1160 ));
1161 messages.push_str(&format!(
1162 "{}\n",
1163 MarkdownCodeBlock {
1164 tag: "json",
1165 text: &format!("{:#}", tool_use.input)
1166 }
1167 ));
1168 }
1169 MessageContent::ToolResult(tool_result) => {
1170 messages.push_str(&format!(
1171 "**Tool Result**: {} (ID: {})\n\n",
1172 tool_result.tool_name, tool_result.tool_use_id
1173 ));
1174 if tool_result.is_error {
1175 messages.push_str("**ERROR:**\n");
1176 }
1177
1178 match &tool_result.content {
1179 LanguageModelToolResultContent::Text(text) => {
1180 writeln!(messages, "{text}\n").ok();
1181 }
1182 LanguageModelToolResultContent::Image(image) => {
1183 writeln!(messages, "\n", image.source).ok();
1184 }
1185 }
1186
1187 if let Some(output) = tool_result.output.as_ref() {
1188 writeln!(
1189 messages,
1190 "**Debug Output**:\n\n```json\n{}\n```\n",
1191 serde_json::to_string_pretty(output).unwrap()
1192 )
1193 .unwrap();
1194 }
1195 }
1196 }
1197 }
1198 }
1199
1200 Self { tools, messages }
1201 }
1202}
1203
1204pub fn response_events_to_markdown(
1205 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1206) -> String {
1207 let mut response = String::new();
1208 // Print the response events if any
1209 response.push_str("# Response\n\n");
1210 let mut text_buffer = String::new();
1211 let mut thinking_buffer = String::new();
1212
1213 let flush_buffers =
1214 |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
1215 if !text_buffer.is_empty() {
1216 output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
1217 text_buffer.clear();
1218 }
1219 if !thinking_buffer.is_empty() {
1220 output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
1221 thinking_buffer.clear();
1222 }
1223 };
1224
1225 for event in response_events {
1226 match event {
1227 Ok(LanguageModelCompletionEvent::Text(text)) => {
1228 text_buffer.push_str(text);
1229 }
1230 Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
1231 thinking_buffer.push_str(text);
1232 }
1233 Ok(LanguageModelCompletionEvent::RedactedThinking { .. }) => {}
1234 Ok(LanguageModelCompletionEvent::Stop(reason)) => {
1235 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1236 response.push_str(&format!("**Stop**: {:?}\n\n", reason));
1237 }
1238 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1239 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1240 response.push_str(&format!(
1241 "**Tool Use**: {} (ID: {})\n",
1242 tool_use.name, tool_use.id
1243 ));
1244 response.push_str(&format!(
1245 "{}\n",
1246 MarkdownCodeBlock {
1247 tag: "json",
1248 text: &format!("{:#}", tool_use.input)
1249 }
1250 ));
1251 }
1252 Ok(
1253 LanguageModelCompletionEvent::UsageUpdate(_)
1254 | LanguageModelCompletionEvent::StartMessage { .. }
1255 | LanguageModelCompletionEvent::StatusUpdate { .. },
1256 ) => {}
1257 Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
1258 json_parse_error, ..
1259 }) => {
1260 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1261 response.push_str(&format!(
1262 "**Error**: parse error in tool use JSON: {}\n\n",
1263 json_parse_error
1264 ));
1265 }
1266 Err(error) => {
1267 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1268 response.push_str(&format!("**Error**: {}\n\n", error));
1269 }
1270 }
1271 }
1272
1273 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1274
1275 response
1276}
1277
1278#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1279pub struct ThreadDialog {
1280 pub request: LanguageModelRequest,
1281 pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1282}
1283
1284impl ThreadDialog {
1285 pub fn new(
1286 request: &LanguageModelRequest,
1287 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1288 ) -> Self {
1289 Self {
1290 request: request.clone(),
1291 response_events: response_events.to_vec(),
1292 }
1293 }
1294
1295 /// Represents all request and response messages in a unified format.
1296 ///
1297 /// Specifically, it appends the assistant's response (derived from response events)
1298 /// as a new message to existing messages in the request.
1299 pub fn to_combined_request(&self) -> LanguageModelRequest {
1300 let mut request = self.request.clone();
1301 if let Some(assistant_message) = self.response_events_to_message() {
1302 request.messages.push(assistant_message);
1303 }
1304 request
1305 }
1306 fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1307 let response_events = &self.response_events;
1308 let mut content: Vec<MessageContent> = Vec::new();
1309 let mut current_text = String::new();
1310
1311 let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1312 if !text.is_empty() {
1313 content.push(MessageContent::Text(std::mem::take(text)));
1314 }
1315 };
1316
1317 for event in response_events {
1318 match event {
1319 Ok(LanguageModelCompletionEvent::Text(text)) => {
1320 current_text.push_str(text);
1321 }
1322
1323 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1324 flush_text(&mut current_text, &mut content);
1325 if tool_use.is_input_complete {
1326 content.push(MessageContent::ToolUse(tool_use.clone()));
1327 }
1328 }
1329 Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1330 flush_text(&mut current_text, &mut content);
1331 content.push(MessageContent::Thinking {
1332 text: text.clone(),
1333 signature: signature.clone(),
1334 });
1335 }
1336
1337 // Skip these
1338 Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1339 | Ok(LanguageModelCompletionEvent::RedactedThinking { .. })
1340 | Ok(LanguageModelCompletionEvent::StatusUpdate { .. })
1341 | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1342 | Ok(LanguageModelCompletionEvent::Stop(_)) => {}
1343
1344 Ok(LanguageModelCompletionEvent::ToolUseJsonParseError {
1345 json_parse_error,
1346 ..
1347 }) => {
1348 flush_text(&mut current_text, &mut content);
1349 content.push(MessageContent::Text(format!(
1350 "ERROR: parse error in tool use JSON: {}",
1351 json_parse_error
1352 )));
1353 }
1354
1355 Err(error) => {
1356 flush_text(&mut current_text, &mut content);
1357 content.push(MessageContent::Text(format!("ERROR: {}", error)));
1358 }
1359 }
1360 }
1361
1362 flush_text(&mut current_text, &mut content);
1363
1364 if !content.is_empty() {
1365 Some(LanguageModelRequestMessage {
1366 role: Role::Assistant,
1367 content,
1368 cache: false,
1369 })
1370 } else {
1371 None
1372 }
1373 }
1374}
1375
1376#[cfg(test)]
1377mod test {
1378 use super::*;
1379
1380 #[test]
1381 fn test_parse_judge_output() {
1382 let response = r#"
1383 <analysis>The model did a good job but there were still compilations errors.</analysis>
1384 <passed>true</passed>
1385 "#
1386 .unindent();
1387
1388 let output = parse_assertion_result(&response).unwrap();
1389 assert_eq!(
1390 output.analysis,
1391 Some("The model did a good job but there were still compilations errors.".into())
1392 );
1393 assert!(output.passed);
1394
1395 let response = r#"
1396 Text around ignored
1397
1398 <analysis>
1399 Failed to compile:
1400 - Error 1
1401 - Error 2
1402 </analysis>
1403
1404 <passed>false</passed>
1405 "#
1406 .unindent();
1407
1408 let output = parse_assertion_result(&response).unwrap();
1409 assert_eq!(
1410 output.analysis,
1411 Some("Failed to compile:\n- Error 1\n- Error 2".into())
1412 );
1413 assert!(!output.passed);
1414 }
1415}