1use std::collections::BTreeMap;
52use std::sync::Arc;
53
54use futures::stream::{BoxStream, StreamExt};
55use kian_core::confirmation::{PendingCall, confirmable, confirmations, pending_calls};
56use kian_core::context::{Message, derive_model_context};
57use kian_core::control::{ConfirmDecision, ConfirmIntent};
58use kian_core::events::{Event, EventKind};
59use kian_core::model::{AgentDef, Permission, SlotName};
60use kian_core::seams::{
61 LoopDriver, LoopOutcome, ModelRequest, ProviderError, RecoveryAction, RecoveryPolicySource,
62 ToolCall, ToolProvider, ToolResult,
63};
64use kian_llm::provider::{ChatMessage, WireFunctionCall, WireToolCall, build_chat_body};
65use kian_llm::slots::{SessionSlots, SlotBinding, SlotError, SlotResolver};
66use kian_llm::turn::{ProviderRegistry, SlotEventSink, complete_turn};
67use kian_orchestrator::{DrainCtx, EngineError};
68use serde_json::{Value, json};
69
70use crate::evidence::{
71 BUILTIN_GATE_NAME, EvidenceGateConfig, evaluate_evidence_gate, verdict_payload,
72};
73
74pub const CLASS_EMPTY_RESPONSE: &str = "empty_response";
76
77pub const DEFAULT_MAX_ITERATIONS: usize = 32;
79
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
82pub enum BudgetScope {
83 #[default]
87 Lifetime,
88 PerEpisode,
92}
93
94impl BudgetScope {
95 #[must_use]
97 fn used(self, lifetime_iteration: usize, episode_iterations: usize) -> usize {
98 match self {
99 Self::Lifetime => lifetime_iteration,
100 Self::PerEpisode => episode_iterations,
101 }
102 }
103}
104
105#[derive(Debug, Clone)]
111pub struct ReActConfig {
112 pub slot: SlotName,
115 pub max_iterations: usize,
120 pub budget_scope: BudgetScope,
122 pub permissions: BTreeMap<String, Permission>,
128}
129
130impl Default for ReActConfig {
131 fn default() -> Self {
132 Self {
133 slot: SlotName("main".into()),
134 max_iterations: DEFAULT_MAX_ITERATIONS,
135 budget_scope: BudgetScope::Lifetime,
136 permissions: BTreeMap::new(),
137 }
138 }
139}
140
141struct Inner {
142 registry: Arc<ProviderRegistry>,
143 tools: Arc<dyn ToolProvider>,
144 policy: Arc<dyn RecoveryPolicySource>,
145 agent: AgentDef,
146 config: ReActConfig,
147 gate: EvidenceGateConfig,
150 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
154 set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
161}
162
163#[derive(Clone)]
165pub struct ReActLoop(Arc<Inner>);
166
167impl ReActLoop {
168 pub fn new(
172 agent: AgentDef,
173 registry: Arc<ProviderRegistry>,
174 tools: Arc<dyn ToolProvider>,
175 policy: Arc<dyn RecoveryPolicySource>,
176 ) -> Self {
177 Self::with_config(agent, registry, tools, policy, ReActConfig::default())
178 }
179
180 pub fn with_config(
183 agent: AgentDef,
184 registry: Arc<ProviderRegistry>,
185 tools: Arc<dyn ToolProvider>,
186 policy: Arc<dyn RecoveryPolicySource>,
187 config: ReActConfig,
188 ) -> Self {
189 Self::with_evidence_gate(
190 agent,
191 registry,
192 tools,
193 policy,
194 config,
195 EvidenceGateConfig::default(),
196 )
197 }
198
199 pub fn with_evidence_gate(
203 agent: AgentDef,
204 registry: Arc<ProviderRegistry>,
205 tools: Arc<dyn ToolProvider>,
206 policy: Arc<dyn RecoveryPolicySource>,
207 config: ReActConfig,
208 gate: EvidenceGateConfig,
209 ) -> Self {
210 Self::with_hooks(agent, registry, tools, policy, config, gate, None)
211 }
212
213 pub fn with_hooks(
219 agent: AgentDef,
220 registry: Arc<ProviderRegistry>,
221 tools: Arc<dyn ToolProvider>,
222 policy: Arc<dyn RecoveryPolicySource>,
223 config: ReActConfig,
224 gate: EvidenceGateConfig,
225 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
226 ) -> Self {
227 Self::with_hooks_and_guard(agent, registry, tools, policy, config, gate, hooks, None)
228 }
229
230 #[allow(clippy::too_many_arguments)]
239 pub fn with_hooks_and_guard(
240 agent: AgentDef,
241 registry: Arc<ProviderRegistry>,
242 tools: Arc<dyn ToolProvider>,
243 policy: Arc<dyn RecoveryPolicySource>,
244 config: ReActConfig,
245 gate: EvidenceGateConfig,
246 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
247 set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
248 ) -> Self {
249 Self(Arc::new(Inner {
250 registry,
251 tools,
252 policy,
253 agent,
254 config,
255 gate,
256 hooks,
257 set_guard,
258 }))
259 }
260
261 #[must_use]
262 pub fn config(&self) -> &ReActConfig {
263 &self.0.config
264 }
265
266 #[must_use]
270 pub fn evidence_gate(&self) -> &EvidenceGateConfig {
271 &self.0.gate
272 }
273}
274
275struct LoopState {
284 ctx: DrainCtx,
285 done: bool,
286 begun: bool,
287 drain_iterations: usize,
290}
291
292impl LoopDriver for ReActLoop {
293 type Ctx = DrainCtx;
294
295 fn drive(&self, ctx: DrainCtx) -> BoxStream<'static, LoopOutcome> {
296 let inner = Arc::clone(&self.0);
297 futures::stream::unfold(
298 LoopState {
299 ctx,
300 done: false,
301 begun: false,
302 drain_iterations: 0,
303 },
304 move |mut st| {
305 let inner = Arc::clone(&inner);
306 async move {
307 if st.done {
308 return None;
309 }
310 if !st.begun {
321 st.begun = true;
322 if let Some(guard) = inner.set_guard.as_ref() {
323 let worker = match st.ctx.events().await {
324 Ok(events) => kian_plugin::hooks::durable_worker_binding(
325 &events,
326 &st.ctx.session(),
327 )
328 .unwrap_or_default(),
329 Err(_) => String::new(),
333 };
334 guard.session_begin(kian_plugin::hooks::FrameInfo {
335 session: st.ctx.session(),
336 worker,
337 seq: 0,
338 epoch: Some(st.ctx.epoch().0),
339 });
340 }
341 }
342 let outcome = match inner.iteration(&st.ctx, &mut st.drain_iterations).await {
343 Flow::TurnDone => LoopOutcome::TurnDone,
344 Flow::Settled | Flow::Deferred => LoopOutcome::Settled,
345 Flow::Stopped(reason) => LoopOutcome::Stopped { reason },
346 Flow::Soft(reason) => LoopOutcome::SoftFailed { reason },
347 };
348 if !matches!(outcome, LoopOutcome::TurnDone) {
349 st.done = true;
350 }
351 Some((outcome, st))
352 }
353 },
354 )
355 .boxed()
356 }
357}
358
359enum Flow {
361 TurnDone,
363 Settled,
365 Deferred,
370 Stopped(String),
372 Soft(String),
374}
375
376enum TurnOutcome {
377 FinalAnswer,
378 ToolCalls(usize),
379}
380
381struct TurnResult {
386 result: Result<TurnOutcome, TurnError>,
387 usage: Option<Value>,
388}
389
390enum TurnError {
391 Soft { reason: String, audit: Value },
395 Fatal { error: LoopError, audit: Value },
398}
399
400#[derive(Debug, thiserror::Error)]
404pub enum LoopError {
405 #[error("engine: {0}")]
406 Engine(#[from] EngineError),
407 #[error("context projection: {0}")]
408 Context(#[from] kian_core::context::ContextError),
409 #[error("slots: {0}")]
410 Slot(#[from] SlotError),
411}
412
413impl Inner {
414 async fn iteration(&self, ctx: &DrainCtx, drain_iterations: &mut usize) -> Flow {
416 let flow = match self.run_iteration(ctx, drain_iterations).await {
417 Ok(flow) => flow,
418 Err(e) => return Flow::Soft(format!("loop error: {e}")),
419 };
420 match flow {
423 Flow::Settled | Flow::Stopped(_) => self.apply_evidence_gate(ctx, flow).await,
424 other => other,
425 }
426 }
427
428 async fn apply_evidence_gate(&self, ctx: &DrainCtx, flow: Flow) -> Flow {
441 if !self.gate.enabled {
442 return flow;
443 }
444 let events = match ctx.events().await {
445 Ok(events) => events,
446 Err(e) => {
447 return Flow::Soft(format!("evidence gate: stream read failed: {e}"));
448 }
449 };
450 let verdict = evaluate_evidence_gate(BUILTIN_GATE_NAME, &self.gate.checks, &events);
451 let payload = verdict_payload(BUILTIN_GATE_NAME, &verdict);
452 if let Err(e) = ctx.append(EventKind::EvidenceVerdict, payload).await {
453 return Flow::Soft(format!("evidence gate: verdict append failed: {e}"));
454 }
455 if verdict.passed {
456 self.gate.counters.record_passed();
457 flow
458 } else {
459 self.gate.counters.record_failed();
460 if verdict.attempt < self.gate.max_retries {
461 Flow::TurnDone
462 } else {
463 Flow::Soft(format!(
464 "evidence gate `{BUILTIN_GATE_NAME}` failed after {} attempt(s)",
465 verdict.attempt + 1
466 ))
467 }
468 }
469 }
470
471 async fn hook_frame(ctx: &DrainCtx, seq: u64) -> Option<kian_plugin::hooks::FrameInfo> {
488 let worker = match ctx.events().await {
489 Ok(events) => kian_plugin::hooks::durable_worker_binding(&events, &ctx.session())
490 .unwrap_or_default(),
491 Err(_) => String::new(),
494 };
495 Some(kian_plugin::hooks::FrameInfo {
496 session: ctx.session(),
497 worker,
498 seq,
499 epoch: Some(ctx.epoch().0),
500 })
501 }
502
503 #[allow(clippy::too_many_arguments)]
509 async fn observe_request(
510 &self,
511 ctx: &DrainCtx,
512 binding: &SlotBinding,
513 chat_len: usize,
514 schemas: &[kian_core::seams::ToolSchema],
515 iteration: usize,
516 body: &Value,
517 step_request_seq: u64,
518 ) {
519 use kian_plugin::hooks::{RequestMeta, serialized, sha256_hex};
520 let Some(hooks) = self.hooks.as_ref() else {
521 return;
522 };
523 let bytes = serialized(body);
524 let meta = RequestMeta {
525 slot: self.config.slot.0.clone(),
526 provider: binding.target.provider.clone(),
527 model: binding.target.model.clone(),
528 iteration: iteration as u64,
529 request_bytes: bytes.len() as u64,
530 request_sha256: sha256_hex(&bytes),
531 message_count: chat_len as u64,
532 tool_names: schemas.iter().map(|s| s.name.clone()).collect(),
533 tool_schema_sha256: sha256_hex(&serialized(&Value::Array(
534 schemas
535 .iter()
536 .map(|s| serde_json::to_value(s).unwrap_or(Value::Null))
537 .collect(),
538 ))),
539 timing: "pre_send".to_string(),
540 step_request_seq,
541 frame: Self::hook_frame(ctx, step_request_seq).await,
542 };
543 hooks.request(&meta).await;
544 }
545
546 #[allow(clippy::too_many_arguments)] async fn observe_response(
552 &self,
553 ctx: &DrainCtx,
554 iteration: usize,
555 seq: u64,
556 outcome: &str,
557 tool_calls: u64,
558 text_bytes: u64,
559 reasoning_bytes: u64,
560 usage: Option<&Value>,
561 error_audit: Option<&Value>,
562 ) {
563 use kian_plugin::hooks::{ResponseView, TurnErrorAudit};
564 let Some(hooks) = self.hooks.as_ref() else {
565 return;
566 };
567 let error = error_audit.and_then(|audit| {
568 Some(TurnErrorAudit {
569 class: audit.get("class")?.as_str()?.to_string(),
570 action: audit.get("action")?.as_str()?.to_string(),
571 })
572 });
573 let view = ResponseView {
574 iteration: iteration as u64,
575 outcome: outcome.to_string(),
576 tool_calls,
577 text_bytes,
578 reasoning_bytes,
579 usage: usage.cloned().unwrap_or(Value::Null),
580 error,
581 timing: "settled".to_string(),
582 frame: Self::hook_frame(ctx, seq).await,
583 };
584 hooks.response(&view).await;
585 }
586
587 async fn consult_tool_pre(
593 &self,
594 ctx: &DrainCtx,
595 call: &ToolCall,
596 iteration: usize,
597 seq: u64,
598 decision: Option<PermissionDecision>,
599 ) -> kian_plugin::hooks::ToolVerdict {
600 use kian_plugin::hooks::{ToolCallView, bounded_value, serialized, sha256_hex};
601 let Some(hooks) = self.hooks.as_ref() else {
602 return kian_plugin::hooks::ToolVerdict::Allow;
603 };
604 let bytes = serialized(&call.arguments);
605 let (arguments, arguments_truncated) = bounded_value(&call.arguments);
606 let view = ToolCallView {
607 call_id: call.id.clone(),
608 name: call.name.clone(),
609 iteration: iteration as u64,
610 arguments,
611 arguments_bytes: bytes.len() as u64,
612 arguments_sha256: sha256_hex(&bytes),
613 arguments_truncated,
614 permission: permission_view(call, decision),
615 surface: "react".to_string(),
616 frame: Self::hook_frame(ctx, seq).await,
617 };
618 hooks.tool_pre(&view).await
619 }
620
621 async fn observe_tool_post(&self, ctx: &DrainCtx, result: &ToolResult, name: &str, seq: u64) {
625 use kian_plugin::hooks::{RedactionReport, ToolPostView, serialized, sha256_hex};
626 let Some(hooks) = self.hooks.as_ref() else {
627 return;
628 };
629 let bytes = serialized(&result.output);
630 let view = ToolPostView {
631 call_id: result.call_id.clone(),
632 name: name.to_string(),
633 is_error: result.is_error,
634 output_bytes: bytes.len() as u64,
635 output_sha256: sha256_hex(&bytes),
636 redactions: result
637 .redactions
638 .iter()
639 .map(|r| RedactionReport {
640 kind: serde_json::to_value(r.kind)
641 .ok()
642 .and_then(|v| v.as_str().map(str::to_string))
643 .unwrap_or_default(),
644 name: r.name.clone(),
645 count: r.count,
646 })
647 .collect(),
648 frame: Self::hook_frame(ctx, seq).await,
649 };
650 hooks.tool_post(&view).await;
651 }
652
653 async fn observe_recover(&self, ctx: &DrainCtx, iteration: usize, seq: u64, audit: &Value) {
657 let Some(hooks) = self.hooks.as_ref() else {
658 return;
659 };
660 let view = kian_plugin::hooks::RecoveryView {
661 error_class: audit
662 .get("class")
663 .and_then(Value::as_str)
664 .unwrap_or_default()
665 .to_string(),
666 action: audit
667 .get("action")
668 .and_then(Value::as_str)
669 .unwrap_or("none")
670 .to_string(),
671 iteration: iteration as u64,
672 frame: Self::hook_frame(ctx, seq).await,
673 };
674 hooks.recover(&view).await;
675 }
676
677 #[allow(clippy::too_many_arguments)] async fn observe_fatal(
682 &self,
683 ctx: &DrainCtx,
684 iteration: usize,
685 seq: u64,
686 audit: &Value,
687 text_bytes: u64,
688 reasoning_bytes: u64,
689 usage: Option<&Value>,
690 ) {
691 self.observe_recover(ctx, iteration, seq, audit).await;
692 self.observe_response(
693 ctx,
694 iteration,
695 seq,
696 "error",
697 0,
698 text_bytes,
699 reasoning_bytes,
700 usage,
701 Some(audit),
702 )
703 .await;
704 }
705
706 async fn run_iteration(
707 &self,
708 ctx: &DrainCtx,
709 drain_iterations: &mut usize,
710 ) -> Result<Flow, LoopError> {
711 let taken = ctx.take_eligible_inputs().await?;
715
716 let mut events = ctx.events().await?;
718
719 let mut pending = pending_calls(&events);
724 if !pending.is_empty() {
725 let decisions = confirmations(&events);
726 for (call, decision) in confirmable(&pending, &decisions) {
727 self.apply_confirmation(ctx, &call, &decision).await?;
728 }
729 events = ctx.events().await?;
730 pending = pending_calls(&events);
731 if !pending.is_empty() {
732 tracing::debug!(
733 session = %ctx.session().0,
734 pending = pending.len(),
735 "awaiting confirmation: settling without a provider call"
736 );
737 return Ok(Flow::Deferred);
738 }
739 }
740
741 let binding = self.binding_for(ctx, &mut events).await?;
742 let messages = derive_model_context(&events)?;
743
744 if resident_empty_batch(
751 self.config.budget_scope,
752 taken.is_empty(),
753 messages.last().map(|m| m.role.as_str()),
754 ) {
755 tracing::debug!(
756 session = %ctx.session().0,
757 "resident empty batch: settling without a provider call (ADR-025)"
758 );
759 return Ok(Flow::Settled);
760 }
761
762 let iteration = events
765 .iter()
766 .filter(|ev| matches!(ev.kind, EventKind::TurnStart))
767 .count();
768 let used = self.config.budget_scope.used(iteration, *drain_iterations);
769 if used >= self.config.max_iterations {
770 let reason = match self.config.budget_scope {
771 BudgetScope::Lifetime => {
772 format!("iteration budget exhausted after {iteration} turns")
773 }
774 BudgetScope::PerEpisode => format!(
775 "{} after {used} turns",
776 kian_core::seams::EPISODE_BUDGET_STOP_REASON_PREFIX
777 ),
778 };
779 return Ok(Flow::Stopped(reason));
780 }
781 if self.config.budget_scope == BudgetScope::PerEpisode {
782 *drain_iterations += 1;
783 }
784
785 ctx.begin_turn_with(json!({"iteration": iteration})).await?;
788 let turn = self
789 .provider_turn(ctx, &binding, &messages, iteration)
790 .await;
791 let usage = turn.usage.as_ref();
792 let flow = match turn.result {
793 Ok(TurnOutcome::ToolCalls(n)) => {
794 let mut payload = json!({"iteration": iteration, "tool_calls": n});
795 if let Some(u) = usage {
796 payload["usage"] = u.clone();
797 }
798 ctx.end_turn_with(payload).await?;
799 return Ok(Flow::TurnDone);
800 }
801 Ok(TurnOutcome::FinalAnswer) => {
804 if ctx.has_eligible_inputs().await? {
805 Flow::TurnDone
806 } else {
807 Flow::Settled
808 }
809 }
810 Err(TurnError::Soft { reason, audit }) => {
811 let mut payload = json!({
812 "iteration": iteration,
813 "outcome": "soft_failure",
814 "error": audit,
815 });
816 if let Some(u) = usage {
817 payload["usage"] = u.clone();
818 }
819 let _ = ctx.end_turn_with(payload).await;
820 return Ok(Flow::Soft(reason));
821 }
822 Err(TurnError::Fatal { error, audit }) => {
823 let mut payload = json!({
824 "iteration": iteration,
825 "outcome": "error",
826 "error": audit,
827 });
828 if let Some(u) = usage {
829 payload["usage"] = u.clone();
830 }
831 let _ = ctx.end_turn_with(payload).await;
832 return Err(error);
833 }
834 };
835 let mut payload = json!({"iteration": iteration, "outcome": "final_answer"});
836 if let Some(u) = usage {
837 payload["usage"] = u.clone();
838 }
839 ctx.end_turn_with(payload).await?;
840 Ok(flow)
841 }
842
843 async fn apply_confirmation(
850 &self,
851 ctx: &DrainCtx,
852 call: &PendingCall,
853 decision: &ConfirmIntent,
854 ) -> Result<(), LoopError> {
855 let result = match decision.decision {
856 ConfirmDecision::Approve => {
857 let tool_call = ToolCall {
858 id: call.call_id.clone(),
859 name: call.tool.clone(),
860 arguments: call.arguments.clone(),
861 };
862 match self.tools.invoke(tool_call).await {
863 Ok(r) => r,
864 Err(e) => ToolResult {
867 call_id: call.call_id.clone(),
868 output: json!({"error": e.to_string()}),
869 is_error: true,
870 redactions: Vec::new(),
871 },
872 }
873 }
874 ConfirmDecision::Reject => ToolResult {
875 call_id: call.call_id.clone(),
876 output: if decision.expired {
877 json!({
878 "error": "confirmation expired",
879 "policy": "ask",
880 "expired": true
881 })
882 } else {
883 match &decision.reason {
884 Some(reason) => json!({
885 "error": "permission denied by user",
886 "policy": "ask",
887 "reason": reason
888 }),
889 None => json!({
890 "error": "permission denied by user",
891 "policy": "ask"
892 }),
893 }
894 },
895 is_error: true,
896 redactions: Vec::new(),
897 },
898 };
899 let payload = tool_result_payload_confirmed(&result, decision);
900 ctx.append(EventKind::ToolResult, payload).await?;
901 Ok(())
902 }
903
904 async fn binding_for(
908 &self,
909 ctx: &DrainCtx,
910 events: &mut Vec<Event>,
911 ) -> Result<SlotBinding, LoopError> {
912 let session = ctx.session();
913 if let Ok(slots) = SessionSlots::replay(session, events)
914 && slots.binding(&self.config.slot).is_ok()
915 {
916 return Ok(slots.binding(&self.config.slot)?.clone());
917 }
918 let fresh = SlotResolver::from_agent_def(&self.agent).bind_session(session);
919 for payload in fresh.binding_payloads() {
920 ctx.append(EventKind::SlotBinding, payload).await?;
921 }
922 *events = ctx.events().await?;
925 Ok(fresh.binding(&self.config.slot)?.clone())
926 }
927
928 async fn provider_turn(
934 &self,
935 ctx: &DrainCtx,
936 binding: &SlotBinding,
937 messages: &[Message],
938 iteration: usize,
939 ) -> TurnResult {
940 let target = binding.target.clone();
941
942 let mut schemas = self.tools.schemas();
945 schemas.sort_by(|a, b| a.name.cmp(&b.name));
946 let chat: Vec<ChatMessage> = messages.iter().filter_map(to_chat_message).collect();
947
948 let body = build_chat_body(&target.model, &chat, &schemas);
951 let step_request = ctx
952 .append(
953 EventKind::StepRequest,
954 json!({
955 "slot": self.config.slot.0,
956 "provider": target.provider,
957 "model": target.model,
958 "iteration": iteration,
959 "body": body,
960 }),
961 )
962 .await;
963 let step_request_seq = match step_request {
964 Ok(ev) => ev.seq,
965 Err(e) => {
966 let fatal = TurnError::fatal(e, self.policy.as_ref());
967 if let TurnError::Fatal { audit, .. } = &fatal {
969 self.observe_fatal(ctx, iteration, 0, audit, 0, 0, None)
970 .await;
971 }
972 return TurnResult {
973 result: Err(fatal),
974 usage: None,
975 };
976 }
977 };
978 self.observe_request(
983 ctx,
984 binding,
985 chat.len(),
986 &schemas,
987 iteration,
988 &body,
989 step_request_seq,
990 )
991 .await;
992
993 let slot = self.config.slot.clone();
996 let build_chat = chat.clone();
997 let build_schemas = schemas.clone();
998 let build = Arc::new(move |t: &kian_core::model::SlotTarget| ModelRequest {
999 slot: slot.clone(),
1000 body: build_chat_body(&t.model, &build_chat, &build_schemas),
1001 });
1002 let mut stream = complete_turn(
1003 Arc::clone(&self.registry),
1004 self.config.slot.clone(),
1005 binding.clone(),
1006 build,
1007 Arc::new(CtxSlotSink { ctx: ctx.clone() }),
1008 );
1009
1010 let mut text = String::new();
1015 let mut reasoning = String::new();
1016 let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
1017 let mut usage: Option<Value> = None;
1018 let mut stream_error: Option<ProviderError> = None;
1019 while let Some(item) = stream.next().await {
1020 match item {
1021 Ok(chunk) => {
1022 if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
1023 usage = Some(u.clone()); }
1025 if !chunk.delta.is_null() {
1026 assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
1027 }
1028 }
1029 Err(e) => {
1030 stream_error = Some(e);
1031 break;
1032 }
1033 }
1034 }
1035 let text_bytes = text.len() as u64;
1038 let reasoning_bytes = reasoning.len() as u64;
1039 if let Some(e) = stream_error {
1040 let class = error_class(&e);
1041 let action = consult_policy(self.policy.as_ref(), class);
1042 let note = action_note(action);
1043 let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
1044 self.observe_recover(ctx, iteration, step_request_seq, &audit)
1047 .await;
1048 self.observe_response(
1049 ctx,
1050 iteration,
1051 step_request_seq,
1052 "soft_failure",
1053 0,
1054 text_bytes,
1055 reasoning_bytes,
1056 usage.as_ref(),
1057 Some(&audit),
1058 )
1059 .await;
1060 return TurnResult {
1061 result: Err(TurnError::Soft {
1062 reason: format!("provider error ({class}): {e}{note}"),
1063 audit,
1064 }),
1065 usage,
1066 };
1067 }
1068 if text.is_empty() && calls.is_empty() {
1069 let action = consult_policy(self.policy.as_ref(), CLASS_EMPTY_RESPONSE);
1072 let note = action_note(action);
1073 let audit = recovery_audit(
1074 self.policy.as_ref(),
1075 kian_orchestrator::recovery::ErrorClass::EmptyResponse,
1076 );
1077 self.observe_recover(ctx, iteration, step_request_seq, &audit)
1078 .await;
1079 self.observe_response(
1080 ctx,
1081 iteration,
1082 step_request_seq,
1083 "soft_failure",
1084 0,
1085 0,
1086 0,
1087 usage.as_ref(),
1088 Some(&audit),
1089 )
1090 .await;
1091 return TurnResult {
1092 result: Err(TurnError::Soft {
1093 reason: format!("empty model response{note}"),
1094 audit,
1095 }),
1096 usage,
1097 };
1098 }
1099
1100 let tool_calls: Vec<ToolCall> = calls.into_values().map(CallAcc::finish).collect();
1101 let mut content = json!({"text": text});
1102 if !tool_calls.is_empty() {
1103 content["tool_calls"] = Value::Array(
1104 tool_calls
1105 .iter()
1106 .map(|c| json!({"id": c.id, "name": c.name, "arguments": c.arguments}))
1107 .collect(),
1108 );
1109 }
1110 if !reasoning.is_empty() {
1111 content["reasoning_content"] = Value::String(reasoning);
1114 }
1115 if let Err(e) = ctx
1116 .append(
1117 EventKind::AssistantMessage,
1118 json!({"role": "assistant", "content": content}),
1119 )
1120 .await
1121 {
1122 let fatal = TurnError::fatal(e, self.policy.as_ref());
1123 if let TurnError::Fatal { audit, .. } = &fatal {
1124 self.observe_fatal(
1125 ctx,
1126 iteration,
1127 step_request_seq,
1128 audit,
1129 text_bytes,
1130 reasoning_bytes,
1131 usage.as_ref(),
1132 )
1133 .await;
1134 }
1135 return TurnResult {
1136 result: Err(fatal),
1137 usage,
1138 };
1139 }
1140
1141 if tool_calls.is_empty() {
1142 self.observe_response(
1144 ctx,
1145 iteration,
1146 step_request_seq,
1147 "final_answer",
1148 0,
1149 text_bytes,
1150 reasoning_bytes,
1151 usage.as_ref(),
1152 None,
1153 )
1154 .await;
1155 return TurnResult {
1156 result: Ok(TurnOutcome::FinalAnswer),
1157 usage,
1158 };
1159 }
1160
1161 let n = tool_calls.len();
1162 for call in tool_calls {
1168 let decision = evaluate_permission(&self.config.permissions, &call.name);
1173 let hook_verdict = self
1185 .consult_tool_pre(ctx, &call, iteration, step_request_seq, decision)
1186 .await;
1187 let appended = match hook_verdict {
1188 kian_plugin::hooks::ToolVerdict::Deny {
1189 ref plugin,
1190 ref reason,
1191 } => {
1192 ctx.append(
1197 EventKind::ToolCall,
1198 tool_call_payload_hook_denied(&call, plugin, reason),
1199 )
1200 .await
1201 }
1202 _ => {
1203 ctx.append(EventKind::ToolCall, tool_call_payload(&call, decision))
1204 .await
1205 }
1206 };
1207 let call_seq = match appended {
1208 Ok(ev) => ev.seq,
1209 Err(e) => {
1210 let fatal = TurnError::fatal(e, self.policy.as_ref());
1211 if let TurnError::Fatal { audit, .. } = &fatal {
1212 self.observe_fatal(
1213 ctx,
1214 iteration,
1215 step_request_seq,
1216 audit,
1217 text_bytes,
1218 reasoning_bytes,
1219 usage.as_ref(),
1220 )
1221 .await;
1222 }
1223 return TurnResult {
1224 result: Err(fatal),
1225 usage,
1226 };
1227 }
1228 };
1229 if let kian_plugin::hooks::ToolVerdict::Deny {
1240 ref plugin,
1241 ref reason,
1242 } = hook_verdict
1243 {
1244 let denied = ToolResult {
1245 call_id: call.id.clone(),
1246 output: json!({
1247 "error": format!("denied by plugin {plugin}: {reason}"),
1248 "policy": "hook"
1249 }),
1250 is_error: true,
1251 redactions: Vec::new(),
1252 };
1253 if let Err(e) = ctx
1254 .append(EventKind::ToolResult, tool_result_payload(&denied))
1255 .await
1256 {
1257 let fatal = TurnError::fatal(e, self.policy.as_ref());
1258 if let TurnError::Fatal { audit, .. } = &fatal {
1259 self.observe_fatal(
1260 ctx,
1261 iteration,
1262 call_seq,
1263 audit,
1264 text_bytes,
1265 reasoning_bytes,
1266 usage.as_ref(),
1267 )
1268 .await;
1269 }
1270 return TurnResult {
1271 result: Err(fatal),
1272 usage,
1273 };
1274 }
1275 self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1276 .await;
1277 continue;
1278 }
1279 if matches!(decision, Some(PermissionDecision::Ask)) {
1283 continue;
1284 }
1285 if let Some(denied) = declared_denial(&call, decision) {
1290 if let Err(e) = ctx
1291 .append(EventKind::ToolResult, tool_result_payload(&denied))
1292 .await
1293 {
1294 let fatal = TurnError::fatal(e, self.policy.as_ref());
1295 if let TurnError::Fatal { audit, .. } = &fatal {
1296 self.observe_fatal(
1297 ctx,
1298 iteration,
1299 call_seq,
1300 audit,
1301 text_bytes,
1302 reasoning_bytes,
1303 usage.as_ref(),
1304 )
1305 .await;
1306 }
1307 return TurnResult {
1308 result: Err(fatal),
1309 usage,
1310 };
1311 }
1312 self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1315 .await;
1316 continue;
1317 }
1318 let result = match self.tools.invoke(call.clone()).await {
1319 Ok(r) => r,
1320 Err(e) => {
1321 ToolResult {
1324 call_id: call.id.clone(),
1325 output: json!({"error": e.to_string()}),
1326 is_error: true,
1327 redactions: Vec::new(),
1328 }
1329 }
1330 };
1331 let result_seq = match ctx
1336 .append(EventKind::ToolResult, tool_result_payload(&result))
1337 .await
1338 {
1339 Ok(ev) => ev.seq,
1340 Err(e) => {
1341 let fatal = TurnError::fatal(e, self.policy.as_ref());
1342 if let TurnError::Fatal { audit, .. } = &fatal {
1343 self.observe_fatal(
1344 ctx,
1345 iteration,
1346 call_seq,
1347 audit,
1348 text_bytes,
1349 reasoning_bytes,
1350 usage.as_ref(),
1351 )
1352 .await;
1353 }
1354 return TurnResult {
1355 result: Err(fatal),
1356 usage,
1357 };
1358 }
1359 };
1360 self.observe_tool_post(ctx, &result, &call.name, result_seq)
1363 .await;
1364 }
1365 self.observe_response(
1368 ctx,
1369 iteration,
1370 step_request_seq,
1371 "tool_calls",
1372 n as u64,
1373 text_bytes,
1374 reasoning_bytes,
1375 usage.as_ref(),
1376 None,
1377 )
1378 .await;
1379 TurnResult {
1380 result: Ok(TurnOutcome::ToolCalls(n)),
1381 usage,
1382 }
1383 }
1384}
1385
1386impl TurnError {
1391 fn fatal(e: EngineError, policy: &dyn RecoveryPolicySource) -> Self {
1396 let error = LoopError::Engine(e);
1397 let audit = recovery_audit(policy, loop_error_class(&error));
1398 Self::Fatal { error, audit }
1399 }
1400}
1401
1402fn loop_error_class(e: &LoopError) -> kian_orchestrator::recovery::ErrorClass {
1408 match e {
1409 LoopError::Engine(_) => kian_orchestrator::recovery::ErrorClass::StoreFailure,
1410 LoopError::Context(_) | LoopError::Slot(_) => {
1411 kian_orchestrator::recovery::ErrorClass::Unknown
1412 }
1413 }
1414}
1415
1416fn provider_error_class(e: &ProviderError) -> kian_orchestrator::recovery::ErrorClass {
1419 kian_orchestrator::recovery::classify(
1420 &kian_orchestrator::recovery::RecoveryError::Provider(e.clone()),
1421 &kian_orchestrator::recovery::ClassifyCtx { attempt: 0 },
1422 )
1423}
1424
1425fn recovery_audit(
1429 policy: &dyn RecoveryPolicySource,
1430 class: kian_orchestrator::recovery::ErrorClass,
1431) -> Value {
1432 let action = consult_policy(policy, class.name());
1433 json!({
1434 "class": class.name(),
1435 "action": action_name(action.as_ref()),
1436 })
1437}
1438
1439fn action_name(action: Option<&RecoveryAction>) -> &'static str {
1442 match action {
1443 None => "none",
1444 Some(RecoveryAction::BackoffRetry { .. }) => "backoff_retry",
1445 Some(RecoveryAction::CompressThenRetry) => "compress_then_retry",
1446 Some(RecoveryAction::Failover) => "failover",
1447 Some(RecoveryAction::InterruptAsk) => "interrupt_ask",
1448 Some(RecoveryAction::Fail) => "fail",
1449 }
1450}
1451
1452struct CtxSlotSink {
1456 ctx: DrainCtx,
1457}
1458
1459impl SlotEventSink for CtxSlotSink {
1460 fn persist_fallback(
1461 &self,
1462 payload: Value,
1463 ) -> futures::future::BoxFuture<'static, Result<(), String>> {
1464 let ctx = self.ctx.clone();
1465 Box::pin(async move {
1466 ctx.append(EventKind::SlotFallback, payload)
1467 .await
1468 .map(|_| ())
1469 .map_err(|e| e.to_string())
1470 })
1471 }
1472}
1473
1474struct CallAcc {
1476 id: String,
1477 name: String,
1478 arguments: String,
1479}
1480
1481impl CallAcc {
1482 fn finish(self) -> ToolCall {
1483 let arguments = serde_json::from_str::<Value>(&self.arguments)
1484 .unwrap_or_else(|_| Value::String(self.arguments.clone()));
1485 ToolCall {
1486 id: self.id,
1487 name: self.name,
1488 arguments,
1489 }
1490 }
1491}
1492
1493fn assemble_delta(
1496 delta: &Value,
1497 text: &mut String,
1498 reasoning: &mut String,
1499 calls: &mut BTreeMap<u64, CallAcc>,
1500) {
1501 if let Some(fragment) = delta.get("content").and_then(Value::as_str) {
1502 text.push_str(fragment);
1503 }
1504 if let Some(fragment) = delta.get("reasoning_content").and_then(Value::as_str) {
1505 reasoning.push_str(fragment);
1506 }
1507 if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) {
1508 for entry in list {
1509 let index = entry.get("index").and_then(Value::as_u64).unwrap_or(0);
1510 let slot = calls.entry(index).or_insert_with(|| CallAcc {
1511 id: String::new(),
1512 name: String::new(),
1513 arguments: String::new(),
1514 });
1515 if let Some(id) = entry.get("id").and_then(Value::as_str) {
1516 slot.id = id.to_string();
1517 }
1518 if let Some(name) = entry.pointer("/function/name").and_then(Value::as_str) {
1519 slot.name.push_str(name);
1520 }
1521 if let Some(args) = entry.pointer("/function/arguments").and_then(Value::as_str) {
1522 slot.arguments.push_str(args);
1523 }
1524 }
1525 }
1526}
1527
1528pub fn to_chat_message(m: &Message) -> Option<ChatMessage> {
1553 match m.role.as_str() {
1554 "tool" => Some(tool_result_message(&m.content)),
1555 "assistant" => assistant_message(&m.content),
1556 _ => Some(string_or_compact(&m.role, &m.content)),
1557 }
1558}
1559
1560#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1563pub(crate) enum PermissionDecision {
1564 AllowConfigured,
1566 AllowDefault,
1568 Deny,
1570 Ask,
1573}
1574
1575const PERMISSION_DENY_REASON: &str = "tool_denied_by_policy";
1577
1578fn evaluate_permission(
1588 permissions: &BTreeMap<String, Permission>,
1589 tool: &str,
1590) -> Option<PermissionDecision> {
1591 if permissions.is_empty() {
1592 return None;
1593 }
1594 match permissions.get(tool) {
1595 Some(Permission::Allow) => Some(PermissionDecision::AllowConfigured),
1596 Some(Permission::Deny) => Some(PermissionDecision::Deny),
1597 Some(Permission::Ask) => Some(PermissionDecision::Ask),
1598 None => Some(PermissionDecision::AllowDefault),
1599 }
1600}
1601
1602fn declared_denial(call: &ToolCall, decision: Option<PermissionDecision>) -> Option<ToolResult> {
1607 matches!(decision, Some(PermissionDecision::Deny)).then(|| ToolResult {
1608 call_id: call.id.clone(),
1609 output: json!({
1610 "error": format!("permission denied by policy: {}", call.name),
1611 "policy": "deny"
1612 }),
1613 is_error: true,
1614 redactions: Vec::new(),
1615 })
1616}
1617
1618fn tool_call_payload(call: &ToolCall, decision: Option<PermissionDecision>) -> Value {
1624 let mut payload = json!({
1625 "role": "assistant",
1626 "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
1627 });
1628 if let Some(decision) = decision {
1629 payload["permission"] = match decision {
1630 PermissionDecision::AllowConfigured => json!({
1631 "evaluated": "allow", "policy": "configured", "matched": call.name
1632 }),
1633 PermissionDecision::AllowDefault => json!({
1634 "evaluated": "allow", "policy": "default", "matched": call.name
1635 }),
1636 PermissionDecision::Deny => json!({
1637 "evaluated": "deny",
1638 "policy": "configured",
1639 "matched": call.name,
1640 "reason": PERMISSION_DENY_REASON
1641 }),
1642 PermissionDecision::Ask => json!({
1643 "evaluated": "ask",
1644 "policy": "configured",
1645 "matched": call.name
1646 }),
1647 };
1648 }
1649 payload
1650}
1651
1652fn tool_call_payload_hook_denied(call: &ToolCall, plugin: &str, reason: &str) -> Value {
1660 let mut payload = json!({
1661 "role": "assistant",
1662 "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
1663 });
1664 payload["permission"] = json!({
1665 "evaluated": "deny",
1666 "policy": "hook",
1667 "matched": format!("{plugin}:tool/pre"),
1668 "reason": reason,
1669 });
1670 payload
1671}
1672
1673fn permission_view(
1678 call: &ToolCall,
1679 decision: Option<PermissionDecision>,
1680) -> kian_plugin::hooks::PermissionView {
1681 match decision {
1682 Some(PermissionDecision::AllowConfigured) => kian_plugin::hooks::PermissionView {
1683 evaluated: "allow".to_string(),
1684 policy: "configured".to_string(),
1685 matched: call.name.clone(),
1686 reason: None,
1687 },
1688 Some(PermissionDecision::Deny) => kian_plugin::hooks::PermissionView {
1689 evaluated: "deny".to_string(),
1690 policy: "configured".to_string(),
1691 matched: call.name.clone(),
1692 reason: Some(PERMISSION_DENY_REASON.to_string()),
1693 },
1694 Some(PermissionDecision::Ask) => kian_plugin::hooks::PermissionView {
1695 evaluated: "ask".to_string(),
1696 policy: "configured".to_string(),
1697 matched: call.name.clone(),
1698 reason: None,
1699 },
1700 Some(PermissionDecision::AllowDefault) | None => kian_plugin::hooks::PermissionView {
1701 evaluated: "allow".to_string(),
1702 policy: "default".to_string(),
1703 matched: call.name.clone(),
1704 reason: None,
1705 },
1706 }
1707}
1708
1709fn tool_result_payload(result: &ToolResult) -> Value {
1716 let mut payload = json!({
1717 "role": "tool",
1718 "content": {
1719 "call_id": result.call_id,
1720 "output": result.output,
1721 "is_error": result.is_error
1722 }
1723 });
1724 if !result.redactions.is_empty() {
1725 if let Ok(report) = serde_json::to_value(&result.redactions) {
1728 payload["redactions"] = report;
1729 }
1730 }
1731 payload
1732}
1733
1734fn tool_result_payload_confirmed(result: &ToolResult, decision: &ConfirmIntent) -> Value {
1738 let mut payload = tool_result_payload(result);
1739 let mut provenance = json!({
1740 "call_id": result.call_id,
1741 "decision": decision.decision.as_str(),
1742 "requested_by": decision.requested_by,
1743 "answered_at_ms": decision.answered_at_ms,
1744 });
1745 if decision.expired {
1746 provenance["expired"] = json!(true);
1747 }
1748 payload["confirmation"] = provenance;
1749 payload
1750}
1751
1752fn string_or_compact(role: &str, content: &Value) -> ChatMessage {
1755 let text = match content {
1756 Value::String(s) => s.clone(),
1757 other => serde_json::to_string(other).unwrap_or_default(),
1758 };
1759 ChatMessage {
1760 role: role.to_owned(),
1761 content: Some(text),
1762 tool_call_id: None,
1763 tool_calls: None,
1764 reasoning_content: None,
1765 }
1766}
1767
1768fn tool_result_message(content: &Value) -> ChatMessage {
1772 if let Some(obj) = content.as_object()
1773 && let Some(call_id) = obj.get("call_id").and_then(Value::as_str)
1774 {
1775 let output = obj.get("output").cloned().unwrap_or(Value::Null);
1776 return ChatMessage {
1777 role: "tool".into(),
1778 content: Some(serde_json::to_string(&output).unwrap_or_default()),
1779 tool_call_id: Some(call_id.to_owned()),
1780 tool_calls: None,
1781 reasoning_content: None,
1782 };
1783 }
1784 ChatMessage {
1785 role: "tool".into(),
1786 content: Some(serde_json::to_string(content).unwrap_or_default()),
1787 tool_call_id: Some(String::new()),
1788 tool_calls: None,
1789 reasoning_content: None,
1790 }
1791}
1792
1793fn reasoning_field(obj: &serde_json::Map<String, Value>) -> Option<String> {
1796 obj.get("reasoning_content")
1797 .and_then(Value::as_str)
1798 .filter(|r| !r.is_empty())
1799 .map(str::to_owned)
1800}
1801
1802fn assistant_message(content: &Value) -> Option<ChatMessage> {
1806 let Some(obj) = content.as_object() else {
1807 return Some(string_or_compact("assistant", content));
1808 };
1809 if obj.contains_key("tool_calls") {
1810 let calls: Option<Vec<WireToolCall>> =
1811 obj.get("tool_calls").and_then(Value::as_array).map(|list| {
1812 list.iter()
1813 .filter_map(|tc| {
1814 let id = tc.get("id").and_then(Value::as_str)?;
1815 let name = tc.get("name").and_then(Value::as_str)?;
1816 let arguments = tc.get("arguments").cloned().unwrap_or(Value::Null);
1817 Some(WireToolCall {
1818 id: id.to_owned(),
1819 r#type: "function".into(),
1820 function: WireFunctionCall {
1821 name: name.to_owned(),
1822 arguments: serde_json::to_string(&arguments).unwrap_or_default(),
1823 },
1824 })
1825 })
1826 .collect()
1827 });
1828 return Some(ChatMessage {
1829 role: "assistant".into(),
1830 content: obj
1833 .get("text")
1834 .and_then(Value::as_str)
1835 .filter(|t| !t.is_empty())
1836 .map(str::to_owned),
1837 tool_call_id: None,
1838 tool_calls: calls,
1839 reasoning_content: reasoning_field(obj),
1840 });
1841 }
1842 if obj.contains_key("id") && obj.contains_key("name") && obj.contains_key("arguments") {
1845 return None;
1846 }
1847 if let Some(text) = obj.get("text").and_then(Value::as_str) {
1848 return Some(ChatMessage {
1849 role: "assistant".into(),
1850 content: Some(text.to_owned()),
1851 tool_call_id: None,
1852 tool_calls: None,
1853 reasoning_content: reasoning_field(obj),
1854 });
1855 }
1856 Some(string_or_compact("assistant", content))
1857}
1858
1859fn resident_empty_batch(scope: BudgetScope, taken_empty: bool, last_role: Option<&str>) -> bool {
1864 scope == BudgetScope::PerEpisode && taken_empty && last_role == Some("assistant")
1865}
1866
1867fn error_class(e: &ProviderError) -> &'static str {
1870 match e {
1871 ProviderError::RateLimited => "rate_limited",
1872 ProviderError::ContextOverflow => "context_overflow",
1873 ProviderError::Unavailable(_) | ProviderError::Transport(_) => "provider_down",
1874 ProviderError::EmptyResponse => CLASS_EMPTY_RESPONSE,
1875 ProviderError::InvalidResponse(_) => "validation_failed",
1876 ProviderError::Other(_) => "internal",
1877 }
1878}
1879
1880fn consult_policy(policy: &dyn RecoveryPolicySource, class: &str) -> Option<RecoveryAction> {
1884 policy
1885 .table()
1886 .into_iter()
1887 .find(|rule| rule.class == class)
1888 .map(|rule| rule.action)
1889}
1890
1891fn action_note(action: Option<RecoveryAction>) -> String {
1892 match action {
1893 Some(a) => format!("; recovery policy action: {a:?}"),
1894 None => "; no matching recovery policy rule".into(),
1895 }
1896}
1897
1898#[cfg(test)]
1899mod tests {
1900 use crate::react::{
1901 BudgetScope, CLASS_EMPTY_RESPONSE, ReActConfig, ReActLoop, assemble_delta, consult_policy,
1902 to_chat_message, tool_result_payload,
1903 };
1904 use crate::test_support::{NoopPolicy, NoopTools, agent_def};
1905 use kian_core::context::{Message, derive_model_context};
1906 use kian_core::events::{Event, EventKind};
1907 use kian_core::model::SessionId;
1908 use kian_core::seams::{ToolCall, ToolResult};
1909 use kian_core::secrets::{Redaction, RedactionKind};
1910 use kian_llm::provider::build_chat_body;
1911 use serde_json::json;
1912 use std::collections::BTreeMap;
1913
1914 fn msg(role: &str, content: serde_json::Value) -> Message {
1915 Message {
1916 role: role.into(),
1917 content,
1918 synthetic: false,
1919 }
1920 }
1921
1922 #[test]
1927 fn tool_result_payload_carries_redactions_outside_content() {
1928 let plain = ToolResult {
1929 call_id: "call-1".into(),
1930 output: json!({"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false}),
1931 is_error: false,
1932 redactions: Vec::new(),
1933 };
1934 let payload = tool_result_payload(&plain);
1935 assert_eq!(
1936 payload,
1937 json!({
1938 "role": "tool",
1939 "content": {
1940 "call_id": "call-1",
1941 "output": {"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false},
1942 "is_error": false
1943 }
1944 }),
1945 "no redactions → no key, bytes unchanged"
1946 );
1947
1948 let redacted = ToolResult {
1949 call_id: "call-2".into(),
1950 output: json!({"exit_code": 0, "stdout": "[REDACTED:token]", "stderr": "", "timed_out": false}),
1951 is_error: false,
1952 redactions: vec![Redaction {
1953 kind: RedactionKind::TokenPattern,
1954 name: "ghp_".into(),
1955 count: 1,
1956 }],
1957 };
1958 let payload = tool_result_payload(&redacted);
1959 assert_eq!(
1960 payload["redactions"],
1961 json!([{"kind": "token_pattern", "name": "ghp_", "count": 1}])
1962 );
1963 assert!(payload["content"].get("redactions").is_none());
1966 assert_eq!(payload["content"]["call_id"], json!("call-2"));
1967 }
1968
1969 #[test]
1973 fn redactions_payload_key_never_enters_the_model_context() {
1974 let session = SessionId::new();
1975 let bytes = tool_result_payload(&ToolResult {
1976 call_id: "call-9".into(),
1977 output: json!({"content": "scrubbed"}),
1978 is_error: false,
1979 redactions: vec![Redaction {
1980 kind: RedactionKind::EnvLine,
1981 name: "MY_SERVICE_TOKEN".into(),
1982 count: 2,
1983 }],
1984 });
1985 let with = Event {
1986 seq: 2,
1987 session,
1988 epoch: kian_core::model::Epoch(1),
1989 ts: 1,
1990 kind: EventKind::ToolResult,
1991 bytes: bytes.clone(),
1992 version: 0,
1993 };
1994 let mut without_bytes = bytes.clone();
1995 without_bytes.as_object_mut().unwrap().remove("redactions");
1996 let without = Event {
1997 bytes: without_bytes,
1998 ..with.clone()
1999 };
2000 let base = Event {
2001 seq: 1,
2002 session,
2003 epoch: kian_core::model::Epoch(0),
2004 ts: 0,
2005 kind: EventKind::SessionCreated,
2006 bytes: json!({}),
2007 version: 0,
2008 };
2009 let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
2010 let ctx_without = derive_model_context(&[base, without]).unwrap();
2011 assert_eq!(ctx_with, ctx_without);
2012 assert_eq!(ctx_with.len(), 1);
2013 let chat = to_chat_message(&ctx_with[0]).unwrap();
2015 assert_eq!(chat.role, "tool");
2016 assert_eq!(chat.tool_call_id.as_deref(), Some("call-9"));
2017 assert_eq!(chat.content.as_deref(), Some("{\"content\":\"scrubbed\"}"));
2018 }
2019
2020 #[test]
2025 fn tool_round_trip_projects_to_the_strict_wire_shape() {
2026 let assistant = msg(
2027 "assistant",
2028 json!({
2029 "text": "",
2030 "tool_calls": [
2031 {"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}
2032 ]
2033 }),
2034 );
2035 let chat = to_chat_message(&assistant).unwrap();
2036 assert_eq!(chat.role, "assistant");
2037 assert_eq!(chat.content, None, "empty text serializes as null");
2038 let tc = &chat.tool_calls.as_ref().unwrap()[0];
2039 assert_eq!(tc.id, "call-1");
2040 assert_eq!(tc.r#type, "function");
2041 assert_eq!(tc.function.name, "fs_read");
2042 assert_eq!(tc.function.arguments, "{\"path\":\"a.txt\"}");
2043
2044 let with_text = msg(
2046 "assistant",
2047 json!({"text": "checking", "tool_calls": [
2048 {"id": "call-2", "name": "exec", "arguments": {"argv": ["true"]}}
2049 ]}),
2050 );
2051 let chat = to_chat_message(&with_text).unwrap();
2052 assert_eq!(chat.content.as_deref(), Some("checking"));
2053
2054 let dup = msg(
2056 "assistant",
2057 json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}),
2058 );
2059 assert!(to_chat_message(&dup).is_none());
2060
2061 let result = msg(
2063 "tool",
2064 json!({"call_id": "call-1", "output": {"content": "x"}, "is_error": false}),
2065 );
2066 let chat = to_chat_message(&result).unwrap();
2067 assert_eq!(chat.role, "tool");
2068 assert_eq!(chat.tool_call_id.as_deref(), Some("call-1"));
2069 assert_eq!(chat.content.as_deref(), Some("{\"content\":\"x\"}"));
2070 assert!(chat.tool_calls.is_none());
2071 }
2072
2073 #[test]
2077 fn plain_messages_keep_the_v1_shape() {
2078 let user = msg("user", json!("hello"));
2079 let chat = to_chat_message(&user).unwrap();
2080 assert_eq!(chat.role, "user");
2081 assert_eq!(chat.content.as_deref(), Some("hello"));
2082 assert!(chat.tool_call_id.is_none() && chat.tool_calls.is_none());
2083
2084 let bare = msg("assistant", json!({"text": "hi"}));
2085 assert_eq!(
2086 to_chat_message(&bare).unwrap().content.as_deref(),
2087 Some("hi")
2088 );
2089
2090 let foreign = msg("tool", json!({"odd": true}));
2093 let chat = to_chat_message(&foreign).unwrap();
2094 assert_eq!(chat.tool_call_id.as_deref(), Some(""));
2095 }
2096
2097 #[test]
2105 fn permission_evaluation_covers_absent_default_and_configured() {
2106 use crate::react::{PermissionDecision, evaluate_permission};
2107 use kian_core::model::Permission;
2108
2109 let empty: BTreeMap<String, Permission> = BTreeMap::new();
2110 assert_eq!(evaluate_permission(&empty, "fs_write"), None);
2111
2112 let table: BTreeMap<String, Permission> = BTreeMap::from([
2113 ("fs_read".to_string(), Permission::Allow),
2114 ("fs_write".to_string(), Permission::Deny),
2115 ]);
2116 assert_eq!(
2117 evaluate_permission(&table, "fs_read"),
2118 Some(PermissionDecision::AllowConfigured)
2119 );
2120 assert_eq!(
2121 evaluate_permission(&table, "fs_write"),
2122 Some(PermissionDecision::Deny)
2123 );
2124 assert_eq!(
2127 evaluate_permission(&table, "exec"),
2128 Some(PermissionDecision::AllowDefault)
2129 );
2130 }
2131
2132 #[test]
2136 fn tool_call_payload_carries_permission_provenance_outside_content() {
2137 use crate::react::{evaluate_permission, tool_call_payload};
2138 use kian_core::model::Permission;
2139
2140 let call = ToolCall {
2141 id: "call-7".into(),
2142 name: "fs_write".into(),
2143 arguments: json!({"path": "a.txt"}),
2144 };
2145
2146 let empty: BTreeMap<String, Permission> = BTreeMap::new();
2148 let legacy = tool_call_payload(&call, evaluate_permission(&empty, &call.name));
2149 assert_eq!(
2150 legacy,
2151 json!({
2152 "role": "assistant",
2153 "content": {"id": "call-7", "name": "fs_write", "arguments": {"path": "a.txt"}}
2154 })
2155 );
2156
2157 let table: BTreeMap<String, Permission> =
2159 BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
2160 let allowed = tool_call_payload(&call, evaluate_permission(&table, &call.name)); assert_eq!(
2162 allowed["permission"],
2163 json!({"evaluated": "allow", "policy": "default", "matched": "fs_write"})
2164 );
2165 assert_eq!(allowed["content"], legacy["content"]);
2166
2167 let table: BTreeMap<String, Permission> =
2169 BTreeMap::from([("fs_write".to_string(), Permission::Deny)]);
2170 let denied = tool_call_payload(&call, evaluate_permission(&table, &call.name));
2171 assert_eq!(
2172 denied["permission"],
2173 json!({
2174 "evaluated": "deny",
2175 "policy": "configured",
2176 "matched": "fs_write",
2177 "reason": "tool_denied_by_policy"
2178 })
2179 );
2180 assert_eq!(denied["content"], legacy["content"]);
2181 }
2182
2183 #[test]
2194 fn hook_denied_permission_payload_goldens_are_frozen_bytes() {
2195 use crate::react::{evaluate_permission, tool_call_payload, tool_call_payload_hook_denied};
2196 use kian_core::model::Permission;
2197
2198 let call = ToolCall {
2199 id: "call-7".into(),
2200 name: "exec".into(),
2201 arguments: json!({"cmd": ["ls"]}),
2202 };
2203
2204 let hook_denied =
2206 tool_call_payload_hook_denied(&call, "approval-gate", "exec not on the allowlist");
2207 assert_eq!(
2208 serde_json::to_string(&hook_denied).unwrap(),
2209 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2210 \"permission\":{\"evaluated\":\"deny\",\"matched\":\"approval-gate:tool/pre\",\
2211 \"policy\":\"hook\",\"reason\":\"exec not on the allowlist\"},\"role\":\"assistant\"}"
2212 );
2213
2214 let denied_result = ToolResult {
2218 call_id: call.id.clone(),
2219 output: json!({
2220 "error": "denied by plugin approval-gate: exec not on the allowlist",
2221 "policy": "hook"
2222 }),
2223 is_error: true,
2224 redactions: Vec::new(),
2225 };
2226 assert_eq!(
2227 serde_json::to_string(&tool_result_payload(&denied_result)).unwrap(),
2228 "{\"content\":{\"call_id\":\"call-7\",\"is_error\":true,\
2229 \"output\":{\"error\":\"denied by plugin approval-gate: exec not on the allowlist\",\
2230 \"policy\":\"hook\"}},\"role\":\"tool\"}"
2231 );
2232
2233 let empty: BTreeMap<String, Permission> = BTreeMap::new();
2237 assert_eq!(
2238 serde_json::to_string(&tool_call_payload(
2239 &call,
2240 evaluate_permission(&empty, &call.name)
2241 ))
2242 .unwrap(),
2243 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2244 \"role\":\"assistant\"}"
2245 );
2246 let default_table = BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
2247 assert_eq!(
2248 serde_json::to_string(&tool_call_payload(
2249 &call,
2250 evaluate_permission(&default_table, &call.name)
2251 ))
2252 .unwrap(),
2253 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2254 \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"default\"},\
2255 \"role\":\"assistant\"}"
2256 );
2257 let allow_table = BTreeMap::from([("exec".to_string(), Permission::Allow)]);
2258 assert_eq!(
2259 serde_json::to_string(&tool_call_payload(
2260 &call,
2261 evaluate_permission(&allow_table, &call.name)
2262 ))
2263 .unwrap(),
2264 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2265 \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"configured\"},\
2266 \"role\":\"assistant\"}"
2267 );
2268 let deny_table = BTreeMap::from([("exec".to_string(), Permission::Deny)]);
2269 assert_eq!(
2270 serde_json::to_string(&tool_call_payload(
2271 &call,
2272 evaluate_permission(&deny_table, &call.name)
2273 ))
2274 .unwrap(),
2275 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2276 \"permission\":{\"evaluated\":\"deny\",\"matched\":\"exec\",\"policy\":\"configured\",\
2277 \"reason\":\"tool_denied_by_policy\"},\"role\":\"assistant\"}"
2278 );
2279 }
2280
2281 #[test]
2286 fn permission_payload_key_never_enters_the_model_context() {
2287 use crate::react::{PermissionDecision, tool_call_payload};
2288 use kian_core::seams::ToolCall;
2289
2290 let session = SessionId::new();
2291 let call = ToolCall {
2292 id: "call-1".into(),
2293 name: "fs_read".into(),
2294 arguments: json!({"path": "a.txt"}),
2295 };
2296 let with_bytes = tool_call_payload(&call, Some(PermissionDecision::Deny));
2297 let mut without_bytes = with_bytes.clone();
2298 without_bytes.as_object_mut().unwrap().remove("permission");
2299 let with = Event {
2300 seq: 2,
2301 session,
2302 epoch: kian_core::model::Epoch(1),
2303 ts: 1,
2304 kind: EventKind::ToolCall,
2305 bytes: with_bytes,
2306 version: 0,
2307 };
2308 let without = Event {
2309 bytes: without_bytes,
2310 ..with.clone()
2311 };
2312 let base = Event {
2313 seq: 1,
2314 session,
2315 epoch: kian_core::model::Epoch(0),
2316 ts: 0,
2317 kind: EventKind::SessionCreated,
2318 bytes: json!({}),
2319 version: 0,
2320 };
2321 let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
2322 let ctx_without = derive_model_context(&[base, without]).unwrap();
2323 assert_eq!(ctx_with, ctx_without);
2324 assert_eq!(ctx_with.len(), 1);
2325 assert_eq!(ctx_with[0].role, "assistant");
2328 assert_eq!(
2329 ctx_with[0].content,
2330 json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}})
2331 );
2332 assert!(!ctx_with[0].synthetic);
2333 }
2334
2335 #[test]
2342 fn resident_empty_batch_is_skipped_only_for_resident_assistant_tails() {
2343 use super::resident_empty_batch;
2344 assert!(resident_empty_batch(
2345 BudgetScope::PerEpisode,
2346 true,
2347 Some("assistant")
2348 ));
2349 assert!(!resident_empty_batch(
2350 BudgetScope::PerEpisode,
2351 false,
2352 Some("assistant")
2353 ));
2354 assert!(!resident_empty_batch(
2355 BudgetScope::PerEpisode,
2356 true,
2357 Some("tool")
2358 ));
2359 assert!(!resident_empty_batch(
2360 BudgetScope::PerEpisode,
2361 true,
2362 Some("user")
2363 ));
2364 assert!(!resident_empty_batch(
2365 BudgetScope::Lifetime,
2366 true,
2367 Some("assistant")
2368 ));
2369 }
2370
2371 #[test]
2372 fn budget_scope_selects_lifetime_or_episode_counter() {
2373 assert_eq!(BudgetScope::Lifetime.used(9, 0), 9);
2374 assert_eq!(BudgetScope::Lifetime.used(0, 9), 0);
2375 assert_eq!(BudgetScope::PerEpisode.used(9, 2), 2);
2376 assert_eq!(BudgetScope::PerEpisode.used(0, 0), 0);
2377 }
2378
2379 #[test]
2380 fn delta_assembly_concatenates_content_fragments() {
2381 let mut text = String::new();
2382 let mut reasoning = String::new();
2383 let mut calls = Default::default();
2384 for fragment in ["Hello", ", ", "kian"] {
2385 assemble_delta(
2386 &serde_json::json!({"content": fragment}),
2387 &mut text,
2388 &mut reasoning,
2389 &mut calls,
2390 );
2391 }
2392 assert_eq!(text, "Hello, kian");
2393 assert!(calls.is_empty());
2394 }
2395
2396 #[test]
2400 fn reasoning_fragments_are_persisted_and_replayed() {
2401 let mut text = String::new();
2402 let mut reasoning = String::new();
2403 let mut calls = Default::default();
2404 assemble_delta(
2405 &json!({"reasoning_content": "think "}),
2406 &mut text,
2407 &mut reasoning,
2408 &mut calls,
2409 );
2410 assemble_delta(
2411 &json!({"reasoning_content": "harder"}),
2412 &mut text,
2413 &mut reasoning,
2414 &mut calls,
2415 );
2416 assemble_delta(
2417 &json!({"content": "answer"}),
2418 &mut text,
2419 &mut reasoning,
2420 &mut calls,
2421 );
2422 assert_eq!(reasoning, "think harder");
2423 assert_eq!(text, "answer");
2424
2425 let with = to_chat_message(&msg(
2426 "assistant",
2427 json!({"text": text, "reasoning_content": reasoning}),
2428 ))
2429 .unwrap();
2430 assert_eq!(with.reasoning_content.as_deref(), Some("think harder"));
2431 let body = build_chat_body("m", &[with], &[]);
2432 assert_eq!(body["messages"][0]["reasoning_content"], "think harder");
2433
2434 let legacy = to_chat_message(&msg("assistant", json!({"text": "answer"}))).unwrap();
2435 assert!(legacy.reasoning_content.is_none());
2436 let body = build_chat_body("m", &[legacy], &[]);
2437 assert!(body["messages"][0].get("reasoning_content").is_none());
2438 }
2439
2440 #[test]
2441 fn delta_assembly_accumulates_tool_call_fragments_by_index() {
2442 let mut text = String::new();
2443 let mut reasoning = String::new();
2444 let mut calls = Default::default();
2445 assemble_delta(
2446 &serde_json::json!({"tool_calls": [
2447 {"index": 0, "id": "call-1", "function": {"name": "fs.read"}}
2448 ]}),
2449 &mut text,
2450 &mut reasoning,
2451 &mut calls,
2452 );
2453 assemble_delta(
2454 &serde_json::json!({"tool_calls": [
2455 {"index": 0, "function": {"arguments": "{\"pa"}}
2456 ]}),
2457 &mut text,
2458 &mut reasoning,
2459 &mut calls,
2460 );
2461 assemble_delta(
2462 &serde_json::json!({"tool_calls": [
2463 {"index": 0, "function": {"arguments": "th\": \"a.txt\"}"}}
2464 ]}),
2465 &mut text,
2466 &mut reasoning,
2467 &mut calls,
2468 );
2469 let finished: Vec<_> = calls.into_values().map(|c| c.finish()).collect();
2470 assert_eq!(finished.len(), 1);
2471 assert_eq!(finished[0].id, "call-1");
2472 assert_eq!(finished[0].name, "fs.read");
2473 assert_eq!(finished[0].arguments, serde_json::json!({"path": "a.txt"}));
2474 }
2475
2476 #[test]
2477 fn policy_consult_matches_rule_by_class() {
2478 use kian_core::seams::{PolicyRule, RecoveryAction, RecoveryPolicySource};
2479
2480 struct Table(Vec<PolicyRule>);
2481 impl RecoveryPolicySource for Table {
2482 fn table(&self) -> Vec<PolicyRule> {
2483 self.0.clone()
2484 }
2485 }
2486 let table = Table(vec![
2487 PolicyRule {
2488 class: "rate_limited".into(),
2489 action: RecoveryAction::BackoffRetry { delay_ms: 100 },
2490 },
2491 PolicyRule {
2492 class: CLASS_EMPTY_RESPONSE.into(),
2493 action: RecoveryAction::InterruptAsk,
2494 },
2495 ]);
2496 assert_eq!(
2497 consult_policy(&table, "rate_limited"),
2498 Some(RecoveryAction::BackoffRetry { delay_ms: 100 })
2499 );
2500 assert_eq!(
2501 consult_policy(&table, CLASS_EMPTY_RESPONSE),
2502 Some(RecoveryAction::InterruptAsk)
2503 );
2504 assert_eq!(consult_policy(&table, "no_such_class"), None);
2505 }
2506
2507 #[test]
2514 fn recovery_audit_carries_class_and_policy_action() {
2515 use kian_core::seams::{PolicyRule, RecoveryPolicySource};
2516 use kian_orchestrator::recovery::ErrorClass;
2517 use serde_json::json;
2518
2519 struct Table(Vec<PolicyRule>);
2520 impl RecoveryPolicySource for Table {
2521 fn table(&self) -> Vec<PolicyRule> {
2522 self.0.clone()
2523 }
2524 }
2525 let with_rule = Table(vec![PolicyRule {
2526 class: "store_failure".into(),
2527 action: kian_core::seams::RecoveryAction::Fail,
2528 }]);
2529 assert_eq!(
2530 super::recovery_audit(&with_rule, ErrorClass::StoreFailure),
2531 json!({"class": "store_failure", "action": "fail"})
2532 );
2533 assert_eq!(
2534 super::recovery_audit(&with_rule, ErrorClass::EmptyResponse),
2535 json!({"class": "empty_response", "action": "none"}),
2536 "no covering rule → the honest none spelling"
2537 );
2538
2539 assert_eq!(
2541 super::provider_error_class(&kian_core::seams::ProviderError::RateLimited),
2542 ErrorClass::RateLimited
2543 );
2544 assert_eq!(
2545 super::provider_error_class(&kian_core::seams::ProviderError::Unavailable(
2546 "upstream 503".into()
2547 )),
2548 ErrorClass::ProviderDown
2549 );
2550
2551 assert_eq!(
2553 super::loop_error_class(&super::LoopError::Engine(
2554 kian_orchestrator::EngineError::NotAtSafeBoundary {
2555 session: kian_core::model::SessionId::new(),
2556 }
2557 )),
2558 ErrorClass::StoreFailure
2559 );
2560 assert_eq!(
2561 super::loop_error_class(&super::LoopError::Slot(
2562 kian_llm::slots::SlotError::UnknownSlot("aux".into())
2563 )),
2564 ErrorClass::Unknown
2565 );
2566 }
2567
2568 #[test]
2569 fn react_config_defaults_are_sane() {
2570 let cfg = ReActConfig::default();
2571 assert_eq!(cfg.slot.0, "main");
2572 assert!(cfg.max_iterations >= 1);
2573 let react = ReActLoop::new(
2575 agent_def(),
2576 std::sync::Arc::new(kian_llm::ProviderRegistry::new()),
2577 std::sync::Arc::new(NoopTools),
2578 std::sync::Arc::new(NoopPolicy),
2579 );
2580 assert_eq!(react.config().slot.0, "main");
2581 }
2582}