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, ToolSchema,
64};
65use kian_llm::plan::{RequestPlan, build_request_plan};
66use kian_llm::provider::{
67 ChatImage, ChatMessage, WireFunctionCall, WireToolCall, serialize_request_body,
68};
69use kian_llm::slots::{SessionSlots, SlotBinding, SlotError, SlotResolver};
70use kian_llm::turn::{ProviderRegistry, SlotEventSink, complete_turn};
71use kian_orchestrator::compaction::{
72 CompactionPlan, CompactionPressure, CompactionSettings, CompactionTrigger,
73 estimate_context_tokens, plan_compaction,
74};
75use kian_orchestrator::{DrainCtx, EngineError};
76use serde_json::{Value, json};
77
78use crate::evidence::{
79 BUILTIN_GATE_NAME, EvidenceGateConfig, evaluate_evidence_gate, verdict_payload,
80};
81
82pub const CLASS_EMPTY_RESPONSE: &str = "empty_response";
84
85pub const DEFAULT_MAX_ITERATIONS: usize = 32;
87
88const MAX_COMPACTIONS_PER_EPISODE: usize = 2;
92
93const DEFAULT_OUTPUT_RESERVE_TOKENS: u64 = 4_096;
96
97const MAX_IMAGES_PER_MESSAGE: usize = 4;
99
100const MAX_VISION_IMAGE_BYTES: usize = 8 * 1024 * 1024;
102
103pub const DEFAULT_MAX_IMAGES_PER_TURN: usize = 4;
105
106pub const DEFAULT_MAX_VISION_BYTES_PER_TURN: u64 = 4 * 1024 * 1024;
108
109const MAX_TRANSCRIPT_CHARS: usize = 120_000;
113
114const 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.";
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
120pub enum BudgetScope {
121 #[default]
125 Lifetime,
126 PerEpisode,
130}
131
132impl BudgetScope {
133 #[must_use]
135 fn used(self, lifetime_iteration: usize, episode_iterations: usize) -> usize {
136 match self {
137 Self::Lifetime => lifetime_iteration,
138 Self::PerEpisode => episode_iterations,
139 }
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
153pub struct VisionBudget {
154 pub max_images_per_turn: usize,
156 pub max_image_bytes_per_turn: u64,
158}
159
160impl Default for VisionBudget {
161 fn default() -> Self {
162 Self {
163 max_images_per_turn: DEFAULT_MAX_IMAGES_PER_TURN,
164 max_image_bytes_per_turn: DEFAULT_MAX_VISION_BYTES_PER_TURN,
165 }
166 }
167}
168
169#[derive(Debug, Clone)]
171pub struct ReActConfig {
172 pub slot: SlotName,
175 pub max_iterations: usize,
180 pub budget_scope: BudgetScope,
182 pub permissions: BTreeMap<String, Permission>,
188 pub vision: VisionBudget,
191 pub max_request_bytes: BTreeMap<String, u64>,
198}
199
200impl Default for ReActConfig {
201 fn default() -> Self {
202 Self {
203 slot: SlotName("main".into()),
204 max_iterations: DEFAULT_MAX_ITERATIONS,
205 budget_scope: BudgetScope::Lifetime,
206 permissions: BTreeMap::new(),
207 vision: VisionBudget::default(),
208 max_request_bytes: BTreeMap::new(),
209 }
210 }
211}
212
213#[derive(Clone)]
214struct Inner {
215 registry: Arc<ProviderRegistry>,
216 tools: Arc<dyn ToolProvider>,
217 policy: Arc<dyn RecoveryPolicySource>,
218 agent: AgentDef,
219 config: ReActConfig,
220 gate: EvidenceGateConfig,
223 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
227 set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
234 compaction: CompactionSettings,
237}
238
239struct PreparedRequest {
245 schemas: Vec<ToolSchema>,
246 chat: Vec<ChatMessage>,
247 plan: Result<RequestPlan, ProviderError>,
248}
249
250#[derive(Clone)]
252pub struct ReActLoop(Arc<Inner>);
253
254impl ReActLoop {
255 pub fn new(
259 agent: AgentDef,
260 registry: Arc<ProviderRegistry>,
261 tools: Arc<dyn ToolProvider>,
262 policy: Arc<dyn RecoveryPolicySource>,
263 ) -> Self {
264 Self::with_config(agent, registry, tools, policy, ReActConfig::default())
265 }
266
267 pub fn with_config(
270 agent: AgentDef,
271 registry: Arc<ProviderRegistry>,
272 tools: Arc<dyn ToolProvider>,
273 policy: Arc<dyn RecoveryPolicySource>,
274 config: ReActConfig,
275 ) -> Self {
276 Self::with_evidence_gate(
277 agent,
278 registry,
279 tools,
280 policy,
281 config,
282 EvidenceGateConfig::default(),
283 )
284 }
285
286 pub fn with_evidence_gate(
290 agent: AgentDef,
291 registry: Arc<ProviderRegistry>,
292 tools: Arc<dyn ToolProvider>,
293 policy: Arc<dyn RecoveryPolicySource>,
294 config: ReActConfig,
295 gate: EvidenceGateConfig,
296 ) -> Self {
297 Self::with_hooks(agent, registry, tools, policy, config, gate, None)
298 }
299
300 pub fn with_hooks(
306 agent: AgentDef,
307 registry: Arc<ProviderRegistry>,
308 tools: Arc<dyn ToolProvider>,
309 policy: Arc<dyn RecoveryPolicySource>,
310 config: ReActConfig,
311 gate: EvidenceGateConfig,
312 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
313 ) -> Self {
314 Self::with_hooks_and_guard(agent, registry, tools, policy, config, gate, hooks, None)
315 }
316
317 #[allow(clippy::too_many_arguments)]
326 pub fn with_hooks_and_guard(
327 agent: AgentDef,
328 registry: Arc<ProviderRegistry>,
329 tools: Arc<dyn ToolProvider>,
330 policy: Arc<dyn RecoveryPolicySource>,
331 config: ReActConfig,
332 gate: EvidenceGateConfig,
333 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
334 set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
335 ) -> Self {
336 Self(Arc::new(Inner {
337 registry,
338 tools,
339 policy,
340 agent,
341 config,
342 gate,
343 hooks,
344 set_guard,
345 compaction: CompactionSettings::default(),
346 }))
347 }
348
349 #[must_use]
353 pub fn with_compaction(self, compaction: CompactionSettings) -> Self {
354 let mut inner = (*self.0).clone();
355 inner.compaction = compaction.normalized();
356 Self(Arc::new(inner))
357 }
358
359 #[must_use]
361 pub fn compaction_settings(&self) -> CompactionSettings {
362 self.0.compaction
363 }
364
365 #[must_use]
366 pub fn config(&self) -> &ReActConfig {
367 &self.0.config
368 }
369
370 #[must_use]
374 pub fn evidence_gate(&self) -> &EvidenceGateConfig {
375 &self.0.gate
376 }
377}
378
379struct LoopState {
388 ctx: DrainCtx,
389 done: bool,
390 begun: bool,
391 drain_iterations: usize,
394 compactions: usize,
397}
398
399impl LoopDriver for ReActLoop {
400 type Ctx = DrainCtx;
401
402 fn drive(&self, ctx: DrainCtx) -> BoxStream<'static, LoopOutcome> {
403 let inner = Arc::clone(&self.0);
404 futures::stream::unfold(
405 LoopState {
406 ctx,
407 done: false,
408 begun: false,
409 drain_iterations: 0,
410 compactions: 0,
411 },
412 move |mut st| {
413 let inner = Arc::clone(&inner);
414 async move {
415 if st.done {
416 return None;
417 }
418 if !st.begun {
429 st.begun = true;
430 if let Some(guard) = inner.set_guard.as_ref() {
431 let worker = match st.ctx.events().await {
432 Ok(events) => kian_plugin::hooks::durable_worker_binding(
433 &events,
434 &st.ctx.session(),
435 )
436 .unwrap_or_default(),
437 Err(_) => String::new(),
441 };
442 guard.session_begin(kian_plugin::hooks::FrameInfo {
443 session: st.ctx.session(),
444 worker,
445 seq: 0,
446 epoch: Some(st.ctx.epoch().0),
447 });
448 }
449 }
450 let outcome = match inner
451 .iteration(&st.ctx, &mut st.drain_iterations, &mut st.compactions)
452 .await
453 {
454 Flow::TurnDone => LoopOutcome::TurnDone,
455 Flow::Settled | Flow::Deferred => LoopOutcome::Settled,
456 Flow::Stopped(reason) => LoopOutcome::Stopped { reason },
457 Flow::AwaitingBudget(budget) => LoopOutcome::AwaitingBudget { budget },
458 Flow::Soft(reason) => LoopOutcome::SoftFailed { reason },
459 };
460 if !matches!(outcome, LoopOutcome::TurnDone) {
461 st.done = true;
462 }
463 Some((outcome, st))
464 }
465 },
466 )
467 .boxed()
468 }
469}
470
471enum Flow {
473 TurnDone,
475 Settled,
477 Deferred,
482 Stopped(String),
484 AwaitingBudget(Value),
487 Soft(String),
489}
490
491enum TurnOutcome {
492 FinalAnswer,
493 ToolCalls(usize),
494}
495
496struct TurnResult {
501 result: Result<TurnOutcome, TurnError>,
502 usage: Option<Value>,
503}
504
505enum TurnError {
506 Soft { reason: String, audit: Value },
510 Fatal { error: LoopError, audit: Value },
513 AwaitingBudget { budget: Value },
516}
517
518#[derive(Debug, thiserror::Error)]
522pub enum LoopError {
523 #[error("engine: {0}")]
524 Engine(#[from] EngineError),
525 #[error("context projection: {0}")]
526 Context(#[from] kian_core::context::ContextError),
527 #[error("slots: {0}")]
528 Slot(#[from] SlotError),
529}
530
531impl Inner {
532 async fn iteration(
534 &self,
535 ctx: &DrainCtx,
536 drain_iterations: &mut usize,
537 compactions: &mut usize,
538 ) -> Flow {
539 let flow = match self.run_iteration(ctx, drain_iterations, compactions).await {
540 Ok(flow) => flow,
541 Err(e) => return Flow::Soft(format!("loop error: {e}")),
542 };
543 match flow {
546 Flow::Settled | Flow::Stopped(_) => self.apply_evidence_gate(ctx, flow).await,
547 other => other,
548 }
549 }
550
551 async fn apply_evidence_gate(&self, ctx: &DrainCtx, flow: Flow) -> Flow {
564 if !self.gate.enabled {
565 return flow;
566 }
567 let events = match ctx.events().await {
568 Ok(events) => events,
569 Err(e) => {
570 return Flow::Soft(format!("evidence gate: stream read failed: {e}"));
571 }
572 };
573 let verdict = evaluate_evidence_gate(BUILTIN_GATE_NAME, &self.gate.checks, &events);
574 let payload = verdict_payload(BUILTIN_GATE_NAME, &verdict);
575 if let Err(e) = ctx.append(EventKind::EvidenceVerdict, payload).await {
576 return Flow::Soft(format!("evidence gate: verdict append failed: {e}"));
577 }
578 if verdict.passed {
579 self.gate.counters.record_passed();
580 flow
581 } else {
582 self.gate.counters.record_failed();
583 if verdict.attempt < self.gate.max_retries {
584 Flow::TurnDone
585 } else {
586 Flow::Soft(format!(
587 "evidence gate `{BUILTIN_GATE_NAME}` failed after {} attempt(s)",
588 verdict.attempt + 1
589 ))
590 }
591 }
592 }
593
594 async fn hook_frame(ctx: &DrainCtx, seq: u64) -> Option<kian_plugin::hooks::FrameInfo> {
611 let worker = match ctx.events().await {
612 Ok(events) => kian_plugin::hooks::durable_worker_binding(&events, &ctx.session())
613 .unwrap_or_default(),
614 Err(_) => String::new(),
617 };
618 Some(kian_plugin::hooks::FrameInfo {
619 session: ctx.session(),
620 worker,
621 seq,
622 epoch: Some(ctx.epoch().0),
623 })
624 }
625
626 #[allow(clippy::too_many_arguments)]
632 async fn observe_request(
633 &self,
634 ctx: &DrainCtx,
635 binding: &SlotBinding,
636 chat_len: usize,
637 schemas: &[kian_core::seams::ToolSchema],
638 iteration: usize,
639 body: &Value,
640 step_request_seq: u64,
641 ) {
642 use kian_plugin::hooks::{RequestMeta, serialized, sha256_hex};
643 let Some(hooks) = self.hooks.as_ref() else {
644 return;
645 };
646 let bytes = serialized(body);
647 let meta = RequestMeta {
648 slot: self.config.slot.0.clone(),
649 provider: binding.target.provider.clone(),
650 model: binding.target.model.clone(),
651 iteration: iteration as u64,
652 request_bytes: bytes.len() as u64,
653 request_sha256: sha256_hex(&bytes),
654 message_count: chat_len as u64,
655 tool_names: schemas.iter().map(|s| s.name.clone()).collect(),
656 tool_schema_sha256: sha256_hex(&serialized(&Value::Array(
657 schemas
658 .iter()
659 .map(|s| serde_json::to_value(s).unwrap_or(Value::Null))
660 .collect(),
661 ))),
662 timing: "pre_send".to_string(),
663 step_request_seq,
664 frame: Self::hook_frame(ctx, step_request_seq).await,
665 };
666 hooks.request(&meta).await;
667 }
668
669 #[allow(clippy::too_many_arguments)] async fn observe_response(
675 &self,
676 ctx: &DrainCtx,
677 iteration: usize,
678 seq: u64,
679 outcome: &str,
680 tool_calls: u64,
681 text_bytes: u64,
682 reasoning_bytes: u64,
683 usage: Option<&Value>,
684 error_audit: Option<&Value>,
685 ) {
686 use kian_plugin::hooks::{ResponseView, TurnErrorAudit};
687 let Some(hooks) = self.hooks.as_ref() else {
688 return;
689 };
690 let error = error_audit.and_then(|audit| {
691 Some(TurnErrorAudit {
692 class: audit.get("class")?.as_str()?.to_string(),
693 action: audit.get("action")?.as_str()?.to_string(),
694 })
695 });
696 let view = ResponseView {
697 iteration: iteration as u64,
698 outcome: outcome.to_string(),
699 tool_calls,
700 text_bytes,
701 reasoning_bytes,
702 usage: usage.cloned().unwrap_or(Value::Null),
703 error,
704 timing: "settled".to_string(),
705 frame: Self::hook_frame(ctx, seq).await,
706 };
707 hooks.response(&view).await;
708 }
709
710 async fn consult_tool_pre(
716 &self,
717 ctx: &DrainCtx,
718 call: &ToolCall,
719 iteration: usize,
720 seq: u64,
721 decision: Option<PermissionDecision>,
722 ) -> kian_plugin::hooks::ToolVerdict {
723 use kian_plugin::hooks::{ToolCallView, bounded_value, serialized, sha256_hex};
724 let Some(hooks) = self.hooks.as_ref() else {
725 return kian_plugin::hooks::ToolVerdict::Allow;
726 };
727 let bytes = serialized(&call.arguments);
728 let (arguments, arguments_truncated) = bounded_value(&call.arguments);
729 let view = ToolCallView {
730 call_id: call.id.clone(),
731 name: call.name.clone(),
732 iteration: iteration as u64,
733 arguments,
734 arguments_bytes: bytes.len() as u64,
735 arguments_sha256: sha256_hex(&bytes),
736 arguments_truncated,
737 permission: permission_view(call, decision),
738 surface: "react".to_string(),
739 frame: Self::hook_frame(ctx, seq).await,
740 };
741 hooks.tool_pre(&view).await
742 }
743
744 async fn observe_tool_post(&self, ctx: &DrainCtx, result: &ToolResult, name: &str, seq: u64) {
748 use kian_plugin::hooks::{RedactionReport, ToolPostView, serialized, sha256_hex};
749 let Some(hooks) = self.hooks.as_ref() else {
750 return;
751 };
752 let bytes = serialized(&result.output);
753 let view = ToolPostView {
754 call_id: result.call_id.clone(),
755 name: name.to_string(),
756 is_error: result.is_error,
757 output_bytes: bytes.len() as u64,
758 output_sha256: sha256_hex(&bytes),
759 redactions: result
760 .redactions
761 .iter()
762 .map(|r| RedactionReport {
763 kind: serde_json::to_value(r.kind)
764 .ok()
765 .and_then(|v| v.as_str().map(str::to_string))
766 .unwrap_or_default(),
767 name: r.name.clone(),
768 count: r.count,
769 })
770 .collect(),
771 frame: Self::hook_frame(ctx, seq).await,
772 };
773 hooks.tool_post(&view).await;
774 }
775
776 async fn observe_recover(&self, ctx: &DrainCtx, iteration: usize, seq: u64, audit: &Value) {
780 let Some(hooks) = self.hooks.as_ref() else {
781 return;
782 };
783 let view = kian_plugin::hooks::RecoveryView {
784 error_class: audit
785 .get("class")
786 .and_then(Value::as_str)
787 .unwrap_or_default()
788 .to_string(),
789 action: audit
790 .get("action")
791 .and_then(Value::as_str)
792 .unwrap_or("none")
793 .to_string(),
794 iteration: iteration as u64,
795 frame: Self::hook_frame(ctx, seq).await,
796 };
797 hooks.recover(&view).await;
798 }
799
800 #[allow(clippy::too_many_arguments)] async fn observe_fatal(
805 &self,
806 ctx: &DrainCtx,
807 iteration: usize,
808 seq: u64,
809 audit: &Value,
810 text_bytes: u64,
811 reasoning_bytes: u64,
812 usage: Option<&Value>,
813 ) {
814 self.observe_recover(ctx, iteration, seq, audit).await;
815 self.observe_response(
816 ctx,
817 iteration,
818 seq,
819 "error",
820 0,
821 text_bytes,
822 reasoning_bytes,
823 usage,
824 Some(audit),
825 )
826 .await;
827 }
828
829 async fn run_iteration(
830 &self,
831 ctx: &DrainCtx,
832 drain_iterations: &mut usize,
833 compactions: &mut usize,
834 ) -> Result<Flow, LoopError> {
835 let taken = ctx.take_eligible_inputs().await?;
839
840 let mut events = ctx.events().await?;
842
843 let mut pending = pending_calls(&events);
848 if !pending.is_empty() {
849 let decisions = confirmations(&events);
850 for (call, decision) in confirmable(&pending, &decisions) {
851 self.apply_confirmation(ctx, &call, &decision).await?;
852 }
853 events = ctx.events().await?;
854 pending = pending_calls(&events);
855 if !pending.is_empty() {
856 tracing::debug!(
857 session = %ctx.session().0,
858 pending = pending.len(),
859 "awaiting confirmation: settling without a provider call"
860 );
861 return Ok(Flow::Deferred);
862 }
863 }
864
865 let binding = self.binding_for(ctx, &mut events).await?;
866 let messages = derive_model_context(&events)?;
867
868 if resident_empty_batch(
875 self.config.budget_scope,
876 taken.is_empty(),
877 messages.last().map(|m| m.role.as_str()),
878 ) {
879 tracing::debug!(
880 session = %ctx.session().0,
881 "resident empty batch: settling without a provider call (ADR-025)"
882 );
883 return Ok(Flow::Settled);
884 }
885
886 let iteration = events
889 .iter()
890 .filter(|ev| matches!(ev.kind, EventKind::TurnStart))
891 .count();
892 let used = self.config.budget_scope.used(iteration, *drain_iterations);
893 if used >= self.config.max_iterations {
894 let reason = match self.config.budget_scope {
895 BudgetScope::Lifetime => {
896 format!("iteration budget exhausted after {iteration} turns")
897 }
898 BudgetScope::PerEpisode => format!(
899 "{} after {used} turns",
900 kian_core::seams::EPISODE_BUDGET_STOP_REASON_PREFIX
901 ),
902 };
903 return Ok(Flow::Stopped(reason));
904 }
905 if self.config.budget_scope == BudgetScope::PerEpisode {
906 *drain_iterations += 1;
907 }
908
909 if let Some(trigger) = preventive_trigger(&binding, &messages)
914 && let Some(flow) = self
915 .compact_now(ctx, &binding, iteration, trigger, compactions)
916 .await?
917 {
918 return Ok(flow);
919 }
920
921 let prepared = self.prepare_request(ctx, &binding, &messages).await;
927 if let Some(limit) = self
928 .config
929 .max_request_bytes
930 .get(&binding.target.provider)
931 .copied()
932 && let Ok(plan) = &prepared.plan
933 && let Ok(body) = serialize_request_body(&plan.body)
934 {
935 let request_bytes = body.len() as u64;
936 if request_bytes > limit {
937 if let Some(flow) = self
938 .compact_now(
939 ctx,
940 &binding,
941 iteration,
942 CompactionTrigger::Bytes {
943 request_bytes,
944 limit_bytes: limit,
945 },
946 compactions,
947 )
948 .await?
949 {
950 return Ok(flow);
951 }
952 tracing::warn!(
953 session = %ctx.session().0,
954 provider = %binding.target.provider,
955 request_bytes,
956 limit_bytes = limit,
957 compactions = *compactions,
958 keep_recent_turns = self.compaction.keep_recent_turns,
959 "request byte pressure: no fold relieved the request; sending it for the provider bound to refuse (ADR-072)"
960 );
961 }
962 }
963
964 ctx.begin_turn_with(json!({"iteration": iteration})).await?;
967 let turn = self
968 .provider_turn(ctx, &binding, &prepared, iteration)
969 .await;
970 let usage = turn.usage.as_ref();
971 let flow = match turn.result {
972 Ok(TurnOutcome::ToolCalls(n)) => {
973 let mut payload = json!({"iteration": iteration, "tool_calls": n});
974 if let Some(u) = usage {
975 payload["usage"] = u.clone();
976 }
977 ctx.end_turn_with(payload).await?;
978 return Ok(Flow::TurnDone);
979 }
980 Ok(TurnOutcome::FinalAnswer) => {
983 if ctx.has_eligible_inputs().await? {
984 Flow::TurnDone
985 } else {
986 Flow::Settled
987 }
988 }
989 Err(TurnError::AwaitingBudget { budget }) => {
990 let payload = json!({
991 "iteration": iteration,
992 "outcome": "awaiting_budget",
993 "budget": &budget,
994 });
995 let _ = ctx.end_turn_with(payload).await;
996 return Ok(Flow::AwaitingBudget(budget));
997 }
998 Err(TurnError::Soft { reason, audit }) => {
999 let mut payload = json!({
1000 "iteration": iteration,
1001 "outcome": "soft_failure",
1002 "error": audit,
1003 });
1004 if let Some(u) = usage {
1005 payload["usage"] = u.clone();
1006 }
1007 let _ = ctx.end_turn_with(payload).await;
1008 if let Some(trigger) = fold_trigger(&audit)
1017 && let Some(flow) = self
1018 .compact_now(ctx, &binding, iteration, trigger, compactions)
1019 .await?
1020 {
1021 return Ok(flow);
1022 }
1023 return Ok(Flow::Soft(reason));
1024 }
1025 Err(TurnError::Fatal { error, audit }) => {
1026 let mut payload = json!({
1027 "iteration": iteration,
1028 "outcome": "error",
1029 "error": audit,
1030 });
1031 if let Some(u) = usage {
1032 payload["usage"] = u.clone();
1033 }
1034 let _ = ctx.end_turn_with(payload).await;
1035 return Err(error);
1036 }
1037 };
1038 let mut payload = json!({"iteration": iteration, "outcome": "final_answer"});
1039 if let Some(u) = usage {
1040 payload["usage"] = u.clone();
1041 }
1042 ctx.end_turn_with(payload).await?;
1043 Ok(flow)
1044 }
1045
1046 async fn apply_confirmation(
1053 &self,
1054 ctx: &DrainCtx,
1055 call: &PendingCall,
1056 decision: &ConfirmIntent,
1057 ) -> Result<(), LoopError> {
1058 let result = match decision.decision {
1059 ConfirmDecision::Approve => {
1060 let tool_call = ToolCall {
1061 id: call.call_id.clone(),
1062 name: call.tool.clone(),
1063 arguments: call.arguments.clone(),
1064 };
1065 match self.tools.invoke(tool_call).await {
1066 Ok(r) => r,
1067 Err(e) => ToolResult {
1070 call_id: call.call_id.clone(),
1071 output: json!({"error": e.to_string()}),
1072 is_error: true,
1073 redactions: Vec::new(),
1074 },
1075 }
1076 }
1077 ConfirmDecision::Reject => ToolResult {
1078 call_id: call.call_id.clone(),
1079 output: if decision.expired {
1080 json!({
1081 "error": "confirmation expired",
1082 "policy": "ask",
1083 "expired": true
1084 })
1085 } else {
1086 match &decision.reason {
1087 Some(reason) => json!({
1088 "error": "permission denied by user",
1089 "policy": "ask",
1090 "reason": reason
1091 }),
1092 None => json!({
1093 "error": "permission denied by user",
1094 "policy": "ask"
1095 }),
1096 }
1097 },
1098 is_error: true,
1099 redactions: Vec::new(),
1100 },
1101 };
1102 let payload = tool_result_payload_confirmed(&result, decision);
1103 ctx.append(EventKind::ToolResult, payload).await?;
1104 Ok(())
1105 }
1106
1107 async fn binding_for(
1111 &self,
1112 ctx: &DrainCtx,
1113 events: &mut Arc<Vec<Event>>,
1114 ) -> Result<SlotBinding, LoopError> {
1115 let session = ctx.session();
1116 if let Ok(slots) = SessionSlots::replay(session, events)
1117 && slots.binding(&self.config.slot).is_ok()
1118 {
1119 return Ok(slots.binding(&self.config.slot)?.clone());
1120 }
1121 let fresh = SlotResolver::from_agent_def(&self.agent).bind_session(session);
1122 for payload in fresh.binding_payloads() {
1123 ctx.append(EventKind::SlotBinding, payload).await?;
1124 }
1125 *events = ctx.events().await?;
1128 Ok(fresh.binding(&self.config.slot)?.clone())
1129 }
1130
1131 async fn chat_messages(
1137 &self,
1138 ctx: &DrainCtx,
1139 profile: Option<&ModelProfile>,
1140 messages: &[Message],
1141 ) -> Vec<ChatMessage> {
1142 let vision = profile.is_some_and(|p| p.vision);
1143 let mut chat = Vec::with_capacity(messages.len());
1144 let mut pending: Vec<Option<Vec<ImageReference>>> = Vec::with_capacity(messages.len());
1145 let mut tail_start = 0;
1146 for message in messages {
1147 let Some(mut chat_message) = to_chat_message(message) else {
1148 continue;
1149 };
1150 if message.role == "assistant" {
1151 tail_start = chat.len() + 1;
1152 }
1153 let mut references = None;
1154 if vision
1155 && message.role == "user"
1156 && let Some((text, envelope)) = vision_envelope(&message.content)
1157 {
1158 chat_message.content = text;
1159 references = Some(envelope);
1160 }
1161 chat.push(chat_message);
1162 pending.push(references);
1163 }
1164 for (index, references) in pending.iter_mut().enumerate().take(tail_start) {
1165 if let Some(references) = references.take() {
1166 chat[index].images = self.load_images(ctx, &references).await;
1167 }
1168 }
1169 self.attach_tail_images(ctx, &mut chat, &mut pending, tail_start)
1170 .await;
1171 chat
1172 }
1173
1174 async fn attach_tail_images(
1179 &self,
1180 ctx: &DrainCtx,
1181 chat: &mut [ChatMessage],
1182 pending: &mut [Option<Vec<ImageReference>>],
1183 tail_start: usize,
1184 ) {
1185 let budget = self.config.vision;
1186 let mut loaded: Vec<Option<Vec<ChatImage>>> = (0..chat.len()).map(|_| None).collect();
1187 for index in tail_start..chat.len() {
1188 let Some(references) = pending[index].take() else {
1189 continue;
1190 };
1191 let mut images = Vec::with_capacity(references.len());
1192 for (artifact, media_type) in references.iter() {
1193 let Some(bytes) = ctx.artifact_bytes(artifact).await else {
1194 continue;
1195 };
1196 if bytes.len() > MAX_VISION_IMAGE_BYTES {
1197 tracing::warn!(
1198 artifact = %artifact,
1199 bytes = bytes.len(),
1200 limit = MAX_VISION_IMAGE_BYTES,
1201 "vision image is over the byte bound; the image is skipped (ADR-063)"
1202 );
1203 continue;
1204 }
1205 images.push(ChatImage {
1206 media_type: media_type.clone(),
1207 bytes,
1208 });
1209 }
1210 loaded[index] = Some(images);
1211 }
1212 let tail: Vec<Vec<usize>> = loaded
1213 .iter()
1214 .skip(tail_start)
1215 .map(|images| {
1216 images
1217 .as_ref()
1218 .map(|images| images.iter().map(|image| image.bytes.len()).collect())
1219 .unwrap_or_default()
1220 })
1221 .collect();
1222 let (per_message, admitted, dropped) = select_tail_images(budget, &tail);
1223 for (offset, count) in per_message.into_iter().enumerate() {
1224 let index = tail_start + offset;
1225 let Some(mut images) = loaded[index].take() else {
1226 continue;
1227 };
1228 let keep_from = images.len().saturating_sub(count);
1229 chat[index].images = images.split_off(keep_from);
1230 }
1231 if dropped > 0 {
1232 tracing::warn!(
1233 admitted,
1234 dropped,
1235 max_images_per_turn = budget.max_images_per_turn,
1236 max_image_bytes_per_turn = budget.max_image_bytes_per_turn,
1237 "per-turn image budget: the newest references in the tail are rendered; older ones stay text-only (ADR-066)"
1238 );
1239 }
1240 }
1241
1242 async fn load_images(&self, ctx: &DrainCtx, references: &[ImageReference]) -> Vec<ChatImage> {
1248 let mut images = Vec::new();
1249 for (artifact, media_type) in references.iter().take(MAX_IMAGES_PER_MESSAGE) {
1250 let Some(bytes) = ctx.artifact_bytes(artifact).await else {
1251 continue;
1252 };
1253 if bytes.len() > MAX_VISION_IMAGE_BYTES {
1254 tracing::warn!(
1255 artifact = %artifact,
1256 bytes = bytes.len(),
1257 limit = MAX_VISION_IMAGE_BYTES,
1258 "vision image is over the byte bound; the image is skipped (ADR-063)"
1259 );
1260 continue;
1261 }
1262 images.push(ChatImage {
1263 media_type: media_type.clone(),
1264 bytes,
1265 });
1266 }
1267 images
1268 }
1269
1270 async fn prepare_request(
1277 &self,
1278 ctx: &DrainCtx,
1279 binding: &SlotBinding,
1280 messages: &[Message],
1281 ) -> PreparedRequest {
1282 let target = &binding.target;
1283 let mut schemas = self.tools.schemas();
1286 schemas.sort_by(|a, b| a.name.cmp(&b.name));
1287 let chat = self
1288 .chat_messages(ctx, target.profile.as_ref(), messages)
1289 .await;
1290 let plan = build_request_plan(target.profile.as_ref(), &target.model, &chat, &schemas);
1291 PreparedRequest {
1292 schemas,
1293 chat,
1294 plan,
1295 }
1296 }
1297
1298 async fn provider_turn(
1304 &self,
1305 ctx: &DrainCtx,
1306 binding: &SlotBinding,
1307 prepared: &PreparedRequest,
1308 iteration: usize,
1309 ) -> TurnResult {
1310 let target = binding.target.clone();
1311
1312 let schemas = prepared.schemas.clone();
1315
1316 let plan = match &prepared.plan {
1320 Ok(plan) => plan,
1321 Err(e) => {
1322 return TurnResult {
1323 result: Err(TurnError::Soft {
1324 reason: format!("request plan: {e}"),
1325 audit: recovery_audit(self.policy.as_ref(), provider_error_class(e)),
1326 }),
1327 usage: None,
1328 };
1329 }
1330 };
1331 let budget = match ctx.events().await {
1337 Ok(events) => project_budget(&events, &self.agent.budgets),
1338 Err(e) => {
1339 return TurnResult {
1340 result: Err(TurnError::Soft {
1341 reason: format!("budget projection: {e}"),
1342 audit: json!({"class": "internal", "action": "none"}),
1343 }),
1344 usage: None,
1345 };
1346 }
1347 };
1348 let estimate = plan
1349 .estimate
1350 .high
1351 .saturating_add(plan.estimate.max_output_tokens.unwrap_or(0));
1352 let reserve = budget.maintenance_reserve_tokens().unwrap_or(0);
1355 if budget.would_exceed_tokens_reserving(estimate, reserve) {
1356 return TurnResult {
1357 result: Err(TurnError::AwaitingBudget {
1358 budget: json!({
1359 "limit": budget.tokens_limit,
1360 "raised": budget.tokens_raised,
1361 "spent": budget.tokens_spent,
1362 "estimate": estimate,
1363 "reserve": reserve,
1364 }),
1365 }),
1366 usage: None,
1367 };
1368 }
1369 let body = plan.body.clone();
1370 let (audit_body, body_form) = plan.audit();
1373 let mut step_payload = json!({
1374 "slot": self.config.slot.0,
1375 "provider": target.provider,
1376 "model": target.model,
1377 "iteration": iteration,
1378 "body": audit_body,
1379 "body_version": plan.body_version,
1380 "dialect": plan.dialect,
1381 "body_sha256": plan.body_sha256.clone(),
1382 "body_bytes": plan.body_bytes,
1383 "estimate": plan.estimate.clone(),
1384 });
1385 if let Some(form) = body_form {
1386 step_payload["body_form"] = json!(form);
1387 }
1388 if let Some(digest) = &plan.profile_digest {
1389 step_payload["profile_digest"] = json!(digest);
1390 }
1391 let step_request = ctx.append(EventKind::StepRequest, step_payload).await;
1392 let step_request_seq = match step_request {
1393 Ok(ev) => ev.seq,
1394 Err(e) => {
1395 let fatal = TurnError::fatal(e, self.policy.as_ref());
1396 if let TurnError::Fatal { audit, .. } = &fatal {
1398 self.observe_fatal(ctx, iteration, 0, audit, 0, 0, None)
1399 .await;
1400 }
1401 return TurnResult {
1402 result: Err(fatal),
1403 usage: None,
1404 };
1405 }
1406 };
1407 self.observe_request(
1412 ctx,
1413 binding,
1414 prepared.chat.len(),
1415 &schemas,
1416 iteration,
1417 &body,
1418 step_request_seq,
1419 )
1420 .await;
1421
1422 let build_chat = prepared.chat.clone();
1425 let build_schemas = schemas.clone();
1426 let build = Arc::new(move |t: &kian_core::model::SlotTarget| {
1427 build_request_plan(t.profile.as_ref(), &t.model, &build_chat, &build_schemas)
1428 });
1429 let mut stream = complete_turn(
1430 Arc::clone(&self.registry),
1431 self.config.slot.clone(),
1432 binding.clone(),
1433 build,
1434 Arc::new(CtxSlotSink { ctx: ctx.clone() }),
1435 );
1436
1437 let mut text = String::new();
1442 let mut reasoning = String::new();
1443 let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
1444 let mut usage: Option<Value> = None;
1445 let mut stream_error: Option<ProviderError> = None;
1446 while let Some(item) = stream.next().await {
1447 match item {
1448 Ok(chunk) => {
1449 if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
1450 usage = Some(u.clone()); }
1452 if !chunk.delta.is_null() {
1453 assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
1454 }
1455 }
1456 Err(e) => {
1457 stream_error = Some(e);
1458 break;
1459 }
1460 }
1461 }
1462 let text_bytes = text.len() as u64;
1465 let reasoning_bytes = reasoning.len() as u64;
1466 if let Some(e) = stream_error {
1467 let class = error_class(&e);
1468 let action = consult_policy(self.policy.as_ref(), class);
1469 let note = action_note(action);
1470 let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
1471 self.observe_recover(ctx, iteration, step_request_seq, &audit)
1474 .await;
1475 self.observe_response(
1476 ctx,
1477 iteration,
1478 step_request_seq,
1479 "soft_failure",
1480 0,
1481 text_bytes,
1482 reasoning_bytes,
1483 usage.as_ref(),
1484 Some(&audit),
1485 )
1486 .await;
1487 return TurnResult {
1488 result: Err(TurnError::Soft {
1489 reason: format!("provider error ({class}): {e}{note}"),
1490 audit,
1491 }),
1492 usage,
1493 };
1494 }
1495 if text.is_empty() && calls.is_empty() {
1496 let action = consult_policy(self.policy.as_ref(), CLASS_EMPTY_RESPONSE);
1499 let note = action_note(action);
1500 let audit = recovery_audit(
1501 self.policy.as_ref(),
1502 kian_orchestrator::recovery::ErrorClass::EmptyResponse,
1503 );
1504 self.observe_recover(ctx, iteration, step_request_seq, &audit)
1505 .await;
1506 self.observe_response(
1507 ctx,
1508 iteration,
1509 step_request_seq,
1510 "soft_failure",
1511 0,
1512 0,
1513 0,
1514 usage.as_ref(),
1515 Some(&audit),
1516 )
1517 .await;
1518 return TurnResult {
1519 result: Err(TurnError::Soft {
1520 reason: format!("empty model response{note}"),
1521 audit,
1522 }),
1523 usage,
1524 };
1525 }
1526
1527 let tool_calls: Vec<ToolCall> = calls.into_values().map(CallAcc::finish).collect();
1528 let mut content = json!({"text": text});
1529 if !tool_calls.is_empty() {
1530 content["tool_calls"] = Value::Array(
1531 tool_calls
1532 .iter()
1533 .map(|c| json!({"id": c.id, "name": c.name, "arguments": c.arguments}))
1534 .collect(),
1535 );
1536 }
1537 if !reasoning.is_empty() {
1538 content["reasoning_content"] = Value::String(reasoning);
1541 }
1542 if let Err(e) = ctx
1543 .append(
1544 EventKind::AssistantMessage,
1545 json!({"role": "assistant", "content": content}),
1546 )
1547 .await
1548 {
1549 let fatal = TurnError::fatal(e, self.policy.as_ref());
1550 if let TurnError::Fatal { audit, .. } = &fatal {
1551 self.observe_fatal(
1552 ctx,
1553 iteration,
1554 step_request_seq,
1555 audit,
1556 text_bytes,
1557 reasoning_bytes,
1558 usage.as_ref(),
1559 )
1560 .await;
1561 }
1562 return TurnResult {
1563 result: Err(fatal),
1564 usage,
1565 };
1566 }
1567
1568 if tool_calls.is_empty() {
1569 self.observe_response(
1571 ctx,
1572 iteration,
1573 step_request_seq,
1574 "final_answer",
1575 0,
1576 text_bytes,
1577 reasoning_bytes,
1578 usage.as_ref(),
1579 None,
1580 )
1581 .await;
1582 return TurnResult {
1583 result: Ok(TurnOutcome::FinalAnswer),
1584 usage,
1585 };
1586 }
1587
1588 let n = tool_calls.len();
1589 for call in tool_calls {
1595 let decision = evaluate_permission(&self.config.permissions, &call.name);
1600 let hook_verdict = self
1612 .consult_tool_pre(ctx, &call, iteration, step_request_seq, decision)
1613 .await;
1614 let appended = match hook_verdict {
1615 kian_plugin::hooks::ToolVerdict::Deny {
1616 ref plugin,
1617 ref reason,
1618 } => {
1619 ctx.append(
1624 EventKind::ToolCall,
1625 tool_call_payload_hook_denied(&call, plugin, reason),
1626 )
1627 .await
1628 }
1629 _ => {
1630 ctx.append(EventKind::ToolCall, tool_call_payload(&call, decision))
1631 .await
1632 }
1633 };
1634 let call_seq = match appended {
1635 Ok(ev) => ev.seq,
1636 Err(e) => {
1637 let fatal = TurnError::fatal(e, self.policy.as_ref());
1638 if let TurnError::Fatal { audit, .. } = &fatal {
1639 self.observe_fatal(
1640 ctx,
1641 iteration,
1642 step_request_seq,
1643 audit,
1644 text_bytes,
1645 reasoning_bytes,
1646 usage.as_ref(),
1647 )
1648 .await;
1649 }
1650 return TurnResult {
1651 result: Err(fatal),
1652 usage,
1653 };
1654 }
1655 };
1656 if let kian_plugin::hooks::ToolVerdict::Deny {
1667 ref plugin,
1668 ref reason,
1669 } = hook_verdict
1670 {
1671 let denied = ToolResult {
1672 call_id: call.id.clone(),
1673 output: json!({
1674 "error": format!("denied by plugin {plugin}: {reason}"),
1675 "policy": "hook"
1676 }),
1677 is_error: true,
1678 redactions: Vec::new(),
1679 };
1680 if let Err(e) = ctx
1681 .append(EventKind::ToolResult, tool_result_payload(&denied))
1682 .await
1683 {
1684 let fatal = TurnError::fatal(e, self.policy.as_ref());
1685 if let TurnError::Fatal { audit, .. } = &fatal {
1686 self.observe_fatal(
1687 ctx,
1688 iteration,
1689 call_seq,
1690 audit,
1691 text_bytes,
1692 reasoning_bytes,
1693 usage.as_ref(),
1694 )
1695 .await;
1696 }
1697 return TurnResult {
1698 result: Err(fatal),
1699 usage,
1700 };
1701 }
1702 self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1703 .await;
1704 continue;
1705 }
1706 if matches!(decision, Some(PermissionDecision::Ask)) {
1710 continue;
1711 }
1712 if let Some(denied) = declared_denial(&call, decision) {
1717 if let Err(e) = ctx
1718 .append(EventKind::ToolResult, tool_result_payload(&denied))
1719 .await
1720 {
1721 let fatal = TurnError::fatal(e, self.policy.as_ref());
1722 if let TurnError::Fatal { audit, .. } = &fatal {
1723 self.observe_fatal(
1724 ctx,
1725 iteration,
1726 call_seq,
1727 audit,
1728 text_bytes,
1729 reasoning_bytes,
1730 usage.as_ref(),
1731 )
1732 .await;
1733 }
1734 return TurnResult {
1735 result: Err(fatal),
1736 usage,
1737 };
1738 }
1739 self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1742 .await;
1743 continue;
1744 }
1745 let result = match self.tools.invoke(call.clone()).await {
1746 Ok(r) => r,
1747 Err(e) => {
1748 ToolResult {
1751 call_id: call.id.clone(),
1752 output: json!({"error": e.to_string()}),
1753 is_error: true,
1754 redactions: Vec::new(),
1755 }
1756 }
1757 };
1758 let result_seq = match ctx
1763 .append(EventKind::ToolResult, tool_result_payload(&result))
1764 .await
1765 {
1766 Ok(ev) => ev.seq,
1767 Err(e) => {
1768 let fatal = TurnError::fatal(e, self.policy.as_ref());
1769 if let TurnError::Fatal { audit, .. } = &fatal {
1770 self.observe_fatal(
1771 ctx,
1772 iteration,
1773 call_seq,
1774 audit,
1775 text_bytes,
1776 reasoning_bytes,
1777 usage.as_ref(),
1778 )
1779 .await;
1780 }
1781 return TurnResult {
1782 result: Err(fatal),
1783 usage,
1784 };
1785 }
1786 };
1787 self.observe_tool_post(ctx, &result, &call.name, result_seq)
1790 .await;
1791 }
1792 self.observe_response(
1795 ctx,
1796 iteration,
1797 step_request_seq,
1798 "tool_calls",
1799 n as u64,
1800 text_bytes,
1801 reasoning_bytes,
1802 usage.as_ref(),
1803 None,
1804 )
1805 .await;
1806 TurnResult {
1807 result: Ok(TurnOutcome::ToolCalls(n)),
1808 usage,
1809 }
1810 }
1811
1812 async fn compact_now(
1819 &self,
1820 ctx: &DrainCtx,
1821 binding: &SlotBinding,
1822 iteration: usize,
1823 trigger: CompactionTrigger,
1824 compactions: &mut usize,
1825 ) -> Result<Option<Flow>, LoopError> {
1826 if *compactions >= MAX_COMPACTIONS_PER_EPISODE {
1827 return Ok(None);
1828 }
1829 let events = ctx.events().await?;
1830 let plan = match plan_compaction(&events, &self.compaction, Some(&trigger)) {
1831 Ok(Some(plan)) => plan,
1832 Ok(None) => return Ok(None),
1833 Err(e) => {
1834 tracing::warn!(
1835 session = %ctx.session().0,
1836 error = %e,
1837 "compaction planner refused the stream"
1838 );
1839 return Ok(None);
1840 }
1841 };
1842 let transcript = match render_folded_transcript(&events, &plan) {
1843 Ok(transcript) => transcript,
1844 Err(e) => {
1845 tracing::warn!(
1846 session = %ctx.session().0,
1847 error = %e,
1848 "compaction transcript refused the stream"
1849 );
1850 return Ok(None);
1851 }
1852 };
1853 let target = binding.target.clone();
1854 let chat = summary_chat(&transcript);
1855 let request = match build_request_plan(target.profile.as_ref(), &target.model, &chat, &[]) {
1856 Ok(request) => request,
1857 Err(e) => return Ok(Some(Flow::Soft(format!("compact request plan: {e}")))),
1858 };
1859 let estimate = request
1860 .estimate
1861 .high
1862 .saturating_add(request.estimate.max_output_tokens.unwrap_or(0));
1863 let budget = project_budget(&events, &self.agent.budgets);
1866 if budget.would_exceed_tokens(estimate) {
1867 return Ok(Some(Flow::AwaitingBudget(json!({
1868 "limit": budget.tokens_limit,
1869 "raised": budget.tokens_raised,
1870 "spent": budget.tokens_spent,
1871 "estimate": estimate,
1872 "purpose": "compact",
1873 }))));
1874 }
1875
1876 ctx.begin_turn_with(json!({"iteration": iteration, "purpose": "compact"}))
1877 .await?;
1878 let (audit_body, body_form) = request.audit();
1879 let mut step_payload = json!({
1880 "slot": self.config.slot.0,
1881 "provider": target.provider,
1882 "model": target.model,
1883 "iteration": iteration,
1884 "purpose": "compact",
1885 "body": audit_body,
1886 "body_version": request.body_version,
1887 "dialect": request.dialect,
1888 "body_sha256": request.body_sha256,
1889 "body_bytes": request.body_bytes,
1890 "estimate": request.estimate,
1891 });
1892 if let Some(form) = body_form {
1893 step_payload["body_form"] = json!(form);
1894 }
1895 if let Some(digest) = &request.profile_digest {
1896 step_payload["profile_digest"] = json!(digest);
1897 }
1898 let step_request_seq = match ctx.append(EventKind::StepRequest, step_payload).await {
1899 Ok(event) => event.seq,
1900 Err(e) => {
1901 let _ = ctx
1902 .end_turn_with(json!({
1903 "iteration": iteration,
1904 "purpose": "compact",
1905 "outcome": "error",
1906 "error": {"class": "internal", "action": "none"},
1907 }))
1908 .await;
1909 return Err(e.into());
1910 }
1911 };
1912 let Some(provider) = self.registry.get(&target.provider) else {
1915 let audit = recovery_audit(
1916 self.policy.as_ref(),
1917 kian_orchestrator::recovery::ErrorClass::Unknown,
1918 );
1919 let _ = ctx
1920 .end_turn_with(json!({
1921 "iteration": iteration,
1922 "purpose": "compact",
1923 "outcome": "soft_failure",
1924 "error": audit,
1925 }))
1926 .await;
1927 return Ok(Some(Flow::Soft(format!(
1928 "compact: provider {} is not registered",
1929 target.provider
1930 ))));
1931 };
1932 let mut stream = provider.complete(ModelRequest {
1933 slot: self.config.slot.clone(),
1934 body: request.body,
1935 });
1936 let mut text = String::new();
1937 let mut reasoning = String::new();
1938 let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
1939 let mut usage: Option<Value> = None;
1940 let mut stream_error: Option<ProviderError> = None;
1941 while let Some(item) = stream.next().await {
1942 match item {
1943 Ok(chunk) => {
1944 if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
1945 usage = Some(u.clone());
1946 }
1947 if !chunk.delta.is_null() {
1948 assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
1949 }
1950 }
1951 Err(e) => {
1952 stream_error = Some(e);
1953 break;
1954 }
1955 }
1956 }
1957 if let Some(e) = stream_error {
1958 let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
1959 let mut payload = json!({
1960 "iteration": iteration,
1961 "purpose": "compact",
1962 "outcome": "soft_failure",
1963 "error": audit,
1964 });
1965 if let Some(u) = usage.as_ref() {
1966 payload["usage"] = u.clone();
1967 }
1968 let _ = ctx.end_turn_with(payload).await;
1969 return Ok(Some(Flow::Soft(format!(
1970 "compact summary request failed: {e}"
1971 ))));
1972 }
1973 let summary = text.trim().to_string();
1974 if summary.is_empty() {
1975 let audit = recovery_audit(
1976 self.policy.as_ref(),
1977 kian_orchestrator::recovery::ErrorClass::EmptyResponse,
1978 );
1979 let mut payload = json!({
1980 "iteration": iteration,
1981 "purpose": "compact",
1982 "outcome": "soft_failure",
1983 "error": audit,
1984 });
1985 if let Some(u) = usage.as_ref() {
1986 payload["usage"] = u.clone();
1987 }
1988 let _ = ctx.end_turn_with(payload).await;
1989 return Ok(Some(Flow::Soft(
1990 "compact summary request returned an empty response".to_string(),
1991 )));
1992 }
1993 let compact_seq = match ctx
1996 .append(
1997 EventKind::Compact,
1998 json!({
1999 "from_seq": plan.from_seq,
2000 "to_seq": plan.to_seq,
2001 "summary": {"role": "assistant", "content": {"text": summary}},
2002 "produced_by": {"step_seq": step_request_seq},
2003 "reason": plan.reason,
2004 "folded_messages": plan.folded_messages,
2005 "reclaimed_tokens": plan.reclaimed_tokens,
2006 }),
2007 )
2008 .await
2009 {
2010 Ok(event) => event.seq,
2011 Err(e) => {
2012 let _ = ctx
2013 .end_turn_with(json!({
2014 "iteration": iteration,
2015 "purpose": "compact",
2016 "outcome": "error",
2017 "error": {"class": "internal", "action": "none"},
2018 }))
2019 .await;
2020 return Err(e.into());
2021 }
2022 };
2023 let mut payload = json!({
2024 "iteration": iteration,
2025 "purpose": "compact",
2026 "outcome": "compacted",
2027 "compact_seq": compact_seq,
2028 "from_seq": plan.from_seq,
2029 "to_seq": plan.to_seq,
2030 });
2031 if let Some(u) = usage.as_ref() {
2032 payload["usage"] = u.clone();
2033 }
2034 if let Err(e) = ctx.end_turn_with(payload).await {
2035 return Err(e.into());
2036 }
2037 *compactions += 1;
2038 tracing::info!(
2039 session = %ctx.session().0,
2040 from_seq = plan.from_seq,
2041 to_seq = plan.to_seq,
2042 folded_messages = plan.folded_messages,
2043 reclaimed_tokens = plan.reclaimed_tokens,
2044 "context compacted (ADR-058)"
2045 );
2046 Ok(Some(Flow::TurnDone))
2047 }
2048}
2049
2050impl TurnError {
2055 fn fatal(e: EngineError, policy: &dyn RecoveryPolicySource) -> Self {
2060 let error = LoopError::Engine(e);
2061 let audit = recovery_audit(policy, loop_error_class(&error));
2062 Self::Fatal { error, audit }
2063 }
2064}
2065
2066fn loop_error_class(e: &LoopError) -> kian_orchestrator::recovery::ErrorClass {
2072 match e {
2073 LoopError::Engine(_) => kian_orchestrator::recovery::ErrorClass::StoreFailure,
2074 LoopError::Context(_) | LoopError::Slot(_) => {
2075 kian_orchestrator::recovery::ErrorClass::Unknown
2076 }
2077 }
2078}
2079
2080fn preventive_trigger(binding: &SlotBinding, messages: &[Message]) -> Option<CompactionTrigger> {
2083 let profile = binding.target.profile.as_ref()?;
2084 let window = profile.context_window?;
2085 if window == 0 {
2086 return None;
2087 }
2088 let incoming = estimate_context_tokens(messages)
2089 .saturating_add(profile.max_output.unwrap_or(DEFAULT_OUTPUT_RESERVE_TOKENS));
2090 Some(CompactionTrigger::Pressure(CompactionPressure {
2091 context_window_tokens: window,
2092 incoming_estimate_tokens: incoming,
2093 }))
2094}
2095
2096fn render_folded_transcript(
2101 events: &[Event],
2102 plan: &CompactionPlan,
2103) -> Result<String, kian_core::context::ContextError> {
2104 let messages = derive_model_context(events)?;
2105 let provenance = context_provenance(events)?;
2106 let mut out = String::new();
2107 for (message, source) in messages.iter().zip(provenance.iter()) {
2108 if !(plan.from_seq..plan.to_seq).contains(source) {
2109 continue;
2110 }
2111 let body = match &message.content {
2112 Value::String(text) => text.clone(),
2113 other => serde_json::to_string(other).unwrap_or_default(),
2114 };
2115 let line = format!("{}: {body}\n", message.role);
2116 if out.len().saturating_add(line.len()) > MAX_TRANSCRIPT_CHARS {
2117 let room = MAX_TRANSCRIPT_CHARS.saturating_sub(out.len());
2118 out.push_str(take_chars(&line, room));
2119 out.push_str("\n[... transcript truncated ...]\n");
2120 break;
2121 }
2122 out.push_str(&line);
2123 }
2124 Ok(out)
2125}
2126
2127fn take_chars(text: &str, max: usize) -> &str {
2130 match text.char_indices().nth(max) {
2131 Some((index, _)) => &text[..index],
2132 None => text,
2133 }
2134}
2135
2136fn summary_chat(transcript: &str) -> Vec<ChatMessage> {
2140 vec![
2141 ChatMessage::plain("system", SUMMARY_SYSTEM_PROMPT),
2142 ChatMessage::plain(
2143 "user",
2144 format!(
2145 "Compress the following earlier conversation into one dense summary. The summary will replace these turns in the model context.\n\n{transcript}"
2146 ),
2147 ),
2148 ]
2149}
2150
2151fn provider_error_class(e: &ProviderError) -> kian_orchestrator::recovery::ErrorClass {
2154 kian_orchestrator::recovery::classify(
2155 &kian_orchestrator::recovery::RecoveryError::Provider(e.clone()),
2156 &kian_orchestrator::recovery::ClassifyCtx { attempt: 0 },
2157 )
2158}
2159
2160fn recovery_audit(
2164 policy: &dyn RecoveryPolicySource,
2165 class: kian_orchestrator::recovery::ErrorClass,
2166) -> Value {
2167 let action = consult_policy(policy, class.name());
2168 json!({
2169 "class": class.name(),
2170 "action": action_name(action.as_ref()),
2171 })
2172}
2173
2174fn action_name(action: Option<&RecoveryAction>) -> &'static str {
2177 match action {
2178 None => "none",
2179 Some(RecoveryAction::BackoffRetry { .. }) => "backoff_retry",
2180 Some(RecoveryAction::CompressThenRetry) => "compress_then_retry",
2181 Some(RecoveryAction::Failover) => "failover",
2182 Some(RecoveryAction::InterruptAsk) => "interrupt_ask",
2183 Some(RecoveryAction::Fail) => "fail",
2184 }
2185}
2186
2187fn fold_trigger(audit: &Value) -> Option<CompactionTrigger> {
2192 if audit.get("action").and_then(Value::as_str)
2193 != Some(action_name(Some(&RecoveryAction::CompressThenRetry)))
2194 {
2195 return None;
2196 }
2197 let class = audit.get("class").and_then(Value::as_str)?;
2198 if class == kian_orchestrator::recovery::ErrorClass::ContextOverflow.name() {
2199 return Some(CompactionTrigger::Overflow);
2200 }
2201 if class == kian_orchestrator::recovery::ErrorClass::RequestTooLarge.name() {
2202 return Some(CompactionTrigger::Oversized);
2203 }
2204 None
2205}
2206
2207struct CtxSlotSink {
2211 ctx: DrainCtx,
2212}
2213
2214impl SlotEventSink for CtxSlotSink {
2215 fn persist_fallback(
2216 &self,
2217 payload: Value,
2218 ) -> futures::future::BoxFuture<'static, Result<(), String>> {
2219 let ctx = self.ctx.clone();
2220 Box::pin(async move {
2221 ctx.append(EventKind::SlotFallback, payload)
2222 .await
2223 .map(|_| ())
2224 .map_err(|e| e.to_string())
2225 })
2226 }
2227}
2228
2229struct CallAcc {
2231 id: String,
2232 name: String,
2233 arguments: String,
2234}
2235
2236impl CallAcc {
2237 fn finish(self) -> ToolCall {
2238 let arguments = serde_json::from_str::<Value>(&self.arguments)
2239 .unwrap_or_else(|_| Value::String(self.arguments.clone()));
2240 ToolCall {
2241 id: self.id,
2242 name: self.name,
2243 arguments,
2244 }
2245 }
2246}
2247
2248fn assemble_delta(
2251 delta: &Value,
2252 text: &mut String,
2253 reasoning: &mut String,
2254 calls: &mut BTreeMap<u64, CallAcc>,
2255) {
2256 if let Some(fragment) = delta.get("content").and_then(Value::as_str) {
2257 text.push_str(fragment);
2258 }
2259 if let Some(fragment) = delta.get("reasoning_content").and_then(Value::as_str) {
2260 reasoning.push_str(fragment);
2261 }
2262 if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) {
2263 for entry in list {
2264 let index = entry.get("index").and_then(Value::as_u64).unwrap_or(0);
2265 let slot = calls.entry(index).or_insert_with(|| CallAcc {
2266 id: String::new(),
2267 name: String::new(),
2268 arguments: String::new(),
2269 });
2270 if let Some(id) = entry.get("id").and_then(Value::as_str) {
2271 slot.id = id.to_string();
2272 }
2273 if let Some(name) = entry.pointer("/function/name").and_then(Value::as_str) {
2274 slot.name.push_str(name);
2275 }
2276 if let Some(args) = entry.pointer("/function/arguments").and_then(Value::as_str) {
2277 slot.arguments.push_str(args);
2278 }
2279 }
2280 }
2281}
2282
2283pub fn to_chat_message(m: &Message) -> Option<ChatMessage> {
2308 match m.role.as_str() {
2309 "tool" => Some(tool_result_message(&m.content)),
2310 "assistant" => assistant_message(&m.content),
2311 _ => Some(string_or_compact(&m.role, &m.content)),
2312 }
2313}
2314
2315type ImageReference = (String, String);
2317
2318type VisionEnvelope = (Option<String>, Vec<ImageReference>);
2320
2321fn vision_envelope(content: &Value) -> Option<VisionEnvelope> {
2335 let object = content.as_object()?;
2336 let references = object.get("images")?.as_array()?;
2337 let mut usable = Vec::new();
2338 for item in references {
2339 let Some(entry) = item.as_object() else {
2340 continue;
2341 };
2342 let Some(artifact) = entry
2343 .get("artifact")
2344 .and_then(Value::as_str)
2345 .filter(|id| !id.is_empty())
2346 else {
2347 continue;
2348 };
2349 let Some(media_type) = entry
2350 .get("media_type")
2351 .and_then(Value::as_str)
2352 .filter(|t| !t.is_empty())
2353 else {
2354 continue;
2355 };
2356 usable.push((artifact.to_owned(), media_type.to_owned()));
2357 }
2358 if usable.is_empty() {
2359 return None;
2360 }
2361 let mut remainder = object.clone();
2362 remainder.remove("images");
2363 let text = if remainder.is_empty() {
2364 None
2365 } else if remainder.len() == 1 && remainder.get("text").is_some_and(Value::is_string) {
2366 remainder
2367 .get("text")
2368 .and_then(Value::as_str)
2369 .map(str::to_owned)
2370 } else {
2371 Some(serde_json::to_string(&Value::Object(remainder)).unwrap_or_default())
2372 };
2373 Some((text, usable))
2374}
2375
2376#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2379pub(crate) enum PermissionDecision {
2380 AllowConfigured,
2382 AllowDefault,
2384 Deny,
2386 Ask,
2389}
2390
2391const PERMISSION_DENY_REASON: &str = "tool_denied_by_policy";
2393
2394fn evaluate_permission(
2404 permissions: &BTreeMap<String, Permission>,
2405 tool: &str,
2406) -> Option<PermissionDecision> {
2407 if permissions.is_empty() {
2408 return None;
2409 }
2410 match permissions.get(tool) {
2411 Some(Permission::Allow) => Some(PermissionDecision::AllowConfigured),
2412 Some(Permission::Deny) => Some(PermissionDecision::Deny),
2413 Some(Permission::Ask) => Some(PermissionDecision::Ask),
2414 None => Some(PermissionDecision::AllowDefault),
2415 }
2416}
2417
2418fn declared_denial(call: &ToolCall, decision: Option<PermissionDecision>) -> Option<ToolResult> {
2423 matches!(decision, Some(PermissionDecision::Deny)).then(|| ToolResult {
2424 call_id: call.id.clone(),
2425 output: json!({
2426 "error": format!("permission denied by policy: {}", call.name),
2427 "policy": "deny"
2428 }),
2429 is_error: true,
2430 redactions: Vec::new(),
2431 })
2432}
2433
2434fn tool_call_payload(call: &ToolCall, decision: Option<PermissionDecision>) -> Value {
2440 let mut payload = json!({
2441 "role": "assistant",
2442 "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
2443 });
2444 if let Some(decision) = decision {
2445 payload["permission"] = match decision {
2446 PermissionDecision::AllowConfigured => json!({
2447 "evaluated": "allow", "policy": "configured", "matched": call.name
2448 }),
2449 PermissionDecision::AllowDefault => json!({
2450 "evaluated": "allow", "policy": "default", "matched": call.name
2451 }),
2452 PermissionDecision::Deny => json!({
2453 "evaluated": "deny",
2454 "policy": "configured",
2455 "matched": call.name,
2456 "reason": PERMISSION_DENY_REASON
2457 }),
2458 PermissionDecision::Ask => json!({
2459 "evaluated": "ask",
2460 "policy": "configured",
2461 "matched": call.name
2462 }),
2463 };
2464 }
2465 payload
2466}
2467
2468fn tool_call_payload_hook_denied(call: &ToolCall, plugin: &str, reason: &str) -> Value {
2476 let mut payload = json!({
2477 "role": "assistant",
2478 "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
2479 });
2480 payload["permission"] = json!({
2481 "evaluated": "deny",
2482 "policy": "hook",
2483 "matched": format!("{plugin}:tool/pre"),
2484 "reason": reason,
2485 });
2486 payload
2487}
2488
2489fn permission_view(
2494 call: &ToolCall,
2495 decision: Option<PermissionDecision>,
2496) -> kian_plugin::hooks::PermissionView {
2497 match decision {
2498 Some(PermissionDecision::AllowConfigured) => kian_plugin::hooks::PermissionView {
2499 evaluated: "allow".to_string(),
2500 policy: "configured".to_string(),
2501 matched: call.name.clone(),
2502 reason: None,
2503 },
2504 Some(PermissionDecision::Deny) => kian_plugin::hooks::PermissionView {
2505 evaluated: "deny".to_string(),
2506 policy: "configured".to_string(),
2507 matched: call.name.clone(),
2508 reason: Some(PERMISSION_DENY_REASON.to_string()),
2509 },
2510 Some(PermissionDecision::Ask) => kian_plugin::hooks::PermissionView {
2511 evaluated: "ask".to_string(),
2512 policy: "configured".to_string(),
2513 matched: call.name.clone(),
2514 reason: None,
2515 },
2516 Some(PermissionDecision::AllowDefault) | None => kian_plugin::hooks::PermissionView {
2517 evaluated: "allow".to_string(),
2518 policy: "default".to_string(),
2519 matched: call.name.clone(),
2520 reason: None,
2521 },
2522 }
2523}
2524
2525fn tool_result_payload(result: &ToolResult) -> Value {
2532 let mut payload = json!({
2533 "role": "tool",
2534 "content": {
2535 "call_id": result.call_id,
2536 "output": result.output,
2537 "is_error": result.is_error
2538 }
2539 });
2540 if !result.redactions.is_empty() {
2541 if let Ok(report) = serde_json::to_value(&result.redactions) {
2544 payload["redactions"] = report;
2545 }
2546 }
2547 payload
2548}
2549
2550fn tool_result_payload_confirmed(result: &ToolResult, decision: &ConfirmIntent) -> Value {
2554 let mut payload = tool_result_payload(result);
2555 let mut provenance = json!({
2556 "call_id": result.call_id,
2557 "decision": decision.decision.as_str(),
2558 "requested_by": decision.requested_by,
2559 "answered_at_ms": decision.answered_at_ms,
2560 });
2561 if decision.expired {
2562 provenance["expired"] = json!(true);
2563 }
2564 payload["confirmation"] = provenance;
2565 payload
2566}
2567
2568fn string_or_compact(role: &str, content: &Value) -> ChatMessage {
2571 let text = match content {
2572 Value::String(s) => s.clone(),
2573 other => serde_json::to_string(other).unwrap_or_default(),
2574 };
2575 ChatMessage {
2576 role: role.to_owned(),
2577 content: Some(text),
2578 tool_call_id: None,
2579 tool_calls: None,
2580 reasoning_content: None,
2581 images: Vec::new(),
2582 }
2583}
2584
2585fn tool_result_message(content: &Value) -> ChatMessage {
2589 if let Some(obj) = content.as_object()
2590 && let Some(call_id) = obj.get("call_id").and_then(Value::as_str)
2591 {
2592 let output = obj.get("output").cloned().unwrap_or(Value::Null);
2593 return ChatMessage {
2594 role: "tool".into(),
2595 content: Some(serde_json::to_string(&output).unwrap_or_default()),
2596 tool_call_id: Some(call_id.to_owned()),
2597 tool_calls: None,
2598 reasoning_content: None,
2599 images: Vec::new(),
2600 };
2601 }
2602 ChatMessage {
2603 role: "tool".into(),
2604 content: Some(serde_json::to_string(content).unwrap_or_default()),
2605 tool_call_id: Some(String::new()),
2606 tool_calls: None,
2607 reasoning_content: None,
2608 images: Vec::new(),
2609 }
2610}
2611
2612fn reasoning_field(obj: &serde_json::Map<String, Value>) -> Option<String> {
2615 obj.get("reasoning_content")
2616 .and_then(Value::as_str)
2617 .filter(|r| !r.is_empty())
2618 .map(str::to_owned)
2619}
2620
2621fn assistant_message(content: &Value) -> Option<ChatMessage> {
2625 let Some(obj) = content.as_object() else {
2626 return Some(string_or_compact("assistant", content));
2627 };
2628 if obj.contains_key("tool_calls") {
2629 let calls: Option<Vec<WireToolCall>> =
2630 obj.get("tool_calls").and_then(Value::as_array).map(|list| {
2631 list.iter()
2632 .filter_map(|tc| {
2633 let id = tc.get("id").and_then(Value::as_str)?;
2634 let name = tc.get("name").and_then(Value::as_str)?;
2635 let arguments = tc.get("arguments").cloned().unwrap_or(Value::Null);
2636 Some(WireToolCall {
2637 id: id.to_owned(),
2638 r#type: "function".into(),
2639 function: WireFunctionCall {
2640 name: name.to_owned(),
2641 arguments: serde_json::to_string(&arguments).unwrap_or_default(),
2642 },
2643 })
2644 })
2645 .collect()
2646 });
2647 return Some(ChatMessage {
2648 role: "assistant".into(),
2649 content: obj
2652 .get("text")
2653 .and_then(Value::as_str)
2654 .filter(|t| !t.is_empty())
2655 .map(str::to_owned),
2656 tool_call_id: None,
2657 tool_calls: calls,
2658 reasoning_content: reasoning_field(obj),
2659 images: Vec::new(),
2660 });
2661 }
2662 if obj.contains_key("id") && obj.contains_key("name") && obj.contains_key("arguments") {
2665 return None;
2666 }
2667 if let Some(text) = obj.get("text").and_then(Value::as_str) {
2668 return Some(ChatMessage {
2669 role: "assistant".into(),
2670 content: Some(text.to_owned()),
2671 tool_call_id: None,
2672 tool_calls: None,
2673 reasoning_content: reasoning_field(obj),
2674 images: Vec::new(),
2675 });
2676 }
2677 Some(string_or_compact("assistant", content))
2678}
2679
2680fn resident_empty_batch(scope: BudgetScope, taken_empty: bool, last_role: Option<&str>) -> bool {
2685 scope == BudgetScope::PerEpisode && taken_empty && last_role == Some("assistant")
2686}
2687
2688fn error_class(e: &ProviderError) -> &'static str {
2691 match e {
2692 ProviderError::RateLimited => "rate_limited",
2693 ProviderError::ContextOverflow => "context_overflow",
2694 ProviderError::Unavailable(_) | ProviderError::Transport(_) => "provider_down",
2695 ProviderError::EmptyResponse => CLASS_EMPTY_RESPONSE,
2696 ProviderError::RequestTooLarge { .. } => "request_too_large",
2699 ProviderError::InvalidResponse(_) => "validation_failed",
2700 ProviderError::Other(_) => "internal",
2701 }
2702}
2703
2704fn select_tail_images(budget: VisionBudget, tail: &[Vec<usize>]) -> (Vec<usize>, usize, usize) {
2716 let total: usize = tail.iter().map(|sizes| sizes.len()).sum();
2717 let mut per_message = vec![0usize; tail.len()];
2718 let mut admitted = 0usize;
2719 let mut admitted_bytes = 0u64;
2720 'selection: for (index, sizes) in tail.iter().enumerate().rev() {
2721 for size in sizes.iter().rev() {
2722 if per_message[index] >= MAX_IMAGES_PER_MESSAGE {
2723 break 'selection;
2724 }
2725 if admitted >= budget.max_images_per_turn
2726 || admitted_bytes + *size as u64 > budget.max_image_bytes_per_turn
2727 {
2728 break 'selection;
2729 }
2730 admitted += 1;
2731 admitted_bytes += *size as u64;
2732 per_message[index] += 1;
2733 }
2734 }
2735 (per_message, admitted, total - admitted)
2736}
2737
2738fn consult_policy(policy: &dyn RecoveryPolicySource, class: &str) -> Option<RecoveryAction> {
2739 policy
2740 .table()
2741 .into_iter()
2742 .find(|rule| rule.class == class)
2743 .map(|rule| rule.action)
2744}
2745
2746fn action_note(action: Option<RecoveryAction>) -> String {
2747 match action {
2748 Some(a) => format!("; recovery policy action: {a:?}"),
2749 None => "; no matching recovery policy rule".into(),
2750 }
2751}
2752
2753#[cfg(test)]
2754mod tests {
2755 use crate::react::{
2756 BudgetScope, CLASS_EMPTY_RESPONSE, ReActConfig, ReActLoop, assemble_delta, consult_policy,
2757 to_chat_message, tool_result_payload,
2758 };
2759 use crate::test_support::{NoopPolicy, NoopTools, agent_def};
2760 use kian_core::context::{Message, derive_model_context};
2761 use kian_core::events::{Event, EventKind};
2762 use kian_core::model::SessionId;
2763 use kian_core::seams::{ToolCall, ToolResult};
2764 use kian_core::secrets::{Redaction, RedactionKind};
2765 use kian_llm::provider::build_chat_body;
2766 use serde_json::json;
2767 use std::collections::BTreeMap;
2768
2769 fn msg(role: &str, content: serde_json::Value) -> Message {
2770 Message {
2771 role: role.into(),
2772 content,
2773 synthetic: false,
2774 }
2775 }
2776
2777 #[test]
2782 fn tool_result_payload_carries_redactions_outside_content() {
2783 let plain = ToolResult {
2784 call_id: "call-1".into(),
2785 output: json!({"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false}),
2786 is_error: false,
2787 redactions: Vec::new(),
2788 };
2789 let payload = tool_result_payload(&plain);
2790 assert_eq!(
2791 payload,
2792 json!({
2793 "role": "tool",
2794 "content": {
2795 "call_id": "call-1",
2796 "output": {"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false},
2797 "is_error": false
2798 }
2799 }),
2800 "no redactions → no key, bytes unchanged"
2801 );
2802
2803 let redacted = ToolResult {
2804 call_id: "call-2".into(),
2805 output: json!({"exit_code": 0, "stdout": "[REDACTED:token]", "stderr": "", "timed_out": false}),
2806 is_error: false,
2807 redactions: vec![Redaction {
2808 kind: RedactionKind::TokenPattern,
2809 name: "ghp_".into(),
2810 count: 1,
2811 }],
2812 };
2813 let payload = tool_result_payload(&redacted);
2814 assert_eq!(
2815 payload["redactions"],
2816 json!([{"kind": "token_pattern", "name": "ghp_", "count": 1}])
2817 );
2818 assert!(payload["content"].get("redactions").is_none());
2821 assert_eq!(payload["content"]["call_id"], json!("call-2"));
2822 }
2823
2824 #[test]
2828 fn redactions_payload_key_never_enters_the_model_context() {
2829 let session = SessionId::new();
2830 let bytes = tool_result_payload(&ToolResult {
2831 call_id: "call-9".into(),
2832 output: json!({"content": "scrubbed"}),
2833 is_error: false,
2834 redactions: vec![Redaction {
2835 kind: RedactionKind::EnvLine,
2836 name: "MY_SERVICE_TOKEN".into(),
2837 count: 2,
2838 }],
2839 });
2840 let with = Event {
2841 seq: 2,
2842 session,
2843 epoch: kian_core::model::Epoch(1),
2844 ts: 1,
2845 kind: EventKind::ToolResult,
2846 bytes: bytes.clone(),
2847 version: 0,
2848 };
2849 let mut without_bytes = bytes.clone();
2850 without_bytes.as_object_mut().unwrap().remove("redactions");
2851 let without = Event {
2852 bytes: without_bytes,
2853 ..with.clone()
2854 };
2855 let base = Event {
2856 seq: 1,
2857 session,
2858 epoch: kian_core::model::Epoch(0),
2859 ts: 0,
2860 kind: EventKind::SessionCreated,
2861 bytes: json!({}),
2862 version: 0,
2863 };
2864 let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
2865 let ctx_without = derive_model_context(&[base, without]).unwrap();
2866 assert_eq!(ctx_with, ctx_without);
2867 assert_eq!(ctx_with.len(), 1);
2868 let chat = to_chat_message(&ctx_with[0]).unwrap();
2870 assert_eq!(chat.role, "tool");
2871 assert_eq!(chat.tool_call_id.as_deref(), Some("call-9"));
2872 assert_eq!(chat.content.as_deref(), Some("{\"content\":\"scrubbed\"}"));
2873 }
2874
2875 #[test]
2880 fn tool_round_trip_projects_to_the_strict_wire_shape() {
2881 let assistant = msg(
2882 "assistant",
2883 json!({
2884 "text": "",
2885 "tool_calls": [
2886 {"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}
2887 ]
2888 }),
2889 );
2890 let chat = to_chat_message(&assistant).unwrap();
2891 assert_eq!(chat.role, "assistant");
2892 assert_eq!(chat.content, None, "empty text serializes as null");
2893 let tc = &chat.tool_calls.as_ref().unwrap()[0];
2894 assert_eq!(tc.id, "call-1");
2895 assert_eq!(tc.r#type, "function");
2896 assert_eq!(tc.function.name, "fs_read");
2897 assert_eq!(tc.function.arguments, "{\"path\":\"a.txt\"}");
2898
2899 let with_text = msg(
2901 "assistant",
2902 json!({"text": "checking", "tool_calls": [
2903 {"id": "call-2", "name": "exec", "arguments": {"argv": ["true"]}}
2904 ]}),
2905 );
2906 let chat = to_chat_message(&with_text).unwrap();
2907 assert_eq!(chat.content.as_deref(), Some("checking"));
2908
2909 let dup = msg(
2911 "assistant",
2912 json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}),
2913 );
2914 assert!(to_chat_message(&dup).is_none());
2915
2916 let result = msg(
2918 "tool",
2919 json!({"call_id": "call-1", "output": {"content": "x"}, "is_error": false}),
2920 );
2921 let chat = to_chat_message(&result).unwrap();
2922 assert_eq!(chat.role, "tool");
2923 assert_eq!(chat.tool_call_id.as_deref(), Some("call-1"));
2924 assert_eq!(chat.content.as_deref(), Some("{\"content\":\"x\"}"));
2925 assert!(chat.tool_calls.is_none());
2926 }
2927
2928 #[test]
2932 fn plain_messages_keep_the_v1_shape() {
2933 let user = msg("user", json!("hello"));
2934 let chat = to_chat_message(&user).unwrap();
2935 assert_eq!(chat.role, "user");
2936 assert_eq!(chat.content.as_deref(), Some("hello"));
2937 assert!(chat.tool_call_id.is_none() && chat.tool_calls.is_none());
2938
2939 let bare = msg("assistant", json!({"text": "hi"}));
2940 assert_eq!(
2941 to_chat_message(&bare).unwrap().content.as_deref(),
2942 Some("hi")
2943 );
2944
2945 let foreign = msg("tool", json!({"odd": true}));
2948 let chat = to_chat_message(&foreign).unwrap();
2949 assert_eq!(chat.tool_call_id.as_deref(), Some(""));
2950 }
2951
2952 #[test]
2960 fn permission_evaluation_covers_absent_default_and_configured() {
2961 use crate::react::{PermissionDecision, evaluate_permission};
2962 use kian_core::model::Permission;
2963
2964 let empty: BTreeMap<String, Permission> = BTreeMap::new();
2965 assert_eq!(evaluate_permission(&empty, "fs_write"), None);
2966
2967 let table: BTreeMap<String, Permission> = BTreeMap::from([
2968 ("fs_read".to_string(), Permission::Allow),
2969 ("fs_write".to_string(), Permission::Deny),
2970 ]);
2971 assert_eq!(
2972 evaluate_permission(&table, "fs_read"),
2973 Some(PermissionDecision::AllowConfigured)
2974 );
2975 assert_eq!(
2976 evaluate_permission(&table, "fs_write"),
2977 Some(PermissionDecision::Deny)
2978 );
2979 assert_eq!(
2982 evaluate_permission(&table, "exec"),
2983 Some(PermissionDecision::AllowDefault)
2984 );
2985 }
2986
2987 #[test]
2991 fn tool_call_payload_carries_permission_provenance_outside_content() {
2992 use crate::react::{evaluate_permission, tool_call_payload};
2993 use kian_core::model::Permission;
2994
2995 let call = ToolCall {
2996 id: "call-7".into(),
2997 name: "fs_write".into(),
2998 arguments: json!({"path": "a.txt"}),
2999 };
3000
3001 let empty: BTreeMap<String, Permission> = BTreeMap::new();
3003 let legacy = tool_call_payload(&call, evaluate_permission(&empty, &call.name));
3004 assert_eq!(
3005 legacy,
3006 json!({
3007 "role": "assistant",
3008 "content": {"id": "call-7", "name": "fs_write", "arguments": {"path": "a.txt"}}
3009 })
3010 );
3011
3012 let table: BTreeMap<String, Permission> =
3014 BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
3015 let allowed = tool_call_payload(&call, evaluate_permission(&table, &call.name)); assert_eq!(
3017 allowed["permission"],
3018 json!({"evaluated": "allow", "policy": "default", "matched": "fs_write"})
3019 );
3020 assert_eq!(allowed["content"], legacy["content"]);
3021
3022 let table: BTreeMap<String, Permission> =
3024 BTreeMap::from([("fs_write".to_string(), Permission::Deny)]);
3025 let denied = tool_call_payload(&call, evaluate_permission(&table, &call.name));
3026 assert_eq!(
3027 denied["permission"],
3028 json!({
3029 "evaluated": "deny",
3030 "policy": "configured",
3031 "matched": "fs_write",
3032 "reason": "tool_denied_by_policy"
3033 })
3034 );
3035 assert_eq!(denied["content"], legacy["content"]);
3036 }
3037
3038 #[test]
3049 fn hook_denied_permission_payload_goldens_are_frozen_bytes() {
3050 use crate::react::{evaluate_permission, tool_call_payload, tool_call_payload_hook_denied};
3051 use kian_core::model::Permission;
3052
3053 let call = ToolCall {
3054 id: "call-7".into(),
3055 name: "exec".into(),
3056 arguments: json!({"cmd": ["ls"]}),
3057 };
3058
3059 let hook_denied =
3061 tool_call_payload_hook_denied(&call, "approval-gate", "exec not on the allowlist");
3062 assert_eq!(
3063 serde_json::to_string(&hook_denied).unwrap(),
3064 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3065 \"permission\":{\"evaluated\":\"deny\",\"matched\":\"approval-gate:tool/pre\",\
3066 \"policy\":\"hook\",\"reason\":\"exec not on the allowlist\"},\"role\":\"assistant\"}"
3067 );
3068
3069 let denied_result = ToolResult {
3073 call_id: call.id.clone(),
3074 output: json!({
3075 "error": "denied by plugin approval-gate: exec not on the allowlist",
3076 "policy": "hook"
3077 }),
3078 is_error: true,
3079 redactions: Vec::new(),
3080 };
3081 assert_eq!(
3082 serde_json::to_string(&tool_result_payload(&denied_result)).unwrap(),
3083 "{\"content\":{\"call_id\":\"call-7\",\"is_error\":true,\
3084 \"output\":{\"error\":\"denied by plugin approval-gate: exec not on the allowlist\",\
3085 \"policy\":\"hook\"}},\"role\":\"tool\"}"
3086 );
3087
3088 let empty: BTreeMap<String, Permission> = BTreeMap::new();
3092 assert_eq!(
3093 serde_json::to_string(&tool_call_payload(
3094 &call,
3095 evaluate_permission(&empty, &call.name)
3096 ))
3097 .unwrap(),
3098 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3099 \"role\":\"assistant\"}"
3100 );
3101 let default_table = BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
3102 assert_eq!(
3103 serde_json::to_string(&tool_call_payload(
3104 &call,
3105 evaluate_permission(&default_table, &call.name)
3106 ))
3107 .unwrap(),
3108 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3109 \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"default\"},\
3110 \"role\":\"assistant\"}"
3111 );
3112 let allow_table = BTreeMap::from([("exec".to_string(), Permission::Allow)]);
3113 assert_eq!(
3114 serde_json::to_string(&tool_call_payload(
3115 &call,
3116 evaluate_permission(&allow_table, &call.name)
3117 ))
3118 .unwrap(),
3119 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3120 \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"configured\"},\
3121 \"role\":\"assistant\"}"
3122 );
3123 let deny_table = BTreeMap::from([("exec".to_string(), Permission::Deny)]);
3124 assert_eq!(
3125 serde_json::to_string(&tool_call_payload(
3126 &call,
3127 evaluate_permission(&deny_table, &call.name)
3128 ))
3129 .unwrap(),
3130 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3131 \"permission\":{\"evaluated\":\"deny\",\"matched\":\"exec\",\"policy\":\"configured\",\
3132 \"reason\":\"tool_denied_by_policy\"},\"role\":\"assistant\"}"
3133 );
3134 }
3135
3136 #[test]
3141 fn permission_payload_key_never_enters_the_model_context() {
3142 use crate::react::{PermissionDecision, tool_call_payload};
3143 use kian_core::seams::ToolCall;
3144
3145 let session = SessionId::new();
3146 let call = ToolCall {
3147 id: "call-1".into(),
3148 name: "fs_read".into(),
3149 arguments: json!({"path": "a.txt"}),
3150 };
3151 let with_bytes = tool_call_payload(&call, Some(PermissionDecision::Deny));
3152 let mut without_bytes = with_bytes.clone();
3153 without_bytes.as_object_mut().unwrap().remove("permission");
3154 let with = Event {
3155 seq: 2,
3156 session,
3157 epoch: kian_core::model::Epoch(1),
3158 ts: 1,
3159 kind: EventKind::ToolCall,
3160 bytes: with_bytes,
3161 version: 0,
3162 };
3163 let without = Event {
3164 bytes: without_bytes,
3165 ..with.clone()
3166 };
3167 let base = Event {
3168 seq: 1,
3169 session,
3170 epoch: kian_core::model::Epoch(0),
3171 ts: 0,
3172 kind: EventKind::SessionCreated,
3173 bytes: json!({}),
3174 version: 0,
3175 };
3176 let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
3177 let ctx_without = derive_model_context(&[base, without]).unwrap();
3178 assert_eq!(ctx_with, ctx_without);
3179 assert_eq!(ctx_with.len(), 1);
3180 assert_eq!(ctx_with[0].role, "assistant");
3183 assert_eq!(
3184 ctx_with[0].content,
3185 json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}})
3186 );
3187 assert!(!ctx_with[0].synthetic);
3188 }
3189
3190 #[test]
3197 fn resident_empty_batch_is_skipped_only_for_resident_assistant_tails() {
3198 use super::resident_empty_batch;
3199 assert!(resident_empty_batch(
3200 BudgetScope::PerEpisode,
3201 true,
3202 Some("assistant")
3203 ));
3204 assert!(!resident_empty_batch(
3205 BudgetScope::PerEpisode,
3206 false,
3207 Some("assistant")
3208 ));
3209 assert!(!resident_empty_batch(
3210 BudgetScope::PerEpisode,
3211 true,
3212 Some("tool")
3213 ));
3214 assert!(!resident_empty_batch(
3215 BudgetScope::PerEpisode,
3216 true,
3217 Some("user")
3218 ));
3219 assert!(!resident_empty_batch(
3220 BudgetScope::Lifetime,
3221 true,
3222 Some("assistant")
3223 ));
3224 }
3225
3226 #[test]
3227 fn budget_scope_selects_lifetime_or_episode_counter() {
3228 assert_eq!(BudgetScope::Lifetime.used(9, 0), 9);
3229 assert_eq!(BudgetScope::Lifetime.used(0, 9), 0);
3230 assert_eq!(BudgetScope::PerEpisode.used(9, 2), 2);
3231 assert_eq!(BudgetScope::PerEpisode.used(0, 0), 0);
3232 }
3233
3234 #[test]
3235 fn delta_assembly_concatenates_content_fragments() {
3236 let mut text = String::new();
3237 let mut reasoning = String::new();
3238 let mut calls = Default::default();
3239 for fragment in ["Hello", ", ", "kian"] {
3240 assemble_delta(
3241 &serde_json::json!({"content": fragment}),
3242 &mut text,
3243 &mut reasoning,
3244 &mut calls,
3245 );
3246 }
3247 assert_eq!(text, "Hello, kian");
3248 assert!(calls.is_empty());
3249 }
3250
3251 #[test]
3255 fn reasoning_fragments_are_persisted_and_replayed() {
3256 let mut text = String::new();
3257 let mut reasoning = String::new();
3258 let mut calls = Default::default();
3259 assemble_delta(
3260 &json!({"reasoning_content": "think "}),
3261 &mut text,
3262 &mut reasoning,
3263 &mut calls,
3264 );
3265 assemble_delta(
3266 &json!({"reasoning_content": "harder"}),
3267 &mut text,
3268 &mut reasoning,
3269 &mut calls,
3270 );
3271 assemble_delta(
3272 &json!({"content": "answer"}),
3273 &mut text,
3274 &mut reasoning,
3275 &mut calls,
3276 );
3277 assert_eq!(reasoning, "think harder");
3278 assert_eq!(text, "answer");
3279
3280 let with = to_chat_message(&msg(
3281 "assistant",
3282 json!({"text": text, "reasoning_content": reasoning}),
3283 ))
3284 .unwrap();
3285 assert_eq!(with.reasoning_content.as_deref(), Some("think harder"));
3286 let body = build_chat_body("m", &[with], &[]);
3287 assert_eq!(body["messages"][0]["reasoning_content"], "think harder");
3288
3289 let legacy = to_chat_message(&msg("assistant", json!({"text": "answer"}))).unwrap();
3290 assert!(legacy.reasoning_content.is_none());
3291 let body = build_chat_body("m", &[legacy], &[]);
3292 assert!(body["messages"][0].get("reasoning_content").is_none());
3293 }
3294
3295 #[test]
3296 fn delta_assembly_accumulates_tool_call_fragments_by_index() {
3297 let mut text = String::new();
3298 let mut reasoning = String::new();
3299 let mut calls = Default::default();
3300 assemble_delta(
3301 &serde_json::json!({"tool_calls": [
3302 {"index": 0, "id": "call-1", "function": {"name": "fs.read"}}
3303 ]}),
3304 &mut text,
3305 &mut reasoning,
3306 &mut calls,
3307 );
3308 assemble_delta(
3309 &serde_json::json!({"tool_calls": [
3310 {"index": 0, "function": {"arguments": "{\"pa"}}
3311 ]}),
3312 &mut text,
3313 &mut reasoning,
3314 &mut calls,
3315 );
3316 assemble_delta(
3317 &serde_json::json!({"tool_calls": [
3318 {"index": 0, "function": {"arguments": "th\": \"a.txt\"}"}}
3319 ]}),
3320 &mut text,
3321 &mut reasoning,
3322 &mut calls,
3323 );
3324 let finished: Vec<_> = calls.into_values().map(|c| c.finish()).collect();
3325 assert_eq!(finished.len(), 1);
3326 assert_eq!(finished[0].id, "call-1");
3327 assert_eq!(finished[0].name, "fs.read");
3328 assert_eq!(finished[0].arguments, serde_json::json!({"path": "a.txt"}));
3329 }
3330
3331 #[test]
3332 fn policy_consult_matches_rule_by_class() {
3333 use kian_core::seams::{PolicyRule, RecoveryAction, RecoveryPolicySource};
3334
3335 struct Table(Vec<PolicyRule>);
3336 impl RecoveryPolicySource for Table {
3337 fn table(&self) -> Vec<PolicyRule> {
3338 self.0.clone()
3339 }
3340 }
3341 let table = Table(vec![
3342 PolicyRule {
3343 class: "rate_limited".into(),
3344 action: RecoveryAction::BackoffRetry { delay_ms: 100 },
3345 },
3346 PolicyRule {
3347 class: CLASS_EMPTY_RESPONSE.into(),
3348 action: RecoveryAction::InterruptAsk,
3349 },
3350 ]);
3351 assert_eq!(
3352 consult_policy(&table, "rate_limited"),
3353 Some(RecoveryAction::BackoffRetry { delay_ms: 100 })
3354 );
3355 assert_eq!(
3356 consult_policy(&table, CLASS_EMPTY_RESPONSE),
3357 Some(RecoveryAction::InterruptAsk)
3358 );
3359 assert_eq!(consult_policy(&table, "no_such_class"), None);
3360 }
3361
3362 #[test]
3369 fn recovery_audit_carries_class_and_policy_action() {
3370 use kian_core::seams::{PolicyRule, RecoveryPolicySource};
3371 use kian_orchestrator::recovery::ErrorClass;
3372 use serde_json::json;
3373
3374 struct Table(Vec<PolicyRule>);
3375 impl RecoveryPolicySource for Table {
3376 fn table(&self) -> Vec<PolicyRule> {
3377 self.0.clone()
3378 }
3379 }
3380 let with_rule = Table(vec![PolicyRule {
3381 class: "store_failure".into(),
3382 action: kian_core::seams::RecoveryAction::Fail,
3383 }]);
3384 assert_eq!(
3385 super::recovery_audit(&with_rule, ErrorClass::StoreFailure),
3386 json!({"class": "store_failure", "action": "fail"})
3387 );
3388 assert_eq!(
3389 super::recovery_audit(&with_rule, ErrorClass::EmptyResponse),
3390 json!({"class": "empty_response", "action": "none"}),
3391 "no covering rule → the honest none spelling"
3392 );
3393
3394 assert_eq!(
3396 super::provider_error_class(&kian_core::seams::ProviderError::RateLimited),
3397 ErrorClass::RateLimited
3398 );
3399 assert_eq!(
3400 super::provider_error_class(&kian_core::seams::ProviderError::Unavailable(
3401 "upstream 503".into()
3402 )),
3403 ErrorClass::ProviderDown
3404 );
3405
3406 assert_eq!(
3408 super::loop_error_class(&super::LoopError::Engine(
3409 kian_orchestrator::EngineError::NotAtSafeBoundary {
3410 session: kian_core::model::SessionId::new(),
3411 }
3412 )),
3413 ErrorClass::StoreFailure
3414 );
3415 assert_eq!(
3416 super::loop_error_class(&super::LoopError::Slot(
3417 kian_llm::slots::SlotError::UnknownSlot("aux".into())
3418 )),
3419 ErrorClass::Unknown
3420 );
3421 }
3422
3423 #[test]
3424 fn the_default_budget_admits_the_newest_references_in_the_tail() {
3425 let budget = super::VisionBudget::default();
3426 let tail = vec![vec![10], vec![10], vec![10], vec![10], vec![10], vec![10]];
3427 let (per_message, admitted, dropped) = super::select_tail_images(budget, &tail);
3428 assert_eq!(per_message, vec![0, 0, 1, 1, 1, 1], "newest four win");
3429 assert_eq!(admitted, 4);
3430 assert_eq!(dropped, 2);
3431 assert_eq!(
3432 super::select_tail_images(budget, &tail),
3433 (vec![0, 0, 1, 1, 1, 1], 4, 2),
3434 "a retry of the same stream selects the same images"
3435 );
3436 }
3437
3438 #[test]
3439 fn the_byte_budget_stops_at_the_first_reference_that_would_exceed_it() {
3440 let budget = super::VisionBudget {
3441 max_images_per_turn: 8,
3442 max_image_bytes_per_turn: 4,
3443 };
3444 let tail = vec![vec![3], vec![3]];
3445 let (per_message, admitted, dropped) = super::select_tail_images(budget, &tail);
3446 assert_eq!(
3447 per_message,
3448 vec![0, 1],
3449 "the newest 3 bytes fit, the next 3 do not"
3450 );
3451 assert_eq!(admitted, 1);
3452 assert_eq!(dropped, 1);
3453 }
3454
3455 #[test]
3456 fn a_message_still_keeps_at_most_four_references() {
3457 let budget = super::VisionBudget {
3458 max_images_per_turn: 32,
3459 max_image_bytes_per_turn: u64::MAX,
3460 };
3461 let tail = vec![vec![1, 1, 1, 1, 1, 1]];
3462 let (per_message, admitted, dropped) = super::select_tail_images(budget, &tail);
3463 assert_eq!(per_message, vec![4], "the ceiling admits a suffix of four");
3464 assert_eq!(admitted, 4);
3465 assert_eq!(dropped, 2);
3466 }
3467
3468 #[test]
3469 fn a_tail_within_both_limits_keeps_every_reference() {
3470 let budget = super::VisionBudget::default();
3471 let tail = vec![vec![1, 1], vec![1]];
3472 let (per_message, admitted, dropped) = super::select_tail_images(budget, &tail);
3473 assert_eq!(per_message, vec![2, 1]);
3474 assert_eq!(admitted, 3);
3475 assert_eq!(dropped, 0);
3476 }
3477
3478 #[test]
3479 fn react_config_defaults_are_sane() {
3480 let cfg = ReActConfig::default();
3481 assert_eq!(cfg.slot.0, "main");
3482 assert!(cfg.max_iterations >= 1);
3483 let react = ReActLoop::new(
3485 agent_def(),
3486 std::sync::Arc::new(kian_llm::ProviderRegistry::new()),
3487 std::sync::Arc::new(NoopTools),
3488 std::sync::Arc::new(NoopPolicy),
3489 );
3490 assert_eq!(react.config().slot.0, "main");
3491 }
3492}