1use agent::thread::ToolUseSegment;
2use agent::{Message, MessageSegment, SerializedThread, ThreadStore};
3use anyhow::{Context as _, Result, anyhow, bail};
4use assistant_tool::ToolWorkingSet;
5use client::proto::LspWorkProgress;
6use futures::channel::mpsc;
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, LanguageModelRequest, LanguageModelRequestMessage,
13 LanguageModelToolResultContent, MessageContent, Role, TokenUsage,
14};
15use project::lsp_store::OpenLspBufferHandle;
16use project::{DiagnosticSummary, Project, ProjectPath};
17use serde::{Deserialize, Serialize};
18use std::cell::RefCell;
19use std::fmt::Write as _;
20use std::fs;
21use std::fs::File;
22use std::io::Write as _;
23use std::path::Path;
24use std::path::PathBuf;
25use std::rc::Rc;
26use std::sync::Arc;
27use std::time::Duration;
28use unindent::Unindent as _;
29use util::ResultExt as _;
30use util::command::new_smol_command;
31use util::markdown::MarkdownCodeBlock;
32
33use crate::assertions::{AssertionsReport, RanAssertion, RanAssertionResult};
34use crate::example::{Example, ExampleContext, FailedAssertion, JudgeAssertion};
35use crate::{AgentAppState, ToolMetrics};
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 response_count: usize,
62 pub token_usage: TokenUsage,
63 pub tool_metrics: ToolMetrics,
64 pub all_messages: String,
65 pub programmatic_assertions: AssertionsReport,
66}
67
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct JudgeDiffInput {
70 pub repository_diff: String,
71 pub assertion: String,
72}
73
74#[derive(Debug, Clone, Serialize, Deserialize)]
75pub struct JudgeThreadInput {
76 pub messages: String,
77 pub assertion: String,
78}
79
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct JudgeOutput {
82 pub thread: AssertionsReport,
83 pub diff: AssertionsReport,
84}
85
86impl ExampleInstance {
87 pub fn new(
88 thread: Rc<dyn Example>,
89 repos_dir: &Path,
90 run_dir: &Path,
91 worktrees_dir: &Path,
92 repetition: usize,
93 ) -> Self {
94 let name = thread.meta().name.to_string();
95 let run_directory = run_dir
96 .join(&name)
97 .join(repetition.to_string())
98 .to_path_buf();
99
100 let repo_path = repo_path_for_url(repos_dir, &thread.meta().url);
101
102 Self {
103 name,
104 thread,
105 log_prefix: String::new(),
106 run_directory,
107 repetition,
108 repo_path,
109 worktrees_dir: worktrees_dir.to_path_buf(),
110 }
111 }
112
113 pub fn repo_url(&self) -> String {
114 self.thread.meta().url
115 }
116
117 pub fn revision(&self) -> String {
118 self.thread.meta().revision
119 }
120
121 pub fn worktree_name(&self) -> String {
122 format!("{}-{}", self.name, self.repetition)
123 }
124
125 pub fn set_log_prefix_style(&mut self, color: &str, name_width: usize) {
126 self.log_prefix = format!(
127 "{}{:<width$}\x1b[0m | ",
128 color,
129 self.worktree_name(),
130 width = name_width
131 );
132 }
133
134 /// Set up the example by checking out the specified Git revision
135 pub async fn fetch(&mut self) -> Result<()> {
136 let meta = self.thread.meta();
137
138 let revision_exists = run_git(
139 &self.repo_path,
140 &["rev-parse", &format!("{}^{{commit}}", &meta.revision)],
141 )
142 .await
143 .is_ok();
144
145 if !revision_exists {
146 println!("{}Fetching revision {}", self.log_prefix, &meta.revision);
147 run_git(
148 &self.repo_path,
149 &["fetch", "--depth", "1", "origin", &meta.revision],
150 )
151 .await?;
152 }
153 Ok(())
154 }
155
156 /// Set up the example by checking out the specified Git revision
157 pub async fn setup(&mut self) -> Result<()> {
158 let worktree_path = self.worktree_path();
159 let meta = self.thread.meta();
160 if worktree_path.is_dir() {
161 println!("{}Resetting existing worktree", self.log_prefix);
162
163 // TODO: consider including "-x" to remove ignored files. The downside of this is that
164 // it will also remove build artifacts, and so prevent incremental reuse there.
165 run_git(&worktree_path, &["clean", "--force", "-d"]).await?;
166 run_git(&worktree_path, &["reset", "--hard", "HEAD"]).await?;
167 run_git(&worktree_path, &["checkout", &meta.revision]).await?;
168 } else {
169 println!("{}Creating worktree", self.log_prefix);
170
171 let worktree_path_string = worktree_path.to_string_lossy().to_string();
172
173 run_git(
174 &self.repo_path,
175 &[
176 "worktree",
177 "add",
178 "-f",
179 &worktree_path_string,
180 &meta.revision,
181 ],
182 )
183 .await?;
184 }
185
186 if meta.url == ZED_REPO_URL {
187 std::fs::write(worktree_path.join(".rules"), std::fs::read(".rules")?)?;
188 }
189
190 std::fs::create_dir_all(&self.run_directory)?;
191
192 Ok(())
193 }
194
195 pub fn worktree_path(&self) -> PathBuf {
196 self.worktrees_dir
197 .join(self.worktree_name())
198 .join(self.thread.meta().repo_name())
199 }
200
201 pub fn run(
202 &self,
203 model: Arc<dyn LanguageModel>,
204 app_state: Arc<AgentAppState>,
205 cx: &mut App,
206 ) -> Task<Result<RunOutput>> {
207 let project = Project::local(
208 app_state.client.clone(),
209 app_state.node_runtime.clone(),
210 app_state.user_store.clone(),
211 app_state.languages.clone(),
212 app_state.fs.clone(),
213 None,
214 cx,
215 );
216
217 let worktree = project.update(cx, |project, cx| {
218 project.create_worktree(self.worktree_path(), true, cx)
219 });
220
221 let tools = cx.new(|_| ToolWorkingSet::default());
222 let prompt_store = None;
223 let thread_store = ThreadStore::load(
224 project.clone(),
225 tools,
226 prompt_store,
227 app_state.prompt_builder.clone(),
228 cx,
229 );
230 let meta = self.thread.meta();
231 let this = self.clone();
232
233 cx.spawn(async move |cx| {
234 let worktree = worktree.await?;
235
236 // Wait for worktree scan to finish before choosing a file to open.
237 worktree
238 .update(cx, |worktree, _cx| {
239 worktree.as_local().unwrap().scan_complete()
240 })?
241 .await;
242
243 struct LanguageServerState {
244 _lsp_open_handle: OpenLspBufferHandle,
245 language_file_buffer: Entity<Buffer>,
246 }
247
248 let mut diagnostics_before = None;
249 let mut diagnostic_summary_before = DiagnosticSummary::default();
250
251 let lsp = if let Some(language_server) = &meta.language_server {
252 // Open a file that matches the language to cause LSP to start.
253 let language_file = worktree.read_with(cx, |worktree, _cx| {
254 worktree
255 .files(false, 0)
256 .find_map(|e| {
257 if e.path.clone().extension().and_then(|ext| ext.to_str())
258 == Some(&language_server.file_extension)
259 {
260 Some(ProjectPath {
261 worktree_id: worktree.id(),
262 path: e.path.clone(),
263 })
264 } else {
265 None
266 }
267 })
268 .context("Failed to find a file for example language")
269 })??;
270
271 let open_language_file_buffer_task = project.update(cx, |project, cx| {
272 project.open_buffer(language_file.clone(), cx)
273 })?;
274
275 let language_file_buffer = open_language_file_buffer_task.await?;
276
277 let lsp_open_handle = project.update(cx, |project, cx| {
278 project.register_buffer_with_language_servers(&language_file_buffer, cx)
279 })?;
280
281 wait_for_lang_server(&project, &language_file_buffer, this.log_prefix.clone(), cx).await?;
282
283 diagnostic_summary_before = project.read_with(cx, |project, cx| {
284 project.diagnostic_summary(false, cx)
285 })?;
286
287 diagnostics_before = query_lsp_diagnostics(project.clone(), cx).await?;
288 if diagnostics_before.is_some() && language_server.allow_preexisting_diagnostics {
289 anyhow::bail!("Example has pre-existing diagnostics. If you want to run this example regardless, set `allow_preexisting_diagnostics` to `true` in `base.toml`");
290 }
291
292 Some(LanguageServerState {
293 _lsp_open_handle: lsp_open_handle,
294 language_file_buffer,
295 })
296 } else {
297 None
298 };
299
300 anyhow::ensure!(std::env::var("ZED_EVAL_SETUP_ONLY").is_err(), "Setup only mode");
301
302 let last_diff_file_path = this.run_directory.join("last.diff");
303
304 // Write an empty "last.diff" so that it can be opened in Zed for convenient view of the
305 // history using undo/redo.
306 std::fs::write(&last_diff_file_path, "")?;
307
308 let thread_store = thread_store.await?;
309
310
311 let agent =
312 thread_store.update(cx, |thread_store, cx| {
313 let thread = if let Some(json) = &meta.existing_thread_json {
314 let serialized = SerializedThread::from_json(json.as_bytes()).expect("Can't read serialized thread");
315 thread_store.create_thread_from_serialized(serialized, cx)
316 } else {
317 thread_store.create_thread(cx)
318 };
319 thread.update(cx, |thread, cx| {
320 thread.set_profile(meta.profile_id.clone(), cx);
321 });
322 thread
323 })?;
324
325
326 agent.update(cx, |thread, _cx| {
327 let mut request_count = 0;
328 let previous_diff = Rc::new(RefCell::new("".to_string()));
329 let example_output_dir = this.run_directory.clone();
330 let last_diff_file_path = last_diff_file_path.clone();
331 let messages_json_file_path = example_output_dir.join("last.messages.json");
332 let this = this.clone();
333 thread.set_request_callback(move |request, response_events| {
334 request_count += 1;
335 let messages_file_path = example_output_dir.join(format!("{request_count}.messages.md"));
336 let diff_file_path = example_output_dir.join(format!("{request_count}.diff"));
337 let last_messages_file_path = example_output_dir.join("last.messages.md");
338 let request_markdown = RequestMarkdown::new(request);
339 let response_events_markdown = response_events_to_markdown(response_events);
340 let dialog = ThreadDialog::new(request, response_events);
341 let dialog_json = serde_json::to_string_pretty(&dialog.to_combined_request()).unwrap_or_default();
342
343 let messages = format!("{}\n\n{}", request_markdown.messages, response_events_markdown);
344 fs::write(&messages_file_path, messages.clone()).expect("failed to write messages file");
345 fs::write(&last_messages_file_path, messages).expect("failed to write last messages file");
346 fs::write(&messages_json_file_path, dialog_json).expect("failed to write last.messages.json");
347
348 let diff_result = smol::block_on(this.repository_diff());
349 match diff_result {
350 Ok(diff) => {
351 if diff != previous_diff.borrow().clone() {
352 fs::write(&diff_file_path, &diff).expect("failed to write diff file");
353 fs::write(&last_diff_file_path, &diff).expect("failed to write last diff file");
354 *previous_diff.borrow_mut() = diff;
355 }
356 }
357 Err(err) => {
358 let error_message = format!("{err:?}");
359 fs::write(&diff_file_path, &error_message).expect("failed to write diff error to file");
360 fs::write(&last_diff_file_path, &error_message).expect("failed to write last diff file");
361 }
362 }
363
364 if request_count == 1 {
365 let tools_file_path = example_output_dir.join("tools.md");
366 fs::write(tools_file_path, request_markdown.tools).expect("failed to write tools file");
367 }
368 });
369 })?;
370
371 let mut example_cx = ExampleContext::new(
372 meta.clone(),
373 this.log_prefix.clone(),
374 agent.clone(),
375 model.clone(),
376 cx.clone(),
377 );
378 let result = this.thread.conversation(&mut example_cx).await;
379
380 if let Err(err) = result {
381 if !err.is::<FailedAssertion>() {
382 return Err(err);
383 }
384 }
385
386 println!("{}Stopped", this.log_prefix);
387
388 println!("{}Getting repository diff", this.log_prefix);
389 let repository_diff = this.repository_diff().await?;
390
391 std::fs::write(last_diff_file_path, &repository_diff)?;
392
393
394 let mut diagnostics_after = None;
395 let mut diagnostic_summary_after = Default::default();
396
397 if let Some(language_server_state) = lsp {
398 wait_for_lang_server(&project, &language_server_state.language_file_buffer, this.log_prefix.clone(), cx).await?;
399
400 println!("{}Getting diagnostics", this.log_prefix);
401 diagnostics_after = cx
402 .update(|cx| {
403 let project = project.clone();
404 cx.spawn(async move |cx| query_lsp_diagnostics(project, cx).await)
405 })?
406 .await?;
407 println!("{}Got diagnostics", this.log_prefix);
408
409 diagnostic_summary_after = project.read_with(cx, |project, cx| {
410 project.diagnostic_summary(false, cx)
411 })?;
412
413 }
414
415 if let Some(diagnostics_before) = &diagnostics_before {
416 fs::write(this.run_directory.join("diagnostics_before.txt"), diagnostics_before)?;
417 }
418
419 if let Some(diagnostics_after) = &diagnostics_after {
420 fs::write(this.run_directory.join("diagnostics_after.txt"), diagnostics_after)?;
421 }
422
423 agent.update(cx, |agent, _cx| {
424 let response_count = agent
425 .messages()
426 .filter(|message| message.role == language_model::Role::Assistant)
427 .count();
428 let all_messages = messages_to_markdown(agent.messages());
429 RunOutput {
430 repository_diff,
431 diagnostic_summary_before,
432 diagnostic_summary_after,
433 diagnostics_before,
434 diagnostics_after,
435 response_count,
436 token_usage: agent.cumulative_token_usage(),
437 tool_metrics: example_cx.tool_metrics.lock().unwrap().clone(),
438 all_messages,
439 programmatic_assertions: example_cx.assertions,
440 }
441 })
442 })
443 }
444
445 async fn repository_diff(&self) -> Result<String> {
446 let worktree_path = self.worktree_path();
447 run_git(&worktree_path, &["add", "."]).await?;
448 let mut diff_args = vec!["diff", "--staged"];
449 if self.thread.meta().url == ZED_REPO_URL {
450 diff_args.push(":(exclude).rules");
451 }
452 run_git(&worktree_path, &diff_args).await
453 }
454
455 pub async fn judge(
456 &self,
457 model: Arc<dyn LanguageModel>,
458 run_output: &RunOutput,
459 cx: &AsyncApp,
460 ) -> JudgeOutput {
461 let mut output_file =
462 File::create(self.run_directory.join("judge.md")).expect("failed to create judge.md");
463
464 let diff_task = self.judge_diff(model.clone(), &run_output, cx);
465 let thread_task = self.judge_thread(model.clone(), &run_output, cx);
466
467 let (diff_result, thread_result) = futures::join!(diff_task, thread_task);
468
469 let (diff_response, diff_output) = diff_result;
470 let (thread_response, thread_output) = thread_result;
471
472 writeln!(
473 &mut output_file,
474 "# Judgment\n\n## Thread\n\n{thread_response}\n\n## Diff\n\n{diff_response}",
475 )
476 .log_err();
477
478 JudgeOutput {
479 thread: thread_output,
480 diff: diff_output,
481 }
482 }
483
484 async fn judge_diff(
485 &self,
486 model: Arc<dyn LanguageModel>,
487 run_output: &RunOutput,
488 cx: &AsyncApp,
489 ) -> (String, AssertionsReport) {
490 let diff_assertions = self.thread.diff_assertions();
491
492 if diff_assertions.is_empty() {
493 return (
494 "No diff assertions".to_string(),
495 AssertionsReport::default(),
496 );
497 }
498
499 println!("{}Running diff judge", self.log_prefix);
500
501 let judge_diff_prompt = include_str!("judge_diff_prompt.hbs");
502 let judge_diff_prompt_name = "judge_diff_prompt";
503 let mut hbs = Handlebars::new();
504 hbs.register_template_string(judge_diff_prompt_name, judge_diff_prompt)
505 .unwrap();
506
507 let to_prompt = |assertion: String| {
508 hbs.render(
509 judge_diff_prompt_name,
510 &JudgeDiffInput {
511 repository_diff: run_output.repository_diff.clone(),
512 assertion,
513 },
514 )
515 .unwrap()
516 };
517
518 let (responses, report) = self
519 .judge_assertions(model, diff_assertions, to_prompt, cx)
520 .await;
521
522 println!(
523 "{}Judge - Diff score: {}%",
524 self.log_prefix,
525 report.passed_percentage()
526 );
527
528 (responses, report)
529 }
530
531 async fn judge_thread(
532 &self,
533 model: Arc<dyn LanguageModel>,
534 run_output: &RunOutput,
535 cx: &AsyncApp,
536 ) -> (String, AssertionsReport) {
537 let thread_assertions = self.thread.thread_assertions();
538
539 if thread_assertions.is_empty() {
540 return (
541 "No thread assertions".to_string(),
542 AssertionsReport::default(),
543 );
544 }
545
546 let judge_thread_prompt = include_str!("judge_thread_prompt.hbs");
547 let judge_thread_prompt_name = "judge_thread_prompt";
548 let mut hbs = Handlebars::new();
549 hbs.register_template_string(judge_thread_prompt_name, judge_thread_prompt)
550 .unwrap();
551
552 let complete_messages = &run_output.all_messages;
553 let to_prompt = |assertion: String| {
554 hbs.render(
555 judge_thread_prompt_name,
556 &JudgeThreadInput {
557 messages: complete_messages.clone(),
558 assertion,
559 },
560 )
561 .unwrap()
562 };
563
564 let (responses, report) = self
565 .judge_assertions(model, thread_assertions, to_prompt, cx)
566 .await;
567
568 println!(
569 "{}Judge - Thread score: {}%",
570 self.log_prefix,
571 report.passed_percentage()
572 );
573
574 (responses, report)
575 }
576
577 async fn judge_assertions(
578 &self,
579 model: Arc<dyn LanguageModel>,
580 assertions: Vec<JudgeAssertion>,
581 to_prompt: impl Fn(String) -> String,
582 cx: &AsyncApp,
583 ) -> (String, AssertionsReport) {
584 let assertions = assertions.into_iter().map(|assertion| {
585 let request = LanguageModelRequest {
586 thread_id: None,
587 prompt_id: None,
588 mode: None,
589 intent: None,
590 messages: vec![LanguageModelRequestMessage {
591 role: Role::User,
592 content: vec![MessageContent::Text(to_prompt(assertion.description))],
593 cache: false,
594 }],
595 temperature: None,
596 tools: Vec::new(),
597 tool_choice: None,
598 stop: Vec::new(),
599 };
600
601 let model = model.clone();
602 let log_prefix = self.log_prefix.clone();
603 async move {
604 let response = send_language_model_request(model, request, cx).await;
605
606 let (response, result) = match response {
607 Ok(response) => (
608 response.clone(),
609 parse_assertion_result(&response).map_err(|err| err.to_string()),
610 ),
611 Err(err) => (err.to_string(), Err(err.to_string())),
612 };
613
614 if result.is_ok() {
615 println!("{}✅ {}", log_prefix, assertion.id);
616 } else {
617 println!("{}❌ {}", log_prefix, assertion.id);
618 }
619
620 (
621 response,
622 RanAssertion {
623 id: assertion.id,
624 result,
625 },
626 )
627 }
628 });
629
630 let mut responses = String::new();
631 let mut report = AssertionsReport::default();
632
633 for (response, assertion) in future::join_all(assertions).await {
634 writeln!(&mut responses, "# {}", assertion.id).unwrap();
635 writeln!(&mut responses, "{}\n\n", response).unwrap();
636 report.ran.push(assertion);
637 }
638
639 (responses, report)
640 }
641}
642
643pub fn wait_for_lang_server(
644 project: &Entity<Project>,
645 buffer: &Entity<Buffer>,
646 log_prefix: String,
647 cx: &mut AsyncApp,
648) -> Task<Result<()>> {
649 if std::env::var("ZED_EVAL_SKIP_LS").is_ok() {
650 return Task::ready(Ok(()));
651 }
652
653 println!("{}⏵ Waiting for language server", log_prefix);
654
655 let (mut tx, mut rx) = mpsc::channel(1);
656
657 let lsp_store = project
658 .read_with(cx, |project, _| project.lsp_store())
659 .unwrap();
660
661 let has_lang_server = buffer
662 .update(cx, |buffer, cx| {
663 lsp_store.update(cx, |lsp_store, cx| {
664 lsp_store
665 .language_servers_for_local_buffer(&buffer, cx)
666 .next()
667 .is_some()
668 })
669 })
670 .unwrap_or(false);
671
672 if has_lang_server {
673 project
674 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))
675 .unwrap()
676 .detach();
677 }
678
679 let subscriptions =
680 [
681 cx.subscribe(&lsp_store, {
682 let log_prefix = log_prefix.clone();
683 move |_, event, _| match event {
684 project::LspStoreEvent::LanguageServerUpdate {
685 message:
686 client::proto::update_language_server::Variant::WorkProgress(
687 LspWorkProgress {
688 message: Some(message),
689 ..
690 },
691 ),
692 ..
693 } => println!("{}⟲ {message}", log_prefix),
694 _ => {}
695 }
696 }),
697 cx.subscribe(&project, {
698 let buffer = buffer.clone();
699 move |project, event, cx| match event {
700 project::Event::LanguageServerAdded(_, _, _) => {
701 let buffer = buffer.clone();
702 project
703 .update(cx, |project, cx| project.save_buffer(buffer, cx))
704 .detach();
705 }
706 project::Event::DiskBasedDiagnosticsFinished { .. } => {
707 tx.try_send(()).ok();
708 }
709 _ => {}
710 }
711 }),
712 ];
713
714 cx.spawn(async move |cx| {
715 let timeout = cx.background_executor().timer(Duration::new(60 * 5, 0));
716 let result = futures::select! {
717 _ = rx.next() => {
718 println!("{}⚑ Language server idle", log_prefix);
719 anyhow::Ok(())
720 },
721 _ = timeout.fuse() => {
722 anyhow::bail!("LSP wait timed out after 5 minutes");
723 }
724 };
725 drop(subscriptions);
726 result
727 })
728}
729
730pub async fn query_lsp_diagnostics(
731 project: Entity<Project>,
732 cx: &mut AsyncApp,
733) -> Result<Option<String>> {
734 let paths_with_diagnostics = project.update(cx, |project, cx| {
735 project
736 .diagnostic_summaries(true, cx)
737 .filter(|(_, _, summary)| summary.error_count > 0 || summary.warning_count > 0)
738 .map(|(project_path, _, _)| project_path)
739 .collect::<Vec<_>>()
740 })?;
741
742 if paths_with_diagnostics.is_empty() {
743 return Ok(None);
744 }
745
746 let mut output = String::new();
747 for project_path in paths_with_diagnostics {
748 let buffer = project
749 .update(cx, |project, cx| project.open_buffer(project_path, cx))?
750 .await?;
751 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
752
753 for (_, group) in snapshot.diagnostic_groups(None) {
754 let entry = &group.entries[group.primary_ix];
755 let range = entry.range.to_point(&snapshot);
756 let severity = match entry.diagnostic.severity {
757 DiagnosticSeverity::ERROR => "error",
758 DiagnosticSeverity::WARNING => "warning",
759 _ => continue,
760 };
761
762 writeln!(
763 output,
764 "{} at line {}: {}",
765 severity,
766 range.start.row + 1,
767 entry.diagnostic.message
768 )?;
769 }
770 }
771 anyhow::Ok(Some(output))
772}
773
774fn parse_assertion_result(response: &str) -> Result<RanAssertionResult> {
775 let analysis = get_tag("analysis", response)?.to_string();
776 let passed = match get_tag("passed", response)?.to_lowercase().as_str() {
777 "true" => true,
778 "false" => false,
779 value @ _ => bail!("invalid judge `passed` tag: {value}"),
780 };
781 Ok(RanAssertionResult {
782 analysis: Some(analysis),
783 passed,
784 })
785}
786
787fn get_tag(name: &'static str, response: &str) -> Result<String> {
788 let start_tag = format!("<{}>", name);
789 let end_tag = format!("</{}>", name);
790
791 let start_ix = response
792 .find(&start_tag)
793 .context(format!("{} start tag not found", name))?;
794 let content_start_ix = start_ix + start_tag.len();
795
796 let end_ix = content_start_ix
797 + response[content_start_ix..]
798 .find(&end_tag)
799 .context(format!("{} end tag not found", name))?;
800
801 let content = response[content_start_ix..end_ix].trim().unindent();
802
803 anyhow::Ok(content)
804}
805
806pub fn repo_path_for_url(repos_dir: &Path, repo_url: &str) -> PathBuf {
807 let repo_name = repo_url
808 .trim_start_matches("https://")
809 .replace(|c: char| !c.is_alphanumeric(), "-");
810 Path::new(repos_dir).join(repo_name)
811}
812
813pub async fn run_git(repo_path: &Path, args: &[&str]) -> Result<String> {
814 let output = new_smol_command("git")
815 .current_dir(repo_path)
816 .args(args)
817 .output()
818 .await?;
819
820 anyhow::ensure!(
821 output.status.success(),
822 "`git {}` within `{}` failed with status: {}\nstderr:\n{}\nstdout:\n{}",
823 args.join(" "),
824 repo_path.display(),
825 output.status,
826 String::from_utf8_lossy(&output.stderr),
827 String::from_utf8_lossy(&output.stdout),
828 );
829 Ok(String::from_utf8(output.stdout)?.trim().to_string())
830}
831
832fn messages_to_markdown<'a>(message_iter: impl IntoIterator<Item = &'a Message>) -> String {
833 let mut messages = String::new();
834 let mut assistant_message_number: u32 = 1;
835
836 for message in message_iter {
837 push_role(&message.role, &mut messages, &mut assistant_message_number);
838
839 for segment in &message.segments {
840 match segment {
841 MessageSegment::Text(text) => {
842 messages.push_str(&text);
843 messages.push_str("\n\n");
844 }
845 MessageSegment::Thinking { text, signature } => {
846 messages.push_str("**Thinking**:\n\n");
847 if let Some(sig) = signature {
848 messages.push_str(&format!("Signature: {}\n\n", sig));
849 }
850 messages.push_str(&text);
851 messages.push_str("\n");
852 }
853 MessageSegment::ToolUse(ToolUseSegment { name, input, .. }) => {
854 messages.push_str(&format!("**Tool Use**: {}\n\n", name));
855 messages.push_str(&format!("Input: {:?}\n\n", input));
856 }
857 }
858 }
859 }
860
861 messages
862}
863
864fn push_role(role: &Role, buf: &mut String, assistant_message_number: &mut u32) {
865 match role {
866 Role::System => buf.push_str("# ⚙️ SYSTEM\n\n"),
867 Role::User => buf.push_str("# 👤 USER\n\n"),
868 Role::Assistant => {
869 buf.push_str(&format!("# 🤖 ASSISTANT {assistant_message_number}\n\n"));
870 *assistant_message_number = *assistant_message_number + 1;
871 }
872 }
873}
874
875pub async fn send_language_model_request(
876 model: Arc<dyn LanguageModel>,
877 request: LanguageModelRequest,
878 cx: &AsyncApp,
879) -> anyhow::Result<String> {
880 match model.stream_completion_text(request, &cx).await {
881 Ok(mut stream) => {
882 let mut full_response = String::new();
883 while let Some(chunk_result) = stream.stream.next().await {
884 match chunk_result {
885 Ok(chunk_str) => {
886 full_response.push_str(&chunk_str);
887 }
888 Err(err) => {
889 anyhow::bail!("Error receiving response from language model: {err}");
890 }
891 }
892 }
893 Ok(full_response)
894 }
895 Err(err) => Err(anyhow!(
896 "Failed to get response from language model. Error was: {err}"
897 )),
898 }
899}
900
901pub struct RequestMarkdown {
902 pub tools: String,
903 pub messages: String,
904}
905
906impl RequestMarkdown {
907 pub fn new(request: &LanguageModelRequest) -> Self {
908 let mut tools = String::new();
909 let mut messages = String::new();
910 let mut assistant_message_number: u32 = 1;
911
912 // Print the tools
913 if !request.tools.is_empty() {
914 for tool in &request.tools {
915 write!(&mut tools, "# {}\n\n", tool.name).unwrap();
916 write!(&mut tools, "{}\n\n", tool.description).unwrap();
917 write!(
918 &mut tools,
919 "{}\n",
920 MarkdownCodeBlock {
921 tag: "json",
922 text: &format!("{:#}", tool.input_schema)
923 }
924 )
925 .unwrap();
926 }
927 }
928
929 // Print the messages
930 for message in &request.messages {
931 push_role(&message.role, &mut messages, &mut assistant_message_number);
932
933 for content in &message.content {
934 match content {
935 MessageContent::Text(text) => {
936 messages.push_str(text);
937 messages.push_str("\n\n");
938 }
939 MessageContent::Image(_) => {
940 messages.push_str("[IMAGE DATA]\n\n");
941 }
942 MessageContent::Thinking { text, signature } => {
943 messages.push_str("**Thinking**:\n\n");
944 if let Some(sig) = signature {
945 messages.push_str(&format!("Signature: {}\n\n", sig));
946 }
947 messages.push_str(text);
948 messages.push_str("\n");
949 }
950 MessageContent::RedactedThinking(items) => {
951 messages.push_str(&format!(
952 "**Redacted Thinking**: {} item(s)\n\n",
953 items.len()
954 ));
955 }
956 MessageContent::ToolUse(tool_use) => {
957 messages.push_str(&format!(
958 "**Tool Use**: {} (ID: {})\n",
959 tool_use.name, tool_use.id
960 ));
961 messages.push_str(&format!(
962 "{}\n",
963 MarkdownCodeBlock {
964 tag: "json",
965 text: &format!("{:#}", tool_use.input)
966 }
967 ));
968 }
969 MessageContent::ToolResult(tool_result) => {
970 messages.push_str(&format!(
971 "**Tool Result**: {} (ID: {})\n\n",
972 tool_result.tool_name, tool_result.tool_use_id
973 ));
974 if tool_result.is_error {
975 messages.push_str("**ERROR:**\n");
976 }
977
978 match &tool_result.content {
979 LanguageModelToolResultContent::Text(text) => {
980 writeln!(messages, "{text}\n").ok();
981 }
982 LanguageModelToolResultContent::Image(image) => {
983 writeln!(messages, "\n", image.source).ok();
984 }
985 }
986
987 if let Some(output) = tool_result.output.as_ref() {
988 writeln!(
989 messages,
990 "**Debug Output**:\n\n```json\n{}\n```\n",
991 serde_json::to_string_pretty(output).unwrap()
992 )
993 .unwrap();
994 }
995 }
996 }
997 }
998 }
999
1000 Self { tools, messages }
1001 }
1002}
1003
1004pub fn response_events_to_markdown(
1005 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1006) -> String {
1007 let mut response = String::new();
1008 // Print the response events if any
1009 response.push_str("# Response\n\n");
1010 let mut text_buffer = String::new();
1011 let mut thinking_buffer = String::new();
1012
1013 let flush_buffers =
1014 |output: &mut String, text_buffer: &mut String, thinking_buffer: &mut String| {
1015 if !text_buffer.is_empty() {
1016 output.push_str(&format!("**Text**:\n{}\n\n", text_buffer));
1017 text_buffer.clear();
1018 }
1019 if !thinking_buffer.is_empty() {
1020 output.push_str(&format!("**Thinking**:\n{}\n\n", thinking_buffer));
1021 thinking_buffer.clear();
1022 }
1023 };
1024
1025 for event in response_events {
1026 match event {
1027 Ok(LanguageModelCompletionEvent::Text(text)) => {
1028 text_buffer.push_str(text);
1029 }
1030 Ok(LanguageModelCompletionEvent::Thinking { text, .. }) => {
1031 thinking_buffer.push_str(text);
1032 }
1033 Ok(LanguageModelCompletionEvent::RedactedThinking { .. }) => {}
1034 Ok(LanguageModelCompletionEvent::Stop(reason)) => {
1035 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1036 response.push_str(&format!("**Stop**: {:?}\n\n", reason));
1037 }
1038 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1039 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1040 response.push_str(&format!(
1041 "**Tool Use**: {} (ID: {})\n",
1042 tool_use.name, tool_use.id
1043 ));
1044 response.push_str(&format!(
1045 "{}\n",
1046 MarkdownCodeBlock {
1047 tag: "json",
1048 text: &format!("{:#}", tool_use.input)
1049 }
1050 ));
1051 }
1052 Ok(
1053 LanguageModelCompletionEvent::UsageUpdate(_)
1054 | LanguageModelCompletionEvent::StartMessage { .. }
1055 | LanguageModelCompletionEvent::StatusUpdate { .. },
1056 ) => {}
1057 Err(error) => {
1058 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1059 response.push_str(&format!("**Error**: {}\n\n", error));
1060 }
1061 }
1062 }
1063
1064 flush_buffers(&mut response, &mut text_buffer, &mut thinking_buffer);
1065
1066 response
1067}
1068
1069#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
1070pub struct ThreadDialog {
1071 pub request: LanguageModelRequest,
1072 pub response_events: Vec<std::result::Result<LanguageModelCompletionEvent, String>>,
1073}
1074
1075impl ThreadDialog {
1076 pub fn new(
1077 request: &LanguageModelRequest,
1078 response_events: &[std::result::Result<LanguageModelCompletionEvent, String>],
1079 ) -> Self {
1080 Self {
1081 request: request.clone(),
1082 response_events: response_events.to_vec(),
1083 }
1084 }
1085
1086 /// Represents all request and response messages in a unified format.
1087 ///
1088 /// Specifically, it appends the assistant's response (derived from response events)
1089 /// as a new message to existing messages in the request.
1090 pub fn to_combined_request(&self) -> LanguageModelRequest {
1091 let mut request = self.request.clone();
1092 if let Some(assistant_message) = self.response_events_to_message() {
1093 request.messages.push(assistant_message);
1094 }
1095 request
1096 }
1097 fn response_events_to_message(&self) -> Option<LanguageModelRequestMessage> {
1098 let response_events = &self.response_events;
1099 let mut content: Vec<MessageContent> = Vec::new();
1100 let mut current_text = String::new();
1101
1102 let flush_text = |text: &mut String, content: &mut Vec<MessageContent>| {
1103 if !text.is_empty() {
1104 content.push(MessageContent::Text(std::mem::take(text)));
1105 }
1106 };
1107
1108 for event in response_events {
1109 match event {
1110 Ok(LanguageModelCompletionEvent::Text(text)) => {
1111 current_text.push_str(text);
1112 }
1113
1114 Ok(LanguageModelCompletionEvent::ToolUse(tool_use)) => {
1115 flush_text(&mut current_text, &mut content);
1116 if tool_use.is_input_complete {
1117 content.push(MessageContent::ToolUse(tool_use.clone()));
1118 }
1119 }
1120 Ok(LanguageModelCompletionEvent::Thinking { text, signature }) => {
1121 flush_text(&mut current_text, &mut content);
1122 content.push(MessageContent::Thinking {
1123 text: text.clone(),
1124 signature: signature.clone(),
1125 });
1126 }
1127
1128 // Skip these
1129 Ok(LanguageModelCompletionEvent::UsageUpdate(_))
1130 | Ok(LanguageModelCompletionEvent::RedactedThinking { .. })
1131 | Ok(LanguageModelCompletionEvent::StatusUpdate { .. })
1132 | Ok(LanguageModelCompletionEvent::StartMessage { .. })
1133 | Ok(LanguageModelCompletionEvent::Stop(_)) => {}
1134
1135 Err(error) => {
1136 flush_text(&mut current_text, &mut content);
1137 content.push(MessageContent::Text(format!("ERROR: {}", error)));
1138 }
1139 }
1140 }
1141
1142 flush_text(&mut current_text, &mut content);
1143
1144 if !content.is_empty() {
1145 Some(LanguageModelRequestMessage {
1146 role: Role::Assistant,
1147 content,
1148 cache: false,
1149 })
1150 } else {
1151 None
1152 }
1153 }
1154}
1155
1156#[cfg(test)]
1157mod test {
1158 use super::*;
1159
1160 #[test]
1161 fn test_parse_judge_output() {
1162 let response = r#"
1163 <analysis>The model did a good job but there were still compilations errors.</analysis>
1164 <passed>true</passed>
1165 "#
1166 .unindent();
1167
1168 let output = parse_assertion_result(&response).unwrap();
1169 assert_eq!(
1170 output.analysis,
1171 Some("The model did a good job but there were still compilations errors.".into())
1172 );
1173 assert_eq!(output.passed, true);
1174
1175 let response = r#"
1176 Text around ignored
1177
1178 <analysis>
1179 Failed to compile:
1180 - Error 1
1181 - Error 2
1182 </analysis>
1183
1184 <passed>false</passed>
1185 "#
1186 .unindent();
1187
1188 let output = parse_assertion_result(&response).unwrap();
1189 assert_eq!(
1190 output.analysis,
1191 Some("Failed to compile:\n- Error 1\n- Error 2".into())
1192 );
1193 assert_eq!(output.passed, false);
1194 }
1195}