use std::time::Instant;
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use tracing::warn;
use crate::config::ParkedTextPolicy;
use crate::error::TerminationReason;
use crate::flow_source::FlowInvokeOutcome;
use crate::state::{
ChatMessage, ConversationState, MAX_SIDE_TURNS, PENDING_TOOL_MAX_AGE_SECS, PendingToolCall,
ToolCallRecord,
};
use crate::tenant::TenantContext;
use crate::tool_session::ToolCatalogs;
use crate::{AgentRuntime, AgentStep, StepObserver};
pub(crate) const BEHIND_SUSPENSION_ERROR: &str = "another step is waiting for the user";
pub(crate) const AWAITING_PLACEHOLDER: &str = "awaiting_user_input";
fn latest_assistant_with(messages: &[ChatMessage], call_id: &str) -> Option<usize> {
messages.iter().rposition(|m| {
matches!(m, ChatMessage::Assistant { tool_calls, .. }
if tool_calls.iter().any(|c| c.call_id == call_id))
})
}
fn tool_run_end(messages: &[ChatMessage], at: usize) -> usize {
let mut end = at + 1;
while matches!(messages.get(end), Some(ChatMessage::Tool { .. })) {
end += 1;
}
end
}
pub(crate) fn patch_tool_result(state: &mut ConversationState, call_id: &str, content: Value) {
let Some(at) = latest_assistant_with(&state.messages, call_id) else {
return;
};
let end = tool_run_end(&state.messages, at);
let existing = state.messages[at + 1..end]
.iter_mut()
.find_map(|m| match m {
ChatMessage::Tool {
call_id: id,
content,
} if id == call_id => Some(content),
_ => None,
});
match existing {
Some(slot) => *slot = content,
None => state.messages.insert(
end,
ChatMessage::Tool {
call_id: call_id.to_string(),
content,
},
),
}
}
pub(crate) struct Resume {
pub(crate) pending: PendingToolCall,
pub(crate) payload: Value,
}
pub(crate) enum Taken {
Nothing,
Resume(Resume),
Cancelled(AgentStep),
Side,
}
pub(crate) const RESUME_AFTER_SIDE_TURNS_NOTE: &str = "The form step the user was asked to \
complete has now finished; its result is the tool result in the conversation. \
Reply about that result, not about the earlier side questions.";
pub(crate) const SIDE_TURN_NOTE: &str = "A form step is waiting for the user to \
fill it in. Do not start that step again. Answer the user's question, then \
mention that the form can be continued.";
pub(crate) fn take_pending(
state: &mut ConversationState,
resume_payload: Option<Value>,
now: DateTime<Utc>,
observer: &dyn StepObserver,
policy: ParkedTextPolicy,
) -> Taken {
let Some(pending) = state.pending_tool.as_ref() else {
return Taken::Nothing;
};
if policy == ParkedTextPolicy::SideTurn
&& resume_payload.is_none()
&& side_turn_allowed(pending, now)
&& ensure_placeholder(state)
{
if let Some(pending) = state.pending_tool.as_mut() {
begin_side_turn(pending, now);
}
return Taken::Side;
}
let Some(pending) = state.pending_tool.take() else {
return Taken::Nothing;
};
let reason = if pending.is_expired(now) {
"the step waiting for the user expired before they answered"
} else if let Some(payload) = resume_payload {
return Taken::Resume(Resume { pending, payload });
} else {
"the user sent a message instead of completing this step"
};
let result = json!({ "status": "cancelled", "reason": reason });
observer.on_tool_result(&pending.tool_name, &pending.call_id, &result);
patch_tool_result(state, &pending.call_id, result.clone());
Taken::Cancelled(AgentStep::ToolCall {
name: pending.tool_name,
call_id: pending.call_id,
args: pending.args,
result,
duration_ms: 0,
})
}
fn side_turn_allowed(pending: &PendingToolCall, now: DateTime<Utc>) -> bool {
let within_age = pending
.parked_at
.is_none_or(|at| now < at + chrono::Duration::seconds(PENDING_TOOL_MAX_AGE_SECS));
!pending.is_expired(now)
&& within_age
&& pending.side_turns < MAX_SIDE_TURNS
&& pending.presentation.is_some()
}
fn begin_side_turn(pending: &mut PendingToolCall, now: DateTime<Utc>) {
pending.side_turns += 1;
let idle = PendingToolCall::expiry_from(now);
pending.expires_at = match pending.parked_at {
Some(at) => idle.min(at + chrono::Duration::seconds(PENDING_TOOL_MAX_AGE_SECS)),
None => idle,
};
}
fn ensure_placeholder(state: &mut ConversationState) -> bool {
let Some(call_id) = state.pending_tool.as_ref().map(|p| p.call_id.clone()) else {
return false;
};
let Some(at) = latest_assistant_with(&state.messages, &call_id) else {
return false;
};
let end = tool_run_end(&state.messages, at);
if state.messages[at + 1..end]
.iter()
.any(|m| matches!(m, ChatMessage::Tool { call_id: id, .. } if *id == call_id))
{
return true;
}
state.messages.insert(
at + 1,
ChatMessage::Tool {
call_id,
content: json!({ "status": AWAITING_PLACEHOLDER }),
},
);
true
}
pub(crate) fn finish_side_turn(
state: &mut ConversationState,
terminated_by: &mut TerminationReason,
suspension: &mut Option<Value>,
) -> bool {
if matches!(terminated_by, TerminationReason::ConversationEnded) {
if let Some(pending) = state.pending_tool.take() {
patch_tool_result(
state,
&pending.call_id,
json!({ "status": "cancelled", "reason": "the conversation ended" }),
);
}
return false;
}
let Some(card) = state
.pending_tool
.as_ref()
.and_then(|p| p.presentation.clone())
else {
return false;
};
*terminated_by = TerminationReason::AwaitingToolInput;
*suspension = Some(card);
true
}
pub(crate) fn last_user_text(state: &ConversationState) -> String {
state
.messages
.iter()
.rev()
.find_map(|m| match m {
ChatMessage::User { content } => Some(content.clone()),
_ => None,
})
.unwrap_or_default()
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn resume_pending(
runtime: &AgentRuntime,
lock: &crate::state::SessionLock,
tenant: &TenantContext,
session_id: &str,
catalogs: &ToolCatalogs,
state: &mut ConversationState,
trail: &mut Vec<AgentStep>,
observer: &dyn StepObserver,
resume: Resume,
) -> Option<Value> {
let Resume {
mut pending,
payload,
} = resume;
let t0 = Instant::now();
let outcome = match catalogs.flows.as_deref() {
Some(cat) => {
let binding = if pending.extension_id.is_empty() {
format!("flow:{}", pending.flow_ref)
} else {
pending.extension_id.clone()
};
crate::run_trace::under_binding(
&binding,
crate::lock_keepalive::keep_alive(
lock,
crate::lock_keepalive::LOCK_KEEPALIVE_INTERVAL,
crate::tool_call_frame::within(
crate::tool_call_frame::ToolCallFrame::new(
Some(session_id),
&pending.call_id,
)
.with_caller(tenant.caller_or_anonymous()),
cat.resume(&pending.flow_ref, pending.flow_snapshot.clone(), payload),
),
),
)
.await
}
None => FlowInvokeOutcome::Completed(json!({
"error": format!("unknown flow tool '{}'", pending.flow_ref)
})),
};
match outcome {
FlowInvokeOutcome::Completed(result) => {
let duration_ms = t0.elapsed().as_millis() as u64;
observer.on_tool_result(&pending.tool_name, &pending.call_id, &result);
if let Err(e) = runtime
.ledger
.record(tenant, session_id, &pending.call_id, result.clone())
.await
{
warn!(error = %e, "ledger record failed; continuing");
}
patch_tool_result(state, &pending.call_id, result.clone());
trail.push(AgentStep::ToolCall {
name: pending.tool_name,
call_id: pending.call_id,
args: pending.args,
result,
duration_ms,
});
None
}
FlowInvokeOutcome::Waiting {
snapshot,
presentation,
} => {
pending.flow_snapshot = snapshot;
pending.expires_at = PendingToolCall::expiry_from(Utc::now());
pending.presentation = Some(presentation.clone());
pending.side_turns = 0;
state.pending_tool = Some(pending);
Some(presentation)
}
}
}
pub(crate) fn refuse_behind_suspension(
state: &mut ConversationState,
trail: &mut Vec<AgentStep>,
observer: &dyn StepObserver,
call: &ToolCallRecord,
) {
let result = json!({ "error": BEHIND_SUSPENSION_ERROR });
observer.on_tool_call(&call.tool_name, &call.call_id, &call.args);
observer.on_tool_failed(&call.tool_name, &call.call_id, &result);
state.messages.push(ChatMessage::Tool {
call_id: call.call_id.clone(),
content: result.clone(),
});
trail.push(AgentStep::ToolCall {
name: call.tool_name.clone(),
call_id: call.call_id.clone(),
args: call.args.clone(),
result,
duration_ms: 0,
});
}
#[cfg(test)]
mod tests {
use super::*;
fn tool(id: &str, content: Value) -> ChatMessage {
ChatMessage::Tool {
call_id: id.into(),
content,
}
}
fn state_with(messages: Vec<ChatMessage>) -> ConversationState {
let mut s = ConversationState::empty(&TenantContext::new("a", "b"), "x");
s.messages = messages;
s
}
#[test]
fn patch_replaces_the_placeholder_in_place() {
let mut s = state_with(vec![
asst(&["c1"]),
tool("c1", json!({ "status": AWAITING_PLACEHOLDER })),
ChatMessage::User {
content: "q".into(),
},
]);
patch_tool_result(&mut s, "c1", json!({ "ok": true }));
assert_eq!(s.messages.len(), 3);
assert!(matches!(&s.messages[1],
ChatMessage::Tool { content, .. } if content == &json!({ "ok": true })));
}
fn asst(ids: &[&str]) -> ChatMessage {
ChatMessage::Assistant {
content: String::new(),
tool_calls: ids
.iter()
.map(|id| ToolCallRecord {
call_id: (*id).into(),
extension_id: "flow:form".into(),
tool_name: "form".into(),
args: json!({}),
})
.collect(),
}
}
#[test]
fn patch_adds_the_result_after_its_assistant_turn_when_there_is_no_placeholder() {
let mut s = state_with(vec![asst(&["c1"])]);
patch_tool_result(&mut s, "c1", json!({ "status": "cancelled" }));
assert_eq!(s.messages.len(), 2);
}
#[test]
fn patch_never_adds_an_orphan_when_the_assistant_turn_is_gone() {
let mut s = state_with(vec![]);
patch_tool_result(&mut s, "c1", json!({ "status": "cancelled" }));
assert!(s.messages.is_empty());
}
#[test]
fn patch_targets_the_latest_assistant_turn_when_a_call_id_is_reused() {
let old = json!({ "old": true });
let mut s = state_with(vec![
asst(&["c1"]),
tool("c1", old.clone()),
ChatMessage::User {
content: "next".into(),
},
asst(&["c1"]),
tool("c1", json!({ "status": AWAITING_PLACEHOLDER })),
]);
patch_tool_result(&mut s, "c1", json!({ "new": true }));
assert!(matches!(&s.messages[1], ChatMessage::Tool { content, .. } if content == &old));
assert!(matches!(&s.messages[4],
ChatMessage::Tool { content, .. } if content == &json!({ "new": true })));
}
#[test]
fn ensure_placeholder_answers_the_latest_assistant_turn_when_a_call_id_is_reused() {
let mut s = state_with(vec![
asst(&["c1"]),
tool("c1", json!({ "old": true })),
ChatMessage::User {
content: "next".into(),
},
asst(&["c1"]),
]);
s.pending_tool = Some(crate::state::PendingToolCall {
call_id: "c1".into(),
tool_name: "form".into(),
extension_id: "flow:form".into(),
args: json!({}),
flow_ref: "form".into(),
flow_snapshot: json!({}),
iterations_used: 0,
expires_at: Utc::now() + chrono::Duration::hours(1),
presentation: Some(json!({})),
parked_at: None,
side_turns: 0,
});
assert!(ensure_placeholder(&mut s));
assert_eq!(s.messages.len(), 5);
assert!(matches!(&s.messages[4], ChatMessage::Tool { .. }));
}
}