openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(agents): route prediction-market intents via new markets_agent specialist (#2427)

Open oxoxDev opened this issue 6 months ago • 1 comments

Summary

  • Closes the agent routing gap that made #2145 (Polymarket) and #2329 (Kalshi) tools register at the RPC layer but stay invisible to the chat agent.
  • Adds a new markets_agent built-in specialist for prediction-market and event-contract trading (Polymarket + Kalshi) — modelled on crypto_agent, with its own read → browse → propose → confirm → execute safety contract.
  • Wires markets_agent into the orchestrator's subagents so a delegate_do_prediction_markets tool is auto-synthesised; venue intents now route deterministically.
  • Disallows polymarket / kalshi on tools_agent's wildcard so each capability has exactly one canonical route — through the venue-aware approval-gate prompt.
  • All-Rust change: zero touch to RPC controllers, tool implementations, backend, or frontend.

Problem

On a staging build of feat/1398-kalshi (commit e68fa585), the chat orchestrator replied to use kalshi tool to list markets with "I don't have a kalshi tool available right now. The connected integrations I can work with are github, gmail, and slack." Same response for polymarket despite #2145 having shipped that capability. Trace of the runtime delegation surface confirmed exactly 9 delegate_* tools visible to the orchestrator, none of which advertise prediction-market venues — delegate_tools_agent.when_to_use describes only "shell, file I/O, HTTP, web search, memory", so the LLM never picks it for trading intents, falls back to inspecting Composio connections, and reports "not connected."

KalshiTool and PolymarketTool are both in the tools registry (src/openhuman/tools/ops.rs:541-558) and silently sit inside tools_agent's wildcard inventory (ToolScope::Wildcard => true at tool_prep.rs:165). The capabilities exist — the routing layer can't find them, so every dollar of trading work shipped on #2145 / #2329 is functionally unreachable from chat. Hyperliquid (#1398 venue 3/3) would inherit the same gap.

Solution

Mirror the crypto_agent precedent (src/openhuman/agent/agents/crypto_agent/). New specialist markets_agent:

  • delegate_name = "do_prediction_markets" → orchestrator surfaces it as delegate_do_prediction_markets alongside delegate_do_crypto.
  • Named tool allowlist: ["polymarket", "kalshi", "memory_recall", "ask_user_clarification", "current_time"]. Hyperliquid (perps) is intentionally deferred — its routing slot (markets_agent vs crypto_agent) is decided in venue 3/3's plan.
  • Prompt enforces a read → browse → propose → confirm → execute contract anchored on the venue-level approved=true flag. Refuses on missing creds, unknown ticker shape, prices out of band (1–99c on Kalshi, 0.01–0.99 on Polymarket). Never echoes API keys / signing secrets.
  • Hard exclusions in the loader test: no shell / file_write / curl / composio_* / spawn_* / delegate_* / wallet_* — keeps blast radius bounded to the same shape as crypto_agent.

Orchestrator wiring: one new entry in orchestrator/agent.toml subagents list (between crypto_agent and the skills wildcard) with a comment explaining the route. collect_orchestrator_tools (tools/orchestrator_tools.rs) auto-emits the delegation tool — no code change there beyond a new synthesis test.

Single canonical route: tools_agent gains disallowed_tools = ["polymarket", "kalshi"]. The wildcard inventory still grants the generalist every other built-in tool, but the prediction-market venues are explicitly stripped so they route ONLY through delegate_do_prediction_markets. Without this guard the orchestrator's LLM would see two competing paths to the same capability, only one of which carries the safety preamble.

Alternatives considered + rejected

  • Extend crypto_agent to include polymarket/kalshi — conflates wallet-signing safety contract with USD market-buy contract; weakens routing signal as the blurb grows multi-topic. Crypto wallet RPCs and prediction-market REST/CLOB calls have different failure modes.
  • Tweak tools_agent.when_to_use to mention prediction markets — wildcard means every future registry tool becomes implicitly trade-routable; no venue-specific safety preamble owned by the generalist.

Submission Checklist

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy
  • [x] Diff coverage ≥ 80% — changed lines are exercised by 4 new prompt unit tests (markets_agent::prompt::tests::*), 3 new loader tests (markets_agent_has_narrow_*, orchestrator_subagents_include_markets_agent, tools_agent_disallows_prediction_market_tools), the existing all_builtins_parse count assertion (17 → 18), and 1 new orchestrator_tools synthesis test (markets_agent_subagent_synthesises_do_prediction_markets_delegate). 50 / 50 pass locally — see Validation Run below.
  • [x] N/A: Coverage matrix updated — this is a routing-layer change with no new user-facing feature ID; no rows added or renamed in docs/TEST-COVERAGE-MATRIX.md.
  • [x] N/A: All affected feature IDs from the matrix are listed in the PR description under ## Related — no matrix rows touched.
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy) — pure agent-definition wiring, no HTTP / external services added.
  • [x] N/A: Manual smoke checklist updated if this touches release-cut surfaces (docs/RELEASE-MANUAL-SMOKE.md) — Rust-only change, no release-cut surface modified; recommend a one-line addition to the smoke matrix in a follow-up once the markets_agent has run through a live trading flow on staging.
  • [x] Linked issue closed via Closes #NNN in the ## Related section — Closes #2427.

Impact

  • Runtime: desktop only (Tauri shell hosts the in-process core per #1061). No mobile/web/CLI surface change.
  • Security: prediction-market venues continue to enforce their own credential guard + approval gate; this PR just routes intents to a specialist whose prompt makes the gate mechanically enforceable (ask_user_clarification is in the allowlist, prompt requires it before approved=true).
  • Performance: one extra delegation tool (10 instead of 9) in the orchestrator's function-calling schema; trivial token impact.
  • Compatibility: net-new agent registration. Existing chat flows that already worked (composio integrations, crypto agent, planner, etc.) are untouched. tools_agent users that previously accessed polymarket / kalshi via the wildcard would be re-routed — but no callers existed (the LLM never picked that path, as the bug report shows).
  • Migration: none. Agent definitions are baked into the binary at compile time.

Related

  • Closes #2427
  • Refs #1398 — Trading integrations (Polymarket + Kalshi + Hyperliquid)
  • Refs #2145 — Polymarket merged; this PR makes the tool reachable from chat
  • Refs #2329 — Kalshi in review; this PR makes the tool reachable from chat once #2329 merges (markets_agent silently drops missing tools, so it works regardless of merge order)
  • Follow-up PR(s)/TODOs:
    • Venue 3/3 (Hyperliquid) plan must decide whether perps route through markets_agent or crypto_agent's exchange-trading surface; the slot in markets_agent's allowlist is reserved but not pre-allocated.
    • Optional: live staging smoke once the markets_agent has carried a few orders, then add a docs/RELEASE-MANUAL-SMOKE.md row.

AI Authored PR Metadata (required for Codex/Linear PRs)

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/2427-markets-agent-routing
  • Commit SHA: 6702d725 (tip; 4 GPG-signed commits off upstream/main @ bf6f25e6)

Validation Run

  • [x] pnpm --filter openhuman-app format:check — N/A: no TypeScript / app changes in this PR; pure Rust + agent definition TOML + prompt markdown.
  • [x] pnpm typecheck — N/A: same reason as above.
  • [x] Focused tests:
    • cargo test --lib agent::agents::loader → 35 passed, 0 failed in 0.04s (includes new markets_agent_has_narrow_prediction_market_tools_and_safety_on, orchestrator_subagents_include_markets_agent, tools_agent_disallows_prediction_market_tools).
    • cargo test --lib tools::orchestrator_tools → 11 passed, 0 failed in 0.00s (includes new markets_agent_subagent_synthesises_do_prediction_markets_delegate).
    • cargo test --lib agent::agents::markets_agent → 4 passed, 0 failed in 0.00s (prompt body unit tests).
  • [x] Rust fmt/check (if changed): cargo fmt --check clean; cargo check --lib clean (pre-existing warns in secrets.rs, webview_accounts/ops.rs, mcp_clients/connections.rs are unrelated and identical to the upstream/main set).
  • [x] Tauri fmt/check (if changed): N/A — Tauri shell untouched.

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: orchestrator's chat agent now routes "list / trade Polymarket / Kalshi" intents to a new specialist (markets_agent via delegate_do_prediction_markets) instead of falling back to "you don't have that integration." Both venues' approval gates are unchanged at the tool layer; the prompt makes them mechanically enforceable.
  • User-visible effect: chat prompts targeting Polymarket / Kalshi now produce real tool dispatch (cred-guard error if API creds missing, approval-required error if approved=true missing, real venue calls otherwise) instead of the misleading "no kalshi available" reply. Polymarket's gap from #2145 closes alongside Kalshi.

Parity Contract

  • Legacy behavior preserved: crypto_agent route is unchanged (test crypto_agent_has_narrow_wallet_market_tools_and_safety_on still passes); tools_agent retains every tool except the two explicitly disallowed venues; orchestrator's existing 9 delegations remain — delegate_do_prediction_markets is additive, not a replacement.
  • Guard/fallback/dispatch parity checks: the crypto_agent → do_crypto synthesis pattern is preserved (test collects_agentid_entries_and_collapses_skills_wildcard covers it); the new markets_agent → do_prediction_markets synthesis mirrors that pattern verbatim (new test asserts identical shape). Hard exclusions list on markets_agent matches crypto_agent's exclusion list (no shell / curl / wallet primitives / spawn / delegate).

Summary by CodeRabbit

  • New Features
    • Added a new Markets Agent specialized for prediction market trading on Polymarket and Kalshi exchanges.
    • Includes built-in safety constraints with user confirmation required before executing market trades.
    • Market trading operations now route through the dedicated Markets Agent for specialized handling and venue-specific approval gating.
    • Agent validates market conditions and enforces strict operational limits to prevent errors and unauthorized trades.

Review Change Stack

oxoxDev avatar May 21 '26 08:05 oxoxDev

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

google-cla[bot] avatar May 19 '26 09:05 google-cla[bot]

Hey hyzyla!

Thank you for the PR! Can you first file a feature request for this? We need to get some feedback first before proceeding with this. I will close this for now, and if the feature gets approved we can reopen it and address eventual changes!

nroscino avatar May 21 '26 14:05 nroscino