Skip to content

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

feat(tinyplace): remove agent_tools module and inline tool registration

Steven Enamakele22799262fba
diff --git a/src/openhuman/tinyplace/agent_tools/common.rs b/src/openhuman/tinyplace/agent_tools/common.rs
deleted file mode 100644
index 363866bb52..0000000000
--- a/src/openhuman/tinyplace/agent_tools/common.rs
+++ /dev/null
@@ -1,547 +0,0 @@
-//! Shared plumbing for the tiny.place agent flow tools.
-//!
-//! * [`FlowTool`] — a thin, function-pointer-backed [`Tool`] so each flow is a
-//! single free `async fn` plus a one-line registration, instead of a
-//! hand-written `impl Tool` per flow.
-//! * Argument helpers ([`req_str`], [`opt_str`], …) for pulling typed values out
-//! of the LLM's JSON arguments.
-//! * Client / signer access ([`client`], [`agent_id`]) over the process-global
-//! [`TinyPlaceState`](super::super::state::TinyPlaceState).
-//! * Result builders ([`ok_md`], [`err_md`]) and SDK-error rendering
-//! ([`sdk_error`]) so the LLM only ever sees markdown — including the
-//! fund-and-retry guidance synthesised from an x402 `402` challenge.
-
-use std::collections::HashMap;
-use std::future::Future;
-use std::pin::Pin;
-use std::sync::OnceLock;
-
-use async_trait::async_trait;
-use serde_json::{Map, Value};
-
-use crate::core::all::ControllerHandler;
-use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};
-
-use super::render::Markdown;
-use super::suggest::{append_next_steps, Suggestion};
-
-pub(super) const LOG_PREFIX: &str = "[tinyplace][flow]";
-
-// ── FlowTool ──────────────────────────────────────────────────────────────────
-
-/// Boxed future returned by a flow function.
-pub type FlowFuture = Pin<Box<dyn Future<Output = anyhow::Result<ToolResult>> + Send>>;
-
-/// A flow is a plain function from JSON args to a (markdown) tool result.
-pub type FlowFn = fn(Value) -> FlowFuture;
-
-/// Generic agent tool wrapping one flow function with its metadata.
-///
-/// Read flows (`ReadOnly`, concurrency-safe, no external effect) and write
-/// flows (`Write`, external effect → routed through the approval gate) share
-/// this type; only the permission knobs differ. Flows whose gating depends on
-/// arguments (e.g. the raw escape hatch) implement [`Tool`] directly instead.
-pub struct FlowTool {
- name: &'static str,
- description: &'static str,
- schema: Value,
- permission: PermissionLevel,
- external: bool,
- concurrency_safe: bool,
- run: FlowFn,
-}
-
-impl FlowTool {
- /// A read-only flow: no approval gate, safe to run concurrently.
- pub fn read(name: &'static str, description: &'static str, schema: Value, run: FlowFn) -> Self {
- Self {
- name,
- description,
- schema,
- permission: PermissionLevel::ReadOnly,
- external: false,
- concurrency_safe: true,
- run,
- }
- }
-
- /// A write flow: routed through the `ApprovalGate` (external effect) and
- /// never run concurrently with itself.
- pub fn write(
- name: &'static str,
- description: &'static str,
- schema: Value,
- run: FlowFn,
- ) -> Self {
- Self {
- name,
- description,
- schema,
- permission: PermissionLevel::Write,
- external: true,
- concurrency_safe: false,
- run,
- }
- }
-
- pub fn boxed(self) -> Box<dyn Tool> {
- Box::new(self)
- }
-}
-
-#[async_trait]
-impl Tool for FlowTool {
- fn name(&self) -> &str {
- self.name
- }
-
- fn description(&self) -> &str {
- self.description
- }
-
- fn parameters_schema(&self) -> Value {
- self.schema.clone()
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let args = match args {
- Value::Null => Value::Object(Default::default()),
- other => other,
- };
- log::debug!("{LOG_PREFIX} {} start", self.name);
- let result = (self.run)(args).await;
- match &result {
- Ok(r) if r.is_error => log::warn!("{LOG_PREFIX} {} returned error result", self.name),
- Ok(_) => log::debug!("{LOG_PREFIX} {} ok", self.name),
- Err(e) => log::warn!("{LOG_PREFIX} {} failed: {e}", self.name),
- }
- result
- }
-
- fn permission_level(&self) -> PermissionLevel {
- self.permission
- }
-
- fn external_effect(&self) -> bool {
- self.external
- }
-
- fn is_concurrency_safe(&self, _args: &Value) -> bool {
- self.concurrency_safe
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- fn max_result_size_chars(&self) -> Option<usize> {
- Some(48 * 1024)
- }
-}
-
-// ── Argument helpers ────────────────────────────────────────────────────────
-
-/// Required, non-empty string argument.
-pub fn req_str(args: &Value, key: &str) -> anyhow::Result<String> {
- opt_str(args, key).ok_or_else(|| anyhow::anyhow!("missing required parameter '{key}'"))
-}
-
-/// Optional, trimmed, non-empty string argument.
-pub fn opt_str(args: &Value, key: &str) -> Option<String> {
- args.get(key)
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
-}
-
-/// Optional integer argument (accepts JSON numbers and numeric strings).
-pub fn opt_i64(args: &Value, key: &str) -> Option<i64> {
- let v = args.get(key)?;
- v.as_i64()
- .or_else(|| v.as_str().and_then(|s| s.trim().parse().ok()))
-}
-
-/// Optional boolean argument (accepts JSON bools and `"true"`/`"false"`).
-pub fn opt_bool(args: &Value, key: &str) -> Option<bool> {
- let v = args.get(key)?;
- v.as_bool()
- .or_else(|| match v.as_str()?.trim().to_ascii_lowercase().as_str() {
- "true" => Some(true),
- "false" => Some(false),
- _ => None,
- })
-}
-
-/// Optional list-of-strings argument. Accepts a JSON array of strings or a
-/// single comma-separated string. Returns `None` when absent/empty.
-pub fn opt_str_list(args: &Value, key: &str) -> Option<Vec<String>> {
- match args.get(key)? {
- Value::Array(items) => {
- let list: Vec<String> = items
- .iter()
- .filter_map(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .collect();
- (!list.is_empty()).then_some(list)
- }
- Value::String(s) => {
- let list: Vec<String> = s
- .split(',')
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .collect();
- (!list.is_empty()).then_some(list)
- }
- _ => None,
- }
-}
-
-// ── Client / signer access ──────────────────────────────────────────────────
-
-/// Process-global tiny.place client, built lazily from the wallet signer.
-pub async fn client() -> anyhow::Result<&'static tinyplace::TinyPlaceClient> {
- super::super::ops::global_state()
- .client()
- .await
- .map_err(|e| anyhow::anyhow!("tiny.place client unavailable: {e}"))
-}
-
-/// The caller's own agent id, resolved from the wallet signer.
-///
-/// Identity is **always** taken from the signer, never from tool arguments —
-/// the agent cannot act as anyone but itself (anti-spoof).
-pub fn agent_id(client: &tinyplace::TinyPlaceClient) -> anyhow::Result<String> {
- client
- .http()
- .signer()
- .map(|s| s.agent_id())
- .ok_or_else(|| anyhow::anyhow!("tiny.place signer unavailable; unlock your wallet"))
-}
-
-/// The caller's own base64 public (encryption) key, from the wallet signer.
-pub fn public_key(client: &tinyplace::TinyPlaceClient) -> anyhow::Result<String> {
- client
- .http()
- .signer()
- .map(|s| s.public_key_base64())
- .ok_or_else(|| anyhow::anyhow!("tiny.place signer unavailable; unlock your wallet"))
-}
-
-/// Resolve a `@handle` (or bare handle) to its wallet cryptoId, falling back to
-/// the input unchanged when it is already an id or can't be resolved. Used by
-/// the follow/unfollow flows so the agent can pass a friendly handle.
-pub async fn resolve_agent(client: &tinyplace::TinyPlaceClient, target: &str) -> String {
- let name = target.trim().trim_start_matches('@');
- if name.is_empty() {
- return target.trim().to_string();
- }
- match client.directory.resolve(name).await {
- Ok(resolved) => resolved
- .identity
- .map(|i| i.crypto_id)
- .filter(|id| !id.is_empty())
- .or_else(|| resolved.agent.map(|a| a.agent_id))
- .filter(|id| !id.is_empty())
- .unwrap_or_else(|| target.trim().to_string()),
- Err(_) => target.trim().to_string(),
- }
-}
-
-// ── Result builders ─────────────────────────────────────────────────────────
-
-fn md_result(markdown: String, is_error: bool) -> ToolResult {
- let base = if is_error {
- ToolResult::error(markdown.clone())
- } else {
- ToolResult::success(markdown.clone())
- };
- // Populate `markdown_formatted` too so the loop's markdown path is
- // consistent; the primary content is already markdown so the LLM sees it
- // regardless of whether `prefer_markdown` is set.
- base.with_markdown(markdown)
-}
-
-/// A successful flow result whose body is markdown.
-pub fn ok_md(markdown: String) -> ToolResult {
- md_result(markdown, false)
-}
-
-/// A failed flow result whose body is markdown (the LLM still sees the text).
-pub fn err_md(markdown: String) -> ToolResult {
- md_result(markdown, true)
-}
-
-/// Build a markdown document then optionally append a `## Next steps` block.
-pub fn finish(mut md: Markdown, suggestions: &[Suggestion]) -> anyhow::Result<ToolResult> {
- append_next_steps(&mut md, suggestions);
- Ok(ok_md(md.build()))
-}
-
-/// Recursively collect every string value stored under `key` anywhere in a JSON
-/// tree, de-duplicated in first-seen order. Used to harvest ids (e.g. `postId`,
-/// `bountyId`) from a serialised SDK result so flows can pre-fill follow-up
-/// suggestions.
-pub fn collect_field(value: &Value, key: &str) -> Vec<String> {
- let mut out = Vec::new();
- collect_into(value, key, &mut out);
- out
-}
-
-fn collect_into(value: &Value, key: &str, out: &mut Vec<String>) {
- match value {
- Value::Object(map) => {
- for (k, v) in map {
- if k == key {
- if let Some(s) = v.as_str() {
- let s = s.to_string();
- if !s.is_empty() && !out.contains(&s) {
- out.push(s);
- }
- }
- }
- collect_into(v, key, out);
- }
- }
- Value::Array(items) => {
- for item in items {
- collect_into(item, key, out);
- }
- }
- _ => {}
- }
-}
-
-/// Render an SDK error as a markdown **string** the agent can act on.
-///
-/// An x402 `402` becomes a **Payment required** section with fund-and-retry
-/// guidance (mirroring the CLI's `status: payment-required`); any other error
-/// is surfaced through [`map_err`](super::super::ops::map_err) which carries
-/// the backend's reason string.
-pub fn sdk_error_text(action: &str, err: tinyplace::Error) -> String {
- if let Some(challenge) = err.payment_required() {
- let p = &challenge.payment;
- let mut md = Markdown::new();
- md.heading("Payment required");
- md.paragraph(format!(
- "{action} needs an on-chain payment before it can complete. Fund your \
- wallet with the asset below, then retry the same call."
- ));
- let pairs: Vec<(&str, String)> = [
- ("Asset", p.asset.clone()),
- ("Amount", p.amount.clone()),
- ("Network", p.network.clone()),
- ("Pay to", p.to.clone()),
- ]
- .into_iter()
- .filter_map(|(k, v)| v.filter(|s| !s.is_empty()).map(|v| (k, v)))
- .collect();
- md.kv(pairs);
- append_next_steps(
- &mut md,
- &[Suggestion::new(
- "Check your wallet balance, then retry once funded",
- "tinyplace_status",
- Value::Object(Default::default()),
- )],
- );
- return md.build();
- }
-
- let reason = super::super::ops::map_err(err);
- let mut md = Markdown::new();
- md.heading("Could not complete");
- md.paragraph(format!("{action} failed."));
- md.kv([("Reason", reason)]);
- md.build()
-}
-
-/// As [`sdk_error_text`], wrapped into a (failed) [`ToolResult`].
-pub fn sdk_error(action: &str, err: tinyplace::Error) -> ToolResult {
- err_md(sdk_error_text(action, err))
-}
-
-/// Convenience: turn an SDK `Result` into `anyhow::Result<Value>`, rendering
-/// the error as markdown carried in the `anyhow` message (the FlowTool surfaces
-/// it to the LLM verbatim).
-///
-/// Serialization errors are **propagated**, not hidden: a response that fails to
-/// deserialize is a real bug worth surfacing. Callers hitting endpoints that
-/// return `null` for an *empty* collection should use [`list_or_empty`] instead,
-/// which degrades only that specific case.
-pub fn val_or_err<T: serde::Serialize>(
- action: &str,
- result: tinyplace::Result<T>,
-) -> anyhow::Result<Value> {
- match result {
- Ok(v) => serde_json::to_value(v)
- .map_err(|e| anyhow::anyhow!("failed to serialize {action} response: {e}")),
- Err(e) => Err(anyhow::anyhow!("{}", sdk_error_text(action, e))),
- }
-}
-
-/// Like [`val_or_err`], but for the narrow set of SDK calls whose backend
-/// returns `null` for an empty collection (`{"messages": null}`, empty
-/// submissions) — which the typed SDK surfaces as a `Serialization` error.
-/// Degrades **only** that case to an empty array; every other error, including a
-/// genuine shape mismatch, is still surfaced. Mirrors the `*_degrade` handling
-/// in the internal controllers, scoped to the endpoints that actually need it.
-pub fn list_or_empty<T: serde::Serialize>(
- action: &str,
- result: tinyplace::Result<T>,
-) -> anyhow::Result<Value> {
- match result {
- Ok(v) => serde_json::to_value(v)
- .map_err(|e| anyhow::anyhow!("failed to serialize {action} response: {e}")),
- Err(e) if is_empty_state(&e) => Ok(Value::Array(Vec::new())),
- Err(e) => Err(anyhow::anyhow!("{}", sdk_error_text(action, e))),
- }
-}
-
-/// Whether an SDK error is really just an empty backend collection that failed
-/// to deserialize (e.g. a `null` array). Used only by [`list_or_empty`] and the
-/// message flows, which hit endpoints known to return `null` when empty.
-pub fn is_empty_state(err: &tinyplace::Error) -> bool {
- matches!(err, tinyplace::Error::Serialization(_))
-}
-
-/// Parse an optional `limit`, clamping to `default` when absent, non-numeric, or
-/// `<= 0` so a bad value can't reach the SDK/GraphQL layer.
-pub fn positive_limit(args: &Value, key: &str, default: i64) -> i64 {
- match opt_i64(args, key) {
- Some(v) if v > 0 => v,
- _ => default,
- }
-}
-
-// ── Controller delegation ────────────────────────────────────────────────────
-
-/// Process-global map of tiny.place controller handlers keyed by bare function
-/// name (e.g. `registry_register`). Built once from the registered controllers.
-fn controller_handlers() -> &'static HashMap<&'static str, ControllerHandler> {
- static MAP: OnceLock<HashMap<&'static str, ControllerHandler>> = OnceLock::new();
- MAP.get_or_init(|| {
- crate::openhuman::tinyplace::all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c| (c.schema.function, c.handler))
- .collect()
- })
-}
-
-/// Invoke an internal tiny.place controller by name. Flows use this when the
-/// controller does essential work the raw SDK call does not — e.g.
-/// `registry_register` performs the x402 payment retry and publishes the
-/// directory Agent Card, neither of which `client.registry.register` does.
-pub async fn call_controller(function: &str, params: Map<String, Value>) -> Result<Value, String> {
- let param_keys: Vec<&str> = params.keys().map(String::as_str).collect();
- log::debug!("{LOG_PREFIX} controller_call start function={function} param_keys={param_keys:?}");
- let handler = controller_handlers().get(function).ok_or_else(|| {
- log::warn!("{LOG_PREFIX} controller_call unknown function={function}");
- format!("unknown tiny.place controller '{function}'")
- })?;
- let result = handler(params).await;
- match &result {
- Ok(_) => log::debug!("{LOG_PREFIX} controller_call ok function={function}"),
- Err(e) => log::warn!("{LOG_PREFIX} controller_call failed function={function} err={e}"),
- }
- result
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- #[test]
- fn req_str_trims_and_rejects_blank() {
- let args = json!({ "a": " hi ", "b": " " });
- assert_eq!(req_str(&args, "a").unwrap(), "hi");
- assert!(req_str(&args, "b").is_err());
- assert!(req_str(&args, "missing").is_err());
- }
-
- #[test]
- fn opt_i64_accepts_number_or_string() {
- assert_eq!(opt_i64(&json!({ "n": 5 }), "n"), Some(5));
- assert_eq!(opt_i64(&json!({ "n": "7" }), "n"), Some(7));
- assert_eq!(opt_i64(&json!({ "n": "x" }), "n"), None);
- assert_eq!(opt_i64(&json!({}), "n"), None);
- }
-
- #[test]
- fn opt_bool_accepts_bool_or_string() {
- assert_eq!(opt_bool(&json!({ "b": true }), "b"), Some(true));
- assert_eq!(opt_bool(&json!({ "b": "False" }), "b"), Some(false));
- assert_eq!(opt_bool(&json!({ "b": "nope" }), "b"), None);
- }
-
- #[test]
- fn opt_str_list_accepts_array_or_csv() {
- assert_eq!(
- opt_str_list(&json!({ "t": ["a", " b ", ""] }), "t"),
- Some(vec!["a".to_string(), "b".to_string()])
- );
- assert_eq!(
- opt_str_list(&json!({ "t": "a, b ,c" }), "t"),
- Some(vec!["a".to_string(), "b".to_string(), "c".to_string()])
- );
- assert_eq!(opt_str_list(&json!({ "t": [] }), "t"), None);
- }
-
- #[test]
- fn empty_state_degrades_only_serialization_errors() {
- let serde_err = serde_json::from_str::<i32>("not a number").unwrap_err();
- assert!(is_empty_state(&tinyplace::Error::Serialization(serde_err)));
- assert!(!is_empty_state(&tinyplace::Error::InvalidArgument(
- "x".to_string()
- )));
- }
-
- #[test]
- fn val_or_err_propagates_serialization_errors() {
- // val_or_err no longer hides serialization failures.
- let serde_err = serde_json::from_str::<i32>("not a number").unwrap_err();
- let surfaced = val_or_err::<i32>("Read", Err(tinyplace::Error::Serialization(serde_err)));
- assert!(surfaced.is_err());
-
- let ok = val_or_err::<i32>("Read", Ok(7)).unwrap();
- assert_eq!(ok, serde_json::json!(7));
- }
-
- #[test]
- fn list_or_empty_degrades_only_empty_collections() {
- // Null collection (serialization error) → empty array.
- let serde_err = serde_json::from_str::<i32>("not a number").unwrap_err();
- let degraded =
- list_or_empty::<i32>("List", Err(tinyplace::Error::Serialization(serde_err))).unwrap();
- assert_eq!(degraded, Value::Array(Vec::new()));
-
- // A genuine non-serialization error is still surfaced.
- let surfaced = list_or_empty::<i32>(
- "List",
- Err(tinyplace::Error::InvalidArgument("nope".into())),
- );
- assert!(surfaced.is_err());
- }
-
- #[test]
- fn positive_limit_clamps_non_positive() {
- assert_eq!(positive_limit(&json!({ "limit": 5 }), "limit", 10), 5);
- assert_eq!(positive_limit(&json!({ "limit": 0 }), "limit", 10), 10);
- assert_eq!(positive_limit(&json!({ "limit": -3 }), "limit", 10), 10);
- assert_eq!(positive_limit(&json!({}), "limit", 10), 10);
- }
-
- #[test]
- fn ok_md_and_err_md_carry_markdown() {
- let ok = ok_md("**hi**".to_string());
- assert!(!ok.is_error);
- assert_eq!(ok.markdown_formatted.as_deref(), Some("**hi**"));
- let err = err_md("**bad**".to_string());
- assert!(err.is_error);
- assert_eq!(err.markdown_formatted.as_deref(), Some("**bad**"));
- }
-}
diff --git a/src/openhuman/tinyplace/agent_tools/flows_read.rs b/src/openhuman/tinyplace/agent_tools/flows_read.rs
deleted file mode 100644
index 7ff7672965..0000000000
--- a/src/openhuman/tinyplace/agent_tools/flows_read.rs
+++ /dev/null
@@ -1,394 +0,0 @@
-//! Read-only tiny.place flows: whoami, status, discover, search, feed,
-//! find_work, messages. Each calls the SDK directly, serialises the typed
-//! result, and renders agent-friendly markdown with `Next steps` suggestions.
-
-use serde_json::{json, Value};
-
-use tinyplace::api::inbox::InboxQueryParams;
-use tinyplace::types::BountyQueryParams;
-
-use crate::openhuman::tools::traits::Tool;
-
-use super::common::{
- agent_id, client, collect_field, finish, ok_md, positive_limit, public_key, req_str,
- val_or_err, FlowFuture, FlowTool,
-};
-use super::render::{render_json, Markdown};
-use super::suggest::Suggestion;
-
-pub fn read_tools() -> Vec<Box<dyn Tool>> {
- vec![
- FlowTool::read(
- "tinyplace_whoami",
- "Show your tiny.place identity: agentId (cryptoId), public key, and any \
- @handles you hold. Use to confirm who you are acting as.",
- json!({ "type": "object", "additionalProperties": false, "properties": {} }),
- whoami_flow,
- )
- .boxed(),
- FlowTool::read(
- "tinyplace_status",
- "Recurring check-in snapshot: unread inbox counts, pending messages, the \
- bounties you created, and a triage of what needs you now. Run this on a \
- schedule as your steady-state loop.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": { "limit": { "type": "integer", "minimum": 1, "description": "Max items per section (default 10)." } }
- }),
- status_flow,
- )
- .boxed(),
- FlowTool::read(
- "tinyplace_discover",
- "Find where to participate: agents, groups, and feeds matching a query. \
- Pass `q` to search, or omit for what's trending.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "q": { "type": "string", "description": "Free-text query." },
- "limit": { "type": "integer", "minimum": 1, "description": "Max results (default 10)." }
- }
- }),
- discover_flow,
- )
- .boxed(),
- FlowTool::read(
- "tinyplace_search",
- "Search the tiny.place directory for agents/groups by skill, tag, or name.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": { "q": { "type": "string", "description": "Search query." } },
- "required": ["q"]
- }),
- search_flow,
- )
- .boxed(),
- FlowTool::read(
- "tinyplace_feed",
- "Scroll your ranked home feed (batched GraphQL — one request hydrates \
- each post's author). Each post comes with an engage suggestion.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "limit": { "type": "integer", "minimum": 1, "description": "Max posts (default 15)." },
- "include_self": { "type": "boolean", "description": "Include your own posts." }
- }
- }),
- feed_flow,
- )
- .boxed(),
- FlowTool::read(
- "tinyplace_find_work",
- "Browse open bounties you could win, each with a ready-to-run submit \
- suggestion. Bounties are contest-style paid work; submitting is free.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": { "limit": { "type": "integer", "minimum": 1, "description": "Max bounties (default 10)." } }
- }),
- find_work_flow,
- )
- .boxed(),
- FlowTool::read(
- "tinyplace_messages",
- "Read your pending end-to-end-encrypted messages and inbox items. To send \
- or reply, use tinyplace_call (signal_send_message / messages_acknowledge).",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": { "limit": { "type": "integer", "minimum": 1, "description": "Max items (default 20)." } }
- }),
- messages_flow,
- )
- .boxed(),
- ]
-}
-
-fn whoami_flow(_args: Value) -> FlowFuture {
- Box::pin(async move {
- let client = client().await?;
- let me = agent_id(client)?;
- log::debug!("[tinyplace][flow] whoami start");
- let pubkey = public_key(client)?;
- let mut md = Markdown::new();
- md.heading("Your tiny.place identity");
- let mut pairs = vec![("Agent id (cryptoId)", me.clone()), ("Public key", pubkey)];
- // Reverse-resolve any @handles this wallet holds.
- if let Ok(reverse) = client.directory.reverse(&me).await {
- let handles: Vec<String> = reverse
- .identities
- .iter()
- .filter(|i| !i.username.is_empty())
- .map(|i| {
- if i.primary.unwrap_or(false) {
- format!("@{} (primary)", i.username)
- } else {
- format!("@{}", i.username)
- }
- })
- .collect();
- if !handles.is_empty() {
- pairs.push(("Handles", handles.join(", ")));
- }
- }
- md.kv(pairs);
- let suggestions = vec![
- Suggestion::new("Snapshot your loop state", "tinyplace_status", json!({})),
- Suggestion::new(
- "Claim a @handle if you have none",
- "tinyplace_register",
- json!({}),
- ),
- ];
- finish(md, &suggestions)
- })
-}
-
-fn status_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let limit = positive_limit(&args, "limit", 10);
- log::debug!("[tinyplace][flow] status start limit={limit}");
- let client = client().await?;
- let me = agent_id(client)?;
-
- let mut md = Markdown::new();
- md.heading("tiny.place status");
-
- // Inbox counts.
- match client.inbox.counts(None).await {
- Ok(counts) => {
- let v = serde_json::to_value(counts).unwrap_or(Value::Null);
- md.subheading("Inbox");
- md.raw_section(render_json(&v));
- }
- Err(e) => {
- md.kv([("Inbox", super::common::sdk_error_text("Inbox counts", e))]);
- }
- }
-
- // Pending messages. An empty inbox deserialises as a serialization
- // error (`{"messages": null}`) — degrade it to a clean "none" rather
- // than silently dropping the section.
- md.subheading("Pending messages");
- match client.messages.list(&me, Some(limit)).await {
- Ok(messages) => {
- let v = serde_json::to_value(&messages).unwrap_or(Value::Null);
- md.raw_section(render_json(&v));
- }
- Err(e) if super::common::is_empty_state(&e) => {
- md.paragraph("_(none)_");
- }
- Err(_) => {
- md.paragraph("_(unavailable this tick)_");
- }
- }
-
- // Bounties you created.
- let params = BountyQueryParams {
- creator: Some(me.clone()),
- limit: Some(limit),
- ..Default::default()
- };
- if let Ok(bounties) = client.bounties.list(Some(&params)).await {
- let v = serde_json::to_value(&bounties).unwrap_or(Value::Null);
- md.subheading("Your bounties");
- md.raw_section(render_json(&v));
- }
-
- let suggestions = vec![
- Suggestion::new("Read your messages", "tinyplace_messages", json!({})),
- Suggestion::new("Scroll your feed and engage", "tinyplace_feed", json!({})),
- Suggestion::new("Find work to win", "tinyplace_find_work", json!({})),
- ];
- finish(md, &suggestions)
- })
-}
-
-fn discover_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let client = client().await?;
- let limit = positive_limit(&args, "limit", 10);
- log::debug!(
- "[tinyplace][flow] discover start limit={limit} has_q={}",
- args.get("q").is_some()
- );
- let value = match super::common::opt_str(&args, "q") {
- Some(q) => val_or_err("Discover", client.search.unified(&q).await)?,
- None => val_or_err(
- "Discover trending",
- client.search.trending(Some(limit)).await,
- )?,
- };
- let mut md = Markdown::new();
- md.heading("Discover");
- md.raw_section(render_json(&value));
- finish(
- md,
- &[Suggestion::new(
- "Join a group you found",
- "tinyplace_join_group",
- json!({ "group_id": "<groupId>" }),
- )],
- )
- })
-}
-
-fn search_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let q = req_str(&args, "q")?;
- log::debug!("[tinyplace][flow] search start q={q}");
- let client = client().await?;
- let value = val_or_err("Search", client.search.unified(&q).await)?;
- let mut md = Markdown::new();
- md.heading(format!("Search · {q}"));
- md.raw_section(render_json(&value));
- finish(
- md,
- &[Suggestion::new(
- "Follow an agent you found",
- "tinyplace_follow",
- json!({ "target": "<@handle or agentId>" }),
- )],
- )
- })
-}
-
-fn feed_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let client = client().await?;
- let limit = positive_limit(&args, "limit", 15);
- log::debug!("[tinyplace][flow] feed start limit={limit}");
- let include_self = super::common::opt_bool(&args, "include_self");
- let value = val_or_err(
- "Read feed",
- client
- .graphql
- .home_feed(Some(limit), None, include_self)
- .await,
- )?;
- let mut md = Markdown::new();
- md.heading("Your home feed");
- md.raw_section(render_json(&value));
-
- // Suggest engaging with the first few posts via the raw escape hatch.
- // `feeds_like_post` needs BOTH the author handle and the postId, so pull
- // the pair from each hydrated home-feed item rather than postId alone.
- let mut suggestions = Vec::new();
- if let Some(items) = value.get("items").and_then(Value::as_array) {
- for item in items.iter().take(3) {
- let post = item.get("post").unwrap_or(item);
- let post_id = post.get("postId").and_then(Value::as_str);
- let handle = post
- .get("author")
- .and_then(|a| a.get("handle"))
- .and_then(Value::as_str);
- if let (Some(post_id), Some(handle)) = (post_id, handle) {
- suggestions.push(Suggestion::new(
- format!("Like post {post_id}"),
- "tinyplace_call",
- json!({ "command": "feeds_like_post", "params": { "handle": handle, "postId": post_id } }),
- ));
- }
- }
- }
- finish(md, &suggestions)
- })
-}
-
-fn find_work_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let client = client().await?;
- let limit = positive_limit(&args, "limit", 10);
- log::debug!("[tinyplace][flow] find_work start limit={limit}");
- let params = tinyplace::api::graphql::BountyGraphQLParams {
- status: Some("open".to_string()),
- creator: None,
- limit: Some(limit),
- offset: None,
- };
- let value = val_or_err("Find work", client.graphql.bounties(Some(&params)).await)?;
- let mut md = Markdown::new();
- md.heading("Open bounties");
- md.raw_section(render_json(&value));
-
- let mut suggestions = Vec::new();
- for bounty_id in collect_field(&value, "bountyId").into_iter().take(5) {
- suggestions.push(Suggestion::new(
- format!("Submit work to bounty {bounty_id}"),
- "tinyplace_submit_work",
- json!({ "bounty_id": bounty_id, "url": "<your work URL>" }),
- ));
- }
- if suggestions.is_empty() {
- return Ok(ok_md(md.build()));
- }
- finish(md, &suggestions)
- })
-}
-
-fn messages_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let client = client().await?;
- let limit = positive_limit(&args, "limit", 20);
- log::debug!("[tinyplace][flow] messages start limit={limit}");
- let me = agent_id(client)?;
-
- let mut md = Markdown::new();
- md.heading("Messages & inbox");
-
- md.subheading("Pending messages (E2E encrypted)");
- match client.messages.list(&me, Some(limit)).await {
- Ok(messages) => {
- let v = serde_json::to_value(&messages).unwrap_or(Value::Null);
- md.raw_section(render_json(&v));
- }
- // Empty inbox deserialises as a serialization error — degrade to none.
- Err(e) if super::common::is_empty_state(&e) => {
- md.paragraph("No pending messages.");
- }
- Err(e) => {
- md.kv([(
- "Messages",
- super::common::sdk_error_text("List messages", e),
- )]);
- }
- }
-
- // Honour `limit` on the inbox read too (not just pending messages), and
- // degrade an empty inbox (`{"items": null}` serialization error) to a
- // clean "empty" instead of dropping the section.
- let inbox_params = InboxQueryParams {
- limit: Some(limit),
- ..Default::default()
- };
- md.subheading("Inbox");
- match client.inbox.list(Some(&inbox_params), None).await {
- Ok(inbox) => {
- let v = serde_json::to_value(&inbox).unwrap_or(Value::Null);
- md.raw_section(render_json(&v));
- }
- Err(e) if super::common::is_empty_state(&e) => {
- md.paragraph("Empty inbox.");
- }
- Err(_) => {
- md.paragraph("_(unavailable this tick)_");
- }
- }
-
- let mut suggestions = vec![Suggestion::new(
- "Acknowledge a handled message so re-runs don't re-process it",
- "tinyplace_call",
- json!({ "command": "messages_acknowledge", "params": { "messageId": "<id>" } }),
- )];
- suggestions.push(Suggestion::new(
- "Reply to a sender (Signal-encrypted)",
- "tinyplace_call",
- json!({ "command": "signal_send_message", "params": { "recipient": "<agentId>", "plaintext": "<text>" } }),
- ));
- finish(md, &suggestions)
- })
-}
diff --git a/src/openhuman/tinyplace/agent_tools/flows_write.rs b/src/openhuman/tinyplace/agent_tools/flows_write.rs
deleted file mode 100644
index e1692269ef..0000000000
--- a/src/openhuman/tinyplace/agent_tools/flows_write.rs
+++ /dev/null
@@ -1,664 +0,0 @@
-//! Write tiny.place flows: register, follow/unfollow, join/create group,
-//! post_bounty, submit_work, post, submissions, job_apply.
-//!
-//! All declare `Write` + external effect, so the agent harness routes them
-//! through the `ApprovalGate`. Identity is always taken from the wallet signer
-//! (never an argument) — the agent can only ever act as itself. Paid actions
-//! (register, post_bounty) surface an x402 `402` as a **Payment required**
-//! fund-and-retry block rather than failing opaquely.
-
-use serde_json::{json, Value};
-
-use tinyplace::types::{
- BountySubmissionCreateRequest, BountySubmissionQueryParams, GroupCreateRequest,
- ProposalCreateRequest,
-};
-
-use crate::openhuman::tools::traits::{Tool, ToolResult};
-
-use super::common::{
- agent_id, call_controller, client, collect_field, err_md, finish, list_or_empty, ok_md,
- opt_bool, opt_str, opt_str_list, positive_limit, req_str, resolve_agent, sdk_error, FlowFuture,
- FlowTool,
-};
-use super::render::{render_json, Markdown};
-use super::suggest::Suggestion;
-
-pub fn write_tools() -> Vec<Box<dyn Tool>> {
- vec![
- FlowTool::write(
- "tinyplace_register",
- "Claim a @handle on tiny.place. Free handles register immediately and \
- publish your discoverable Agent Card. Paid handles preview the on-chain \
- fee first; pass confirm=true to settle the payment from your wallet and \
- claim. Your cryptoId/public key are taken from your wallet automatically.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "handle": { "type": "string", "description": "The @handle to claim (without the @)." },
- "confirm": { "type": "boolean", "description": "Set true to settle the on-chain fee and claim a paid handle (default false = preview the fee)." }
- },
- "required": ["handle"]
- }),
- register_flow,
- )
- .boxed(),
- FlowTool::write(
- "tinyplace_follow",
- "Follow an agent (by @handle or agentId) so their posts reach your home feed.",
- target_schema("Agent to follow (@handle or agentId)."),
- follow_flow,
- )
- .boxed(),
- FlowTool::write(
- "tinyplace_unfollow",
- "Stop following an agent (by @handle or agentId).",
- target_schema("Agent to unfollow (@handle or agentId)."),
- unfollow_flow,
- )
- .boxed(),
- FlowTool::write(
- "tinyplace_join_group",
- "Join a group by id. Open groups admit you immediately; others queue for \
- approval.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": { "group_id": { "type": "string", "description": "The group id to join." } },
- "required": ["group_id"]
- }),
- join_group_flow,
- )
- .boxed(),
- FlowTool::write(
- "tinyplace_create_group",
- "Create a group you own. Defaults to an open (publicly discoverable) policy.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "name": { "type": "string", "description": "Group name." },
- "description": { "type": "string", "description": "Optional description." },
- "policy": { "type": "string", "description": "Membership policy: open | approval | invite-only." },
- "tags": { "type": "array", "items": { "type": "string" }, "description": "Optional tags." }
- },
- "required": ["name"]
- }),
- create_group_flow,
- )
- .boxed(),
- FlowTool::write(
- "tinyplace_post_bounty",
- "Create + fund a bounty (contest-style paid work). The reward is escrowed \
- at creation via x402 (SPL only — USDC/CASH). If unfunded it returns a \
- Payment required block; fund, then retry.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "title": { "type": "string", "description": "Bounty title." },
- "description": { "type": "string", "description": "What the work is (required)." },
- "amount": { "type": "string", "description": "Reward amount, e.g. '10'." },
- "asset": { "type": "string", "description": "Reward asset: USDC or CASH (default USDC)." },
- "days": { "type": "integer", "minimum": 1, "description": "Days until the deadline (ignored if deadline is set)." },
- "deadline": { "type": "string", "description": "RFC3339 deadline (takes precedence over days)." },
- "confirm": { "type": "boolean", "description": "Set true to escrow the reward on-chain and open the bounty (default false = preview the fee)." }
- },
- "required": ["title", "amount", "description"]
- }),
- post_bounty_flow,
- )
- .boxed(),
- FlowTool::write(
- "tinyplace_submit_work",
- "Submit your work (a URL) to a bounty. Submitting is free. The submitter \
- is your own identity.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "bounty_id": { "type": "string", "description": "The bounty id." },
- "url": { "type": "string", "description": "URL of your work." },
- "title": { "type": "string", "description": "Optional submission title." },
- "note": { "type": "string", "description": "Optional note to the judges." }
- },
- "required": ["bounty_id", "url"]
- }),
- submit_work_flow,
- )
- .boxed(),
- FlowTool::write(
- "tinyplace_post",
- "Publish a post to your own tiny.place feed and get back a shareable \
- URL. Use this to host a bounty deliverable: post your finished work, \
- then submit the returned URL with tinyplace_submit_work. Posting is \
- free and goes to your own feed (no @handle required).",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "body": { "type": "string", "description": "The post content — your work / deliverable. Markdown is fine." },
- "content_type": { "type": "string", "description": "Optional content-type hint, e.g. 'text/markdown'." },
- "bounty_id": { "type": "string", "description": "Optional: the bounty this deliverable is for — pre-fills the submit suggestion with this URL." }
- },
- "required": ["body"]
- }),
- post_flow,
- )
- .boxed(),
- // A read (list_submissions) — registered as a read flow so it isn't
- // approval-gated; the suggested `bounties_run_council` action is gated
- // on its own through `tinyplace_call`.
- FlowTool::read(
- "tinyplace_submissions",
- "Review the submissions on a bounty you created, with a council command to \
- trigger judging.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "bounty_id": { "type": "string", "description": "The bounty id." },
- "limit": { "type": "integer", "minimum": 1, "description": "Max submissions (default 20)." }
- },
- "required": ["bounty_id"]
- }),
- submissions_flow,
- )
- .boxed(),
- FlowTool::write(
- "tinyplace_job_apply",
- "Submit a proposal (apply) to an open tiny.place job. Free. Your candidate \
- identity is taken from your wallet — it cannot be supplied as an argument.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "job_id": { "type": "string", "description": "The job id to apply for." },
- "cover_letter": { "type": "string", "description": "Cover letter." },
- "bid_amount": { "type": "string", "description": "Bid, e.g. '450 USDC'." },
- "estimated_delivery": { "type": "string", "description": "e.g. '2 weeks'." },
- "past_work": { "type": "array", "items": { "type": "string" }, "description": "Past work URLs." }
- },
- "required": ["job_id"]
- }),
- job_apply_flow,
- )
- .boxed(),
- ]
-}
-
-fn target_schema(desc: &str) -> Value {
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": { "target": { "type": "string", "description": desc } },
- "required": ["target"]
- })
-}
-
-fn register_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let handle = req_str(&args, "handle")?;
- let handle = handle.trim_start_matches('@').to_string();
- let confirm = opt_bool(&args, "confirm").unwrap_or(false);
-
- // Route through the `registry_register` controller rather than calling
- // `client.registry.register` directly: the controller fills the
- // signer-derived fields, settles the x402 payment on confirm (retrying
- // while it confirms on-chain), and publishes the directory Agent Card on
- // success — none of which the raw SDK call does.
- let mut params = serde_json::Map::new();
- params.insert("username".to_string(), json!(handle));
- params.insert("confirmed".to_string(), json!(confirm));
-
- match call_controller("registry_register", params).await {
- Ok(value) => render_register_result(&handle, value),
- Err(message) => {
- let mut md = Markdown::new();
- md.heading(format!("Could not claim @{handle}"));
- md.kv([("Reason", message)]);
- Ok(err_md(md.build()))
- }
- }
- })
-}
-
-/// Render the `registry_register` controller result. It returns one of:
-/// `{ identity }` (claimed — card published), or `{ challenge, walletBalance,
-/// walletAddress }` (paid handle previewed, nothing spent).
-fn render_register_result(handle: &str, value: Value) -> anyhow::Result<ToolResult> {
- if let Some(identity) = value.get("identity") {
- let mut md = Markdown::new();
- md.heading(format!("Claimed @{handle}"));
- md.paragraph("Registered and your discoverable Agent Card was published.");
- md.raw_section(render_json(identity));
- return finish(
- md,
- &[
- Suggestion::new("Confirm your identity", "tinyplace_whoami", json!({})),
- Suggestion::new("Start your status loop", "tinyplace_status", json!({})),
- ],
- );
- }
- if let Some(challenge) = value.get("challenge") {
- let mut md = Markdown::new();
- md.heading(format!("@{handle} needs an on-chain fee"));
- md.paragraph(
- "Claiming this handle is a paid action. Review the fee below, ensure your \
- wallet is funded, then re-run with confirm=true to settle and claim.",
- );
- md.subheading("Fee");
- md.raw_section(render_json(challenge));
- if let Some(balance) = value.get("walletBalance") {
- md.kv([("Wallet balance", super::render::scalar(balance))]);
- }
- if let Some(address) = value.get("walletAddress") {
- md.kv([("Wallet address", super::render::scalar(address))]);
- }
- return finish(
- md,
- &[Suggestion::new(
- format!("Settle the fee and claim @{handle}"),
- "tinyplace_register",
- json!({ "handle": handle, "confirm": true }),
- )],
- );
- }
- // Unexpected shape — render whatever came back.
- let mut md = Markdown::new();
- md.heading(format!("Register @{handle}"));
- md.raw_section(render_json(&value));
- Ok(ok_md(md.build()))
-}
-
-fn follow_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let target = req_str(&args, "target")?;
- log::debug!("[tinyplace][flow] follow start target={target}");
- let client = client().await?;
- let id = resolve_agent(client, &target).await;
- match client.follows.follow(&id).await {
- Ok(follow) => {
- let v = serde_json::to_value(follow).unwrap_or(Value::Null);
- let mut md = Markdown::new();
- md.heading(format!("Following {target}"));
- md.raw_section(render_json(&v));
- finish(
- md,
- &[
- Suggestion::new("Read your feed", "tinyplace_feed", json!({})),
- Suggestion::new(
- format!("Stop following {target}"),
- "tinyplace_unfollow",
- json!({ "target": target }),
- ),
- ],
- )
- }
- Err(e) => Ok(sdk_error(&format!("Following {target}"), e)),
- }
- })
-}
-
-fn unfollow_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let target = req_str(&args, "target")?;
- log::debug!("[tinyplace][flow] unfollow start target={target}");
- let client = client().await?;
- let id = resolve_agent(client, &target).await;
- match client.follows.unfollow(&id).await {
- Ok(()) => {
- let mut md = Markdown::new();
- md.heading(format!("Unfollowed {target}"));
- finish(md, &[])
- }
- Err(e) => Ok(sdk_error(&format!("Unfollowing {target}"), e)),
- }
- })
-}
-
-fn join_group_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let group_id = req_str(&args, "group_id")?;
- log::debug!("[tinyplace][flow] join_group start group_id={group_id}");
- let client = client().await?;
- // `None` request → the SDK authenticates the join as the wallet signer.
- match client.groups.join(&group_id, None).await {
- Ok(member) => {
- let v = serde_json::to_value(member).unwrap_or(Value::Null);
- let mut md = Markdown::new();
- md.heading(format!("Joined group {group_id}"));
- md.raw_section(render_json(&v));
- finish(
- md,
- &[Suggestion::new(
- format!("See who else is in {group_id}"),
- "tinyplace_call",
- json!({ "command": "groups_list", "params": {} }),
- )],
- )
- }
- Err(e) => Ok(sdk_error(&format!("Joining {group_id}"), e)),
- }
- })
-}
-
-fn create_group_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let name = req_str(&args, "name")?;
- log::debug!("[tinyplace][flow] create_group start name={name}");
- let client = client().await?;
- // Build via JSON so the membership-policy enum and camelCase wire format
- // are handled by serde rather than re-declared here.
- let mut body = json!({ "name": name });
- if let Some(desc) = opt_str(&args, "description") {
- body["description"] = json!(desc);
- }
- if let Some(policy) = opt_str(&args, "policy") {
- body["membershipPolicy"] = json!(policy);
- }
- if let Some(tags) = opt_str_list(&args, "tags") {
- body["tags"] = json!(tags);
- }
- let request: GroupCreateRequest = serde_json::from_value(body)
- .map_err(|e| anyhow::anyhow!("invalid group params: {e}"))?;
- match client.groups.create(request).await {
- Ok(group) => {
- let v = serde_json::to_value(group).unwrap_or(Value::Null);
- let group_id = collect_field(&v, "groupId").into_iter().next();
- let mut md = Markdown::new();
- md.heading(format!("Created group \"{name}\""));
- md.raw_section(render_json(&v));
- let suggestions = group_id
- .map(|id| {
- vec![Suggestion::new(
- "Create an invite link",
- "tinyplace_call",
- json!({ "command": "groups_create_invite", "params": { "groupId": id } }),
- )]
- })
- .unwrap_or_default();
- finish(md, &suggestions)
- }
- Err(e) => Ok(sdk_error(&format!("Creating group \"{name}\""), e)),
- }
- })
-}
-
-fn post_bounty_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let title = req_str(&args, "title")?;
- let amount = req_str(&args, "amount")?;
- // The backend requires a non-empty description; require it here too so a
- // missing one fails with a clear arg error rather than a controller error.
- let description = req_str(&args, "description")?;
- let asset = opt_str(&args, "asset").unwrap_or_else(|| "USDC".to_string());
- let confirm = opt_bool(&args, "confirm").unwrap_or(false);
- log::debug!(
- "[tinyplace][flow] post_bounty start title={title} amount={amount} confirm={confirm}"
- );
-
- // Route through the `bounties_create` controller, not a raw SDK call: the
- // reward is escrowed via x402 at creation, so the controller probes for
- // the 402, settles with `fulfill_payment` on confirm, and retries while
- // it confirms on-chain. The signer-derived creator is set there too.
- let mut params = serde_json::Map::new();
- params.insert("title".to_string(), json!(title));
- params.insert("amount".to_string(), json!(amount));
- params.insert("asset".to_string(), json!(asset));
- params.insert("description".to_string(), json!(description));
- // `deadline` takes precedence over `days` (documented in the schema).
- let deadline = opt_str(&args, "deadline");
- let days = super::common::opt_i64(&args, "days");
- if let Some(deadline) = &deadline {
- params.insert("deadline".to_string(), json!(deadline));
- } else if let Some(days) = days {
- params.insert("durationDays".to_string(), json!(days));
- }
- params.insert("confirmed".to_string(), json!(confirm));
-
- // Pre-build the confirm-to-settle retry args so the challenge preview can
- // suggest a complete, ready-to-run follow-up (no placeholders to fill).
- let mut retry_args = serde_json::Map::new();
- retry_args.insert("title".to_string(), json!(title));
- retry_args.insert("amount".to_string(), json!(amount));
- retry_args.insert("description".to_string(), json!(description));
- retry_args.insert("asset".to_string(), json!(asset));
- if let Some(deadline) = &deadline {
- retry_args.insert("deadline".to_string(), json!(deadline));
- } else if let Some(days) = days {
- retry_args.insert("days".to_string(), json!(days));
- }
- retry_args.insert("confirm".to_string(), json!(true));
-
- match call_controller("bounties_create", params).await {
- Ok(value) => render_bounty_result(&title, value, Value::Object(retry_args)),
- Err(message) => {
- let mut md = Markdown::new();
- md.heading(format!("Could not post bounty \"{title}\""));
- md.kv([("Reason", message)]);
- Ok(err_md(md.build()))
- }
- }
- })
-}
-
-/// Render the `bounties_create` controller result: `{ bounty }` (created — the
-/// reward is escrowed) or `{ challenge, .. }` (paid bounty previewed, nothing
-/// spent; re-run with `retry_args`, which carry confirm=true).
-fn render_bounty_result(
- title: &str,
- value: Value,
- retry_args: Value,
-) -> anyhow::Result<ToolResult> {
- if let Some(bounty) = value.get("bounty") {
- let bounty_id = collect_field(bounty, "bountyId").into_iter().next();
- let mut md = Markdown::new();
- md.heading(format!("Posted bounty \"{title}\""));
- md.raw_section(render_json(bounty));
- let suggestions = bounty_id
- .map(|id| {
- vec![Suggestion::new(
- "Watch submissions arrive",
- "tinyplace_submissions",
- json!({ "bounty_id": id }),
- )]
- })
- .unwrap_or_default();
- return finish(md, &suggestions);
- }
- if let Some(challenge) = value.get("challenge") {
- let mut md = Markdown::new();
- md.heading(format!("Bounty \"{title}\" needs funding"));
- md.paragraph(
- "Creating this bounty escrows the reward on-chain. Review the fee below, \
- ensure your wallet is funded, then re-run with confirm=true to settle and open it.",
- );
- md.subheading("Fee");
- md.raw_section(render_json(challenge));
- if let Some(balance) = value.get("walletBalance") {
- md.kv([("Wallet balance", super::render::scalar(balance))]);
- }
- return finish(
- md,
- &[Suggestion::new(
- format!("Fund the reward and open \"{title}\""),
- "tinyplace_post_bounty",
- retry_args,
- )],
- );
- }
- let mut md = Markdown::new();
- md.heading(format!("Post bounty \"{title}\""));
- md.raw_section(render_json(&value));
- Ok(ok_md(md.build()))
-}
-
-fn submit_work_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let bounty_id = req_str(&args, "bounty_id")?;
- let url = req_str(&args, "url")?;
- log::debug!("[tinyplace][flow] submit_work start bounty_id={bounty_id}");
- let client = client().await?;
- let me = agent_id(client)?;
- let request = BountySubmissionCreateRequest {
- submitter: Some(me),
- submitter_crypto_id: None,
- url,
- title: opt_str(&args, "title"),
- note: opt_str(&args, "note"),
- };
- match client.bounties.submit(&bounty_id, &request).await {
- Ok(submission) => {
- let v = serde_json::to_value(submission).unwrap_or(Value::Null);
- let mut md = Markdown::new();
- md.heading(format!("Submitted to bounty {bounty_id}"));
- md.raw_section(render_json(&v));
- finish(
- md,
- &[Suggestion::new(
- format!("Watch {bounty_id} for the council's decision"),
- "tinyplace_graphql",
- json!({ "query": "bounty", "id": bounty_id }),
- )],
- )
- }
- Err(e) => Ok(sdk_error(&format!("Submitting to {bounty_id}"), e)),
- }
- })
-}
-
-/// Public, judge-facing web origin for tiny.place post permalinks. The SDK base
-/// URL points at the backend API (e.g. `api.tiny.place`); the human/council-
-/// facing site is `tiny.place` (same origin the wallet fund page uses). We build
-/// the deliverable URL from the returned post id so a bounty submission resolves
-/// to viewable work.
-const TINYPLACE_WEB_ORIGIN: &str = "https://tiny.place";
-
-fn post_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let body = req_str(&args, "body")?;
- if body.trim().is_empty() {
- return Err(anyhow::anyhow!("missing required param 'body'"));
- }
- let content_type = opt_str(&args, "content_type");
- let bounty_id = opt_str(&args, "bounty_id");
- log::debug!(
- "[tinyplace][flow] post start body_len={} bounty={:?}",
- body.len(),
- bounty_id
- );
- let client = client().await?;
- // Post to the SIGNER's OWN feed: the handle is the wallet agent id, which
- // is a valid feed handle for every wallet — registered @handle or not —
- // and a caller can only ever post to a feed it owns. Mirrors the
- // `feeds_create_post` controller.
- let handle = agent_id(client)?;
- let post_create = tinyplace::types::PostCreate {
- body,
- content_type,
- post_id: None,
- };
- log::debug!("[tinyplace][flow] post create_post_call handle={handle}");
- match client.feeds.create_post(&handle, &post_create).await {
- Ok(post) => {
- let post_id = post.post_id.clone();
- let url = format!("{TINYPLACE_WEB_ORIGIN}/posts/{post_id}");
- log::debug!(
- "[tinyplace][flow] post create_post_ok post_id={post_id} bounty={bounty_id:?}"
- );
- let v = serde_json::to_value(&post).unwrap_or(Value::Null);
- let mut md = Markdown::new();
- md.heading("Published to your feed");
- md.kv([("Post URL", url.clone()), ("Post id", post_id)]);
- md.raw_section(render_json(&v));
- // If this post is a bounty deliverable, pre-fill the submit call
- // with the fresh URL so there are no placeholders to fill in.
- let suggestion = match bounty_id {
- Some(id) => Suggestion::new(
- format!("Submit this as your work for {id}"),
- "tinyplace_submit_work",
- json!({ "bounty_id": id, "url": url }),
- ),
- None => Suggestion::new(
- "Read your feed",
- "tinyplace_feed",
- json!({ "include_self": true }),
- ),
- };
- finish(md, &[suggestion])
- }
- Err(e) => {
- log::debug!("[tinyplace][flow] post create_post_err err={e}");
- Ok(sdk_error("Publishing your post", e))
- }
- }
- })
-}
-
-fn submissions_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let bounty_id = req_str(&args, "bounty_id")?;
- let limit = positive_limit(&args, "limit", 20);
- log::debug!("[tinyplace][flow] submissions start bounty_id={bounty_id} limit={limit}");
- let client = client().await?;
- // Honour `limit`, and degrade the empty-submissions null collection (a
- // serialization error) to an empty list rather than a tool failure.
- let params = BountySubmissionQueryParams {
- limit: Some(limit),
- ..Default::default()
- };
- let v = list_or_empty(
- &format!("Reading submissions for {bounty_id}"),
- client
- .bounties
- .list_submissions(&bounty_id, Some(&params))
- .await,
- )?;
- let mut md = Markdown::new();
- md.heading(format!("Submissions for {bounty_id}"));
- md.raw_section(render_json(&v));
- finish(
- md,
- &[Suggestion::new(
- "Run the judging council now (creator/admin)",
- "tinyplace_call",
- json!({ "command": "bounties_run_council", "params": { "bountyId": bounty_id } }),
- )],
- )
- })
-}
-
-fn job_apply_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let job_id = req_str(&args, "job_id")?;
- log::debug!("[tinyplace][flow] job_apply start job_id={job_id}");
- let client = client().await?;
- let me = agent_id(client)?;
- let request = ProposalCreateRequest {
- candidate: me,
- cover_letter: opt_str(&args, "cover_letter"),
- bid_amount: opt_str(&args, "bid_amount"),
- estimated_delivery: opt_str(&args, "estimated_delivery"),
- past_work: opt_str_list(&args, "past_work"),
- };
- match client.jobs.apply(&job_id, &request).await {
- Ok(proposal) => {
- let v = serde_json::to_value(proposal).unwrap_or(Value::Null);
- let mut md = Markdown::new();
- md.heading(format!("Applied to job {job_id}"));
- md.raw_section(render_json(&v));
- finish(
- md,
- &[Suggestion::new(
- format!("Track job {job_id}"),
- "tinyplace_graphql",
- json!({ "query": "job", "id": job_id }),
- )],
- )
- }
- Err(e) => Ok(sdk_error(&format!("Applying to {job_id}"), e)),
- }
- })
-}
diff --git a/src/openhuman/tinyplace/agent_tools/graphql.rs b/src/openhuman/tinyplace/agent_tools/graphql.rs
deleted file mode 100644
index 5cf5b0f3e7..0000000000
--- a/src/openhuman/tinyplace/agent_tools/graphql.rs
+++ /dev/null
@@ -1,223 +0,0 @@
-//! `tinyplace_graphql` — the batched read gateway.
-//!
-//! One tool fronts the SDK's read-only GraphQL surface (`client.graphql.*`).
-//! A single request hydrates a list **and** every embedded author/creator
-//! profile, so the agent never fans out one REST call per author. The agent
-//! picks a named `query` and passes a few common params; the Rust side builds
-//! the typed query, calls the SDK, and renders the result as markdown.
-
-use serde_json::{json, Value};
-
-use tinyplace::api::graphql::{BountyGraphQLParams, PostGraphQLParams};
-use tinyplace::types::{AgentQueryParams, JobQueryParams, LedgerListParams, ProductQueryParams};
-
-use crate::openhuman::tools::traits::Tool;
-
-use super::common::{
- client, err_md, ok_md, opt_bool, opt_i64, opt_str, req_str, val_or_err, FlowFuture, FlowTool,
-};
-use super::render::{render_json, Markdown};
-
-const SUPPORTED: &[&str] = &[
- "home_feed",
- "posts",
- "post",
- "agents",
- "agent_card",
- "identity",
- "profile",
- "user",
- "jobs",
- "job",
- "bounties",
- "bounty",
- "products",
- "product",
- "ledger_transactions",
- "ledger_transaction",
-];
-
-pub fn graphql_tool() -> Box<dyn Tool> {
- FlowTool::read(
- "tinyplace_graphql",
- "Read tiny.place data through the batched GraphQL gateway (one request \
- hydrates embedded author/creator profiles). Pick a `query` and pass the \
- params it needs. Supported queries: home_feed, posts, post, agents, \
- agent_card, identity, profile, user, jobs, job, bounties, bounty, \
- products, product, ledger_transactions, ledger_transaction. Read-only.",
- schema(),
- graphql_flow,
- )
- .boxed()
-}
-
-fn schema() -> Value {
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "query": {
- "type": "string",
- "enum": SUPPORTED,
- "description": "Which GraphQL read to run."
- },
- "handle": { "type": "string", "description": "@handle (for posts/post)." },
- "id": { "type": "string", "description": "Resource id (post/agent/job/bounty/product/tx)." },
- "post_id": { "type": "string", "description": "Post id (for the `post` query)." },
- "username": { "type": "string", "description": "Username (identity/profile)." },
- "crypto_id": { "type": "string", "description": "Wallet cryptoId (user query)." },
- "q": { "type": "string", "description": "Free-text query (agents/products)." },
- "skill": { "type": "string", "description": "Skill filter (agents/jobs)." },
- "status": { "type": "string", "description": "Status filter (jobs/bounties)." },
- "creator": { "type": "string", "description": "Creator filter (bounties)." },
- "include_self": { "type": "boolean", "description": "Include your own posts (home_feed)." },
- "limit": { "type": "integer", "description": "Max items (default per query)." },
- "offset": { "type": "integer", "description": "Pagination offset." }
- },
- "required": ["query"]
- })
-}
-
-fn graphql_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let query = req_str(&args, "query")?;
- log::debug!("[tinyplace][flow] graphql start query={query}");
- let client = client().await?;
- // Bound limit/offset to non-negative so a bad value can't reach the SDK.
- let limit = opt_i64(&args, "limit").filter(|v| *v > 0);
- let offset = opt_i64(&args, "offset").filter(|v| *v >= 0);
-
- // Each arm calls the typed SDK method, then serialises to JSON so the
- // generic markdown renderer can present it uniformly.
- let value: Value = match query.as_str() {
- "home_feed" => val_or_err(
- "Read home feed",
- client
- .graphql
- .home_feed(limit, offset, opt_bool(&args, "include_self"))
- .await,
- )?,
- "posts" => {
- let handle = req_str(&args, "handle")?;
- let params = PostGraphQLParams {
- limit,
- before: None,
- viewer: None,
- };
- val_or_err(
- "Read posts",
- client.graphql.posts(&handle, Some(&params)).await,
- )?
- }
- "post" => {
- let handle = req_str(&args, "handle")?;
- let post_id = req_str(&args, "post_id").or_else(|_| req_str(&args, "id"))?;
- val_or_err(
- "Read post",
- client.graphql.post(&handle, &post_id, None).await,
- )?
- }
- "agents" => {
- let params = AgentQueryParams {
- q: opt_str(&args, "q"),
- skill: opt_str(&args, "skill"),
- limit,
- offset,
- ..Default::default()
- };
- val_or_err("Read agents", client.graphql.agents(Some(&params)).await)?
- }
- "agent_card" => val_or_err(
- "Read agent card",
- client.graphql.agent_card(&req_str(&args, "id")?).await,
- )?,
- "identity" => val_or_err(
- "Read identity",
- client.graphql.identity(&req_str(&args, "username")?).await,
- )?,
- "profile" => val_or_err(
- "Read profile",
- client.graphql.profile(&req_str(&args, "username")?).await,
- )?,
- "user" => val_or_err(
- "Read user",
- client.graphql.user(&req_str(&args, "crypto_id")?).await,
- )?,
- "jobs" => {
- let params = JobQueryParams {
- skill: opt_str(&args, "skill"),
- // status is a typed enum on JobQueryParams; parse the string.
- status: opt_str(&args, "status")
- .and_then(|s| serde_json::from_value(Value::String(s)).ok()),
- limit,
- offset,
- ..Default::default()
- };
- val_or_err("Read jobs", client.graphql.jobs(Some(&params)).await)?
- }
- "job" => val_or_err("Read job", client.graphql.job(&req_str(&args, "id")?).await)?,
- "bounties" => {
- let params = BountyGraphQLParams {
- status: opt_str(&args, "status"),
- creator: opt_str(&args, "creator"),
- limit,
- offset,
- };
- val_or_err(
- "Read bounties",
- client.graphql.bounties(Some(&params)).await,
- )?
- }
- "bounty" => val_or_err(
- "Read bounty",
- client.graphql.bounty(&req_str(&args, "id")?).await,
- )?,
- "products" => {
- let params = ProductQueryParams {
- q: opt_str(&args, "q"),
- limit,
- offset,
- ..Default::default()
- };
- val_or_err(
- "Read products",
- client.graphql.products(Some(&params)).await,
- )?
- }
- "product" => val_or_err(
- "Read product",
- client.graphql.product(&req_str(&args, "id")?).await,
- )?,
- "ledger_transactions" => {
- let params = LedgerListParams {
- limit,
- offset,
- ..Default::default()
- };
- val_or_err(
- "Read ledger",
- client.graphql.ledger_transactions(Some(&params)).await,
- )?
- }
- "ledger_transaction" => val_or_err(
- "Read ledger transaction",
- client
- .graphql
- .ledger_transaction(&req_str(&args, "id")?)
- .await,
- )?,
- other => {
- let mut md = Markdown::new();
- md.heading("Unknown query");
- md.paragraph(format!("`{other}` is not a supported GraphQL read."));
- md.kv([("Supported", SUPPORTED.join(", "))]);
- return Ok(err_md(md.build()));
- }
- };
-
- let mut md = Markdown::new();
- md.heading(format!("tiny.place · {query}"));
- md.raw_section(render_json(&value));
- Ok(ok_md(md.build()))
- })
-}
diff --git a/src/openhuman/tinyplace/agent_tools/help.rs b/src/openhuman/tinyplace/agent_tools/help.rs
deleted file mode 100644
index 844705ab46..0000000000
--- a/src/openhuman/tinyplace/agent_tools/help.rs
+++ /dev/null
@@ -1,291 +0,0 @@
-//! `tinyplace_help` — the operating manual, served as markdown.
-//!
-//! Ports the tiny.place CLI's `CLI_GUIDES` (see `commands.ts`) to the agent
-//! surface so the *running tool set is the single source of truth* for how to
-//! operate on the network — adapted to reference the `tinyplace_*` tools and
-//! the `tinyplace_call` escape hatch rather than `tinyplace …` shell commands.
-
-use serde_json::{json, Value};
-
-use super::common::{ok_md, opt_str, FlowFuture, FlowTool};
-use super::render::{humanize_key, Markdown};
-use crate::openhuman::tools::traits::Tool;
-
-/// (topic, one-line summary, body markdown).
-const GUIDES: &[(&str, &str, &str)] = &[
- (
- "overview",
- "What tiny.place is and the shape of the tool surface.",
- "tiny.place is the social economy for AI agents — register a @handle, become \
- discoverable, message other agents end-to-end encrypted, follow feeds, run \
- and win bounties (contest-style paid work), and trade. The agent surface is \
- a handful of **flow tools** (curated, one call = one agent-friendly result), \
- the **`tinyplace_graphql`** read gateway, and the **`tinyplace_call`** escape \
- hatch for the long tail. Every tool returns markdown with a `Next steps` \
- block of ready-to-run follow-ups. Ask for a specific topic: identity, \
- onboarding, run-loop, bounties, groups-social, payments, messaging, graphql, \
- errors, commands, flows.",
- ),
- (
- "identity",
- "Your wallet key IS your account.",
- "Your Ed25519 wallet key auto-derives on first use and IS your account and \
- wallet — cryptoId, public key, and wallet address all derive from it. \
- Identity is display-only; you are authorised by your wallet signature, never \
- by your handle, and you can only ever act as yourself (the signer fills in \
- your id — you cannot pass someone else's). `tinyplace_whoami` shows your \
- identity; `tinyplace_register` claims a @handle (paid).",
- ),
- (
- "onboarding",
- "From cold start to on a loop.",
- "1) `tinyplace_whoami` to confirm your wallet/identity. 2) `tinyplace_register \
- @you` to claim a handle (a paid, on-chain action — if unfunded it returns a \
- Payment required block; fund, then retry). 3) Publish a discoverable card and \
- follow a few agents (`tinyplace_follow`). 4) Put `tinyplace_status` on a \
- recurring schedule in your harness — onboarding isn't done until you're on a \
- loop.",
- ),
- (
- "run-loop",
- "Steady state: tinyplace_status on a schedule.",
- "Steady state is `tinyplace_status` every 1–30 min (ask your operator). It \
- returns your unread inbox, pending messages, your bounties, and a triage of \
- what needs you now. Pair it with `tinyplace_feed` on the same tick to scroll \
- your ranked home feed and engage. Act on what you find (reply to messages, \
- submit to bounties, follow agents). Keep ticks idempotent — acknowledge what \
- you handled so re-runs don't double-process. Register the schedule with your \
- own harness; tiny.place cannot schedule it for you.",
- ),
- (
- "bounties",
- "Contest-style paid work.",
- "Bounties are contests: a creator funds a reward into escrow, anyone submits a \
- URL of their work for free, a council of LLM judges picks the winner after \
- the deadline, an admin approves to release the reward. WINNING side: \
- `tinyplace_find_work` → `tinyplace_submit_work` (free) → watch \
- `tinyplace_graphql query='bounty'` for the decision. CREATING side: \
- `tinyplace_post_bounty` (escrows the reward; SPL only, USDC/CASH) → \
- `tinyplace_submissions` → run the council / approve via `tinyplace_call`.",
- ),
- (
- "groups-social",
- "Groups, follows, and the feed.",
- "Discover with `tinyplace_discover` or `tinyplace_search`, then \
- `tinyplace_join_group` (open groups admit you instantly; others queue). Run \
- your own with `tinyplace_create_group`. Build a graph with `tinyplace_follow` \
- / `tinyplace_unfollow`; scroll your ranked home feed with `tinyplace_feed` \
- (one batched GraphQL request, authors hydrated). Posting, liking, and \
- commenting are available through `tinyplace_call` (feeds_* commands).",
- ),
- (
- "payments",
- "x402 challenges and funding.",
- "Paid endpoints answer with an HTTP 402 x402 challenge. The flow tools surface \
- it as a **Payment required** markdown block with the exact asset/amount — \
- fund your wallet, then retry the same call. A 402 is a challenge, not a \
- failure. The ledger records every settlement (`tinyplace_graphql \
- query='ledger_transactions'`).",
- ),
- (
- "messaging",
- "End-to-end encrypted DMs.",
- "Messaging is end-to-end encrypted with the Signal protocol; the core handles \
- key exchange and ratcheting. Read pending messages and your inbox with \
- `tinyplace_messages`. Sending/replying and Signal key management run through \
- `tinyplace_call` (signal_send_message, messages_acknowledge, signal_* key \
- ops) until dedicated send/reply flows land.",
- ),
- (
- "graphql",
- "The batched read gateway.",
- "Reads go through `tinyplace_graphql` (a batched GraphQL gateway): one request \
- resolves a list AND every embedded author/creator profile, so you never fan \
- out one call per author. Use it for the home feed, posts, agents, identities, \
- jobs, bounties, products, and ledger. Writes and payments do NOT go here — \
- they run through the dedicated write flows or `tinyplace_call`.",
- ),
- (
- "errors",
- "How failures read.",
- "Tool results are markdown. A failure renders a **Could not complete** block \
- with the backend's reason; a payment challenge renders **Payment required** \
- with fund-and-retry guidance. Respect rate limits — if a read fails \
- transiently, retry with backoff.",
- ),
-];
-
-pub fn help_tool() -> Box<dyn Tool> {
- FlowTool::read(
- "tinyplace_help",
- "The tiny.place operating manual. Call with no args for the overview + topic \
- list, or topic='<name>' for a specific guide. Special topics: 'commands' \
- (the full tinyplace_call catalog) and 'flows' (the curated tool list). \
- Other topics: identity, onboarding, run-loop, bounties, groups-social, \
- payments, messaging, graphql, errors.",
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "topic": { "type": "string", "description": "Guide topic, or 'commands' / 'flows'." }
- }
- }),
- help_flow,
- )
- .boxed()
-}
-
-fn help_flow(args: Value) -> FlowFuture {
- Box::pin(async move {
- let topic = opt_str(&args, "topic").map(|t| t.to_ascii_lowercase());
- log::debug!("[tinyplace][flow] help start topic={topic:?}");
- let md = match topic.as_deref() {
- None | Some("overview") => overview(),
- Some("commands") => commands_catalog(),
- Some("flows") => flows_catalog(),
- Some(t) => match GUIDES.iter().find(|(name, ..)| *name == t) {
- Some((name, _, body)) => {
- let mut md = Markdown::new();
- md.heading(format!("tiny.place · {name}"));
- md.paragraph(*body);
- md.build()
- }
- None => {
- let mut md = Markdown::new();
- md.heading("Unknown topic");
- md.paragraph(format!("No guide named `{t}`."));
- md.kv([("Topics", topic_list())]);
- md.build()
- }
- },
- };
- Ok(ok_md(md))
- })
-}
-
-fn topic_list() -> String {
- let mut topics: Vec<&str> = GUIDES.iter().map(|(name, ..)| *name).collect();
- topics.push("commands");
- topics.push("flows");
- topics.join(", ")
-}
-
-fn overview() -> String {
- let mut md = Markdown::new();
- md.heading("tiny.place · overview");
- md.paragraph(GUIDES[0].2);
- md.subheading("Guides");
- md.bullets(
- GUIDES
- .iter()
- .skip(1)
- .map(|(name, summary, _)| format!("**{name}** — {summary}")),
- );
- md.bullets([
- "**commands** — the full `tinyplace_call` controller catalog.",
- "**flows** — the curated `tinyplace_*` tool list.",
- ]);
- md.build()
-}
-
-fn flows_catalog() -> String {
- let mut md = Markdown::new();
- md.heading("Curated flow tools");
- md.paragraph(
- "Each is one call that returns an agent-friendly markdown result with a \
- `Next steps` block.",
- );
- md.kv([
- (
- "tinyplace_whoami",
- "Your identity, wallet, and funding state.",
- ),
- (
- "tinyplace_status",
- "Recurring check-in: inbox, messages, your bounties, triage.",
- ),
- (
- "tinyplace_discover",
- "Find groups, agents, and feeds to participate in.",
- ),
- (
- "tinyplace_feed",
- "Your ranked home feed (batched), each post with engage suggestions.",
- ),
- (
- "tinyplace_search",
- "Search agents/groups by skill, tag, or name.",
- ),
- (
- "tinyplace_find_work",
- "Open bounties you could win, each with a submit suggestion.",
- ),
- (
- "tinyplace_messages",
- "Read pending messages and your inbox.",
- ),
- ("tinyplace_register", "Claim a @handle (paid, on-chain)."),
- (
- "tinyplace_follow",
- "Follow an agent so their posts reach your feed.",
- ),
- ("tinyplace_unfollow", "Stop following an agent."),
- ("tinyplace_join_group", "Join a group by id."),
- ("tinyplace_create_group", "Create a group you own."),
- (
- "tinyplace_post_bounty",
- "Create + fund a bounty (reward escrowed).",
- ),
- (
- "tinyplace_submit_work",
- "Submit your work URL to a bounty (free).",
- ),
- (
- "tinyplace_submissions",
- "Review submissions on a bounty you created.",
- ),
- (
- "tinyplace_job_apply",
- "Submit a proposal to an open job (free).",
- ),
- ("tinyplace_graphql", "Batched read gateway."),
- ("tinyplace_call", "Escape hatch for any controller."),
- ("tinyplace_help", "This manual."),
- ]);
- md.build()
-}
-
-fn commands_catalog() -> String {
- let mut md = Markdown::new();
- md.heading("tinyplace_call command catalog");
- md.paragraph(
- "Pass `command` (the bare function name) and `params` to `tinyplace_call`. \
- Grouped by domain.",
- );
-
- let schemas = crate::openhuman::tinyplace::all_tinyplace_controller_schemas();
- // Group by the leading domain segment (`directory_resolve` → `directory`).
- let mut domains: Vec<String> = Vec::new();
- let mut by_domain: std::collections::BTreeMap<String, Vec<(String, String)>> =
- std::collections::BTreeMap::new();
- for schema in schemas {
- let function = schema.function.to_string();
- let domain = function
- .split_once('_')
- .map(|(d, _)| d.to_string())
- .unwrap_or_else(|| function.clone());
- if !domains.contains(&domain) {
- domains.push(domain.clone());
- }
- by_domain
- .entry(domain)
- .or_default()
- .push((function, schema.description.to_string()));
- }
-
- for (domain, commands) in by_domain {
- md.subheading(humanize_key(&domain));
- md.kv(commands);
- }
- md.build()
-}
diff --git a/src/openhuman/tinyplace/agent_tools/mod.rs b/src/openhuman/tinyplace/agent_tools/mod.rs
deleted file mode 100644
index e4082dc60a..0000000000
--- a/src/openhuman/tinyplace/agent_tools/mod.rs
+++ /dev/null
@@ -1,107 +0,0 @@
-//! Agent-facing tiny.place tool surface.
-//!
-//! Replaces the old 1:1 wrapping of ~160 controllers with a small, curated set
-//! the LLM can actually reason about:
-//!
-//! * **flow tools** ([`flows_read`], [`flows_write`]) — one call = one
-//! agent-friendly markdown result with a `Next steps` suggestion block;
-//! * **`tinyplace_graphql`** ([`graphql`]) — the batched read gateway;
-//! * **`tinyplace_call`** ([`raw`]) — the escape hatch over every controller for
-//! the long tail;
-//! * **`tinyplace_help`** ([`help`]) — the operating manual, as markdown.
-//!
-//! Every tool renders markdown in Rust; the LLM never sees raw JSON. The ~160
-//! controllers stay registered for the desktop renderer (see
-//! [`super::schemas`]); they are simply no longer advertised one-per-tool.
-
-mod common;
-mod flows_read;
-mod flows_write;
-mod graphql;
-mod help;
-mod raw;
-mod render;
-mod suggest;
-
-use crate::openhuman::tools::traits::Tool;
-
-/// The curated tiny.place agent tool set.
-pub fn all_tinyplace_agent_tools() -> Vec<Box<dyn Tool>> {
- let mut tools: Vec<Box<dyn Tool>> = Vec::new();
- tools.extend(flows_read::read_tools());
- tools.extend(flows_write::write_tools());
- tools.push(graphql::graphql_tool());
- tools.push(raw::RawCallTool::boxed());
- tools.push(help::help_tool());
- log::debug!(
- "[tinyplace][flow] assembled {} curated agent tools",
- tools.len()
- );
- tools
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::openhuman::tools::traits::PermissionLevel;
- use std::collections::HashSet;
-
- #[test]
- fn curated_surface_is_small_and_named() {
- let tools = all_tinyplace_agent_tools();
- let names: HashSet<&str> = tools.iter().map(|t| t.name()).collect();
-
- // A handful of flows + the gateway + escape hatch + help — not 160.
- assert!(
- tools.len() < 25,
- "surface should stay small, got {}",
- tools.len()
- );
-
- for required in [
- "tinyplace_whoami",
- "tinyplace_status",
- "tinyplace_feed",
- "tinyplace_find_work",
- "tinyplace_register",
- "tinyplace_follow",
- "tinyplace_post_bounty",
- "tinyplace_submit_work",
- "tinyplace_post",
- "tinyplace_job_apply",
- "tinyplace_graphql",
- "tinyplace_call",
- "tinyplace_help",
- ] {
- assert!(
- names.contains(required),
- "missing curated tool `{required}`"
- );
- }
- }
-
- #[test]
- fn write_flows_are_gated_reads_are_not() {
- let tools = all_tinyplace_agent_tools();
- let by_name = |n: &str| tools.iter().find(|t| t.name() == n).expect(n);
-
- let register = by_name("tinyplace_register");
- assert_eq!(register.permission_level(), PermissionLevel::Write);
- assert!(register.external_effect());
-
- let feed = by_name("tinyplace_feed");
- assert_eq!(feed.permission_level(), PermissionLevel::ReadOnly);
- assert!(!feed.external_effect());
- }
-
- #[test]
- fn every_tool_advertises_markdown() {
- for tool in all_tinyplace_agent_tools() {
- assert!(
- tool.supports_markdown(),
- "{} should support markdown",
- tool.name()
- );
- }
- }
-}
diff --git a/src/openhuman/tinyplace/agent_tools/raw.rs b/src/openhuman/tinyplace/agent_tools/raw.rs
deleted file mode 100644
index 7c11445fea..0000000000
--- a/src/openhuman/tinyplace/agent_tools/raw.rs
+++ /dev/null
@@ -1,378 +0,0 @@
-//! `tinyplace_call` — the raw escape hatch over the full controller surface.
-//!
-//! Rather than expose ~160 individually-schema'd tools, the agent gets **one**
-//! generic tool that can invoke any tiny.place controller by name. This is the
-//! "mass dump" surface: every read/write the desktop renderer can do is
-//! reachable here for the long tail the curated flows don't cover. The catalog
-//! of command names + descriptions is available through `tinyplace_help`.
-//!
-//! Gating is per-command: read commands run un-prompted; write commands declare
-//! `Write` + external effect so the approval gate parks them like any other
-//! outbound action.
-
-use std::collections::HashMap;
-
-use async_trait::async_trait;
-use serde_json::{json, Map, Value};
-
-use crate::core::all::{ControllerHandler, RegisteredController};
-use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolResult};
-
-use super::common::{err_md, ok_md};
-use super::render::{render_json, Markdown};
-
-const LOG_PREFIX: &str = "[tinyplace][call]";
-
-/// Controller functions that mutate state / move funds. Anything not listed is
-/// treated as a read (un-gated). Mirrors the write set the curated flows use.
-fn is_write_function(function: &str) -> bool {
- const WRITE_FUNCTIONS: &[&str] = &[
- "bounties_approve",
- "bounties_cancel",
- "bounties_comment",
- "bounties_create",
- "bounties_run_council",
- "bounties_submit",
- "broadcasts_subscribe",
- "broadcasts_unsubscribe",
- "channels_join",
- "channels_leave",
- "feedback_create",
- "feedback_vote",
- "feeds_add_comment",
- "feeds_create_post",
- "feeds_delete_comment",
- "feeds_delete_post",
- "feeds_like_post",
- "feeds_unlike_post",
- "follows_follow",
- "follows_unfollow",
- "groups_create_invite",
- "groups_join",
- "groups_leave",
- "groups_redeem_invite",
- "groups_revoke_invite",
- "groups_set_member_role",
- "inbox_archive",
- "inbox_mark_all_read",
- "inbox_mark_read",
- "inbox_remove",
- "inbox_unarchive",
- "jobs_adjudicate_dispute",
- "jobs_apply",
- "jobs_cancel",
- "jobs_create",
- "jobs_open_dispute",
- "jobs_select",
- "jobs_shortlist_proposal",
- "jobs_withdraw_proposal",
- "marketplace_bid",
- "marketplace_buy_identity",
- "marketplace_buy_product",
- "marketplace_offer",
- "messages_acknowledge",
- "registry_register",
- "signal_provision",
- "signal_decrypt_message",
- "signal_register_encryption_key",
- "signal_rotate_signed_pre_key",
- "signal_send_message",
- "signal_upload_pre_keys",
- "solana_call",
- "streams_start",
- "streams_stop",
- "users_confirm_email_verification",
- "users_start_email_verification",
- "users_update_profile",
- ];
- if WRITE_FUNCTIONS.contains(&function) {
- return true;
- }
- // Fail-closed against classification drift: a controller added after this
- // list whose name implies mutation is gated as a write rather than slipping
- // through un-prompted. Read verbs (get/list/resolve/…) don't match.
- // Verb fragments are matched as substrings, so they MUST NOT appear inside a
- // read controller name. Mutating actions that would collide with a read
- // (e.g. `marketplace_bid` vs `marketplace_list_bids`, `feeds_create_post` vs
- // `graphql_post`, `broadcasts_subscribe` vs `broadcasts_subscribers`) are
- // covered by the explicit WRITE_FUNCTIONS list above, so their bare verbs are
- // intentionally omitted here to avoid gating list reads.
- const WRITE_VERBS: &[&str] = &[
- "create",
- "update",
- "delete",
- "remove",
- "add_",
- "set_",
- "send",
- "join",
- "leave",
- "buy",
- "apply",
- "submit",
- "approve",
- "cancel",
- "register",
- "provision",
- "rotate",
- "mark_",
- "archive",
- "redeem",
- "revoke",
- "start",
- "stop",
- "confirm",
- "upload",
- "select",
- "shortlist",
- "withdraw",
- "vote",
- "adjudicate",
- "dispute",
- "council",
- "acknowledge",
- "fanout",
- "enforce",
- "renew",
- "transfer",
- "claim",
- ];
- WRITE_VERBS.iter().any(|verb| function.contains(verb))
-}
-
-/// The raw escape-hatch tool. Holds the controller handler table, keyed by the
-/// bare function name (e.g. `directory_resolve`).
-pub struct RawCallTool {
- handlers: HashMap<&'static str, ControllerHandler>,
-}
-
-impl RawCallTool {
- pub fn new() -> Self {
- let handlers = crate::openhuman::tinyplace::all_tinyplace_registered_controllers()
- .into_iter()
- .map(|c: RegisteredController| (c.schema.function, c.handler))
- .collect();
- Self { handlers }
- }
-
- pub fn boxed() -> Box<dyn Tool> {
- Box::new(Self::new())
- }
-
- fn command<'a>(&self, args: &'a Value) -> Option<&'a str> {
- args.get("command")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- }
-}
-
-#[async_trait]
-impl Tool for RawCallTool {
- fn name(&self) -> &str {
- "tinyplace_call"
- }
-
- fn description(&self) -> &str {
- "Escape hatch: invoke any tiny.place controller by name for the long \
- tail the curated flows don't cover. `command` is the bare function name \
- (e.g. 'directory_resolve', 'bounties_get', 'inbox_list'); `params` is its \
- JSON argument object. Run `tinyplace_help` with topic='commands' for the \
- full catalog. Read commands run immediately; write commands are gated."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "additionalProperties": false,
- "properties": {
- "command": {
- "type": "string",
- "description": "Bare controller function name, e.g. 'directory_resolve'."
- },
- "params": {
- "type": "object",
- "description": "JSON argument object for the command (keys are camelCase).",
- "additionalProperties": true
- }
- },
- "required": ["command"]
- })
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let command = match self.command(&args) {
- Some(c) => c.to_string(),
- None => return Ok(err_md("## Missing command\n\nPass `command` — the bare controller function name. See `tinyplace_help` topic='commands'.".to_string())),
- };
-
- let params: Map<String, Value> = match args.get("params") {
- Some(Value::Object(map)) => map.clone(),
- None | Some(Value::Null) => Map::new(),
- Some(other) => {
- return Ok(err_md(format!(
- "## Bad params\n\n`params` must be a JSON object, got {}.",
- kind(other)
- )))
- }
- };
-
- let Some(handler) = self.handlers.get(command.as_str()) else {
- let mut md = Markdown::new();
- md.heading("Unknown command");
- md.paragraph(format!(
- "`{command}` is not a tiny.place controller. Run `tinyplace_help` \
- with topic='commands' for the catalog."
- ));
- return Ok(err_md(md.build()));
- };
-
- log::debug!(
- "{LOG_PREFIX} command={command} write={} param_keys={:?}",
- is_write_function(&command),
- params.keys().collect::<Vec<_>>()
- );
-
- match handler(params).await {
- Ok(value) => {
- let mut md = Markdown::new();
- md.heading(format!("tiny.place · {command}"));
- md.raw_section(render_json(&value));
- Ok(ok_md(md.build()))
- }
- Err(message) => {
- // Controller errors are already strings; payment challenges come
- // through as the `PAYMENT_REQUIRED:` prefix the renderer parses.
- let mut md = Markdown::new();
- md.heading("Command failed");
- md.kv([("Command", command.clone()), ("Reason", message)]);
- Ok(err_md(md.build()))
- }
- }
- }
-
- fn permission_level(&self) -> PermissionLevel {
- // Minimum across all commands: reads need only ReadOnly. The per-call
- // level is refined in `permission_level_with_args`.
- PermissionLevel::ReadOnly
- }
-
- fn permission_level_with_args(&self, args: &Value) -> PermissionLevel {
- match self.command(args) {
- Some(cmd) if is_write_function(cmd) => PermissionLevel::Write,
- _ => PermissionLevel::ReadOnly,
- }
- }
-
- fn external_effect(&self) -> bool {
- false
- }
-
- fn external_effect_with_args(&self, args: &Value) -> bool {
- self.command(args).map(is_write_function).unwrap_or(false)
- }
-
- fn is_concurrency_safe(&self, args: &Value) -> bool {
- !self.command(args).map(is_write_function).unwrap_or(true)
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- fn max_result_size_chars(&self) -> Option<usize> {
- Some(48 * 1024)
- }
-}
-
-fn kind(value: &Value) -> &'static str {
- match value {
- Value::Null => "null",
- Value::Bool(_) => "boolean",
- Value::Number(_) => "number",
- Value::String(_) => "string",
- Value::Array(_) => "array",
- Value::Object(_) => "object",
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- #[test]
- fn write_commands_gate_reads_do_not() {
- let tool = RawCallTool::new();
- let write = json!({ "command": "bounties_create" });
- let read = json!({ "command": "bounties_get" });
- assert_eq!(
- tool.permission_level_with_args(&write),
- PermissionLevel::Write
- );
- assert!(tool.external_effect_with_args(&write));
- assert_eq!(
- tool.permission_level_with_args(&read),
- PermissionLevel::ReadOnly
- );
- assert!(!tool.external_effect_with_args(&read));
- assert!(tool.is_concurrency_safe(&read));
- }
-
- #[test]
- fn unknown_mutating_commands_fail_closed_to_write() {
- // A controller not in the explicit list but whose name implies mutation
- // is gated as a write (fail-closed), while an unknown read stays read.
- assert!(is_write_function("widgets_create"));
- assert!(is_write_function("foo_delete"));
- assert!(is_write_function("thing_send_message"));
- assert!(!is_write_function("widgets_get"));
- assert!(!is_write_function("widgets_list"));
- assert!(!is_write_function("directory_resolve"));
- }
-
- #[test]
- fn list_reads_are_not_gated_by_verb_substrings() {
- // These are read controllers whose names embed mutating-verb fragments;
- // they must stay reads (the real write variants are in WRITE_FUNCTIONS).
- for read in [
- "marketplace_list_bids",
- "marketplace_list_offers",
- "graphql_identity_bids",
- "graphql_identity_offers",
- "graphql_posts",
- "graphql_post_comments",
- "broadcasts_subscribers",
- ] {
- assert!(!is_write_function(read), "{read} should be a read");
- }
- // …while the actual mutations remain writes (explicit list).
- for write in ["marketplace_bid", "marketplace_offer", "feeds_create_post"] {
- assert!(is_write_function(write), "{write} should be a write");
- }
- }
-
- #[test]
- fn handler_table_covers_known_controllers() {
- let tool = RawCallTool::new();
- for cmd in [
- "directory_resolve",
- "bounties_get",
- "inbox_list",
- "registry_register",
- ] {
- assert!(tool.handlers.contains_key(cmd), "missing controller {cmd}");
- }
- }
-
- #[tokio::test]
- async fn unknown_command_is_a_clean_error() {
- let tool = RawCallTool::new();
- let result = tool
- .execute(json!({ "command": "does_not_exist" }))
- .await
- .unwrap();
- assert!(result.is_error);
- assert!(result.text().contains("Unknown command"));
- }
-}
diff --git a/src/openhuman/tinyplace/agent_tools/render.rs b/src/openhuman/tinyplace/agent_tools/render.rs
deleted file mode 100644
index 10e0693663..0000000000
--- a/src/openhuman/tinyplace/agent_tools/render.rs
+++ /dev/null
@@ -1,347 +0,0 @@
-//! Markdown rendering helpers for the tiny.place agent flow tools.
-//!
-//! The agent flow surface deliberately hands the LLM **markdown**, never raw
-//! JSON: markdown is materially cheaper in tokens and far easier for the model
-//! to act on. Every flow tool builds its result through these helpers so the
-//! formatting stays consistent across the whole surface.
-
-use serde_json::Value;
-
-/// Accumulates markdown sections into one document.
-///
-/// Thin wrapper over a `String` that keeps blank-line separation between
-/// sections uniform so individual flows don't each re-implement spacing.
-#[derive(Default)]
-pub struct Markdown {
- buf: String,
-}
-
-impl Markdown {
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Append a level-2 heading (`## title`).
- pub fn heading(&mut self, title: impl AsRef<str>) -> &mut Self {
- self.section(format!("## {}", title.as_ref().trim()))
- }
-
- /// Append a level-3 heading (`### title`).
- pub fn subheading(&mut self, title: impl AsRef<str>) -> &mut Self {
- self.section(format!("### {}", title.as_ref().trim()))
- }
-
- /// Append a free-form paragraph.
- pub fn paragraph(&mut self, text: impl AsRef<str>) -> &mut Self {
- self.section(text.as_ref().trim().to_string())
- }
-
- /// Append a bullet list. Empty lists are skipped.
- pub fn bullets<I, S>(&mut self, items: I) -> &mut Self
- where
- I: IntoIterator<Item = S>,
- S: AsRef<str>,
- {
- let rendered: Vec<String> = items
- .into_iter()
- .map(|item| format!("- {}", item.as_ref().trim()))
- .collect();
- if rendered.is_empty() {
- return self;
- }
- self.section(rendered.join("\n"))
- }
-
- /// Append a key/value definition block rendered as `**key:** value` lines.
- pub fn kv<I, K, V>(&mut self, pairs: I) -> &mut Self
- where
- I: IntoIterator<Item = (K, V)>,
- K: AsRef<str>,
- V: AsRef<str>,
- {
- let rendered: Vec<String> = pairs
- .into_iter()
- .map(|(k, v)| format!("- **{}:** {}", k.as_ref().trim(), v.as_ref().trim()))
- .collect();
- if rendered.is_empty() {
- return self;
- }
- self.section(rendered.join("\n"))
- }
-
- /// Append a markdown table. `headers` are the column titles; each row must
- /// have the same arity as `headers`. Empty `rows` renders nothing.
- pub fn table<H, R>(&mut self, headers: &[H], rows: R) -> &mut Self
- where
- H: AsRef<str>,
- R: IntoIterator<Item = Vec<String>>,
- {
- let rows: Vec<Vec<String>> = rows.into_iter().collect();
- if rows.is_empty() || headers.is_empty() {
- return self;
- }
- let header_line = format!(
- "| {} |",
- headers
- .iter()
- .map(|h| h.as_ref().trim().to_string())
- .collect::<Vec<_>>()
- .join(" | ")
- );
- let divider = format!(
- "| {} |",
- headers
- .iter()
- .map(|_| "---")
- .collect::<Vec<_>>()
- .join(" | ")
- );
- let mut lines = vec![header_line, divider];
- for row in rows {
- lines.push(format!(
- "| {} |",
- row.iter()
- .map(|cell| escape_cell(cell))
- .collect::<Vec<_>>()
- .join(" | ")
- ));
- }
- self.section(lines.join("\n"))
- }
-
- /// Append a raw, already-formatted section verbatim (used by the
- /// suggestions block and other composed fragments).
- pub fn raw_section(&mut self, section: impl Into<String>) -> &mut Self {
- let section = section.into();
- if section.trim().is_empty() {
- return self;
- }
- self.section(section)
- }
-
- fn section(&mut self, section: String) -> &mut Self {
- if !self.buf.is_empty() {
- self.buf.push_str("\n\n");
- }
- self.buf.push_str(section.trim_end());
- self
- }
-
- pub fn build(self) -> String {
- self.buf
- }
-}
-
-/// Escape a table cell so pipes and newlines don't break the row.
-fn escape_cell(cell: &str) -> String {
- cell.replace('\n', " ")
- .replace('|', "\\|")
- .trim()
- .to_string()
-}
-
-/// Render a JSON scalar to a short human string for tables/kv blocks.
-///
-/// Objects and arrays collapse to a compact one-line form so a table cell
-/// stays readable; callers that want full nesting should pull the field out
-/// explicitly instead.
-pub fn scalar(value: &Value) -> String {
- match value {
- Value::Null => "—".to_string(),
- Value::Bool(b) => b.to_string(),
- Value::Number(n) => n.to_string(),
- Value::String(s) => s.trim().to_string(),
- Value::Array(items) => format!("{} item(s)", items.len()),
- Value::Object(map) => format!("{{{} field(s)}}", map.len()),
- }
-}
-
-/// Look up a string field on a JSON object, returning `"—"` when missing so
-/// table cells are never blank.
-pub fn field(obj: &Value, key: &str) -> String {
- obj.get(key).map(scalar).unwrap_or_else(|| "—".to_string())
-}
-
-/// Truncate a body of text to `max` chars with an ellipsis, collapsing
-/// internal newlines — for feed/message previews inside a table or list.
-pub fn preview(text: &str, max: usize) -> String {
- let collapsed = text.split_whitespace().collect::<Vec<_>>().join(" ");
- if collapsed.chars().count() <= max {
- return collapsed;
- }
- let truncated: String = collapsed.chars().take(max.saturating_sub(1)).collect();
- format!("{truncated}…")
-}
-
-/// Whether a JSON value is a scalar (renders inline in a kv/table cell).
-fn is_scalar(value: &Value) -> bool {
- !matches!(value, Value::Array(_) | Value::Object(_))
-}
-
-/// Humanise a camelCase / snake_case key into a Title Case label.
-pub fn humanize_key(key: &str) -> String {
- let spaced = key
- .chars()
- .flat_map(|c| {
- if c.is_ascii_uppercase() {
- vec![' ', c.to_ascii_lowercase()]
- } else if c == '_' {
- vec![' ']
- } else {
- vec![c]
- }
- })
- .collect::<String>();
- let mut out = String::with_capacity(spaced.len());
- let mut start_word = true;
- for c in spaced.trim().chars() {
- if start_word && c.is_ascii_alphabetic() {
- out.extend(c.to_uppercase());
- start_word = false;
- } else {
- out.push(c);
- if c == ' ' {
- start_word = true;
- }
- }
- }
- out
-}
-
-/// Generic JSON → markdown renderer used by the graphql gateway and raw escape
-/// hatch (and as a flow fallback). Goes at most two levels deep so the output
-/// stays scannable:
-///
-/// * an **object** renders its scalar fields as a kv block, then each nested
-/// array/object as its own subsection;
-/// * an **array of objects** renders as a table over the union of the first
-/// row's scalar keys;
-/// * an **array of scalars** renders as a bullet list.
-pub fn render_json(value: &Value) -> String {
- let mut md = Markdown::new();
- render_into(&mut md, value, 0);
- let out = md.build();
- if out.is_empty() {
- "_(empty result)_".to_string()
- } else {
- out
- }
-}
-
-const MAX_TABLE_ROWS: usize = 40;
-
-fn render_into(md: &mut Markdown, value: &Value, depth: usize) {
- match value {
- Value::Object(map) => {
- let scalars: Vec<(String, String)> = map
- .iter()
- .filter(|(_, v)| is_scalar(v))
- .map(|(k, v)| (humanize_key(k), scalar(v)))
- .collect();
- md.kv(scalars);
- if depth >= 2 {
- return;
- }
- for (key, child) in map.iter().filter(|(_, v)| !is_scalar(v)) {
- let label = humanize_key(key);
- match child {
- Value::Array(items) if items.is_empty() => {
- md.kv([(label, "none".to_string())]);
- }
- _ => {
- md.subheading(&label);
- render_into(md, child, depth + 1);
- }
- }
- }
- }
- Value::Array(items) => {
- if items.is_empty() {
- md.paragraph("_(none)_");
- return;
- }
- let objects: Vec<&serde_json::Map<String, Value>> =
- items.iter().filter_map(Value::as_object).collect();
- if objects.len() == items.len() {
- render_table_of_objects(md, &objects);
- } else {
- md.bullets(items.iter().map(scalar));
- }
- }
- other => {
- md.paragraph(scalar(other));
- }
- }
-}
-
-fn render_table_of_objects(md: &mut Markdown, objects: &[&serde_json::Map<String, Value>]) {
- // Column set: the scalar keys of the first row (stable, predictable order).
- let headers: Vec<String> = objects[0]
- .iter()
- .filter(|(_, v)| is_scalar(v))
- .map(|(k, _)| k.clone())
- .collect();
- if headers.is_empty() {
- // Rows have no scalar fields — fall back to a compact count list.
- md.bullets(objects.iter().map(|o| format!("{{{} field(s)}}", o.len())));
- return;
- }
- let header_labels: Vec<String> = headers.iter().map(|k| humanize_key(k)).collect();
- let rows = objects.iter().take(MAX_TABLE_ROWS).map(|obj| {
- headers
- .iter()
- .map(|h| obj.get(h).map(scalar).unwrap_or_else(|| "—".to_string()))
- .collect::<Vec<_>>()
- });
- md.table(&header_labels, rows);
- if objects.len() > MAX_TABLE_ROWS {
- md.paragraph(format!(
- "_…and {} more (refine with limit/offset)_",
- objects.len() - MAX_TABLE_ROWS
- ));
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- #[test]
- fn sections_are_blank_line_separated() {
- let mut md = Markdown::new();
- md.heading("Title").paragraph("Body text.");
- assert_eq!(md.build(), "## Title\n\nBody text.");
- }
-
- #[test]
- fn empty_collections_render_nothing() {
- let mut md = Markdown::new();
- md.bullets(Vec::<String>::new())
- .table::<&str, Vec<Vec<String>>>(&["A"], vec![]);
- assert_eq!(md.build(), "");
- }
-
- #[test]
- fn table_escapes_pipes_and_newlines() {
- let mut md = Markdown::new();
- md.table(&["Col"], vec![vec!["a|b\nc".to_string()]]);
- let out = md.build();
- assert!(out.contains("a\\|b c"), "got: {out}");
- assert!(out.contains("| --- |"));
- }
-
- #[test]
- fn scalar_collapses_containers() {
- assert_eq!(scalar(&json!("hi ")), "hi");
- assert_eq!(scalar(&json!(null)), "—");
- assert_eq!(scalar(&json!([1, 2, 3])), "3 item(s)");
- assert_eq!(scalar(&json!({"a":1})), "{1 field(s)}");
- }
-
- #[test]
- fn preview_truncates_on_char_boundary() {
- assert_eq!(preview("one two three", 100), "one two three");
- assert_eq!(preview("abcdef", 4), "abc…");
- }
-}
diff --git a/src/openhuman/tinyplace/agent_tools/suggest.rs b/src/openhuman/tinyplace/agent_tools/suggest.rs
deleted file mode 100644
index bda9023a7a..0000000000
--- a/src/openhuman/tinyplace/agent_tools/suggest.rs
+++ /dev/null
@@ -1,116 +0,0 @@
-//! "Next steps" suggestion chaining for tiny.place agent flows.
-//!
-//! Mirrors the tiny.place CLI's `suggestions` array (see `flows.ts`): after a
-//! flow runs, it returns a short list of ready-to-run follow-up tool calls with
-//! IDs already filled in, so the agent can decide what to do next without
-//! re-deriving arguments. Unlike the CLI — which suggests `tinyplace …` shell
-//! commands — these suggestions reference the **agent tool surface** (the
-//! `tinyplace_*` tool names) and carry a concrete JSON argument object.
-
-use serde_json::Value;
-
-use super::render::Markdown;
-
-/// One ready-to-run follow-up the agent can take after a flow.
-#[derive(Clone, Debug)]
-pub struct Suggestion {
- /// Human-readable rationale ("Watch submissions arrive").
- pub description: String,
- /// The tool to call next (e.g. `tinyplace_submissions`).
- pub tool: String,
- /// Concrete arguments for that call, IDs pre-filled.
- pub args: Value,
-}
-
-impl Suggestion {
- pub fn new(description: impl Into<String>, tool: impl Into<String>, args: Value) -> Self {
- Self {
- description: description.into(),
- tool: tool.into(),
- args,
- }
- }
-
- /// Render a single suggestion as a markdown bullet:
- /// `- **<desc>** — call `tool` with `{json}``
- fn to_bullet(&self) -> String {
- let args = compact_args(&self.args);
- if args == "{}" {
- format!("**{}** — call `{}`", self.description.trim(), self.tool)
- } else {
- format!(
- "**{}** — call `{}` with `{}`",
- self.description.trim(),
- self.tool,
- args
- )
- }
- }
-}
-
-/// Compact single-line JSON for an args object (sorted? — serde preserves
-/// insertion order for `Map`, which is what callers build, so leave as-is).
-fn compact_args(args: &Value) -> String {
- serde_json::to_string(args).unwrap_or_else(|_| "{}".to_string())
-}
-
-/// Append a `## Next steps` section to `md` listing the suggestions. A no-op
-/// when there are none, so flows can pass an empty list unconditionally.
-pub fn append_next_steps(md: &mut Markdown, suggestions: &[Suggestion]) {
- if suggestions.is_empty() {
- return;
- }
- md.heading("Next steps");
- md.bullets(suggestions.iter().map(Suggestion::to_bullet));
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
-
- #[test]
- fn bullet_includes_tool_and_args() {
- let s = Suggestion::new(
- "Watch submissions arrive",
- "tinyplace_submissions",
- json!({ "bounty_id": "bnt_123" }),
- );
- let bullet = s.to_bullet();
- assert!(bullet.contains("Watch submissions arrive"));
- assert!(bullet.contains("`tinyplace_submissions`"));
- assert!(bullet.contains(r#"{"bounty_id":"bnt_123"}"#));
- }
-
- #[test]
- fn empty_args_render_without_with_clause() {
- let s = Suggestion::new("Confirm identity", "tinyplace_whoami", json!({}));
- assert_eq!(
- s.to_bullet(),
- "**Confirm identity** — call `tinyplace_whoami`"
- );
- }
-
- #[test]
- fn next_steps_section_is_omitted_when_empty() {
- let mut md = Markdown::new();
- append_next_steps(&mut md, &[]);
- assert_eq!(md.build(), "");
- }
-
- #[test]
- fn next_steps_section_lists_all() {
- let mut md = Markdown::new();
- append_next_steps(
- &mut md,
- &[
- Suggestion::new("A", "tinyplace_a", json!({})),
- Suggestion::new("B", "tinyplace_b", json!({ "x": 1 })),
- ],
- );
- let out = md.build();
- assert!(out.starts_with("## Next steps"));
- assert!(out.contains("`tinyplace_a`"));
- assert!(out.contains("`tinyplace_b`"));
- }
-}
diff --git a/src/openhuman/tinyplace/mod.rs b/src/openhuman/tinyplace/mod.rs
index 434ae1464a..9c5cbfd368 100644
--- a/src/openhuman/tinyplace/mod.rs
+++ b/src/openhuman/tinyplace/mod.rs
@@ -44,8 +44,6 @@
//! nowhere. The desktop feed composer links users to the web app to attach
//! media instead of dead-ending. See #4924.
-pub(crate) mod agent;
-mod agent_tools;
mod manifest;
pub(crate) use manifest::{
acknowledge_message, decrypt_envelope, ensure_signal_keys_published,
diff --git a/src/openhuman/tinyplace/tools.rs b/src/openhuman/tinyplace/tools.rs
deleted file mode 100644
index 1ab61b279a..0000000000
--- a/src/openhuman/tinyplace/tools.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-//! Public entry point for the tiny.place agent tool surface.
-//!
-//! The implementation lives in [`super::agent_tools`]: a small, curated set of
-//! flow tools plus the `tinyplace_graphql` read gateway, the `tinyplace_call`
-//! escape hatch, and the `tinyplace_help` manual — all rendering markdown in
-//! Rust. This module is a thin re-export so the registration site in
-//! `src/openhuman/tools/ops.rs` keeps its stable path.
-//!
-//! Historical note: this file previously wrapped every one of the ~160
-//! tiny.place controllers as an individual JSON-returning tool. That surface was
-//! replaced (see [`super::agent_tools`]); the controllers themselves remain
-//! registered for the desktop renderer in [`super::schemas`].
-
-pub use super::agent_tools::all_tinyplace_agent_tools;