1use std::collections::{HashSet, VecDeque};
8use std::pin::Pin;
9use std::sync::{
10 Arc,
11 atomic::{AtomicBool, Ordering},
12};
13use std::task::{Context as TaskContext, Poll};
14
15use crate::client::{
16 agent::RemoteAgent,
17 apply::{
18 Applier, Changed, MessageChangeKind, ReasoningChangeKind, Subagent, SubagentChangeKind,
19 },
20 chunks::ChunkNormalizer,
21 error::{Error, Result},
22 interrupts::InterruptExt,
23 transport::{EventStream, Transport},
24 verify::Verifier,
25};
26use crate::{
27 Context, Event, Interrupt, Message, MessageId, ReasoningMessage, ResumeEntry, RunAgentInput,
28 RunId, RunOutcome, ThreadId, Tool,
29};
30use futures_core::Stream;
31use futures_util::{StreamExt, task::AtomicWaker};
32use serde::{Deserialize, Serialize, de::DeserializeOwned};
33use serde_json::Value;
34
35#[cfg(not(target_family = "wasm"))]
36type Observer = Box<dyn FnMut(&Event) + Send>;
37#[cfg(target_family = "wasm")]
38type Observer = Box<dyn FnMut(&Event)>;
39#[cfg(not(target_family = "wasm"))]
40type IdGenerator = Box<dyn FnMut() -> Result<String> + Send>;
41#[cfg(target_family = "wasm")]
42type IdGenerator = Box<dyn FnMut() -> Result<String>>;
43
44#[derive(Debug)]
49#[non_exhaustive]
50pub enum Update<S = Value> {
51 Message(MessageUpdate),
53 Messages(Vec<Message>),
56 State(S),
63 Reasoning(ReasoningUpdate),
65 Subagent(SubagentUpdate),
72 Interrupt(Interrupt),
75 Error(Error),
81 Done(RunEnd),
85}
86
87#[derive(Clone, Debug, PartialEq)]
89pub struct MessageUpdate {
90 pub index: usize,
92 pub id: MessageId,
94 pub change: MessageChangeKind,
96 pub message: Message,
98}
99
100#[derive(Clone, Debug, PartialEq)]
102pub struct ReasoningUpdate {
103 pub id: MessageId,
105 pub change: ReasoningChangeKind,
107 pub text: String,
109}
110
111#[derive(Clone, Debug, PartialEq)]
113pub struct SubagentUpdate {
114 pub index: usize,
116 pub run_id: crate::SubagentRunId,
118 pub change: SubagentChangeKind,
120 pub subagent: Subagent,
122}
123
124#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
126pub enum RunEnd {
127 Success {
129 result: Option<Value>,
131 },
132 Interrupted {
134 interrupts: Vec<Interrupt>,
136 },
137 Failed {
139 message: String,
141 code: Option<String>,
143 },
144 Aborted,
146}
147
148#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
150#[error("state does not match the expected type: {message}")]
151pub struct StateViewError {
152 pub message: String,
154}
155
156#[derive(Clone, Debug, PartialEq, Eq)]
158pub struct RunDiagnostic {
159 pub kind: &'static str,
161 pub message: String,
163}
164
165#[derive(Clone, Debug, PartialEq)]
167pub struct RunReport {
168 pub end: RunEnd,
170 pub new_messages: Vec<Message>,
172 pub diagnostics: Vec<RunDiagnostic>,
174 pub diagnostics_omitted: usize,
176}
177
178#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
180pub struct ResumeSubmission {
181 pub run_id: RunId,
183 pub entries: Vec<ResumeEntry>,
185 pub status: SubmissionStatus,
187}
188
189#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
191pub enum SubmissionStatus {
192 InFlight,
194 Unconfirmed,
196}
197
198#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
201pub struct ThreadSnapshot {
202 pub version: u32,
204 pub thread_id: ThreadId,
206 pub messages: Vec<Message>,
208 pub state: Value,
210 pub reasoning: Vec<ReasoningMessage>,
212 pub subagents: Vec<Subagent>,
214 pub interrupts: Vec<Interrupt>,
216 pub submission: Option<ResumeSubmission>,
218 pub run_ids: Vec<RunId>,
220 pub last_run_end: Option<RunEnd>,
222 pub active_run_id: Option<RunId>,
224}
225
226pub struct Thread<T, S = Value> {
229 agent: RemoteAgent<Arc<T>>,
230 thread_id: ThreadId,
231 applier: Applier,
232 state: core::result::Result<S, StateViewError>,
233 tools: Vec<Tool>,
234 context: Vec<Context>,
235 forwarded_props: Value,
236 verify: bool,
237 interrupts: Vec<Interrupt>,
238 submission: Option<ResumeSubmission>,
239 run_ids: HashSet<RunId>,
240 next_run_id: Option<RunId>,
241 last_run_end: Option<RunEnd>,
242 active_run_id: Option<RunId>,
243 observer: Option<Observer>,
244 id_generator: IdGenerator,
245 diagnostic_limit: usize,
246}
247
248impl<T, S: std::fmt::Debug> std::fmt::Debug for Thread<T, S> {
249 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250 f.debug_struct("Thread")
251 .field("thread_id", &self.thread_id)
252 .field("state", &self.state)
253 .field("messages", &self.messages())
254 .field("interrupts", &self.interrupts)
255 .finish_non_exhaustive()
256 }
257}
258
259impl<T: Transport> Thread<T> {
260 pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self {
262 Self::from_shared(Arc::new(transport), thread_id)
263 }
264
265 pub(crate) fn from_shared(transport: Arc<T>, thread_id: impl Into<ThreadId>) -> Self {
266 ThreadBuilder::from_shared(transport, thread_id)
267 .build()
268 .expect("an empty JSON object always deserializes to Value")
269 }
270}
271
272impl<T, S> Thread<T, S> {
273 pub fn builder(transport: T, thread_id: impl Into<ThreadId>) -> ThreadBuilder<T, S>
275 where
276 T: Transport,
277 {
278 ThreadBuilder::new(transport, thread_id)
279 }
280 pub fn thread_id(&self) -> &ThreadId {
282 &self.thread_id
283 }
284 pub fn messages(&self) -> &[Message] {
286 self.applier.messages()
287 }
288 pub fn state(&self) -> core::result::Result<&S, StateViewError> {
290 self.state.as_ref().map_err(Clone::clone)
291 }
292 pub fn raw_state(&self) -> &Value {
294 self.applier.state()
295 }
296 pub fn reasoning(&self) -> &[ReasoningMessage] {
298 self.applier.reasoning()
299 }
300 pub fn interrupts(&self) -> &[Interrupt] {
302 &self.interrupts
303 }
304 pub fn submission(&self) -> Option<&ResumeSubmission> {
306 self.submission.as_ref()
307 }
308 pub fn subagents(&self) -> &[Subagent] {
310 self.applier.subagents()
311 }
312 pub fn subagent(&self, id: &crate::SubagentRunId) -> Option<&Subagent> {
314 self.applier.subagent(id)
315 }
316 pub fn applier(&self) -> &Applier {
318 &self.applier
319 }
320 pub fn agent(&self) -> &RemoteAgent<Arc<T>> {
322 &self.agent
323 }
324 pub fn last_run_end(&self) -> Option<&RunEnd> {
326 self.last_run_end.as_ref()
327 }
328 pub fn push_message(&mut self, message: Message) -> Result<()> {
330 if self.applier.message(message.id()).is_some() {
331 return Err(Error::Request(format!(
332 "duplicate message ID {}",
333 message.id()
334 )));
335 }
336 self.applier.push_message(message);
337 Ok(())
338 }
339 pub fn set_tools(&mut self, tools: impl Into<Vec<Tool>>) {
341 self.tools = tools.into();
342 }
343 pub fn set_context(&mut self, context: impl Into<Vec<Context>>) {
345 self.context = context.into();
346 }
347 pub fn set_forwarded_props(&mut self, props: impl Into<Value>) {
349 self.forwarded_props = props.into();
350 }
351 pub fn set_verify(&mut self, verify: bool) {
353 self.verify = verify;
354 }
355 pub fn set_diagnostic_limit(&mut self, limit: usize) {
357 self.diagnostic_limit = limit;
358 }
359 pub fn set_next_run_id(&mut self, id: impl Into<RunId>) {
361 self.next_run_id = Some(id.into());
362 }
363 pub fn clear_event_observer(&mut self) {
365 self.observer = None;
366 }
367
368 #[cfg(not(target_family = "wasm"))]
371 pub fn on_event(&mut self, observer: impl FnMut(&Event) + Send + 'static) {
372 self.observer = Some(Box::new(observer));
373 }
374 #[cfg(target_family = "wasm")]
376 pub fn on_event(&mut self, observer: impl FnMut(&Event) + 'static) {
377 self.observer = Some(Box::new(observer));
378 }
379
380 pub fn snapshot(&self) -> ThreadSnapshot {
382 let mut run_ids: Vec<_> = self.run_ids.iter().cloned().collect();
383 run_ids.sort_by(|a, b| a.as_str().cmp(b.as_str()));
384 ThreadSnapshot {
385 version: 1,
386 thread_id: self.thread_id.clone(),
387 messages: self.messages().to_vec(),
388 state: self.raw_state().clone(),
389 reasoning: self.reasoning().to_vec(),
390 subagents: self.subagents().to_vec(),
391 interrupts: self.interrupts.clone(),
392 submission: self.submission.clone(),
393 run_ids,
394 last_run_end: self.last_run_end.clone(),
395 active_run_id: self.active_run_id.clone(),
396 }
397 }
398
399 fn unconfirm(&mut self) {
400 if let Some(submission) = &mut self.submission {
401 submission.status = SubmissionStatus::Unconfirmed;
402 }
403 }
404}
405
406impl<T, S: DeserializeOwned> Thread<T, S> {
407 pub fn set_state(&mut self, state: impl Into<Value>) -> Result<()> {
409 let state = state.into();
410 let typed = S::deserialize(&state).map_err(Error::State)?;
411 self.applier.set_state(state);
412 self.state = Ok(typed);
413 Ok(())
414 }
415
416 pub fn restore(transport: T, snapshot: ThreadSnapshot) -> Result<Self>
418 where
419 T: Transport,
420 {
421 Self::restore_shared(Arc::new(transport), snapshot)
422 }
423
424 pub(crate) fn restore_shared(transport: Arc<T>, mut snapshot: ThreadSnapshot) -> Result<Self> {
425 validate_snapshot(&snapshot)?;
426 if snapshot.active_run_id.take().is_some() {
427 snapshot.last_run_end = Some(RunEnd::Aborted);
428 }
429 let typed = S::deserialize(&snapshot.state).map_err(Error::State)?;
430 if let Some(submission) = &mut snapshot.submission {
431 submission.status = SubmissionStatus::Unconfirmed;
432 }
433 for subagent in &mut snapshot.subagents {
434 if subagent.status == crate::client::SubagentStatus::Running {
435 subagent.status = crate::client::SubagentStatus::Aborted;
436 }
437 }
438 let mut applier = Applier::new()
439 .with_messages(snapshot.messages)
440 .with_state(snapshot.state);
441 applier.restore_auxiliary(
442 snapshot.reasoning,
443 snapshot.subagents,
444 snapshot.interrupts.clone(),
445 );
446 Ok(Self {
447 agent: RemoteAgent::new(transport),
448 thread_id: snapshot.thread_id,
449 applier,
450 state: Ok(typed),
451 tools: Vec::new(),
452 context: Vec::new(),
453 forwarded_props: Value::Null,
454 verify: true,
455 interrupts: snapshot.interrupts,
456 submission: snapshot.submission,
457 run_ids: snapshot.run_ids.into_iter().collect(),
458 next_run_id: None,
459 last_run_end: snapshot.last_run_end,
460 active_run_id: None,
461 observer: None,
462 id_generator: Box::new(random_id),
463 diagnostic_limit: 100,
464 })
465 }
466}
467
468impl<T: Transport, S> Thread<T, S> {
469 pub fn send(&mut self, text: impl Into<String>) -> Result<RunStream<'_, T, S>> {
472 self.preflight(None)?;
473 let id = self.fresh_id(false)?;
474 self.start(Some(Message::user(id, text.into())), None)
475 }
476 pub fn send_message(&mut self, message: Message) -> Result<RunStream<'_, T, S>> {
478 self.preflight(None)?;
479 if self.applier.message(message.id()).is_some() {
480 return Err(Error::Request(format!(
481 "duplicate message ID {}",
482 message.id()
483 )));
484 }
485 self.start(Some(message), None)
486 }
487 pub fn run(&mut self) -> Result<RunStream<'_, T, S>> {
489 self.preflight(None)?;
490 self.start(None, None)
491 }
492 pub fn resume(
494 &mut self,
495 interrupt: &Interrupt,
496 payload: impl Into<Value>,
497 ) -> Result<RunStream<'_, T, S>> {
498 self.resume_many([interrupt.resolve(payload)])
499 }
500 pub fn decline(&mut self, interrupt: &Interrupt) -> Result<RunStream<'_, T, S>> {
502 self.resume_many([interrupt.cancel()])
503 }
504 pub fn resume_many(
508 &mut self,
509 entries: impl IntoIterator<Item = ResumeEntry>,
510 ) -> Result<RunStream<'_, T, S>> {
511 let entries: Vec<_> = entries.into_iter().collect();
512 self.preflight(Some(&entries))?;
513 self.start(None, Some(entries))
514 }
515 fn preflight(&self, resume: Option<&[ResumeEntry]>) -> Result<()> {
516 if self.thread_id.as_str().is_empty() {
517 return Err(Error::Request("thread ID must not be empty".into()));
518 }
519 if self.submission.is_some() {
520 return Err(Error::Request("an unconfirmed submission requires reconciliation with server state before another run".into()));
521 }
522 if let Some(id) = &self.next_run_id {
523 if id.as_str().is_empty() || self.run_ids.contains(id) {
524 return Err(Error::Request(format!(
525 "run ID {id} is empty or already used"
526 )));
527 }
528 }
529 match resume {
530 None if !self.interrupts.is_empty() => Err(Error::Request(
531 "pending interrupts must be answered with resume_many".into(),
532 )),
533 Some(entries) => validate_responses(&self.interrupts, entries, true),
534 None => Ok(()),
535 }
536 }
537 fn fresh_id(&mut self, run: bool) -> Result<String> {
538 for _ in 0..64 {
539 let id = (self.id_generator)()?;
540 let exists = if run {
541 self.run_ids.contains(&RunId::new(&id))
542 } else {
543 self.applier.message(&MessageId::new(&id)).is_some()
544 };
545 if !id.is_empty() && !exists {
546 return Ok(id);
547 }
548 }
549 Err(Error::Request(
550 "ID generator repeatedly returned empty or existing IDs".into(),
551 ))
552 }
553 fn start(
554 &mut self,
555 message: Option<Message>,
556 resume: Option<Vec<ResumeEntry>>,
557 ) -> Result<RunStream<'_, T, S>> {
558 let run_id = match &self.next_run_id {
559 Some(id) => id.clone(),
560 None => RunId::new(self.fresh_id(true)?),
561 };
562 let initial_ids = self
563 .messages()
564 .iter()
565 .map(|message| message.id().clone())
566 .collect();
567 let messages = self
570 .messages()
571 .iter()
572 .chain(message.iter())
573 .filter(|message| !matches!(message, Message::Activity(_)))
574 .cloned()
575 .collect();
576 let input = RunAgentInput {
577 thread_id: self.thread_id.clone(),
578 run_id,
579 parent_run_id: None,
580 state: self.raw_state().clone(),
581 messages,
582 tools: self.tools.clone(),
583 context: self.context.clone(),
584 forwarded_props: self.forwarded_props.clone(),
585 resume,
586 };
587 let verifier = self.verify.then(Verifier::new);
588 let request_run_id = input.run_id.clone();
589 Ok(RunStream {
590 request_run_id,
591 thread: self,
592 prepared: Some((input, message)),
593 events: None,
594 normalizer: ChunkNormalizer::new(),
595 verifier,
596 expanded: Vec::new(),
597 ready: VecDeque::new(),
598 done: false,
599 dispatched: false,
600 abort: AbortHandle::default(),
601 end: None,
602 diagnostics: Vec::new(),
603 diagnostics_omitted: 0,
604 initial_ids,
605 response_ids: None,
606 })
607 }
608}
609
610pub struct ThreadBuilder<T, S = Value> {
612 transport: Arc<T>,
613 thread_id: ThreadId,
614 messages: Vec<Message>,
615 state: Value,
616 tools: Vec<Tool>,
617 context: Vec<Context>,
618 forwarded_props: Value,
619 verify: bool,
620 diagnostic_limit: usize,
621 id_generator: IdGenerator,
622 marker: std::marker::PhantomData<fn() -> S>,
623}
624impl<T, S> std::fmt::Debug for ThreadBuilder<T, S> {
625 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
626 f.debug_struct("ThreadBuilder")
627 .field("thread_id", &self.thread_id)
628 .finish_non_exhaustive()
629 }
630}
631impl<T, S> ThreadBuilder<T, S> {
632 pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self
634 where
635 T: Transport,
636 {
637 Self::from_shared(Arc::new(transport), thread_id)
638 }
639 pub(crate) fn from_shared(transport: Arc<T>, thread_id: impl Into<ThreadId>) -> Self {
640 Self {
641 transport,
642 thread_id: thread_id.into(),
643 messages: Vec::new(),
644 state: serde_json::json!({}),
645 tools: Vec::new(),
646 context: Vec::new(),
647 forwarded_props: Value::Null,
648 verify: true,
649 diagnostic_limit: 100,
650 id_generator: Box::new(random_id),
651 marker: std::marker::PhantomData,
652 }
653 }
654 #[must_use]
656 pub fn messages(mut self, messages: impl Into<Vec<Message>>) -> Self {
657 self.messages = messages.into();
658 self
659 }
660 #[must_use]
662 pub fn state(mut self, state: impl Into<Value>) -> Self {
663 self.state = state.into();
664 self
665 }
666 #[must_use]
668 pub fn tools(mut self, tools: impl Into<Vec<Tool>>) -> Self {
669 self.tools = tools.into();
670 self
671 }
672 #[must_use]
674 pub fn context(mut self, context: impl Into<Vec<Context>>) -> Self {
675 self.context = context.into();
676 self
677 }
678 #[must_use]
680 pub fn forwarded_props(mut self, props: impl Into<Value>) -> Self {
681 self.forwarded_props = props.into();
682 self
683 }
684 #[must_use]
686 pub fn verify(mut self, verify: bool) -> Self {
687 self.verify = verify;
688 self
689 }
690 #[must_use]
692 pub fn diagnostic_limit(mut self, limit: usize) -> Self {
693 self.diagnostic_limit = limit;
694 self
695 }
696 #[cfg(not(target_family = "wasm"))]
698 #[must_use]
699 pub fn id_generator(mut self, mut generator: impl FnMut() -> String + Send + 'static) -> Self {
700 self.id_generator = Box::new(move || Ok(generator()));
701 self
702 }
703 #[cfg(target_family = "wasm")]
705 #[must_use]
706 pub fn id_generator(mut self, mut generator: impl FnMut() -> String + 'static) -> Self {
707 self.id_generator = Box::new(move || Ok(generator()));
708 self
709 }
710 pub fn build(self) -> Result<Thread<T, S>>
712 where
713 S: DeserializeOwned,
714 {
715 unique(
716 self.messages.iter().map(|message| message.id().as_str()),
717 "message",
718 )?;
719 let state = S::deserialize(&self.state).map_err(Error::State)?;
720 Ok(Thread {
721 agent: RemoteAgent::new(self.transport),
722 thread_id: self.thread_id,
723 applier: Applier::new()
724 .with_messages(self.messages)
725 .with_state(self.state),
726 state: Ok(state),
727 tools: self.tools,
728 context: self.context,
729 forwarded_props: self.forwarded_props,
730 verify: self.verify,
731 interrupts: Vec::new(),
732 submission: None,
733 run_ids: HashSet::new(),
734 next_run_id: None,
735 last_run_end: None,
736 active_run_id: None,
737 observer: None,
738 id_generator: self.id_generator,
739 diagnostic_limit: self.diagnostic_limit,
740 })
741 }
742}
743
744#[derive(Default)]
745struct AbortState {
746 aborted: AtomicBool,
747 waker: AtomicWaker,
748}
749#[derive(Clone, Default)]
752pub struct AbortHandle {
753 state: Arc<AbortState>,
754}
755impl std::fmt::Debug for AbortHandle {
756 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
757 f.debug_struct("AbortHandle")
758 .field("aborted", &self.is_aborted())
759 .finish()
760 }
761}
762impl AbortHandle {
763 pub fn abort(&self) {
765 self.state.aborted.store(true, Ordering::Release);
766 self.state.waker.wake();
767 }
768 pub fn is_aborted(&self) -> bool {
770 self.state.aborted.load(Ordering::Acquire)
771 }
772}
773
774pub struct RunStream<'a, T, S = Value> {
777 thread: &'a mut Thread<T, S>,
778 prepared: Option<(RunAgentInput, Option<Message>)>,
779 events: Option<EventStream>,
780 normalizer: ChunkNormalizer,
781 verifier: Option<Verifier>,
782 expanded: Vec<Event>,
783 ready: VecDeque<Update<S>>,
784 done: bool,
785 dispatched: bool,
786 abort: AbortHandle,
787 end: Option<RunEnd>,
788 diagnostics: Vec<RunDiagnostic>,
789 diagnostics_omitted: usize,
790 initial_ids: HashSet<MessageId>,
791 response_ids: Option<(ThreadId, RunId)>,
792 request_run_id: RunId,
793}
794impl<T, S> std::fmt::Debug for RunStream<'_, T, S> {
795 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
796 f.debug_struct("RunStream")
797 .field("pending", &self.ready.len())
798 .field("dispatched", &self.dispatched)
799 .field("done", &self.done)
800 .finish_non_exhaustive()
801 }
802}
803impl<T, S> RunStream<'_, T, S> {
804 pub fn thread(&self) -> &Thread<T, S> {
806 self.thread
807 }
808 pub fn abort_handle(&self) -> AbortHandle {
810 self.abort.clone()
811 }
812 pub fn abort(&self) {
814 self.abort.abort();
815 }
816 fn diagnostic(&mut self, error: Error) {
817 if self.diagnostics.len() < self.thread.diagnostic_limit {
818 let kind = match &error {
819 Error::State(_) => "state",
820 Error::Protocol(_) => "protocol",
821 Error::Patch { .. } => "patch",
822 Error::Run { .. } => "run",
823 Error::Json(_) | Error::Decode(_) => "decode",
824 _ => "transport",
825 };
826 self.diagnostics.push(RunDiagnostic {
827 kind,
828 message: error.to_string(),
829 });
830 } else {
831 self.diagnostics_omitted += 1;
832 }
833 self.ready.push_back(Update::Error(error));
834 }
835 fn terminate(&mut self, end: RunEnd) {
836 if self.done {
837 return;
838 }
839 self.done = true;
840 self.events = None;
841 self.prepared = None;
842 self.thread.applier.reset_streams();
843 if self.dispatched {
844 self.thread.last_run_end = Some(end.clone());
845 self.thread.active_run_id = None;
846 }
847 self.end = Some(end.clone());
848 self.ready.push_back(Update::Done(end));
849 }
850 fn stop_subagents(&mut self) {
851 let (messages, reasoning) = self.thread.applier.abort_messages();
852 for change in messages {
853 if let Some(message) = self.thread.applier.messages().get(change.index) {
854 self.ready.push_back(Update::Message(MessageUpdate {
855 index: change.index,
856 id: change.id,
857 change: change.kind,
858 message: message.clone(),
859 }));
860 }
861 }
862 for change in reasoning {
863 let text = self
864 .thread
865 .applier
866 .reasoning_text(&change.id)
867 .unwrap_or_default()
868 .to_owned();
869 self.ready.push_back(Update::Reasoning(ReasoningUpdate {
870 id: change.id,
871 change: change.kind,
872 text,
873 }));
874 }
875 for change in self.thread.applier.abort_subagents() {
876 let subagent = self.thread.applier.subagents()[change.index].clone();
877 self.ready.push_back(Update::Subagent(SubagentUpdate {
878 index: change.index,
879 run_id: change.run_id,
880 change: change.kind,
881 subagent,
882 }));
883 }
884 }
885 fn fail(&mut self, error: Error) {
886 let message = error.to_string();
887 self.diagnostic(error);
888 self.thread.unconfirm();
889 self.stop_subagents();
890 self.terminate(RunEnd::Failed {
891 message,
892 code: None,
893 });
894 }
895}
896impl<T, S> Drop for RunStream<'_, T, S> {
897 fn drop(&mut self) {
898 if self.dispatched && !self.done {
899 self.thread.unconfirm();
900 self.thread.applier.abort_subagents();
901 self.thread.last_run_end = Some(RunEnd::Aborted);
902 self.thread.active_run_id = None;
903 }
904 }
905}
906
907impl<T: Transport, S: DeserializeOwned + Clone + Unpin> RunStream<'_, T, S> {
908 pub async fn collect_report(mut self) -> RunReport {
910 while self.next().await.is_some() {}
911 RunReport {
912 end: self
913 .end
914 .clone()
915 .expect("a consumed stream has a terminal outcome"),
916 new_messages: self
917 .thread
918 .messages()
919 .iter()
920 .filter(|message| !self.initial_ids.contains(message.id()))
921 .cloned()
922 .collect(),
923 diagnostics: std::mem::take(&mut self.diagnostics),
924 diagnostics_omitted: self.diagnostics_omitted,
925 }
926 }
927}
928
929impl<T, S: DeserializeOwned + Clone> RunStream<'_, T, S> {
930 fn ingest(&mut self, event: Event) {
931 if let Some(observer) = &mut self.thread.observer {
932 observer(&event);
933 }
934 if matches!(event, Event::RunError(_)) {
935 self.handle(event);
936 return;
937 }
938 let mut expanded = std::mem::take(&mut self.expanded);
939 expanded.clear();
940 let result = self.normalizer.normalize(event, &mut expanded);
941 for event in expanded.drain(..) {
942 if !self.done {
943 self.handle(event);
944 }
945 }
946 self.expanded = expanded;
947 if let Err(error) = result {
948 self.diagnostic(error);
949 }
950 }
951 fn handle(&mut self, event: Event) {
952 match &event {
955 Event::RunStarted(started) => {
956 if started.thread_id != self.thread.thread_id
957 || started.run_id != self.request_run_id
958 {
959 self.fail(Error::protocol(
960 "RUN_STARTED does not match the requested thread and run IDs",
961 ));
962 return;
963 }
964 self.response_ids = Some((started.thread_id.clone(), started.run_id.clone()));
965 }
966 Event::RunFinished(finished) => {
967 if self.response_ids.as_ref()
968 != Some(&(finished.thread_id.clone(), finished.run_id.clone()))
969 {
970 self.fail(Error::protocol("RUN_FINISHED does not match RUN_STARTED"));
971 return;
972 }
973 if let Some(RunOutcome::Interrupt { interrupts }) = &finished.outcome {
974 if let Err(error) =
975 unique(interrupts.iter().map(|i| i.id.as_str()), "interrupt")
976 {
977 self.fail(Error::protocol(error.to_string()));
978 return;
979 }
980 }
981 }
982 _ => {}
983 }
984 if let Some(verifier) = &mut self.verifier {
985 if let Err(error) = verifier.verify(&event) {
986 if matches!(event, Event::RunFinished(_) | Event::RunError(_)) {
987 self.fail(error);
988 } else {
989 self.diagnostic(error);
990 }
991 return;
992 }
993 }
994 match self.thread.applier.apply(&event) {
995 Ok(changed) => self.emit(changed),
996 Err(error) if matches!(event, Event::RunFinished(_) | Event::RunError(_)) => {
997 self.fail(error)
998 }
999 Err(error) => self.diagnostic(error),
1000 }
1001 }
1002 fn emit(&mut self, changed: Changed) {
1003 match changed {
1004 Changed::Nothing | Changed::RunStarted { .. } => {}
1005 Changed::Message(change) => {
1006 if let Some(message) = self.thread.applier.messages().get(change.index) {
1007 self.ready.push_back(Update::Message(MessageUpdate {
1008 index: change.index,
1009 id: change.id,
1010 change: change.kind,
1011 message: message.clone(),
1012 }));
1013 }
1014 }
1015 Changed::MessagesReplaced => self
1016 .ready
1017 .push_back(Update::Messages(self.thread.messages().to_vec())),
1018 Changed::State => match self.thread.applier.state_as::<S>() {
1019 Ok(state) => {
1020 self.thread.state = Ok(state.clone());
1021 self.ready.push_back(Update::State(state));
1022 }
1023 Err(error) => {
1024 self.thread.state = Err(StateViewError {
1025 message: match &error {
1026 Error::State(error) => error.to_string(),
1027 _ => error.to_string(),
1028 },
1029 });
1030 self.diagnostic(error);
1031 }
1032 },
1033 Changed::Reasoning(change) => {
1034 let text = self
1035 .thread
1036 .applier
1037 .reasoning_text(&change.id)
1038 .unwrap_or_default()
1039 .to_owned();
1040 self.ready.push_back(Update::Reasoning(ReasoningUpdate {
1041 id: change.id,
1042 change: change.kind,
1043 text,
1044 }));
1045 }
1046 Changed::Subagent(change) => {
1047 if let Some(subagent) = self.thread.applier.subagents().get(change.index) {
1048 self.ready.push_back(Update::Subagent(SubagentUpdate {
1049 index: change.index,
1050 run_id: change.run_id,
1051 change: change.kind,
1052 subagent: subagent.clone(),
1053 }));
1054 }
1055 }
1056 Changed::RunFinished { outcome, result } => {
1057 self.thread.submission = None;
1058 match outcome {
1059 RunOutcome::Success => {
1060 self.thread.interrupts.clear();
1061 self.terminate(RunEnd::Success { result });
1062 }
1063 RunOutcome::Interrupt { interrupts } => {
1064 self.thread.interrupts.clone_from(&interrupts);
1065 for interrupt in &interrupts {
1066 self.ready.push_back(Update::Interrupt(interrupt.clone()));
1067 }
1068 self.terminate(RunEnd::Interrupted { interrupts });
1069 }
1070 }
1071 }
1072 Changed::RunError { message, code } => {
1073 self.diagnostic(Error::Run {
1074 message: message.clone(),
1075 code: code.clone(),
1076 });
1077 self.thread.unconfirm();
1078 self.stop_subagents();
1079 self.terminate(RunEnd::Failed { message, code });
1080 }
1081 }
1082 }
1083}
1084
1085impl<T: Transport, S: DeserializeOwned + Clone + Unpin> Stream for RunStream<'_, T, S> {
1086 type Item = Update<S>;
1087 fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
1088 let this = self.get_mut();
1089 this.abort.state.waker.register(cx.waker());
1090 loop {
1091 if !this.done && this.abort.is_aborted() {
1093 if this.dispatched {
1094 this.thread.unconfirm();
1095 this.stop_subagents();
1096 }
1097 this.terminate(RunEnd::Aborted);
1098 }
1099 if let Some(update) = this.ready.pop_front() {
1100 return Poll::Ready(Some(update));
1101 }
1102 if this.done {
1103 return Poll::Ready(None);
1104 }
1105 if let Some((input, message)) = this.prepared.take() {
1106 if let Some(entries) = &input.resume {
1108 if let Err(error) = validate_responses(&this.thread.interrupts, entries, true) {
1109 this.fail(error);
1110 continue;
1111 }
1112 }
1113 this.dispatched = true;
1114 this.thread.applier.reset_streams();
1115 this.thread.run_ids.insert(input.run_id.clone());
1116 this.thread.active_run_id = Some(input.run_id.clone());
1117 this.thread.next_run_id = None;
1118 if let Some(message) = message {
1119 this.thread.applier.push_message(message);
1120 }
1121 if let Some(entries) = &input.resume {
1122 this.thread.submission = Some(ResumeSubmission {
1123 run_id: input.run_id.clone(),
1124 entries: entries.clone(),
1125 status: SubmissionStatus::InFlight,
1126 });
1127 }
1128 this.events = Some(this.thread.agent.run_events(input));
1129 }
1130 match this
1131 .events
1132 .as_mut()
1133 .expect("dispatched run has a stream")
1134 .as_mut()
1135 .poll_next(cx)
1136 {
1137 Poll::Pending => return Poll::Pending,
1138 Poll::Ready(Some(Ok(event))) => this.ingest(event),
1139 Poll::Ready(Some(Err(error))) => this.fail(error),
1140 Poll::Ready(None) => {
1141 let error = this
1142 .verifier
1143 .as_ref()
1144 .and_then(|verifier| verifier.finish().err())
1145 .unwrap_or_else(|| {
1146 Error::protocol("the stream ended before RUN_FINISHED or RUN_ERROR")
1147 });
1148 this.fail(error);
1149 }
1150 }
1151 }
1152 }
1153}
1154
1155fn random_id() -> Result<String> {
1156 let mut bytes = [0u8; 16];
1157 getrandom::getrandom(&mut bytes)
1158 .map_err(|error| Error::Config(format!("could not obtain ID entropy: {error}")))?;
1159 use std::fmt::Write;
1160 let mut id = String::with_capacity(32);
1161 for byte in bytes {
1162 write!(id, "{byte:02x}").expect("writing to String cannot fail");
1163 }
1164 Ok(id)
1165}
1166
1167fn unique<'a>(ids: impl IntoIterator<Item = &'a str>, label: &str) -> Result<()> {
1168 let mut seen = HashSet::new();
1169 for id in ids {
1170 if id.is_empty() || !seen.insert(id) {
1171 return Err(Error::Snapshot(format!(
1172 "{label} ID {id:?} is empty or duplicated"
1173 )));
1174 }
1175 }
1176 Ok(())
1177}
1178
1179fn validate_responses(pending: &[Interrupt], entries: &[ResumeEntry], expiry: bool) -> Result<()> {
1180 if pending.is_empty() {
1181 return Err(Error::Request("there are no pending interrupts".into()));
1182 }
1183 let mut seen = HashSet::new();
1184 for entry in entries {
1185 if !seen.insert(&entry.interrupt_id) {
1186 return Err(Error::Request(format!(
1187 "duplicate interrupt ID {}",
1188 entry.interrupt_id
1189 )));
1190 }
1191 let interrupt = pending
1192 .iter()
1193 .find(|interrupt| interrupt.id == entry.interrupt_id)
1194 .ok_or_else(|| {
1195 Error::Request(format!("unknown interrupt ID {}", entry.interrupt_id))
1196 })?;
1197 if expiry {
1198 if let Some(timestamp) = &interrupt.expires_at {
1199 let expires = chrono::DateTime::parse_from_rfc3339(timestamp).map_err(|_| {
1200 Error::Request(format!(
1201 "interrupt {} has an invalid expiry timestamp",
1202 interrupt.id
1203 ))
1204 })?;
1205 if expires.timestamp_subsec_nanos() >= 1_000_000_000 {
1207 let utc_date = expires.naive_utc().date();
1208 let ends_month = utc_date
1209 .succ_opt()
1210 .is_some_and(|next| chrono::Datelike::day(&next) == 1);
1211 if expires.timestamp().rem_euclid(86_400) != 86_399 || !ends_month {
1212 return Err(Error::Request(format!(
1213 "interrupt {} has an invalid expiry timestamp",
1214 interrupt.id
1215 )));
1216 }
1217 }
1218 let expires_nanos = i128::from(expires.timestamp()) * 1_000_000_000
1220 + i128::from(expires.timestamp_subsec_nanos().min(999_999_999));
1221 if expires_nanos <= now_unix_nanos() {
1222 return Err(Error::Request(format!(
1223 "interrupt {} has expired",
1224 interrupt.id
1225 )));
1226 }
1227 }
1228 }
1229 }
1230 if seen.len() != pending.len() {
1231 return Err(Error::Request(
1232 "every pending interrupt must be answered exactly once".into(),
1233 ));
1234 }
1235 Ok(())
1236}
1237
1238fn validate_snapshot(snapshot: &ThreadSnapshot) -> Result<()> {
1239 if snapshot.version != 1 {
1240 return Err(Error::Snapshot(format!(
1241 "unsupported version {}",
1242 snapshot.version
1243 )));
1244 }
1245 if snapshot.thread_id.as_str().is_empty() {
1246 return Err(Error::Snapshot("empty thread ID".into()));
1247 }
1248 unique(
1249 snapshot
1250 .messages
1251 .iter()
1252 .map(|message| message.id().as_str()),
1253 "message",
1254 )?;
1255 unique(
1256 snapshot.reasoning.iter().map(|message| message.id.as_str()),
1257 "reasoning",
1258 )?;
1259 unique(
1260 snapshot
1261 .subagents
1262 .iter()
1263 .map(|subagent| subagent.run_id.as_str()),
1264 "subagent",
1265 )?;
1266 unique(
1267 snapshot
1268 .interrupts
1269 .iter()
1270 .map(|interrupt| interrupt.id.as_str()),
1271 "interrupt",
1272 )?;
1273 unique(snapshot.run_ids.iter().map(|id| id.as_str()), "run")?;
1274 if let Some(id) = &snapshot.active_run_id {
1275 if !snapshot.run_ids.contains(id) {
1276 return Err(Error::Snapshot(
1277 "active run refers to an unknown run ID".into(),
1278 ));
1279 }
1280 }
1281 for subagent in &snapshot.subagents {
1282 let mut seen = HashSet::from([subagent.run_id.as_str()]);
1283 let mut parent = subagent.parent_subagent_run_id.as_ref();
1284 while let Some(id) = parent {
1285 if !seen.insert(id.as_str()) {
1286 return Err(Error::Snapshot("cyclic subagent ancestry".into()));
1287 }
1288 let ancestor = snapshot
1289 .subagents
1290 .iter()
1291 .find(|subagent| &subagent.run_id == id)
1292 .ok_or_else(|| Error::Snapshot(format!("unknown parent subagent {id}")))?;
1293 parent = ancestor.parent_subagent_run_id.as_ref();
1294 }
1295 }
1296 if let Some(submission) = &snapshot.submission {
1297 if submission.status == SubmissionStatus::InFlight
1298 && snapshot.active_run_id.as_ref() != Some(&submission.run_id)
1299 {
1300 return Err(Error::Snapshot(
1301 "in-flight submission must reference the active run".into(),
1302 ));
1303 }
1304 if !snapshot.run_ids.contains(&submission.run_id) {
1305 return Err(Error::Snapshot(
1306 "submission refers to an unknown run ID".into(),
1307 ));
1308 }
1309 validate_responses(&snapshot.interrupts, &submission.entries, false)
1310 .map_err(|error| Error::Snapshot(error.to_string()))?;
1311 }
1312 Ok(())
1313}
1314
1315#[cfg(not(target_family = "wasm"))]
1316fn now_unix_nanos() -> i128 {
1317 match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
1318 Ok(elapsed) => elapsed.as_nanos() as i128,
1319 Err(error) => -(error.duration().as_nanos() as i128),
1320 }
1321}
1322#[cfg(target_family = "wasm")]
1323fn now_unix_nanos() -> i128 {
1324 (js_sys::Date::now() * 1_000_000.0) as i128
1325}