apoc 0.9.1

Agentic process control for LLMs
Documentation
//! apoc inside another process, with no daemon and no socket.
//!
//! A [`CoreHandle`] is the daemon's core without its socket: it owns one state
//! root exclusively, closes out work that root's previous owner left behind,
//! recovers what can resume, and then answers the same typed requests the
//! daemon answers — directly, in this process. Code Mode programs it runs reach
//! `apoc.*` in-process too.
//!
//! Two things are worth knowing before embedding it:
//!
//! - **It owns its state root.** Opening a root another core or the user's
//!   daemon already owns fails with `STATE_ROOT_BUSY`. Two owners of one root
//!   would cancel each other's work, so sharing is refused rather than
//!   attempted. To use the per-user daemon's state, talk to the daemon.
//! - **No daemon does not mean no threads.** A handle runs process monitors,
//!   a maintenance loop for hooks and leases, and a pool of JavaScript workers.

use std::path::PathBuf;
use std::sync::Arc;

use serde_json::Value;

use crate::daemon::{CoreConfig, Daemon, InProcess, Serving};
use crate::operation::DaemonOperation;

/// An open apoc core, driven from an async runtime the caller owns.
pub struct CoreHandle {
    daemon: Arc<Daemon>,
    runtime: tokio::runtime::Handle,
    maintenance: Option<tokio::task::JoinHandle<()>>,
    _serving: Serving,
}

impl CoreHandle {
    /// Claims `config.state_dir`, reconciles and recovers it, and starts the
    /// core's background work. No handle exists until recovery has finished,
    /// so no request can observe unreconciled state.
    ///
    /// Must be called from inside a multi-threaded tokio runtime with I/O and
    /// time enabled; the core's background work runs on it.
    pub async fn open(config: CoreConfig) -> Result<Self, String> {
        let daemon = Daemon::open(&config)?;
        daemon.recover_owned_state().await?;
        let daemon = Arc::new(daemon);
        let serving = daemon.serve_in_process();
        let maintenance = Daemon::spawn_maintenance(&daemon);
        Ok(Self {
            daemon,
            runtime: tokio::runtime::Handle::current(),
            maintenance: Some(maintenance),
            _serving: serving,
        })
    }

    /// Sends one request by method name, exactly as the daemon would receive it
    /// over its socket, and returns its JSON result.
    pub async fn call(&self, method: &str, params: Value) -> Result<Value, String> {
        let controller = crate::process::controller(false);
        InProcess::call(
            Arc::clone(&self.daemon),
            self.runtime.clone(),
            method.to_string(),
            params,
            controller,
        )
        .await
    }

    /// Sends one typed request and decodes its typed response.
    pub async fn execute<O: DaemonOperation>(&self, operation: O) -> Result<O::Response, String> {
        let params = serde_json::to_value(operation).map_err(|error| error.to_string())?;
        let value = self.call(O::METHOD, params).await?;
        serde_json::from_value(value).map_err(|error| error.to_string())
    }

    /// Stops the core's background work and waits for it, then releases the
    /// state root.
    pub async fn shutdown(mut self) {
        self.daemon.stop();
        if let Some(maintenance) = self.maintenance.take() {
            let _ = maintenance.await;
        }
    }
}

impl Drop for CoreHandle {
    fn drop(&mut self) {
        self.daemon.stop();
        if let Some(maintenance) = self.maintenance.take() {
            maintenance.abort();
        }
    }
}

/// An open apoc core for callers without an async runtime.
///
/// It owns a runtime for the core's background work. Its methods block the
/// calling thread, so calling one from inside an async task returns an error
/// instead of deadlocking that task's runtime.
pub struct Apoc {
    core: Option<CoreHandle>,
    runtime: tokio::runtime::Runtime,
}

impl Apoc {
    /// Opens a core whose state lives in `state_dir`.
    pub fn open(state_dir: impl Into<PathBuf>) -> Result<Self, String> {
        Self::open_with(CoreConfig::new(state_dir))
    }

    /// Opens a core with an explicit configuration.
    pub fn open_with(config: CoreConfig) -> Result<Self, String> {
        refuse_inside_async("Apoc::open")?;
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .thread_name("apoc-core")
            .enable_all()
            .build()
            .map_err(|error| error.to_string())?;
        let core = runtime.block_on(CoreHandle::open(config))?;
        Ok(Self {
            core: Some(core),
            runtime,
        })
    }

    /// Sends one request by method name and returns its JSON result.
    pub fn call(&self, method: &str, params: Value) -> Result<Value, String> {
        refuse_inside_async("Apoc::call")?;
        let core = self.core.as_ref().expect("an open core");
        self.runtime.block_on(core.call(method, params))
    }

    /// Sends one typed request and decodes its typed response.
    pub fn execute<O: DaemonOperation>(&self, operation: O) -> Result<O::Response, String> {
        refuse_inside_async("Apoc::execute")?;
        let core = self.core.as_ref().expect("an open core");
        self.runtime.block_on(core.execute(operation))
    }
}

impl Drop for Apoc {
    fn drop(&mut self) {
        if let Some(core) = self.core.take() {
            // Dropping inside an async task cannot block; the core's own drop
            // still stops its background work.
            if tokio::runtime::Handle::try_current().is_err() {
                self.runtime.block_on(core.shutdown());
            }
        }
    }
}

fn refuse_inside_async(call: &str) -> Result<(), String> {
    if tokio::runtime::Handle::try_current().is_ok() {
        return Err(format!(
            "BLOCKING_FROM_ASYNC: {call} blocks its thread and was called inside an async \
             runtime; use CoreHandle from async code"
        ));
    }
    Ok(())
}