Skip to main content

graphrt_ffi/
lib.rs

1//! # graphrt-ffi
2//!
3//! Embedding API for apps written in Kotlin (Android), Swift (iOS / macOS),
4//! Python and other languages supported by UniFFI.
5//!
6//! The surface is deliberately small and JSON-string based so it stays stable
7//! across languages and versions:
8//!
9//! ```text
10//! Runtime::new(config_json)                       // providers, env, limits
11//!   .register_wasm_plugin(bytes)                  // optional, sandboxed plugins
12//!   .register_tool_provider(name, tools, provider) // native tools of the app
13//!   .load_workflow(yaml_or_json) -> WorkflowHandle
14//! WorkflowHandle.start(inputs_json, sys_json, run_listener) -> RunHandle   // typed events
15//! WorkflowHandle.resume_paused(paused_run, secrets_json, run_listener) -> RunHandle
16//! WorkflowHandle.run(inputs_json, sys_json, listener) -> RunHandle        // raw JSON events
17//! WorkflowHandle.resume(snapshot_json, inputs_json, secrets_json, listener) -> RunHandle
18//! RunHandle.abort(reason) / pause(reason) / wait_json(timeout_ms)
19//! Runtime.set_credential_provider(provider, callback)  // keys from Keychain / Keystore
20//! Runtime.install_skill / list_lessons / decide_lesson ...  // features `skills`, `learning`
21//! validate_ui_block(json)                         // feature `ui`
22//! ```
23//!
24//! Runs execute on a Tokio runtime owned by [`Runtime`]; listener callbacks are
25//! invoked from its worker threads, never from the caller's thread. Nothing in
26//! this crate spawns processes, so every feature is usable on iOS and Android.
27//!
28//! Every exported function and type exists whatever the cargo features: a
29//! capability that is compiled out fails with [`GraphrtError::Unsupported`], so
30//! one set of generated bindings fits every build.
31//!
32//! ## Config JSON
33//!
34//! ```json
35//! {
36//!   "providers": { "OPENAI_API_KEY": "sk-...", "OLLAMA_HOST": "http://10.0.2.2:11434" },
37//!   "env": { "CRM_TOKEN": "..." },
38//!   "limits": { "max_steps": 10000, "max_duration_ms": 60000, "default_node_timeout_ms": 30000 },
39//!   "allow_private_network": false,
40//!   "knowledge": { "...": "knowledge-retrieval datasets (see graphrt-rag)" },
41//!   "mcp_servers": { "mcpServers": { "docs": { "url": "https://..." } } },
42//!   "wasm": { "fuel": 1000000000, "memory_bytes": 67108864 },
43//!   "credentials": {
44//!     "openai": { "source": "external" },
45//!     "proxy": { "source": "external", "kind": "openai", "base_url": "https://llm-proxy.example.com/v1" },
46//!     "anthropic": { "source": "token_broker", "url": "https://api.example.com/llm-token", "app_auth": "external" }
47//!   },
48//!   "skills_dir": "/data/user/0/com.example/files/graphrt/skills",
49//!   "learning_dir": "/data/user/0/com.example/files/graphrt/learning",
50//!   "workspace": { "dir": "/data/user/0/com.example/files/graphrt/workspace", "read_only": false },
51//!   "scripted_models": { "demo": [{ "text": "Hello from a scripted model." }] }
52//! }
53//! ```
54//!
55//! `skills_dir` (feature `skills`), `learning_dir` (feature `learning`) and
56//! `workspace` (feature `files`, the agents' `files` tools) must be
57//! directories in the app's own storage. `scripted_models` (feature
58//! `scripted-llm`) registers offline model providers for tests and previews.
59//!
60//! `credentials` declares providers whose keys never appear in the config: an
61//! `external` provider asks the [`CredentialProvider`] registered with
62//! [`Runtime::set_credential_provider`]; a `token_broker` provider fetches
63//! short-lived tokens from your backend. See `docs/credentials.md`.
64//!
65//! `providers` uses the same variable names as the CLI's environment
66//! (`OPENAI_API_KEY`, `OPENAI_BASE_URL`, `ANTHROPIC_API_KEY`, `OLLAMA_HOST`,
67//! `GRAPHRT_OPENAI_COMPAT_<NAME>_BASE_URL`...). `env` values are exposed to
68//! workflows only for the `env` variables a workflow declares.
69
70use std::panic::{AssertUnwindSafe, catch_unwind};
71use std::sync::{Arc, Condvar, Mutex, PoisonError, RwLock};
72use std::time::Duration;
73
74use futures::StreamExt;
75use graphrt_core::engine::{Limits, ResumeFrom};
76use graphrt_core::response::ResponseAssembler;
77use graphrt_core::snapshot::Snapshot;
78use graphrt_core::{Engine, Event, Graph, Registry, RunInput, Selector, Services, Value, Workflow};
79use indexmap::IndexMap;
80use serde::Deserialize;
81
82mod approvals;
83mod credentials;
84mod events;
85mod host_tools;
86mod learning;
87#[cfg(feature = "scripted-llm")]
88mod scripted;
89mod skills;
90mod ui;
91
92pub use approvals::{ApprovalRequest, FormAction, FormField, PausedRun, PendingToolCall, RequestKind};
93pub use credentials::{CredentialProvider, CredentialRecord};
94pub use events::{RunEvent, RunListener, RunResult, RunStatus, UiBlock};
95pub use host_tools::{HostToolCall, HostToolResult, HostToolSpec, ToolCallError, ToolProvider};
96pub use learning::{LessonDecision, LessonInfo, LessonKind, LessonProposal, LessonStatus};
97pub use skills::{SkillGrant, SkillInfo, SkillInstall};
98pub use ui::validate_ui_block;
99
100uniffi::setup_scaffolding!();
101
102/// Errors surfaced to foreign code as exceptions.
103#[derive(Debug, thiserror::Error, uniffi::Error)]
104#[non_exhaustive]
105pub enum GraphrtError {
106    /// The runtime configuration JSON is invalid.
107    #[error("invalid config: {message}")]
108    InvalidConfig { message: String },
109    /// The workflow document could not be parsed or compiled.
110    #[error("invalid workflow: {message}")]
111    InvalidWorkflow { message: String },
112    /// Run inputs, snapshot or selector JSON is invalid.
113    #[error("invalid input: {message}")]
114    InvalidInput { message: String },
115    /// A WebAssembly plugin could not be loaded.
116    #[error("plugin error: {message}")]
117    Plugin { message: String },
118    /// Internal failure (runtime could not start, lock poisoned...).
119    #[error("runtime error: {message}")]
120    Runtime { message: String },
121    /// The capability is not compiled into this build, or not configured.
122    #[error("unsupported: {message}")]
123    Unsupported { message: String },
124}
125
126impl From<uniffi::UnexpectedUniFFICallbackError> for GraphrtError {
127    fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self {
128        Self::Runtime { message: format!("callback failed: {}", e.reason) }
129    }
130}
131
132impl GraphrtError {
133    pub(crate) fn config(message: impl Into<String>) -> Self {
134        Self::InvalidConfig { message: message.into() }
135    }
136    pub(crate) fn input(message: impl Into<String>) -> Self {
137        Self::InvalidInput { message: message.into() }
138    }
139    /// `what` needs cargo feature `feature`, which this build does not have.
140    #[allow(dead_code)] // unused when every feature is on
141    pub(crate) fn unsupported(what: &str, feature: &str) -> Self {
142        Self::Unsupported { message: format!("{what} needs a build with the `{feature}` feature") }
143    }
144    /// `what` needs the config key `key`.
145    #[allow(dead_code)] // unused when no feature needs a config key
146    pub(crate) fn not_configured(what: &str, key: &str) -> Self {
147        Self::Unsupported { message: format!("{what} needs `{key}` in the runtime config") }
148    }
149}
150
151/// Receives the events of one run. Implemented in the host language.
152///
153/// Callbacks run on a background thread; marshal to your UI thread yourself.
154/// Exceptions thrown by a callback are swallowed so they cannot break the run.
155#[uniffi::export(with_foreign)]
156pub trait EventListener: Send + Sync {
157    /// Every raw engine event, as JSON (`{"type": "node_started", ...}`).
158    fn on_event(&self, event_json: String);
159    /// Ordered user-facing answer text (answer nodes), streamed as it is produced.
160    fn on_answer_chunk(&self, text: String);
161    /// Called exactly once with the final result (see [`RunHandle::wait_json`]).
162    fn on_finish(&self, result_json: String);
163}
164
165/// Version of the embedded runtime.
166#[uniffi::export]
167pub fn graphrt_version() -> String {
168    env!("CARGO_PKG_VERSION").to_owned()
169}
170
171#[derive(Debug, Default, Deserialize)]
172#[serde(deny_unknown_fields)]
173struct RuntimeConfig {
174    #[serde(default)]
175    providers: IndexMap<String, String>,
176    #[serde(default)]
177    env: IndexMap<String, String>,
178    #[serde(default)]
179    limits: LimitsConfig,
180    #[serde(default)]
181    allow_private_network: bool,
182    #[serde(default)]
183    knowledge: Option<serde_json::Value>,
184    #[serde(default)]
185    mcp_servers: Option<serde_json::Value>,
186    #[serde(default)]
187    wasm: WasmConfig,
188    #[serde(default)]
189    credentials: IndexMap<String, graphrt_llm::credential_config::ProviderCredentialConfig>,
190    /// Feature `skills`: the skill store's directory.
191    #[serde(default)]
192    skills_dir: Option<String>,
193    /// Feature `learning`: the lesson store's directory.
194    #[serde(default)]
195    learning_dir: Option<String>,
196    /// Feature `files`: the agents' file workspace.
197    #[serde(default)]
198    workspace: Option<WorkspaceConfig>,
199    /// Feature `scripted-llm`: offline model providers.
200    #[serde(default)]
201    scripted_models: Option<serde_json::Value>,
202}
203
204#[derive(Debug, Deserialize)]
205#[serde(deny_unknown_fields)]
206#[cfg_attr(not(feature = "files"), allow(dead_code))]
207struct WorkspaceConfig {
208    dir: String,
209    #[serde(default)]
210    read_only: bool,
211    max_file_bytes: Option<u64>,
212    max_total_bytes: Option<u64>,
213    max_files: Option<usize>,
214}
215
216#[derive(Debug, Default, Deserialize)]
217#[serde(deny_unknown_fields)]
218struct LimitsConfig {
219    max_steps: Option<u64>,
220    max_duration_ms: Option<u64>,
221    max_depth: Option<u32>,
222    default_node_timeout_ms: Option<u64>,
223    max_concurrency: Option<usize>,
224    /// Token budget of a run, child runs included.
225    max_total_tokens: Option<u64>,
226    /// Cost budget of a run in micro units of the providers' price unit.
227    max_cost_micros: Option<u64>,
228}
229
230impl LimitsConfig {
231    fn to_limits(&self) -> Limits {
232        let mut limits = Limits::default();
233        if let Some(v) = self.max_steps {
234            limits.max_steps = v;
235        }
236        if self.max_duration_ms.is_some() {
237            limits.max_duration_ms = self.max_duration_ms;
238        }
239        if let Some(v) = self.max_depth {
240            limits.max_depth = v;
241        }
242        if self.default_node_timeout_ms.is_some() {
243            limits.default_node_timeout_ms = self.default_node_timeout_ms;
244        }
245        if let Some(v) = self.max_concurrency {
246            limits.max_concurrency = v.max(1);
247        }
248        limits.max_total_tokens = self.max_total_tokens;
249        limits.max_cost_micros = self.max_cost_micros;
250        limits
251    }
252}
253
254#[derive(Debug, Default, Deserialize)]
255#[serde(deny_unknown_fields)]
256struct WasmConfig {
257    fuel: Option<u64>,
258    memory_bytes: Option<usize>,
259    module_bytes: Option<usize>,
260}
261
262impl WasmConfig {
263    fn to_limits(&self) -> graphrt_wasm::WasmLimits {
264        let mut limits = graphrt_wasm::WasmLimits::default();
265        if let Some(v) = self.fuel {
266            limits.fuel = v;
267        }
268        if let Some(v) = self.memory_bytes {
269            limits.memory_bytes = v;
270        }
271        if let Some(v) = self.module_bytes {
272            limits.module_bytes = v;
273        }
274        limits
275    }
276}
277
278/// A configured runtime: node registry, host services and a thread pool.
279/// Create one per app and share it.
280#[derive(uniffi::Object)]
281pub struct Runtime {
282    /// Always `Some` until drop; taken in `Drop` to shut down without blocking.
283    tokio: Option<tokio::runtime::Runtime>,
284    registry: Mutex<Registry>,
285    /// Replaced (never mutated) when a tool provider is registered; workflows
286    /// loaded before keep the services they were compiled with.
287    services: RwLock<Arc<Services>>,
288    env: IndexMap<String, String>,
289    limits: Limits,
290    wasm_limits: graphrt_wasm::WasmLimits,
291    credentials: graphrt_llm::credential_config::HostCredentials,
292    #[cfg_attr(not(feature = "skills"), allow(dead_code))]
293    skills: Option<skills::Store>,
294    #[cfg_attr(not(feature = "learning"), allow(dead_code))]
295    lessons: Option<learning::Store>,
296}
297
298impl Drop for Runtime {
299    fn drop(&mut self) {
300        // Do not block the dropping thread (often a UI thread) on node work that is
301        // still finishing in the blocking pool (e.g. an aborted code node).
302        if let Some(rt) = self.tokio.take() {
303            rt.shutdown_background();
304        }
305    }
306}
307
308impl std::fmt::Debug for Runtime {
309    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310        f.debug_struct("Runtime").field("limits", &self.limits).finish_non_exhaustive()
311    }
312}
313
314fn base_registry() -> Registry {
315    let mut registry = Registry::with_builtins();
316    graphrt_llm::register(&mut registry);
317    graphrt_http::register(&mut registry);
318    #[cfg(feature = "code-js")]
319    graphrt_code::register(&mut registry);
320    #[cfg(feature = "doc")]
321    graphrt_doc::register(&mut registry);
322    #[cfg(feature = "rag")]
323    graphrt_rag::register(&mut registry);
324    registry
325}
326
327#[uniffi::export]
328impl Runtime {
329    /// Create a runtime from a config JSON document (`"{}"` for defaults).
330    /// May perform network I/O (MCP handshakes); call it off the UI thread.
331    #[uniffi::constructor]
332    pub fn new(config_json: String) -> Result<Arc<Self>, GraphrtError> {
333        let text = if config_json.trim().is_empty() { "{}" } else { config_json.as_str() };
334        let config: RuntimeConfig = serde_json::from_str(text).map_err(|e| GraphrtError::config(e.to_string()))?;
335        let tokio = tokio::runtime::Builder::new_multi_thread()
336            .worker_threads(2)
337            .thread_name("graphrt")
338            .enable_time()
339            .enable_io()
340            .build()
341            .map_err(|e| GraphrtError::Runtime { message: format!("cannot start runtime: {e}") })?;
342
343        let vars: Vec<(String, String)> = config.providers.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
344        let lookup =
345            |name: &str| -> Option<String> { config.providers.get(name).or_else(|| config.env.get(name)).cloned() };
346
347        let mut services = Services::new();
348        let mut models =
349            graphrt_llm::ModelRegistry::from_vars(&vars).map_err(|e| GraphrtError::config(e.to_string()))?;
350        install_scripted_models(&mut models, config.scripted_models)?;
351        // Credentialed providers replace env-configured ones of the same name; their
352        // keys come from the host at request time, never from this config.
353        let host_credentials = graphrt_llm::credential_config::HostCredentials::new();
354        // A `typesafe`-kind entry is never registered as a chat model: it becomes the
355        // System One client, built from the same cached credential source.
356        let applied = graphrt_llm::credential_config::apply(&mut models, &config.credentials, &host_credentials)
357            .map_err(|e| GraphrtError::config(e.to_string()))?;
358        services.insert(models);
359
360        // TypeSafe System One (Jev): a `typesafe` credentials entry (token broker /
361        // host keychain) wins over a static `TYPESAFE_API_KEY` provider variable.
362        let typesafe = match applied.system_one {
363            Some(client) => Some(client),
364            None => graphrt_llm::typesafe::SystemOneClient::from_vars(&vars)
365                .map_err(|e| GraphrtError::config(e.to_string()))?,
366        };
367        if let Some(client) = typesafe {
368            services.insert(Arc::new(client));
369        }
370
371        let policy = graphrt_http::EgressPolicy { allow_private: config.allow_private_network, ..Default::default() };
372        let client = graphrt_http::HttpClient::new(policy).map_err(|e| GraphrtError::config(e.to_string()))?;
373        services.insert(client);
374
375        let mut tools = tokio.block_on(build_tools(config.mcp_servers.as_ref()))?;
376        #[allow(unused_mut)]
377        let mut files = graphrt_core::file::ChainResolver::with_data_urls();
378        if let Some(workspace) = &config.workspace {
379            files = install_workspace(workspace, &mut tools, files)?;
380        }
381        let resolver: Arc<dyn graphrt_core::file::FileResolver> = Arc::new(files);
382        // Every image a model node sends is checked, stripped of metadata and downscaled.
383        #[cfg(feature = "image")]
384        {
385            let preparer: Arc<dyn graphrt_core::file::ImagePreparer> = Arc::new(graphrt_image::VisionPreparer::new(
386                Arc::clone(&resolver),
387                graphrt_image::ImageLimits::default(),
388            ));
389            services.insert(preparer);
390        }
391        services.insert(resolver);
392        services.insert(tools);
393
394        #[cfg(feature = "skills")]
395        let skills = config.skills_dir.as_deref().map(|dir| skills::install(dir, &mut services));
396        #[cfg(not(feature = "skills"))]
397        let skills = match config.skills_dir {
398            Some(_) => return Err(GraphrtError::config("`skills_dir` requires the `skills` feature")),
399            None => None,
400        };
401        #[cfg(feature = "learning")]
402        let lessons = config.learning_dir.as_deref().map(|dir| learning::install(dir, &mut services));
403        #[cfg(not(feature = "learning"))]
404        let lessons = match config.learning_dir {
405            Some(_) => return Err(GraphrtError::config("`learning_dir` requires the `learning` feature")),
406            None => None,
407        };
408
409        #[cfg(feature = "rag")]
410        if let Some(raw) = &config.knowledge {
411            let kb_config: graphrt_rag::KnowledgeConfig =
412                serde_json::from_value(raw.clone()).map_err(|e| GraphrtError::config(format!("knowledge: {e}")))?;
413            let kb = kb_config.build_with_env(&lookup).map_err(|e| GraphrtError::config(format!("knowledge: {e}")))?;
414            services.insert(kb);
415        }
416        #[cfg(not(feature = "rag"))]
417        if config.knowledge.is_some() {
418            return Err(GraphrtError::config("`knowledge` requires the `rag` feature"));
419        }
420        let _ = &lookup;
421
422        Ok(Arc::new(Self {
423            tokio: Some(tokio),
424            registry: Mutex::new(base_registry()),
425            services: RwLock::new(Arc::new(services)),
426            env: config.env,
427            limits: config.limits.to_limits(),
428            wasm_limits: config.wasm.to_limits(),
429            credentials: host_credentials,
430            skills,
431            lessons,
432        }))
433    }
434
435    /// Register native tools implemented by the app under provider `name`.
436    /// Agents list them in `tools` as `<name>/<tool>`, or all of them with a `*` as the tool; `require_approval`
437    /// of an `agent` node can hold their calls for approval. Workflows loaded
438    /// after this call see the tools. Fails when the name is taken (by an MCP
439    /// server, the `files` workspace or an earlier provider) or a declaration
440    /// is invalid.
441    pub fn register_tool_provider(
442        &self,
443        name: String,
444        tools: Vec<HostToolSpec>,
445        provider: Arc<dyn ToolProvider>,
446    ) -> Result<(), GraphrtError> {
447        let runtime = host_tools::HostTools::new(&name, tools, provider)?;
448        let mut slot = self.services.write().unwrap_or_else(PoisonError::into_inner);
449        let mut services = Services::clone(&slot);
450        let mut registry = services.get::<graphrt_core::tool::ToolRegistry>().cloned().unwrap_or_default();
451        if registry.get(&name).is_some() {
452            return Err(GraphrtError::input(format!("tool provider `{name}` is already registered")));
453        }
454        registry.add(name, Arc::new(runtime));
455        services.insert(registry);
456        *slot = Arc::new(services);
457        Ok(())
458    }
459
460    /// Names of the registered tool providers (MCP servers, `files`, the app's own).
461    pub fn tool_providers(&self) -> Vec<String> {
462        let services = self.current_services();
463        services
464            .get::<graphrt_core::tool::ToolRegistry>()
465            .map(|r| r.providers().map(|(name, _)| name.to_owned()).collect())
466            .unwrap_or_default()
467    }
468
469    /// Register the host's credential callback for `provider` (a name from the
470    /// config's `credentials` section), or `"*"` for every provider. Replaces any
471    /// previous callback and drops every cached credential, so it takes effect for
472    /// requests made after the call (e.g. a different user signed in).
473    pub fn set_credential_provider(&self, provider: String, callback: Arc<dyn CredentialProvider>) {
474        self.credentials.set(provider, Arc::new(credentials::ForeignCredentials::new(callback)));
475    }
476
477    /// Remove the credential callback registered for `provider` (or `"*"`) and drop
478    /// every cached credential (sign-out takes effect on the next request).
479    pub fn clear_credential_provider(&self, provider: String) {
480        self.credentials.remove(&provider);
481    }
482
483    /// Drop every cached credential without changing the registered callbacks
484    /// (e.g. the user signed out of your backend and broker tokens must not be reused).
485    pub fn clear_credential_cache(&self) {
486        self.credentials.clear_cache();
487    }
488
489    /// Load a sandboxed WebAssembly plugin; its node kinds become available to
490    /// workflows loaded afterwards. Returns the registered kinds.
491    pub fn register_wasm_plugin(&self, wasm: Vec<u8>) -> Result<Vec<String>, GraphrtError> {
492        let plugin = graphrt_wasm::WasmPlugin::load(&wasm, self.wasm_limits.clone())
493            .map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
494        let kinds = plugin.descriptors().into_iter().map(|d| d.kind).collect();
495        let mut registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
496        plugin.register(&mut registry).map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
497        Ok(kinds)
498    }
499
500    /// Catalog of every node kind available in this runtime, as a JSON array.
501    pub fn catalog_json(&self) -> String {
502        let registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
503        serde_json::to_string(&registry.descriptors()).unwrap_or_else(|_| "[]".to_owned())
504    }
505
506    /// Parse and compile a workflow (YAML or JSON).
507    pub fn load_workflow(self: Arc<Self>, document: String) -> Result<Arc<WorkflowHandle>, GraphrtError> {
508        let workflow =
509            Workflow::parse(&document).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
510        let graph = {
511            let registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
512            Graph::build(workflow, &registry).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?
513        };
514        let graph = Arc::new(graph);
515        let engine = Engine::new(graph.clone())
516            .with_shared_services(self.current_services())
517            .with_clock(Arc::new(graphrt_core::node::TokioClock))
518            .with_limits(self.limits.clone());
519        Ok(Arc::new(WorkflowHandle { runtime: self, graph, engine }))
520    }
521
522    /// Open a portable bundle (`.grt` bytes), register its WebAssembly plugins and
523    /// compile its entry workflow. Every file is checked against the manifest's
524    /// SHA-256; when `trusted_keys` (hex Ed25519 public keys) is non-empty, the
525    /// bundle must be signed by one of them. Bundles needing process or HTTP
526    /// plugins are rejected: embedded hosts cannot spawn processes.
527    pub fn load_bundle(
528        self: Arc<Self>,
529        bundle: Vec<u8>,
530        trusted_keys: Vec<String>,
531    ) -> Result<Arc<WorkflowHandle>, GraphrtError> {
532        let mut options = graphrt_bundle::OpenOptions::default();
533        for key in trusted_keys {
534            options = options.trust_key(key);
535        }
536        let opened = graphrt_bundle::Bundle::open(&bundle, &options)
537            .map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
538        let non_portable: Vec<&str> =
539            opened.manifest().requires.plugins.iter().filter(|p| !p.portable).map(|p| p.name.as_str()).collect();
540        if !non_portable.is_empty() {
541            return Err(GraphrtError::Plugin {
542                message: format!(
543                    "bundle needs process/http plugins ({}), which cannot run embedded",
544                    non_portable.join(", ")
545                ),
546            });
547        }
548        let workflow = opened.workflow(None).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
549        let graph = {
550            let mut registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
551            opened
552                .register_wasm_plugins(&mut registry, &self.wasm_limits)
553                .map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
554            let report = opened.check(&registry);
555            if let Some(mismatch) = report.version_mismatch {
556                return Err(GraphrtError::InvalidWorkflow { message: mismatch });
557            }
558            Graph::build(workflow, &registry).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?
559        };
560        let graph = Arc::new(graph);
561        let engine = Engine::new(graph.clone())
562            .with_shared_services(self.current_services())
563            .with_clock(Arc::new(graphrt_core::node::TokioClock))
564            .with_limits(self.limits.clone());
565        Ok(Arc::new(WorkflowHandle { runtime: self, graph, engine }))
566    }
567}
568
569impl Runtime {
570    fn current_services(&self) -> Arc<Services> {
571        Arc::clone(&self.services.read().unwrap_or_else(PoisonError::into_inner))
572    }
573}
574
575#[cfg(feature = "scripted-llm")]
576fn install_scripted_models(
577    models: &mut graphrt_llm::ModelRegistry,
578    raw: Option<serde_json::Value>,
579) -> Result<(), GraphrtError> {
580    let Some(raw) = raw else {
581        return Ok(());
582    };
583    let scripts = serde_json::from_value(raw).map_err(|e| GraphrtError::config(format!("scripted_models: {e}")))?;
584    scripted::register(models, scripts)
585}
586
587#[cfg(not(feature = "scripted-llm"))]
588fn install_scripted_models(
589    _models: &mut graphrt_llm::ModelRegistry,
590    raw: Option<serde_json::Value>,
591) -> Result<(), GraphrtError> {
592    match raw {
593        Some(_) => Err(GraphrtError::config("`scripted_models` requires the `scripted-llm` feature")),
594        None => Ok(()),
595    }
596}
597
598/// Open the agents' workspace: the `files` tools and a resolver for the files they store.
599#[cfg(feature = "files")]
600fn install_workspace(
601    config: &WorkspaceConfig,
602    tools: &mut graphrt_core::tool::ToolRegistry,
603    files: graphrt_core::file::ChainResolver,
604) -> Result<graphrt_core::file::ChainResolver, GraphrtError> {
605    use graphrt_files::{FileTools, PROVIDER, Workspace, WorkspaceLimits, WorkspaceResolver};
606    let defaults = WorkspaceLimits::default();
607    let limits = WorkspaceLimits {
608        read_only: config.read_only,
609        max_file_bytes: config.max_file_bytes.unwrap_or(defaults.max_file_bytes),
610        max_total_bytes: config.max_total_bytes.unwrap_or(defaults.max_total_bytes),
611        max_files: config.max_files.unwrap_or(defaults.max_files),
612        ..defaults
613    };
614    let workspace = Workspace::dir(&config.dir, limits)
615        .map_err(|e| GraphrtError::config(format!("workspace `{}`: {e}", config.dir)))?;
616    if tools.get(PROVIDER).is_some() {
617        return Err(GraphrtError::config(format!(
618            "tool provider `{PROVIDER}` is defined by an MCP server and by `workspace`; rename the server"
619        )));
620    }
621    tools.add(PROVIDER, Arc::new(FileTools::new(workspace.clone())));
622    Ok(files.then(Arc::new(WorkspaceResolver::new(workspace))))
623}
624
625#[cfg(not(feature = "files"))]
626fn install_workspace(
627    _config: &WorkspaceConfig,
628    _tools: &mut graphrt_core::tool::ToolRegistry,
629    _files: graphrt_core::file::ChainResolver,
630) -> Result<graphrt_core::file::ChainResolver, GraphrtError> {
631    Err(GraphrtError::config("`workspace` requires the `files` feature"))
632}
633
634async fn build_tools(raw: Option<&serde_json::Value>) -> Result<graphrt_core::tool::ToolRegistry, GraphrtError> {
635    let Some(raw) = raw else {
636        return Ok(graphrt_core::tool::ToolRegistry::new());
637    };
638    #[cfg(feature = "mcp-http")]
639    {
640        let servers: graphrt_mcp::McpServers =
641            serde_json::from_value(raw.clone()).map_err(|e| GraphrtError::config(format!("mcp_servers: {e}")))?;
642        let configs = servers.into_configs();
643        for cfg in &configs {
644            if !matches!(cfg.transport, graphrt_mcp::McpTransport::Http(_)) {
645                return Err(GraphrtError::config(format!(
646                    "mcp server `{}`: only HTTP servers are supported when embedded (no process spawning)",
647                    cfg.name
648                )));
649            }
650        }
651        graphrt_mcp::connect_all(&configs).await.map_err(|e| GraphrtError::config(format!("mcp: {e}")))
652    }
653    #[cfg(not(feature = "mcp-http"))]
654    {
655        let _ = raw;
656        Err(GraphrtError::config("`mcp_servers` requires the `mcp-http` feature"))
657    }
658}
659
660/// A compiled workflow, ready to run any number of times concurrently.
661#[derive(uniffi::Object)]
662pub struct WorkflowHandle {
663    runtime: Arc<Runtime>,
664    graph: Arc<Graph>,
665    engine: Engine,
666}
667
668impl std::fmt::Debug for WorkflowHandle {
669    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
670        f.debug_struct("WorkflowHandle").field("graph", &self.graph).finish_non_exhaustive()
671    }
672}
673
674#[uniffi::export]
675impl WorkflowHandle {
676    /// Workflow name from the document, if any.
677    pub fn name(&self) -> Option<String> {
678        self.graph.workflow().name.clone()
679    }
680
681    /// Non-fatal findings from compilation (e.g. unreachable nodes).
682    pub fn warnings(&self) -> Vec<String> {
683        self.graph.warnings().to_vec()
684    }
685
686    /// Descriptors of the node kinds this workflow uses, as a JSON array.
687    pub fn catalog_json(&self) -> String {
688        let registry = self.runtime.registry.lock().unwrap_or_else(PoisonError::into_inner);
689        let mut kinds: Vec<&str> = self.graph.nodes().iter().map(|n| n.kind.as_ref()).collect();
690        kinds.sort_unstable();
691        kinds.dedup();
692        let descriptors: Vec<_> = kinds.into_iter().filter_map(|k| registry.descriptor(k)).collect();
693        serde_json::to_string(&descriptors).unwrap_or_else(|_| "[]".to_owned())
694    }
695
696    /// The workflow document as canonical JSON.
697    pub fn document_json(&self) -> String {
698        serde_json::to_string(self.graph.workflow()).unwrap_or_default()
699    }
700
701    /// Start a run. `inputs_json` / `sys_json` are JSON objects (`"{}"` when empty).
702    pub fn run(
703        &self,
704        inputs_json: String,
705        sys_json: String,
706        listener: Arc<dyn EventListener>,
707    ) -> Result<Arc<RunHandle>, GraphrtError> {
708        let mut input = self.base_input(&sys_json)?;
709        input.inputs = parse_object(&inputs_json, "inputs")?;
710        Ok(self.launch(input, None, Sink::Raw(listener)))
711    }
712
713    /// Start a run whose events arrive typed ([`RunEvent`]). It ends with
714    /// [`RunEvent::Paused`] or [`RunEvent::Finished`].
715    pub fn start(
716        &self,
717        inputs_json: String,
718        sys_json: String,
719        listener: Arc<dyn RunListener>,
720    ) -> Result<Arc<RunHandle>, GraphrtError> {
721        let mut input = self.base_input(&sys_json)?;
722        input.inputs = parse_object(&inputs_json, "inputs")?;
723        Ok(self.launch(input, None, Sink::Typed(listener)))
724    }
725
726    /// Resume a paused run with the answers given on `paused`
727    /// ([`PausedRun::approve`], [`PausedRun::answer`]...). `secrets_json`
728    /// re-supplies non-env secrets as `{"namespace.name": "value"}`.
729    pub fn resume_paused(
730        &self,
731        paused: Arc<PausedRun>,
732        secrets_json: String,
733        listener: Arc<dyn RunListener>,
734    ) -> Result<Arc<RunHandle>, GraphrtError> {
735        let inputs = paused.inputs().into_iter().map(|(k, v)| (k, Value::from_json(v))).collect();
736        self.resume_from(paused.snapshot().clone(), inputs, &secrets_json, Sink::Typed(listener))
737    }
738
739    /// Resume a paused run from the snapshot carried by its `run_paused` event.
740    /// `inputs_json` maps paused node ids (or `frame/node` ids) to their input,
741    /// e.g. `{"review": {"action": "approve", "values": {}}}`. `secrets_json`
742    /// re-supplies non-env secrets as `{"namespace.name": "value"}`.
743    pub fn resume(
744        &self,
745        snapshot_json: String,
746        inputs_json: String,
747        secrets_json: String,
748        listener: Arc<dyn EventListener>,
749    ) -> Result<Arc<RunHandle>, GraphrtError> {
750        let snapshot =
751            Snapshot::from_json(&snapshot_json).map_err(|e| GraphrtError::input(format!("snapshot: {e}")))?;
752        let inputs = parse_object(&inputs_json, "inputs")?;
753        self.resume_from(snapshot, inputs, &secrets_json, Sink::Raw(listener))
754    }
755}
756
757/// Where the events of a run go.
758enum Sink {
759    Raw(Arc<dyn EventListener>),
760    Typed(Arc<dyn RunListener>),
761}
762
763impl Sink {
764    fn event(&self, event: &Event, typed: &mut Vec<RunEvent>) {
765        match self {
766            Sink::Raw(listener) => {
767                if let Ok(json) = serde_json::to_string(event) {
768                    notify(|| listener.on_event(json));
769                }
770            }
771            Sink::Typed(listener) => {
772                events::translate(event, typed);
773                for event in typed.drain(..) {
774                    notify(|| listener.on_event(event));
775                }
776            }
777        }
778    }
779
780    fn chunk(&self, text: String) {
781        match self {
782            Sink::Raw(listener) => notify(|| listener.on_answer_chunk(text)),
783            Sink::Typed(listener) => notify(|| listener.on_event(RunEvent::AnswerChunk { text })),
784        }
785    }
786
787    fn finish(&self, terminal: Option<&Event>, answer: &str, result: String) {
788        match self {
789            Sink::Raw(listener) => notify(|| listener.on_finish(result)),
790            Sink::Typed(listener) => {
791                let event = events::terminal(terminal, answer, result);
792                notify(|| listener.on_event(event));
793            }
794        }
795    }
796}
797
798impl WorkflowHandle {
799    fn resume_from(
800        &self,
801        snapshot: Snapshot,
802        inputs: IndexMap<String, Value>,
803        secrets_json: &str,
804        sink: Sink,
805    ) -> Result<Arc<RunHandle>, GraphrtError> {
806        let mut input = self.base_input("{}")?;
807        let mut resume = ResumeFrom::new(snapshot.clone(), inputs);
808        let secrets: IndexMap<String, String> = if secrets_json.trim().is_empty() {
809            IndexMap::new()
810        } else {
811            serde_json::from_str(secrets_json).map_err(|e| GraphrtError::input(format!("secrets: {e}")))?
812        };
813        for (selector, value) in secrets {
814            resume = resume.secret(selector, value);
815        }
816        input.resume = Some(resume);
817        Ok(self.launch(input, Some(snapshot), sink))
818    }
819}
820
821impl WorkflowHandle {
822    fn base_input(&self, sys_json: &str) -> Result<RunInput, GraphrtError> {
823        let mut input = RunInput::new();
824        input.sys = parse_object(sys_json, "sys")?;
825        for decl in &self.graph.workflow().env {
826            if let Some(value) = self.runtime.env.get(&decl.name) {
827                input.env.insert(decl.name.clone(), Value::from(value.as_str()));
828            }
829        }
830        Ok(input)
831    }
832
833    fn launch(&self, input: RunInput, resumed_from: Option<Snapshot>, sink: Sink) -> Arc<RunHandle> {
834        let mut assembler = ResponseAssembler::new(&self.graph);
835        for (k, v) in &input.sys {
836            assembler = assembler.with_value(&Selector::of("sys", k), v.clone());
837        }
838        if let Some(snapshot) = &resumed_from {
839            assembler = assembler.resume_from(&snapshot.root);
840        }
841        let mut stream = self.engine.run(input);
842        let run = Arc::new(RunHandle { control: stream.handle(), result: Mutex::new(None), done: Condvar::new() });
843        let task_run = run.clone();
844        let Some(tokio) = self.runtime.tokio.as_ref() else {
845            let result = result_json(None, "");
846            run.complete(result.clone());
847            sink.finish(None, "", result);
848            return run;
849        };
850        tokio.spawn(async move {
851            let mut terminal: Option<Event> = None;
852            let mut chunks = Vec::new();
853            let mut typed = Vec::new();
854            while let Some(event) = stream.next().await {
855                // The terminal event goes out last, after the final answer chunks.
856                if !event.is_terminal() {
857                    sink.event(&event, &mut typed);
858                }
859                assembler.push_into(&event, &mut chunks);
860                for chunk in chunks.drain(..) {
861                    if !chunk.text.is_empty() {
862                        sink.chunk(chunk.text);
863                    }
864                }
865                if event.is_terminal() {
866                    terminal = Some(event);
867                }
868            }
869            for chunk in assembler.finish() {
870                if !chunk.text.is_empty() {
871                    sink.chunk(chunk.text);
872                }
873            }
874            if let (Some(event), Sink::Raw(_)) = (&terminal, &sink) {
875                sink.event(event, &mut typed);
876            }
877            let answer = assembler.text_so_far().to_owned();
878            let result = result_json(terminal.as_ref(), &answer);
879            task_run.complete(result.clone());
880            sink.finish(terminal.as_ref(), &answer, result);
881        });
882        run
883    }
884}
885
886/// Invoke a foreign callback, containing any panic it causes.
887fn notify(f: impl FnOnce()) {
888    let _ = catch_unwind(AssertUnwindSafe(f));
889}
890
891fn parse_object(json: &str, what: &str) -> Result<IndexMap<String, Value>, GraphrtError> {
892    if json.trim().is_empty() {
893        return Ok(IndexMap::new());
894    }
895    let raw: serde_json::Value = serde_json::from_str(json).map_err(|e| GraphrtError::input(format!("{what}: {e}")))?;
896    match raw {
897        serde_json::Value::Object(map) => Ok(map.into_iter().map(|(k, v)| (k, Value::from_json(v))).collect()),
898        serde_json::Value::Null => Ok(IndexMap::new()),
899        _ => Err(GraphrtError::input(format!("{what}: expected a JSON object"))),
900    }
901}
902
903/// Final result: the terminal event's fields plus `status` and the assembled `answer`.
904fn result_json(terminal: Option<&Event>, answer: &str) -> String {
905    let status = RunStatus::of(terminal).as_str();
906    let mut body = match terminal.map(serde_json::to_value) {
907        Some(Ok(serde_json::Value::Object(map))) => map,
908        _ => {
909            let mut map = serde_json::Map::new();
910            map.insert("error".into(), serde_json::Value::from("run ended without a terminal event"));
911            map.insert("error_type".into(), serde_json::Value::from("internal"));
912            map
913        }
914    };
915    body.remove("type");
916    body.insert("status".into(), serde_json::Value::from(status));
917    body.insert("answer".into(), serde_json::Value::from(answer));
918    serde_json::Value::Object(body).to_string()
919}
920
921/// Controls one run.
922#[derive(uniffi::Object)]
923pub struct RunHandle {
924    control: graphrt_core::RunHandle,
925    result: Mutex<Option<String>>,
926    done: Condvar,
927}
928
929impl std::fmt::Debug for RunHandle {
930    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
931        f.debug_struct("RunHandle").field("finished", &self.is_finished()).finish_non_exhaustive()
932    }
933}
934
935impl RunHandle {
936    fn complete(&self, result: String) {
937        let mut slot = self.result.lock().unwrap_or_else(PoisonError::into_inner);
938        *slot = Some(result);
939        self.done.notify_all();
940    }
941}
942
943#[uniffi::export]
944impl RunHandle {
945    /// Cancel the run immediately. It ends with status `aborted`.
946    pub fn abort(&self, reason: String) {
947        self.control.abort(reason);
948    }
949
950    /// Stop scheduling new nodes; the run ends with status `paused` and a snapshot.
951    pub fn pause(&self, reason: String) {
952        self.control.pause(reason);
953    }
954
955    /// Write a variable (`"conversation.topic"`) while the run is in progress.
956    pub fn update_variable(&self, selector: String, value_json: String) -> Result<(), GraphrtError> {
957        let selector = Selector::parse(&selector).map_err(|e| GraphrtError::input(e.to_string()))?;
958        let value: serde_json::Value =
959            serde_json::from_str(&value_json).map_err(|e| GraphrtError::input(format!("value: {e}")))?;
960        self.control.update_variable(selector, Value::from_json(value));
961        Ok(())
962    }
963
964    pub fn is_finished(&self) -> bool {
965        self.result.lock().unwrap_or_else(PoisonError::into_inner).is_some()
966    }
967
968    /// Block until the run finishes (or `timeout_ms` elapses) and return the result
969    /// JSON (`{"status": "succeeded"|"failed"|"aborted"|"paused", "answer": ..., ...}`).
970    /// Returns `None` on timeout. Do not call from a UI thread.
971    pub fn wait_json(&self, timeout_ms: u64) -> Option<String> {
972        let guard = self.result.lock().unwrap_or_else(PoisonError::into_inner);
973        let (guard, _) = self
974            .done
975            .wait_timeout_while(guard, Duration::from_millis(timeout_ms), |r| r.is_none())
976            .unwrap_or_else(PoisonError::into_inner);
977        guard.clone()
978    }
979}