1use std::io::Write;
2use std::sync::Arc;
3
4use anyhow::{Context as _, Result};
5use assistant_tool::ToolWorkingSet;
6use chrono::{DateTime, Utc};
7use collections::{BTreeMap, HashMap, HashSet};
8use futures::StreamExt as _;
9use gpui::{App, AppContext, Context, Entity, EventEmitter, SharedString, Task};
10use language_model::{
11 LanguageModel, LanguageModelCompletionEvent, LanguageModelRegistry, LanguageModelRequest,
12 LanguageModelRequestMessage, LanguageModelRequestTool, LanguageModelToolResult,
13 LanguageModelToolUseId, MaxMonthlySpendReachedError, MessageContent, PaymentRequiredError,
14 Role, StopReason,
15};
16use project::Project;
17use prompt_store::{AssistantSystemPromptWorktree, PromptBuilder};
18use scripting_tool::{ScriptingSession, ScriptingTool};
19use serde::{Deserialize, Serialize};
20use util::{post_inc, ResultExt, TryFutureExt as _};
21use uuid::Uuid;
22
23use crate::context::{attach_context_to_message, ContextId, ContextSnapshot};
24use crate::thread_store::SavedThread;
25use crate::tool_use::{PendingToolUse, ToolUse, ToolUseState};
26
27#[derive(Debug, Clone, Copy)]
28pub enum RequestKind {
29 Chat,
30 /// Used when summarizing a thread.
31 Summarize,
32}
33
34#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Serialize, Deserialize)]
35pub struct ThreadId(Arc<str>);
36
37impl ThreadId {
38 pub fn new() -> Self {
39 Self(Uuid::new_v4().to_string().into())
40 }
41}
42
43impl std::fmt::Display for ThreadId {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 write!(f, "{}", self.0)
46 }
47}
48
49#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Serialize, Deserialize)]
50pub struct MessageId(pub(crate) usize);
51
52impl MessageId {
53 fn post_inc(&mut self) -> Self {
54 Self(post_inc(&mut self.0))
55 }
56}
57
58/// A message in a [`Thread`].
59#[derive(Debug, Clone)]
60pub struct Message {
61 pub id: MessageId,
62 pub role: Role,
63 pub text: String,
64}
65
66/// A thread of conversation with the LLM.
67pub struct Thread {
68 id: ThreadId,
69 updated_at: DateTime<Utc>,
70 summary: Option<SharedString>,
71 pending_summary: Task<Option<()>>,
72 messages: Vec<Message>,
73 next_message_id: MessageId,
74 context: BTreeMap<ContextId, ContextSnapshot>,
75 context_by_message: HashMap<MessageId, Vec<ContextId>>,
76 completion_count: usize,
77 pending_completions: Vec<PendingCompletion>,
78 project: Entity<Project>,
79 prompt_builder: Arc<PromptBuilder>,
80 tools: Arc<ToolWorkingSet>,
81 tool_use: ToolUseState,
82 scripting_session: Entity<ScriptingSession>,
83 scripting_tool_use: ToolUseState,
84}
85
86impl Thread {
87 pub fn new(
88 project: Entity<Project>,
89 tools: Arc<ToolWorkingSet>,
90 prompt_builder: Arc<PromptBuilder>,
91 cx: &mut Context<Self>,
92 ) -> Self {
93 let scripting_session = cx.new(|cx| ScriptingSession::new(project.clone(), cx));
94
95 Self {
96 id: ThreadId::new(),
97 updated_at: Utc::now(),
98 summary: None,
99 pending_summary: Task::ready(None),
100 messages: Vec::new(),
101 next_message_id: MessageId(0),
102 context: BTreeMap::default(),
103 context_by_message: HashMap::default(),
104 completion_count: 0,
105 pending_completions: Vec::new(),
106 project,
107 prompt_builder,
108 tools,
109 tool_use: ToolUseState::new(),
110 scripting_session,
111 scripting_tool_use: ToolUseState::new(),
112 }
113 }
114
115 pub fn from_saved(
116 id: ThreadId,
117 saved: SavedThread,
118 project: Entity<Project>,
119 tools: Arc<ToolWorkingSet>,
120 prompt_builder: Arc<PromptBuilder>,
121 cx: &mut Context<Self>,
122 ) -> Self {
123 let next_message_id = MessageId(
124 saved
125 .messages
126 .last()
127 .map(|message| message.id.0 + 1)
128 .unwrap_or(0),
129 );
130 let tool_use =
131 ToolUseState::from_saved_messages(&saved.messages, |name| name != ScriptingTool::NAME);
132 let scripting_tool_use =
133 ToolUseState::from_saved_messages(&saved.messages, |name| name == ScriptingTool::NAME);
134 let scripting_session = cx.new(|cx| ScriptingSession::new(project.clone(), cx));
135
136 Self {
137 id,
138 updated_at: saved.updated_at,
139 summary: Some(saved.summary),
140 pending_summary: Task::ready(None),
141 messages: saved
142 .messages
143 .into_iter()
144 .map(|message| Message {
145 id: message.id,
146 role: message.role,
147 text: message.text,
148 })
149 .collect(),
150 next_message_id,
151 context: BTreeMap::default(),
152 context_by_message: HashMap::default(),
153 completion_count: 0,
154 pending_completions: Vec::new(),
155 project,
156 prompt_builder,
157 tools,
158 tool_use,
159 scripting_session,
160 scripting_tool_use,
161 }
162 }
163
164 pub fn id(&self) -> &ThreadId {
165 &self.id
166 }
167
168 pub fn is_empty(&self) -> bool {
169 self.messages.is_empty()
170 }
171
172 pub fn updated_at(&self) -> DateTime<Utc> {
173 self.updated_at
174 }
175
176 pub fn touch_updated_at(&mut self) {
177 self.updated_at = Utc::now();
178 }
179
180 pub fn summary(&self) -> Option<SharedString> {
181 self.summary.clone()
182 }
183
184 pub fn summary_or_default(&self) -> SharedString {
185 const DEFAULT: SharedString = SharedString::new_static("New Thread");
186 self.summary.clone().unwrap_or(DEFAULT)
187 }
188
189 pub fn set_summary(&mut self, summary: impl Into<SharedString>, cx: &mut Context<Self>) {
190 self.summary = Some(summary.into());
191 cx.emit(ThreadEvent::SummaryChanged);
192 }
193
194 pub fn message(&self, id: MessageId) -> Option<&Message> {
195 self.messages.iter().find(|message| message.id == id)
196 }
197
198 pub fn messages(&self) -> impl Iterator<Item = &Message> {
199 self.messages.iter()
200 }
201
202 pub fn is_streaming(&self) -> bool {
203 !self.pending_completions.is_empty()
204 }
205
206 pub fn tools(&self) -> &Arc<ToolWorkingSet> {
207 &self.tools
208 }
209
210 pub fn context_for_message(&self, id: MessageId) -> Option<Vec<ContextSnapshot>> {
211 let context = self.context_by_message.get(&id)?;
212 Some(
213 context
214 .into_iter()
215 .filter_map(|context_id| self.context.get(&context_id))
216 .cloned()
217 .collect::<Vec<_>>(),
218 )
219 }
220
221 /// Returns whether all of the tool uses have finished running.
222 pub fn all_tools_finished(&self) -> bool {
223 let mut all_pending_tool_uses = self
224 .tool_use
225 .pending_tool_uses()
226 .into_iter()
227 .chain(self.scripting_tool_use.pending_tool_uses());
228
229 // If the only pending tool uses left are the ones with errors, then that means that we've finished running all
230 // of the pending tools.
231 all_pending_tool_uses.all(|tool_use| tool_use.status.is_error())
232 }
233
234 pub fn tool_uses_for_message(&self, id: MessageId) -> Vec<ToolUse> {
235 self.tool_use.tool_uses_for_message(id)
236 }
237
238 pub fn scripting_tool_uses_for_message(&self, id: MessageId) -> Vec<ToolUse> {
239 self.scripting_tool_use.tool_uses_for_message(id)
240 }
241
242 pub fn tool_results_for_message(&self, id: MessageId) -> Vec<&LanguageModelToolResult> {
243 self.tool_use.tool_results_for_message(id)
244 }
245
246 pub fn scripting_tool_results_for_message(
247 &self,
248 id: MessageId,
249 ) -> Vec<&LanguageModelToolResult> {
250 self.scripting_tool_use.tool_results_for_message(id)
251 }
252
253 pub fn scripting_changed_buffers<'a>(
254 &self,
255 cx: &'a App,
256 ) -> impl ExactSizeIterator<Item = &'a Entity<language::Buffer>> {
257 self.scripting_session.read(cx).changed_buffers()
258 }
259
260 pub fn message_has_tool_results(&self, message_id: MessageId) -> bool {
261 self.tool_use.message_has_tool_results(message_id)
262 }
263
264 pub fn message_has_scripting_tool_results(&self, message_id: MessageId) -> bool {
265 self.scripting_tool_use.message_has_tool_results(message_id)
266 }
267
268 pub fn insert_user_message(
269 &mut self,
270 text: impl Into<String>,
271 context: Vec<ContextSnapshot>,
272 cx: &mut Context<Self>,
273 ) -> MessageId {
274 let message_id = self.insert_message(Role::User, text, cx);
275 let context_ids = context.iter().map(|context| context.id).collect::<Vec<_>>();
276 self.context
277 .extend(context.into_iter().map(|context| (context.id, context)));
278 self.context_by_message.insert(message_id, context_ids);
279 message_id
280 }
281
282 pub fn insert_message(
283 &mut self,
284 role: Role,
285 text: impl Into<String>,
286 cx: &mut Context<Self>,
287 ) -> MessageId {
288 let id = self.next_message_id.post_inc();
289 self.messages.push(Message {
290 id,
291 role,
292 text: text.into(),
293 });
294 self.touch_updated_at();
295 cx.emit(ThreadEvent::MessageAdded(id));
296 id
297 }
298
299 pub fn edit_message(
300 &mut self,
301 id: MessageId,
302 new_role: Role,
303 new_text: String,
304 cx: &mut Context<Self>,
305 ) -> bool {
306 let Some(message) = self.messages.iter_mut().find(|message| message.id == id) else {
307 return false;
308 };
309 message.role = new_role;
310 message.text = new_text;
311 self.touch_updated_at();
312 cx.emit(ThreadEvent::MessageEdited(id));
313 true
314 }
315
316 pub fn delete_message(&mut self, id: MessageId, cx: &mut Context<Self>) -> bool {
317 let Some(index) = self.messages.iter().position(|message| message.id == id) else {
318 return false;
319 };
320 self.messages.remove(index);
321 self.context_by_message.remove(&id);
322 self.touch_updated_at();
323 cx.emit(ThreadEvent::MessageDeleted(id));
324 true
325 }
326
327 /// Returns the representation of this [`Thread`] in a textual form.
328 ///
329 /// This is the representation we use when attaching a thread as context to another thread.
330 pub fn text(&self) -> String {
331 let mut text = String::new();
332
333 for message in &self.messages {
334 text.push_str(match message.role {
335 language_model::Role::User => "User:",
336 language_model::Role::Assistant => "Assistant:",
337 language_model::Role::System => "System:",
338 });
339 text.push('\n');
340
341 text.push_str(&message.text);
342 text.push('\n');
343 }
344
345 text
346 }
347
348 pub fn send_to_model(
349 &mut self,
350 model: Arc<dyn LanguageModel>,
351 request_kind: RequestKind,
352 cx: &mut Context<Self>,
353 ) {
354 let mut request = self.to_completion_request(request_kind, cx);
355 request.tools = {
356 let mut tools = Vec::new();
357
358 if self.tools.is_scripting_tool_enabled() {
359 tools.push(LanguageModelRequestTool {
360 name: ScriptingTool::NAME.into(),
361 description: ScriptingTool::DESCRIPTION.into(),
362 input_schema: ScriptingTool::input_schema(),
363 });
364 }
365
366 tools.extend(self.tools().enabled_tools(cx).into_iter().map(|tool| {
367 LanguageModelRequestTool {
368 name: tool.name(),
369 description: tool.description(),
370 input_schema: tool.input_schema(),
371 }
372 }));
373
374 tools
375 };
376
377 self.stream_completion(request, model, cx);
378 }
379
380 pub fn to_completion_request(
381 &self,
382 request_kind: RequestKind,
383 cx: &App,
384 ) -> LanguageModelRequest {
385 let worktree_root_names = self
386 .project
387 .read(cx)
388 .visible_worktrees(cx)
389 .map(|worktree| {
390 let worktree = worktree.read(cx);
391 AssistantSystemPromptWorktree {
392 root_name: worktree.root_name().into(),
393 abs_path: worktree.abs_path(),
394 }
395 })
396 .collect::<Vec<_>>();
397 let system_prompt = self
398 .prompt_builder
399 .generate_assistant_system_prompt(worktree_root_names)
400 .context("failed to generate assistant system prompt")
401 .log_err()
402 .unwrap_or_default();
403
404 let mut request = LanguageModelRequest {
405 messages: vec![LanguageModelRequestMessage {
406 role: Role::System,
407 content: vec![MessageContent::Text(system_prompt)],
408 cache: true,
409 }],
410 tools: Vec::new(),
411 stop: Vec::new(),
412 temperature: None,
413 };
414
415 let mut referenced_context_ids = HashSet::default();
416
417 for message in &self.messages {
418 if let Some(context_ids) = self.context_by_message.get(&message.id) {
419 referenced_context_ids.extend(context_ids);
420 }
421
422 let mut request_message = LanguageModelRequestMessage {
423 role: message.role,
424 content: Vec::new(),
425 cache: false,
426 };
427
428 match request_kind {
429 RequestKind::Chat => {
430 self.tool_use
431 .attach_tool_results(message.id, &mut request_message);
432 self.scripting_tool_use
433 .attach_tool_results(message.id, &mut request_message);
434 }
435 RequestKind::Summarize => {
436 // We don't care about tool use during summarization.
437 }
438 }
439
440 if !message.text.is_empty() {
441 request_message
442 .content
443 .push(MessageContent::Text(message.text.clone()));
444 }
445
446 match request_kind {
447 RequestKind::Chat => {
448 self.tool_use
449 .attach_tool_uses(message.id, &mut request_message);
450 self.scripting_tool_use
451 .attach_tool_uses(message.id, &mut request_message);
452 }
453 RequestKind::Summarize => {
454 // We don't care about tool use during summarization.
455 }
456 };
457
458 request.messages.push(request_message);
459 }
460
461 if !referenced_context_ids.is_empty() {
462 let mut context_message = LanguageModelRequestMessage {
463 role: Role::User,
464 content: Vec::new(),
465 cache: false,
466 };
467
468 let referenced_context = referenced_context_ids
469 .into_iter()
470 .filter_map(|context_id| self.context.get(context_id))
471 .cloned();
472 attach_context_to_message(&mut context_message, referenced_context);
473
474 request.messages.push(context_message);
475 }
476
477 request
478 }
479
480 pub fn stream_completion(
481 &mut self,
482 request: LanguageModelRequest,
483 model: Arc<dyn LanguageModel>,
484 cx: &mut Context<Self>,
485 ) {
486 let pending_completion_id = post_inc(&mut self.completion_count);
487
488 let task = cx.spawn(|thread, mut cx| async move {
489 let stream = model.stream_completion(request, &cx);
490 let stream_completion = async {
491 let mut events = stream.await?;
492 let mut stop_reason = StopReason::EndTurn;
493
494 while let Some(event) = events.next().await {
495 let event = event?;
496
497 thread.update(&mut cx, |thread, cx| {
498 match event {
499 LanguageModelCompletionEvent::StartMessage { .. } => {
500 thread.insert_message(Role::Assistant, String::new(), cx);
501 }
502 LanguageModelCompletionEvent::Stop(reason) => {
503 stop_reason = reason;
504 }
505 LanguageModelCompletionEvent::Text(chunk) => {
506 if let Some(last_message) = thread.messages.last_mut() {
507 if last_message.role == Role::Assistant {
508 last_message.text.push_str(&chunk);
509 cx.emit(ThreadEvent::StreamedAssistantText(
510 last_message.id,
511 chunk,
512 ));
513 } else {
514 // If we won't have an Assistant message yet, assume this chunk marks the beginning
515 // of a new Assistant response.
516 //
517 // Importantly: We do *not* want to emit a `StreamedAssistantText` event here, as it
518 // will result in duplicating the text of the chunk in the rendered Markdown.
519 thread.insert_message(Role::Assistant, chunk, cx);
520 };
521 }
522 }
523 LanguageModelCompletionEvent::ToolUse(tool_use) => {
524 if let Some(last_assistant_message) = thread
525 .messages
526 .iter()
527 .rfind(|message| message.role == Role::Assistant)
528 {
529 if tool_use.name.as_ref() == ScriptingTool::NAME {
530 thread
531 .scripting_tool_use
532 .request_tool_use(last_assistant_message.id, tool_use);
533 } else {
534 thread
535 .tool_use
536 .request_tool_use(last_assistant_message.id, tool_use);
537 }
538 }
539 }
540 }
541
542 thread.touch_updated_at();
543 cx.emit(ThreadEvent::StreamedCompletion);
544 cx.notify();
545 })?;
546
547 smol::future::yield_now().await;
548 }
549
550 thread.update(&mut cx, |thread, cx| {
551 thread
552 .pending_completions
553 .retain(|completion| completion.id != pending_completion_id);
554
555 if thread.summary.is_none() && thread.messages.len() >= 2 {
556 thread.summarize(cx);
557 }
558 })?;
559
560 anyhow::Ok(stop_reason)
561 };
562
563 let result = stream_completion.await;
564
565 thread
566 .update(&mut cx, |thread, cx| match result.as_ref() {
567 Ok(stop_reason) => match stop_reason {
568 StopReason::ToolUse => {
569 cx.emit(ThreadEvent::UsePendingTools);
570 }
571 StopReason::EndTurn => {}
572 StopReason::MaxTokens => {}
573 },
574 Err(error) => {
575 if error.is::<PaymentRequiredError>() {
576 cx.emit(ThreadEvent::ShowError(ThreadError::PaymentRequired));
577 } else if error.is::<MaxMonthlySpendReachedError>() {
578 cx.emit(ThreadEvent::ShowError(ThreadError::MaxMonthlySpendReached));
579 } else {
580 let error_message = error
581 .chain()
582 .map(|err| err.to_string())
583 .collect::<Vec<_>>()
584 .join("\n");
585 cx.emit(ThreadEvent::ShowError(ThreadError::Message(
586 SharedString::from(error_message.clone()),
587 )));
588 }
589
590 thread.cancel_last_completion();
591 }
592 })
593 .ok();
594 });
595
596 self.pending_completions.push(PendingCompletion {
597 id: pending_completion_id,
598 _task: task,
599 });
600 }
601
602 pub fn summarize(&mut self, cx: &mut Context<Self>) {
603 let Some(provider) = LanguageModelRegistry::read_global(cx).active_provider() else {
604 return;
605 };
606 let Some(model) = LanguageModelRegistry::read_global(cx).active_model() else {
607 return;
608 };
609
610 if !provider.is_authenticated(cx) {
611 return;
612 }
613
614 let mut request = self.to_completion_request(RequestKind::Summarize, cx);
615 request.messages.push(LanguageModelRequestMessage {
616 role: Role::User,
617 content: vec![
618 "Generate a concise 3-7 word title for this conversation, omitting punctuation. Go straight to the title, without any preamble and prefix like `Here's a concise suggestion:...` or `Title:`"
619 .into(),
620 ],
621 cache: false,
622 });
623
624 self.pending_summary = cx.spawn(|this, mut cx| {
625 async move {
626 let stream = model.stream_completion_text(request, &cx);
627 let mut messages = stream.await?;
628
629 let mut new_summary = String::new();
630 while let Some(message) = messages.stream.next().await {
631 let text = message?;
632 let mut lines = text.lines();
633 new_summary.extend(lines.next());
634
635 // Stop if the LLM generated multiple lines.
636 if lines.next().is_some() {
637 break;
638 }
639 }
640
641 this.update(&mut cx, |this, cx| {
642 if !new_summary.is_empty() {
643 this.summary = Some(new_summary.into());
644 }
645
646 cx.emit(ThreadEvent::SummaryChanged);
647 })?;
648
649 anyhow::Ok(())
650 }
651 .log_err()
652 });
653 }
654
655 pub fn use_pending_tools(&mut self, cx: &mut Context<Self>) {
656 let request = self.to_completion_request(RequestKind::Chat, cx);
657 let pending_tool_uses = self
658 .tool_use
659 .pending_tool_uses()
660 .into_iter()
661 .filter(|tool_use| tool_use.status.is_idle())
662 .cloned()
663 .collect::<Vec<_>>();
664
665 for tool_use in pending_tool_uses {
666 if let Some(tool) = self.tools.tool(&tool_use.name, cx) {
667 let task = tool.run(tool_use.input, &request.messages, self.project.clone(), cx);
668
669 self.insert_tool_output(tool_use.id.clone(), task, cx);
670 }
671 }
672
673 let pending_scripting_tool_uses = self
674 .scripting_tool_use
675 .pending_tool_uses()
676 .into_iter()
677 .filter(|tool_use| tool_use.status.is_idle())
678 .cloned()
679 .collect::<Vec<_>>();
680
681 for scripting_tool_use in pending_scripting_tool_uses {
682 let task = match ScriptingTool::deserialize_input(scripting_tool_use.input) {
683 Err(err) => Task::ready(Err(err.into())),
684 Ok(input) => {
685 let (script_id, script_task) =
686 self.scripting_session.update(cx, move |session, cx| {
687 session.run_script(input.lua_script, cx)
688 });
689
690 let session = self.scripting_session.clone();
691 cx.spawn(|_, cx| async move {
692 script_task.await;
693
694 let message = session.read_with(&cx, |session, _cx| {
695 // Using a id to get the script output seems impractical.
696 // Why not just include it in the Task result?
697 // This is because we'll later report the script state as it runs,
698 session
699 .get(script_id)
700 .output_message_for_llm()
701 .expect("Script shouldn't still be running")
702 })?;
703
704 Ok(message)
705 })
706 }
707 };
708
709 self.insert_scripting_tool_output(scripting_tool_use.id.clone(), task, cx);
710 }
711 }
712
713 pub fn insert_tool_output(
714 &mut self,
715 tool_use_id: LanguageModelToolUseId,
716 output: Task<Result<String>>,
717 cx: &mut Context<Self>,
718 ) {
719 let insert_output_task = cx.spawn(|thread, mut cx| {
720 let tool_use_id = tool_use_id.clone();
721 async move {
722 let output = output.await;
723 thread
724 .update(&mut cx, |thread, cx| {
725 let pending_tool_use = thread
726 .tool_use
727 .insert_tool_output(tool_use_id.clone(), output);
728
729 cx.emit(ThreadEvent::ToolFinished {
730 tool_use_id,
731 pending_tool_use,
732 });
733 })
734 .ok();
735 }
736 });
737
738 self.tool_use
739 .run_pending_tool(tool_use_id, insert_output_task);
740 }
741
742 pub fn insert_scripting_tool_output(
743 &mut self,
744 tool_use_id: LanguageModelToolUseId,
745 output: Task<Result<String>>,
746 cx: &mut Context<Self>,
747 ) {
748 let insert_output_task = cx.spawn(|thread, mut cx| {
749 let tool_use_id = tool_use_id.clone();
750 async move {
751 let output = output.await;
752 thread
753 .update(&mut cx, |thread, cx| {
754 let pending_tool_use = thread
755 .scripting_tool_use
756 .insert_tool_output(tool_use_id.clone(), output);
757
758 cx.emit(ThreadEvent::ToolFinished {
759 tool_use_id,
760 pending_tool_use,
761 });
762 })
763 .ok();
764 }
765 });
766
767 self.scripting_tool_use
768 .run_pending_tool(tool_use_id, insert_output_task);
769 }
770
771 pub fn send_tool_results_to_model(
772 &mut self,
773 model: Arc<dyn LanguageModel>,
774 cx: &mut Context<Self>,
775 ) {
776 // Insert a user message to contain the tool results.
777 self.insert_user_message(
778 // TODO: Sending up a user message without any content results in the model sending back
779 // responses that also don't have any content. We currently don't handle this case well,
780 // so for now we provide some text to keep the model on track.
781 "Here are the tool results.",
782 Vec::new(),
783 cx,
784 );
785 self.send_to_model(model, RequestKind::Chat, cx);
786 }
787
788 /// Cancels the last pending completion, if there are any pending.
789 ///
790 /// Returns whether a completion was canceled.
791 pub fn cancel_last_completion(&mut self) -> bool {
792 if let Some(_last_completion) = self.pending_completions.pop() {
793 true
794 } else {
795 false
796 }
797 }
798
799 pub fn to_markdown(&self) -> Result<String> {
800 let mut markdown = Vec::new();
801
802 if let Some(summary) = self.summary() {
803 writeln!(markdown, "# {summary}\n")?;
804 };
805
806 for message in self.messages() {
807 writeln!(
808 markdown,
809 "## {role}\n",
810 role = match message.role {
811 Role::User => "User",
812 Role::Assistant => "Assistant",
813 Role::System => "System",
814 }
815 )?;
816 writeln!(markdown, "{}\n", message.text)?;
817
818 for tool_use in self.tool_uses_for_message(message.id) {
819 writeln!(
820 markdown,
821 "**Use Tool: {} ({})**",
822 tool_use.name, tool_use.id
823 )?;
824 writeln!(markdown, "```json")?;
825 writeln!(
826 markdown,
827 "{}",
828 serde_json::to_string_pretty(&tool_use.input)?
829 )?;
830 writeln!(markdown, "```")?;
831 }
832
833 for tool_result in self.tool_results_for_message(message.id) {
834 write!(markdown, "**Tool Results: {}", tool_result.tool_use_id)?;
835 if tool_result.is_error {
836 write!(markdown, " (Error)")?;
837 }
838
839 writeln!(markdown, "**\n")?;
840 writeln!(markdown, "{}", tool_result.content)?;
841 }
842 }
843
844 Ok(String::from_utf8_lossy(&markdown).to_string())
845 }
846}
847
848#[derive(Debug, Clone)]
849pub enum ThreadError {
850 PaymentRequired,
851 MaxMonthlySpendReached,
852 Message(SharedString),
853}
854
855#[derive(Debug, Clone)]
856pub enum ThreadEvent {
857 ShowError(ThreadError),
858 StreamedCompletion,
859 StreamedAssistantText(MessageId, String),
860 MessageAdded(MessageId),
861 MessageEdited(MessageId),
862 MessageDeleted(MessageId),
863 SummaryChanged,
864 UsePendingTools,
865 ToolFinished {
866 #[allow(unused)]
867 tool_use_id: LanguageModelToolUseId,
868 /// The pending tool use that corresponds to this tool.
869 pending_tool_use: Option<PendingToolUse>,
870 },
871}
872
873impl EventEmitter<ThreadEvent> for Thread {}
874
875struct PendingCompletion {
876 id: usize,
877 _task: Task<()>,
878}