Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

27.3 KB
Raw Blame
use crate::core::runtime::DispatchCtx;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde_json::{Map, Value};

use crate::config::rpc as config_rpc;
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::Outcome;
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};

use crate::agent_runs::agent_chat::params::AgentChatParams;

pub fn all_controller_schemas() -> Vec<ControllerSchema> {
    vec![
        schemas("chat"),
        schemas("chat_simple"),
        schemas("server_status"),
        schemas("list_definitions"),
        schemas("get_definition"),
        schemas("reload_definitions"),
        schemas("triage_evaluate"),
        schemas("registry_snapshot"),
        schemas("context_breakdown"),
    ]
}

pub fn all_registered_controllers() -> Vec<RegisteredController> {
    vec![
        RegisteredController {
            schema: schemas("chat"),
            handler: handle_chat,
        },
        RegisteredController {
            schema: schemas("chat_simple"),
            handler: handle_chat_simple,
        },
        RegisteredController {
            schema: schemas("server_status"),
            handler: handle_server_status,
        },
        RegisteredController {
            schema: schemas("list_definitions"),
            handler: handle_list_definitions,
        },
        RegisteredController {
            schema: schemas("get_definition"),
            handler: handle_get_definition,
        },
        RegisteredController {
            schema: schemas("reload_definitions"),
            handler: handle_reload_definitions,
        },
        RegisteredController {
            schema: schemas("triage_evaluate"),
            handler: handle_triage_evaluate,
        },
        RegisteredController {
            schema: schemas("registry_snapshot"),
            handler: handle_registry_snapshot,
        },
        RegisteredController {
            schema: schemas("context_breakdown"),
            handler: handle_context_breakdown,
        },
    ]
}

pub fn schemas(function: &str) -> ControllerSchema {
    match function {
        "chat" => ControllerSchema {
            namespace: "agent",
            function: "chat",
            description: "Run one-shot agent chat with optional model overrides.",
            inputs: vec![
                required_string("message", "User message."),
                optional_string("model_override", "Optional model override."),
                optional_f64("temperature", "Optional temperature override."),
                optional_string(
                    "thread_id",
                    "Optional backend thread id for cache grouping and inference logs.",
                ),
                optional_string(
                    "cwd",
                    "Optional working directory for this turn: the agent's file and shell \
                     tools are rooted here, so relative paths resolve inside it. Must be an \
                     existing directory. Omit (or pass empty) to use the configured action_dir.",
                ),
            ],
            outputs: vec![json_output("response", "Agent response payload.")],
        },
        "chat_simple" => ControllerSchema {
            namespace: "agent",
            function: "chat_simple",
            description: "Run one-shot lightweight provider chat.",
            inputs: vec![
                required_string("message", "User message."),
                optional_string("model_override", "Optional model override."),
                optional_f64("temperature", "Optional temperature override."),
                optional_string(
                    "thread_id",
                    "Optional backend thread id for cache grouping and inference logs.",
                ),
            ],
            outputs: vec![json_output("response", "Agent response payload.")],
        },
        "server_status" => ControllerSchema {
            namespace: "agent",
            function: "server_status",
            description: "Return core runtime URL and status for agent calls.",
            inputs: vec![],
            outputs: vec![json_output("status", "Agent server status payload.")],
        },
        "list_definitions" => ControllerSchema {
            namespace: "agent",
            function: "list_definitions",
            description:
                "List safe display metadata for sub-agent definitions in the global registry.",
            inputs: vec![],
            outputs: vec![json_output(
                "definitions",
                "Array of safe AgentDefinitionDisplay payloads; prompt bodies are omitted.",
            )],
        },
        "get_definition" => ControllerSchema {
            namespace: "agent",
            function: "get_definition",
            description: "Fetch a single sub-agent definition by id.",
            inputs: vec![required_string("id", "Definition id (e.g. code_executor).")],
            outputs: vec![json_output("definition", "AgentDefinition payload.")],
        },
        "reload_definitions" => ControllerSchema {
            namespace: "agent",
            function: "reload_definitions",
            description: "Reload custom sub-agent definitions from disk. \
                          NOTE: only takes effect on next process restart in v1 \
                          since the global registry is OnceLock-backed.",
            inputs: vec![],
            outputs: vec![json_output("status", "Reload status payload.")],
        },
        "triage_evaluate" => ControllerSchema {
            namespace: "agent",
            function: "triage_evaluate",
            description: "Run the trigger-triage classifier against a synthetic trigger \
                          payload for testing and replay. Returns the parsed decision \
                          and timing metadata. When dry_run=true the decision is NOT \
                          acted on (no sub-agent dispatch, no events beyond TriggerEvaluated).",
            inputs: vec![
                required_string("source", "Trigger source slug (e.g. 'composio')."),
                optional_string("toolkit", "Toolkit slug (composio-specific)."),
                optional_string("trigger", "Trigger slug (composio-specific)."),
                optional_string("external_id", "Stable per-occurrence id."),
                required_string("display_label", "Human-friendly label."),
                FieldSchema {
                    name: "payload",
                    ty: TypeSchema::Json,
                    comment: "Trigger payload as JSON.",
                    required: true,
                },
                FieldSchema {
                    name: "dry_run",
                    ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),
                    comment: "When true, skip apply_decision (default: false).",
                    required: false,
                },
            ],
            outputs: vec![json_output("result", "Triage evaluation result.")],
        },
        "registry_snapshot" => ControllerSchema {
            namespace: "agent",
            function: "registry_snapshot",
            description: "Project the tinyagents CapabilityRegistry inventory into a durable, \
                          read-only snapshot: every reachable model / tool / graph / agent \
                          component with its ComponentMetadata (id, kind, description, tags, \
                          aliases), plus a Graphviz DOT rendering. Assembled from the sources \
                          reachable outside an in-flight turn (static model catalog, baseline \
                          tool registry, graph topologies, built-in agents); live per-run \
                          tool/model handles are not included. Metadata only — never run state.",
            inputs: vec![],
            outputs: vec![json_output(
                "components",
                "Array of ComponentMetadata (id/kind/description/tags/aliases). Companion \
                 fields: `counts` (per-kind totals), `dot` (Graphviz DOT), `deferred` (kinds \
                 not fully projected outside a turn).",
            )],
        },
        "context_breakdown" => ControllerSchema {
            namespace: "agent",
            function: "context_breakdown",
            description: "Where an agent turn's fixed prompt budget goes: rendered system-prompt \
                          sections, advertised tool-schema bytes, and (with a thread_id) that \
                          thread's persisted history spend, as {label, bytes, est_tokens} rows \
                          the composer's context-usage indicator can render as a stacked bar. \
                          Expensive (rebuilds the agent and fetches live Composio connections); \
                          cached per agent id and invalidated only when config content changes.",
            inputs: vec![
                optional_string(
                    "agent_id",
                    "Agent whose prompt to measure. Defaults to 'orchestrator'.",
                ),
                optional_string(
                    "thread_id",
                    "When given, adds a 'history' section sized from this thread's persisted \
                     usage.",
                ),
            ],
            outputs: vec![json_output(
                "breakdown",
                "{agent_id, model, sections: [{label, bytes, est_tokens}], tools_bytes, \
                 total_est_tokens, context_window}.",
            )],
        },
        _ => ControllerSchema {
            namespace: "agent",
            function: "unknown",
            description: "Unknown agent controller function.",
            inputs: vec![],
            outputs: vec![FieldSchema {
                name: "error",
                ty: TypeSchema::String,
                comment: "Lookup error details.",
                required: true,
            }],
        },
    }
}

fn handle_chat(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let p = deserialize_params::<AgentChatParams>(params)?;
        let mut config = ctx.load_config().await?;
        to_json(
            crate::agent_runs::agent_chat::agent_chat(
                &mut config,
                &p.message,
                p.model_override,
                p.temperature,
                p.thread_id,
                p.cwd,
                // `openhuman.agent_chat` describes a turn on the account's own
                // configured inference. A caller that wants this one turn
                // somewhere else says so through `inference_agent_chat`, which
                // takes the endpoint and bearer as parameters.
                None,
            )
            .await?,
        )
    })
}

fn handle_chat_simple(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let p = deserialize_params::<AgentChatParams>(params)?;
        let config = ctx.load_config().await?;
        to_json(
            crate::inference::host_runtime::ops::agent_chat_simple(
                &ctx,
                &config,
                &p.message,
                p.model_override,
                p.temperature,
                p.thread_id,
            )
            .await?,
        )
    })
}

fn handle_server_status(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async { to_json(config_rpc::agent_server_status()) })
}

fn handle_list_definitions(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let defs = crate::agent_registry::library::list_definition_metadata(&ctx).await?;
        Ok(serde_json::json!({ "definitions": defs }))
    })
}

#[derive(Debug, Deserialize)]
struct GetDefinitionParams {
    id: String,
}

fn handle_get_definition(_ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let p = deserialize_params::<GetDefinitionParams>(params)?;
        let registry = crate::agent_registry::host_definition::AgentDefinitionRegistry::current()
            .ok_or_else(|| "AgentDefinitionRegistry not initialised".to_string())?;
        match registry.get(p.id.trim()) {
            Some(def) => Ok(serde_json::json!({ "definition": def })),
            None => Err(format!("definition '{}' not found", p.id)),
        }
    })
}

fn handle_reload_definitions(_ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async {
        // The global registry is OnceLock-backed so live reload is a
        // no-op in v1. Reply with a status payload that explains this
        // and tells the caller how to refresh.
        let already_loaded =
            crate::agent_registry::host_definition::AgentDefinitionRegistry::global().is_some();
        Ok(serde_json::json!({
            "status": "noop",
            "registry_initialised": already_loaded,
            "note": "Sub-agent definitions are loaded once at process startup. \
                     Restart the core process to pick up new TOML files under \
                     <workspace>/agents/.",
        }))
    })
}

#[derive(Debug, Deserialize)]
struct TriageEvaluateParams {
    source: String,
    toolkit: Option<String>,
    trigger: Option<String>,
    external_id: Option<String>,
    display_label: String,
    payload: Value,
    dry_run: Option<bool>,
}

fn handle_triage_evaluate(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let p = deserialize_params::<TriageEvaluateParams>(params)?;

        tracing::debug!(
            source = %p.source,
            dry_run = p.dry_run.unwrap_or(false),
            has_external_id = p.external_id.is_some(),
            "[rpc][agent] triage_evaluate received"
        );

        // Build a TriggerEnvelope from the RPC params. Source-specific
        // variants are discriminated by `p.source`.
        let envelope = match p.source.as_str() {
            "composio" => {
                tracing::trace!("[rpc][agent] building composio trigger envelope");
                let toolkit = p.toolkit.as_deref().unwrap_or("unknown");
                let trigger = p.trigger.as_deref().unwrap_or("unknown");
                let eid = p.external_id.as_deref().unwrap_or("rpc");
                crate::triage::TriggerEnvelope::from_composio(
                    toolkit, trigger, "rpc", eid, p.payload,
                )
            }
            "webhook" => {
                tracing::trace!("[rpc][agent] building webhook trigger envelope");
                let tunnel_id = p.external_id.as_deref().unwrap_or("unknown");
                let method = p.toolkit.as_deref().unwrap_or("POST");
                let path = p.trigger.as_deref().unwrap_or("/");
                crate::triage::TriggerEnvelope::from_webhook(tunnel_id, method, path, p.payload)
            }
            "cron" => {
                tracing::trace!("[rpc][agent] building cron trigger envelope");
                let job_id = p.external_id.as_deref().unwrap_or("unknown");
                let job_name = p.display_label.as_str();
                // Preserve the structured payload — extract the output string
                // for the envelope label but keep the full JSON for triage.
                let output = p
                    .payload
                    .get("output")
                    .and_then(Value::as_str)
                    .unwrap_or(job_name);
                crate::triage::TriggerEnvelope::from_cron(job_id, job_name, output)
            }
            "external" => {
                tracing::trace!("[rpc][agent] building external trigger envelope");
                let caller_id = p.external_id.as_deref().unwrap_or("unknown");
                let reason = p.display_label.as_str();
                crate::triage::TriggerEnvelope::from_external(caller_id, reason, p.payload)
            }
            other => {
                tracing::warn!(source = %other, "[rpc][agent] unsupported trigger source");
                return Err(format!(
                    "unsupported trigger source `{other}` — supported: composio, webhook, cron, external"
                ));
            }
        };

        tracing::debug!(
            source = %envelope.source.slug(),
            external_id_len = envelope.external_id.len(),
            "[rpc][agent] running triage pipeline"
        );

        let outcome = crate::triage::run_triage(&ctx, &envelope)
            .await
            .map_err(|e| format!("triage evaluation failed: {e}"))?;

        let dry_run = p.dry_run.unwrap_or(false);
        match outcome {
            crate::triage::TriageOutcome::Decision(run) => {
                if !dry_run {
                    // Locally initiated: this is the desktop's own RPC surface,
                    // so the dispatch keeps the authority its caller already
                    // had. The envelope it builds may name a remote *source*,
                    // but the request itself is local (#5634).
                    let origin = crate::triage::local_trigger_origin();
                    crate::security::turn_origin::with_origin(
                        origin,
                        crate::triage::apply_decision(&ctx, run.clone(), &envelope),
                    )
                    .await
                    .map_err(|e| format!("apply_decision failed: {e}"))?;
                }

                Ok(serde_json::json!({
                    "decision": run.decision.action.as_str(),
                    "target_agent": run.decision.target_agent,
                    "prompt": run.decision.prompt,
                    "reason": run.decision.reason,
                    "used_local": run.used_local,
                    "latency_ms": run.latency_ms,
                    "resolution_path": run.resolution_path.as_str(),
                    "dry_run": dry_run,
                }))
            }
            crate::triage::TriageOutcome::Deferred {
                defer_until_ms,
                reason,
            } => {
                // Deferred outcome: the chain (cloud → cloud-retry →
                // local) all failed; the caller is expected to
                // re-issue this trigger after `defer_until_ms`. No
                // side effects fire on this path.
                Ok(serde_json::json!({
                    "decision": "deferred",
                    "resolution_path": "deferred",
                    "defer_until_ms": defer_until_ms,
                    "reason": reason,
                    "dry_run": dry_run,
                }))
            }
            crate::triage::TriageOutcome::Terminal { reason } => Ok(serde_json::json!({
                "decision": "terminal",
                "resolution_path": "terminal",
                "reason": reason,
                "dry_run": dry_run,
            })),
        }
    })
}

/// Read-only projection of the tinyagents `CapabilityRegistry` inventory.
///
/// The per-turn registry (`tinyagents::assemble_turn_harness`) owns live model
/// and tool handles that only exist while a run is in flight and cannot be
/// reached from a standalone RPC. So here we re-project the **same durable
/// descriptor sources** that ARE reachable outside a turn into a
/// [`RegistrySnapshot`], entirely from metadata (no live handles):
///
/// * **Model** — the static cost catalog projection
///   (`cost::catalog::tinyagents_catalog_snapshot`); carries model id, aliases,
///   provider/mode tags.
/// * **Tool** — the baseline tool registry (`tools::ops::default_tools`); names +
///   descriptions. NOTE: the *full* per-agent tool surface (`tools::ops::all_tools`)
///   needs config/memory/audit/action-dir wiring that only exists inside a turn,
///   so only the baseline set is projected here. Deferred — see `deferred` in
///   the response and the migration follow-up.
/// * **Graph** — the surviving host graph descriptors registered as
///   `ComponentKind::Graph` components.
/// * **Agent** — the built-in agent archetypes
///   (`agent_registry::agents::load_builtins()`); id + `when_to_use` blurb.
///
/// Other kinds (Router/Reducer/Store/Middleware/Checkpointer/TaskStore/Listener)
/// are wired per-run and are not enumerable outside a turn; they are reported in
/// `deferred`.
/// Project the user's model registry into runtime-discovered local models for
/// the unified catalog overlay.
///
/// A registry entry is treated as a local runtime model when its `provider`
/// parses as a [`LocalProviderKind`] (`ollama`, `lmstudio`, `mlx`, …). The
/// context window comes from the entry when set, else the runtime profile's
/// default; tool-calling/streaming flags come from the static provider profile
/// (the local runtimes do not advertise per-model capability here). Non-local
/// (cloud/BYOK) rows are skipped — those are owned by the priced catalog layers.
fn local_catalog_models_from_config(
    config: &crate::config::Config,
) -> Vec<crate::platform::cost::catalog::LocalCatalogModel> {
    use tinyinference_local::profile::{profile_for_kind, LocalProviderKind, ToolSupport};

    config
        .model_registry
        .iter()
        .filter_map(|entry| {
            let kind = LocalProviderKind::from_str_loose(&entry.provider)?;
            let profile = profile_for_kind(kind);
            let context_window = if entry.context_window > 0 {
                Some(u64::from(entry.context_window))
            } else {
                profile.default_context_window
            };
            Some(crate::platform::cost::catalog::LocalCatalogModel {
                provider: entry.provider.clone(),
                model_id: entry.id.clone(),
                context_window,
                tool_calling: matches!(profile.tool_support, ToolSupport::Native),
                streaming: profile.supports_streaming,
            })
        })
        .collect()
}

fn handle_registry_snapshot(ctx: DispatchCtx, _params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        use tinyagents_registry::{ComponentKind, ComponentMetadata, RegistrySnapshot};

        let mut components: Vec<ComponentMetadata> = Vec::new();

        // ── Models: unified catalog (crate seed + OpenHuman overlay + local) ─
        // Derive runtime-discovered local models from the user's model registry:
        // any entry whose provider is a local runtime (ollama, lmstudio, mlx, …)
        // is overlaid as a free, runtime-profiled catalog entry so local models
        // appear in the one projection alongside priced vendor rows.
        let local_models = match ctx.load_config().await {
            Ok(config) => local_catalog_models_from_config(&config),
            Err(err) => {
                tracing::debug!(
                    error = %err,
                    "[registry][rpc][agent] config unavailable; unified catalog omits local models"
                );
                Vec::new()
            }
        };
        let catalog = crate::platform::cost::catalog::unified_model_catalog(&local_models);
        let model_count = catalog.models.len();
        for entry in catalog.models {
            let mut meta = ComponentMetadata::new(entry.model_id.clone(), ComponentKind::Model)
                .with_description(format!("{} · {}", entry.provider, entry.mode))
                .with_tag(entry.provider.clone())
                .with_tag(entry.mode.clone());
            meta.aliases = entry.aliases;
            components.push(meta);
        }

        // ── Tools: baseline registry (full per-agent surface deferred) ──────
        let security = std::sync::Arc::new(crate::security::SecurityPolicy::default());
        let baseline_tools = crate::tools::ops::default_tools(security);
        let tool_count = baseline_tools.len();
        for tool in &baseline_tools {
            components.push(
                ComponentMetadata::new(tool.name().to_string(), ComponentKind::Tool)
                    .with_description(tool.description().to_string()),
            );
        }

        // ── Agents: built-in archetypes ─────────────────────────────────────
        let agent_defs = crate::agent_registry::agents::load_builtins()
            .map_err(|e| format!("loading built-in agents for registry snapshot: {e}"))?;
        let agent_count = agent_defs.len();
        for def in &agent_defs {
            let mut meta = ComponentMetadata::new(def.id.clone(), ComponentKind::Agent)
                .with_description(def.when_to_use.clone());
            if let Some(display) = &def.display_name {
                meta = meta.with_tag(display.clone());
            }
            components.push(meta);
        }

        // Sort by (kind, id) for stable, diff-friendly output — mirrors the
        // ordering `CapabilityRegistry::snapshot()` produces.
        components.sort_by(|a, b| (a.kind, a.id.0.as_str()).cmp(&(b.kind, b.id.0.as_str())));

        let snapshot = RegistrySnapshot {
            components,
            ..Default::default()
        };
        let dot = snapshot.to_dot();

        tracing::debug!(
            models = model_count,
            tools = tool_count,
            agents = agent_count,
            total = snapshot.len(),
            "[registry][rpc][agent] registry_snapshot export"
        );

        Ok(serde_json::json!({
            "components": snapshot.components,
            "counts": {
                "model": model_count,
                "tool": tool_count,
                "agent": agent_count,
                "total": snapshot.len(),
            },
            "dot": dot,
            // Kinds not fully enumerable outside an in-flight turn, so callers
            // know the snapshot is a reachable subset rather than the whole
            // per-run registry.
            "deferred": {
                "tool_full_surface": "only baseline tools projected; per-agent all_tools \
                    requires turn-scoped config/memory/audit state",
                "kinds": ["router", "reducer", "store", "middleware", "checkpointer",
                          "task_store", "listener"],
            },
        }))
    })
}

fn handle_context_breakdown(ctx: DispatchCtx, params: Map<String, Value>) -> ControllerFuture {
    Box::pin(async move {
        let p = deserialize_params::<crate::agent_runs::context_breakdown::ContextBreakdownParams>(
            params,
        )?;
        to_json(crate::agent_runs::context_breakdown::context_breakdown(&ctx, p).await?)
    })
}

fn deserialize_params<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {
    serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))
}

fn required_string(name: &'static str, comment: &'static str) -> FieldSchema {
    FieldSchema {
        name,
        ty: TypeSchema::String,
        comment,
        required: true,
    }
}

fn optional_string(name: &'static str, comment: &'static str) -> FieldSchema {
    FieldSchema {
        name,
        ty: TypeSchema::Option(Box::new(TypeSchema::String)),
        comment,
        required: false,
    }
}

fn optional_f64(name: &'static str, comment: &'static str) -> FieldSchema {
    FieldSchema {
        name,
        ty: TypeSchema::Option(Box::new(TypeSchema::F64)),
        comment,
        required: false,
    }
}

fn json_output(name: &'static str, comment: &'static str) -> FieldSchema {
    FieldSchema {
        name,
        ty: TypeSchema::Json,
        comment,
        required: true,
    }
}

fn to_json<T: serde::Serialize>(outcome: Outcome<T>) -> Result<Value, String> {
    outcome.into_cli_compatible_json()
}

#[cfg(test)]
#[path = "schemas_tests.rs"]
mod tests;