Skip to main content

multicast_codemode_local/
lib.rs

1//! Native actor service and optional QuickJS execution adapter for Code Mode.
2
3#[cfg(all(feature = "quickjs", feature = "sqlite"))]
4use std::path::Path;
5use std::rc::Rc;
6#[cfg(all(feature = "quickjs", feature = "sqlite"))]
7use std::sync::Arc;
8
9use multicast_codemode::opentelemetry::{Context, trace::FutureExt};
10
11use multicast_codemode::{
12    CodeMode, CodeModeRunOptions, CodeModeService, ExecutionState, SearchOutput, Snippet,
13};
14use serde_json::Value;
15use tokio::sync::{mpsc, oneshot};
16
17#[cfg(feature = "quickjs")]
18mod native;
19#[cfg(feature = "quickjs")]
20mod quickjs;
21#[cfg(feature = "quickjs")]
22pub use quickjs::{LocalExecutor, LocalExecutorOptions};
23
24#[cfg(feature = "sqlite")]
25mod store;
26#[cfg(feature = "sqlite")]
27pub use store::DurableStore;
28
29/// Opens Code Mode with its journal, artifacts, and heap in one SQLite database.
30#[cfg(all(feature = "quickjs", feature = "sqlite"))]
31pub fn open_codemode(
32    path: impl AsRef<Path>,
33    options: LocalExecutorOptions,
34    connectors: Vec<Arc<dyn multicast_codemode::Connector>>,
35) -> Result<CodeMode, String> {
36    let store = Arc::new(DurableStore::open(path)?);
37    Ok(CodeMode::with_artifact_store(
38        store.clone(),
39        store,
40        LocalExecutor::new(options),
41        connectors,
42    ))
43}
44
45/// Opens a durable actor service for a CLI or MCP host.
46///
47/// The host owns the database until its service thread exits. Restarting with
48/// the same path preserves approvals, artifacts, and engine continuations.
49#[cfg(all(feature = "quickjs", feature = "sqlite"))]
50pub fn spawn_codemode(
51    path: impl AsRef<Path>,
52    options: LocalExecutorOptions,
53    connectors: Vec<Arc<dyn multicast_codemode::Connector>>,
54) -> Result<LocalCodeModeService, String> {
55    spawn_codemode_with_limits(
56        path,
57        options,
58        connectors,
59        multicast_codemode::WorkflowLimits::default(),
60    )
61}
62
63/// Opens a durable actor with finite host-owned budgets shared by each workflow tree.
64#[cfg(all(feature = "quickjs", feature = "sqlite"))]
65pub fn spawn_codemode_with_limits(
66    path: impl AsRef<Path>,
67    options: LocalExecutorOptions,
68    connectors: Vec<Arc<dyn multicast_codemode::Connector>>,
69    limits: multicast_codemode::WorkflowLimits,
70) -> Result<LocalCodeModeService, String> {
71    limits.check()?;
72    let store = Arc::new(DurableStore::open(path)?);
73    LocalCodeModeService::spawn(move || {
74        CodeMode::with_artifact_store(
75            store.clone(),
76            store,
77            LocalExecutor::new(options),
78            connectors,
79        )
80        .with_workflow_limits(limits)
81        .expect("validated limits on an unshared runtime")
82    })
83}
84
85fn random_execution_id() -> Result<String, String> {
86    #[cfg(not(target_arch = "wasm32"))]
87    {
88        let mut bytes = [0_u8; 24];
89        getrandom::fill(&mut bytes).map_err(|error| error.to_string())?;
90        Ok(format!(
91            "exec_{}",
92            bytes
93                .iter()
94                .map(|byte| format!("{byte:02x}"))
95                .collect::<String>()
96        ))
97    }
98    #[cfg(target_arch = "wasm32")]
99    {
100        Err("SECURE_EXECUTION_ID_UNAVAILABLE: host must supply secure randomness".into())
101    }
102}
103
104enum ServiceRequest {
105    InstallWorkflows {
106        definitions: std::collections::BTreeMap<String, multicast_codemode::WorkflowDefinition>,
107        response: oneshot::Sender<Result<(), String>>,
108    },
109    Prepare {
110        code: String,
111        response: oneshot::Sender<Result<ExecutionState, String>>,
112    },
113    Search {
114        query: String,
115        response: oneshot::Sender<Result<SearchOutput, String>>,
116    },
117    Execute {
118        code: String,
119        retention_ms: Option<u64>,
120        options: CodeModeRunOptions,
121        response: oneshot::Sender<Result<ExecutionState, String>>,
122    },
123    Execution {
124        execution_id: String,
125        response: oneshot::Sender<Result<ExecutionState, String>>,
126    },
127    Resume {
128        execution_id: String,
129        recover: bool,
130        options: CodeModeRunOptions,
131        response: oneshot::Sender<Result<ExecutionState, String>>,
132    },
133    Artifact {
134        execution_id: String,
135        artifact_id: String,
136        response: oneshot::Sender<Result<Value, String>>,
137    },
138    Approve {
139        execution_id: String,
140        detached: bool,
141        seq: u64,
142        options: CodeModeRunOptions,
143        response: oneshot::Sender<Result<ExecutionState, String>>,
144    },
145    Reject {
146        telemetry_context: Context,
147        execution_id: String,
148        seq: u64,
149        response: oneshot::Sender<Result<ExecutionState, String>>,
150    },
151    Cancel {
152        telemetry_context: Context,
153        execution_id: String,
154        response: oneshot::Sender<Result<ExecutionState, String>>,
155    },
156    PublishSnippet {
157        name: String,
158        description: String,
159        code: String,
160        input_schema: Option<Value>,
161        response: oneshot::Sender<Result<Snippet, String>>,
162    },
163    SaveSnippet {
164        name: String,
165        description: String,
166        execution_id: String,
167        input_schema: Option<Value>,
168        response: oneshot::Sender<Result<Snippet, String>>,
169    },
170    Snippets {
171        response: oneshot::Sender<Result<Vec<Snippet>, String>>,
172    },
173    DeleteSnippet {
174        name: String,
175        response: oneshot::Sender<Result<bool, String>>,
176    },
177}
178
179/// Send-safe actor handle for a local non-`Send` Code Mode runtime.
180#[derive(Clone)]
181pub struct LocalCodeModeService {
182    sender: mpsc::Sender<ServiceRequest>,
183}
184
185impl LocalCodeModeService {
186    /// Starts a dedicated current-thread runtime and constructs Code Mode on it.
187    pub fn spawn(factory: impl FnOnce() -> CodeMode + Send + 'static) -> Result<Self, String> {
188        Self::spawn_on_thread(
189            std::thread::Builder::new().name("multicast-codemode-local".to_string()),
190            factory,
191        )
192    }
193
194    /// Starts an actor with an explicit native stack size in bytes.
195    ///
196    /// Allow headroom beyond the executor's QuickJS stack limit so the engine
197    /// can raise a JavaScript exception before exhausting the host thread.
198    pub fn spawn_with_stack_size(
199        stack_size: usize,
200        factory: impl FnOnce() -> CodeMode + Send + 'static,
201    ) -> Result<Self, String> {
202        Self::spawn_on_thread(
203            std::thread::Builder::new()
204                .name("multicast-codemode-local".to_string())
205                .stack_size(stack_size),
206            factory,
207        )
208    }
209
210    fn spawn_on_thread(
211        thread: std::thread::Builder,
212        factory: impl FnOnce() -> CodeMode + Send + 'static,
213    ) -> Result<Self, String> {
214        let (sender, receiver) = mpsc::channel(64);
215        let (ready_sender, ready_receiver) = std::sync::mpsc::sync_channel(1);
216        thread
217            .spawn(move || {
218                let runtime = match tokio::runtime::Builder::new_current_thread()
219                    .enable_time()
220                    .build()
221                {
222                    Ok(runtime) => runtime,
223                    Err(error) => {
224                        let _ = ready_sender.send(Err(error.to_string()));
225                        return;
226                    }
227                };
228                let codemode = Rc::new(factory());
229                let _ = ready_sender.send(Ok(()));
230                tokio::task::LocalSet::new().block_on(&runtime, serve_requests(codemode, receiver));
231            })
232            .map_err(|error| error.to_string())?;
233        ready_receiver.recv().map_err(|error| error.to_string())??;
234        Ok(Self { sender })
235    }
236
237    /// Persists a running execution without driving any JavaScript or host calls.
238    ///
239    /// A host can journal the returned identifier before calling `recover` to
240    /// start its first pass. An unbound prepared execution has no host effects.
241    pub async fn prepare(&self, code: String) -> Result<ExecutionState, String> {
242        let (response, receiver) = oneshot::channel();
243        self.send(ServiceRequest::Prepare { code, response })
244            .await?;
245        receive(receiver).await
246    }
247
248    async fn send(&self, request: ServiceRequest) -> Result<(), String> {
249        self.sender
250            .send(request)
251            .await
252            .map_err(|_| "Local Code Mode service stopped".to_string())
253    }
254}
255
256#[async_trait::async_trait]
257impl CodeModeService for LocalCodeModeService {
258    async fn install_workflows(
259        &self,
260        definitions: std::collections::BTreeMap<String, multicast_codemode::WorkflowDefinition>,
261    ) -> Result<(), String> {
262        let (response, receiver) = oneshot::channel();
263        self.send(ServiceRequest::InstallWorkflows {
264            definitions,
265            response,
266        })
267        .await?;
268        receive(receiver).await
269    }
270    async fn prepare(&self, code: String) -> Result<ExecutionState, String> {
271        LocalCodeModeService::prepare(self, code).await
272    }
273
274    async fn recover(
275        &self,
276        execution_id: String,
277        options: CodeModeRunOptions,
278    ) -> Result<ExecutionState, String> {
279        let (response, receiver) = oneshot::channel();
280        self.send(ServiceRequest::Resume {
281            execution_id,
282            recover: true,
283            options,
284            response,
285        })
286        .await?;
287        receive(receiver).await
288    }
289    async fn approve_detached(
290        &self,
291        execution_id: String,
292        seq: u64,
293        options: CodeModeRunOptions,
294    ) -> Result<ExecutionState, String> {
295        let (response, receiver) = oneshot::channel();
296        self.send(ServiceRequest::Approve {
297            execution_id,
298            detached: true,
299            seq,
300            options,
301            response,
302        })
303        .await?;
304        receive(receiver).await
305    }
306    fn supports_retained_execution(&self) -> bool {
307        true
308    }
309
310    async fn execute_retained(
311        &self,
312        code: String,
313        retention_ms: u64,
314        options: CodeModeRunOptions,
315    ) -> Result<ExecutionState, String> {
316        let (response, receiver) = oneshot::channel();
317        self.send(ServiceRequest::Execute {
318            code,
319            retention_ms: Some(retention_ms),
320            options,
321            response,
322        })
323        .await?;
324        receive(receiver).await
325    }
326
327    async fn resume(
328        &self,
329        execution_id: String,
330        options: CodeModeRunOptions,
331    ) -> Result<ExecutionState, String> {
332        let (response, receiver) = oneshot::channel();
333        self.send(ServiceRequest::Resume {
334            execution_id,
335            recover: false,
336            options,
337            response,
338        })
339        .await?;
340        receive(receiver).await
341    }
342    async fn search(&self, query: String) -> Result<SearchOutput, String> {
343        let (response, receiver) = oneshot::channel();
344        self.send(ServiceRequest::Search { query, response })
345            .await?;
346        receive(receiver).await
347    }
348
349    async fn execute(
350        &self,
351        code: String,
352        options: CodeModeRunOptions,
353    ) -> Result<ExecutionState, String> {
354        let (response, receiver) = oneshot::channel();
355        self.send(ServiceRequest::Execute {
356            code,
357            retention_ms: None,
358            options,
359            response,
360        })
361        .await?;
362        receive(receiver).await
363    }
364
365    async fn execution(&self, execution_id: String) -> Result<ExecutionState, String> {
366        let (response, receiver) = oneshot::channel();
367        self.send(ServiceRequest::Execution {
368            execution_id,
369            response,
370        })
371        .await?;
372        receive(receiver).await
373    }
374
375    async fn artifact(&self, execution_id: String, artifact_id: String) -> Result<Value, String> {
376        let (response, receiver) = oneshot::channel();
377        self.send(ServiceRequest::Artifact {
378            execution_id,
379            artifact_id,
380            response,
381        })
382        .await?;
383        receive(receiver).await
384    }
385
386    async fn approve(
387        &self,
388        execution_id: String,
389        seq: u64,
390        options: CodeModeRunOptions,
391    ) -> Result<ExecutionState, String> {
392        let (response, receiver) = oneshot::channel();
393        self.send(ServiceRequest::Approve {
394            execution_id,
395            detached: false,
396            seq,
397            options,
398            response,
399        })
400        .await?;
401        receive(receiver).await
402    }
403
404    async fn reject(&self, execution_id: String, seq: u64) -> Result<ExecutionState, String> {
405        let (response, receiver) = oneshot::channel();
406        self.send(ServiceRequest::Reject {
407            telemetry_context: Context::current(),
408            execution_id,
409            seq,
410            response,
411        })
412        .await?;
413        receive(receiver).await
414    }
415
416    async fn cancel(&self, execution_id: String) -> Result<ExecutionState, String> {
417        let (response, receiver) = oneshot::channel();
418        self.send(ServiceRequest::Cancel {
419            telemetry_context: Context::current(),
420            execution_id,
421            response,
422        })
423        .await?;
424        receive(receiver).await
425    }
426
427    async fn publish_snippet(
428        &self,
429        name: String,
430        description: String,
431        code: String,
432        input_schema: Option<Value>,
433    ) -> Result<Snippet, String> {
434        let (response, receiver) = oneshot::channel();
435        self.send(ServiceRequest::PublishSnippet {
436            name,
437            description,
438            code,
439            input_schema,
440            response,
441        })
442        .await?;
443        receive(receiver).await
444    }
445
446    async fn save_snippet(
447        &self,
448        name: String,
449        description: String,
450        execution_id: String,
451        input_schema: Option<Value>,
452    ) -> Result<Snippet, String> {
453        let (response, receiver) = oneshot::channel();
454        self.send(ServiceRequest::SaveSnippet {
455            name,
456            description,
457            execution_id,
458            input_schema,
459            response,
460        })
461        .await?;
462        receive(receiver).await
463    }
464
465    async fn snippets(&self) -> Result<Vec<Snippet>, String> {
466        let (response, receiver) = oneshot::channel();
467        self.send(ServiceRequest::Snippets { response }).await?;
468        receive(receiver).await
469    }
470
471    async fn delete_snippet(&self, name: String) -> Result<bool, String> {
472        let (response, receiver) = oneshot::channel();
473        self.send(ServiceRequest::DeleteSnippet { name, response })
474            .await?;
475        receive(receiver).await
476    }
477}
478
479async fn receive<T>(receiver: oneshot::Receiver<Result<T, String>>) -> Result<T, String> {
480    receiver
481        .await
482        .map_err(|_| "Local Code Mode service stopped".to_string())?
483}
484
485async fn serve_requests(codemode: Rc<CodeMode>, mut receiver: mpsc::Receiver<ServiceRequest>) {
486    while let Some(request) = receiver.recv().await {
487        let codemode = Rc::clone(&codemode);
488        tokio::task::spawn_local(async move {
489            match request {
490                ServiceRequest::InstallWorkflows {
491                    definitions,
492                    response,
493                } => {
494                    let _ = response.send(
495                        codemode
496                            .runtime()
497                            .install_workflows(
498                                definitions,
499                                multicast_codemode::Clock::now_ms(&multicast_codemode::SystemClock),
500                            )
501                            .await,
502                    );
503                }
504                ServiceRequest::Resume {
505                    execution_id,
506                    recover,
507                    options,
508                    response,
509                } => match if recover {
510                    codemode.execution_snapshot(&execution_id).await
511                } else {
512                    codemode.prepare_resume(&execution_id).await
513                } {
514                    Ok(state)
515                        if state.status == multicast_codemode::ExecutionStatus::Running
516                            || (recover && state.workflow_wait.is_some()) =>
517                    {
518                        let _ = response.send(Ok(state));
519                        if recover {
520                            let _ = codemode.drive_if_idle(&execution_id, options).await;
521                        } else {
522                            let _ = codemode.drive_with(&execution_id, options).await;
523                        }
524                    }
525                    Ok(state) if recover => {
526                        let _ = response.send(Ok(state));
527                    }
528                    Ok(_) => {
529                        let _ = response.send(Err("Only an interrupted running execution can resume; pending approvals require a decision".into()));
530                    }
531                    Err(error) => {
532                        let _ = response.send(Err(error));
533                    }
534                },
535                ServiceRequest::Prepare { code, response } => {
536                    let _ = response.send(codemode.start(&code).await);
537                }
538                ServiceRequest::Search { query, response } => {
539                    let _ = response.send(codemode.search(&query).await);
540                }
541                ServiceRequest::Execute {
542                    code,
543                    retention_ms,
544                    options,
545                    response,
546                } => match async {
547                    let id = if retention_ms.is_some() {
548                        Some(random_execution_id()?)
549                    } else {
550                        None
551                    };
552                    codemode.start_retained(&code, retention_ms, id).await
553                }
554                .await
555                {
556                    Ok(state) => {
557                        let execution_id = state.id.clone();
558                        let _ = response.send(Ok(state));
559                        let _ = codemode.drive_with(&execution_id, options).await;
560                    }
561                    Err(error) => {
562                        let _ = response.send(Err(error));
563                    }
564                },
565                ServiceRequest::Execution {
566                    execution_id,
567                    response,
568                } => {
569                    let _ = response.send(codemode.execution_snapshot(&execution_id).await);
570                }
571                ServiceRequest::Artifact {
572                    execution_id,
573                    artifact_id,
574                    response,
575                } => {
576                    let _ = response.send(codemode.artifact(&execution_id, &artifact_id).await);
577                }
578                ServiceRequest::Approve {
579                    execution_id,
580                    detached,
581                    seq,
582                    options,
583                    response,
584                } => {
585                    if detached {
586                        match codemode
587                            .approve_pending(&execution_id, seq)
588                            .with_context(options.telemetry_context.clone())
589                            .await
590                        {
591                            Ok(winner) => {
592                                let _ =
593                                    response.send(codemode.execution_snapshot(&execution_id).await);
594                                if winner {
595                                    let _ = codemode.drive_with(&execution_id, options).await;
596                                }
597                            }
598                            Err(error) => {
599                                let _ = response.send(Err(error));
600                            }
601                        }
602                        return;
603                    }
604                    let result = match codemode.approve_with(&execution_id, seq, options).await {
605                        Ok(_) => codemode.execution_snapshot(&execution_id).await,
606                        Err(error) => Err(error),
607                    };
608                    let _ = response.send(result);
609                }
610                ServiceRequest::Reject {
611                    telemetry_context,
612                    execution_id,
613                    seq,
614                    response,
615                } => {
616                    let result = match codemode
617                        .reject(&execution_id, seq)
618                        .with_context(telemetry_context)
619                        .await
620                    {
621                        Ok(_) => codemode.execution_snapshot(&execution_id).await,
622                        Err(error) => Err(error),
623                    };
624                    let _ = response.send(result);
625                }
626                ServiceRequest::Cancel {
627                    telemetry_context,
628                    execution_id,
629                    response,
630                } => {
631                    let result = match codemode
632                        .cancel(&execution_id)
633                        .with_context(telemetry_context)
634                        .await
635                    {
636                        Ok(_) => codemode.execution_snapshot(&execution_id).await,
637                        Err(error) => Err(error),
638                    };
639                    let _ = response.send(result);
640                }
641                ServiceRequest::PublishSnippet {
642                    name,
643                    description,
644                    code,
645                    input_schema,
646                    response,
647                } => {
648                    let _ = response.send(
649                        codemode
650                            .publish_snippet(&name, &description, &code, input_schema)
651                            .await,
652                    );
653                }
654                ServiceRequest::SaveSnippet {
655                    name,
656                    description,
657                    execution_id,
658                    input_schema,
659                    response,
660                } => {
661                    let _ = response.send(
662                        codemode
663                            .save_snippet(&name, &description, &execution_id, input_schema)
664                            .await,
665                    );
666                }
667                ServiceRequest::Snippets { response } => {
668                    let _ = response.send(codemode.snippets().await);
669                }
670                ServiceRequest::DeleteSnippet { name, response } => {
671                    let _ = response.send(codemode.delete_snippet(&name).await);
672                }
673            }
674        });
675    }
676}
677
678#[cfg(all(test, feature = "quickjs"))]
679mod tests {
680    use std::sync::Arc;
681    use std::sync::atomic::{AtomicUsize, Ordering};
682    use std::time::Duration;
683
684    use multicast::cli::Cli;
685    use multicast::command::{
686        CommandContext, CommandDef, CommandHandler, McpAnnotations, McpCommandOptions,
687    };
688    use multicast::output::CommandResult;
689    use multicast::tool::ToolEvent;
690    use multicast_codemode::{
691        CodeMode, CodeModeRunOptions, CodeModeService, Connector, ConnectorDescription,
692        ConnectorTool, ExecutionEvent, ExecutionStatus, MAX_DURABLE_VALUE_BYTES, MemoryStore,
693        MulticastConnector, ReplayPolicy, ToolAnnotations, ToolContext,
694    };
695    use serde::Deserialize;
696    use serde_json::{Value, json};
697
698    use super::*;
699
700    #[derive(Default)]
701    struct MathConnector {
702        saves: AtomicUsize,
703        reverts: AtomicUsize,
704    }
705
706    struct MulticastSum;
707
708    struct ContextConnector;
709
710    struct DelayConnector;
711
712    #[async_trait::async_trait]
713    impl CommandHandler for MulticastSum {
714        async fn run(&self, context: CommandContext) -> CommandResult {
715            CommandResult::Ok {
716                data: json!({
717                    "sum": context.options["left"].as_i64().unwrap()
718                        + context.options["right"].as_i64().unwrap()
719                }),
720                cta: None,
721                exit_code: None,
722            }
723        }
724    }
725
726    #[derive(multicast::Options, Deserialize)]
727    #[allow(dead_code)]
728    struct MulticastSumOptions {
729        /// Left operand.
730        left: i64,
731        /// Right operand.
732        right: i64,
733    }
734
735    /// Stands in for a configured server that cannot be reached.
736    ///
737    /// Counts describes so a test can assert an untouched namespace is never
738    /// contacted, rather than inferring it from timing.
739    struct UnreachableConnector {
740        describes: Arc<std::sync::atomic::AtomicUsize>,
741    }
742
743    #[async_trait::async_trait]
744    impl Connector for UnreachableConnector {
745        fn name(&self) -> &str {
746            "unreachable"
747        }
748
749        async fn describe(&self) -> Result<ConnectorDescription, String> {
750            self.describes
751                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
752            Err("connection refused".to_string())
753        }
754
755        async fn execute(
756            &self,
757            _method: &str,
758            _arguments: Value,
759            _context: &ToolContext,
760        ) -> Result<Value, String> {
761            Err("connection refused".to_string())
762        }
763    }
764
765    #[async_trait::async_trait]
766    impl Connector for MathConnector {
767        fn name(&self) -> &str {
768            "math"
769        }
770
771        async fn describe(&self) -> Result<ConnectorDescription, String> {
772            Ok(ConnectorDescription {
773                name: "math".to_string(),
774                instructions: Some("Local arithmetic and mock persistence.".to_string()),
775                tools: vec![
776                    ConnectorTool {
777                        name: "sum".to_string(),
778                        description: Some("Add two integers.".to_string()),
779                        input_schema: json!({
780                            "type": "object",
781                            "properties": {
782                                "left": {"type": "integer"},
783                                "right": {"type": "integer"}
784                            },
785                            "required": ["left", "right"]
786                        }),
787                        output_schema: Some(json!({
788                            "type": "object",
789                            "properties": {"sum": {"type": "integer"}},
790                            "required": ["sum"]
791                        })),
792                        instructions: None,
793                        examples: Vec::new(),
794                        annotations: ToolAnnotations {
795                            read_only: Some(true),
796                            ..ToolAnnotations::default()
797                        },
798                        policy: multicast_codemode::ToolPolicy {
799                            requires_approval: false,
800                            replay: ReplayPolicy::Reexecute,
801                        },
802                    },
803                    ConnectorTool {
804                        name: "save".to_string(),
805                        description: Some("Save one value.".to_string()),
806                        input_schema: json!({
807                            "type": "object",
808                            "properties": {"value": {}},
809                            "required": ["value"]
810                        }),
811                        output_schema: None,
812                        instructions: None,
813                        examples: Vec::new(),
814                        annotations: ToolAnnotations::default(),
815                        policy: multicast_codemode::ToolPolicy {
816                            requires_approval: true,
817                            replay: ReplayPolicy::Log,
818                        },
819                    },
820                ],
821            })
822        }
823
824        async fn execute(
825            &self,
826            method: &str,
827            arguments: Value,
828            _context: &ToolContext,
829        ) -> Result<Value, String> {
830            match method {
831                "sum" => Ok(json!({
832                    "sum": arguments["left"].as_i64().unwrap()
833                        + arguments["right"].as_i64().unwrap()
834                })),
835                "save" => {
836                    self.saves.fetch_add(1, Ordering::Relaxed);
837                    Ok(json!({"saved": arguments["value"]}))
838                }
839                _ => Err(format!("Unknown method: {method}")),
840            }
841        }
842
843        async fn revert(
844            &self,
845            method: &str,
846            _arguments: Value,
847            _result: Value,
848            _context: &ToolContext,
849        ) -> Result<bool, String> {
850            if method != "save" {
851                return Ok(false);
852            }
853            self.reverts.fetch_add(1, Ordering::Relaxed);
854            Ok(true)
855        }
856    }
857
858    #[async_trait::async_trait]
859    impl Connector for ContextConnector {
860        fn name(&self) -> &str {
861            "context"
862        }
863
864        async fn describe(&self) -> Result<ConnectorDescription, String> {
865            Ok(ConnectorDescription {
866                name: "context".to_string(),
867                instructions: None,
868                tools: vec![ConnectorTool {
869                    name: "inspect".to_string(),
870                    description: None,
871                    input_schema: json!({"type": "object"}),
872                    output_schema: None,
873                    instructions: None,
874                    examples: Vec::new(),
875                    annotations: ToolAnnotations {
876                        read_only: Some(true),
877                        ..ToolAnnotations::default()
878                    },
879                    policy: multicast_codemode::ToolPolicy {
880                        requires_approval: false,
881                        replay: ReplayPolicy::Reexecute,
882                    },
883                }],
884            })
885        }
886
887        async fn execute(
888            &self,
889            _method: &str,
890            _arguments: Value,
891            context: &ToolContext,
892        ) -> Result<Value, String> {
893            let events = context
894                .control
895                .events
896                .as_ref()
897                .expect("execution event sink");
898            events
899                .emit(ToolEvent::Progress {
900                    message: "halfway".to_string(),
901                    fraction: Some(0.5),
902                })
903                .await;
904            events
905                .emit(ToolEvent::Log {
906                    level: "info".to_string(),
907                    message: "inspected".to_string(),
908                })
909                .await;
910            events
911                .emit(ToolEvent::Chunk {
912                    data: json!({"part": 1}),
913                })
914                .await;
915            Ok(json!({
916                "method": context.request.as_ref().map(|request| request.method.clone()),
917                "path": context.request.as_ref().map(|request| request.path.clone()),
918            }))
919        }
920    }
921
922    #[async_trait::async_trait]
923    impl Connector for DelayConnector {
924        fn name(&self) -> &str {
925            "delay"
926        }
927
928        async fn describe(&self) -> Result<ConnectorDescription, String> {
929            Ok(ConnectorDescription {
930                name: "delay".to_string(),
931                instructions: None,
932                tools: vec![ConnectorTool {
933                    name: "sleep".to_string(),
934                    description: None,
935                    input_schema: json!({
936                        "type": "object",
937                        "properties": {"ms": {"type": "integer"}},
938                        "required": ["ms"]
939                    }),
940                    output_schema: None,
941                    instructions: None,
942                    examples: Vec::new(),
943                    annotations: ToolAnnotations {
944                        read_only: Some(true),
945                        ..ToolAnnotations::default()
946                    },
947                    policy: multicast_codemode::ToolPolicy {
948                        requires_approval: false,
949                        replay: ReplayPolicy::Reexecute,
950                    },
951                }],
952            })
953        }
954
955        async fn execute(
956            &self,
957            _method: &str,
958            arguments: Value,
959            _context: &ToolContext,
960        ) -> Result<Value, String> {
961            let ms = arguments["ms"].as_u64().unwrap();
962            tokio::time::sleep(Duration::from_millis(ms)).await;
963            Ok(json!({"slept": ms}))
964        }
965    }
966
967    struct WaitingConnector;
968
969    #[tokio::test]
970    async fn concurrent_executions_keep_distinct_native_heaps() {
971        let mode = CodeMode::new(
972            Arc::new(MemoryStore::default()),
973            LocalExecutor::default(),
974            vec![Arc::new(DelayConnector)],
975        );
976        let first = mode.execute(
977            "async () => { const token = 'first'; await delay.sleep({ms: 20}); return token; }",
978        );
979        let second = mode.execute(
980            "async () => { const token = 'second'; await delay.sleep({ms: 1}); return token; }",
981        );
982        let (first, second) = tokio::join!(first, second);
983        assert_eq!(first.unwrap().result, Some(json!("first")));
984        assert_eq!(second.unwrap().result, Some(json!("second")));
985    }
986
987    #[async_trait::async_trait]
988    impl Connector for WaitingConnector {
989        fn name(&self) -> &str {
990            "waiting"
991        }
992
993        async fn describe(&self) -> Result<ConnectorDescription, String> {
994            Ok(ConnectorDescription {
995                name: "waiting".to_string(),
996                instructions: None,
997                tools: vec![ConnectorTool {
998                    name: "until_cancelled".to_string(),
999                    description: None,
1000                    input_schema: json!({"type": "object"}),
1001                    output_schema: None,
1002                    instructions: None,
1003                    examples: Vec::new(),
1004                    annotations: ToolAnnotations {
1005                        read_only: Some(true),
1006                        ..ToolAnnotations::default()
1007                    },
1008                    policy: multicast_codemode::ToolPolicy {
1009                        requires_approval: false,
1010                        replay: ReplayPolicy::Reexecute,
1011                    },
1012                }],
1013            })
1014        }
1015
1016        async fn execute(
1017            &self,
1018            _method: &str,
1019            _arguments: Value,
1020            context: &ToolContext,
1021        ) -> Result<Value, String> {
1022            context.control.cancellation.cancelled().await;
1023            Err("cancelled".to_string())
1024        }
1025    }
1026
1027    #[tokio::test]
1028    async fn executes_programs_locally() {
1029        let connector = Arc::new(MathConnector::default());
1030        let codemode = CodeMode::new(
1031            Arc::new(MemoryStore::default()),
1032            LocalExecutor::default(),
1033            vec![connector],
1034        );
1035        let execution = codemode
1036            .execute(
1037                "const found = await codemode.search(\"sum\"); \
1038                 const values = await Promise.all([ \
1039                   math.sum({ left: 2, right: 3 }), \
1040                   math.sum({ left: 4, right: 5 }) \
1041                 ]); \
1042                 return { found: found.results[0].path, values };",
1043            )
1044            .await
1045            .unwrap();
1046
1047        assert_eq!(
1048            execution.status,
1049            ExecutionStatus::Completed,
1050            "{execution:?}"
1051        );
1052        assert_eq!(
1053            execution.result,
1054            Some(json!({
1055                "found": "math.sum",
1056                "values": [{"sum": 5}, {"sum": 9}]
1057            }))
1058        );
1059        let capabilities = execution
1060            .capabilities
1061            .expect("capabilities must be captured");
1062        assert_eq!(capabilities.connectors[0].name, "math");
1063        assert_eq!(capabilities.fingerprint.len(), 64);
1064    }
1065
1066    #[tokio::test]
1067    async fn executes_an_incur_catalog_locally() {
1068        let catalog = Cli::create("math")
1069            .command(
1070                "sum",
1071                CommandDef::build("sum", MulticastSum)
1072                    .options::<MulticastSumOptions>()
1073                    .mcp(McpCommandOptions {
1074                        annotations: Some(McpAnnotations {
1075                            read_only_hint: Some(true),
1076                            ..McpAnnotations::default()
1077                        }),
1078                        ..McpCommandOptions::default()
1079                    })
1080                    .done(),
1081            )
1082            .tool_catalog();
1083        let codemode = CodeMode::new(
1084            Arc::new(MemoryStore::default()),
1085            LocalExecutor::default(),
1086            vec![Arc::new(MulticastConnector::new(catalog))],
1087        );
1088
1089        let execution = codemode
1090            .execute("math.sum({ left: 20, right: 22 })")
1091            .await
1092            .unwrap();
1093
1094        assert_eq!(execution.status, ExecutionStatus::Completed);
1095        assert_eq!(execution.result, Some(json!({"sum": 42})));
1096    }
1097
1098    #[tokio::test]
1099    async fn pauses_replays_and_rolls_back_locally() {
1100        let connector = Arc::new(MathConnector::default());
1101        let codemode = CodeMode::new(
1102            Arc::new(MemoryStore::default()),
1103            LocalExecutor::default(),
1104            vec![connector.clone()],
1105        );
1106        let paused = codemode
1107            .execute(
1108                "const token = await codemode.step(\"token\", async () => \"stable\"); \
1109                 await math.save({ value: token }); \
1110                 return token;",
1111            )
1112            .await
1113            .unwrap();
1114        assert_eq!(paused.status, ExecutionStatus::Paused, "{paused:?}");
1115
1116        let completed = codemode.approve(&paused.id, 1).await.unwrap();
1117        assert_eq!(completed.status, ExecutionStatus::Completed);
1118        assert_eq!(completed.result, Some(json!("stable")));
1119        assert_eq!(connector.saves.load(Ordering::Relaxed), 1);
1120
1121        let rolled_back = codemode.rollback(&paused.id).await.unwrap();
1122        assert_eq!(rolled_back.status, ExecutionStatus::RolledBack);
1123        assert_eq!(connector.reverts.load(Ordering::Relaxed), 1);
1124    }
1125
1126    #[tokio::test]
1127    async fn interrupts_runaway_local_programs() {
1128        let codemode = CodeMode::new(
1129            Arc::new(MemoryStore::default()),
1130            LocalExecutor::new(LocalExecutorOptions {
1131                timeout: Duration::from_millis(10),
1132                ..LocalExecutorOptions::default()
1133            }),
1134            Vec::new(),
1135        );
1136        let execution = codemode.execute("while (true) {}").await.unwrap();
1137
1138        assert_eq!(execution.status, ExecutionStatus::Error);
1139        assert_eq!(
1140            execution.error.as_deref(),
1141            Some(
1142                "CODE_EXECUTION_TIMEOUT: maximum uninterrupted JavaScript execution interval exceeded"
1143            )
1144        );
1145    }
1146
1147    #[tokio::test]
1148    async fn host_calls_renew_local_execution_timeout() {
1149        let codemode = CodeMode::new(
1150            Arc::new(MemoryStore::default()),
1151            LocalExecutor::new(LocalExecutorOptions {
1152                timeout: Duration::from_millis(25),
1153                ..LocalExecutorOptions::default()
1154            }),
1155            vec![Arc::new(DelayConnector)],
1156        );
1157        let execution = codemode
1158            .execute(
1159                "const result = await delay.sleep({ ms: 75 }); \
1160                 let total = 0; \
1161                 for (let i = 0; i < 10_000; i++) total += i; \
1162                 return { result, total };",
1163            )
1164            .await
1165            .unwrap();
1166
1167        assert_eq!(
1168            execution.status,
1169            ExecutionStatus::Completed,
1170            "{execution:?}"
1171        );
1172        assert_eq!(
1173            execution.result,
1174            Some(json!({
1175                "result": {"slept": 75},
1176                "total": 49_995_000
1177            }))
1178        );
1179    }
1180
1181    #[tokio::test]
1182    async fn propagates_request_control_and_events() {
1183        let codemode = CodeMode::new(
1184            Arc::new(MemoryStore::default()),
1185            LocalExecutor::default(),
1186            vec![Arc::new(ContextConnector)],
1187        );
1188        let execution = codemode
1189            .execute_with(
1190                "context.inspect({})",
1191                CodeModeRunOptions {
1192                    request: Some(multicast::command::RequestContext {
1193                        elicitation: None,
1194                        headers: Default::default(),
1195                        method: "POST".to_string(),
1196                        path: "/codemode".to_string(),
1197                    }),
1198                    ..CodeModeRunOptions::default()
1199                },
1200            )
1201            .await
1202            .unwrap();
1203
1204        assert_eq!(
1205            execution.result,
1206            Some(json!({"method": "POST", "path": "/codemode"}))
1207        );
1208        assert!(execution.events.iter().any(|event| matches!(
1209            event,
1210            ExecutionEvent::Progress {
1211                message,
1212                fraction: Some(0.5),
1213                ..
1214            } if message == "halfway"
1215        )));
1216        assert!(execution.events.iter().any(|event| matches!(
1217            event,
1218            ExecutionEvent::Log { message, .. } if message == "inspected"
1219        )));
1220        assert!(execution.events.iter().any(|event| matches!(
1221            event,
1222            ExecutionEvent::Chunk { data, .. } if data == &json!({"part": 1})
1223        )));
1224    }
1225
1226    #[tokio::test]
1227    async fn service_returns_running_state_and_cancels_active_quickjs() {
1228        let service = LocalCodeModeService::spawn(|| {
1229            CodeMode::new(
1230                Arc::new(MemoryStore::default()),
1231                LocalExecutor::default(),
1232                vec![Arc::new(WaitingConnector)],
1233            )
1234        })
1235        .unwrap();
1236        let running = service
1237            .execute(
1238                "waiting.until_cancelled({})".to_string(),
1239                CodeModeRunOptions::default(),
1240            )
1241            .await
1242            .unwrap();
1243
1244        assert_eq!(running.status, ExecutionStatus::Running);
1245        let cancelled = service.cancel(running.id.clone()).await.unwrap();
1246        assert_eq!(cancelled.status, ExecutionStatus::Cancelled);
1247    }
1248
1249    #[tokio::test]
1250    async fn service_exposes_artifact_references_for_oversized_results() {
1251        let service = LocalCodeModeService::spawn(|| {
1252            CodeMode::new(
1253                Arc::new(MemoryStore::default()),
1254                LocalExecutor::default(),
1255                vec![],
1256            )
1257        })
1258        .unwrap();
1259        let running = service
1260            .execute(
1261                format!("\"x\".repeat({})", MAX_DURABLE_VALUE_BYTES + 1),
1262                CodeModeRunOptions::default(),
1263            )
1264            .await
1265            .unwrap();
1266        let execution = loop {
1267            let execution = service.execution(running.id.clone()).await.unwrap();
1268            if execution.status == ExecutionStatus::Completed {
1269                break execution;
1270            }
1271            tokio::time::sleep(Duration::from_millis(5)).await;
1272        };
1273        let artifact_id = execution.result.as_ref().unwrap()["$artifact"]["id"]
1274            .as_str()
1275            .unwrap();
1276        assert_eq!(
1277            service
1278                .artifact(execution.id.clone(), artifact_id.to_string())
1279                .await
1280                .unwrap(),
1281            json!("x".repeat(MAX_DURABLE_VALUE_BYTES + 1))
1282        );
1283    }
1284
1285    #[tokio::test]
1286    async fn an_unreachable_namespace_does_not_break_a_program_that_ignores_it() {
1287        // The whole point of binding lazily: a configured server that is dead must
1288        // cost nothing until something uses it. Describing every connector up front
1289        // meant one unreachable server failed every execution, including the ones
1290        // that never mentioned it -- an unactionable failure, because no program the
1291        // agent could write would avoid it.
1292        let describes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1293        let codemode = CodeMode::new(
1294            Arc::new(MemoryStore::default()),
1295            LocalExecutor::default(),
1296            vec![
1297                Arc::new(MathConnector::default()),
1298                Arc::new(UnreachableConnector {
1299                    describes: Arc::clone(&describes),
1300                }),
1301            ],
1302        );
1303
1304        let execution = codemode
1305            .execute("return (await math.sum({ left: 2, right: 3 })).sum")
1306            .await
1307            .unwrap();
1308
1309        assert_eq!(
1310            execution.status,
1311            ExecutionStatus::Completed,
1312            "a dead namespace the program never names must not fail it: {execution:?}"
1313        );
1314        assert_eq!(execution.result, Some(json!(5)));
1315        assert_eq!(
1316            describes.load(std::sync::atomic::Ordering::SeqCst),
1317            0,
1318            "an untouched namespace must never be contacted"
1319        );
1320    }
1321
1322    #[tokio::test]
1323    async fn using_an_unreachable_namespace_fails_with_its_own_error() {
1324        // Fail fast, scoped: the failure surfaces when the program reaches for it,
1325        // carrying the reason, so the agent can route around it.
1326        let describes = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1327        let codemode = CodeMode::new(
1328            Arc::new(MemoryStore::default()),
1329            LocalExecutor::default(),
1330            vec![
1331                Arc::new(MathConnector::default()),
1332                Arc::new(UnreachableConnector {
1333                    describes: Arc::clone(&describes),
1334                }),
1335            ],
1336        );
1337
1338        let execution = codemode
1339            .execute("return await unreachable.anything({})")
1340            .await
1341            .unwrap();
1342
1343        assert_eq!(execution.status, ExecutionStatus::Error, "{execution:?}");
1344        assert!(
1345            execution
1346                .error
1347                .as_deref()
1348                .is_some_and(|error| error.contains("connection refused")),
1349            "the error must say why: {:?}",
1350            execution.error
1351        );
1352        assert_eq!(
1353            describes.load(std::sync::atomic::Ordering::SeqCst),
1354            1,
1355            "a used namespace is described exactly once per pass"
1356        );
1357    }
1358    #[tokio::test]
1359    async fn circular_values_fail_without_rejecting_shared_references() {
1360        let codemode = CodeMode::new(
1361            Arc::new(MemoryStore::default()),
1362            LocalExecutor::default(),
1363            vec![Arc::new(ContextConnector)],
1364        );
1365        for code in [
1366            "const value = {}; value.self = value; return value;",
1367            "const value = []; value.push(value); return value;",
1368            "const value = {}; value.self = value; return await context.inspect(value);",
1369            "return await codemode.step('cycle', async () => { const value = {}; value.self = value; return value; });",
1370        ] {
1371            let execution = codemode.execute(code).await.unwrap();
1372            assert_eq!(execution.status, ExecutionStatus::Error, "{execution:?}");
1373            let error = execution.error.as_deref().expect("recorded cycle error");
1374            assert!(
1375                error.contains("CODE_VALUE_CYCLE"),
1376                "cycle must have a specific diagnostic: {error}"
1377            );
1378        }
1379        let execution = codemode
1380            .execute("const shared = {answer: 42}; return {left: shared, right: shared};")
1381            .await
1382            .unwrap();
1383        assert_eq!(execution.status, ExecutionStatus::Completed);
1384        assert_eq!(
1385            execution.result,
1386            Some(json!({"left": {"answer": 42}, "right": {"answer": 42}}))
1387        );
1388    }
1389
1390    #[tokio::test]
1391    async fn caught_cycles_preserve_recovery_and_unrecorded_step_outcomes() {
1392        let codemode = CodeMode::new(
1393            Arc::new(MemoryStore::default()),
1394            LocalExecutor::default(),
1395            vec![Arc::new(MathConnector::default())],
1396        );
1397        let execution = codemode
1398            .execute(
1399                "const value = {}; value.self = value; const errors = []; \
1400                 try { await math.sum(value); } catch (error) { errors.push(String(error)); } \
1401                 try { await codemode.step('unrecorded', async () => value); } \
1402                 catch (error) { errors.push(String(error)); } \
1403                 const answer = await codemode.step('valid', async () => \
1404                   (await math.sum({left: 20, right: 22})).sum); \
1405                 return {errors, answer};",
1406            )
1407            .await
1408            .unwrap();
1409        assert_eq!(
1410            execution.status,
1411            ExecutionStatus::Completed,
1412            "{execution:?}"
1413        );
1414        let result = execution.result.as_ref().unwrap();
1415        assert_eq!(result["answer"], json!(42));
1416        let errors = result["errors"].as_array().unwrap();
1417        assert_eq!(errors.len(), 2);
1418        assert!(errors.iter().all(|error| {
1419            error
1420                .as_str()
1421                .is_some_and(|message| message.contains("CODE_VALUE_CYCLE"))
1422        }));
1423        assert_eq!(execution.log.len(), 3);
1424        let unrecorded = &execution.log[0];
1425        assert_eq!(unrecorded.seq, 1);
1426        assert_eq!(unrecorded.connector, "__step");
1427        assert_eq!(
1428            unrecorded.state,
1429            multicast_codemode::LogEntryState::Executing
1430        );
1431        assert!(unrecorded.result.is_none());
1432        let recorded = &execution.log[1];
1433        assert_eq!(recorded.seq, 2);
1434        assert_eq!(recorded.state, multicast_codemode::LogEntryState::Applied);
1435        assert_eq!(recorded.result, Some(json!(42)));
1436        let error = codemode.rollback(&execution.id).await.unwrap_err();
1437        assert!(error.contains("unfinished"), "{error}");
1438    }
1439
1440    #[tokio::test]
1441    async fn javascript_errors_preserve_exception_details() {
1442        let codemode = CodeMode::new(
1443            Arc::new(MemoryStore::default()),
1444            LocalExecutor::default(),
1445            Vec::new(),
1446        );
1447        for (code, expected) in [
1448            (
1449                "const value = \"first\nsecond\"; return value;",
1450                "SyntaxError",
1451            ),
1452            (
1453                "throw new TypeError('diagnostic-sentinel');",
1454                "diagnostic-sentinel",
1455            ),
1456            (
1457                "await Promise.reject(new Error('rejection-sentinel'));",
1458                "rejection-sentinel",
1459            ),
1460        ] {
1461            let execution = codemode.execute(code).await.unwrap();
1462            assert_eq!(execution.status, ExecutionStatus::Error);
1463            let error = execution.error.as_deref().expect("recorded exception");
1464            assert!(error.contains(expected), "{expected}: {error}");
1465            if expected == "SyntaxError" {
1466                assert!(
1467                    error.contains("codemode.js"),
1468                    "missing source location: {error}"
1469                );
1470            }
1471        }
1472    }
1473
1474    #[tokio::test]
1475    async fn javascript_primitive_exceptions_preserve_the_thrown_value() {
1476        let codemode = CodeMode::new(
1477            Arc::new(MemoryStore::default()),
1478            LocalExecutor::default(),
1479            Vec::new(),
1480        );
1481        let execution = codemode.execute("throw 42;").await.unwrap();
1482        assert_eq!(execution.status, ExecutionStatus::Error);
1483        assert!(
1484            execution
1485                .error
1486                .as_deref()
1487                .is_some_and(|error| error.contains("42")),
1488            "{execution:?}"
1489        );
1490    }
1491
1492    #[tokio::test]
1493    async fn actor_stack_headroom_preserves_service_after_javascript_overflow() {
1494        let service = LocalCodeModeService::spawn_with_stack_size(8 * 1024 * 1024, || {
1495            CodeMode::new(
1496                Arc::new(MemoryStore::default()),
1497                LocalExecutor::new(LocalExecutorOptions {
1498                    stack_size: 2 * 1024 * 1024,
1499                    ..LocalExecutorOptions::default()
1500                }),
1501                vec![],
1502            )
1503        })
1504        .unwrap();
1505        for (code, expected_status, expected_error) in [
1506            (
1507                "function recurse() { return recurse() + 1; } return recurse();",
1508                ExecutionStatus::Error,
1509                Some("stack overflow"),
1510            ),
1511            ("return 42;", ExecutionStatus::Completed, None),
1512        ] {
1513            let running = service
1514                .execute(code.to_string(), CodeModeRunOptions::default())
1515                .await
1516                .unwrap();
1517            let execution = tokio::time::timeout(Duration::from_secs(5), async {
1518                loop {
1519                    let execution = service.execution(running.id.clone()).await.unwrap();
1520                    if execution.status != ExecutionStatus::Running {
1521                        break execution;
1522                    }
1523                    tokio::task::yield_now().await;
1524                }
1525            })
1526            .await
1527            .expect("actor must remain responsive");
1528            assert_eq!(execution.status, expected_status, "{execution:?}");
1529            if let Some(expected) = expected_error {
1530                assert!(
1531                    execution
1532                        .error
1533                        .as_deref()
1534                        .is_some_and(|error| error.contains(expected)),
1535                    "{execution:?}"
1536                );
1537            } else {
1538                assert_eq!(execution.result, Some(json!(42)));
1539            }
1540        }
1541    }
1542}