use std::{
fmt,
sync::Arc,
time::{Duration, Instant},
};
use anyhow::Context as _;
use odori_agents::{
AgentRegistry, Providers, Runner, TurnActivities, register_odori, run::ToolActivities,
};
use temporalio_client::{
Client, ClientOptions, Connection, ConnectionOptions, Url,
callback_based::CallbackBasedGrpcService,
};
use temporalio_sdk::{Runtime, Worker, WorkerOptions};
pub use tokeira_config::{
DsqlMigrationPolicy, EmbeddedConfigError, EmbeddedDsqlLimits, EmbeddedEngineConfig,
EmbeddedStorageConfig, EmbeddedValidationError, ExistingEmbeddedDsqlConfig,
ManagedClusterIntent, ManagedEmbeddedDsqlConfig, SnapshotPolicyConfig, TokeiraConfig,
};
pub use tokeira_engine::{
ClusterStartupReport, EmbeddedEngineShutdownError, EmbeddedEngineStartError,
EmbeddedShutdownFailure, EmbeddedStartupPhase, EmbeddedStorageMode, EngineStartupReport,
OwnershipStartupReport, SchemaStartupOutcome, SchemaStartupReport,
};
#[derive(Debug)]
pub struct Engine {
inner: tokeira_engine::Engine,
startup_elapsed: Duration,
}
impl Engine {
pub async fn start_with_embedded_config(
config: EmbeddedEngineConfig,
) -> Result<Self, EmbeddedEngineStartError> {
let started_at = Instant::now();
let inner = tokeira_engine::Engine::start_with_embedded_config(config).await?;
Ok(Self {
inner,
startup_elapsed: started_at.elapsed(),
})
}
pub fn startup_report(&self) -> &EngineStartupReport {
self.inner.startup_report()
}
pub fn startup_elapsed(&self) -> Duration {
self.startup_elapsed
}
pub fn service_override(&self) -> CallbackBasedGrpcService {
self.inner.service_override()
}
pub async fn shutdown(self) -> Result<(), EmbeddedEngineShutdownError> {
self.inner.shutdown().await
}
}
#[derive(Clone)]
pub enum ConnectTarget {
ServiceOverride(CallbackBasedGrpcService),
Url(Url),
}
impl ConnectTarget {
pub fn service_override(service: CallbackBasedGrpcService) -> Self {
ConnectTarget::ServiceOverride(service)
}
}
impl fmt::Debug for ConnectTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConnectTarget::ServiceOverride(_) => f.write_str("ConnectTarget::ServiceOverride"),
ConnectTarget::Url(url) => f.debug_tuple("ConnectTarget::Url").field(url).finish(),
}
}
}
#[derive(Debug)]
pub struct OdoriRuntimeBuilder {
task_queue: String,
namespace: String,
target: Option<ConnectTarget>,
registry: AgentRegistry,
providers: Option<Providers>,
#[cfg(feature = "preview")]
bridge: Option<odori_mcp_bridge::BridgeConfig>,
}
impl OdoriRuntimeBuilder {
pub fn agents(mut self, registry: AgentRegistry) -> Self {
self.registry = registry;
self
}
pub fn providers(mut self, providers: Providers) -> Self {
self.providers = Some(providers);
self
}
pub fn connect(mut self, target: ConnectTarget) -> Self {
self.target = Some(target);
self
}
pub fn namespace(mut self, namespace: impl Into<String>) -> Self {
self.namespace = namespace.into();
self
}
#[cfg(feature = "preview")]
pub fn bridge(mut self, config: odori_mcp_bridge::BridgeConfig) -> Self {
self.bridge = Some(config);
self
}
pub async fn start(self) -> anyhow::Result<OdoriRuntime> {
let target = self.target.context("ConnectTarget is required")?;
let providers = self.providers.context("a provider set is required")?;
let connection_options = match target {
ConnectTarget::ServiceOverride(service) => ConnectionOptions::new(
Url::parse("http://odori-embedded.invalid:7233")
.context("static embedded URL must parse")?,
)
.service_override(service)
.dns_load_balancing(None)
.build(),
ConnectTarget::Url(url) => ConnectionOptions::new(url).build(),
};
let connection = Connection::connect(connection_options)
.await
.context("connect the Temporal Rust SDK client")?;
let client = Client::new(connection, ClientOptions::new(self.namespace).build())
.context("construct the SDK client")?;
let registry = Arc::new(self.registry);
#[allow(unused_mut)]
let mut activities = TurnActivities::new(registry.clone(), providers);
#[allow(unused_mut)]
let mut tool_activities = ToolActivities::new(registry.clone());
#[cfg(feature = "preview")]
let bridge = match self.bridge {
Some(config) => {
tool_activities = tool_activities.with_max_result_bytes(config.max_result_bytes);
let bridge = odori_mcp_bridge::Bridge::start(
registry.clone(),
Arc::new(odori_mcp_bridge::WorkflowUpdateClient::new(client.clone())),
config,
)
.await
.context("start the mcp-bridge server")?;
activities = activities.with_attachments(Arc::new(bridge.clone()));
Some(bridge)
}
None => None,
};
let _ = ®istry;
let (ready_sender, ready_receiver) = tokio::sync::oneshot::channel();
let worker_client = client.clone();
let worker_queue = self.task_queue.clone();
let worker_thread = std::thread::Builder::new()
.name("odori-worker".to_owned())
.spawn(move || -> anyhow::Result<()> {
let local = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.context("build the worker thread's runtime")?;
local.block_on(async move {
let runtime = Runtime::from_current_tokio(Default::default())
.context("assemble the SDK runtime")?;
let worker_options = register_odori(
WorkerOptions::new(worker_queue),
activities,
tool_activities,
)
.context("register the Odori workflow and activities")?
.build();
let mut worker = Worker::new(&runtime, worker_client, worker_options)
.context("construct the SDK worker")?;
let shutdown: Box<dyn Fn() + Send + Sync> = Box::new(worker.shutdown_handle());
if ready_sender.send(shutdown).is_err() {
return Ok(());
}
worker.run().await.context("run the SDK worker")
})
})
.context("spawn the worker thread")?;
let shutdown = ready_receiver
.await
.context("worker thread ended before signalling readiness")?;
Ok(OdoriRuntime {
client,
task_queue: self.task_queue,
shutdown: Some(shutdown),
worker_thread: Some(worker_thread),
#[cfg(feature = "preview")]
bridge,
})
}
}
pub struct OdoriRuntime {
client: Client,
task_queue: String,
shutdown: Option<Box<dyn Fn() + Send + Sync>>,
worker_thread: Option<std::thread::JoinHandle<anyhow::Result<()>>>,
#[cfg(feature = "preview")]
bridge: Option<odori_mcp_bridge::Bridge>,
}
impl fmt::Debug for OdoriRuntime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OdoriRuntime")
.field("task_queue", &self.task_queue)
.finish_non_exhaustive()
}
}
impl OdoriRuntime {
pub fn builder(task_queue: impl Into<String>) -> OdoriRuntimeBuilder {
OdoriRuntimeBuilder {
task_queue: task_queue.into(),
namespace: "default".to_owned(),
target: None,
registry: AgentRegistry::new(),
providers: None,
#[cfg(feature = "preview")]
bridge: None,
}
}
pub fn runner(&self) -> Runner {
Runner::new(self.client.clone(), self.task_queue.clone())
}
pub fn client(&self) -> Client {
self.client.clone()
}
#[cfg(feature = "preview")]
pub fn bridge_url(&self) -> Option<&str> {
self.bridge.as_ref().map(|bridge| bridge.url())
}
pub async fn shutdown(mut self) -> anyhow::Result<()> {
if let Some(shutdown) = self.shutdown.take() {
shutdown();
}
if let Some(thread) = self.worker_thread.take() {
tokio::task::spawn_blocking(move || {
thread
.join()
.map_err(|_| anyhow::anyhow!("worker thread panicked"))?
})
.await
.context("join the worker thread")??;
}
Ok(())
}
}