Skip to main content

robonix_executor/
main.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Author: wheatfox <wheatfox17@icloud.com>
3//
4// robonix-executor — capability-call dispatch runtime.
5// On startup executor:
6//   1. Connects to atlas, registers as `com.robonix.system.executor`.
7//   2. Declares its gRPC Execute and CancelAllPlans capabilities.
8//   3. Declares built-in capabilities under `robonix/system/executor/builtin/<op>`
9//      so pilot's atlas-driven discovery surfaces them to the LLM as plain
10//      capabilities. Calls hitting these contracts short-circuit to in-process
11//      handlers in `dispatch::builtin` — no MCP loopback.
12//   4. Serves Execute on `listen`. Per-call dispatch resolves provider via
13//      `ConnectCapability(provider_id, contract_id, MCP)` on atlas.
14
15mod active_plans;
16mod capability_execution;
17mod config;
18mod dispatch;
19mod execution_context;
20mod expression;
21mod grpc_server;
22mod lifecycle;
23mod output_view;
24mod pb;
25mod plan_input;
26mod plan_scheduler;
27mod rtdl_events;
28mod verification;
29
30// Preserve the unchanged dispatch module's imports during this reorganization.
31use active_plans as plan_runtime;
32use rtdl_events as rtdl_wire;
33
34use anyhow::{Context, Result};
35use clap::Parser;
36use config::{Args, EXECUTOR_NAMESPACE, ExecutorConfig};
37use dispatch::builtin::BUILTINS;
38use grpc_server::ExecutorServiceImpl;
39use lifecycle::{ExecutorLifecycleDriver, SHARED_DRIVER_CONTRACT};
40use pb::contracts::robonix_lifecycle_driver_server::RobonixLifecycleDriverServer;
41use pb::contracts::robonix_system_executor_cancel_all_plans_server::RobonixSystemExecutorCancelAllPlansServer;
42use pb::contracts::robonix_system_executor_control_plan_server::RobonixSystemExecutorControlPlanServer;
43use pb::contracts::robonix_system_executor_execute_server::RobonixSystemExecutorExecuteServer;
44use pb::contracts::robonix_system_executor_execute_stream_server::RobonixSystemExecutorExecuteStreamServer;
45use pb::contracts::robonix_system_executor_get_health_server::RobonixSystemExecutorGetHealthServer;
46use pb::contracts::robonix_system_executor_list_active_plans_server::RobonixSystemExecutorListActivePlansServer;
47use robonix_atlas::client::{self as atlas_client, AtlasClient};
48use robonix_atlas::pb as atlas_pb;
49use robonix_scribe::{info, warn};
50use std::sync::Arc;
51use std::time::Duration;
52
53#[tokio::main]
54async fn main() -> Result<()> {
55    let parsed = Args::parse();
56    // Apply the manifest's per-component `log:` level (delivered inside
57    // --config-json) to scribe's file sink before the first log line.
58    robonix_scribe::init_from_config("executor", parsed.config_json.as_deref());
59    info!("robonix-executor starting");
60
61    let cfg = ExecutorConfig::resolve(parsed)?;
62
63    info!("connecting to atlas at {}", cfg.atlas_endpoint);
64    let mut atlas =
65        AtlasClient::connect_with_retry(&cfg.atlas_endpoint, 10, Duration::from_secs(2))
66            .await
67            .context("connect to atlas")?;
68
69    let listen_addr: std::net::SocketAddr = cfg
70        .listen
71        .parse()
72        .with_context(|| format!("invalid executor listen address '{}'", cfg.listen))?;
73    // Own the port before self-dialing, so startup cannot reach another server.
74    let incoming = tonic::transport::server::TcpIncoming::bind(listen_addr)
75        .with_context(|| format!("bind executor gRPC at {listen_addr}"))?
76        .with_nodelay(Some(true));
77    let listen_addr = incoming.local_addr().context("executor listener address")?;
78    let advertised = lifecycle::advertised_endpoint(listen_addr);
79    atlas
80        .register_service(&cfg.id, EXECUTOR_NAMESPACE, "")
81        .await?;
82    info!("registered as '{}' under '{EXECUTOR_NAMESPACE}'", cfg.id);
83    atlas
84        .declare_capability(
85            &cfg.id,
86            SHARED_DRIVER_CONTRACT,
87            atlas_pb::Transport::Grpc,
88            &advertised,
89            atlas_client::grpc_params(
90                "capabilities/lifecycle/driver.v1.toml",
91                "robonix.contracts.RobonixLifecycleDriver",
92                "/robonix.contracts.RobonixLifecycleDriver/Driver",
93            ),
94        )
95        .await
96        .context("declare Executor shared lifecycle Driver")?;
97
98    // Execute RPC: pilot → executor for plan dispatch.
99    atlas
100        .declare_capability(
101            &cfg.id,
102            "robonix/system/executor/execute",
103            atlas_pb::Transport::Grpc,
104            &advertised,
105            atlas_client::grpc_params(
106                "capabilities/system/executor/execute.v1.toml",
107                "robonix.contracts.RobonixSystemExecutorExecute",
108                "/robonix.contracts.RobonixSystemExecutorExecute/Execute",
109            ),
110        )
111        .await?;
112
113    atlas
114        .declare_capability(
115            &cfg.id,
116            "robonix/system/executor/execute_stream",
117            atlas_pb::Transport::Grpc,
118            &advertised,
119            atlas_client::grpc_params(
120                "capabilities/system/executor/execute_stream.v1.toml",
121                "robonix.contracts.RobonixSystemExecutorExecuteStream",
122                "/robonix.contracts.RobonixSystemExecutorExecuteStream/ExecuteStream",
123            ),
124        )
125        .await?;
126
127    // Out-of-band RTDL meta operations. These never enter PlanRuntime as a
128    // new plan, so canceling work cannot create a self-referential cancel tree.
129    atlas
130        .declare_capability(
131            &cfg.id,
132            "robonix/system/executor/control_plan",
133            atlas_pb::Transport::Grpc,
134            &advertised,
135            atlas_client::grpc_params(
136                "capabilities/system/executor/control_plan.v1.toml",
137                "robonix.contracts.RobonixSystemExecutorControlPlan",
138                "/robonix.contracts.RobonixSystemExecutorControlPlan/ControlPlan",
139            ),
140        )
141        .await?;
142
143    // Read-only control path for clients and observability. Polling it must not
144    // create an RTDL query plan of its own.
145    atlas
146        .declare_capability(
147            &cfg.id,
148            "robonix/system/executor/list_active_plans",
149            atlas_pb::Transport::Grpc,
150            &advertised,
151            atlas_client::grpc_params(
152                "capabilities/system/executor/list_active_plans.v1.toml",
153                "robonix.contracts.RobonixSystemExecutorListActivePlans",
154                "/robonix.contracts.RobonixSystemExecutorListActivePlans/ListActivePlans",
155            ),
156        )
157        .await?;
158
159    // CancelAllPlans RPC: control path for cancelling every active RTDL plan.
160    atlas
161        .declare_capability(
162            &cfg.id,
163            "robonix/system/executor/cancel_all_plans",
164            atlas_pb::Transport::Grpc,
165            &advertised,
166            atlas_client::grpc_params(
167                "capabilities/system/executor/cancel_all_plans.v1.toml",
168                "robonix.contracts.RobonixSystemExecutorCancelAllPlans",
169                "/robonix.contracts.RobonixSystemExecutorCancelAllPlans/CancelAll",
170            ),
171        )
172        .await?;
173
174    // Module health RPC: Vitals polls this for system-module health.
175    atlas
176        .declare_capability(
177            &cfg.id,
178            "robonix/system/executor/get_health",
179            atlas_pb::Transport::Grpc,
180            &advertised,
181            atlas_client::grpc_params(
182                "capabilities/system/executor/get_health.toml",
183                "robonix.contracts.RobonixSystemExecutorGetHealth",
184                "/robonix.contracts.RobonixSystemExecutorGetHealth/GetModuleHealth",
185            ),
186        )
187        .await?;
188
189    // Built-in capabilities: declared as MCP-transport capabilities so pilot's
190    // catalog discovery sees them like any user MCP provider. The endpoint is a
191    // sentinel — dispatch never dials it; calls hitting these contracts hit
192    // the provider_id == self short-circuit in `dispatch::dispatch`.
193    let builtin_endpoint = format!("internal://{}/builtin", cfg.id);
194    for spec in BUILTINS {
195        let contract_id = format!("{EXECUTOR_NAMESPACE}/builtin/{}", spec.op);
196        atlas
197            .declare_capability_with_description(
198                &cfg.id,
199                &contract_id,
200                atlas_pb::Transport::Mcp,
201                &builtin_endpoint,
202                atlas_client::mcp_params(spec.input_schema_json),
203                spec.description,
204            )
205            .await
206            .with_context(|| format!("declare builtin '{}'", contract_id))?;
207    }
208    info!(
209        "declared executor gRPC capabilities + {} builtin capabilities at {advertised}",
210        BUILTINS.len()
211    );
212
213    let verification = Arc::new(verification::VerificationPolicy::new(
214        cfg.verification.overlap,
215        cfg.verification.rules,
216    ));
217    info!(
218        "loaded {} executor verification rule(s)",
219        verification.len()
220    );
221    let svc = ExecutorServiceImpl::new(atlas.clone(), cfg.id.clone(), verification);
222    svc.runtime
223        .close_admission()
224        .await
225        .map_err(anyhow::Error::msg)?;
226    let lifecycle =
227        ExecutorLifecycleDriver::new(atlas.clone(), cfg.id.clone(), svc.runtime.clone());
228    let server_shutdown = lifecycle.subscribe_shutdown();
229    let server_lifecycle = lifecycle.clone();
230    let mut server_task = tokio::spawn(async move {
231        tonic::transport::Server::builder()
232            .add_service(RobonixLifecycleDriverServer::new(server_lifecycle))
233            .add_service(RobonixSystemExecutorExecuteServer::new(svc.clone()))
234            .add_service(RobonixSystemExecutorExecuteStreamServer::new(svc.clone()))
235            .add_service(RobonixSystemExecutorCancelAllPlansServer::new(svc.clone()))
236            .add_service(RobonixSystemExecutorControlPlanServer::new(svc.clone()))
237            .add_service(RobonixSystemExecutorListActivePlansServer::new(svc.clone()))
238            .add_service(RobonixSystemExecutorGetHealthServer::new(svc))
239            .serve_with_incoming_shutdown(incoming, lifecycle::wait_for_shutdown(server_shutdown))
240            .await
241    });
242    tokio::select! {
243        result = lifecycle::initialize_and_activate(&advertised) => result?,
244        result = &mut server_task => {
245            result.context("join Executor gRPC server")?
246                .context("Executor gRPC server failed before readiness")?;
247            anyhow::bail!("Executor gRPC server stopped before readiness");
248        }
249    }
250
251    // Atlas evicts providers after ~60s without a heartbeat. Send one every
252    // 20s so we stay registered for the lifetime of the process.
253    {
254        let mut hb = atlas.clone();
255        let provider_id = cfg.id.clone();
256        let shutdown = lifecycle::wait_for_shutdown(lifecycle.subscribe_shutdown());
257        tokio::spawn(async move {
258            let mut tick = tokio::time::interval(Duration::from_secs(20));
259            tick.tick().await;
260            tokio::pin!(shutdown);
261            loop {
262                tokio::select! {
263                    _ = &mut shutdown => break,
264                    _ = tick.tick() => {
265                        if let Err(e) = hb.heartbeat(&provider_id).await {
266                            warn!("heartbeat failed: {e:#}");
267                        }
268                    }
269                }
270            }
271        });
272    }
273
274    info!("executor gRPC on {listen_addr}");
275    info!("robonix-executor ready on {listen_addr}");
276
277    let result = tokio::select! {
278        result = &mut server_task => result,
279        _ = lifecycle::wait_for_shutdown(lifecycle.subscribe_shutdown()) => {
280            // Completed plans can leave unread responses blocked by a client's flow control.
281            match tokio::time::timeout(Duration::from_secs(5), &mut server_task).await {
282                Ok(result) => result,
283                Err(_) => {
284                    server_task.abort();
285                    let _ = server_task.await;
286                    anyhow::bail!("Executor gRPC shutdown timed out draining connections");
287                }
288            }
289        }
290    };
291    result
292        .context("join Executor gRPC server")?
293        .context("executor gRPC server failed")?;
294
295    Ok(())
296}
浙ICP备2023005800号-2 浙公网安备33010902005384号