legate 0.1.0
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.
- checksums.yaml +7 -0
- data/LICENSE +21 -0
- data/README.md +345 -0
- data/bin/legate +13 -0
- data/examples/00_quickstart.rb +51 -0
- data/examples/01_simple_agent.rb +105 -0
- data/examples/02_multi_tool_agent.rb +140 -0
- data/examples/03_custom_tool.rb +93 -0
- data/examples/04_agent_instructions.rb +84 -0
- data/examples/05_state_and_sessions.rb +91 -0
- data/examples/06_callbacks.rb +186 -0
- data/examples/07_async_jobs.rb +112 -0
- data/examples/08_loop_agent.rb +197 -0
- data/examples/09_sequential_workflow.rb +40 -0
- data/examples/10_parallel_workflow.rb +34 -0
- data/examples/11_agent_delegation.rb +24 -0
- data/examples/12_http_client_tool.rb +156 -0
- data/examples/13_authentication.rb +220 -0
- data/examples/14_mcp_client.rb +154 -0
- data/examples/15_mcp_server.rb +79 -0
- data/examples/16_webhooks.rb +91 -0
- data/examples/README_sequential_agents.md +164 -0
- data/examples/advanced/auth/cookie_auth_tool.rb +146 -0
- data/examples/advanced/auth/custom_auth_flows_example.rb +626 -0
- data/examples/advanced/auth/excon_middleware.rb +317 -0
- data/examples/advanced/auth/excon_middleware_auth.rb +399 -0
- data/examples/advanced/auth/fiber_auth_example.rb +281 -0
- data/examples/advanced/auth/fiber_oidc_example.rb +403 -0
- data/examples/advanced/auth/httpbin_bearer_tool.rb +159 -0
- data/examples/advanced/auth/oauth2_auth.rb +419 -0
- data/examples/advanced/auth/oidc_auth.rb +514 -0
- data/examples/advanced/auth/openweather_api.rb +251 -0
- data/examples/advanced/auth/openweather_tool.rb +153 -0
- data/examples/advanced/auth/query_param_middleware_test.rb +138 -0
- data/examples/advanced/auth/service_account.rb +135 -0
- data/examples/advanced/auth/test_with_httpbin.rb +202 -0
- data/examples/advanced/auth/token_lifecycle_example.rb +428 -0
- data/examples/advanced/callback_monitoring.rb +679 -0
- data/examples/advanced/mas/fixed_delegation_example.rb +191 -0
- data/examples/advanced/mas/loop_workflow.rb +28 -0
- data/examples/advanced/mas/mock_planner.rb +77 -0
- data/examples/advanced/mas/proper_delegation_example.rb +276 -0
- data/examples/advanced/mcp/legate_mcp_server_resource_example.rb +182 -0
- data/examples/advanced/mcp/mcp_resource_server_example.rb +309 -0
- data/examples/advanced/mcp/mcp_server_async.rb +76 -0
- data/examples/advanced/mcp/mcp_server_async_tools.rb +122 -0
- data/examples/advanced/mcp/mcp_server_legate_agent.rb +95 -0
- data/examples/advanced/mcp/mcp_server_rack.rb +89 -0
- data/examples/advanced/random_calculator.rb +104 -0
- data/examples/advanced/sleep_agent.rb +153 -0
- data/examples/advanced/webhooks/webhook_e2e_runner.rb +110 -0
- data/examples/advanced/webhooks/webhook_receiver_agent.rb +58 -0
- data/examples/advanced/workflows/task_refinement_loop_agent.rb +278 -0
- data/examples/advanced/workflows/travel_planner_auto_sequential.rb +444 -0
- data/examples/advanced/workflows/travel_planner_parallel.rb +656 -0
- data/examples/advanced/workflows/travel_planner_sequential.rb +512 -0
- data/examples/tools/oauth2_example.rb +136 -0
- data/examples/tools/sleepy_tool.rb +42 -0
- data/lib/legate/activity_log.rb +71 -0
- data/lib/legate/agent.rb +959 -0
- data/lib/legate/agent_code_generator.rb +185 -0
- data/lib/legate/agent_definition.rb +812 -0
- data/lib/legate/agentic/decision.rb +49 -0
- data/lib/legate/agentic/loop.rb +134 -0
- data/lib/legate/agentic.rb +5 -0
- data/lib/legate/agents/loop_agent.rb +248 -0
- data/lib/legate/agents/parallel_agent.rb +163 -0
- data/lib/legate/agents/sequential_agent.rb +190 -0
- data/lib/legate/agents.rb +14 -0
- data/lib/legate/auth/config.rb +148 -0
- data/lib/legate/auth/coordinator.rb +218 -0
- data/lib/legate/auth/coordinators/oauth2_coordinator.rb +99 -0
- data/lib/legate/auth/coordinators/oidc_coordinator.rb +68 -0
- data/lib/legate/auth/coordinators/service_account_coordinator.rb +122 -0
- data/lib/legate/auth/credential.rb +157 -0
- data/lib/legate/auth/encryption.rb +108 -0
- data/lib/legate/auth/error.rb +94 -0
- data/lib/legate/auth/exchanged_credential.rb +180 -0
- data/lib/legate/auth/excon_middleware.rb +285 -0
- data/lib/legate/auth/http_client_utils.rb +364 -0
- data/lib/legate/auth/manager.rb +531 -0
- data/lib/legate/auth/manager_store.rb +394 -0
- data/lib/legate/auth/middleware_factory.rb +290 -0
- data/lib/legate/auth/runner.rb +279 -0
- data/lib/legate/auth/scheme.rb +125 -0
- data/lib/legate/auth/schemes/api_key.rb +212 -0
- data/lib/legate/auth/schemes/google_service_account.rb +108 -0
- data/lib/legate/auth/schemes/http_bearer.rb +98 -0
- data/lib/legate/auth/schemes/oauth2.rb +396 -0
- data/lib/legate/auth/schemes/openid_connect.rb +346 -0
- data/lib/legate/auth/schemes/service_account.rb +388 -0
- data/lib/legate/auth/schemes.rb +40 -0
- data/lib/legate/auth/token_manager.rb +362 -0
- data/lib/legate/auth/token_store.rb +86 -0
- data/lib/legate/auth/tool_context_extension.rb +97 -0
- data/lib/legate/auth/tool_integration.rb +188 -0
- data/lib/legate/auth/url_guard.rb +81 -0
- data/lib/legate/auth.rb +453 -0
- data/lib/legate/callbacks/callback_context.rb +71 -0
- data/lib/legate/cli/agent_commands.rb +950 -0
- data/lib/legate/cli/auth_commands.rb +520 -0
- data/lib/legate/cli/base_command.rb +24 -0
- data/lib/legate/cli/deployment_commands.rb +934 -0
- data/lib/legate/cli/output_helper.rb +108 -0
- data/lib/legate/cli/session_commands.rb +138 -0
- data/lib/legate/cli/skaffold_commands.rb +223 -0
- data/lib/legate/cli/tool_commands.rb +261 -0
- data/lib/legate/cli/web_commands.rb +182 -0
- data/lib/legate/cli.rb +40 -0
- data/lib/legate/configuration/webhooks.rb +113 -0
- data/lib/legate/configuration.rb +39 -0
- data/lib/legate/definition_store.rb +23 -0
- data/lib/legate/errors.rb +118 -0
- data/lib/legate/event.rb +161 -0
- data/lib/legate/gemini_ai_beta_patch.rb +39 -0
- data/lib/legate/generators/agent_generator.rb +412 -0
- data/lib/legate/generators/code_validator.rb +48 -0
- data/lib/legate/generators/legate/install_generator.rb +35 -0
- data/lib/legate/generators/legate/templates/create_legate_tables.rb.tt +36 -0
- data/lib/legate/generators/legate/templates/initializer.rb +18 -0
- data/lib/legate/generators/runtime_tool_loader.rb +76 -0
- data/lib/legate/generators/tool_generator.rb +408 -0
- data/lib/legate/generators.rb +11 -0
- data/lib/legate/global_definition_registry.rb +506 -0
- data/lib/legate/global_tool_manager.rb +135 -0
- data/lib/legate/llm/adapter.rb +69 -0
- data/lib/legate/llm/gemini.rb +172 -0
- data/lib/legate/llm/ollama.rb +80 -0
- data/lib/legate/llm.rb +34 -0
- data/lib/legate/mcp/client.rb +320 -0
- data/lib/legate/mcp/connection/sse.rb +292 -0
- data/lib/legate/mcp/connection/stdio.rb +273 -0
- data/lib/legate/mcp/connection_manager.rb +103 -0
- data/lib/legate/mcp/server/legate_agent_adapter.rb +170 -0
- data/lib/legate/mcp/server/legate_direct_agent_adapter.rb +140 -0
- data/lib/legate/mcp/server/legate_tool_adapter.rb +119 -0
- data/lib/legate/mcp/tool_wrapper.rb +138 -0
- data/lib/legate/mcp/util/schema_converter.rb +134 -0
- data/lib/legate/mcp.rb +23 -0
- data/lib/legate/plan_executor.rb +375 -0
- data/lib/legate/planner.rb +839 -0
- data/lib/legate/rails/railtie.rb +43 -0
- data/lib/legate/rails.rb +9 -0
- data/lib/legate/redaction.rb +32 -0
- data/lib/legate/session.rb +299 -0
- data/lib/legate/session_service/active_record.rb +300 -0
- data/lib/legate/session_service/base.rb +68 -0
- data/lib/legate/session_service/event_broadcast.rb +74 -0
- data/lib/legate/session_service/in_memory.rb +188 -0
- data/lib/legate/tool/metadata_dsl.rb +122 -0
- data/lib/legate/tool.rb +276 -0
- data/lib/legate/tool_code_generator.rb +103 -0
- data/lib/legate/tool_context.rb +350 -0
- data/lib/legate/tool_loader.rb +39 -0
- data/lib/legate/tool_registry.rb +73 -0
- data/lib/legate/tool_result.rb +61 -0
- data/lib/legate/tools/agent_tool.rb +187 -0
- data/lib/legate/tools/base/http_client.rb +319 -0
- data/lib/legate/tools/base/safe_url.rb +56 -0
- data/lib/legate/tools/base_async_job_tool.rb +91 -0
- data/lib/legate/tools/calculator.rb +89 -0
- data/lib/legate/tools/cat_facts.rb +81 -0
- data/lib/legate/tools/check_job_status_tool.rb +48 -0
- data/lib/legate/tools/current_time_tool.rb +64 -0
- data/lib/legate/tools/echo.rb +43 -0
- data/lib/legate/tools/http_request_tool.rb +105 -0
- data/lib/legate/tools/random_number_tool.rb +64 -0
- data/lib/legate/tools/read_webpage_tool.rb +92 -0
- data/lib/legate/tools/sleepy_tool.rb +74 -0
- data/lib/legate/tools/webhook_tool.rb +146 -0
- data/lib/legate/version.rb +5 -0
- data/lib/legate/web/app.rb +984 -0
- data/lib/legate/web/public/css/main.css +4980 -0
- data/lib/legate/web/public/images/favicon-256.png +0 -0
- data/lib/legate/web/public/images/favicon-32.png +0 -0
- data/lib/legate/web/public/images/legate-logo-dark.png +0 -0
- data/lib/legate/web/public/images/legate-logo-light.png +0 -0
- data/lib/legate/web/public/js/legate.js +616 -0
- data/lib/legate/web/public/styles/main.scss +4402 -0
- data/lib/legate/web/routes/agent_authentication_routes.rb +530 -0
- data/lib/legate/web/routes/agent_definition_routes.rb +803 -0
- data/lib/legate/web/routes/agent_generator_routes.rb +80 -0
- data/lib/legate/web/routes/agent_interaction_routes.rb +734 -0
- data/lib/legate/web/routes/agent_runtime_routes.rb +323 -0
- data/lib/legate/web/routes/api_routes.rb +56 -0
- data/lib/legate/web/routes/authentication_routes.rb +1541 -0
- data/lib/legate/web/routes/core_routes.rb +111 -0
- data/lib/legate/web/routes/documentation_routes.rb +220 -0
- data/lib/legate/web/routes/tool_generator_routes.rb +81 -0
- data/lib/legate/web/routes/tools_ui_routes.rb +207 -0
- data/lib/legate/web/sass_compiler.rb +73 -0
- data/lib/legate/web/views/_active_session_info.slim +25 -0
- data/lib/legate/web/views/_activity_list.slim +55 -0
- data/lib/legate/web/views/_agent_card.slim +56 -0
- data/lib/legate/web/views/_agent_generator_modal.slim +382 -0
- data/lib/legate/web/views/_agent_status_controls.slim +71 -0
- data/lib/legate/web/views/_agent_tool_table.slim +74 -0
- data/lib/legate/web/views/_chat_message.slim +95 -0
- data/lib/legate/web/views/_display_agent_configuration.slim +26 -0
- data/lib/legate/web/views/_display_agent_description.slim +11 -0
- data/lib/legate/web/views/_display_agent_fallback.slim +15 -0
- data/lib/legate/web/views/_display_agent_hierarchy.slim +93 -0
- data/lib/legate/web/views/_display_agent_instruction.slim +17 -0
- data/lib/legate/web/views/_display_agent_mcp.slim +13 -0
- data/lib/legate/web/views/_display_agent_model.slim +17 -0
- data/lib/legate/web/views/_display_agent_name.slim +42 -0
- data/lib/legate/web/views/_display_agent_output_key.slim +26 -0
- data/lib/legate/web/views/_display_agent_type.slim +65 -0
- data/lib/legate/web/views/_edit_agent_configuration.slim +74 -0
- data/lib/legate/web/views/_edit_agent_description.slim +16 -0
- data/lib/legate/web/views/_edit_agent_fallback.slim +25 -0
- data/lib/legate/web/views/_edit_agent_hierarchy.slim +98 -0
- data/lib/legate/web/views/_edit_agent_instruction.slim +49 -0
- data/lib/legate/web/views/_edit_agent_mcp.slim +33 -0
- data/lib/legate/web/views/_edit_agent_model.slim +23 -0
- data/lib/legate/web/views/_edit_agent_output_key.slim +36 -0
- data/lib/legate/web/views/_edit_agent_tools.slim +40 -0
- data/lib/legate/web/views/_edit_agent_type.slim +67 -0
- data/lib/legate/web/views/_session_error.slim +4 -0
- data/lib/legate/web/views/_skeleton.slim +69 -0
- data/lib/legate/web/views/_tool_card.slim +9 -0
- data/lib/legate/web/views/_tool_generator_modal.slim +311 -0
- data/lib/legate/web/views/agent.slim +436 -0
- data/lib/legate/web/views/agent_auth.slim +562 -0
- data/lib/legate/web/views/agents.slim +369 -0
- data/lib/legate/web/views/auth.slim +112 -0
- data/lib/legate/web/views/auth_credential_detail.slim +327 -0
- data/lib/legate/web/views/auth_credentials.slim +261 -0
- data/lib/legate/web/views/auth_debug.slim +94 -0
- data/lib/legate/web/views/auth_mapping_detail.slim +151 -0
- data/lib/legate/web/views/auth_mapping_new.slim +123 -0
- data/lib/legate/web/views/auth_mappings.slim +120 -0
- data/lib/legate/web/views/auth_scheme_detail.slim +274 -0
- data/lib/legate/web/views/auth_schemes.slim +259 -0
- data/lib/legate/web/views/auth_test.slim +418 -0
- data/lib/legate/web/views/chat.slim +192 -0
- data/lib/legate/web/views/docs_index.slim +105 -0
- data/lib/legate/web/views/docs_show.slim +105 -0
- data/lib/legate/web/views/error_404.slim +5 -0
- data/lib/legate/web/views/index.slim +148 -0
- data/lib/legate/web/views/layout.slim +144 -0
- data/lib/legate/web/views/tool_detail.slim +87 -0
- data/lib/legate/web/views/tools.slim +50 -0
- data/lib/legate/web/webhook_listener.rb +367 -0
- data/lib/legate/web.rb +9 -0
- data/lib/legate.rb +220 -0
- data/public/docs/advanced/callbacks.md +828 -0
- data/public/docs/advanced/mcp_schema_conversion.md +59 -0
- data/public/docs/authentication/api_reference/config.md +210 -0
- data/public/docs/authentication/api_reference/credential.md +246 -0
- data/public/docs/authentication/api_reference/encryption.md +218 -0
- data/public/docs/authentication/api_reference/exchanged_credential.md +271 -0
- data/public/docs/authentication/api_reference/excon_middleware.md +175 -0
- data/public/docs/authentication/api_reference/index.md +30 -0
- data/public/docs/authentication/api_reference/scheme.md +250 -0
- data/public/docs/authentication/api_reference/schemes/api_key.md +175 -0
- data/public/docs/authentication/api_reference/schemes/google_service_account.md +221 -0
- data/public/docs/authentication/api_reference/schemes/http_bearer.md +169 -0
- data/public/docs/authentication/api_reference/schemes/oauth2.md +343 -0
- data/public/docs/authentication/api_reference/schemes/oidc.md +73 -0
- data/public/docs/authentication/api_reference/schemes/openid_connect.md +311 -0
- data/public/docs/authentication/api_reference/schemes/service_account.md +287 -0
- data/public/docs/authentication/api_reference/token_manager.md +221 -0
- data/public/docs/authentication/api_reference/token_store.md +146 -0
- data/public/docs/authentication/api_reference/tool_context_extension.md +166 -0
- data/public/docs/authentication/guides/api_key.md +190 -0
- data/public/docs/authentication/guides/bearer.md +172 -0
- data/public/docs/authentication/guides/configuration.md +255 -0
- data/public/docs/authentication/guides/custom_flow.md +523 -0
- data/public/docs/authentication/guides/index.md +24 -0
- data/public/docs/authentication/guides/migration.md +435 -0
- data/public/docs/authentication/guides/oauth2.md +252 -0
- data/public/docs/authentication/guides/oidc.md +241 -0
- data/public/docs/authentication/guides/overview.md +155 -0
- data/public/docs/authentication/guides/secure_storage.md +301 -0
- data/public/docs/authentication/guides/service_account.md +228 -0
- data/public/docs/authentication/guides/token_lifecycle.md +295 -0
- data/public/docs/authentication/guides/web_ui_integration.md +504 -0
- data/public/docs/authentication/index.md +58 -0
- data/public/docs/authentication/troubleshooting/credential_storage.md +550 -0
- data/public/docs/authentication/troubleshooting/environment_variables.md +540 -0
- data/public/docs/authentication/troubleshooting/index.md +11 -0
- data/public/docs/authentication/troubleshooting/oauth2_issues.md +220 -0
- data/public/docs/authentication/troubleshooting/oidc_issues.md +412 -0
- data/public/docs/authentication/troubleshooting/token_refresh.md +338 -0
- data/public/docs/cli/legate_cli_usage.md +363 -0
- data/public/docs/core_concepts/legate_agent_lifecycle.md +124 -0
- data/public/docs/core_concepts/legate_architecture_overview.md +110 -0
- data/public/docs/core_concepts/legate_configuration.md +116 -0
- data/public/docs/core_concepts/legate_definition_store.md +102 -0
- data/public/docs/core_concepts/legate_planner.md +94 -0
- data/public/docs/core_concepts/legate_session_service.md +104 -0
- data/public/docs/error_handling/legate_error_handling.md +122 -0
- data/public/docs/examples.md +199 -0
- data/public/docs/getting_started.md +111 -0
- data/public/docs/guides/agentic_agents.md +137 -0
- data/public/docs/guides/ai_code_generators.md +437 -0
- data/public/docs/guides/auto_loading.md +326 -0
- data/public/docs/guides/configuring_agent_webhooks.md +219 -0
- data/public/docs/guides/http_client_usage.md +264 -0
- data/public/docs/guides/llm_providers.md +137 -0
- data/public/docs/guides/mcp_client_integration.md +232 -0
- data/public/docs/guides/mcp_server_exposure.md +206 -0
- data/public/docs/guides/rails_integration.md +128 -0
- data/public/docs/guides/sending_outbound_webhooks.md +227 -0
- data/public/docs/guides/streaming.md +112 -0
- data/public/docs/guides/webhooks.md +288 -0
- data/public/docs/introduction.md +51 -0
- data/public/docs/multi_agent_systems/advanced_features.md +57 -0
- data/public/docs/multi_agent_systems/agent_delegation.md +190 -0
- data/public/docs/multi_agent_systems/agent_hierarchy.md +49 -0
- data/public/docs/multi_agent_systems/state_management.md +47 -0
- data/public/docs/multi_agent_systems/workflow_agents.md +72 -0
- data/public/docs/tools/legate_built_in_tools.md +332 -0
- data/public/docs/tools/legate_tools_and_registry.md +263 -0
- data/public/docs/web_ui/legate_web_ui.md +137 -0
- metadata +823 -0
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
# File: lib/legate/web/routes/agent_interaction_routes.rb
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
module Legate
|
|
5
|
+
module Web
|
|
6
|
+
module AgentInteractionRoutes
|
|
7
|
+
# Helper to update the last_run_at timestamp for an agent
|
|
8
|
+
def self.update_agent_last_run(definition_store, agent_name, logger)
|
|
9
|
+
return unless definition_store
|
|
10
|
+
|
|
11
|
+
begin
|
|
12
|
+
definition_store.update_definition(agent_name, { 'last_run_at' => Time.now.iso8601 })
|
|
13
|
+
logger.debug("Updated last_run_at for agent '#{agent_name}'")
|
|
14
|
+
rescue StandardError => e
|
|
15
|
+
logger.warn("Failed to update last_run_at for agent '#{agent_name}': #{e.message}")
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
def self.registered(app)
|
|
20
|
+
# GET /agents/:name/chat - Display the chat interface for an agent.
|
|
21
|
+
app.get '/agents/:name/chat' do |name|
|
|
22
|
+
logger.debug "GET /agents/#{name}/chat: Entry. web_user_id: #{session[:web_user_id]}, session_id: #{request.session_options[:id]}"
|
|
23
|
+
# `self` is the Sinatra app instance
|
|
24
|
+
definition_store = instance_variable_get(:@definition_store)
|
|
25
|
+
session_service = instance_variable_get(:@session_service)
|
|
26
|
+
active_agents_hash = instance_variable_get(:@agents)
|
|
27
|
+
|
|
28
|
+
halt 503, 'Definition Store unavailable.' unless definition_store
|
|
29
|
+
halt 503, 'Session Service unavailable.' unless session_service # Added check for session_service
|
|
30
|
+
|
|
31
|
+
agent_definition = nil
|
|
32
|
+
begin
|
|
33
|
+
agent_definition = definition_store.get_definition(name)
|
|
34
|
+
rescue Legate::DefinitionStore::StoreError => e
|
|
35
|
+
logger.error("Store error fetching definition for '#{name}' chat (from AgentInteractionRoutes): #{e.message}")
|
|
36
|
+
halt 500, 'Error retrieving agent definition.'
|
|
37
|
+
end
|
|
38
|
+
unless agent_definition
|
|
39
|
+
logger.warn("Agent definition not found for '#{name}' in store (GET /chat from AgentInteractionRoutes).")
|
|
40
|
+
halt 404,
|
|
41
|
+
slim(:error_404, locals: { title: 'Agent Not Found', message: "Definition for '#{name}' not found." })
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
agent_description_for_view = agent_definition[:description]
|
|
45
|
+
is_running = active_agents_hash.key?(name)
|
|
46
|
+
web_user_id = session[:web_user_id] # From the before filter
|
|
47
|
+
|
|
48
|
+
# --- BEGIN NEW MULTI-SESSION LOGIC ---
|
|
49
|
+
active_session_id = nil
|
|
50
|
+
active_session_object = nil
|
|
51
|
+
session_load_error_occurred = false # Flag if a chosen session ID failed to load
|
|
52
|
+
|
|
53
|
+
# Initialize Sinatra session structure for storing active sessions per agent
|
|
54
|
+
session[:active_agent_sessions] ||= {}
|
|
55
|
+
|
|
56
|
+
# 1. Check for 'desired_session_id' query parameter
|
|
57
|
+
desired_id_from_param = params[:desired_session_id]
|
|
58
|
+
if desired_id_from_param
|
|
59
|
+
logger.debug "Attempting to use desired_session_id: #{desired_id_from_param} for agent '#{name}', user '#{web_user_id}'"
|
|
60
|
+
begin
|
|
61
|
+
potential_session = session_service.get_session(session_id: desired_id_from_param)
|
|
62
|
+
if potential_session && potential_session.user_id == web_user_id && potential_session.app_name == name
|
|
63
|
+
active_session_id = desired_id_from_param
|
|
64
|
+
active_session_object = potential_session
|
|
65
|
+
logger.info "Successfully loaded session via desired_session_id: #{active_session_id}"
|
|
66
|
+
else
|
|
67
|
+
logger.warn "desired_session_id '#{desired_id_from_param}' is invalid, not found, or does not belong to user '#{web_user_id}' for agent '#{name}'. Ignoring."
|
|
68
|
+
end
|
|
69
|
+
rescue StandardError => e
|
|
70
|
+
logger.error "Error trying to load desired_session_id '#{desired_id_from_param}': #{e.message}"
|
|
71
|
+
session_load_error_occurred = true
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# 2. If no active session yet, try the stored active ID from the Sinatra session
|
|
76
|
+
unless active_session_id
|
|
77
|
+
stored_active_id = session[:active_agent_sessions][name]
|
|
78
|
+
if stored_active_id
|
|
79
|
+
logger.debug "Attempting to use stored active session ID: #{stored_active_id} for agent '#{name}', user '#{web_user_id}'"
|
|
80
|
+
begin
|
|
81
|
+
potential_session = session_service.get_session(session_id: stored_active_id)
|
|
82
|
+
if potential_session && potential_session.user_id == web_user_id && potential_session.app_name == name
|
|
83
|
+
active_session_id = stored_active_id
|
|
84
|
+
active_session_object = potential_session
|
|
85
|
+
logger.info "Successfully loaded stored active session ID: #{active_session_id}"
|
|
86
|
+
else
|
|
87
|
+
logger.warn "Stored active session ID '#{stored_active_id}' is stale or invalid for user '#{web_user_id}' / agent '#{name}'. Clearing it."
|
|
88
|
+
session[:active_agent_sessions].delete(name)
|
|
89
|
+
session_load_error_occurred = true
|
|
90
|
+
end
|
|
91
|
+
rescue StandardError => e
|
|
92
|
+
logger.error "Error trying to load stored active session ID '#{stored_active_id}': #{e.message}"
|
|
93
|
+
session[:active_agent_sessions].delete(name) # Clear if error
|
|
94
|
+
session_load_error_occurred = true
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
# 3. If still no active session, list all sessions for the user/agent and pick the most recently updated
|
|
100
|
+
unless active_session_id
|
|
101
|
+
logger.debug "No valid active session from params or Sinatra session. Listing sessions for agent '#{name}', user '#{web_user_id}'"
|
|
102
|
+
begin
|
|
103
|
+
user_agent_sessions = session_service.list_sessions(app_name: name, user_id: web_user_id)
|
|
104
|
+
if user_agent_sessions && !user_agent_sessions.empty?
|
|
105
|
+
latest_session = user_agent_sessions.sort_by(&:updated_at).last
|
|
106
|
+
if latest_session
|
|
107
|
+
active_session_id = latest_session.id
|
|
108
|
+
active_session_object = latest_session
|
|
109
|
+
logger.info "Found existing sessions. Set active to most recently updated: #{active_session_id}"
|
|
110
|
+
else
|
|
111
|
+
logger.warn "list_sessions for agent '#{name}', user '#{web_user_id}' returned sortable but empty/nil data."
|
|
112
|
+
session_load_error_occurred = true
|
|
113
|
+
end
|
|
114
|
+
else
|
|
115
|
+
logger.info "No existing sessions found for agent '#{name}', user '#{web_user_id}'. Will create a new one."
|
|
116
|
+
end
|
|
117
|
+
rescue StandardError => e
|
|
118
|
+
logger.error "Error listing sessions for agent '#{name}', user '#{web_user_id}': #{e.message}"
|
|
119
|
+
halt 500, 'Error retrieving session list.'
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# 4. If still no active session object, create a new one.
|
|
124
|
+
unless active_session_object
|
|
125
|
+
logger.info "No active session determined or loaded. Creating new session for agent '#{name}', user '#{web_user_id}'."
|
|
126
|
+
logger.warn 'Proceeding to create new session because a previous attempt to load a specific session failed.' if session_load_error_occurred
|
|
127
|
+
begin
|
|
128
|
+
new_session = session_service.create_session(app_name: name, user_id: web_user_id, initial_state: {})
|
|
129
|
+
active_session_id = new_session.id
|
|
130
|
+
active_session_object = new_session
|
|
131
|
+
logger.info "Created new Legate session: #{active_session_id}"
|
|
132
|
+
session_load_error_occurred = false
|
|
133
|
+
rescue StandardError => e
|
|
134
|
+
logger.error "Failed to create new Legate session for agent '#{name}', user '#{web_user_id}': #{e.message}"
|
|
135
|
+
halt 500, 'Failed to initialize chat session.'
|
|
136
|
+
end
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# 5. Ensure the determined active Legate session ID is stored in the Sinatra session
|
|
140
|
+
if active_session_id
|
|
141
|
+
session[:active_agent_sessions][name] = active_session_id
|
|
142
|
+
logger.debug "Ensured active Legate session ID '#{active_session_id}' is stored for agent '#{name}'."
|
|
143
|
+
else
|
|
144
|
+
logger.fatal "CRITICAL: Could not determine or create an active session ID for agent '#{name}', user '#{web_user_id}'. Halting."
|
|
145
|
+
halt 500, 'Critical error: Unable to establish an active chat session.'
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
logger.warn 'A previously selected or stored session could not be loaded. A new session was started or the latest available was used.' if session_load_error_occurred
|
|
149
|
+
|
|
150
|
+
# 6. Load chat history for the active session
|
|
151
|
+
chat_history_events_list = active_session_object&.events || []
|
|
152
|
+
logger.debug "Loaded #{chat_history_events_list.count} events for active session '#{active_session_id}'"
|
|
153
|
+
|
|
154
|
+
# 7. Load all sessions for this agent/user for the sidebar list
|
|
155
|
+
previous_sessions_list = []
|
|
156
|
+
begin
|
|
157
|
+
all_sessions_for_user_agent = session_service.list_sessions(app_name: name, user_id: web_user_id)
|
|
158
|
+
if all_sessions_for_user_agent
|
|
159
|
+
previous_sessions_list = all_sessions_for_user_agent.sort_by(&:updated_at).reverse
|
|
160
|
+
logger.debug "Loaded #{previous_sessions_list.count} total sessions for agent '#{name}', user '#{web_user_id}' for sidebar."
|
|
161
|
+
end
|
|
162
|
+
rescue StandardError => e
|
|
163
|
+
logger.error "Failed to load all previous sessions list for agent '#{name}', user '#{web_user_id}': #{e.message}"
|
|
164
|
+
end
|
|
165
|
+
# --- END NEW MULTI-SESSION LOGIC ---
|
|
166
|
+
|
|
167
|
+
instance_variable_set(:@agent_data,
|
|
168
|
+
{ name: name,
|
|
169
|
+
description: agent_description_for_view,
|
|
170
|
+
running: is_running,
|
|
171
|
+
model: agent_definition[:model] || agent_definition[:model_name],
|
|
172
|
+
configured_tools: agent_definition[:tools] || agent_definition[:configured_tools] || [] })
|
|
173
|
+
instance_variable_set(:@active_session_details, active_session_object)
|
|
174
|
+
instance_variable_set(:@previous_sessions_list, previous_sessions_list)
|
|
175
|
+
instance_variable_set(:@chat_history_events, chat_history_events_list)
|
|
176
|
+
slim :chat
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# POST /agents/:name/chat - Process a user message from the chat interface.
|
|
180
|
+
app.post '/agents/:name/chat' do |name|
|
|
181
|
+
content_type :html
|
|
182
|
+
active_agents_hash = instance_variable_get(:@agents)
|
|
183
|
+
session_service = instance_variable_get(:@session_service)
|
|
184
|
+
web_user_id = session[:web_user_id]
|
|
185
|
+
|
|
186
|
+
current_agent_instance = active_agents_hash[name]
|
|
187
|
+
user_message_text = params['message']&.strip
|
|
188
|
+
|
|
189
|
+
session[:active_agent_sessions] ||= {}
|
|
190
|
+
active_session_id = session[:active_agent_sessions][name]
|
|
191
|
+
|
|
192
|
+
view_locals = {
|
|
193
|
+
user_message: user_message_text || '[Empty Message]',
|
|
194
|
+
agent_result: nil,
|
|
195
|
+
agent_name: current_agent_instance ? current_agent_instance.name : name
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
current_session_object = nil
|
|
199
|
+
if active_session_id
|
|
200
|
+
begin
|
|
201
|
+
current_session_object = session_service.get_session(session_id: active_session_id)
|
|
202
|
+
unless current_session_object && current_session_object.user_id == web_user_id && current_session_object.app_name == name
|
|
203
|
+
logger.error("Chat POST Error: Active session ID '#{active_session_id}' is invalid. Redirecting.")
|
|
204
|
+
session[:active_agent_sessions].delete(name)
|
|
205
|
+
redirect "/agents/#{name}/chat"
|
|
206
|
+
end
|
|
207
|
+
rescue StandardError => e
|
|
208
|
+
logger.error("Chat POST Error: Failed to retrieve session '#{active_session_id}': #{e.message}. Redirecting.")
|
|
209
|
+
session[:active_agent_sessions].delete(name)
|
|
210
|
+
redirect "/agents/#{name}/chat"
|
|
211
|
+
end
|
|
212
|
+
else
|
|
213
|
+
logger.error("Chat POST Error: No active Legate session ID found for agent '#{name}'. Redirecting.")
|
|
214
|
+
redirect "/agents/#{name}/chat"
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
unless current_agent_instance
|
|
218
|
+
view_locals[:agent_result] = { status: :error, error_message: "[Error: Agent '#{name}' is not running.]" }
|
|
219
|
+
halt 400, slim(:_chat_message, layout: false, locals: view_locals)
|
|
220
|
+
end
|
|
221
|
+
if user_message_text.nil? || user_message_text.empty?
|
|
222
|
+
view_locals[:agent_result] = { status: :error, error_message: '[Error: Message cannot be empty.]' }
|
|
223
|
+
halt 400, slim(:_chat_message, layout: false, locals: view_locals)
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
begin
|
|
227
|
+
logger.info("Agent '#{name}' processing chat in session '#{active_session_id}' for user '#{web_user_id}': #{user_message_text}")
|
|
228
|
+
final_event_or_error = current_agent_instance.run_task(
|
|
229
|
+
session_id: active_session_id,
|
|
230
|
+
user_input: user_message_text,
|
|
231
|
+
session_service: session_service
|
|
232
|
+
)
|
|
233
|
+
logger.info("Agent '#{name}' task processing complete for session '#{active_session_id}'. Final result: #{final_event_or_error.inspect}")
|
|
234
|
+
view_locals[:agent_result] = final_event_or_error
|
|
235
|
+
|
|
236
|
+
# Track last run time
|
|
237
|
+
definition_store = instance_variable_get(:@definition_store)
|
|
238
|
+
AgentInteractionRoutes.update_agent_last_run(definition_store, name, logger)
|
|
239
|
+
|
|
240
|
+
updated_session_object = nil
|
|
241
|
+
if current_session_object
|
|
242
|
+
begin
|
|
243
|
+
updated_session_object = session_service.get_session(session_id: current_session_object.id)
|
|
244
|
+
rescue StandardError => e
|
|
245
|
+
logger.error("Chat POST: Failed to re-fetch session '#{current_session_object.id}' for stats update: #{e.message}")
|
|
246
|
+
updated_session_object = current_session_object
|
|
247
|
+
end
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
chat_message_html = slim(:_chat_message, layout: false, locals: view_locals)
|
|
251
|
+
session_info_inner_html = slim(:_active_session_info, layout: false,
|
|
252
|
+
locals: { active_session_details: updated_session_object })
|
|
253
|
+
active_session_info_oob_wrapper_html = %(<div id="active-session-info" class="mt-2" hx-swap-oob="outerHTML">#{session_info_inner_html}</div>)
|
|
254
|
+
|
|
255
|
+
status 200
|
|
256
|
+
chat_message_html + active_session_info_oob_wrapper_html
|
|
257
|
+
rescue StandardError => e
|
|
258
|
+
logger.error("Error processing chat for agent #{name}, session '#{active_session_id}': #{e.class} - #{e.message}\n#{e.backtrace.join("\n")}")
|
|
259
|
+
view_locals[:agent_result] =
|
|
260
|
+
{ status: :error, error_message: "[Internal Error executing task: #{e.message}]" }
|
|
261
|
+
halt 500, slim(:_chat_message, layout: false, locals: view_locals)
|
|
262
|
+
end
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
# POST /agents/:name/stream - Run a task and stream lifecycle events as
|
|
266
|
+
# Server-Sent Events (R3). Each appended event is emitted as an
|
|
267
|
+
# `event: message` frame the instant it happens; the run ends with an
|
|
268
|
+
# `event: done` frame carrying the final result (or `event: error`).
|
|
269
|
+
# Consume with fetch() streaming (CSRF-protected, so EventSource can't be
|
|
270
|
+
# used directly). Creates a fresh one-shot session per request.
|
|
271
|
+
app.post '/agents/:name/stream' do
|
|
272
|
+
name = params[:name]
|
|
273
|
+
active_agents_hash = instance_variable_get(:@agents)
|
|
274
|
+
session_service = instance_variable_get(:@session_service)
|
|
275
|
+
agent_instance = active_agents_hash[name]
|
|
276
|
+
message = params['message'].to_s
|
|
277
|
+
web_user_id = session[:web_user_id]
|
|
278
|
+
|
|
279
|
+
content_type 'text/event-stream'
|
|
280
|
+
headers 'Cache-Control' => 'no-cache', 'X-Accel-Buffering' => 'no'
|
|
281
|
+
|
|
282
|
+
stream do |out|
|
|
283
|
+
write_sse = lambda do |type, data|
|
|
284
|
+
out << "event: #{type}\ndata: #{JSON.generate(data)}\n\n"
|
|
285
|
+
end
|
|
286
|
+
|
|
287
|
+
if agent_instance.nil?
|
|
288
|
+
write_sse.call('error', { error_message: "Agent '#{name}' is not running." })
|
|
289
|
+
elsif message.empty?
|
|
290
|
+
write_sse.call('error', { error_message: "Missing 'message'." })
|
|
291
|
+
else
|
|
292
|
+
begin
|
|
293
|
+
legate_session = session_service.create_session(app_name: name, user_id: web_user_id)
|
|
294
|
+
final = agent_instance.run_task(
|
|
295
|
+
session_id: legate_session.id, user_input: message, session_service: session_service,
|
|
296
|
+
on_event: ->(event) { write_sse.call('message', event.to_h) }
|
|
297
|
+
)
|
|
298
|
+
write_sse.call('done', final.to_h)
|
|
299
|
+
rescue StandardError => e
|
|
300
|
+
logger.error("Stream error for agent '#{name}': #{e.class}: #{e.message}")
|
|
301
|
+
write_sse.call('error', { error_message: e.message })
|
|
302
|
+
end
|
|
303
|
+
end
|
|
304
|
+
end
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
# POST /agents/:name/execute - Execute a task directly via JSON input.
|
|
308
|
+
app.post '/agents/:name/execute' do
|
|
309
|
+
name = params[:name]
|
|
310
|
+
content_type :html # Change to HTML for the richer response
|
|
311
|
+
active_agents_hash = instance_variable_get(:@agents)
|
|
312
|
+
session_service = instance_variable_get(:@session_service)
|
|
313
|
+
agent_instance = active_agents_hash[name]
|
|
314
|
+
final_result_content_for_diagram = nil # To store content for mermaid
|
|
315
|
+
task_desc = nil # Initialize task_desc
|
|
316
|
+
|
|
317
|
+
error_handler = lambda do |message, code = 400|
|
|
318
|
+
# For HTML response, format error differently
|
|
319
|
+
halt code, format_execution_result_html({ status: :error, error_message: message })
|
|
320
|
+
end
|
|
321
|
+
|
|
322
|
+
success_handler = lambda do |result_hash, original_task_description|
|
|
323
|
+
mermaid_diagram_html = ''
|
|
324
|
+
current_final_content = result_hash # Use the direct result_hash
|
|
325
|
+
|
|
326
|
+
if current_final_content.is_a?(Hash) && current_final_content[:plan_details]
|
|
327
|
+
mermaid_def = generate_mermaid_sequence_diagram(current_final_content, original_task_description)
|
|
328
|
+
unless mermaid_def.empty?
|
|
329
|
+
# Ensure unique ID for mermaid modal trigger
|
|
330
|
+
mermaid_button_id = "direct-exec-mermaid-btn-#{name.gsub(/[^a-zA-Z0-9_-]/, '-')}-#{SecureRandom.hex(4)}"
|
|
331
|
+
mermaid_diagram_html = <<~HTML
|
|
332
|
+
<div class="mt-3 pt-3" style="border-top: 1px dashed #ccc;">
|
|
333
|
+
<button class="button is-small is-info is-light mb-2 show-mermaid-flow-btn"
|
|
334
|
+
id="#{mermaid_button_id}"
|
|
335
|
+
data-mermaid-definition="#{Rack::Utils.escape_html(mermaid_def)}">
|
|
336
|
+
<span class="icon is-small"><i class="fas fa-project-diagram"></i></span>
|
|
337
|
+
<span>Toggle Execution Flow</span>
|
|
338
|
+
</button>
|
|
339
|
+
</div>
|
|
340
|
+
HTML
|
|
341
|
+
end
|
|
342
|
+
end
|
|
343
|
+
formatted_result_html = format_execution_result_html(result_hash)
|
|
344
|
+
formatted_result_html + mermaid_diagram_html
|
|
345
|
+
end
|
|
346
|
+
|
|
347
|
+
error_handler.call("Error: Agent '#{name}' not found or not running.", 400) unless agent_instance
|
|
348
|
+
task_json_string = params['task_json']
|
|
349
|
+
unless task_json_string && !task_json_string.empty?
|
|
350
|
+
error_handler.call("Error: Missing 'task_json' data.",
|
|
351
|
+
400)
|
|
352
|
+
end
|
|
353
|
+
|
|
354
|
+
exec_params = nil
|
|
355
|
+
tool_to_exec = nil
|
|
356
|
+
parsed_data = nil
|
|
357
|
+
begin
|
|
358
|
+
parsed_data = JSON.parse(task_json_string)
|
|
359
|
+
if parsed_data.is_a?(Hash)
|
|
360
|
+
if parsed_data.key?('tool_name') && parsed_data.key?('task') && parsed_data.key?('parameters')
|
|
361
|
+
tool_to_exec = parsed_data['tool_name']&.strip
|
|
362
|
+
task_desc = parsed_data['task'] # Used for planner and mermaid
|
|
363
|
+
exec_params = parsed_data['parameters']
|
|
364
|
+
if tool_to_exec.nil? || tool_to_exec.empty?
|
|
365
|
+
error_handler.call("Error: Missing 'tool_name' in JSON for direct execution.",
|
|
366
|
+
400)
|
|
367
|
+
end
|
|
368
|
+
unless exec_params.is_a?(Hash)
|
|
369
|
+
error_handler.call("Error: Missing or invalid 'parameters' object in JSON for direct execution.",
|
|
370
|
+
400)
|
|
371
|
+
end
|
|
372
|
+
elsif parsed_data.key?('task')
|
|
373
|
+
task_desc = parsed_data['task'] # Used for planner and mermaid
|
|
374
|
+
unless (parsed_data.keys - ['task']).empty?
|
|
375
|
+
error_handler.call(
|
|
376
|
+
"Error: Invalid JSON. Use {'task': '...'} or {'tool_name': ..., 'task': ..., 'parameters': {...}}.", 400
|
|
377
|
+
)
|
|
378
|
+
end
|
|
379
|
+
else
|
|
380
|
+
error_handler.call("Error: Invalid JSON structure. Missing 'task' key.", 400)
|
|
381
|
+
end
|
|
382
|
+
else
|
|
383
|
+
error_handler.call('Error: Input must be a JSON object.', 400)
|
|
384
|
+
end
|
|
385
|
+
rescue JSON::ParserError => e
|
|
386
|
+
logger.warn("Invalid JSON for /execute (AgentInteractionRoutes): #{e.message}. Input: #{task_json_string}")
|
|
387
|
+
error_handler.call("Error: Invalid JSON format - #{e.message}", 400)
|
|
388
|
+
end
|
|
389
|
+
if tool_to_exec.nil? && (task_desc.nil? || task_desc.empty?)
|
|
390
|
+
error_handler.call('Error: Missing task description.',
|
|
391
|
+
400)
|
|
392
|
+
end
|
|
393
|
+
|
|
394
|
+
temp_session = nil
|
|
395
|
+
begin
|
|
396
|
+
original_input_for_diagram = task_desc # Capture before potential modification if tool_to_exec
|
|
397
|
+
if tool_to_exec
|
|
398
|
+
logger.info("Agent '#{name}' executing DIRECT tool '#{tool_to_exec}' (AgentInteractionRoutes) with params: #{exec_params.inspect}")
|
|
399
|
+
tool_instance_to_run = agent_instance.find_tool(tool_to_exec.to_sym)
|
|
400
|
+
unless tool_instance_to_run
|
|
401
|
+
error_handler.call("Error: Tool '#{tool_to_exec}' not configured for agent '#{name}'.",
|
|
402
|
+
400)
|
|
403
|
+
end
|
|
404
|
+
temp_session = session_service.create_session(app_name: name,
|
|
405
|
+
user_id: "web_direct_#{SecureRandom.hex(4)}")
|
|
406
|
+
tool_ctx = Legate::ToolContext.new(session_id: temp_session.id, user_id: temp_session.user_id,
|
|
407
|
+
app_name: temp_session.app_name, tool_registry: agent_instance.tool_registry)
|
|
408
|
+
result = tool_instance_to_run.execute(exec_params.transform_keys(&:to_sym), tool_ctx)
|
|
409
|
+
# For direct tool execution, plan_details might not exist unless the tool itself populates it (unlikely)
|
|
410
|
+
# To ensure mermaid can work, we can construct a minimal plan_details for this single step.
|
|
411
|
+
# This makes the success_handler's mermaid logic more robust.
|
|
412
|
+
minimal_plan_details = [{ tool_name: tool_to_exec.to_sym, params: exec_params.transform_keys(&:to_sym),
|
|
413
|
+
result: result }]
|
|
414
|
+
final_result_content_for_diagram = result.merge(plan_details: minimal_plan_details)
|
|
415
|
+
# Track last run time
|
|
416
|
+
definition_store = instance_variable_get(:@definition_store)
|
|
417
|
+
AgentInteractionRoutes.update_agent_last_run(definition_store, name, logger)
|
|
418
|
+
success_handler.call(final_result_content_for_diagram, original_input_for_diagram)
|
|
419
|
+
else
|
|
420
|
+
logger.info("Agent '#{name}' executing task via PLANNER (AgentInteractionRoutes): #{task_desc}")
|
|
421
|
+
temp_session = session_service.create_session(app_name: name,
|
|
422
|
+
user_id: "web_direct_#{SecureRandom.hex(4)}")
|
|
423
|
+
final_result = agent_instance.run_task(session_id: temp_session.id, user_input: task_desc,
|
|
424
|
+
session_service: session_service)
|
|
425
|
+
content_to_show = final_result.is_a?(Legate::Event) ? final_result.content : final_result
|
|
426
|
+
# Track last run time
|
|
427
|
+
definition_store = instance_variable_get(:@definition_store)
|
|
428
|
+
AgentInteractionRoutes.update_agent_last_run(definition_store, name, logger)
|
|
429
|
+
success_handler.call(content_to_show, original_input_for_diagram)
|
|
430
|
+
end
|
|
431
|
+
rescue StandardError => e
|
|
432
|
+
logger.error "Error during agent execution for '#{name}' (AgentInteractionRoutes): #{e.class} - #{e.message}\n#{e.backtrace.join("\n")}"
|
|
433
|
+
error_handler.call("Error: Internal server error during task execution: #{e.message}", 500)
|
|
434
|
+
ensure
|
|
435
|
+
session_service.delete_session(session_id: temp_session.id) if temp_session
|
|
436
|
+
end
|
|
437
|
+
end
|
|
438
|
+
|
|
439
|
+
# GET /agents/:name/generate_example_task - Generate example task JSON for an agent.
|
|
440
|
+
app.get '/agents/:name/generate_example_task' do |name|
|
|
441
|
+
content_type :json
|
|
442
|
+
logger.info("Generating example task for agent: #{name} (from AgentInteractionRoutes)")
|
|
443
|
+
definition_store = instance_variable_get(:@definition_store)
|
|
444
|
+
halt 503, json(error: 'Definition Store unavailable.') unless definition_store
|
|
445
|
+
|
|
446
|
+
agent_definition = definition_store.get_definition(name)
|
|
447
|
+
halt 404, json(error: "Agent definition not found for '#{name}'") unless agent_definition
|
|
448
|
+
|
|
449
|
+
agent_model_name = agent_definition[:model]
|
|
450
|
+
configured_tool_names_str = agent_definition[:tools]
|
|
451
|
+
mcp_servers_config_json = agent_definition[:mcp_servers_json]
|
|
452
|
+
|
|
453
|
+
configured_tool_syms_list = configured_tool_names_str.map(&:to_sym)
|
|
454
|
+
|
|
455
|
+
return json(example: { task: "Agent '#{name}' has no tools. Cannot generate example." }) if configured_tool_syms_list.empty? && mcp_servers_config_json == '[]'
|
|
456
|
+
|
|
457
|
+
native_tools_meta = Legate::GlobalToolManager.list_all_tools.map do |tm|
|
|
458
|
+
params = []
|
|
459
|
+
if tm[:parameters].is_a?(Hash) && !tm[:parameters].empty?
|
|
460
|
+
tm[:parameters].each { |pn, d|
|
|
461
|
+
params << { name: pn, type: d[:type], description: d[:description], required: d[:required] }
|
|
462
|
+
}
|
|
463
|
+
end
|
|
464
|
+
tm.merge(parameters: params, source: :native)
|
|
465
|
+
end
|
|
466
|
+
|
|
467
|
+
mcp_configs_list = begin
|
|
468
|
+
JSON.parse(mcp_servers_config_json)
|
|
469
|
+
rescue StandardError
|
|
470
|
+
[]
|
|
471
|
+
end
|
|
472
|
+
mcp_fetch_results = fetch_mcp_tools(mcp_configs_list) # Helper method from app instance
|
|
473
|
+
|
|
474
|
+
mcp_tools_meta = []
|
|
475
|
+
mcp_fetch_results.each do |res|
|
|
476
|
+
next unless res[:status] == :success && res[:tools]
|
|
477
|
+
|
|
478
|
+
res[:tools].each do |schema|
|
|
479
|
+
params = Legate::Mcp::Util::SchemaConverter.json_to_legate(schema.dig(:inputSchema, 'properties') || {},
|
|
480
|
+
schema.dig(:inputSchema, 'required') || [])
|
|
481
|
+
mcp_tools_meta << { name: schema[:name].to_sym, description: schema[:description] || '',
|
|
482
|
+
parameters: params, source: :mcp }
|
|
483
|
+
end
|
|
484
|
+
end
|
|
485
|
+
|
|
486
|
+
all_tools_map = (native_tools_meta + mcp_tools_meta).each_with_object({}) { |t, map| map[t[:name]] ||= t }
|
|
487
|
+
final_configured_tools_meta = configured_tool_syms_list.map { |sym| all_tools_map[sym] }.compact
|
|
488
|
+
|
|
489
|
+
return json(example: { task: "Agent '#{name}' tools metadata incomplete. Cannot generate." }) if final_configured_tools_meta.empty?
|
|
490
|
+
|
|
491
|
+
tool_details_for_prompt = final_configured_tools_meta.map do |meta|
|
|
492
|
+
params_str = if meta[:parameters].empty?
|
|
493
|
+
'None'
|
|
494
|
+
else
|
|
495
|
+
meta[:parameters].map { |p|
|
|
496
|
+
"#{p[:name]} (#{p[:type]}, #{p[:required] ? 'required' : 'optional'})"
|
|
497
|
+
}.join(', ')
|
|
498
|
+
end
|
|
499
|
+
"- Tool: #{meta[:name]}\n Description: #{meta[:description]}\n Parameters: #{params_str}"
|
|
500
|
+
end.join("\n")
|
|
501
|
+
|
|
502
|
+
gemini_prompt = <<~PROMPT
|
|
503
|
+
Based on the following tools configured for an agent, generate a single, simple example JSON object representing a task that uses ONE of these tools.
|
|
504
|
+
|
|
505
|
+
The JSON object MUST follow this exact structure:
|
|
506
|
+
{ "tool_name": "chosen_tool_name", "task": "A brief description of what the example task does", "parameters": { /* parameters for the chosen tool */ } }
|
|
507
|
+
|
|
508
|
+
**Instructions for choosing a tool and generating parameters:**
|
|
509
|
+
1. ** You can pick any tool you want. Do not pick the calculator or cat fact tool every time if others are available. **
|
|
510
|
+
2. If multiple tools have required parameters, choose one that seems suitable for a simple example.
|
|
511
|
+
3. If no tools have required parameters, you may choose a tool with only optional parameters or one with no parameters.
|
|
512
|
+
4. If the chosen tool has parameters (required or optional), populate the `parameters` object in the JSON with plausible example values matching their specified types and descriptions.
|
|
513
|
+
5. **Crucially, if the chosen tool has REQUIRED parameters, the generated `parameters` object MUST include ALL of those required parameters.**
|
|
514
|
+
6. If the chosen tool has no parameters, the `parameters` object MUST be empty: {}.
|
|
515
|
+
7. The `task` description should briefly explain what the example task does.
|
|
516
|
+
8. Include the chosen tool's exact name in the `tool_name` field.
|
|
517
|
+
|
|
518
|
+
Return ONLY the raw JSON object string. Do not include any other text, explanations, markdown formatting like ```json, or anything else.
|
|
519
|
+
|
|
520
|
+
Available Tools:
|
|
521
|
+
---
|
|
522
|
+
#{tool_details_for_prompt}
|
|
523
|
+
---
|
|
524
|
+
You should generate engaging examples!
|
|
525
|
+
Generate the example JSON object now:
|
|
526
|
+
PROMPT
|
|
527
|
+
logger.debug("Gemini Prompt (AgentInteractionRoutes):\n#{gemini_prompt}")
|
|
528
|
+
|
|
529
|
+
begin
|
|
530
|
+
adapter = Legate::LLM.build_adapter(model: agent_model_name)
|
|
531
|
+
halt 503, json(error: 'LLM provider not configured (set GOOGLE_API_KEY for the default Gemini adapter).') unless adapter.available?
|
|
532
|
+
|
|
533
|
+
logger.info("Using model '#{agent_model_name}' for example task generation (AgentInteractionRoutes).")
|
|
534
|
+
generated_json_str = adapter.generate(gemini_prompt, json: true)
|
|
535
|
+
unless generated_json_str && !generated_json_str.strip.empty?
|
|
536
|
+
halt 500,
|
|
537
|
+
json(error: 'AI service returned empty response.')
|
|
538
|
+
end
|
|
539
|
+
|
|
540
|
+
logger.debug("Raw Gemini Response (AgentInteractionRoutes): #{generated_json_str}")
|
|
541
|
+
clean_json_str = generated_json_str.strip.delete_prefix('```json').delete_suffix('```').strip.delete_prefix('```').delete_suffix('```').strip
|
|
542
|
+
|
|
543
|
+
parsed_json_output = JSON.parse(clean_json_str)
|
|
544
|
+
raise JSON::ParserError, 'Generated JSON structure incorrect.' unless parsed_json_output.is_a?(Hash) && parsed_json_output.key?('tool_name') && parsed_json_output.key?('task') && parsed_json_output.key?('parameters')
|
|
545
|
+
|
|
546
|
+
JSON.pretty_generate(parsed_json_output)
|
|
547
|
+
rescue JSON::ParserError => e
|
|
548
|
+
logger.error("Gemini invalid JSON (AgentInteractionRoutes): #{e.message}. Cleaned: #{clean_json_str}")
|
|
549
|
+
halt 500, json(error: "Failed to generate valid JSON example: #{e.message}")
|
|
550
|
+
rescue StandardError => e
|
|
551
|
+
logger.error("Gemini API error (AgentInteractionRoutes): #{e.class} - #{e.message}")
|
|
552
|
+
halt 503, json(error: 'AI service communication error.')
|
|
553
|
+
end
|
|
554
|
+
end
|
|
555
|
+
|
|
556
|
+
# --- NEW ROUTE: Create a new chat session ---
|
|
557
|
+
app.post '/agents/:name/chat/session/new' do |name|
|
|
558
|
+
session_service = instance_variable_get(:@session_service)
|
|
559
|
+
web_user_id = session[:web_user_id]
|
|
560
|
+
|
|
561
|
+
halt 503, 'Session Service unavailable.' unless session_service
|
|
562
|
+
|
|
563
|
+
begin
|
|
564
|
+
logger.info "User '#{web_user_id}' requesting new chat session for agent '#{name}'"
|
|
565
|
+
new_session = session_service.create_session(app_name: name, user_id: web_user_id, initial_state: {})
|
|
566
|
+
logger.info "Created new Legate session '#{new_session.id}' for user '#{web_user_id}', agent '#{name}'"
|
|
567
|
+
|
|
568
|
+
session[:active_agent_sessions] ||= {}
|
|
569
|
+
session[:active_agent_sessions][name] = new_session.id
|
|
570
|
+
logger.debug "Set active session to new session '#{new_session.id}' for agent '#{name}'"
|
|
571
|
+
|
|
572
|
+
if request.env['HTTP_HX_REQUEST'] == 'true'
|
|
573
|
+
definition_store = instance_variable_get(:@definition_store)
|
|
574
|
+
active_agents_hash = instance_variable_get(:@agents)
|
|
575
|
+
agent_definition = definition_store.get_definition(name)
|
|
576
|
+
instance_variable_set(:@agent_data,
|
|
577
|
+
{ name: name, description: agent_definition[:description],
|
|
578
|
+
running: active_agents_hash.key?(name) })
|
|
579
|
+
instance_variable_set(:@active_session_details, new_session)
|
|
580
|
+
instance_variable_set(:@chat_history_events, new_session.events || [])
|
|
581
|
+
all_sessions_for_user_agent = session_service.list_sessions(app_name: name, user_id: web_user_id)
|
|
582
|
+
previous_sessions_list = all_sessions_for_user_agent.sort_by(&:updated_at).reverse
|
|
583
|
+
instance_variable_set(:@previous_sessions_list, previous_sessions_list)
|
|
584
|
+
slim :chat, layout: false
|
|
585
|
+
else
|
|
586
|
+
redirect "/agents/#{name}/chat"
|
|
587
|
+
end
|
|
588
|
+
rescue StandardError => e
|
|
589
|
+
logger.error "Error creating new session for agent '#{name}', user '#{web_user_id}': #{e.message}\n#{e.backtrace.join("\n")}"
|
|
590
|
+
halt 500, 'Failed to create new chat session.'
|
|
591
|
+
end
|
|
592
|
+
end
|
|
593
|
+
# --- END NEW ROUTE ---
|
|
594
|
+
|
|
595
|
+
# --- NEW ROUTE: Switch active chat session ---
|
|
596
|
+
app.post '/agents/:name/chat/session/switch' do |name|
|
|
597
|
+
session_service = instance_variable_get(:@session_service)
|
|
598
|
+
web_user_id = session[:web_user_id]
|
|
599
|
+
legate_session_to_switch_to = params[:legate_session_to_switch_to]
|
|
600
|
+
|
|
601
|
+
halt 503, 'Session Service unavailable.' unless session_service
|
|
602
|
+
halt 400, 'Missing legate_session_to_switch_to parameter.' unless legate_session_to_switch_to
|
|
603
|
+
|
|
604
|
+
logger.info "User '#{web_user_id}' requesting to switch to session '#{legate_session_to_switch_to}' for agent '#{name}'"
|
|
605
|
+
|
|
606
|
+
begin
|
|
607
|
+
potential_session = session_service.get_session(session_id: legate_session_to_switch_to)
|
|
608
|
+
if potential_session && potential_session.user_id == web_user_id && potential_session.app_name == name
|
|
609
|
+
session[:active_agent_sessions] ||= {}
|
|
610
|
+
session[:active_agent_sessions][name] = potential_session.id
|
|
611
|
+
logger.info "Successfully switched active session to '#{potential_session.id}' for user '#{web_user_id}', agent '#{name}'"
|
|
612
|
+
if request.env['HTTP_HX_REQUEST'] == 'true'
|
|
613
|
+
definition_store = instance_variable_get(:@definition_store)
|
|
614
|
+
active_agents_hash = instance_variable_get(:@agents)
|
|
615
|
+
agent_definition = definition_store.get_definition(name)
|
|
616
|
+
instance_variable_set(:@agent_data,
|
|
617
|
+
{ name: name, description: agent_definition[:description],
|
|
618
|
+
running: active_agents_hash.key?(name) })
|
|
619
|
+
instance_variable_set(:@active_session_details, potential_session)
|
|
620
|
+
instance_variable_set(:@chat_history_events, potential_session.events || [])
|
|
621
|
+
all_sessions_for_user_agent = session_service.list_sessions(app_name: name, user_id: web_user_id)
|
|
622
|
+
previous_sessions_list = all_sessions_for_user_agent.sort_by(&:updated_at).reverse
|
|
623
|
+
instance_variable_set(:@previous_sessions_list, previous_sessions_list)
|
|
624
|
+
slim :chat, layout: false
|
|
625
|
+
else
|
|
626
|
+
redirect "/agents/#{name}/chat"
|
|
627
|
+
end
|
|
628
|
+
else
|
|
629
|
+
logger.warn "Failed switch attempt: Session '#{legate_session_to_switch_to}' not found, or does not belong to user '#{web_user_id}' for agent '#{name}'."
|
|
630
|
+
if request.env['HTTP_HX_REQUEST'] == 'true'
|
|
631
|
+
response.headers['HX-Location'] =
|
|
632
|
+
JSON.dump({ path: "/agents/#{name}/chat", target: '#chat_interface_wrapper' })
|
|
633
|
+
halt 200
|
|
634
|
+
else
|
|
635
|
+
redirect "/agents/#{name}/chat"
|
|
636
|
+
end
|
|
637
|
+
end
|
|
638
|
+
rescue StandardError => e
|
|
639
|
+
logger.error "Error switching session for agent '#{name}', user '#{web_user_id}' to '#{legate_session_to_switch_to}': #{e.message}\n#{e.backtrace.join("\n")}"
|
|
640
|
+
halt 500, 'Failed to switch chat session.'
|
|
641
|
+
end
|
|
642
|
+
end
|
|
643
|
+
# --- END NEW ROUTE ---
|
|
644
|
+
|
|
645
|
+
# --- NEW ROUTE: Delete a specific chat session ---
|
|
646
|
+
app.delete '/agents/:name/chat/session/:legate_session_id_to_delete' do |name, legate_session_id_to_delete|
|
|
647
|
+
session_service = instance_variable_get(:@session_service)
|
|
648
|
+
web_user_id = session[:web_user_id]
|
|
649
|
+
|
|
650
|
+
halt 503, 'Session Service unavailable.' unless session_service
|
|
651
|
+
logger.info "User '#{web_user_id}' requesting deletion of session '#{legate_session_id_to_delete}' for agent '#{name}'"
|
|
652
|
+
|
|
653
|
+
session_to_delete = nil
|
|
654
|
+
begin
|
|
655
|
+
session_to_delete = session_service.get_session(session_id: legate_session_id_to_delete)
|
|
656
|
+
unless session_to_delete && session_to_delete.user_id == web_user_id && session_to_delete.app_name == name
|
|
657
|
+
logger.warn "Attempt to delete invalid/unowned session '#{legate_session_id_to_delete}' by user '#{web_user_id}' for agent '#{name}'."
|
|
658
|
+
if request.env['HTTP_HX_REQUEST'] == 'true'
|
|
659
|
+
response.headers['HX-Retarget'] = '#session-operation-error'
|
|
660
|
+
response.headers['HX-Reswap'] = 'outerHTML'
|
|
661
|
+
halt 403,
|
|
662
|
+
slim(:_session_error, layout: false,
|
|
663
|
+
locals: { error_message: 'Forbidden: Cannot delete this session.' })
|
|
664
|
+
else
|
|
665
|
+
redirect "/agents/#{name}/chat", 403
|
|
666
|
+
end
|
|
667
|
+
end
|
|
668
|
+
rescue StandardError => e
|
|
669
|
+
logger.error "Error fetching session '#{legate_session_id_to_delete}' for deletion: #{e.message}"
|
|
670
|
+
if request.env['HTTP_HX_REQUEST'] == 'true'
|
|
671
|
+
response.headers['HX-Retarget'] = '#session-operation-error'
|
|
672
|
+
response.headers['HX-Reswap'] = 'outerHTML'
|
|
673
|
+
halt 500,
|
|
674
|
+
slim(:_session_error, layout: false,
|
|
675
|
+
locals: { error_message: 'Error verifying session for deletion.' })
|
|
676
|
+
else
|
|
677
|
+
redirect "/agents/#{name}/chat", 500
|
|
678
|
+
end
|
|
679
|
+
end
|
|
680
|
+
|
|
681
|
+
begin
|
|
682
|
+
session_service.delete_session(session_id: legate_session_id_to_delete)
|
|
683
|
+
logger.info "Successfully deleted session '#{legate_session_id_to_delete}' for user '#{web_user_id}', agent '#{name}'."
|
|
684
|
+
rescue StandardError => e
|
|
685
|
+
logger.error "Error deleting session '#{legate_session_id_to_delete}': #{e.message}"
|
|
686
|
+
if request.env['HTTP_HX_REQUEST'] == 'true'
|
|
687
|
+
response.headers['HX-Retarget'] = '#session-operation-error'
|
|
688
|
+
response.headers['HX-Reswap'] = 'outerHTML'
|
|
689
|
+
halt 500, slim(:_session_error, layout: false, locals: { error_message: 'Failed to delete session.' })
|
|
690
|
+
else
|
|
691
|
+
redirect "/agents/#{name}/chat", 500
|
|
692
|
+
end
|
|
693
|
+
end
|
|
694
|
+
|
|
695
|
+
session[:active_agent_sessions] ||= {}
|
|
696
|
+
if session[:active_agent_sessions][name] == legate_session_id_to_delete
|
|
697
|
+
logger.info "Deleted session '#{legate_session_id_to_delete}' was the active one for agent '#{name}'. Finding new active session."
|
|
698
|
+
session[:active_agent_sessions].delete(name)
|
|
699
|
+
remaining_sessions = session_service.list_sessions(app_name: name, user_id: web_user_id)
|
|
700
|
+
if remaining_sessions && !remaining_sessions.empty?
|
|
701
|
+
next_active_session = remaining_sessions.sort_by(&:updated_at).last
|
|
702
|
+
session[:active_agent_sessions][name] = next_active_session.id
|
|
703
|
+
logger.info "Set next active session for agent '#{name}' to '#{next_active_session.id}'."
|
|
704
|
+
else
|
|
705
|
+
logger.info "No remaining sessions found for agent '#{name}', user '#{web_user_id}'. Active session cleared."
|
|
706
|
+
end
|
|
707
|
+
end
|
|
708
|
+
|
|
709
|
+
if request.env['HTTP_HX_REQUEST'] == 'true'
|
|
710
|
+
logger.debug 'HTMX request detected for delete session, re-rendering chat interface.'
|
|
711
|
+
definition_store = instance_variable_get(:@definition_store)
|
|
712
|
+
active_agents_hash = instance_variable_get(:@agents)
|
|
713
|
+
agent_definition = definition_store.get_definition(name)
|
|
714
|
+
new_active_session_id = session[:active_agent_sessions][name]
|
|
715
|
+
new_active_session_details = new_active_session_id ? session_service.get_session(session_id: new_active_session_id) : nil
|
|
716
|
+
new_chat_history = new_active_session_details&.events || []
|
|
717
|
+
new_previous_sessions_list = session_service.list_sessions(app_name: name,
|
|
718
|
+
user_id: web_user_id).sort_by(&:updated_at).reverse
|
|
719
|
+
instance_variable_set(:@agent_data,
|
|
720
|
+
{ name: name, description: agent_definition[:description],
|
|
721
|
+
running: active_agents_hash.key?(name) })
|
|
722
|
+
instance_variable_set(:@active_session_details, new_active_session_details)
|
|
723
|
+
instance_variable_set(:@chat_history_events, new_chat_history)
|
|
724
|
+
instance_variable_set(:@previous_sessions_list, new_previous_sessions_list)
|
|
725
|
+
slim :chat, layout: false
|
|
726
|
+
else
|
|
727
|
+
redirect "/agents/#{name}/chat"
|
|
728
|
+
end
|
|
729
|
+
end
|
|
730
|
+
# --- END DELETE ROUTE ---
|
|
731
|
+
end # self.registered
|
|
732
|
+
end
|
|
733
|
+
end
|
|
734
|
+
end
|