mod merge;
mod pending;
mod run;
mod snapshot;
pub use merge::{MergeReport, merge_messages};
pub use pending::{ResumeSubmission, SubmissionStatus};
pub use run::{
AbortHandle, MessageUpdate, ReasoningUpdate, RunDiagnostic, RunEnd, RunReport, RunStream,
RunSummary, SubagentUpdate, Update,
};
pub use snapshot::ThreadSnapshot;
use std::collections::HashSet;
use std::sync::Arc;
use crate::client::{
agent::RemoteAgent,
apply::{Applier, Subagent},
error::{Error, Result},
transport::Transport,
};
use crate::{
Context, Event, Interrupt, Message, MessageId, ReasoningMessage, RunId, ThreadId, Tool,
ToolCallId,
};
use serde::de::DeserializeOwned;
use serde_json::Value;
#[cfg(not(target_family = "wasm"))]
type Observer = Box<dyn FnMut(&Event) + Send>;
#[cfg(target_family = "wasm")]
type Observer = Box<dyn FnMut(&Event)>;
#[cfg(not(target_family = "wasm"))]
type IdGenerator = Box<dyn FnMut() -> Result<String> + Send>;
#[cfg(target_family = "wasm")]
type IdGenerator = Box<dyn FnMut() -> Result<String>>;
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("state does not match the expected type: {message}")]
pub struct StateViewError {
pub message: String,
}
pub struct Thread<T, S = Value> {
agent: RemoteAgent<Arc<T>>,
thread_id: ThreadId,
applier: Applier,
state: core::result::Result<S, StateViewError>,
tools: Vec<Tool>,
context: Vec<Context>,
forwarded_props: Value,
protocol_version: Option<String>,
verify: bool,
interrupts: Vec<Interrupt>,
decided_interrupt_tool_call_ids: HashSet<ToolCallId>,
abandoned: HashSet<MessageId>,
submission: Option<ResumeSubmission>,
run_ids: HashSet<RunId>,
next_run_id: Option<RunId>,
last_run_end: Option<RunEnd>,
active_run_id: Option<RunId>,
observer: Option<Observer>,
id_generator: IdGenerator,
diagnostic_limit: usize,
}
impl<T, S: std::fmt::Debug> std::fmt::Debug for Thread<T, S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Thread")
.field("thread_id", &self.thread_id)
.field("state", &self.state)
.field("messages", &self.messages())
.field("interrupts", &self.interrupts)
.finish_non_exhaustive()
}
}
impl<T: Transport> Thread<T> {
pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self {
Self::from_shared(Arc::new(transport), thread_id)
}
pub(crate) fn from_shared(transport: Arc<T>, thread_id: impl Into<ThreadId>) -> Self {
ThreadBuilder::from_shared(transport, thread_id)
.build()
.expect("an empty JSON object always deserializes to Value")
}
}
impl<T, S> Thread<T, S> {
pub fn builder(transport: T, thread_id: impl Into<ThreadId>) -> ThreadBuilder<T, S>
where
T: Transport,
{
ThreadBuilder::new(transport, thread_id)
}
pub fn thread_id(&self) -> &ThreadId {
&self.thread_id
}
pub fn messages(&self) -> &[Message] {
self.applier.messages()
}
pub fn state(&self) -> core::result::Result<&S, StateViewError> {
self.state.as_ref().map_err(Clone::clone)
}
pub fn raw_state(&self) -> &Value {
self.applier.state()
}
pub fn reasoning(&self) -> impl Iterator<Item = &ReasoningMessage> {
self.applier.reasoning()
}
pub fn interrupts(&self) -> &[Interrupt] {
&self.interrupts
}
pub fn submission(&self) -> Option<&ResumeSubmission> {
self.submission.as_ref()
}
pub fn subagents(&self) -> &[Subagent] {
self.applier.subagents()
}
pub fn subagent(&self, id: &crate::SubagentRunId) -> Option<&Subagent> {
self.applier.subagent(id)
}
pub fn applier(&self) -> &Applier {
&self.applier
}
pub fn agent(&self) -> &RemoteAgent<Arc<T>> {
&self.agent
}
pub fn last_run_end(&self) -> Option<&RunEnd> {
self.last_run_end.as_ref()
}
pub fn push_message(&mut self, message: Message) -> Result<()> {
if self.applier.message(message.id()).is_some() {
return Err(Error::Request(format!(
"duplicate message ID {}",
message.id()
)));
}
self.append_local_message(message);
Ok(())
}
fn append_local_message(&mut self, message: Message) {
if let Message::Assistant(assistant) = &message {
for call in assistant.tool_calls.iter().flatten() {
self.decided_interrupt_tool_call_ids.remove(&call.id);
}
}
self.applier.push_message(message);
}
pub fn set_tools(&mut self, tools: impl Into<Vec<Tool>>) {
self.tools = tools.into();
}
pub fn set_context(&mut self, context: impl Into<Vec<Context>>) {
self.context = context.into();
}
pub fn set_forwarded_props(&mut self, props: impl Into<Value>) {
self.forwarded_props = props.into();
}
pub fn set_verify(&mut self, verify: bool) {
self.verify = verify;
}
pub fn set_diagnostic_limit(&mut self, limit: usize) {
self.diagnostic_limit = limit;
}
pub fn set_next_run_id(&mut self, id: impl Into<RunId>) {
self.next_run_id = Some(id.into());
}
pub fn clear_event_observer(&mut self) {
self.observer = None;
}
#[cfg(not(target_family = "wasm"))]
pub fn on_event(&mut self, observer: impl FnMut(&Event) + Send + 'static) {
self.observer = Some(Box::new(observer));
}
#[cfg(target_family = "wasm")]
pub fn on_event(&mut self, observer: impl FnMut(&Event) + 'static) {
self.observer = Some(Box::new(observer));
}
}
impl<T, S: DeserializeOwned> Thread<T, S> {
pub fn set_state(&mut self, state: impl Into<Value>) -> Result<()> {
let state = state.into();
let typed = S::deserialize(&state).map_err(Error::State)?;
self.applier.set_state(state);
self.state = Ok(typed);
Ok(())
}
}
impl<T: Transport, S> Thread<T, S> {
pub fn send(&mut self, text: impl Into<String>) -> Result<RunStream<'_, T, S>> {
self.preflight(None, None)?;
let id = self.fresh_id(false)?;
self.start(Some(Message::user(id, text.into())), None)
}
pub fn send_message(&mut self, message: Message) -> Result<RunStream<'_, T, S>> {
if self.applier.message(message.id()).is_some() {
return Err(Error::Request(format!(
"duplicate message ID {}",
message.id()
)));
}
self.preflight(None, Some(&message))?;
self.start(Some(message), None)
}
pub fn run(&mut self) -> Result<RunStream<'_, T, S>> {
self.preflight(None, None)?;
self.start(None, None)
}
fn fresh_id(&mut self, run: bool) -> Result<String> {
for _ in 0..64 {
let id = (self.id_generator)()?;
let exists = if run {
self.run_ids.contains(&RunId::new(&id))
} else {
self.applier.message(&MessageId::new(&id)).is_some()
};
if !id.is_empty() && !exists {
return Ok(id);
}
}
Err(Error::Request(
"ID generator repeatedly returned empty or existing IDs".into(),
))
}
}
pub struct ThreadBuilder<T, S = Value> {
transport: Arc<T>,
thread_id: ThreadId,
messages: Vec<Message>,
state: Value,
tools: Vec<Tool>,
context: Vec<Context>,
forwarded_props: Value,
protocol_version: Option<String>,
verify: bool,
diagnostic_limit: usize,
id_generator: IdGenerator,
marker: std::marker::PhantomData<fn() -> S>,
}
impl<T, S> std::fmt::Debug for ThreadBuilder<T, S> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ThreadBuilder")
.field("thread_id", &self.thread_id)
.finish_non_exhaustive()
}
}
impl<T, S> ThreadBuilder<T, S> {
pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self
where
T: Transport,
{
Self::from_shared(Arc::new(transport), thread_id)
}
pub(crate) fn from_shared(transport: Arc<T>, thread_id: impl Into<ThreadId>) -> Self {
Self {
transport,
thread_id: thread_id.into(),
messages: Vec::new(),
state: serde_json::json!({}),
tools: Vec::new(),
context: Vec::new(),
forwarded_props: Value::Null,
protocol_version: Some(crate::input::PROTOCOL_VERSION.to_owned()),
verify: true,
diagnostic_limit: 100,
id_generator: Box::new(random_id),
marker: std::marker::PhantomData,
}
}
#[must_use]
pub fn messages(mut self, messages: impl Into<Vec<Message>>) -> Self {
self.messages = messages.into();
self
}
#[must_use]
pub fn state(mut self, state: impl Into<Value>) -> Self {
self.state = state.into();
self
}
#[must_use]
pub fn tools(mut self, tools: impl Into<Vec<Tool>>) -> Self {
self.tools = tools.into();
self
}
#[must_use]
pub fn context(mut self, context: impl Into<Vec<Context>>) -> Self {
self.context = context.into();
self
}
#[must_use]
pub fn forwarded_props(mut self, props: impl Into<Value>) -> Self {
self.forwarded_props = props.into();
self
}
#[must_use]
pub fn protocol_version(mut self, version: Option<String>) -> Self {
self.protocol_version = version;
self
}
#[must_use]
pub fn verify(mut self, verify: bool) -> Self {
self.verify = verify;
self
}
#[must_use]
pub fn diagnostic_limit(mut self, limit: usize) -> Self {
self.diagnostic_limit = limit;
self
}
#[cfg(not(target_family = "wasm"))]
#[must_use]
pub fn id_generator(mut self, mut generator: impl FnMut() -> String + Send + 'static) -> Self {
self.id_generator = Box::new(move || Ok(generator()));
self
}
#[cfg(target_family = "wasm")]
#[must_use]
pub fn id_generator(mut self, mut generator: impl FnMut() -> String + 'static) -> Self {
self.id_generator = Box::new(move || Ok(generator()));
self
}
pub fn build(self) -> Result<Thread<T, S>>
where
S: DeserializeOwned,
{
unique(
self.messages.iter().map(|message| message.id().as_str()),
"message",
)?;
let state = S::deserialize(&self.state).map_err(Error::State)?;
Ok(Thread {
agent: RemoteAgent::new(self.transport),
thread_id: self.thread_id,
applier: Applier::new()
.with_messages(self.messages)
.with_state(self.state),
state: Ok(state),
tools: self.tools,
context: self.context,
forwarded_props: self.forwarded_props,
protocol_version: self.protocol_version,
verify: self.verify,
interrupts: Vec::new(),
decided_interrupt_tool_call_ids: HashSet::new(),
abandoned: HashSet::new(),
submission: None,
run_ids: HashSet::new(),
next_run_id: None,
last_run_end: None,
active_run_id: None,
observer: None,
id_generator: self.id_generator,
diagnostic_limit: self.diagnostic_limit,
})
}
}
pub(crate) fn random_id() -> Result<String> {
let mut bytes = [0u8; 16];
getrandom::getrandom(&mut bytes)
.map_err(|error| Error::Config(format!("could not obtain ID entropy: {error}")))?;
use std::fmt::Write;
let mut id = String::with_capacity(32);
for byte in bytes {
write!(id, "{byte:02x}").expect("writing to String cannot fail");
}
Ok(id)
}
fn unique<'a>(ids: impl IntoIterator<Item = &'a str>, label: &str) -> Result<()> {
let mut seen = HashSet::new();
for id in ids {
if !seen.insert(id) {
return Err(Error::Snapshot(format!(
"{label} ID {id:?} is held more than once"
)));
}
}
Ok(())
}