feat: initialize server structure and database schema

- Added initial server setup with Cargo.toml defining dependencies and project structure.
- Created build.rs for generating protobuf bindings and validating wire contracts.
- Established database schema with initial migration files for conversations, messages, and runs.
- Introduced tools and prompts for Cursor functionality, enhancing user interaction capabilities.
This commit is contained in:
leookun committed 2026-08-30 01:33:39 +08:00
1 parent d200b3791d
commit 44e2d8057a
206 files changed
+37923 -21

No files matched your search

+35
View File
@@ -0,0 +1,35 @@
//! Defines Run commands and their explicit delivery results.
use tokio::sync::oneshot;
use crate::model::{CanonicalMessage, ToolResult};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CommandResult {
Applied,
Duplicate,
RunClosing,
RunEnded,
StaleTarget,
}
#[derive(Debug)]
pub struct MessageBatch {
pub event_id: String,
pub messages: Vec<CanonicalMessage>,
pub result: oneshot::Sender<CommandResult>,
}
impl MessageBatch {
pub fn complete(self, result: CommandResult) {
let _ = self.result.send(result);
}
}
#[derive(Debug)]
pub enum RunCommand {
ToolResult(ToolResult),
InsertMessages(MessageBatch),
BreakMessages(MessageBatch),
Cancel,
}
+111
View File
@@ -0,0 +1,111 @@
//! Decides when to compact context and builds a stable fallback summary.
use std::collections::HashSet;
use crate::model::{
CanonicalMessage, LlmCallUsageAnchor, PreparedRun, ProjectedMessage, RunAction,
};
const RESERVE_TOKENS: u64 = 10_000;
const FALLBACK_CHARS: usize = 12_000;
pub(super) const OUTPUT_TOKENS: u64 = 4_096;
pub(super) const INSTRUCTIONS: &str = "Summarize the conversation for the next model turn. Preserve goals, constraints, decisions, files, commands, errors, results, and unfinished work. Do not call tools. Return only the concise durable summary.";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct ContextUsageAnchor {
input_tokens: u64,
message_count: usize,
tool_count: usize,
}
impl ContextUsageAnchor {
pub(super) fn from_llm_call(anchor: LlmCallUsageAnchor) -> Option<Self> {
Some(Self {
input_tokens: anchor.usage.context_input_tokens(anchor.request_type)?,
message_count: anchor.message_count,
tool_count: anchor.tool_count,
})
}
}
pub(super) fn should_compact(
prepared: &PreparedRun,
messages: &[CanonicalMessage],
projected_messages: &[ProjectedMessage],
anchor: Option<ContextUsageAnchor>,
) -> bool {
if prepared.action != RunAction::Start {
return false;
}
let Some(context_window) = prepared.model.context_window_tokens else {
return false;
};
if context_window <= RESERVE_TOKENS || messages.len() <= prepared.initial_messages.len() {
return false;
}
let estimated_input = anchor
.filter(|anchor| {
anchor.message_count <= projected_messages.len()
&& anchor.tool_count == prepared.prompt.tools.len()
})
.map(|anchor| {
anchor
.input_tokens
.saturating_add(estimate_serialized_tokens(
&serde_json::to_string(&projected_messages[anchor.message_count..])
.unwrap_or_default(),
))
})
.unwrap_or_else(|| {
estimate_serialized_tokens(
&serde_json::to_string(&(&prepared.prompt, messages)).unwrap_or_default(),
)
});
estimated_input > context_window.saturating_sub(RESERVE_TOKENS)
}
pub(super) fn partition(
messages: &[CanonicalMessage],
current_ids: &HashSet<&str>,
) -> (Vec<CanonicalMessage>, Option<CanonicalMessage>) {
let latest_request_context = messages
.iter()
.rposition(|message| message.message_id.starts_with("request-context:"));
let compactable = messages
.iter()
.enumerate()
.filter(|(index, message)| {
Some(*index) != latest_request_context
&& !current_ids.contains(message.message_id.as_str())
})
.map(|(_, message)| message.clone())
.collect();
let retained = latest_request_context
.and_then(|index| messages.get(index))
.filter(|message| !current_ids.contains(message.message_id.as_str()))
.cloned();
(compactable, retained)
}
pub(super) fn fallback_summary(messages: &[CanonicalMessage]) -> String {
let serialized = serde_json::to_string(messages).unwrap_or_default();
let start = serialized
.char_indices()
.rev()
.nth(FALLBACK_CHARS.saturating_sub(1))
.map_or(0, |(index, _)| index);
format!(
"Durable recent conversation state:\n{}",
&serialized[start..]
)
}
fn estimate_serialized_tokens(serialized: &str) -> u64 {
serialized
.chars()
.fold(0_u64, |units, character| {
units.saturating_add(if character.is_ascii() { 273 } else { 550 })
})
.div_ceil(1_000)
}
+831
View File
@@ -0,0 +1,831 @@
//! Executes one Run across model cycles, Tool rounds, and message commits.
use std::collections::HashSet;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use crate::{
model::{
CanonicalMessage, MessageContent, Origin, PreparedRun, Role, RunAction, ToolRoundAssistant,
ToolRoundId, Usage,
},
provider::Provider,
store::{RunStatus, Store},
};
use super::{
consume_model_cycle, CommitBarrier, CommitCause, MessagesCommitted, ModelCycleFailure,
RunCommand, RunEvent, RunFailure, RunOutcome, RunPort,
};
pub struct RunEngine {
store: Store,
provider: Arc<dyn Provider>,
}
impl RunEngine {
pub fn new(store: Store, provider: Arc<dyn Provider>) -> Self {
Self { store, provider }
}
#[tracing::instrument(
skip_all,
fields(run_id = %prepared.run_id, conversation_id = %prepared.conversation_id)
)]
pub async fn run(
&self,
prepared: PreparedRun,
mut client: RunPort,
cancellation: CancellationToken,
) -> RunOutcome {
let claimed = match self.store.claim_run(&prepared).await {
Ok(claimed) => claimed,
Err(error) => {
let outcome = RunOutcome::Failed(error.into());
client.phase.finish();
let _ = client.events.send(RunEvent::Ended(outcome.clone())).await;
tracing::info!(outcome = ?outcome, "Run claim failed");
return outcome;
}
};
let outcome = self
.run_claimed(
&prepared,
claimed.head_checkpoint_id,
&mut client,
&cancellation,
)
.await;
let usage = outcome.1;
let outcome = outcome.0;
let (status, failure) = match &outcome {
RunOutcome::Completed => (RunStatus::Completed, None),
RunOutcome::Cancelled => (RunStatus::Cancelled, None),
RunOutcome::Failed(failure) => (
RunStatus::Failed,
Some((failure.category(), failure_message(failure))),
),
};
let failure_ref = failure
.as_ref()
.map(|(category, summary)| (*category, summary.as_str()));
if let Err(error) = self
.store
.finish_run(&prepared.run_id, status, usage, failure_ref)
.await
{
tracing::error!(run_id = %prepared.run_id, %error, "failed to persist Run outcome");
}
client.phase.finish();
let _ = client.events.send(RunEvent::Ended(outcome.clone())).await;
tracing::info!(outcome = ?outcome, usage = ?usage, "Run ended");
outcome
}
async fn run_claimed(
&self,
prepared: &PreparedRun,
mut checkpoint: crate::model::CheckpointId,
client: &mut RunPort,
cancellation: &CancellationToken,
) -> (RunOutcome, Option<Usage>) {
let mut usage = None;
tracing::info!(
checkpoint_id = checkpoint.0,
"Run claimed conversation ownership"
);
if !prepared.initial_messages.is_empty() {
let mut changed = false;
for message in &prepared.initial_messages {
match self
.store
.append_message_once(
&prepared.conversation_id,
&prepared.run_id,
checkpoint,
message,
)
.await
{
Ok((next, inserted)) => {
checkpoint = next;
changed |= inserted;
}
Err(error) => return (RunOutcome::Failed(error.into()), usage),
}
}
if changed {
let (barrier, ready) = CommitBarrier::before_continue();
if emit(
client,
RunEvent::MessagesCommitted(MessagesCommitted {
checkpoint_id: checkpoint,
tool_round_version: 0,
cause: CommitCause::InitialMessages,
barrier,
}),
)
.await
.is_err()
{
return (client_failure(), usage);
}
if let Err(outcome) = wait_for_state_ready(ready, cancellation).await {
return (outcome, usage);
}
}
}
if let RunAction::Resume {
pending_tool_round: Some(round),
} = &prepared.action
{
checkpoint = match super::tool_round::execute(
&self.store,
prepared,
client,
cancellation,
checkpoint,
super::tool_round::ToolRound {
id: ToolRoundId::new(format!("{}:round:resume", prepared.run_id)),
assistant: round.assistant.clone(),
calls: round.calls.clone(),
recovered_started_at_ms: Some(round.started_at_ms),
},
Vec::new(),
)
.await
{
Ok(checkpoint) => checkpoint,
Err(outcome) => return (outcome, usage),
};
}
let mut auto_compacted = prepared.action == RunAction::Compact;
'model: loop {
if cancellation.is_cancelled() {
return (RunOutcome::Cancelled, usage);
}
let messages = match self.store.load_checkpoint_messages(checkpoint).await {
Ok(messages) => messages,
Err(error) => return (RunOutcome::Failed(error.into()), usage),
};
let context_anchor = if !auto_compacted && prepared.action == RunAction::Start {
match self
.store
.latest_llm_call_usage_anchor(
&prepared.conversation_id,
&prepared.model.model_id,
)
.await
{
Ok(anchor) => {
anchor.and_then(super::compaction::ContextUsageAnchor::from_llm_call)
}
Err(error) => return (RunOutcome::Failed(error.into()), usage),
}
} else {
None
};
let history = match crate::model::project_messages(&messages) {
Ok(history) => history,
Err(error) => return (RunOutcome::Failed(error.into()), usage),
};
if !auto_compacted
&& super::compaction::should_compact(prepared, &messages, &history, context_anchor)
{
auto_compacted = true;
match self
.auto_compact(prepared, checkpoint, &messages, client, cancellation)
.await
{
Ok((next_checkpoint, compaction_usage)) => {
checkpoint = next_checkpoint;
if let Some(compaction_usage) = compaction_usage {
accumulate_usage(&mut usage, compaction_usage);
}
continue 'model;
}
Err(outcome) => return (outcome, usage),
}
}
let provider_call_index = match self.store.begin_provider_call(&prepared.run_id).await {
Ok(index) => index,
Err(error) => return (RunOutcome::Failed(error.into()), usage),
};
tracing::debug!(
provider_call_index,
checkpoint_id = checkpoint.0,
"starting model call"
);
let mut history = history;
if let Err(error) = hydrate_tool_images(&self.store, &mut history).await {
return (RunOutcome::Failed(error.into()), usage);
}
let request = crate::model::ModelRequest {
prompt: prepared.prompt.clone(),
model: prepared.model.clone(),
history,
};
let invocation = crate::model::ModelInvocation {
call_id: format!("{}:{provider_call_index}", prepared.run_id),
run_id: prepared.run_id.to_string(),
conversation_id: prepared.conversation_id.to_string(),
provider_call_index,
request,
};
let cycle_cancellation = cancellation.child_token();
let cycle_events = client.events.clone();
let cycle = consume_model_cycle(
self.provider.stream(invocation, cycle_cancellation.clone()),
&cycle_events,
&cycle_cancellation,
);
tokio::pin!(cycle);
let mut pending_insertions = Vec::new();
let cycle = loop {
tokio::select! {
biased;
command = client.commands.recv() => {
let interruption = match command {
Some(RunCommand::InsertMessages(insertion)) => {
pending_insertions.push(insertion);
continue;
}
Some(RunCommand::BreakMessages(messages)) => messages,
Some(RunCommand::Cancel) => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (RunOutcome::Cancelled, usage);
}
Some(RunCommand::ToolResult(_)) => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (
RunOutcome::Failed(RunFailure::Protocol(
"received a tool result while the model was running".into(),
)),
usage,
);
}
None => {
cycle_cancellation.cancel();
let _ = cycle.await;
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (client_failure(), usage);
}
};
cycle_cancellation.cancel();
let interrupted = cycle.await;
match interrupted {
Ok(cycle) => {
if let Some(cycle_usage) = cycle.usage {
accumulate_usage(&mut usage, cycle_usage);
}
}
Err(failure) => {
if let Some(cycle_usage) = failure.usage {
accumulate_usage(&mut usage, cycle_usage);
}
}
}
if emit(client, RunEvent::CycleInterrupted).await.is_err() {
return (client_failure(), usage);
}
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
std::mem::take(&mut pending_insertions),
)
.await
{
Ok((checkpoint, _)) => checkpoint,
Err(outcome) => return (outcome, usage),
};
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
vec![interruption],
)
.await
{
Ok((checkpoint, _)) => checkpoint,
Err(outcome) => return (outcome, usage),
};
continue 'model;
},
result = &mut cycle => break result,
}
};
let cycle = match cycle {
Ok(cycle) => cycle,
Err(ModelCycleFailure {
failure,
usage: cycle_usage,
..
}) => {
if let Some(cycle_usage) = cycle_usage {
accumulate_usage(&mut usage, cycle_usage);
}
if cancellation.is_cancelled() {
let _ = emit(client, RunEvent::CycleInterrupted).await;
return (RunOutcome::Cancelled, usage);
}
return (RunOutcome::Failed(failure), usage);
}
};
if let Some(cycle_usage) = cycle.usage {
accumulate_usage(&mut usage, cycle_usage);
}
if prepared.action == RunAction::Compact {
if !cycle.calls.is_empty() {
return (
RunOutcome::Failed(RunFailure::Protocol(
"compaction model returned tool calls".into(),
)),
usage,
);
}
let summary = cycle.text.trim().to_string();
if summary.is_empty() {
return (
RunOutcome::Failed(RunFailure::Protocol(
"compaction model returned an empty summary".into(),
)),
usage,
);
}
let event_id = format!("summary:{}", prepared.run_id);
let summary_message = CanonicalMessage {
message_id: format!("runtime:{event_id}"),
role: Role::User,
origin: Origin::Runtime,
content: MessageContent::Parts {
parts: vec![crate::model::ContentPart::Text {
text: format!(
"<conversation_summary>\n{summary}\n</conversation_summary>"
),
}],
},
runtime_event_id: Some(event_id),
};
checkpoint = match self
.store
.replace_checkpoint(
&prepared.conversation_id,
&prepared.run_id,
checkpoint,
&[summary_message],
)
.await
{
Ok(checkpoint) => checkpoint,
Err(error) => return (RunOutcome::Failed(error.into()), usage),
};
if !pending_insertions.is_empty() {
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
pending_insertions,
)
.await
{
Ok((next, _)) => next,
Err(outcome) => return (outcome, usage),
};
}
client.phase.begin_finalizing();
let closing_insertions = match super::messages::drain_accepted(client) {
Ok(insertions) => insertions,
Err(outcome) => return (outcome, usage),
};
if !closing_insertions.is_empty() {
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
closing_insertions,
)
.await
{
Ok((next, _)) => next,
Err(outcome) => return (outcome, usage),
};
}
let (barrier, ready) = CommitBarrier::before_continue();
if emit(
client,
RunEvent::MessagesCommitted(MessagesCommitted {
checkpoint_id: checkpoint,
tool_round_version: 0,
cause: CommitCause::Compaction { summary },
barrier,
}),
)
.await
.is_err()
{
return (client_failure(), usage);
}
if let Err(outcome) = wait_for_state_ready(ready, cancellation).await {
return (outcome, usage);
}
return (RunOutcome::Completed, usage);
}
if cycle.calls.is_empty() {
let assistant = CanonicalMessage {
message_id: format!("{}:assistant:{provider_call_index}", prepared.run_id),
role: Role::Assistant,
origin: Origin::Assistant,
content: MessageContent::Assistant {
text: cycle.text,
thinking: cycle.reasoning,
tool_round_id: None,
replay_state: cycle.replay_state,
tool_calls: Vec::new(),
},
runtime_event_id: None,
};
checkpoint = match self
.store
.append_checkpoint(
&prepared.conversation_id,
&prepared.run_id,
checkpoint,
&[assistant],
)
.await
{
Ok(checkpoint) => checkpoint,
Err(error) => return (RunOutcome::Failed(error.into()), usage),
};
if !pending_insertions.is_empty() {
let inserted = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
pending_insertions,
)
.await
{
Ok((next, inserted)) => {
checkpoint = next;
inserted
}
Err(outcome) => return (outcome, usage),
};
if inserted {
continue 'model;
}
}
client.phase.begin_finalizing();
let closing_insertions = match super::messages::drain_accepted(client) {
Ok(insertions) => insertions,
Err(outcome) => return (outcome, usage),
};
if !closing_insertions.is_empty() {
checkpoint = match super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
closing_insertions,
)
.await
{
Ok((next, _)) => next,
Err(outcome) => return (outcome, usage),
};
client.phase.resume_running();
continue 'model;
}
let (barrier, ready) = CommitBarrier::before_continue();
if emit(
client,
RunEvent::MessagesCommitted(MessagesCommitted {
checkpoint_id: checkpoint,
tool_round_version: 0,
cause: CommitCause::FinalTurn,
barrier,
}),
)
.await
.is_err()
{
return (client_failure(), usage);
}
if let Err(outcome) = wait_for_state_ready(ready, cancellation).await {
return (outcome, usage);
}
return (RunOutcome::Completed, usage);
}
let round_id =
ToolRoundId::new(format!("{}:round:{provider_call_index}", prepared.run_id));
checkpoint = match super::tool_round::execute(
&self.store,
prepared,
client,
cancellation,
checkpoint,
super::tool_round::ToolRound {
id: round_id,
assistant: ToolRoundAssistant {
text: cycle.text,
thinking: cycle.reasoning,
model_call_id: cycle.model_call_id,
replay_state: cycle.replay_state,
},
calls: cycle.calls,
recovered_started_at_ms: None,
},
pending_insertions,
)
.await
{
Ok(checkpoint) => checkpoint,
Err(outcome) => return (outcome, usage),
};
}
}
async fn auto_compact(
&self,
prepared: &PreparedRun,
checkpoint: crate::model::CheckpointId,
messages: &[CanonicalMessage],
client: &mut RunPort,
cancellation: &CancellationToken,
) -> std::result::Result<(crate::model::CheckpointId, Option<Usage>), RunOutcome> {
let current_ids = prepared
.initial_messages
.iter()
.map(|message| message.message_id.as_str())
.collect::<HashSet<_>>();
let (compactable, retained_request_context) =
super::compaction::partition(messages, &current_ids);
if compactable.is_empty() {
return Ok((checkpoint, None));
}
emit(client, RunEvent::AutoCompactionStarted)
.await
.map_err(|_| client_failure())?;
let provider_call_index = self
.store
.begin_provider_call(&prepared.run_id)
.await
.map_err(|error| RunOutcome::Failed(error.into()))?;
let history = crate::model::project_messages(&compactable)
.map_err(|error| RunOutcome::Failed(error.into()))?;
let mut model = prepared.model.clone();
model.max_output_tokens = Some(super::compaction::OUTPUT_TOKENS);
model.reasoning.enabled = false;
model.reasoning.effort = None;
let invocation = crate::model::ModelInvocation {
call_id: format!("{}:{provider_call_index}", prepared.run_id),
run_id: prepared.run_id.to_string(),
conversation_id: prepared.conversation_id.to_string(),
provider_call_index,
request: crate::model::ModelRequest {
prompt: crate::model::PromptSpec {
instructions: super::compaction::INSTRUCTIONS.into(),
tools: Vec::new(),
},
model,
history,
},
};
let cycle_cancellation = cancellation.child_token();
let (silent_events, mut discarded_events) = tokio::sync::mpsc::channel(256);
let drain = tokio::spawn(async move { while discarded_events.recv().await.is_some() {} });
let mut pending_insertions = Vec::new();
let mut break_messages = None;
let cycle = {
let cycle = consume_model_cycle(
self.provider.stream(invocation, cycle_cancellation.clone()),
&silent_events,
&cycle_cancellation,
);
tokio::pin!(cycle);
loop {
tokio::select! {
biased;
command = client.commands.recv() => match command {
Some(RunCommand::InsertMessages(insertion)) => {
pending_insertions.push(insertion);
}
Some(RunCommand::BreakMessages(messages)) => {
cycle_cancellation.cancel();
break_messages = Some(messages);
break cycle.await;
}
Some(RunCommand::Cancel) => {
cycle_cancellation.cancel();
let _ = cycle.await;
return Err(RunOutcome::Cancelled);
}
Some(RunCommand::ToolResult(_)) => {
cycle_cancellation.cancel();
let _ = cycle.await;
return Err(RunOutcome::Failed(RunFailure::Protocol(
"received a tool result while automatic compaction was running".into(),
)));
}
None => {
cycle_cancellation.cancel();
let _ = cycle.await;
return Err(client_failure());
}
},
result = &mut cycle => break result,
}
}
};
drop(silent_events);
let _ = drain.await;
let (summary, compaction_usage) = match (break_messages.is_some(), cycle) {
(true, Ok(cycle)) => (
super::compaction::fallback_summary(&compactable),
cycle.usage,
),
(true, Err(failure)) => (
super::compaction::fallback_summary(&compactable),
failure.usage,
),
(false, Ok(cycle)) if cycle.calls.is_empty() && !cycle.text.trim().is_empty() => {
(cycle.text.trim().to_string(), cycle.usage)
}
(false, Ok(cycle)) => {
tracing::warn!("automatic compaction returned no usable summary; using fallback");
(
super::compaction::fallback_summary(&compactable),
cycle.usage,
)
}
(false, Err(failure)) => {
tracing::warn!(error = ?failure.failure, "automatic compaction model failed; using fallback");
(
super::compaction::fallback_summary(&compactable),
failure.usage,
)
}
};
let event_id = format!("summary:auto:{}", prepared.run_id);
let summary_message = CanonicalMessage {
message_id: format!("runtime:{event_id}"),
role: Role::User,
origin: Origin::Runtime,
content: MessageContent::Parts {
parts: vec![crate::model::ContentPart::Text {
text: format!("<conversation_summary>\n{summary}\n</conversation_summary>"),
}],
},
runtime_event_id: Some(event_id),
};
let mut replacement = retained_request_context.into_iter().collect::<Vec<_>>();
replacement.push(summary_message);
replacement.extend(prepared.initial_messages.iter().cloned());
let mut checkpoint = self
.store
.replace_checkpoint(
&prepared.conversation_id,
&prepared.run_id,
checkpoint,
&replacement,
)
.await
.map_err(|error| RunOutcome::Failed(error.into()))?;
let (barrier, ready) = CommitBarrier::before_continue();
emit(
client,
RunEvent::MessagesCommitted(MessagesCommitted {
checkpoint_id: checkpoint,
tool_round_version: 0,
cause: CommitCause::Compaction { summary },
barrier,
}),
)
.await
.map_err(|_| client_failure())?;
wait_for_state_ready(ready, cancellation).await?;
emit(client, RunEvent::AutoCompactionCompleted)
.await
.map_err(|_| client_failure())?;
checkpoint = super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
pending_insertions,
)
.await?
.0;
if let Some(messages) = break_messages {
checkpoint = super::messages::append_batches(
&self.store,
prepared,
client,
cancellation,
checkpoint,
vec![messages],
)
.await?
.0;
}
Ok((checkpoint, compaction_usage))
}
}
async fn hydrate_tool_images(
store: &Store,
messages: &mut [crate::model::ProjectedMessage],
) -> crate::Result<()> {
use crate::{
model::{ContentPart, ProjectedContent},
store::BlobId,
Error,
};
for message in messages {
let ProjectedContent::ToolResult(result) = &mut message.content else {
continue;
};
let Some(image) = &result.image else {
continue;
};
let id = BlobId::from_base64(&image.blob_id)?;
let data = store.get_blob(&id).await?.ok_or_else(|| {
Error::Protocol(format!("Read image Blob is missing: {}", image.blob_id))
})?;
result.provider_parts = vec![
ContentPart::Text {
text: result.content.clone(),
},
ContentPart::Image {
mime_type: image.mime_type.clone(),
data,
},
];
}
Ok(())
}
fn accumulate_usage(total: &mut Option<Usage>, usage: Usage) {
match total {
Some(total) => *total += usage,
None => *total = Some(usage),
}
}
pub(super) async fn wait_for_state_ready(
ready: tokio::sync::oneshot::Receiver<std::result::Result<(), String>>,
cancellation: &CancellationToken,
) -> std::result::Result<(), RunOutcome> {
let result = tokio::select! {
biased;
result = ready => result,
_ = cancellation.cancelled() => return Err(RunOutcome::Cancelled),
};
match result {
Ok(Ok(())) => Ok(()),
Ok(Err(error)) => Err(RunOutcome::Failed(RunFailure::Client(error))),
Err(_) => Err(client_failure()),
}
}
pub(super) async fn emit(client: &RunPort, event: RunEvent) -> Result<(), ()> {
client.events.send(event).await.map_err(|_| ())
}
pub(super) fn client_failure() -> RunOutcome {
RunOutcome::Failed(RunFailure::Client("client event channel closed".into()))
}
fn failure_message(failure: &RunFailure) -> String {
match failure {
RunFailure::Protocol(message)
| RunFailure::Provider(message)
| RunFailure::Store(message)
| RunFailure::Client(message) => message.clone(),
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Defines Run events and terminal outcomes.
use std::time::Duration;
use tokio::sync::oneshot;
use crate::model::{CheckpointId, ToolCall, ToolRoundId, Usage};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RunFailure {
Protocol(String),
Provider(String),
Store(String),
Client(String),
}
impl RunFailure {
pub fn category(&self) -> &'static str {
match self {
Self::Protocol(_) => "protocol",
Self::Provider(_) => "provider",
Self::Store(_) => "store",
Self::Client(_) => "client",
}
}
}
impl From<crate::Error> for RunFailure {
fn from(error: crate::Error) -> Self {
use crate::Error;
match error {
Error::Protocol(message) | Error::Config(message) => Self::Protocol(message),
Error::Provider(message) => Self::Provider(message),
Error::Store(message) => Self::Store(message),
Error::Cancelled => Self::Client("run was cancelled".into()),
Error::Http(error) => Self::Provider(error.to_string()),
Error::Database(error) => Self::Store(error.to_string()),
Error::Migration(error) => Self::Store(error.to_string()),
Error::Io(error) => Self::Store(error.to_string()),
Error::Decode(error) => Self::Protocol(error.to_string()),
Error::Encode(error) => Self::Protocol(error.to_string()),
Error::Json(error) => Self::Protocol(error.to_string()),
Error::RunNotFound(run_id) => Self::Store(format!("run not found: {run_id}")),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RunOutcome {
Completed,
Cancelled,
Failed(RunFailure),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CommitCause {
InitialMessages,
ToolRoundStarted(ToolRoundId),
ToolResult { call_id: String, interrupted: bool },
FinalTurn,
Compaction { summary: String },
RuntimeEvent { event_id: String },
}
#[derive(Debug)]
pub enum CommitBarrier {
None,
BeforeContinue(oneshot::Sender<std::result::Result<(), String>>),
}
impl CommitBarrier {
pub fn before_continue() -> (Self, oneshot::Receiver<std::result::Result<(), String>>) {
let (sender, receiver) = oneshot::channel();
(Self::BeforeContinue(sender), receiver)
}
pub fn is_required(&self) -> bool {
matches!(self, Self::BeforeContinue(_))
}
pub fn complete(self, result: std::result::Result<(), String>) {
if let Self::BeforeContinue(sender) = self {
let _ = sender.send(result);
}
}
}
#[derive(Debug)]
pub struct MessagesCommitted {
pub checkpoint_id: CheckpointId,
pub tool_round_version: u64,
pub cause: CommitCause,
pub barrier: CommitBarrier,
}
#[derive(Debug)]
pub enum RunEvent {
AutoCompactionStarted,
AutoCompactionCompleted,
CycleInterrupted,
TextStart,
TextDelta(String),
TextEnd,
ThinkingStart,
ThinkingDelta(String),
ThinkingEnd {
duration: Duration,
},
ToolCallStart {
index: usize,
call_id: String,
name: String,
model_call_id: String,
},
ToolCallArgumentsDelta {
index: usize,
delta: String,
},
ToolCallEnd {
index: usize,
},
Usage(Usage),
ExecuteToolRound {
round_id: ToolRoundId,
calls: Vec<ToolCall>,
},
MessagesCommitted(MessagesCommitted),
Ended(RunOutcome),
}
+159
View File
@@ -0,0 +1,159 @@
//! Provides phase-aware command submission and cancellation for an active Run.
use std::sync::Arc;
use parking_lot::Mutex;
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;
use crate::model::{CanonicalMessage, RunId, ToolResult};
use super::{CommandResult, MessageBatch, RunCommand};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunPhase {
Running,
Finalizing,
Ended,
}
#[derive(Clone)]
pub(crate) struct RunPhaseControl {
value: Arc<Mutex<RunPhase>>,
}
impl RunPhaseControl {
pub(crate) fn new() -> Self {
Self {
value: Arc::new(Mutex::new(RunPhase::Running)),
}
}
pub(crate) fn get(&self) -> RunPhase {
*self.value.lock()
}
pub(crate) fn begin_finalizing(&self) {
let mut phase = self.value.lock();
if *phase == RunPhase::Running {
*phase = RunPhase::Finalizing;
}
}
pub(crate) fn resume_running(&self) {
let mut phase = self.value.lock();
if *phase == RunPhase::Finalizing {
*phase = RunPhase::Running;
}
}
pub(crate) fn finish(&self) {
*self.value.lock() = RunPhase::Ended;
}
pub(crate) fn with_phase<T>(&self, action: impl FnOnce(RunPhase) -> T) -> T {
action(*self.value.lock())
}
}
#[derive(Clone)]
pub struct RunHandle {
run_id: RunId,
phase: RunPhaseControl,
commands: mpsc::UnboundedSender<RunCommand>,
cancellation: CancellationToken,
}
impl RunHandle {
pub(crate) fn new(
run_id: RunId,
phase: RunPhaseControl,
commands: mpsc::UnboundedSender<RunCommand>,
cancellation: CancellationToken,
) -> Self {
Self {
run_id,
phase,
commands,
cancellation,
}
}
pub fn run_id(&self) -> &RunId {
&self.run_id
}
pub fn phase(&self) -> RunPhase {
self.phase.get()
}
pub async fn insert_messages(
&self,
event_id: String,
messages: Vec<CanonicalMessage>,
) -> CommandResult {
self.submit_messages(event_id, messages, false).await
}
pub async fn break_messages(
&self,
event_id: String,
messages: Vec<CanonicalMessage>,
) -> CommandResult {
self.submit_messages(event_id, messages, true).await
}
async fn submit_messages(
&self,
event_id: String,
messages: Vec<CanonicalMessage>,
should_break: bool,
) -> CommandResult {
let (result, delivered) = oneshot::channel();
let batch = MessageBatch {
event_id,
messages,
result,
};
let command = if should_break {
RunCommand::BreakMessages(batch)
} else {
RunCommand::InsertMessages(batch)
};
let sent = self.phase.with_phase(|phase| match phase {
RunPhase::Running if self.commands.send(command).is_ok() => CommandResult::Applied,
RunPhase::Running | RunPhase::Ended => CommandResult::RunEnded,
RunPhase::Finalizing => CommandResult::RunClosing,
});
match sent {
CommandResult::RunClosing => return CommandResult::RunClosing,
CommandResult::RunEnded => return CommandResult::RunEnded,
CommandResult::Applied => {}
CommandResult::Duplicate | CommandResult::StaleTarget => unreachable!(),
}
delivered.await.unwrap_or_else(|_| match self.phase() {
RunPhase::Running => CommandResult::RunEnded,
RunPhase::Finalizing => CommandResult::RunClosing,
RunPhase::Ended => CommandResult::RunEnded,
})
}
pub async fn tool_result(&self, result: ToolResult) -> CommandResult {
self.phase.with_phase(|phase| match phase {
RunPhase::Running if self.commands.send(RunCommand::ToolResult(result)).is_ok() => {
CommandResult::Applied
}
RunPhase::Running | RunPhase::Ended => CommandResult::RunEnded,
RunPhase::Finalizing => CommandResult::RunClosing,
})
}
pub fn cancel(&self) {
self.cancellation.cancel();
let _ = self.commands.send(RunCommand::Cancel);
}
pub fn cancellation(&self) -> CancellationToken {
self.cancellation.clone()
}
}
+99
View File
@@ -0,0 +1,99 @@
//! Commits runtime messages once and acknowledges their delivery result.
use tokio_util::sync::CancellationToken;
use crate::{
model::{CanonicalMessage, CheckpointId, PreparedRun},
store::Store,
};
use super::{
engine::{client_failure, emit, wait_for_state_ready},
CommandResult, CommitBarrier, CommitCause, MessageBatch, MessagesCommitted, RunCommand,
RunEvent, RunFailure, RunOutcome, RunPort,
};
pub(super) async fn append_batches(
store: &Store,
prepared: &PreparedRun,
client: &mut RunPort,
cancellation: &CancellationToken,
mut checkpoint: CheckpointId,
batches: Vec<MessageBatch>,
) -> Result<(CheckpointId, bool), RunOutcome> {
let mut inserted_any = false;
for batch in batches {
let mut batch_inserted = false;
for message in batch.messages {
let (next, inserted) =
append_one(store, prepared, client, cancellation, checkpoint, message).await?;
checkpoint = next;
inserted_any |= inserted;
batch_inserted |= inserted;
}
let _ = batch.result.send(if batch_inserted {
CommandResult::Applied
} else {
CommandResult::Duplicate
});
}
Ok((checkpoint, inserted_any))
}
pub(super) fn drain_accepted(client: &mut RunPort) -> Result<Vec<MessageBatch>, RunOutcome> {
let mut messages = Vec::new();
loop {
match client.commands.try_recv() {
Ok(RunCommand::InsertMessages(batch) | RunCommand::BreakMessages(batch)) => {
messages.push(batch);
}
Ok(RunCommand::Cancel) => return Err(RunOutcome::Cancelled),
Ok(RunCommand::ToolResult(_)) => {}
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => return Ok(messages),
Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
return Err(client_failure())
}
}
}
}
async fn append_one(
store: &Store,
prepared: &PreparedRun,
client: &mut RunPort,
cancellation: &CancellationToken,
checkpoint: CheckpointId,
message: CanonicalMessage,
) -> Result<(CheckpointId, bool), RunOutcome> {
let event_id = message.runtime_event_id.clone().ok_or_else(|| {
RunOutcome::Failed(RunFailure::Protocol(
"runtime message has no event identity".into(),
))
})?;
let (checkpoint, inserted) = store
.append_message_once(
&prepared.conversation_id,
&prepared.run_id,
checkpoint,
&message,
)
.await
.map_err(|error| RunOutcome::Failed(error.into()))?;
if !inserted {
return Ok((checkpoint, false));
}
let (barrier, ready) = CommitBarrier::before_continue();
emit(
client,
RunEvent::MessagesCommitted(MessagesCommitted {
checkpoint_id: checkpoint,
tool_round_version: 0,
cause: CommitCause::RuntimeEvent { event_id },
barrier,
}),
)
.await
.map_err(|_| client_failure())?;
wait_for_state_ready(ready, cancellation).await?;
Ok((checkpoint, true))
}
+18
View File
@@ -0,0 +1,18 @@
//! Exposes the provider-independent Agent Run loop.
mod command;
mod compaction;
mod engine;
mod event;
mod handle;
mod messages;
mod model_cycle;
mod port;
mod tool_round;
pub use command::*;
pub use engine::*;
pub use event::*;
pub use handle::*;
pub use model_cycle::*;
pub use port::*;
+369
View File
@@ -0,0 +1,369 @@
//! Executes and consumes one streaming provider call.
use std::{collections::btree_map::Entry, collections::BTreeMap, time::Instant};
use futures_util::StreamExt;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::{
model::{ProviderReplayState, ToolCall, Usage},
provider::{FinishReason, ModelEvent, ProviderStream},
};
use super::{RunEvent, RunFailure};
#[derive(Clone, Debug, PartialEq)]
pub struct ModelCycleResult {
pub model_call_id: String,
pub text: String,
pub reasoning: String,
pub replay_state: Option<ProviderReplayState>,
pub calls: Vec<ToolCall>,
pub usage: Option<Usage>,
pub finish_reason: FinishReason,
}
#[derive(Clone, Debug, PartialEq)]
pub struct ModelCycleFailure {
pub failure: RunFailure,
pub partial_text: String,
pub partial_reasoning: String,
pub usage: Option<Usage>,
}
struct OpenTool {
call: ToolCall,
ended: bool,
}
pub async fn consume_model_cycle(
mut stream: ProviderStream,
client: &mpsc::Sender<RunEvent>,
cancellation: &CancellationToken,
) -> std::result::Result<ModelCycleResult, ModelCycleFailure> {
let mut model_call_id = None;
let mut text = String::new();
let mut reasoning = String::new();
let mut text_open = false;
let mut thinking_started = None::<Instant>;
let mut tools = BTreeMap::<usize, OpenTool>::new();
let mut call_ids = std::collections::HashSet::new();
let mut replay_state = None;
let mut usage = None;
let mut finish = None;
loop {
let next = tokio::select! {
// Give the provider stream first chance to observe the shared token. Its
// cancellation branch owns the HTTP response body and recorder cleanup.
// The second branch remains a fallback for providers that ignore tokens.
biased;
next = stream.next() => next,
_ = cancellation.cancelled() => {
interrupt_cycle(client, text_open, thinking_started.take()).await;
return Err(failure(
RunFailure::Client("run was cancelled".into()),
text,
reasoning,
usage,
));
}
};
let Some(next) = next else {
if cancellation.is_cancelled() {
interrupt_cycle(client, text_open, thinking_started.take()).await;
return Err(failure(
RunFailure::Client("run was cancelled".into()),
text,
reasoning,
usage,
));
}
break;
};
let event = match next {
Ok(event) => event,
Err(error) => {
return Err(failure(error.into(), text, reasoning, usage));
}
};
if finish.is_some() {
return Err(failure(
RunFailure::Protocol("provider emitted an event after Done".into()),
text,
reasoning,
usage,
));
}
let result = match event {
ModelEvent::Start { model_call_id: id } => {
if model_call_id.replace(id).is_some() {
Err("provider emitted duplicate Start")
} else {
Ok(())
}
}
ModelEvent::TextStart => {
if model_call_id.is_none() {
Err("provider emitted content before Start")
} else if text_open {
Err("provider emitted duplicate TextStart")
} else {
text_open = true;
send(client, RunEvent::TextStart).await
}
}
ModelEvent::TextDelta(delta) => {
if !text_open {
Err("provider emitted TextDelta before TextStart")
} else {
text.push_str(&delta);
send(client, RunEvent::TextDelta(delta)).await
}
}
ModelEvent::TextEnd => {
if !text_open {
Err("provider emitted TextEnd before TextStart")
} else {
text_open = false;
send(client, RunEvent::TextEnd).await
}
}
ModelEvent::ThinkingStart => {
if model_call_id.is_none() {
Err("provider emitted content before Start")
} else if thinking_started.replace(Instant::now()).is_some() {
Err("provider emitted duplicate ThinkingStart")
} else {
send(client, RunEvent::ThinkingStart).await
}
}
ModelEvent::ThinkingDelta(delta) => {
if thinking_started.is_none() {
Err("provider emitted ThinkingDelta before ThinkingStart")
} else {
reasoning.push_str(&delta);
send(client, RunEvent::ThinkingDelta(delta)).await
}
}
ModelEvent::ThinkingEnd => {
if let Some(started) = thinking_started.take() {
send(
client,
RunEvent::ThinkingEnd {
duration: started.elapsed(),
},
)
.await
} else {
Err("provider emitted ThinkingEnd before ThinkingStart")
}
}
ModelEvent::ToolCallStart {
index,
call_id,
name,
} => {
let Some(model_call_id) = model_call_id.as_ref() else {
return Err(failure(
RunFailure::Protocol("provider emitted content before Start".into()),
text,
reasoning,
usage,
));
};
match tools.entry(index) {
Entry::Occupied(_) => Err("provider reused a tool index"),
Entry::Vacant(_) if !call_ids.insert(call_id.clone()) => {
Err("provider reused a tool call_id")
}
Entry::Vacant(entry) => {
entry.insert(OpenTool {
call: ToolCall {
index,
call_id: call_id.clone(),
model_call_id: model_call_id.clone(),
name: name.clone(),
arguments_text: String::new(),
arguments: serde_json::Value::Null,
},
ended: false,
});
send(
client,
RunEvent::ToolCallStart {
index,
call_id,
name,
model_call_id: model_call_id.clone(),
},
)
.await
}
}
}
ModelEvent::ToolCallArgumentsDelta { index, delta } => match tools.get_mut(&index) {
Some(tool) if !tool.ended => {
tool.call.arguments_text.push_str(&delta);
send(client, RunEvent::ToolCallArgumentsDelta { index, delta }).await
}
Some(_) => Err("provider emitted tool arguments after ToolCallEnd"),
None => Err("provider emitted tool arguments for an unknown index"),
},
ModelEvent::ToolCallEnd { index } => match tools.get_mut(&index) {
Some(tool) if !tool.ended => {
let arguments = if tool.call.arguments_text.trim().is_empty() {
Ok(serde_json::json!({}))
} else {
serde_json::from_str(&tool.call.arguments_text)
};
match arguments {
Ok(arguments) => {
tool.call.arguments = arguments;
tool.ended = true;
send(client, RunEvent::ToolCallEnd { index }).await
}
Err(_) => Err("provider ended a tool call with invalid JSON arguments"),
}
}
Some(_) => Err("provider emitted duplicate ToolCallEnd"),
None => Err("provider ended an unknown tool index"),
},
ModelEvent::ProviderReplayState(state) => {
if replay_state.replace(state).is_some() {
Err("provider emitted duplicate ProviderReplayState")
} else {
Ok(())
}
}
ModelEvent::Usage(value) => {
if usage.replace(value).is_some() {
Err("provider emitted duplicate Usage")
} else {
Ok(())
}
}
ModelEvent::Done(reason) => {
if model_call_id.is_none() {
Err("provider emitted content before Start")
} else if text_open
|| thinking_started.is_some()
|| tools.values().any(|tool| !tool.ended)
{
Err("provider emitted Done with an open content block")
} else {
finish = Some(reason);
Ok(())
}
}
};
if let Err(message) = result {
return Err(failure(
RunFailure::Protocol(message.into()),
text,
reasoning,
usage,
));
}
}
let Some(finish_reason) = finish else {
return Err(failure(
RunFailure::Provider("provider stream reached EOF before Done".into()),
text,
reasoning,
usage,
));
};
let calls = tools
.into_values()
.map(|tool| tool.call)
.collect::<Vec<_>>();
if finish_reason == FinishReason::Length {
return Err(failure(
RunFailure::Provider("model stopped before completing the response".into()),
text,
reasoning,
usage,
));
}
let has_tool_calls = !calls.is_empty();
if matches!(finish_reason, FinishReason::ToolUse) != has_tool_calls {
return Err(failure(
RunFailure::Protocol("finish reason and tool calls disagree".into()),
text,
reasoning,
usage,
));
}
if let Some(usage) = usage {
if send(client, RunEvent::Usage(usage)).await.is_err() {
return Err(failure(
RunFailure::Client("client event channel closed".into()),
text,
reasoning,
Some(usage),
));
}
}
let model_call_id = model_call_id.ok_or_else(|| {
failure(
RunFailure::Protocol("provider completed without Start".into()),
text.clone(),
reasoning.clone(),
usage,
)
})?;
Ok(ModelCycleResult {
model_call_id,
text,
reasoning,
replay_state,
calls,
usage,
finish_reason,
})
}
async fn send(
client: &mpsc::Sender<RunEvent>,
event: RunEvent,
) -> std::result::Result<(), &'static str> {
client
.send(event)
.await
.map_err(|_| "client event channel closed")
}
async fn interrupt_cycle(
client: &mpsc::Sender<RunEvent>,
text_open: bool,
thinking_started: Option<Instant>,
) {
if text_open {
let _ = send(client, RunEvent::TextEnd).await;
}
if let Some(started) = thinking_started {
let _ = send(
client,
RunEvent::ThinkingEnd {
duration: started.elapsed(),
},
)
.await;
}
}
fn failure(
failure: RunFailure,
partial_text: String,
partial_reasoning: String,
usage: Option<Usage>,
) -> ModelCycleFailure {
ModelCycleFailure {
failure,
partial_text,
partial_reasoning,
usage,
}
}
+35
View File
@@ -0,0 +1,35 @@
//! Defines the channel boundary between a Run and its adapter.
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use crate::model::RunId;
use super::{RunCommand, RunEvent, RunHandle, RunPhaseControl};
pub struct RunPort {
pub commands: mpsc::UnboundedReceiver<RunCommand>,
pub events: mpsc::Sender<RunEvent>,
pub(crate) phase: RunPhaseControl,
}
pub struct RunSession {
pub events: mpsc::Receiver<RunEvent>,
}
pub fn channel(run_id: RunId, capacity: usize) -> (RunPort, RunSession, RunHandle) {
let (commands_tx, commands_rx) = mpsc::unbounded_channel();
let (events_tx, events_rx) = mpsc::channel(capacity);
let phase = RunPhaseControl::new();
let cancellation = CancellationToken::new();
let handle = RunHandle::new(run_id, phase.clone(), commands_tx, cancellation.clone());
(
RunPort {
commands: commands_rx,
events: events_tx,
phase,
},
RunSession { events: events_rx },
handle,
)
}
+230
View File
@@ -0,0 +1,230 @@
//! Executes one logical round of Tool calls and results.
use std::collections::HashSet;
use tokio_util::sync::CancellationToken;
use crate::{
model::{CheckpointId, PreparedRun, ToolCall, ToolResult, ToolRoundAssistant, ToolRoundId},
store::Store,
};
use super::{
CommitBarrier, CommitCause, MessageBatch, MessagesCommitted, RunCommand, RunEvent, RunFailure,
RunOutcome, RunPort,
};
pub(super) struct ToolRound {
pub id: ToolRoundId,
pub assistant: ToolRoundAssistant,
pub calls: Vec<ToolCall>,
pub recovered_started_at_ms: Option<u64>,
}
pub(super) async fn execute(
store: &Store,
prepared: &PreparedRun,
client: &mut RunPort,
cancellation: &CancellationToken,
mut checkpoint: CheckpointId,
round: ToolRound,
insertions: Vec<MessageBatch>,
) -> std::result::Result<CheckpointId, RunOutcome> {
let ToolRound {
id: round_id,
assistant,
calls,
recovered_started_at_ms,
} = round;
store
.create_tool_round(
&round_id,
&prepared.run_id,
checkpoint,
&assistant,
&calls,
recovered_started_at_ms,
)
.await
.map_err(failed)?;
tracing::info!(
round_id = %round_id,
checkpoint_id = checkpoint.0,
calls = calls.len(),
"tool round started"
);
send(
client,
RunEvent::MessagesCommitted(MessagesCommitted {
checkpoint_id: checkpoint,
tool_round_version: 0,
cause: CommitCause::ToolRoundStarted(round_id.clone()),
barrier: CommitBarrier::None,
}),
)
.await?;
send(
client,
RunEvent::ExecuteToolRound {
round_id: round_id.clone(),
calls: calls.clone(),
},
)
.await?;
let mut remaining = calls.len();
let mut completed_call_ids = HashSet::new();
let mut pending_insertions = insertions;
while remaining > 0 {
let command = tokio::select! {
_ = cancellation.cancelled() => return Err(RunOutcome::Cancelled),
command = client.commands.recv() => command,
};
match command {
Some(RunCommand::ToolResult(result)) => {
let call_id = result.call_id.clone();
if completed_call_ids.contains(&call_id) {
continue;
}
let committed = store
.commit_tool_result(
&prepared.conversation_id,
&prepared.run_id,
&round_id,
&result,
)
.await
.map_err(failed)?;
checkpoint = committed.checkpoint_id;
completed_call_ids.insert(call_id.clone());
tracing::info!(
round_id = %round_id,
call_id,
checkpoint_id = checkpoint.0,
tool_round_version = committed.tool_round_version,
completion_seq = committed.completion_seq,
settled = committed.settled,
"tool result committed"
);
remaining -= 1;
let (barrier, ready) = if committed.settled {
let (barrier, ready) = CommitBarrier::before_continue();
(barrier, Some(ready))
} else {
(CommitBarrier::None, None)
};
send(
client,
RunEvent::MessagesCommitted(MessagesCommitted {
checkpoint_id: checkpoint,
tool_round_version: committed.tool_round_version,
cause: CommitCause::ToolResult {
call_id,
interrupted: false,
},
barrier,
}),
)
.await?;
if let Some(ready) = ready {
super::engine::wait_for_state_ready(ready, cancellation).await?;
}
}
Some(RunCommand::BreakMessages(messages)) => {
for call in calls
.iter()
.filter(|call| !completed_call_ids.contains(&call.call_id))
{
let result = ToolResult {
call_id: call.call_id.clone(),
content: "Tool execution was interrupted by a newer user message.".into(),
is_error: true,
image: None,
};
let committed = store
.commit_tool_result(
&prepared.conversation_id,
&prepared.run_id,
&round_id,
&result,
)
.await
.map_err(failed)?;
checkpoint = committed.checkpoint_id;
let (barrier, ready) = if committed.settled {
let (barrier, ready) = CommitBarrier::before_continue();
(barrier, Some(ready))
} else {
(CommitBarrier::None, None)
};
send(
client,
RunEvent::MessagesCommitted(MessagesCommitted {
checkpoint_id: checkpoint,
tool_round_version: committed.tool_round_version,
cause: CommitCause::ToolResult {
call_id: call.call_id.clone(),
interrupted: true,
},
barrier,
}),
)
.await?;
if let Some(ready) = ready {
super::engine::wait_for_state_ready(ready, cancellation).await?;
}
}
checkpoint = super::messages::append_batches(
store,
prepared,
client,
cancellation,
checkpoint,
pending_insertions,
)
.await?
.0;
checkpoint = super::messages::append_batches(
store,
prepared,
client,
cancellation,
checkpoint,
vec![messages],
)
.await?
.0;
return Ok(checkpoint);
}
Some(RunCommand::InsertMessages(insertion)) => pending_insertions.push(insertion),
Some(RunCommand::Cancel) => return Err(RunOutcome::Cancelled),
None => return Err(client_failure()),
}
}
checkpoint = super::messages::append_batches(
store,
prepared,
client,
cancellation,
checkpoint,
pending_insertions,
)
.await?
.0;
Ok(checkpoint)
}
async fn send(client: &RunPort, event: RunEvent) -> std::result::Result<(), RunOutcome> {
client
.events
.send(event)
.await
.map_err(|_| client_failure())
}
fn failed(error: crate::Error) -> RunOutcome {
RunOutcome::Failed(error.into())
}
fn client_failure() -> RunOutcome {
RunOutcome::Failed(RunFailure::Client("client event channel closed".into()))
}