Skip to main content

multicast_codemode/
codemode.rs

1use std::collections::{HashMap, HashSet};
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use futures_util::{FutureExt as _, StreamExt, stream::FuturesUnordered};
6use multicast::command::RequestContext;
7use multicast::telemetry::opentelemetry::{Context, trace::FutureExt};
8use multicast::tool::{ToolCallControl, ToolEvent, ToolEventSink};
9use serde_json::Value;
10use tokio::sync::{Mutex, Semaphore};
11use tokio_util::sync::CancellationToken;
12
13use crate::{
14    ArtifactStore, CapabilitySnapshot, Clock, CodeExecutor, CodeModeRuntime, Connector,
15    ConnectorDescription, DispatchRequest, DispatchSession, ExecutionEvent, ExecutionHost,
16    ExecutionState, ExecutionStatus, RuntimeStore, SearchOutput, Snippet, SystemClock, ToolContext,
17};
18
19/// Transport context inherited by one Code Mode execution pass.
20#[derive(Clone)]
21pub struct CodeModeRunOptions {
22    /// Tracing context captured at the caller before crossing an actor boundary.
23    pub telemetry_context: Context,
24    /// Named workflow identity for span correlation.
25    pub workflow: Option<crate::WorkflowIdentity>,
26    /// Cooperative cancellation signal for the active pass.
27    pub cancellation: CancellationToken,
28    /// Request metadata inherited by connector calls.
29    pub request: Option<RequestContext>,
30}
31
32impl Default for CodeModeRunOptions {
33    fn default() -> Self {
34        Self {
35            cancellation: CancellationToken::new(),
36            request: None,
37            telemetry_context: Context::current(),
38            workflow: None,
39        }
40    }
41}
42
43struct RuntimeEventSink {
44    runtime: Arc<CodeModeRuntime>,
45    execution_id: String,
46    clock: Arc<dyn Clock>,
47}
48
49#[async_trait]
50impl ToolEventSink for RuntimeEventSink {
51    async fn emit(&self, event: ToolEvent) {
52        let at = self.clock.now_ms();
53        let event = match event {
54            ToolEvent::Progress { message, fraction } => ExecutionEvent::Progress {
55                message,
56                fraction,
57                at,
58            },
59            ToolEvent::Log { level, message } => ExecutionEvent::Log { level, message, at },
60            ToolEvent::Chunk { data } => ExecutionEvent::Chunk { data, at },
61        };
62        let _ = self.runtime.event(&self.execution_id, event).await;
63    }
64}
65
66/// Generic Code Mode lifecycle over interchangeable execution and storage adapters.
67pub struct CodeMode {
68    runtime: Arc<CodeModeRuntime>,
69    executor: Box<dyn CodeExecutor>,
70    connectors: Vec<Arc<dyn Connector>>,
71    clock: Arc<dyn Clock>,
72    contexts: Mutex<HashMap<String, ToolContext>>,
73    pass_gates: Mutex<HashMap<String, Arc<Semaphore>>>,
74    active_rollbacks: Mutex<HashSet<String>>,
75}
76
77impl CodeMode {
78    /// Creates a native Code Mode runtime using the system clock.
79    pub fn new(
80        store: Arc<dyn RuntimeStore>,
81        executor: impl CodeExecutor + 'static,
82        connectors: Vec<Arc<dyn Connector>>,
83    ) -> Self {
84        Self::with_clock(store, executor, connectors, SystemClock)
85    }
86
87    /// Creates Code Mode with an explicit oversized-value artifact store.
88    pub fn with_artifact_store(
89        store: Arc<dyn RuntimeStore>,
90        artifacts: Arc<dyn ArtifactStore>,
91        executor: impl CodeExecutor + 'static,
92        connectors: Vec<Arc<dyn Connector>>,
93    ) -> Self {
94        Self {
95            runtime: Arc::new(CodeModeRuntime::with_artifacts(store, artifacts)),
96            executor: Box::new(executor),
97            connectors,
98            clock: Arc::new(SystemClock),
99            contexts: Mutex::new(HashMap::new()),
100            pass_gates: Mutex::new(HashMap::new()),
101            active_rollbacks: Mutex::new(HashSet::new()),
102        }
103    }
104
105    /// Creates Code Mode with an explicit platform clock.
106    pub fn with_clock(
107        store: Arc<dyn RuntimeStore>,
108        executor: impl CodeExecutor + 'static,
109        connectors: Vec<Arc<dyn Connector>>,
110        clock: impl Clock + 'static,
111    ) -> Self {
112        Self {
113            runtime: Arc::new(CodeModeRuntime::new(store)),
114            executor: Box::new(executor),
115            connectors,
116            clock: Arc::new(clock),
117            contexts: Mutex::new(HashMap::new()),
118            pass_gates: Mutex::new(HashMap::new()),
119            active_rollbacks: Mutex::new(HashSet::new()),
120        }
121    }
122
123    /// Creates Code Mode with explicit platform clock and artifact storage.
124    pub fn with_clock_and_artifact_store(
125        store: Arc<dyn RuntimeStore>,
126        artifacts: Arc<dyn ArtifactStore>,
127        executor: impl CodeExecutor + 'static,
128        connectors: Vec<Arc<dyn Connector>>,
129        clock: impl Clock + 'static,
130    ) -> Self {
131        Self {
132            runtime: Arc::new(CodeModeRuntime::with_artifacts(store, artifacts)),
133            executor: Box::new(executor),
134            connectors,
135            clock: Arc::new(clock),
136            contexts: Mutex::new(HashMap::new()),
137            pass_gates: Mutex::new(HashMap::new()),
138            active_rollbacks: Mutex::new(HashSet::new()),
139        }
140    }
141
142    /// Sets host-owned finite limits before sharing this runtime or starting executions.
143    pub fn with_workflow_limits(mut self, limits: crate::WorkflowLimits) -> Result<Self, String> {
144        limits.check()?;
145        Arc::get_mut(&mut self.runtime)
146            .ok_or("Workflow limits must be configured before sharing the runtime")?
147            .workflow_limits = limits;
148        Ok(self)
149    }
150
151    /// Returns the host defaults used when admitting new workflow roots.
152    pub fn workflow_limits(&self) -> &crate::WorkflowLimits {
153        &self.runtime.workflow_limits
154    }
155
156    /// Returns the portable runtime for approvals, history, and snippets.
157    pub fn runtime(&self) -> Arc<CodeModeRuntime> {
158        Arc::clone(&self.runtime)
159    }
160
161    /// Returns model-facing JavaScript declarations and connector guidance.
162    pub async fn instructions(&self) -> Result<String, String> {
163        let mut descriptions = Vec::new();
164        for connector in &self.connectors {
165            descriptions.push(connector.describe().await?);
166        }
167        let mut sections = descriptions
168            .iter()
169            .filter_map(|connector| {
170                connector
171                    .instructions
172                    .as_ref()
173                    .map(|instructions| format!("## {}\n\n{instructions}", connector.name))
174            })
175            .collect::<Vec<_>>();
176        sections.extend(descriptions.iter().map(crate::generate_types));
177        sections.push(crate::workflow_api::types());
178        Ok(sections.join("\n\n"))
179    }
180
181    /// Searches current connector methods and saved snippets.
182    pub async fn search(&self, query: &str) -> Result<SearchOutput, String> {
183        let mut descriptions = Vec::new();
184        for connector in &self.connectors {
185            descriptions.push(connector.describe().await?);
186        }
187        let snippets = self
188            .runtime
189            .snippets()
190            .await
191            .map_err(|error| error.to_string())?;
192        Ok(crate::search(query, &descriptions, &snippets))
193    }
194
195    /// Returns one execution by identifier.
196    pub async fn execution(&self, execution_id: &str) -> Result<ExecutionState, String> {
197        self.require(execution_id).await
198    }
199
200    /// Returns one bounded execution snapshot with artifact references intact.
201    pub async fn execution_snapshot(&self, execution_id: &str) -> Result<ExecutionState, String> {
202        self.runtime
203            .execution_snapshot(execution_id)
204            .await
205            .map_err(|error| error.to_string())?
206            .ok_or_else(|| format!("Execution \"{execution_id}\" not found"))
207    }
208
209    /// Returns one oversized value owned by an execution.
210    pub async fn artifact(&self, execution_id: &str, artifact_id: &str) -> Result<Value, String> {
211        self.runtime
212            .artifact(execution_id, artifact_id)
213            .await
214            .map_err(|error| error.to_string())?
215            .ok_or_else(|| {
216                format!("Artifact \"{artifact_id}\" not found for execution \"{execution_id}\"")
217            })
218    }
219
220    /// Saves a completed execution as a named snippet stamped with this host's clock.
221    pub async fn save_snippet(
222        &self,
223        name: &str,
224        description: &str,
225        execution_id: &str,
226        input_schema: Option<Value>,
227    ) -> Result<Snippet, String> {
228        self.runtime
229            .save_snippet(
230                name,
231                description,
232                execution_id,
233                input_schema,
234                self.clock.now_ms(),
235            )
236            .await
237            .map_err(|error| error.to_string())
238    }
239
240    /// Publishes callable source without running it; each named run supplies fresh input.
241    /// Syntax and connector calls are checked when the program runs.
242    pub async fn publish_snippet(
243        &self,
244        name: &str,
245        description: &str,
246        code: &str,
247        input_schema: Option<Value>,
248    ) -> Result<Snippet, String> {
249        self.runtime
250            .publish_snippet(Snippet {
251                name: name.into(),
252                description: description.into(),
253                code: code.into(),
254                saved_at: self.clock.now_ms(),
255                input_schema,
256                connectors: self
257                    .connectors
258                    .iter()
259                    .map(|connector| connector.name().to_string())
260                    .collect(),
261            })
262            .await
263            .map_err(|error| error.to_string())
264    }
265
266    /// Lists saved snippets in stable name order.
267    pub async fn snippets(&self) -> Result<Vec<Snippet>, String> {
268        self.runtime
269            .snippets()
270            .await
271            .map_err(|error| error.to_string())
272    }
273
274    /// Deletes one saved snippet, returning whether it existed.
275    pub async fn delete_snippet(&self, name: &str) -> Result<bool, String> {
276        self.runtime
277            .delete_snippet(name)
278            .await
279            .map_err(|error| error.to_string())
280    }
281
282    /// Returns ordered retained events for one execution.
283    pub async fn events(&self, execution_id: &str) -> Result<Vec<ExecutionEvent>, String> {
284        Ok(self.require(execution_id).await?.events)
285    }
286
287    /// Cancels a running or paused execution.
288    pub async fn cancel(&self, execution_id: &str) -> Result<ExecutionState, String> {
289        self.cancel_descendants(execution_id).await?;
290        let previous = self.require(execution_id).await?;
291        let now = self.clock.now_ms();
292        let pass_active = self.contexts.lock().await.contains_key(execution_id);
293        if let Some(context) = self.contexts.lock().await.get(execution_id) {
294            context.control.cancellation.cancel();
295        }
296        let changed = self
297            .runtime
298            .cancel(execution_id, now)
299            .await
300            .map_err(|error| error.to_string())?;
301        if changed {
302            crate::telemetry::approval(&previous, now, "cancelled");
303        }
304        if changed && !pass_active {
305            self.notify_execution_end(execution_id, "cancelled").await;
306        }
307        self.require(execution_id).await
308    }
309
310    /// Names every connector without contacting any of them.
311    ///
312    /// The capability snapshot and the program's bindings both need to know which
313    /// namespaces exist, and nothing more. Building them from `describe` meant
314    /// connecting to every configured server before the program ran; a name-only
315    /// description carries exactly what they use, and the tools are resolved per
316    /// namespace on first call.
317    fn namespace_stubs(&self) -> Vec<ConnectorDescription> {
318        self.connectors
319            .iter()
320            .map(|connector| ConnectorDescription {
321                name: connector.name().to_string(),
322                instructions: None,
323                tools: Vec::new(),
324            })
325            .collect()
326    }
327
328    /// Creates a durable running execution without driving its first pass.
329    pub async fn start(&self, code: &str) -> Result<ExecutionState, String> {
330        self.start_retained(code, None, None).await
331    }
332
333    /// Creates a running execution with an optional history retention duration.
334    pub async fn start_retained(
335        &self,
336        code: &str,
337        retention_ms: Option<u64>,
338        execution_id: Option<String>,
339    ) -> Result<ExecutionState, String> {
340        let capabilities = CapabilitySnapshot::new(self.namespace_stubs())?;
341        let now = self.clock.now_ms();
342        let id = self
343            .runtime
344            .begin_retained(
345                code,
346                capabilities,
347                now,
348                retention_ms.map(|duration| now.saturating_add(duration)),
349                execution_id,
350            )
351            .await
352            .map_err(|error| error.to_string())?;
353        self.require(&id).await
354    }
355
356    /// Starts and drives a new execution until it completes, fails, or pauses.
357    pub async fn execute(&self, code: &str) -> Result<ExecutionState, String> {
358        self.execute_with(code, CodeModeRunOptions::default()).await
359    }
360
361    /// Starts and drives a new execution with transport request context.
362    pub async fn execute_with(
363        &self,
364        code: &str,
365        options: CodeModeRunOptions,
366    ) -> Result<ExecutionState, String> {
367        let state = self.start(code).await?;
368        self.drive_with(&state.id, options).await
369    }
370
371    /// Commits a recovery resume before a host schedules its detached pass.
372    ///
373    /// Running executions are returned unchanged. Paused executions must have no
374    /// pending approval; terminal executions cannot be resumed.
375    pub async fn prepare_resume(&self, execution_id: &str) -> Result<ExecutionState, String> {
376        let state = self.require(execution_id).await?;
377        match state.status {
378            ExecutionStatus::Running => Ok(state),
379            ExecutionStatus::Paused => self
380                .runtime
381                .resume(execution_id, self.clock.now_ms())
382                .await
383                .map_err(|error| error.to_string()),
384            _ => Err("Only interrupted running or recovery-paused executions can resume".into()),
385        }
386    }
387
388    /// Resumes a paused execution and drives the next replay pass.
389    pub async fn resume(&self, execution_id: &str) -> Result<ExecutionState, String> {
390        self.resume_with(execution_id, CodeModeRunOptions::default())
391            .await
392    }
393
394    /// Resumes a paused execution with transport request context.
395    pub async fn resume_with(
396        &self,
397        execution_id: &str,
398        options: CodeModeRunOptions,
399    ) -> Result<ExecutionState, String> {
400        self.runtime
401            .resume(execution_id, self.clock.now_ms())
402            .await
403            .map_err(|error| error.to_string())?;
404        self.drive_with(execution_id, options).await
405    }
406
407    /// Approves a pending action and resumes only if this call won the race.
408    pub async fn approve(&self, execution_id: &str, seq: u64) -> Result<ExecutionState, String> {
409        self.approve_with(execution_id, seq, CodeModeRunOptions::default())
410            .await
411    }
412
413    /// Approves a pending action and resumes with transport request context.
414    pub async fn approve_with(
415        &self,
416        execution_id: &str,
417        seq: u64,
418        options: CodeModeRunOptions,
419    ) -> Result<ExecutionState, String> {
420        if !self
421            .approve_pending(execution_id, seq)
422            .with_context(options.telemetry_context.clone())
423            .await?
424        {
425            return self.require(execution_id).await;
426        }
427        self.drive_with(execution_id, options).await
428    }
429
430    /// Commits a pending approval, returning whether this caller owns its next pass.
431    /// The winner must drive the execution using its current transport authority.
432    pub async fn approve_pending(&self, execution_id: &str, seq: u64) -> Result<bool, String> {
433        let previous = self.require(execution_id).await?;
434        let now = self.clock.now_ms();
435        let changed = self
436            .runtime
437            .approve(execution_id, seq, now)
438            .await
439            .map_err(|error| error.to_string())?;
440        if changed {
441            crate::telemetry::approval(&previous, now, "approved");
442        }
443        Ok(changed)
444    }
445
446    /// Rejects a pending action and notifies connector lifecycle hooks.
447    pub async fn reject(&self, execution_id: &str, seq: u64) -> Result<ExecutionState, String> {
448        let previous = self.require(execution_id).await?;
449        let now = self.clock.now_ms();
450        if self
451            .runtime
452            .reject(execution_id, seq, now)
453            .await
454            .map_err(|error| error.to_string())?
455        {
456            crate::telemetry::approval(&previous, now, "rejected");
457            self.notify_execution_end(execution_id, "rejected").await;
458        }
459        if let Some((root, _, _)) = self.runtime.workflow_nodes(execution_id).await?
460            && root != execution_id
461        {
462            self.drive_if_idle(&root, CodeModeRunOptions::default())
463                .await?;
464        }
465        self.require(execution_id).await
466    }
467
468    /// Compensates applied connector actions in reverse order.
469    pub async fn rollback(&self, execution_id: &str) -> Result<ExecutionState, String> {
470        {
471            let mut active = self.active_rollbacks.lock().await;
472            if !active.insert(execution_id.to_string()) {
473                return Err(format!(
474                    "Execution \"{execution_id}\" is already rolling back"
475                ));
476            }
477        }
478        let result = self.rollback_inner(execution_id).await;
479        self.active_rollbacks.lock().await.remove(execution_id);
480        result
481    }
482
483    async fn rollback_inner(&self, execution_id: &str) -> Result<ExecutionState, String> {
484        for action in self
485            .runtime
486            .actions_to_revert(execution_id)
487            .await
488            .map_err(|error| error.to_string())?
489        {
490            let connector = self
491                .connector(&action.connector)
492                .await?
493                .ok_or_else(|| format!("Connector \"{}\" not found", action.connector))?;
494            if !connector
495                .revert(
496                    &action.method,
497                    action.arguments,
498                    action.result.unwrap_or(Value::Null),
499                    &ToolContext {
500                        call: None,
501                        execution_id: execution_id.to_string(),
502                        control: Default::default(),
503                        request: None,
504                        telemetry_context: multicast::telemetry::opentelemetry::Context::current(),
505                    },
506                )
507                .await?
508            {
509                return Err(format!(
510                    "{}.{} did not compensate step {}",
511                    action.connector, action.method, action.seq
512                ));
513            }
514            self.runtime
515                .mark_reverted(execution_id, action.seq, self.clock.now_ms())
516                .await
517                .map_err(|error| error.to_string())?;
518        }
519        self.runtime
520            .finish_rollback(execution_id, self.clock.now_ms())
521            .await
522            .map_err(|error| error.to_string())?;
523        self.notify_execution_end(execution_id, "rolled_back").await;
524        self.require(execution_id).await
525    }
526
527    /// Expires stale live executions and releases connector resources.
528    pub async fn expire(&self, max_age_ms: u64) -> Result<Vec<String>, String> {
529        let ids = self
530            .runtime
531            .expire(self.clock.now_ms(), max_age_ms)
532            .await
533            .map_err(|error| error.to_string())?;
534        for id in &ids {
535            let status = self.require(id).await?.status;
536            self.notify_execution_end(
537                id,
538                if status == ExecutionStatus::Rejected {
539                    "rejected"
540                } else {
541                    "error"
542                },
543            )
544            .await;
545        }
546        Ok(ids)
547    }
548
549    /// Handles one program-to-host dispatch request.
550    pub async fn dispatch(&self, request: DispatchRequest) -> Result<Value, String> {
551        match request {
552            DispatchRequest::LoadCheckpoint { execution_id } => {
553                let _ = self.active_context(&execution_id).await?;
554                serde_json::to_value(
555                    self.runtime
556                        .checkpoint(&execution_id)
557                        .await
558                        .map_err(|e| e.to_string())?,
559                )
560                .map_err(|e| e.to_string())
561            }
562            DispatchRequest::SaveCheckpoint {
563                execution_id,
564                checkpoint,
565            } => {
566                let _ = self.active_context(&execution_id).await?;
567                self.runtime
568                    .save_checkpoint(&execution_id, &checkpoint)
569                    .await
570                    .map_err(|e| e.to_string())?;
571                Ok(serde_json::json!({"ok": true}))
572            }
573            DispatchRequest::Call {
574                execution_id,
575                seq,
576                connector,
577                method,
578                arguments,
579            } => {
580                let session = self.session(&execution_id).await?;
581                serde_json::to_value(
582                    session
583                        .call_at(seq, &connector, &method, arguments, self.clock.now_ms())
584                        .await,
585                )
586                .map_err(|error| error.to_string())
587            }
588            DispatchRequest::BeginStep {
589                execution_id,
590                seq,
591                name,
592            } => {
593                let session = self.session(&execution_id).await?;
594                serde_json::to_value(
595                    session
596                        .begin_step_at(seq, &name, self.clock.now_ms())
597                        .await
598                        .map_err(|error| error.to_string())?,
599                )
600                .map_err(|error| error.to_string())
601            }
602            DispatchRequest::RecordStep {
603                execution_id,
604                seq,
605                result,
606            } => {
607                let _ = self.active_context(&execution_id).await?;
608                self.runtime
609                    .record_result(&execution_id, seq, result, self.clock.now_ms())
610                    .await
611                    .map_err(|error| error.to_string())?;
612                Ok(serde_json::json!({ "ok": true }))
613            }
614        }
615    }
616
617    /// Drives one running execution pass with transport request context.
618    pub async fn drive_with(
619        &self,
620        execution_id: &str,
621        options: CodeModeRunOptions,
622    ) -> Result<ExecutionState, String> {
623        let root = self
624            .runtime
625            .workflow_nodes(execution_id)
626            .await?
627            .map(|n| n.0)
628            .unwrap_or_else(|| execution_id.to_string());
629        let gate = self.pass_gate(&format!("tree:{root}")).await;
630        let _permit = gate
631            .acquire_owned()
632            .await
633            .map_err(|_| "Code Mode execution gate closed".to_string())?;
634        self.drive_tree(&root, options).await?;
635        self.require(execution_id).await
636    }
637
638    async fn pass_gate(&self, execution_id: &str) -> Arc<Semaphore> {
639        Arc::clone(
640            self.pass_gates
641                .lock()
642                .await
643                .entry(execution_id.to_string())
644                .or_insert_with(|| Arc::new(Semaphore::new(1))),
645        )
646    }
647
648    /// Drives an interrupted running execution without queueing behind an active pass.
649    /// Paused approvals and terminal executions remain unchanged.
650    pub async fn drive_if_idle(
651        &self,
652        execution_id: &str,
653        options: CodeModeRunOptions,
654    ) -> Result<ExecutionState, String> {
655        let root = self
656            .runtime
657            .workflow_nodes(execution_id)
658            .await?
659            .map(|n| n.0)
660            .unwrap_or_else(|| execution_id.to_string());
661        let Ok(_permit) = self
662            .pass_gate(&format!("tree:{root}"))
663            .await
664            .try_acquire_owned()
665        else {
666            return self.require(execution_id).await;
667        };
668        self.drive_tree(&root, options).await?;
669        self.require(execution_id).await
670    }
671
672    async fn drive_tree(&self, root: &str, options: CodeModeRunOptions) -> Result<(), String> {
673        let result = self.drive_tree_inner(root, options.clone()).await;
674        if let Err(error) = &result {
675            options.cancellation.cancel();
676            self.runtime
677                .fail_tree(root, error.clone(), self.clock.now_ms())
678                .await
679                .map_err(|e| e.to_string())?;
680            if let Some((_, _, nodes)) = self.runtime.workflow_nodes(root).await? {
681                for (id, _) in nodes {
682                    if let Some(context) = self.contexts.lock().await.remove(&id) {
683                        context.control.cancellation.cancel();
684                    }
685                    if id != root
686                        && self
687                            .runtime
688                            .execution(&id)
689                            .await
690                            .map_err(|e| e.to_string())?
691                            .is_some_and(|s| {
692                                matches!(
693                                    s.status,
694                                    ExecutionStatus::Running | ExecutionStatus::Paused
695                                )
696                            })
697                    {
698                        self.runtime
699                            .cancel(&id, self.clock.now_ms())
700                            .await
701                            .map_err(|e| e.to_string())?;
702                    }
703                }
704            }
705        }
706        result
707    }
708    async fn drive_tree_inner(
709        &self,
710        root: &str,
711        options: CodeModeRunOptions,
712    ) -> Result<(), String> {
713        type TreePlan = Result<(usize, Vec<(String, Option<String>)>), String>;
714        enum Event {
715            Deadline,
716            Pass(String, Box<Result<ExecutionState, String>>),
717            Plan(TreePlan),
718        }
719        let mut active = HashSet::new();
720        let mut events: FuturesUnordered<futures_util::future::LocalBoxFuture<'_, Event>> =
721            FuturesUnordered::new();
722        if let Some(deadline) = self
723            .runtime
724            .workflow_admit_root(root, self.clock.now_ms())
725            .await?
726        {
727            events.push(
728                async move {
729                    self.clock
730                        .sleep(deadline.saturating_sub(self.clock.now_ms()))
731                        .await;
732                    Event::Deadline
733                }
734                .boxed_local(),
735            );
736        }
737        let mut planning = false;
738        let mut dirty = true;
739        let mut failed = Vec::new();
740        loop {
741            if dirty && !planning {
742                let active = active.clone();
743                let failed = std::mem::take(&mut failed);
744                events.push(
745                    async move { Event::Plan(self.plan_tree(root, &active, failed).await) }
746                        .boxed_local(),
747                );
748                planning = true;
749                dirty = false;
750            }
751            let Some(event) = events.next().await else {
752                break;
753            };
754            match event {
755                Event::Deadline => {
756                    dirty = true;
757                }
758                Event::Pass(id, result) => {
759                    active.remove(&id);
760                    let state = match *result {
761                        Ok(state) => state,
762                        Err(error) => {
763                            if self.require(&id).await?.status == ExecutionStatus::Running {
764                                self.runtime
765                                    .fail(&id, error, Vec::new(), self.clock.now_ms())
766                                    .await
767                                    .map_err(|e| e.to_string())?;
768                            }
769                            self.require(&id).await?
770                        }
771                    };
772                    if matches!(
773                        state.status,
774                        ExecutionStatus::Error
775                            | ExecutionStatus::Rejected
776                            | ExecutionStatus::Cancelled
777                    ) {
778                        failed.push(id);
779                    }
780                    dirty = true;
781                }
782                Event::Plan(result) => {
783                    planning = false;
784                    let (limit, nodes) = result?;
785                    if nodes.is_empty() && active.is_empty() && !dirty {
786                        break;
787                    }
788                    for (id, parent) in nodes {
789                        if active.len() >= limit {
790                            break;
791                        }
792                        if !active.insert(id.clone()) {
793                            continue;
794                        }
795                        let mut pass_options = options.clone();
796                        pass_options.cancellation = options.cancellation.child_token();
797                        events.push(
798                            async move {
799                                let result = async {
800                                    if let Some(parent) = parent {
801                                        for connector in &self.connectors {
802                                            connector
803                                                .admit_child(
804                                                    &parent,
805                                                    &id,
806                                                    pass_options.request.as_ref(),
807                                                )
808                                                .await?;
809                                        }
810                                    }
811                                    self.drive_pass(&id, pass_options).await
812                                }
813                                .await;
814                                Event::Pass(id, Box::new(result))
815                            }
816                            .boxed_local(),
817                        );
818                    }
819                }
820            }
821        }
822        self.runtime.workflow_sweep().await?;
823        Ok(())
824    }
825
826    async fn plan_tree(
827        &self,
828        root: &str,
829        active: &HashSet<String>,
830        failed: Vec<String>,
831    ) -> Result<(usize, Vec<(String, Option<String>)>), String> {
832        for id in failed {
833            self.cancel_descendants(&id).await?;
834        }
835        if let Some((_, _, nodes)) = self.runtime.workflow_nodes(root).await? {
836            for (id, _) in nodes {
837                let state = self.require(&id).await.map_err(|_| {
838                    "WORKFLOW_BOUND_CHILD_MISSING: reconciliation required".to_string()
839                })?;
840                if matches!(
841                    state.status,
842                    ExecutionStatus::Error | ExecutionStatus::Rejected | ExecutionStatus::Cancelled
843                ) {
844                    if let Some(context) = self.contexts.lock().await.get(&id) {
845                        context.control.cancellation.cancel();
846                    }
847                    self.cancel_descendants(&id).await?;
848                }
849            }
850        }
851        if let Err(error) = self
852            .runtime
853            .workflow_deadline(root, self.clock.now_ms())
854            .await
855        {
856            self.runtime
857                .workflow_wake(root, self.clock.now_ms())
858                .await?;
859            self.runtime
860                .fail_tree(root, error, self.clock.now_ms())
861                .await
862                .map_err(|e| e.to_string())?;
863            self.cancel_descendants(root).await?;
864            return Ok((1, Vec::new()));
865        }
866        let (_, limit, nodes) = self.runtime.workflow_nodes(root).await?.unwrap_or((
867            root.to_string(),
868            1,
869            vec![(root.to_string(), None)],
870        ));
871        let mut runnable = Vec::new();
872        for (id, parent) in nodes {
873            let state = self.require(&id).await?;
874            if let Some(wait) = &state.workflow_wait {
875                let mut all = true;
876                let mut failed = false;
877                for child in &wait.children {
878                    let child = self.require(child).await.map_err(|_| {
879                        "WORKFLOW_BOUND_CHILD_MISSING: reconciliation required".to_string()
880                    })?;
881                    if matches!(
882                        child.status,
883                        ExecutionStatus::Running | ExecutionStatus::Paused
884                    ) {
885                        all = false;
886                    } else if child.status != ExecutionStatus::Completed {
887                        failed = true;
888                    }
889                }
890                if all || (!wait.settle && failed) {
891                    self.runtime.workflow_wake(&id, self.clock.now_ms()).await?;
892                }
893            }
894            if !active.contains(&id) && self.require(&id).await?.status == ExecutionStatus::Running
895            {
896                runnable.push((id, parent));
897            }
898        }
899        Ok((limit, runnable))
900    }
901
902    async fn cancel_descendants(&self, id: &str) -> Result<(), String> {
903        let Some((_, _, nodes)) = self.runtime.workflow_nodes(id).await? else {
904            return Ok(());
905        };
906        let mut descendants = HashSet::from([id.to_string()]);
907        loop {
908            let before = descendants.len();
909            for (child, parent) in &nodes {
910                if parent.as_ref().is_some_and(|p| descendants.contains(p)) {
911                    descendants.insert(child.clone());
912                }
913            }
914            if descendants.len() == before {
915                break;
916            }
917        }
918        descendants.remove(id);
919        for child in descendants {
920            if let Some(context) = self.contexts.lock().await.get(&child) {
921                context.control.cancellation.cancel();
922            }
923            let state = self.require(&child).await?;
924            if matches!(
925                state.status,
926                ExecutionStatus::Running | ExecutionStatus::Paused
927            ) {
928                self.runtime
929                    .cancel(&child, self.clock.now_ms())
930                    .await
931                    .map_err(|e| e.to_string())?;
932                self.notify_execution_end(&child, "cancelled").await;
933            }
934        }
935        Ok(())
936    }
937
938    async fn drive_pass(
939        &self,
940        execution_id: &str,
941        options: CodeModeRunOptions,
942    ) -> Result<ExecutionState, String> {
943        let state = self.require(execution_id).await?;
944        if matches!(
945            state.status,
946            ExecutionStatus::Completed
947                | ExecutionStatus::Error
948                | ExecutionStatus::Rejected
949                | ExecutionStatus::RolledBack
950                | ExecutionStatus::Cancelled
951        ) {
952            return Ok(state);
953        }
954        let parent = options.telemetry_context.clone();
955        async {
956            let workflow = state
957                .trace
958                .as_ref()
959                .and_then(|trace| trace.workflow.clone())
960                .or(options.workflow.clone());
961            let mut observation = crate::telemetry::Observation::pass(&state, workflow.as_ref());
962            if let Some((root, parent, definition)) =
963                self.runtime.workflow_lineage(execution_id).await?
964            {
965                observation.lineage(&root, parent.as_deref(), definition.as_ref());
966            }
967            if let Some(trace) = observation.trace(workflow) {
968                self.runtime
969                    .record_trace(execution_id, trace)
970                    .await
971                    .map_err(|error| error.to_string())?;
972            }
973            let mut options = options;
974            options.telemetry_context = observation.context();
975            let cancellation = options.cancellation.clone();
976            let result = self
977                .drive_pass_inner(execution_id, state, options)
978                .with_context(observation.context())
979                .await;
980            observation.finish(if cancellation.is_cancelled() {
981                "cancelled"
982            } else {
983                result
984                    .as_ref()
985                    .map(|state| crate::telemetry::outcome(state.status))
986                    .unwrap_or("error")
987            });
988            result
989        }
990        .with_context(parent)
991        .await
992    }
993
994    async fn drive_pass_inner(
995        &self,
996        execution_id: &str,
997        state: ExecutionState,
998        options: CodeModeRunOptions,
999    ) -> Result<ExecutionState, String> {
1000        let context = self.context(execution_id, options);
1001        let cancellation = context.control.cancellation.clone();
1002        self.contexts
1003            .lock()
1004            .await
1005            .insert(execution_id.to_string(), context.clone());
1006        let session = match self.session_with_context(execution_id, context).await {
1007            Ok(session) => session,
1008            Err(error) => {
1009                self.contexts.lock().await.remove(execution_id);
1010                return Err(error);
1011            }
1012        };
1013        let descriptions = session.descriptions();
1014        let execution = self.executor.execute(
1015            &state.code,
1016            &descriptions,
1017            execution_id,
1018            Arc::new(ExecutionHost::new(
1019                Arc::clone(&session),
1020                Arc::clone(&self.clock),
1021            )),
1022        );
1023        tokio::pin!(execution);
1024        let response = tokio::select! {
1025            _ = cancellation.cancelled() => None,
1026            response = &mut execution => Some(response),
1027        };
1028        self.contexts.lock().await.remove(execution_id);
1029        let Some(response) = response else {
1030            self.runtime
1031                .cancel(execution_id, self.clock.now_ms())
1032                .await
1033                .map_err(|error| error.to_string())?;
1034            session.pass_ended("cancelled").await;
1035            session.execution_ended("cancelled").await;
1036            return self.require(execution_id).await;
1037        };
1038        let response = match response {
1039            Ok(response) => response,
1040            Err(error) => {
1041                self.runtime
1042                    .fail(execution_id, error, Vec::new(), self.clock.now_ms())
1043                    .await
1044                    .map_err(|error| error.to_string())?;
1045                session.pass_ended("error").await;
1046                session.execution_ended("error").await;
1047                return self.require(execution_id).await;
1048            }
1049        };
1050        let current = self.require(execution_id).await?;
1051        if current.status == ExecutionStatus::Paused {
1052            session.pass_ended("paused").await;
1053            return Ok(current);
1054        }
1055        if current.status == ExecutionStatus::Error {
1056            session.pass_ended("error").await;
1057            session.execution_ended("error").await;
1058            return Ok(current);
1059        }
1060        if current.status == ExecutionStatus::Cancelled {
1061            session.pass_ended("cancelled").await;
1062            session.execution_ended("cancelled").await;
1063            return Ok(current);
1064        }
1065        if let Some(error) = response.error {
1066            self.runtime
1067                .fail(execution_id, error, response.logs, self.clock.now_ms())
1068                .await
1069                .map_err(|error| error.to_string())?;
1070            session.pass_ended("error").await;
1071            session.execution_ended("error").await;
1072        } else {
1073            let value = response.result.unwrap_or(Value::Null);
1074            if let Err(error) = self.runtime.workflow_output(execution_id, &value).await {
1075                self.runtime
1076                    .fail(execution_id, error, response.logs, self.clock.now_ms())
1077                    .await
1078                    .map_err(|e| e.to_string())?;
1079                session.pass_ended("error").await;
1080                session.execution_ended("error").await;
1081                return self.require(execution_id).await;
1082            }
1083            match self
1084                .runtime
1085                .workflow_finish(execution_id, self.clock.now_ms())
1086                .await
1087            {
1088                Ok(true) => {
1089                    session.pass_ended("paused").await;
1090                    return self.require(execution_id).await;
1091                }
1092                Err(error) => {
1093                    self.runtime
1094                        .fail(execution_id, error, response.logs, self.clock.now_ms())
1095                        .await
1096                        .map_err(|e| e.to_string())?;
1097                    session.pass_ended("error").await;
1098                    session.execution_ended("error").await;
1099                    return self.require(execution_id).await;
1100                }
1101                Ok(false) => {}
1102            }
1103            self.runtime
1104                .complete(execution_id, value, response.logs, self.clock.now_ms())
1105                .await
1106                .map_err(|error| error.to_string())?;
1107            session.pass_ended("completed").await;
1108            session.execution_ended("completed").await;
1109        }
1110        self.require(execution_id).await
1111    }
1112
1113    async fn session(&self, execution_id: &str) -> Result<Arc<DispatchSession>, String> {
1114        let context = self.active_context(execution_id).await?;
1115        self.session_with_context(execution_id, context).await
1116    }
1117
1118    async fn active_context(&self, execution_id: &str) -> Result<ToolContext, String> {
1119        self.contexts
1120            .lock()
1121            .await
1122            .get(execution_id)
1123            .cloned()
1124            .ok_or_else(|| format!("Execution \"{execution_id}\" does not have an active pass"))
1125    }
1126
1127    async fn session_with_context(
1128        &self,
1129        execution_id: &str,
1130        context: ToolContext,
1131    ) -> Result<Arc<DispatchSession>, String> {
1132        let state = self.require(execution_id).await?;
1133        let descriptions = match state.capabilities {
1134            Some(capabilities) => capabilities.connectors,
1135            None => self.namespace_stubs(),
1136        };
1137        Ok(Arc::new(
1138            DispatchSession::new_with_descriptions_and_context(
1139                Arc::clone(&self.runtime),
1140                context,
1141                self.connectors.clone(),
1142                descriptions,
1143            )
1144            .await?,
1145        ))
1146    }
1147
1148    fn context(&self, execution_id: &str, options: CodeModeRunOptions) -> ToolContext {
1149        ToolContext {
1150            call: None,
1151            execution_id: execution_id.to_string(),
1152            control: ToolCallControl {
1153                cancellation: options.cancellation,
1154                events: Some(Arc::new(RuntimeEventSink {
1155                    runtime: Arc::clone(&self.runtime),
1156                    execution_id: execution_id.to_string(),
1157                    clock: Arc::clone(&self.clock),
1158                })),
1159            },
1160            request: options.request,
1161            telemetry_context: options.telemetry_context,
1162        }
1163    }
1164
1165    async fn require(&self, execution_id: &str) -> Result<ExecutionState, String> {
1166        self.runtime
1167            .execution(execution_id)
1168            .await
1169            .map_err(|error| error.to_string())?
1170            .ok_or_else(|| format!("Execution \"{execution_id}\" not found"))
1171    }
1172
1173    async fn connector(&self, name: &str) -> Result<Option<&Arc<dyn Connector>>, String> {
1174        for connector in &self.connectors {
1175            if connector.describe().await?.name == name {
1176                return Ok(Some(connector));
1177            }
1178        }
1179        Ok(None)
1180    }
1181
1182    async fn notify_execution_end(&self, execution_id: &str, status: &str) {
1183        for connector in &self.connectors {
1184            connector.execution_ended(execution_id, status).await;
1185        }
1186    }
1187}
1188
1189#[cfg(test)]
1190mod tests {
1191    use std::sync::atomic::{AtomicUsize, Ordering};
1192
1193    use serde_json::json;
1194    use tokio::sync::Notify;
1195
1196    use super::*;
1197    use crate::{
1198        ConnectorDescription, ConnectorTool, ExecuteResult, MemoryStore, ReplayPolicy,
1199        ToolAnnotations, ToolPolicy,
1200    };
1201
1202    struct TestConnector {
1203        calls: AtomicUsize,
1204        ended: Mutex<Vec<String>>,
1205        started: Notify,
1206        release: Notify,
1207        blocked: bool,
1208    }
1209
1210    impl TestConnector {
1211        fn new(blocked: bool) -> Self {
1212            Self {
1213                calls: AtomicUsize::new(0),
1214                ended: Mutex::new(Vec::new()),
1215                started: Notify::new(),
1216                release: Notify::new(),
1217                blocked,
1218            }
1219        }
1220    }
1221
1222    #[async_trait]
1223    impl Connector for TestConnector {
1224        fn name(&self) -> &str {
1225            "test"
1226        }
1227
1228        async fn describe(&self) -> Result<ConnectorDescription, String> {
1229            Ok(ConnectorDescription {
1230                name: "test".to_string(),
1231                instructions: None,
1232                tools: vec![ConnectorTool {
1233                    name: "run".to_string(),
1234                    description: None,
1235                    input_schema: json!({"type": "object"}),
1236                    output_schema: Some(json!({"type": "integer"})),
1237                    instructions: None,
1238                    examples: Vec::new(),
1239                    annotations: ToolAnnotations {
1240                        read_only: Some(true),
1241                        ..ToolAnnotations::default()
1242                    },
1243                    policy: ToolPolicy {
1244                        requires_approval: false,
1245                        replay: ReplayPolicy::Log,
1246                    },
1247                }],
1248            })
1249        }
1250
1251        async fn execute(
1252            &self,
1253            _method: &str,
1254            _arguments: Value,
1255            _context: &ToolContext,
1256        ) -> Result<Value, String> {
1257            self.calls.fetch_add(1, Ordering::SeqCst);
1258            self.started.notify_one();
1259            if self.blocked {
1260                self.release.notified().await;
1261            }
1262            Ok(json!(42))
1263        }
1264
1265        async fn execution_ended(&self, _execution_id: &str, status: &str) {
1266            self.ended.lock().await.push(status.to_string());
1267        }
1268    }
1269
1270    struct HostExecutor;
1271
1272    #[async_trait(?Send)]
1273    impl CodeExecutor for HostExecutor {
1274        async fn execute(
1275            &self,
1276            _code: &str,
1277            _connectors: &[ConnectorDescription],
1278            _execution_id: &str,
1279            host: Arc<ExecutionHost>,
1280        ) -> Result<ExecuteResult, String> {
1281            let response = host.call(0, "test", "run", json!({})).await;
1282            Ok(ExecuteResult {
1283                result: response.result,
1284                error: response.message,
1285                logs: Vec::new(),
1286            })
1287        }
1288    }
1289
1290    #[tokio::test(flavor = "current_thread")]
1291    async fn dispatch_requires_an_active_pass() {
1292        let connector = Arc::new(TestConnector::new(false));
1293        let code_mode = CodeMode::new(
1294            Arc::new(MemoryStore::default()),
1295            HostExecutor,
1296            vec![connector.clone()],
1297        );
1298        let state = code_mode.start("ignored").await.unwrap();
1299
1300        let error = code_mode
1301            .dispatch(DispatchRequest::Call {
1302                execution_id: state.id.clone(),
1303                seq: 0,
1304                connector: "test".to_string(),
1305                method: "run".to_string(),
1306                arguments: json!({}),
1307            })
1308            .await
1309            .unwrap_err();
1310
1311        assert!(error.contains("active pass"));
1312        for request in [
1313            DispatchRequest::LoadCheckpoint {
1314                execution_id: state.id.clone(),
1315            },
1316            DispatchRequest::SaveCheckpoint {
1317                execution_id: state.id.clone(),
1318                checkpoint: crate::ExecutionCheckpoint {
1319                    identity: "fixture".into(),
1320                    bytes: vec![1, 2],
1321                },
1322            },
1323        ] {
1324            assert!(
1325                code_mode
1326                    .dispatch(request)
1327                    .await
1328                    .unwrap_err()
1329                    .contains("active pass")
1330            );
1331        }
1332        assert_eq!(connector.calls.load(Ordering::SeqCst), 0);
1333        assert_eq!(
1334            code_mode.execution(&state.id).await.unwrap().status,
1335            ExecutionStatus::Running
1336        );
1337    }
1338
1339    #[tokio::test(flavor = "current_thread")]
1340    async fn cancelling_an_idle_execution_ends_connector_lifecycle_once() {
1341        let connector = Arc::new(TestConnector::new(false));
1342        let code_mode = CodeMode::new(
1343            Arc::new(MemoryStore::default()),
1344            HostExecutor,
1345            vec![connector.clone()],
1346        );
1347        let state = code_mode.start("ignored").await.unwrap();
1348
1349        code_mode.cancel(&state.id).await.unwrap();
1350        code_mode.cancel(&state.id).await.unwrap();
1351
1352        assert_eq!(&*connector.ended.lock().await, &["cancelled"]);
1353    }
1354
1355    #[tokio::test(flavor = "current_thread")]
1356    async fn concurrent_drive_calls_execute_one_pass() {
1357        let connector = Arc::new(TestConnector::new(true));
1358        let code_mode = CodeMode::new(
1359            Arc::new(MemoryStore::default()),
1360            HostExecutor,
1361            vec![connector.clone()],
1362        );
1363        let state = code_mode.start("ignored").await.unwrap();
1364        let first = code_mode.drive_with(&state.id, CodeModeRunOptions::default());
1365        let second = code_mode.drive_with(&state.id, CodeModeRunOptions::default());
1366        let release = async {
1367            connector.started.notified().await;
1368            tokio::task::yield_now().await;
1369            connector.release.notify_waiters();
1370        };
1371
1372        let (first, second, ()) = tokio::join!(first, second, release);
1373
1374        assert_eq!(first.unwrap().status, ExecutionStatus::Completed);
1375        assert_eq!(second.unwrap().status, ExecutionStatus::Completed);
1376        assert_eq!(connector.calls.load(Ordering::SeqCst), 1);
1377    }
1378
1379    #[tokio::test(flavor = "current_thread")]
1380    async fn rollback_rejects_live_executions() {
1381        let code_mode = CodeMode::new(
1382            Arc::new(MemoryStore::default()),
1383            HostExecutor,
1384            vec![Arc::new(TestConnector::new(false))],
1385        );
1386        let state = code_mode.start("ignored").await.unwrap();
1387
1388        let error = code_mode.rollback(&state.id).await.unwrap_err();
1389
1390        assert!(error.contains("not rollback eligible"));
1391        assert_eq!(
1392            code_mode.execution(&state.id).await.unwrap().status,
1393            ExecutionStatus::Running
1394        );
1395    }
1396}