This commit is contained in:
leookun committed 2026-08-29 22:05:04 +08:00
1 parent 279e6bb07c
commit d200b3791d
204 files changed
+710 -440

No files matched your search

File diff suppressed because it is too large. Load diff
-10
View File
@@ -1,10 +0,0 @@
mod engine;
mod model_cycle;
mod port;
mod runtime;
mod tool_round;
pub use engine::*;
pub use model_cycle::*;
pub use port::*;
pub use runtime::*;
-370
View File
@@ -1,370 +0,0 @@
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::{ClientEvent, 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<ClientEvent>,
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() => {
// An injected runtime message cancels only this provider cycle. Close any
// presentation blocks that were opened by the old cycle before the engine
// starts the replacement cycle, otherwise Cursor appends the new deltas to
// the old Thinking/Text block and makes it look as if cancellation failed.
if text_open {
let _ = send(client, ClientEvent::TextEnd).await;
}
if let Some(started) = thinking_started.take() {
let _ = send(
client,
ClientEvent::ThinkingEnd {
duration: started.elapsed(),
},
)
.await;
}
return Err(failure(RunFailure::Client("run was cancelled".into()), text, reasoning, usage));
}
};
let Some(next) = next else {
if cancellation.is_cancelled() {
if text_open {
let _ = send(client, ClientEvent::TextEnd).await;
}
if let Some(started) = thinking_started.take() {
let _ = send(
client,
ClientEvent::ThinkingEnd {
duration: started.elapsed(),
},
)
.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, ClientEvent::TextStart).await
}
}
ModelEvent::TextDelta(delta) => {
if !text_open {
Err("provider emitted TextDelta before TextStart")
} else {
text.push_str(&delta);
send(client, ClientEvent::TextDelta(delta)).await
}
}
ModelEvent::TextEnd => {
if !text_open {
Err("provider emitted TextEnd before TextStart")
} else {
text_open = false;
send(client, ClientEvent::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, ClientEvent::ThinkingStart).await
}
}
ModelEvent::ThinkingDelta(delta) => {
if thinking_started.is_none() {
Err("provider emitted ThinkingDelta before ThinkingStart")
} else {
reasoning.push_str(&delta);
send(client, ClientEvent::ThinkingDelta(delta)).await
}
}
ModelEvent::ThinkingEnd => {
if let Some(started) = thinking_started.take() {
send(
client,
ClientEvent::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,
ClientEvent::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, ClientEvent::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, ClientEvent::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, ClientEvent::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<ClientEvent>,
event: ClientEvent,
) -> std::result::Result<(), &'static str> {
client
.send(event)
.await
.map_err(|_| "client event channel closed")
}
fn failure(
failure: RunFailure,
partial_text: String,
partial_reasoning: String,
usage: Option<Usage>,
) -> ModelCycleFailure {
ModelCycleFailure {
failure,
partial_text,
partial_reasoning,
usage,
}
}
-125
View File
@@ -1,125 +0,0 @@
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use crate::model::{
CanonicalMessage, RevisionId, RuntimeEvent, ToolCall, ToolResult, ToolRoundId, Usage,
};
use super::RunOutcome;
#[derive(Debug)]
pub struct MessageInsertion {
pub messages: Vec<CanonicalMessage>,
pub delivered: oneshot::Sender<()>,
}
#[derive(Debug)]
pub enum ClientCommand {
ToolResult(ToolResult),
InterruptWithMessage(CanonicalMessage),
RuntimeEvent(RuntimeEvent),
InsertMessages(MessageInsertion),
ClientClosed { error: String },
Cancel,
}
#[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 StateCommitted {
pub revision_id: RevisionId,
pub tool_round_version: u64,
pub cause: CommitCause,
pub barrier: CommitBarrier,
}
#[derive(Debug)]
pub enum ClientEvent {
AutoCompactionStarted,
AutoCompactionCompleted,
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>,
},
StateCommitted(StateCommitted),
Ended(RunOutcome),
}
pub struct ClientPort {
pub commands: mpsc::Receiver<ClientCommand>,
pub events: mpsc::Sender<ClientEvent>,
}
pub struct ClientSession {
pub commands: mpsc::Sender<ClientCommand>,
pub events: mpsc::Receiver<ClientEvent>,
}
pub fn session(capacity: usize) -> (ClientPort, ClientSession) {
let (commands_tx, commands_rx) = mpsc::channel(capacity);
let (events_tx, events_rx) = mpsc::channel(capacity);
(
ClientPort {
commands: commands_rx,
events: events_tx,
},
ClientSession {
commands: commands_tx,
events: events_rx,
},
)
}
-183
View File
@@ -1,183 +0,0 @@
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;
use tokio_util::sync::CancellationToken;
use crate::{
model::{CanonicalMessage, ConversationId, PreparedRun, RunId},
provider::Provider,
store::Store,
};
use super::{ClientCommand, ClientPort, MessageInsertion, RunEngine};
#[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, Default)]
pub struct RunRegistry {
active: Arc<Mutex<HashMap<ConversationId, ActiveRun>>>,
}
struct ActiveRun {
run_id: RunId,
cancellation: CancellationToken,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
}
impl RunRegistry {
pub async fn activate(
&self,
conversation_id: ConversationId,
run_id: RunId,
cancellation: CancellationToken,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
) {
let previous = self.active.lock().await.insert(
conversation_id,
ActiveRun {
run_id: run_id.clone(),
cancellation,
commands,
},
);
if let Some(previous) = previous.filter(|previous| previous.run_id != run_id) {
previous.cancellation.cancel();
}
}
pub async fn insert_messages(
&self,
conversation_id: &ConversationId,
messages: Vec<CanonicalMessage>,
) -> bool {
if messages.is_empty() {
return true;
}
let commands = self
.active
.lock()
.await
.get(conversation_id)
.map(|run| run.commands.clone());
let Some(commands) = commands else {
return false;
};
let (delivered, delivery) = tokio::sync::oneshot::channel();
if commands
.send(ClientCommand::InsertMessages(MessageInsertion {
messages,
delivered,
}))
.await
.is_err()
{
return false;
}
delivery.await.is_ok()
}
pub async fn release(&self, conversation_id: &ConversationId, run_id: &RunId) {
let mut active = self.active.lock().await;
if active
.get(conversation_id)
.is_some_and(|current| &current.run_id == run_id)
{
active.remove(conversation_id);
}
}
pub async fn shutdown(&self) {
let active = std::mem::take(&mut *self.active.lock().await);
for run in active.into_values() {
run.cancellation.cancel();
}
}
}
#[derive(Clone)]
pub struct RunActor {
store: Store,
provider: Arc<dyn Provider>,
registry: RunRegistry,
}
impl RunActor {
pub fn new(store: Store, provider: Arc<dyn Provider>, registry: RunRegistry) -> Self {
Self {
store,
provider,
registry,
}
}
pub async fn spawn(
&self,
prepared: PreparedRun,
client: ClientPort,
commands: tokio::sync::mpsc::Sender<ClientCommand>,
cancellation: CancellationToken,
) -> tokio::task::JoinHandle<RunOutcome> {
let run_id = prepared.run_id.clone();
let conversation_id = prepared.conversation_id.clone();
self.registry
.activate(
conversation_id.clone(),
run_id.clone(),
cancellation.clone(),
commands,
)
.await;
let actor = self.clone();
tokio::spawn(async move {
let outcome = RunEngine::new(actor.store, actor.provider)
.run(prepared, client, cancellation)
.await;
actor.registry.release(&conversation_id, &run_id).await;
outcome
})
}
}
-262
View File
@@ -1,262 +0,0 @@
use std::collections::HashSet;
use tokio_util::sync::CancellationToken;
use crate::{
model::{PreparedRun, RevisionId, ToolCall, ToolResult, ToolRoundAssistant, ToolRoundId},
store::Store,
};
use super::{
ClientCommand, ClientEvent, ClientPort, CommitBarrier, CommitCause, MessageInsertion,
RunFailure, RunOutcome, StateCommitted,
};
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 ClientPort,
cancellation: &CancellationToken,
mut revision: RevisionId,
round: ToolRound,
insertions: Vec<MessageInsertion>,
) -> std::result::Result<RevisionId, RunOutcome> {
let ToolRound {
id: round_id,
assistant,
calls,
recovered_started_at_ms,
} = round;
store
.create_tool_round(
&round_id,
&prepared.run_id,
revision,
&assistant,
&calls,
recovered_started_at_ms,
)
.await
.map_err(failed)?;
tracing::info!(
round_id = %round_id,
revision_id = revision.0,
calls = calls.len(),
"tool round started"
);
send(
client,
ClientEvent::StateCommitted(StateCommitted {
revision_id: revision,
tool_round_version: 0,
cause: CommitCause::ToolRoundStarted(round_id.clone()),
barrier: CommitBarrier::None,
}),
)
.await?;
send(
client,
ClientEvent::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_runtime_messages = insertions
.into_iter()
.map(PendingRuntimeMessage::Insertion)
.collect::<Vec<_>>();
while remaining > 0 {
let command = tokio::select! {
_ = cancellation.cancelled() => return Err(RunOutcome::Cancelled),
command = client.commands.recv() => command,
};
match command {
Some(ClientCommand::ToolResult(result)) => {
let call_id = result.call_id.clone();
let committed = store
.commit_tool_result(
&prepared.conversation_id,
&prepared.run_id,
&round_id,
&result,
)
.await
.map_err(failed)?;
revision = committed.revision_id;
completed_call_ids.insert(call_id.clone());
tracing::info!(
round_id = %round_id,
call_id,
revision_id = revision.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,
ClientEvent::StateCommitted(StateCommitted {
revision_id: revision,
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(ClientCommand::RuntimeEvent(event)) => {
pending_runtime_messages.push(PendingRuntimeMessage::Message(event.into_message()));
}
Some(ClientCommand::InterruptWithMessage(message)) => {
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)?;
revision = committed.revision_id;
let (barrier, ready) = if committed.settled {
let (barrier, ready) = CommitBarrier::before_continue();
(barrier, Some(ready))
} else {
(CommitBarrier::None, None)
};
send(
client,
ClientEvent::StateCommitted(StateCommitted {
revision_id: revision,
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?;
}
}
for pending in pending_runtime_messages {
revision =
append_pending(store, prepared, client, cancellation, revision, pending)
.await?;
}
revision = super::engine::append_runtime_message(
store,
prepared,
client,
cancellation,
revision,
message,
)
.await?
.0;
return Ok(revision);
}
Some(ClientCommand::InsertMessages(insertion)) => {
pending_runtime_messages.push(PendingRuntimeMessage::Insertion(insertion))
}
Some(ClientCommand::Cancel) => return Err(RunOutcome::Cancelled),
Some(ClientCommand::ClientClosed { error }) => {
return Err(RunOutcome::Failed(RunFailure::Client(error)));
}
None => return Err(client_failure()),
}
}
for pending in pending_runtime_messages {
revision = append_pending(store, prepared, client, cancellation, revision, pending).await?;
}
Ok(revision)
}
enum PendingRuntimeMessage {
Message(crate::model::CanonicalMessage),
Insertion(MessageInsertion),
}
async fn append_pending(
store: &Store,
prepared: &PreparedRun,
client: &mut ClientPort,
cancellation: &CancellationToken,
revision: RevisionId,
pending: PendingRuntimeMessage,
) -> std::result::Result<RevisionId, RunOutcome> {
match pending {
PendingRuntimeMessage::Message(message) => Ok(super::engine::append_runtime_message(
store,
prepared,
client,
cancellation,
revision,
message,
)
.await?
.0),
PendingRuntimeMessage::Insertion(insertion) => Ok(super::engine::append_insertions(
store,
prepared,
client,
cancellation,
revision,
vec![insertion],
)
.await?
.0),
}
}
async fn send(client: &ClientPort, event: ClientEvent) -> 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()))
}