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//!   .load_workflow(yaml_or_json) -> WorkflowHandle
13//! WorkflowHandle.run(inputs_json, sys_json, listener) -> RunHandle
14//! WorkflowHandle.resume(snapshot_json, inputs_json, secrets_json, listener) -> RunHandle
15//! RunHandle.abort(reason) / pause(reason) / wait_json(timeout_ms)
16//! Runtime.set_credential_provider(provider, callback)  // keys from Keychain / Keystore
17//! ```
18//!
19//! Runs execute on a Tokio runtime owned by [`Runtime`]; listener callbacks are
20//! invoked from its worker threads, never from the caller's thread. Nothing in
21//! this crate spawns processes, so every feature is usable on iOS and Android.
22//!
23//! ## Config JSON
24//!
25//! ```json
26//! {
27//!   "providers": { "OPENAI_API_KEY": "sk-...", "OLLAMA_HOST": "http://10.0.2.2:11434" },
28//!   "env": { "CRM_TOKEN": "..." },
29//!   "limits": { "max_steps": 10000, "max_duration_ms": 60000, "default_node_timeout_ms": 30000 },
30//!   "allow_private_network": false,
31//!   "knowledge": { "...": "knowledge-retrieval datasets (see graphrt-rag)" },
32//!   "mcp_servers": { "mcpServers": { "docs": { "url": "https://..." } } },
33//!   "wasm": { "fuel": 1000000000, "memory_bytes": 67108864 },
34//!   "credentials": {
35//!     "openai": { "source": "external" },
36//!     "proxy": { "source": "external", "kind": "openai", "base_url": "https://llm-proxy.example.com/v1" },
37//!     "anthropic": { "source": "token_broker", "url": "https://api.example.com/llm-token", "app_auth": "external" }
38//!   }
39//! }
40//! ```
41//!
42//! `credentials` declares providers whose keys never appear in the config: an
43//! `external` provider asks the [`CredentialProvider`] registered with
44//! [`Runtime::set_credential_provider`]; a `token_broker` provider fetches
45//! short-lived tokens from your backend. See `docs/credentials.md`.
46//!
47//! `providers` uses the same variable names as the CLI's environment
48//! (`OPENAI_API_KEY`, `OPENAI_BASE_URL`, `ANTHROPIC_API_KEY`, `OLLAMA_HOST`,
49//! `GRAPHRT_OPENAI_COMPAT_<NAME>_BASE_URL`...). `env` values are exposed to
50//! workflows only for the `env` variables a workflow declares.
51
52use std::panic::{AssertUnwindSafe, catch_unwind};
53use std::sync::{Arc, Condvar, Mutex, PoisonError};
54use std::time::Duration;
55
56use futures::StreamExt;
57use graphrt_core::engine::{Limits, ResumeFrom};
58use graphrt_core::response::ResponseAssembler;
59use graphrt_core::snapshot::Snapshot;
60use graphrt_core::{Engine, Event, Graph, Registry, RunInput, Selector, Services, Value, Workflow};
61use indexmap::IndexMap;
62use serde::Deserialize;
63
64mod credentials;
65
66pub use credentials::{CredentialProvider, CredentialRecord};
67
68uniffi::setup_scaffolding!();
69
70/// Errors surfaced to foreign code as exceptions.
71#[derive(Debug, thiserror::Error, uniffi::Error)]
72#[non_exhaustive]
73pub enum GraphrtError {
74    /// The runtime configuration JSON is invalid.
75    #[error("invalid config: {message}")]
76    InvalidConfig { message: String },
77    /// The workflow document could not be parsed or compiled.
78    #[error("invalid workflow: {message}")]
79    InvalidWorkflow { message: String },
80    /// Run inputs, snapshot or selector JSON is invalid.
81    #[error("invalid input: {message}")]
82    InvalidInput { message: String },
83    /// A WebAssembly plugin could not be loaded.
84    #[error("plugin error: {message}")]
85    Plugin { message: String },
86    /// Internal failure (runtime could not start, lock poisoned...).
87    #[error("runtime error: {message}")]
88    Runtime { message: String },
89}
90
91impl From<uniffi::UnexpectedUniFFICallbackError> for GraphrtError {
92    fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self {
93        Self::Runtime { message: format!("callback failed: {}", e.reason) }
94    }
95}
96
97impl GraphrtError {
98    fn config(message: impl Into<String>) -> Self {
99        Self::InvalidConfig { message: message.into() }
100    }
101    fn input(message: impl Into<String>) -> Self {
102        Self::InvalidInput { message: message.into() }
103    }
104}
105
106/// Receives the events of one run. Implemented in the host language.
107///
108/// Callbacks run on a background thread; marshal to your UI thread yourself.
109/// Exceptions thrown by a callback are swallowed so they cannot break the run.
110#[uniffi::export(with_foreign)]
111pub trait EventListener: Send + Sync {
112    /// Every raw engine event, as JSON (`{"type": "node_started", ...}`).
113    fn on_event(&self, event_json: String);
114    /// Ordered user-facing answer text (answer nodes), streamed as it is produced.
115    fn on_answer_chunk(&self, text: String);
116    /// Called exactly once with the final result (see [`RunHandle::wait_json`]).
117    fn on_finish(&self, result_json: String);
118}
119
120/// Version of the embedded runtime.
121#[uniffi::export]
122pub fn graphrt_version() -> String {
123    env!("CARGO_PKG_VERSION").to_owned()
124}
125
126#[derive(Debug, Default, Deserialize)]
127#[serde(deny_unknown_fields)]
128struct RuntimeConfig {
129    #[serde(default)]
130    providers: IndexMap<String, String>,
131    #[serde(default)]
132    env: IndexMap<String, String>,
133    #[serde(default)]
134    limits: LimitsConfig,
135    #[serde(default)]
136    allow_private_network: bool,
137    #[serde(default)]
138    knowledge: Option<serde_json::Value>,
139    #[serde(default)]
140    mcp_servers: Option<serde_json::Value>,
141    #[serde(default)]
142    wasm: WasmConfig,
143    #[serde(default)]
144    credentials: IndexMap<String, graphrt_llm::credential_config::ProviderCredentialConfig>,
145}
146
147#[derive(Debug, Default, Deserialize)]
148#[serde(deny_unknown_fields)]
149struct LimitsConfig {
150    max_steps: Option<u64>,
151    max_duration_ms: Option<u64>,
152    max_depth: Option<u32>,
153    default_node_timeout_ms: Option<u64>,
154    max_concurrency: Option<usize>,
155}
156
157impl LimitsConfig {
158    fn to_limits(&self) -> Limits {
159        let mut limits = Limits::default();
160        if let Some(v) = self.max_steps {
161            limits.max_steps = v;
162        }
163        if self.max_duration_ms.is_some() {
164            limits.max_duration_ms = self.max_duration_ms;
165        }
166        if let Some(v) = self.max_depth {
167            limits.max_depth = v;
168        }
169        if self.default_node_timeout_ms.is_some() {
170            limits.default_node_timeout_ms = self.default_node_timeout_ms;
171        }
172        if let Some(v) = self.max_concurrency {
173            limits.max_concurrency = v.max(1);
174        }
175        limits
176    }
177}
178
179#[derive(Debug, Default, Deserialize)]
180#[serde(deny_unknown_fields)]
181struct WasmConfig {
182    fuel: Option<u64>,
183    memory_bytes: Option<usize>,
184    module_bytes: Option<usize>,
185}
186
187impl WasmConfig {
188    fn to_limits(&self) -> graphrt_wasm::WasmLimits {
189        let mut limits = graphrt_wasm::WasmLimits::default();
190        if let Some(v) = self.fuel {
191            limits.fuel = v;
192        }
193        if let Some(v) = self.memory_bytes {
194            limits.memory_bytes = v;
195        }
196        if let Some(v) = self.module_bytes {
197            limits.module_bytes = v;
198        }
199        limits
200    }
201}
202
203/// A configured runtime: node registry, host services and a thread pool.
204/// Create one per app and share it.
205#[derive(uniffi::Object)]
206pub struct Runtime {
207    /// Always `Some` until drop; taken in `Drop` to shut down without blocking.
208    tokio: Option<tokio::runtime::Runtime>,
209    registry: Mutex<Registry>,
210    services: Arc<Services>,
211    env: IndexMap<String, String>,
212    limits: Limits,
213    wasm_limits: graphrt_wasm::WasmLimits,
214    credentials: graphrt_llm::credential_config::HostCredentials,
215}
216
217impl Drop for Runtime {
218    fn drop(&mut self) {
219        // Do not block the dropping thread (often a UI thread) on node work that is
220        // still finishing in the blocking pool (e.g. an aborted code node).
221        if let Some(rt) = self.tokio.take() {
222            rt.shutdown_background();
223        }
224    }
225}
226
227impl std::fmt::Debug for Runtime {
228    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229        f.debug_struct("Runtime").field("limits", &self.limits).finish_non_exhaustive()
230    }
231}
232
233fn base_registry() -> Registry {
234    let mut registry = Registry::with_builtins();
235    graphrt_llm::register(&mut registry);
236    graphrt_http::register(&mut registry);
237    #[cfg(feature = "code-js")]
238    graphrt_code::register(&mut registry);
239    #[cfg(feature = "doc")]
240    graphrt_doc::register(&mut registry);
241    #[cfg(feature = "rag")]
242    graphrt_rag::register(&mut registry);
243    registry
244}
245
246#[uniffi::export]
247impl Runtime {
248    /// Create a runtime from a config JSON document (`"{}"` for defaults).
249    /// May perform network I/O (MCP handshakes); call it off the UI thread.
250    #[uniffi::constructor]
251    pub fn new(config_json: String) -> Result<Arc<Self>, GraphrtError> {
252        let text = if config_json.trim().is_empty() { "{}" } else { config_json.as_str() };
253        let config: RuntimeConfig = serde_json::from_str(text).map_err(|e| GraphrtError::config(e.to_string()))?;
254        let tokio = tokio::runtime::Builder::new_multi_thread()
255            .worker_threads(2)
256            .thread_name("graphrt")
257            .enable_time()
258            .enable_io()
259            .build()
260            .map_err(|e| GraphrtError::Runtime { message: format!("cannot start runtime: {e}") })?;
261
262        let vars: Vec<(String, String)> = config.providers.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
263        let lookup =
264            |name: &str| -> Option<String> { config.providers.get(name).or_else(|| config.env.get(name)).cloned() };
265
266        let mut services = Services::new();
267        let mut models =
268            graphrt_llm::ModelRegistry::from_vars(&vars).map_err(|e| GraphrtError::config(e.to_string()))?;
269        // Credentialed providers replace env-configured ones of the same name; their
270        // keys come from the host at request time, never from this config.
271        let host_credentials = graphrt_llm::credential_config::HostCredentials::new();
272        // A `typesafe`-kind entry is never registered as a chat model: it becomes the
273        // System One client, built from the same cached credential source.
274        let applied = graphrt_llm::credential_config::apply(&mut models, &config.credentials, &host_credentials)
275            .map_err(|e| GraphrtError::config(e.to_string()))?;
276        services.insert(models);
277
278        // TypeSafe System One (Jev): a `typesafe` credentials entry (token broker /
279        // host keychain) wins over a static `TYPESAFE_API_KEY` provider variable.
280        let typesafe = match applied.system_one {
281            Some(client) => Some(client),
282            None => graphrt_llm::typesafe::SystemOneClient::from_vars(&vars)
283                .map_err(|e| GraphrtError::config(e.to_string()))?,
284        };
285        if let Some(client) = typesafe {
286            services.insert(Arc::new(client));
287        }
288
289        let policy = graphrt_http::EgressPolicy { allow_private: config.allow_private_network, ..Default::default() };
290        let client = graphrt_http::HttpClient::new(policy).map_err(|e| GraphrtError::config(e.to_string()))?;
291        services.insert(client);
292
293        let resolver: Arc<dyn graphrt_core::file::FileResolver> =
294            Arc::new(graphrt_core::file::ChainResolver::with_data_urls());
295        services.insert(resolver);
296
297        let tools = tokio.block_on(build_tools(config.mcp_servers.as_ref()))?;
298        services.insert(tools);
299
300        #[cfg(feature = "rag")]
301        if let Some(raw) = &config.knowledge {
302            let kb_config: graphrt_rag::KnowledgeConfig =
303                serde_json::from_value(raw.clone()).map_err(|e| GraphrtError::config(format!("knowledge: {e}")))?;
304            let kb = kb_config.build_with_env(&lookup).map_err(|e| GraphrtError::config(format!("knowledge: {e}")))?;
305            services.insert(kb);
306        }
307        #[cfg(not(feature = "rag"))]
308        if config.knowledge.is_some() {
309            return Err(GraphrtError::config("`knowledge` requires the `rag` feature"));
310        }
311        let _ = &lookup;
312
313        Ok(Arc::new(Self {
314            tokio: Some(tokio),
315            registry: Mutex::new(base_registry()),
316            services: Arc::new(services),
317            env: config.env,
318            limits: config.limits.to_limits(),
319            wasm_limits: config.wasm.to_limits(),
320            credentials: host_credentials,
321        }))
322    }
323
324    /// Register the host's credential callback for `provider` (a name from the
325    /// config's `credentials` section), or `"*"` for every provider. Replaces any
326    /// previous callback and drops every cached credential, so it takes effect for
327    /// requests made after the call (e.g. a different user signed in).
328    pub fn set_credential_provider(&self, provider: String, callback: Arc<dyn CredentialProvider>) {
329        self.credentials.set(provider, Arc::new(credentials::ForeignCredentials::new(callback)));
330    }
331
332    /// Remove the credential callback registered for `provider` (or `"*"`) and drop
333    /// every cached credential (sign-out takes effect on the next request).
334    pub fn clear_credential_provider(&self, provider: String) {
335        self.credentials.remove(&provider);
336    }
337
338    /// Drop every cached credential without changing the registered callbacks
339    /// (e.g. the user signed out of your backend and broker tokens must not be reused).
340    pub fn clear_credential_cache(&self) {
341        self.credentials.clear_cache();
342    }
343
344    /// Load a sandboxed WebAssembly plugin; its node kinds become available to
345    /// workflows loaded afterwards. Returns the registered kinds.
346    pub fn register_wasm_plugin(&self, wasm: Vec<u8>) -> Result<Vec<String>, GraphrtError> {
347        let plugin = graphrt_wasm::WasmPlugin::load(&wasm, self.wasm_limits.clone())
348            .map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
349        let kinds = plugin.descriptors().into_iter().map(|d| d.kind).collect();
350        let mut registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
351        plugin.register(&mut registry).map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
352        Ok(kinds)
353    }
354
355    /// Catalog of every node kind available in this runtime, as a JSON array.
356    pub fn catalog_json(&self) -> String {
357        let registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
358        serde_json::to_string(&registry.descriptors()).unwrap_or_else(|_| "[]".to_owned())
359    }
360
361    /// Parse and compile a workflow (YAML or JSON).
362    pub fn load_workflow(self: Arc<Self>, document: String) -> Result<Arc<WorkflowHandle>, GraphrtError> {
363        let workflow =
364            Workflow::parse(&document).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
365        let graph = {
366            let registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
367            Graph::build(workflow, &registry).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?
368        };
369        let graph = Arc::new(graph);
370        let engine = Engine::new(graph.clone())
371            .with_shared_services(self.services.clone())
372            .with_clock(Arc::new(graphrt_core::node::TokioClock))
373            .with_limits(self.limits.clone());
374        Ok(Arc::new(WorkflowHandle { runtime: self, graph, engine }))
375    }
376
377    /// Open a portable bundle (`.grt` bytes), register its WebAssembly plugins and
378    /// compile its entry workflow. Every file is checked against the manifest's
379    /// SHA-256; when `trusted_keys` (hex Ed25519 public keys) is non-empty, the
380    /// bundle must be signed by one of them. Bundles needing process or HTTP
381    /// plugins are rejected: embedded hosts cannot spawn processes.
382    pub fn load_bundle(
383        self: Arc<Self>,
384        bundle: Vec<u8>,
385        trusted_keys: Vec<String>,
386    ) -> Result<Arc<WorkflowHandle>, GraphrtError> {
387        let mut options = graphrt_bundle::OpenOptions::default();
388        for key in trusted_keys {
389            options = options.trust_key(key);
390        }
391        let opened = graphrt_bundle::Bundle::open(&bundle, &options)
392            .map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
393        let non_portable: Vec<&str> =
394            opened.manifest().requires.plugins.iter().filter(|p| !p.portable).map(|p| p.name.as_str()).collect();
395        if !non_portable.is_empty() {
396            return Err(GraphrtError::Plugin {
397                message: format!(
398                    "bundle needs process/http plugins ({}), which cannot run embedded",
399                    non_portable.join(", ")
400                ),
401            });
402        }
403        let workflow = opened.workflow(None).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?;
404        let graph = {
405            let mut registry = self.registry.lock().unwrap_or_else(PoisonError::into_inner);
406            opened
407                .register_wasm_plugins(&mut registry, &self.wasm_limits)
408                .map_err(|e| GraphrtError::Plugin { message: e.to_string() })?;
409            let report = opened.check(&registry);
410            if let Some(mismatch) = report.version_mismatch {
411                return Err(GraphrtError::InvalidWorkflow { message: mismatch });
412            }
413            Graph::build(workflow, &registry).map_err(|e| GraphrtError::InvalidWorkflow { message: e.to_string() })?
414        };
415        let graph = Arc::new(graph);
416        let engine = Engine::new(graph.clone())
417            .with_shared_services(self.services.clone())
418            .with_clock(Arc::new(graphrt_core::node::TokioClock))
419            .with_limits(self.limits.clone());
420        Ok(Arc::new(WorkflowHandle { runtime: self, graph, engine }))
421    }
422}
423
424async fn build_tools(raw: Option<&serde_json::Value>) -> Result<graphrt_core::tool::ToolRegistry, GraphrtError> {
425    let Some(raw) = raw else {
426        return Ok(graphrt_core::tool::ToolRegistry::new());
427    };
428    #[cfg(feature = "mcp-http")]
429    {
430        let servers: graphrt_mcp::McpServers =
431            serde_json::from_value(raw.clone()).map_err(|e| GraphrtError::config(format!("mcp_servers: {e}")))?;
432        let configs = servers.into_configs();
433        for cfg in &configs {
434            if !matches!(cfg.transport, graphrt_mcp::McpTransport::Http(_)) {
435                return Err(GraphrtError::config(format!(
436                    "mcp server `{}`: only HTTP servers are supported when embedded (no process spawning)",
437                    cfg.name
438                )));
439            }
440        }
441        graphrt_mcp::connect_all(&configs).await.map_err(|e| GraphrtError::config(format!("mcp: {e}")))
442    }
443    #[cfg(not(feature = "mcp-http"))]
444    {
445        let _ = raw;
446        Err(GraphrtError::config("`mcp_servers` requires the `mcp-http` feature"))
447    }
448}
449
450/// A compiled workflow, ready to run any number of times concurrently.
451#[derive(uniffi::Object)]
452pub struct WorkflowHandle {
453    runtime: Arc<Runtime>,
454    graph: Arc<Graph>,
455    engine: Engine,
456}
457
458impl std::fmt::Debug for WorkflowHandle {
459    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
460        f.debug_struct("WorkflowHandle").field("graph", &self.graph).finish_non_exhaustive()
461    }
462}
463
464#[uniffi::export]
465impl WorkflowHandle {
466    /// Workflow name from the document, if any.
467    pub fn name(&self) -> Option<String> {
468        self.graph.workflow().name.clone()
469    }
470
471    /// Non-fatal findings from compilation (e.g. unreachable nodes).
472    pub fn warnings(&self) -> Vec<String> {
473        self.graph.warnings().to_vec()
474    }
475
476    /// Descriptors of the node kinds this workflow uses, as a JSON array.
477    pub fn catalog_json(&self) -> String {
478        let registry = self.runtime.registry.lock().unwrap_or_else(PoisonError::into_inner);
479        let mut kinds: Vec<&str> = self.graph.nodes().iter().map(|n| n.kind.as_ref()).collect();
480        kinds.sort_unstable();
481        kinds.dedup();
482        let descriptors: Vec<_> = kinds.into_iter().filter_map(|k| registry.descriptor(k)).collect();
483        serde_json::to_string(&descriptors).unwrap_or_else(|_| "[]".to_owned())
484    }
485
486    /// The workflow document as canonical JSON.
487    pub fn document_json(&self) -> String {
488        serde_json::to_string(self.graph.workflow()).unwrap_or_default()
489    }
490
491    /// Start a run. `inputs_json` / `sys_json` are JSON objects (`"{}"` when empty).
492    pub fn run(
493        &self,
494        inputs_json: String,
495        sys_json: String,
496        listener: Arc<dyn EventListener>,
497    ) -> Result<Arc<RunHandle>, GraphrtError> {
498        let mut input = self.base_input(&sys_json)?;
499        input.inputs = parse_object(&inputs_json, "inputs")?;
500        Ok(self.start(input, None, listener))
501    }
502
503    /// Resume a paused run from the snapshot carried by its `run_paused` event.
504    /// `inputs_json` maps paused node ids (or `frame/node` ids) to their input,
505    /// e.g. `{"review": {"action": "approve", "values": {}}}`. `secrets_json`
506    /// re-supplies non-env secrets as `{"namespace.name": "value"}`.
507    pub fn resume(
508        &self,
509        snapshot_json: String,
510        inputs_json: String,
511        secrets_json: String,
512        listener: Arc<dyn EventListener>,
513    ) -> Result<Arc<RunHandle>, GraphrtError> {
514        let snapshot =
515            Snapshot::from_json(&snapshot_json).map_err(|e| GraphrtError::input(format!("snapshot: {e}")))?;
516        let mut input = self.base_input("{}")?;
517        let mut resume = ResumeFrom::new(snapshot.clone(), parse_object(&inputs_json, "inputs")?);
518        let secrets: IndexMap<String, String> = if secrets_json.trim().is_empty() {
519            IndexMap::new()
520        } else {
521            serde_json::from_str(&secrets_json).map_err(|e| GraphrtError::input(format!("secrets: {e}")))?
522        };
523        for (selector, value) in secrets {
524            resume = resume.secret(selector, value);
525        }
526        input.resume = Some(resume);
527        Ok(self.start(input, Some(snapshot), listener))
528    }
529}
530
531impl WorkflowHandle {
532    fn base_input(&self, sys_json: &str) -> Result<RunInput, GraphrtError> {
533        let mut input = RunInput::new();
534        input.sys = parse_object(sys_json, "sys")?;
535        for decl in &self.graph.workflow().env {
536            if let Some(value) = self.runtime.env.get(&decl.name) {
537                input.env.insert(decl.name.clone(), Value::from(value.as_str()));
538            }
539        }
540        Ok(input)
541    }
542
543    fn start(
544        &self,
545        input: RunInput,
546        resumed_from: Option<Snapshot>,
547        listener: Arc<dyn EventListener>,
548    ) -> Arc<RunHandle> {
549        let mut assembler = ResponseAssembler::new(&self.graph);
550        for (k, v) in &input.sys {
551            assembler = assembler.with_value(&Selector::of("sys", k), v.clone());
552        }
553        if let Some(snapshot) = &resumed_from {
554            assembler = assembler.resume_from(&snapshot.root);
555        }
556        let mut stream = self.engine.run(input);
557        let run = Arc::new(RunHandle { control: stream.handle(), result: Mutex::new(None), done: Condvar::new() });
558        let task_run = run.clone();
559        let Some(tokio) = self.runtime.tokio.as_ref() else {
560            let result = result_json(None, "");
561            run.complete(result.clone());
562            notify(|| listener.on_finish(result));
563            return run;
564        };
565        tokio.spawn(async move {
566            let mut terminal: Option<Event> = None;
567            let mut chunks = Vec::new();
568            while let Some(event) = stream.next().await {
569                if let Ok(json) = serde_json::to_string(&event) {
570                    notify(|| listener.on_event(json));
571                }
572                assembler.push_into(&event, &mut chunks);
573                for chunk in chunks.drain(..) {
574                    if !chunk.text.is_empty() {
575                        notify(|| listener.on_answer_chunk(chunk.text));
576                    }
577                }
578                if event.is_terminal() {
579                    terminal = Some(event);
580                }
581            }
582            for chunk in assembler.finish() {
583                if !chunk.text.is_empty() {
584                    notify(|| listener.on_answer_chunk(chunk.text));
585                }
586            }
587            let result = result_json(terminal.as_ref(), assembler.text_so_far());
588            task_run.complete(result.clone());
589            notify(|| listener.on_finish(result));
590        });
591        run
592    }
593}
594
595/// Invoke a foreign callback, containing any panic it causes.
596fn notify(f: impl FnOnce()) {
597    let _ = catch_unwind(AssertUnwindSafe(f));
598}
599
600fn parse_object(json: &str, what: &str) -> Result<IndexMap<String, Value>, GraphrtError> {
601    if json.trim().is_empty() {
602        return Ok(IndexMap::new());
603    }
604    let raw: serde_json::Value = serde_json::from_str(json).map_err(|e| GraphrtError::input(format!("{what}: {e}")))?;
605    match raw {
606        serde_json::Value::Object(map) => Ok(map.into_iter().map(|(k, v)| (k, Value::from_json(v))).collect()),
607        serde_json::Value::Null => Ok(IndexMap::new()),
608        _ => Err(GraphrtError::input(format!("{what}: expected a JSON object"))),
609    }
610}
611
612/// Final result: the terminal event's fields plus `status` and the assembled `answer`.
613fn result_json(terminal: Option<&Event>, answer: &str) -> String {
614    let status = match terminal {
615        Some(Event::RunSucceeded { .. }) => "succeeded",
616        Some(Event::RunFailed { .. }) => "failed",
617        Some(Event::RunAborted { .. }) => "aborted",
618        Some(Event::RunPaused { .. }) => "paused",
619        _ => "failed",
620    };
621    let mut body = match terminal.map(serde_json::to_value) {
622        Some(Ok(serde_json::Value::Object(map))) => map,
623        _ => {
624            let mut map = serde_json::Map::new();
625            map.insert("error".into(), serde_json::Value::from("run ended without a terminal event"));
626            map.insert("error_type".into(), serde_json::Value::from("internal"));
627            map
628        }
629    };
630    body.remove("type");
631    body.insert("status".into(), serde_json::Value::from(status));
632    body.insert("answer".into(), serde_json::Value::from(answer));
633    serde_json::Value::Object(body).to_string()
634}
635
636/// Controls one run.
637#[derive(uniffi::Object)]
638pub struct RunHandle {
639    control: graphrt_core::RunHandle,
640    result: Mutex<Option<String>>,
641    done: Condvar,
642}
643
644impl std::fmt::Debug for RunHandle {
645    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
646        f.debug_struct("RunHandle").field("finished", &self.is_finished()).finish_non_exhaustive()
647    }
648}
649
650impl RunHandle {
651    fn complete(&self, result: String) {
652        let mut slot = self.result.lock().unwrap_or_else(PoisonError::into_inner);
653        *slot = Some(result);
654        self.done.notify_all();
655    }
656}
657
658#[uniffi::export]
659impl RunHandle {
660    /// Cancel the run immediately. It ends with status `aborted`.
661    pub fn abort(&self, reason: String) {
662        self.control.abort(reason);
663    }
664
665    /// Stop scheduling new nodes; the run ends with status `paused` and a snapshot.
666    pub fn pause(&self, reason: String) {
667        self.control.pause(reason);
668    }
669
670    /// Write a variable (`"conversation.topic"`) while the run is in progress.
671    pub fn update_variable(&self, selector: String, value_json: String) -> Result<(), GraphrtError> {
672        let selector = Selector::parse(&selector).map_err(|e| GraphrtError::input(e.to_string()))?;
673        let value: serde_json::Value =
674            serde_json::from_str(&value_json).map_err(|e| GraphrtError::input(format!("value: {e}")))?;
675        self.control.update_variable(selector, Value::from_json(value));
676        Ok(())
677    }
678
679    pub fn is_finished(&self) -> bool {
680        self.result.lock().unwrap_or_else(PoisonError::into_inner).is_some()
681    }
682
683    /// Block until the run finishes (or `timeout_ms` elapses) and return the result
684    /// JSON (`{"status": "succeeded"|"failed"|"aborted"|"paused", "answer": ..., ...}`).
685    /// Returns `None` on timeout. Do not call from a UI thread.
686    pub fn wait_json(&self, timeout_ms: u64) -> Option<String> {
687        let guard = self.result.lock().unwrap_or_else(PoisonError::into_inner);
688        let (guard, _) = self
689            .done
690            .wait_timeout_while(guard, Duration::from_millis(timeout_ms), |r| r.is_none())
691            .unwrap_or_else(PoisonError::into_inner);
692        guard.clone()
693    }
694}