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