feat(agents): route prediction-market intents via new markets_agent specialist (#2427)
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_agentbuilt-in specialist for prediction-market and event-contract trading (Polymarket + Kalshi) — modelled oncrypto_agent, with its own read → browse → propose → confirm → execute safety contract. - Wires
markets_agentinto the orchestrator'ssubagentsso adelegate_do_prediction_marketstool is auto-synthesised; venue intents now route deterministically. - Disallows
polymarket/kalshiontools_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 asdelegate_do_prediction_marketsalongsidedelegate_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=trueflag. 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 ascrypto_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_agentto 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_useto 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 existingall_builtins_parsecount assertion (17 → 18), and 1 neworchestrator_toolssynthesis 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 #NNNin the## Relatedsection —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_clarificationis in the allowlist, prompt requires it beforeapproved=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_agentusers that previously accessedpolymarket/kalshivia 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_agentorcrypto_agent's exchange-trading surface; the slot inmarkets_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.mdrow.
- Venue 3/3 (Hyperliquid) plan must decide whether perps route through
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 offupstream/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 newmarkets_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 newmarkets_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 --checkclean;cargo check --libclean (pre-existing warns insecrets.rs,webview_accounts/ops.rs,mcp_clients/connections.rsare unrelated and identical to the upstream/main set). - [x] Tauri fmt/check (if changed): N/A — Tauri shell untouched.
Validation Blocked
command:N/Aerror:N/Aimpact:N/A
Behavior Changes
- Intended behavior change: orchestrator's chat agent now routes "list / trade Polymarket / Kalshi" intents to a new specialist (
markets_agentviadelegate_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=truemissing, 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_agentroute is unchanged (testcrypto_agent_has_narrow_wallet_market_tools_and_safety_onstill passes);tools_agentretains every tool except the two explicitly disallowed venues; orchestrator's existing 9 delegations remain —delegate_do_prediction_marketsis additive, not a replacement. - Guard/fallback/dispatch parity checks: the
crypto_agent → do_cryptosynthesis pattern is preserved (testcollects_agentid_entries_and_collapses_skills_wildcardcovers it); the newmarkets_agent → do_prediction_marketssynthesis mirrors that pattern verbatim (new test asserts identical shape). Hard exclusions list onmarkets_agentmatchescrypto_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.
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.
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!