use std::collections::BTreeMap;
use std::sync::Arc;
use futures::stream::{BoxStream, StreamExt};
use kian_core::confirmation::{PendingCall, confirmable, confirmations, pending_calls};
use kian_core::context::{Message, derive_model_context};
use kian_core::control::{ConfirmDecision, ConfirmIntent};
use kian_core::events::{Event, EventKind};
use kian_core::model::{AgentDef, Permission, SlotName};
use kian_core::seams::{
LoopDriver, LoopOutcome, ModelRequest, ProviderError, RecoveryAction, RecoveryPolicySource,
ToolCall, ToolProvider, ToolResult,
};
use kian_llm::provider::{ChatMessage, WireFunctionCall, WireToolCall, build_chat_body};
use kian_llm::slots::{SessionSlots, SlotBinding, SlotError, SlotResolver};
use kian_llm::turn::{ProviderRegistry, SlotEventSink, complete_turn};
use kian_orchestrator::{DrainCtx, EngineError};
use serde_json::{Value, json};
use crate::evidence::{
BUILTIN_GATE_NAME, EvidenceGateConfig, evaluate_evidence_gate, verdict_payload,
};
pub const CLASS_EMPTY_RESPONSE: &str = "empty_response";
pub const DEFAULT_MAX_ITERATIONS: usize = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BudgetScope {
#[default]
Lifetime,
PerEpisode,
}
impl BudgetScope {
#[must_use]
fn used(self, lifetime_iteration: usize, episode_iterations: usize) -> usize {
match self {
Self::Lifetime => lifetime_iteration,
Self::PerEpisode => episode_iterations,
}
}
}
#[derive(Debug, Clone)]
pub struct ReActConfig {
pub slot: SlotName,
pub max_iterations: usize,
pub budget_scope: BudgetScope,
pub permissions: BTreeMap<String, Permission>,
}
impl Default for ReActConfig {
fn default() -> Self {
Self {
slot: SlotName("main".into()),
max_iterations: DEFAULT_MAX_ITERATIONS,
budget_scope: BudgetScope::Lifetime,
permissions: BTreeMap::new(),
}
}
}
struct Inner {
registry: Arc<ProviderRegistry>,
tools: Arc<dyn ToolProvider>,
policy: Arc<dyn RecoveryPolicySource>,
agent: AgentDef,
config: ReActConfig,
gate: EvidenceGateConfig,
hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
}
#[derive(Clone)]
pub struct ReActLoop(Arc<Inner>);
impl ReActLoop {
pub fn new(
agent: AgentDef,
registry: Arc<ProviderRegistry>,
tools: Arc<dyn ToolProvider>,
policy: Arc<dyn RecoveryPolicySource>,
) -> Self {
Self::with_config(agent, registry, tools, policy, ReActConfig::default())
}
pub fn with_config(
agent: AgentDef,
registry: Arc<ProviderRegistry>,
tools: Arc<dyn ToolProvider>,
policy: Arc<dyn RecoveryPolicySource>,
config: ReActConfig,
) -> Self {
Self::with_evidence_gate(
agent,
registry,
tools,
policy,
config,
EvidenceGateConfig::default(),
)
}
pub fn with_evidence_gate(
agent: AgentDef,
registry: Arc<ProviderRegistry>,
tools: Arc<dyn ToolProvider>,
policy: Arc<dyn RecoveryPolicySource>,
config: ReActConfig,
gate: EvidenceGateConfig,
) -> Self {
Self::with_hooks(agent, registry, tools, policy, config, gate, None)
}
pub fn with_hooks(
agent: AgentDef,
registry: Arc<ProviderRegistry>,
tools: Arc<dyn ToolProvider>,
policy: Arc<dyn RecoveryPolicySource>,
config: ReActConfig,
gate: EvidenceGateConfig,
hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
) -> Self {
Self::with_hooks_and_guard(agent, registry, tools, policy, config, gate, hooks, None)
}
#[allow(clippy::too_many_arguments)]
pub fn with_hooks_and_guard(
agent: AgentDef,
registry: Arc<ProviderRegistry>,
tools: Arc<dyn ToolProvider>,
policy: Arc<dyn RecoveryPolicySource>,
config: ReActConfig,
gate: EvidenceGateConfig,
hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
) -> Self {
Self(Arc::new(Inner {
registry,
tools,
policy,
agent,
config,
gate,
hooks,
set_guard,
}))
}
#[must_use]
pub fn config(&self) -> &ReActConfig {
&self.0.config
}
#[must_use]
pub fn evidence_gate(&self) -> &EvidenceGateConfig {
&self.0.gate
}
}
struct LoopState {
ctx: DrainCtx,
done: bool,
begun: bool,
drain_iterations: usize,
}
impl LoopDriver for ReActLoop {
type Ctx = DrainCtx;
fn drive(&self, ctx: DrainCtx) -> BoxStream<'static, LoopOutcome> {
let inner = Arc::clone(&self.0);
futures::stream::unfold(
LoopState {
ctx,
done: false,
begun: false,
drain_iterations: 0,
},
move |mut st| {
let inner = Arc::clone(&inner);
async move {
if st.done {
return None;
}
if !st.begun {
st.begun = true;
if let Some(guard) = inner.set_guard.as_ref() {
let worker = match st.ctx.events().await {
Ok(events) => kian_plugin::hooks::durable_worker_binding(
&events,
&st.ctx.session(),
)
.unwrap_or_default(),
Err(_) => String::new(),
};
guard.session_begin(kian_plugin::hooks::FrameInfo {
session: st.ctx.session(),
worker,
seq: 0,
epoch: Some(st.ctx.epoch().0),
});
}
}
let outcome = match inner.iteration(&st.ctx, &mut st.drain_iterations).await {
Flow::TurnDone => LoopOutcome::TurnDone,
Flow::Settled | Flow::Deferred => LoopOutcome::Settled,
Flow::Stopped(reason) => LoopOutcome::Stopped { reason },
Flow::Soft(reason) => LoopOutcome::SoftFailed { reason },
};
if !matches!(outcome, LoopOutcome::TurnDone) {
st.done = true;
}
Some((outcome, st))
}
},
)
.boxed()
}
}
enum Flow {
TurnDone,
Settled,
Deferred,
Stopped(String),
Soft(String),
}
enum TurnOutcome {
FinalAnswer,
ToolCalls(usize),
}
struct TurnResult {
result: Result<TurnOutcome, TurnError>,
usage: Option<Value>,
}
enum TurnError {
Soft { reason: String, audit: Value },
Fatal { error: LoopError, audit: Value },
}
#[derive(Debug, thiserror::Error)]
pub enum LoopError {
#[error("engine: {0}")]
Engine(#[from] EngineError),
#[error("context projection: {0}")]
Context(#[from] kian_core::context::ContextError),
#[error("slots: {0}")]
Slot(#[from] SlotError),
}
impl Inner {
async fn iteration(&self, ctx: &DrainCtx, drain_iterations: &mut usize) -> Flow {
let flow = match self.run_iteration(ctx, drain_iterations).await {
Ok(flow) => flow,
Err(e) => return Flow::Soft(format!("loop error: {e}")),
};
match flow {
Flow::Settled | Flow::Stopped(_) => self.apply_evidence_gate(ctx, flow).await,
other => other,
}
}
async fn apply_evidence_gate(&self, ctx: &DrainCtx, flow: Flow) -> Flow {
if !self.gate.enabled {
return flow;
}
let events = match ctx.events().await {
Ok(events) => events,
Err(e) => {
return Flow::Soft(format!("evidence gate: stream read failed: {e}"));
}
};
let verdict = evaluate_evidence_gate(BUILTIN_GATE_NAME, &self.gate.checks, &events);
let payload = verdict_payload(BUILTIN_GATE_NAME, &verdict);
if let Err(e) = ctx.append(EventKind::EvidenceVerdict, payload).await {
return Flow::Soft(format!("evidence gate: verdict append failed: {e}"));
}
if verdict.passed {
self.gate.counters.record_passed();
flow
} else {
self.gate.counters.record_failed();
if verdict.attempt < self.gate.max_retries {
Flow::TurnDone
} else {
Flow::Soft(format!(
"evidence gate `{BUILTIN_GATE_NAME}` failed after {} attempt(s)",
verdict.attempt + 1
))
}
}
}
async fn hook_frame(ctx: &DrainCtx, seq: u64) -> Option<kian_plugin::hooks::FrameInfo> {
let worker = match ctx.events().await {
Ok(events) => kian_plugin::hooks::durable_worker_binding(&events, &ctx.session())
.unwrap_or_default(),
Err(_) => String::new(),
};
Some(kian_plugin::hooks::FrameInfo {
session: ctx.session(),
worker,
seq,
epoch: Some(ctx.epoch().0),
})
}
#[allow(clippy::too_many_arguments)]
async fn observe_request(
&self,
ctx: &DrainCtx,
binding: &SlotBinding,
chat_len: usize,
schemas: &[kian_core::seams::ToolSchema],
iteration: usize,
body: &Value,
step_request_seq: u64,
) {
use kian_plugin::hooks::{RequestMeta, serialized, sha256_hex};
let Some(hooks) = self.hooks.as_ref() else {
return;
};
let bytes = serialized(body);
let meta = RequestMeta {
slot: self.config.slot.0.clone(),
provider: binding.target.provider.clone(),
model: binding.target.model.clone(),
iteration: iteration as u64,
request_bytes: bytes.len() as u64,
request_sha256: sha256_hex(&bytes),
message_count: chat_len as u64,
tool_names: schemas.iter().map(|s| s.name.clone()).collect(),
tool_schema_sha256: sha256_hex(&serialized(&Value::Array(
schemas
.iter()
.map(|s| serde_json::to_value(s).unwrap_or(Value::Null))
.collect(),
))),
timing: "pre_send".to_string(),
step_request_seq,
frame: Self::hook_frame(ctx, step_request_seq).await,
};
hooks.request(&meta).await;
}
#[allow(clippy::too_many_arguments)] async fn observe_response(
&self,
ctx: &DrainCtx,
iteration: usize,
seq: u64,
outcome: &str,
tool_calls: u64,
text_bytes: u64,
reasoning_bytes: u64,
usage: Option<&Value>,
error_audit: Option<&Value>,
) {
use kian_plugin::hooks::{ResponseView, TurnErrorAudit};
let Some(hooks) = self.hooks.as_ref() else {
return;
};
let error = error_audit.and_then(|audit| {
Some(TurnErrorAudit {
class: audit.get("class")?.as_str()?.to_string(),
action: audit.get("action")?.as_str()?.to_string(),
})
});
let view = ResponseView {
iteration: iteration as u64,
outcome: outcome.to_string(),
tool_calls,
text_bytes,
reasoning_bytes,
usage: usage.cloned().unwrap_or(Value::Null),
error,
timing: "settled".to_string(),
frame: Self::hook_frame(ctx, seq).await,
};
hooks.response(&view).await;
}
async fn consult_tool_pre(
&self,
ctx: &DrainCtx,
call: &ToolCall,
iteration: usize,
seq: u64,
decision: Option<PermissionDecision>,
) -> kian_plugin::hooks::ToolVerdict {
use kian_plugin::hooks::{ToolCallView, bounded_value, serialized, sha256_hex};
let Some(hooks) = self.hooks.as_ref() else {
return kian_plugin::hooks::ToolVerdict::Allow;
};
let bytes = serialized(&call.arguments);
let (arguments, arguments_truncated) = bounded_value(&call.arguments);
let view = ToolCallView {
call_id: call.id.clone(),
name: call.name.clone(),
iteration: iteration as u64,
arguments,
arguments_bytes: bytes.len() as u64,
arguments_sha256: sha256_hex(&bytes),
arguments_truncated,
permission: permission_view(call, decision),
surface: "react".to_string(),
frame: Self::hook_frame(ctx, seq).await,
};
hooks.tool_pre(&view).await
}
async fn observe_tool_post(&self, ctx: &DrainCtx, result: &ToolResult, name: &str, seq: u64) {
use kian_plugin::hooks::{RedactionReport, ToolPostView, serialized, sha256_hex};
let Some(hooks) = self.hooks.as_ref() else {
return;
};
let bytes = serialized(&result.output);
let view = ToolPostView {
call_id: result.call_id.clone(),
name: name.to_string(),
is_error: result.is_error,
output_bytes: bytes.len() as u64,
output_sha256: sha256_hex(&bytes),
redactions: result
.redactions
.iter()
.map(|r| RedactionReport {
kind: serde_json::to_value(r.kind)
.ok()
.and_then(|v| v.as_str().map(str::to_string))
.unwrap_or_default(),
name: r.name.clone(),
count: r.count,
})
.collect(),
frame: Self::hook_frame(ctx, seq).await,
};
hooks.tool_post(&view).await;
}
async fn observe_recover(&self, ctx: &DrainCtx, iteration: usize, seq: u64, audit: &Value) {
let Some(hooks) = self.hooks.as_ref() else {
return;
};
let view = kian_plugin::hooks::RecoveryView {
error_class: audit
.get("class")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string(),
action: audit
.get("action")
.and_then(Value::as_str)
.unwrap_or("none")
.to_string(),
iteration: iteration as u64,
frame: Self::hook_frame(ctx, seq).await,
};
hooks.recover(&view).await;
}
#[allow(clippy::too_many_arguments)] async fn observe_fatal(
&self,
ctx: &DrainCtx,
iteration: usize,
seq: u64,
audit: &Value,
text_bytes: u64,
reasoning_bytes: u64,
usage: Option<&Value>,
) {
self.observe_recover(ctx, iteration, seq, audit).await;
self.observe_response(
ctx,
iteration,
seq,
"error",
0,
text_bytes,
reasoning_bytes,
usage,
Some(audit),
)
.await;
}
async fn run_iteration(
&self,
ctx: &DrainCtx,
drain_iterations: &mut usize,
) -> Result<Flow, LoopError> {
let taken = ctx.take_eligible_inputs().await?;
let mut events = ctx.events().await?;
let mut pending = pending_calls(&events);
if !pending.is_empty() {
let decisions = confirmations(&events);
for (call, decision) in confirmable(&pending, &decisions) {
self.apply_confirmation(ctx, &call, &decision).await?;
}
events = ctx.events().await?;
pending = pending_calls(&events);
if !pending.is_empty() {
tracing::debug!(
session = %ctx.session().0,
pending = pending.len(),
"awaiting confirmation: settling without a provider call"
);
return Ok(Flow::Deferred);
}
}
let binding = self.binding_for(ctx, &mut events).await?;
let messages = derive_model_context(&events)?;
if resident_empty_batch(
self.config.budget_scope,
taken.is_empty(),
messages.last().map(|m| m.role.as_str()),
) {
tracing::debug!(
session = %ctx.session().0,
"resident empty batch: settling without a provider call (ADR-025)"
);
return Ok(Flow::Settled);
}
let iteration = events
.iter()
.filter(|ev| matches!(ev.kind, EventKind::TurnStart))
.count();
let used = self.config.budget_scope.used(iteration, *drain_iterations);
if used >= self.config.max_iterations {
let reason = match self.config.budget_scope {
BudgetScope::Lifetime => {
format!("iteration budget exhausted after {iteration} turns")
}
BudgetScope::PerEpisode => format!(
"{} after {used} turns",
kian_core::seams::EPISODE_BUDGET_STOP_REASON_PREFIX
),
};
return Ok(Flow::Stopped(reason));
}
if self.config.budget_scope == BudgetScope::PerEpisode {
*drain_iterations += 1;
}
ctx.begin_turn_with(json!({"iteration": iteration})).await?;
let turn = self
.provider_turn(ctx, &binding, &messages, iteration)
.await;
let usage = turn.usage.as_ref();
let flow = match turn.result {
Ok(TurnOutcome::ToolCalls(n)) => {
let mut payload = json!({"iteration": iteration, "tool_calls": n});
if let Some(u) = usage {
payload["usage"] = u.clone();
}
ctx.end_turn_with(payload).await?;
return Ok(Flow::TurnDone);
}
Ok(TurnOutcome::FinalAnswer) => {
if ctx.has_eligible_inputs().await? {
Flow::TurnDone
} else {
Flow::Settled
}
}
Err(TurnError::Soft { reason, audit }) => {
let mut payload = json!({
"iteration": iteration,
"outcome": "soft_failure",
"error": audit,
});
if let Some(u) = usage {
payload["usage"] = u.clone();
}
let _ = ctx.end_turn_with(payload).await;
return Ok(Flow::Soft(reason));
}
Err(TurnError::Fatal { error, audit }) => {
let mut payload = json!({
"iteration": iteration,
"outcome": "error",
"error": audit,
});
if let Some(u) = usage {
payload["usage"] = u.clone();
}
let _ = ctx.end_turn_with(payload).await;
return Err(error);
}
};
let mut payload = json!({"iteration": iteration, "outcome": "final_answer"});
if let Some(u) = usage {
payload["usage"] = u.clone();
}
ctx.end_turn_with(payload).await?;
Ok(flow)
}
async fn apply_confirmation(
&self,
ctx: &DrainCtx,
call: &PendingCall,
decision: &ConfirmIntent,
) -> Result<(), LoopError> {
let result = match decision.decision {
ConfirmDecision::Approve => {
let tool_call = ToolCall {
id: call.call_id.clone(),
name: call.tool.clone(),
arguments: call.arguments.clone(),
};
match self.tools.invoke(tool_call).await {
Ok(r) => r,
Err(e) => ToolResult {
call_id: call.call_id.clone(),
output: json!({"error": e.to_string()}),
is_error: true,
redactions: Vec::new(),
},
}
}
ConfirmDecision::Reject => ToolResult {
call_id: call.call_id.clone(),
output: if decision.expired {
json!({
"error": "confirmation expired",
"policy": "ask",
"expired": true
})
} else {
match &decision.reason {
Some(reason) => json!({
"error": "permission denied by user",
"policy": "ask",
"reason": reason
}),
None => json!({
"error": "permission denied by user",
"policy": "ask"
}),
}
},
is_error: true,
redactions: Vec::new(),
},
};
let payload = tool_result_payload_confirmed(&result, decision);
ctx.append(EventKind::ToolResult, payload).await?;
Ok(())
}
async fn binding_for(
&self,
ctx: &DrainCtx,
events: &mut Vec<Event>,
) -> Result<SlotBinding, LoopError> {
let session = ctx.session();
if let Ok(slots) = SessionSlots::replay(session, events)
&& slots.binding(&self.config.slot).is_ok()
{
return Ok(slots.binding(&self.config.slot)?.clone());
}
let fresh = SlotResolver::from_agent_def(&self.agent).bind_session(session);
for payload in fresh.binding_payloads() {
ctx.append(EventKind::SlotBinding, payload).await?;
}
*events = ctx.events().await?;
Ok(fresh.binding(&self.config.slot)?.clone())
}
async fn provider_turn(
&self,
ctx: &DrainCtx,
binding: &SlotBinding,
messages: &[Message],
iteration: usize,
) -> TurnResult {
let target = binding.target.clone();
let mut schemas = self.tools.schemas();
schemas.sort_by(|a, b| a.name.cmp(&b.name));
let chat: Vec<ChatMessage> = messages.iter().filter_map(to_chat_message).collect();
let body = build_chat_body(&target.model, &chat, &schemas);
let step_request = ctx
.append(
EventKind::StepRequest,
json!({
"slot": self.config.slot.0,
"provider": target.provider,
"model": target.model,
"iteration": iteration,
"body": body,
}),
)
.await;
let step_request_seq = match step_request {
Ok(ev) => ev.seq,
Err(e) => {
let fatal = TurnError::fatal(e, self.policy.as_ref());
if let TurnError::Fatal { audit, .. } = &fatal {
self.observe_fatal(ctx, iteration, 0, audit, 0, 0, None)
.await;
}
return TurnResult {
result: Err(fatal),
usage: None,
};
}
};
self.observe_request(
ctx,
binding,
chat.len(),
&schemas,
iteration,
&body,
step_request_seq,
)
.await;
let slot = self.config.slot.clone();
let build_chat = chat.clone();
let build_schemas = schemas.clone();
let build = Arc::new(move |t: &kian_core::model::SlotTarget| ModelRequest {
slot: slot.clone(),
body: build_chat_body(&t.model, &build_chat, &build_schemas),
});
let mut stream = complete_turn(
Arc::clone(&self.registry),
self.config.slot.clone(),
binding.clone(),
build,
Arc::new(CtxSlotSink { ctx: ctx.clone() }),
);
let mut text = String::new();
let mut reasoning = String::new();
let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
let mut usage: Option<Value> = None;
let mut stream_error: Option<ProviderError> = None;
while let Some(item) = stream.next().await {
match item {
Ok(chunk) => {
if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
usage = Some(u.clone()); }
if !chunk.delta.is_null() {
assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
}
}
Err(e) => {
stream_error = Some(e);
break;
}
}
}
let text_bytes = text.len() as u64;
let reasoning_bytes = reasoning.len() as u64;
if let Some(e) = stream_error {
let class = error_class(&e);
let action = consult_policy(self.policy.as_ref(), class);
let note = action_note(action);
let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
self.observe_recover(ctx, iteration, step_request_seq, &audit)
.await;
self.observe_response(
ctx,
iteration,
step_request_seq,
"soft_failure",
0,
text_bytes,
reasoning_bytes,
usage.as_ref(),
Some(&audit),
)
.await;
return TurnResult {
result: Err(TurnError::Soft {
reason: format!("provider error ({class}): {e}{note}"),
audit,
}),
usage,
};
}
if text.is_empty() && calls.is_empty() {
let action = consult_policy(self.policy.as_ref(), CLASS_EMPTY_RESPONSE);
let note = action_note(action);
let audit = recovery_audit(
self.policy.as_ref(),
kian_orchestrator::recovery::ErrorClass::EmptyResponse,
);
self.observe_recover(ctx, iteration, step_request_seq, &audit)
.await;
self.observe_response(
ctx,
iteration,
step_request_seq,
"soft_failure",
0,
0,
0,
usage.as_ref(),
Some(&audit),
)
.await;
return TurnResult {
result: Err(TurnError::Soft {
reason: format!("empty model response{note}"),
audit,
}),
usage,
};
}
let tool_calls: Vec<ToolCall> = calls.into_values().map(CallAcc::finish).collect();
let mut content = json!({"text": text});
if !tool_calls.is_empty() {
content["tool_calls"] = Value::Array(
tool_calls
.iter()
.map(|c| json!({"id": c.id, "name": c.name, "arguments": c.arguments}))
.collect(),
);
}
if !reasoning.is_empty() {
content["reasoning_content"] = Value::String(reasoning);
}
if let Err(e) = ctx
.append(
EventKind::AssistantMessage,
json!({"role": "assistant", "content": content}),
)
.await
{
let fatal = TurnError::fatal(e, self.policy.as_ref());
if let TurnError::Fatal { audit, .. } = &fatal {
self.observe_fatal(
ctx,
iteration,
step_request_seq,
audit,
text_bytes,
reasoning_bytes,
usage.as_ref(),
)
.await;
}
return TurnResult {
result: Err(fatal),
usage,
};
}
if tool_calls.is_empty() {
self.observe_response(
ctx,
iteration,
step_request_seq,
"final_answer",
0,
text_bytes,
reasoning_bytes,
usage.as_ref(),
None,
)
.await;
return TurnResult {
result: Ok(TurnOutcome::FinalAnswer),
usage,
};
}
let n = tool_calls.len();
for call in tool_calls {
let decision = evaluate_permission(&self.config.permissions, &call.name);
let hook_verdict = self
.consult_tool_pre(ctx, &call, iteration, step_request_seq, decision)
.await;
let appended = match hook_verdict {
kian_plugin::hooks::ToolVerdict::Deny {
ref plugin,
ref reason,
} => {
ctx.append(
EventKind::ToolCall,
tool_call_payload_hook_denied(&call, plugin, reason),
)
.await
}
_ => {
ctx.append(EventKind::ToolCall, tool_call_payload(&call, decision))
.await
}
};
let call_seq = match appended {
Ok(ev) => ev.seq,
Err(e) => {
let fatal = TurnError::fatal(e, self.policy.as_ref());
if let TurnError::Fatal { audit, .. } = &fatal {
self.observe_fatal(
ctx,
iteration,
step_request_seq,
audit,
text_bytes,
reasoning_bytes,
usage.as_ref(),
)
.await;
}
return TurnResult {
result: Err(fatal),
usage,
};
}
};
if let kian_plugin::hooks::ToolVerdict::Deny {
ref plugin,
ref reason,
} = hook_verdict
{
let denied = ToolResult {
call_id: call.id.clone(),
output: json!({
"error": format!("denied by plugin {plugin}: {reason}"),
"policy": "hook"
}),
is_error: true,
redactions: Vec::new(),
};
if let Err(e) = ctx
.append(EventKind::ToolResult, tool_result_payload(&denied))
.await
{
let fatal = TurnError::fatal(e, self.policy.as_ref());
if let TurnError::Fatal { audit, .. } = &fatal {
self.observe_fatal(
ctx,
iteration,
call_seq,
audit,
text_bytes,
reasoning_bytes,
usage.as_ref(),
)
.await;
}
return TurnResult {
result: Err(fatal),
usage,
};
}
self.observe_tool_post(ctx, &denied, &call.name, call_seq)
.await;
continue;
}
if matches!(decision, Some(PermissionDecision::Ask)) {
continue;
}
if let Some(denied) = declared_denial(&call, decision) {
if let Err(e) = ctx
.append(EventKind::ToolResult, tool_result_payload(&denied))
.await
{
let fatal = TurnError::fatal(e, self.policy.as_ref());
if let TurnError::Fatal { audit, .. } = &fatal {
self.observe_fatal(
ctx,
iteration,
call_seq,
audit,
text_bytes,
reasoning_bytes,
usage.as_ref(),
)
.await;
}
return TurnResult {
result: Err(fatal),
usage,
};
}
self.observe_tool_post(ctx, &denied, &call.name, call_seq)
.await;
continue;
}
let result = match self.tools.invoke(call.clone()).await {
Ok(r) => r,
Err(e) => {
ToolResult {
call_id: call.id.clone(),
output: json!({"error": e.to_string()}),
is_error: true,
redactions: Vec::new(),
}
}
};
let result_seq = match ctx
.append(EventKind::ToolResult, tool_result_payload(&result))
.await
{
Ok(ev) => ev.seq,
Err(e) => {
let fatal = TurnError::fatal(e, self.policy.as_ref());
if let TurnError::Fatal { audit, .. } = &fatal {
self.observe_fatal(
ctx,
iteration,
call_seq,
audit,
text_bytes,
reasoning_bytes,
usage.as_ref(),
)
.await;
}
return TurnResult {
result: Err(fatal),
usage,
};
}
};
self.observe_tool_post(ctx, &result, &call.name, result_seq)
.await;
}
self.observe_response(
ctx,
iteration,
step_request_seq,
"tool_calls",
n as u64,
text_bytes,
reasoning_bytes,
usage.as_ref(),
None,
)
.await;
TurnResult {
result: Ok(TurnOutcome::ToolCalls(n)),
usage,
}
}
}
impl TurnError {
fn fatal(e: EngineError, policy: &dyn RecoveryPolicySource) -> Self {
let error = LoopError::Engine(e);
let audit = recovery_audit(policy, loop_error_class(&error));
Self::Fatal { error, audit }
}
}
fn loop_error_class(e: &LoopError) -> kian_orchestrator::recovery::ErrorClass {
match e {
LoopError::Engine(_) => kian_orchestrator::recovery::ErrorClass::StoreFailure,
LoopError::Context(_) | LoopError::Slot(_) => {
kian_orchestrator::recovery::ErrorClass::Unknown
}
}
}
fn provider_error_class(e: &ProviderError) -> kian_orchestrator::recovery::ErrorClass {
kian_orchestrator::recovery::classify(
&kian_orchestrator::recovery::RecoveryError::Provider(e.clone()),
&kian_orchestrator::recovery::ClassifyCtx { attempt: 0 },
)
}
fn recovery_audit(
policy: &dyn RecoveryPolicySource,
class: kian_orchestrator::recovery::ErrorClass,
) -> Value {
let action = consult_policy(policy, class.name());
json!({
"class": class.name(),
"action": action_name(action.as_ref()),
})
}
fn action_name(action: Option<&RecoveryAction>) -> &'static str {
match action {
None => "none",
Some(RecoveryAction::BackoffRetry { .. }) => "backoff_retry",
Some(RecoveryAction::CompressThenRetry) => "compress_then_retry",
Some(RecoveryAction::Failover) => "failover",
Some(RecoveryAction::InterruptAsk) => "interrupt_ask",
Some(RecoveryAction::Fail) => "fail",
}
}
struct CtxSlotSink {
ctx: DrainCtx,
}
impl SlotEventSink for CtxSlotSink {
fn persist_fallback(
&self,
payload: Value,
) -> futures::future::BoxFuture<'static, Result<(), String>> {
let ctx = self.ctx.clone();
Box::pin(async move {
ctx.append(EventKind::SlotFallback, payload)
.await
.map(|_| ())
.map_err(|e| e.to_string())
})
}
}
struct CallAcc {
id: String,
name: String,
arguments: String,
}
impl CallAcc {
fn finish(self) -> ToolCall {
let arguments = serde_json::from_str::<Value>(&self.arguments)
.unwrap_or_else(|_| Value::String(self.arguments.clone()));
ToolCall {
id: self.id,
name: self.name,
arguments,
}
}
}
fn assemble_delta(
delta: &Value,
text: &mut String,
reasoning: &mut String,
calls: &mut BTreeMap<u64, CallAcc>,
) {
if let Some(fragment) = delta.get("content").and_then(Value::as_str) {
text.push_str(fragment);
}
if let Some(fragment) = delta.get("reasoning_content").and_then(Value::as_str) {
reasoning.push_str(fragment);
}
if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) {
for entry in list {
let index = entry.get("index").and_then(Value::as_u64).unwrap_or(0);
let slot = calls.entry(index).or_insert_with(|| CallAcc {
id: String::new(),
name: String::new(),
arguments: String::new(),
});
if let Some(id) = entry.get("id").and_then(Value::as_str) {
slot.id = id.to_string();
}
if let Some(name) = entry.pointer("/function/name").and_then(Value::as_str) {
slot.name.push_str(name);
}
if let Some(args) = entry.pointer("/function/arguments").and_then(Value::as_str) {
slot.arguments.push_str(args);
}
}
}
}
pub fn to_chat_message(m: &Message) -> Option<ChatMessage> {
match m.role.as_str() {
"tool" => Some(tool_result_message(&m.content)),
"assistant" => assistant_message(&m.content),
_ => Some(string_or_compact(&m.role, &m.content)),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PermissionDecision {
AllowConfigured,
AllowDefault,
Deny,
Ask,
}
const PERMISSION_DENY_REASON: &str = "tool_denied_by_policy";
fn evaluate_permission(
permissions: &BTreeMap<String, Permission>,
tool: &str,
) -> Option<PermissionDecision> {
if permissions.is_empty() {
return None;
}
match permissions.get(tool) {
Some(Permission::Allow) => Some(PermissionDecision::AllowConfigured),
Some(Permission::Deny) => Some(PermissionDecision::Deny),
Some(Permission::Ask) => Some(PermissionDecision::Ask),
None => Some(PermissionDecision::AllowDefault),
}
}
fn declared_denial(call: &ToolCall, decision: Option<PermissionDecision>) -> Option<ToolResult> {
matches!(decision, Some(PermissionDecision::Deny)).then(|| ToolResult {
call_id: call.id.clone(),
output: json!({
"error": format!("permission denied by policy: {}", call.name),
"policy": "deny"
}),
is_error: true,
redactions: Vec::new(),
})
}
fn tool_call_payload(call: &ToolCall, decision: Option<PermissionDecision>) -> Value {
let mut payload = json!({
"role": "assistant",
"content": {"id": call.id, "name": call.name, "arguments": call.arguments}
});
if let Some(decision) = decision {
payload["permission"] = match decision {
PermissionDecision::AllowConfigured => json!({
"evaluated": "allow", "policy": "configured", "matched": call.name
}),
PermissionDecision::AllowDefault => json!({
"evaluated": "allow", "policy": "default", "matched": call.name
}),
PermissionDecision::Deny => json!({
"evaluated": "deny",
"policy": "configured",
"matched": call.name,
"reason": PERMISSION_DENY_REASON
}),
PermissionDecision::Ask => json!({
"evaluated": "ask",
"policy": "configured",
"matched": call.name
}),
};
}
payload
}
fn tool_call_payload_hook_denied(call: &ToolCall, plugin: &str, reason: &str) -> Value {
let mut payload = json!({
"role": "assistant",
"content": {"id": call.id, "name": call.name, "arguments": call.arguments}
});
payload["permission"] = json!({
"evaluated": "deny",
"policy": "hook",
"matched": format!("{plugin}:tool/pre"),
"reason": reason,
});
payload
}
fn permission_view(
call: &ToolCall,
decision: Option<PermissionDecision>,
) -> kian_plugin::hooks::PermissionView {
match decision {
Some(PermissionDecision::AllowConfigured) => kian_plugin::hooks::PermissionView {
evaluated: "allow".to_string(),
policy: "configured".to_string(),
matched: call.name.clone(),
reason: None,
},
Some(PermissionDecision::Deny) => kian_plugin::hooks::PermissionView {
evaluated: "deny".to_string(),
policy: "configured".to_string(),
matched: call.name.clone(),
reason: Some(PERMISSION_DENY_REASON.to_string()),
},
Some(PermissionDecision::Ask) => kian_plugin::hooks::PermissionView {
evaluated: "ask".to_string(),
policy: "configured".to_string(),
matched: call.name.clone(),
reason: None,
},
Some(PermissionDecision::AllowDefault) | None => kian_plugin::hooks::PermissionView {
evaluated: "allow".to_string(),
policy: "default".to_string(),
matched: call.name.clone(),
reason: None,
},
}
}
fn tool_result_payload(result: &ToolResult) -> Value {
let mut payload = json!({
"role": "tool",
"content": {
"call_id": result.call_id,
"output": result.output,
"is_error": result.is_error
}
});
if !result.redactions.is_empty() {
if let Ok(report) = serde_json::to_value(&result.redactions) {
payload["redactions"] = report;
}
}
payload
}
fn tool_result_payload_confirmed(result: &ToolResult, decision: &ConfirmIntent) -> Value {
let mut payload = tool_result_payload(result);
let mut provenance = json!({
"call_id": result.call_id,
"decision": decision.decision.as_str(),
"requested_by": decision.requested_by,
"answered_at_ms": decision.answered_at_ms,
});
if decision.expired {
provenance["expired"] = json!(true);
}
payload["confirmation"] = provenance;
payload
}
fn string_or_compact(role: &str, content: &Value) -> ChatMessage {
let text = match content {
Value::String(s) => s.clone(),
other => serde_json::to_string(other).unwrap_or_default(),
};
ChatMessage {
role: role.to_owned(),
content: Some(text),
tool_call_id: None,
tool_calls: None,
reasoning_content: None,
}
}
fn tool_result_message(content: &Value) -> ChatMessage {
if let Some(obj) = content.as_object()
&& let Some(call_id) = obj.get("call_id").and_then(Value::as_str)
{
let output = obj.get("output").cloned().unwrap_or(Value::Null);
return ChatMessage {
role: "tool".into(),
content: Some(serde_json::to_string(&output).unwrap_or_default()),
tool_call_id: Some(call_id.to_owned()),
tool_calls: None,
reasoning_content: None,
};
}
ChatMessage {
role: "tool".into(),
content: Some(serde_json::to_string(content).unwrap_or_default()),
tool_call_id: Some(String::new()),
tool_calls: None,
reasoning_content: None,
}
}
fn reasoning_field(obj: &serde_json::Map<String, Value>) -> Option<String> {
obj.get("reasoning_content")
.and_then(Value::as_str)
.filter(|r| !r.is_empty())
.map(str::to_owned)
}
fn assistant_message(content: &Value) -> Option<ChatMessage> {
let Some(obj) = content.as_object() else {
return Some(string_or_compact("assistant", content));
};
if obj.contains_key("tool_calls") {
let calls: Option<Vec<WireToolCall>> =
obj.get("tool_calls").and_then(Value::as_array).map(|list| {
list.iter()
.filter_map(|tc| {
let id = tc.get("id").and_then(Value::as_str)?;
let name = tc.get("name").and_then(Value::as_str)?;
let arguments = tc.get("arguments").cloned().unwrap_or(Value::Null);
Some(WireToolCall {
id: id.to_owned(),
r#type: "function".into(),
function: WireFunctionCall {
name: name.to_owned(),
arguments: serde_json::to_string(&arguments).unwrap_or_default(),
},
})
})
.collect()
});
return Some(ChatMessage {
role: "assistant".into(),
content: obj
.get("text")
.and_then(Value::as_str)
.filter(|t| !t.is_empty())
.map(str::to_owned),
tool_call_id: None,
tool_calls: calls,
reasoning_content: reasoning_field(obj),
});
}
if obj.contains_key("id") && obj.contains_key("name") && obj.contains_key("arguments") {
return None;
}
if let Some(text) = obj.get("text").and_then(Value::as_str) {
return Some(ChatMessage {
role: "assistant".into(),
content: Some(text.to_owned()),
tool_call_id: None,
tool_calls: None,
reasoning_content: reasoning_field(obj),
});
}
Some(string_or_compact("assistant", content))
}
fn resident_empty_batch(scope: BudgetScope, taken_empty: bool, last_role: Option<&str>) -> bool {
scope == BudgetScope::PerEpisode && taken_empty && last_role == Some("assistant")
}
fn error_class(e: &ProviderError) -> &'static str {
match e {
ProviderError::RateLimited => "rate_limited",
ProviderError::ContextOverflow => "context_overflow",
ProviderError::Unavailable(_) | ProviderError::Transport(_) => "provider_down",
ProviderError::EmptyResponse => CLASS_EMPTY_RESPONSE,
ProviderError::InvalidResponse(_) => "validation_failed",
ProviderError::Other(_) => "internal",
}
}
fn consult_policy(policy: &dyn RecoveryPolicySource, class: &str) -> Option<RecoveryAction> {
policy
.table()
.into_iter()
.find(|rule| rule.class == class)
.map(|rule| rule.action)
}
fn action_note(action: Option<RecoveryAction>) -> String {
match action {
Some(a) => format!("; recovery policy action: {a:?}"),
None => "; no matching recovery policy rule".into(),
}
}
#[cfg(test)]
mod tests {
use crate::react::{
BudgetScope, CLASS_EMPTY_RESPONSE, ReActConfig, ReActLoop, assemble_delta, consult_policy,
to_chat_message, tool_result_payload,
};
use crate::test_support::{NoopPolicy, NoopTools, agent_def};
use kian_core::context::{Message, derive_model_context};
use kian_core::events::{Event, EventKind};
use kian_core::model::SessionId;
use kian_core::seams::{ToolCall, ToolResult};
use kian_core::secrets::{Redaction, RedactionKind};
use kian_llm::provider::build_chat_body;
use serde_json::json;
use std::collections::BTreeMap;
fn msg(role: &str, content: serde_json::Value) -> Message {
Message {
role: role.into(),
content,
synthetic: false,
}
}
#[test]
fn tool_result_payload_carries_redactions_outside_content() {
let plain = ToolResult {
call_id: "call-1".into(),
output: json!({"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false}),
is_error: false,
redactions: Vec::new(),
};
let payload = tool_result_payload(&plain);
assert_eq!(
payload,
json!({
"role": "tool",
"content": {
"call_id": "call-1",
"output": {"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false},
"is_error": false
}
}),
"no redactions → no key, bytes unchanged"
);
let redacted = ToolResult {
call_id: "call-2".into(),
output: json!({"exit_code": 0, "stdout": "[REDACTED:token]", "stderr": "", "timed_out": false}),
is_error: false,
redactions: vec![Redaction {
kind: RedactionKind::TokenPattern,
name: "ghp_".into(),
count: 1,
}],
};
let payload = tool_result_payload(&redacted);
assert_eq!(
payload["redactions"],
json!([{"kind": "token_pattern", "name": "ghp_", "count": 1}])
);
assert!(payload["content"].get("redactions").is_none());
assert_eq!(payload["content"]["call_id"], json!("call-2"));
}
#[test]
fn redactions_payload_key_never_enters_the_model_context() {
let session = SessionId::new();
let bytes = tool_result_payload(&ToolResult {
call_id: "call-9".into(),
output: json!({"content": "scrubbed"}),
is_error: false,
redactions: vec![Redaction {
kind: RedactionKind::EnvLine,
name: "MY_SERVICE_TOKEN".into(),
count: 2,
}],
});
let with = Event {
seq: 2,
session,
epoch: kian_core::model::Epoch(1),
ts: 1,
kind: EventKind::ToolResult,
bytes: bytes.clone(),
version: 0,
};
let mut without_bytes = bytes.clone();
without_bytes.as_object_mut().unwrap().remove("redactions");
let without = Event {
bytes: without_bytes,
..with.clone()
};
let base = Event {
seq: 1,
session,
epoch: kian_core::model::Epoch(0),
ts: 0,
kind: EventKind::SessionCreated,
bytes: json!({}),
version: 0,
};
let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
let ctx_without = derive_model_context(&[base, without]).unwrap();
assert_eq!(ctx_with, ctx_without);
assert_eq!(ctx_with.len(), 1);
let chat = to_chat_message(&ctx_with[0]).unwrap();
assert_eq!(chat.role, "tool");
assert_eq!(chat.tool_call_id.as_deref(), Some("call-9"));
assert_eq!(chat.content.as_deref(), Some("{\"content\":\"scrubbed\"}"));
}
#[test]
fn tool_round_trip_projects_to_the_strict_wire_shape() {
let assistant = msg(
"assistant",
json!({
"text": "",
"tool_calls": [
{"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}
]
}),
);
let chat = to_chat_message(&assistant).unwrap();
assert_eq!(chat.role, "assistant");
assert_eq!(chat.content, None, "empty text serializes as null");
let tc = &chat.tool_calls.as_ref().unwrap()[0];
assert_eq!(tc.id, "call-1");
assert_eq!(tc.r#type, "function");
assert_eq!(tc.function.name, "fs_read");
assert_eq!(tc.function.arguments, "{\"path\":\"a.txt\"}");
let with_text = msg(
"assistant",
json!({"text": "checking", "tool_calls": [
{"id": "call-2", "name": "exec", "arguments": {"argv": ["true"]}}
]}),
);
let chat = to_chat_message(&with_text).unwrap();
assert_eq!(chat.content.as_deref(), Some("checking"));
let dup = msg(
"assistant",
json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}),
);
assert!(to_chat_message(&dup).is_none());
let result = msg(
"tool",
json!({"call_id": "call-1", "output": {"content": "x"}, "is_error": false}),
);
let chat = to_chat_message(&result).unwrap();
assert_eq!(chat.role, "tool");
assert_eq!(chat.tool_call_id.as_deref(), Some("call-1"));
assert_eq!(chat.content.as_deref(), Some("{\"content\":\"x\"}"));
assert!(chat.tool_calls.is_none());
}
#[test]
fn plain_messages_keep_the_v1_shape() {
let user = msg("user", json!("hello"));
let chat = to_chat_message(&user).unwrap();
assert_eq!(chat.role, "user");
assert_eq!(chat.content.as_deref(), Some("hello"));
assert!(chat.tool_call_id.is_none() && chat.tool_calls.is_none());
let bare = msg("assistant", json!({"text": "hi"}));
assert_eq!(
to_chat_message(&bare).unwrap().content.as_deref(),
Some("hi")
);
let foreign = msg("tool", json!({"odd": true}));
let chat = to_chat_message(&foreign).unwrap();
assert_eq!(chat.tool_call_id.as_deref(), Some(""));
}
#[test]
fn permission_evaluation_covers_absent_default_and_configured() {
use crate::react::{PermissionDecision, evaluate_permission};
use kian_core::model::Permission;
let empty: BTreeMap<String, Permission> = BTreeMap::new();
assert_eq!(evaluate_permission(&empty, "fs_write"), None);
let table: BTreeMap<String, Permission> = BTreeMap::from([
("fs_read".to_string(), Permission::Allow),
("fs_write".to_string(), Permission::Deny),
]);
assert_eq!(
evaluate_permission(&table, "fs_read"),
Some(PermissionDecision::AllowConfigured)
);
assert_eq!(
evaluate_permission(&table, "fs_write"),
Some(PermissionDecision::Deny)
);
assert_eq!(
evaluate_permission(&table, "exec"),
Some(PermissionDecision::AllowDefault)
);
}
#[test]
fn tool_call_payload_carries_permission_provenance_outside_content() {
use crate::react::{evaluate_permission, tool_call_payload};
use kian_core::model::Permission;
let call = ToolCall {
id: "call-7".into(),
name: "fs_write".into(),
arguments: json!({"path": "a.txt"}),
};
let empty: BTreeMap<String, Permission> = BTreeMap::new();
let legacy = tool_call_payload(&call, evaluate_permission(&empty, &call.name));
assert_eq!(
legacy,
json!({
"role": "assistant",
"content": {"id": "call-7", "name": "fs_write", "arguments": {"path": "a.txt"}}
})
);
let table: BTreeMap<String, Permission> =
BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
let allowed = tool_call_payload(&call, evaluate_permission(&table, &call.name)); assert_eq!(
allowed["permission"],
json!({"evaluated": "allow", "policy": "default", "matched": "fs_write"})
);
assert_eq!(allowed["content"], legacy["content"]);
let table: BTreeMap<String, Permission> =
BTreeMap::from([("fs_write".to_string(), Permission::Deny)]);
let denied = tool_call_payload(&call, evaluate_permission(&table, &call.name));
assert_eq!(
denied["permission"],
json!({
"evaluated": "deny",
"policy": "configured",
"matched": "fs_write",
"reason": "tool_denied_by_policy"
})
);
assert_eq!(denied["content"], legacy["content"]);
}
#[test]
fn hook_denied_permission_payload_goldens_are_frozen_bytes() {
use crate::react::{evaluate_permission, tool_call_payload, tool_call_payload_hook_denied};
use kian_core::model::Permission;
let call = ToolCall {
id: "call-7".into(),
name: "exec".into(),
arguments: json!({"cmd": ["ls"]}),
};
let hook_denied =
tool_call_payload_hook_denied(&call, "approval-gate", "exec not on the allowlist");
assert_eq!(
serde_json::to_string(&hook_denied).unwrap(),
"{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
\"permission\":{\"evaluated\":\"deny\",\"matched\":\"approval-gate:tool/pre\",\
\"policy\":\"hook\",\"reason\":\"exec not on the allowlist\"},\"role\":\"assistant\"}"
);
let denied_result = ToolResult {
call_id: call.id.clone(),
output: json!({
"error": "denied by plugin approval-gate: exec not on the allowlist",
"policy": "hook"
}),
is_error: true,
redactions: Vec::new(),
};
assert_eq!(
serde_json::to_string(&tool_result_payload(&denied_result)).unwrap(),
"{\"content\":{\"call_id\":\"call-7\",\"is_error\":true,\
\"output\":{\"error\":\"denied by plugin approval-gate: exec not on the allowlist\",\
\"policy\":\"hook\"}},\"role\":\"tool\"}"
);
let empty: BTreeMap<String, Permission> = BTreeMap::new();
assert_eq!(
serde_json::to_string(&tool_call_payload(
&call,
evaluate_permission(&empty, &call.name)
))
.unwrap(),
"{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
\"role\":\"assistant\"}"
);
let default_table = BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
assert_eq!(
serde_json::to_string(&tool_call_payload(
&call,
evaluate_permission(&default_table, &call.name)
))
.unwrap(),
"{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
\"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"default\"},\
\"role\":\"assistant\"}"
);
let allow_table = BTreeMap::from([("exec".to_string(), Permission::Allow)]);
assert_eq!(
serde_json::to_string(&tool_call_payload(
&call,
evaluate_permission(&allow_table, &call.name)
))
.unwrap(),
"{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
\"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"configured\"},\
\"role\":\"assistant\"}"
);
let deny_table = BTreeMap::from([("exec".to_string(), Permission::Deny)]);
assert_eq!(
serde_json::to_string(&tool_call_payload(
&call,
evaluate_permission(&deny_table, &call.name)
))
.unwrap(),
"{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
\"permission\":{\"evaluated\":\"deny\",\"matched\":\"exec\",\"policy\":\"configured\",\
\"reason\":\"tool_denied_by_policy\"},\"role\":\"assistant\"}"
);
}
#[test]
fn permission_payload_key_never_enters_the_model_context() {
use crate::react::{PermissionDecision, tool_call_payload};
use kian_core::seams::ToolCall;
let session = SessionId::new();
let call = ToolCall {
id: "call-1".into(),
name: "fs_read".into(),
arguments: json!({"path": "a.txt"}),
};
let with_bytes = tool_call_payload(&call, Some(PermissionDecision::Deny));
let mut without_bytes = with_bytes.clone();
without_bytes.as_object_mut().unwrap().remove("permission");
let with = Event {
seq: 2,
session,
epoch: kian_core::model::Epoch(1),
ts: 1,
kind: EventKind::ToolCall,
bytes: with_bytes,
version: 0,
};
let without = Event {
bytes: without_bytes,
..with.clone()
};
let base = Event {
seq: 1,
session,
epoch: kian_core::model::Epoch(0),
ts: 0,
kind: EventKind::SessionCreated,
bytes: json!({}),
version: 0,
};
let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
let ctx_without = derive_model_context(&[base, without]).unwrap();
assert_eq!(ctx_with, ctx_without);
assert_eq!(ctx_with.len(), 1);
assert_eq!(ctx_with[0].role, "assistant");
assert_eq!(
ctx_with[0].content,
json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}})
);
assert!(!ctx_with[0].synthetic);
}
#[test]
fn resident_empty_batch_is_skipped_only_for_resident_assistant_tails() {
use super::resident_empty_batch;
assert!(resident_empty_batch(
BudgetScope::PerEpisode,
true,
Some("assistant")
));
assert!(!resident_empty_batch(
BudgetScope::PerEpisode,
false,
Some("assistant")
));
assert!(!resident_empty_batch(
BudgetScope::PerEpisode,
true,
Some("tool")
));
assert!(!resident_empty_batch(
BudgetScope::PerEpisode,
true,
Some("user")
));
assert!(!resident_empty_batch(
BudgetScope::Lifetime,
true,
Some("assistant")
));
}
#[test]
fn budget_scope_selects_lifetime_or_episode_counter() {
assert_eq!(BudgetScope::Lifetime.used(9, 0), 9);
assert_eq!(BudgetScope::Lifetime.used(0, 9), 0);
assert_eq!(BudgetScope::PerEpisode.used(9, 2), 2);
assert_eq!(BudgetScope::PerEpisode.used(0, 0), 0);
}
#[test]
fn delta_assembly_concatenates_content_fragments() {
let mut text = String::new();
let mut reasoning = String::new();
let mut calls = Default::default();
for fragment in ["Hello", ", ", "kian"] {
assemble_delta(
&serde_json::json!({"content": fragment}),
&mut text,
&mut reasoning,
&mut calls,
);
}
assert_eq!(text, "Hello, kian");
assert!(calls.is_empty());
}
#[test]
fn reasoning_fragments_are_persisted_and_replayed() {
let mut text = String::new();
let mut reasoning = String::new();
let mut calls = Default::default();
assemble_delta(
&json!({"reasoning_content": "think "}),
&mut text,
&mut reasoning,
&mut calls,
);
assemble_delta(
&json!({"reasoning_content": "harder"}),
&mut text,
&mut reasoning,
&mut calls,
);
assemble_delta(
&json!({"content": "answer"}),
&mut text,
&mut reasoning,
&mut calls,
);
assert_eq!(reasoning, "think harder");
assert_eq!(text, "answer");
let with = to_chat_message(&msg(
"assistant",
json!({"text": text, "reasoning_content": reasoning}),
))
.unwrap();
assert_eq!(with.reasoning_content.as_deref(), Some("think harder"));
let body = build_chat_body("m", &[with], &[]);
assert_eq!(body["messages"][0]["reasoning_content"], "think harder");
let legacy = to_chat_message(&msg("assistant", json!({"text": "answer"}))).unwrap();
assert!(legacy.reasoning_content.is_none());
let body = build_chat_body("m", &[legacy], &[]);
assert!(body["messages"][0].get("reasoning_content").is_none());
}
#[test]
fn delta_assembly_accumulates_tool_call_fragments_by_index() {
let mut text = String::new();
let mut reasoning = String::new();
let mut calls = Default::default();
assemble_delta(
&serde_json::json!({"tool_calls": [
{"index": 0, "id": "call-1", "function": {"name": "fs.read"}}
]}),
&mut text,
&mut reasoning,
&mut calls,
);
assemble_delta(
&serde_json::json!({"tool_calls": [
{"index": 0, "function": {"arguments": "{\"pa"}}
]}),
&mut text,
&mut reasoning,
&mut calls,
);
assemble_delta(
&serde_json::json!({"tool_calls": [
{"index": 0, "function": {"arguments": "th\": \"a.txt\"}"}}
]}),
&mut text,
&mut reasoning,
&mut calls,
);
let finished: Vec<_> = calls.into_values().map(|c| c.finish()).collect();
assert_eq!(finished.len(), 1);
assert_eq!(finished[0].id, "call-1");
assert_eq!(finished[0].name, "fs.read");
assert_eq!(finished[0].arguments, serde_json::json!({"path": "a.txt"}));
}
#[test]
fn policy_consult_matches_rule_by_class() {
use kian_core::seams::{PolicyRule, RecoveryAction, RecoveryPolicySource};
struct Table(Vec<PolicyRule>);
impl RecoveryPolicySource for Table {
fn table(&self) -> Vec<PolicyRule> {
self.0.clone()
}
}
let table = Table(vec![
PolicyRule {
class: "rate_limited".into(),
action: RecoveryAction::BackoffRetry { delay_ms: 100 },
},
PolicyRule {
class: CLASS_EMPTY_RESPONSE.into(),
action: RecoveryAction::InterruptAsk,
},
]);
assert_eq!(
consult_policy(&table, "rate_limited"),
Some(RecoveryAction::BackoffRetry { delay_ms: 100 })
);
assert_eq!(
consult_policy(&table, CLASS_EMPTY_RESPONSE),
Some(RecoveryAction::InterruptAsk)
);
assert_eq!(consult_policy(&table, "no_such_class"), None);
}
#[test]
fn recovery_audit_carries_class_and_policy_action() {
use kian_core::seams::{PolicyRule, RecoveryPolicySource};
use kian_orchestrator::recovery::ErrorClass;
use serde_json::json;
struct Table(Vec<PolicyRule>);
impl RecoveryPolicySource for Table {
fn table(&self) -> Vec<PolicyRule> {
self.0.clone()
}
}
let with_rule = Table(vec![PolicyRule {
class: "store_failure".into(),
action: kian_core::seams::RecoveryAction::Fail,
}]);
assert_eq!(
super::recovery_audit(&with_rule, ErrorClass::StoreFailure),
json!({"class": "store_failure", "action": "fail"})
);
assert_eq!(
super::recovery_audit(&with_rule, ErrorClass::EmptyResponse),
json!({"class": "empty_response", "action": "none"}),
"no covering rule → the honest none spelling"
);
assert_eq!(
super::provider_error_class(&kian_core::seams::ProviderError::RateLimited),
ErrorClass::RateLimited
);
assert_eq!(
super::provider_error_class(&kian_core::seams::ProviderError::Unavailable(
"upstream 503".into()
)),
ErrorClass::ProviderDown
);
assert_eq!(
super::loop_error_class(&super::LoopError::Engine(
kian_orchestrator::EngineError::NotAtSafeBoundary {
session: kian_core::model::SessionId::new(),
}
)),
ErrorClass::StoreFailure
);
assert_eq!(
super::loop_error_class(&super::LoopError::Slot(
kian_llm::slots::SlotError::UnknownSlot("aux".into())
)),
ErrorClass::Unknown
);
}
#[test]
fn react_config_defaults_are_sane() {
let cfg = ReActConfig::default();
assert_eq!(cfg.slot.0, "main");
assert!(cfg.max_iterations >= 1);
let react = ReActLoop::new(
agent_def(),
std::sync::Arc::new(kian_llm::ProviderRegistry::new()),
std::sync::Arc::new(NoopTools),
std::sync::Arc::new(NoopPolicy),
);
assert_eq!(react.config().slot.0, "main");
}
}