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, SessionId, 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
213pub trait ToolScope: Send + Sync {
224 fn tools_for(&self, session: SessionId) -> Arc<dyn ToolProvider>;
225}
226
227#[derive(Clone)]
228struct Inner {
229 registry: Arc<ProviderRegistry>,
230 tools: Arc<dyn ToolProvider>,
231 tool_scope: Option<Arc<dyn ToolScope>>,
233 policy: Arc<dyn RecoveryPolicySource>,
234 agent: AgentDef,
235 config: ReActConfig,
236 gate: EvidenceGateConfig,
239 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
243 set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
250 compaction: CompactionSettings,
253}
254
255struct PreparedRequest {
261 schemas: Vec<ToolSchema>,
262 chat: Vec<ChatMessage>,
263 plan: Result<RequestPlan, ProviderError>,
264}
265
266#[derive(Clone)]
268pub struct ReActLoop(Arc<Inner>);
269
270impl ReActLoop {
271 pub fn new(
275 agent: AgentDef,
276 registry: Arc<ProviderRegistry>,
277 tools: Arc<dyn ToolProvider>,
278 policy: Arc<dyn RecoveryPolicySource>,
279 ) -> Self {
280 Self::with_config(agent, registry, tools, policy, ReActConfig::default())
281 }
282
283 pub fn with_config(
286 agent: AgentDef,
287 registry: Arc<ProviderRegistry>,
288 tools: Arc<dyn ToolProvider>,
289 policy: Arc<dyn RecoveryPolicySource>,
290 config: ReActConfig,
291 ) -> Self {
292 Self::with_evidence_gate(
293 agent,
294 registry,
295 tools,
296 policy,
297 config,
298 EvidenceGateConfig::default(),
299 )
300 }
301
302 pub fn with_evidence_gate(
306 agent: AgentDef,
307 registry: Arc<ProviderRegistry>,
308 tools: Arc<dyn ToolProvider>,
309 policy: Arc<dyn RecoveryPolicySource>,
310 config: ReActConfig,
311 gate: EvidenceGateConfig,
312 ) -> Self {
313 Self::with_hooks(agent, registry, tools, policy, config, gate, None)
314 }
315
316 pub fn with_hooks(
322 agent: AgentDef,
323 registry: Arc<ProviderRegistry>,
324 tools: Arc<dyn ToolProvider>,
325 policy: Arc<dyn RecoveryPolicySource>,
326 config: ReActConfig,
327 gate: EvidenceGateConfig,
328 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
329 ) -> Self {
330 Self::with_hooks_and_guard(agent, registry, tools, policy, config, gate, hooks, None)
331 }
332
333 #[allow(clippy::too_many_arguments)]
342 pub fn with_hooks_and_guard(
343 agent: AgentDef,
344 registry: Arc<ProviderRegistry>,
345 tools: Arc<dyn ToolProvider>,
346 policy: Arc<dyn RecoveryPolicySource>,
347 config: ReActConfig,
348 gate: EvidenceGateConfig,
349 hooks: Option<Arc<dyn kian_plugin::hooks::HookPorts>>,
350 set_guard: Option<Arc<dyn kian_plugin::hooks::SessionSetGuard>>,
351 ) -> Self {
352 Self(Arc::new(Inner {
353 registry,
354 tools,
355 tool_scope: None,
356 policy,
357 agent,
358 config,
359 gate,
360 hooks,
361 set_guard,
362 compaction: CompactionSettings::default(),
363 }))
364 }
365
366 #[must_use]
371 pub fn with_tool_scope(self, scope: Arc<dyn ToolScope>) -> Self {
372 let mut inner = (*self.0).clone();
373 inner.tool_scope = Some(scope);
374 Self(Arc::new(inner))
375 }
376
377 #[must_use]
381 pub fn with_compaction(self, compaction: CompactionSettings) -> Self {
382 let mut inner = (*self.0).clone();
383 inner.compaction = compaction.normalized();
384 Self(Arc::new(inner))
385 }
386
387 #[must_use]
389 pub fn compaction_settings(&self) -> CompactionSettings {
390 self.0.compaction
391 }
392
393 #[must_use]
394 pub fn config(&self) -> &ReActConfig {
395 &self.0.config
396 }
397
398 #[must_use]
402 pub fn evidence_gate(&self) -> &EvidenceGateConfig {
403 &self.0.gate
404 }
405}
406
407struct LoopState {
416 ctx: DrainCtx,
417 done: bool,
418 begun: bool,
419 drain_iterations: usize,
422 compactions: usize,
425}
426
427impl LoopDriver for ReActLoop {
428 type Ctx = DrainCtx;
429
430 fn drive(&self, ctx: DrainCtx) -> BoxStream<'static, LoopOutcome> {
431 let inner = match &self.0.tool_scope {
435 Some(scope) => {
436 let mut inner = (*self.0).clone();
437 inner.tools = scope.tools_for(ctx.session());
438 Arc::new(inner)
439 }
440 None => Arc::clone(&self.0),
441 };
442 futures::stream::unfold(
443 LoopState {
444 ctx,
445 done: false,
446 begun: false,
447 drain_iterations: 0,
448 compactions: 0,
449 },
450 move |mut st| {
451 let inner = Arc::clone(&inner);
452 async move {
453 if st.done {
454 return None;
455 }
456 if !st.begun {
467 st.begun = true;
468 if let Some(guard) = inner.set_guard.as_ref() {
469 let worker = match st.ctx.events().await {
470 Ok(events) => kian_plugin::hooks::durable_worker_binding(
471 &events,
472 &st.ctx.session(),
473 )
474 .unwrap_or_default(),
475 Err(_) => String::new(),
479 };
480 guard.session_begin(kian_plugin::hooks::FrameInfo {
481 session: st.ctx.session(),
482 worker,
483 seq: 0,
484 epoch: Some(st.ctx.epoch().0),
485 });
486 }
487 }
488 let outcome = match inner
489 .iteration(&st.ctx, &mut st.drain_iterations, &mut st.compactions)
490 .await
491 {
492 Flow::TurnDone => LoopOutcome::TurnDone,
493 Flow::Settled | Flow::Deferred => LoopOutcome::Settled,
494 Flow::Stopped(reason) => LoopOutcome::Stopped { reason },
495 Flow::AwaitingBudget(budget) => LoopOutcome::AwaitingBudget { budget },
496 Flow::Soft(reason) => LoopOutcome::SoftFailed { reason },
497 };
498 if !matches!(outcome, LoopOutcome::TurnDone) {
499 st.done = true;
500 }
501 Some((outcome, st))
502 }
503 },
504 )
505 .boxed()
506 }
507}
508
509enum Flow {
511 TurnDone,
513 Settled,
515 Deferred,
520 Stopped(String),
522 AwaitingBudget(Value),
525 Soft(String),
527}
528
529enum TurnOutcome {
530 FinalAnswer,
531 ToolCalls(usize),
532}
533
534struct TurnResult {
539 result: Result<TurnOutcome, TurnError>,
540 usage: Option<Value>,
541}
542
543enum TurnError {
544 Soft { reason: String, audit: Value },
548 Fatal { error: LoopError, audit: Value },
551 AwaitingBudget { budget: Value },
554}
555
556#[derive(Debug, thiserror::Error)]
560pub enum LoopError {
561 #[error("engine: {0}")]
562 Engine(#[from] EngineError),
563 #[error("context projection: {0}")]
564 Context(#[from] kian_core::context::ContextError),
565 #[error("slots: {0}")]
566 Slot(#[from] SlotError),
567}
568
569impl Inner {
570 async fn iteration(
572 &self,
573 ctx: &DrainCtx,
574 drain_iterations: &mut usize,
575 compactions: &mut usize,
576 ) -> Flow {
577 let flow = match self.run_iteration(ctx, drain_iterations, compactions).await {
578 Ok(flow) => flow,
579 Err(e) => return Flow::Soft(format!("loop error: {e}")),
580 };
581 match flow {
584 Flow::Settled | Flow::Stopped(_) => self.apply_evidence_gate(ctx, flow).await,
585 other => other,
586 }
587 }
588
589 async fn apply_evidence_gate(&self, ctx: &DrainCtx, flow: Flow) -> Flow {
602 if !self.gate.enabled {
603 return flow;
604 }
605 let events = match ctx.events().await {
606 Ok(events) => events,
607 Err(e) => {
608 return Flow::Soft(format!("evidence gate: stream read failed: {e}"));
609 }
610 };
611 let verdict = evaluate_evidence_gate(BUILTIN_GATE_NAME, &self.gate.checks, &events);
612 let payload = verdict_payload(BUILTIN_GATE_NAME, &verdict);
613 if let Err(e) = ctx.append(EventKind::EvidenceVerdict, payload).await {
614 return Flow::Soft(format!("evidence gate: verdict append failed: {e}"));
615 }
616 if verdict.passed {
617 self.gate.counters.record_passed();
618 flow
619 } else {
620 self.gate.counters.record_failed();
621 if verdict.attempt < self.gate.max_retries {
622 Flow::TurnDone
623 } else {
624 Flow::Soft(format!(
625 "evidence gate `{BUILTIN_GATE_NAME}` failed after {} attempt(s)",
626 verdict.attempt + 1
627 ))
628 }
629 }
630 }
631
632 async fn hook_frame(ctx: &DrainCtx, seq: u64) -> Option<kian_plugin::hooks::FrameInfo> {
649 let worker = match ctx.events().await {
650 Ok(events) => kian_plugin::hooks::durable_worker_binding(&events, &ctx.session())
651 .unwrap_or_default(),
652 Err(_) => String::new(),
655 };
656 Some(kian_plugin::hooks::FrameInfo {
657 session: ctx.session(),
658 worker,
659 seq,
660 epoch: Some(ctx.epoch().0),
661 })
662 }
663
664 #[allow(clippy::too_many_arguments)]
670 async fn observe_request(
671 &self,
672 ctx: &DrainCtx,
673 binding: &SlotBinding,
674 chat_len: usize,
675 schemas: &[kian_core::seams::ToolSchema],
676 iteration: usize,
677 body: &Value,
678 step_request_seq: u64,
679 ) {
680 use kian_plugin::hooks::{RequestMeta, serialized, sha256_hex};
681 let Some(hooks) = self.hooks.as_ref() else {
682 return;
683 };
684 let bytes = serialized(body);
685 let meta = RequestMeta {
686 slot: self.config.slot.0.clone(),
687 provider: binding.target.provider.clone(),
688 model: binding.target.model.clone(),
689 iteration: iteration as u64,
690 request_bytes: bytes.len() as u64,
691 request_sha256: sha256_hex(&bytes),
692 message_count: chat_len as u64,
693 tool_names: schemas.iter().map(|s| s.name.clone()).collect(),
694 tool_schema_sha256: sha256_hex(&serialized(&Value::Array(
695 schemas
696 .iter()
697 .map(|s| serde_json::to_value(s).unwrap_or(Value::Null))
698 .collect(),
699 ))),
700 timing: "pre_send".to_string(),
701 step_request_seq,
702 frame: Self::hook_frame(ctx, step_request_seq).await,
703 };
704 hooks.request(&meta).await;
705 }
706
707 #[allow(clippy::too_many_arguments)] async fn observe_response(
713 &self,
714 ctx: &DrainCtx,
715 iteration: usize,
716 seq: u64,
717 outcome: &str,
718 tool_calls: u64,
719 text_bytes: u64,
720 reasoning_bytes: u64,
721 usage: Option<&Value>,
722 error_audit: Option<&Value>,
723 ) {
724 use kian_plugin::hooks::{ResponseView, TurnErrorAudit};
725 let Some(hooks) = self.hooks.as_ref() else {
726 return;
727 };
728 let error = error_audit.and_then(|audit| {
729 Some(TurnErrorAudit {
730 class: audit.get("class")?.as_str()?.to_string(),
731 action: audit.get("action")?.as_str()?.to_string(),
732 })
733 });
734 let view = ResponseView {
735 iteration: iteration as u64,
736 outcome: outcome.to_string(),
737 tool_calls,
738 text_bytes,
739 reasoning_bytes,
740 usage: usage.cloned().unwrap_or(Value::Null),
741 error,
742 timing: "settled".to_string(),
743 frame: Self::hook_frame(ctx, seq).await,
744 };
745 hooks.response(&view).await;
746 }
747
748 async fn consult_tool_pre(
754 &self,
755 ctx: &DrainCtx,
756 call: &ToolCall,
757 iteration: usize,
758 seq: u64,
759 decision: Option<PermissionDecision>,
760 ) -> kian_plugin::hooks::ToolVerdict {
761 use kian_plugin::hooks::{ToolCallView, bounded_value, serialized, sha256_hex};
762 let Some(hooks) = self.hooks.as_ref() else {
763 return kian_plugin::hooks::ToolVerdict::Allow;
764 };
765 let bytes = serialized(&call.arguments);
766 let (arguments, arguments_truncated) = bounded_value(&call.arguments);
767 let view = ToolCallView {
768 call_id: call.id.clone(),
769 name: call.name.clone(),
770 iteration: iteration as u64,
771 arguments,
772 arguments_bytes: bytes.len() as u64,
773 arguments_sha256: sha256_hex(&bytes),
774 arguments_truncated,
775 permission: permission_view(call, decision),
776 surface: "react".to_string(),
777 frame: Self::hook_frame(ctx, seq).await,
778 };
779 hooks.tool_pre(&view).await
780 }
781
782 async fn observe_tool_post(&self, ctx: &DrainCtx, result: &ToolResult, name: &str, seq: u64) {
786 use kian_plugin::hooks::{RedactionReport, ToolPostView, serialized, sha256_hex};
787 let Some(hooks) = self.hooks.as_ref() else {
788 return;
789 };
790 let bytes = serialized(&result.output);
791 let view = ToolPostView {
792 call_id: result.call_id.clone(),
793 name: name.to_string(),
794 is_error: result.is_error,
795 output_bytes: bytes.len() as u64,
796 output_sha256: sha256_hex(&bytes),
797 redactions: result
798 .redactions
799 .iter()
800 .map(|r| RedactionReport {
801 kind: serde_json::to_value(r.kind)
802 .ok()
803 .and_then(|v| v.as_str().map(str::to_string))
804 .unwrap_or_default(),
805 name: r.name.clone(),
806 count: r.count,
807 })
808 .collect(),
809 frame: Self::hook_frame(ctx, seq).await,
810 };
811 hooks.tool_post(&view).await;
812 }
813
814 async fn observe_recover(&self, ctx: &DrainCtx, iteration: usize, seq: u64, audit: &Value) {
818 let Some(hooks) = self.hooks.as_ref() else {
819 return;
820 };
821 let view = kian_plugin::hooks::RecoveryView {
822 error_class: audit
823 .get("class")
824 .and_then(Value::as_str)
825 .unwrap_or_default()
826 .to_string(),
827 action: audit
828 .get("action")
829 .and_then(Value::as_str)
830 .unwrap_or("none")
831 .to_string(),
832 iteration: iteration as u64,
833 frame: Self::hook_frame(ctx, seq).await,
834 };
835 hooks.recover(&view).await;
836 }
837
838 #[allow(clippy::too_many_arguments)] async fn observe_fatal(
843 &self,
844 ctx: &DrainCtx,
845 iteration: usize,
846 seq: u64,
847 audit: &Value,
848 text_bytes: u64,
849 reasoning_bytes: u64,
850 usage: Option<&Value>,
851 ) {
852 self.observe_recover(ctx, iteration, seq, audit).await;
853 self.observe_response(
854 ctx,
855 iteration,
856 seq,
857 "error",
858 0,
859 text_bytes,
860 reasoning_bytes,
861 usage,
862 Some(audit),
863 )
864 .await;
865 }
866
867 async fn run_iteration(
868 &self,
869 ctx: &DrainCtx,
870 drain_iterations: &mut usize,
871 compactions: &mut usize,
872 ) -> Result<Flow, LoopError> {
873 let taken = ctx.take_eligible_inputs().await?;
877
878 let mut events = ctx.events().await?;
880
881 let mut pending = pending_calls(&events);
886 if !pending.is_empty() {
887 let decisions = confirmations(&events);
888 for (call, decision) in confirmable(&pending, &decisions) {
889 self.apply_confirmation(ctx, &call, &decision).await?;
890 }
891 events = ctx.events().await?;
892 pending = pending_calls(&events);
893 if !pending.is_empty() {
894 tracing::debug!(
895 session = %ctx.session().0,
896 pending = pending.len(),
897 "awaiting confirmation: settling without a provider call"
898 );
899 return Ok(Flow::Deferred);
900 }
901 }
902
903 let binding = self.binding_for(ctx, &mut events).await?;
904 let messages = derive_model_context(&events)?;
905
906 if resident_empty_batch(
913 self.config.budget_scope,
914 taken.is_empty(),
915 messages.last().map(|m| m.role.as_str()),
916 ) {
917 tracing::debug!(
918 session = %ctx.session().0,
919 "resident empty batch: settling without a provider call (ADR-025)"
920 );
921 return Ok(Flow::Settled);
922 }
923
924 let iteration = events
927 .iter()
928 .filter(|ev| matches!(ev.kind, EventKind::TurnStart))
929 .count();
930 let used = self.config.budget_scope.used(iteration, *drain_iterations);
931 if used >= self.config.max_iterations {
932 let reason = match self.config.budget_scope {
933 BudgetScope::Lifetime => {
934 format!("iteration budget exhausted after {iteration} turns")
935 }
936 BudgetScope::PerEpisode => format!(
937 "{} after {used} turns",
938 kian_core::seams::EPISODE_BUDGET_STOP_REASON_PREFIX
939 ),
940 };
941 return Ok(Flow::Stopped(reason));
942 }
943 if self.config.budget_scope == BudgetScope::PerEpisode {
944 *drain_iterations += 1;
945 }
946
947 if let Some(trigger) = preventive_trigger(&binding, &messages)
952 && let Some(flow) = self
953 .compact_now(ctx, &binding, iteration, trigger, compactions)
954 .await?
955 {
956 return Ok(flow);
957 }
958
959 let prepared = self.prepare_request(ctx, &binding, &messages).await;
965 if let Some(limit) = self
966 .config
967 .max_request_bytes
968 .get(&binding.target.provider)
969 .copied()
970 && let Ok(plan) = &prepared.plan
971 && let Ok(body) = serialize_request_body(&plan.body)
972 {
973 let request_bytes = body.len() as u64;
974 if request_bytes > limit {
975 if let Some(flow) = self
976 .compact_now(
977 ctx,
978 &binding,
979 iteration,
980 CompactionTrigger::Bytes {
981 request_bytes,
982 limit_bytes: limit,
983 },
984 compactions,
985 )
986 .await?
987 {
988 return Ok(flow);
989 }
990 tracing::warn!(
991 session = %ctx.session().0,
992 provider = %binding.target.provider,
993 request_bytes,
994 limit_bytes = limit,
995 compactions = *compactions,
996 keep_recent_turns = self.compaction.keep_recent_turns,
997 "request byte pressure: no fold relieved the request; sending it for the provider bound to refuse (ADR-072)"
998 );
999 }
1000 }
1001
1002 ctx.begin_turn_with(json!({"iteration": iteration})).await?;
1005 let turn = self
1006 .provider_turn(ctx, &binding, &prepared, iteration)
1007 .await;
1008 let usage = turn.usage.as_ref();
1009 let flow = match turn.result {
1010 Ok(TurnOutcome::ToolCalls(n)) => {
1011 let mut payload = json!({"iteration": iteration, "tool_calls": n});
1012 if let Some(u) = usage {
1013 payload["usage"] = u.clone();
1014 }
1015 ctx.end_turn_with(payload).await?;
1016 return Ok(Flow::TurnDone);
1017 }
1018 Ok(TurnOutcome::FinalAnswer) => {
1021 if ctx.has_eligible_inputs().await? {
1022 Flow::TurnDone
1023 } else {
1024 Flow::Settled
1025 }
1026 }
1027 Err(TurnError::AwaitingBudget { budget }) => {
1028 let payload = json!({
1029 "iteration": iteration,
1030 "outcome": "awaiting_budget",
1031 "budget": &budget,
1032 });
1033 let _ = ctx.end_turn_with(payload).await;
1034 return Ok(Flow::AwaitingBudget(budget));
1035 }
1036 Err(TurnError::Soft { reason, audit }) => {
1037 let mut payload = json!({
1038 "iteration": iteration,
1039 "outcome": "soft_failure",
1040 "error": audit,
1041 });
1042 if let Some(u) = usage {
1043 payload["usage"] = u.clone();
1044 }
1045 let _ = ctx.end_turn_with(payload).await;
1046 if let Some(trigger) = fold_trigger(&audit)
1055 && let Some(flow) = self
1056 .compact_now(ctx, &binding, iteration, trigger, compactions)
1057 .await?
1058 {
1059 return Ok(flow);
1060 }
1061 return Ok(Flow::Soft(reason));
1062 }
1063 Err(TurnError::Fatal { error, audit }) => {
1064 let mut payload = json!({
1065 "iteration": iteration,
1066 "outcome": "error",
1067 "error": audit,
1068 });
1069 if let Some(u) = usage {
1070 payload["usage"] = u.clone();
1071 }
1072 let _ = ctx.end_turn_with(payload).await;
1073 return Err(error);
1074 }
1075 };
1076 let mut payload = json!({"iteration": iteration, "outcome": "final_answer"});
1077 if let Some(u) = usage {
1078 payload["usage"] = u.clone();
1079 }
1080 ctx.end_turn_with(payload).await?;
1081 Ok(flow)
1082 }
1083
1084 async fn apply_confirmation(
1091 &self,
1092 ctx: &DrainCtx,
1093 call: &PendingCall,
1094 decision: &ConfirmIntent,
1095 ) -> Result<(), LoopError> {
1096 let result = match decision.decision {
1097 ConfirmDecision::Approve => {
1098 let tool_call = ToolCall {
1099 id: call.call_id.clone(),
1100 name: call.tool.clone(),
1101 arguments: call.arguments.clone(),
1102 };
1103 match self.tools.invoke(tool_call).await {
1104 Ok(r) => r,
1105 Err(e) => ToolResult {
1108 call_id: call.call_id.clone(),
1109 output: json!({"error": e.to_string()}),
1110 is_error: true,
1111 redactions: Vec::new(),
1112 },
1113 }
1114 }
1115 ConfirmDecision::Reject => ToolResult {
1116 call_id: call.call_id.clone(),
1117 output: if decision.expired {
1118 json!({
1119 "error": "confirmation expired",
1120 "policy": "ask",
1121 "expired": true
1122 })
1123 } else {
1124 match &decision.reason {
1125 Some(reason) => json!({
1126 "error": "permission denied by user",
1127 "policy": "ask",
1128 "reason": reason
1129 }),
1130 None => json!({
1131 "error": "permission denied by user",
1132 "policy": "ask"
1133 }),
1134 }
1135 },
1136 is_error: true,
1137 redactions: Vec::new(),
1138 },
1139 };
1140 let payload = tool_result_payload_confirmed(&result, decision);
1141 ctx.append(EventKind::ToolResult, payload).await?;
1142 Ok(())
1143 }
1144
1145 async fn binding_for(
1149 &self,
1150 ctx: &DrainCtx,
1151 events: &mut Arc<Vec<Event>>,
1152 ) -> Result<SlotBinding, LoopError> {
1153 let session = ctx.session();
1154 if let Ok(slots) = SessionSlots::replay(session, events)
1155 && slots.binding(&self.config.slot).is_ok()
1156 {
1157 return Ok(slots.binding(&self.config.slot)?.clone());
1158 }
1159 let fresh = SlotResolver::from_agent_def(&self.agent).bind_session(session);
1160 for payload in fresh.binding_payloads() {
1161 ctx.append(EventKind::SlotBinding, payload).await?;
1162 }
1163 *events = ctx.events().await?;
1166 Ok(fresh.binding(&self.config.slot)?.clone())
1167 }
1168
1169 async fn chat_messages(
1175 &self,
1176 ctx: &DrainCtx,
1177 profile: Option<&ModelProfile>,
1178 messages: &[Message],
1179 ) -> Vec<ChatMessage> {
1180 let vision = profile.is_some_and(|p| p.vision);
1181 let mut chat = Vec::with_capacity(messages.len());
1182 let mut pending: Vec<Option<Vec<ImageReference>>> = Vec::with_capacity(messages.len());
1183 let mut tail_start = 0;
1184 for message in messages {
1185 let Some(mut chat_message) = to_chat_message(message) else {
1186 continue;
1187 };
1188 if message.role == "assistant" {
1189 tail_start = chat.len() + 1;
1190 }
1191 let mut references = None;
1192 if vision
1193 && message.role == "user"
1194 && let Some((text, envelope)) = vision_envelope(&message.content)
1195 {
1196 chat_message.content = text;
1197 references = Some(envelope);
1198 }
1199 chat.push(chat_message);
1200 pending.push(references);
1201 }
1202 for (index, references) in pending.iter_mut().enumerate().take(tail_start) {
1203 if let Some(references) = references.take() {
1204 chat[index].images = self.load_images(ctx, &references).await;
1205 }
1206 }
1207 self.attach_tail_images(ctx, &mut chat, &mut pending, tail_start)
1208 .await;
1209 chat
1210 }
1211
1212 async fn attach_tail_images(
1217 &self,
1218 ctx: &DrainCtx,
1219 chat: &mut [ChatMessage],
1220 pending: &mut [Option<Vec<ImageReference>>],
1221 tail_start: usize,
1222 ) {
1223 let budget = self.config.vision;
1224 let mut loaded: Vec<Option<Vec<ChatImage>>> = (0..chat.len()).map(|_| None).collect();
1225 for index in tail_start..chat.len() {
1226 let Some(references) = pending[index].take() else {
1227 continue;
1228 };
1229 let mut images = Vec::with_capacity(references.len());
1230 for (artifact, media_type) in references.iter() {
1231 let Some(bytes) = ctx.artifact_bytes(artifact).await else {
1232 continue;
1233 };
1234 if bytes.len() > MAX_VISION_IMAGE_BYTES {
1235 tracing::warn!(
1236 artifact = %artifact,
1237 bytes = bytes.len(),
1238 limit = MAX_VISION_IMAGE_BYTES,
1239 "vision image is over the byte bound; the image is skipped (ADR-063)"
1240 );
1241 continue;
1242 }
1243 images.push(ChatImage {
1244 media_type: media_type.clone(),
1245 bytes,
1246 });
1247 }
1248 loaded[index] = Some(images);
1249 }
1250 let tail: Vec<Vec<usize>> = loaded
1251 .iter()
1252 .skip(tail_start)
1253 .map(|images| {
1254 images
1255 .as_ref()
1256 .map(|images| images.iter().map(|image| image.bytes.len()).collect())
1257 .unwrap_or_default()
1258 })
1259 .collect();
1260 let (per_message, admitted, dropped) = select_tail_images(budget, &tail);
1261 for (offset, count) in per_message.into_iter().enumerate() {
1262 let index = tail_start + offset;
1263 let Some(mut images) = loaded[index].take() else {
1264 continue;
1265 };
1266 let keep_from = images.len().saturating_sub(count);
1267 chat[index].images = images.split_off(keep_from);
1268 }
1269 if dropped > 0 {
1270 tracing::warn!(
1271 admitted,
1272 dropped,
1273 max_images_per_turn = budget.max_images_per_turn,
1274 max_image_bytes_per_turn = budget.max_image_bytes_per_turn,
1275 "per-turn image budget: the newest references in the tail are rendered; older ones stay text-only (ADR-066)"
1276 );
1277 }
1278 }
1279
1280 async fn load_images(&self, ctx: &DrainCtx, references: &[ImageReference]) -> Vec<ChatImage> {
1286 let mut images = Vec::new();
1287 for (artifact, media_type) in references.iter().take(MAX_IMAGES_PER_MESSAGE) {
1288 let Some(bytes) = ctx.artifact_bytes(artifact).await else {
1289 continue;
1290 };
1291 if bytes.len() > MAX_VISION_IMAGE_BYTES {
1292 tracing::warn!(
1293 artifact = %artifact,
1294 bytes = bytes.len(),
1295 limit = MAX_VISION_IMAGE_BYTES,
1296 "vision image is over the byte bound; the image is skipped (ADR-063)"
1297 );
1298 continue;
1299 }
1300 images.push(ChatImage {
1301 media_type: media_type.clone(),
1302 bytes,
1303 });
1304 }
1305 images
1306 }
1307
1308 async fn prepare_request(
1315 &self,
1316 ctx: &DrainCtx,
1317 binding: &SlotBinding,
1318 messages: &[Message],
1319 ) -> PreparedRequest {
1320 let target = &binding.target;
1321 let mut schemas = self.tools.schemas();
1324 schemas.sort_by(|a, b| a.name.cmp(&b.name));
1325 let chat = self
1326 .chat_messages(ctx, target.profile.as_ref(), messages)
1327 .await;
1328 let plan = build_request_plan(target.profile.as_ref(), &target.model, &chat, &schemas);
1329 PreparedRequest {
1330 schemas,
1331 chat,
1332 plan,
1333 }
1334 }
1335
1336 async fn provider_turn(
1342 &self,
1343 ctx: &DrainCtx,
1344 binding: &SlotBinding,
1345 prepared: &PreparedRequest,
1346 iteration: usize,
1347 ) -> TurnResult {
1348 let target = binding.target.clone();
1349
1350 let schemas = prepared.schemas.clone();
1353
1354 let plan = match &prepared.plan {
1358 Ok(plan) => plan,
1359 Err(e) => {
1360 return TurnResult {
1361 result: Err(TurnError::Soft {
1362 reason: format!("request plan: {e}"),
1363 audit: recovery_audit(self.policy.as_ref(), provider_error_class(e)),
1364 }),
1365 usage: None,
1366 };
1367 }
1368 };
1369 let budget = match ctx.events().await {
1375 Ok(events) => project_budget(&events, &self.agent.budgets),
1376 Err(e) => {
1377 return TurnResult {
1378 result: Err(TurnError::Soft {
1379 reason: format!("budget projection: {e}"),
1380 audit: json!({"class": "internal", "action": "none"}),
1381 }),
1382 usage: None,
1383 };
1384 }
1385 };
1386 let estimate = plan
1387 .estimate
1388 .high
1389 .saturating_add(plan.estimate.max_output_tokens.unwrap_or(0));
1390 let reserve = budget.maintenance_reserve_tokens().unwrap_or(0);
1393 if budget.would_exceed_tokens_reserving(estimate, reserve) {
1394 return TurnResult {
1395 result: Err(TurnError::AwaitingBudget {
1396 budget: json!({
1397 "limit": budget.tokens_limit,
1398 "raised": budget.tokens_raised,
1399 "spent": budget.tokens_spent,
1400 "estimate": estimate,
1401 "reserve": reserve,
1402 }),
1403 }),
1404 usage: None,
1405 };
1406 }
1407 let body = plan.body.clone();
1408 let (audit_body, body_form) = plan.audit();
1411 let mut step_payload = json!({
1412 "slot": self.config.slot.0,
1413 "provider": target.provider,
1414 "model": target.model,
1415 "iteration": iteration,
1416 "body": audit_body,
1417 "body_version": plan.body_version,
1418 "dialect": plan.dialect,
1419 "body_sha256": plan.body_sha256.clone(),
1420 "body_bytes": plan.body_bytes,
1421 "estimate": plan.estimate.clone(),
1422 });
1423 if let Some(form) = body_form {
1424 step_payload["body_form"] = json!(form);
1425 }
1426 if let Some(digest) = &plan.profile_digest {
1427 step_payload["profile_digest"] = json!(digest);
1428 }
1429 let step_request = ctx.append(EventKind::StepRequest, step_payload).await;
1430 let step_request_seq = match step_request {
1431 Ok(ev) => ev.seq,
1432 Err(e) => {
1433 let fatal = TurnError::fatal(e, self.policy.as_ref());
1434 if let TurnError::Fatal { audit, .. } = &fatal {
1436 self.observe_fatal(ctx, iteration, 0, audit, 0, 0, None)
1437 .await;
1438 }
1439 return TurnResult {
1440 result: Err(fatal),
1441 usage: None,
1442 };
1443 }
1444 };
1445 self.observe_request(
1450 ctx,
1451 binding,
1452 prepared.chat.len(),
1453 &schemas,
1454 iteration,
1455 &body,
1456 step_request_seq,
1457 )
1458 .await;
1459
1460 let build_chat = prepared.chat.clone();
1463 let build_schemas = schemas.clone();
1464 let build = Arc::new(move |t: &kian_core::model::SlotTarget| {
1465 build_request_plan(t.profile.as_ref(), &t.model, &build_chat, &build_schemas)
1466 });
1467 let mut stream = complete_turn(
1468 Arc::clone(&self.registry),
1469 self.config.slot.clone(),
1470 binding.clone(),
1471 build,
1472 Arc::new(CtxSlotSink { ctx: ctx.clone() }),
1473 );
1474
1475 let mut text = String::new();
1480 let mut reasoning = String::new();
1481 let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
1482 let mut usage: Option<Value> = None;
1483 let mut stream_error: Option<ProviderError> = None;
1484 while let Some(item) = stream.next().await {
1485 match item {
1486 Ok(chunk) => {
1487 if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
1488 usage = Some(u.clone()); }
1490 if !chunk.delta.is_null() {
1491 assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
1492 }
1493 }
1494 Err(e) => {
1495 stream_error = Some(e);
1496 break;
1497 }
1498 }
1499 }
1500 let text_bytes = text.len() as u64;
1503 let reasoning_bytes = reasoning.len() as u64;
1504 if let Some(e) = stream_error {
1505 let class = error_class(&e);
1506 let action = consult_policy(self.policy.as_ref(), class);
1507 let note = action_note(action);
1508 let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
1509 self.observe_recover(ctx, iteration, step_request_seq, &audit)
1512 .await;
1513 self.observe_response(
1514 ctx,
1515 iteration,
1516 step_request_seq,
1517 "soft_failure",
1518 0,
1519 text_bytes,
1520 reasoning_bytes,
1521 usage.as_ref(),
1522 Some(&audit),
1523 )
1524 .await;
1525 return TurnResult {
1526 result: Err(TurnError::Soft {
1527 reason: format!("provider error ({class}): {e}{note}"),
1528 audit,
1529 }),
1530 usage,
1531 };
1532 }
1533 if text.is_empty() && calls.is_empty() {
1534 let action = consult_policy(self.policy.as_ref(), CLASS_EMPTY_RESPONSE);
1537 let note = action_note(action);
1538 let audit = recovery_audit(
1539 self.policy.as_ref(),
1540 kian_orchestrator::recovery::ErrorClass::EmptyResponse,
1541 );
1542 self.observe_recover(ctx, iteration, step_request_seq, &audit)
1543 .await;
1544 self.observe_response(
1545 ctx,
1546 iteration,
1547 step_request_seq,
1548 "soft_failure",
1549 0,
1550 0,
1551 0,
1552 usage.as_ref(),
1553 Some(&audit),
1554 )
1555 .await;
1556 return TurnResult {
1557 result: Err(TurnError::Soft {
1558 reason: format!("empty model response{note}"),
1559 audit,
1560 }),
1561 usage,
1562 };
1563 }
1564
1565 let tool_calls: Vec<ToolCall> = calls.into_values().map(CallAcc::finish).collect();
1566 let mut content = json!({"text": text});
1567 if !tool_calls.is_empty() {
1568 content["tool_calls"] = Value::Array(
1569 tool_calls
1570 .iter()
1571 .map(|c| json!({"id": c.id, "name": c.name, "arguments": c.arguments}))
1572 .collect(),
1573 );
1574 }
1575 if !reasoning.is_empty() {
1576 content["reasoning_content"] = Value::String(reasoning);
1579 }
1580 if let Err(e) = ctx
1581 .append(
1582 EventKind::AssistantMessage,
1583 json!({"role": "assistant", "content": content}),
1584 )
1585 .await
1586 {
1587 let fatal = TurnError::fatal(e, self.policy.as_ref());
1588 if let TurnError::Fatal { audit, .. } = &fatal {
1589 self.observe_fatal(
1590 ctx,
1591 iteration,
1592 step_request_seq,
1593 audit,
1594 text_bytes,
1595 reasoning_bytes,
1596 usage.as_ref(),
1597 )
1598 .await;
1599 }
1600 return TurnResult {
1601 result: Err(fatal),
1602 usage,
1603 };
1604 }
1605
1606 if tool_calls.is_empty() {
1607 self.observe_response(
1609 ctx,
1610 iteration,
1611 step_request_seq,
1612 "final_answer",
1613 0,
1614 text_bytes,
1615 reasoning_bytes,
1616 usage.as_ref(),
1617 None,
1618 )
1619 .await;
1620 return TurnResult {
1621 result: Ok(TurnOutcome::FinalAnswer),
1622 usage,
1623 };
1624 }
1625
1626 let n = tool_calls.len();
1627 for call in tool_calls {
1633 let decision = evaluate_permission(&self.config.permissions, &call.name);
1638 let hook_verdict = self
1650 .consult_tool_pre(ctx, &call, iteration, step_request_seq, decision)
1651 .await;
1652 let appended = match hook_verdict {
1653 kian_plugin::hooks::ToolVerdict::Deny {
1654 ref plugin,
1655 ref reason,
1656 } => {
1657 ctx.append(
1662 EventKind::ToolCall,
1663 tool_call_payload_hook_denied(&call, plugin, reason),
1664 )
1665 .await
1666 }
1667 _ => {
1668 ctx.append(EventKind::ToolCall, tool_call_payload(&call, decision))
1669 .await
1670 }
1671 };
1672 let call_seq = match appended {
1673 Ok(ev) => ev.seq,
1674 Err(e) => {
1675 let fatal = TurnError::fatal(e, self.policy.as_ref());
1676 if let TurnError::Fatal { audit, .. } = &fatal {
1677 self.observe_fatal(
1678 ctx,
1679 iteration,
1680 step_request_seq,
1681 audit,
1682 text_bytes,
1683 reasoning_bytes,
1684 usage.as_ref(),
1685 )
1686 .await;
1687 }
1688 return TurnResult {
1689 result: Err(fatal),
1690 usage,
1691 };
1692 }
1693 };
1694 if let kian_plugin::hooks::ToolVerdict::Deny {
1705 ref plugin,
1706 ref reason,
1707 } = hook_verdict
1708 {
1709 let denied = ToolResult {
1710 call_id: call.id.clone(),
1711 output: json!({
1712 "error": format!("denied by plugin {plugin}: {reason}"),
1713 "policy": "hook"
1714 }),
1715 is_error: true,
1716 redactions: Vec::new(),
1717 };
1718 if let Err(e) = ctx
1719 .append(EventKind::ToolResult, tool_result_payload(&denied))
1720 .await
1721 {
1722 let fatal = TurnError::fatal(e, self.policy.as_ref());
1723 if let TurnError::Fatal { audit, .. } = &fatal {
1724 self.observe_fatal(
1725 ctx,
1726 iteration,
1727 call_seq,
1728 audit,
1729 text_bytes,
1730 reasoning_bytes,
1731 usage.as_ref(),
1732 )
1733 .await;
1734 }
1735 return TurnResult {
1736 result: Err(fatal),
1737 usage,
1738 };
1739 }
1740 self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1741 .await;
1742 continue;
1743 }
1744 if matches!(decision, Some(PermissionDecision::Ask)) {
1748 continue;
1749 }
1750 if let Some(denied) = declared_denial(&call, decision) {
1755 if let Err(e) = ctx
1756 .append(EventKind::ToolResult, tool_result_payload(&denied))
1757 .await
1758 {
1759 let fatal = TurnError::fatal(e, self.policy.as_ref());
1760 if let TurnError::Fatal { audit, .. } = &fatal {
1761 self.observe_fatal(
1762 ctx,
1763 iteration,
1764 call_seq,
1765 audit,
1766 text_bytes,
1767 reasoning_bytes,
1768 usage.as_ref(),
1769 )
1770 .await;
1771 }
1772 return TurnResult {
1773 result: Err(fatal),
1774 usage,
1775 };
1776 }
1777 self.observe_tool_post(ctx, &denied, &call.name, call_seq)
1780 .await;
1781 continue;
1782 }
1783 let result = match self.tools.invoke(call.clone()).await {
1784 Ok(r) => r,
1785 Err(e) => {
1786 ToolResult {
1789 call_id: call.id.clone(),
1790 output: json!({"error": e.to_string()}),
1791 is_error: true,
1792 redactions: Vec::new(),
1793 }
1794 }
1795 };
1796 let result_seq = match ctx
1801 .append(EventKind::ToolResult, tool_result_payload(&result))
1802 .await
1803 {
1804 Ok(ev) => ev.seq,
1805 Err(e) => {
1806 let fatal = TurnError::fatal(e, self.policy.as_ref());
1807 if let TurnError::Fatal { audit, .. } = &fatal {
1808 self.observe_fatal(
1809 ctx,
1810 iteration,
1811 call_seq,
1812 audit,
1813 text_bytes,
1814 reasoning_bytes,
1815 usage.as_ref(),
1816 )
1817 .await;
1818 }
1819 return TurnResult {
1820 result: Err(fatal),
1821 usage,
1822 };
1823 }
1824 };
1825 self.observe_tool_post(ctx, &result, &call.name, result_seq)
1828 .await;
1829 }
1830 self.observe_response(
1833 ctx,
1834 iteration,
1835 step_request_seq,
1836 "tool_calls",
1837 n as u64,
1838 text_bytes,
1839 reasoning_bytes,
1840 usage.as_ref(),
1841 None,
1842 )
1843 .await;
1844 TurnResult {
1845 result: Ok(TurnOutcome::ToolCalls(n)),
1846 usage,
1847 }
1848 }
1849
1850 async fn compact_now(
1857 &self,
1858 ctx: &DrainCtx,
1859 binding: &SlotBinding,
1860 iteration: usize,
1861 trigger: CompactionTrigger,
1862 compactions: &mut usize,
1863 ) -> Result<Option<Flow>, LoopError> {
1864 if *compactions >= MAX_COMPACTIONS_PER_EPISODE {
1865 return Ok(None);
1866 }
1867 let events = ctx.events().await?;
1868 let plan = match plan_compaction(&events, &self.compaction, Some(&trigger)) {
1869 Ok(Some(plan)) => plan,
1870 Ok(None) => return Ok(None),
1871 Err(e) => {
1872 tracing::warn!(
1873 session = %ctx.session().0,
1874 error = %e,
1875 "compaction planner refused the stream"
1876 );
1877 return Ok(None);
1878 }
1879 };
1880 let transcript = match render_folded_transcript(&events, &plan) {
1881 Ok(transcript) => transcript,
1882 Err(e) => {
1883 tracing::warn!(
1884 session = %ctx.session().0,
1885 error = %e,
1886 "compaction transcript refused the stream"
1887 );
1888 return Ok(None);
1889 }
1890 };
1891 let target = binding.target.clone();
1892 let chat = summary_chat(&transcript);
1893 let request = match build_request_plan(target.profile.as_ref(), &target.model, &chat, &[]) {
1894 Ok(request) => request,
1895 Err(e) => return Ok(Some(Flow::Soft(format!("compact request plan: {e}")))),
1896 };
1897 let estimate = request
1898 .estimate
1899 .high
1900 .saturating_add(request.estimate.max_output_tokens.unwrap_or(0));
1901 let budget = project_budget(&events, &self.agent.budgets);
1904 if budget.would_exceed_tokens(estimate) {
1905 return Ok(Some(Flow::AwaitingBudget(json!({
1906 "limit": budget.tokens_limit,
1907 "raised": budget.tokens_raised,
1908 "spent": budget.tokens_spent,
1909 "estimate": estimate,
1910 "purpose": "compact",
1911 }))));
1912 }
1913
1914 ctx.begin_turn_with(json!({"iteration": iteration, "purpose": "compact"}))
1915 .await?;
1916 let (audit_body, body_form) = request.audit();
1917 let mut step_payload = json!({
1918 "slot": self.config.slot.0,
1919 "provider": target.provider,
1920 "model": target.model,
1921 "iteration": iteration,
1922 "purpose": "compact",
1923 "body": audit_body,
1924 "body_version": request.body_version,
1925 "dialect": request.dialect,
1926 "body_sha256": request.body_sha256,
1927 "body_bytes": request.body_bytes,
1928 "estimate": request.estimate,
1929 });
1930 if let Some(form) = body_form {
1931 step_payload["body_form"] = json!(form);
1932 }
1933 if let Some(digest) = &request.profile_digest {
1934 step_payload["profile_digest"] = json!(digest);
1935 }
1936 let step_request_seq = match ctx.append(EventKind::StepRequest, step_payload).await {
1937 Ok(event) => event.seq,
1938 Err(e) => {
1939 let _ = ctx
1940 .end_turn_with(json!({
1941 "iteration": iteration,
1942 "purpose": "compact",
1943 "outcome": "error",
1944 "error": {"class": "internal", "action": "none"},
1945 }))
1946 .await;
1947 return Err(e.into());
1948 }
1949 };
1950 let Some(provider) = self.registry.get(&target.provider) else {
1953 let audit = recovery_audit(
1954 self.policy.as_ref(),
1955 kian_orchestrator::recovery::ErrorClass::Unknown,
1956 );
1957 let _ = ctx
1958 .end_turn_with(json!({
1959 "iteration": iteration,
1960 "purpose": "compact",
1961 "outcome": "soft_failure",
1962 "error": audit,
1963 }))
1964 .await;
1965 return Ok(Some(Flow::Soft(format!(
1966 "compact: provider {} is not registered",
1967 target.provider
1968 ))));
1969 };
1970 let mut stream = provider.complete(ModelRequest {
1971 slot: self.config.slot.clone(),
1972 body: request.body,
1973 });
1974 let mut text = String::new();
1975 let mut reasoning = String::new();
1976 let mut calls: BTreeMap<u64, CallAcc> = BTreeMap::new();
1977 let mut usage: Option<Value> = None;
1978 let mut stream_error: Option<ProviderError> = None;
1979 while let Some(item) = stream.next().await {
1980 match item {
1981 Ok(chunk) => {
1982 if let Some(u) = chunk.usage.as_ref().filter(|u| !u.is_null()) {
1983 usage = Some(u.clone());
1984 }
1985 if !chunk.delta.is_null() {
1986 assemble_delta(&chunk.delta, &mut text, &mut reasoning, &mut calls);
1987 }
1988 }
1989 Err(e) => {
1990 stream_error = Some(e);
1991 break;
1992 }
1993 }
1994 }
1995 if let Some(e) = stream_error {
1996 let audit = recovery_audit(self.policy.as_ref(), provider_error_class(&e));
1997 let mut payload = json!({
1998 "iteration": iteration,
1999 "purpose": "compact",
2000 "outcome": "soft_failure",
2001 "error": audit,
2002 });
2003 if let Some(u) = usage.as_ref() {
2004 payload["usage"] = u.clone();
2005 }
2006 let _ = ctx.end_turn_with(payload).await;
2007 return Ok(Some(Flow::Soft(format!(
2008 "compact summary request failed: {e}"
2009 ))));
2010 }
2011 let summary = text.trim().to_string();
2012 if summary.is_empty() {
2013 let audit = recovery_audit(
2014 self.policy.as_ref(),
2015 kian_orchestrator::recovery::ErrorClass::EmptyResponse,
2016 );
2017 let mut payload = json!({
2018 "iteration": iteration,
2019 "purpose": "compact",
2020 "outcome": "soft_failure",
2021 "error": audit,
2022 });
2023 if let Some(u) = usage.as_ref() {
2024 payload["usage"] = u.clone();
2025 }
2026 let _ = ctx.end_turn_with(payload).await;
2027 return Ok(Some(Flow::Soft(
2028 "compact summary request returned an empty response".to_string(),
2029 )));
2030 }
2031 let compact_seq = match ctx
2034 .append(
2035 EventKind::Compact,
2036 json!({
2037 "from_seq": plan.from_seq,
2038 "to_seq": plan.to_seq,
2039 "summary": {"role": "assistant", "content": {"text": summary}},
2040 "produced_by": {"step_seq": step_request_seq},
2041 "reason": plan.reason,
2042 "folded_messages": plan.folded_messages,
2043 "reclaimed_tokens": plan.reclaimed_tokens,
2044 }),
2045 )
2046 .await
2047 {
2048 Ok(event) => event.seq,
2049 Err(e) => {
2050 let _ = ctx
2051 .end_turn_with(json!({
2052 "iteration": iteration,
2053 "purpose": "compact",
2054 "outcome": "error",
2055 "error": {"class": "internal", "action": "none"},
2056 }))
2057 .await;
2058 return Err(e.into());
2059 }
2060 };
2061 let mut payload = json!({
2062 "iteration": iteration,
2063 "purpose": "compact",
2064 "outcome": "compacted",
2065 "compact_seq": compact_seq,
2066 "from_seq": plan.from_seq,
2067 "to_seq": plan.to_seq,
2068 });
2069 if let Some(u) = usage.as_ref() {
2070 payload["usage"] = u.clone();
2071 }
2072 if let Err(e) = ctx.end_turn_with(payload).await {
2073 return Err(e.into());
2074 }
2075 *compactions += 1;
2076 tracing::info!(
2077 session = %ctx.session().0,
2078 from_seq = plan.from_seq,
2079 to_seq = plan.to_seq,
2080 folded_messages = plan.folded_messages,
2081 reclaimed_tokens = plan.reclaimed_tokens,
2082 "context compacted (ADR-058)"
2083 );
2084 Ok(Some(Flow::TurnDone))
2085 }
2086}
2087
2088impl TurnError {
2093 fn fatal(e: EngineError, policy: &dyn RecoveryPolicySource) -> Self {
2098 let error = LoopError::Engine(e);
2099 let audit = recovery_audit(policy, loop_error_class(&error));
2100 Self::Fatal { error, audit }
2101 }
2102}
2103
2104fn loop_error_class(e: &LoopError) -> kian_orchestrator::recovery::ErrorClass {
2110 match e {
2111 LoopError::Engine(_) => kian_orchestrator::recovery::ErrorClass::StoreFailure,
2112 LoopError::Context(_) | LoopError::Slot(_) => {
2113 kian_orchestrator::recovery::ErrorClass::Unknown
2114 }
2115 }
2116}
2117
2118fn preventive_trigger(binding: &SlotBinding, messages: &[Message]) -> Option<CompactionTrigger> {
2121 let profile = binding.target.profile.as_ref()?;
2122 let window = profile.context_window?;
2123 if window == 0 {
2124 return None;
2125 }
2126 let incoming = estimate_context_tokens(messages)
2127 .saturating_add(profile.max_output.unwrap_or(DEFAULT_OUTPUT_RESERVE_TOKENS));
2128 Some(CompactionTrigger::Pressure(CompactionPressure {
2129 context_window_tokens: window,
2130 incoming_estimate_tokens: incoming,
2131 }))
2132}
2133
2134fn render_folded_transcript(
2139 events: &[Event],
2140 plan: &CompactionPlan,
2141) -> Result<String, kian_core::context::ContextError> {
2142 let messages = derive_model_context(events)?;
2143 let provenance = context_provenance(events)?;
2144 let mut out = String::new();
2145 for (message, source) in messages.iter().zip(provenance.iter()) {
2146 if !(plan.from_seq..plan.to_seq).contains(source) {
2147 continue;
2148 }
2149 let body = match &message.content {
2150 Value::String(text) => text.clone(),
2151 other => serde_json::to_string(other).unwrap_or_default(),
2152 };
2153 let line = format!("{}: {body}\n", message.role);
2154 if out.len().saturating_add(line.len()) > MAX_TRANSCRIPT_CHARS {
2155 let room = MAX_TRANSCRIPT_CHARS.saturating_sub(out.len());
2156 out.push_str(take_chars(&line, room));
2157 out.push_str("\n[... transcript truncated ...]\n");
2158 break;
2159 }
2160 out.push_str(&line);
2161 }
2162 Ok(out)
2163}
2164
2165fn take_chars(text: &str, max: usize) -> &str {
2168 match text.char_indices().nth(max) {
2169 Some((index, _)) => &text[..index],
2170 None => text,
2171 }
2172}
2173
2174fn summary_chat(transcript: &str) -> Vec<ChatMessage> {
2178 vec![
2179 ChatMessage::plain("system", SUMMARY_SYSTEM_PROMPT),
2180 ChatMessage::plain(
2181 "user",
2182 format!(
2183 "Compress the following earlier conversation into one dense summary. The summary will replace these turns in the model context.\n\n{transcript}"
2184 ),
2185 ),
2186 ]
2187}
2188
2189fn provider_error_class(e: &ProviderError) -> kian_orchestrator::recovery::ErrorClass {
2192 kian_orchestrator::recovery::classify(
2193 &kian_orchestrator::recovery::RecoveryError::Provider(e.clone()),
2194 &kian_orchestrator::recovery::ClassifyCtx { attempt: 0 },
2195 )
2196}
2197
2198fn recovery_audit(
2202 policy: &dyn RecoveryPolicySource,
2203 class: kian_orchestrator::recovery::ErrorClass,
2204) -> Value {
2205 let action = consult_policy(policy, class.name());
2206 json!({
2207 "class": class.name(),
2208 "action": action_name(action.as_ref()),
2209 })
2210}
2211
2212fn action_name(action: Option<&RecoveryAction>) -> &'static str {
2215 match action {
2216 None => "none",
2217 Some(RecoveryAction::BackoffRetry { .. }) => "backoff_retry",
2218 Some(RecoveryAction::CompressThenRetry) => "compress_then_retry",
2219 Some(RecoveryAction::Failover) => "failover",
2220 Some(RecoveryAction::InterruptAsk) => "interrupt_ask",
2221 Some(RecoveryAction::Fail) => "fail",
2222 }
2223}
2224
2225fn fold_trigger(audit: &Value) -> Option<CompactionTrigger> {
2230 if audit.get("action").and_then(Value::as_str)
2231 != Some(action_name(Some(&RecoveryAction::CompressThenRetry)))
2232 {
2233 return None;
2234 }
2235 let class = audit.get("class").and_then(Value::as_str)?;
2236 if class == kian_orchestrator::recovery::ErrorClass::ContextOverflow.name() {
2237 return Some(CompactionTrigger::Overflow);
2238 }
2239 if class == kian_orchestrator::recovery::ErrorClass::RequestTooLarge.name() {
2240 return Some(CompactionTrigger::Oversized);
2241 }
2242 None
2243}
2244
2245struct CtxSlotSink {
2249 ctx: DrainCtx,
2250}
2251
2252impl SlotEventSink for CtxSlotSink {
2253 fn persist_fallback(
2254 &self,
2255 payload: Value,
2256 ) -> futures::future::BoxFuture<'static, Result<(), String>> {
2257 let ctx = self.ctx.clone();
2258 Box::pin(async move {
2259 ctx.append(EventKind::SlotFallback, payload)
2260 .await
2261 .map(|_| ())
2262 .map_err(|e| e.to_string())
2263 })
2264 }
2265}
2266
2267struct CallAcc {
2269 id: String,
2270 name: String,
2271 arguments: String,
2272}
2273
2274impl CallAcc {
2275 fn finish(self) -> ToolCall {
2276 let arguments = serde_json::from_str::<Value>(&self.arguments)
2277 .unwrap_or_else(|_| Value::String(self.arguments.clone()));
2278 ToolCall {
2279 id: self.id,
2280 name: self.name,
2281 arguments,
2282 }
2283 }
2284}
2285
2286fn assemble_delta(
2289 delta: &Value,
2290 text: &mut String,
2291 reasoning: &mut String,
2292 calls: &mut BTreeMap<u64, CallAcc>,
2293) {
2294 if let Some(fragment) = delta.get("content").and_then(Value::as_str) {
2295 text.push_str(fragment);
2296 }
2297 if let Some(fragment) = delta.get("reasoning_content").and_then(Value::as_str) {
2298 reasoning.push_str(fragment);
2299 }
2300 if let Some(list) = delta.get("tool_calls").and_then(Value::as_array) {
2301 for entry in list {
2302 let index = entry.get("index").and_then(Value::as_u64).unwrap_or(0);
2303 let slot = calls.entry(index).or_insert_with(|| CallAcc {
2304 id: String::new(),
2305 name: String::new(),
2306 arguments: String::new(),
2307 });
2308 if let Some(id) = entry.get("id").and_then(Value::as_str) {
2309 slot.id = id.to_string();
2310 }
2311 if let Some(name) = entry.pointer("/function/name").and_then(Value::as_str) {
2312 slot.name.push_str(name);
2313 }
2314 if let Some(args) = entry.pointer("/function/arguments").and_then(Value::as_str) {
2315 slot.arguments.push_str(args);
2316 }
2317 }
2318 }
2319}
2320
2321pub fn to_chat_message(m: &Message) -> Option<ChatMessage> {
2346 match m.role.as_str() {
2347 "tool" => Some(tool_result_message(&m.content)),
2348 "assistant" => assistant_message(&m.content),
2349 _ => Some(string_or_compact(&m.role, &m.content)),
2350 }
2351}
2352
2353type ImageReference = (String, String);
2355
2356type VisionEnvelope = (Option<String>, Vec<ImageReference>);
2358
2359fn vision_envelope(content: &Value) -> Option<VisionEnvelope> {
2373 let object = content.as_object()?;
2374 let references = object.get("images")?.as_array()?;
2375 let mut usable = Vec::new();
2376 for item in references {
2377 let Some(entry) = item.as_object() else {
2378 continue;
2379 };
2380 let Some(artifact) = entry
2381 .get("artifact")
2382 .and_then(Value::as_str)
2383 .filter(|id| !id.is_empty())
2384 else {
2385 continue;
2386 };
2387 let Some(media_type) = entry
2388 .get("media_type")
2389 .and_then(Value::as_str)
2390 .filter(|t| !t.is_empty())
2391 else {
2392 continue;
2393 };
2394 usable.push((artifact.to_owned(), media_type.to_owned()));
2395 }
2396 if usable.is_empty() {
2397 return None;
2398 }
2399 let mut remainder = object.clone();
2400 remainder.remove("images");
2401 let text = if remainder.is_empty() {
2402 None
2403 } else if remainder.len() == 1 && remainder.get("text").is_some_and(Value::is_string) {
2404 remainder
2405 .get("text")
2406 .and_then(Value::as_str)
2407 .map(str::to_owned)
2408 } else {
2409 Some(serde_json::to_string(&Value::Object(remainder)).unwrap_or_default())
2410 };
2411 Some((text, usable))
2412}
2413
2414#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2417pub(crate) enum PermissionDecision {
2418 AllowConfigured,
2420 AllowDefault,
2422 Deny,
2424 Ask,
2427}
2428
2429const PERMISSION_DENY_REASON: &str = "tool_denied_by_policy";
2431
2432fn evaluate_permission(
2442 permissions: &BTreeMap<String, Permission>,
2443 tool: &str,
2444) -> Option<PermissionDecision> {
2445 if permissions.is_empty() {
2446 return None;
2447 }
2448 match permissions.get(tool) {
2449 Some(Permission::Allow) => Some(PermissionDecision::AllowConfigured),
2450 Some(Permission::Deny) => Some(PermissionDecision::Deny),
2451 Some(Permission::Ask) => Some(PermissionDecision::Ask),
2452 None => Some(PermissionDecision::AllowDefault),
2453 }
2454}
2455
2456fn declared_denial(call: &ToolCall, decision: Option<PermissionDecision>) -> Option<ToolResult> {
2461 matches!(decision, Some(PermissionDecision::Deny)).then(|| ToolResult {
2462 call_id: call.id.clone(),
2463 output: json!({
2464 "error": format!("permission denied by policy: {}", call.name),
2465 "policy": "deny"
2466 }),
2467 is_error: true,
2468 redactions: Vec::new(),
2469 })
2470}
2471
2472fn tool_call_payload(call: &ToolCall, decision: Option<PermissionDecision>) -> Value {
2478 let mut payload = json!({
2479 "role": "assistant",
2480 "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
2481 });
2482 if let Some(decision) = decision {
2483 payload["permission"] = match decision {
2484 PermissionDecision::AllowConfigured => json!({
2485 "evaluated": "allow", "policy": "configured", "matched": call.name
2486 }),
2487 PermissionDecision::AllowDefault => json!({
2488 "evaluated": "allow", "policy": "default", "matched": call.name
2489 }),
2490 PermissionDecision::Deny => json!({
2491 "evaluated": "deny",
2492 "policy": "configured",
2493 "matched": call.name,
2494 "reason": PERMISSION_DENY_REASON
2495 }),
2496 PermissionDecision::Ask => json!({
2497 "evaluated": "ask",
2498 "policy": "configured",
2499 "matched": call.name
2500 }),
2501 };
2502 }
2503 payload
2504}
2505
2506fn tool_call_payload_hook_denied(call: &ToolCall, plugin: &str, reason: &str) -> Value {
2514 let mut payload = json!({
2515 "role": "assistant",
2516 "content": {"id": call.id, "name": call.name, "arguments": call.arguments}
2517 });
2518 payload["permission"] = json!({
2519 "evaluated": "deny",
2520 "policy": "hook",
2521 "matched": format!("{plugin}:tool/pre"),
2522 "reason": reason,
2523 });
2524 payload
2525}
2526
2527fn permission_view(
2532 call: &ToolCall,
2533 decision: Option<PermissionDecision>,
2534) -> kian_plugin::hooks::PermissionView {
2535 match decision {
2536 Some(PermissionDecision::AllowConfigured) => kian_plugin::hooks::PermissionView {
2537 evaluated: "allow".to_string(),
2538 policy: "configured".to_string(),
2539 matched: call.name.clone(),
2540 reason: None,
2541 },
2542 Some(PermissionDecision::Deny) => kian_plugin::hooks::PermissionView {
2543 evaluated: "deny".to_string(),
2544 policy: "configured".to_string(),
2545 matched: call.name.clone(),
2546 reason: Some(PERMISSION_DENY_REASON.to_string()),
2547 },
2548 Some(PermissionDecision::Ask) => kian_plugin::hooks::PermissionView {
2549 evaluated: "ask".to_string(),
2550 policy: "configured".to_string(),
2551 matched: call.name.clone(),
2552 reason: None,
2553 },
2554 Some(PermissionDecision::AllowDefault) | None => kian_plugin::hooks::PermissionView {
2555 evaluated: "allow".to_string(),
2556 policy: "default".to_string(),
2557 matched: call.name.clone(),
2558 reason: None,
2559 },
2560 }
2561}
2562
2563fn tool_result_payload(result: &ToolResult) -> Value {
2570 let mut payload = json!({
2571 "role": "tool",
2572 "content": {
2573 "call_id": result.call_id,
2574 "output": result.output,
2575 "is_error": result.is_error
2576 }
2577 });
2578 if !result.redactions.is_empty() {
2579 if let Ok(report) = serde_json::to_value(&result.redactions) {
2582 payload["redactions"] = report;
2583 }
2584 }
2585 payload
2586}
2587
2588fn tool_result_payload_confirmed(result: &ToolResult, decision: &ConfirmIntent) -> Value {
2592 let mut payload = tool_result_payload(result);
2593 let mut provenance = json!({
2594 "call_id": result.call_id,
2595 "decision": decision.decision.as_str(),
2596 "requested_by": decision.requested_by,
2597 "answered_at_ms": decision.answered_at_ms,
2598 });
2599 if decision.expired {
2600 provenance["expired"] = json!(true);
2601 }
2602 payload["confirmation"] = provenance;
2603 payload
2604}
2605
2606fn string_or_compact(role: &str, content: &Value) -> ChatMessage {
2609 let text = match content {
2610 Value::String(s) => s.clone(),
2611 other => serde_json::to_string(other).unwrap_or_default(),
2612 };
2613 ChatMessage {
2614 role: role.to_owned(),
2615 content: Some(text),
2616 tool_call_id: None,
2617 tool_calls: None,
2618 reasoning_content: None,
2619 images: Vec::new(),
2620 }
2621}
2622
2623fn tool_result_message(content: &Value) -> ChatMessage {
2627 if let Some(obj) = content.as_object()
2628 && let Some(call_id) = obj.get("call_id").and_then(Value::as_str)
2629 {
2630 let output = obj.get("output").cloned().unwrap_or(Value::Null);
2631 return ChatMessage {
2632 role: "tool".into(),
2633 content: Some(serde_json::to_string(&output).unwrap_or_default()),
2634 tool_call_id: Some(call_id.to_owned()),
2635 tool_calls: None,
2636 reasoning_content: None,
2637 images: Vec::new(),
2638 };
2639 }
2640 ChatMessage {
2641 role: "tool".into(),
2642 content: Some(serde_json::to_string(content).unwrap_or_default()),
2643 tool_call_id: Some(String::new()),
2644 tool_calls: None,
2645 reasoning_content: None,
2646 images: Vec::new(),
2647 }
2648}
2649
2650fn reasoning_field(obj: &serde_json::Map<String, Value>) -> Option<String> {
2653 obj.get("reasoning_content")
2654 .and_then(Value::as_str)
2655 .filter(|r| !r.is_empty())
2656 .map(str::to_owned)
2657}
2658
2659fn assistant_message(content: &Value) -> Option<ChatMessage> {
2663 let Some(obj) = content.as_object() else {
2664 return Some(string_or_compact("assistant", content));
2665 };
2666 if obj.contains_key("tool_calls") {
2667 let calls: Option<Vec<WireToolCall>> =
2668 obj.get("tool_calls").and_then(Value::as_array).map(|list| {
2669 list.iter()
2670 .filter_map(|tc| {
2671 let id = tc.get("id").and_then(Value::as_str)?;
2672 let name = tc.get("name").and_then(Value::as_str)?;
2673 let arguments = tc.get("arguments").cloned().unwrap_or(Value::Null);
2674 Some(WireToolCall {
2675 id: id.to_owned(),
2676 r#type: "function".into(),
2677 function: WireFunctionCall {
2678 name: name.to_owned(),
2679 arguments: serde_json::to_string(&arguments).unwrap_or_default(),
2680 },
2681 })
2682 })
2683 .collect()
2684 });
2685 return Some(ChatMessage {
2686 role: "assistant".into(),
2687 content: obj
2690 .get("text")
2691 .and_then(Value::as_str)
2692 .filter(|t| !t.is_empty())
2693 .map(str::to_owned),
2694 tool_call_id: None,
2695 tool_calls: calls,
2696 reasoning_content: reasoning_field(obj),
2697 images: Vec::new(),
2698 });
2699 }
2700 if obj.contains_key("id") && obj.contains_key("name") && obj.contains_key("arguments") {
2703 return None;
2704 }
2705 if let Some(text) = obj.get("text").and_then(Value::as_str) {
2706 return Some(ChatMessage {
2707 role: "assistant".into(),
2708 content: Some(text.to_owned()),
2709 tool_call_id: None,
2710 tool_calls: None,
2711 reasoning_content: reasoning_field(obj),
2712 images: Vec::new(),
2713 });
2714 }
2715 Some(string_or_compact("assistant", content))
2716}
2717
2718fn resident_empty_batch(scope: BudgetScope, taken_empty: bool, last_role: Option<&str>) -> bool {
2723 scope == BudgetScope::PerEpisode && taken_empty && last_role == Some("assistant")
2724}
2725
2726fn error_class(e: &ProviderError) -> &'static str {
2729 match e {
2730 ProviderError::RateLimited => "rate_limited",
2731 ProviderError::ContextOverflow => "context_overflow",
2732 ProviderError::Unavailable(_) | ProviderError::Transport(_) => "provider_down",
2733 ProviderError::EmptyResponse => CLASS_EMPTY_RESPONSE,
2734 ProviderError::RequestTooLarge { .. } => "request_too_large",
2737 ProviderError::InvalidResponse(_) => "validation_failed",
2738 ProviderError::Other(_) => "internal",
2739 }
2740}
2741
2742fn select_tail_images(budget: VisionBudget, tail: &[Vec<usize>]) -> (Vec<usize>, usize, usize) {
2754 let total: usize = tail.iter().map(|sizes| sizes.len()).sum();
2755 let mut per_message = vec![0usize; tail.len()];
2756 let mut admitted = 0usize;
2757 let mut admitted_bytes = 0u64;
2758 'selection: for (index, sizes) in tail.iter().enumerate().rev() {
2759 for size in sizes.iter().rev() {
2760 if per_message[index] >= MAX_IMAGES_PER_MESSAGE {
2761 break 'selection;
2762 }
2763 if admitted >= budget.max_images_per_turn
2764 || admitted_bytes + *size as u64 > budget.max_image_bytes_per_turn
2765 {
2766 break 'selection;
2767 }
2768 admitted += 1;
2769 admitted_bytes += *size as u64;
2770 per_message[index] += 1;
2771 }
2772 }
2773 (per_message, admitted, total - admitted)
2774}
2775
2776fn consult_policy(policy: &dyn RecoveryPolicySource, class: &str) -> Option<RecoveryAction> {
2777 policy
2778 .table()
2779 .into_iter()
2780 .find(|rule| rule.class == class)
2781 .map(|rule| rule.action)
2782}
2783
2784fn action_note(action: Option<RecoveryAction>) -> String {
2785 match action {
2786 Some(a) => format!("; recovery policy action: {a:?}"),
2787 None => "; no matching recovery policy rule".into(),
2788 }
2789}
2790
2791#[cfg(test)]
2792mod tests {
2793 use crate::react::{
2794 BudgetScope, CLASS_EMPTY_RESPONSE, ReActConfig, ReActLoop, assemble_delta, consult_policy,
2795 to_chat_message, tool_result_payload,
2796 };
2797 use crate::test_support::{NoopPolicy, NoopTools, agent_def};
2798 use kian_core::context::{Message, derive_model_context};
2799 use kian_core::events::{Event, EventKind};
2800 use kian_core::model::SessionId;
2801 use kian_core::seams::{ToolCall, ToolResult};
2802 use kian_core::secrets::{Redaction, RedactionKind};
2803 use kian_llm::provider::build_chat_body;
2804 use serde_json::json;
2805 use std::collections::BTreeMap;
2806
2807 fn msg(role: &str, content: serde_json::Value) -> Message {
2808 Message {
2809 role: role.into(),
2810 content,
2811 synthetic: false,
2812 }
2813 }
2814
2815 #[test]
2820 fn tool_result_payload_carries_redactions_outside_content() {
2821 let plain = ToolResult {
2822 call_id: "call-1".into(),
2823 output: json!({"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false}),
2824 is_error: false,
2825 redactions: Vec::new(),
2826 };
2827 let payload = tool_result_payload(&plain);
2828 assert_eq!(
2829 payload,
2830 json!({
2831 "role": "tool",
2832 "content": {
2833 "call_id": "call-1",
2834 "output": {"exit_code": 0, "stdout": "ok", "stderr": "", "timed_out": false},
2835 "is_error": false
2836 }
2837 }),
2838 "no redactions → no key, bytes unchanged"
2839 );
2840
2841 let redacted = ToolResult {
2842 call_id: "call-2".into(),
2843 output: json!({"exit_code": 0, "stdout": "[REDACTED:token]", "stderr": "", "timed_out": false}),
2844 is_error: false,
2845 redactions: vec![Redaction {
2846 kind: RedactionKind::TokenPattern,
2847 name: "ghp_".into(),
2848 count: 1,
2849 }],
2850 };
2851 let payload = tool_result_payload(&redacted);
2852 assert_eq!(
2853 payload["redactions"],
2854 json!([{"kind": "token_pattern", "name": "ghp_", "count": 1}])
2855 );
2856 assert!(payload["content"].get("redactions").is_none());
2859 assert_eq!(payload["content"]["call_id"], json!("call-2"));
2860 }
2861
2862 #[test]
2866 fn redactions_payload_key_never_enters_the_model_context() {
2867 let session = SessionId::new();
2868 let bytes = tool_result_payload(&ToolResult {
2869 call_id: "call-9".into(),
2870 output: json!({"content": "scrubbed"}),
2871 is_error: false,
2872 redactions: vec![Redaction {
2873 kind: RedactionKind::EnvLine,
2874 name: "MY_SERVICE_TOKEN".into(),
2875 count: 2,
2876 }],
2877 });
2878 let with = Event {
2879 seq: 2,
2880 session,
2881 epoch: kian_core::model::Epoch(1),
2882 ts: 1,
2883 kind: EventKind::ToolResult,
2884 bytes: bytes.clone(),
2885 version: 0,
2886 };
2887 let mut without_bytes = bytes.clone();
2888 without_bytes.as_object_mut().unwrap().remove("redactions");
2889 let without = Event {
2890 bytes: without_bytes,
2891 ..with.clone()
2892 };
2893 let base = Event {
2894 seq: 1,
2895 session,
2896 epoch: kian_core::model::Epoch(0),
2897 ts: 0,
2898 kind: EventKind::SessionCreated,
2899 bytes: json!({}),
2900 version: 0,
2901 };
2902 let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
2903 let ctx_without = derive_model_context(&[base, without]).unwrap();
2904 assert_eq!(ctx_with, ctx_without);
2905 assert_eq!(ctx_with.len(), 1);
2906 let chat = to_chat_message(&ctx_with[0]).unwrap();
2908 assert_eq!(chat.role, "tool");
2909 assert_eq!(chat.tool_call_id.as_deref(), Some("call-9"));
2910 assert_eq!(chat.content.as_deref(), Some("{\"content\":\"scrubbed\"}"));
2911 }
2912
2913 #[test]
2918 fn tool_round_trip_projects_to_the_strict_wire_shape() {
2919 let assistant = msg(
2920 "assistant",
2921 json!({
2922 "text": "",
2923 "tool_calls": [
2924 {"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}
2925 ]
2926 }),
2927 );
2928 let chat = to_chat_message(&assistant).unwrap();
2929 assert_eq!(chat.role, "assistant");
2930 assert_eq!(chat.content, None, "empty text serializes as null");
2931 let tc = &chat.tool_calls.as_ref().unwrap()[0];
2932 assert_eq!(tc.id, "call-1");
2933 assert_eq!(tc.r#type, "function");
2934 assert_eq!(tc.function.name, "fs_read");
2935 assert_eq!(tc.function.arguments, "{\"path\":\"a.txt\"}");
2936
2937 let with_text = msg(
2939 "assistant",
2940 json!({"text": "checking", "tool_calls": [
2941 {"id": "call-2", "name": "exec", "arguments": {"argv": ["true"]}}
2942 ]}),
2943 );
2944 let chat = to_chat_message(&with_text).unwrap();
2945 assert_eq!(chat.content.as_deref(), Some("checking"));
2946
2947 let dup = msg(
2949 "assistant",
2950 json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}}),
2951 );
2952 assert!(to_chat_message(&dup).is_none());
2953
2954 let result = msg(
2956 "tool",
2957 json!({"call_id": "call-1", "output": {"content": "x"}, "is_error": false}),
2958 );
2959 let chat = to_chat_message(&result).unwrap();
2960 assert_eq!(chat.role, "tool");
2961 assert_eq!(chat.tool_call_id.as_deref(), Some("call-1"));
2962 assert_eq!(chat.content.as_deref(), Some("{\"content\":\"x\"}"));
2963 assert!(chat.tool_calls.is_none());
2964 }
2965
2966 #[test]
2970 fn plain_messages_keep_the_v1_shape() {
2971 let user = msg("user", json!("hello"));
2972 let chat = to_chat_message(&user).unwrap();
2973 assert_eq!(chat.role, "user");
2974 assert_eq!(chat.content.as_deref(), Some("hello"));
2975 assert!(chat.tool_call_id.is_none() && chat.tool_calls.is_none());
2976
2977 let bare = msg("assistant", json!({"text": "hi"}));
2978 assert_eq!(
2979 to_chat_message(&bare).unwrap().content.as_deref(),
2980 Some("hi")
2981 );
2982
2983 let foreign = msg("tool", json!({"odd": true}));
2986 let chat = to_chat_message(&foreign).unwrap();
2987 assert_eq!(chat.tool_call_id.as_deref(), Some(""));
2988 }
2989
2990 #[test]
2998 fn permission_evaluation_covers_absent_default_and_configured() {
2999 use crate::react::{PermissionDecision, evaluate_permission};
3000 use kian_core::model::Permission;
3001
3002 let empty: BTreeMap<String, Permission> = BTreeMap::new();
3003 assert_eq!(evaluate_permission(&empty, "fs_write"), None);
3004
3005 let table: BTreeMap<String, Permission> = BTreeMap::from([
3006 ("fs_read".to_string(), Permission::Allow),
3007 ("fs_write".to_string(), Permission::Deny),
3008 ]);
3009 assert_eq!(
3010 evaluate_permission(&table, "fs_read"),
3011 Some(PermissionDecision::AllowConfigured)
3012 );
3013 assert_eq!(
3014 evaluate_permission(&table, "fs_write"),
3015 Some(PermissionDecision::Deny)
3016 );
3017 assert_eq!(
3020 evaluate_permission(&table, "exec"),
3021 Some(PermissionDecision::AllowDefault)
3022 );
3023 }
3024
3025 #[test]
3029 fn tool_call_payload_carries_permission_provenance_outside_content() {
3030 use crate::react::{evaluate_permission, tool_call_payload};
3031 use kian_core::model::Permission;
3032
3033 let call = ToolCall {
3034 id: "call-7".into(),
3035 name: "fs_write".into(),
3036 arguments: json!({"path": "a.txt"}),
3037 };
3038
3039 let empty: BTreeMap<String, Permission> = BTreeMap::new();
3041 let legacy = tool_call_payload(&call, evaluate_permission(&empty, &call.name));
3042 assert_eq!(
3043 legacy,
3044 json!({
3045 "role": "assistant",
3046 "content": {"id": "call-7", "name": "fs_write", "arguments": {"path": "a.txt"}}
3047 })
3048 );
3049
3050 let table: BTreeMap<String, Permission> =
3052 BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
3053 let allowed = tool_call_payload(&call, evaluate_permission(&table, &call.name)); assert_eq!(
3055 allowed["permission"],
3056 json!({"evaluated": "allow", "policy": "default", "matched": "fs_write"})
3057 );
3058 assert_eq!(allowed["content"], legacy["content"]);
3059
3060 let table: BTreeMap<String, Permission> =
3062 BTreeMap::from([("fs_write".to_string(), Permission::Deny)]);
3063 let denied = tool_call_payload(&call, evaluate_permission(&table, &call.name));
3064 assert_eq!(
3065 denied["permission"],
3066 json!({
3067 "evaluated": "deny",
3068 "policy": "configured",
3069 "matched": "fs_write",
3070 "reason": "tool_denied_by_policy"
3071 })
3072 );
3073 assert_eq!(denied["content"], legacy["content"]);
3074 }
3075
3076 #[test]
3087 fn hook_denied_permission_payload_goldens_are_frozen_bytes() {
3088 use crate::react::{evaluate_permission, tool_call_payload, tool_call_payload_hook_denied};
3089 use kian_core::model::Permission;
3090
3091 let call = ToolCall {
3092 id: "call-7".into(),
3093 name: "exec".into(),
3094 arguments: json!({"cmd": ["ls"]}),
3095 };
3096
3097 let hook_denied =
3099 tool_call_payload_hook_denied(&call, "approval-gate", "exec not on the allowlist");
3100 assert_eq!(
3101 serde_json::to_string(&hook_denied).unwrap(),
3102 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3103 \"permission\":{\"evaluated\":\"deny\",\"matched\":\"approval-gate:tool/pre\",\
3104 \"policy\":\"hook\",\"reason\":\"exec not on the allowlist\"},\"role\":\"assistant\"}"
3105 );
3106
3107 let denied_result = ToolResult {
3111 call_id: call.id.clone(),
3112 output: json!({
3113 "error": "denied by plugin approval-gate: exec not on the allowlist",
3114 "policy": "hook"
3115 }),
3116 is_error: true,
3117 redactions: Vec::new(),
3118 };
3119 assert_eq!(
3120 serde_json::to_string(&tool_result_payload(&denied_result)).unwrap(),
3121 "{\"content\":{\"call_id\":\"call-7\",\"is_error\":true,\
3122 \"output\":{\"error\":\"denied by plugin approval-gate: exec not on the allowlist\",\
3123 \"policy\":\"hook\"}},\"role\":\"tool\"}"
3124 );
3125
3126 let empty: BTreeMap<String, Permission> = BTreeMap::new();
3130 assert_eq!(
3131 serde_json::to_string(&tool_call_payload(
3132 &call,
3133 evaluate_permission(&empty, &call.name)
3134 ))
3135 .unwrap(),
3136 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3137 \"role\":\"assistant\"}"
3138 );
3139 let default_table = BTreeMap::from([("fs_read".to_string(), Permission::Allow)]);
3140 assert_eq!(
3141 serde_json::to_string(&tool_call_payload(
3142 &call,
3143 evaluate_permission(&default_table, &call.name)
3144 ))
3145 .unwrap(),
3146 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3147 \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"default\"},\
3148 \"role\":\"assistant\"}"
3149 );
3150 let allow_table = BTreeMap::from([("exec".to_string(), Permission::Allow)]);
3151 assert_eq!(
3152 serde_json::to_string(&tool_call_payload(
3153 &call,
3154 evaluate_permission(&allow_table, &call.name)
3155 ))
3156 .unwrap(),
3157 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3158 \"permission\":{\"evaluated\":\"allow\",\"matched\":\"exec\",\"policy\":\"configured\"},\
3159 \"role\":\"assistant\"}"
3160 );
3161 let deny_table = BTreeMap::from([("exec".to_string(), Permission::Deny)]);
3162 assert_eq!(
3163 serde_json::to_string(&tool_call_payload(
3164 &call,
3165 evaluate_permission(&deny_table, &call.name)
3166 ))
3167 .unwrap(),
3168 "{\"content\":{\"arguments\":{\"cmd\":[\"ls\"]},\"id\":\"call-7\",\"name\":\"exec\"},\
3169 \"permission\":{\"evaluated\":\"deny\",\"matched\":\"exec\",\"policy\":\"configured\",\
3170 \"reason\":\"tool_denied_by_policy\"},\"role\":\"assistant\"}"
3171 );
3172 }
3173
3174 #[test]
3179 fn permission_payload_key_never_enters_the_model_context() {
3180 use crate::react::{PermissionDecision, tool_call_payload};
3181 use kian_core::seams::ToolCall;
3182
3183 let session = SessionId::new();
3184 let call = ToolCall {
3185 id: "call-1".into(),
3186 name: "fs_read".into(),
3187 arguments: json!({"path": "a.txt"}),
3188 };
3189 let with_bytes = tool_call_payload(&call, Some(PermissionDecision::Deny));
3190 let mut without_bytes = with_bytes.clone();
3191 without_bytes.as_object_mut().unwrap().remove("permission");
3192 let with = Event {
3193 seq: 2,
3194 session,
3195 epoch: kian_core::model::Epoch(1),
3196 ts: 1,
3197 kind: EventKind::ToolCall,
3198 bytes: with_bytes,
3199 version: 0,
3200 };
3201 let without = Event {
3202 bytes: without_bytes,
3203 ..with.clone()
3204 };
3205 let base = Event {
3206 seq: 1,
3207 session,
3208 epoch: kian_core::model::Epoch(0),
3209 ts: 0,
3210 kind: EventKind::SessionCreated,
3211 bytes: json!({}),
3212 version: 0,
3213 };
3214 let ctx_with = derive_model_context(&[base.clone(), with]).unwrap();
3215 let ctx_without = derive_model_context(&[base, without]).unwrap();
3216 assert_eq!(ctx_with, ctx_without);
3217 assert_eq!(ctx_with.len(), 1);
3218 assert_eq!(ctx_with[0].role, "assistant");
3221 assert_eq!(
3222 ctx_with[0].content,
3223 json!({"id": "call-1", "name": "fs_read", "arguments": {"path": "a.txt"}})
3224 );
3225 assert!(!ctx_with[0].synthetic);
3226 }
3227
3228 #[test]
3235 fn resident_empty_batch_is_skipped_only_for_resident_assistant_tails() {
3236 use super::resident_empty_batch;
3237 assert!(resident_empty_batch(
3238 BudgetScope::PerEpisode,
3239 true,
3240 Some("assistant")
3241 ));
3242 assert!(!resident_empty_batch(
3243 BudgetScope::PerEpisode,
3244 false,
3245 Some("assistant")
3246 ));
3247 assert!(!resident_empty_batch(
3248 BudgetScope::PerEpisode,
3249 true,
3250 Some("tool")
3251 ));
3252 assert!(!resident_empty_batch(
3253 BudgetScope::PerEpisode,
3254 true,
3255 Some("user")
3256 ));
3257 assert!(!resident_empty_batch(
3258 BudgetScope::Lifetime,
3259 true,
3260 Some("assistant")
3261 ));
3262 }
3263
3264 #[test]
3265 fn budget_scope_selects_lifetime_or_episode_counter() {
3266 assert_eq!(BudgetScope::Lifetime.used(9, 0), 9);
3267 assert_eq!(BudgetScope::Lifetime.used(0, 9), 0);
3268 assert_eq!(BudgetScope::PerEpisode.used(9, 2), 2);
3269 assert_eq!(BudgetScope::PerEpisode.used(0, 0), 0);
3270 }
3271
3272 #[test]
3273 fn delta_assembly_concatenates_content_fragments() {
3274 let mut text = String::new();
3275 let mut reasoning = String::new();
3276 let mut calls = Default::default();
3277 for fragment in ["Hello", ", ", "kian"] {
3278 assemble_delta(
3279 &serde_json::json!({"content": fragment}),
3280 &mut text,
3281 &mut reasoning,
3282 &mut calls,
3283 );
3284 }
3285 assert_eq!(text, "Hello, kian");
3286 assert!(calls.is_empty());
3287 }
3288
3289 #[test]
3293 fn reasoning_fragments_are_persisted_and_replayed() {
3294 let mut text = String::new();
3295 let mut reasoning = String::new();
3296 let mut calls = Default::default();
3297 assemble_delta(
3298 &json!({"reasoning_content": "think "}),
3299 &mut text,
3300 &mut reasoning,
3301 &mut calls,
3302 );
3303 assemble_delta(
3304 &json!({"reasoning_content": "harder"}),
3305 &mut text,
3306 &mut reasoning,
3307 &mut calls,
3308 );
3309 assemble_delta(
3310 &json!({"content": "answer"}),
3311 &mut text,
3312 &mut reasoning,
3313 &mut calls,
3314 );
3315 assert_eq!(reasoning, "think harder");
3316 assert_eq!(text, "answer");
3317
3318 let with = to_chat_message(&msg(
3319 "assistant",
3320 json!({"text": text, "reasoning_content": reasoning}),
3321 ))
3322 .unwrap();
3323 assert_eq!(with.reasoning_content.as_deref(), Some("think harder"));
3324 let body = build_chat_body("m", &[with], &[]);
3325 assert_eq!(body["messages"][0]["reasoning_content"], "think harder");
3326
3327 let legacy = to_chat_message(&msg("assistant", json!({"text": "answer"}))).unwrap();
3328 assert!(legacy.reasoning_content.is_none());
3329 let body = build_chat_body("m", &[legacy], &[]);
3330 assert!(body["messages"][0].get("reasoning_content").is_none());
3331 }
3332
3333 #[test]
3334 fn delta_assembly_accumulates_tool_call_fragments_by_index() {
3335 let mut text = String::new();
3336 let mut reasoning = String::new();
3337 let mut calls = Default::default();
3338 assemble_delta(
3339 &serde_json::json!({"tool_calls": [
3340 {"index": 0, "id": "call-1", "function": {"name": "fs.read"}}
3341 ]}),
3342 &mut text,
3343 &mut reasoning,
3344 &mut calls,
3345 );
3346 assemble_delta(
3347 &serde_json::json!({"tool_calls": [
3348 {"index": 0, "function": {"arguments": "{\"pa"}}
3349 ]}),
3350 &mut text,
3351 &mut reasoning,
3352 &mut calls,
3353 );
3354 assemble_delta(
3355 &serde_json::json!({"tool_calls": [
3356 {"index": 0, "function": {"arguments": "th\": \"a.txt\"}"}}
3357 ]}),
3358 &mut text,
3359 &mut reasoning,
3360 &mut calls,
3361 );
3362 let finished: Vec<_> = calls.into_values().map(|c| c.finish()).collect();
3363 assert_eq!(finished.len(), 1);
3364 assert_eq!(finished[0].id, "call-1");
3365 assert_eq!(finished[0].name, "fs.read");
3366 assert_eq!(finished[0].arguments, serde_json::json!({"path": "a.txt"}));
3367 }
3368
3369 #[test]
3370 fn policy_consult_matches_rule_by_class() {
3371 use kian_core::seams::{PolicyRule, RecoveryAction, RecoveryPolicySource};
3372
3373 struct Table(Vec<PolicyRule>);
3374 impl RecoveryPolicySource for Table {
3375 fn table(&self) -> Vec<PolicyRule> {
3376 self.0.clone()
3377 }
3378 }
3379 let table = Table(vec![
3380 PolicyRule {
3381 class: "rate_limited".into(),
3382 action: RecoveryAction::BackoffRetry { delay_ms: 100 },
3383 },
3384 PolicyRule {
3385 class: CLASS_EMPTY_RESPONSE.into(),
3386 action: RecoveryAction::InterruptAsk,
3387 },
3388 ]);
3389 assert_eq!(
3390 consult_policy(&table, "rate_limited"),
3391 Some(RecoveryAction::BackoffRetry { delay_ms: 100 })
3392 );
3393 assert_eq!(
3394 consult_policy(&table, CLASS_EMPTY_RESPONSE),
3395 Some(RecoveryAction::InterruptAsk)
3396 );
3397 assert_eq!(consult_policy(&table, "no_such_class"), None);
3398 }
3399
3400 #[test]
3407 fn recovery_audit_carries_class_and_policy_action() {
3408 use kian_core::seams::{PolicyRule, RecoveryPolicySource};
3409 use kian_orchestrator::recovery::ErrorClass;
3410 use serde_json::json;
3411
3412 struct Table(Vec<PolicyRule>);
3413 impl RecoveryPolicySource for Table {
3414 fn table(&self) -> Vec<PolicyRule> {
3415 self.0.clone()
3416 }
3417 }
3418 let with_rule = Table(vec![PolicyRule {
3419 class: "store_failure".into(),
3420 action: kian_core::seams::RecoveryAction::Fail,
3421 }]);
3422 assert_eq!(
3423 super::recovery_audit(&with_rule, ErrorClass::StoreFailure),
3424 json!({"class": "store_failure", "action": "fail"})
3425 );
3426 assert_eq!(
3427 super::recovery_audit(&with_rule, ErrorClass::EmptyResponse),
3428 json!({"class": "empty_response", "action": "none"}),
3429 "no covering rule → the honest none spelling"
3430 );
3431
3432 assert_eq!(
3434 super::provider_error_class(&kian_core::seams::ProviderError::RateLimited),
3435 ErrorClass::RateLimited
3436 );
3437 assert_eq!(
3438 super::provider_error_class(&kian_core::seams::ProviderError::Unavailable(
3439 "upstream 503".into()
3440 )),
3441 ErrorClass::ProviderDown
3442 );
3443
3444 assert_eq!(
3446 super::loop_error_class(&super::LoopError::Engine(
3447 kian_orchestrator::EngineError::NotAtSafeBoundary {
3448 session: kian_core::model::SessionId::new(),
3449 }
3450 )),
3451 ErrorClass::StoreFailure
3452 );
3453 assert_eq!(
3454 super::loop_error_class(&super::LoopError::Slot(
3455 kian_llm::slots::SlotError::UnknownSlot("aux".into())
3456 )),
3457 ErrorClass::Unknown
3458 );
3459 }
3460
3461 #[test]
3462 fn the_default_budget_admits_the_newest_references_in_the_tail() {
3463 let budget = super::VisionBudget::default();
3464 let tail = vec![vec![10], vec![10], vec![10], vec![10], vec![10], vec![10]];
3465 let (per_message, admitted, dropped) = super::select_tail_images(budget, &tail);
3466 assert_eq!(per_message, vec![0, 0, 1, 1, 1, 1], "newest four win");
3467 assert_eq!(admitted, 4);
3468 assert_eq!(dropped, 2);
3469 assert_eq!(
3470 super::select_tail_images(budget, &tail),
3471 (vec![0, 0, 1, 1, 1, 1], 4, 2),
3472 "a retry of the same stream selects the same images"
3473 );
3474 }
3475
3476 #[test]
3477 fn the_byte_budget_stops_at_the_first_reference_that_would_exceed_it() {
3478 let budget = super::VisionBudget {
3479 max_images_per_turn: 8,
3480 max_image_bytes_per_turn: 4,
3481 };
3482 let tail = vec![vec![3], vec![3]];
3483 let (per_message, admitted, dropped) = super::select_tail_images(budget, &tail);
3484 assert_eq!(
3485 per_message,
3486 vec![0, 1],
3487 "the newest 3 bytes fit, the next 3 do not"
3488 );
3489 assert_eq!(admitted, 1);
3490 assert_eq!(dropped, 1);
3491 }
3492
3493 #[test]
3494 fn a_message_still_keeps_at_most_four_references() {
3495 let budget = super::VisionBudget {
3496 max_images_per_turn: 32,
3497 max_image_bytes_per_turn: u64::MAX,
3498 };
3499 let tail = vec![vec![1, 1, 1, 1, 1, 1]];
3500 let (per_message, admitted, dropped) = super::select_tail_images(budget, &tail);
3501 assert_eq!(per_message, vec![4], "the ceiling admits a suffix of four");
3502 assert_eq!(admitted, 4);
3503 assert_eq!(dropped, 2);
3504 }
3505
3506 #[test]
3507 fn a_tail_within_both_limits_keeps_every_reference() {
3508 let budget = super::VisionBudget::default();
3509 let tail = vec![vec![1, 1], vec![1]];
3510 let (per_message, admitted, dropped) = super::select_tail_images(budget, &tail);
3511 assert_eq!(per_message, vec![2, 1]);
3512 assert_eq!(admitted, 3);
3513 assert_eq!(dropped, 0);
3514 }
3515
3516 #[test]
3517 fn react_config_defaults_are_sane() {
3518 let cfg = ReActConfig::default();
3519 assert_eq!(cfg.slot.0, "main");
3520 assert!(cfg.max_iterations >= 1);
3521 let react = ReActLoop::new(
3523 agent_def(),
3524 std::sync::Arc::new(kian_llm::ProviderRegistry::new()),
3525 std::sync::Arc::new(NoopTools),
3526 std::sync::Arc::new(NoopPolicy),
3527 );
3528 assert_eq!(react.config().slot.0, "main");
3529 }
3530}