use std::collections::{BTreeMap, VecDeque};
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use futures::StreamExt;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use kian_core::model::{AgentDef, Budgets, SlotName, SlotSpec};
use kian_core::seams::{
ModelChunk, ModelProvider, ModelRequest, PolicyRule, ProviderError, RecoveryPolicySource,
ToolCall, ToolError, ToolProvider, ToolResult,
};
use serde_json::{Value, json};
pub fn agent_def() -> AgentDef {
AgentDef {
id: "react-test".into(),
version: 1,
model_slots: BTreeMap::from([(
SlotName("main".into()),
SlotSpec {
provider: "mock".into(),
model: "mock-model".into(),
fallback: Vec::new(),
profile: None,
},
)]),
tools: vec!["fs_read".into(), "fs_write".into(), "exec".into()],
budgets: Budgets {
tokens: None,
wall_clock_ms: None,
},
}
}
pub struct NoopTools;
impl ToolProvider for NoopTools {
fn schemas(&self) -> Vec<kian_core::seams::ToolSchema> {
Vec::new()
}
fn invoke(&self, _call: ToolCall) -> BoxFuture<'static, Result<ToolResult, ToolError>> {
Box::pin(async { Err(ToolError::InvalidCall("noop".into())) })
}
}
pub struct NoopPolicy;
impl RecoveryPolicySource for NoopPolicy {
fn table(&self) -> Vec<PolicyRule> {
Vec::new()
}
}
pub struct TablePolicy(pub Vec<PolicyRule>);
impl RecoveryPolicySource for TablePolicy {
fn table(&self) -> Vec<PolicyRule> {
self.0.clone()
}
}
pub type ScriptedChunks = Vec<Result<ModelChunk, ProviderError>>;
type RequestHook = Arc<dyn Fn(usize) -> BoxFuture<'static, ()> + Send + Sync>;
pub struct ScriptedProvider {
turns: Mutex<VecDeque<ScriptedChunks>>,
requests: Mutex<Vec<Value>>,
hook: Mutex<Option<RequestHook>>,
call_count: AtomicUsize,
}
impl ScriptedProvider {
pub fn new(turns: Vec<ScriptedChunks>) -> Self {
Self {
turns: Mutex::new(turns.into()),
requests: Mutex::new(Vec::new()),
hook: Mutex::new(None),
call_count: AtomicUsize::new(0),
}
}
pub fn on_request<F, Fut>(&self, hook: F)
where
F: Fn(usize) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
*self.hook.lock().unwrap() = Some(Arc::new(move |n| Box::pin(hook(n))));
}
pub fn requests(&self) -> Vec<Value> {
self.requests.lock().unwrap().clone()
}
}
impl ModelProvider for ScriptedProvider {
fn complete(&self, req: ModelRequest) -> BoxStream<'static, Result<ModelChunk, ProviderError>> {
self.requests.lock().unwrap().push(req.body.clone());
let n = self.call_count.fetch_add(1, Ordering::SeqCst) + 1;
let hook = self.hook.lock().unwrap().clone();
let turn = self
.turns
.lock()
.unwrap()
.pop_front()
.unwrap_or_default();
let state = (hook, n, turn.into_iter(), false);
futures::stream::unfold(state, |(hook, n, mut iter, mut hook_done)| async move {
if !hook_done {
hook_done = true;
if let Some(hook) = &hook {
hook(n).await;
}
}
iter.next().map(|item| (item, (hook, n, iter, hook_done)))
})
.boxed()
}
}
pub fn text_chunk(text: &str) -> Result<ModelChunk, ProviderError> {
Ok(ModelChunk::new(json!({"content": text})))
}
pub fn usage_chunk(usage: Value) -> Result<ModelChunk, ProviderError> {
Ok(ModelChunk::with_usage(Value::Null, usage))
}
pub fn tool_call_chunk(
id: &str,
name: &str,
arguments: Value,
) -> Result<ModelChunk, ProviderError> {
Ok(ModelChunk::new(json!({"tool_calls": [{
"index": 0,
"id": id,
"function": {"name": name, "arguments": arguments.to_string()}
}]})))
}
pub struct RecordingPolicy {
pub rules: Vec<PolicyRule>,
pub consulted: AtomicBool,
}
impl RecordingPolicy {
pub fn with_empty_response_rule() -> Self {
Self {
rules: vec![PolicyRule {
class: "empty_response".into(),
action: kian_core::seams::RecoveryAction::InterruptAsk,
}],
consulted: AtomicBool::new(false),
}
}
}
impl RecoveryPolicySource for RecordingPolicy {
fn table(&self) -> Vec<PolicyRule> {
self.consulted.store(true, Ordering::SeqCst);
self.rules.clone()
}
}
pub struct HookTools {
pub hook: Arc<dyn Fn(ToolCall) -> BoxFuture<'static, ToolResult> + Send + Sync>,
}
impl HookTools {
pub fn new(
hook: Arc<dyn Fn(ToolCall) -> BoxFuture<'static, ToolResult> + Send + Sync>,
) -> Self {
Self { hook }
}
pub fn ok(output: Value) -> (Self, Arc<Mutex<Vec<ToolCall>>>) {
let seen = Arc::new(Mutex::new(Vec::new()));
let seen2 = Arc::clone(&seen);
let tools = Self::new(Arc::new(move |call| {
seen2.lock().unwrap().push(call.clone());
let output = output.clone();
Box::pin(async move {
let call_id = call.id;
ToolResult {
call_id,
output,
is_error: false,
redactions: Vec::new(),
}
})
}));
(tools, seen)
}
}
impl ToolProvider for HookTools {
fn schemas(&self) -> Vec<kian_core::seams::ToolSchema> {
Vec::new()
}
fn invoke(&self, call: ToolCall) -> BoxFuture<'static, Result<ToolResult, ToolError>> {
let fut = (self.hook)(call);
Box::pin(async move { Ok(fut.await) })
}
}