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}
225
226impl LimitsConfig {
227    fn to_limits(&self) -> Limits {
228        let mut limits = Limits::default();
229        if let Some(v) = self.max_steps {
230            limits.max_steps = v;
231        }
232        if self.max_duration_ms.is_some() {
233            limits.max_duration_ms = self.max_duration_ms;
234        }
235        if let Some(v) = self.max_depth {
236            limits.max_depth = v;
237        }
238        if self.default_node_timeout_ms.is_some() {
239            limits.default_node_timeout_ms = self.default_node_timeout_ms;
240        }
241        if let Some(v) = self.max_concurrency {
242            limits.max_concurrency = v.max(1);
243        }
244        limits
245    }
246}
247
248#[derive(Debug, Default, Deserialize)]
249#[serde(deny_unknown_fields)]
250struct WasmConfig {
251    fuel: Option<u64>,
252    memory_bytes: Option<usize>,
253    module_bytes: Option<usize>,
254}
255
256impl WasmConfig {
257    fn to_limits(&self) -> graphrt_wasm::WasmLimits {
258        let mut limits = graphrt_wasm::WasmLimits::default();
259        if let Some(v) = self.fuel {
260            limits.fuel = v;
261        }
262        if let Some(v) = self.memory_bytes {
263            limits.memory_bytes = v;
264        }
265        if let Some(v) = self.module_bytes {
266            limits.module_bytes = v;
267        }
268        limits
269    }
270}
271
272/// A configured runtime: node registry, host services and a thread pool.
273/// Create one per app and share it.
274#[derive(uniffi::Object)]
275pub struct Runtime {
276    /// Always `Some` until drop; taken in `Drop` to shut down without blocking.
277    tokio: Option<tokio::runtime::Runtime>,
278    registry: Mutex<Registry>,
279    /// Replaced (never mutated) when a tool provider is registered; workflows
280    /// loaded before keep the services they were compiled with.
281    services: RwLock<Arc<Services>>,
282    env: IndexMap<String, String>,
283    limits: Limits,
284    wasm_limits: graphrt_wasm::WasmLimits,
285    credentials: graphrt_llm::credential_config::HostCredentials,
286    #[cfg_attr(not(feature = "skills"), allow(dead_code))]
287    skills: Option<skills::Store>,
288    #[cfg_attr(not(feature = "learning"), allow(dead_code))]
289    lessons: Option<learning::Store>,
290}
291
292impl Drop for Runtime {
293    fn drop(&mut self) {
294        // Do not block the dropping thread (often a UI thread) on node work that is
295        // still finishing in the blocking pool (e.g. an aborted code node).
296        if let Some(rt) = self.tokio.take() {
297            rt.shutdown_background();
298        }
299    }
300}
301
302impl std::fmt::Debug for Runtime {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        f.debug_struct("Runtime").field("limits", &self.limits).finish_non_exhaustive()
305    }
306}
307
308fn base_registry() -> Registry {
309    let mut registry = Registry::with_builtins();
310    graphrt_llm::register(&mut registry);
311    graphrt_http::register(&mut registry);
312    #[cfg(feature = "code-js")]
313    graphrt_code::register(&mut registry);
314    #[cfg(feature = "doc")]
315    graphrt_doc::register(&mut registry);
316    #[cfg(feature = "rag")]
317    graphrt_rag::register(&mut registry);
318    registry
319}
320
321#[uniffi::export]
322impl Runtime {
323    /// Create a runtime from a config JSON document (`"{}"` for defaults).
324    /// May perform network I/O (MCP handshakes); call it off the UI thread.
325    #[uniffi::constructor]
326    pub fn new(config_json: String) -> Result<Arc<Self>, GraphrtError> {
327        let text = if config_json.trim().is_empty() { "{}" } else { config_json.as_str() };
328        let config: RuntimeConfig = serde_json::from_str(text).map_err(|e| GraphrtError::config(e.to_string()))?;
329        let tokio = tokio::runtime::Builder::new_multi_thread()
330            .worker_threads(2)
331            .thread_name("graphrt")
332            .enable_time()
333            .enable_io()
334            .build()
335            .map_err(|e| GraphrtError::Runtime { message: format!("cannot start runtime: {e}") })?;
336
337        let vars: Vec<(String, String)> = config.providers.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
338        let lookup =
339            |name: &str| -> Option<String> { config.providers.get(name).or_else(|| config.env.get(name)).cloned() };
340
341        let mut services = Services::new();
342        let mut models =
343            graphrt_llm::ModelRegistry::from_vars(&vars).map_err(|e| GraphrtError::config(e.to_string()))?;
344        install_scripted_models(&mut models, config.scripted_models)?;
345        // Credentialed providers replace env-configured ones of the same name; their
346        // keys come from the host at request time, never from this config.
347        let host_credentials = graphrt_llm::credential_config::HostCredentials::new();
348        // A `typesafe`-kind entry is never registered as a chat model: it becomes the
349        // System One client, built from the same cached credential source.
350        let applied = graphrt_llm::credential_config::apply(&mut models, &config.credentials, &host_credentials)
351            .map_err(|e| GraphrtError::config(e.to_string()))?;
352        services.insert(models);
353
354        // TypeSafe System One (Jev): a `typesafe` credentials entry (token broker /
355        // host keychain) wins over a static `TYPESAFE_API_KEY` provider variable.
356        let typesafe = match applied.system_one {
357            Some(client) => Some(client),
358            None => graphrt_llm::typesafe::SystemOneClient::from_vars(&vars)
359                .map_err(|e| GraphrtError::config(e.to_string()))?,
360        };
361        if let Some(client) = typesafe {
362            services.insert(Arc::new(client));
363        }
364
365        let policy = graphrt_http::EgressPolicy { allow_private: config.allow_private_network, ..Default::default() };
366        let client = graphrt_http::HttpClient::new(policy).map_err(|e| GraphrtError::config(e.to_string()))?;
367        services.insert(client);
368
369        let mut tools = tokio.block_on(build_tools(config.mcp_servers.as_ref()))?;
370        #[allow(unused_mut)]
371        let mut files = graphrt_core::file::ChainResolver::with_data_urls();
372        if let Some(workspace) = &config.workspace {
373            files = install_workspace(workspace, &mut tools, files)?;
374        }
375        let resolver: Arc<dyn graphrt_core::file::FileResolver> = Arc::new(files);
376        // Every image a model node sends is checked, stripped of metadata and downscaled.
377        #[cfg(feature = "image")]
378        {
379            let preparer: Arc<dyn graphrt_core::file::ImagePreparer> = Arc::new(graphrt_image::VisionPreparer::new(
380                Arc::clone(&resolver),
381                graphrt_image::ImageLimits::default(),
382            ));
383            services.insert(preparer);
384        }
385        services.insert(resolver);
386        services.insert(tools);
387
388        #[cfg(feature = "skills")]
389        let skills = config.skills_dir.as_deref().map(|dir| skills::install(dir, &mut services));
390        #[cfg(not(feature = "skills"))]
391        let skills = match config.skills_dir {
392            Some(_) => return Err(GraphrtError::config("`skills_dir` requires the `skills` feature")),
393            None => None,
394        };
395        #[cfg(feature = "learning")]
396        let lessons = config.learning_dir.as_deref().map(|dir| learning::install(dir, &mut services));
397        #[cfg(not(feature = "learning"))]
398        let lessons = match config.learning_dir {
399            Some(_) => return Err(GraphrtError::config("`learning_dir` requires the `learning` feature")),
400            None => None,
401        };
402
403        #[cfg(feature = "rag")]
404        if let Some(raw) = &config.knowledge {
405            let kb_config: graphrt_rag::KnowledgeConfig =
406                serde_json::from_value(raw.clone()).map_err(|e| GraphrtError::config(format!("knowledge: {e}")))?;
407            let kb = kb_config.build_with_env(&lookup).map_err(|e| GraphrtError::config(format!("knowledge: {e}")))?;
408            services.insert(kb);
409        }
410        #[cfg(not(feature = "rag"))]
411        if config.knowledge.is_some() {
412            return Err(GraphrtError::config("`knowledge` requires the `rag` feature"));
413        }
414        let _ = &lookup;
415
416        Ok(Arc::new(Self {
417            tokio: Some(tokio),
418            registry: Mutex::new(base_registry()),
419            services: RwLock::new(Arc::new(services)),
420            env: config.env,
421            limits: config.limits.to_limits(),
422            wasm_limits: config.wasm.to_limits(),
423            credentials: host_credentials,
424            skills,
425            lessons,
426        }))
427    }
428
429    /// Register native tools implemented by the app under provider `name`.
430    /// Agents list them in `tools` as `<name>/<tool>`, or all of them with a `*` as the tool; `require_approval`
431    /// of an `agent` node can hold their calls for approval. Workflows loaded
432    /// after this call see the tools. Fails when the name is taken (by an MCP
433    /// server, the `files` workspace or an earlier provider) or a declaration
434    /// is invalid.
435    pub fn register_tool_provider(
436        &self,
437        name: String,
438        tools: Vec<HostToolSpec>,
439        provider: Arc<dyn ToolProvider>,
440    ) -> Result<(), GraphrtError> {
441        let runtime = host_tools::HostTools::new(&name, tools, provider)?;
442        let mut slot = self.services.write().unwrap_or_else(PoisonError::into_inner);
443        let mut services = Services::clone(&slot);
444        let mut registry = services.get::<graphrt_core::tool::ToolRegistry>().cloned().unwrap_or_default();
445        if registry.get(&name).is_some() {
446            return Err(GraphrtError::input(format!("tool provider `{name}` is already registered")));
447        }
448        registry.add(name, Arc::new(runtime));
449        services.insert(registry);
450        *slot = Arc::new(services);
451        Ok(())
452    }
453
454    /// Names of the registered tool providers (MCP servers, `files`, the app's own).
455    pub fn tool_providers(&self) -> Vec<String> {
456        let services = self.current_services();
457        services
458            .get::<graphrt_core::tool::ToolRegistry>()
459            .map(|r| r.providers().map(|(name, _)| name.to_owned()).collect())
460            .unwrap_or_default()
461    }
462
463    /// Register the host's credential callback for `provider` (a name from the
464    /// config's `credentials` section), or `"*"` for every provider. Replaces any
465    /// previous callback and drops every cached credential, so it takes effect for
466    /// requests made after the call (e.g. a different user signed in).
467    pub fn set_credential_provider(&self, provider: String, callback: Arc<dyn CredentialProvider>) {
468        self.credentials.set(provider, Arc::new(credentials::ForeignCredentials::new(callback)));
469    }
470
471    /// Remove the credential callback registered for `provider` (or `"*"`) and drop
472    /// every cached credential (sign-out takes effect on the next request).
473    pub fn clear_credential_provider(&self, provider: String) {
474        self.credentials.remove(&provider);
475    }
476
477    /// Drop every cached credential without changing the registered callbacks
478    /// (e.g. the user signed out of your backend and broker tokens must not be reused).
479    pub fn clear_credential_cache(&self) {
480        self.credentials.clear_cache();
481    }
482
483    /// Load a sandboxed WebAssembly plugin; its node kinds become available to
484    /// workflows loaded afterwards. Returns the registered kinds.
485    pub fn register_wasm_plugin(&self, wasm: Vec<u8>) -> Result<Vec<String>, GraphrtError> {
486        let plugin = graphrt_wasm::WasmPlugin::load(&wasm, self.wasm_limits.clone())
487            .map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
488        let kinds = plugin.descriptors().into_iter().map(|d| d.kind).collect();
489        let mut registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
490        plugin.register(&mut registry).map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
491        Ok(kinds)
492    }
493
494    /// Catalog of every node kind available in this runtime, as a JSON array.
495    pub fn catalog_json(&self) -> String {
496        let registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
497        serde_json::to_string(&registry.descriptors()).unwrap_or_else(|_| "[]".to_owned())
498    }
499
500    /// Parse and compile a workflow (YAML or JSON).
501    pub fn load_workflow(self: Arc<Self>, document: String) -> Result<Arc<WorkflowHandle>, GraphrtError> {
502        let workflow =
503            Workflow::parse(&document).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
504        let graph = {
505            let registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
506            Graph::build(workflow, &registry).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?
507        };
508        let graph = Arc::new(graph);
509        let engine = Engine::new(graph.clone())
510            .with_shared_services(self.current_services())
511            .with_clock(Arc::new(graphrt_core::node::TokioClock))
512            .with_limits(self.limits.clone());
513        Ok(Arc::new(WorkflowHandle { runtime: self, graph, engine }))
514    }
515
516    /// Open a portable bundle (`.grt` bytes), register its WebAssembly plugins and
517    /// compile its entry workflow. Every file is checked against the manifest's
518    /// SHA-256; when `trusted_keys` (hex Ed25519 public keys) is non-empty, the
519    /// bundle must be signed by one of them. Bundles needing process or HTTP
520    /// plugins are rejected: embedded hosts cannot spawn processes.
521    pub fn load_bundle(
522        self: Arc<Self>,
523        bundle: Vec<u8>,
524        trusted_keys: Vec<String>,
525    ) -> Result<Arc<WorkflowHandle>, GraphrtError> {
526        let mut options = graphrt_bundle::OpenOptions::default();
527        for key in trusted_keys {
528            options = options.trust_key(key);
529        }
530        let opened = graphrt_bundle::Bundle::open(&bundle, &options)
531            .map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
532        let non_portable: Vec<&str> =
533            opened.manifest().requires.plugins.iter().filter(|p| !p.portable).map(|p| p.name.as_str()).collect();
534        if !non_portable.is_empty() {
535            return Err(GraphrtError::Plugin {
536                message: format!(
537                    "bundle needs process/http plugins ({}), which cannot run embedded",
538                    non_portable.join(", ")
539                ),
540            });
541        }
542        let workflow = opened.workflow(None).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
543        let graph = {
544            let mut registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
545            opened
546                .register_wasm_plugins(&mut registry, &self.wasm_limits)
547                .map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
548            let report = opened.check(&registry);
549            if let Some(mismatch) = report.version_mismatch {
550                return Err(GraphrtError::InvalidWorkflow { message: mismatch });
551            }
552            Graph::build(workflow, &registry).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?
553        };
554        let graph = Arc::new(graph);
555        let engine = Engine::new(graph.clone())
556            .with_shared_services(self.current_services())
557            .with_clock(Arc::new(graphrt_core::node::TokioClock))
558            .with_limits(self.limits.clone());
559        Ok(Arc::new(WorkflowHandle { runtime: self, graph, engine }))
560    }
561}
562
563impl Runtime {
564    fn current_services(&self) -> Arc<Services> {
565        Arc::clone(&self.services.read().unwrap_or_else(PoisonError::into_inner))
566    }
567}
568
569#[cfg(feature = "scripted-llm")]
570fn install_scripted_models(
571    models: &mut graphrt_llm::ModelRegistry,
572    raw: Option<serde_json::Value>,
573) -> Result<(), GraphrtError> {
574    let Some(raw) = raw else {
575        return Ok(());
576    };
577    let scripts = serde_json::from_value(raw).map_err(|e| GraphrtError::config(format!("scripted_models: {e}")))?;
578    scripted::register(models, scripts)
579}
580
581#[cfg(not(feature = "scripted-llm"))]
582fn install_scripted_models(
583    _models: &mut graphrt_llm::ModelRegistry,
584    raw: Option<serde_json::Value>,
585) -> Result<(), GraphrtError> {
586    match raw {
587        Some(_) => Err(GraphrtError::config("`scripted_models` requires the `scripted-llm` feature")),
588        None => Ok(()),
589    }
590}
591
592/// Open the agents' workspace: the `files` tools and a resolver for the files they store.
593#[cfg(feature = "files")]
594fn install_workspace(
595    config: &WorkspaceConfig,
596    tools: &mut graphrt_core::tool::ToolRegistry,
597    files: graphrt_core::file::ChainResolver,
598) -> Result<graphrt_core::file::ChainResolver, GraphrtError> {
599    use graphrt_files::{FileTools, PROVIDER, Workspace, WorkspaceLimits, WorkspaceResolver};
600    let defaults = WorkspaceLimits::default();
601    let limits = WorkspaceLimits {
602        read_only: config.read_only,
603        max_file_bytes: config.max_file_bytes.unwrap_or(defaults.max_file_bytes),
604        max_total_bytes: config.max_total_bytes.unwrap_or(defaults.max_total_bytes),
605        max_files: config.max_files.unwrap_or(defaults.max_files),
606        ..defaults
607    };
608    let workspace = Workspace::dir(&config.dir, limits)
609        .map_err(|e| GraphrtError::config(format!("workspace `{}`: {e}", config.dir)))?;
610    if tools.get(PROVIDER).is_some() {
611        return Err(GraphrtError::config(format!(
612            "tool provider `{PROVIDER}` is defined by an MCP server and by `workspace`; rename the server"
613        )));
614    }
615    tools.add(PROVIDER, Arc::new(FileTools::new(workspace.clone())));
616    Ok(files.then(Arc::new(WorkspaceResolver::new(workspace))))
617}
618
619#[cfg(not(feature = "files"))]
620fn install_workspace(
621    _config: &WorkspaceConfig,
622    _tools: &mut graphrt_core::tool::ToolRegistry,
623    _files: graphrt_core::file::ChainResolver,
624) -> Result<graphrt_core::file::ChainResolver, GraphrtError> {
625    Err(GraphrtError::config("`workspace` requires the `files` feature"))
626}
627
628async fn build_tools(raw: Option<&serde_json::Value>) -> Result<graphrt_core::tool::ToolRegistry, GraphrtError> {
629    let Some(raw) = raw else {
630        return Ok(graphrt_core::tool::ToolRegistry::new());
631    };
632    #[cfg(feature = "mcp-http")]
633    {
634        let servers: graphrt_mcp::McpServers =
635            serde_json::from_value(raw.clone()).map_err(|e| GraphrtError::config(format!("mcp_servers: {e}")))?;
636        let configs = servers.into_configs();
637        for cfg in &configs {
638            if !matches!(cfg.transport, graphrt_mcp::McpTransport::Http(_)) {
639                return Err(GraphrtError::config(format!(
640                    "mcp server `{}`: only HTTP servers are supported when embedded (no process spawning)",
641                    cfg.name
642                )));
643            }
644        }
645        graphrt_mcp::connect_all(&configs).await.map_err(|e| GraphrtError::config(format!("mcp: {e}")))
646    }
647    #[cfg(not(feature = "mcp-http"))]
648    {
649        let _ = raw;
650        Err(GraphrtError::config("`mcp_servers` requires the `mcp-http` feature"))
651    }
652}
653
654/// A compiled workflow, ready to run any number of times concurrently.
655#[derive(uniffi::Object)]
656pub struct WorkflowHandle {
657    runtime: Arc<Runtime>,
658    graph: Arc<Graph>,
659    engine: Engine,
660}
661
662impl std::fmt::Debug for WorkflowHandle {
663    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
664        f.debug_struct("WorkflowHandle").field("graph", &self.graph).finish_non_exhaustive()
665    }
666}
667
668#[uniffi::export]
669impl WorkflowHandle {
670    /// Workflow name from the document, if any.
671    pub fn name(&self) -> Option<String> {
672        self.graph.workflow().name.clone()
673    }
674
675    /// Non-fatal findings from compilation (e.g. unreachable nodes).
676    pub fn warnings(&self) -> Vec<String> {
677        self.graph.warnings().to_vec()
678    }
679
680    /// Descriptors of the node kinds this workflow uses, as a JSON array.
681    pub fn catalog_json(&self) -> String {
682        let registry = self.runtime.registry.lock().unwrap_or_else(PoisonError::into_inner);
683        let mut kinds: Vec<&str> = self.graph.nodes().iter().map(|n| n.kind.as_ref()).collect();
684        kinds.sort_unstable();
685        kinds.dedup();
686        let descriptors: Vec<_> = kinds.into_iter().filter_map(|k| registry.descriptor(k)).collect();
687        serde_json::to_string(&descriptors).unwrap_or_else(|_| "[]".to_owned())
688    }
689
690    /// The workflow document as canonical JSON.
691    pub fn document_json(&self) -> String {
692        serde_json::to_string(self.graph.workflow()).unwrap_or_default()
693    }
694
695    /// Start a run. `inputs_json` / `sys_json` are JSON objects (`"{}"` when empty).
696    pub fn run(
697        &self,
698        inputs_json: String,
699        sys_json: String,
700        listener: Arc<dyn EventListener>,
701    ) -> Result<Arc<RunHandle>, GraphrtError> {
702        let mut input = self.base_input(&sys_json)?;
703        input.inputs = parse_object(&inputs_json, "inputs")?;
704        Ok(self.launch(input, None, Sink::Raw(listener)))
705    }
706
707    /// Start a run whose events arrive typed ([`RunEvent`]). It ends with
708    /// [`RunEvent::Paused`] or [`RunEvent::Finished`].
709    pub fn start(
710        &self,
711        inputs_json: String,
712        sys_json: String,
713        listener: Arc<dyn RunListener>,
714    ) -> Result<Arc<RunHandle>, GraphrtError> {
715        let mut input = self.base_input(&sys_json)?;
716        input.inputs = parse_object(&inputs_json, "inputs")?;
717        Ok(self.launch(input, None, Sink::Typed(listener)))
718    }
719
720    /// Resume a paused run with the answers given on `paused`
721    /// ([`PausedRun::approve`], [`PausedRun::answer`]...). `secrets_json`
722    /// re-supplies non-env secrets as `{"namespace.name": "value"}`.
723    pub fn resume_paused(
724        &self,
725        paused: Arc<PausedRun>,
726        secrets_json: String,
727        listener: Arc<dyn RunListener>,
728    ) -> Result<Arc<RunHandle>, GraphrtError> {
729        let inputs = paused.inputs().into_iter().map(|(k, v)| (k, Value::from_json(v))).collect();
730        self.resume_from(paused.snapshot().clone(), inputs, &secrets_json, Sink::Typed(listener))
731    }
732
733    /// Resume a paused run from the snapshot carried by its `run_paused` event.
734    /// `inputs_json` maps paused node ids (or `frame/node` ids) to their input,
735    /// e.g. `{"review": {"action": "approve", "values": {}}}`. `secrets_json`
736    /// re-supplies non-env secrets as `{"namespace.name": "value"}`.
737    pub fn resume(
738        &self,
739        snapshot_json: String,
740        inputs_json: String,
741        secrets_json: String,
742        listener: Arc<dyn EventListener>,
743    ) -> Result<Arc<RunHandle>, GraphrtError> {
744        let snapshot =
745            Snapshot::from_json(&snapshot_json).map_err(|e| GraphrtError::input(format!("snapshot: {e}")))?;
746        let inputs = parse_object(&inputs_json, "inputs")?;
747        self.resume_from(snapshot, inputs, &secrets_json, Sink::Raw(listener))
748    }
749}
750
751/// Where the events of a run go.
752enum Sink {
753    Raw(Arc<dyn EventListener>),
754    Typed(Arc<dyn RunListener>),
755}
756
757impl Sink {
758    fn event(&self, event: &Event, typed: &mut Vec<RunEvent>) {
759        match self {
760            Sink::Raw(listener) => {
761                if let Ok(json) = serde_json::to_string(event) {
762                    notify(|| listener.on_event(json));
763                }
764            }
765            Sink::Typed(listener) => {
766                events::translate(event, typed);
767                for event in typed.drain(..) {
768                    notify(|| listener.on_event(event));
769                }
770            }
771        }
772    }
773
774    fn chunk(&self, text: String) {
775        match self {
776            Sink::Raw(listener) => notify(|| listener.on_answer_chunk(text)),
777            Sink::Typed(listener) => notify(|| listener.on_event(RunEvent::AnswerChunk { text })),
778        }
779    }
780
781    fn finish(&self, terminal: Option<&Event>, answer: &str, result: String) {
782        match self {
783            Sink::Raw(listener) => notify(|| listener.on_finish(result)),
784            Sink::Typed(listener) => {
785                let event = events::terminal(terminal, answer, result);
786                notify(|| listener.on_event(event));
787            }
788        }
789    }
790}
791
792impl WorkflowHandle {
793    fn resume_from(
794        &self,
795        snapshot: Snapshot,
796        inputs: IndexMap<String, Value>,
797        secrets_json: &str,
798        sink: Sink,
799    ) -> Result<Arc<RunHandle>, GraphrtError> {
800        let mut input = self.base_input("{}")?;
801        let mut resume = ResumeFrom::new(snapshot.clone(), inputs);
802        let secrets: IndexMap<String, String> = if secrets_json.trim().is_empty() {
803            IndexMap::new()
804        } else {
805            serde_json::from_str(secrets_json).map_err(|e| GraphrtError::input(format!("secrets: {e}")))?
806        };
807        for (selector, value) in secrets {
808            resume = resume.secret(selector, value);
809        }
810        input.resume = Some(resume);
811        Ok(self.launch(input, Some(snapshot), sink))
812    }
813}
814
815impl WorkflowHandle {
816    fn base_input(&self, sys_json: &str) -> Result<RunInput, GraphrtError> {
817        let mut input = RunInput::new();
818        input.sys = parse_object(sys_json, "sys")?;
819        for decl in &self.graph.workflow().env {
820            if let Some(value) = self.runtime.env.get(&decl.name) {
821                input.env.insert(decl.name.clone(), Value::from(value.as_str()));
822            }
823        }
824        Ok(input)
825    }
826
827    fn launch(&self, input: RunInput, resumed_from: Option<Snapshot>, sink: Sink) -> Arc<RunHandle> {
828        let mut assembler = ResponseAssembler::new(&self.graph);
829        for (k, v) in &input.sys {
830            assembler = assembler.with_value(&Selector::of("sys", k), v.clone());
831        }
832        if let Some(snapshot) = &resumed_from {
833            assembler = assembler.resume_from(&snapshot.root);
834        }
835        let mut stream = self.engine.run(input);
836        let run = Arc::new(RunHandle { control: stream.handle(), result: Mutex::new(None), done: Condvar::new() });
837        let task_run = run.clone();
838        let Some(tokio) = self.runtime.tokio.as_ref() else {
839            let result = result_json(None, "");
840            run.complete(result.clone());
841            sink.finish(None, "", result);
842            return run;
843        };
844        tokio.spawn(async move {
845            let mut terminal: Option<Event> = None;
846            let mut chunks = Vec::new();
847            let mut typed = Vec::new();
848            while let Some(event) = stream.next().await {
849                // The terminal event goes out last, after the final answer chunks.
850                if !event.is_terminal() {
851                    sink.event(&event, &mut typed);
852                }
853                assembler.push_into(&event, &mut chunks);
854                for chunk in chunks.drain(..) {
855                    if !chunk.text.is_empty() {
856                        sink.chunk(chunk.text);
857                    }
858                }
859                if event.is_terminal() {
860                    terminal = Some(event);
861                }
862            }
863            for chunk in assembler.finish() {
864                if !chunk.text.is_empty() {
865                    sink.chunk(chunk.text);
866                }
867            }
868            if let (Some(event), Sink::Raw(_)) = (&terminal, &sink) {
869                sink.event(event, &mut typed);
870            }
871            let answer = assembler.text_so_far().to_owned();
872            let result = result_json(terminal.as_ref(), &answer);
873            task_run.complete(result.clone());
874            sink.finish(terminal.as_ref(), &answer, result);
875        });
876        run
877    }
878}
879
880/// Invoke a foreign callback, containing any panic it causes.
881fn notify(f: impl FnOnce()) {
882    let _ = catch_unwind(AssertUnwindSafe(f));
883}
884
885fn parse_object(json: &str, what: &str) -> Result<IndexMap<String, Value>, GraphrtError> {
886    if json.trim().is_empty() {
887        return Ok(IndexMap::new());
888    }
889    let raw: serde_json::Value = serde_json::from_str(json).map_err(|e| GraphrtError::input(format!("{what}: {e}")))?;
890    match raw {
891        serde_json::Value::Object(map) => Ok(map.into_iter().map(|(k, v)| (k, Value::from_json(v))).collect()),
892        serde_json::Value::Null => Ok(IndexMap::new()),
893        _ => Err(GraphrtError::input(format!("{what}: expected a JSON object"))),
894    }
895}
896
897/// Final result: the terminal event's fields plus `status` and the assembled `answer`.
898fn result_json(terminal: Option<&Event>, answer: &str) -> String {
899    let status = RunStatus::of(terminal).as_str();
900    let mut body = match terminal.map(serde_json::to_value) {
901        Some(Ok(serde_json::Value::Object(map))) => map,
902        _ => {
903            let mut map = serde_json::Map::new();
904            map.insert("error".into(), serde_json::Value::from("run ended without a terminal event"));
905            map.insert("error_type".into(), serde_json::Value::from("internal"));
906            map
907        }
908    };
909    body.remove("type");
910    body.insert("status".into(), serde_json::Value::from(status));
911    body.insert("answer".into(), serde_json::Value::from(answer));
912    serde_json::Value::Object(body).to_string()
913}
914
915/// Controls one run.
916#[derive(uniffi::Object)]
917pub struct RunHandle {
918    control: graphrt_core::RunHandle,
919    result: Mutex<Option<String>>,
920    done: Condvar,
921}
922
923impl std::fmt::Debug for RunHandle {
924    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
925        f.debug_struct("RunHandle").field("finished", &self.is_finished()).finish_non_exhaustive()
926    }
927}
928
929impl RunHandle {
930    fn complete(&self, result: String) {
931        let mut slot = self.result.lock().unwrap_or_else(PoisonError::into_inner);
932        *slot = Some(result);
933        self.done.notify_all();
934    }
935}
936
937#[uniffi::export]
938impl RunHandle {
939    /// Cancel the run immediately. It ends with status `aborted`.
940    pub fn abort(&self, reason: String) {
941        self.control.abort(reason);
942    }
943
944    /// Stop scheduling new nodes; the run ends with status `paused` and a snapshot.
945    pub fn pause(&self, reason: String) {
946        self.control.pause(reason);
947    }
948
949    /// Write a variable (`"conversation.topic"`) while the run is in progress.
950    pub fn update_variable(&self, selector: String, value_json: String) -> Result<(), GraphrtError> {
951        let selector = Selector::parse(&selector).map_err(|e| GraphrtError::input(e.to_string()))?;
952        let value: serde_json::Value =
953            serde_json::from_str(&value_json).map_err(|e| GraphrtError::input(format!("value: {e}")))?;
954        self.control.update_variable(selector, Value::from_json(value));
955        Ok(())
956    }
957
958    pub fn is_finished(&self) -> bool {
959        self.result.lock().unwrap_or_else(PoisonError::into_inner).is_some()
960    }
961
962    /// Block until the run finishes (or `timeout_ms` elapses) and return the result
963    /// JSON (`{"status": "succeeded"|"failed"|"aborted"|"paused", "answer": ..., ...}`).
964    /// Returns `None` on timeout. Do not call from a UI thread.
965    pub fn wait_json(&self, timeout_ms: u64) -> Option<String> {
966        let guard = self.result.lock().unwrap_or_else(PoisonError::into_inner);
967        let (guard, _) = self
968            .done
969            .wait_timeout_while(guard, Duration::from_millis(timeout_ms), |r| r.is_none())
970            .unwrap_or_else(PoisonError::into_inner);
971        guard.clone()
972    }
973}