The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
chore: remove legacy LLM tool wrappers for billing, referral, team, and people domains
Steven Enamakel75a2e1de7713
diff --git a/src/openhuman/hosted/billing/tools.rs b/src/openhuman/hosted/billing/tools.rsdeleted file mode 100644index da43c73ad4..0000000000--- a/src/openhuman/hosted/billing/tools.rs+++ /dev/null@@ -1,516 +0,0 @@-//! LLM-callable wrappers over the `billing` domain.-//!-//! Reads (plan/balance/transactions/cards/coupons/auto-recharge + the Stripe-//! portal link) are default-ON. Every money-moving or payment-method mutator-//! ships default-OFF via `tools/user_filter.rs` (`billing_writes` toggle);-//! `billing_delete_card` is `Dangerous`.--use std::sync::Arc;--use async_trait::async_trait;-use serde_json::{json, Value};--use crate::openhuman::config::Config;-use crate::openhuman::hosted::billing;-use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};--macro_rules! emit {- ($outcome:expr, $name:literal) => {{- let outcome = $outcome.map_err(|e| anyhow::anyhow!(concat!($name, ": {}"), e))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }};-}--fn req_str(args: &serde_json::Value, key: &str) -> anyhow::Result<String> {- args.get(key)- .and_then(Value::as_str)- .map(str::trim)- .filter(|s| !s.is_empty())- .map(str::to_string)- .ok_or_else(|| anyhow::anyhow!("missing required string argument `{key}`"))-}--/// Read tool over a `&Config`-only `async fn -> Result<RpcOutcome<Value>, String>`.-macro_rules! cfg_read {- ($ty:ident, $name:literal, $fn:ident, $desc:literal) => {- pub struct $ty {- config: Arc<Config>,- }- impl $ty {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }- }- #[async_trait]- impl Tool for $ty {- fn name(&self) -> &str {- $name- }- fn description(&self) -> &str {- $desc- }- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!(concat!("[tool][billing] ", $name, " invoked"));- emit!(billing::$fn(&self.config).await, $name)- }- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }- }- };-}--cfg_read!(- BillingPlanTool,- "billing_get_plan",- get_current_plan,- "Return the user's current billing plan."-);-cfg_read!(- BillingBalanceTool,- "billing_get_balance",- get_balance,- "Return the user's current credit balance."-);-cfg_read!(- BillingAutoRechargeTool,- "billing_get_auto_recharge",- get_auto_recharge,- "Return the auto-recharge configuration."-);-cfg_read!(- BillingCardsTool,- "billing_list_cards",- get_cards,- "List the user's saved payment cards (masked)."-);-cfg_read!(- BillingCouponsTool,- "billing_list_coupons",- get_user_coupons,- "List the user's coupons / redemption history."-);-cfg_read!(- BillingPortalTool,- "billing_create_stripe_portal",- create_portal_session,- "Create a Stripe customer-portal session and return its URL (read-only; no charge)."-);--/// Transaction history (paginated).-pub struct BillingTransactionsTool {- config: Arc<Config>,-}--impl BillingTransactionsTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for BillingTransactionsTool {- fn name(&self) -> &str {- "billing_list_transactions"- }-- fn description(&self) -> &str {- "List billing transactions, optionally paginated by `limit` / `offset`."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "limit": { "type": "integer", "minimum": 1 },- "offset": { "type": "integer", "minimum": 0 }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][billing] transactions invoked");- let limit = args.get("limit").and_then(Value::as_u64);- let offset = args.get("offset").and_then(Value::as_u64);- emit!(- billing::get_transactions(&self.config, limit, offset).await,- "billing_list_transactions"- )- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--// ── Mutators (default-OFF) ──────────────────────────────────────────────────--/// Purchase a plan.-pub struct BillingPurchasePlanTool {- config: Arc<Config>,-}-impl BillingPurchasePlanTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for BillingPurchasePlanTool {- fn name(&self) -> &str {- "billing_purchase_plan"- }- fn description(&self) -> &str {- "Start a checkout to purchase a billing `plan`. Initiates a payment \- flow. Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": { "plan": { "type": "string" } }, "required": ["plan"] })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- fn external_effect(&self) -> bool {- true- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let plan = req_str(&args, "plan")?;- emit!(- billing::purchase_plan(&self.config, &plan).await,- "billing_purchase_plan"- )- }-}--/// Top up credits.-pub struct BillingTopUpTool {- config: Arc<Config>,-}-impl BillingTopUpTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for BillingTopUpTool {- fn name(&self) -> &str {- "billing_top_up_credits"- }- fn description(&self) -> &str {- "Top up account credits by `amount_usd`, optionally via a specific \- `gateway`. Charges the user. Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "amount_usd": { "type": "number", "minimum": 0 },- "gateway": { "type": "string" }- },- "required": ["amount_usd"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- fn external_effect(&self) -> bool {- true- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let amount = args- .get("amount_usd")- .and_then(Value::as_f64)- .ok_or_else(|| anyhow::anyhow!("missing required number argument `amount_usd`"))?;- let gateway = args- .get("gateway")- .and_then(Value::as_str)- .map(str::to_string);- emit!(- billing::top_up_credits(&self.config, amount, gateway).await,- "billing_top_up_credits"- )- }-}--/// Create a Coinbase crypto charge.-pub struct BillingCoinbaseChargeTool {- config: Arc<Config>,-}-impl BillingCoinbaseChargeTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for BillingCoinbaseChargeTool {- fn name(&self) -> &str {- "billing_create_coinbase_charge"- }- fn description(&self) -> &str {- "Create a Coinbase crypto charge for a `plan`, optional `interval`. \- Initiates a payment. Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "plan": { "type": "string" }, "interval": { "type": "string" } },- "required": ["plan"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- fn external_effect(&self) -> bool {- true- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let plan = req_str(&args, "plan")?;- let interval = args- .get("interval")- .and_then(Value::as_str)- .map(str::to_string);- emit!(- billing::create_coinbase_charge(&self.config, &plan, interval).await,- "billing_create_coinbase_charge"- )- }-}--/// Create a Stripe setup intent (add payment method).-pub struct BillingSetupIntentTool {- config: Arc<Config>,-}-impl BillingSetupIntentTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for BillingSetupIntentTool {- fn name(&self) -> &str {- "billing_create_setup_intent"- }- fn description(&self) -> &str {- "Create a Stripe setup intent to add a payment method. Default-OFF \- (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- fn external_effect(&self) -> bool {- true- }- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- emit!(- billing::create_setup_intent(&self.config).await,- "billing_create_setup_intent"- )- }-}--/// Update a saved card.-pub struct BillingUpdateCardTool {- config: Arc<Config>,-}-impl BillingUpdateCardTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for BillingUpdateCardTool {- fn name(&self) -> &str {- "billing_update_card"- }- fn description(&self) -> &str {- "Update a saved card (`payment_method_id`) with a `payload` of fields. \- Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "payment_method_id": { "type": "string" },- "payload": { "type": "object" }- },- "required": ["payment_method_id", "payload"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- fn external_effect(&self) -> bool {- true- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let pm = req_str(&args, "payment_method_id")?;- let payload = args.get("payload").cloned().unwrap_or(Value::Null);- emit!(- billing::update_card(&self.config, &pm, payload).await,- "billing_update_card"- )- }-}--/// Delete a saved card. Dangerous.-pub struct BillingDeleteCardTool {- config: Arc<Config>,-}-impl BillingDeleteCardTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for BillingDeleteCardTool {- fn name(&self) -> &str {- "billing_delete_card"- }- fn description(&self) -> &str {- "Delete a saved payment card by `payment_method_id`. Default-OFF \- (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "payment_method_id": { "type": "string" } },- "required": ["payment_method_id"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Dangerous- }- fn external_effect(&self) -> bool {- true- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let pm = req_str(&args, "payment_method_id")?;- emit!(- billing::delete_card(&self.config, &pm).await,- "billing_delete_card"- )- }-}--/// Redeem a coupon.-pub struct BillingRedeemCouponTool {- config: Arc<Config>,-}-impl BillingRedeemCouponTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for BillingRedeemCouponTool {- fn name(&self) -> &str {- "billing_redeem_coupon"- }- fn description(&self) -> &str {- "Redeem a coupon `code`. Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": { "code": { "type": "string" } }, "required": ["code"] })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- fn external_effect(&self) -> bool {- true- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let code = req_str(&args, "code")?;- emit!(- billing::redeem_coupon(&self.config, &code).await,- "billing_redeem_coupon"- )- }-}--/// Update auto-recharge policy.-pub struct BillingUpdateAutoRechargeTool {- config: Arc<Config>,-}-impl BillingUpdateAutoRechargeTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for BillingUpdateAutoRechargeTool {- fn name(&self) -> &str {- "billing_update_auto_recharge"- }- fn description(&self) -> &str {- "Update the auto-recharge policy with a `payload` of settings. \- Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "payload": { "type": "object" } },- "required": ["payload"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- fn external_effect(&self) -> bool {- true- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let payload = args- .get("payload")- .cloned()- .ok_or_else(|| anyhow::anyhow!("missing required object argument `payload`"))?;- emit!(- billing::update_auto_recharge(&self.config, payload).await,- "billing_update_auto_recharge"- )- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::openhuman::tools::traits::ToolScope;-- fn cfg() -> Arc<Config> {- Arc::new(Config::default())- }-- #[test]- fn names_and_levels() {- assert_eq!(BillingPlanTool::new(cfg()).name(), "billing_get_plan");- assert_eq!(- BillingPlanTool::new(cfg()).permission_level(),- PermissionLevel::ReadOnly- );- assert_eq!(- BillingPurchasePlanTool::new(cfg()).permission_level(),- PermissionLevel::Write- );- assert!(- BillingPurchasePlanTool::new(cfg()).external_effect_with_args(&serde_json::Value::Null)- );- assert_eq!(- BillingDeleteCardTool::new(cfg()).permission_level(),- PermissionLevel::Dangerous- );- assert_eq!(BillingPlanTool::new(cfg()).scope(), ToolScope::All);- }-- #[tokio::test]- async fn purchase_requires_plan() {- let err = BillingPurchasePlanTool::new(cfg())- .execute(json!({}))- .await- .expect_err("missing plan");- assert!(err.to_string().contains("plan"));- }-}diff --git a/src/openhuman/hosted/referral/tools.rs b/src/openhuman/hosted/referral/tools.rsdeleted file mode 100644index 5aebf8cf16..0000000000--- a/src/openhuman/hosted/referral/tools.rs+++ /dev/null@@ -1,142 +0,0 @@-//! LLM-callable wrappers over the `referral` domain. Both default-ON-//! (claim is bounded and self-service).--use std::sync::Arc;--use async_trait::async_trait;-use serde_json::{json, Value};--use crate::openhuman::config::Config;-use crate::openhuman::hosted::referral;-use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};--macro_rules! emit {- ($outcome:expr, $name:literal) => {{- let outcome = $outcome.map_err(|e| anyhow::anyhow!(concat!($name, ": {}"), e))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }};-}--/// Referral stats.-pub struct ReferralStatsTool {- config: Arc<Config>,-}--impl ReferralStatsTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for ReferralStatsTool {- fn name(&self) -> &str {- "referral_get_stats"- }-- fn description(&self) -> &str {- "Return the user's referral stats (code, referrals, rewards)."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }-- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][referral] stats invoked");- emit!(- referral::get_stats(&self.config).await,- "referral_get_stats"- )- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Claim a referral code.-pub struct ReferralClaimTool {- config: Arc<Config>,-}--impl ReferralClaimTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for ReferralClaimTool {- fn name(&self) -> &str {- "referral_claim"- }-- fn description(&self) -> &str {- "Claim a referral `code` (optionally with a `device_fingerprint`). \- Bounded, self-service."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "code": { "type": "string" },- "device_fingerprint": { "type": "string" }- },- "required": ["code"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][referral] claim invoked");- let code = args- .get("code")- .and_then(Value::as_str)- .map(str::trim)- .filter(|s| !s.is_empty())- .ok_or_else(|| anyhow::anyhow!("missing required string argument `code`"))?;- let fp = args.get("device_fingerprint").and_then(Value::as_str);- emit!(- referral::claim_referral(&self.config, code, fp).await,- "referral_claim"- )- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::openhuman::tools::traits::ToolScope;-- fn cfg() -> Arc<Config> {- Arc::new(Config::default())- }-- #[test]- fn metadata() {- assert_eq!(ReferralStatsTool::new(cfg()).name(), "referral_get_stats");- assert_eq!(- ReferralStatsTool::new(cfg()).permission_level(),- PermissionLevel::ReadOnly- );- assert_eq!(- ReferralClaimTool::new(cfg()).permission_level(),- PermissionLevel::Write- );- assert_eq!(ReferralStatsTool::new(cfg()).scope(), ToolScope::All);- }-- #[tokio::test]- async fn claim_requires_code() {- let err = ReferralClaimTool::new(cfg())- .execute(json!({}))- .await- .expect_err("missing code");- assert!(err.to_string().contains("code"));- }-}diff --git a/src/openhuman/hosted/team/tools.rs b/src/openhuman/hosted/team/tools.rsdeleted file mode 100644index 4a8c9f2171..0000000000--- a/src/openhuman/hosted/team/tools.rs+++ /dev/null@@ -1,486 +0,0 @@-//! LLM-callable wrappers over the `team` domain.-//!-//! Reads (list teams/members/invites, get team, usage) are default-ON. Every-//! membership/org mutator ships default-OFF via `tools/user_filter.rs`-//! (`team_admin` toggle); delete_team and remove_member are `Dangerous`.--use std::sync::Arc;--use async_trait::async_trait;-use serde_json::{json, Value};--use crate::openhuman::config::Config;-use crate::openhuman::hosted::team;-use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};--macro_rules! emit {- ($outcome:expr, $name:literal) => {{- let outcome = $outcome.map_err(|e| anyhow::anyhow!(concat!($name, ": {}"), e))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }};-}--fn req_str(args: &serde_json::Value, key: &str) -> anyhow::Result<String> {- args.get(key)- .and_then(Value::as_str)- .map(str::trim)- .filter(|s| !s.is_empty())- .map(str::to_string)- .ok_or_else(|| anyhow::anyhow!("missing required string argument `{key}`"))-}--fn team_id_schema() -> serde_json::Value {- json!({- "type": "object",- "properties": { "team_id": { "type": "string" } },- "required": ["team_id"]- })-}--/// `&Config`-only read.-macro_rules! cfg_read {- ($ty:ident, $name:literal, $fn:ident, $desc:literal) => {- pub struct $ty {- config: Arc<Config>,- }- impl $ty {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }- }- #[async_trait]- impl Tool for $ty {- fn name(&self) -> &str {- $name- }- fn description(&self) -> &str {- $desc- }- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- emit!(team::$fn(&self.config).await, $name)- }- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }- }- };-}--/// `(config, team_id)` read.-macro_rules! team_id_read {- ($ty:ident, $name:literal, $fn:ident, $desc:literal) => {- pub struct $ty {- config: Arc<Config>,- }- impl $ty {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }- }- #[async_trait]- impl Tool for $ty {- fn name(&self) -> &str {- $name- }- fn description(&self) -> &str {- $desc- }- fn parameters_schema(&self) -> serde_json::Value {- team_id_schema()- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let team_id = req_str(&args, "team_id")?;- emit!(team::$fn(&self.config, &team_id).await, $name)- }- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }- }- };-}--cfg_read!(- TeamListTool,- "team_list",- list_teams,- "List the teams the user belongs to."-);-cfg_read!(- TeamUsageTool,- "team_get_usage",- get_usage,- "Return usage metrics for the active team."-);-team_id_read!(- TeamGetTool,- "team_get",- get_team,- "Get one team by `team_id`."-);-team_id_read!(- TeamListMembersTool,- "team_list_members",- list_members,- "List the members of a team by `team_id`."-);-team_id_read!(- TeamListInvitesTool,- "team_list_invites",- list_invites,- "List the outstanding invites for a team by `team_id`."-);--/// `(config, team_id)` mutator at a given permission level.-macro_rules! team_id_mutator {- ($ty:ident, $name:literal, $fn:ident, $perm:expr, $desc:literal) => {- pub struct $ty {- config: Arc<Config>,- }- impl $ty {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }- }- #[async_trait]- impl Tool for $ty {- fn name(&self) -> &str {- $name- }- fn description(&self) -> &str {- $desc- }- fn parameters_schema(&self) -> serde_json::Value {- team_id_schema()- }- fn permission_level(&self) -> PermissionLevel {- $perm- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let team_id = req_str(&args, "team_id")?;- emit!(team::$fn(&self.config, &team_id).await, $name)- }- }- };-}--team_id_mutator!(- TeamDeleteTool,- "team_delete",- delete_team,- PermissionLevel::Dangerous,- "Delete a team by `team_id`. Default-OFF (opt-in)."-);-team_id_mutator!(- TeamSwitchTool,- "team_switch",- switch_team,- PermissionLevel::Write,- "Switch the active team to `team_id`. Default-OFF (opt-in)."-);-team_id_mutator!(- TeamLeaveTool,- "team_leave",- leave_team,- PermissionLevel::Write,- "Leave a team by `team_id`. Default-OFF (opt-in)."-);--/// Create a team.-pub struct TeamCreateTool {- config: Arc<Config>,-}-impl TeamCreateTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for TeamCreateTool {- fn name(&self) -> &str {- "team_create"- }- fn description(&self) -> &str {- "Create a new team with `name`. Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let name = req_str(&args, "name")?;- emit!(team::create_team(&self.config, &name).await, "team_create")- }-}--/// Update a team's name.-pub struct TeamUpdateTool {- config: Arc<Config>,-}-impl TeamUpdateTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for TeamUpdateTool {- fn name(&self) -> &str {- "team_update"- }- fn description(&self) -> &str {- "Update a team (`team_id`) name. Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "team_id": { "type": "string" }, "name": { "type": "string" } },- "required": ["team_id"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let team_id = req_str(&args, "team_id")?;- let name = args.get("name").and_then(Value::as_str);- emit!(- team::update_team(&self.config, &team_id, name).await,- "team_update"- )- }-}--/// Join a team via invite code.-pub struct TeamJoinTool {- config: Arc<Config>,-}-impl TeamJoinTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for TeamJoinTool {- fn name(&self) -> &str {- "team_join"- }- fn description(&self) -> &str {- "Join a team via an invite `code`. Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": { "code": { "type": "string" } }, "required": ["code"] })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let code = req_str(&args, "code")?;- emit!(team::join_team(&self.config, &code).await, "team_join")- }-}--/// Create a team invite.-pub struct TeamCreateInviteTool {- config: Arc<Config>,-}-impl TeamCreateInviteTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for TeamCreateInviteTool {- fn name(&self) -> &str {- "team_create_invite"- }- fn description(&self) -> &str {- "Create an invite for a team (`team_id`), optional `max_uses` and \- `expires_in_days`. Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "team_id": { "type": "string" },- "max_uses": { "type": "integer", "minimum": 1 },- "expires_in_days": { "type": "integer", "minimum": 1 }- },- "required": ["team_id"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let team_id = req_str(&args, "team_id")?;- let max_uses = args.get("max_uses").and_then(Value::as_u64);- let expires = args.get("expires_in_days").and_then(Value::as_u64);- emit!(- team::create_invite(&self.config, &team_id, max_uses, expires).await,- "team_create_invite"- )- }-}--/// Revoke a team invite.-pub struct TeamRevokeInviteTool {- config: Arc<Config>,-}-impl TeamRevokeInviteTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for TeamRevokeInviteTool {- fn name(&self) -> &str {- "team_revoke_invite"- }- fn description(&self) -> &str {- "Revoke a team invite (`team_id` + `invite_id`). Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "team_id": { "type": "string" }, "invite_id": { "type": "string" } },- "required": ["team_id", "invite_id"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let team_id = req_str(&args, "team_id")?;- let invite_id = req_str(&args, "invite_id")?;- emit!(- team::revoke_invite(&self.config, &team_id, &invite_id).await,- "team_revoke_invite"- )- }-}--/// Remove a team member.-pub struct TeamRemoveMemberTool {- config: Arc<Config>,-}-impl TeamRemoveMemberTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for TeamRemoveMemberTool {- fn name(&self) -> &str {- "team_remove_member"- }- fn description(&self) -> &str {- "Remove a member (`user_id`) from a team (`team_id`). Default-OFF \- (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "team_id": { "type": "string" }, "user_id": { "type": "string" } },- "required": ["team_id", "user_id"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Dangerous- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let team_id = req_str(&args, "team_id")?;- let user_id = req_str(&args, "user_id")?;- emit!(- team::remove_member(&self.config, &team_id, &user_id).await,- "team_remove_member"- )- }-}--/// Change a team member's role.-pub struct TeamChangeMemberRoleTool {- config: Arc<Config>,-}-impl TeamChangeMemberRoleTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}-#[async_trait]-impl Tool for TeamChangeMemberRoleTool {- fn name(&self) -> &str {- "team_change_member_role"- }- fn description(&self) -> &str {- "Change a team member's `role` (`team_id` + `user_id` + `role`). \- Default-OFF (opt-in)."- }- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "team_id": { "type": "string" },- "user_id": { "type": "string" },- "role": { "type": "string" }- },- "required": ["team_id", "user_id", "role"]- })- }- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let team_id = req_str(&args, "team_id")?;- let user_id = req_str(&args, "user_id")?;- let role = req_str(&args, "role")?;- emit!(- team::change_member_role(&self.config, &team_id, &user_id, &role).await,- "team_change_member_role"- )- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::openhuman::tools::traits::ToolScope;-- fn cfg() -> Arc<Config> {- Arc::new(Config::default())- }-- #[test]- fn names_and_levels() {- assert_eq!(TeamListTool::new(cfg()).name(), "team_list");- assert_eq!(- TeamListTool::new(cfg()).permission_level(),- PermissionLevel::ReadOnly- );- assert_eq!(- TeamCreateTool::new(cfg()).permission_level(),- PermissionLevel::Write- );- assert_eq!(- TeamDeleteTool::new(cfg()).permission_level(),- PermissionLevel::Dangerous- );- assert_eq!(- TeamRemoveMemberTool::new(cfg()).permission_level(),- PermissionLevel::Dangerous- );- assert_eq!(TeamListTool::new(cfg()).scope(), ToolScope::All);- }-- #[tokio::test]- async fn get_requires_team_id() {- let err = TeamGetTool::new(cfg())- .execute(json!({}))- .await- .expect_err("missing team_id");- assert!(err.to_string().contains("team_id"));- }-}diff --git a/src/openhuman/memory/tools/people.rs b/src/openhuman/memory/tools/people.rsdeleted file mode 100644index 26f7682d61..0000000000--- a/src/openhuman/memory/tools/people.rs+++ /dev/null@@ -1,456 +0,0 @@-//! LLM-callable wrappers over the `people` domain (local relationship graph).-//!-//! These tools let the agent rank known contacts, resolve handles to stable-//! person ids, inspect closeness scores, attach aliases, log interactions,-//! and read a person record. Read + bounded-write tools delegate to-//! [`crate::openhuman::memory::people::rpc`] (which returns `RpcOutcome`) or to-//! `PeopleStore` methods; results are emitted as JSON.-//!-//! All tools here are device-local and default-enabled EXCEPT-//! `people_refresh_address_book`, which performs a bulk OS address-book-//! ingest (and can trigger a Contacts permission prompt) — it is `Execute`-//! and ships default-OFF via `tools/user_filter.rs`.--use async_trait::async_trait;-use chrono::Utc;-use serde_json::json;--use crate::openhuman::memory::api::provider::{MemoryProvider, PersonHandle, PersonInteraction};-use crate::openhuman::memory::guard::MemoryGuard;-use crate::openhuman::memory::ops::guard::active_memory_guard;-use crate::openhuman::memory::people::rpc;-use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};--/// The guarded driver for this call, checked to serve the people family.-///-/// Returns the guard rather than the family handle because the accessor-/// borrows from it.-async fn people_guard() -> anyhow::Result<std::sync::Arc<MemoryGuard>> {- let guard = active_memory_guard()- .await- .map_err(|e| anyhow::anyhow!("people unavailable: {e}"))?;- if guard.as_people().is_none() {- return Err(anyhow::anyhow!(- "people unavailable: memory driver does not support the people family"- ));- }- Ok(guard)-}--fn read_required_str(args: &serde_json::Value, key: &str) -> anyhow::Result<String> {- args.get(key)- .and_then(serde_json::Value::as_str)- .map(str::trim)- .filter(|s| !s.is_empty())- .map(str::to_string)- .ok_or_else(|| anyhow::anyhow!("missing required string argument `{key}`"))-}--/// Read `person_id` as the opaque token the contract defines it to be.-///-/// It is not parsed into a `Uuid` here: `PersonRef` is opaque by contract and-/// the driver owns its format. Validating a shape the host does not define-/// would reject a driver that identifies people some other way.-fn parse_person_id(args: &serde_json::Value) -> anyhow::Result<String> {- read_required_str(args, "person_id")-}--/// Build a [`PersonHandle`] from `kind` + `value` args.-fn parse_handle(args: &serde_json::Value) -> anyhow::Result<PersonHandle> {- let kind = read_required_str(args, "kind")?;- let value = read_required_str(args, "value")?;- serde_json::from_value(json!({ "kind": kind, "value": value })).map_err(|e| {- anyhow::anyhow!("invalid handle (kind must be imessage|email|display_name): {e}")- })-}--fn handle_schema_props() -> serde_json::Value {- json!({- "kind": { "type": "string", "enum": ["imessage", "email", "display_name"], "description": "Handle kind." },- "value": { "type": "string", "description": "Handle value (phone / email / display name)." }- })-}--/// List ranked contacts.-pub struct PeopleListTool;--#[async_trait]-impl Tool for PeopleListTool {- fn name(&self) -> &str {- "people_list"- }-- fn description(&self) -> &str {- "List the user's known contacts ranked by a closeness score (recency × \- frequency × reciprocity × depth). Each entry carries `person_id`, \- names, handles, the score and its components, and interaction count. \- Use to find who the user is closest to or to resolve a name to a \- `person_id`."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "limit": { "type": "integer", "minimum": 1, "description": "Max contacts (default 100, cap 500)." }- }- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][people] list invoked");- let limit = args- .get("limit")- .and_then(serde_json::Value::as_u64)- .map(|v| v as usize)- .unwrap_or(100);- let guard = people_guard().await?;- let outcome = rpc::handle_list(guard.as_people().expect("checked"), limit)- .await- .map_err(|e| anyhow::anyhow!("people_list: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Resolve a handle to a person id.-pub struct PeopleResolveTool;--#[async_trait]-impl Tool for PeopleResolveTool {- fn name(&self) -> &str {- "people_resolve"- }-- fn description(&self) -> &str {- "Resolve a contact handle (kind = imessage | email | display_name) to a \- stable `person_id`. When `create_if_missing` is true, mints a new \- person for an unknown handle. Returns `{ person_id, created }`."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "kind": handle_schema_props()["kind"],- "value": handle_schema_props()["value"],- "create_if_missing": { "type": "boolean", "description": "Mint a person if the handle is unknown (default false)." }- },- "required": ["kind", "value"]- })- }-- fn permission_level(&self) -> PermissionLevel {- // May mint a new person record when create_if_missing is set.- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][people] resolve invoked");- let handle = parse_handle(&args)?;- let create = args- .get("create_if_missing")- .and_then(serde_json::Value::as_bool)- .unwrap_or(false);- let guard = people_guard().await?;- let outcome = rpc::handle_resolve(guard.as_people().expect("checked"), handle, create)- .await- .map_err(|e| anyhow::anyhow!("people_resolve: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-}--/// Score breakdown for a person.-pub struct PeopleScoreTool;--#[async_trait]-impl Tool for PeopleScoreTool {- fn name(&self) -> &str {- "people_score"- }-- fn description(&self) -> &str {- "Return the closeness score and its components (recency, frequency, \- reciprocity, depth) plus interaction count for one `person_id`."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "person_id": { "type": "string", "description": "Person id (UUID)." } },- "required": ["person_id"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][people] score invoked");- let person_id = parse_person_id(&args)?;- let guard = people_guard().await?;- let outcome = rpc::handle_score(guard.as_people().expect("checked"), &person_id)- .await- .map_err(|e| anyhow::anyhow!("people_score: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Read a full person record.-pub struct PeopleGetTool;--#[async_trait]-impl Tool for PeopleGetTool {- fn name(&self) -> &str {- "people_get"- }-- fn description(&self) -> &str {- "Load the full record for one `person_id`: display name, primary email \- / phone, and every attached handle/alias."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "person_id": { "type": "string", "description": "Person id (UUID)." } },- "required": ["person_id"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][people] get invoked");- let person_id = parse_person_id(&args)?;- let guard = people_guard().await?;- let person = guard- .as_people()- .expect("checked")- .get_person(&person_id)- .await- .map_err(|e| anyhow::anyhow!("people_get: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&json!({- "person": person,- }))?))- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Attach a handle alias to a person.-pub struct PeopleAddAliasTool;--#[async_trait]-impl Tool for PeopleAddAliasTool {- fn name(&self) -> &str {- "people_add_alias"- }-- fn description(&self) -> &str {- "Attach an additional handle (kind = imessage | email | display_name) \- to an existing `person_id` so future messages from that handle map to \- the same person. Idempotent."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "person_id": { "type": "string", "description": "Person id (UUID)." },- "kind": handle_schema_props()["kind"],- "value": handle_schema_props()["value"]- },- "required": ["person_id", "kind", "value"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][people] add_alias invoked");- let person_id = parse_person_id(&args)?;- let handle = parse_handle(&args)?;- let guard = people_guard().await?;- guard- .as_people()- .expect("checked")- .add_handle_alias(&person_id, &handle)- .await- .map_err(|e| anyhow::anyhow!("people_add_alias: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(- &json!({ "ok": true }),- )?))- }-}--/// Record an interaction (append-only, feeds scoring).-pub struct PeopleRecordInteractionTool;--#[async_trait]-impl Tool for PeopleRecordInteractionTool {- fn name(&self) -> &str {- "people_record_interaction"- }-- fn description(&self) -> &str {- "Log an interaction with a `person_id` to feed the closeness score. \- `is_outbound` marks who initiated; `length` is a depth proxy (e.g. \- message length). Timestamp defaults to now. Append-only."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "person_id": { "type": "string", "description": "Person id (UUID)." },- "is_outbound": { "type": "boolean", "description": "True if the user sent it (required)." },- "length": { "type": "integer", "minimum": 0, "description": "Depth proxy (default 0)." }- },- "required": ["person_id", "is_outbound"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][people] record_interaction invoked");- let person_id = parse_person_id(&args)?;- let is_outbound = args- .get("is_outbound")- .and_then(serde_json::Value::as_bool)- .ok_or_else(|| anyhow::anyhow!("missing required boolean argument `is_outbound`"))?;- let length = args- .get("length")- .and_then(serde_json::Value::as_u64)- .unwrap_or(0) as u32;- let interaction = PersonInteraction {- person_id,- at: Utc::now().to_rfc3339(),- is_outbound,- length,- };- let guard = people_guard().await?;- guard- .as_people()- .expect("checked")- .record_interaction(&interaction)- .await- .map_err(|e| anyhow::anyhow!("people_record_interaction: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(- &json!({ "ok": true }),- )?))- }-}--/// Bulk-ingest the OS address book. **Triggers a permission prompt** —-/// default-OFF.-pub struct PeopleRefreshAddressBookTool;--#[async_trait]-impl Tool for PeopleRefreshAddressBookTool {- fn name(&self) -> &str {- "people_refresh_address_book"- }-- fn description(&self) -> &str {- "Bulk-import the operating system address book into the people store, \- seeding contacts and their handles. On macOS this may trigger a \- Contacts (TCC) permission prompt. Returns counts of seeded / skipped \- contacts. Only use when the user explicitly asks to import contacts."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Execute- }-- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][people] refresh_address_book invoked");- let guard = people_guard().await?;- let outcome = rpc::handle_refresh_address_book(guard.as_people().expect("checked"))- .await- .map_err(|e| anyhow::anyhow!("people_refresh_address_book: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::openhuman::tools::traits::ToolScope;-- #[test]- fn names_and_levels() {- assert_eq!(PeopleListTool.name(), "people_list");- assert_eq!(PeopleListTool.permission_level(), PermissionLevel::ReadOnly);- assert_eq!(PeopleResolveTool.permission_level(), PermissionLevel::Write);- assert_eq!(- PeopleRecordInteractionTool.permission_level(),- PermissionLevel::Write- );- assert_eq!(- PeopleRefreshAddressBookTool.permission_level(),- PermissionLevel::Execute- );- assert_eq!(PeopleListTool.scope(), ToolScope::All);- }-- #[test]- fn parse_handle_accepts_known_kinds() {- let h = parse_handle(&json!({ "kind": "email", "value": "[email protected]" })).expect("email");- assert!(matches!(h, PersonHandle::Email(_)));- let d =- parse_handle(&json!({ "kind": "display_name", "value": "Alice" })).expect("display");- assert!(matches!(d, PersonHandle::DisplayName(_)));- }-- #[test]- fn parse_handle_rejects_unknown_kind() {- let err = parse_handle(&json!({ "kind": "fax", "value": "x" })).expect_err("bad kind");- assert!(err.to_string().contains("handle"));- }-- /// `person_id` is opaque now — a non-UUID is **not** rejected here.- ///- /// This test previously asserted the opposite. `PersonRef` is opaque by- /// contract: the driver issues the id and owns its format, so validating a- /// UUID shape host-side would reject a perfectly good driver that- /// identifies people some other way. An id the driver does not recognise- /// comes back as `Invalid` from the driver, which is where that judgement- /// belongs.- #[test]- fn parse_person_id_accepts_any_non_empty_token() {- let id = parse_person_id(&json!({ "person_id": "not-a-uuid" }))- .expect("an opaque id is passed through");- assert_eq!(id, "not-a-uuid");- }-- /// A *missing* id is still the host's to reject: it is a malformed call,- /// not an unrecognised identity.- #[test]- fn parse_person_id_still_requires_the_argument() {- let err = parse_person_id(&json!({})).expect_err("missing person_id");- assert!(err.to_string().contains("person_id"));- }-- #[tokio::test]- async fn score_requires_person_id() {- let err = PeopleScoreTool- .execute(json!({}))- .await- .expect_err("missing person_id");- assert!(err.to_string().contains("person_id"));- }-}diff --git a/src/openhuman/threads/tools.rs b/src/openhuman/threads/tools.rsdeleted file mode 100644index a3b280dfd4..0000000000--- a/src/openhuman/threads/tools.rs+++ /dev/null@@ -1,904 +0,0 @@-//! LLM-callable wrappers over the `threads` domain (conversation threads).-//!-//! These tools let the agent enumerate, create, retitle, relabel, and read-//! conversation threads and their messages, inspect/clear in-flight turn-//! state, and read/write a thread's kanban task board. Most tools deserialize-//! their args into the same request struct the RPC layer uses and delegate to-//! [`crate::openhuman::threads::ops`] (which returns-//! `RpcOutcome<ApiEnvelope<_>>`); the wrapper emits the inner envelope as JSON.-//!-//! Read/bounded-write tools are default-enabled. The destructive ones —-//! `thread_delete` (one thread) and `thread_purge_all` (every thread) — ship-//! default-OFF via `tools/user_filter.rs`.--use std::sync::Arc;--use async_trait::async_trait;-use chrono::Utc;-use serde_json::json;--use crate::openhuman::agent::task_board::{- board_for_thread, TaskBoard, TaskBoardCard, TaskBoardStore,-};-use crate::openhuman::config::Config;-use crate::openhuman::memory::{- AppendConversationMessageRequest, ConversationMessagesRequest, CreateConversationThreadRequest,- DeleteConversationThreadRequest, EmptyRequest, GenerateConversationThreadTitleRequest,- UpdateConversationMessageRequest, UpdateConversationThreadLabelsRequest,- UpdateConversationThreadTitleRequest,-};-use crate::openhuman::threads::ops;-use crate::openhuman::threads::turn_state::{ClearTurnStateRequest, GetTurnStateRequest};-use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};--fn read_required_str(args: &serde_json::Value, key: &str) -> anyhow::Result<String> {- args.get(key)- .and_then(serde_json::Value::as_str)- .map(str::trim)- .filter(|s| !s.is_empty())- .map(str::to_string)- .ok_or_else(|| anyhow::anyhow!("missing required string argument `{key}`"))-}--/// Deserialize tool args into a request struct with a uniform error.-fn parse_req<T: serde::de::DeserializeOwned>(- args: serde_json::Value,- tool: &str,-) -> anyhow::Result<T> {- serde_json::from_value(args).map_err(|e| anyhow::anyhow!("{tool}: invalid arguments: {e}"))-}--/// Emit a thread ops `RpcOutcome` envelope as a JSON tool result.-macro_rules! emit {- ($outcome:expr, $name:literal) => {{- let outcome = $outcome.map_err(|e| anyhow::anyhow!(concat!($name, ": {}"), e))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }};-}--/// List conversation threads.-pub struct ThreadListTool;--#[async_trait]-impl Tool for ThreadListTool {- fn name(&self) -> &str {- "thread_list"- }-- fn description(&self) -> &str {- "List conversation threads (id, title, labels, timestamps). Use to find \- a thread id before reading its messages, retitling, or relabeling."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }-- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] list invoked");- emit!(ops::threads_list(EmptyRequest {}).await, "thread_list")- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Read one thread's metadata (filtered from the list).-pub struct ThreadReadTool;--/// Recursively find the first JSON object whose id field matches `target`.-fn find_thread_obj(value: &serde_json::Value, target: &str) -> Option<serde_json::Value> {- match value {- serde_json::Value::Object(map) => {- for key in ["id", "thread_id", "threadId"] {- if map.get(key).and_then(|v| v.as_str()) == Some(target) {- return Some(value.clone());- }- }- map.values().find_map(|v| find_thread_obj(v, target))- }- serde_json::Value::Array(items) => items.iter().find_map(|v| find_thread_obj(v, target)),- _ => None,- }-}--#[async_trait]-impl Tool for ThreadReadTool {- fn name(&self) -> &str {- "thread_read"- }-- fn description(&self) -> &str {- "Read one conversation thread's metadata by `thread_id` (title, labels, \- timestamps). For the messages themselves, use `thread_message_list`."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "thread_id": { "type": "string", "description": "Thread id." } },- "required": ["thread_id"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] read invoked");- let thread_id = read_required_str(&args, "thread_id")?;- let outcome = ops::threads_list(EmptyRequest {})- .await- .map_err(|e| anyhow::anyhow!("thread_read: {e}"))?;- let value = serde_json::to_value(&outcome.value)?;- match find_thread_obj(&value, &thread_id) {- Some(found) => Ok(ToolResult::success(serde_json::to_string(&found)?)),- None => Err(anyhow::anyhow!(- "thread_read: thread `{thread_id}` not found"- )),- }- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Create a new thread.-pub struct ThreadCreateTool;--#[async_trait]-impl Tool for ThreadCreateTool {- fn name(&self) -> &str {- "thread_create"- }-- fn description(&self) -> &str {- "Create a new conversation thread, optionally with `labels` and a \- `personality_id`. Returns the new thread summary (including its id)."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "labels": { "type": "array", "items": { "type": "string" } },- "personality_id": { "type": "string" }- }- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] create invoked");- let req: CreateConversationThreadRequest = parse_req(args, "thread_create")?;- emit!(ops::thread_create_new(req).await, "thread_create")- }-}--/// Update a thread's title.-pub struct ThreadUpdateTitleTool;--#[async_trait]-impl Tool for ThreadUpdateTitleTool {- fn name(&self) -> &str {- "thread_update_title"- }-- fn description(&self) -> &str {- "Set a conversation thread's title. Requires `thread_id` and a \- non-empty `title`."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "thread_id": { "type": "string" },- "title": { "type": "string" }- },- "required": ["thread_id", "title"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] update_title invoked");- let req: UpdateConversationThreadTitleRequest = parse_req(args, "thread_update_title")?;- emit!(ops::thread_update_title(req).await, "thread_update_title")- }-}--/// Update a thread's labels.-pub struct ThreadUpdateLabelsTool;--#[async_trait]-impl Tool for ThreadUpdateLabelsTool {- fn name(&self) -> &str {- "thread_update_labels"- }-- fn description(&self) -> &str {- "Replace a conversation thread's labels with the supplied `labels` \- array (empty clears all labels). Requires `thread_id`."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "thread_id": { "type": "string" },- "labels": { "type": "array", "items": { "type": "string" } }- },- "required": ["thread_id", "labels"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] update_labels invoked");- let req: UpdateConversationThreadLabelsRequest = parse_req(args, "thread_update_labels")?;- emit!(ops::thread_update_labels(req).await, "thread_update_labels")- }-}--/// List a thread's messages.-pub struct ThreadMessageListTool;--#[async_trait]-impl Tool for ThreadMessageListTool {- fn name(&self) -> &str {- "thread_message_list"- }-- fn description(&self) -> &str {- "List the messages in a conversation thread by `thread_id`, in order."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "thread_id": { "type": "string" } },- "required": ["thread_id"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] message_list invoked");- let req: ConversationMessagesRequest = parse_req(args, "thread_message_list")?;- emit!(ops::messages_list(req).await, "thread_message_list")- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Search past conversations (all threads) for messages matching a query.-pub struct ThreadTranscriptSearchTool;--impl ThreadTranscriptSearchTool {- /// Default and ceiling for the number of matches returned. Kept small so a- /// context-gathering caller's prompt only grows by a bounded amount.- const DEFAULT_LIMIT: usize = 8;- const MAX_LIMIT: usize = 25;- /// Per-hit snippet cap (chars) — enough to recognise the message without- /// dumping whole turns into the caller's context.- const SNIPPET_CHARS: usize = 220;-- fn snippet(content: &str) -> String {- let collapsed: String = content.split_whitespace().collect::<Vec<_>>().join(" ");- if collapsed.chars().count() <= Self::SNIPPET_CHARS {- return collapsed;- }- let cut = collapsed- .char_indices()- .nth(Self::SNIPPET_CHARS)- .map(|(i, _)| i)- .unwrap_or(collapsed.len());- format!("{}…", &collapsed[..cut])- }-}--#[async_trait]-impl Tool for ThreadTranscriptSearchTool {- fn name(&self) -> &str {- "transcript_search"- }-- fn description(&self) -> &str {- "Search your PAST conversations across all threads for messages matching \- a query (keyword/substring, recency-ranked). Returns the most relevant \- recent matches — each with its thread id, sender, timestamp, and a \- snippet. Use to recall what the user said, asked, or decided in earlier \- chats before answering."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "required": ["query"],- "properties": {- "query": {- "type": "string",- "description": "Keywords or phrase to match against past messages. Be specific — short common words are ignored."- },- "limit": {- "type": "integer",- "description": "Max matches to return (default 8, max 25).",- "minimum": 1,- "maximum": 25- },- "exclude_thread_id": {- "type": "string",- "description": "Thread id to omit from results. Defaults to the active thread when omitted, so the message the user just sent does not crowd out the prior chats you are trying to recall. Pass a specific id to override, or an empty string to search every thread."- }- }- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::ReadOnly- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let query = read_required_str(&args, "query")?;- let limit = args- .get("limit")- .and_then(serde_json::Value::as_u64)- .map(|n| (n as usize).clamp(1, Self::MAX_LIMIT))- .unwrap_or(Self::DEFAULT_LIMIT);- // Resolve the effective thread to exclude:- // - arg omitted → default to the ACTIVE thread, so the message the- // user just sent (persisted before inference starts)- // doesn't become the top "past conversation" hit and- // crowd out the real prior chats we're recalling.- // - arg = "" (empty) → explicit opt-out: search every thread.- // - arg = "<id>" → exclude that specific thread.- let exclude_owned: Option<String> = match args- .get("exclude_thread_id")- .and_then(serde_json::Value::as_str)- {- None => crate::openhuman::agent::tinyagents::thread_context::current_thread_id(),- Some(s) if s.trim().is_empty() => None,- Some(s) => Some(s.trim().to_string()),- };- let exclude = exclude_owned.as_deref();- log::debug!(- "[tool][threads] transcript_search invoked query_chars={} limit={} exclude={:?}",- query.chars().count(),- limit,- exclude- );-- let hits = ops::transcript_search(&query, limit, exclude)- .await- .map_err(|e| anyhow::anyhow!("transcript_search: {e}"))?;-- if hits.is_empty() {- return Ok(ToolResult::success(format!(- "No past messages matched `{query}`."- )));- }-- let mut out = format!(- "{} past message(s) matched `{query}` (newest first):\n",- hits.len()- );- for hit in &hits {- let _ = std::fmt::Write::write_fmt(- &mut out,- format_args!(- "- [thread {} · {} · {}] {}\n",- hit.thread_id,- hit.role,- hit.created_at,- Self::snippet(&hit.content)- ),- );- }- Ok(ToolResult::success(out))- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Append a message to a thread.-pub struct ThreadMessageAppendTool;--#[async_trait]-impl Tool for ThreadMessageAppendTool {- fn name(&self) -> &str {- "thread_message_append"- }-- fn description(&self) -> &str {- "Append a message record to a conversation thread. Requires `thread_id` \- and a `message` object (id, content, type, sender, created_at)."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "thread_id": { "type": "string" },- "message": { "type": "object", "description": "ConversationMessageRecord." }- },- "required": ["thread_id", "message"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] message_append invoked");- let req: AppendConversationMessageRequest = parse_req(args, "thread_message_append")?;- let outcome = ops::message_append(req)- .await- .map_err(|e| anyhow::anyhow!("thread_message_append: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-}--/// Patch a message's metadata.-pub struct ThreadMessageUpdateTool;--#[async_trait]-impl Tool for ThreadMessageUpdateTool {- fn name(&self) -> &str {- "thread_message_update"- }-- fn description(&self) -> &str {- "Patch a message's `extra_metadata` in a thread. Requires `thread_id` \- and `message_id`; `extra_metadata` is the new metadata object."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "thread_id": { "type": "string" },- "message_id": { "type": "string" },- "extra_metadata": { "type": "object" }- },- "required": ["thread_id", "message_id"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] message_update invoked");- let req: UpdateConversationMessageRequest = parse_req(args, "thread_message_update")?;- emit!(ops::message_update(req).await, "thread_message_update")- }-}--/// AI-generate a thread title.-pub struct ThreadTitleGenerateTool;--#[async_trait]-impl Tool for ThreadTitleGenerateTool {- fn name(&self) -> &str {- "thread_title_generate"- }-- fn description(&self) -> &str {- "Generate a concise title for a conversation thread using the model, \- based on its messages. Requires `thread_id`; optional \- `assistant_message` to bias the title. Skips if a non-placeholder \- title already exists."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "thread_id": { "type": "string" },- "assistant_message": { "type": "string" }- },- "required": ["thread_id"]- })- }-- fn permission_level(&self) -> PermissionLevel {- // Runs an inference call.- PermissionLevel::Execute- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] title_generate invoked");- let req: GenerateConversationThreadTitleRequest = parse_req(args, "thread_title_generate")?;- let outcome = ops::thread_generate_title(req)- .await- .map_err(|e| anyhow::anyhow!("thread_title_generate: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&outcome.value)?))- }-}--/// Read in-flight turn state for one thread.-pub struct ThreadTurnStateGetTool;--#[async_trait]-impl Tool for ThreadTurnStateGetTool {- fn name(&self) -> &str {- "thread_turn_state_get"- }-- fn description(&self) -> &str {- "Read the saved in-flight turn state for a thread by `thread_id` (the \- snapshot of an interrupted/streaming agent turn), or null if none."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "thread_id": { "type": "string" } },- "required": ["thread_id"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] turn_state_get invoked");- let req: GetTurnStateRequest = parse_req(args, "thread_turn_state_get")?;- emit!(ops::turn_state_get(req).await, "thread_turn_state_get")- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// List all saved turn-state snapshots.-pub struct ThreadTurnStateListTool;--#[async_trait]-impl Tool for ThreadTurnStateListTool {- fn name(&self) -> &str {- "thread_turn_state_list"- }-- fn description(&self) -> &str {- "List all saved in-flight turn-state snapshots across threads."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }-- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] turn_state_list invoked");- emit!(- ops::turn_state_list(EmptyRequest {}).await,- "thread_turn_state_list"- )- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Clear a thread's turn-state snapshot.-pub struct ThreadTurnStateClearTool;--#[async_trait]-impl Tool for ThreadTurnStateClearTool {- fn name(&self) -> &str {- "thread_turn_state_clear"- }-- fn description(&self) -> &str {- "Clear (delete) the saved in-flight turn-state snapshot for a thread by \- `thread_id`. Returns whether a snapshot existed."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "thread_id": { "type": "string" } },- "required": ["thread_id"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] turn_state_clear invoked");- let req: ClearTurnStateRequest = parse_req(args, "thread_turn_state_clear")?;- emit!(ops::turn_state_clear(req).await, "thread_turn_state_clear")- }-}--/// Read a thread's kanban task board.-pub struct ThreadTaskBoardReadTool {- config: Arc<Config>,-}--impl ThreadTaskBoardReadTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for ThreadTaskBoardReadTool {- fn name(&self) -> &str {- "thread_task_board_read"- }-- fn description(&self) -> &str {- "Read a thread's kanban task board by `thread_id`, returning its cards \- (empty board if none exists yet)."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": { "thread_id": { "type": "string" } },- "required": ["thread_id"]- })- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] task_board_read invoked");- let thread_id = read_required_str(&args, "thread_id")?;- let board = board_for_thread(&self.config.workspace_dir, &thread_id)- .await- .map_err(|e| anyhow::anyhow!("thread_task_board_read: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&json!({- "task_board": board,- }))?))- }-- fn is_concurrency_safe(&self, _args: &serde_json::Value) -> bool {- true- }-}--/// Replace a thread's kanban task board.-pub struct ThreadTaskBoardWriteTool {- config: Arc<Config>,-}--impl ThreadTaskBoardWriteTool {- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-}--#[async_trait]-impl Tool for ThreadTaskBoardWriteTool {- fn name(&self) -> &str {- "thread_task_board_write"- }-- fn description(&self) -> &str {- "Replace a thread's kanban task board with the supplied `cards` array \- (TaskBoardCard objects). Requires `thread_id`. The board is normalized \- and persisted; returns the saved board."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "thread_id": { "type": "string" },- "cards": { "type": "array", "items": { "type": "object" } }- },- "required": ["thread_id", "cards"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Write- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] task_board_write invoked");- let thread_id = read_required_str(&args, "thread_id")?;- let cards_val = args- .get("cards")- .cloned()- .ok_or_else(|| anyhow::anyhow!("missing required array argument `cards`"))?;- let cards: Vec<TaskBoardCard> = serde_json::from_value(cards_val)- .map_err(|e| anyhow::anyhow!("thread_task_board_write: invalid cards: {e}"))?;- let board = TaskBoard {- thread_id,- cards,- updated_at: Utc::now().to_rfc3339(),- };- let saved = TaskBoardStore::new(self.config.workspace_dir.clone())- .put(board)- .await- .map_err(|e| anyhow::anyhow!("thread_task_board_write: {e}"))?;- Ok(ToolResult::success(serde_json::to_string(&json!({- "task_board": saved,- }))?))- }-}--/// Delete one thread. **Irreversible** — default-OFF.-pub struct ThreadDeleteTool;--#[async_trait]-impl Tool for ThreadDeleteTool {- fn name(&self) -> &str {- "thread_delete"- }-- fn description(&self) -> &str {- "Permanently delete a conversation thread (and its messages + turn \- state) by `thread_id`. Requires `deleted_at` (RFC3339 timestamp). \- Irreversible. Only use when the user asks to delete a specific thread."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "thread_id": { "type": "string" },- "deleted_at": { "type": "string", "description": "RFC3339 deletion timestamp." }- },- "required": ["thread_id", "deleted_at"]- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Dangerous- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] delete invoked");- let req: DeleteConversationThreadRequest = parse_req(args, "thread_delete")?;- emit!(ops::thread_delete(req).await, "thread_delete")- }-}--/// Purge every thread. **Irreversible** — default-OFF.-pub struct ThreadPurgeAllTool;--#[async_trait]-impl Tool for ThreadPurgeAllTool {- fn name(&self) -> &str {- "thread_purge_all"- }-- fn description(&self) -> &str {- "Delete EVERY conversation thread and message, and clear all turn-state \- snapshots. Irreversible and total. Only use when the user explicitly \- asks to wipe all conversation history."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({ "type": "object", "properties": {} })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Dangerous- }-- async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {- log::debug!("[tool][threads] purge_all invoked");- emit!(- ops::threads_purge(EmptyRequest {}).await,- "thread_purge_all"- )- }-}--#[cfg(test)]-mod tests {- use super::*;- use crate::openhuman::tools::traits::ToolScope;-- fn cfg() -> Arc<Config> {- Arc::new(Config::default())- }-- #[test]- fn names_and_levels() {- assert_eq!(ThreadListTool.name(), "thread_list");- assert_eq!(ThreadListTool.permission_level(), PermissionLevel::ReadOnly);- assert_eq!(ThreadCreateTool.permission_level(), PermissionLevel::Write);- assert_eq!(- ThreadTitleGenerateTool.permission_level(),- PermissionLevel::Execute- );- assert_eq!(- ThreadDeleteTool.permission_level(),- PermissionLevel::Dangerous- );- assert_eq!(- ThreadPurgeAllTool.permission_level(),- PermissionLevel::Dangerous- );- assert_eq!(- ThreadTaskBoardReadTool::new(cfg()).permission_level(),- PermissionLevel::ReadOnly- );- assert_eq!(- ThreadTaskBoardWriteTool::new(cfg()).permission_level(),- PermissionLevel::Write- );- assert_eq!(ThreadListTool.scope(), ToolScope::All);- assert_eq!(ThreadTranscriptSearchTool.name(), "transcript_search");- assert_eq!(- ThreadTranscriptSearchTool.permission_level(),- PermissionLevel::ReadOnly- );- assert!(ThreadTranscriptSearchTool.is_concurrency_safe(&json!({})));- }-- #[test]- fn transcript_search_requires_query() {- let schema = ThreadTranscriptSearchTool.parameters_schema();- let required = schema["required"].as_array().expect("required array");- assert!(required.iter().any(|v| v == "query"));- }-- #[test]- fn transcript_search_snippet_collapses_and_truncates() {- // Short content is returned with whitespace collapsed, untruncated.- let short = ThreadTranscriptSearchTool::snippet("hello there\n\nworld");- assert_eq!(short, "hello there world");- // Long content is cut to the cap with an ellipsis.- let long_src = "x ".repeat(400);- let long = ThreadTranscriptSearchTool::snippet(&long_src);- assert!(long.ends_with('…'));- assert!(long.chars().count() <= ThreadTranscriptSearchTool::SNIPPET_CHARS + 1);- }-- #[test]- fn find_thread_obj_matches_nested_id() {- let blob = json!({- "data": { "threads": [ { "id": "t1", "title": "A" }, { "id": "t2" } ] }- });- let found = find_thread_obj(&blob, "t2").expect("found t2");- assert_eq!(found["id"], "t2");- assert!(find_thread_obj(&blob, "nope").is_none());- }-- #[tokio::test]- async fn update_title_requires_args() {- let err = ThreadUpdateTitleTool- .execute(json!({ "thread_id": "t1" }))- .await- .expect_err("missing title");- assert!(err.to_string().contains("thread_update_title"));- }-- #[tokio::test]- async fn delete_requires_deleted_at() {- let err = ThreadDeleteTool- .execute(json!({ "thread_id": "t1" }))- .await- .expect_err("missing deleted_at");- assert!(err.to_string().contains("thread_delete"));- }-- #[tokio::test]- async fn task_board_read_requires_thread_id() {- let err = ThreadTaskBoardReadTool::new(cfg())- .execute(json!({}))- .await- .expect_err("missing thread_id");- assert!(err.to_string().contains("thread_id"));- }-}