Skip to main content

lash_core/runtime/effect/
executor.rs

1use std::collections::{HashMap, HashSet};
2use std::pin::Pin;
3use std::sync::{Arc, OnceLock};
4use std::time::Instant;
5
6use hmac::{Hmac, Mac};
7use serde::{Deserialize, Serialize};
8use tokio::sync::{Notify, mpsc};
9use tokio_util::sync::CancellationToken;
10
11use crate::AttachmentStore;
12use crate::LlmRequest as CoreLlmRequest;
13use crate::LlmResponse;
14use crate::ProcessRecord;
15use crate::ProcessRegistry;
16use crate::provider::ProviderHandle;
17use crate::runtime::{RuntimeStreamEvent, RuntimeTurnDriver};
18use crate::sansio::LlmCallError;
19use crate::{PluginError, RuntimeError, RuntimeErrorCode};
20
21use super::envelope::{
22    ProcessCommand, ProcessEffectOutcome, RuntimeEffectCommand, RuntimeEffectEnvelope,
23    RuntimeEffectKind, RuntimeEffectOutcome,
24};
25use super::outcome::llm_call_error_from_transport;
26
27type HmacSha256 = Hmac<sha2::Sha256>;
28type AwaitEventOptions = (CancellationToken, Option<Instant>, Arc<dyn crate::Clock>);
29
30fn inline_await_events() -> &'static AwaitEventRegistry {
31    static REGISTRY: OnceLock<AwaitEventRegistry> = OnceLock::new();
32    REGISTRY.get_or_init(AwaitEventRegistry::new)
33}
34
35// =============================================================================
36// Effect host + controller trait + scope + error
37// =============================================================================
38
39/// Stable semantic identity for one effectful runtime operation.
40///
41/// The scope is chosen by the host boundary before any nondeterministic work is
42/// planned. It is intentionally generic: Restate, an inline test host, or a
43/// future durable effect host all receive the same Lash scope vocabulary.
44#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
45#[serde(tag = "type", rename_all = "snake_case")]
46pub enum ExecutionScope {
47    Turn {
48        session_id: String,
49        turn_id: String,
50    },
51    Process {
52        process_id: String,
53    },
54    QueueDrain {
55        session_id: String,
56        drain_id: String,
57    },
58    SessionDelete {
59        session_id: String,
60    },
61    RuntimeOperation {
62        operation_id: String,
63    },
64}
65
66impl ExecutionScope {
67    pub fn turn(session_id: impl Into<String>, turn_id: impl Into<String>) -> Self {
68        Self::Turn {
69            session_id: session_id.into(),
70            turn_id: turn_id.into(),
71        }
72    }
73
74    pub fn process(process_id: impl Into<String>) -> Self {
75        Self::Process {
76            process_id: process_id.into(),
77        }
78    }
79
80    pub fn queue_drain(session_id: impl Into<String>, drain_id: impl Into<String>) -> Self {
81        Self::QueueDrain {
82            session_id: session_id.into(),
83            drain_id: drain_id.into(),
84        }
85    }
86
87    pub fn session_delete(session_id: impl Into<String>) -> Self {
88        Self::SessionDelete {
89            session_id: session_id.into(),
90        }
91    }
92
93    pub fn runtime_operation(operation_id: impl Into<String>) -> Self {
94        Self::RuntimeOperation {
95            operation_id: operation_id.into(),
96        }
97    }
98
99    pub fn id(&self) -> &str {
100        match self {
101            Self::Turn { turn_id, .. } => turn_id,
102            Self::Process { process_id } => process_id,
103            Self::QueueDrain { drain_id, .. } => drain_id,
104            Self::SessionDelete { session_id } => session_id,
105            Self::RuntimeOperation { operation_id } => operation_id,
106        }
107    }
108
109    pub fn session_id(&self) -> Option<&str> {
110        match self {
111            Self::Turn { session_id, .. }
112            | Self::QueueDrain { session_id, .. }
113            | Self::SessionDelete { session_id } => Some(session_id),
114            Self::Process { .. } | Self::RuntimeOperation { .. } => None,
115        }
116    }
117
118    pub fn turn_id(&self) -> Option<&str> {
119        match self {
120            Self::Turn { turn_id, .. } => Some(turn_id),
121            _ => None,
122        }
123    }
124
125    pub fn validates_turn_trace_id(&self) -> bool {
126        matches!(self, Self::Turn { .. })
127    }
128
129    fn validate(&self) -> Result<(), RuntimeError> {
130        let missing = match self {
131            Self::Turn {
132                session_id,
133                turn_id,
134            } => session_id.trim().is_empty() || turn_id.trim().is_empty(),
135            Self::Process { process_id } => process_id.trim().is_empty(),
136            Self::QueueDrain {
137                session_id,
138                drain_id,
139            } => session_id.trim().is_empty() || drain_id.trim().is_empty(),
140            Self::SessionDelete { session_id } => session_id.trim().is_empty(),
141            Self::RuntimeOperation { operation_id } => operation_id.trim().is_empty(),
142        };
143        if missing {
144            return Err(RuntimeError::new(
145                RuntimeErrorCode::MissingExecutionScopeId,
146                "execution scopes require non-empty stable ids",
147            ));
148        }
149        Ok(())
150    }
151}
152
153#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
154#[serde(tag = "type", rename_all = "snake_case")]
155pub enum AwaitEventWaitIdentity {
156    ToolCompletion {
157        tool_call_id: String,
158    },
159    ProcessSignal {
160        process_id: String,
161        signal_name: String,
162        ordinal: u64,
163    },
164    Custom {
165        key: String,
166    },
167}
168
169impl AwaitEventWaitIdentity {
170    pub fn tool_completion(tool_call_id: impl Into<String>) -> Self {
171        Self::ToolCompletion {
172            tool_call_id: tool_call_id.into(),
173        }
174    }
175
176    pub fn process_signal(
177        process_id: impl Into<String>,
178        signal_name: impl Into<String>,
179        ordinal: u64,
180    ) -> Self {
181        Self::ProcessSignal {
182            process_id: process_id.into(),
183            signal_name: signal_name.into(),
184            ordinal,
185        }
186    }
187
188    fn validate(&self) -> Result<(), RuntimeError> {
189        let invalid = match self {
190            Self::ToolCompletion { tool_call_id } => tool_call_id.trim().is_empty(),
191            Self::ProcessSignal {
192                process_id,
193                signal_name,
194                ordinal,
195            } => process_id.trim().is_empty() || signal_name.trim().is_empty() || *ordinal == 0,
196            Self::Custom { key } => key.trim().is_empty(),
197        };
198        if invalid {
199            return Err(RuntimeError::new(
200                "invalid_await_event_wait_identity",
201                "await-event wait identity requires non-empty stable ids",
202            ));
203        }
204        Ok(())
205    }
206}
207
208#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
209pub struct AwaitEventKey {
210    pub scope: ExecutionScope,
211    pub wait: AwaitEventWaitIdentity,
212    pub key_id: String,
213    pub signature: String,
214}
215
216impl AwaitEventKey {
217    pub fn promise_key(&self) -> String {
218        format!("lash-await-event:{}", self.key_id)
219    }
220}
221
222#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
223pub struct ExternalCompletionError {
224    pub code: String,
225    pub message: String,
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub raw: Option<serde_json::Value>,
228}
229
230impl ExternalCompletionError {
231    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
232        Self {
233            code: code.into(),
234            message: message.into(),
235            raw: None,
236        }
237    }
238}
239
240#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
241#[serde(tag = "status", content = "payload", rename_all = "snake_case")]
242pub enum Resolution {
243    Ok(serde_json::Value),
244    Err(ExternalCompletionError),
245    Timeout,
246    Cancelled,
247}
248
249#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
250#[serde(tag = "status", rename_all = "snake_case")]
251pub enum ResolveOutcome {
252    Accepted,
253    AlreadyResolved { terminal: Resolution },
254    UnknownOrRevoked,
255}
256
257#[derive(Debug)]
258struct AwaitEventEntry {
259    terminal: Option<Resolution>,
260    notify: Arc<Notify>,
261}
262
263#[derive(Debug)]
264struct AwaitEventRegistryState {
265    entries: HashMap<String, AwaitEventEntry>,
266    revoked_key_ids: HashSet<String>,
267    revoked_session_ids: HashSet<String>,
268}
269
270#[derive(Debug)]
271struct AwaitEventRegistry {
272    secret: Vec<u8>,
273    state: std::sync::Mutex<AwaitEventRegistryState>,
274}
275
276impl AwaitEventRegistry {
277    fn new() -> Self {
278        Self {
279            secret: uuid::Uuid::new_v4().as_bytes().to_vec(),
280            state: std::sync::Mutex::new(AwaitEventRegistryState {
281                entries: HashMap::new(),
282                revoked_key_ids: HashSet::new(),
283                revoked_session_ids: HashSet::new(),
284            }),
285        }
286    }
287
288    fn key_for(
289        &self,
290        scope: &ExecutionScope,
291        wait: AwaitEventWaitIdentity,
292    ) -> Result<AwaitEventKey, RuntimeError> {
293        scope.validate()?;
294        wait.validate()?;
295        let key_id =
296            crate::stable_hash::stable_json_sha256_hex(&(scope, &wait)).map_err(|err| {
297                RuntimeError::new(
298                    "await_event_key_hash",
299                    format!("failed to hash await-event identity: {err}"),
300                )
301            })?;
302        let signature = self.signature(scope, &wait, &key_id)?;
303        Ok(AwaitEventKey {
304            scope: scope.clone(),
305            wait,
306            key_id,
307            signature,
308        })
309    }
310
311    fn signature(
312        &self,
313        scope: &ExecutionScope,
314        wait: &AwaitEventWaitIdentity,
315        key_id: &str,
316    ) -> Result<String, RuntimeError> {
317        let mut mac = HmacSha256::new_from_slice(&self.secret).map_err(|err| {
318            RuntimeError::new(
319                "await_event_key_sign",
320                format!("failed to initialize await-event key signer: {err}"),
321            )
322        })?;
323        let canonical = serde_json::to_vec(&(scope, wait, key_id)).map_err(|err| {
324            RuntimeError::new(
325                "await_event_key_sign",
326                format!("failed to serialize await-event key identity: {err}"),
327            )
328        })?;
329        mac.update(&canonical);
330        Ok(format!("{:x}", mac.finalize().into_bytes()))
331    }
332
333    fn verify(&self, key: &AwaitEventKey) -> Result<bool, RuntimeError> {
334        let expected = self.signature(&key.scope, &key.wait, &key.key_id)?;
335        Ok(expected == key.signature)
336    }
337
338    fn resolve(
339        &self,
340        key: &AwaitEventKey,
341        resolution: Resolution,
342    ) -> Result<ResolveOutcome, RuntimeError> {
343        if !self.verify(key)? {
344            return Ok(ResolveOutcome::UnknownOrRevoked);
345        }
346        let mut state = self.state.lock().map_err(|_| {
347            RuntimeError::new(
348                "await_event_registry_poisoned",
349                "await-event registry lock poisoned",
350            )
351        })?;
352        if state.revoked_key_ids.contains(&key.key_id)
353            || key
354                .scope
355                .session_id()
356                .is_some_and(|session_id| state.revoked_session_ids.contains(session_id))
357        {
358            return Ok(ResolveOutcome::UnknownOrRevoked);
359        }
360        let entry = state
361            .entries
362            .entry(key.key_id.clone())
363            .or_insert_with(|| AwaitEventEntry {
364                terminal: None,
365                notify: Arc::new(Notify::new()),
366            });
367        if let Some(terminal) = &entry.terminal {
368            return Ok(ResolveOutcome::AlreadyResolved {
369                terminal: terminal.clone(),
370            });
371        }
372        entry.terminal = Some(resolution);
373        entry.notify.notify_waiters();
374        Ok(ResolveOutcome::Accepted)
375    }
376
377    async fn await_resolution(
378        &self,
379        key: &AwaitEventKey,
380        cancel: CancellationToken,
381        deadline: Option<Instant>,
382        clock: &dyn crate::Clock,
383    ) -> Result<Resolution, RuntimeError> {
384        if !self.verify(key)? {
385            return Err(RuntimeError::new(
386                "await_event_unknown_or_revoked",
387                "await-event key is invalid or revoked",
388            ));
389        }
390        loop {
391            let notify =
392                {
393                    let mut state = self.state.lock().map_err(|_| {
394                        RuntimeError::new(
395                            "await_event_registry_poisoned",
396                            "await-event registry lock poisoned",
397                        )
398                    })?;
399                    if state.revoked_key_ids.contains(&key.key_id)
400                        || key.scope.session_id().is_some_and(|session_id| {
401                            state.revoked_session_ids.contains(session_id)
402                        })
403                    {
404                        return Err(RuntimeError::new(
405                            "await_event_unknown_or_revoked",
406                            "await-event key is invalid or revoked",
407                        ));
408                    }
409                    let entry = state.entries.entry(key.key_id.clone()).or_insert_with(|| {
410                        AwaitEventEntry {
411                            terminal: None,
412                            notify: Arc::new(Notify::new()),
413                        }
414                    });
415                    if let Some(terminal) = entry.terminal.clone() {
416                        return Ok(terminal);
417                    }
418                    Arc::clone(&entry.notify)
419                };
420            if let Some(deadline) = deadline {
421                tokio::select! {
422                    _ = cancel.cancelled() => {
423                        let _ = self.resolve(key, Resolution::Cancelled)?;
424                    }
425                    _ = clock.sleep_until(deadline) => {
426                        let _ = self.resolve(key, Resolution::Timeout)?;
427                    }
428                    _ = notify.notified() => {}
429                }
430            } else {
431                tokio::select! {
432                    _ = cancel.cancelled() => {
433                        let _ = self.resolve(key, Resolution::Cancelled)?;
434                    }
435                    _ = notify.notified() => {}
436                }
437            }
438        }
439    }
440
441    fn revoke_session(&self, session_id: &str) -> Result<(), RuntimeError> {
442        let mut state = self.state.lock().map_err(|_| {
443            RuntimeError::new(
444                "await_event_registry_poisoned",
445                "await-event registry lock poisoned",
446            )
447        })?;
448        state.revoked_session_ids.insert(session_id.to_string());
449        for entry in state.entries.values() {
450            entry.notify.notify_waiters();
451        }
452        Ok(())
453    }
454}
455
456enum ScopedEffectControllerInner<'run> {
457    Borrowed(&'run dyn RuntimeEffectController),
458    Shared(Arc<dyn RuntimeEffectController>),
459}
460
461impl Clone for ScopedEffectControllerInner<'_> {
462    fn clone(&self) -> Self {
463        match self {
464            Self::Borrowed(controller) => Self::Borrowed(*controller),
465            Self::Shared(controller) => Self::Shared(Arc::clone(controller)),
466        }
467    }
468}
469
470/// Scoped low-level controller plus the semantic execution scope it is serving.
471#[derive(Clone)]
472pub struct ScopedEffectController<'run> {
473    controller: ScopedEffectControllerInner<'run>,
474    scope: ExecutionScope,
475}
476
477impl<'run> ScopedEffectController<'run> {
478    pub fn borrowed(
479        controller: &'run dyn RuntimeEffectController,
480        scope: ExecutionScope,
481    ) -> Result<Self, RuntimeError> {
482        scope.validate()?;
483        Ok(Self {
484            controller: ScopedEffectControllerInner::Borrowed(controller),
485            scope,
486        })
487    }
488
489    pub fn shared(
490        controller: Arc<dyn RuntimeEffectController>,
491        scope: ExecutionScope,
492    ) -> Result<Self, RuntimeError> {
493        scope.validate()?;
494        Ok(Self {
495            controller: ScopedEffectControllerInner::Shared(controller),
496            scope,
497        })
498    }
499
500    pub fn controller(&self) -> &dyn RuntimeEffectController {
501        match &self.controller {
502            ScopedEffectControllerInner::Borrowed(controller) => *controller,
503            ScopedEffectControllerInner::Shared(controller) => controller.as_ref(),
504        }
505    }
506
507    pub fn execution_scope(&self) -> &ExecutionScope {
508        &self.scope
509    }
510
511    pub fn scope_id(&self) -> &str {
512        self.scope.id()
513    }
514
515    pub fn turn_id(&self) -> Option<&str> {
516        self.scope.turn_id()
517    }
518}
519
520/// Shared durability and Durable Wait contract for effect boundaries.
521///
522/// Both the deployment-level [`EffectHost`] factory and the per-run
523/// [`RuntimeEffectController`] resolve Durable Waits and describe their
524/// durability; this supertrait is the single declaration of that contract.
525#[async_trait::async_trait]
526pub trait AwaitEventResolver: Send + Sync {
527    fn durability_tier(&self) -> crate::DurabilityTier {
528        crate::DurabilityTier::Inline
529    }
530
531    fn requires_durable_attachment_store(&self) -> bool {
532        false
533    }
534
535    fn supports_durable_effects(&self) -> bool {
536        false
537    }
538
539    async fn await_event_key(
540        &self,
541        _scope: &ExecutionScope,
542        _wait: AwaitEventWaitIdentity,
543    ) -> Result<AwaitEventKey, RuntimeError> {
544        Err(RuntimeError::new(
545            "await_event_unsupported",
546            "this effect boundary does not support await-event keys",
547        ))
548    }
549
550    async fn resolve_await_event(
551        &self,
552        _key: &AwaitEventKey,
553        _resolution: Resolution,
554    ) -> Result<ResolveOutcome, RuntimeError> {
555        Ok(ResolveOutcome::UnknownOrRevoked)
556    }
557
558    async fn await_await_event(
559        &self,
560        _key: &AwaitEventKey,
561        _cancel: CancellationToken,
562        _deadline: Option<Instant>,
563    ) -> Result<Resolution, RuntimeError> {
564        Err(RuntimeError::new(
565            "await_event_unsupported",
566            "this effect boundary does not support await-event waits",
567        ))
568    }
569
570    async fn revoke_await_events_for_session(&self, _session_id: &str) -> Result<(), RuntimeError> {
571        Ok(())
572    }
573}
574
575/// Deployment-level factory for scoped effect controllers.
576#[async_trait::async_trait]
577pub trait EffectHost: AwaitEventResolver {
578    fn scoped<'run>(
579        &'run self,
580        scope: ExecutionScope,
581    ) -> Result<ScopedEffectController<'run>, RuntimeError>;
582
583    fn scoped_static(
584        &self,
585        _scope: ExecutionScope,
586    ) -> Result<Option<ScopedEffectController<'static>>, RuntimeError> {
587        Ok(None)
588    }
589}
590
591/// Boundary for nondeterministic runtime work.
592#[async_trait::async_trait]
593pub trait RuntimeEffectController: AwaitEventResolver {
594    /// Whether this controller can safely accept overlapping `execute_effect`
595    /// calls from one runtime coordinator.
596    ///
597    /// Local and store-backed controllers can usually fan out independent
598    /// effects. Some workflow substrates expose a single ordered journal
599    /// context where native operations must be awaited immediately before the
600    /// next context call is issued. Those controllers should return `false` so
601    /// coordinators serialize child effects while still replaying each child by
602    /// its own stable key.
603    fn supports_concurrent_effects(&self) -> bool {
604        true
605    }
606
607    async fn execute_effect(
608        &self,
609        envelope: RuntimeEffectEnvelope,
610        local_executor: RuntimeEffectLocalExecutor<'_>,
611    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError>;
612}
613
614/// Runtime-internal handle for effect-controller references carried through
615/// per-turn execution contexts.
616#[derive(Clone)]
617pub(crate) enum RuntimeEffectControllerHandle<'run> {
618    Borrowed(ScopedEffectController<'run>),
619    #[cfg(any(test, feature = "testing"))]
620    Shared {
621        controller: Arc<dyn RuntimeEffectController>,
622        scope: ExecutionScope,
623    },
624}
625
626impl<'run> RuntimeEffectControllerHandle<'run> {
627    pub(crate) fn borrowed(scoped: ScopedEffectController<'run>) -> Self {
628        Self::Borrowed(scoped)
629    }
630
631    #[cfg(any(test, feature = "testing"))]
632    pub(crate) fn shared(controller: Arc<dyn RuntimeEffectController>) -> Self {
633        Self::Shared {
634            controller,
635            scope: ExecutionScope::runtime_operation("test-runtime-effect-controller"),
636        }
637    }
638
639    pub(crate) fn controller(&self) -> &dyn RuntimeEffectController {
640        match self {
641            Self::Borrowed(scoped) => scoped.controller(),
642            #[cfg(any(test, feature = "testing"))]
643            Self::Shared { controller, .. } => controller.as_ref(),
644        }
645    }
646
647    pub(crate) fn scoped(&self) -> ScopedEffectController<'_> {
648        match self {
649            Self::Borrowed(scoped) => scoped.clone(),
650            #[cfg(any(test, feature = "testing"))]
651            Self::Shared { controller, scope } => {
652                ScopedEffectController::shared(Arc::clone(controller), scope.clone())
653                    .expect("runtime effect controller handle carries a valid scope")
654            }
655        }
656    }
657
658    pub(crate) fn clone_scoped(&self) -> RuntimeEffectControllerHandle<'run> {
659        self.clone()
660    }
661}
662
663#[derive(Clone, Debug, thiserror::Error, Serialize, Deserialize)]
664#[error("{code}: {message}")]
665pub struct RuntimeEffectControllerError {
666    pub code: String,
667    pub message: String,
668}
669
670impl RuntimeEffectControllerError {
671    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
672        Self {
673            code: code.into(),
674            message: message.into(),
675        }
676    }
677
678    pub(super) fn wrong_outcome(expected: RuntimeEffectKind, actual: RuntimeEffectKind) -> Self {
679        Self::new(
680            "runtime_effect_wrong_outcome",
681            format!(
682                "expected {} outcome, got {}",
683                expected.as_str(),
684                actual.as_str()
685            ),
686        )
687    }
688
689    pub(crate) fn into_runtime_error(self) -> RuntimeError {
690        RuntimeError::new(self.code, self.message)
691    }
692}
693
694impl From<RuntimeError> for RuntimeEffectControllerError {
695    fn from(err: RuntimeError) -> Self {
696        Self::new(err.code.as_str(), err.message)
697    }
698}
699
700impl From<PluginError> for RuntimeEffectControllerError {
701    fn from(err: PluginError) -> Self {
702        Self::new("plugin", err.to_string())
703    }
704}
705
706impl From<crate::StoreError> for RuntimeEffectControllerError {
707    fn from(err: crate::StoreError) -> Self {
708        Self::new("runtime_store", err.to_string())
709    }
710}
711
712// =============================================================================
713// Local executor (per-effect borrowed runner state)
714// =============================================================================
715
716#[async_trait::async_trait]
717pub(crate) trait ProcessRunner: Send + Sync {
718    async fn run_process(
719        &self,
720        registration: crate::ProcessRegistration,
721        execution_context: crate::ProcessExecutionContext,
722        registry: Arc<dyn ProcessRegistry>,
723        scoped_effect_controller: crate::ScopedEffectController<'_>,
724        cancellation: CancellationToken,
725    ) -> crate::ProcessAwaitOutput;
726}
727
728pub struct ProcessLocalExecution {
729    pub registry: Arc<dyn ProcessRegistry>,
730    pub process_work_driver: Option<crate::ProcessWorkDriver>,
731}
732
733pub(super) struct LocalTurnEffectRunner<'a, 'run> {
734    driver: &'a mut RuntimeTurnDriver<'run>,
735    machine: &'a mut crate::TurnMachine,
736    event_tx: mpsc::Sender<RuntimeStreamEvent>,
737    cancellation: CancellationToken,
738}
739
740pub(super) struct LocalDirectEffectRunner {
741    provider: ProviderHandle,
742    attachment_store: Arc<dyn AttachmentStore>,
743}
744
745struct LocalToolBatchEffectRunner<'run> {
746    context: crate::RuntimeExecutionContext<'run>,
747    child_trace_hooks: HashMap<String, crate::ToolChildExecutionTraceHook>,
748}
749
750#[async_trait::async_trait]
751trait RuntimeEffectLocalRunner: Send {
752    async fn execute(
753        self: Box<Self>,
754        envelope: RuntimeEffectEnvelope,
755    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError>;
756}
757
758#[cfg(any(test, feature = "testing"))]
759type TestingRuntimeEffectLocalRunnerFn<'run> = dyn FnOnce(
760        RuntimeEffectEnvelope,
761    ) -> Pin<
762        Box<
763            dyn Future<Output = Result<RuntimeEffectOutcome, RuntimeEffectControllerError>>
764                + Send
765                + 'run,
766        >,
767    > + Send
768    + 'run;
769
770#[cfg(any(test, feature = "testing"))]
771struct TestingRuntimeEffectLocalRunner<'run> {
772    run: Box<TestingRuntimeEffectLocalRunnerFn<'run>>,
773}
774
775type DurableStepLocalRunnerFn<'run> = dyn FnOnce(
776        serde_json::Value,
777    ) -> Pin<
778        Box<
779            dyn Future<Output = Result<serde_json::Value, RuntimeEffectControllerError>>
780                + Send
781                + 'run,
782        >,
783    > + Send
784    + 'run;
785
786struct DurableStepLocalRunner<'run> {
787    run: Box<DurableStepLocalRunnerFn<'run>>,
788}
789
790enum RuntimeEffectLocalExecutorState<'run> {
791    Unavailable,
792    SleepOnly {
793        cancellation: CancellationToken,
794        clock: Arc<dyn crate::Clock>,
795    },
796    ExternalWaitOptions {
797        cancellation: CancellationToken,
798        deadline: Option<Instant>,
799        clock: Arc<dyn crate::Clock>,
800    },
801    Process(ProcessLocalExecution),
802    Runner(Box<dyn RuntimeEffectLocalRunner + Send + 'run>),
803}
804
805/// Scoped local executor provided to a [`RuntimeEffectController`] for one effect.
806///
807/// Durable controllers may ignore it and replay their own recorded result. The
808/// default inline controller delegates to it, so local provider/tool/checkpoint
809/// work still crosses the same `execute_effect` boundary as durable controllers.
810pub struct RuntimeEffectLocalExecutor<'run> {
811    state: RuntimeEffectLocalExecutorState<'run>,
812}
813
814impl<'run> RuntimeEffectLocalExecutor<'run> {
815    pub fn unavailable() -> Self {
816        Self {
817            state: RuntimeEffectLocalExecutorState::Unavailable,
818        }
819    }
820
821    pub fn sleep(cancellation: CancellationToken) -> Self {
822        Self::sleep_with_clock(cancellation, Arc::new(crate::SystemClock))
823    }
824
825    pub fn sleep_with_clock(cancellation: CancellationToken, clock: Arc<dyn crate::Clock>) -> Self {
826        Self {
827            state: RuntimeEffectLocalExecutorState::SleepOnly {
828                cancellation,
829                clock,
830            },
831        }
832    }
833
834    pub fn await_event(cancellation: CancellationToken, deadline: Option<Instant>) -> Self {
835        Self::await_event_with_clock(cancellation, deadline, Arc::new(crate::SystemClock))
836    }
837
838    pub fn await_event_with_clock(
839        cancellation: CancellationToken,
840        deadline: Option<Instant>,
841        clock: Arc<dyn crate::Clock>,
842    ) -> Self {
843        Self {
844            state: RuntimeEffectLocalExecutorState::ExternalWaitOptions {
845                cancellation,
846                deadline,
847                clock,
848            },
849        }
850    }
851
852    pub fn processes(registry: Arc<dyn ProcessRegistry>) -> Self {
853        Self::processes_with_driver(registry, None)
854    }
855
856    pub fn processes_with_driver(
857        registry: Arc<dyn ProcessRegistry>,
858        process_work_driver: Option<crate::ProcessWorkDriver>,
859    ) -> Self {
860        Self {
861            state: RuntimeEffectLocalExecutorState::Process(ProcessLocalExecution {
862                registry,
863                process_work_driver,
864            }),
865        }
866    }
867
868    pub fn durable_step<F, Fut>(run: F) -> Self
869    where
870        F: FnOnce(serde_json::Value) -> Fut + Send + 'run,
871        Fut: Future<Output = Result<serde_json::Value, RuntimeError>> + Send + 'run,
872    {
873        Self {
874            state: RuntimeEffectLocalExecutorState::Runner(Box::new(DurableStepLocalRunner {
875                run: Box::new(move |input| {
876                    Box::pin(async move { run(input).await.map_err(Into::into) })
877                }),
878            })),
879        }
880    }
881
882    #[cfg(any(test, feature = "testing"))]
883    pub fn testing<F, Fut>(run: F) -> Self
884    where
885        F: FnOnce(RuntimeEffectEnvelope) -> Fut + Send + 'run,
886        Fut: Future<Output = Result<RuntimeEffectOutcome, RuntimeEffectControllerError>>
887            + Send
888            + 'run,
889    {
890        Self {
891            state: RuntimeEffectLocalExecutorState::Runner(Box::new(
892                TestingRuntimeEffectLocalRunner {
893                    run: Box::new(move |envelope| Box::pin(run(envelope))),
894                },
895            )),
896        }
897    }
898
899    pub(in crate::runtime) fn turn<'scope>(
900        driver: &'run mut RuntimeTurnDriver<'scope>,
901        machine: &'run mut crate::TurnMachine,
902        event_tx: mpsc::Sender<RuntimeStreamEvent>,
903        cancellation: CancellationToken,
904    ) -> Self
905    where
906        'scope: 'run,
907    {
908        Self {
909            state: RuntimeEffectLocalExecutorState::Runner(Box::new(LocalTurnEffectRunner {
910                driver,
911                machine,
912                event_tx,
913                cancellation,
914            })),
915        }
916    }
917
918    pub(in crate::runtime) fn direct(
919        provider: ProviderHandle,
920        attachment_store: Arc<dyn AttachmentStore>,
921    ) -> Self {
922        Self {
923            state: RuntimeEffectLocalExecutorState::Runner(Box::new(LocalDirectEffectRunner {
924                provider,
925                attachment_store,
926            })),
927        }
928    }
929
930    pub(crate) fn tool_batch(
931        context: crate::RuntimeExecutionContext<'run>,
932        child_trace_hooks: HashMap<String, crate::ToolChildExecutionTraceHook>,
933    ) -> Self {
934        Self {
935            state: RuntimeEffectLocalExecutorState::Runner(Box::new(LocalToolBatchEffectRunner {
936                context,
937                child_trace_hooks,
938            })),
939        }
940    }
941
942    pub async fn execute(
943        self,
944        envelope: RuntimeEffectEnvelope,
945    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError> {
946        match self.state {
947            RuntimeEffectLocalExecutorState::Runner(runner) => runner.execute(envelope).await,
948            RuntimeEffectLocalExecutorState::SleepOnly {
949                cancellation,
950                clock,
951            } => execute_local_sleep(envelope, cancellation, clock.as_ref()).await,
952            RuntimeEffectLocalExecutorState::ExternalWaitOptions { .. } => {
953                Err(RuntimeEffectControllerError::new(
954                    "runtime_effect_local_executor_mismatch",
955                    format!(
956                        "local await-event options cannot execute {} command directly",
957                        envelope.command.kind().as_str()
958                    ),
959                ))
960            }
961            RuntimeEffectLocalExecutorState::Unavailable => Err(RuntimeEffectControllerError::new(
962                "runtime_effect_local_executor_unavailable",
963                format!(
964                    "no local executor is available for {}",
965                    envelope.command.kind().as_str()
966                ),
967            )),
968            RuntimeEffectLocalExecutorState::Process(_) => Err(RuntimeEffectControllerError::new(
969                "runtime_effect_local_executor_mismatch",
970                format!(
971                    "process executor cannot execute {} command directly",
972                    envelope.command.kind().as_str()
973                ),
974            )),
975        }
976    }
977
978    pub fn into_process(self) -> Result<ProcessLocalExecution, RuntimeEffectControllerError> {
979        match self.state {
980            RuntimeEffectLocalExecutorState::Process(execution) => Ok(execution),
981            _ => Err(RuntimeEffectControllerError::new(
982                "runtime_effect_local_executor_unavailable",
983                "no process executor is available for process command",
984            )),
985        }
986    }
987
988    fn into_await_event_options(self) -> Result<AwaitEventOptions, RuntimeEffectControllerError> {
989        match self.state {
990            RuntimeEffectLocalExecutorState::ExternalWaitOptions {
991                cancellation,
992                deadline,
993                clock,
994            } => Ok((cancellation, deadline, clock)),
995            _ => Ok((CancellationToken::new(), None, Arc::new(crate::SystemClock))),
996        }
997    }
998}
999
1000#[cfg(any(test, feature = "testing"))]
1001#[async_trait::async_trait]
1002impl RuntimeEffectLocalRunner for TestingRuntimeEffectLocalRunner<'_> {
1003    async fn execute(
1004        self: Box<Self>,
1005        envelope: RuntimeEffectEnvelope,
1006    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError> {
1007        (self.run)(envelope).await
1008    }
1009}
1010
1011#[async_trait::async_trait]
1012impl RuntimeEffectLocalRunner for DurableStepLocalRunner<'_> {
1013    async fn execute(
1014        self: Box<Self>,
1015        envelope: RuntimeEffectEnvelope,
1016    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError> {
1017        match envelope.command {
1018            RuntimeEffectCommand::DurableStep { input, .. } => {
1019                let value = (self.run)(input).await?;
1020                Ok(RuntimeEffectOutcome::DurableStep { value })
1021            }
1022            command => Err(RuntimeEffectControllerError::new(
1023                "runtime_effect_local_executor_mismatch",
1024                format!(
1025                    "local durable step executor cannot execute {} command",
1026                    command.kind().as_str()
1027                ),
1028            )),
1029        }
1030    }
1031}
1032
1033#[async_trait::async_trait]
1034impl RuntimeEffectLocalRunner for LocalToolBatchEffectRunner<'_> {
1035    async fn execute(
1036        self: Box<Self>,
1037        envelope: RuntimeEffectEnvelope,
1038    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError> {
1039        match envelope.command {
1040            RuntimeEffectCommand::ToolBatch { batch } => {
1041                let outcome = self
1042                    .context
1043                    .execute_prepared_tool_batch_launches(
1044                        batch,
1045                        envelope.invocation,
1046                        self.child_trace_hooks,
1047                    )
1048                    .await?;
1049                Ok(RuntimeEffectOutcome::ToolBatch {
1050                    launches: outcome.launches,
1051                    triggers: outcome.triggers,
1052                })
1053            }
1054            RuntimeEffectCommand::ToolAttempt {
1055                call,
1056                execution_grant,
1057                attempt,
1058                max_attempts,
1059            } => {
1060                let child_execution_trace_hook = self.child_trace_hooks.get(&call.call_id).cloned();
1061                let outcome = self
1062                    .context
1063                    .execute_prepared_tool_attempt_effect(
1064                        call,
1065                        execution_grant,
1066                        attempt,
1067                        max_attempts,
1068                        envelope.invocation,
1069                        child_execution_trace_hook,
1070                    )
1071                    .await?;
1072                Ok(RuntimeEffectOutcome::ToolAttempt {
1073                    launch: outcome.launch,
1074                    triggers: outcome.triggers,
1075                })
1076            }
1077            command => Err(RuntimeEffectControllerError::new(
1078                "runtime_effect_local_executor_mismatch",
1079                format!(
1080                    "local tool executor cannot execute {} command",
1081                    command.kind().as_str()
1082                ),
1083            )),
1084        }
1085    }
1086}
1087
1088#[async_trait::async_trait]
1089impl RuntimeEffectLocalRunner for LocalTurnEffectRunner<'_, '_> {
1090    async fn execute(
1091        self: Box<Self>,
1092        envelope: RuntimeEffectEnvelope,
1093    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError> {
1094        let runner = *self;
1095        match envelope.command {
1096            RuntimeEffectCommand::LlmCall { request } => {
1097                let protocol_iteration = runner.machine.protocol_iteration();
1098                let (result, text_streamed) = runner
1099                    .driver
1100                    .run_llm_call(
1101                        Arc::new((*request).into_request(None, None)),
1102                        protocol_iteration,
1103                        envelope.invocation,
1104                        &runner.event_tx,
1105                        &runner.cancellation,
1106                    )
1107                    .await;
1108                Ok(RuntimeEffectOutcome::LlmCall {
1109                    result,
1110                    text_streamed,
1111                })
1112            }
1113            RuntimeEffectCommand::ToolBatch { batch } => {
1114                let outcome = runner
1115                    .driver
1116                    .run_tool_batch(
1117                        batch,
1118                        envelope.invocation,
1119                        &runner.event_tx,
1120                        &runner.cancellation,
1121                    )
1122                    .await?;
1123                Ok(RuntimeEffectOutcome::ToolBatch {
1124                    launches: outcome.launches,
1125                    triggers: outcome.triggers,
1126                })
1127            }
1128            RuntimeEffectCommand::ExecCode { language, code } => {
1129                let protocol_iteration = runner.machine.protocol_iteration();
1130                let messages = runner.machine.message_sequence();
1131                Ok(RuntimeEffectOutcome::ExecCode {
1132                    result: runner
1133                        .driver
1134                        .run_exec_code(
1135                            language,
1136                            &code,
1137                            messages,
1138                            protocol_iteration,
1139                            envelope.invocation,
1140                            &runner.event_tx,
1141                        )
1142                        .await,
1143                })
1144            }
1145            RuntimeEffectCommand::Checkpoint { checkpoint } => {
1146                Ok(RuntimeEffectOutcome::Checkpoint {
1147                    result: runner
1148                        .driver
1149                        .run_checkpoint(runner.machine, checkpoint, &runner.event_tx)
1150                        .await
1151                        .map_err(RuntimeEffectControllerError::from),
1152                })
1153            }
1154            RuntimeEffectCommand::SyncExecutionEnvironment {
1155                update_machine_config,
1156            } => Ok(RuntimeEffectOutcome::SyncExecutionEnvironment {
1157                result: runner
1158                    .driver
1159                    .refresh_execution_environment(runner.machine, update_machine_config)
1160                    .await
1161                    .map_err(|err| err.to_string()),
1162            }),
1163            RuntimeEffectCommand::Sleep { duration_ms } => {
1164                sleep_with_cancellation(
1165                    duration_ms,
1166                    &runner.cancellation,
1167                    runner.driver.host.core.clock.as_ref(),
1168                )
1169                .await?;
1170                Ok(RuntimeEffectOutcome::Sleep)
1171            }
1172            command => Err(RuntimeEffectControllerError::new(
1173                "runtime_effect_local_executor_mismatch",
1174                format!(
1175                    "local turn executor cannot execute {} command",
1176                    command.kind().as_str()
1177                ),
1178            )),
1179        }
1180    }
1181}
1182
1183#[async_trait::async_trait]
1184impl RuntimeEffectLocalRunner for LocalDirectEffectRunner {
1185    async fn execute(
1186        mut self: Box<Self>,
1187        envelope: RuntimeEffectEnvelope,
1188    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError> {
1189        match envelope.command {
1190            RuntimeEffectCommand::Direct { request, .. } => Ok(RuntimeEffectOutcome::Direct {
1191                result: self
1192                    .run_direct_llm_request((*request).into_request(
1193                        crate::session_model::transport_stream_events(&self.provider, None),
1194                        None,
1195                    ))
1196                    .await,
1197            }),
1198            RuntimeEffectCommand::Sleep { duration_ms } => {
1199                sleep_with_cancellation(
1200                    duration_ms,
1201                    &CancellationToken::new(),
1202                    &crate::SystemClock,
1203                )
1204                .await?;
1205                Ok(RuntimeEffectOutcome::Sleep)
1206            }
1207            command => Err(RuntimeEffectControllerError::new(
1208                "runtime_effect_local_executor_mismatch",
1209                format!(
1210                    "local direct executor cannot execute {} command",
1211                    command.kind().as_str()
1212                ),
1213            )),
1214        }
1215    }
1216}
1217
1218impl LocalDirectEffectRunner {
1219    async fn run_direct_llm_request(
1220        &mut self,
1221        request: CoreLlmRequest,
1222    ) -> Result<LlmResponse, LlmCallError> {
1223        let request = crate::attachments::resolve_llm_request_attachments(
1224            request,
1225            self.attachment_store.as_ref(),
1226        )
1227        .await
1228        .map_err(|err| LlmCallError {
1229            message: err.to_string(),
1230            retryable: false,
1231            raw: None,
1232            code: Some("attachment_resolution_failed".to_string()),
1233            terminal_reason: crate::LlmTerminalReason::ProviderError,
1234            request_body: None,
1235        })?;
1236        self.provider
1237            .complete(request)
1238            .await
1239            .map_err(llm_call_error_from_transport)
1240    }
1241}
1242
1243async fn execute_local_sleep(
1244    envelope: RuntimeEffectEnvelope,
1245    cancellation: CancellationToken,
1246    clock: &dyn crate::Clock,
1247) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError> {
1248    match envelope.command {
1249        RuntimeEffectCommand::Sleep { duration_ms } => {
1250            sleep_with_cancellation(duration_ms, &cancellation, clock).await?;
1251            Ok(RuntimeEffectOutcome::Sleep)
1252        }
1253        command => Err(RuntimeEffectControllerError::new(
1254            "runtime_effect_local_executor_mismatch",
1255            format!(
1256                "local sleep executor cannot execute {} command",
1257                command.kind().as_str()
1258            ),
1259        )),
1260    }
1261}
1262
1263async fn sleep_with_cancellation(
1264    duration_ms: u64,
1265    cancellation: &CancellationToken,
1266    clock: &dyn crate::Clock,
1267) -> Result<(), RuntimeEffectControllerError> {
1268    let sleep = clock.sleep(std::time::Duration::from_millis(duration_ms));
1269    tokio::pin!(sleep);
1270    tokio::select! {
1271        _ = cancellation.cancelled() => Err(RuntimeEffectControllerError::new(
1272            "runtime_effect_sleep_cancelled",
1273            "runtime effect sleep was cancelled",
1274        )),
1275        _ = &mut sleep => Ok(()),
1276    }
1277}
1278
1279// =============================================================================
1280// Default in-process effect controller
1281// =============================================================================
1282
1283/// Default in-process effect controller.
1284///
1285/// The inline controller executes local runners in process, provides in-memory
1286/// await-event resolution, and exposes durable-tool-effect semantics for local
1287/// runs. It does not make in-flight effects crash durable; workflow adapters
1288/// provide that by recording outcomes in their own history.
1289#[derive(Clone, Default)]
1290pub struct InlineRuntimeEffectController;
1291
1292#[async_trait::async_trait]
1293impl AwaitEventResolver for InlineRuntimeEffectController {
1294    fn supports_durable_effects(&self) -> bool {
1295        true
1296    }
1297
1298    async fn await_event_key(
1299        &self,
1300        scope: &ExecutionScope,
1301        wait: AwaitEventWaitIdentity,
1302    ) -> Result<AwaitEventKey, RuntimeError> {
1303        inline_await_events().key_for(scope, wait)
1304    }
1305
1306    async fn resolve_await_event(
1307        &self,
1308        key: &AwaitEventKey,
1309        resolution: Resolution,
1310    ) -> Result<ResolveOutcome, RuntimeError> {
1311        inline_await_events().resolve(key, resolution)
1312    }
1313
1314    async fn await_await_event(
1315        &self,
1316        key: &AwaitEventKey,
1317        cancel: CancellationToken,
1318        deadline: Option<Instant>,
1319    ) -> Result<Resolution, RuntimeError> {
1320        inline_await_events()
1321            .await_resolution(key, cancel, deadline, &crate::SystemClock)
1322            .await
1323    }
1324
1325    async fn revoke_await_events_for_session(&self, session_id: &str) -> Result<(), RuntimeError> {
1326        inline_await_events().revoke_session(session_id)
1327    }
1328}
1329
1330#[async_trait::async_trait]
1331impl RuntimeEffectController for InlineRuntimeEffectController {
1332    async fn execute_effect(
1333        &self,
1334        envelope: RuntimeEffectEnvelope,
1335        local_executor: RuntimeEffectLocalExecutor<'_>,
1336    ) -> Result<RuntimeEffectOutcome, RuntimeEffectControllerError> {
1337        match envelope.command {
1338            RuntimeEffectCommand::AwaitEvent { key } => {
1339                let (cancellation, deadline, clock) = local_executor.into_await_event_options()?;
1340                let resolution = inline_await_events()
1341                    .await_resolution(&key, cancellation, deadline, clock.as_ref())
1342                    .await
1343                    .map_err(RuntimeEffectControllerError::from)?;
1344                Ok(RuntimeEffectOutcome::AwaitEvent { resolution })
1345            }
1346            RuntimeEffectCommand::Process { command } => {
1347                let execution = local_executor.into_process()?;
1348                let registry = execution.registry;
1349                let process_work_driver = execution.process_work_driver;
1350                let result = tokio::task::spawn(async move {
1351                    Self::execute_process_command(registry, process_work_driver, *command).await
1352                })
1353                .await
1354                .map_err(|err| {
1355                    RuntimeEffectControllerError::new(
1356                        "runtime_effect_process_task_join",
1357                        format!("inline process effect task failed: {err}"),
1358                    )
1359                })??;
1360                Ok(RuntimeEffectOutcome::Process { result })
1361            }
1362            _ => local_executor.execute(envelope).await,
1363        }
1364    }
1365}
1366
1367/// In-process deployment effect host.
1368#[derive(Clone)]
1369pub struct InlineEffectHost {
1370    controller: Arc<dyn RuntimeEffectController>,
1371}
1372
1373impl InlineEffectHost {
1374    pub fn new(controller: Arc<dyn RuntimeEffectController>) -> Self {
1375        Self { controller }
1376    }
1377}
1378
1379impl Default for InlineEffectHost {
1380    fn default() -> Self {
1381        Self::new(Arc::new(InlineRuntimeEffectController))
1382    }
1383}
1384
1385#[async_trait::async_trait]
1386impl AwaitEventResolver for InlineEffectHost {
1387    fn durability_tier(&self) -> crate::DurabilityTier {
1388        self.controller.durability_tier()
1389    }
1390
1391    fn requires_durable_attachment_store(&self) -> bool {
1392        self.controller.requires_durable_attachment_store()
1393    }
1394
1395    fn supports_durable_effects(&self) -> bool {
1396        self.controller.supports_durable_effects()
1397    }
1398
1399    async fn await_event_key(
1400        &self,
1401        scope: &ExecutionScope,
1402        wait: AwaitEventWaitIdentity,
1403    ) -> Result<AwaitEventKey, RuntimeError> {
1404        self.controller.await_event_key(scope, wait).await
1405    }
1406
1407    async fn resolve_await_event(
1408        &self,
1409        key: &AwaitEventKey,
1410        resolution: Resolution,
1411    ) -> Result<ResolveOutcome, RuntimeError> {
1412        self.controller.resolve_await_event(key, resolution).await
1413    }
1414
1415    async fn await_await_event(
1416        &self,
1417        key: &AwaitEventKey,
1418        cancel: CancellationToken,
1419        deadline: Option<Instant>,
1420    ) -> Result<Resolution, RuntimeError> {
1421        self.controller
1422            .await_await_event(key, cancel, deadline)
1423            .await
1424    }
1425
1426    async fn revoke_await_events_for_session(&self, session_id: &str) -> Result<(), RuntimeError> {
1427        self.controller
1428            .revoke_await_events_for_session(session_id)
1429            .await
1430    }
1431}
1432
1433#[async_trait::async_trait]
1434impl EffectHost for InlineEffectHost {
1435    fn scoped<'run>(
1436        &'run self,
1437        scope: ExecutionScope,
1438    ) -> Result<ScopedEffectController<'run>, RuntimeError> {
1439        ScopedEffectController::shared(Arc::clone(&self.controller), scope)
1440    }
1441
1442    fn scoped_static(
1443        &self,
1444        scope: ExecutionScope,
1445    ) -> Result<Option<ScopedEffectController<'static>>, RuntimeError> {
1446        Ok(Some(ScopedEffectController::shared(
1447            Arc::clone(&self.controller),
1448            scope,
1449        )?))
1450    }
1451}
1452
1453impl InlineRuntimeEffectController {
1454    /// Register the process (and any handle grant) into the durable registry.
1455    ///
1456    /// The inline controller no longer runs the process here: the registry's
1457    /// non-terminal row *is* the durable work queue, and the host-owned
1458    /// [`ProcessWorkDriver`](crate::ProcessWorkDriver) is the sole executor.
1459    /// Registering the row is all this path does; the control seam drives the
1460    /// host driver after a successful start.
1461    pub(crate) async fn start_process(
1462        registry: Arc<dyn crate::ProcessRegistry>,
1463        registration: crate::ProcessRegistration,
1464        grant: Option<crate::ProcessStartGrant>,
1465    ) -> Result<ProcessRecord, PluginError> {
1466        let registration_for_record = registration.clone();
1467        let record = registry.register_process(registration_for_record).await?;
1468        if let Some(grant) = grant {
1469            registry
1470                .grant_handle(&grant.session_scope, &registration.id, grant.descriptor)
1471                .await?;
1472        }
1473        Ok(record)
1474    }
1475
1476    pub(crate) async fn request_process_cancel(
1477        &self,
1478        registry: Arc<dyn crate::ProcessRegistry>,
1479        process_id: &str,
1480        reason: Option<String>,
1481    ) -> Result<ProcessRecord, PluginError> {
1482        // Cancellation is a durable signal: the cancel event is what the
1483        // runner-run process observes, so the inline controller appends it and
1484        // no longer tracks an in-process cancellation token.
1485        registry
1486            .append_event(
1487                process_id,
1488                crate::ProcessEventAppendRequest::cancel_requested(process_id, reason.clone()),
1489            )
1490            .await?;
1491        registry
1492            .get_process(process_id)
1493            .await
1494            .ok_or_else(|| PluginError::Session(format!("unknown process `{process_id}`")))
1495    }
1496
1497    async fn execute_process_command(
1498        registry: Arc<dyn crate::ProcessRegistry>,
1499        process_work_driver: Option<crate::ProcessWorkDriver>,
1500        command: ProcessCommand,
1501    ) -> Result<ProcessEffectOutcome, RuntimeEffectControllerError> {
1502        match command {
1503            ProcessCommand::Start {
1504                registration,
1505                grant,
1506                execution_context: _,
1507            } => {
1508                let record = Self::start_process(registry, registration, grant).await?;
1509                if let Some(driver) = process_work_driver.as_ref() {
1510                    driver.claim_and_run_pending("process_start").await?;
1511                }
1512                Ok(ProcessEffectOutcome::Start { record })
1513            }
1514            ProcessCommand::List {
1515                session_scope,
1516                mode,
1517            } => {
1518                let entries = match mode {
1519                    crate::ProcessListMode::Live => {
1520                        registry.list_live_handle_grants(&session_scope).await?
1521                    }
1522                    crate::ProcessListMode::All => {
1523                        registry.list_handle_grants(&session_scope).await?
1524                    }
1525                };
1526                Ok(ProcessEffectOutcome::List { entries })
1527            }
1528            ProcessCommand::Transfer {
1529                from_scope,
1530                to_scope,
1531                process_ids,
1532            } => {
1533                registry
1534                    .transfer_handle_grants(&from_scope, &to_scope, &process_ids)
1535                    .await?;
1536                Ok(ProcessEffectOutcome::Transfer)
1537            }
1538            ProcessCommand::DeleteSession { session_id } => {
1539                let report = registry.delete_session_process_state(&session_id).await?;
1540                Ok(ProcessEffectOutcome::DeleteSession { report })
1541            }
1542            ProcessCommand::Await { process_id } => {
1543                let output = registry.await_process(&process_id).await?;
1544                Ok(ProcessEffectOutcome::Await { output })
1545            }
1546            ProcessCommand::Cancel { process_id, reason } => {
1547                let record = InlineRuntimeEffectController
1548                    .request_process_cancel(registry, &process_id, reason)
1549                    .await?;
1550                Ok(ProcessEffectOutcome::Cancel { record })
1551            }
1552            ProcessCommand::Signal {
1553                process_id,
1554                request,
1555                ..
1556            } => {
1557                let result = registry.append_event(&process_id, request).await?;
1558                Ok(ProcessEffectOutcome::Signal {
1559                    event: result.event,
1560                })
1561            }
1562        }
1563    }
1564}
1565
1566impl std::fmt::Debug for InlineRuntimeEffectController {
1567    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1568        f.debug_struct("InlineRuntimeEffectController").finish()
1569    }
1570}