@@ -29,8 +29,8 @@ use filter::SubscriptionRule;
2929use futures_util:: FutureExt ;
3030use nostr:: { PublicKey , ToBech32 } ;
3131use pool:: {
32- AgentPool , ControlSignal , OwnedAgent , PromptContext , PromptOutcome , PromptResult , PromptSource ,
33- SessionState ,
32+ AgentPool , ControlSignal , IdleSwitchResult , OwnedAgent , PromptContext , PromptOutcome ,
33+ PromptResult , PromptSource , SessionState ,
3434} ;
3535use queue:: { CancelReason , EventQueue , QueuedEvent , ThreadTags } ;
3636use relay:: { HarnessRelay , RelayEventPublisher } ;
@@ -710,11 +710,25 @@ fn handle_relay_observer_control_event(
710710 } ;
711711
712712 let command_type = payload. get ( "type" ) . and_then ( |value| value. as_str ( ) ) ;
713- if command_type != Some ( "cancel_turn" ) {
714- tracing:: debug!( payload = %payload, "ignoring unknown observer control frame" ) ;
715- return ;
713+ match command_type {
714+ Some ( "cancel_turn" ) => {
715+ handle_cancel_turn_control ( & payload, pool, observer) ;
716+ }
717+ Some ( "switch_model" ) => {
718+ handle_switch_model_control ( & payload, pool, observer) ;
719+ }
720+ _ => {
721+ tracing:: debug!( payload = %payload, "ignoring unknown observer control frame" ) ;
722+ }
716723 }
724+ }
717725
726+ /// Handle a `cancel_turn` control frame: signal the in-flight task to cancel.
727+ fn handle_cancel_turn_control (
728+ payload : & serde_json:: Value ,
729+ pool : & mut AgentPool ,
730+ observer : Option < & observer:: ObserverHandle > ,
731+ ) {
718732 let Some ( channel_id) = payload
719733 . get ( "channelId" )
720734 . and_then ( |value| value. as_str ( ) )
@@ -743,6 +757,83 @@ fn handle_relay_observer_control_event(
743757 }
744758}
745759
760+ /// Handle a `switch_model` control frame (Phase 3a, Option ii).
761+ ///
762+ /// Busy path: deliver `SwitchModel` over the in-flight task's oneshot — the
763+ /// task cancels the turn, sets `desired_model`, and requeues the batch so it
764+ /// re-runs on a fresh session under the new model. A catalog miss surfaces
765+ /// post-cancel via `create_session_and_apply_model` (the turn restarts on the
766+ /// unchanged model + an `unsupported_model` result).
767+ ///
768+ /// Idle path: validate against the cached catalog *before* invalidating
769+ /// (pre-cancel guard), then set `desired_model` + invalidate. The override
770+ /// takes visible effect on the agent's next turn.
771+ fn handle_switch_model_control (
772+ payload : & serde_json:: Value ,
773+ pool : & mut AgentPool ,
774+ observer : Option < & observer:: ObserverHandle > ,
775+ ) {
776+ let Some ( channel_id) = payload
777+ . get ( "channelId" )
778+ . and_then ( |value| value. as_str ( ) )
779+ . and_then ( |value| value. parse :: < Uuid > ( ) . ok ( ) )
780+ else {
781+ tracing:: warn!( "observer switch_model control frame missing valid channelId" ) ;
782+ return ;
783+ } ;
784+ let Some ( model_id) = payload. get ( "modelId" ) . and_then ( |value| value. as_str ( ) ) else {
785+ tracing:: warn!( "observer switch_model control frame missing modelId" ) ;
786+ return ;
787+ } ;
788+
789+ // A turn is in flight for this channel iff a task_map entry exists. The
790+ // agent is moved out of the pool during a turn, so the control oneshot is
791+ // the only reachable lever; an idle channel has no such entry.
792+ let turn_in_flight = pool
793+ . task_map ( )
794+ . values ( )
795+ . any ( |m| m. channel_id == Some ( channel_id) ) ;
796+
797+ let status = if turn_in_flight {
798+ // Busy path: deliver over the oneshot. `false` means the oneshot was
799+ // already consumed this turn (a prior cancel/interrupt) — the turn is
800+ // already ending, so the switch cannot land on it.
801+ if signal_in_flight_task (
802+ pool,
803+ channel_id,
804+ ControlSignal :: SwitchModel ( model_id. to_string ( ) ) ,
805+ ) {
806+ "sent"
807+ } else {
808+ "turn_ending"
809+ }
810+ } else {
811+ // Idle path: validate against the cached catalog before invalidating.
812+ match pool. switch_idle_agent_model ( channel_id, model_id) {
813+ IdleSwitchResult :: Switched => "switched" ,
814+ IdleSwitchResult :: UnsupportedModel => "unsupported_model" ,
815+ IdleSwitchResult :: NoIdleAgent => "no_active_turn" ,
816+ }
817+ } ;
818+
819+ if let Some ( observer) = observer {
820+ observer. emit (
821+ "control_result" ,
822+ None ,
823+ & observer:: ObserverContext {
824+ channel_id : Some ( channel_id. to_string ( ) ) ,
825+ session_id : None ,
826+ turn_id : None ,
827+ } ,
828+ serde_json:: json!( {
829+ "type" : "switch_model" ,
830+ "status" : status,
831+ "modelId" : model_id,
832+ } ) ,
833+ ) ;
834+ }
835+ }
836+
746837/// Maximum crashes in a 60-second window before a slot's circuit opens.
747838const CIRCUIT_BREAKER_THRESHOLD : usize = 3 ;
748839/// Window for circuit-breaker crash counting.
@@ -1068,6 +1159,7 @@ async fn tokio_main() -> Result<()> {
10681159 state : SessionState :: default ( ) ,
10691160 model_capabilities : None ,
10701161 desired_model : config. model . clone ( ) ,
1162+ model_overridden : false ,
10711163 protocol_version,
10721164 } ) ) ;
10731165 }
@@ -1502,6 +1594,7 @@ async fn tokio_main() -> Result<()> {
15021594 state : SessionState :: default ( ) ,
15031595 model_capabilities : None ,
15041596 desired_model : config. model . clone ( ) ,
1597+ model_overridden : false ,
15051598 protocol_version,
15061599 } ;
15071600 pool. return_agent ( agent) ;
@@ -2351,8 +2444,8 @@ fn signal_in_flight_task(
23512444
23522445 if let Some ( meta) = entry {
23532446 if let Some ( tx) = meta. control_tx . take ( ) {
2354- let _ = tx. send ( mode) ;
23552447 tracing:: info!( channel = %channel_id, ?mode, "control signal sent to in-flight task" ) ;
2448+ let _ = tx. send ( mode) ;
23562449 return true ;
23572450 }
23582451 }
@@ -3867,6 +3960,7 @@ mod error_outcome_emission_tests {
38673960 state : Default :: default ( ) ,
38683961 model_capabilities : None ,
38693962 desired_model : None ,
3963+ model_overridden : false ,
38703964 // Error branches under test never read this; 1 is the legacy
38713965 // non-systemPrompt path, the simplest valid value.
38723966 protocol_version : 1 ,
0 commit comments