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