Skip to main content

everruns_runtime/
host.rs

1// Shared host orchestration for embedded and durable execution hosts.
2// Decision: everruns-runtime owns worker-facing turn phase execution so
3// durable/server-backed hosts reuse the same input/reason/act wiring.
4
5use async_trait::async_trait;
6use everruns_core::atoms::{
7    ActAtom, ActInput, ActResult, Atom, InputAtom, InputAtomInput, InputAtomResult, ReasonAtom,
8    ReasonInput, ReasonResult,
9};
10use everruns_core::capabilities::{SystemPromptContext, collect_capabilities_with_configs};
11use everruns_core::events::{
12    EventContext, EventRequest, OutputMessageCompletedData, SessionActivatedData, SessionIdledData,
13    TurnCompletedData, TurnFailedData, TurnStartedData,
14};
15use everruns_core::message::Message;
16use everruns_core::message_retriever::MessageRetriever;
17use everruns_core::platform_store::PlatformStore;
18use everruns_core::session::SessionStatus;
19use everruns_core::traits::{
20    AgentStore, BudgetChecker, EventEmitter, HarnessStore, ImageArtifactStore, ImageResolver,
21    LeasedResourceStore, LlmProviderStore, ModelWithProvider, PaymentAuthority,
22    ProviderCredentialStore, SessionFileSystem, SessionMutator, SessionResourceRegistry,
23    SessionScheduleStore, SessionSqlDbStoreRef, SessionStorageStore, SessionStore,
24    UserConnectionResolver,
25};
26use everruns_core::typed_id::{AgentId, HarnessId, MessageId, SessionId, TurnId};
27use everruns_core::{
28    Agent, CapabilityRegistry, DependencyBlocker, DriverRegistry, EgressService, Harness, Session,
29    TokenUsage, ToolDefinition, ToolRegistry, UserFacingError, UtilityLlmService,
30    org_public_id_from_internal, resolve_runtime_capabilities,
31};
32use std::sync::Arc;
33use tracing::warn;
34
35/// Turn context loaded in one batched call for runtime host execution.
36#[derive(Debug, Clone)]
37pub struct RuntimeHostTurnContext {
38    pub agent: Option<Agent>,
39    pub session: Session,
40    pub messages: Vec<Message>,
41    pub model: Option<ModelWithProvider>,
42    pub mcp_tool_definitions: Vec<ToolDefinition>,
43}
44
45/// Public adapter contract for server-backed or durable runtime hosts.
46///
47/// `everruns-runtime` owns shared host orchestration for both embedded and
48/// durable execution. That includes phase execution (`input -> reason -> act`),
49/// lifecycle emission, and the generic turn-strategy decisions used by durable
50/// or custom hosts.
51///
52/// Host crates implement this trait to provide persistence, session-lifecycle
53/// plumbing, event delivery, and their own orchestration backend. The durable
54/// engine itself remains outside this crate.
55#[async_trait]
56pub trait RuntimeHostAdapter: Send + Sync + Clone + 'static {
57    async fn get_agent(
58        &self,
59        org_id: i64,
60        agent_id: AgentId,
61    ) -> everruns_core::error::Result<Option<Agent>>;
62
63    async fn get_harness(
64        &self,
65        org_id: i64,
66        harness_id: HarnessId,
67    ) -> everruns_core::error::Result<Option<Harness>>;
68
69    async fn set_session_status(
70        &self,
71        org_id: i64,
72        session_id: SessionId,
73        status: SessionStatus,
74    ) -> everruns_core::error::Result<Session>;
75
76    async fn load_turn_context(
77        &self,
78        org_id: i64,
79        session_id: SessionId,
80    ) -> everruns_core::error::Result<RuntimeHostTurnContext>;
81
82    fn capability_registry(&self) -> CapabilityRegistry;
83
84    fn driver_registry(&self) -> DriverRegistry;
85
86    fn harness_store(&self, org_id: i64) -> Arc<dyn HarnessStore>;
87
88    fn agent_store(&self, org_id: i64) -> Arc<dyn AgentStore>;
89
90    fn session_store(&self, org_id: i64) -> Arc<dyn SessionStore>;
91
92    fn session_mutator(&self, org_id: i64) -> Arc<dyn SessionMutator>;
93
94    fn provider_store(&self, org_id: i64) -> Arc<dyn LlmProviderStore>;
95
96    fn message_store(&self) -> Arc<dyn MessageRetriever>;
97
98    fn event_emitter(&self) -> Arc<dyn EventEmitter>;
99
100    fn file_store(&self) -> Arc<dyn SessionFileSystem>;
101
102    fn image_resolver(&self, _org_id: i64) -> Option<Arc<dyn ImageResolver>> {
103        None
104    }
105
106    fn image_artifact_store(&self, _org_id: i64) -> Option<Arc<dyn ImageArtifactStore>> {
107        None
108    }
109
110    fn provider_credential_store(&self, _org_id: i64) -> Option<Arc<dyn ProviderCredentialStore>> {
111        None
112    }
113
114    fn utility_llm_service(&self) -> Option<Arc<dyn UtilityLlmService>> {
115        None
116    }
117
118    fn egress_service(&self) -> Option<Arc<dyn EgressService>> {
119        None
120    }
121
122    fn storage_store(&self) -> Option<Arc<dyn SessionStorageStore>> {
123        None
124    }
125
126    fn memory_store(&self, _org_id: i64) -> Option<Arc<dyn everruns_core::MemoryStoreBackend>> {
127        None
128    }
129
130    fn connection_resolver(&self) -> Option<Arc<dyn UserConnectionResolver>> {
131        None
132    }
133
134    fn sqldb_store(&self) -> Option<SessionSqlDbStoreRef> {
135        None
136    }
137
138    fn leased_resource_store(&self) -> Option<Arc<dyn LeasedResourceStore>> {
139        None
140    }
141
142    fn session_resource_registry(&self) -> Option<Arc<dyn SessionResourceRegistry>> {
143        None
144    }
145
146    fn schedule_store(&self, _org_id: i64) -> Option<Arc<dyn SessionScheduleStore>> {
147        None
148    }
149
150    fn platform_store(
151        &self,
152        _org_id: i64,
153        _session_id: SessionId,
154    ) -> Option<Arc<dyn PlatformStore>> {
155        None
156    }
157
158    fn budget_checker(
159        &self,
160        _org_id: i64,
161        _agent_id: Option<AgentId>,
162    ) -> Option<Arc<dyn BudgetChecker>> {
163        None
164    }
165
166    fn payment_authority(
167        &self,
168        _org_id: i64,
169        _agent_id: Option<AgentId>,
170    ) -> Option<Arc<dyn PaymentAuthority>> {
171        None
172    }
173
174    /// Per-org outbound tool-call rate limiter (TM-TOOL-009).
175    /// Default: `None` (no rate limiting — suitable for in-process / test environments).
176    fn outbound_tool_rate_limiter(
177        &self,
178        _org_id: i64,
179    ) -> Option<Arc<dyn everruns_core::OutboundToolRateLimiter>> {
180        None
181    }
182
183    /// MCP executor routing `mcp_*` tool calls for this session, if the host
184    /// configures MCP (specs/runtime-mcp.md D4). Default: `None`, so hosts
185    /// without scoped MCP servers keep the plain tool registry unchanged.
186    async fn mcp_executor(
187        &self,
188        _org_id: i64,
189        _session_id: SessionId,
190    ) -> Option<Arc<everruns_mcp::McpExecutor>> {
191        None
192    }
193}
194
195struct RuntimeExecutionCapabilities {
196    tool_registry: ToolRegistry,
197    post_tool_hooks: Vec<Arc<dyn everruns_core::PostToolExecHook>>,
198    pre_tool_hooks: Vec<Arc<dyn everruns_core::atoms::PreToolUseHook>>,
199    tool_call_hooks: Vec<Arc<dyn everruns_core::ToolCallHook>>,
200}
201
202/// Collect and finalize user-hook specs for a session from its resolved
203/// capability configs, plus the shared bash dispatcher used to run them.
204///
205/// This is the single place hook specs are gathered so every firing point —
206/// the act path (`load_execution_capabilities`) and the lifecycle firing
207/// points (`execute_reason_activity` for `user_prompt_submit`, turn completion
208/// for `turn_end`, and the server session paths) — applies identical
209/// `finalize_hook_specs` semantics: `{capability_id}:` namespace stamping,
210/// stable default ids, and `disabled_contributions` muting (TM-HOOK-004).
211fn finalize_specs_from_configs(
212    resolved_capability_configs: &[everruns_core::capability_types::AgentCapabilityConfig],
213    capability_registry: &CapabilityRegistry,
214) -> Vec<everruns_core::user_hook_types::UserHookSpec> {
215    let mut hook_contributions: Vec<(String, Vec<everruns_core::user_hook_types::UserHookSpec>)> =
216        Vec::new();
217    let mut disabled_contributions: Vec<String> = Vec::new();
218    for config in resolved_capability_configs {
219        let Some(capability) = capability_registry.get(config.capability_id()) else {
220            continue;
221        };
222        let specs = capability.user_hooks_with_config(&config.config);
223        if !specs.is_empty() {
224            hook_contributions.push((config.capability_id().to_string(), specs));
225        }
226        if config.capability_id() == "user_hooks" {
227            disabled_contributions.extend(
228                everruns_core::capabilities::user_hooks::disabled_contributions(&config.config),
229            );
230        }
231    }
232    everruns_core::hook_adapter::finalize_hook_specs(hook_contributions, &disabled_contributions)
233}
234
235/// Resolve a session's capability configs and collect finalized hook specs.
236/// Used by the lifecycle firing points, which need specs outside the act path.
237/// Returns `(specs, dispatcher)`; `specs` is empty when the session has no
238/// hook-contributing capabilities.
239async fn collect_lifecycle_hook_specs<A: RuntimeHostAdapter>(
240    adapter: &A,
241    org_id: i64,
242    session_id: SessionId,
243    harness_id: HarnessId,
244    agent_id: Option<AgentId>,
245) -> everruns_core::error::Result<(
246    Vec<everruns_core::user_hook_types::UserHookSpec>,
247    Arc<dyn everruns_core::hook_executor::BashHookDispatcher>,
248)> {
249    let capability_registry = adapter.capability_registry();
250    let harness_chain = adapter
251        .harness_store(org_id)
252        .get_harness_chain(harness_id)
253        .await?;
254    if harness_chain.is_empty() {
255        return Err(everruns_core::error::AgentLoopError::harness_not_found(
256            harness_id,
257        ));
258    }
259    let session = adapter
260        .session_store(org_id)
261        .get_session(session_id)
262        .await?
263        .ok_or_else(|| everruns_core::error::AgentLoopError::session_not_found(session_id))?;
264    let agent = match agent_id {
265        Some(agent_id) => adapter.agent_store(org_id).get_agent(agent_id).await?,
266        None => None,
267    };
268    let resolved = resolve_runtime_capabilities(
269        &harness_chain,
270        agent.as_ref(),
271        &session,
272        &capability_registry,
273    );
274    let specs =
275        finalize_specs_from_configs(&resolved.resolved_capability_configs, &capability_registry);
276    let dispatcher: Arc<dyn everruns_core::hook_executor::BashHookDispatcher> = Arc::new(
277        everruns_core::hook_dispatch::VirtualBashHookDispatcher::new(adapter.file_store()),
278    );
279    Ok((specs, dispatcher))
280}
281
282async fn load_execution_capabilities<A: RuntimeHostAdapter>(
283    adapter: &A,
284    org_id: i64,
285    session_id: SessionId,
286    harness_id: HarnessId,
287    agent_id: Option<AgentId>,
288    locale: Option<String>,
289    blueprint_id: Option<&str>,
290) -> everruns_core::error::Result<RuntimeExecutionCapabilities> {
291    let capability_registry = adapter.capability_registry();
292    if let Some(blueprint_id) = blueprint_id {
293        let mut registry = ToolRegistry::with_defaults();
294        let blueprint = capability_registry.blueprint(blueprint_id).ok_or_else(|| {
295            everruns_core::error::AgentLoopError::config(format!(
296                "Blueprint \"{blueprint_id}\" not found in registry"
297            ))
298        })?;
299        for tool in blueprint.tools {
300            registry.register_boxed(tool);
301        }
302        return Ok(RuntimeExecutionCapabilities {
303            tool_registry: registry,
304            post_tool_hooks: Vec::new(),
305            pre_tool_hooks: Vec::new(),
306            tool_call_hooks: Vec::new(),
307        });
308    }
309
310    let harness_chain = adapter
311        .harness_store(org_id)
312        .get_harness_chain(harness_id)
313        .await?;
314    if harness_chain.is_empty() {
315        return Err(everruns_core::error::AgentLoopError::harness_not_found(
316            harness_id,
317        ));
318    }
319
320    let session = adapter
321        .session_store(org_id)
322        .get_session(session_id)
323        .await?
324        .ok_or_else(|| everruns_core::error::AgentLoopError::session_not_found(session_id))?;
325
326    let agent_store = adapter.agent_store(org_id);
327    let agent = match agent_id {
328        Some(agent_id) => Some(
329            agent_store
330                .get_agent(agent_id)
331                .await?
332                .ok_or_else(|| everruns_core::error::AgentLoopError::agent_not_found(agent_id))?,
333        ),
334        None => None,
335    };
336
337    let resolved = resolve_runtime_capabilities(
338        &harness_chain,
339        agent.as_ref(),
340        &session,
341        &capability_registry,
342    );
343    let prompt_ctx = SystemPromptContext {
344        session_id,
345        locale: locale.or(session.locale.clone()),
346        file_store: Some(adapter.file_store()),
347    };
348    let collected = collect_capabilities_with_configs(
349        &resolved.resolved_capability_configs,
350        &capability_registry,
351        &prompt_ctx,
352    )
353    .await;
354
355    let mut registry = ToolRegistry::with_defaults();
356    for tool in collected.tools {
357        registry.register_boxed(tool);
358    }
359
360    let mut post_tool_hooks: Vec<Arc<dyn everruns_core::PostToolExecHook>> = resolved
361        .resolved_capability_configs
362        .iter()
363        .flat_map(|config| {
364            capability_registry
365                .get(config.capability_id())
366                .map(|capability| capability.post_tool_exec_hooks())
367                .unwrap_or_default()
368        })
369        .collect();
370
371    // User-hook contributions (see `specs/user-hooks.md`). `finalize_specs_from_configs`
372    // gathers specs across every resolved capability — both the user-facing
373    // `user_hooks` capability and any capability that bundles hooks — and applies
374    // `finalize_hook_specs` (namespace stamping, stable ids, `disabled_contributions`
375    // muting; TM-HOOK-004). The same helper backs the lifecycle firing points so
376    // every event finalizes specs identically.
377    let user_hook_specs =
378        finalize_specs_from_configs(&resolved.resolved_capability_configs, &capability_registry);
379    let mut pre_tool_hooks: Vec<Arc<dyn everruns_core::atoms::PreToolUseHook>> = Vec::new();
380    if !user_hook_specs.is_empty() {
381        let dispatcher: Arc<dyn everruns_core::hook_executor::BashHookDispatcher> = Arc::new(
382            everruns_core::hook_dispatch::VirtualBashHookDispatcher::new(adapter.file_store()),
383        );
384        post_tool_hooks.extend(everruns_core::hook_adapter::build_post_tool_use_hooks(
385            &user_hook_specs,
386            dispatcher.clone(),
387        ));
388        pre_tool_hooks.extend(everruns_core::hook_adapter::build_pre_tool_use_hooks(
389            &user_hook_specs,
390            dispatcher,
391        ));
392    }
393
394    let tool_call_hooks = resolved
395        .resolved_capability_configs
396        .iter()
397        .flat_map(|config| {
398            capability_registry
399                .get(config.capability_id())
400                .map(|capability| capability.tool_call_hooks())
401                .unwrap_or_default()
402        })
403        .collect();
404
405    Ok(RuntimeExecutionCapabilities {
406        tool_registry: registry,
407        post_tool_hooks,
408        pre_tool_hooks,
409        tool_call_hooks,
410    })
411}
412
413/// Shared lifecycle helper for runtime-backed hosts.
414pub struct RuntimeSessionLifecycle<A: RuntimeHostAdapter> {
415    adapter: A,
416    org_id: i64,
417    session_id: SessionId,
418}
419
420impl<A: RuntimeHostAdapter> RuntimeSessionLifecycle<A> {
421    pub fn new(adapter: A, org_id: i64, session_id: SessionId) -> Self {
422        Self {
423            adapter,
424            org_id,
425            session_id,
426        }
427    }
428
429    async fn set_session_status(&self, status: SessionStatus, action: &'static str) {
430        if let Err(error) = self
431            .adapter
432            .set_session_status(self.org_id, self.session_id, status)
433            .await
434        {
435            warn!(
436                session_id = %self.session_id,
437                org_id = self.org_id,
438                action,
439                %error,
440                "runtime host lifecycle status update failed"
441            );
442        }
443    }
444
445    async fn emit_event(&self, request: EventRequest) {
446        let event_type = request.event_type.clone();
447        if let Err(error) = self.adapter.event_emitter().emit(request).await {
448            warn!(
449                session_id = %self.session_id,
450                org_id = self.org_id,
451                event_type,
452                %error,
453                "runtime host lifecycle event emission failed"
454            );
455        }
456    }
457
458    pub async fn turn_started(&self, turn_id: TurnId, input_message_id: MessageId) {
459        let input_content = self
460            .adapter
461            .message_store()
462            .get(self.session_id, input_message_id)
463            .await
464            .ok()
465            .flatten()
466            .map(|message| message.content_to_llm_string());
467
468        self.set_session_status(SessionStatus::Active, "turn_started")
469            .await;
470
471        self.emit_event(EventRequest::new(
472            self.session_id,
473            EventContext::turn(turn_id, input_message_id),
474            SessionActivatedData {
475                turn_id,
476                input_message_id,
477            },
478        ))
479        .await;
480
481        self.emit_event(EventRequest::new(
482            self.session_id,
483            EventContext::turn(turn_id, input_message_id),
484            TurnStartedData {
485                turn_id,
486                input_message_id,
487                input_content,
488            },
489        ))
490        .await;
491    }
492
493    pub async fn emit_turn_completed(&self, input_message_id: MessageId, data: TurnCompletedData) {
494        let turn_id = data.turn_id;
495        self.emit_event(EventRequest::new(
496            self.session_id,
497            EventContext::turn(turn_id, input_message_id),
498            data,
499        ))
500        .await;
501    }
502
503    pub async fn emit_session_idled(
504        &self,
505        turn_id: TurnId,
506        input_message_id: MessageId,
507        iterations: Option<u32>,
508        usage: Option<TokenUsage>,
509    ) {
510        self.set_session_status(SessionStatus::Idle, "emit_session_idled")
511            .await;
512
513        self.emit_event(EventRequest::new(
514            self.session_id,
515            EventContext::turn(turn_id, input_message_id),
516            SessionIdledData {
517                turn_id,
518                iterations,
519                usage,
520            },
521        ))
522        .await;
523    }
524
525    pub async fn turn_completed(
526        &self,
527        turn_id: TurnId,
528        input_message_id: MessageId,
529        iterations: u32,
530        usage: Option<TokenUsage>,
531        input_content: Option<String>,
532    ) {
533        self.emit_turn_completed(
534            input_message_id,
535            TurnCompletedData {
536                turn_id,
537                iterations,
538                duration_ms: None,
539                usage: usage.clone(),
540                input_content,
541                final_message_id: None,
542                final_answer_preview: None,
543                time_to_first_token_ms: None,
544                tool_call_count: None,
545                llm_call_count: None,
546                status: Some("completed".to_string()),
547            },
548        )
549        .await;
550        self.emit_session_idled(turn_id, input_message_id, Some(iterations), usage)
551            .await;
552    }
553
554    /// Fire `turn_end` lifecycle hooks (advisory). Collects the session's hook
555    /// specs and runs every `turn_end` hook; failures are logged, never fatal.
556    /// `harness_id`/`agent_id` are required to resolve the capability chain.
557    pub async fn fire_turn_end_hooks(
558        &self,
559        harness_id: HarnessId,
560        agent_id: Option<AgentId>,
561        turn_id: TurnId,
562        success: bool,
563    ) {
564        let (specs, dispatcher) = match collect_lifecycle_hook_specs(
565            &self.adapter,
566            self.org_id,
567            self.session_id,
568            harness_id,
569            agent_id,
570        )
571        .await
572        {
573            Ok(pair) => pair,
574            Err(error) => {
575                warn!(
576                    session_id = %self.session_id,
577                    %error,
578                    "failed to collect turn_end hook specs; skipping"
579                );
580                return;
581            }
582        };
583        let hooks = everruns_core::lifecycle_hooks::build_turn_lifecycle_hooks(
584            &specs,
585            everruns_core::user_hook_types::HookEvent::TurnEnd,
586            dispatcher,
587        );
588        if hooks.is_empty() {
589            return;
590        }
591        let ctx = everruns_core::lifecycle_hooks::TurnHookContext {
592            session_id: self.session_id,
593            turn_id: Some(turn_id),
594            org_id: org_public_id_from_internal(self.org_id).parse().ok(),
595            agent_id: agent_id.map(|a| a.to_string()),
596        };
597        everruns_core::lifecycle_hooks::run_turn_end_hooks(
598            &hooks,
599            &ctx,
600            serde_json::json!({ "success": success }),
601        )
602        .await;
603    }
604
605    /// Abort a turn because a `user_prompt_submit` hook returned `Block`.
606    /// Reuses the dependency-blocked failure shape: emit a user-facing message
607    /// carrying the hook's `user_message` (or `reason`), then mark the turn
608    /// failed and idle the session.
609    pub async fn user_prompt_blocked(
610        &self,
611        turn_id: TurnId,
612        input_message_id: MessageId,
613        reason: &str,
614        user_message: Option<&str>,
615    ) {
616        let user_error =
617            UserFacingError::new(everruns_core::user_facing_error_codes::BLOCKED_BY_HOOK);
618        let shown = user_message.unwrap_or(reason);
619        let mut error_message = Message::assistant(shown);
620        let mut metadata = std::collections::HashMap::new();
621        user_error.apply_to_message_metadata(&mut metadata);
622        error_message.metadata = Some(metadata);
623
624        self.emit_event(EventRequest::new(
625            self.session_id,
626            EventContext::turn(turn_id, input_message_id),
627            OutputMessageCompletedData::new(error_message).with_user_facing_error(&user_error),
628        ))
629        .await;
630
631        self.turn_failed(turn_id, input_message_id, reason, Some(&user_error))
632            .await;
633    }
634
635    pub async fn turn_failed(
636        &self,
637        turn_id: TurnId,
638        input_message_id: MessageId,
639        error: &str,
640        user_error: Option<&UserFacingError>,
641    ) {
642        self.set_session_status(SessionStatus::Idle, "turn_failed")
643            .await;
644
645        self.emit_event(EventRequest::new(
646            self.session_id,
647            EventContext::turn(turn_id, input_message_id),
648            {
649                let mut data = TurnFailedData {
650                    turn_id,
651                    error: error.to_string(),
652                    error_code: None,
653                    error_fields: None,
654                };
655                if let Some(user_error) = user_error {
656                    user_error.apply_to_event_fields(&mut data.error_code, &mut data.error_fields);
657                }
658                data
659            },
660        ))
661        .await;
662
663        self.emit_event(EventRequest::new(
664            self.session_id,
665            EventContext::turn(turn_id, input_message_id),
666            SessionIdledData {
667                turn_id,
668                iterations: None,
669                usage: None,
670            },
671        ))
672        .await;
673    }
674
675    pub async fn waiting_for_tool_results(&self) {
676        self.set_session_status(
677            SessionStatus::WaitingForToolResults,
678            "waiting_for_tool_results",
679        )
680        .await;
681    }
682
683    pub async fn dependency_blocked(
684        &self,
685        turn_id: TurnId,
686        input_message_id: MessageId,
687        blocker: DependencyBlocker,
688    ) {
689        let user_error = UserFacingError::new(blocker.error_code())
690            .with_field(
691                "dependency",
692                match blocker {
693                    DependencyBlocker::HarnessArchived | DependencyBlocker::HarnessDeleted => {
694                        "harness"
695                    }
696                    DependencyBlocker::AgentArchived | DependencyBlocker::AgentDeleted => "agent",
697                },
698            )
699            .with_field(
700                "state",
701                match blocker {
702                    DependencyBlocker::HarnessArchived | DependencyBlocker::AgentArchived => {
703                        "archived"
704                    }
705                    DependencyBlocker::HarnessDeleted | DependencyBlocker::AgentDeleted => {
706                        "deleted"
707                    }
708                },
709            );
710        let mut error_message = Message::assistant(blocker.message());
711        let mut metadata = std::collections::HashMap::new();
712        user_error.apply_to_message_metadata(&mut metadata);
713        error_message.metadata = Some(metadata);
714
715        self.emit_event(EventRequest::new(
716            self.session_id,
717            EventContext::turn(turn_id, input_message_id),
718            OutputMessageCompletedData::new(error_message).with_user_facing_error(&user_error),
719        ))
720        .await;
721
722        self.turn_failed(
723            turn_id,
724            input_message_id,
725            blocker.message(),
726            Some(&user_error),
727        )
728        .await;
729    }
730}
731
732pub async fn detect_dependency_blocker<A: RuntimeHostAdapter>(
733    adapter: &A,
734    org_id: i64,
735    harness_id: HarnessId,
736    agent_id: Option<AgentId>,
737) -> everruns_core::error::Result<Option<DependencyBlocker>> {
738    let harness_store = adapter.harness_store(org_id);
739    let agent_store = adapter.agent_store(org_id);
740    everruns_core::detect_dependency_blocker(
741        harness_store.as_ref(),
742        agent_store.as_ref(),
743        harness_id,
744        agent_id,
745    )
746    .await
747}
748
749pub async fn execute_input_activity<A: RuntimeHostAdapter>(
750    adapter: &A,
751    org_id: i64,
752    input: InputAtomInput,
753) -> everruns_core::error::Result<InputAtomResult> {
754    RuntimeSessionLifecycle::new(adapter.clone(), org_id, input.context.session_id)
755        .turn_started(input.context.turn_id, input.context.input_message_id)
756        .await;
757
758    let atom = InputAtom::new(adapter.message_store());
759    atom.execute(input).await
760}
761
762/// Collect `user_prompt_submit` hooks for this turn and run them against the
763/// inbound user message text. Returns `None` when the session has no such
764/// hooks (the common case — no overhead beyond the spec collection, which is
765/// skipped early). Errors loading specs are logged and treated as "no hooks"
766/// so a hook-collection failure never blocks a turn that wasn't asking to be
767/// hooked.
768async fn run_user_prompt_submit_for_turn<A: RuntimeHostAdapter>(
769    adapter: &A,
770    org_id: i64,
771    input: &ReasonInput,
772) -> everruns_core::error::Result<Option<everruns_core::lifecycle_hooks::UserPromptDecision>> {
773    let (specs, dispatcher) = match collect_lifecycle_hook_specs(
774        adapter,
775        org_id,
776        input.context.session_id,
777        input.harness_id,
778        input.agent_id,
779    )
780    .await
781    {
782        Ok(pair) => pair,
783        Err(error) => {
784            warn!(
785                session_id = %input.context.session_id,
786                %error,
787                "failed to collect user_prompt_submit hook specs; continuing without them"
788            );
789            return Ok(None);
790        }
791    };
792    let hooks = everruns_core::lifecycle_hooks::build_turn_lifecycle_hooks(
793        &specs,
794        everruns_core::user_hook_types::HookEvent::UserPromptSubmit,
795        dispatcher,
796    );
797    if hooks.is_empty() {
798        return Ok(None);
799    }
800
801    let message_text = adapter
802        .message_store()
803        .get(input.context.session_id, input.context.input_message_id)
804        .await
805        .ok()
806        .flatten()
807        .map(|m| m.content_to_llm_string())
808        .unwrap_or_default();
809
810    let ctx = everruns_core::lifecycle_hooks::TurnHookContext {
811        session_id: input.context.session_id,
812        turn_id: Some(input.context.turn_id),
813        org_id: org_public_id_from_internal(org_id).parse().ok(),
814        agent_id: input.agent_id.map(|a| a.to_string()),
815    };
816    Ok(Some(
817        everruns_core::lifecycle_hooks::run_user_prompt_submit_hooks(&hooks, &ctx, message_text)
818            .await,
819    ))
820}
821
822pub async fn execute_reason_activity<A: RuntimeHostAdapter>(
823    adapter: &A,
824    org_id: i64,
825    input: ReasonInput,
826) -> everruns_core::error::Result<ReasonResult> {
827    if let Some(blocker) =
828        detect_dependency_blocker(adapter, org_id, input.harness_id, input.agent_id).await?
829    {
830        RuntimeSessionLifecycle::new(adapter.clone(), org_id, input.context.session_id)
831            .dependency_blocked(
832                input.context.turn_id,
833                input.context.input_message_id,
834                blocker,
835            )
836            .await;
837        return Ok(ReasonResult {
838            success: false,
839            text: blocker.message().to_string(),
840            tool_calls: vec![],
841            has_tool_calls: false,
842            tool_definitions: vec![],
843            max_iterations: everruns_core::runtime_agent::default_max_iterations(),
844            error: Some("dependency_unavailable".to_string()),
845            usage: None,
846            output_message_id: None,
847            time_to_first_token_ms: None,
848            response_id: None,
849            locale: None,
850            network_access: None,
851        });
852    }
853
854    // user_prompt_submit hook (see `specs/user-hooks.md`). Fires once per turn,
855    // on the first reason iteration, before the LLM is consulted — the closest
856    // choke point to "inbound user message accepted, before reason" that both
857    // the in-process loop and the durable worker share. A `Block` aborts the
858    // turn by reusing the same failure path as `dependency_blocked`: emit a
859    // user-facing message + turn.failed, idle the session, and return a
860    // non-success `ReasonResult` so no LLM/act work runs.
861    if input.iteration <= 1
862        && let Some(everruns_core::lifecycle_hooks::UserPromptDecision::Block {
863            reason,
864            user_message,
865        }) = run_user_prompt_submit_for_turn(adapter, org_id, &input).await?
866    {
867        RuntimeSessionLifecycle::new(adapter.clone(), org_id, input.context.session_id)
868            .user_prompt_blocked(
869                input.context.turn_id,
870                input.context.input_message_id,
871                &reason,
872                user_message.as_deref(),
873            )
874            .await;
875        return Ok(ReasonResult {
876            success: false,
877            text: user_message.unwrap_or_else(|| reason.clone()),
878            tool_calls: vec![],
879            has_tool_calls: false,
880            tool_definitions: vec![],
881            max_iterations: everruns_core::runtime_agent::default_max_iterations(),
882            error: Some("blocked_by_user_prompt_hook".to_string()),
883            usage: None,
884            output_message_id: None,
885            time_to_first_token_ms: None,
886            response_id: None,
887            locale: None,
888            network_access: None,
889        });
890    }
891
892    let turn_context = adapter
893        .load_turn_context(org_id, input.context.session_id)
894        .await?;
895
896    let mut atom = ReasonAtom::new(
897        adapter.harness_store(org_id),
898        adapter.agent_store(org_id),
899        adapter.session_store(org_id),
900        adapter.message_store(),
901        adapter.provider_store(org_id),
902        adapter.capability_registry(),
903        adapter.driver_registry(),
904        adapter.event_emitter(),
905    )
906    .with_file_store(adapter.file_store());
907    if let Some(image_resolver) = adapter.image_resolver(org_id) {
908        atom = atom.with_image_resolver(image_resolver);
909    }
910
911    atom.execute(ReasonInput {
912        mcp_tool_definitions: turn_context.mcp_tool_definitions,
913        ..input
914    })
915    .await
916}
917
918pub async fn execute_act_activity<A: RuntimeHostAdapter>(
919    adapter: &A,
920    input: ActInput,
921) -> everruns_core::error::Result<ActResult> {
922    let org_id = input.org_id.ok_or_else(|| {
923        everruns_core::error::AgentLoopError::config(
924            "ActInput.org_id must be set for runtime host execution",
925        )
926    })?;
927
928    if let Some(blocker) =
929        detect_dependency_blocker(adapter, org_id, input.harness_id, input.agent_id).await?
930    {
931        RuntimeSessionLifecycle::new(adapter.clone(), org_id, input.context.session_id)
932            .dependency_blocked(
933                input.context.turn_id,
934                input.context.input_message_id,
935                blocker,
936            )
937            .await;
938        return Ok(ActResult {
939            results: vec![],
940            completed: true,
941            success_count: 0,
942            error_count: 1,
943            waiting_for_tool_results: false,
944            blocked: true,
945            client_tool_calls: vec![],
946            client_tool_definitions: vec![],
947        });
948    }
949
950    let execution_capabilities = load_execution_capabilities(
951        adapter,
952        org_id,
953        input.context.session_id,
954        input.harness_id,
955        input.agent_id,
956        input.locale.clone(),
957        input.blueprint_id.as_deref(),
958    )
959    .await?;
960    let tool_registry = execution_capabilities.tool_registry;
961    let builtin_tool_registry = Arc::new(tool_registry.clone());
962
963    // Route `mcp_*` tool calls to the host's MCP executor when configured.
964    // Hosts that don't (default `None`, e.g. the worker) keep the plain
965    // registry, so their behavior is unchanged (specs/runtime-mcp.md D4).
966    let executor: Arc<dyn everruns_core::traits::ToolExecutor> =
967        match adapter.mcp_executor(org_id, input.context.session_id).await {
968            Some(mcp) => Arc::new(everruns_mcp::CompositeToolExecutor::new(tool_registry, mcp)),
969            None => Arc::new(tool_registry),
970        };
971
972    let mut atom =
973        ActAtom::with_file_store(executor, adapter.event_emitter(), adapter.file_store())
974            .with_session_store(adapter.session_store(org_id))
975            .with_session_mutator(adapter.session_mutator(org_id))
976            .with_agent_store(adapter.agent_store(org_id))
977            .with_tool_registry(builtin_tool_registry)
978            .with_org_id(
979                org_public_id_from_internal(org_id)
980                    .parse()
981                    .expect("internal org id converts to valid public org id"),
982            )
983            .with_capability_registry(adapter.capability_registry())
984            .with_post_tool_hooks(execution_capabilities.post_tool_hooks)
985            .with_pre_tool_hooks(execution_capabilities.pre_tool_hooks)
986            .with_tool_call_hooks(execution_capabilities.tool_call_hooks);
987
988    if let Some(storage_store) = adapter.storage_store() {
989        atom = atom.with_storage_store(storage_store);
990    }
991    if let Some(image_store) = adapter.image_artifact_store(org_id) {
992        atom = atom.with_image_store(image_store);
993    }
994    if let Some(provider_credential_store) = adapter.provider_credential_store(org_id) {
995        atom = atom.with_provider_credential_store(provider_credential_store);
996    }
997    if let Some(utility_llm_service) = adapter.utility_llm_service() {
998        atom = atom.with_utility_llm_service(utility_llm_service);
999    }
1000    if let Some(egress_service) = adapter.egress_service() {
1001        atom = atom.with_egress_service(egress_service);
1002    }
1003    if let Some(memory_store) = adapter.memory_store(org_id) {
1004        atom = atom.with_memory_store(memory_store);
1005    }
1006    if let Some(connection_resolver) = adapter.connection_resolver() {
1007        atom = atom.with_connection_resolver(connection_resolver);
1008    }
1009    if let Some(sqldb_store) = adapter.sqldb_store() {
1010        atom = atom.with_sqldb_store(sqldb_store);
1011    }
1012    if let Some(leased_resource_store) = adapter.leased_resource_store() {
1013        atom = atom.with_leased_resource_store(leased_resource_store);
1014    }
1015    if let Some(registry) = adapter.session_resource_registry() {
1016        atom = atom.with_session_resource_registry(registry);
1017    }
1018    if let Some(schedule_store) = adapter.schedule_store(org_id) {
1019        atom = atom.with_schedule_store(schedule_store);
1020    }
1021    if let Some(platform_store) = adapter.platform_store(org_id, input.context.session_id) {
1022        atom = atom.with_platform_store(platform_store);
1023    }
1024    if let Some(budget_checker) = adapter.budget_checker(org_id, input.agent_id) {
1025        atom = atom.with_budget_checker(budget_checker);
1026    }
1027    if let Some(payment_authority) = adapter.payment_authority(org_id, input.agent_id) {
1028        atom = atom.with_payment_authority(payment_authority);
1029    }
1030    if let Some(limiter) = adapter.outbound_tool_rate_limiter(org_id) {
1031        atom = atom.with_outbound_tool_rate_limiter(limiter);
1032    }
1033
1034    atom.execute(input).await
1035}