use std::collections::{BTreeMap, BTreeSet};
use serde_json::Value;
use crate::control::{ConfirmDecision, ConfirmIntent};
use crate::events::{Event, EventKind};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PendingCall {
pub call_id: String,
pub tool: String,
pub arguments: Value,
pub call_seq: u64,
pub requested_at_ms: u64,
}
#[must_use]
pub fn pending_calls(events: &[Event]) -> Vec<PendingCall> {
let mut calls: Vec<PendingCall> = Vec::new();
let mut answered: BTreeSet<String> = BTreeSet::new();
for ev in events {
match &ev.kind {
EventKind::ToolCall => {
if let Some(call) = ask_call(ev) {
calls.push(call);
}
}
EventKind::ToolResult => {
if let Some(id) = ev.bytes.pointer("/content/call_id").and_then(Value::as_str) {
answered.insert(id.to_owned());
}
}
_ => {}
}
}
calls.retain(|c| !answered.contains(&c.call_id));
calls
}
fn ask_call(ev: &Event) -> Option<PendingCall> {
let evaluated = ev
.bytes
.pointer("/permission/evaluated")
.and_then(Value::as_str)?;
if evaluated != "ask" {
return None;
}
let call_id = ev
.bytes
.pointer("/content/id")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())?
.to_owned();
let tool = ev
.bytes
.pointer("/content/name")
.and_then(Value::as_str)
.filter(|s| !s.is_empty())?
.to_owned();
let arguments = ev
.bytes
.pointer("/content/arguments")
.cloned()
.unwrap_or(Value::Null);
Some(PendingCall {
call_id,
tool,
arguments,
call_seq: ev.seq,
requested_at_ms: ev.ts,
})
}
#[must_use]
pub fn confirmations(events: &[Event]) -> BTreeMap<String, ConfirmIntent> {
let mut out = BTreeMap::new();
for ev in events {
if ev.kind != EventKind::ControlConfirm {
continue;
}
if let Some(intent) = ConfirmIntent::from_event_payload(&ev.bytes) {
out.entry(intent.call_id.clone()).or_insert(intent);
}
}
out
}
#[must_use]
pub fn confirmable(
pending: &[PendingCall],
decisions: &BTreeMap<String, ConfirmIntent>,
) -> Vec<(PendingCall, ConfirmIntent)> {
let mut out = Vec::new();
for call in pending {
match decisions.get(&call.call_id) {
Some(decision) => out.push((call.clone(), decision.clone())),
None => break,
}
}
out
}
#[must_use]
pub fn is_expired(call: &PendingCall, ttl_ms: u64, now_ms: u64) -> bool {
ttl_ms > 0 && now_ms.saturating_sub(call.requested_at_ms) > ttl_ms
}
#[must_use]
pub fn effective_decision(
call: &PendingCall,
ttl_ms: u64,
now_ms: u64,
intent: &ConfirmIntent,
) -> ConfirmIntent {
if is_expired(call, ttl_ms, now_ms) {
ConfirmIntent {
decision: ConfirmDecision::Reject,
expired: true,
..intent.clone()
}
} else {
intent.clone()
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use uuid::Uuid;
use super::{confirmable, confirmations, effective_decision, is_expired, pending_calls};
use crate::control::{ConfirmDecision, ConfirmIntent};
use crate::events::{EndReason, Event, EventKind, SCHEMA_VERSION};
use crate::model::{Epoch, SessionId};
fn ev(seq: u64, ts: u64, kind: EventKind, bytes: serde_json::Value) -> Event {
Event {
seq,
session: SessionId(Uuid::nil()),
epoch: Epoch(1),
ts,
kind,
bytes,
version: SCHEMA_VERSION,
}
}
fn ask(seq: u64, ts: u64, id: &str, tool: &str, args: serde_json::Value) -> Event {
ev(
seq,
ts,
EventKind::ToolCall,
json!({
"role": "assistant",
"content": {"id": id, "name": tool, "arguments": args},
"permission": {"evaluated": "ask", "policy": "configured", "matched": tool}
}),
)
}
fn allow(seq: u64, ts: u64, id: &str) -> Event {
ev(
seq,
ts,
EventKind::ToolCall,
json!({
"role": "assistant",
"content": {"id": id, "name": "read", "arguments": {}},
"permission": {"evaluated": "allow", "policy": "configured", "matched": "read"}
}),
)
}
fn result(seq: u64, ts: u64, id: &str) -> Event {
ev(
seq,
ts,
EventKind::ToolResult,
json!({"role": "tool", "content": {"call_id": id, "output": {}, "is_error": false}}),
)
}
fn decision(seq: u64, id: &str, d: ConfirmDecision) -> Event {
let intent = ConfirmIntent {
call_id: id.into(),
decision: d,
reason: None,
requested_by: Some("alice".into()),
answered_at_ms: 50,
expired: false,
};
ev(seq, 50, EventKind::ControlConfirm, intent.event_payload())
}
#[test]
fn pending_is_call_ordered_and_excludes_answered_and_allowed_calls() {
let events = vec![
ask(1, 10, "a", "send_email", json!({"to": "x"})),
allow(2, 11, "b"),
result(3, 12, "b"),
ask(4, 13, "c", "delete", json!({})),
];
let pending = pending_calls(&events);
assert_eq!(
pending
.iter()
.map(|p| p.call_id.as_str())
.collect::<Vec<_>>(),
vec!["a", "c"]
);
assert_eq!(pending[0].tool, "send_email");
assert_eq!(pending[0].arguments, json!({"to": "x"}));
assert_eq!(pending[0].requested_at_ms, 10);
assert_eq!(pending[0].call_seq, 1);
}
#[test]
fn an_unanswered_call_is_legal_and_stays_pending_across_an_end_write() {
let events = vec![
ask(1, 10, "a", "send_email", json!({})),
ev(
2,
11,
EventKind::SessionEnded {
reason: EndReason::AwaitingInput,
},
json!({}),
),
];
assert_eq!(pending_calls(&events).len(), 1);
}
#[test]
fn a_result_answers_exactly_its_own_call() {
let events = vec![
ask(1, 10, "a", "t", json!({})),
ask(2, 11, "b", "t", json!({})),
result(3, 12, "a"),
];
let pending = pending_calls(&events);
assert_eq!(pending.len(), 1);
assert_eq!(pending[0].call_id, "b");
}
#[test]
fn malformed_payloads_are_not_asks() {
let events = vec![
ev(1, 10, EventKind::ToolCall, json!({"role": "assistant"})),
ev(
2,
11,
EventKind::ToolCall,
json!({"role": "assistant", "content": {"id": "x", "name": "t"},
"permission": {"evaluated": "maybe"}}),
),
ev(
3,
12,
EventKind::ToolCall,
json!({"role": "assistant", "content": {"id": "", "name": "t"},
"permission": {"evaluated": "ask"}}),
),
];
assert!(pending_calls(&events).is_empty());
}
#[test]
fn confirmable_is_the_call_ordered_prefix() {
let events = vec![
ask(1, 10, "a", "t", json!({})),
ask(2, 11, "b", "t", json!({})),
decision(3, "b", ConfirmDecision::Approve),
];
let pending = pending_calls(&events);
let decisions = confirmations(&events);
assert!(confirmable(&pending, &decisions).is_empty());
let events2 = vec![
ask(1, 10, "a", "t", json!({})),
decision(2, "a", ConfirmDecision::Reject),
];
let pending2 = pending_calls(&events2);
let decisions2 = confirmations(&events2);
let ready = confirmable(&pending2, &decisions2);
assert_eq!(ready.len(), 1);
assert_eq!(ready[0].0.call_id, "a");
assert_eq!(ready[0].1.decision, ConfirmDecision::Reject);
}
#[test]
fn ttl_overlay_and_effective_decision() {
let call = pending_calls(&[ask(1, 10_000, "a", "t", json!({}))])
.into_iter()
.next()
.unwrap();
assert!(!is_expired(&call, 0, 99_999));
assert!(!is_expired(&call, 5_000, 14_999));
assert!(is_expired(&call, 5_000, 15_001));
let approve = ConfirmIntent {
call_id: "a".into(),
decision: ConfirmDecision::Approve,
reason: None,
requested_by: None,
answered_at_ms: 0,
expired: false,
};
let applied = effective_decision(&call, 5_000, 20_000, &approve);
assert_eq!(applied.decision, ConfirmDecision::Reject);
assert!(applied.expired);
let kept = effective_decision(&call, 0, 20_000, &approve);
assert_eq!(kept.decision, ConfirmDecision::Approve);
assert!(!kept.expired);
}
}