Skip to content

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

feat(hosting): add hosting module with tools and analytics support

Steven Enamakelb925669b76d4
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 6d0480b241..2ea3c1d309 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -618,7 +618,7 @@ tinyjuice = { path = "../../vendor/tinyjuice", default-features = false, feature
# After cloning: `git submodule update --init vendor/tinyhosts`.
#
# Optional: exclusive to the default-OFF `hosting` feature.
-tinyhosts = { path = "../../vendor/tinyhosts", default-features = false, features = ["vercel"], optional = true }
+tinyhosts = { path = "../../vendor/tinyhosts", default-features = false, features = ["vercel", "tools"], optional = true }
# TinyWallet — host-agnostic multi-chain wallet primitives. Owns the address
# formats themselves: parsing, validation, and the conversions between their
diff --git a/crates/openhuman-core/src/hosting/hosting_tests.rs b/crates/openhuman-core/src/hosting/hosting_tests.rs
index 4b15077a19..600e165091 100644
--- a/crates/openhuman-core/src/hosting/hosting_tests.rs
+++ b/crates/openhuman-core/src/hosting/hosting_tests.rs
@@ -1,11 +1,9 @@
-//! Tests for hosting account resolution, workspace containment, and the tools.
+//! Tests for hosting account resolution and the tool set it exposes.
//!
-//! The provider itself is TinyHosts' problem and is tested there against a mock
-//! of its REST API. What is tested here is the seam: whether an account resolves
-//! from configuration, whether a path an agent named can escape the workspace,
-//! and whether each tool's schema says what its `execute` actually reads.
-
-use serde_json::json;
+//! The provider and the tools themselves (workspace containment, argument
+//! validation, the rollback guard, the declarations a model sees) are TinyHosts'
+//! and are tested there. What is tested here is the seam: whether an account
+//! resolves from configuration and hands the crate's tools its host and workspace.
use super::*;
use crate::config::Config;
@@ -147,495 +145,3 @@ fn every_tool_schema_is_an_object_naming_its_required_arguments() {
);
}
}
-
-#[test]
-fn a_directory_inside_the_workspace_resolves() {
- let workspace = tempfile::tempdir().expect("tempdir");
- std::fs::create_dir(workspace.path().join("site")).expect("mkdir");
-
- let resolved = resolve_in_workspace(workspace.path(), "site").expect("resolves");
-
- assert_eq!(
- resolved,
- workspace
- .path()
- .canonicalize()
- .expect("canonical root")
- .join("site")
- );
-}
-
-#[test]
-fn an_empty_path_is_the_workspace_root() {
- let workspace = tempfile::tempdir().expect("tempdir");
-
- let resolved = resolve_in_workspace(workspace.path(), " ").expect("resolves");
-
- assert_eq!(
- resolved,
- workspace.path().canonicalize().expect("canonical root")
- );
-}
-
-#[test]
-fn a_path_outside_the_workspace_is_refused() {
- let workspace = tempfile::tempdir().expect("tempdir");
- let root = workspace.path();
-
- // A deployment uploads every byte under the directory to a third party, so
- // this is the check that decides what may leave the machine.
- assert!(resolve_in_workspace(root, "/etc").is_err());
- assert!(resolve_in_workspace(root, "../..").is_err());
- assert!(resolve_in_workspace(root, "does-not-exist").is_err());
-}
-
-#[test]
-fn a_file_is_not_a_deployable_directory() {
- let workspace = tempfile::tempdir().expect("tempdir");
- std::fs::write(workspace.path().join("page.tsx"), b"x").expect("write");
-
- let error =
- resolve_in_workspace(workspace.path(), "page.tsx").expect_err("a file is not a directory");
-
- assert!(error.to_string().contains("not a directory"), "{error}");
-}
-
-#[tokio::test]
-async fn launching_reports_a_missing_directory_instead_of_deploying_nothing() {
- let workspace = tempfile::tempdir().expect("tempdir");
- let config = config_with(workspace.path(), true, "token");
- let account = Account::from_config(&config)
- .expect("resolution does not fail")
- .expect("an account");
-
- let tool = tools::LaunchSiteTool::new(account);
- let result = tool
- .execute(json!({"site": "shop", "path": "missing"}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(result.is_error);
-}
-
-#[tokio::test]
-async fn launching_without_a_site_name_is_refused_before_any_upload() {
- let workspace = tempfile::tempdir().expect("tempdir");
- std::fs::write(workspace.path().join("package.json"), b"{}").expect("write");
- let config = config_with(workspace.path(), true, "token");
- let account = Account::from_config(&config)
- .expect("resolution does not fail")
- .expect("an account");
-
- let tool = tools::LaunchSiteTool::new(account);
- let result = tool
- .execute(json!({"path": "."}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(result.is_error);
-}
-
-#[tokio::test]
-async fn a_read_tool_reports_a_missing_argument_rather_than_calling_out() {
- let workspace = tempfile::tempdir().expect("tempdir");
- let config = config_with(workspace.path(), true, "token");
- let account = Account::from_config(&config)
- .expect("resolution does not fail")
- .expect("an account");
-
- let result = tools::DeploymentStatusTool::new(account.host())
- .execute(json!({}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(result.is_error);
-}
-
-// ── The deployment-history and rollback tools (issue opencompany#913) ────────
-
-#[tokio::test]
-async fn the_new_read_tools_report_a_missing_site_rather_than_calling_out() {
- let workspace = tempfile::tempdir().expect("tempdir");
- let config = config_with(workspace.path(), true, "token");
- let account = Account::from_config(&config)
- .expect("resolution does not fail")
- .expect("an account");
-
- let listed = tools::ListDeploymentsTool::new(account.host())
- .execute(json!({}))
- .await
- .expect("the tool reports rather than panics");
- assert!(listed.is_error);
-
- let domains = tools::DomainStatusTool::new(account.host())
- .execute(json!({}))
- .await
- .expect("the tool reports rather than panics");
- assert!(domains.is_error);
-}
-
-#[tokio::test]
-async fn a_rollback_missing_either_argument_is_refused_before_any_call() {
- let workspace = tempfile::tempdir().expect("tempdir");
- let config = config_with(workspace.path(), true, "token");
- let account = Account::from_config(&config)
- .expect("resolution does not fail")
- .expect("an account");
-
- // A rollback names two things and neither can be guessed: repointing
- // production at an unnamed deployment is not a recoverable mistake.
- for args in [
- json!({}),
- json!({"site": "shop"}),
- json!({"deployment_id": "d1"}),
- ] {
- let result = tools::RollbackTool::new(account.host())
- .execute(args.clone())
- .await
- .expect("the tool reports rather than panics");
- assert!(result.is_error, "{args} should have been refused");
- }
-}
-
-// ── The rollback guard, against a mock of the provider's API ─────────────────
-
-use std::sync::Arc as TestArc;
-
-use wiremock::matchers::{method, path};
-use wiremock::{Mock, MockServer, ResponseTemplate};
-
-/// A real provider client pointed at a local mock rather than at Vercel.
-///
-/// `connect_to`'s own documentation names this case, and loopback `http://` is
-/// accepted precisely so a test can carry a bearer token to a server that never
-/// leaves the machine.
-fn host_against(server: &MockServer) -> TestArc<dyn tinyhosts::Host> {
- let base_url = server.uri();
- TestArc::from(
- tinyhosts::connect_to(
- tinyhosts::ProviderKind::Vercel,
- tinyhosts::Credentials::new("token").expect("credentials"),
- Some(base_url.as_str()),
- )
- .expect("a client against the mock"),
- )
-}
-
-/// **The guard that makes this tool a recovery path rather than a second way to
-/// break the site.**
-///
-/// `hosting_list_deployments` returns failed and still-building deployments too
-/// — they are part of the history an agent reads — so the id it picks is not
-/// necessarily one that can serve traffic. Promoting a failed build would take
-/// the site down during an attempt to bring it back up.
-///
-/// The assertion that matters is `expect(0)` on the promote route: the refusal
-/// has to happen *before* the outward call, not be an error message reported
-/// after production already moved.
-#[tokio::test]
-async fn rolling_back_to_a_deployment_that_never_built_does_not_touch_production() {
- let server = MockServer::start().await;
-
- Mock::given(method("GET"))
- .and(path("/v13/deployments/dpl_broken"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "id": "dpl_broken",
- "name": "shop",
- "readyState": "ERROR",
- "errorMessage": "build failed"
- })))
- .mount(&server)
- .await;
-
- // Vercel's promote is POST /v10/projects/{project}/promote/{deployment},
- // reached only after GET /v9/projects/{site} resolves the id. Neither may
- // be called at all.
- Mock::given(method("GET"))
- .and(path("/v9/projects/shop"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "id": "prj_1",
- "name": "shop"
- })))
- .expect(0)
- .mount(&server)
- .await;
-
- let result = tools::RollbackTool::new(host_against(&server))
- .execute(json!({"site": "shop", "deployment_id": "dpl_broken"}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(result.is_error, "a failed deployment must not be promoted");
- // The status is named, so a model can pick a different deployment rather
- // than retry the same one.
- let rendered = result.text();
- assert!(
- rendered.contains("Failed"),
- "the refusal should name the state it refused: {rendered}"
- );
-}
-
-/// The ordinary path: a deployment that built is promoted, and the site's URL
-/// comes back so the agent can say where production now points.
-#[tokio::test]
-async fn rolling_back_to_a_ready_deployment_promotes_it() {
- let server = MockServer::start().await;
-
- Mock::given(method("GET"))
- .and(path("/v13/deployments/dpl_good"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "id": "dpl_good",
- "name": "shop",
- "url": "shop-abc.vercel.app",
- "readyState": "READY",
- "target": "production"
- })))
- .mount(&server)
- .await;
- Mock::given(method("GET"))
- .and(path("/v9/projects/shop"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "id": "prj_1",
- "name": "shop"
- })))
- .mount(&server)
- .await;
- Mock::given(method("POST"))
- .and(path("/v10/projects/prj_1/promote/dpl_good"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({})))
- .expect(1)
- .mount(&server)
- .await;
-
- let result = tools::RollbackTool::new(host_against(&server))
- .execute(json!({"site": "shop", "deployment_id": "dpl_good"}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(!result.is_error, "{result:?}");
- let rendered = result.text();
- assert!(
- rendered.contains("dpl_good") && rendered.contains("shop-abc.vercel.app"),
- "the result should say what is serving and where: {rendered}"
- );
-}
-
-/// The history read an agent uses to *find* the id above.
-#[tokio::test]
-async fn listing_deployments_reports_the_history_a_rollback_picks_from() {
- let server = MockServer::start().await;
-
- Mock::given(method("GET"))
- .and(path("/v7/deployments"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "deployments": [
- {"id": "dpl_new", "name": "shop", "readyState": "ERROR"},
- {"id": "dpl_old", "name": "shop", "readyState": "READY"}
- ]
- })))
- .mount(&server)
- .await;
-
- let result = tools::ListDeploymentsTool::new(host_against(&server))
- .execute(json!({"site": "shop"}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(!result.is_error, "{result:?}");
-
- // Both are reported, and each status is bound to its id. The failed one is
- // why the agent is here and the ready one is where it is going, so a list
- // that returned the right ids against the wrong statuses would send the
- // rollback at the deployment that just broke the site.
- let deployments: serde_json::Value =
- serde_json::from_str(&result.text()).expect("the tool answers with JSON");
- let rows = deployments.as_array().expect("an array of deployments");
-
- assert_eq!(rows.len(), 2, "{deployments}");
- // Newest first, as the crate documents and as the provider returned them.
- assert_eq!(rows[0]["id"], "dpl_new", "{deployments}");
- assert_eq!(rows[0]["status"], "failed", "{deployments}");
- assert_eq!(rows[1]["id"], "dpl_old", "{deployments}");
- assert_eq!(rows[1]["status"], "ready", "{deployments}");
-}
-
-/// A domain that is attached but unverified is not serving, and the tool has to
-/// say so — that difference is the entire reason to read domains.
-#[tokio::test]
-async fn domain_status_distinguishes_a_verified_domain_from_a_pending_one() {
- let server = MockServer::start().await;
-
- Mock::given(method("GET"))
- .and(path("/v9/projects/shop/domains"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!({
- "domains": [
- {"name": "shop.example.com", "verified": true},
- {"name": "www.example.com", "verified": false}
- ]
- })))
- .mount(&server)
- .await;
-
- let result = tools::DomainStatusTool::new(host_against(&server))
- .execute(json!({"site": "shop"}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(!result.is_error, "{result:?}");
-
- // Bound to the name rather than checked for presence: asserting only that a
- // `true` and a `false` both appear somewhere passes just as happily if the
- // two are swapped, which is the one thing this tool must not get wrong.
- let domains: serde_json::Value =
- serde_json::from_str(&result.text()).expect("the tool answers with JSON");
- let verified_for = |name: &str| -> bool {
- let entry = domains
- .as_array()
- .expect("an array of domains")
- .iter()
- .find(|domain| domain["name"] == name)
- .unwrap_or_else(|| panic!("{name} is missing from {domains}"));
- entry["verified"]
- .as_bool()
- .expect("`verified` is a boolean")
- };
-
- assert!(
- verified_for("shop.example.com"),
- "the verified domain must report verified: {domains}"
- );
- assert!(
- !verified_for("www.example.com"),
- "and the pending one must not — that difference is the entire reason to \
- read domains: {domains}"
- );
-}
-
-/// The read an agent reaches for once `hosting_deployment_status` says a build
-/// failed. A status carries one error line; the reason is in the events.
-#[tokio::test]
-async fn deployment_logs_report_the_build_error_behind_a_failed_status() {
- let server = MockServer::start().await;
-
- Mock::given(method("GET"))
- .and(path("/v3/deployments/dpl_broken/events"))
- .respond_with(ResponseTemplate::new(200).set_body_json(json!([
- {"created": 1, "type": "stdout", "payload": "installing dependencies"},
- {"created": 2, "type": "stderr", "payload": "error TS2304: cannot find name 'foo'"}
- ])))
- .mount(&server)
- .await;
-
- let result = tools::DeploymentLogsTool::new(host_against(&server))
- .execute(json!({"deployment_id": "dpl_broken"}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(!result.is_error, "{result:?}");
-
- let logs: serde_json::Value =
- serde_json::from_str(&result.text()).expect("the tool answers with JSON");
- let rows = logs.as_array().expect("an array of events");
-
- assert_eq!(rows.len(), 2, "{logs}");
- // Oldest first, as the crate documents, and each message bound to its kind:
- // a log that reported the right lines against the wrong streams would show
- // a build error as ordinary output and hide the one line worth reading.
- assert_eq!(rows[0]["kind"], "stdout", "{logs}");
- assert_eq!(rows[1]["kind"], "stderr", "{logs}");
- assert!(
- rows[1]["message"]
- .as_str()
- .expect("a message")
- .contains("TS2304"),
- "the build error must survive to the model: {logs}"
- );
-}
-
-/// Trimming keeps the tail. A build that fails after a thousand lines of setup
-/// puts its error at the end, so a limit that kept the head would return a
-/// thousand lines of noise and drop the only one an agent came for.
-#[tokio::test]
-async fn a_limited_log_read_keeps_the_end_where_the_failure_is() {
- let server = MockServer::start().await;
-
- let events: Vec<serde_json::Value> = (0..10)
- .map(|n| json!({"created": n, "type": "stdout", "payload": format!("line {n}")}))
- .collect();
- Mock::given(method("GET"))
- .and(path("/v3/deployments/dpl_long/events"))
- .respond_with(ResponseTemplate::new(200).set_body_json(events))
- .mount(&server)
- .await;
-
- let result = tools::DeploymentLogsTool::new(host_against(&server))
- .execute(json!({"deployment_id": "dpl_long", "limit": 3}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(!result.is_error, "{result:?}");
-
- let logs: serde_json::Value =
- serde_json::from_str(&result.text()).expect("the tool answers with JSON");
- let rows = logs.as_array().expect("an array of events");
-
- assert_eq!(rows.len(), 3, "{logs}");
- assert_eq!(rows[0]["message"], "line 7", "{logs}");
- assert_eq!(rows[2]["message"], "line 9", "{logs}");
-}
-
-#[tokio::test]
-async fn a_negative_log_limit_is_clamped_to_one() {
- let server = MockServer::start().await;
-
- let events: Vec<serde_json::Value> = (0..3)
- .map(|n| json!({"created": n, "type": "stdout", "payload": format!("line {n}")}))
- .collect();
- Mock::given(method("GET"))
- .and(path("/v3/deployments/dpl_negative_limit/events"))
- .respond_with(ResponseTemplate::new(200).set_body_json(events))
- .mount(&server)
- .await;
-
- let result = tools::DeploymentLogsTool::new(host_against(&server))
- .execute(json!({"deployment_id": "dpl_negative_limit", "limit": -1}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(!result.is_error, "{result:?}");
- let logs: serde_json::Value =
- serde_json::from_str(&result.text()).expect("the tool answers with JSON");
- let rows = logs.as_array().expect("an array of events");
-
- assert_eq!(rows.len(), 1, "{logs}");
- assert_eq!(rows[0]["message"], "line 2", "{logs}");
-}
-
-/// A read tool that calls out before checking its arguments turns a model's
-/// omission into a provider request.
-#[tokio::test]
-async fn reading_logs_without_a_deployment_id_is_refused_before_any_call() {
- let server = MockServer::start().await;
-
- let result = tools::DeploymentLogsTool::new(host_against(&server))
- .execute(json!({}))
- .await
- .expect("the tool reports rather than panics");
-
- assert!(result.is_error, "{result:?}");
- assert!(
- result.text().contains("deployment_id"),
- "the error should name the argument: {}",
- result.text()
- );
- // Nothing was mounted, so any request would have been a miss; assert the
- // absence rather than trusting that.
- assert!(
- server
- .received_requests()
- .await
- .unwrap_or_default()
- .is_empty(),
- "a missing argument must not reach the provider"
- );
-}
diff --git a/crates/openhuman-core/src/hosting/mod.rs b/crates/openhuman-core/src/hosting/mod.rs
index a328957a57..a4af9235ea 100644
--- a/crates/openhuman-core/src/hosting/mod.rs
+++ b/crates/openhuman-core/src/hosting/mod.rs
@@ -12,7 +12,7 @@
//!
//! # What the agent gets
//!
-//! Ten tools, in [`tools`]. `hosting_launch_site` is the one that matters: it
+//! Ten tools, in [`tinyhosts::tools`]. `hosting_launch_site` is the one that matters: it
//! turns a directory in the workspace into a live site with a database behind
//! it. `hosting_rollback` is its counterweight — it points production back at
//! an earlier deployment, so an agent that ships a broken site has a way back
@@ -26,7 +26,7 @@
//! registry then does not register the tools at all. A tool that is present and
//! cannot work is worse than one that is absent: a model will retry it.
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
@@ -34,7 +34,7 @@ use tinyhosts::{Credentials, Host, ProviderKind};
use crate::config::Config;
-pub mod tools;
+pub use tinyhosts::tools::resolve_in_workspace;
#[cfg(test)]
#[path = "hosting_tests.rs"]
@@ -151,46 +151,6 @@ impl Account {
/// The agent tools this account exposes.
pub fn tools(&self) -> Vec<Box<dyn tinytools::Tool>> {
- tools::hosting_tools(self)
+ tinyhosts::tools::hosting_tools(&self.host, &self.workspace_dir)
}
}
-
-/// Resolves `relative` against the workspace, refusing anything outside it.
-///
-/// An agent names the directory to deploy, and a deployment uploads every byte
-/// under it to a third party. `../` and absolute paths are therefore refused
-/// here rather than trusted to the model — this is the only place in the domain
-/// that decides what may leave the machine.
-///
-/// # Errors
-///
-/// Returns an error when the path is absolute, escapes the workspace, or does
-/// not name a directory.
-pub fn resolve_in_workspace(workspace_dir: &Path, relative: &str) -> anyhow::Result<PathBuf> {
- let trimmed = relative.trim();
- let candidate = PathBuf::from(if trimmed.is_empty() { "." } else { trimmed });
-
- if candidate.is_absolute() {
- anyhow::bail!("path must be relative to the workspace, not absolute: {relative}");
- }
-
- let joined = workspace_dir.join(&candidate);
- let canonical = joined
- .canonicalize()
- .map_err(|error| anyhow::anyhow!("cannot read {}: {error}", joined.display()))?;
- let root = workspace_dir.canonicalize().map_err(|error| {
- anyhow::anyhow!(
- "cannot read the workspace {}: {error}",
- workspace_dir.display()
- )
- })?;
-
- if !canonical.starts_with(&root) {
- anyhow::bail!("path escapes the workspace: {relative}");
- }
- if !canonical.is_dir() {
- anyhow::bail!("not a directory: {relative}");
- }
-
- Ok(canonical)
-}
diff --git a/crates/openhuman-core/src/hosting/tools.rs b/crates/openhuman-core/src/hosting/tools.rs
deleted file mode 100644
index 3d59d1b3cd..0000000000
--- a/crates/openhuman-core/src/hosting/tools.rs
+++ /dev/null
@@ -1,74 +0,0 @@
-//! The `hosting_*` agent tools.
-//!
-//! Ten tools over one hosting account. They are thin on purpose: argument
-//! parsing, one call into [`tinyhosts`], and a result described for a model.
-//! Anything that looks like hosting logic belongs in the crate, where it is
-//! provider-independent and tested against a mock of the provider's API.
-//!
-//! `hosting_launch_site` uploads a directory to a third party and can spend
-//! money on a database, and `hosting_rollback` repoints a live site's
-//! production traffic; both route through the approval gate, as do
-//! `hosting_set_env` and `hosting_add_domain`. The rest read.
-//!
-//! # Why there is a rollback but no separate "promote"
-//!
-//! [`Host::promote`] is both: a rollback *is* a promote of an older deployment,
-//! and the crate models it once deliberately. The tool is named for the reason
-//! an agent reaches for it. Without it an agent can deploy a broken site and
-//! have no way back, which is the whole argument for the tool existing.
-
-mod analytics;
-mod deployments;
-mod domains;
-mod launch;
-mod sites;
-
-use serde_json::Value;
-
-pub use analytics::AnalyticsTool;
-pub use deployments::{
- DeploymentLogsTool, DeploymentStatusTool, ListDeploymentsTool, RollbackTool,
-};
-pub use domains::{AddDomainTool, DomainStatusTool};
-pub use launch::LaunchSiteTool;
-pub use sites::{ListSitesTool, SetEnvTool};
-
-use super::Account;
-use tinytools::Tool;
-
-/// Every hosting tool, for one account.
-pub fn hosting_tools(account: &Account) -> Vec<Box<dyn Tool>> {
- vec![
- Box::new(LaunchSiteTool::new(account.clone())),
- Box::new(DeploymentStatusTool::new(account.host())),
- Box::new(ListDeploymentsTool::new(account.host())),
- Box::new(DeploymentLogsTool::new(account.host())),
- Box::new(RollbackTool::new(account.host())),
- Box::new(ListSitesTool::new(account.host())),
- Box::new(SetEnvTool::new(account.host())),
- Box::new(AddDomainTool::new(account.host())),
- Box::new(DomainStatusTool::new(account.host())),
- Box::new(AnalyticsTool::new(account.host())),
- ]
-}
-
-/// Reads a required string argument.
-fn required_str(args: &Value, key: &str) -> anyhow::Result<String> {
- args.get(key)
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|value| !value.is_empty())
- .map(ToOwned::to_owned)
- .ok_or_else(|| anyhow::anyhow!("`{key}` is required"))
-}
-
-/// Renders one `env` object value. A number or a bool is still a variable, so
-/// it is rendered rather than dropped. `null` and a container are refused: a
-/// variable silently set to `"null"` is worse than a named error.
-fn env_value(key: &str, value: &Value) -> anyhow::Result<String> {
- match value {
- Value::String(value) => Ok(value.clone()),
- Value::Number(_) | Value::Bool(_) => Ok(value.to_string()),
- _ => anyhow::bail!("`env.{key}` must be a string, number, or boolean"),
- }
-}
diff --git a/crates/openhuman-core/src/hosting/tools/analytics.rs b/crates/openhuman-core/src/hosting/tools/analytics.rs
deleted file mode 100644
index 3828274f46..0000000000
--- a/crates/openhuman-core/src/hosting/tools/analytics.rs
+++ /dev/null
@@ -1,102 +0,0 @@
-//! `hosting_analytics`: reports the traffic a site served.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinyhosts::{AnalyticsDimension, AnalyticsQuery, Host};
-
-use super::required_str;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ── hosting_analytics ───────────────────────────────────────────────────────
-
-/// Reports the traffic a site served.
-pub struct AnalyticsTool {
- host: Arc<dyn Host>,
-}
-
-impl AnalyticsTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for AnalyticsTool {
- fn name(&self) -> &str {
- "hosting_analytics"
- }
-
- fn description(&self) -> &str {
- "Report how much traffic a hosted site served over the last N days — \
- visitors and page views, optionally broken down by country, path, \
- device, browser, or referrer."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["site"],
- "properties": {
- "site": { "type": "string", "description": "The site's name." },
- "days": {
- "type": "integer",
- "description": "How many days back to report. Defaults to 7."
- },
- "breakdown": {
- "type": "string",
- "enum": [
- "country", "request_path", "device_type",
- "browser_name", "os_name", "referrer_hostname", "route"
- ],
- "description": "Break the totals down by this dimension."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let site = match required_str(&args, "site") {
- Ok(site) => site,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
- let days = args
- .get("days")
- .and_then(Value::as_u64)
- .unwrap_or(7)
- .clamp(1, 365);
-
- let until_ms = chrono::Utc::now().timestamp_millis().max(0) as u64;
- let since_ms = until_ms.saturating_sub(days * 24 * 60 * 60 * 1000);
-
- let mut query = AnalyticsQuery::new(site, since_ms, until_ms);
- if let Some(dimension) = args.get("breakdown").and_then(Value::as_str) {
- let breakdown = match dimension {
- "country" => AnalyticsDimension::Country,
- "request_path" => AnalyticsDimension::RequestPath,
- "device_type" => AnalyticsDimension::DeviceType,
- "browser_name" => AnalyticsDimension::BrowserName,
- "os_name" => AnalyticsDimension::OsName,
- "referrer_hostname" => AnalyticsDimension::ReferrerHostname,
- "route" => AnalyticsDimension::Route,
- other => {
- return Ok(ToolResult::error(format!(
- "`breakdown` must be one of country, request_path, device_type, \
- browser_name, os_name, referrer_hostname, route — not `{other}`"
- )));
- }
- };
- query = query.with_breakdown(breakdown);
- }
-
- match self.host.analytics(&query).await {
- Ok(summary) => Ok(ToolResult::success(serde_json::to_string_pretty(&summary)?)),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
diff --git a/crates/openhuman-core/src/hosting/tools/deployments.rs b/crates/openhuman-core/src/hosting/tools/deployments.rs
deleted file mode 100644
index 5359053566..0000000000
--- a/crates/openhuman-core/src/hosting/tools/deployments.rs
+++ /dev/null
@@ -1,342 +0,0 @@
-//! Deployment tools: status, listing, logs, and rollback.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinyhosts::Host;
-
-use super::required_str;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ── hosting_deployment_status ───────────────────────────────────────────────
-
-/// Reads one deployment's current state.
-pub struct DeploymentStatusTool {
- host: Arc<dyn Host>,
-}
-
-impl DeploymentStatusTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for DeploymentStatusTool {
- fn name(&self) -> &str {
- "hosting_deployment_status"
- }
-
- fn description(&self) -> &str {
- "Check whether a deployment has finished building and is serving. Poll \
- this after hosting_launch_site until the status is ready, failed, or \
- canceled. A failed deployment reports the provider's build error."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["deployment_id"],
- "properties": {
- "deployment_id": {
- "type": "string",
- "description": "The id hosting_launch_site returned."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let id = match required_str(&args, "deployment_id") {
- Ok(id) => id,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
-
- match self.host.deployment(&id).await {
- Ok(deployment) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &deployment,
- )?)),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
-
-// ── hosting_list_deployments ────────────────────────────────────────────────
-
-/// Lists a site's recent deployments, newest first.
-///
-/// Mostly the other half of [`RollbackTool`]: a rollback needs a deployment id
-/// to promote, and before this tool nothing returned one except the launch that
-/// created it. An agent that wanted to go back to the deployment *before* the
-/// bad one had no way to name it.
-pub struct ListDeploymentsTool {
- host: Arc<dyn Host>,
-}
-
-impl ListDeploymentsTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for ListDeploymentsTool {
- fn name(&self) -> &str {
- "hosting_list_deployments"
- }
-
- fn description(&self) -> &str {
- "List a site's recent deployments, newest first, with their status, \
- target and creation time. Use it to find the deployment id of a known \
- good version before rolling back to it, or to see the history of what \
- has been shipped. Each entry's id is what hosting_rollback and \
- hosting_deployment_status take."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["site"],
- "properties": {
- "site": { "type": "string", "description": "The site's name." },
- "limit": {
- "type": "integer",
- "description": "How many to return. Defaults to 20."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let site = match required_str(&args, "site") {
- Ok(site) => site,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
- // Clamped to the same window as `hosting_list_sites`, for the same
- // reason: a model that asks for everything gets a page, not a bill.
- let limit = args
- .get("limit")
- .and_then(Value::as_u64)
- .unwrap_or(20)
- .clamp(1, 100) as u32;
-
- match self.host.list_deployments(&site, limit).await {
- Ok(deployments) => Ok(ToolResult::success(serde_json::to_string_pretty(
- &deployments,
- )?)),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
-
-// ── hosting_deployment_logs ─────────────────────────────
-
-/// Reads the build and runtime events a deployment recorded.
-///
-/// The other half of [`DeploymentStatusTool`]. That tool reports *that* a build
-/// failed and carries the provider's one-line error; this one is how an agent
-/// finds out *why*, which is the difference between reporting a broken deploy
-/// and fixing it.
-pub struct DeploymentLogsTool {
- host: Arc<dyn Host>,
-}
-
-impl DeploymentLogsTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for DeploymentLogsTool {
- fn name(&self) -> &str {
- "hosting_deployment_logs"
- }
-
- fn description(&self) -> &str {
- "Read a deployment's build and runtime log events, oldest first. Use it \
- after hosting_deployment_status reports a failed deployment to find the \
- error that caused it. Takes the same deployment id as \
- hosting_deployment_status."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["deployment_id"],
- "properties": {
- "deployment_id": {
- "type": "string",
- "description": "The id hosting_launch_site returned, or one \
- from hosting_list_deployments."
- },
- "limit": {
- "type": "integer",
- "description": "How many of the most recent events to return. \
- Defaults to 100."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let id = match required_str(&args, "deployment_id") {
- Ok(id) => id,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
- let limit = args.get("limit").map_or(100, |value| {
- value
- .as_i64()
- .map(|value| value.clamp(1, 1000) as usize)
- .or_else(|| value.as_u64().map(|value| value.clamp(1, 1000) as usize))
- .unwrap_or(100)
- });
-
- match self.host.deployment_logs(&id).await {
- Ok(logs) => {
- // The crate returns the whole log oldest-first and a build can
- // record thousands of lines, which is a context window rather
- // than a bill. Trimming takes the *tail*: the failure that sent
- // an agent here is at the end, and dropping the head loses
- // setup noise rather than the error.
- let trimmed = if logs.len() > limit {
- &logs[logs.len() - limit..]
- } else {
- &logs[..]
- };
-
- Ok(ToolResult::success(serde_json::to_string_pretty(&trimmed)?))
- }
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
-
-// ── hosting_rollback ────────────────────────────────────────────────────────
-
-/// Points a site's production traffic back at an earlier deployment.
-pub struct RollbackTool {
- host: Arc<dyn Host>,
-}
-
-impl RollbackTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for RollbackTool {
- fn name(&self) -> &str {
- "hosting_rollback"
- }
-
- fn description(&self) -> &str {
- "Roll a site back by pointing its production traffic at an earlier \
- deployment that already built successfully. Use it when a deploy broke \
- a live site: this is the recovery path. It does not rebuild anything — \
- the deployment being promoted was built when it was first deployed, \
- which is why it is the fast way back. Get the id from \
- hosting_list_deployments; only a deployment that finished building can \
- be promoted."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["site", "deployment_id"],
- "properties": {
- "site": {
- "type": "string",
- "description": "The site whose production traffic moves."
- },
- "deployment_id": {
- "type": "string",
- "description": "The deployment to serve, from hosting_list_deployments. \
- It must have finished building."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-
- /// Changes what the public sees on a live site, so it gates.
- fn external_effect(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let site = match required_str(&args, "site") {
- Ok(site) => site,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
- let deployment_id = match required_str(&args, "deployment_id") {
- Ok(id) => id,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
-
- // Read the deployment before promoting it. `hosting_list_deployments`
- // returns failed and still-building deployments too — they are part of
- // the history an agent is reading — so the id it picks is not
- // necessarily one that can serve traffic. Promoting a failed build
- // would take the site down in the middle of an attempt to bring it
- // back up, which is the one outcome this tool exists to prevent.
- //
- // Only the status is checked, deliberately. The site a deployment
- // belongs to is *not* reliable here: `Host::deployment` looks a
- // deployment up by id alone and falls back to an empty name when the
- // provider's response omits one, so comparing it against `site` would
- // refuse legitimate rollbacks. The provider owns that check.
- let deployment = match self.host.deployment(&deployment_id).await {
- Ok(deployment) => deployment,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
-
- if !deployment.status.is_ready() {
- return Ok(ToolResult::error(format!(
- "Deployment `{deployment_id}` is {:?}, so it cannot be promoted \
- — only a deployment that finished building can serve traffic. \
- Use hosting_list_deployments to find one that is ready.",
- deployment.status,
- )));
- }
-
- tracing::info!(
- site = %site,
- deployment = %deployment_id,
- "[hosting] rolling back"
- );
-
- match self.host.promote(&site, &deployment_id).await {
- Ok(()) => Ok(ToolResult::success(match &deployment.url {
- Some(url) => format!(
- "{site} is now serving deployment `{deployment_id}` in \
- production ({url}). The change is at the provider's edge; \
- nothing was rebuilt."
- ),
- None => format!(
- "{site} is now serving deployment `{deployment_id}` in \
- production. The change is at the provider's edge; nothing \
- was rebuilt."
- ),
- })),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
diff --git a/crates/openhuman-core/src/hosting/tools/domains.rs b/crates/openhuman-core/src/hosting/tools/domains.rs
deleted file mode 100644
index 3a97323d34..0000000000
--- a/crates/openhuman-core/src/hosting/tools/domains.rs
+++ /dev/null
@@ -1,141 +0,0 @@
-//! Domain tools: attaching a custom domain and reading its verification.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinyhosts::{Domain, Host};
-
-use super::required_str;
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ── hosting_add_domain ──────────────────────────────────────────────────────
-
-/// Attaches a custom domain to a site.
-pub struct AddDomainTool {
- host: Arc<dyn Host>,
-}
-
-impl AddDomainTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for AddDomainTool {
- fn name(&self) -> &str {
- "hosting_add_domain"
- }
-
- fn description(&self) -> &str {
- "Attach a custom domain to a site. The domain does not serve traffic \
- until its DNS records point at the provider, which the user has to do \
- at their registrar — the response says whether the provider has \
- verified it yet."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["site", "domain"],
- "properties": {
- "site": { "type": "string", "description": "The site's name." },
- "domain": { "type": "string", "description": "e.g. 'shop.example.com'." }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-
- fn external_effect(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let site = match required_str(&args, "site") {
- Ok(site) => site,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
- let domain = match required_str(&args, "domain") {
- Ok(domain) => domain,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
-
- match self.host.add_domain(&site, &domain).await {
- Ok(Domain {
- name,
- verified: true,
- ..
- }) => Ok(ToolResult::success(format!(
- "{name} is attached to {site} and verified."
- ))),
- Ok(Domain { name, .. }) => Ok(ToolResult::success(format!(
- "{name} is attached to {site} but not verified yet: its DNS \
- records still have to point at the provider."
- ))),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
-
-// ── hosting_domain_status ───────────────────────────────────────────────────
-
-/// Reports whether a site's domains are verified and serving.
-///
-/// The read half of [`AddDomainTool`]. Attaching a domain is not the end of the
-/// job: it does not serve traffic until its DNS records point at the provider,
-/// which the user has to do at their registrar, and until now nothing could
-/// answer "did that work?" without attaching it again.
-pub struct DomainStatusTool {
- host: Arc<dyn Host>,
-}
-
-impl DomainStatusTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for DomainStatusTool {
- fn name(&self) -> &str {
- "hosting_domain_status"
- }
-
- fn description(&self) -> &str {
- "List the custom domains attached to a site and whether the provider \
- has verified each one. A domain that is attached but unverified is not \
- serving traffic yet — its DNS records still have to point at the \
- provider, which the user does at their registrar. Use it to check \
- whether a domain added earlier has come up."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["site"],
- "properties": {
- "site": { "type": "string", "description": "The site's name." }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let site = match required_str(&args, "site") {
- Ok(site) => site,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
-
- match self.host.list_domains(&site).await {
- Ok(domains) => Ok(ToolResult::success(serde_json::to_string_pretty(&domains)?)),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
diff --git a/crates/openhuman-core/src/hosting/tools/launch.rs b/crates/openhuman-core/src/hosting/tools/launch.rs
deleted file mode 100644
index f881b1d9ac..0000000000
--- a/crates/openhuman-core/src/hosting/tools/launch.rs
+++ /dev/null
@@ -1,258 +0,0 @@
-//! `hosting_launch_site`: deploys a workspace directory as a live site.
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinyhosts::{Bundle, DatabaseKind, DatabaseSpec, EnvVar, Launch, LaunchPlan, SiteSpec};
-
-use super::{env_value, required_str};
-use crate::hosting::{resolve_in_workspace, Account};
-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult};
-
-/// Renders a launch as the two sentences a model needs: where it is, and what
-/// it still has to wait for.
-fn describe(launch: &Launch) -> String {
- let mut lines = vec![format!(
- "Site **{}** ({}), deployment `{}` is {:?}.",
- launch.site.name,
- if launch.created_site {
- "created"
- } else {
- "already existed"
- },
- launch.deployment.id,
- launch.deployment.status,
- )];
-
- match launch.url() {
- Some(url) => lines.push(format!(
- "It will serve from {url} once the build finishes — poll \
- `hosting_deployment_status` with the deployment id."
- )),
- None => lines.push(
- "The provider has not assigned a URL yet; poll \
- `hosting_deployment_status` with the deployment id."
- .to_string(),
- ),
- }
-
- if let Some(database) = &launch.database {
- lines.push(format!(
- "Database **{}** ({}) is {}; it injected {} into the site's \
- environment. The values are the provider's — nothing here can read them.",
- database.name,
- database.kind.as_str(),
- database.status,
- if launch.database_env_keys.is_empty() {
- "no variables".to_string()
- } else {
- launch.database_env_keys.join(", ")
- },
- ));
- }
-
- if !launch.domains.is_empty() {
- let unverified: Vec<&str> = launch
- .domains
- .iter()
- .filter(|domain| !domain.verified)
- .map(|domain| domain.name.as_str())
- .collect();
- if unverified.is_empty() {
- lines.push("Every domain is verified.".to_string());
- } else {
- lines.push(format!(
- "These domains still need their DNS records pointed at the \
- provider before they serve traffic: {}.",
- unverified.join(", ")
- ));
- }
- }
-
- lines.join("\n\n")
-}
-
-// ── hosting_launch_site ─────────────────────────────────────────────────────
-
-/// Deploys a workspace directory as a live site, with an optional database.
-pub struct LaunchSiteTool {
- account: Account,
-}
-
-impl LaunchSiteTool {
- pub fn new(account: Account) -> Self {
- Self { account }
- }
-
- /// Builds the plan an invocation describes.
- fn plan(&self, args: &Value) -> anyhow::Result<LaunchPlan> {
- let site = required_str(args, "site")?;
- let path = args
- .get("path")
- .and_then(Value::as_str)
- .unwrap_or(".")
- .to_string();
-
- let directory = resolve_in_workspace(self.account.workspace_dir(), &path)?;
- let bundle = Bundle::from_dir(&directory)?;
-
- let mut plan = LaunchPlan::new(SiteSpec::new(site), bundle);
-
- if let Some(name) = args.get("database").and_then(Value::as_str) {
- let name = name.trim();
- if !name.is_empty() {
- let kind = match args
- .get("database_kind")
- .and_then(Value::as_str)
- .unwrap_or("postgres")
- {
- "postgres" => DatabaseKind::Postgres,
- "redis" => DatabaseKind::Redis,
- "blob" => DatabaseKind::Blob,
- other => DatabaseKind::Other(other.to_string()),
- };
- plan = plan.with_database(DatabaseSpec::new(name).with_kind(kind));
- }
- }
-
- if let Some(env) = args.get("env").and_then(Value::as_object) {
- let vars = env
- .iter()
- .map(|(key, value)| Ok(EnvVar::new(key, env_value(key, value)?)))
- .collect::<anyhow::Result<Vec<_>>>()?;
- plan = plan.with_env(vars);
- }
-
- if let Some(domains) = args.get("domains").and_then(Value::as_array) {
- plan = plan.with_domains(
- domains
- .iter()
- .filter_map(Value::as_str)
- .map(str::trim)
- .filter(|domain| !domain.is_empty())
- .map(ToOwned::to_owned)
- .collect(),
- );
- }
-
- if args
- .get("production")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- {
- plan = plan.into_production();
- }
-
- Ok(plan)
- }
-}
-
-#[async_trait]
-impl Tool for LaunchSiteTool {
- fn name(&self) -> &str {
- "hosting_launch_site"
- }
-
- fn description(&self) -> &str {
- "Deploy a directory in the workspace to a real hosting provider as a \
- live website, optionally provisioning a managed database and wiring it \
- in. Creates the site if it does not exist yet, so calling it again \
- redeploys. Use for a Next.js application or a static site. The build \
- starts immediately and finishes later: poll hosting_deployment_status \
- with the returned deployment id until it is ready. Node dependencies, \
- build output and .git are never uploaded — the provider builds from \
- source."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["site"],
- "properties": {
- "site": {
- "type": "string",
- "description": "The site's name on the provider, e.g. 'acme-shop'. \
- Reused on a redeploy."
- },
- "path": {
- "type": "string",
- "description": "Directory to deploy, relative to the workspace. \
- Defaults to the workspace root."
- },
- "database": {
- "type": "string",
- "description": "Name for a managed database to provision and connect. \
- Omit if the site needs none. The connection variables \
- are injected by the provider before the build."
- },
- "database_kind": {
- "type": "string",
- "enum": ["postgres", "redis", "blob"],
- "description": "What the database speaks. Defaults to postgres."
- },
- "env": {
- "type": "object",
- "description": "Environment variables to set before the build. \
- Do not put a database connection string here; the \
- provider injects its own.",
- "additionalProperties": { "type": "string" }
- },
- "domains": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Custom domains to attach. They need DNS records \
- pointed at the provider before they serve traffic."
- },
- "production": {
- "type": "boolean",
- "description": "Deploy to production rather than to a preview URL. \
- Defaults to false."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-
- fn external_effect(&self) -> bool {
- true
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: Value,
- _options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let plan = match self.plan(&args) {
- Ok(plan) => plan,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
-
- tracing::info!(
- site = %plan.site.name,
- files = plan.bundle.len(),
- bytes = plan.bundle.total_bytes(),
- database = plan.database.is_some(),
- target = plan.target.as_str(),
- "[hosting] launching"
- );
-
- match tinyhosts::launch(self.account.host().as_ref(), &plan).await {
- Ok(launch) => Ok(ToolResult::success_with_markdown(
- serde_json::to_value(&launch)?,
- describe(&launch),
- )),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
diff --git a/crates/openhuman-core/src/hosting/tools/sites.rs b/crates/openhuman-core/src/hosting/tools/sites.rs
deleted file mode 100644
index 53c0d721a1..0000000000
--- a/crates/openhuman-core/src/hosting/tools/sites.rs
+++ /dev/null
@@ -1,164 +0,0 @@
-//! Site tools: listing sites and setting their environment variables.
-
-use std::sync::Arc;
-
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinyhosts::{DeploymentTarget, EnvVar, Host};
-
-use super::{env_value, required_str};
-use tinytools::{PermissionLevel, Tool, ToolResult};
-
-// ── hosting_list_sites ──────────────────────────────────────────────────────
-
-/// Lists the sites on the account.
-pub struct ListSitesTool {
- host: Arc<dyn Host>,
-}
-
-impl ListSitesTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for ListSitesTool {
- fn name(&self) -> &str {
- "hosting_list_sites"
- }
-
- fn description(&self) -> &str {
- "List the sites already on the hosting account, newest first. Use it to \
- find out whether a site exists before deploying, or to recover a name."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "limit": {
- "type": "integer",
- "description": "How many to return. Defaults to 20."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::ReadOnly
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let limit = args
- .get("limit")
- .and_then(Value::as_u64)
- .unwrap_or(20)
- .clamp(1, 100) as u32;
-
- match self.host.list_sites(limit).await {
- Ok(sites) => Ok(ToolResult::success(serde_json::to_string_pretty(&sites)?)),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}
-
-// ── hosting_set_env ─────────────────────────────────────────────────────────
-
-/// Sets environment variables on an existing site.
-pub struct SetEnvTool {
- host: Arc<dyn Host>,
-}
-
-impl SetEnvTool {
- pub fn new(host: Arc<dyn Host>) -> Self {
- Self { host }
- }
-}
-
-#[async_trait]
-impl Tool for SetEnvTool {
- fn name(&self) -> &str {
- "hosting_set_env"
- }
-
- fn description(&self) -> &str {
- "Set environment variables on a site, replacing any of the same name. \
- The site must be redeployed afterwards for a build-time variable to \
- take effect. Values are write-only: they can never be read back through \
- these tools."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "required": ["site", "env"],
- "properties": {
- "site": { "type": "string", "description": "The site's name." },
- "env": {
- "type": "object",
- "description": "Variables to set.",
- "additionalProperties": { "type": "string" }
- },
- "secret": {
- "type": "boolean",
- "description": "Store them write-only at the provider. Defaults to false."
- },
- "production_only": {
- "type": "boolean",
- "description": "Apply to production only rather than every environment."
- }
- }
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Write
- }
-
- fn external_effect(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let site = match required_str(&args, "site") {
- Ok(site) => site,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
- let Some(env) = args.get("env").and_then(Value::as_object) else {
- return Ok(ToolResult::error("`env` must be an object of variables"));
- };
-
- let secret = args.get("secret").and_then(Value::as_bool).unwrap_or(false);
- let targets = if args
- .get("production_only")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- {
- vec![DeploymentTarget::Production]
- } else {
- Vec::new()
- };
-
- let vars: Vec<EnvVar> = match env
- .iter()
- .map(|(key, value)| {
- let var = EnvVar::new(key, env_value(key, value)?).with_targets(targets.clone());
- Ok(if secret { var.secret() } else { var })
- })
- .collect::<anyhow::Result<Vec<_>>>()
- {
- Ok(vars) => vars,
- Err(error) => return Ok(ToolResult::error(error.to_string())),
- };
-
- let names: Vec<&str> = vars.iter().map(|var| var.key.as_str()).collect();
- match self.host.set_env(&site, &vars).await {
- Ok(()) => Ok(ToolResult::success(format!(
- "Set {} on {site}. Redeploy the site for a build-time variable to take effect.",
- names.join(", ")
- ))),
- Err(error) => Ok(ToolResult::error(error.to_string())),
- }
- }
-}