polyrob 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agents/README.md +453 -0
- agents/__init__.py +164 -0
- agents/base_agent.py +743 -0
- agents/personality/character.py +119 -0
- agents/personality/character_manager.py +309 -0
- agents/personality/characters/rob.character.json +56 -0
- agents/personality/characters/trump.character.json +63 -0
- agents/personality/persona_render.py +78 -0
- agents/personality/persona_resolver.py +115 -0
- agents/prompt/__init__.py +58 -0
- agents/prompt/base_prompt.py +92 -0
- agents/prompt/system.py +417 -0
- agents/task/README_PATH_MANAGEMENT.md +141 -0
- agents/task/__init__.py +162 -0
- agents/task/agent/__init__.py +70 -0
- agents/task/agent/agent_state.py +408 -0
- agents/task/agent/async_delegation.py +274 -0
- agents/task/agent/autonomy_state.py +275 -0
- agents/task/agent/conversation.py +75 -0
- agents/task/agent/core/__init__.py +6 -0
- agents/task/agent/core/aux_metering.py +61 -0
- agents/task/agent/core/background_review.py +157 -0
- agents/task/agent/core/construction.py +1179 -0
- agents/task/agent/core/conversational_exit.py +49 -0
- agents/task/agent/core/correspondent_gate.py +227 -0
- agents/task/agent/core/curator.py +246 -0
- agents/task/agent/core/episodic_digest.py +103 -0
- agents/task/agent/core/error_recovery.py +480 -0
- agents/task/agent/core/history_io.py +257 -0
- agents/task/agent/core/llm_provisioning.py +287 -0
- agents/task/agent/core/llm_runner.py +547 -0
- agents/task/agent/core/logging_io.py +276 -0
- agents/task/agent/core/loop_detection.py +262 -0
- agents/task/agent/core/memory_prefetch.py +325 -0
- agents/task/agent/core/memory_writer.py +667 -0
- agents/task/agent/core/model_introspection.py +82 -0
- agents/task/agent/core/model_swap.py +177 -0
- agents/task/agent/core/next_action_internal.py +1331 -0
- agents/task/agent/core/output_validation.py +303 -0
- agents/task/agent/core/project_context.py +272 -0
- agents/task/agent/core/resources.py +93 -0
- agents/task/agent/core/result_processing.py +389 -0
- agents/task/agent/core/run_loop.py +661 -0
- agents/task/agent/core/safety_lifecycle.py +228 -0
- agents/task/agent/core/secret_guard.py +293 -0
- agents/task/agent/core/self_wake.py +280 -0
- agents/task/agent/core/session_metadata.py +104 -0
- agents/task/agent/core/step.py +781 -0
- agents/task/agent/core/step_execution.py +398 -0
- agents/task/agent/core/step_telemetry.py +222 -0
- agents/task/agent/core/test_aux_metering.py +50 -0
- agents/task/agent/core/test_billing_failover.py +68 -0
- agents/task/agent/core/test_fatal_error_classifier.py +38 -0
- agents/task/agent/core/test_judge_validation.py +275 -0
- agents/task/agent/core/test_model_swap.py +190 -0
- agents/task/agent/core/test_reflection_offload.py +54 -0
- agents/task/agent/core/turn_input.py +8 -0
- agents/task/agent/core/untrusted_wrap.py +103 -0
- agents/task/agent/core/user_ingress.py +228 -0
- agents/task/agent/hitl_manager.py +396 -0
- agents/task/agent/log_sanitize.py +36 -0
- agents/task/agent/message_manager/config.py +97 -0
- agents/task/agent/message_manager/service.py +758 -0
- agents/task/agent/message_manager/tests.py +305 -0
- agents/task/agent/message_manager/tool_call_builder.py +539 -0
- agents/task/agent/message_manager/tool_message_repair.py +364 -0
- agents/task/agent/message_manager/views.py +143 -0
- agents/task/agent/messages/__init__.py +8 -0
- agents/task/agent/messages/builders.py +309 -0
- agents/task/agent/messages/compactor.py +611 -0
- agents/task/agent/messages/context_references.py +271 -0
- agents/task/agent/messages/filters.py +333 -0
- agents/task/agent/messages/guidance.py +328 -0
- agents/task/agent/messages/persistence.py +448 -0
- agents/task/agent/messages/retrieval.py +506 -0
- agents/task/agent/messages/sqlite_persistence.py +85 -0
- agents/task/agent/messages/test_compaction_upgrade.py +349 -0
- agents/task/agent/messages/test_persistence_subdir_fix.py +28 -0
- agents/task/agent/messages/test_sqlite_persistence.py +54 -0
- agents/task/agent/messages/token_counter.py +532 -0
- agents/task/agent/orchestrator.py +776 -0
- agents/task/agent/profile_manager.py +105 -0
- agents/task/agent/profile_registry.py +173 -0
- agents/task/agent/prompts.py +1090 -0
- agents/task/agent/scenario_registry.py +226 -0
- agents/task/agent/service.py +509 -0
- agents/task/agent/session.py +984 -0
- agents/task/agent/skill_discovery.py +110 -0
- agents/task/agent/skill_frontmatter.py +94 -0
- agents/task/agent/skill_manager.py +1201 -0
- agents/task/agent/skill_store.py +627 -0
- agents/task/agent/skill_validation.py +56 -0
- agents/task/agent/skill_writer.py +492 -0
- agents/task/agent/sub_agent_manager.py +1137 -0
- agents/task/agent/test_session_disk_recovery.py +34 -0
- agents/task/agent/tests.py +513 -0
- agents/task/agent/tool_call_tracker.py +511 -0
- agents/task/agent/views.py +469 -0
- agents/task/config.py +432 -0
- agents/task/constants.py +1384 -0
- agents/task/flag_defaults.py +63 -0
- agents/task/goals/__init__.py +1 -0
- agents/task/goals/autonomy_marker.py +28 -0
- agents/task/goals/board.py +690 -0
- agents/task/goals/completion_judge.py +247 -0
- agents/task/goals/context.py +62 -0
- agents/task/goals/dispatcher.py +848 -0
- agents/task/goals/escalation.py +102 -0
- agents/task/goals/planner.py +114 -0
- agents/task/logging_config.py +155 -0
- agents/task/path.py +991 -0
- agents/task/robust_parse_config.py +400 -0
- agents/task/runtime/__init__.py +0 -0
- agents/task/runtime/run_as_session.py +130 -0
- agents/task/runtime_safety.py +308 -0
- agents/task/session/__init__.py +5 -0
- agents/task/session/browser_pool.py +130 -0
- agents/task/session/cleanup.py +612 -0
- agents/task/session/execution.py +397 -0
- agents/task/session/feed.py +200 -0
- agents/task/session/hitl_ingress.py +201 -0
- agents/task/session/hooks.py +83 -0
- agents/task/session/multi_agent.py +243 -0
- agents/task/session/workspace.py +91 -0
- agents/task/session_registry.py +91 -0
- agents/task/session_route.py +35 -0
- agents/task/sqlite_session_registry.py +261 -0
- agents/task/surface_config.py +185 -0
- agents/task/telemetry/__init__.py +58 -0
- agents/task/telemetry/event_log.py +180 -0
- agents/task/telemetry/formatters.py +642 -0
- agents/task/telemetry/manager.py +571 -0
- agents/task/telemetry/memory_events.py +66 -0
- agents/task/telemetry/self_events.py +53 -0
- agents/task/telemetry/sequence.py +160 -0
- agents/task/telemetry/service.py +1265 -0
- agents/task/telemetry/views.py +882 -0
- agents/task/templates.py +98 -0
- agents/task/test_aux_chain.py +151 -0
- agents/task/test_aux_router.py +41 -0
- agents/task/tests/test_parse_robustness.py +170 -0
- agents/task/tool_defaults.py +110 -0
- agents/task/utils.py +762 -0
- agents/task/utils_json.py +768 -0
- agents/task/utils_webview.py +86 -0
- agents/task/workspace_context.py +229 -0
- agents/task_agent_lite.py +2398 -0
- api/README.md +683 -0
- api/TASK_API_DOCS.md +151 -0
- api/__init__.py +0 -0
- api/a2a/__init__.py +37 -0
- api/a2a/agent_card.py +337 -0
- api/a2a/client.py +657 -0
- api/a2a/endpoints.py +375 -0
- api/a2a/models.py +268 -0
- api/a2a/streaming.py +419 -0
- api/a2a/task_handler.py +929 -0
- api/admin_endpoints.py +1584 -0
- api/app.py +923 -0
- api/auth_constants.py +28 -0
- api/auth_endpoints.py +402 -0
- api/auth_state.py +36 -0
- api/chat_via_task.py +42 -0
- api/conversation_manager.py +231 -0
- api/dependencies.py +186 -0
- api/eip8004_endpoints.py +452 -0
- api/hyperliquid_models.py +174 -0
- api/hyperliquid_routes.py +450 -0
- api/interfaces.py +207 -0
- api/jwt_middleware.py +83 -0
- api/kb/__init__.py +1 -0
- api/kb/endpoints.py +314 -0
- api/mcp_models.py +279 -0
- api/mcp_routes.py +438 -0
- api/middleware.py +526 -0
- api/models.py +176 -0
- api/openai_compat/__init__.py +0 -0
- api/openai_compat/model_map.py +25 -0
- api/openai_compat/models.py +59 -0
- api/openai_compat/router.py +140 -0
- api/payment_endpoints.py +444 -0
- api/payment_verification.py +138 -0
- api/polymarket_models.py +155 -0
- api/polymarket_routes.py +501 -0
- api/pricing_endpoints.py +89 -0
- api/session_routing.py +54 -0
- api/skill_endpoints.py +453 -0
- api/task_http_api.py +1856 -0
- api/webhooks.py +52 -0
- api/x402_endpoints.py +280 -0
- avatar/README.md +44 -0
- avatar/__init__.py +1 -0
- avatar/config/rob.json +7 -0
- avatar/mindprint.js +395 -0
- avatar/renders/rob.meta.json +20 -0
- avatar/renders/rob.png +0 -0
- avatar/studio.html +373 -0
- avatar/webview/avatar-live.js +44 -0
- cli/README.md +89 -0
- cli/__init__.py +0 -0
- cli/cli_surface.py +67 -0
- cli/commands/__init__.py +0 -0
- cli/commands/_bootstrap.py +49 -0
- cli/commands/_errors.py +53 -0
- cli/commands/chat.py +973 -0
- cli/commands/config.py +100 -0
- cli/commands/dashboard.py +103 -0
- cli/commands/doctor.py +222 -0
- cli/commands/email.py +174 -0
- cli/commands/gateway.py +346 -0
- cli/commands/goals.py +509 -0
- cli/commands/init.py +276 -0
- cli/commands/journey.py +30 -0
- cli/commands/kb.py +280 -0
- cli/commands/model.py +107 -0
- cli/commands/owner.py +431 -0
- cli/commands/pfp.py +232 -0
- cli/commands/run.py +414 -0
- cli/commands/serve.py +41 -0
- cli/commands/session.py +684 -0
- cli/commands/skill_install.py +786 -0
- cli/commands/skills.py +128 -0
- cli/commands/subagents.py +100 -0
- cli/commands/surface.py +81 -0
- cli/commands/telegram.py +185 -0
- cli/commands/todos.py +209 -0
- cli/commands/tools.py +102 -0
- cli/commands/update.py +316 -0
- cli/commands/whatsapp.py +175 -0
- cli/config_store.py +276 -0
- cli/gitignore.py +43 -0
- cli/inventory.py +46 -0
- cli/keys.py +101 -0
- cli/persona.py +17 -0
- cli/polyrob.py +137 -0
- cli/ui/__init__.py +64 -0
- cli/ui/activity.py +141 -0
- cli/ui/app.py +538 -0
- cli/ui/banner.py +233 -0
- cli/ui/blocks.py +534 -0
- cli/ui/bootstrap_notice.py +47 -0
- cli/ui/commands/__init__.py +41 -0
- cli/ui/commands/h_cron.py +64 -0
- cli/ui/commands/h_journey.py +164 -0
- cli/ui/commands/h_kb.py +121 -0
- cli/ui/commands/h_learn.py +100 -0
- cli/ui/commands/h_mcp.py +215 -0
- cli/ui/commands/h_self.py +113 -0
- cli/ui/commands/h_skills.py +314 -0
- cli/ui/commands/handlers.py +1672 -0
- cli/ui/commands/registry.py +426 -0
- cli/ui/dialog.py +425 -0
- cli/ui/event_registry.py +110 -0
- cli/ui/event_specs.py +45 -0
- cli/ui/events.py +433 -0
- cli/ui/identity.py +15 -0
- cli/ui/lifecycle.py +159 -0
- cli/ui/live_hooks.py +43 -0
- cli/ui/model_selector.py +532 -0
- cli/ui/persistent_loop.py +181 -0
- cli/ui/pick.py +113 -0
- cli/ui/plain_renderer.py +351 -0
- cli/ui/renderer.py +384 -0
- cli/ui/rich_renderer.py +533 -0
- cli/ui/secrets.py +115 -0
- cli/ui/state.py +376 -0
- cli/ui/statusbar.py +231 -0
- cli/ui/streaming.py +254 -0
- cli/ui/terminal_render.py +105 -0
- cli/ui/theme.py +132 -0
- cli/update/__init__.py +6 -0
- cli/update/context.py +121 -0
- cli/update/detect.py +176 -0
- cli/update/engine.py +95 -0
- cli/update/migrate_guarded.py +55 -0
- cli/update/process_guard.py +215 -0
- cli/update/runners.py +78 -0
- cli/update/snapshot.py +270 -0
- cli/update/versions.py +205 -0
- core/README.md +377 -0
- core/__init__.py +174 -0
- core/assets.py +87 -0
- core/async_bridge.py +76 -0
- core/autonomy_runtime.py +259 -0
- core/base_component.py +302 -0
- core/bootstrap.py +681 -0
- core/bot.py +310 -0
- core/config.py +833 -0
- core/constants.py +126 -0
- core/container.py +462 -0
- core/db_manifest.py +101 -0
- core/embedding.py +57 -0
- core/env.py +39 -0
- core/exceptions.py +287 -0
- core/flags.py +144 -0
- core/flags_catalog.py +345 -0
- core/home_migration.py +62 -0
- core/identity.py +118 -0
- core/initialization.py +1004 -0
- core/instance.py +537 -0
- core/interactive_gate.py +96 -0
- core/logging.py +436 -0
- core/owner_doc_writer.py +176 -0
- core/pairing.py +193 -0
- core/path_safety.py +20 -0
- core/paths.py +27 -0
- core/payment_config.py +21 -0
- core/permissions.py +322 -0
- core/runtime_config.py +96 -0
- core/runtime_paths.py +135 -0
- core/seams.py +35 -0
- core/secret_scan.py +25 -0
- core/secret_scrub.py +71 -0
- core/secrets.py +35 -0
- core/security_logging_filter.py +148 -0
- core/self_context_writer.py +333 -0
- core/self_evolution.py +294 -0
- core/session_context.py +47 -0
- core/sqlite_util.py +59 -0
- core/surfaces/__init__.py +16 -0
- core/surfaces/access.py +118 -0
- core/surfaces/binding.py +88 -0
- core/surfaces/bootstrap.py +78 -0
- core/surfaces/circuit.py +168 -0
- core/surfaces/continuity.py +77 -0
- core/surfaces/correspondents.py +228 -0
- core/surfaces/dispatcher.py +216 -0
- core/surfaces/envelopes.py +75 -0
- core/surfaces/gc.py +30 -0
- core/surfaces/idempotency.py +57 -0
- core/surfaces/inbound_webhook.py +124 -0
- core/surfaces/media.py +32 -0
- core/surfaces/message_router.py +91 -0
- core/surfaces/outbound_allowlist.py +80 -0
- core/surfaces/outbound_dispatcher.py +110 -0
- core/surfaces/outbound_mirror.py +37 -0
- core/surfaces/outbound_queue.py +107 -0
- core/surfaces/outbound_target.py +12 -0
- core/surfaces/owner_admin.py +29 -0
- core/surfaces/proactive.py +78 -0
- core/surfaces/progress.py +108 -0
- core/surfaces/rate_bucket.py +21 -0
- core/surfaces/registry.py +51 -0
- core/surfaces/rendering.py +53 -0
- core/surfaces/send_policy.py +14 -0
- core/surfaces/serialize.py +24 -0
- core/surfaces/session_chat_registry.py +112 -0
- core/surfaces/session_policy.py +60 -0
- core/surfaces/surface.py +288 -0
- core/surfaces/transcription.py +88 -0
- core/surfaces/voice_echo.py +26 -0
- core/surfaces/voice_guard.py +23 -0
- core/tickers.py +174 -0
- core/tool_catalog.py +192 -0
- core/version.py +75 -0
- core/wallet/__init__.py +5 -0
- core/wallet/agent_wallet.py +59 -0
- core/wallet/audit_sink.py +61 -0
- core/wallet/config.py +70 -0
- core/wallet/factory.py +87 -0
- core/wallet/policy.py +104 -0
- core/wallet/signer.py +51 -0
- cron/README.md +65 -0
- cron/__init__.py +0 -0
- cron/delivery.py +277 -0
- cron/digest.py +124 -0
- cron/jobs.py +207 -0
- cron/runner.py +297 -0
- cron/schedule.py +194 -0
- cron/scheduler.py +201 -0
- cron/service.py +57 -0
- cron/wake_gate.py +223 -0
- data/__init__.py +1 -0
- data/prompts/autov2_prompts.json +87 -0
- data/prompts/skills/browser-automation/SKILL.md +43 -0
- data/prompts/skills/coding-workflow/SKILL.md +36 -0
- data/prompts/skills/crypto-trading-safety/SKILL.md +53 -0
- data/prompts/skills/document-writing/SKILL.md +33 -0
- data/prompts/skills/email-comms/SKILL.md +33 -0
- data/prompts/skills/file-data-ops/SKILL.md +35 -0
- data/prompts/skills/hyperliquid-account-review/SKILL.md +48 -0
- data/prompts/skills/hyperliquid-market-data/SKILL.md +52 -0
- data/prompts/skills/hyperliquid-trading/SKILL.md +59 -0
- data/prompts/skills/lead-research/SKILL.md +86 -0
- data/prompts/skills/market-research-brief/SKILL.md +104 -0
- data/prompts/skills/person-analyzer/SKILL.md +124 -0
- data/prompts/skills/polymarket-market-research/SKILL.md +54 -0
- data/prompts/skills/polymarket-portfolio-review/SKILL.md +50 -0
- data/prompts/skills/polymarket-trading/SKILL.md +55 -0
- data/prompts/skills/presentation-creator/SKILL.md +36 -0
- data/prompts/skills/project-analyzer/SKILL.md +169 -0
- data/prompts/skills/rules.json +268 -0
- data/prompts/skills/secret-handling/SKILL.md +20 -0
- data/prompts/skills/skill-authoring/SKILL.md +31 -0
- data/prompts/skills/skill-security-review/SKILL.md +27 -0
- data/prompts/skills/social-discovery/SKILL.md +57 -0
- data/prompts/skills/task-planning/SKILL.md +33 -0
- data/prompts/skills/web-research/SKILL.md +39 -0
- data/prompts/skills/web-scraping/SKILL.md +73 -0
- data/prompts/skills/x-engagement/SKILL.md +69 -0
- data/prompts/system_prompts.json +4 -0
- data/subscription_channels.json +5 -0
- modules/README.md +503 -0
- modules/__init__.py +124 -0
- modules/auth/__init__.py +13 -0
- modules/auth/api_key_manager.py +157 -0
- modules/auth/identity_mapper.py +380 -0
- modules/auth/siwe_auth.py +273 -0
- modules/auth/tier_manager.py +173 -0
- modules/base_module.py +190 -0
- modules/credits/__init__.py +29 -0
- modules/credits/balance_manager.py +237 -0
- modules/credits/cost_utils.py +129 -0
- modules/credits/pricing.py +139 -0
- modules/credits/unified_ledger.py +148 -0
- modules/credits/usage_meter.py +310 -0
- modules/credits/usage_tracker.py +674 -0
- modules/database/__init__.py +33 -0
- modules/database/audit_log.py +322 -0
- modules/database/auth_tables.py +276 -0
- modules/database/connection.py +644 -0
- modules/database/connection_pool.py +305 -0
- modules/database/conversation_contexts.py +446 -0
- modules/database/database_manager.py +237 -0
- modules/database/hyperliquid.py +375 -0
- modules/database/polymarket.py +574 -0
- modules/database/user_mcp_servers.py +728 -0
- modules/database/user_profiles.py +562 -0
- modules/database/utils.py +107 -0
- modules/database/x402_tables.py +92 -0
- modules/eip8004/README.md +1069 -0
- modules/eip8004/__init__.py +65 -0
- modules/eip8004/contracts.py +498 -0
- modules/eip8004/models.py +271 -0
- modules/eip8004/registration.py +148 -0
- modules/eip8004/reputation.py +367 -0
- modules/eip8004/validation.py +277 -0
- modules/llm/__init__.py +97 -0
- modules/llm/adapters.py +963 -0
- modules/llm/anthropic_client.py +831 -0
- modules/llm/available_models.py +106 -0
- modules/llm/brain_scrubber.py +137 -0
- modules/llm/cache_hints.py +162 -0
- modules/llm/deepseek_client.py +562 -0
- modules/llm/gemini_client.py +1367 -0
- modules/llm/llm_client.py +1139 -0
- modules/llm/llm_client_registry.py +188 -0
- modules/llm/llm_factory.py +237 -0
- modules/llm/llm_manager.py +1036 -0
- modules/llm/messages.py +374 -0
- modules/llm/model_registry.py +1935 -0
- modules/llm/nvidia_client.py +125 -0
- modules/llm/openai_client.py +800 -0
- modules/llm/openrouter_client.py +969 -0
- modules/llm/profiles.py +178 -0
- modules/llm/test_anthropic_cache_capture.py +35 -0
- modules/llm/test_cached_pricing_derivation.py +24 -0
- modules/llm/think_scrubber.py +444 -0
- modules/llm/token_counter.py +268 -0
- modules/memory/__init__.py +35 -0
- modules/memory/backend_factory.py +83 -0
- modules/memory/cache_manager.py +186 -0
- modules/memory/episodic.py +108 -0
- modules/memory/local_vector_memory_provider.py +552 -0
- modules/memory/memory_manager.py +225 -0
- modules/memory/models.py +312 -0
- modules/memory/provider.py +210 -0
- modules/memory/registry.py +205 -0
- modules/memory/sqlite_memory_provider.py +767 -0
- modules/memory/task/__init__.py +52 -0
- modules/memory/task/compaction_manager.py +157 -0
- modules/memory/task/context_retriever.py +809 -0
- modules/memory/task/hierarchical_memory.py +1002 -0
- modules/memory/task/lexical_retriever.py +71 -0
- modules/memory/task/null_context_manager.py +213 -0
- modules/memory/task/phase_manager.py +625 -0
- modules/memory/task/reflection_service.py +157 -0
- modules/memory/task/semantic_retriever.py +218 -0
- modules/memory/task/task_context_manager.py +1165 -0
- modules/memory/task/test_forgetting_engages.py +24 -0
- modules/memory/task/test_reflection_llm.py +39 -0
- modules/memory/task/test_threat_scan.py +53 -0
- modules/memory/task/threat_scan.py +90 -0
- modules/memory/test_sqlite_memory_provider.py +106 -0
- modules/memory/user_profile_manager.py +527 -0
- modules/payments/__init__.py +11 -0
- modules/payments/deposit_monitor.py +478 -0
- modules/payments/price_oracle.py +70 -0
- modules/payments/treasury_sweeper.py +401 -0
- modules/payments/wallet_generator.py +145 -0
- modules/pfp/__init__.py +1 -0
- modules/pfp/config.py +92 -0
- modules/pfp/mesh.py +565 -0
- modules/pfp/push.py +69 -0
- modules/pfp/renderer.py +85 -0
- modules/pfp/store.py +82 -0
- modules/skills/__init__.py +1 -0
- modules/skills/skill_usage.py +248 -0
- modules/transcription/__init__.py +24 -0
- modules/transcription/base.py +20 -0
- modules/transcription/faster_whisper_transcriber.py +55 -0
- modules/x402/README.md +249 -0
- modules/x402/__init__.py +22 -0
- modules/x402/invoicing.py +416 -0
- modules/x402/middleware.py +364 -0
- modules/x402/settlement_watcher.py +145 -0
- modules/x402/x402_integration.py +344 -0
- polyrob-0.5.0.dist-info/METADATA +482 -0
- polyrob-0.5.0.dist-info/RECORD +745 -0
- polyrob-0.5.0.dist-info/WHEEL +5 -0
- polyrob-0.5.0.dist-info/entry_points.txt +2 -0
- polyrob-0.5.0.dist-info/licenses/LICENSE +21 -0
- polyrob-0.5.0.dist-info/top_level.txt +12 -0
- surfaces/README.md +70 -0
- surfaces/__init__.py +0 -0
- surfaces/email/__init__.py +0 -0
- surfaces/email/dedup.py +44 -0
- surfaces/email/harness.py +187 -0
- surfaces/email/inbound.py +159 -0
- surfaces/email/seed.py +60 -0
- surfaces/email/surface.py +105 -0
- surfaces/telegram/__init__.py +0 -0
- surfaces/telegram/dedup.py +83 -0
- surfaces/telegram/harness.py +886 -0
- surfaces/telegram/inbound.py +145 -0
- surfaces/telegram/interactive_tools.py +49 -0
- surfaces/telegram/markdown.py +347 -0
- surfaces/telegram/rate_limit.py +167 -0
- surfaces/telegram/surface.py +187 -0
- surfaces/telegram/voice.py +52 -0
- surfaces/whatsapp/__init__.py +0 -0
- surfaces/whatsapp/client.py +51 -0
- surfaces/whatsapp/harness.py +62 -0
- surfaces/whatsapp/inbound.py +132 -0
- surfaces/whatsapp/surface.py +64 -0
- surfaces/whatsapp/window.py +34 -0
- tools/README.md +578 -0
- tools/__init__.py +424 -0
- tools/alchemy/__init__.py +5 -0
- tools/alchemy/alchemy_tool.py +389 -0
- tools/anysite/__init__.py +17 -0
- tools/anysite/client.py +88 -0
- tools/anysite/tool.py +89 -0
- tools/base_tool.py +468 -0
- tools/browser/__init__.py +22 -0
- tools/browser/actions.py +118 -0
- tools/browser/browser.py +1457 -0
- tools/browser/browser_manager.py +690 -0
- tools/browser/context.py +1748 -0
- tools/browser/playwright_utils.py +137 -0
- tools/browser/views.py +56 -0
- tools/code_exec/SANDBOX_SECURITY.md +144 -0
- tools/code_exec/__init__.py +178 -0
- tools/code_exec/backend.py +73 -0
- tools/code_exec/backends/__init__.py +1 -0
- tools/code_exec/backends/docker.py +779 -0
- tools/code_exec/backends/local_subprocess.py +154 -0
- tools/code_exec/env_policy.py +45 -0
- tools/code_exec/result.py +42 -0
- tools/code_exec/sandbox_guard.py +59 -0
- tools/code_exec/tool.py +227 -0
- tools/coding/__init__.py +50 -0
- tools/coding/edit.py +107 -0
- tools/coding/search.py +113 -0
- tools/coding/tool.py +353 -0
- tools/collabland/__init__.py +5 -0
- tools/collabland/collabland_tool.py +471 -0
- tools/controller/__init__.py +0 -0
- tools/controller/_helpers.py +165 -0
- tools/controller/action_registration.py +1765 -0
- tools/controller/approval.py +244 -0
- tools/controller/approval_interactive.py +90 -0
- tools/controller/delegation.py +195 -0
- tools/controller/execution.py +797 -0
- tools/controller/execution_context.py +141 -0
- tools/controller/hooks.py +135 -0
- tools/controller/introspection.py +344 -0
- tools/controller/mcp_registrar.py +190 -0
- tools/controller/message_send.py +31 -0
- tools/controller/registry/__init__.py +4 -0
- tools/controller/registry/schema_generators.py +395 -0
- tools/controller/registry/schema_sanitizer.py +406 -0
- tools/controller/registry/service.py +1266 -0
- tools/controller/registry/views.py +151 -0
- tools/controller/service.py +409 -0
- tools/controller/tool_management.py +334 -0
- tools/controller/types.py +28 -0
- tools/controller/views.py +450 -0
- tools/cronjob_tools.py +166 -0
- tools/crypto_trade_gate.py +59 -0
- tools/descriptors.py +452 -0
- tools/dom/__init__.py +0 -0
- tools/dom/history_tree_processor/service.py +244 -0
- tools/dom/history_tree_processor/view.py +99 -0
- tools/dom/service.py +471 -0
- tools/dom/views.py +346 -0
- tools/email_tool.py +403 -0
- tools/exceptions.py +169 -0
- tools/filesystem.py +1038 -0
- tools/filesystem_docproc.py +331 -0
- tools/filesystem_pdf.py +755 -0
- tools/git/__init__.py +42 -0
- tools/git/tool.py +258 -0
- tools/github/__init__.py +33 -0
- tools/github/client.py +94 -0
- tools/github/tool.py +237 -0
- tools/goal_tools.py +309 -0
- tools/hyperliquid/__init__.py +56 -0
- tools/hyperliquid/models.py +233 -0
- tools/hyperliquid/service.py +1680 -0
- tools/knowledge_ingest.py +950 -0
- tools/mcp/README.md +535 -0
- tools/mcp/__init__.py +52 -0
- tools/mcp/catalog.py +115 -0
- tools/mcp/config.py +337 -0
- tools/mcp/mcp_tool.py +1415 -0
- tools/mcp/param_coercion.py +289 -0
- tools/mcp/protocol.py +1520 -0
- tools/mcp/rate_limit.py +50 -0
- tools/mcp/security.py +424 -0
- tools/mcp/self_install.py +111 -0
- tools/mcp/server_manager.py +829 -0
- tools/mcp/subscriptions.py +72 -0
- tools/mcp/user_mcp_service.py +899 -0
- tools/mcp/validation_tracker.py +89 -0
- tools/mcp/views.py +346 -0
- tools/oauth/__init__.py +17 -0
- tools/oauth/manager.py +75 -0
- tools/oauth/provider.py +69 -0
- tools/oauth/providers/__init__.py +1 -0
- tools/oauth/providers/generic_oauth2.py +96 -0
- tools/perplexity_tool.py +280 -0
- tools/polymarket/__init__.py +41 -0
- tools/polymarket/clob_adapter.py +76 -0
- tools/polymarket/models.py +182 -0
- tools/polymarket/service.py +2082 -0
- tools/self_env/__init__.py +61 -0
- tools/self_env/tool.py +274 -0
- tools/shell/__init__.py +80 -0
- tools/shell/backend_pool.py +118 -0
- tools/shell/discipline.py +62 -0
- tools/shell/executor.py +157 -0
- tools/shell/loopback_allow.py +87 -0
- tools/shell/process_registry.py +113 -0
- tools/shell/process_tool.py +131 -0
- tools/shell/state.py +129 -0
- tools/shell/tool.py +151 -0
- tools/task_tool.py +637 -0
- tools/twitter_tool.py +2086 -0
- tools/user_directory.py +179 -0
- tools/web_fetch/__init__.py +3 -0
- tools/web_fetch/fetcher.py +144 -0
- tools/web_fetch/render.py +44 -0
- tools/web_fetch/tool.py +60 -0
- tools/x402/__init__.py +60 -0
- tools/x402/client.py +47 -0
- tools/x402/invoice_tool.py +143 -0
- tools/x402/real_client.py +250 -0
- tools/x402/service.py +131 -0
- utils/README.md +498 -0
- utils/__init__.py +46 -0
- utils/auth_utils.py +114 -0
- utils/bounded_collections.py +162 -0
- utils/circuit_breaker.py +389 -0
- utils/gif_utils.py +435 -0
- utils/markdown_utils.py +291 -0
- utils/message_utils.py +147 -0
- utils/metrics.py +36 -0
- utils/path_validator.py +227 -0
- utils/rate_limit_manager.py +399 -0
- utils/result_size.py +296 -0
- utils/time_utils.py +206 -0
- utils/user_utils.py +188 -0
- webview/README.md +111 -0
- webview/RENAME_AND_ALIGN_HANDOFF.md +200 -0
- webview/__init__.py +8 -0
- webview/activity.py +636 -0
- webview/owner_auth.py +108 -0
- webview/pages.py +448 -0
- webview/repair_sessions.py +399 -0
- webview/server.py +4323 -0
- webview/server_launcher.py +112 -0
- webview/static/css/activity.css +89 -0
- webview/static/css/chat.css +1772 -0
- webview/static/css/components.css +1190 -0
- webview/static/css/config-panel.css +651 -0
- webview/static/css/pages/admin.css +766 -0
- webview/static/css/pages/profile.css +231 -0
- webview/static/css/pages/settings.css +297 -0
- webview/static/css/pages/signin.css +316 -0
- webview/static/css/style.css +4250 -0
- webview/static/css/variables.css +147 -0
- webview/static/css/workspace-fullwidth-fix.css +109 -0
- webview/static/img/favicon.ico +0 -0
- webview/static/js/activity.js +394 -0
- webview/static/js/admin/activity.js +186 -0
- webview/static/js/admin/dashboard.js +163 -0
- webview/static/js/admin/user_detail.js +400 -0
- webview/static/js/admin/users.js +174 -0
- webview/static/js/admin/utils.js +214 -0
- webview/static/js/chat.js +3178 -0
- webview/static/js/config-panel.js +522 -0
- webview/static/js/constants.js +20 -0
- webview/static/js/error-handler.js +226 -0
- webview/static/js/ethers.min.js +1 -0
- webview/static/js/event-filter.js +137 -0
- webview/static/js/event-store.js +351 -0
- webview/static/js/file-attachments.js +374 -0
- webview/static/js/file-loader.js +163 -0
- webview/static/js/index.js +103 -0
- webview/static/js/performance-utils.js +196 -0
- webview/static/js/profile.js +396 -0
- webview/static/js/screenshot.js +386 -0
- webview/static/js/session.js +1527 -0
- webview/static/js/settings.js +1288 -0
- webview/static/js/sidebar-data.js +766 -0
- webview/static/js/sidebar-toggle.js +296 -0
- webview/static/js/socket.io.min.js +7 -0
- webview/static/js/stats.js +355 -0
- webview/static/js/ui-utils.js +420 -0
- webview/static/js/workspace.js +966 -0
- webview/stats_service.py +613 -0
- webview/templates/__init__.py +1 -0
- webview/templates/__pycache__/__init__.cpython-311.pyc +0 -0
- webview/templates/activity.html +36 -0
- webview/templates/admin/activity.html +122 -0
- webview/templates/admin/dashboard.html +112 -0
- webview/templates/admin/user_detail.html +228 -0
- webview/templates/admin/users.html +105 -0
- webview/templates/autonomy.html +60 -0
- webview/templates/error.html +133 -0
- webview/templates/finance.html +90 -0
- webview/templates/identity.html +73 -0
- webview/templates/index.html +42 -0
- webview/templates/layout.html +125 -0
- webview/templates/memory.html +59 -0
- webview/templates/owner_login.html +15 -0
- webview/templates/profile.html +121 -0
- webview/templates/session.html +312 -0
- webview/templates/settings.html +534 -0
- webview/templates/sidebar.html +112 -0
- webview/templates/signin.html +213 -0
- webview/templates/status.html +14 -0
- webview/templates/system.html +45 -0
- webview/webgate.py +196 -0
|
@@ -0,0 +1,1680 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Hyperliquid Tool Service
|
|
3
|
+
|
|
4
|
+
Provides trading capabilities for Hyperliquid perpetuals and spot markets.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import time
|
|
8
|
+
import httpx
|
|
9
|
+
from typing import Optional, Dict, Any, List, Tuple
|
|
10
|
+
from pydantic import BaseModel, Field
|
|
11
|
+
|
|
12
|
+
from tools.base_tool import BaseTool, ToolStatus
|
|
13
|
+
from tools.hyperliquid.models import (
|
|
14
|
+
HyperliquidCredentials,
|
|
15
|
+
TradingLimits,
|
|
16
|
+
ExecutionResult,
|
|
17
|
+
MAINNET_API_URL,
|
|
18
|
+
TESTNET_API_URL,
|
|
19
|
+
MIN_ORDER_VALUE_USD,
|
|
20
|
+
)
|
|
21
|
+
from core.logging import get_component_logger
|
|
22
|
+
|
|
23
|
+
# Try to import official SDK
|
|
24
|
+
try:
|
|
25
|
+
from hyperliquid.info import Info
|
|
26
|
+
from hyperliquid.exchange import Exchange
|
|
27
|
+
from hyperliquid.utils import constants as hl_constants
|
|
28
|
+
HAS_SDK = True
|
|
29
|
+
except ImportError:
|
|
30
|
+
HAS_SDK = False
|
|
31
|
+
Info = None
|
|
32
|
+
Exchange = None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# =============================================================================
|
|
36
|
+
# Parameter Models (Pydantic)
|
|
37
|
+
# =============================================================================
|
|
38
|
+
|
|
39
|
+
class EmptyParams(BaseModel):
|
|
40
|
+
"""Empty parameters for actions that don't need input"""
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SearchMarketsParams(BaseModel):
|
|
45
|
+
"""Parameters for searching markets"""
|
|
46
|
+
query: Optional[str] = Field(None, description="Search query (coin name/symbol)")
|
|
47
|
+
market_type: str = Field("perpetual", description="Market type: 'perpetual' or 'spot'")
|
|
48
|
+
limit: int = Field(20, ge=1, le=100, description="Max results to return")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class GetPriceParams(BaseModel):
|
|
52
|
+
"""Parameters for getting current price"""
|
|
53
|
+
coin: str = Field(..., description="Coin symbol (e.g., 'BTC', 'ETH')")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class GetOrderbookParams(BaseModel):
|
|
57
|
+
"""Parameters for getting orderbook"""
|
|
58
|
+
coin: str = Field(..., description="Coin symbol")
|
|
59
|
+
depth: int = Field(10, ge=1, le=100, description="Orderbook depth")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class GetFundingParams(BaseModel):
|
|
63
|
+
"""Parameters for getting funding rate"""
|
|
64
|
+
coin: str = Field(..., description="Coin symbol")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class GetCandlesParams(BaseModel):
|
|
68
|
+
"""Parameters for getting candlestick data"""
|
|
69
|
+
coin: str = Field(..., description="Coin symbol")
|
|
70
|
+
interval: str = Field("1h", description="Candle interval: 1m, 5m, 15m, 1h, 4h, 1d")
|
|
71
|
+
limit: int = Field(100, ge=1, le=500, description="Number of candles")
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class PlaceLimitOrderParams(BaseModel):
|
|
75
|
+
"""Parameters for placing a limit order"""
|
|
76
|
+
coin: str = Field(..., description="Coin symbol")
|
|
77
|
+
is_buy: bool = Field(..., description="True for buy/long, False for sell/short")
|
|
78
|
+
size: float = Field(..., gt=0, description="Order size in base asset")
|
|
79
|
+
price: float = Field(..., gt=0, description="Limit price")
|
|
80
|
+
reduce_only: bool = Field(False, description="Reduce-only order")
|
|
81
|
+
post_only: bool = Field(False, description="Post-only (maker) order")
|
|
82
|
+
client_order_id: Optional[str] = Field(None, description="Custom order ID")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class PlaceMarketOrderParams(BaseModel):
|
|
86
|
+
"""Parameters for placing a market order"""
|
|
87
|
+
coin: str = Field(..., description="Coin symbol")
|
|
88
|
+
is_buy: bool = Field(..., description="True for buy/long, False for sell/short")
|
|
89
|
+
size: float = Field(..., gt=0, description="Order size in base asset")
|
|
90
|
+
slippage: float = Field(0.05, ge=0, le=0.2, description="Max slippage (0.05 = 5%)")
|
|
91
|
+
reduce_only: bool = Field(False, description="Reduce-only order")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class CancelOrderParams(BaseModel):
|
|
95
|
+
"""Parameters for canceling an order"""
|
|
96
|
+
coin: str = Field(..., description="Coin symbol")
|
|
97
|
+
order_id: int = Field(..., description="Order ID to cancel")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class CancelAllOrdersParams(BaseModel):
|
|
101
|
+
"""Parameters for canceling all orders"""
|
|
102
|
+
coin: Optional[str] = Field(None, description="Optional: cancel only for this coin")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class UpdateLeverageParams(BaseModel):
|
|
106
|
+
"""Parameters for updating leverage"""
|
|
107
|
+
coin: str = Field(..., description="Coin symbol")
|
|
108
|
+
leverage: int = Field(..., ge=1, le=50, description="New leverage value")
|
|
109
|
+
is_cross: bool = Field(True, description="Cross margin (True) or Isolated (False)")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class GetFillsParams(BaseModel):
|
|
113
|
+
"""Parameters for getting fill history"""
|
|
114
|
+
limit: int = Field(50, ge=1, le=500, description="Max fills to return")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class GetOrderHistoryParams(BaseModel):
|
|
118
|
+
"""Parameters for getting order history"""
|
|
119
|
+
limit: int = Field(50, ge=1, le=500, description="Max orders to return")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
# =============================================================================
|
|
123
|
+
# Service Class
|
|
124
|
+
# =============================================================================
|
|
125
|
+
|
|
126
|
+
class HyperliquidTool(BaseTool):
|
|
127
|
+
"""
|
|
128
|
+
Hyperliquid trading tool for perpetuals and spot markets.
|
|
129
|
+
|
|
130
|
+
Provides market data, portfolio management, and trading capabilities
|
|
131
|
+
with built-in safety limits and audit logging.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
tool_id = "hyperliquid"
|
|
135
|
+
name = "hyperliquid"
|
|
136
|
+
description = "Hyperliquid perpetual futures and spot trading"
|
|
137
|
+
|
|
138
|
+
def __init__(
|
|
139
|
+
self,
|
|
140
|
+
name: str = "hyperliquid",
|
|
141
|
+
config: Any = None,
|
|
142
|
+
container: Any = None,
|
|
143
|
+
):
|
|
144
|
+
super().__init__(name=name, config=config, container=container)
|
|
145
|
+
self.db = None # HyperliquidDBHandler
|
|
146
|
+
self._user_id: Optional[str] = None
|
|
147
|
+
self._credentials_cache: Dict[str, HyperliquidCredentials] = {}
|
|
148
|
+
self._http_client: Optional[httpx.AsyncClient] = None
|
|
149
|
+
self._info_clients: Dict[str, Info] = {} # Cached Info clients per user
|
|
150
|
+
self._exchange_clients: Dict[str, Exchange] = {} # Cached Exchange clients
|
|
151
|
+
self._tools_cache: Optional[List[Dict[str, Any]]] = None
|
|
152
|
+
|
|
153
|
+
self.logger = get_component_logger("HyperliquidTool")
|
|
154
|
+
self._enabled = True
|
|
155
|
+
|
|
156
|
+
if not HAS_SDK:
|
|
157
|
+
self.logger.warning("hyperliquid-python-sdk not installed - trading features disabled")
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def required_services(self) -> Dict[str, str]:
|
|
161
|
+
"""Get required services."""
|
|
162
|
+
return {
|
|
163
|
+
'rate_limit_manager': 'Rate limit management for API calls'
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
@property
|
|
167
|
+
def optional_services(self) -> Dict[str, str]:
|
|
168
|
+
"""Get optional services."""
|
|
169
|
+
return {
|
|
170
|
+
'cache_manager': 'Cache for market data',
|
|
171
|
+
'database_manager': 'Database for credentials'
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async def _initialize(self) -> None:
|
|
175
|
+
"""Initialize the tool"""
|
|
176
|
+
await super()._initialize()
|
|
177
|
+
|
|
178
|
+
# Create HTTP client with connection pooling
|
|
179
|
+
self._http_client = httpx.AsyncClient(
|
|
180
|
+
timeout=httpx.Timeout(30.0, connect=10.0),
|
|
181
|
+
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20),
|
|
182
|
+
follow_redirects=True
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
# Initialize database handler
|
|
186
|
+
if self.container:
|
|
187
|
+
self.db = self.container.get_service('hyperliquid_db')
|
|
188
|
+
if not self.db:
|
|
189
|
+
db_manager = self.container.get_service('database_manager')
|
|
190
|
+
if db_manager:
|
|
191
|
+
from modules.database.hyperliquid import HyperliquidDBHandler
|
|
192
|
+
self.db = HyperliquidDBHandler(db_manager.connection)
|
|
193
|
+
await self.db.ensure_tables()
|
|
194
|
+
self.container.register_service('hyperliquid_db', self.db)
|
|
195
|
+
|
|
196
|
+
self._status = ToolStatus.HEALTHY
|
|
197
|
+
self.logger.info("HyperliquidTool initialized")
|
|
198
|
+
|
|
199
|
+
async def _cleanup(self) -> None:
|
|
200
|
+
"""Cleanup resources"""
|
|
201
|
+
if self._http_client:
|
|
202
|
+
await self._http_client.aclose()
|
|
203
|
+
self._http_client = None
|
|
204
|
+
|
|
205
|
+
self._credentials_cache.clear()
|
|
206
|
+
self._info_clients.clear()
|
|
207
|
+
self._exchange_clients.clear()
|
|
208
|
+
self._status = ToolStatus.UNINITIALIZED
|
|
209
|
+
|
|
210
|
+
self.logger.info("HyperliquidTool cleaned up")
|
|
211
|
+
|
|
212
|
+
def set_user_context(self, user_id: str) -> None:
|
|
213
|
+
"""Set the current user context for credential resolution"""
|
|
214
|
+
if user_id != self._user_id:
|
|
215
|
+
self._user_id = user_id
|
|
216
|
+
self.logger.debug(f"Hyperliquid user context set: {user_id}")
|
|
217
|
+
|
|
218
|
+
# =========================================================================
|
|
219
|
+
# Credential Management
|
|
220
|
+
# =========================================================================
|
|
221
|
+
|
|
222
|
+
async def _get_user_credentials(self) -> Optional[HyperliquidCredentials]:
|
|
223
|
+
"""Get credentials for the current user"""
|
|
224
|
+
if not self._user_id:
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
# Check cache first
|
|
228
|
+
if self._user_id in self._credentials_cache:
|
|
229
|
+
return self._credentials_cache[self._user_id]
|
|
230
|
+
|
|
231
|
+
# Load from database
|
|
232
|
+
if self.db:
|
|
233
|
+
credentials = await self.db.get_credentials(self._user_id)
|
|
234
|
+
if credentials:
|
|
235
|
+
self._credentials_cache[self._user_id] = credentials
|
|
236
|
+
return credentials
|
|
237
|
+
|
|
238
|
+
return None
|
|
239
|
+
|
|
240
|
+
@staticmethod
|
|
241
|
+
def _resolve_query_address(credentials: HyperliquidCredentials) -> str:
|
|
242
|
+
"""The address to query /info for. ALWAYS the master/owner account: an
|
|
243
|
+
agent/API-wallet address returns an empty account for state/positions/fills."""
|
|
244
|
+
return credentials.wallet_address
|
|
245
|
+
|
|
246
|
+
async def _get_info_client(self) -> Optional[Info]:
|
|
247
|
+
"""Get or create Info client for read-only operations"""
|
|
248
|
+
if not HAS_SDK:
|
|
249
|
+
return None
|
|
250
|
+
|
|
251
|
+
credentials = await self._get_user_credentials()
|
|
252
|
+
api_url = credentials.api_url if credentials else MAINNET_API_URL
|
|
253
|
+
|
|
254
|
+
cache_key = f"{self._user_id or 'anon'}:{api_url}"
|
|
255
|
+
if cache_key in self._info_clients:
|
|
256
|
+
return self._info_clients[cache_key]
|
|
257
|
+
|
|
258
|
+
info = Info(api_url, skip_ws=True)
|
|
259
|
+
self._info_clients[cache_key] = info
|
|
260
|
+
return info
|
|
261
|
+
|
|
262
|
+
async def _get_exchange_client(self) -> Tuple[Optional[Exchange], Optional[str]]:
|
|
263
|
+
"""Get or create authenticated Exchange client for trading"""
|
|
264
|
+
if not HAS_SDK:
|
|
265
|
+
return None, "hyperliquid-python-sdk not installed"
|
|
266
|
+
|
|
267
|
+
credentials = await self._get_user_credentials()
|
|
268
|
+
if not credentials:
|
|
269
|
+
return None, "Credentials not configured"
|
|
270
|
+
|
|
271
|
+
if not credentials.is_configured():
|
|
272
|
+
return None, "Wallet not properly configured"
|
|
273
|
+
|
|
274
|
+
if credentials.demo_mode:
|
|
275
|
+
return None, "Trading disabled in demo mode"
|
|
276
|
+
|
|
277
|
+
cache_key = f"{self._user_id}:{credentials.api_url}"
|
|
278
|
+
if cache_key in self._exchange_clients:
|
|
279
|
+
return self._exchange_clients[cache_key], None
|
|
280
|
+
|
|
281
|
+
# Get Info client first (required by Exchange)
|
|
282
|
+
info = await self._get_info_client()
|
|
283
|
+
if not info:
|
|
284
|
+
return None, "Failed to create info client"
|
|
285
|
+
|
|
286
|
+
try:
|
|
287
|
+
# Prefer the agent personal wallet (gated) over per-user DB creds.
|
|
288
|
+
from core.wallet.factory import get_agent_wallet
|
|
289
|
+
agent_wallet = get_agent_wallet()
|
|
290
|
+
if agent_wallet is not None:
|
|
291
|
+
account = agent_wallet.account_for("hyperliquid")
|
|
292
|
+
# SDK signature: Exchange(wallet: LocalAccount, base_url=None, ...,
|
|
293
|
+
# account_address=None). The agent key IS the signer here; the
|
|
294
|
+
# master/account distinction (approveAgent) is the deferred
|
|
295
|
+
# funding-ops follow-on.
|
|
296
|
+
exchange = Exchange(
|
|
297
|
+
account,
|
|
298
|
+
base_url=credentials.api_url,
|
|
299
|
+
account_address=account.address,
|
|
300
|
+
)
|
|
301
|
+
else:
|
|
302
|
+
# P0-2 fix: the SDK `wallet` arg is a LocalAccount SIGNER, not an
|
|
303
|
+
# address string. Build the account from the stored key and use
|
|
304
|
+
# the keyword signature, mirroring the agent-wallet branch.
|
|
305
|
+
from eth_account import Account
|
|
306
|
+
try:
|
|
307
|
+
account = Account.from_key(credentials.trading_private_key)
|
|
308
|
+
except Exception:
|
|
309
|
+
# Never echo the raw key in the surfaced error/log.
|
|
310
|
+
return None, "invalid trading private key"
|
|
311
|
+
# When a delegated agent_wallet signs, the SDK must trade for the
|
|
312
|
+
# MASTER account (credentials.wallet_address), NOT the agent address —
|
|
313
|
+
# querying/trading the agent address hits an empty account. With no
|
|
314
|
+
# agent_wallet the signer IS the master, so wallet_address is still right.
|
|
315
|
+
exchange = Exchange(
|
|
316
|
+
account,
|
|
317
|
+
base_url=credentials.api_url,
|
|
318
|
+
account_address=credentials.wallet_address or account.address,
|
|
319
|
+
)
|
|
320
|
+
self._exchange_clients[cache_key] = exchange
|
|
321
|
+
return exchange, None
|
|
322
|
+
except Exception as e:
|
|
323
|
+
self.logger.error(f"Failed to create exchange client: {e}")
|
|
324
|
+
return None, str(e)
|
|
325
|
+
|
|
326
|
+
# =========================================================================
|
|
327
|
+
# Trading Limits Check
|
|
328
|
+
# =========================================================================
|
|
329
|
+
|
|
330
|
+
async def _check_trading_limits(
|
|
331
|
+
self,
|
|
332
|
+
credentials: HyperliquidCredentials,
|
|
333
|
+
coin: str,
|
|
334
|
+
size_usd: float,
|
|
335
|
+
leverage: int = 1
|
|
336
|
+
) -> Tuple[bool, str]:
|
|
337
|
+
"""Validate order against trading limits"""
|
|
338
|
+
limits = credentials.trading_limits
|
|
339
|
+
|
|
340
|
+
# Check if trading is enabled
|
|
341
|
+
if not credentials.can_trade():
|
|
342
|
+
return False, "Trading not enabled. Set demo_mode=False and enable_autonomous_trading=True"
|
|
343
|
+
|
|
344
|
+
# Check coin restrictions
|
|
345
|
+
if limits.blocked_coins and coin.upper() in [c.upper() for c in limits.blocked_coins]:
|
|
346
|
+
return False, f"Coin '{coin}' is blocked"
|
|
347
|
+
|
|
348
|
+
if limits.allowed_coins and coin.upper() not in [c.upper() for c in limits.allowed_coins]:
|
|
349
|
+
return False, f"Coin '{coin}' not in allowed list"
|
|
350
|
+
|
|
351
|
+
# Check order size
|
|
352
|
+
if size_usd > limits.max_order_size_usd:
|
|
353
|
+
return False, f"Order size ${size_usd:.2f} exceeds max ${limits.max_order_size_usd:.2f}"
|
|
354
|
+
|
|
355
|
+
# Check leverage
|
|
356
|
+
if leverage > limits.max_leverage:
|
|
357
|
+
return False, f"Leverage {leverage}x exceeds max {limits.max_leverage}x"
|
|
358
|
+
|
|
359
|
+
return True, "OK"
|
|
360
|
+
|
|
361
|
+
async def _check_exposure(
|
|
362
|
+
self, credentials, new_value_usd: float, reduce_only: bool
|
|
363
|
+
) -> Tuple[bool, str]:
|
|
364
|
+
"""Enforce max_total_exposure_usd (P1-6).
|
|
365
|
+
|
|
366
|
+
Reduce-only orders de-risk and are exempt. For opening orders, fetch the
|
|
367
|
+
live total notional and reject if existing + new would exceed the cap.
|
|
368
|
+
Fail CLOSED if the position snapshot is unavailable (don't open blind).
|
|
369
|
+
"""
|
|
370
|
+
if reduce_only:
|
|
371
|
+
return True, "OK"
|
|
372
|
+
cap = getattr(credentials.trading_limits, "max_total_exposure_usd", None)
|
|
373
|
+
if not cap:
|
|
374
|
+
return True, "OK"
|
|
375
|
+
state = await self.get_account_state(EmptyParams())
|
|
376
|
+
if not state.get("success"):
|
|
377
|
+
return False, "Cannot verify total exposure (position fetch failed); refusing to open"
|
|
378
|
+
current = float(state.get("total_ntl_pos", 0.0))
|
|
379
|
+
if current + new_value_usd > cap:
|
|
380
|
+
return False, (
|
|
381
|
+
f"Total exposure cap ${cap:.2f} would be exceeded "
|
|
382
|
+
f"(current ${current:.2f} + ${new_value_usd:.2f})"
|
|
383
|
+
)
|
|
384
|
+
return True, "OK"
|
|
385
|
+
|
|
386
|
+
async def _check_daily_loss(
|
|
387
|
+
self, credentials, reduce_only: bool
|
|
388
|
+
) -> Tuple[bool, str]:
|
|
389
|
+
"""Enforce max_daily_loss_usd (previously a settable no-op safety stop).
|
|
390
|
+
|
|
391
|
+
Reject NEW opening orders once the day's realized loss (from fills within
|
|
392
|
+
the current UTC day) plus current unrealized loss reaches the cap.
|
|
393
|
+
Reduce-only orders de-risk and are exempt. Fail CLOSED if the PnL snapshot
|
|
394
|
+
cannot be fetched (don't open blind), mirroring _check_exposure.
|
|
395
|
+
"""
|
|
396
|
+
if reduce_only:
|
|
397
|
+
return True, "OK"
|
|
398
|
+
cap = getattr(credentials.trading_limits, "max_daily_loss_usd", None)
|
|
399
|
+
if not cap:
|
|
400
|
+
return True, "OK"
|
|
401
|
+
# Realized PnL from fills within the current UTC day.
|
|
402
|
+
fills_res = await self.get_fills(GetFillsParams(limit=500))
|
|
403
|
+
if not fills_res.get("success"):
|
|
404
|
+
return False, "Cannot verify daily loss (fills fetch failed); refusing to open"
|
|
405
|
+
import datetime as _dt
|
|
406
|
+
now = _dt.datetime.now(_dt.timezone.utc)
|
|
407
|
+
day_start_ms = int(_dt.datetime(
|
|
408
|
+
now.year, now.month, now.day, tzinfo=_dt.timezone.utc).timestamp() * 1000)
|
|
409
|
+
realized = 0.0
|
|
410
|
+
for f in fills_res.get("fills", []):
|
|
411
|
+
t = f.get("time")
|
|
412
|
+
pnl = f.get("closed_pnl")
|
|
413
|
+
if t is not None and pnl is not None and int(t) >= day_start_ms:
|
|
414
|
+
realized += float(pnl)
|
|
415
|
+
# Current unrealized PnL from open positions.
|
|
416
|
+
state = await self.get_account_state(EmptyParams())
|
|
417
|
+
if not state.get("success"):
|
|
418
|
+
return False, "Cannot verify daily loss (account fetch failed); refusing to open"
|
|
419
|
+
unrealized = sum(
|
|
420
|
+
float(p.get("unrealized_pnl", 0) or 0) for p in state.get("positions", [])
|
|
421
|
+
)
|
|
422
|
+
day_pnl = realized + unrealized
|
|
423
|
+
loss = -day_pnl # positive == net loss
|
|
424
|
+
if loss >= cap:
|
|
425
|
+
return False, (
|
|
426
|
+
f"Daily-loss cap ${cap:.2f} reached (today's PnL ${day_pnl:.2f}); "
|
|
427
|
+
f"refusing to open new positions"
|
|
428
|
+
)
|
|
429
|
+
return True, "OK"
|
|
430
|
+
|
|
431
|
+
# =========================================================================
|
|
432
|
+
# Market Discovery Actions
|
|
433
|
+
# =========================================================================
|
|
434
|
+
|
|
435
|
+
@BaseTool.action(
|
|
436
|
+
'Get all available perpetual futures markets with metadata',
|
|
437
|
+
param_model=EmptyParams
|
|
438
|
+
)
|
|
439
|
+
async def get_perpetual_markets(self, params: EmptyParams) -> Dict[str, Any]:
|
|
440
|
+
"""Get all available perpetual markets"""
|
|
441
|
+
await self.ensure_initialized()
|
|
442
|
+
await self.rate_limit("get_perpetual_markets")
|
|
443
|
+
|
|
444
|
+
start_time = time.time()
|
|
445
|
+
try:
|
|
446
|
+
credentials = await self._get_user_credentials()
|
|
447
|
+
api_url = credentials.api_url if credentials else MAINNET_API_URL
|
|
448
|
+
|
|
449
|
+
response = await self._http_client.post(
|
|
450
|
+
f"{api_url}/info",
|
|
451
|
+
json={"type": "metaAndAssetCtxs"}
|
|
452
|
+
)
|
|
453
|
+
response.raise_for_status()
|
|
454
|
+
data = response.json()
|
|
455
|
+
|
|
456
|
+
# Parse universe and asset contexts
|
|
457
|
+
markets = []
|
|
458
|
+
if len(data) >= 2:
|
|
459
|
+
meta = data[0]
|
|
460
|
+
asset_ctxs = data[1]
|
|
461
|
+
|
|
462
|
+
for i, asset in enumerate(meta.get("universe", [])):
|
|
463
|
+
ctx = asset_ctxs[i] if i < len(asset_ctxs) else {}
|
|
464
|
+
markets.append({
|
|
465
|
+
"coin": asset.get("name"),
|
|
466
|
+
"max_leverage": asset.get("maxLeverage"),
|
|
467
|
+
"mark_price": ctx.get("markPx"),
|
|
468
|
+
"funding_rate": ctx.get("funding"),
|
|
469
|
+
"open_interest": ctx.get("openInterest"),
|
|
470
|
+
"volume_24h": ctx.get("dayNtlVlm"),
|
|
471
|
+
})
|
|
472
|
+
|
|
473
|
+
return {
|
|
474
|
+
"success": True,
|
|
475
|
+
"markets": markets,
|
|
476
|
+
"count": len(markets),
|
|
477
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
478
|
+
}
|
|
479
|
+
except Exception as e:
|
|
480
|
+
self.logger.error(f"get_perpetual_markets failed: {e}")
|
|
481
|
+
return {"success": False, "error": str(e), "markets": []}
|
|
482
|
+
|
|
483
|
+
@BaseTool.action(
|
|
484
|
+
'Get all available spot trading pairs',
|
|
485
|
+
param_model=EmptyParams
|
|
486
|
+
)
|
|
487
|
+
async def get_spot_markets(self, params: EmptyParams) -> Dict[str, Any]:
|
|
488
|
+
"""Get all available spot markets"""
|
|
489
|
+
await self.ensure_initialized()
|
|
490
|
+
await self.rate_limit("get_spot_markets")
|
|
491
|
+
|
|
492
|
+
start_time = time.time()
|
|
493
|
+
try:
|
|
494
|
+
credentials = await self._get_user_credentials()
|
|
495
|
+
api_url = credentials.api_url if credentials else MAINNET_API_URL
|
|
496
|
+
|
|
497
|
+
response = await self._http_client.post(
|
|
498
|
+
f"{api_url}/info",
|
|
499
|
+
json={"type": "spotMetaAndAssetCtxs"}
|
|
500
|
+
)
|
|
501
|
+
response.raise_for_status()
|
|
502
|
+
data = response.json()
|
|
503
|
+
|
|
504
|
+
markets = []
|
|
505
|
+
if len(data) >= 2:
|
|
506
|
+
meta = data[0]
|
|
507
|
+
asset_ctxs = data[1]
|
|
508
|
+
|
|
509
|
+
tokens = {t["index"]: t for t in meta.get("tokens", [])}
|
|
510
|
+
for i, pair in enumerate(meta.get("universe", [])):
|
|
511
|
+
ctx = asset_ctxs[i] if i < len(asset_ctxs) else {}
|
|
512
|
+
pair_tokens = pair.get("tokens", [0, 0])
|
|
513
|
+
base_token = tokens.get(pair_tokens[0], {}) if len(pair_tokens) > 0 else {}
|
|
514
|
+
quote_token = tokens.get(pair_tokens[1], {}) if len(pair_tokens) > 1 else {}
|
|
515
|
+
|
|
516
|
+
markets.append({
|
|
517
|
+
"pair": pair.get("name"),
|
|
518
|
+
"base": base_token.get("name"),
|
|
519
|
+
"quote": quote_token.get("name"),
|
|
520
|
+
"index": pair.get("index"),
|
|
521
|
+
"mark_price": ctx.get("markPx"),
|
|
522
|
+
"mid_price": ctx.get("midPx"),
|
|
523
|
+
"volume_24h": ctx.get("dayNtlVlm"),
|
|
524
|
+
})
|
|
525
|
+
|
|
526
|
+
return {
|
|
527
|
+
"success": True,
|
|
528
|
+
"markets": markets,
|
|
529
|
+
"count": len(markets),
|
|
530
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
531
|
+
}
|
|
532
|
+
except Exception as e:
|
|
533
|
+
self.logger.error(f"get_spot_markets failed: {e}")
|
|
534
|
+
return {"success": False, "error": str(e), "markets": []}
|
|
535
|
+
|
|
536
|
+
# =========================================================================
|
|
537
|
+
# Market Data Actions
|
|
538
|
+
# =========================================================================
|
|
539
|
+
|
|
540
|
+
@BaseTool.action(
|
|
541
|
+
'Get current mid price for a coin',
|
|
542
|
+
param_model=GetPriceParams
|
|
543
|
+
)
|
|
544
|
+
async def get_current_price(self, params: GetPriceParams) -> Dict[str, Any]:
|
|
545
|
+
"""Get current price for a coin"""
|
|
546
|
+
await self.ensure_initialized()
|
|
547
|
+
await self.rate_limit("get_current_price")
|
|
548
|
+
|
|
549
|
+
start_time = time.time()
|
|
550
|
+
try:
|
|
551
|
+
credentials = await self._get_user_credentials()
|
|
552
|
+
api_url = credentials.api_url if credentials else MAINNET_API_URL
|
|
553
|
+
|
|
554
|
+
response = await self._http_client.post(
|
|
555
|
+
f"{api_url}/info",
|
|
556
|
+
json={"type": "allMids"}
|
|
557
|
+
)
|
|
558
|
+
response.raise_for_status()
|
|
559
|
+
mids = response.json()
|
|
560
|
+
|
|
561
|
+
coin = params.coin.upper()
|
|
562
|
+
if coin not in mids:
|
|
563
|
+
return {
|
|
564
|
+
"success": False,
|
|
565
|
+
"error": f"Coin '{coin}' not found",
|
|
566
|
+
"available_coins": list(mids.keys())[:20]
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
return {
|
|
570
|
+
"success": True,
|
|
571
|
+
"coin": coin,
|
|
572
|
+
"mid_price": float(mids[coin]),
|
|
573
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
574
|
+
}
|
|
575
|
+
except Exception as e:
|
|
576
|
+
self.logger.error(f"get_current_price failed: {e}")
|
|
577
|
+
return {"success": False, "error": str(e)}
|
|
578
|
+
|
|
579
|
+
@BaseTool.action(
|
|
580
|
+
'Get all mid prices for all markets',
|
|
581
|
+
param_model=EmptyParams
|
|
582
|
+
)
|
|
583
|
+
async def get_all_mids(self, params: EmptyParams) -> Dict[str, Any]:
|
|
584
|
+
"""Get all mid prices"""
|
|
585
|
+
await self.ensure_initialized()
|
|
586
|
+
await self.rate_limit("get_all_mids")
|
|
587
|
+
|
|
588
|
+
start_time = time.time()
|
|
589
|
+
try:
|
|
590
|
+
credentials = await self._get_user_credentials()
|
|
591
|
+
api_url = credentials.api_url if credentials else MAINNET_API_URL
|
|
592
|
+
|
|
593
|
+
response = await self._http_client.post(
|
|
594
|
+
f"{api_url}/info",
|
|
595
|
+
json={"type": "allMids"}
|
|
596
|
+
)
|
|
597
|
+
response.raise_for_status()
|
|
598
|
+
mids = response.json()
|
|
599
|
+
|
|
600
|
+
return {
|
|
601
|
+
"success": True,
|
|
602
|
+
"prices": {k: float(v) for k, v in mids.items()},
|
|
603
|
+
"count": len(mids),
|
|
604
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
605
|
+
}
|
|
606
|
+
except Exception as e:
|
|
607
|
+
self.logger.error(f"get_all_mids failed: {e}")
|
|
608
|
+
return {"success": False, "error": str(e)}
|
|
609
|
+
|
|
610
|
+
@BaseTool.action(
|
|
611
|
+
'Get L2 orderbook with bid/ask levels',
|
|
612
|
+
param_model=GetOrderbookParams
|
|
613
|
+
)
|
|
614
|
+
async def get_orderbook(self, params: GetOrderbookParams) -> Dict[str, Any]:
|
|
615
|
+
"""Get L2 orderbook for a coin"""
|
|
616
|
+
await self.ensure_initialized()
|
|
617
|
+
await self.rate_limit("get_orderbook")
|
|
618
|
+
|
|
619
|
+
start_time = time.time()
|
|
620
|
+
try:
|
|
621
|
+
credentials = await self._get_user_credentials()
|
|
622
|
+
api_url = credentials.api_url if credentials else MAINNET_API_URL
|
|
623
|
+
|
|
624
|
+
response = await self._http_client.post(
|
|
625
|
+
f"{api_url}/info",
|
|
626
|
+
json={"type": "l2Book", "coin": params.coin.upper()}
|
|
627
|
+
)
|
|
628
|
+
response.raise_for_status()
|
|
629
|
+
data = response.json()
|
|
630
|
+
|
|
631
|
+
levels = data.get("levels", [[], []])
|
|
632
|
+
bids = levels[0][:params.depth] if len(levels) > 0 else []
|
|
633
|
+
asks = levels[1][:params.depth] if len(levels) > 1 else []
|
|
634
|
+
|
|
635
|
+
# Calculate spread
|
|
636
|
+
best_bid = float(bids[0]["px"]) if bids else 0
|
|
637
|
+
best_ask = float(asks[0]["px"]) if asks else 0
|
|
638
|
+
spread = (best_ask - best_bid) / best_bid if best_bid > 0 else 0
|
|
639
|
+
|
|
640
|
+
return {
|
|
641
|
+
"success": True,
|
|
642
|
+
"coin": params.coin.upper(),
|
|
643
|
+
"bids": [{"price": float(b["px"]), "size": float(b["sz"])} for b in bids],
|
|
644
|
+
"asks": [{"price": float(a["px"]), "size": float(a["sz"])} for a in asks],
|
|
645
|
+
"best_bid": best_bid,
|
|
646
|
+
"best_ask": best_ask,
|
|
647
|
+
"spread": spread,
|
|
648
|
+
"spread_bps": spread * 10000,
|
|
649
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
650
|
+
}
|
|
651
|
+
except Exception as e:
|
|
652
|
+
self.logger.error(f"get_orderbook failed: {e}")
|
|
653
|
+
return {"success": False, "error": str(e)}
|
|
654
|
+
|
|
655
|
+
@BaseTool.action(
|
|
656
|
+
'Get current funding rate for a perpetual',
|
|
657
|
+
param_model=GetFundingParams
|
|
658
|
+
)
|
|
659
|
+
async def get_funding_rate(self, params: GetFundingParams) -> Dict[str, Any]:
|
|
660
|
+
"""Get current and predicted funding rate for a coin"""
|
|
661
|
+
await self.ensure_initialized()
|
|
662
|
+
await self.rate_limit("get_funding_rate")
|
|
663
|
+
|
|
664
|
+
start_time = time.time()
|
|
665
|
+
try:
|
|
666
|
+
credentials = await self._get_user_credentials()
|
|
667
|
+
api_url = credentials.api_url if credentials else MAINNET_API_URL
|
|
668
|
+
|
|
669
|
+
response = await self._http_client.post(
|
|
670
|
+
f"{api_url}/info",
|
|
671
|
+
json={"type": "metaAndAssetCtxs"}
|
|
672
|
+
)
|
|
673
|
+
response.raise_for_status()
|
|
674
|
+
data = response.json()
|
|
675
|
+
|
|
676
|
+
coin = params.coin.upper()
|
|
677
|
+
funding_info = None
|
|
678
|
+
|
|
679
|
+
if len(data) >= 2:
|
|
680
|
+
meta = data[0]
|
|
681
|
+
asset_ctxs = data[1]
|
|
682
|
+
|
|
683
|
+
for i, asset in enumerate(meta.get("universe", [])):
|
|
684
|
+
if asset.get("name") == coin:
|
|
685
|
+
ctx = asset_ctxs[i] if i < len(asset_ctxs) else {}
|
|
686
|
+
funding_info = {
|
|
687
|
+
"coin": coin,
|
|
688
|
+
"current_funding": ctx.get("funding"),
|
|
689
|
+
"mark_price": ctx.get("markPx"),
|
|
690
|
+
"premium": ctx.get("premium"),
|
|
691
|
+
"open_interest": ctx.get("openInterest"),
|
|
692
|
+
}
|
|
693
|
+
break
|
|
694
|
+
|
|
695
|
+
if not funding_info:
|
|
696
|
+
return {"success": False, "error": f"Coin '{coin}' not found"}
|
|
697
|
+
|
|
698
|
+
return {
|
|
699
|
+
"success": True,
|
|
700
|
+
**funding_info,
|
|
701
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
702
|
+
}
|
|
703
|
+
except Exception as e:
|
|
704
|
+
self.logger.error(f"get_funding_rate failed: {e}")
|
|
705
|
+
return {"success": False, "error": str(e)}
|
|
706
|
+
|
|
707
|
+
# =========================================================================
|
|
708
|
+
# Portfolio Actions
|
|
709
|
+
# =========================================================================
|
|
710
|
+
|
|
711
|
+
@BaseTool.action(
|
|
712
|
+
'Get perpetuals account summary including margin and positions',
|
|
713
|
+
param_model=EmptyParams
|
|
714
|
+
)
|
|
715
|
+
async def get_account_state(self, params: EmptyParams) -> Dict[str, Any]:
|
|
716
|
+
"""Get perpetuals account summary"""
|
|
717
|
+
await self.ensure_initialized()
|
|
718
|
+
await self.rate_limit("get_account_state")
|
|
719
|
+
|
|
720
|
+
start_time = time.time()
|
|
721
|
+
try:
|
|
722
|
+
credentials = await self._get_user_credentials()
|
|
723
|
+
if not credentials:
|
|
724
|
+
return {"success": False, "error": "Credentials not configured"}
|
|
725
|
+
|
|
726
|
+
response = await self._http_client.post(
|
|
727
|
+
f"{credentials.api_url}/info",
|
|
728
|
+
json={
|
|
729
|
+
"type": "clearinghouseState",
|
|
730
|
+
"user": self._resolve_query_address(credentials)
|
|
731
|
+
}
|
|
732
|
+
)
|
|
733
|
+
response.raise_for_status()
|
|
734
|
+
data = response.json()
|
|
735
|
+
|
|
736
|
+
# Parse margin summary
|
|
737
|
+
margin = data.get("marginSummary", {})
|
|
738
|
+
positions = data.get("assetPositions", [])
|
|
739
|
+
|
|
740
|
+
return {
|
|
741
|
+
"success": True,
|
|
742
|
+
"wallet_address": credentials.wallet_address,
|
|
743
|
+
"account_value": float(margin.get("accountValue", 0)),
|
|
744
|
+
"total_margin_used": float(margin.get("totalMarginUsed", 0)),
|
|
745
|
+
"total_ntl_pos": float(margin.get("totalNtlPos", 0)),
|
|
746
|
+
"total_raw_usd": float(margin.get("totalRawUsd", 0)),
|
|
747
|
+
"withdrawable": float(data.get("withdrawable", 0)),
|
|
748
|
+
"cross_margin_summary": data.get("crossMarginSummary"),
|
|
749
|
+
"position_count": len(positions),
|
|
750
|
+
"positions": [
|
|
751
|
+
{
|
|
752
|
+
"coin": p.get("position", {}).get("coin"),
|
|
753
|
+
"size": float(p.get("position", {}).get("szi", 0)),
|
|
754
|
+
"entry_price": float(p.get("position", {}).get("entryPx", 0)),
|
|
755
|
+
"unrealized_pnl": float(p.get("position", {}).get("unrealizedPnl", 0)),
|
|
756
|
+
"leverage": p.get("position", {}).get("leverage"),
|
|
757
|
+
"liquidation_px": p.get("position", {}).get("liquidationPx"),
|
|
758
|
+
"margin_used": float(p.get("position", {}).get("marginUsed", 0)),
|
|
759
|
+
}
|
|
760
|
+
for p in positions
|
|
761
|
+
],
|
|
762
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
763
|
+
}
|
|
764
|
+
except Exception as e:
|
|
765
|
+
self.logger.error(f"get_account_state failed: {e}")
|
|
766
|
+
return {"success": False, "error": str(e)}
|
|
767
|
+
|
|
768
|
+
@BaseTool.action(
|
|
769
|
+
'Get spot token balances',
|
|
770
|
+
param_model=EmptyParams
|
|
771
|
+
)
|
|
772
|
+
async def get_spot_balances(self, params: EmptyParams) -> Dict[str, Any]:
|
|
773
|
+
"""Get spot token balances"""
|
|
774
|
+
await self.ensure_initialized()
|
|
775
|
+
await self.rate_limit("get_spot_balances")
|
|
776
|
+
|
|
777
|
+
start_time = time.time()
|
|
778
|
+
try:
|
|
779
|
+
credentials = await self._get_user_credentials()
|
|
780
|
+
if not credentials:
|
|
781
|
+
return {"success": False, "error": "Credentials not configured"}
|
|
782
|
+
|
|
783
|
+
response = await self._http_client.post(
|
|
784
|
+
f"{credentials.api_url}/info",
|
|
785
|
+
json={
|
|
786
|
+
"type": "spotClearinghouseState",
|
|
787
|
+
"user": self._resolve_query_address(credentials)
|
|
788
|
+
}
|
|
789
|
+
)
|
|
790
|
+
response.raise_for_status()
|
|
791
|
+
data = response.json()
|
|
792
|
+
|
|
793
|
+
balances = []
|
|
794
|
+
for balance in data.get("balances", []):
|
|
795
|
+
total = float(balance.get("total", 0))
|
|
796
|
+
hold = float(balance.get("hold", 0))
|
|
797
|
+
balances.append({
|
|
798
|
+
"coin": balance.get("coin"),
|
|
799
|
+
"total": total,
|
|
800
|
+
"hold": hold,
|
|
801
|
+
"available": total - hold,
|
|
802
|
+
"entry_notional": float(balance.get("entryNtl", 0)),
|
|
803
|
+
})
|
|
804
|
+
|
|
805
|
+
return {
|
|
806
|
+
"success": True,
|
|
807
|
+
"wallet_address": credentials.wallet_address,
|
|
808
|
+
"balances": balances,
|
|
809
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
810
|
+
}
|
|
811
|
+
except Exception as e:
|
|
812
|
+
self.logger.error(f"get_spot_balances failed: {e}")
|
|
813
|
+
return {"success": False, "error": str(e)}
|
|
814
|
+
|
|
815
|
+
@BaseTool.action(
|
|
816
|
+
'Get all open orders',
|
|
817
|
+
param_model=EmptyParams
|
|
818
|
+
)
|
|
819
|
+
async def get_open_orders(self, params: EmptyParams) -> Dict[str, Any]:
|
|
820
|
+
"""Get all open orders"""
|
|
821
|
+
await self.ensure_initialized()
|
|
822
|
+
await self.rate_limit("get_open_orders")
|
|
823
|
+
|
|
824
|
+
start_time = time.time()
|
|
825
|
+
try:
|
|
826
|
+
credentials = await self._get_user_credentials()
|
|
827
|
+
if not credentials:
|
|
828
|
+
return {"success": False, "error": "Credentials not configured"}
|
|
829
|
+
|
|
830
|
+
response = await self._http_client.post(
|
|
831
|
+
f"{credentials.api_url}/info",
|
|
832
|
+
json={
|
|
833
|
+
"type": "openOrders",
|
|
834
|
+
"user": self._resolve_query_address(credentials)
|
|
835
|
+
}
|
|
836
|
+
)
|
|
837
|
+
response.raise_for_status()
|
|
838
|
+
orders = response.json()
|
|
839
|
+
|
|
840
|
+
return {
|
|
841
|
+
"success": True,
|
|
842
|
+
"orders": [
|
|
843
|
+
{
|
|
844
|
+
"order_id": o.get("oid"),
|
|
845
|
+
"coin": o.get("coin"),
|
|
846
|
+
"side": "buy" if o.get("side") == "B" else "sell",
|
|
847
|
+
"size": float(o.get("sz", 0)),
|
|
848
|
+
"price": float(o.get("limitPx", 0)),
|
|
849
|
+
"filled": float(o.get("origSz", 0)) - float(o.get("sz", 0)),
|
|
850
|
+
"order_type": o.get("orderType"),
|
|
851
|
+
"reduce_only": o.get("reduceOnly", False),
|
|
852
|
+
"timestamp": o.get("timestamp"),
|
|
853
|
+
}
|
|
854
|
+
for o in orders
|
|
855
|
+
],
|
|
856
|
+
"count": len(orders),
|
|
857
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
858
|
+
}
|
|
859
|
+
except Exception as e:
|
|
860
|
+
self.logger.error(f"get_open_orders failed: {e}")
|
|
861
|
+
return {"success": False, "error": str(e)}
|
|
862
|
+
|
|
863
|
+
@BaseTool.action(
|
|
864
|
+
'Get user fill history',
|
|
865
|
+
param_model=GetFillsParams
|
|
866
|
+
)
|
|
867
|
+
async def get_fills(self, params: GetFillsParams) -> Dict[str, Any]:
|
|
868
|
+
"""Get fill history"""
|
|
869
|
+
await self.ensure_initialized()
|
|
870
|
+
await self.rate_limit("get_fills")
|
|
871
|
+
|
|
872
|
+
start_time = time.time()
|
|
873
|
+
try:
|
|
874
|
+
credentials = await self._get_user_credentials()
|
|
875
|
+
if not credentials:
|
|
876
|
+
return {"success": False, "error": "Credentials not configured"}
|
|
877
|
+
|
|
878
|
+
response = await self._http_client.post(
|
|
879
|
+
f"{credentials.api_url}/info",
|
|
880
|
+
json={
|
|
881
|
+
"type": "userFills",
|
|
882
|
+
"user": self._resolve_query_address(credentials)
|
|
883
|
+
}
|
|
884
|
+
)
|
|
885
|
+
response.raise_for_status()
|
|
886
|
+
fills = response.json()
|
|
887
|
+
|
|
888
|
+
# Limit results
|
|
889
|
+
fills = fills[:params.limit]
|
|
890
|
+
|
|
891
|
+
return {
|
|
892
|
+
"success": True,
|
|
893
|
+
"fills": [
|
|
894
|
+
{
|
|
895
|
+
"coin": f.get("coin"),
|
|
896
|
+
"side": "buy" if f.get("side") == "B" else "sell",
|
|
897
|
+
"price": float(f.get("px", 0)),
|
|
898
|
+
"size": float(f.get("sz", 0)),
|
|
899
|
+
"time": f.get("time"),
|
|
900
|
+
"fee": float(f.get("fee", 0)),
|
|
901
|
+
"fee_token": f.get("feeToken"),
|
|
902
|
+
"start_position": f.get("startPosition"),
|
|
903
|
+
"closed_pnl": float(f.get("closedPnl", 0)) if f.get("closedPnl") else None,
|
|
904
|
+
}
|
|
905
|
+
for f in fills
|
|
906
|
+
],
|
|
907
|
+
"count": len(fills),
|
|
908
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
909
|
+
}
|
|
910
|
+
except Exception as e:
|
|
911
|
+
self.logger.error(f"get_fills failed: {e}")
|
|
912
|
+
return {"success": False, "error": str(e)}
|
|
913
|
+
|
|
914
|
+
# =========================================================================
|
|
915
|
+
# Trading Actions
|
|
916
|
+
# =========================================================================
|
|
917
|
+
|
|
918
|
+
@BaseTool.action(
|
|
919
|
+
'Place a limit order for perpetuals or spot',
|
|
920
|
+
param_model=PlaceLimitOrderParams
|
|
921
|
+
)
|
|
922
|
+
async def place_limit_order(self, params: PlaceLimitOrderParams) -> Dict[str, Any]:
|
|
923
|
+
"""Place a limit order"""
|
|
924
|
+
await self.ensure_initialized()
|
|
925
|
+
|
|
926
|
+
start_time = time.time()
|
|
927
|
+
|
|
928
|
+
credentials = await self._get_user_credentials()
|
|
929
|
+
if not credentials:
|
|
930
|
+
return {"success": False, "error": "Credentials not configured"}
|
|
931
|
+
|
|
932
|
+
# Calculate order value
|
|
933
|
+
order_value_usd = params.size * params.price
|
|
934
|
+
|
|
935
|
+
# Check trading limits
|
|
936
|
+
can_trade, message = await self._check_trading_limits(
|
|
937
|
+
credentials, params.coin, order_value_usd
|
|
938
|
+
)
|
|
939
|
+
if not can_trade:
|
|
940
|
+
return {"success": False, "error": message}
|
|
941
|
+
|
|
942
|
+
# Check if confirmation required
|
|
943
|
+
if order_value_usd > credentials.trading_limits.require_confirmation_above_usd:
|
|
944
|
+
return {
|
|
945
|
+
"success": False,
|
|
946
|
+
"error": f"Orders above ${credentials.trading_limits.require_confirmation_above_usd} require manual confirmation",
|
|
947
|
+
"order_details": {
|
|
948
|
+
"coin": params.coin,
|
|
949
|
+
"side": "buy" if params.is_buy else "sell",
|
|
950
|
+
"price": params.price,
|
|
951
|
+
"size": params.size,
|
|
952
|
+
"value_usd": order_value_usd,
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
# P1-6: enforce cumulative exposure cap (reduce-only exempt; fail closed).
|
|
957
|
+
ok_exp, exp_msg = await self._check_exposure(
|
|
958
|
+
credentials, order_value_usd, params.reduce_only
|
|
959
|
+
)
|
|
960
|
+
if not ok_exp:
|
|
961
|
+
return {"success": False, "error": exp_msg}
|
|
962
|
+
|
|
963
|
+
# Enforce the daily-loss stop (reduce-only exempt; fail closed).
|
|
964
|
+
ok_dl, dl_msg = await self._check_daily_loss(credentials, params.reduce_only)
|
|
965
|
+
if not ok_dl:
|
|
966
|
+
return {"success": False, "error": dl_msg}
|
|
967
|
+
|
|
968
|
+
# N2: route value-moving trades through the wallet PolicyGate (catastrophic
|
|
969
|
+
# ceiling + daily/venue caps + audit). idempotency_key=None: trades may
|
|
970
|
+
# legitimately repeat, so we don't replay-block — caps/ceiling/audit apply.
|
|
971
|
+
from core.wallet.factory import get_policy_gate
|
|
972
|
+
policy = get_policy_gate()
|
|
973
|
+
decision = policy.check(venue="hyperliquid", amount_usd=order_value_usd, idempotency_key=None)
|
|
974
|
+
if not decision.allowed:
|
|
975
|
+
return {"success": False, "error": f"Policy gate denied: {decision.reason}"}
|
|
976
|
+
|
|
977
|
+
# T11 live kill-switch: dry-run unless master + venue switches on AND within cap.
|
|
978
|
+
from tools.crypto_trade_gate import evaluate_live_trade
|
|
979
|
+
gate = evaluate_live_trade("hyperliquid", order_value_usd)
|
|
980
|
+
if not gate.live:
|
|
981
|
+
return {"success": False, "dry_run": True,
|
|
982
|
+
"error": f"Order not submitted (dry-run): {gate.reason}",
|
|
983
|
+
"order_details": {"coin": params.coin, "is_buy": params.is_buy,
|
|
984
|
+
"size": params.size, "price": params.price}}
|
|
985
|
+
|
|
986
|
+
await self.rate_limit("place_limit_order")
|
|
987
|
+
|
|
988
|
+
exchange, error = await self._get_exchange_client()
|
|
989
|
+
if error:
|
|
990
|
+
return {"success": False, "error": error}
|
|
991
|
+
|
|
992
|
+
try:
|
|
993
|
+
# Determine order type
|
|
994
|
+
order_type = {"limit": {"tif": "Alo" if params.post_only else "Gtc"}}
|
|
995
|
+
|
|
996
|
+
# Place order via SDK
|
|
997
|
+
result = exchange.order(
|
|
998
|
+
name=params.coin.upper(),
|
|
999
|
+
is_buy=params.is_buy,
|
|
1000
|
+
sz=params.size,
|
|
1001
|
+
limit_px=params.price,
|
|
1002
|
+
order_type=order_type,
|
|
1003
|
+
reduce_only=params.reduce_only,
|
|
1004
|
+
cloid=params.client_order_id,
|
|
1005
|
+
)
|
|
1006
|
+
|
|
1007
|
+
policy.record(
|
|
1008
|
+
venue="hyperliquid", action="place_limit_order",
|
|
1009
|
+
amount_usd=order_value_usd, counterparty=params.coin.upper(),
|
|
1010
|
+
idempotency_key=None, result_ref=str(result)[:80],
|
|
1011
|
+
)
|
|
1012
|
+
|
|
1013
|
+
# Audit log
|
|
1014
|
+
if self.db:
|
|
1015
|
+
await self.db.audit_log(
|
|
1016
|
+
user_id=self._user_id,
|
|
1017
|
+
action="place_limit_order",
|
|
1018
|
+
tool_name="place_limit_order",
|
|
1019
|
+
market_id=params.coin,
|
|
1020
|
+
details={
|
|
1021
|
+
"side": "buy" if params.is_buy else "sell",
|
|
1022
|
+
"size": params.size,
|
|
1023
|
+
"price": params.price,
|
|
1024
|
+
"result": result,
|
|
1025
|
+
}
|
|
1026
|
+
)
|
|
1027
|
+
|
|
1028
|
+
return {
|
|
1029
|
+
"success": True,
|
|
1030
|
+
"result": result,
|
|
1031
|
+
"order_details": {
|
|
1032
|
+
"coin": params.coin.upper(),
|
|
1033
|
+
"side": "buy" if params.is_buy else "sell",
|
|
1034
|
+
"size": params.size,
|
|
1035
|
+
"price": params.price,
|
|
1036
|
+
"value_usd": order_value_usd,
|
|
1037
|
+
},
|
|
1038
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
1039
|
+
}
|
|
1040
|
+
except Exception as e:
|
|
1041
|
+
self.logger.error(f"place_limit_order failed: {e}")
|
|
1042
|
+
return {"success": False, "error": str(e)}
|
|
1043
|
+
|
|
1044
|
+
@BaseTool.action(
|
|
1045
|
+
'Place a market order (marketable IOC at mid +/- slippage) for perpetuals or spot',
|
|
1046
|
+
param_model=PlaceMarketOrderParams
|
|
1047
|
+
)
|
|
1048
|
+
async def place_market_order(self, params: PlaceMarketOrderParams) -> Dict[str, Any]:
|
|
1049
|
+
"""Place a market order as a marketable IOC limit at mid +/- slippage."""
|
|
1050
|
+
await self.ensure_initialized()
|
|
1051
|
+
|
|
1052
|
+
start_time = time.time()
|
|
1053
|
+
|
|
1054
|
+
credentials = await self._get_user_credentials()
|
|
1055
|
+
if not credentials:
|
|
1056
|
+
return {"success": False, "error": "Credentials not configured"}
|
|
1057
|
+
|
|
1058
|
+
# A market order needs a live mid to both size (USD) and price the
|
|
1059
|
+
# marketable limit. Never submit a naked market order without a price.
|
|
1060
|
+
price_res = await self.get_current_price(GetPriceParams(coin=params.coin))
|
|
1061
|
+
if not price_res.get("success"):
|
|
1062
|
+
return {
|
|
1063
|
+
"success": False,
|
|
1064
|
+
"error": f"No live price for {params.coin.upper()}: {price_res.get('error')}",
|
|
1065
|
+
}
|
|
1066
|
+
mid = float(price_res["mid_price"])
|
|
1067
|
+
order_value_usd = params.size * mid
|
|
1068
|
+
|
|
1069
|
+
# Check trading limits
|
|
1070
|
+
can_trade, message = await self._check_trading_limits(
|
|
1071
|
+
credentials, params.coin, order_value_usd
|
|
1072
|
+
)
|
|
1073
|
+
if not can_trade:
|
|
1074
|
+
return {"success": False, "error": message}
|
|
1075
|
+
|
|
1076
|
+
# Check if confirmation required
|
|
1077
|
+
if order_value_usd > credentials.trading_limits.require_confirmation_above_usd:
|
|
1078
|
+
return {
|
|
1079
|
+
"success": False,
|
|
1080
|
+
"error": f"Orders above ${credentials.trading_limits.require_confirmation_above_usd} require manual confirmation",
|
|
1081
|
+
"order_details": {
|
|
1082
|
+
"coin": params.coin.upper(),
|
|
1083
|
+
"side": "buy" if params.is_buy else "sell",
|
|
1084
|
+
"size": params.size,
|
|
1085
|
+
"mid_price": mid,
|
|
1086
|
+
"value_usd": order_value_usd,
|
|
1087
|
+
},
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
# Marketable IOC limit: cross the spread by `slippage`.
|
|
1091
|
+
limit_px = mid * (1 + params.slippage) if params.is_buy else mid * (1 - params.slippage)
|
|
1092
|
+
|
|
1093
|
+
# P1-6: enforce cumulative exposure cap (reduce-only exempt; fail closed).
|
|
1094
|
+
ok_exp, exp_msg = await self._check_exposure(
|
|
1095
|
+
credentials, order_value_usd, params.reduce_only
|
|
1096
|
+
)
|
|
1097
|
+
if not ok_exp:
|
|
1098
|
+
return {"success": False, "error": exp_msg}
|
|
1099
|
+
|
|
1100
|
+
# Enforce the daily-loss stop (reduce-only exempt; fail closed).
|
|
1101
|
+
ok_dl, dl_msg = await self._check_daily_loss(credentials, params.reduce_only)
|
|
1102
|
+
if not ok_dl:
|
|
1103
|
+
return {"success": False, "error": dl_msg}
|
|
1104
|
+
|
|
1105
|
+
# N2: route value-moving trades through the wallet PolicyGate.
|
|
1106
|
+
from core.wallet.factory import get_policy_gate
|
|
1107
|
+
policy = get_policy_gate()
|
|
1108
|
+
decision = policy.check(venue="hyperliquid", amount_usd=order_value_usd, idempotency_key=None)
|
|
1109
|
+
if not decision.allowed:
|
|
1110
|
+
return {"success": False, "error": f"Policy gate denied: {decision.reason}"}
|
|
1111
|
+
|
|
1112
|
+
# T11 live kill-switch: dry-run unless master + venue switches on AND within cap.
|
|
1113
|
+
from tools.crypto_trade_gate import evaluate_live_trade
|
|
1114
|
+
gate = evaluate_live_trade("hyperliquid", order_value_usd)
|
|
1115
|
+
if not gate.live:
|
|
1116
|
+
return {"success": False, "dry_run": True,
|
|
1117
|
+
"error": f"Order not submitted (dry-run): {gate.reason}",
|
|
1118
|
+
"order_details": {"coin": params.coin, "is_buy": params.is_buy,
|
|
1119
|
+
"size": params.size}}
|
|
1120
|
+
|
|
1121
|
+
await self.rate_limit("place_market_order")
|
|
1122
|
+
|
|
1123
|
+
exchange, error = await self._get_exchange_client()
|
|
1124
|
+
if error:
|
|
1125
|
+
return {"success": False, "error": error}
|
|
1126
|
+
|
|
1127
|
+
try:
|
|
1128
|
+
order_type = {"limit": {"tif": "Ioc"}}
|
|
1129
|
+
result = exchange.order(
|
|
1130
|
+
name=params.coin.upper(),
|
|
1131
|
+
is_buy=params.is_buy,
|
|
1132
|
+
sz=params.size,
|
|
1133
|
+
limit_px=limit_px,
|
|
1134
|
+
order_type=order_type,
|
|
1135
|
+
reduce_only=params.reduce_only,
|
|
1136
|
+
)
|
|
1137
|
+
|
|
1138
|
+
policy.record(
|
|
1139
|
+
venue="hyperliquid", action="place_market_order",
|
|
1140
|
+
amount_usd=order_value_usd, counterparty=params.coin.upper(),
|
|
1141
|
+
idempotency_key=None, result_ref=str(result)[:80],
|
|
1142
|
+
)
|
|
1143
|
+
|
|
1144
|
+
if self.db:
|
|
1145
|
+
await self.db.audit_log(
|
|
1146
|
+
user_id=self._user_id,
|
|
1147
|
+
action="place_market_order",
|
|
1148
|
+
tool_name="place_market_order",
|
|
1149
|
+
market_id=params.coin,
|
|
1150
|
+
details={
|
|
1151
|
+
"side": "buy" if params.is_buy else "sell",
|
|
1152
|
+
"size": params.size,
|
|
1153
|
+
"mid_price": mid,
|
|
1154
|
+
"limit_px": limit_px,
|
|
1155
|
+
"slippage": params.slippage,
|
|
1156
|
+
"result": result,
|
|
1157
|
+
},
|
|
1158
|
+
)
|
|
1159
|
+
|
|
1160
|
+
return {
|
|
1161
|
+
"success": True,
|
|
1162
|
+
"result": result,
|
|
1163
|
+
"order_details": {
|
|
1164
|
+
"coin": params.coin.upper(),
|
|
1165
|
+
"side": "buy" if params.is_buy else "sell",
|
|
1166
|
+
"size": params.size,
|
|
1167
|
+
"mid_price": mid,
|
|
1168
|
+
"limit_px": limit_px,
|
|
1169
|
+
"slippage": params.slippage,
|
|
1170
|
+
"value_usd": order_value_usd,
|
|
1171
|
+
},
|
|
1172
|
+
"execution_time_ms": (time.time() - start_time) * 1000,
|
|
1173
|
+
}
|
|
1174
|
+
except Exception as e:
|
|
1175
|
+
self.logger.error(f"place_market_order failed: {e}")
|
|
1176
|
+
return {"success": False, "error": str(e)}
|
|
1177
|
+
|
|
1178
|
+
@BaseTool.action(
|
|
1179
|
+
'Cancel an open order',
|
|
1180
|
+
param_model=CancelOrderParams
|
|
1181
|
+
)
|
|
1182
|
+
async def cancel_order(self, params: CancelOrderParams) -> Dict[str, Any]:
|
|
1183
|
+
"""Cancel an order"""
|
|
1184
|
+
await self.ensure_initialized()
|
|
1185
|
+
await self.rate_limit("cancel_order")
|
|
1186
|
+
|
|
1187
|
+
start_time = time.time()
|
|
1188
|
+
|
|
1189
|
+
credentials = await self._get_user_credentials()
|
|
1190
|
+
if not credentials or not credentials.can_trade():
|
|
1191
|
+
return {"success": False, "error": "Trading not enabled"}
|
|
1192
|
+
|
|
1193
|
+
exchange, error = await self._get_exchange_client()
|
|
1194
|
+
if error:
|
|
1195
|
+
return {"success": False, "error": error}
|
|
1196
|
+
|
|
1197
|
+
try:
|
|
1198
|
+
result = exchange.cancel(params.coin.upper(), params.order_id)
|
|
1199
|
+
|
|
1200
|
+
# Audit log
|
|
1201
|
+
if self.db:
|
|
1202
|
+
await self.db.audit_log(
|
|
1203
|
+
user_id=self._user_id,
|
|
1204
|
+
action="cancel_order",
|
|
1205
|
+
tool_name="cancel_order",
|
|
1206
|
+
market_id=params.coin,
|
|
1207
|
+
details={"order_id": params.order_id, "result": result}
|
|
1208
|
+
)
|
|
1209
|
+
|
|
1210
|
+
return {
|
|
1211
|
+
"success": True,
|
|
1212
|
+
"result": result,
|
|
1213
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
1214
|
+
}
|
|
1215
|
+
except Exception as e:
|
|
1216
|
+
self.logger.error(f"cancel_order failed: {e}")
|
|
1217
|
+
return {"success": False, "error": str(e)}
|
|
1218
|
+
|
|
1219
|
+
@BaseTool.action(
|
|
1220
|
+
'Cancel all open orders',
|
|
1221
|
+
param_model=CancelAllOrdersParams
|
|
1222
|
+
)
|
|
1223
|
+
async def cancel_all_orders(self, params: CancelAllOrdersParams) -> Dict[str, Any]:
|
|
1224
|
+
"""Cancel all open orders"""
|
|
1225
|
+
await self.ensure_initialized()
|
|
1226
|
+
await self.rate_limit("cancel_all_orders")
|
|
1227
|
+
|
|
1228
|
+
start_time = time.time()
|
|
1229
|
+
|
|
1230
|
+
credentials = await self._get_user_credentials()
|
|
1231
|
+
if not credentials or not credentials.can_trade():
|
|
1232
|
+
return {"success": False, "error": "Trading not enabled"}
|
|
1233
|
+
|
|
1234
|
+
exchange, error = await self._get_exchange_client()
|
|
1235
|
+
if error:
|
|
1236
|
+
return {"success": False, "error": error}
|
|
1237
|
+
|
|
1238
|
+
try:
|
|
1239
|
+
if params.coin:
|
|
1240
|
+
result = exchange.cancel_all_orders(params.coin.upper())
|
|
1241
|
+
else:
|
|
1242
|
+
result = exchange.cancel_all_orders()
|
|
1243
|
+
|
|
1244
|
+
# Audit log
|
|
1245
|
+
if self.db:
|
|
1246
|
+
await self.db.audit_log(
|
|
1247
|
+
user_id=self._user_id,
|
|
1248
|
+
action="cancel_all_orders",
|
|
1249
|
+
tool_name="cancel_all_orders",
|
|
1250
|
+
market_id=params.coin,
|
|
1251
|
+
details={"coin": params.coin, "result": result}
|
|
1252
|
+
)
|
|
1253
|
+
|
|
1254
|
+
return {
|
|
1255
|
+
"success": True,
|
|
1256
|
+
"result": result,
|
|
1257
|
+
"coin": params.coin,
|
|
1258
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
1259
|
+
}
|
|
1260
|
+
except Exception as e:
|
|
1261
|
+
self.logger.error(f"cancel_all_orders failed: {e}")
|
|
1262
|
+
return {"success": False, "error": str(e)}
|
|
1263
|
+
|
|
1264
|
+
@BaseTool.action(
|
|
1265
|
+
'Update leverage for a perpetual market',
|
|
1266
|
+
param_model=UpdateLeverageParams
|
|
1267
|
+
)
|
|
1268
|
+
async def update_leverage(self, params: UpdateLeverageParams) -> Dict[str, Any]:
|
|
1269
|
+
"""Update leverage for a coin"""
|
|
1270
|
+
await self.ensure_initialized()
|
|
1271
|
+
await self.rate_limit("update_leverage")
|
|
1272
|
+
|
|
1273
|
+
start_time = time.time()
|
|
1274
|
+
|
|
1275
|
+
credentials = await self._get_user_credentials()
|
|
1276
|
+
if not credentials or not credentials.can_trade():
|
|
1277
|
+
return {"success": False, "error": "Trading not enabled"}
|
|
1278
|
+
|
|
1279
|
+
# Check against max allowed leverage
|
|
1280
|
+
if params.leverage > credentials.trading_limits.max_leverage:
|
|
1281
|
+
return {
|
|
1282
|
+
"success": False,
|
|
1283
|
+
"error": f"Leverage {params.leverage}x exceeds max allowed {credentials.trading_limits.max_leverage}x"
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
exchange, error = await self._get_exchange_client()
|
|
1287
|
+
if error:
|
|
1288
|
+
return {"success": False, "error": error}
|
|
1289
|
+
|
|
1290
|
+
try:
|
|
1291
|
+
result = exchange.update_leverage(
|
|
1292
|
+
params.leverage,
|
|
1293
|
+
params.coin.upper(),
|
|
1294
|
+
params.is_cross
|
|
1295
|
+
)
|
|
1296
|
+
|
|
1297
|
+
# Audit log
|
|
1298
|
+
if self.db:
|
|
1299
|
+
await self.db.audit_log(
|
|
1300
|
+
user_id=self._user_id,
|
|
1301
|
+
action="update_leverage",
|
|
1302
|
+
tool_name="update_leverage",
|
|
1303
|
+
market_id=params.coin,
|
|
1304
|
+
details={
|
|
1305
|
+
"leverage": params.leverage,
|
|
1306
|
+
"is_cross": params.is_cross,
|
|
1307
|
+
"result": result,
|
|
1308
|
+
}
|
|
1309
|
+
)
|
|
1310
|
+
|
|
1311
|
+
return {
|
|
1312
|
+
"success": True,
|
|
1313
|
+
"result": result,
|
|
1314
|
+
"coin": params.coin.upper(),
|
|
1315
|
+
"leverage": params.leverage,
|
|
1316
|
+
"is_cross": params.is_cross,
|
|
1317
|
+
"execution_time_ms": (time.time() - start_time) * 1000
|
|
1318
|
+
}
|
|
1319
|
+
except Exception as e:
|
|
1320
|
+
self.logger.error(f"update_leverage failed: {e}")
|
|
1321
|
+
return {"success": False, "error": str(e)}
|
|
1322
|
+
|
|
1323
|
+
@BaseTool.action(
|
|
1324
|
+
'Show Hyperliquid agent-wallet delegation status (no keys exposed)',
|
|
1325
|
+
param_model=EmptyParams,
|
|
1326
|
+
)
|
|
1327
|
+
async def agent_status(self, params: EmptyParams) -> Dict[str, Any]:
|
|
1328
|
+
"""Report whether a delegated agent/API wallet is configured for trading.
|
|
1329
|
+
|
|
1330
|
+
Read-only and key-safe: never returns a private key. The on-chain
|
|
1331
|
+
approve_agent/revoke_agent lifecycle is a separate change (testnet-verified).
|
|
1332
|
+
"""
|
|
1333
|
+
await self.ensure_initialized()
|
|
1334
|
+
credentials = await self._get_user_credentials()
|
|
1335
|
+
if not credentials:
|
|
1336
|
+
return {"success": False, "error": "Credentials not configured"}
|
|
1337
|
+
|
|
1338
|
+
aw = credentials.agent_wallet
|
|
1339
|
+
return {
|
|
1340
|
+
"success": True,
|
|
1341
|
+
"delegated": aw is not None,
|
|
1342
|
+
"signer": "agent" if aw else "master",
|
|
1343
|
+
"master_address": credentials.wallet_address,
|
|
1344
|
+
"agent_address": aw.address if aw else None,
|
|
1345
|
+
"agent_name": aw.name if aw else None,
|
|
1346
|
+
"testnet": credentials.testnet,
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
@BaseTool.action(
|
|
1350
|
+
'Delegate trading to a fresh Hyperliquid agent/API wallet (signed by the master key)',
|
|
1351
|
+
param_model=EmptyParams,
|
|
1352
|
+
)
|
|
1353
|
+
async def approve_agent(self, params: Any) -> Dict[str, Any]:
|
|
1354
|
+
"""Approve a freshly-generated agent wallet so trades can be signed without the
|
|
1355
|
+
master key. Signed by the MASTER key (the one place it's used). Persists the new
|
|
1356
|
+
agent wallet (never returns its private key). On-chain behavior is testnet-verified.
|
|
1357
|
+
"""
|
|
1358
|
+
await self.ensure_initialized()
|
|
1359
|
+
if not HAS_SDK:
|
|
1360
|
+
return {"success": False, "error": "hyperliquid-python-sdk not installed"}
|
|
1361
|
+
|
|
1362
|
+
credentials = await self._get_user_credentials()
|
|
1363
|
+
if not credentials or not getattr(credentials, "private_key", None):
|
|
1364
|
+
return {"success": False, "error": "Master wallet not configured (private key required to approve an agent)"}
|
|
1365
|
+
|
|
1366
|
+
from eth_account import Account
|
|
1367
|
+
try:
|
|
1368
|
+
master = Account.from_key(credentials.private_key)
|
|
1369
|
+
except Exception:
|
|
1370
|
+
return {"success": False, "error": "invalid master private key"}
|
|
1371
|
+
|
|
1372
|
+
name = getattr(params, "name", None)
|
|
1373
|
+
try:
|
|
1374
|
+
await self._get_info_client()
|
|
1375
|
+
exchange = Exchange(master, base_url=credentials.api_url, account_address=master.address)
|
|
1376
|
+
# SDK generates a fresh agent key and signs the approval with the master wallet.
|
|
1377
|
+
result, agent_key = exchange.approve_agent(name)
|
|
1378
|
+
agent_addr = Account.from_key(agent_key).address
|
|
1379
|
+
except Exception as e:
|
|
1380
|
+
self.logger.error(f"approve_agent failed: {e}")
|
|
1381
|
+
return {"success": False, "error": f"approve_agent failed: {e}"}
|
|
1382
|
+
|
|
1383
|
+
# Persist the new agent wallet (encrypted). Never reuse an old one (replay safety).
|
|
1384
|
+
from tools.hyperliquid.models import AgentWallet
|
|
1385
|
+
agent_wallet = AgentWallet(address=agent_addr, private_key=agent_key, name=name)
|
|
1386
|
+
if self.db:
|
|
1387
|
+
await self.db.save_credentials(
|
|
1388
|
+
user_id=self._user_id,
|
|
1389
|
+
wallet_address=credentials.wallet_address,
|
|
1390
|
+
private_key=credentials.private_key,
|
|
1391
|
+
agent_wallet=agent_wallet,
|
|
1392
|
+
testnet=credentials.testnet,
|
|
1393
|
+
demo_mode=credentials.demo_mode,
|
|
1394
|
+
trading_limits=credentials.trading_limits,
|
|
1395
|
+
)
|
|
1396
|
+
try:
|
|
1397
|
+
await self.db.audit_log(self._user_id, "approve_agent", tool_name="hyperliquid",
|
|
1398
|
+
details={"agent_address": agent_addr})
|
|
1399
|
+
except Exception:
|
|
1400
|
+
pass
|
|
1401
|
+
self._credentials_cache.clear()
|
|
1402
|
+
|
|
1403
|
+
return {
|
|
1404
|
+
"success": True,
|
|
1405
|
+
"agent_address": agent_addr,
|
|
1406
|
+
"master_address": credentials.wallet_address,
|
|
1407
|
+
"note": "Agent wallet approved + persisted. Verify on testnet before live trading.",
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1410
|
+
@BaseTool.action(
|
|
1411
|
+
'Revoke the local Hyperliquid agent wallet (stop using it for signing)',
|
|
1412
|
+
param_model=EmptyParams,
|
|
1413
|
+
)
|
|
1414
|
+
async def revoke_agent(self, params: Any) -> Dict[str, Any]:
|
|
1415
|
+
"""Clear the stored agent wallet so trading falls back to the master key. NOTE: the
|
|
1416
|
+
on-chain approval persists until it expires; rotate by approving a fresh agent."""
|
|
1417
|
+
await self.ensure_initialized()
|
|
1418
|
+
credentials = await self._get_user_credentials()
|
|
1419
|
+
if not credentials:
|
|
1420
|
+
return {"success": False, "error": "Credentials not configured"}
|
|
1421
|
+
if self.db:
|
|
1422
|
+
await self.db.save_credentials(
|
|
1423
|
+
user_id=self._user_id,
|
|
1424
|
+
wallet_address=credentials.wallet_address,
|
|
1425
|
+
private_key=credentials.private_key,
|
|
1426
|
+
agent_wallet=None,
|
|
1427
|
+
testnet=credentials.testnet,
|
|
1428
|
+
demo_mode=credentials.demo_mode,
|
|
1429
|
+
trading_limits=credentials.trading_limits,
|
|
1430
|
+
)
|
|
1431
|
+
self._credentials_cache.clear()
|
|
1432
|
+
return {"success": True, "note": "Local agent wallet cleared; signing falls back to the master key. "
|
|
1433
|
+
"The on-chain approval persists until it expires."}
|
|
1434
|
+
|
|
1435
|
+
# =========================================================================
|
|
1436
|
+
# Tool Discovery
|
|
1437
|
+
# =========================================================================
|
|
1438
|
+
|
|
1439
|
+
def get_available_tools(self) -> List[Dict[str, Any]]:
|
|
1440
|
+
"""Return list of available tools with their schemas"""
|
|
1441
|
+
if self._tools_cache:
|
|
1442
|
+
return self._tools_cache
|
|
1443
|
+
|
|
1444
|
+
tools = [
|
|
1445
|
+
# Market Discovery
|
|
1446
|
+
{
|
|
1447
|
+
"name": "get_perpetual_markets",
|
|
1448
|
+
"description": "Get all available perpetual futures markets with metadata",
|
|
1449
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1450
|
+
"category": "market_discovery",
|
|
1451
|
+
},
|
|
1452
|
+
{
|
|
1453
|
+
"name": "get_spot_markets",
|
|
1454
|
+
"description": "Get all available spot trading pairs",
|
|
1455
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1456
|
+
"category": "market_discovery",
|
|
1457
|
+
},
|
|
1458
|
+
# Market Data
|
|
1459
|
+
{
|
|
1460
|
+
"name": "get_current_price",
|
|
1461
|
+
"description": "Get current mid price for a coin",
|
|
1462
|
+
"inputSchema": GetPriceParams.model_json_schema(),
|
|
1463
|
+
"category": "market_data",
|
|
1464
|
+
},
|
|
1465
|
+
{
|
|
1466
|
+
"name": "get_all_mids",
|
|
1467
|
+
"description": "Get all mid prices for all markets",
|
|
1468
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1469
|
+
"category": "market_data",
|
|
1470
|
+
},
|
|
1471
|
+
{
|
|
1472
|
+
"name": "get_orderbook",
|
|
1473
|
+
"description": "Get L2 orderbook with bid/ask levels",
|
|
1474
|
+
"inputSchema": GetOrderbookParams.model_json_schema(),
|
|
1475
|
+
"category": "market_data",
|
|
1476
|
+
},
|
|
1477
|
+
{
|
|
1478
|
+
"name": "get_funding_rate",
|
|
1479
|
+
"description": "Get current funding rate for a perpetual",
|
|
1480
|
+
"inputSchema": GetFundingParams.model_json_schema(),
|
|
1481
|
+
"category": "market_data",
|
|
1482
|
+
},
|
|
1483
|
+
# Portfolio
|
|
1484
|
+
{
|
|
1485
|
+
"name": "get_account_state",
|
|
1486
|
+
"description": "Get perpetuals account summary including margin and positions",
|
|
1487
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1488
|
+
"category": "portfolio",
|
|
1489
|
+
"requires_auth": True,
|
|
1490
|
+
},
|
|
1491
|
+
{
|
|
1492
|
+
"name": "get_spot_balances",
|
|
1493
|
+
"description": "Get spot token balances",
|
|
1494
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1495
|
+
"category": "portfolio",
|
|
1496
|
+
"requires_auth": True,
|
|
1497
|
+
},
|
|
1498
|
+
{
|
|
1499
|
+
"name": "get_open_orders",
|
|
1500
|
+
"description": "Get all open orders",
|
|
1501
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1502
|
+
"category": "portfolio",
|
|
1503
|
+
"requires_auth": True,
|
|
1504
|
+
},
|
|
1505
|
+
{
|
|
1506
|
+
"name": "get_fills",
|
|
1507
|
+
"description": "Get fill history",
|
|
1508
|
+
"inputSchema": GetFillsParams.model_json_schema(),
|
|
1509
|
+
"category": "portfolio",
|
|
1510
|
+
"requires_auth": True,
|
|
1511
|
+
},
|
|
1512
|
+
# Trading
|
|
1513
|
+
{
|
|
1514
|
+
"name": "place_limit_order",
|
|
1515
|
+
"description": "Place a limit order for perpetuals or spot",
|
|
1516
|
+
"inputSchema": PlaceLimitOrderParams.model_json_schema(),
|
|
1517
|
+
"category": "trading",
|
|
1518
|
+
"requires_auth": True,
|
|
1519
|
+
"requires_trading_enabled": True,
|
|
1520
|
+
},
|
|
1521
|
+
{
|
|
1522
|
+
"name": "place_market_order",
|
|
1523
|
+
"description": "Place a market order (marketable IOC at mid +/- slippage)",
|
|
1524
|
+
"inputSchema": PlaceMarketOrderParams.model_json_schema(),
|
|
1525
|
+
"category": "trading",
|
|
1526
|
+
"requires_auth": True,
|
|
1527
|
+
"requires_trading_enabled": True,
|
|
1528
|
+
},
|
|
1529
|
+
{
|
|
1530
|
+
"name": "cancel_order",
|
|
1531
|
+
"description": "Cancel an open order",
|
|
1532
|
+
"inputSchema": CancelOrderParams.model_json_schema(),
|
|
1533
|
+
"category": "trading",
|
|
1534
|
+
"requires_auth": True,
|
|
1535
|
+
"requires_trading_enabled": True,
|
|
1536
|
+
},
|
|
1537
|
+
{
|
|
1538
|
+
"name": "cancel_all_orders",
|
|
1539
|
+
"description": "Cancel all open orders",
|
|
1540
|
+
"inputSchema": CancelAllOrdersParams.model_json_schema(),
|
|
1541
|
+
"category": "trading",
|
|
1542
|
+
"requires_auth": True,
|
|
1543
|
+
"requires_trading_enabled": True,
|
|
1544
|
+
},
|
|
1545
|
+
{
|
|
1546
|
+
"name": "update_leverage",
|
|
1547
|
+
"description": "Update leverage for a perpetual market",
|
|
1548
|
+
"inputSchema": UpdateLeverageParams.model_json_schema(),
|
|
1549
|
+
"category": "trading",
|
|
1550
|
+
"requires_auth": True,
|
|
1551
|
+
"requires_trading_enabled": True,
|
|
1552
|
+
},
|
|
1553
|
+
{
|
|
1554
|
+
"name": "agent_status",
|
|
1555
|
+
"description": "Show agent-wallet delegation status (read-only, no keys)",
|
|
1556
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1557
|
+
"category": "account",
|
|
1558
|
+
"requires_auth": True,
|
|
1559
|
+
"requires_trading_enabled": False,
|
|
1560
|
+
},
|
|
1561
|
+
{
|
|
1562
|
+
"name": "approve_agent",
|
|
1563
|
+
"description": "Delegate trading to a fresh agent wallet (signed by the master key)",
|
|
1564
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1565
|
+
"category": "account",
|
|
1566
|
+
"requires_auth": True,
|
|
1567
|
+
"requires_trading_enabled": True,
|
|
1568
|
+
},
|
|
1569
|
+
{
|
|
1570
|
+
"name": "revoke_agent",
|
|
1571
|
+
"description": "Revoke the local agent wallet (fall back to the master key)",
|
|
1572
|
+
"inputSchema": EmptyParams.model_json_schema(),
|
|
1573
|
+
"category": "account",
|
|
1574
|
+
"requires_auth": True,
|
|
1575
|
+
"requires_trading_enabled": True,
|
|
1576
|
+
},
|
|
1577
|
+
]
|
|
1578
|
+
|
|
1579
|
+
self._tools_cache = tools
|
|
1580
|
+
return tools
|
|
1581
|
+
|
|
1582
|
+
async def execute_action(
|
|
1583
|
+
self,
|
|
1584
|
+
tool_name: str,
|
|
1585
|
+
arguments: Dict[str, Any]
|
|
1586
|
+
) -> ExecutionResult:
|
|
1587
|
+
"""Execute a tool action by name"""
|
|
1588
|
+
start_time = time.time()
|
|
1589
|
+
|
|
1590
|
+
action_map = {
|
|
1591
|
+
"get_perpetual_markets": (self.get_perpetual_markets, EmptyParams),
|
|
1592
|
+
"get_spot_markets": (self.get_spot_markets, EmptyParams),
|
|
1593
|
+
"get_current_price": (self.get_current_price, GetPriceParams),
|
|
1594
|
+
"get_all_mids": (self.get_all_mids, EmptyParams),
|
|
1595
|
+
"get_orderbook": (self.get_orderbook, GetOrderbookParams),
|
|
1596
|
+
"get_funding_rate": (self.get_funding_rate, GetFundingParams),
|
|
1597
|
+
"get_account_state": (self.get_account_state, EmptyParams),
|
|
1598
|
+
"get_spot_balances": (self.get_spot_balances, EmptyParams),
|
|
1599
|
+
"get_open_orders": (self.get_open_orders, EmptyParams),
|
|
1600
|
+
"get_fills": (self.get_fills, GetFillsParams),
|
|
1601
|
+
"place_limit_order": (self.place_limit_order, PlaceLimitOrderParams),
|
|
1602
|
+
"place_market_order": (self.place_market_order, PlaceMarketOrderParams),
|
|
1603
|
+
"cancel_order": (self.cancel_order, CancelOrderParams),
|
|
1604
|
+
"cancel_all_orders": (self.cancel_all_orders, CancelAllOrdersParams),
|
|
1605
|
+
"update_leverage": (self.update_leverage, UpdateLeverageParams),
|
|
1606
|
+
"agent_status": (self.agent_status, EmptyParams),
|
|
1607
|
+
"approve_agent": (self.approve_agent, EmptyParams),
|
|
1608
|
+
"revoke_agent": (self.revoke_agent, EmptyParams),
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
if tool_name not in action_map:
|
|
1612
|
+
return ExecutionResult(
|
|
1613
|
+
success=False,
|
|
1614
|
+
error=f"Unknown tool: {tool_name}. Available: {', '.join(action_map.keys())}",
|
|
1615
|
+
tool_name=tool_name
|
|
1616
|
+
)
|
|
1617
|
+
|
|
1618
|
+
method, param_class = action_map[tool_name]
|
|
1619
|
+
|
|
1620
|
+
try:
|
|
1621
|
+
params = param_class(**arguments)
|
|
1622
|
+
result = await method(params)
|
|
1623
|
+
|
|
1624
|
+
execution_time = (time.time() - start_time) * 1000
|
|
1625
|
+
|
|
1626
|
+
return ExecutionResult(
|
|
1627
|
+
success=result.get("success", False),
|
|
1628
|
+
data=result,
|
|
1629
|
+
error=result.get("error"),
|
|
1630
|
+
tool_name=tool_name,
|
|
1631
|
+
execution_time_ms=execution_time
|
|
1632
|
+
)
|
|
1633
|
+
except Exception as e:
|
|
1634
|
+
execution_time = (time.time() - start_time) * 1000
|
|
1635
|
+
self.logger.error(f"Tool execution failed: {tool_name}: {e}")
|
|
1636
|
+
return ExecutionResult(
|
|
1637
|
+
success=False,
|
|
1638
|
+
error=f"Parameter validation failed: {str(e)}",
|
|
1639
|
+
tool_name=tool_name,
|
|
1640
|
+
execution_time_ms=execution_time
|
|
1641
|
+
)
|
|
1642
|
+
|
|
1643
|
+
|
|
1644
|
+
# =============================================================================
|
|
1645
|
+
# READ / TRADE SPLIT (additive)
|
|
1646
|
+
# =============================================================================
|
|
1647
|
+
|
|
1648
|
+
# Wallet-free read actions. All are public /info reads (market data + account state by
|
|
1649
|
+
# the MASTER address) plus the read-only agent_status. Trading actions stay on the gated
|
|
1650
|
+
# 'hyperliquid' tool.
|
|
1651
|
+
HL_READ_ACTIONS = frozenset({
|
|
1652
|
+
"get_perpetual_markets", "get_spot_markets", "get_current_price", "get_all_mids",
|
|
1653
|
+
"get_orderbook", "get_funding_rate", "get_account_state", "get_spot_balances",
|
|
1654
|
+
"get_open_orders", "get_fills", "agent_status",
|
|
1655
|
+
})
|
|
1656
|
+
|
|
1657
|
+
|
|
1658
|
+
class HyperliquidDataTool(HyperliquidTool):
|
|
1659
|
+
"""Read-only Hyperliquid tool (no signing, delegatable). Exposes only HL_READ_ACTIONS;
|
|
1660
|
+
trade actions are filtered at registration, advertisement, and execution."""
|
|
1661
|
+
|
|
1662
|
+
tool_id = "hyperliquid_data"
|
|
1663
|
+
name = "hyperliquid_data"
|
|
1664
|
+
description = "Hyperliquid perps/spot — read-only market data & account state (no signing)"
|
|
1665
|
+
|
|
1666
|
+
def get_actions(self) -> Dict[str, Any]:
|
|
1667
|
+
return {k: v for k, v in super().get_actions().items() if k in HL_READ_ACTIONS}
|
|
1668
|
+
|
|
1669
|
+
def get_available_tools(self) -> List[Dict[str, Any]]:
|
|
1670
|
+
return [t for t in super().get_available_tools() if t.get("name") in HL_READ_ACTIONS]
|
|
1671
|
+
|
|
1672
|
+
async def execute_action(self, tool_name: str, arguments: Dict[str, Any]) -> ExecutionResult:
|
|
1673
|
+
if tool_name not in HL_READ_ACTIONS:
|
|
1674
|
+
return ExecutionResult(
|
|
1675
|
+
success=False,
|
|
1676
|
+
error=f"'{tool_name}' is a trade action; use the gated 'hyperliquid' tool. "
|
|
1677
|
+
f"'hyperliquid_data' is read-only.",
|
|
1678
|
+
tool_name=tool_name,
|
|
1679
|
+
)
|
|
1680
|
+
return await super().execute_action(tool_name, arguments)
|