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.
Files changed (317) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +345 -0
  4. data/bin/legate +13 -0
  5. data/examples/00_quickstart.rb +51 -0
  6. data/examples/01_simple_agent.rb +105 -0
  7. data/examples/02_multi_tool_agent.rb +140 -0
  8. data/examples/03_custom_tool.rb +93 -0
  9. data/examples/04_agent_instructions.rb +84 -0
  10. data/examples/05_state_and_sessions.rb +91 -0
  11. data/examples/06_callbacks.rb +186 -0
  12. data/examples/07_async_jobs.rb +112 -0
  13. data/examples/08_loop_agent.rb +197 -0
  14. data/examples/09_sequential_workflow.rb +40 -0
  15. data/examples/10_parallel_workflow.rb +34 -0
  16. data/examples/11_agent_delegation.rb +24 -0
  17. data/examples/12_http_client_tool.rb +156 -0
  18. data/examples/13_authentication.rb +220 -0
  19. data/examples/14_mcp_client.rb +154 -0
  20. data/examples/15_mcp_server.rb +79 -0
  21. data/examples/16_webhooks.rb +91 -0
  22. data/examples/README_sequential_agents.md +164 -0
  23. data/examples/advanced/auth/cookie_auth_tool.rb +146 -0
  24. data/examples/advanced/auth/custom_auth_flows_example.rb +626 -0
  25. data/examples/advanced/auth/excon_middleware.rb +317 -0
  26. data/examples/advanced/auth/excon_middleware_auth.rb +399 -0
  27. data/examples/advanced/auth/fiber_auth_example.rb +281 -0
  28. data/examples/advanced/auth/fiber_oidc_example.rb +403 -0
  29. data/examples/advanced/auth/httpbin_bearer_tool.rb +159 -0
  30. data/examples/advanced/auth/oauth2_auth.rb +419 -0
  31. data/examples/advanced/auth/oidc_auth.rb +514 -0
  32. data/examples/advanced/auth/openweather_api.rb +251 -0
  33. data/examples/advanced/auth/openweather_tool.rb +153 -0
  34. data/examples/advanced/auth/query_param_middleware_test.rb +138 -0
  35. data/examples/advanced/auth/service_account.rb +135 -0
  36. data/examples/advanced/auth/test_with_httpbin.rb +202 -0
  37. data/examples/advanced/auth/token_lifecycle_example.rb +428 -0
  38. data/examples/advanced/callback_monitoring.rb +679 -0
  39. data/examples/advanced/mas/fixed_delegation_example.rb +191 -0
  40. data/examples/advanced/mas/loop_workflow.rb +28 -0
  41. data/examples/advanced/mas/mock_planner.rb +77 -0
  42. data/examples/advanced/mas/proper_delegation_example.rb +276 -0
  43. data/examples/advanced/mcp/legate_mcp_server_resource_example.rb +182 -0
  44. data/examples/advanced/mcp/mcp_resource_server_example.rb +309 -0
  45. data/examples/advanced/mcp/mcp_server_async.rb +76 -0
  46. data/examples/advanced/mcp/mcp_server_async_tools.rb +122 -0
  47. data/examples/advanced/mcp/mcp_server_legate_agent.rb +95 -0
  48. data/examples/advanced/mcp/mcp_server_rack.rb +89 -0
  49. data/examples/advanced/random_calculator.rb +104 -0
  50. data/examples/advanced/sleep_agent.rb +153 -0
  51. data/examples/advanced/webhooks/webhook_e2e_runner.rb +110 -0
  52. data/examples/advanced/webhooks/webhook_receiver_agent.rb +58 -0
  53. data/examples/advanced/workflows/task_refinement_loop_agent.rb +278 -0
  54. data/examples/advanced/workflows/travel_planner_auto_sequential.rb +444 -0
  55. data/examples/advanced/workflows/travel_planner_parallel.rb +656 -0
  56. data/examples/advanced/workflows/travel_planner_sequential.rb +512 -0
  57. data/examples/tools/oauth2_example.rb +136 -0
  58. data/examples/tools/sleepy_tool.rb +42 -0
  59. data/lib/legate/activity_log.rb +71 -0
  60. data/lib/legate/agent.rb +959 -0
  61. data/lib/legate/agent_code_generator.rb +185 -0
  62. data/lib/legate/agent_definition.rb +812 -0
  63. data/lib/legate/agentic/decision.rb +49 -0
  64. data/lib/legate/agentic/loop.rb +134 -0
  65. data/lib/legate/agentic.rb +5 -0
  66. data/lib/legate/agents/loop_agent.rb +248 -0
  67. data/lib/legate/agents/parallel_agent.rb +163 -0
  68. data/lib/legate/agents/sequential_agent.rb +190 -0
  69. data/lib/legate/agents.rb +14 -0
  70. data/lib/legate/auth/config.rb +148 -0
  71. data/lib/legate/auth/coordinator.rb +218 -0
  72. data/lib/legate/auth/coordinators/oauth2_coordinator.rb +99 -0
  73. data/lib/legate/auth/coordinators/oidc_coordinator.rb +68 -0
  74. data/lib/legate/auth/coordinators/service_account_coordinator.rb +122 -0
  75. data/lib/legate/auth/credential.rb +157 -0
  76. data/lib/legate/auth/encryption.rb +108 -0
  77. data/lib/legate/auth/error.rb +94 -0
  78. data/lib/legate/auth/exchanged_credential.rb +180 -0
  79. data/lib/legate/auth/excon_middleware.rb +285 -0
  80. data/lib/legate/auth/http_client_utils.rb +364 -0
  81. data/lib/legate/auth/manager.rb +531 -0
  82. data/lib/legate/auth/manager_store.rb +394 -0
  83. data/lib/legate/auth/middleware_factory.rb +290 -0
  84. data/lib/legate/auth/runner.rb +279 -0
  85. data/lib/legate/auth/scheme.rb +125 -0
  86. data/lib/legate/auth/schemes/api_key.rb +212 -0
  87. data/lib/legate/auth/schemes/google_service_account.rb +108 -0
  88. data/lib/legate/auth/schemes/http_bearer.rb +98 -0
  89. data/lib/legate/auth/schemes/oauth2.rb +396 -0
  90. data/lib/legate/auth/schemes/openid_connect.rb +346 -0
  91. data/lib/legate/auth/schemes/service_account.rb +388 -0
  92. data/lib/legate/auth/schemes.rb +40 -0
  93. data/lib/legate/auth/token_manager.rb +362 -0
  94. data/lib/legate/auth/token_store.rb +86 -0
  95. data/lib/legate/auth/tool_context_extension.rb +97 -0
  96. data/lib/legate/auth/tool_integration.rb +188 -0
  97. data/lib/legate/auth/url_guard.rb +81 -0
  98. data/lib/legate/auth.rb +453 -0
  99. data/lib/legate/callbacks/callback_context.rb +71 -0
  100. data/lib/legate/cli/agent_commands.rb +950 -0
  101. data/lib/legate/cli/auth_commands.rb +520 -0
  102. data/lib/legate/cli/base_command.rb +24 -0
  103. data/lib/legate/cli/deployment_commands.rb +934 -0
  104. data/lib/legate/cli/output_helper.rb +108 -0
  105. data/lib/legate/cli/session_commands.rb +138 -0
  106. data/lib/legate/cli/skaffold_commands.rb +223 -0
  107. data/lib/legate/cli/tool_commands.rb +261 -0
  108. data/lib/legate/cli/web_commands.rb +182 -0
  109. data/lib/legate/cli.rb +40 -0
  110. data/lib/legate/configuration/webhooks.rb +113 -0
  111. data/lib/legate/configuration.rb +39 -0
  112. data/lib/legate/definition_store.rb +23 -0
  113. data/lib/legate/errors.rb +118 -0
  114. data/lib/legate/event.rb +161 -0
  115. data/lib/legate/gemini_ai_beta_patch.rb +39 -0
  116. data/lib/legate/generators/agent_generator.rb +412 -0
  117. data/lib/legate/generators/code_validator.rb +48 -0
  118. data/lib/legate/generators/legate/install_generator.rb +35 -0
  119. data/lib/legate/generators/legate/templates/create_legate_tables.rb.tt +36 -0
  120. data/lib/legate/generators/legate/templates/initializer.rb +18 -0
  121. data/lib/legate/generators/runtime_tool_loader.rb +76 -0
  122. data/lib/legate/generators/tool_generator.rb +408 -0
  123. data/lib/legate/generators.rb +11 -0
  124. data/lib/legate/global_definition_registry.rb +506 -0
  125. data/lib/legate/global_tool_manager.rb +135 -0
  126. data/lib/legate/llm/adapter.rb +69 -0
  127. data/lib/legate/llm/gemini.rb +172 -0
  128. data/lib/legate/llm/ollama.rb +80 -0
  129. data/lib/legate/llm.rb +34 -0
  130. data/lib/legate/mcp/client.rb +320 -0
  131. data/lib/legate/mcp/connection/sse.rb +292 -0
  132. data/lib/legate/mcp/connection/stdio.rb +273 -0
  133. data/lib/legate/mcp/connection_manager.rb +103 -0
  134. data/lib/legate/mcp/server/legate_agent_adapter.rb +170 -0
  135. data/lib/legate/mcp/server/legate_direct_agent_adapter.rb +140 -0
  136. data/lib/legate/mcp/server/legate_tool_adapter.rb +119 -0
  137. data/lib/legate/mcp/tool_wrapper.rb +138 -0
  138. data/lib/legate/mcp/util/schema_converter.rb +134 -0
  139. data/lib/legate/mcp.rb +23 -0
  140. data/lib/legate/plan_executor.rb +375 -0
  141. data/lib/legate/planner.rb +839 -0
  142. data/lib/legate/rails/railtie.rb +43 -0
  143. data/lib/legate/rails.rb +9 -0
  144. data/lib/legate/redaction.rb +32 -0
  145. data/lib/legate/session.rb +299 -0
  146. data/lib/legate/session_service/active_record.rb +300 -0
  147. data/lib/legate/session_service/base.rb +68 -0
  148. data/lib/legate/session_service/event_broadcast.rb +74 -0
  149. data/lib/legate/session_service/in_memory.rb +188 -0
  150. data/lib/legate/tool/metadata_dsl.rb +122 -0
  151. data/lib/legate/tool.rb +276 -0
  152. data/lib/legate/tool_code_generator.rb +103 -0
  153. data/lib/legate/tool_context.rb +350 -0
  154. data/lib/legate/tool_loader.rb +39 -0
  155. data/lib/legate/tool_registry.rb +73 -0
  156. data/lib/legate/tool_result.rb +61 -0
  157. data/lib/legate/tools/agent_tool.rb +187 -0
  158. data/lib/legate/tools/base/http_client.rb +319 -0
  159. data/lib/legate/tools/base/safe_url.rb +56 -0
  160. data/lib/legate/tools/base_async_job_tool.rb +91 -0
  161. data/lib/legate/tools/calculator.rb +89 -0
  162. data/lib/legate/tools/cat_facts.rb +81 -0
  163. data/lib/legate/tools/check_job_status_tool.rb +48 -0
  164. data/lib/legate/tools/current_time_tool.rb +64 -0
  165. data/lib/legate/tools/echo.rb +43 -0
  166. data/lib/legate/tools/http_request_tool.rb +105 -0
  167. data/lib/legate/tools/random_number_tool.rb +64 -0
  168. data/lib/legate/tools/read_webpage_tool.rb +92 -0
  169. data/lib/legate/tools/sleepy_tool.rb +74 -0
  170. data/lib/legate/tools/webhook_tool.rb +146 -0
  171. data/lib/legate/version.rb +5 -0
  172. data/lib/legate/web/app.rb +984 -0
  173. data/lib/legate/web/public/css/main.css +4980 -0
  174. data/lib/legate/web/public/images/favicon-256.png +0 -0
  175. data/lib/legate/web/public/images/favicon-32.png +0 -0
  176. data/lib/legate/web/public/images/legate-logo-dark.png +0 -0
  177. data/lib/legate/web/public/images/legate-logo-light.png +0 -0
  178. data/lib/legate/web/public/js/legate.js +616 -0
  179. data/lib/legate/web/public/styles/main.scss +4402 -0
  180. data/lib/legate/web/routes/agent_authentication_routes.rb +530 -0
  181. data/lib/legate/web/routes/agent_definition_routes.rb +803 -0
  182. data/lib/legate/web/routes/agent_generator_routes.rb +80 -0
  183. data/lib/legate/web/routes/agent_interaction_routes.rb +734 -0
  184. data/lib/legate/web/routes/agent_runtime_routes.rb +323 -0
  185. data/lib/legate/web/routes/api_routes.rb +56 -0
  186. data/lib/legate/web/routes/authentication_routes.rb +1541 -0
  187. data/lib/legate/web/routes/core_routes.rb +111 -0
  188. data/lib/legate/web/routes/documentation_routes.rb +220 -0
  189. data/lib/legate/web/routes/tool_generator_routes.rb +81 -0
  190. data/lib/legate/web/routes/tools_ui_routes.rb +207 -0
  191. data/lib/legate/web/sass_compiler.rb +73 -0
  192. data/lib/legate/web/views/_active_session_info.slim +25 -0
  193. data/lib/legate/web/views/_activity_list.slim +55 -0
  194. data/lib/legate/web/views/_agent_card.slim +56 -0
  195. data/lib/legate/web/views/_agent_generator_modal.slim +382 -0
  196. data/lib/legate/web/views/_agent_status_controls.slim +71 -0
  197. data/lib/legate/web/views/_agent_tool_table.slim +74 -0
  198. data/lib/legate/web/views/_chat_message.slim +95 -0
  199. data/lib/legate/web/views/_display_agent_configuration.slim +26 -0
  200. data/lib/legate/web/views/_display_agent_description.slim +11 -0
  201. data/lib/legate/web/views/_display_agent_fallback.slim +15 -0
  202. data/lib/legate/web/views/_display_agent_hierarchy.slim +93 -0
  203. data/lib/legate/web/views/_display_agent_instruction.slim +17 -0
  204. data/lib/legate/web/views/_display_agent_mcp.slim +13 -0
  205. data/lib/legate/web/views/_display_agent_model.slim +17 -0
  206. data/lib/legate/web/views/_display_agent_name.slim +42 -0
  207. data/lib/legate/web/views/_display_agent_output_key.slim +26 -0
  208. data/lib/legate/web/views/_display_agent_type.slim +65 -0
  209. data/lib/legate/web/views/_edit_agent_configuration.slim +74 -0
  210. data/lib/legate/web/views/_edit_agent_description.slim +16 -0
  211. data/lib/legate/web/views/_edit_agent_fallback.slim +25 -0
  212. data/lib/legate/web/views/_edit_agent_hierarchy.slim +98 -0
  213. data/lib/legate/web/views/_edit_agent_instruction.slim +49 -0
  214. data/lib/legate/web/views/_edit_agent_mcp.slim +33 -0
  215. data/lib/legate/web/views/_edit_agent_model.slim +23 -0
  216. data/lib/legate/web/views/_edit_agent_output_key.slim +36 -0
  217. data/lib/legate/web/views/_edit_agent_tools.slim +40 -0
  218. data/lib/legate/web/views/_edit_agent_type.slim +67 -0
  219. data/lib/legate/web/views/_session_error.slim +4 -0
  220. data/lib/legate/web/views/_skeleton.slim +69 -0
  221. data/lib/legate/web/views/_tool_card.slim +9 -0
  222. data/lib/legate/web/views/_tool_generator_modal.slim +311 -0
  223. data/lib/legate/web/views/agent.slim +436 -0
  224. data/lib/legate/web/views/agent_auth.slim +562 -0
  225. data/lib/legate/web/views/agents.slim +369 -0
  226. data/lib/legate/web/views/auth.slim +112 -0
  227. data/lib/legate/web/views/auth_credential_detail.slim +327 -0
  228. data/lib/legate/web/views/auth_credentials.slim +261 -0
  229. data/lib/legate/web/views/auth_debug.slim +94 -0
  230. data/lib/legate/web/views/auth_mapping_detail.slim +151 -0
  231. data/lib/legate/web/views/auth_mapping_new.slim +123 -0
  232. data/lib/legate/web/views/auth_mappings.slim +120 -0
  233. data/lib/legate/web/views/auth_scheme_detail.slim +274 -0
  234. data/lib/legate/web/views/auth_schemes.slim +259 -0
  235. data/lib/legate/web/views/auth_test.slim +418 -0
  236. data/lib/legate/web/views/chat.slim +192 -0
  237. data/lib/legate/web/views/docs_index.slim +105 -0
  238. data/lib/legate/web/views/docs_show.slim +105 -0
  239. data/lib/legate/web/views/error_404.slim +5 -0
  240. data/lib/legate/web/views/index.slim +148 -0
  241. data/lib/legate/web/views/layout.slim +144 -0
  242. data/lib/legate/web/views/tool_detail.slim +87 -0
  243. data/lib/legate/web/views/tools.slim +50 -0
  244. data/lib/legate/web/webhook_listener.rb +367 -0
  245. data/lib/legate/web.rb +9 -0
  246. data/lib/legate.rb +220 -0
  247. data/public/docs/advanced/callbacks.md +828 -0
  248. data/public/docs/advanced/mcp_schema_conversion.md +59 -0
  249. data/public/docs/authentication/api_reference/config.md +210 -0
  250. data/public/docs/authentication/api_reference/credential.md +246 -0
  251. data/public/docs/authentication/api_reference/encryption.md +218 -0
  252. data/public/docs/authentication/api_reference/exchanged_credential.md +271 -0
  253. data/public/docs/authentication/api_reference/excon_middleware.md +175 -0
  254. data/public/docs/authentication/api_reference/index.md +30 -0
  255. data/public/docs/authentication/api_reference/scheme.md +250 -0
  256. data/public/docs/authentication/api_reference/schemes/api_key.md +175 -0
  257. data/public/docs/authentication/api_reference/schemes/google_service_account.md +221 -0
  258. data/public/docs/authentication/api_reference/schemes/http_bearer.md +169 -0
  259. data/public/docs/authentication/api_reference/schemes/oauth2.md +343 -0
  260. data/public/docs/authentication/api_reference/schemes/oidc.md +73 -0
  261. data/public/docs/authentication/api_reference/schemes/openid_connect.md +311 -0
  262. data/public/docs/authentication/api_reference/schemes/service_account.md +287 -0
  263. data/public/docs/authentication/api_reference/token_manager.md +221 -0
  264. data/public/docs/authentication/api_reference/token_store.md +146 -0
  265. data/public/docs/authentication/api_reference/tool_context_extension.md +166 -0
  266. data/public/docs/authentication/guides/api_key.md +190 -0
  267. data/public/docs/authentication/guides/bearer.md +172 -0
  268. data/public/docs/authentication/guides/configuration.md +255 -0
  269. data/public/docs/authentication/guides/custom_flow.md +523 -0
  270. data/public/docs/authentication/guides/index.md +24 -0
  271. data/public/docs/authentication/guides/migration.md +435 -0
  272. data/public/docs/authentication/guides/oauth2.md +252 -0
  273. data/public/docs/authentication/guides/oidc.md +241 -0
  274. data/public/docs/authentication/guides/overview.md +155 -0
  275. data/public/docs/authentication/guides/secure_storage.md +301 -0
  276. data/public/docs/authentication/guides/service_account.md +228 -0
  277. data/public/docs/authentication/guides/token_lifecycle.md +295 -0
  278. data/public/docs/authentication/guides/web_ui_integration.md +504 -0
  279. data/public/docs/authentication/index.md +58 -0
  280. data/public/docs/authentication/troubleshooting/credential_storage.md +550 -0
  281. data/public/docs/authentication/troubleshooting/environment_variables.md +540 -0
  282. data/public/docs/authentication/troubleshooting/index.md +11 -0
  283. data/public/docs/authentication/troubleshooting/oauth2_issues.md +220 -0
  284. data/public/docs/authentication/troubleshooting/oidc_issues.md +412 -0
  285. data/public/docs/authentication/troubleshooting/token_refresh.md +338 -0
  286. data/public/docs/cli/legate_cli_usage.md +363 -0
  287. data/public/docs/core_concepts/legate_agent_lifecycle.md +124 -0
  288. data/public/docs/core_concepts/legate_architecture_overview.md +110 -0
  289. data/public/docs/core_concepts/legate_configuration.md +116 -0
  290. data/public/docs/core_concepts/legate_definition_store.md +102 -0
  291. data/public/docs/core_concepts/legate_planner.md +94 -0
  292. data/public/docs/core_concepts/legate_session_service.md +104 -0
  293. data/public/docs/error_handling/legate_error_handling.md +122 -0
  294. data/public/docs/examples.md +199 -0
  295. data/public/docs/getting_started.md +111 -0
  296. data/public/docs/guides/agentic_agents.md +137 -0
  297. data/public/docs/guides/ai_code_generators.md +437 -0
  298. data/public/docs/guides/auto_loading.md +326 -0
  299. data/public/docs/guides/configuring_agent_webhooks.md +219 -0
  300. data/public/docs/guides/http_client_usage.md +264 -0
  301. data/public/docs/guides/llm_providers.md +137 -0
  302. data/public/docs/guides/mcp_client_integration.md +232 -0
  303. data/public/docs/guides/mcp_server_exposure.md +206 -0
  304. data/public/docs/guides/rails_integration.md +128 -0
  305. data/public/docs/guides/sending_outbound_webhooks.md +227 -0
  306. data/public/docs/guides/streaming.md +112 -0
  307. data/public/docs/guides/webhooks.md +288 -0
  308. data/public/docs/introduction.md +51 -0
  309. data/public/docs/multi_agent_systems/advanced_features.md +57 -0
  310. data/public/docs/multi_agent_systems/agent_delegation.md +190 -0
  311. data/public/docs/multi_agent_systems/agent_hierarchy.md +49 -0
  312. data/public/docs/multi_agent_systems/state_management.md +47 -0
  313. data/public/docs/multi_agent_systems/workflow_agents.md +72 -0
  314. data/public/docs/tools/legate_built_in_tools.md +332 -0
  315. data/public/docs/tools/legate_tools_and_registry.md +263 -0
  316. data/public/docs/web_ui/legate_web_ui.md +137 -0
  317. metadata +823 -0
@@ -0,0 +1,363 @@
1
+ # Legate Command-Line Interface (CLI)
2
+
3
+ This document describes the `legate` command-line interface, a tool provided for managing Legate agents, definitions, and running related processes.
4
+
5
+ ## 1. Installation & Setup
6
+
7
+ The `legate` CLI is typically made available when you install the `legate` gem or include it in your project's Gemfile and run `bundle install`.
8
+
9
+ Ensure your environment is set up correctly (e.g., Ruby version, Bundler, necessary environment variables like `GOOGLE_API_KEY`).
10
+
11
+ ## 2. Basic Usage
12
+
13
+ You invoke the CLI using the `legate` command, followed by a subcommand and its specific options.
14
+
15
+ ```bash
16
+ legate <subcommand> [options]
17
+ ```
18
+
19
+ Use `legate help` or `legate <subcommand> --help` to see available commands and their options.
20
+
21
+ ## 3. Core Commands
22
+
23
+ ### 3.1. Agent Management (`legate agent`)
24
+
25
+ This subcommand group deals with managing agent definitions stored in the `GlobalDefinitionRegistry` (in-memory).
26
+
27
+ * **`legate agent save NAME [options]`**: Creates or updates an agent definition in the store.
28
+ * **Required Argument:**
29
+ * `NAME`: The unique name for the agent.
30
+ * **Required Options:**
31
+ * `--description "Agent description"`: Set the agent's description.
32
+ * **Common Options:**
33
+ * `--instruction "Agent instructions..."`: Set the core instructions/system prompt.
34
+ * `--tools` / `-t` `tool1,tool2,tool3`: Comma-separated list of tool names (must be registered globally) to associate with the agent.
35
+ * `--model "model-name"`: Specify the LLM to use (e.g., `gemini-3.5-flash`).
36
+ * `--webhook-enabled`: Flag to enable this agent for inbound webhooks.
37
+ * `--webhook-secret "your-secret"`: Set the secret for webhook validation.
38
+ * `--mcp-servers-json '[{"type":"stdio", ...}]'`: JSON string defining MCP servers to connect to.
39
+ * **Example:**
40
+ ```bash
41
+ legate agent save my_calculator --description "A simple calculator agent" --instruction "Use the calculator tool." --tools calculator --model gemini-pro
42
+ ```
43
+
44
+ * **`legate agent list`**: Lists all agent definitions found in the store.
45
+ * **Options:**
46
+ * `--json`: Output result in JSON format.
47
+ * **Example Output:**
48
+ ```
49
+ Defined Agents:
50
+ - my_calculator: A simple calculator agent (Model: gemini-pro, Tools: calculator)
51
+ ```
52
+
53
+ * **`legate agent generate NAME [options]`**: Generates a new agent definition Ruby file from a template.
54
+ * **Options:**
55
+ * `--description "Agent description"`: Agent description (default: "A new Legate agent.").
56
+ * `--instruction "Agent instruction"`: Agent instruction/system prompt (default: "You are a helpful assistant.").
57
+ * `--tools` / `-t` `tool1,tool2`: Comma-separated list of tool names.
58
+ * `--model "model-name"`: LLM model name.
59
+ * `--dir "./agents"`: Directory to save the agent definition file (default: `./agents`).
60
+ * `--force`: Overwrite existing file without prompting.
61
+ * `--webhook-enabled`: Include webhook configuration placeholders.
62
+ * **Example:** `legate agent generate my_calculator --description "A calculator" --tools calculator`
63
+
64
+ * **`legate agent delete NAME`**: Deletes an agent definition from the store. Prompts for confirmation.
65
+ * **Example:** `legate agent delete my_calculator`
66
+
67
+ * **`legate agent stop \u003cagent_name\u003e [options]`**: Stops a persistent agent by marking it as 'stopped' in the definition store.
68
+ * **Options:**
69
+ * `--force`: Skip confirmation prompt
70
+ * `--quiet` / `-q`: Suppress status messages, only output result.
71
+ * `--json`: Output result in JSON format (implies --quiet).
72
+ * **Notes:**
73
+ * If the agent is running in a web server, it will stop on the next status check or server restart.
74
+ * Useful for remotely stopping agents without accessing the web UI.
75
+ * **Example:** `legate agent stop my_calculator --force`
76
+
77
+ * **`legate agent start NAME [options]`**: Verifies agent definition loading and starts the agent runtime (ephemeral diagnostic). Loads the definition, instantiates the agent, starts and stops the runtime, prints details, and exits.
78
+ * **Options:**
79
+ * `--quiet` / `-q`: Suppress status messages, only output result.
80
+ * `--json`: Output result in JSON format (implies --quiet).
81
+ * **Example:** `legate agent start my_calculator --json`
82
+
83
+ * **`legate agent status \u003cagent_name\u003e [options]`**: Checks the current status of an agent.
84
+ * **Options:**
85
+ * `--json`: Output result in JSON format.
86
+ * **Example:** `legate agent status my_calculator --json`
87
+ * **JSON Output Format:**
88
+ ```json
89
+ {
90
+ "agent": "my_calculator",
91
+ "status": "running",
92
+ "model": "gemini-2.0-flash",
93
+ "tools": ["calculator"]
94
+ }
95
+ ```
96
+
97
+ * **`legate agent ai_generate [options]`**: Uses AI (Gemini LLM) to generate production-ready agent definition code from a natural language description.
98
+ * **Input Options (one required):**
99
+ * `--description` / `-d`: Inline description
100
+ * `--prompt-file` / `-f`: Read description from a file
101
+ * **stdin**: Pipe description via stdin (auto-outputs to stdout)
102
+ * **Output Options:**
103
+ * `--output` / `-o`: Custom output file path (default: `./<suggested_name>_agent.rb`)
104
+ * `--stdout`: Force output to stdout instead of file
105
+ * `--force`: Overwrite existing file without prompting
106
+ * **Environment:** Requires `GOOGLE_API_KEY` to be set
107
+ * **Examples:**
108
+ ```bash
109
+ legate agent ai_generate -d "An agent that helps with customer support"
110
+ legate agent ai_generate -f prompt.txt -o ./agents/support_agent.rb
111
+ echo "A calculator agent" | legate agent ai_generate > calc_agent.rb
112
+ ```
113
+
114
+ * **`legate agent export <agent_name> [options]`**: Exports an agent definition to YAML or JSON.
115
+ * **Options:**
116
+ * `--format`: Output format, either `yaml` (default) or `json`.
117
+ * `--output` / `-o`: Output file path. If omitted, prints to stdout.
118
+ * **Example:** `legate agent export my_calculator --format=json --output=my_calculator.json`
119
+
120
+ * **`legate agent execute <agent_name> <task> [options]`**: Executes a single task with an agent and exits.
121
+ * **Required Arguments:**
122
+ * `<agent_name>`: Name of the agent to execute.
123
+ * `<task>`: The task/prompt to execute.
124
+ * **Options:**
125
+ * `--session-id=<id>`: Continue an existing session.
126
+ * `--user-id=<id>`: Associate session with a user ID for tracking and resumption.
127
+ * `--quiet` / `-q`: Suppress status messages, only output result.
128
+ * `--json`: Output result in JSON format (implies --quiet).
129
+ * **Examples:**
130
+ ```bash
131
+ # Normal execution with verbose status
132
+ legate agent execute my_calculator "What is 5 + 3?"
133
+
134
+ # Quiet mode - only show result
135
+ legate agent execute my_calculator "What is 5 + 3?" --quiet
136
+
137
+ # JSON output for scripting/automation
138
+ legate agent execute my_calculator "What is 5 + 3?" --json
139
+ ```
140
+ * **JSON Output Format:**
141
+ ```json
142
+ {
143
+ "session_id": "uuid-here",
144
+ "agent": "my_calculator",
145
+ "result": {
146
+ "role": "agent",
147
+ "content": {"status": "success", "result": "8"},
148
+ "timestamp": "2025-12-16 00:00:00 UTC"
149
+ }
150
+ }
151
+ ```
152
+
153
+ ### 3.2. Web Server (`legate web`)
154
+
155
+ This subcommand group manages the built-in development web server, which includes the Web UI and potentially the Webhook Listener.
156
+
157
+ * **`legate web start [options]`**: Starts the Legate development web server (using Puma by default).
158
+ * **Options:**
159
+ * `--port <port>`: Specify the port number (default: `4567`).
160
+ * `--host <address>`: Specify the address to bind to (default: `localhost`). Use `0.0.0.0` to listen on all interfaces.
161
+ * `--no-autoload`: Disable auto-loading of custom tools and agents.
162
+ * **Webhook Listener:** If `Legate.configure { |c| c.webhooks.listener_enabled = true }` is set in your configuration, this command will *also* typically start the webhook listener application, either mounted within the main web app or alongside it, according to the Legate's internal setup.
163
+ * **Example:** `legate web start --port 3000 --host 0.0.0.0`
164
+
165
+ ### 3.3. Tool Management (`legate tool`)
166
+
167
+ * **`legate tool list`**: Lists all tools currently registered in the `Legate::GlobalToolManager`. Useful for seeing which tools are available to be added to agent definitions.
168
+ * **Options:**
169
+ * `--json`: Output result in JSON format.
170
+ * **Example Output:**
171
+ ```
172
+ Available tools:
173
+ - calculator: Performs basic arithmetic operations.
174
+ - echo: Echoes back the input message.
175
+ - webhook: Sends an outbound HTTP POST request (webhook).
176
+ ```
177
+
178
+ * **`legate tool info NAME`**: Shows detailed information about a specific tool, including its description and parameter definitions (names, types, required/optional status).
179
+ * **Example:** `legate tool info calculator`
180
+
181
+ * **`legate tool ai_generate [options]`**: Uses AI (Gemini LLM) to generate production-ready tool class code from a natural language description. Automatically determines if the tool should be simple, HTTP API, or async.
182
+ * **Input Options (one required):**
183
+ * `--description` / `-d`: Inline description
184
+ * `--prompt-file` / `-f`: Read description from a file
185
+ * **stdin**: Pipe description via stdin (auto-outputs to stdout)
186
+ * **Output Options:**
187
+ * `--output` / `-o`: Custom output file path (default: `./<suggested_name>.rb`)
188
+ * `--stdout`: Force output to stdout instead of file
189
+ * `--force`: Overwrite existing file without prompting
190
+ * **Environment:** Requires `GOOGLE_API_KEY` to be set
191
+ * **Examples:**
192
+ ```bash
193
+ legate tool ai_generate -d "A tool that converts temperatures"
194
+ echo "A URL status checker" | legate tool ai_generate > url_checker.rb
195
+ ```
196
+
197
+ * **`legate tool execute <tool_name> [param=value ...] [options]`**: Executes a tool directly with parameters.
198
+ * **Options:**
199
+ * `--quiet` / `-q`: Suppress status messages, only output result.
200
+ * `--json`: Output result in JSON format (implies --quiet).
201
+ * **Example:**
202
+ ```bash
203
+ legate tool execute calculator operand1=5 operand2=3 operation=add --json
204
+ ```
205
+
206
+ ### 3.4. Session Management (`legate session`)
207
+
208
+ * **`legate session show <session_id>`**: Retrieves and displays the details and event history of a specific session from the configured `SessionService`.
209
+ * **`legate session list [APP_NAME] [USER_ID]`**: Lists all sessions, optionally filtered by `app_name` and/or `user_id`.
210
+ * **`legate session delete <session_id>`**: Deletes a specific session.
211
+
212
+ ### 3.5. Authentication (`legate auth`)
213
+
214
+ Manages authentication schemes, credentials, and URL mappings. These commands interact with the same `Legate::Auth::Manager` used by the web UI.
215
+
216
+ #### Status
217
+
218
+ * **`legate auth status`**: Shows an overview of the authentication system.
219
+ * **Example Output:**
220
+ ```
221
+ Authentication System Status
222
+
223
+ Schemes: 6
224
+ Credentials: 2
225
+ Mappings: 1
226
+
227
+ Scheme types: api_key, http_bearer, oauth2
228
+ Credential types: api_key, oauth2
229
+ ```
230
+
231
+ #### Scheme Management (`legate auth schemes`)
232
+
233
+ * **`legate auth schemes list`**: Lists all registered authentication schemes.
234
+ * **`legate auth schemes show <name>`**: Shows details for a specific scheme.
235
+ * **`legate auth schemes create <name> --type=<type> [options]`**: Creates a new scheme.
236
+ * **Required Options:**
237
+ * `--type`: Scheme type (`api_key`, `http_bearer`, `oauth2`, `oidc`, `service_account`, `google_service_account`)
238
+ * **Type-specific Options (OAuth2/OIDC):**
239
+ * `--authorization-url`: OAuth2 authorization endpoint
240
+ * `--token-url`: OAuth2 token endpoint
241
+ * `--userinfo-url`: OIDC userinfo endpoint
242
+ * `--scopes`: Space-separated scopes
243
+ * `--use-pkce`: Enable PKCE
244
+ * **Example:**
245
+ ```bash
246
+ legate auth schemes create my_oauth --type=oauth2 \
247
+ --authorization-url="https://auth.example.com/authorize" \
248
+ --token-url="https://auth.example.com/token"
249
+ ```
250
+ * **`legate auth schemes delete <name> [--force]`**: Deletes a scheme.
251
+
252
+ #### Credential Management (`legate auth credentials`)
253
+
254
+ * **`legate auth credentials list`**: Lists all credentials (sensitive values are masked).
255
+ * **`legate auth credentials show <name>`**: Shows credential details with masked values.
256
+ * **`legate auth credentials create <name> --type=<type> [options]`**: Creates a new credential.
257
+ * **Required Options:**
258
+ * `--type`: Credential type (`api_key`, `http_bearer`, `oauth2`, `oidc`, `service_account`, `google_service_account`, `basic`)
259
+ * **Type-specific Options:**
260
+ * `--api-key`: API key value (or `ENV:VAR_NAME` for environment variable)
261
+ * `--bearer-token`: Bearer token value
262
+ * `--client-id`: OAuth2/OIDC client ID
263
+ * `--client-secret`: OAuth2/OIDC client secret
264
+ * `--service-account-key`: Service account JSON key
265
+ * `--service-account-key-file`: Path to service account key file
266
+ * `--username`, `--password`: Basic auth credentials
267
+ * **Example:**
268
+ ```bash
269
+ legate auth credentials create my_api_key --type=api_key --api-key="ENV:MY_API_KEY"
270
+ ```
271
+ * **`legate auth credentials delete <name> [--force]`**: Deletes a credential.
272
+ * **`legate auth credentials test <name> [--url=<url>]`**: Tests a credential's validity.
273
+
274
+ #### URL Mapping (`legate auth mappings`)
275
+
276
+ * **`legate auth mappings list`**: Lists all URL-to-auth mappings.
277
+ * **`legate auth mappings create --pattern=<pattern> --scheme=<name> --credential=<name> [--regex]`**: Creates a mapping.
278
+ * **Required Options:**
279
+ * `--pattern`: URL pattern to match
280
+ * `--scheme`: Name of the scheme to use
281
+ * `--credential`: Name of the credential to use
282
+ * **Optional:**
283
+ * `--regex`: Treat pattern as a regular expression
284
+ * **Example:**
285
+ ```bash
286
+ legate auth mappings create \
287
+ --pattern="https://api.example.com/*" \
288
+ --scheme=api_key \
289
+ --credential=my_api_key
290
+ ```
291
+ * **`legate auth mappings delete <index>`**: Deletes a mapping by its index.
292
+
293
+ ### 3.6. Deployment (`legate deployment`)
294
+
295
+ Helps in generating assets for deploying your Legate application.
296
+
297
+ #### `legate deployment generate [directory]`
298
+
299
+ Generates deployment assets such as Dockerfiles, `.dockerignore` files, a `config.ru` for Rack applications, and cloud-specific configuration scripts. These assets are placed into a new directory (default name: `deployment`).
300
+
301
+ **Arguments:**
302
+
303
+ * `[directory]` (Optional): The base path where the deployment assets directory will be created. If not specified, it defaults to the current directory (`.`). The actual assets will be placed in a subdirectory named according to the `--name` option.
304
+
305
+ **Generic Options:**
306
+
307
+ * `--cloud <provider>` / `-c <provider>`: **(Required)** Specifies the target cloud provider for which to generate assets.
308
+ * Allowed values: `gcp`, `aws`, `azure`, `none`.
309
+ * Default: `none` (generates only generic Docker assets).
310
+ * `--entry-point <path>` / `-e <path>`: The path to your main application entry point script (e.g., `bin/web_server.rb`, `app.rb`, or a `config.ru`). This is required unless `--generate-sample-entrypoint` is used. The generated `config.ru` will reference this script to run your application.
311
+ * `--agent-entry-points <path1,path2,...>` / `-a <path1,path2,...>`: A comma-separated list of paths to entry point scripts for any standalone agent processes you want to deploy. A separate Dockerfile may be generated for each.
312
+ * `--name <name>` / `-n <name>`: The base name for the output directory where assets will be generated (e.g., if `my-app-deploy` is given, assets will be in `./my-app-deploy/`). This name may also be used as a prefix for generated cloud resources.
313
+ * Default: `deployment`.
314
+ * `--base-image <image_name:tag>`: The base Ruby Docker image to use for the generated Dockerfile(s) (e.g., `ruby:3.3-slim`).
315
+ * Default: `ruby:3.2-slim`.
316
+ * `--generate-sample-entrypoint`: If set, a sample web entrypoint script (default: `bin/legate_web_entrypoint.rb`) with a basic `/healthz` endpoint and an example `/echo` agent endpoint will be generated. This is useful if your Legate application doesn't have an existing web server entry point.
317
+ * Default: `false`.
318
+
319
+ **GCP Specific Options (applicable if `--cloud gcp` is used):**
320
+
321
+ * `--gcp-project-id <id>`: **(Required for GCP)** Your Google Cloud Project ID.
322
+ * `--gcp-region <region>`: The GCP region where resources will be deployed (e.g., `us-central1`).
323
+ * Default: `us-central1`.
324
+ * `--gcp-service-name <name>`: The name for the main GCP Cloud Run service that will host your application.
325
+ * Default: `legate-agent-service`.
326
+ * `--gcp-memory <size>`: The memory allocation for the main Cloud Run service (e.g., `512Mi`, `1Gi`).
327
+ * Default: `512Mi`.
328
+ * `--gcp-cpu <count>`: The CPU allocation for the main Cloud Run service.
329
+ * Default: `1`.
330
+
331
+ **Example:**
332
+
333
+ To generate deployment assets for GCP, targeting your project `my-gcp-project-123`, with the main application entry point at `bin/my_app_server.rb`, and outputting to a directory named `my_legate_prod_deployment`:
334
+
335
+ ```bash
336
+ bundle exec legate deployment generate . --cloud gcp \
337
+ --gcp-project-id "my-gcp-project-123" \
338
+ --entry-point "bin/my_app_server.rb" \
339
+ --name "my_legate_prod_deployment" \
340
+ --gcp-region "us-east1"
341
+ ```
342
+
343
+ This will create a directory `./my_legate_prod_deployment/` containing a `Dockerfile`, `.dockerignore`, `config.ru`, a `deploy-gcp.sh` script, a `cloudbuild.yaml` file, and a `README-GCP-DEPLOYMENT.md` guide.
344
+
345
+ ### 3.7. Help (`legate help`)
346
+
347
+ * **`legate help`**: Displays the main help message listing all available subcommands.
348
+ * **`legate help <subcommand>`**: Displays detailed help for a specific subcommand (e.g., `legate help agent`).
349
+
350
+ ## 4. Configuration
351
+
352
+ The CLI relies on the same Legate configuration mechanisms as the library itself:
353
+
354
+ * It loads the application environment (often via `Bundler.setup` and `Dotenv.load`).
355
+ * It respects settings configured in `Legate.configure` blocks within your application's initialization code.
356
+ * It uses environment variables (e.g., `GOOGLE_API_KEY`, `LEGATE_LOG_LEVEL`).
357
+
358
+ ## Further Reading
359
+
360
+ * [`legate_configuration`](../core_concepts/legate_configuration)
361
+ * [`legate_definition_store`](../core_concepts/legate_definition_store)
362
+ * [`legate_web_ui`](../web_ui/legate_web_ui)
363
+ * [`legate_tools_and_registry`](../tools/legate_tools_and_registry)
@@ -0,0 +1,124 @@
1
+ # Legate Agent Lifecycle
2
+
3
+ This document describes the lifecycle of an `Legate::Agent` instance, from its creation and initialization through starting, task execution, and stopping.
4
+
5
+ ## Lifecycle States & Transitions
6
+
7
+ The following diagram illustrates the primary states of an agent instance and the methods or events that cause transitions between these states:
8
+
9
+ ```mermaid
10
+ stateDiagram-v2
11
+ [*] --> Initialized : "Legate Agent new"
12
+ Initialized --> Running : agent.start()
13
+ Running --> Running : agent.run_task()
14
+ Running --> Stopped : agent.stop()
15
+ Stopped --> Running : agent.start()
16
+ Stopped --> [*]
17
+ Initialized --> [*]
18
+
19
+ note right of Initialized : Agent object exists, planner initialized,
20
+ note right of Initialized : tool registry created, but not ready for tasks
21
+ note left of Running : Connected to MCP servers (if any),
22
+ note left of Running : selected MCP tools registered,
23
+ note left of Running : ready to execute tasks
24
+ note right of Stopped : Disconnected from MCP servers,
25
+ note right of Stopped : runtime resources released (if any)
26
+ ```
27
+
28
+ ## Quick path: `Agent#ask`
29
+
30
+ For the common "just answer this" case you don't need to drive the lifecycle by
31
+ hand. `Agent#ask` lazily starts the agent, creates (or reuses) a session on the
32
+ agent's own session service, runs the task, and returns the final event:
33
+
34
+ ```ruby
35
+ agent = Legate::Agent.new(definition: my_definition)
36
+
37
+ puts agent.ask('What is 2 + 2?').answer # => "4"
38
+ agent.ask('Search for ruby') { |event| ... } # optional block streams progress (see Streaming guide)
39
+ agent.ask('Follow-up', session_id: existing_id) # continue a conversation
40
+ ```
41
+
42
+ The returned `Legate::Event` exposes `#answer`, `#success?`, `#error?`, and
43
+ `#error_message`, so you rarely reach into `event.content` directly. `ask` does
44
+ **not** auto-stop (stopping tears down MCP connections that are costly to
45
+ re-establish); call `#stop` when done, or let process exit reclaim it.
46
+
47
+ The phases below describe the explicit lifecycle `ask` automates — reach for them
48
+ when you need fine control (long-lived hosts, custom session management, the
49
+ workflow agent types).
50
+
51
+ ## Lifecycle Phases
52
+
53
+ ### 1. Initialization (`Legate::Agent.new`)
54
+
55
+ * **Trigger:** Calling `Legate::Agent.new(definition:, session_service: nil, planner_override: nil, sub_agents: nil)` where `definition` is an instance of `Legate::AgentDefinition`. This definition object would have been created programmatically (e.g., `Legate::AgentDefinition.new.define { ... }`) or loaded and deserialized (e.g., from a store, often involving `Legate::AgentDefinition.from_hash(hash_from_store)` if the store provides hashes). Optional parameters allow injecting a custom `session_service`, a `planner_override`, or pre-initialized `sub_agents`.
56
+ * **State:** Enters the **Initialized** state.
57
+ * **Actions:**
58
+ * The `Legate::AgentDefinition` object provides all core static properties: `name`, `description`, `instruction`, `tool_names` (symbols of tools to use), `model_name`, `temperature`, `fallback_mode`, `mcp_servers` configuration, `sub_agent_names`, `output_key`, and webhook configurations.
59
+ * The agent copies these properties from the provided `definition` object.
60
+ * Creates an instance of `Legate::ToolRegistry` specific to this agent instance.
61
+ * For each tool name specified in `definition.tool_names`, it resolves the corresponding tool class using `Legate::GlobalToolManager.find_class(tool_name)` and registers this class with the agent's local `ToolRegistry`.
62
+ * Initializes the `Legate::Planner` (e.g., `Legate::Planner`), using the agent's effective model name (from definition or default).
63
+ * If the `sub_agents:` parameter was provided to `Legate::Agent.new` with pre-initialized sub-agent instances, those are linked. Otherwise, if `definition.sub_agent_names` is populated, it attempts to instantiate these sub-agents by looking up their full `Legate::AgentDefinition` objects in `Legate::GlobalDefinitionRegistry` and then calling `Legate::Agent.new` for each.
64
+ * **Notes:** At this point, the agent object exists, but it hasn't connected to external systems like MCP servers (that happens in `start`). It cannot execute tasks until started.
65
+
66
+ ### 2. Starting (`agent.start`)
67
+
68
+ * **Trigger:** Calling the `start` method on an `Initialized` or `Stopped` agent instance.
69
+ * **State:** Transitions to the **Running** state.
70
+ * **Actions:**
71
+ * Sets the agent's internal running status flag to `true`.
72
+ * Iterates through the configured `mcp_servers` (if any):
73
+ * Creates an `Legate::Mcp::Client` for each server.
74
+ * Calls `client.connect` to establish the connection (STDIO process or SSE connection) and perform the MCP handshake.
75
+ * If successful, calls `client.list_tools` to get available tools from the MCP server.
76
+ * Compares the received tool names against the agent's `selected_tool_names`.
77
+ * For each matching tool, creates an `Legate::Mcp::ToolWrapper` instance using the schema from the MCP server.
78
+ * Registers the `ToolWrapper` instance with the agent's `ToolRegistry`.
79
+ * Handles connection or handshake errors gracefully (usually logs an error and proceeds without that MCP server's tools).
80
+ * **Notes:** The agent is now fully operational and ready to accept tasks via `run_task`. It has registered both its native tools and the selected tools from any successfully connected MCP servers.
81
+
82
+ ### 3. Running Tasks (`agent.run_task`)
83
+
84
+ * **Trigger:** Calling the `run_task` method on a `Running` agent instance.
85
+ * **State:** Remains in the **Running** state, but performs work.
86
+ * **Actions (Simplified Flow):**
87
+ 1. **Session Handling:** Loads or creates the relevant session using the provided `session_id` and `session_service`.
88
+ 2. **Record Input:** Adds the `user_input` as an event to the session history.
89
+ 3. **Planning:** Calls `planner.plan(user_input, invocation_id)` with the user's input and the invocation ID for callback support.
90
+ 4. **Plan Execution:** Iterates through the steps returned by the planner.
91
+ * For each step (typically a tool call):
92
+ * Retrieves the tool instance (native or `ToolWrapper`) from the `ToolRegistry`.
93
+ * Creates an `Legate::ToolContext` (containing session info).
94
+ * Calls `tool.execute(params, context)`.
95
+ * Adds the tool call event and the tool result event to the session history.
96
+ * Handles tool errors (`Legate::ToolError`) by catching them, logging, and adding an error event to the history, potentially halting plan execution.
97
+ 5. **Response Generation:** May consult the LLM one last time to generate a final response based on the completed plan and tool results.
98
+ 6. **Record Output:** Adds the final agent response event to the session history.
99
+ 7. **Return:** Returns the final `Legate::Event` (usually the agent response or an error event).
100
+ * **Notes:** This is the primary work loop of the agent. It involves interaction with the planner, tool registry, session service, and potentially external tools via MCP wrappers.
101
+
102
+ ### 4. Stopping (`agent.stop`)
103
+
104
+ * **Trigger:** Calling the `stop` method on a `Running` agent instance.
105
+ * **State:** Transitions to the **Stopped** state.
106
+ * **Actions:**
107
+ * Sets the agent's internal running status flag to `false`.
108
+ * Iterates through any active `Legate::Mcp::Client` instances and calls `client.disconnect`.
109
+ * This terminates STDIO processes or closes SSE connections associated with MCP servers.
110
+ * Performs any other necessary cleanup (though typically minimal for the base agent).
111
+ * **Notes:** The agent is no longer ready to run tasks. It needs to be explicitly started again via `agent.start()`.
112
+
113
+ ## Relationship to Agent Definition
114
+
115
+ The lifecycle described above pertains to an *instance* of `Legate::Agent`. Agent *definitions*, managed by the `DefinitionStore` or created programmatically (e.g. using `Legate::AgentDefinition.new.define`), represent the blueprint used to create these instances. Passing an `Legate::AgentDefinition` object to `Legate::Agent.new` is the first step (Initialization) in this lifecycle.
116
+
117
+ ## Further Reading
118
+
119
+ * [`legate_architecture_overview`](./legate_architecture_overview)
120
+ * [`legate_session_service`](./legate_session_service)
121
+ * [`legate_planner`](./legate_planner)
122
+ * [`legate_tools_and_registry`](../tools/legate_tools_and_registry)
123
+ * [`mcp_client_integration`](../guides/mcp_client_integration)
124
+ * [`legate_definition_store`](./legate_definition_store)
@@ -0,0 +1,110 @@
1
+ # Legate Architecture Overview
2
+
3
+ This document provides a high-level overview of the Legate — AI Agent Framework for Ruby — library, its core components, and how they interact to enable the development and operation of AI agents.
4
+
5
+ ## Core Components Diagram
6
+
7
+ The following diagram illustrates the main architectural components of the Legate:
8
+
9
+ ```mermaid
10
+ graph TD
11
+ subgraph UserInteraction ["User Interaction"]
12
+ CLI[Legate CLI]
13
+ WebUI[Legate Web UI]
14
+ end
15
+
16
+ subgraph LegateCore ["Legate Core"]
17
+ Agent["Legate::Agent"]
18
+ Planner["Legate::Planner"]
19
+ ToolRegistry["Legate::ToolRegistry"]
20
+ SessionService["Legate::SessionService"]
21
+ DefinitionStore["Legate::DefinitionStore"]
22
+ GlobalToolMgr["Legate::GlobalToolManager"]
23
+ end
24
+
25
+ subgraph ToolsAndExecution ["Tools & Execution"]
26
+ GenericTool["Legate::Tool"]
27
+ LLM["Language Model (LLM)"]
28
+ ExternalServices["External APIs/Services"]
29
+ end
30
+
31
+ UserInteraction -- Manages/Interacts with --> Agent
32
+ UserInteraction -- Manages/Interacts with --> DefinitionStore
33
+
34
+ Agent -- Uses --> Planner
35
+ Agent -- Uses --> ToolRegistry
36
+ Agent -- Uses --> SessionService
37
+ Agent -- Loads Definition from --> DefinitionStore
38
+
39
+ Planner -- Uses --> ToolRegistry
40
+ Planner -- Communicates with --> LLM
41
+
42
+ ToolRegistry -- Contains/Manages --> GenericTool
43
+ ToolRegistry -- Populated by --> GlobalToolMgr
44
+ GlobalToolMgr -- Discovers --> GenericTool
45
+
46
+ Agent -- Executes --> GenericTool
47
+ GenericTool -- Can call --> ExternalServices
48
+ GenericTool -- Can interact with --> SessionService
49
+
50
+ style Agent fill:#ccf,stroke:#333,stroke-width:2px
51
+ style Planner fill:#cff,stroke:#333,stroke-width:2px
52
+ style ToolRegistry fill:#cfc,stroke:#333,stroke-width:2px
53
+ style GenericTool fill:#cfc,stroke:#333,stroke-width:2px
54
+ style SessionService fill:#fcc,stroke:#333,stroke-width:2px
55
+ style DefinitionStore fill:#fcc,stroke:#333,stroke-width:2px
56
+ style LLM fill:#f9f,stroke:#333,stroke-width:2px
57
+ ```
58
+
59
+ ## Component Descriptions
60
+
61
+ * **User Interaction (CLI/Web UI):** Interfaces for users to create, manage, and interact with agents and their definitions.
62
+ * **`Legate::Agent`:** The central orchestrator. It manages the execution of tasks, interacts with the planner, tools, and session service based on its definition.
63
+ * **`Legate::Planner`:** Responsible for creating a sequence of steps (a plan) for the agent to follow to accomplish a given task. It uses the agent's instructions, available tools, and conversation history, often leveraging an LLM.
64
+ * **`Legate::ToolRegistry`:** An instance-specific collection of tools available to a particular agent. It provides tool metadata to the planner and tool instances to the agent for execution.
65
+ * **`Legate::GlobalToolManager`:** A global registry module (with `self.` class methods) where tool classes are registered. The `ToolRegistry` of an agent is typically populated from this manager.
66
+ * **`Legate::Tool`:** Represents a specific capability or action an agent can perform (e.g., calculator, web search, API call). Tools have defined metadata (name, description, parameters) and an execution method.
67
+ * **`Legate::SessionService`:** Manages the state of an agent's conversation over time, including history of prompts, tool calls, and responses. Uses in-memory storage via `InMemory`.
68
+ * **`Legate::DefinitionStore`:** A module namespace for storing and retrieving agent definitions (configurations like name, instructions, tools to use, model, etc.). Definitions are stored in-memory via `Legate::GlobalDefinitionRegistry`.
69
+ * **Language Model (LLM):** An external AI model (e.g., from OpenAI, Google) that the planner consults to generate plans and that the agent may use to generate final responses.
70
+ * **External APIs/Services:** Third-party services that `Legate::Tool`s might interact with to perform their actions.
71
+
72
+ ## Basic Workflow
73
+
74
+ A typical agent task execution involves the following simplified flow:
75
+
76
+ 1. **User Input:** A user provides a prompt or task to an `Legate::Agent` via a CLI or Web UI, usually associated with a `session_id`.
77
+ 2. **Agent Activation:** The `Legate::Agent` loads its definition and retrieves the session history using the `Legate::SessionService`.
78
+ 3. **Planning:** The agent invokes the `Legate::Planner`. The planner, using the agent's instructions, available tool metadata (from `Legate::ToolRegistry`), and conversation history, consults an LLM to create a plan (a sequence of tool calls).
79
+ 4. **Tool Execution:** The agent iterates through the plan:
80
+ * For each step, it retrieves the appropriate `Legate::Tool` from its `ToolRegistry`.
81
+ * It executes the tool with the parameters specified in the plan.
82
+ * The tool performs its action (potentially calling external APIs) and returns a result.
83
+ * The agent records the tool call and its result in the session history via the `Legate::SessionService`.
84
+ 5. **Response Generation:** After plan completion (or if no plan is needed), the agent may use an LLM to generate a final response based on the task and tool results.
85
+ 6. **Output:** The agent returns the final response or result to the user, and this event is also saved to the session history.
86
+
87
+ ## Key Concepts
88
+
89
+ * **Agent Definition:** The configuration of an agent, specifying its behavior, instructions, and capabilities (tools, model).
90
+ * **Session:** A record of an interaction or conversation with an agent over time, identified by a `session_id`. It includes all events like user prompts, tool calls, and agent responses.
91
+ * **Tool Metadata:** The information that describes a tool to the planner and LLM, including its name, a description of what it does, and the parameters it accepts.
92
+ * **Plan:** A sequence of steps (primarily tool calls) generated by the planner for the agent to execute to achieve a goal.
93
+
94
+ ## Further Reading
95
+
96
+ For more detailed information on specific components, refer to:
97
+
98
+ * [`legate_agent_lifecycle`](./legate_agent_lifecycle)
99
+ * [`legate_tools_and_registry`](../tools/legate_tools_and_registry)
100
+ * [`legate_session_service`](./legate_session_service)
101
+ * [`legate_planner`](./legate_planner)
102
+ * [`legate_configuration`](./legate_configuration)
103
+ * [`legate_definition_store`](./legate_definition_store)
104
+ * [`legate_cli_usage`](../cli/legate_cli_usage)
105
+ * [`http_client_usage`](../guides/http_client_usage)
106
+ * [`mcp_client_integration`](../guides/mcp_client_integration)
107
+ * [`mcp_server_exposure`](../guides/mcp_server_exposure)
108
+ * [`configuring_agent_webhooks`](../guides/configuring_agent_webhooks)
109
+ * [`sending_outbound_webhooks`](../guides/sending_outbound_webhooks)
110
+ * [`webhooks`](../guides/webhooks)