1use std::collections::BTreeMap;
52use std::sync::Arc;
53
54use futures::stream::{BoxStream, StreamExt};
55use kian_core::budget::project_budget;
56use kian_core::confirmation::{PendingCall, confirmable, confirmations, pending_calls};
57use kian_core::context::{Message, context_provenance, derive_model_context};
58use kian_core::control::{ConfirmDecision, ConfirmIntent};
59use kian_core::events::{Event, EventKind};
60use kian_core::model::{AgentDef, ModelProfile, Permission, SlotName};
61use kian_core::seams::{
62 LoopDriver, LoopOutcome, ModelRequest, ProviderError, RecoveryAction, RecoveryPolicySource,
63 ToolCall, ToolProvider, ToolResult,
64};
65use kian_llm::plan::build_request_plan;
66use kian_llm::provider::{ChatImage, ChatMessage, WireFunctionCall, WireToolCall};
67use kian_llm::slots::{SessionSlots, SlotBinding, SlotError, SlotResolver};
68use kian_llm::turn::{ProviderRegistry, SlotEventSink, complete_turn};
69use kian_orchestrator::compaction::{
70 CompactionPlan, CompactionPressure, CompactionSettings, CompactionTrigger,
71 estimate_context_tokens, plan_compaction,
72};
73use kian_orchestrator::{DrainCtx, EngineError};
74use serde_json::{Value, json};
75
76use crate::evidence::{
77 BUILTIN_GATE_NAME, EvidenceGateConfig, evaluate_evidence_gate, verdict_payload,
78};
79
80pub const CLASS_EMPTY_RESPONSE: &str = "empty_response";
82
83pub const DEFAULT_MAX_ITERATIONS: usize = 32;
85
86const MAX_COMPACTIONS_PER_EPISODE: usize = 2;
90
91const DEFAULT_OUTPUT_RESERVE_TOKENS: u64 = 4_096;
94
95const MAX_IMAGES_PER_MESSAGE: usize = 4;
97
98const MAX_VISION_IMAGE_BYTES: usize = 8 * 1024 * 1024;
100
101const MAX_TRANSCRIPT_CHARS: usize = 120_000;
105
106const SUMMARY_SYSTEM_PROMPT: &str = "You summarize conversation history for an execution runtime. Preserve the user's goals and constraints, decisions and their reasons, exact file paths/commands/identifiers, tool results that matter, and unresolved TODOs or failures. Reply with the summary only, in English.";
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
112pub enum BudgetScope {
113 #[default]
117 Lifetime,
118 PerEpisode,
122}
123
124impl BudgetScope {
125 #[must_use]
127 fn used(self, lifetime_iteration: usize, episode_iterations: usize) -> usize {
128 match self {
129 Self::Lifetime => lifetime_iteration,
130 Self::PerEpisode => episode_iterations,
131 }
132 }
133}
134
135#[derive(Debug, Clone)]
141pub struct ReActConfig {
142 pub slot: SlotName,
145 pub max_iterations: usize,
150 pub budget_scope: BudgetScope,
152 pub permissions: BTreeMap<String, Permission>,
158}
159
160impl Default for ReActConfig {
161 fn default() -> Self {
162 Self {
163 slot: SlotName("main".into()),
164 max_iterations: DEFAULT_MAX_ITERATIONS,
165 budget_scope: BudgetScope::Lifetime,
166 permissions: BTreeMap::new(),
167 }
168 }
169}
170
171#[derive(Clone)]
172struct Inner {
173 registry: Arc<ProviderRegistry>,
174 tools: Arc<dyn ToolProvider>,
175 policy: Arc<dyn RecoveryPolicySource>,
176 agent: AgentDef,
177 config: ReActConfig,
178 gate: EvidenceGateConfig,
181 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
185 set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
192 compaction: CompactionSettings,
195}
196
197#[derive(Clone)]
199pub struct ReActLoop(Arc<Inner>);
200
201impl ReActLoop {
202 pub fn new(
206 agent: AgentDef,
207 registry: Arc<ProviderRegistry>,
208 tools: Arc<dyn ToolProvider>,
209 policy: Arc<dyn RecoveryPolicySource>,
210 ) -> Self {
211 Self::with_config(agent, registry, tools, policy, ReActConfig::default())
212 }
213
214 pub fn with_config(
217 agent: AgentDef,
218 registry: Arc<ProviderRegistry>,
219 tools: Arc<dyn ToolProvider>,
220 policy: Arc<dyn RecoveryPolicySource>,
221 config: ReActConfig,
222 ) -> Self {
223 Self::with_evidence_gate(
224 agent,
225 registry,
226 tools,
227 policy,
228 config,
229 EvidenceGateConfig::default(),
230 )
231 }
232
233 pub fn with_evidence_gate(
237 agent: AgentDef,
238 registry: Arc<ProviderRegistry>,
239 tools: Arc<dyn ToolProvider>,
240 policy: Arc<dyn RecoveryPolicySource>,
241 config: ReActConfig,
242 gate: EvidenceGateConfig,
243 ) -> Self {
244 Self::with_hooks(agent, registry, tools, policy, config, gate, None)
245 }
246
247 pub fn with_hooks(
253 agent: AgentDef,
254 registry: Arc<ProviderRegistry>,
255 tools: Arc<dyn ToolProvider>,
256 policy: Arc<dyn RecoveryPolicySource>,
257 config: ReActConfig,
258 gate: EvidenceGateConfig,
259 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
260 ) -> Self {
261 Self::with_hooks_and_guard(agent, registry, tools, policy, config, gate, hooks, None)
262 }
263
264 #[allow(clippy::too_many_arguments)]
273 pub fn with_hooks_and_guard(
274 agent: AgentDef,
275 registry: Arc<ProviderRegistry>,
276 tools: Arc<dyn ToolProvider>,
277 policy: Arc<dyn RecoveryPolicySource>,
278 config: ReActConfig,
279 gate: EvidenceGateConfig,
280 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
281 set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
282 ) -> Self {
283 Self(Arc::new(Inner {
284 registry,
285 tools,
286 policy,
287 agent,
288 config,
289 gate,
290 hooks,
291 set_guard,
292 compaction: CompactionSettings::default(),
293 }))
294 }
295
296 #[must_use]
300 pub fn with_compaction(self, compaction: CompactionSettings) -> Self {
301 let mut inner = (*self.0).clone();
302 inner.compaction = compaction.normalized();
303 Self(Arc::new(inner))
304 }
305
306 #[must_use]
308 pub fn compaction_settings(&self) -> CompactionSettings {
309 self.0.compaction
310 }
311
312 #[must_use]
313 pub fn config(&self) -> &ReActConfig {
314 &self.0.config
315 }
316
317 #[must_use]
321 pub fn evidence_gate(&self) -> &EvidenceGateConfig {
322 &self.0.gate
323 }
324}
325
326struct LoopState {
335 ctx: DrainCtx,
336 done: bool,
337 begun: bool,
338 drain_iterations: usize,
341 compactions: usize,
344}
345
346impl LoopDriver for ReActLoop {
347 type Ctx = DrainCtx;
348
349 fn drive(&self, ctx: DrainCtx) -> BoxStream<'static, LoopOutcome> {
350 let inner = Arc::clone(&self.0);
351 futures::stream::unfold(
352 LoopState {
353 ctx,
354 done: false,
355 begun: false,
356 drain_iterations: 0,
357 compactions: 0,
358 },
359 move |mut st| {
360 let inner = Arc::clone(&inner);
361 async move {
362 if st.done {
363 return None;
364 }
365 if !st.begun {
376 st.begun = true;
377 if let Some(guard) = inner.set_guard.as_ref() {
378 let worker = match st.ctx.events().await {
379 Ok(events) => kian_plugin::hooks::durable_worker_binding(
380 &events,
381 &st.ctx.session(),
382 )
383 .unwrap_or_default(),
384 Err(_) => String::new(),
388 };
389 guard.session_begin(kian_plugin::hooks::FrameInfo {
390 session: st.ctx.session(),
391 worker,
392 seq: 0,
393 epoch: Some(st.ctx.epoch().0),
394 });
395 }
396 }
397 let outcome = match inner
398 .iteration(&st.ctx, &mut st.drain_iterations, &mut st.compactions)
399 .await
400 {
401 Flow::TurnDone => LoopOutcome::TurnDone,
402 Flow::Settled | Flow::Deferred => LoopOutcome::Settled,
403 Flow::Stopped(reason) => LoopOutcome::Stopped { reason },
404 Flow::AwaitingBudget(budget) => LoopOutcome::AwaitingBudget { budget },
405 Flow::Soft(reason) => LoopOutcome::SoftFailed { reason },
406 };
407 if !matches!(outcome, LoopOutcome::TurnDone) {
408 st.done = true;
409 }
410 Some((outcome, st))
411 }
412 },
413 )
414 .boxed()
415 }
416}
417
418enum Flow {
420 TurnDone,
422 Settled,
424 Deferred,
429 Stopped(String),
431 AwaitingBudget(Value),
434 Soft(String),
436}
437
438enum TurnOutcome {
439 FinalAnswer,
440 ToolCalls(usize),
441}
442
443struct TurnResult {
448 result: Result<TurnOutcome, TurnError>,
449 usage: Option<Value>,
450}
451
452enum TurnError {
453 Soft { reason: String, audit: Value },
457 Fatal { error: LoopError, audit: Value },
460 AwaitingBudget { budget: Value },
463}
464
465#[derive(Debug, thiserror::Error)]
469pub enum LoopError {
470 #[error("engine: {0}")]
471 Engine(#[from] EngineError),
472 #[error("context projection: {0}")]
473 Context(#[from] kian_core::context::ContextError),
474 #[error("slots: {0}")]
475 Slot(#[from] SlotError),
476}
477
478impl Inner {
479 async fn iteration(
481 &self,
482 ctx: &DrainCtx,
483 drain_iterations: &mut usize,
484 compactions: &mut usize,
485 ) -> Flow {
486 let flow = match self.run_iteration(ctx, drain_iterations, compactions).await {
487 Ok(flow) => flow,
488 Err(e) => return Flow::Soft(format!("loop error: {e}")),
489 };
490 match flow {
493 Flow::Settled | Flow::Stopped(_) => self.apply_evidence_gate(ctx, flow).await,
494 other => other,
495 }
496 }
497
498 async fn apply_evidence_gate(&self, ctx: &DrainCtx, flow: Flow) -> Flow {
511 if !self.gate.enabled {
512 return flow;
513 }
514 let events = match ctx.events().await {
515 Ok(events) => events,
516 Err(e) => {
517 return Flow::Soft(format!("evidence gate: stream read failed: {e}"));
518 }
519 };
520 let verdict = evaluate_evidence_gate(BUILTIN_GATE_NAME, &self.gate.checks, &events);
521 let payload = verdict_payload(BUILTIN_GATE_NAME, &verdict);
522 if let Err(e) = ctx.append(EventKind::EvidenceVerdict, payload).await {
523 return Flow::Soft(format!("evidence gate: verdict append failed: {e}"));
524 }
525 if verdict.passed {
526 self.gate.counters.record_passed();
527 flow
528 } else {
529 self.gate.counters.record_failed();
530 if verdict.attempt < self.gate.max_retries {
531 Flow::TurnDone
532 } else {
533 Flow::Soft(format!(
534 "evidence gate `{BUILTIN_GATE_NAME}` failed after {} attempt(s)",
535 verdict.attempt + 1
536 ))
537 }
538 }
539 }
540
541 async fn hook_frame(ctx: &DrainCtx, seq: u64) -> Option<kian_plugin::hooks::FrameInfo> {
558 let worker = match ctx.events().await {
559 Ok(events) => kian_plugin::hooks::durable_worker_binding(&events, &ctx.session())
560 .unwrap_or_default(),
561 Err(_) => String::new(),
564 };
565 Some(kian_plugin::hooks::FrameInfo {
566 session: ctx.session(),
567 worker,
568 seq,
569 epoch: Some(ctx.epoch().0),
570 })
571 }
572
573 #[allow(clippy::too_many_arguments)]
579 async fn observe_request(
580 &self,
581 ctx: &DrainCtx,
582 binding: &SlotBinding,
583 chat_len: usize,
584 schemas: &[kian_core::seams::ToolSchema],
585 iteration: usize,
586 body: &Value,
587 step_request_seq: u64,
588 ) {
589 use kian_plugin::hooks::{RequestMeta, serialized, sha256_hex};
590 let Some(hooks) = self.hooks.as_ref() else {
591 return;
592 };
593 let bytes = serialized(body);
594 let meta = RequestMeta {
595 slot: self.config.slot.0.clone(),
596 provider: binding.target.provider.clone(),
597 model: binding.target.model.clone(),
598 iteration: iteration as u64,
599 request_bytes: bytes.len() as u64,
600 request_sha256: sha256_hex(&bytes),
601 message_count: chat_len as u64,
602 tool_names: schemas.iter().map(|s| s.name.clone()).collect(),
603 tool_schema_sha256: sha256_hex(&serialized(&Value::Array(
604 schemas
605 .iter()
606 .map(|s| serde_json::to_value(s).unwrap_or(Value::Null))
607 .collect(),
608 ))),
609 timing: "pre_send".to_string(),
610 step_request_seq,
611 frame: Self::hook_frame(ctx, step_request_seq).await,
612 };
613 hooks.request(&meta).await;
614 }
615
616 #[allow(clippy::too_many_arguments)] async fn observe_response(
622 &self,
623 ctx: &DrainCtx,
624 iteration: usize,
625 seq: u64,
626 outcome: &str,
627 tool_calls: u64,
628 text_bytes: u64,
629 reasoning_bytes: u64,
630 usage: Option<&Value>,
631 error_audit: Option<&Value>,
632 ) {
633 use kian_plugin::hooks::{ResponseView, TurnErrorAudit};
634 let Some(hooks) = self.hooks.as_ref() else {
635 return;
636 };
637 let error = error_audit.and_then(|audit| {
638 Some(TurnErrorAudit {
639 class: audit.get("class")?.as_str()?.to_string(),
640 action: audit.get("action")?.as_str()?.to_string(),
641 })
642 });
643 let view = ResponseView {
644 iteration: iteration as u64,
645 outcome: outcome.to_string(),
646 tool_calls,
647 text_bytes,
648 reasoning_bytes,
649 usage: usage.cloned().unwrap_or(Value::Null),
650 error,
651 timing: "settled".to_string(),
652 frame: Self::hook_frame(ctx, seq).await,
653 };
654 hooks.response(&view).await;
655 }
656
657 async fn consult_tool_pre(
663 &self,
664 ctx: &DrainCtx,
665 call: &ToolCall,
666 iteration: usize,
667 seq: u64,
668 decision: Option<PermissionDecision>,
669 ) -> kian_plugin::hooks::ToolVerdict {
670 use kian_plugin::hooks::{ToolCallView, bounded_value, serialized, sha256_hex};
671 let Some(hooks) = self.hooks.as_ref() else {
672 return kian_plugin::hooks::ToolVerdict::Allow;
673 };
674 let bytes = serialized(&call.arguments);
675 let (arguments, arguments_truncated) = bounded_value(&call.arguments);
676 let view = ToolCallView {
677 call_id: call.id.clone(),
678 name: call.name.clone(),
679 iteration: iteration as u64,
680 arguments,
681 arguments_bytes: bytes.len() as u64,
682 arguments_sha256: sha256_hex(&bytes),
683 arguments_truncated,
684 permission: permission_view(call, decision),
685 surface: "react".to_string(),
686 frame: Self::hook_frame(ctx, seq).await,
687 };
688 hooks.tool_pre(&view).await
689 }
690
691 async fn observe_tool_post(&self, ctx: &DrainCtx, result: &ToolResult, name: &str, seq: u64) {
695 use kian_plugin::hooks::{RedactionReport, ToolPostView, serialized, sha256_hex};
696 let Some(hooks) = self.hooks.as_ref() else {
697 return;
698 };
699 let bytes = serialized(&result.output);
700 let view = ToolPostView {
701 call_id: result.call_id.clone(),
702 name: name.to_string(),
703 is_error: result.is_error,
704 output_bytes: bytes.len() as u64,
705 output_sha256: sha256_hex(&bytes),
706 redactions: result
707 .redactions
708 .iter()
709 .map(|r| RedactionReport {
710 kind: serde_json::to_value(r.kind)
711 .ok()
712 .and_then(|v| v.as_str().map(str::to_string))
713 .unwrap_or_default(),
714 name: r.name.clone(),
715 count: r.count,
716 })
717 .collect(),
718 frame: Self::hook_frame(ctx, seq).await,
719 };
720 hooks.tool_post(&view).await;
721 }
722
723 async fn observe_recover(&self, ctx: &DrainCtx, iteration: usize, seq: u64, audit: &Value) {
727 let Some(hooks) = self.hooks.as_ref() else {
728 return;
729 };
730 let view = kian_plugin::hooks::RecoveryView {
731 error_class: audit
732 .get("class")
733 .and_then(Value::as_str)
734 .unwrap_or_default()
735 .to_string(),
736 action: audit
737 .get("action")
738 .and_then(Value::as_str)
739 .unwrap_or("none")
740 .to_string(),
741 iteration: iteration as u64,
742 frame: Self::hook_frame(ctx, seq).await,
743 };
744 hooks.recover(&view).await;
745 }
746
747 #[allow(clippy::too_many_arguments)] async fn observe_fatal(
752 &self,
753 ctx: &DrainCtx,
754 iteration: usize,
755 seq: u64,
756 audit: &Value,
757 text_bytes: u64,
758 reasoning_bytes: u64,
759 usage: Option<&Value>,
760 ) {
761 self.observe_recover(ctx, iteration, seq, audit).await;
762 self.observe_response(
763 ctx,
764 iteration,
765 seq,
766 "error",
767 0,
768 text_bytes,
769 reasoning_bytes,
770 usage,
771 Some(audit),
772 )
773 .await;
774 }
775
776 async fn run_iteration(
777 &self,
778 ctx: &DrainCtx,
779 drain_iterations: &mut usize,
780 compactions: &mut usize,
781 ) -> Result<Flow, LoopError> {
782 let taken = ctx.take_eligible_inputs().await?;
786
787 let mut events = ctx.events().await?;
789
790 let mut pending = pending_calls(&events);
795 if !pending.is_empty() {
796 let decisions = confirmations(&events);
797 for (call, decision) in confirmable(&pending, &decisions) {
798 self.apply_confirmation(ctx, &call, &decision).await?;
799 }
800 events = ctx.events().await?;
801 pending = pending_calls(&events);
802 if !pending.is_empty() {
803 tracing::debug!(
804 session = %ctx.session().0,
805 pending = pending.len(),
806 "awaiting confirmation: settling without a provider call"
807 );
808 return Ok(Flow::Deferred);
809 }
810 }
811
812 let binding = self.binding_for(ctx, &mut events).await?;
813 let messages = derive_model_context(&events)?;
814
815 if resident_empty_batch(
822 self.config.budget_scope,
823 taken.is_empty(),
824 messages.last().map(|m| m.role.as_str()),
825 ) {
826 tracing::debug!(
827 session = %ctx.session().0,
828 "resident empty batch: settling without a provider call (ADR-025)"
829 );
830 return Ok(Flow::Settled);
831 }
832
833 let iteration = events
836 .iter()
837 .filter(|ev| matches!(ev.kind, EventKind::TurnStart))
838 .count();
839 let used = self.config.budget_scope.used(iteration, *drain_iterations);
840 if used >= self.config.max_iterations {
841 let reason = match self.config.budget_scope {
842 BudgetScope::Lifetime => {
843 format!("iteration budget exhausted after {iteration} turns")
844 }
845 BudgetScope::PerEpisode => format!(
846 "{} after {used} turns",
847 kian_core::seams::EPISODE_BUDGET_STOP_REASON_PREFIX
848 ),
849 };
850 return Ok(Flow::Stopped(reason));
851 }
852 if self.config.budget_scope == BudgetScope::PerEpisode {
853 *drain_iterations += 1;
854 }
855
856 if let Some(trigger) = preventive_trigger(&binding, &messages)
861 && let Some(flow) = self
862 .compact_now(ctx, &binding, iteration, trigger, compactions)
863 .await?
864 {
865 return Ok(flow);
866 }
867
868 ctx.begin_turn_with(json!({"iteration": iteration})).await?;
871 let turn = self
872 .provider_turn(ctx, &binding, &messages, iteration)
873 .await;
874 let usage = turn.usage.as_ref();
875 let flow = match turn.result {
876 Ok(TurnOutcome::ToolCalls(n)) => {
877 let mut payload = json!({"iteration": iteration, "tool_calls": n});
878 if let Some(u) = usage {
879 payload["usage"] = u.clone();
880 }
881 ctx.end_turn_with(payload).await?;
882 return Ok(Flow::TurnDone);
883 }
884 Ok(TurnOutcome::FinalAnswer) => {
887 if ctx.has_eligible_inputs().await? {
888 Flow::TurnDone
889 } else {
890 Flow::Settled
891 }
892 }
893 Err(TurnError::AwaitingBudget { budget }) => {
894 let payload = json!({
895 "iteration": iteration,
896 "outcome": "awaiting_budget",
897 "budget": &budget,
898 });
899 let _ = ctx.end_turn_with(payload).await;
900 return Ok(Flow::AwaitingBudget(budget));
901 }
902 Err(TurnError::Soft { reason, audit }) => {
903 let mut payload = json!({
904 "iteration": iteration,
905 "outcome": "soft_failure",
906 "error": audit,
907 });
908 if let Some(u) = usage {
909 payload["usage"] = u.clone();
910 }
911 let _ = ctx.end_turn_with(payload).await;
912 let overflow = audit.get("class").and_then(Value::as_str)
918 == Some(kian_orchestrator::recovery::ErrorClass::ContextOverflow.name());
919 if overflow
920 && let Some(flow) = self
921 .compact_now(
922 ctx,
923 &binding,
924 iteration,
925 CompactionTrigger::Overflow,
926 compactions,
927 )
928 .await?
929 {
930 return Ok(flow);
931 }
932 return Ok(Flow::Soft(reason));
933 }
934 Err(TurnError::Fatal { error, audit }) => {
935 let mut payload = json!({
936 "iteration": iteration,
937 "outcome": "error",
938 "error": audit,
939 });
940 if let Some(u) = usage {
941 payload["usage"] = u.clone();
942 }
943 let _ = ctx.end_turn_with(payload).await;
944 return Err(error);
945 }
946 };
947 let mut payload = json!({"iteration": iteration, "outcome": "final_answer"});
948 if let Some(u) = usage {
949 payload["usage"] = u.clone();
950 }
951 ctx.end_turn_with(payload).await?;
952 Ok(flow)
953 }
954
955 async fn apply_confirmation(
962 &self,
963 ctx: &DrainCtx,
964 call: &PendingCall,
965 decision: &ConfirmIntent,
966 ) -> Result<(), LoopError> {
967 let result = match decision.decision {
968 ConfirmDecision::Approve => {
969 let tool_call = ToolCall {
970 id: call.call_id.clone(),
971 name: call.tool.clone(),
972 arguments: call.arguments.clone(),
973 };
974 match self.tools.invoke(tool_call).await {
975 Ok(r) => r,
976 Err(e) => ToolResult {
979 call_id: call.call_id.clone(),
980 output: json!({"error": e.to_string()}),
981 is_error: true,
982 redactions: Vec::new(),
983 },
984 }
985 }
986 ConfirmDecision::Reject => ToolResult {
987 call_id: call.call_id.clone(),
988 output: if decision.expired {
989 json!({
990 "error": "confirmation expired",
991 "policy": "ask",
992 "expired": true
993 })
994 } else {
995 match &decision.reason {
996 Some(reason) => json!({
997 "error": "permission denied by user",
998 "policy": "ask",
999 "reason": reason
1000 }),
1001 None => json!({
1002 "error": "permission denied by user",
1003 "policy": "ask"
1004 }),
1005 }
1006 },
1007 is_error: true,
1008 redactions: Vec::new(),
1009 },
1010 };
1011 let payload = tool_result_payload_confirmed(&result, decision);
1012 ctx.append(EventKind::ToolResult, payload).await?;
1013 Ok(())
1014 }
1015
1016 async fn binding_for(
1020 &self,
1021 ctx: &DrainCtx,
1022 events: &mut Vec<Event>,
1023 ) -> Result<SlotBinding, LoopError> {
1024 let session = ctx.session();
1025 if let Ok(slots) = SessionSlots::replay(session, events)
1026 && slots.binding(&self.config.slot).is_ok()
1027 {
1028 return Ok(slots.binding(&self.config.slot)?.clone());
1029 }
1030 let fresh = SlotResolver::from_agent_def(&self.agent).bind_session(session);
1031 for payload in fresh.binding_payloads() {
1032 ctx.append(EventKind::SlotBinding, payload).await?;
1033 }
1034 *events = ctx.events().await?;
1037 Ok(fresh.binding(&self.config.slot)?.clone())
1038 }
1039
1040 async fn chat_messages(
1046 &self,
1047 ctx: &DrainCtx,
1048 profile: Option<&ModelProfile>,
1049 messages: &[Message],
1050 ) -> Vec<ChatMessage> {
1051 let vision = profile.is_some_and(|p| p.vision);
1052 let mut chat = Vec::with_capacity(messages.len());
1053 for message in messages {
1054 let Some(mut chat_message) = to_chat_message(message) else {
1055 continue;
1056 };
1057 if vision
1058 && message.role == "user"
1059 && let Some((text, references)) = vision_envelope(&message.content)
1060 {
1061 chat_message.content = text;
1062 chat_message.images = self.load_images(ctx, &references).await;
1063 }
1064 chat.push(chat_message);
1065 }
1066 chat
1067 }
1068
1069 async fn load_images(&self, ctx: &DrainCtx, references: &[ImageReference]) -> Vec<ChatImage> {
1075 let mut images = Vec::new();
1076 for (artifact, media_type) in references.iter().take(MAX_IMAGES_PER_MESSAGE) {
1077 let Some(bytes) = ctx.artifact_bytes(artifact).await else {
1078 continue;
1079 };
1080 if bytes.len() > MAX_VISION_IMAGE_BYTES {
1081 tracing::warn!(
1082 artifact = %artifact,
1083 bytes = bytes.len(),
1084 limit = MAX_VISION_IMAGE_BYTES,
1085 "vision image is over the byte bound; the image is skipped (ADR-063)"
1086 );
1087 continue;
1088 }
1089 images.push(ChatImage {
1090 media_type: media_type.clone(),
1091 bytes,
1092 });
1093 }
1094 images
1095 }
1096
1097 async fn provider_turn(
1103 &self,
1104 ctx: &DrainCtx,
1105 binding: &SlotBinding,
1106 messages: &[Message],
1107 iteration: usize,
1108 ) -> TurnResult {
1109 let target = binding.target.clone();
1110
1111 let mut schemas = self.tools.schemas();
1114 schemas.sort_by(|a, b| a.name.cmp(&b.name));
1115 let chat = self
1116 .chat_messages(ctx, target.profile.as_ref(), messages)
1117 .await;
1118
1119 let plan = match build_request_plan(target.profile.as_ref(), &target.model, &chat, &schemas)
1123 {
1124 Ok(plan) => plan,
1125 Err(e) => {
1126 return TurnResult {
1127 result: Err(TurnError::Soft {
1128 reason: format!("request plan: {e}"),
1129 audit: recovery_audit(self.policy.as_ref(), provider_error_class(&e)),
1130 }),
1131 usage: None,
1132 };
1133 }
1134 };
1135 let budget = match ctx.events().await {
1141 Ok(events) => project_budget(&events, &self.agent.budgets),
1142 Err(e) => {
1143 return TurnResult {
1144 result: Err(TurnError::Soft {
1145 reason: format!("budget projection: {e}"),
1146 audit: json!({"class": "internal", "action": "none"}),
1147 }),
1148 usage: None,
1149 };
1150 }
1151 };
1152 let estimate = plan
1153 .estimate
1154 .high
1155 .saturating_add(plan.estimate.max_output_tokens.unwrap_or(0));
1156 let reserve = budget.maintenance_reserve_tokens().unwrap_or(0);
1159 if budget.would_exceed_tokens_reserving(estimate, reserve) {
1160 return TurnResult {
1161 result: Err(TurnError::AwaitingBudget {
1162 budget: json!({
1163 "limit": budget.tokens_limit,
1164 "raised": budget.tokens_raised,
1165 "spent": budget.tokens_spent,
1166 "estimate": estimate,
1167 "reserve": reserve,
1168 }),
1169 }),
1170 usage: None,
1171 };
1172 }
1173 let body = plan.body.clone();
1174 let mut step_payload = json!({
1175 "slot": self.config.slot.0,
1176 "provider": target.provider,
1177 "model": target.model,
1178 "iteration": iteration,
1179 "body": body,
1180 "body_version": plan.body_version,
1181 "dialect": plan.dialect,
1182 "body_sha256": plan.body_sha256,
1183 "estimate": plan.estimate,
1184 });
1185 if let Some(digest) = &plan.profile_digest {
1186 step_payload["profile_digest"] = json!(digest);
1187 }
1188 let step_request = ctx.append(EventKind::StepRequest, step_payload).await;
1189 let step_request_seq = match step_request {
1190 Ok(ev) => ev.seq,
1191 Err(e) => {
1192 let fatal = TurnError::fatal(e, self.policy.as_ref());
1193 if let TurnError::Fatal { audit, .. } = &fatal {
1195 self.observe_fatal(ctx, iteration, 0, audit, 0, 0, None)
1196 .await;
1197 }
1198 return TurnResult {
1199 result: Err(fatal),
1200 usage: None,
1201 };
1202 }
1203 };
1204 self.observe_request(
1209 ctx,
1210 binding,
1211 chat.len(),
1212 &schemas,
1213 iteration,
1214 &body,
1215 step_request_seq,
1216 )
1217 .await;
1218
1219 let build_chat = chat.clone();
1222 let build_schemas = schemas.clone();
1223 let build = Arc::new(move |t: &kian_core::model::SlotTarget| {
1224 build_request_plan(t.profile.as_ref(), &t.model, &build_chat, &build_schemas)
1225 });
1226 let mut stream = complete_turn(
1227 Arc::clone(&self.registry),
1228 self.config.slot.clone(),
1229 binding.clone(),
1230 build,
1231 Arc::new(CtxSlotSink { ctx: ctx.clone() }),
1232 );
1233
1234 let mut text = String::new();
1239 let mut reasoning = String::new();
1240 let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
1241 let mut usage: Option<Value> = None;
1242 let mut stream_error: Option<ProviderError> = None;
1243 while let Some(item) = stream.next().await {
1244 match item {
1245 Ok(chunk) => {
1246 if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
1247 usage = Some(u.clone()); }
1249 if !chunk.delta.is_null() {
1250 assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
1251 }
1252 }
1253 Err(e) => {
1254 stream_error = Some(e);
1255 break;
1256 }
1257 }
1258 }
1259 let text_bytes = text.len() as u64;
1262 let reasoning_bytes = reasoning.len() as u64;
1263 if let Some(e) = stream_error {
1264 let class = error_class(&e);
1265 let action = consult_policy(self.policy.as_ref(), class);
1266 let note = action_note(action);
1267 let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
1268 self.observe_recover(ctx, iteration, step_request_seq, &audit)
1271 .await;
1272 self.observe_response(
1273 ctx,
1274 iteration,
1275 step_request_seq,
1276 "soft_failure",
1277 0,
1278 text_bytes,
1279 reasoning_bytes,
1280 usage.as_ref(),
1281 Some(&audit),
1282 )
1283 .await;
1284 return TurnResult {
1285 result: Err(TurnError::Soft {
1286 reason: format!("provider error ({class}): {e}{note}"),
1287 audit,
1288 }),
1289 usage,
1290 };
1291 }
1292 if text.is_empty() && calls.is_empty() {
1293 let action = consult_policy(self.policy.as_ref(), CLASS_EMPTY_RESPONSE);
1296 let note = action_note(action);
1297 let audit = recovery_audit(
1298 self.policy.as_ref(),
1299 kian_orchestrator::recovery::ErrorClass::EmptyResponse,
1300 );
1301 self.observe_recover(ctx, iteration, step_request_seq, &audit)
1302 .await;
1303 self.observe_response(
1304 ctx,
1305 iteration,
1306 step_request_seq,
1307 "soft_failure",
1308 0,
1309 0,
1310 0,
1311 usage.as_ref(),
1312 Some(&audit),
1313 )
1314 .await;
1315 return TurnResult {
1316 result: Err(TurnError::Soft {
1317 reason: format!("empty model response{note}"),
1318 audit,
1319 }),
1320 usage,
1321 };
1322 }
1323
1324 let tool_calls: Vec<ToolCall> = calls.into_values().map(CallAcc::finish).collect();
1325 let mut content = json!({"text": text});
1326 if !tool_calls.is_empty() {
1327 content["tool_calls"] = Value::Array(
1328 tool_calls
1329 .iter()
1330 .map(|c| json!({"id": c.id, "name": c.name, "arguments": c.arguments}))
1331 .collect(),
1332 );
1333 }
1334 if !reasoning.is_empty() {
1335 content["reasoning_content"] = Value::String(reasoning);
1338 }
1339 if let Err(e) = ctx
1340 .append(
1341 EventKind::AssistantMessage,
1342 json!({"role": "assistant", "content": content}),
1343 )
1344 .await
1345 {
1346 let fatal = TurnError::fatal(e, self.policy.as_ref());
1347 if let TurnError::Fatal { audit, .. } = &fatal {
1348 self.observe_fatal(
1349 ctx,
1350 iteration,
1351 step_request_seq,
1352 audit,
1353 text_bytes,
1354 reasoning_bytes,
1355 usage.as_ref(),
1356 )
1357 .await;
1358 }
1359 return TurnResult {
1360 result: Err(fatal),
1361 usage,
1362 };
1363 }
1364
1365 if tool_calls.is_empty() {
1366 self.observe_response(
1368 ctx,
1369 iteration,
1370 step_request_seq,
1371 "final_answer",
1372 0,
1373 text_bytes,
1374 reasoning_bytes,
1375 usage.as_ref(),
1376 None,
1377 )
1378 .await;
1379 return TurnResult {
1380 result: Ok(TurnOutcome::FinalAnswer),
1381 usage,
1382 };
1383 }
1384
1385 let n = tool_calls.len();
1386 for call in tool_calls {
1392 let decision = evaluate_permission(&self.config.permissions, &call.name);
1397 let hook_verdict = self
1409 .consult_tool_pre(ctx, &call, iteration, step_request_seq, decision)
1410 .await;
1411 let appended = match hook_verdict {
1412 kian_plugin::hooks::ToolVerdict::Deny {
1413 ref plugin,
1414 ref reason,
1415 } => {
1416 ctx.append(
1421 EventKind::ToolCall,
1422 tool_call_payload_hook_denied(&call, plugin, reason),
1423 )
1424 .await
1425 }
1426 _ => {
1427 ctx.append(EventKind::ToolCall, tool_call_payload(&call, decision))
1428 .await
1429 }
1430 };
1431 let call_seq = match appended {
1432 Ok(ev) => ev.seq,
1433 Err(e) => {
1434 let fatal = TurnError::fatal(e, self.policy.as_ref());
1435 if let TurnError::Fatal { audit, .. } = &fatal {
1436 self.observe_fatal(
1437 ctx,
1438 iteration,
1439 step_request_seq,
1440 audit,
1441 text_bytes,
1442 reasoning_bytes,
1443 usage.as_ref(),
1444 )
1445 .await;
1446 }
1447 return TurnResult {
1448 result: Err(fatal),
1449 usage,
1450 };
1451 }
1452 };
1453 if let kian_plugin::hooks::ToolVerdict::Deny {
1464 ref plugin,
1465 ref reason,
1466 } = hook_verdict
1467 {
1468 let denied = ToolResult {
1469 call_id: call.id.clone(),
1470 output: json!({
1471 "error": format!("denied by plugin {plugin}: {reason}"),
1472 "policy": "hook"
1473 }),
1474 is_error: true,
1475 redactions: Vec::new(),
1476 };
1477 if let Err(e) = ctx
1478 .append(EventKind::ToolResult, tool_result_payload(&denied))
1479 .await
1480 {
1481 let fatal = TurnError::fatal(e, self.policy.as_ref());
1482 if let TurnError::Fatal { audit, .. } = &fatal {
1483 self.observe_fatal(
1484 ctx,
1485 iteration,
1486 call_seq,
1487 audit,
1488 text_bytes,
1489 reasoning_bytes,
1490 usage.as_ref(),
1491 )
1492 .await;
1493 }
1494 return TurnResult {
1495 result: Err(fatal),
1496 usage,
1497 };
1498 }
1499 self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1500 .await;
1501 continue;
1502 }
1503 if matches!(decision, Some(PermissionDecision::Ask)) {
1507 continue;
1508 }
1509 if let Some(denied) = declared_denial(&call, decision) {
1514 if let Err(e) = ctx
1515 .append(EventKind::ToolResult, tool_result_payload(&denied))
1516 .await
1517 {
1518 let fatal = TurnError::fatal(e, self.policy.as_ref());
1519 if let TurnError::Fatal { audit, .. } = &fatal {
1520 self.observe_fatal(
1521 ctx,
1522 iteration,
1523 call_seq,
1524 audit,
1525 text_bytes,
1526 reasoning_bytes,
1527 usage.as_ref(),
1528 )
1529 .await;
1530 }
1531 return TurnResult {
1532 result: Err(fatal),
1533 usage,
1534 };
1535 }
1536 self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1539 .await;
1540 continue;
1541 }
1542 let result = match self.tools.invoke(call.clone()).await {
1543 Ok(r) => r,
1544 Err(e) => {
1545 ToolResult {
1548 call_id: call.id.clone(),
1549 output: json!({"error": e.to_string()}),
1550 is_error: true,
1551 redactions: Vec::new(),
1552 }
1553 }
1554 };
1555 let result_seq = match ctx
1560 .append(EventKind::ToolResult, tool_result_payload(&result))
1561 .await
1562 {
1563 Ok(ev) => ev.seq,
1564 Err(e) => {
1565 let fatal = TurnError::fatal(e, self.policy.as_ref());
1566 if let TurnError::Fatal { audit, .. } = &fatal {
1567 self.observe_fatal(
1568 ctx,
1569 iteration,
1570 call_seq,
1571 audit,
1572 text_bytes,
1573 reasoning_bytes,
1574 usage.as_ref(),
1575 )
1576 .await;
1577 }
1578 return TurnResult {
1579 result: Err(fatal),
1580 usage,
1581 };
1582 }
1583 };
1584 self.observe_tool_post(ctx, &result, &call.name, result_seq)
1587 .await;
1588 }
1589 self.observe_response(
1592 ctx,
1593 iteration,
1594 step_request_seq,
1595 "tool_calls",
1596 n as u64,
1597 text_bytes,
1598 reasoning_bytes,
1599 usage.as_ref(),
1600 None,
1601 )
1602 .await;
1603 TurnResult {
1604 result: Ok(TurnOutcome::ToolCalls(n)),
1605 usage,
1606 }
1607 }
1608
1609 async fn compact_now(
1616 &self,
1617 ctx: &DrainCtx,
1618 binding: &SlotBinding,
1619 iteration: usize,
1620 trigger: CompactionTrigger,
1621 compactions: &mut usize,
1622 ) -> Result<Option<Flow>, LoopError> {
1623 if *compactions >= MAX_COMPACTIONS_PER_EPISODE {
1624 return Ok(None);
1625 }
1626 let events = ctx.events().await?;
1627 let plan = match plan_compaction(&events, &self.compaction, Some(&trigger)) {
1628 Ok(Some(plan)) => plan,
1629 Ok(None) => return Ok(None),
1630 Err(e) => {
1631 tracing::warn!(
1632 session = %ctx.session().0,
1633 error = %e,
1634 "compaction planner refused the stream"
1635 );
1636 return Ok(None);
1637 }
1638 };
1639 let transcript = match render_folded_transcript(&events, &plan) {
1640 Ok(transcript) => transcript,
1641 Err(e) => {
1642 tracing::warn!(
1643 session = %ctx.session().0,
1644 error = %e,
1645 "compaction transcript refused the stream"
1646 );
1647 return Ok(None);
1648 }
1649 };
1650 let target = binding.target.clone();
1651 let chat = summary_chat(&transcript);
1652 let request = match build_request_plan(target.profile.as_ref(), &target.model, &chat, &[]) {
1653 Ok(request) => request,
1654 Err(e) => return Ok(Some(Flow::Soft(format!("compact request plan: {e}")))),
1655 };
1656 let estimate = request
1657 .estimate
1658 .high
1659 .saturating_add(request.estimate.max_output_tokens.unwrap_or(0));
1660 let budget = project_budget(&events, &self.agent.budgets);
1663 if budget.would_exceed_tokens(estimate) {
1664 return Ok(Some(Flow::AwaitingBudget(json!({
1665 "limit": budget.tokens_limit,
1666 "raised": budget.tokens_raised,
1667 "spent": budget.tokens_spent,
1668 "estimate": estimate,
1669 "purpose": "compact",
1670 }))));
1671 }
1672
1673 ctx.begin_turn_with(json!({"iteration": iteration, "purpose": "compact"}))
1674 .await?;
1675 let mut step_payload = json!({
1676 "slot": self.config.slot.0,
1677 "provider": target.provider,
1678 "model": target.model,
1679 "iteration": iteration,
1680 "purpose": "compact",
1681 "body": request.body.clone(),
1682 "body_version": request.body_version,
1683 "dialect": request.dialect,
1684 "body_sha256": request.body_sha256,
1685 "estimate": request.estimate,
1686 });
1687 if let Some(digest) = &request.profile_digest {
1688 step_payload["profile_digest"] = json!(digest);
1689 }
1690 let step_request_seq = match ctx.append(EventKind::StepRequest, step_payload).await {
1691 Ok(event) => event.seq,
1692 Err(e) => {
1693 let _ = ctx
1694 .end_turn_with(json!({
1695 "iteration": iteration,
1696 "purpose": "compact",
1697 "outcome": "error",
1698 "error": {"class": "internal", "action": "none"},
1699 }))
1700 .await;
1701 return Err(e.into());
1702 }
1703 };
1704 let Some(provider) = self.registry.get(&target.provider) else {
1707 let audit = recovery_audit(
1708 self.policy.as_ref(),
1709 kian_orchestrator::recovery::ErrorClass::Unknown,
1710 );
1711 let _ = ctx
1712 .end_turn_with(json!({
1713 "iteration": iteration,
1714 "purpose": "compact",
1715 "outcome": "soft_failure",
1716 "error": audit,
1717 }))
1718 .await;
1719 return Ok(Some(Flow::Soft(format!(
1720 "compact: provider {} is not registered",
1721 target.provider
1722 ))));
1723 };
1724 let mut stream = provider.complete(ModelRequest {
1725 slot: self.config.slot.clone(),
1726 body: request.body,
1727 });
1728 let mut text = String::new();
1729 let mut reasoning = String::new();
1730 let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
1731 let mut usage: Option<Value> = None;
1732 let mut stream_error: Option<ProviderError> = None;
1733 while let Some(item) = stream.next().await {
1734 match item {
1735 Ok(chunk) => {
1736 if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
1737 usage = Some(u.clone());
1738 }
1739 if !chunk.delta.is_null() {
1740 assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
1741 }
1742 }
1743 Err(e) => {
1744 stream_error = Some(e);
1745 break;
1746 }
1747 }
1748 }
1749 if let Some(e) = stream_error {
1750 let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
1751 let mut payload = json!({
1752 "iteration": iteration,
1753 "purpose": "compact",
1754 "outcome": "soft_failure",
1755 "error": audit,
1756 });
1757 if let Some(u) = usage.as_ref() {
1758 payload["usage"] = u.clone();
1759 }
1760 let _ = ctx.end_turn_with(payload).await;
1761 return Ok(Some(Flow::Soft(format!(
1762 "compact summary request failed: {e}"
1763 ))));
1764 }
1765 let summary = text.trim().to_string();
1766 if summary.is_empty() {
1767 let audit = recovery_audit(
1768 self.policy.as_ref(),
1769 kian_orchestrator::recovery::ErrorClass::EmptyResponse,
1770 );
1771 let mut payload = json!({
1772 "iteration": iteration,
1773 "purpose": "compact",
1774 "outcome": "soft_failure",
1775 "error": audit,
1776 });
1777 if let Some(u) = usage.as_ref() {
1778 payload["usage"] = u.clone();
1779 }
1780 let _ = ctx.end_turn_with(payload).await;
1781 return Ok(Some(Flow::Soft(
1782 "compact summary request returned an empty response".to_string(),
1783 )));
1784 }
1785 let compact_seq = match ctx
1788 .append(
1789 EventKind::Compact,
1790 json!({
1791 "from_seq": plan.from_seq,
1792 "to_seq": plan.to_seq,
1793 "summary": {"role": "assistant", "content": {"text": summary}},
1794 "produced_by": {"step_seq": step_request_seq},
1795 "reason": plan.reason,
1796 "folded_messages": plan.folded_messages,
1797 "reclaimed_tokens": plan.reclaimed_tokens,
1798 }),
1799 )
1800 .await
1801 {
1802 Ok(event) => event.seq,
1803 Err(e) => {
1804 let _ = ctx
1805 .end_turn_with(json!({
1806 "iteration": iteration,
1807 "purpose": "compact",
1808 "outcome": "error",
1809 "error": {"class": "internal", "action": "none"},
1810 }))
1811 .await;
1812 return Err(e.into());
1813 }
1814 };
1815 let mut payload = json!({
1816 "iteration": iteration,
1817 "purpose": "compact",
1818 "outcome": "compacted",
1819 "compact_seq": compact_seq,
1820 "from_seq": plan.from_seq,
1821 "to_seq": plan.to_seq,
1822 });
1823 if let Some(u) = usage.as_ref() {
1824 payload["usage"] = u.clone();
1825 }
1826 if let Err(e) = ctx.end_turn_with(payload).await {
1827 return Err(e.into());
1828 }
1829 *compactions += 1;
1830 tracing::info!(
1831 session = %ctx.session().0,
1832 from_seq = plan.from_seq,
1833 to_seq = plan.to_seq,
1834 folded_messages = plan.folded_messages,
1835 reclaimed_tokens = plan.reclaimed_tokens,
1836 "context compacted (ADR-058)"
1837 );
1838 Ok(Some(Flow::TurnDone))
1839 }
1840}
1841
1842impl TurnError {
1847 fn fatal(e: EngineError, policy: &dyn RecoveryPolicySource) -> Self {
1852 let error = LoopError::Engine(e);
1853 let audit = recovery_audit(policy, loop_error_class(&error));
1854 Self::Fatal { error, audit }
1855 }
1856}
1857
1858fn loop_error_class(e: &LoopError) -> kian_orchestrator::recovery::ErrorClass {
1864 match e {
1865 LoopError::Engine(_) => kian_orchestrator::recovery::ErrorClass::StoreFailure,
1866 LoopError::Context(_) | LoopError::Slot(_) => {
1867 kian_orchestrator::recovery::ErrorClass::Unknown
1868 }
1869 }
1870}
1871
1872fn preventive_trigger(binding: &SlotBinding, messages: &[Message]) -> Option<CompactionTrigger> {
1875 let profile = binding.target.profile.as_ref()?;
1876 let window = profile.context_window?;
1877 if window == 0 {
1878 return None;
1879 }
1880 let incoming = estimate_context_tokens(messages)
1881 .saturating_add(profile.max_output.unwrap_or(DEFAULT_OUTPUT_RESERVE_TOKENS));
1882 Some(CompactionTrigger::Pressure(CompactionPressure {
1883 context_window_tokens: window,
1884 incoming_estimate_tokens: incoming,
1885 }))
1886}
1887
1888fn render_folded_transcript(
1893 events: &[Event],
1894 plan: &CompactionPlan,
1895) -> Result<String, kian_core::context::ContextError> {
1896 let messages = derive_model_context(events)?;
1897 let provenance = context_provenance(events)?;
1898 let mut out = String::new();
1899 for (message, source) in messages.iter().zip(provenance.iter()) {
1900 if !(plan.from_seq..plan.to_seq).contains(source) {
1901 continue;
1902 }
1903 let body = match &message.content {
1904 Value::String(text) => text.clone(),
1905 other => serde_json::to_string(other).unwrap_or_default(),
1906 };
1907 let line = format!("{}: {body}\n", message.role);
1908 if out.len().saturating_add(line.len()) > MAX_TRANSCRIPT_CHARS {
1909 let room = MAX_TRANSCRIPT_CHARS.saturating_sub(out.len());
1910 out.push_str(take_chars(&line, room));
1911 out.push_str("\n[... transcript truncated ...]\n");
1912 break;
1913 }
1914 out.push_str(&line);
1915 }
1916 Ok(out)
1917}
1918
1919fn take_chars(text: &str, max: usize) -> &str {
1922 match text.char_indices().nth(max) {
1923 Some((index, _)) => &text[..index],
1924 None => text,
1925 }
1926}
1927
1928fn summary_chat(transcript: &str) -> Vec<ChatMessage> {
1932 vec![
1933 ChatMessage::plain("system", SUMMARY_SYSTEM_PROMPT),
1934 ChatMessage::plain(
1935 "user",
1936 format!(
1937 "Compress the following earlier conversation into one dense summary. The summary will replace these turns in the model context.\n\n{transcript}"
1938 ),
1939 ),
1940 ]
1941}
1942
1943fn provider_error_class(e: &ProviderError) -> kian_orchestrator::recovery::ErrorClass {
1946 kian_orchestrator::recovery::classify(
1947 &kian_orchestrator::recovery::RecoveryError::Provider(e.clone()),
1948 &kian_orchestrator::recovery::ClassifyCtx { attempt: 0 },
1949 )
1950}
1951
1952fn recovery_audit(
1956 policy: &dyn RecoveryPolicySource,
1957 class: kian_orchestrator::recovery::ErrorClass,
1958) -> Value {
1959 let action = consult_policy(policy, class.name());
1960 json!({
1961 "class": class.name(),
1962 "action": action_name(action.as_ref()),
1963 })
1964}
1965
1966fn action_name(action: Option<&RecoveryAction>) -> &'static str {
1969 match action {
1970 None => "none",
1971 Some(RecoveryAction::BackoffRetry { .. }) => "backoff_retry",
1972 Some(RecoveryAction::CompressThenRetry) => "compress_then_retry",
1973 Some(RecoveryAction::Failover) => "failover",
1974 Some(RecoveryAction::InterruptAsk) => "interrupt_ask",
1975 Some(RecoveryAction::Fail) => "fail",
1976 }
1977}
1978
1979struct CtxSlotSink {
1983 ctx: DrainCtx,
1984}
1985
1986impl SlotEventSink for CtxSlotSink {
1987 fn persist_fallback(
1988 &self,
1989 payload: Value,
1990 ) -> futures::future::BoxFuture<'static, Result<(), String>> {
1991 let ctx = self.ctx.clone();
1992 Box::pin(async move {
1993 ctx.append(EventKind::SlotFallback, payload)
1994 .await
1995 .map(|_| ())
1996 .map_err(|e| e.to_string())
1997 })
1998 }
1999}
2000
2001struct CallAcc {
2003 id: String,
2004 name: String,
2005 arguments: String,
2006}
2007
2008impl CallAcc {
2009 fn finish(self) -> ToolCall {
2010 let arguments = serde_json::from_str::<Value>(&self.arguments)
2011 .unwrap_or_else(|_| Value::String(self.arguments.clone()));
2012 ToolCall {
2013 id: self.id,
2014 name: self.name,
2015 arguments,
2016 }
2017 }
2018}
2019
2020fn assemble_delta(
2023 delta: &Value,
2024 text: &mut String,
2025 reasoning: &mut String,
2026 calls: &mut BTreeMap<u64, CallAcc>,
2027) {
2028 if let Some(fragment) = delta.get("content").and_then(Value::as_str) {
2029 text.push_str(fragment);
2030 }
2031 if let Some(fragment) = delta.get("reasoning_content").and_then(Value::as_str) {
2032 reasoning.push_str(fragment);
2033 }
2034 if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) {
2035 for entry in list {
2036 let index = entry.get("index").and_then(Value::as_u64).unwrap_or(0);
2037 let slot = calls.entry(index).or_insert_with(|| CallAcc {
2038 id: String::new(),
2039 name: String::new(),
2040 arguments: String::new(),
2041 });
2042 if let Some(id) = entry.get("id").and_then(Value::as_str) {
2043 slot.id = id.to_string();
2044 }
2045 if let Some(name) = entry.pointer("/function/name").and_then(Value::as_str) {
2046 slot.name.push_str(name);
2047 }
2048 if let Some(args) = entry.pointer("/function/arguments").and_then(Value::as_str) {
2049 slot.arguments.push_str(args);
2050 }
2051 }
2052 }
2053}
2054
2055pub fn to_chat_message(m: &Message) -> Option<ChatMessage> {
2080 match m.role.as_str() {
2081 "tool" => Some(tool_result_message(&m.content)),
2082 "assistant" => assistant_message(&m.content),
2083 _ => Some(string_or_compact(&m.role, &m.content)),
2084 }
2085}
2086
2087type ImageReference = (String, String);
2089
2090type VisionEnvelope = (Option<String>, Vec<ImageReference>);
2092
2093fn vision_envelope(content: &Value) -> Option<VisionEnvelope> {
2101 let object = content.as_object()?;
2102 let references = object.get("images")?.as_array()?;
2103 let mut usable = Vec::new();
2104 for item in references {
2105 let Some(entry) = item.as_object() else {
2106 continue;
2107 };
2108 let Some(artifact) = entry
2109 .get("artifact")
2110 .and_then(Value::as_str)
2111 .filter(|id| !id.is_empty())
2112 else {
2113 continue;
2114 };
2115 let Some(media_type) = entry
2116 .get("media_type")
2117 .and_then(Value::as_str)
2118 .filter(|t| !t.is_empty())
2119 else {
2120 continue;
2121 };
2122 usable.push((artifact.to_owned(), media_type.to_owned()));
2123 }
2124 if usable.is_empty() {
2125 return None;
2126 }
2127 let text = object
2128 .get("text")
2129 .and_then(Value::as_str)
2130 .map(str::to_owned);
2131 Some((text, usable))
2132}
2133
2134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2137pub(crate) enum PermissionDecision {
2138 AllowConfigured,
2140 AllowDefault,
2142 Deny,
2144 Ask,
2147}
2148
2149const PERMISSION_DENY_REASON: &str = "tool_denied_by_policy";
2151
2152fn evaluate_permission(
2162 permissions: &BTreeMap<String, Permission>,
2163 tool: &str,
2164) -> Option<PermissionDecision> {
2165 if permissions.is_empty() {
2166 return None;
2167 }
2168 match permissions.get(tool) {
2169 Some(Permission::Allow) => Some(PermissionDecision::AllowConfigured),
2170 Some(Permission::Deny) => Some(PermissionDecision::Deny),
2171 Some(Permission::Ask) => Some(PermissionDecision::Ask),
2172 None => Some(PermissionDecision::AllowDefault),
2173 }
2174}
2175
2176fn declared_denial(call: &ToolCall, decision: Option<PermissionDecision>) -> Option<ToolResult> {
2181 matches!(decision, Some(PermissionDecision::Deny)).then(|| ToolResult {
2182 call_id: call.id.clone(),
2183 output: json!({
2184 "error": format!("permission denied by policy: {}", call.name),
2185 "policy": "deny"
2186 }),
2187 is_error: true,
2188 redactions: Vec::new(),
2189 })
2190}
2191
2192fn tool_call_payload(call: &ToolCall, decision: Option<PermissionDecision>) -> Value {
2198 let mut payload = json!({
2199 "role": "assistant",
2200 "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
2201 });
2202 if let Some(decision) = decision {
2203 payload["permission"] = match decision {
2204 PermissionDecision::AllowConfigured => json!({
2205 "evaluated": "allow", "policy": "configured", "matched": call.name
2206 }),
2207 PermissionDecision::AllowDefault => json!({
2208 "evaluated": "allow", "policy": "default", "matched": call.name
2209 }),
2210 PermissionDecision::Deny => json!({
2211 "evaluated": "deny",
2212 "policy": "configured",
2213 "matched": call.name,
2214 "reason": PERMISSION_DENY_REASON
2215 }),
2216 PermissionDecision::Ask => json!({
2217 "evaluated": "ask",
2218 "policy": "configured",
2219 "matched": call.name
2220 }),
2221 };
2222 }
2223 payload
2224}
2225
2226fn tool_call_payload_hook_denied(call: &ToolCall, plugin: &str, reason: &str) -> Value {
2234 let mut payload = json!({
2235 "role": "assistant",
2236 "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
2237 });
2238 payload["permission"] = json!({
2239 "evaluated": "deny",
2240 "policy": "hook",
2241 "matched": format!("{plugin}:tool/pre"),
2242 "reason": reason,
2243 });
2244 payload
2245}
2246
2247fn permission_view(
2252 call: &ToolCall,
2253 decision: Option<PermissionDecision>,
2254) -> kian_plugin::hooks::PermissionView {
2255 match decision {
2256 Some(PermissionDecision::AllowConfigured) => kian_plugin::hooks::PermissionView {
2257 evaluated: "allow".to_string(),
2258 policy: "configured".to_string(),
2259 matched: call.name.clone(),
2260 reason: None,
2261 },
2262 Some(PermissionDecision::Deny) => kian_plugin::hooks::PermissionView {
2263 evaluated: "deny".to_string(),
2264 policy: "configured".to_string(),
2265 matched: call.name.clone(),
2266 reason: Some(PERMISSION_DENY_REASON.to_string()),
2267 },
2268 Some(PermissionDecision::Ask) => kian_plugin::hooks::PermissionView {
2269 evaluated: "ask".to_string(),
2270 policy: "configured".to_string(),
2271 matched: call.name.clone(),
2272 reason: None,
2273 },
2274 Some(PermissionDecision::AllowDefault) | None => kian_plugin::hooks::PermissionView {
2275 evaluated: "allow".to_string(),
2276 policy: "default".to_string(),
2277 matched: call.name.clone(),
2278 reason: None,
2279 },
2280 }
2281}
2282
2283fn tool_result_payload(result: &ToolResult) -> Value {
2290 let mut payload = json!({
2291 "role": "tool",
2292 "content": {
2293 "call_id": result.call_id,
2294 "output": result.output,
2295 "is_error": result.is_error
2296 }
2297 });
2298 if !result.redactions.is_empty() {
2299 if let Ok(report) = serde_json::to_value(&result.redactions) {
2302 payload["redactions"] = report;
2303 }
2304 }
2305 payload
2306}
2307
2308fn tool_result_payload_confirmed(result: &ToolResult, decision: &ConfirmIntent) -> Value {
2312 let mut payload = tool_result_payload(result);
2313 let mut provenance = json!({
2314 "call_id": result.call_id,
2315 "decision": decision.decision.as_str(),
2316 "requested_by": decision.requested_by,
2317 "answered_at_ms": decision.answered_at_ms,
2318 });
2319 if decision.expired {
2320 provenance["expired"] = json!(true);
2321 }
2322 payload["confirmation"] = provenance;
2323 payload
2324}
2325
2326fn string_or_compact(role: &str, content: &Value) -> ChatMessage {
2329 let text = match content {
2330 Value::String(s) => s.clone(),
2331 other => serde_json::to_string(other).unwrap_or_default(),
2332 };
2333 ChatMessage {
2334 role: role.to_owned(),
2335 content: Some(text),
2336 tool_call_id: None,
2337 tool_calls: None,
2338 reasoning_content: None,
2339 images: Vec::new(),
2340 }
2341}
2342
2343fn tool_result_message(content: &Value) -> ChatMessage {
2347 if let Some(obj) = content.as_object()
2348 && let Some(call_id) = obj.get("call_id").and_then(Value::as_str)
2349 {
2350 let output = obj.get("output").cloned().unwrap_or(Value::Null);
2351 return ChatMessage {
2352 role: "tool".into(),
2353 content: Some(serde_json::to_string(&output).unwrap_or_default()),
2354 tool_call_id: Some(call_id.to_owned()),
2355 tool_calls: None,
2356 reasoning_content: None,
2357 images: Vec::new(),
2358 };
2359 }
2360 ChatMessage {
2361 role: "tool".into(),
2362 content: Some(serde_json::to_string(content).unwrap_or_default()),
2363 tool_call_id: Some(String::new()),
2364 tool_calls: None,
2365 reasoning_content: None,
2366 images: Vec::new(),
2367 }
2368}
2369
2370fn reasoning_field(obj: &serde_json::Map<String, Value>) -> Option<String> {
2373 obj.get("reasoning_content")
2374 .and_then(Value::as_str)
2375 .filter(|r| !r.is_empty())
2376 .map(str::to_owned)
2377}
2378
2379fn assistant_message(content: &Value) -> Option<ChatMessage> {
2383 let Some(obj) = content.as_object() else {
2384 return Some(string_or_compact("assistant", content));
2385 };
2386 if obj.contains_key("tool_calls") {
2387 let calls: Option<Vec<WireToolCall>> =
2388 obj.get("tool_calls").and_then(Value::as_array).map(|list| {
2389 list.iter()
2390 .filter_map(|tc| {
2391 let id = tc.get("id").and_then(Value::as_str)?;
2392 let name = tc.get("name").and_then(Value::as_str)?;
2393 let arguments = tc.get("arguments").cloned().unwrap_or(Value::Null);
2394 Some(WireToolCall {
2395 id: id.to_owned(),
2396 r#type: "function".into(),
2397 function: WireFunctionCall {
2398 name: name.to_owned(),
2399 arguments: serde_json::to_string(&arguments).unwrap_or_default(),
2400 },
2401 })
2402 })
2403 .collect()
2404 });
2405 return Some(ChatMessage {
2406 role: "assistant".into(),
2407 content: obj
2410 .get("text")
2411 .and_then(Value::as_str)
2412 .filter(|t| !t.is_empty())
2413 .map(str::to_owned),
2414 tool_call_id: None,
2415 tool_calls: calls,
2416 reasoning_content: reasoning_field(obj),
2417 images: Vec::new(),
2418 });
2419 }
2420 if obj.contains_key("id") && obj.contains_key("name") && obj.contains_key("arguments") {
2423 return None;
2424 }
2425 if let Some(text) = obj.get("text").and_then(Value::as_str) {
2426 return Some(ChatMessage {
2427 role: "assistant".into(),
2428 content: Some(text.to_owned()),
2429 tool_call_id: None,
2430 tool_calls: None,
2431 reasoning_content: reasoning_field(obj),
2432 images: Vec::new(),
2433 });
2434 }
2435 Some(string_or_compact("assistant", content))
2436}
2437
2438fn resident_empty_batch(scope: BudgetScope, taken_empty: bool, last_role: Option<&str>) -> bool {
2443 scope == BudgetScope::PerEpisode && taken_empty && last_role == Some("assistant")
2444}
2445
2446fn error_class(e: &ProviderError) -> &'static str {
2449 match e {
2450 ProviderError::RateLimited => "rate_limited",
2451 ProviderError::ContextOverflow => "context_overflow",
2452 ProviderError::Unavailable(_) | ProviderError::Transport(_) => "provider_down",
2453 ProviderError::EmptyResponse => CLASS_EMPTY_RESPONSE,
2454 ProviderError::InvalidResponse(_) => "validation_failed",
2455 ProviderError::Other(_) => "internal",
2456 }
2457}
2458
2459fn consult_policy(policy: &dyn RecoveryPolicySource, class: &str) -> Option<RecoveryAction> {
2463 policy
2464 .table()
2465 .into_iter()
2466 .find(|rule| rule.class == class)
2467 .map(|rule| rule.action)
2468}
2469
2470fn action_note(action: Option<RecoveryAction>) -> String {
2471 match action {
2472 Some(a) => format!("; recovery policy action: {a:?}"),
2473 None => "; no matching recovery policy rule".into(),
2474 }
2475}
2476
2477#[cfg(test)]
2478mod tests {
2479 use crate::react::{
2480 BudgetScope, CLASS_EMPTY_RESPONSE, ReActConfig, ReActLoop, assemble_delta, consult_policy,
2481 to_chat_message, tool_result_payload,
2482 };
2483 use crate::test_support::{NoopPolicy, NoopTools, agent_def};
2484 use kian_core::context::{Message, derive_model_context};
2485 use kian_core::events::{Event, EventKind};
2486 use kian_core::model::SessionId;
2487 use kian_core::seams::{ToolCall, ToolResult};
2488 use kian_core::secrets::{Redaction, RedactionKind};
2489 use kian_llm::provider::build_chat_body;
2490 use serde_json::json;
2491 use std::collections::BTreeMap;
2492
2493 fn msg(role: &str, content: serde_json::Value) -> Message {
2494 Message {
2495 role: role.into(),
2496 content,
2497 synthetic: false,
2498 }
2499 }
2500
2501 #[test]
2506 fn tool_result_payload_carries_redactions_outside_content() {
2507 let plain = ToolResult {
2508 call_id: "call-1".into(),
2509 output: json!({"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false}),
2510 is_error: false,
2511 redactions: Vec::new(),
2512 };
2513 let payload = tool_result_payload(&plain);
2514 assert_eq!(
2515 payload,
2516 json!({
2517 "role": "tool",
2518 "content": {
2519 "call_id": "call-1",
2520 "output": {"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false},
2521 "is_error": false
2522 }
2523 }),
2524 "no redactions → no key, bytes unchanged"
2525 );
2526
2527 let redacted = ToolResult {
2528 call_id: "call-2".into(),
2529 output: json!({"exit_code": 0, "stdout": "[REDACTED:token]", "stderr": "", "timed_out": false}),
2530 is_error: false,
2531 redactions: vec![Redaction {
2532 kind: RedactionKind::TokenPattern,
2533 name: "ghp_".into(),
2534 count: 1,
2535 }],
2536 };
2537 let payload = tool_result_payload(&redacted);
2538 assert_eq!(
2539 payload["redactions"],
2540 json!([{"kind": "token_pattern", "name": "ghp_", "count": 1}])
2541 );
2542 assert!(payload["content"].get("redactions").is_none());
2545 assert_eq!(payload["content"]["call_id"], json!("call-2"));
2546 }
2547
2548 #[test]
2552 fn redactions_payload_key_never_enters_the_model_context() {
2553 let session = SessionId::new();
2554 let bytes = tool_result_payload(&ToolResult {
2555 call_id: "call-9".into(),
2556 output: json!({"content": "scrubbed"}),
2557 is_error: false,
2558 redactions: vec![Redaction {
2559 kind: RedactionKind::EnvLine,
2560 name: "MY_SERVICE_TOKEN".into(),
2561 count: 2,
2562 }],
2563 });
2564 let with = Event {
2565 seq: 2,
2566 session,
2567 epoch: kian_core::model::Epoch(1),
2568 ts: 1,
2569 kind: EventKind::ToolResult,
2570 bytes: bytes.clone(),
2571 version: 0,
2572 };
2573 let mut without_bytes = bytes.clone();
2574 without_bytes.as_object_mut().unwrap().remove("redactions");
2575 let without = Event {
2576 bytes: without_bytes,
2577 ..with.clone()
2578 };
2579 let base = Event {
2580 seq: 1,
2581 session,
2582 epoch: kian_core::model::Epoch(0),
2583 ts: 0,
2584 kind: EventKind::SessionCreated,
2585 bytes: json!({}),
2586 version: 0,
2587 };
2588 let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
2589 let ctx_without = derive_model_context(&[base, without]).unwrap();
2590 assert_eq!(ctx_with, ctx_without);
2591 assert_eq!(ctx_with.len(), 1);
2592 let chat = to_chat_message(&ctx_with[0]).unwrap();
2594 assert_eq!(chat.role, "tool");
2595 assert_eq!(chat.tool_call_id.as_deref(), Some("call-9"));
2596 assert_eq!(chat.content.as_deref(), Some("{\"content\":\"scrubbed\"}"));
2597 }
2598
2599 #[test]
2604 fn tool_round_trip_projects_to_the_strict_wire_shape() {
2605 let assistant = msg(
2606 "assistant",
2607 json!({
2608 "text": "",
2609 "tool_calls": [
2610 {"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}
2611 ]
2612 }),
2613 );
2614 let chat = to_chat_message(&assistant).unwrap();
2615 assert_eq!(chat.role, "assistant");
2616 assert_eq!(chat.content, None, "empty text serializes as null");
2617 let tc = &chat.tool_calls.as_ref().unwrap()[0];
2618 assert_eq!(tc.id, "call-1");
2619 assert_eq!(tc.r#type, "function");
2620 assert_eq!(tc.function.name, "fs_read");
2621 assert_eq!(tc.function.arguments, "{\"path\":\"a.txt\"}");
2622
2623 let with_text = msg(
2625 "assistant",
2626 json!({"text": "checking", "tool_calls": [
2627 {"id": "call-2", "name": "exec", "arguments": {"argv": ["true"]}}
2628 ]}),
2629 );
2630 let chat = to_chat_message(&with_text).unwrap();
2631 assert_eq!(chat.content.as_deref(), Some("checking"));
2632
2633 let dup = msg(
2635 "assistant",
2636 json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}),
2637 );
2638 assert!(to_chat_message(&dup).is_none());
2639
2640 let result = msg(
2642 "tool",
2643 json!({"call_id": "call-1", "output": {"content": "x"}, "is_error": false}),
2644 );
2645 let chat = to_chat_message(&result).unwrap();
2646 assert_eq!(chat.role, "tool");
2647 assert_eq!(chat.tool_call_id.as_deref(), Some("call-1"));
2648 assert_eq!(chat.content.as_deref(), Some("{\"content\":\"x\"}"));
2649 assert!(chat.tool_calls.is_none());
2650 }
2651
2652 #[test]
2656 fn plain_messages_keep_the_v1_shape() {
2657 let user = msg("user", json!("hello"));
2658 let chat = to_chat_message(&user).unwrap();
2659 assert_eq!(chat.role, "user");
2660 assert_eq!(chat.content.as_deref(), Some("hello"));
2661 assert!(chat.tool_call_id.is_none() && chat.tool_calls.is_none());
2662
2663 let bare = msg("assistant", json!({"text": "hi"}));
2664 assert_eq!(
2665 to_chat_message(&bare).unwrap().content.as_deref(),
2666 Some("hi")
2667 );
2668
2669 let foreign = msg("tool", json!({"odd": true}));
2672 let chat = to_chat_message(&foreign).unwrap();
2673 assert_eq!(chat.tool_call_id.as_deref(), Some(""));
2674 }
2675
2676 #[test]
2684 fn permission_evaluation_covers_absent_default_and_configured() {
2685 use crate::react::{PermissionDecision, evaluate_permission};
2686 use kian_core::model::Permission;
2687
2688 let empty: BTreeMap<String, Permission> = BTreeMap::new();
2689 assert_eq!(evaluate_permission(&empty, "fs_write"), None);
2690
2691 let table: BTreeMap<String, Permission> = BTreeMap::from([
2692 ("fs_read".to_string(), Permission::Allow),
2693 ("fs_write".to_string(), Permission::Deny),
2694 ]);
2695 assert_eq!(
2696 evaluate_permission(&table, "fs_read"),
2697 Some(PermissionDecision::AllowConfigured)
2698 );
2699 assert_eq!(
2700 evaluate_permission(&table, "fs_write"),
2701 Some(PermissionDecision::Deny)
2702 );
2703 assert_eq!(
2706 evaluate_permission(&table, "exec"),
2707 Some(PermissionDecision::AllowDefault)
2708 );
2709 }
2710
2711 #[test]
2715 fn tool_call_payload_carries_permission_provenance_outside_content() {
2716 use crate::react::{evaluate_permission, tool_call_payload};
2717 use kian_core::model::Permission;
2718
2719 let call = ToolCall {
2720 id: "call-7".into(),
2721 name: "fs_write".into(),
2722 arguments: json!({"path": "a.txt"}),
2723 };
2724
2725 let empty: BTreeMap<String, Permission> = BTreeMap::new();
2727 let legacy = tool_call_payload(&call, evaluate_permission(&empty, &call.name));
2728 assert_eq!(
2729 legacy,
2730 json!({
2731 "role": "assistant",
2732 "content": {"id": "call-7", "name": "fs_write", "arguments": {"path": "a.txt"}}
2733 })
2734 );
2735
2736 let table: BTreeMap<String, Permission> =
2738 BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
2739 let allowed = tool_call_payload(&call, evaluate_permission(&table, &call.name)); assert_eq!(
2741 allowed["permission"],
2742 json!({"evaluated": "allow", "policy": "default", "matched": "fs_write"})
2743 );
2744 assert_eq!(allowed["content"], legacy["content"]);
2745
2746 let table: BTreeMap<String, Permission> =
2748 BTreeMap::from([("fs_write".to_string(), Permission::Deny)]);
2749 let denied = tool_call_payload(&call, evaluate_permission(&table, &call.name));
2750 assert_eq!(
2751 denied["permission"],
2752 json!({
2753 "evaluated": "deny",
2754 "policy": "configured",
2755 "matched": "fs_write",
2756 "reason": "tool_denied_by_policy"
2757 })
2758 );
2759 assert_eq!(denied["content"], legacy["content"]);
2760 }
2761
2762 #[test]
2773 fn hook_denied_permission_payload_goldens_are_frozen_bytes() {
2774 use crate::react::{evaluate_permission, tool_call_payload, tool_call_payload_hook_denied};
2775 use kian_core::model::Permission;
2776
2777 let call = ToolCall {
2778 id: "call-7".into(),
2779 name: "exec".into(),
2780 arguments: json!({"cmd": ["ls"]}),
2781 };
2782
2783 let hook_denied =
2785 tool_call_payload_hook_denied(&call, "approval-gate", "exec not on the allowlist");
2786 assert_eq!(
2787 serde_json::to_string(&hook_denied).unwrap(),
2788 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2789 \"permission\":{\"evaluated\":\"deny\",\"matched\":\"approval-gate:tool/pre\",\
2790 \"policy\":\"hook\",\"reason\":\"exec not on the allowlist\"},\"role\":\"assistant\"}"
2791 );
2792
2793 let denied_result = ToolResult {
2797 call_id: call.id.clone(),
2798 output: json!({
2799 "error": "denied by plugin approval-gate: exec not on the allowlist",
2800 "policy": "hook"
2801 }),
2802 is_error: true,
2803 redactions: Vec::new(),
2804 };
2805 assert_eq!(
2806 serde_json::to_string(&tool_result_payload(&denied_result)).unwrap(),
2807 "{\"content\":{\"call_id\":\"call-7\",\"is_error\":true,\
2808 \"output\":{\"error\":\"denied by plugin approval-gate: exec not on the allowlist\",\
2809 \"policy\":\"hook\"}},\"role\":\"tool\"}"
2810 );
2811
2812 let empty: BTreeMap<String, Permission> = BTreeMap::new();
2816 assert_eq!(
2817 serde_json::to_string(&tool_call_payload(
2818 &call,
2819 evaluate_permission(&empty, &call.name)
2820 ))
2821 .unwrap(),
2822 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2823 \"role\":\"assistant\"}"
2824 );
2825 let default_table = BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
2826 assert_eq!(
2827 serde_json::to_string(&tool_call_payload(
2828 &call,
2829 evaluate_permission(&default_table, &call.name)
2830 ))
2831 .unwrap(),
2832 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2833 \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"default\"},\
2834 \"role\":\"assistant\"}"
2835 );
2836 let allow_table = BTreeMap::from([("exec".to_string(), Permission::Allow)]);
2837 assert_eq!(
2838 serde_json::to_string(&tool_call_payload(
2839 &call,
2840 evaluate_permission(&allow_table, &call.name)
2841 ))
2842 .unwrap(),
2843 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2844 \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"configured\"},\
2845 \"role\":\"assistant\"}"
2846 );
2847 let deny_table = BTreeMap::from([("exec".to_string(), Permission::Deny)]);
2848 assert_eq!(
2849 serde_json::to_string(&tool_call_payload(
2850 &call,
2851 evaluate_permission(&deny_table, &call.name)
2852 ))
2853 .unwrap(),
2854 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
2855 \"permission\":{\"evaluated\":\"deny\",\"matched\":\"exec\",\"policy\":\"configured\",\
2856 \"reason\":\"tool_denied_by_policy\"},\"role\":\"assistant\"}"
2857 );
2858 }
2859
2860 #[test]
2865 fn permission_payload_key_never_enters_the_model_context() {
2866 use crate::react::{PermissionDecision, tool_call_payload};
2867 use kian_core::seams::ToolCall;
2868
2869 let session = SessionId::new();
2870 let call = ToolCall {
2871 id: "call-1".into(),
2872 name: "fs_read".into(),
2873 arguments: json!({"path": "a.txt"}),
2874 };
2875 let with_bytes = tool_call_payload(&call, Some(PermissionDecision::Deny));
2876 let mut without_bytes = with_bytes.clone();
2877 without_bytes.as_object_mut().unwrap().remove("permission");
2878 let with = Event {
2879 seq: 2,
2880 session,
2881 epoch: kian_core::model::Epoch(1),
2882 ts: 1,
2883 kind: EventKind::ToolCall,
2884 bytes: with_bytes,
2885 version: 0,
2886 };
2887 let without = Event {
2888 bytes: without_bytes,
2889 ..with.clone()
2890 };
2891 let base = Event {
2892 seq: 1,
2893 session,
2894 epoch: kian_core::model::Epoch(0),
2895 ts: 0,
2896 kind: EventKind::SessionCreated,
2897 bytes: json!({}),
2898 version: 0,
2899 };
2900 let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
2901 let ctx_without = derive_model_context(&[base, without]).unwrap();
2902 assert_eq!(ctx_with, ctx_without);
2903 assert_eq!(ctx_with.len(), 1);
2904 assert_eq!(ctx_with[0].role, "assistant");
2907 assert_eq!(
2908 ctx_with[0].content,
2909 json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}})
2910 );
2911 assert!(!ctx_with[0].synthetic);
2912 }
2913
2914 #[test]
2921 fn resident_empty_batch_is_skipped_only_for_resident_assistant_tails() {
2922 use super::resident_empty_batch;
2923 assert!(resident_empty_batch(
2924 BudgetScope::PerEpisode,
2925 true,
2926 Some("assistant")
2927 ));
2928 assert!(!resident_empty_batch(
2929 BudgetScope::PerEpisode,
2930 false,
2931 Some("assistant")
2932 ));
2933 assert!(!resident_empty_batch(
2934 BudgetScope::PerEpisode,
2935 true,
2936 Some("tool")
2937 ));
2938 assert!(!resident_empty_batch(
2939 BudgetScope::PerEpisode,
2940 true,
2941 Some("user")
2942 ));
2943 assert!(!resident_empty_batch(
2944 BudgetScope::Lifetime,
2945 true,
2946 Some("assistant")
2947 ));
2948 }
2949
2950 #[test]
2951 fn budget_scope_selects_lifetime_or_episode_counter() {
2952 assert_eq!(BudgetScope::Lifetime.used(9, 0), 9);
2953 assert_eq!(BudgetScope::Lifetime.used(0, 9), 0);
2954 assert_eq!(BudgetScope::PerEpisode.used(9, 2), 2);
2955 assert_eq!(BudgetScope::PerEpisode.used(0, 0), 0);
2956 }
2957
2958 #[test]
2959 fn delta_assembly_concatenates_content_fragments() {
2960 let mut text = String::new();
2961 let mut reasoning = String::new();
2962 let mut calls = Default::default();
2963 for fragment in ["Hello", ", ", "kian"] {
2964 assemble_delta(
2965 &serde_json::json!({"content": fragment}),
2966 &mut text,
2967 &mut reasoning,
2968 &mut calls,
2969 );
2970 }
2971 assert_eq!(text, "Hello, kian");
2972 assert!(calls.is_empty());
2973 }
2974
2975 #[test]
2979 fn reasoning_fragments_are_persisted_and_replayed() {
2980 let mut text = String::new();
2981 let mut reasoning = String::new();
2982 let mut calls = Default::default();
2983 assemble_delta(
2984 &json!({"reasoning_content": "think "}),
2985 &mut text,
2986 &mut reasoning,
2987 &mut calls,
2988 );
2989 assemble_delta(
2990 &json!({"reasoning_content": "harder"}),
2991 &mut text,
2992 &mut reasoning,
2993 &mut calls,
2994 );
2995 assemble_delta(
2996 &json!({"content": "answer"}),
2997 &mut text,
2998 &mut reasoning,
2999 &mut calls,
3000 );
3001 assert_eq!(reasoning, "think harder");
3002 assert_eq!(text, "answer");
3003
3004 let with = to_chat_message(&msg(
3005 "assistant",
3006 json!({"text": text, "reasoning_content": reasoning}),
3007 ))
3008 .unwrap();
3009 assert_eq!(with.reasoning_content.as_deref(), Some("think harder"));
3010 let body = build_chat_body("m", &[with], &[]);
3011 assert_eq!(body["messages"][0]["reasoning_content"], "think harder");
3012
3013 let legacy = to_chat_message(&msg("assistant", json!({"text": "answer"}))).unwrap();
3014 assert!(legacy.reasoning_content.is_none());
3015 let body = build_chat_body("m", &[legacy], &[]);
3016 assert!(body["messages"][0].get("reasoning_content").is_none());
3017 }
3018
3019 #[test]
3020 fn delta_assembly_accumulates_tool_call_fragments_by_index() {
3021 let mut text = String::new();
3022 let mut reasoning = String::new();
3023 let mut calls = Default::default();
3024 assemble_delta(
3025 &serde_json::json!({"tool_calls": [
3026 {"index": 0, "id": "call-1", "function": {"name": "fs.read"}}
3027 ]}),
3028 &mut text,
3029 &mut reasoning,
3030 &mut calls,
3031 );
3032 assemble_delta(
3033 &serde_json::json!({"tool_calls": [
3034 {"index": 0, "function": {"arguments": "{\"pa"}}
3035 ]}),
3036 &mut text,
3037 &mut reasoning,
3038 &mut calls,
3039 );
3040 assemble_delta(
3041 &serde_json::json!({"tool_calls": [
3042 {"index": 0, "function": {"arguments": "th\": \"a.txt\"}"}}
3043 ]}),
3044 &mut text,
3045 &mut reasoning,
3046 &mut calls,
3047 );
3048 let finished: Vec<_> = calls.into_values().map(|c| c.finish()).collect();
3049 assert_eq!(finished.len(), 1);
3050 assert_eq!(finished[0].id, "call-1");
3051 assert_eq!(finished[0].name, "fs.read");
3052 assert_eq!(finished[0].arguments, serde_json::json!({"path": "a.txt"}));
3053 }
3054
3055 #[test]
3056 fn policy_consult_matches_rule_by_class() {
3057 use kian_core::seams::{PolicyRule, RecoveryAction, RecoveryPolicySource};
3058
3059 struct Table(Vec<PolicyRule>);
3060 impl RecoveryPolicySource for Table {
3061 fn table(&self) -> Vec<PolicyRule> {
3062 self.0.clone()
3063 }
3064 }
3065 let table = Table(vec![
3066 PolicyRule {
3067 class: "rate_limited".into(),
3068 action: RecoveryAction::BackoffRetry { delay_ms: 100 },
3069 },
3070 PolicyRule {
3071 class: CLASS_EMPTY_RESPONSE.into(),
3072 action: RecoveryAction::InterruptAsk,
3073 },
3074 ]);
3075 assert_eq!(
3076 consult_policy(&table, "rate_limited"),
3077 Some(RecoveryAction::BackoffRetry { delay_ms: 100 })
3078 );
3079 assert_eq!(
3080 consult_policy(&table, CLASS_EMPTY_RESPONSE),
3081 Some(RecoveryAction::InterruptAsk)
3082 );
3083 assert_eq!(consult_policy(&table, "no_such_class"), None);
3084 }
3085
3086 #[test]
3093 fn recovery_audit_carries_class_and_policy_action() {
3094 use kian_core::seams::{PolicyRule, RecoveryPolicySource};
3095 use kian_orchestrator::recovery::ErrorClass;
3096 use serde_json::json;
3097
3098 struct Table(Vec<PolicyRule>);
3099 impl RecoveryPolicySource for Table {
3100 fn table(&self) -> Vec<PolicyRule> {
3101 self.0.clone()
3102 }
3103 }
3104 let with_rule = Table(vec![PolicyRule {
3105 class: "store_failure".into(),
3106 action: kian_core::seams::RecoveryAction::Fail,
3107 }]);
3108 assert_eq!(
3109 super::recovery_audit(&with_rule, ErrorClass::StoreFailure),
3110 json!({"class": "store_failure", "action": "fail"})
3111 );
3112 assert_eq!(
3113 super::recovery_audit(&with_rule, ErrorClass::EmptyResponse),
3114 json!({"class": "empty_response", "action": "none"}),
3115 "no covering rule → the honest none spelling"
3116 );
3117
3118 assert_eq!(
3120 super::provider_error_class(&kian_core::seams::ProviderError::RateLimited),
3121 ErrorClass::RateLimited
3122 );
3123 assert_eq!(
3124 super::provider_error_class(&kian_core::seams::ProviderError::Unavailable(
3125 "upstream 503".into()
3126 )),
3127 ErrorClass::ProviderDown
3128 );
3129
3130 assert_eq!(
3132 super::loop_error_class(&super::LoopError::Engine(
3133 kian_orchestrator::EngineError::NotAtSafeBoundary {
3134 session: kian_core::model::SessionId::new(),
3135 }
3136 )),
3137 ErrorClass::StoreFailure
3138 );
3139 assert_eq!(
3140 super::loop_error_class(&super::LoopError::Slot(
3141 kian_llm::slots::SlotError::UnknownSlot("aux".into())
3142 )),
3143 ErrorClass::Unknown
3144 );
3145 }
3146
3147 #[test]
3148 fn react_config_defaults_are_sane() {
3149 let cfg = ReActConfig::default();
3150 assert_eq!(cfg.slot.0, "main");
3151 assert!(cfg.max_iterations >= 1);
3152 let react = ReActLoop::new(
3154 agent_def(),
3155 std::sync::Arc::new(kian_llm::ProviderRegistry::new()),
3156 std::sync::Arc::new(NoopTools),
3157 std::sync::Arc::new(NoopPolicy),
3158 );
3159 assert_eq!(react.config().slot.0, "main");
3160 }
3161}