Skip to content

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

feat(tinyflows): add copilot proxy accessor

Steven Enamakel9c66cc1e6852
diff --git a/crates/openhuman-core/src/flows/copilot_bus.rs b/crates/openhuman-core/src/flows/copilot_bus.rs
new file mode 100644
index 0000000000..a3fde40f5d
--- /dev/null
+++ b/crates/openhuman-core/src/flows/copilot_bus.rs
@@ -0,0 +1,168 @@
+//! Host tools that invoke the TinyFlows Copilot implementation through its bus contract.
+
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use serde_json::{Value, json};
+use tinyflows_bus::copilot::{ToolCatalogRequest, ToolDescriptor};
+use tinytools::{PermissionLevel, Tool, ToolResult};
+
+use crate::config::Config;
+
+/// The module's tool metadata plus the host-only node-kind overlay for calls.
+pub(crate) struct CopilotToolCatalog {
+ config: Arc<Config>,
+ node_kinds: Vec<Value>,
+ descriptors: HashMap<String, ToolDescriptor>,
+}
+
+impl CopilotToolCatalog {
+ /// Load the tools the compiled module serves for this host configuration.
+ pub(crate) fn load(config: Arc<Config>) -> Result<Self, String> {
+ let node_kinds = serde_json::to_value(crate::flows::all_node_kind_contracts())
+ .map_err(|error| format!("could not encode workflow node contracts: {error}"))?
+ .as_array()
+ .cloned()
+ .ok_or_else(|| "workflow node contracts were not an array".to_string())?;
+ let request = ToolCatalogRequest {
+ node_kinds: node_kinds.clone(),
+ };
+ let call_config = Arc::clone(&config);
+ let descriptors: Vec<ToolDescriptor> = crate::storage::block_on_anyhow(async move {
+ let proxy = crate::modules::tinyflows::copilot_proxy(&call_config)
+ .await
+ .map_err(anyhow::Error::msg)?;
+ proxy
+ .call("ToolCatalog", (request,))
+ .await
+ .map_err(|error| anyhow::anyhow!(error.wire_message()))
+ })
+ .map_err(|error| format!("could not load TinyFlows Copilot tools: {error}"))?;
+
+ let mut by_name = HashMap::with_capacity(descriptors.len());
+ for descriptor in descriptors {
+ permission_level(&descriptor.permission).ok_or_else(|| {
+ format!(
+ "TinyFlows Copilot tool `{}` has unsupported permission `{}`",
+ descriptor.name, descriptor.permission
+ )
+ })?;
+ if by_name.insert(descriptor.name.clone(), descriptor).is_some() {
+ return Err("TinyFlows Copilot returned duplicate tool names".into());
+ }
+ }
+ Ok(Self {
+ config,
+ node_kinds,
+ descriptors: by_name,
+ })
+ }
+
+ pub(crate) fn tool(&self, name: &str) -> Result<BusCopilotTool, String> {
+ let descriptor = self
+ .descriptors
+ .get(name)
+ .cloned()
+ .ok_or_else(|| format!("TinyFlows Copilot does not provide `{name}`"))?;
+ Ok(BusCopilotTool {
+ config: Arc::clone(&self.config),
+ descriptor,
+ node_kinds: self.node_kinds.clone(),
+ })
+ }
+}
+
+/// A `tinytools::Tool` facade over one tool served by TinyFlows Copilot.
+pub(crate) struct BusCopilotTool {
+ config: Arc<Config>,
+ descriptor: ToolDescriptor,
+ node_kinds: Vec<Value>,
+}
+
+impl BusCopilotTool {
+ #[cfg(test)]
+ pub(crate) fn from_name(config: Arc<Config>, name: &str) -> Self {
+ CopilotToolCatalog::load(config)
+ .and_then(|catalog| catalog.tool(name))
+ .unwrap_or_else(|error| panic!("could not prepare Copilot tool `{name}`: {error}"))
+ }
+
+ async fn invoke(
+ &self,
+ args: Value,
+ context: Option<&dyn tinytools::ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ let host = super::builder_host::register(
+ Arc::clone(&self.config),
+ crate::agent::tinyagents::host::run_context::dispatch_ctx_for_tool(context),
+ )
+ .await
+ .map_err(anyhow::Error::msg)?;
+ let proxy = crate::modules::tinyflows::copilot_proxy(&self.config)
+ .await
+ .map_err(anyhow::Error::msg)?;
+ let request = tinyflows_bus::copilot::InvokeToolRequest {
+ name: self.descriptor.name.clone(),
+ arguments: args,
+ host: host.address(),
+ node_kinds: self.node_kinds.clone(),
+ };
+ let result: Value = proxy
+ .call("InvokeTool", (request,))
+ .await
+ .map_err(|error| anyhow::anyhow!(error.wire_message()))?;
+ serde_json::from_value(result)
+ .map_err(|error| anyhow::anyhow!("invalid TinyFlows Copilot tool result: {error}"))
+ }
+}
+
+#[async_trait::async_trait]
+impl Tool for BusCopilotTool {
+ fn name(&self) -> &str {
+ &self.descriptor.name
+ }
+
+ fn description(&self) -> &str {
+ &self.descriptor.description
+ }
+
+ fn parameters_schema(&self) -> Value {
+ self.descriptor.parameters_schema.clone()
+ }
+
+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
+ self.invoke(args, None).await
+ }
+
+ async fn execute_with_context(
+ &self,
+ args: Value,
+ _options: tinytools::ToolCallOptions,
+ context: Option<&dyn tinytools::ToolRunContext>,
+ ) -> anyhow::Result<ToolResult> {
+ self.invoke(args, context).await
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ permission_level(&self.descriptor.permission).unwrap_or(PermissionLevel::Dangerous)
+ }
+
+ fn external_effect(&self) -> bool {
+ self.descriptor.external_effect
+ }
+}
+
+fn permission_level(permission: &str) -> Option<PermissionLevel> {
+ match permission {
+ "None" => Some(PermissionLevel::None),
+ "ReadOnly" => Some(PermissionLevel::ReadOnly),
+ "Write" => Some(PermissionLevel::Write),
+ "Execute" => Some(PermissionLevel::Execute),
+ "Dangerous" => Some(PermissionLevel::Dangerous),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+#[path = "copilot_bus_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/modules/tinyflows.rs b/crates/openhuman-core/src/modules/tinyflows.rs
index fdafb4239f..62279a7d46 100644
--- a/crates/openhuman-core/src/modules/tinyflows.rs
+++ b/crates/openhuman-core/src/modules/tinyflows.rs
@@ -96,6 +96,22 @@ mod imp {
.map_err(|error| format!("the tinyflows schedule object is unreachable: {error}"))
}
+ async fn copilot_interface_proxy(config: &Config) -> Result<Proxy, String> {
+ ensure(config).await?;
+ let runtime = runtime::runtime()
+ .await
+ .map_err(|error| format!("the module bus is unavailable: {error}"))?;
+ runtime
+ .connection()
+ .proxy(
+ tinyflows_bus::BUS_NAME,
+ tinyflows_bus::OBJECT_PATH,
+ tinyflows_bus::copilot::INTERFACE,
+ )
+ .map(|proxy| proxy.with_timeout(CALL_TIMEOUT))
+ .map_err(|error| format!("the tinyflows copilot object is unreachable: {error}"))
+ }
+
/// A proxy for the module's `Schedule` object (store, maths and
/// validation members, which answer quickly).
pub(crate) async fn proxy(config: &Config) -> Result<Proxy, String> {
@@ -107,6 +123,11 @@ mod imp {
schedule_proxy(config, RUN_TIMEOUT).await
}
+ /// A proxy for the module's Copilot tool, prompt and fallback services.
+ pub(crate) async fn copilot_proxy(config: &Config) -> Result<Proxy, String> {
+ copilot_interface_proxy(config).await
+ }
+
/// Serve `object` at `path` on the module bus, on the module runtime, and
/// own the host bus name. Idempotent per path only if `path` is unserved
/// first ([`unserve`]).
@@ -167,7 +188,7 @@ mod imp {
mod fixture;
#[cfg(feature = "modules")]
-pub(crate) use imp::{proxy, run_proxy, serve, unserve};
+ pub(crate) use imp::{copilot_proxy, proxy, run_proxy, serve, unserve};
#[cfg(not(feature = "modules"))]
mod imp {
@@ -191,6 +212,10 @@ mod imp {
Err(unavailable(config))
}
+ pub(crate) async fn copilot_proxy(config: &Config) -> Result<tinybus::Proxy, String> {
+ Err(unavailable(config))
+ }
+
pub(crate) async fn serve(
_path: String,
_object: impl tinybus::service::Interface + 'static,
@@ -202,7 +227,7 @@ mod imp {
}
#[cfg(not(feature = "modules"))]
-pub(crate) use imp::{proxy, run_proxy, serve, unserve};
+pub(crate) use imp::{copilot_proxy, proxy, run_proxy, serve, unserve};
/// Whether the module can serve in this build and configuration (the switch
/// is on and the loader exists). Does not load anything.