Skip to main content

agent_engine/extensions/runtime/
mod.rs

1//! Extension runtime trait and registry.
2
3pub mod process;
4pub mod restart;
5
6pub use restart::RestartPolicy;
7
8use self::process::{
9    NotificationFrame, ProviderCompleteParams, ProviderCompleteResult, ProviderStreamEvent,
10};
11use crate::extensions::commands::CommandOutputEvent;
12use crate::extensions::hooks::events::{HookEvent, HookResult};
13use crate::extensions::info::PluginInfo;
14use crate::extensions::tasks::TaskEvent;
15use async_trait::async_trait;
16use serde_json::Value;
17
18/// Streamed event delivered to a `command.invoke` caller.
19#[derive(Debug, Clone, PartialEq)]
20pub enum InvokeCommandEvent {
21    /// Command output event matching the caller's `request_id`.
22    Output(CommandOutputEvent),
23    /// Spontaneous plugin task event (any `request_id`).
24    Task(TaskEvent),
25}
26
27/// Health state for an extension handler.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum ExtensionHealth {
30    /// Manifest validated, process spawned, but `initialize` not yet completed.
31    Loaded,
32    /// Manifest failed validation — the extension never started.
33    FailedValidation,
34    /// `initialize` rpc failed — the extension started but couldn't capability-handshake.
35    FailedInitialize,
36    /// Healthy and serving requests.
37    Running,
38    /// Process restarting after transport failure but within restart budget.
39    Restarting,
40    /// Running, but at least one recent operation failed (e.g. hook timeout).
41    Degraded,
42    /// Permanent failure — restart budget exhausted or unrecoverable error.
43    Failed,
44}
45
46impl ExtensionHealth {
47    pub fn as_str(self) -> &'static str {
48        match self {
49            Self::Loaded => "loaded",
50            Self::FailedValidation => "failed_validation",
51            Self::FailedInitialize => "failed_initialize",
52            Self::Running => "running",
53            Self::Restarting => "restarting",
54            Self::Degraded => "degraded",
55            Self::Failed => "failed",
56        }
57    }
58}
59
60#[cfg(test)]
61#[allow(clippy::items_after_test_module)]
62mod health_tests {
63    use super::ExtensionHealth;
64
65    #[test]
66    fn as_str_covers_all_variants() {
67        assert_eq!(ExtensionHealth::Loaded.as_str(), "loaded");
68        assert_eq!(
69            ExtensionHealth::FailedValidation.as_str(),
70            "failed_validation"
71        );
72        assert_eq!(
73            ExtensionHealth::FailedInitialize.as_str(),
74            "failed_initialize"
75        );
76        assert_eq!(ExtensionHealth::Running.as_str(), "running");
77        assert_eq!(ExtensionHealth::Restarting.as_str(), "restarting");
78        assert_eq!(ExtensionHealth::Degraded.as_str(), "degraded");
79        assert_eq!(ExtensionHealth::Failed.as_str(), "failed");
80    }
81}
82
83/// A point-in-time lifecycle observation, not a lease on future execution.
84///
85/// Generations are opaque and local to one handler instance. A caller must pin
86/// both the handler identity and generation before dispatch, then require the
87/// same generation with `Running` or `Degraded` health when accepting a reply
88/// and before executing any deferred work. All other health states fail closed.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct ExtensionLifecycle {
91    pub generation: u64,
92    pub health: ExtensionHealth,
93}
94
95/// Trait for extension runtimes that can handle hook events.
96#[async_trait]
97pub trait ExtensionHandler: Send + Sync {
98    /// Unique identifier for this extension.
99    fn id(&self) -> &str;
100
101    /// Observe the actual serving runtime without waiting for locks or RPC I/O.
102    ///
103    /// `None` means unsupported or temporarily unavailable, never "healthy".
104    /// Implementations must invalidate the generation on runtime/transport loss
105    /// and before replacement, even if the handler itself remains the same Arc.
106    /// Consumers retaining authority must fail closed on `None`, non-live health,
107    /// or a changed generation, including while a previously valid reply waits
108    /// to execute. Recheck at dispatch, reply acceptance, and each frontend tick;
109    /// this snapshot cannot eliminate exit races after the final observation.
110    fn lifecycle_snapshot(&self) -> Option<ExtensionLifecycle> {
111        None
112    }
113
114    /// Handle a hook event. Returns the handler's decision.
115    async fn handle(&self, event: &HookEvent) -> HookResult;
116
117    /// [`Self::handle`] for a caller that must never start or restart the
118    /// extension: a subagent worker's hook view
119    /// ([`HookBus::worker_transforms`]). A worker runs on its own throwaway
120    /// current-thread tokio runtime, so a child process or reader task
121    /// spawned from it would die with the worker and leave the shared
122    /// extension broken for the foreground and every other worker. An
123    /// extension that is not running (crashed, stopped by a reload, deferred
124    /// and not started yet) answers `Continue`; the foreground's next call
125    /// starts it as before. Default: [`Self::handle`] (nothing to start).
126    ///
127    /// [`HookBus::worker_transforms`]: crate::extensions::hooks::HookBus::worker_transforms
128    async fn handle_no_spawn(&self, event: &HookEvent) -> HookResult {
129        self.handle(event).await
130    }
131
132    /// Call an extension-provided tool.
133    async fn call_tool(&self, _name: &str, _input: Value) -> Result<Value, String> {
134        Err("extension runtime does not support tool.call".to_string())
135    }
136
137    /// Call an extension-provided tool on behalf of a conversation.
138    ///
139    /// `session_id` is the owning conversation id (`None` = worker/subagent
140    /// or no conversation). Runtimes that put it on the wire override this;
141    /// the default drops it and calls [`Self::call_tool`], so handlers that
142    /// predate the field (and wrappers that fail closed) keep their exact
143    /// behaviour.
144    async fn call_tool_for(
145        &self,
146        name: &str,
147        input: Value,
148        session_id: Option<&str>,
149    ) -> Result<Value, String> {
150        let _ = session_id;
151        self.call_tool(name, input).await
152    }
153
154    /// Complete a chat request through an extension-provided model provider.
155    async fn provider_complete(
156        &self,
157        _params: ProviderCompleteParams,
158    ) -> Result<ProviderCompleteResult, String> {
159        Err("extension runtime does not support provider.complete".to_string())
160    }
161
162    /// Stream a chat request through an extension-provided model provider.
163    ///
164    /// The handler must forward `provider.stream.event` notifications to `sink`
165    /// in order. The returned `ProviderCompleteResult` is the final aggregated
166    /// response (so callers that don't need streaming can use it as the final
167    /// state). Implementations that don't support streaming should return
168    /// `Err("provider.stream is not supported by this extension")`.
169    async fn provider_stream(
170        &self,
171        _params: ProviderCompleteParams,
172        _sink: tokio::sync::mpsc::Sender<ProviderStreamEvent>,
173    ) -> Result<ProviderCompleteResult, String> {
174        Err("provider.stream is not supported by this extension".to_string())
175    }
176
177    /// Invoke a plugin-registered interactive slash command. The handler must
178    /// forward `command.output` notifications matching `request_id` and any
179    /// `task.*` notifications to `sink`. Returns the final response value.
180    ///
181    /// CP-11 fix-3: the sink is BOUNDED and metered
182    /// ([`crate::extensions::invoke_output::InvokeEventSink`]). It must be
183    /// paired with an EAGERLY CONCURRENT consumer — normally the collector
184    /// half of [`crate::extensions::invoke_output::invoke_event_channel`],
185    /// joined with this call by
186    /// `ExtensionManager::invoke_command_collected` — which enforces
187    /// invocation-local byte/event budgets at production time. A hostile
188    /// `command.output` flood is therefore paced by awaited sends and
189    /// bounded retention instead of parking aggregate bytes in an
190    /// unbounded post-hoc queue (the pre-fix behavior). Handlers must
191    /// treat a closed sink like the old closed-unbounded-sink case: stop
192    /// forwarding, still complete the call.
193    async fn invoke_command(
194        &self,
195        _command: &str,
196        _args: Vec<String>,
197        _request_id: &str,
198        _sink: crate::extensions::invoke_output::InvokeEventSink,
199    ) -> Result<Value, String> {
200        Err("extension runtime does not support command.invoke".to_string())
201    }
202
203    /// Fetch optional plugin capability/build/model information.
204    async fn get_info(&self) -> Result<PluginInfo, String> {
205        Err("extension runtime does not support info.get".to_string())
206    }
207
208    /// Ask the plugin to supply sidecar spawn arguments. Used by the
209    /// modality-neutral sidecar bootstrap path (see
210    /// `crate::sidecar::spawn`); plugins that don't host a sidecar
211    /// should leave the default `Err` in place. Core treats the
212    /// returned [`SidecarSpawnArgs::args`] as opaque.
213    async fn sidecar_spawn_args(&self) -> Result<crate::sidecar::spawn::SidecarSpawnArgs, String> {
214        Err("extension runtime does not support sidecar.spawn_args".to_string())
215    }
216
217    /// Open a plugin-owned custom settings editor and return its initial render payload.
218    async fn settings_editor_open(&self, _category: &str, _field: &str) -> Result<Value, String> {
219        Err("extension runtime does not support settings.editor.open".to_string())
220    }
221
222    /// Forward a keypress to the active plugin-owned custom settings editor.
223    async fn settings_editor_key(
224        &self,
225        _category: &str,
226        _field: &str,
227        _key: &str,
228    ) -> Result<Value, String> {
229        Err("extension runtime does not support settings.editor.key".to_string())
230    }
231
232    /// Ask the plugin to commit a custom editor value selected by the UI.
233    async fn settings_editor_commit(
234        &self,
235        _category: &str,
236        _field: &str,
237        _value: Value,
238    ) -> Result<Value, String> {
239        Err("extension runtime does not support settings.editor.commit".to_string())
240    }
241
242    /// Gracefully shut down the extension.
243    async fn shutdown(&self);
244
245    /// Subscribe to raw JSON-RPC notifications from this extension.
246    /// Returns a monotonic subscription id (for unsubscribing) and a
247    /// receiver that yields every notification frame. The default
248    /// implementation returns a channel whose sender is immediately
249    /// dropped, so the receiver yields `None` right away — effectively
250    /// a no-op for handler impls that don't support notifications.
251    async fn subscribe_notifications(
252        &self,
253    ) -> (usize, tokio::sync::mpsc::Receiver<NotificationFrame>) {
254        let (_tx, rx) = tokio::sync::mpsc::channel(1);
255        (0, rx)
256    }
257
258    /// Current health state of this handler.
259    async fn health(&self) -> ExtensionHealth {
260        ExtensionHealth::Running
261    }
262
263    /// Number of transport restarts observed by this handler.
264    async fn restart_count(&self) -> usize {
265        0
266    }
267}
268
269#[cfg(test)]
270mod lifecycle_tests {
271    use super::*;
272
273    struct UnsupportedHandler;
274
275    #[async_trait]
276    impl ExtensionHandler for UnsupportedHandler {
277        fn id(&self) -> &str {
278            "unsupported-lifecycle"
279        }
280
281        async fn handle(&self, _event: &HookEvent) -> HookResult {
282            unreachable!("snapshot must not dispatch a hook")
283        }
284
285        async fn shutdown(&self) {}
286    }
287
288    #[test]
289    fn default_lifecycle_snapshot_is_unavailable_through_trait_object() {
290        let handler: &dyn ExtensionHandler = &UnsupportedHandler;
291        assert_eq!(handler.lifecycle_snapshot(), None);
292    }
293}
294
295#[cfg(test)]
296pub mod tests {
297    use super::*;
298
299    /// Minimal handler for unit tests. Reports generation 0, Running health.
300    pub struct DummyHandler;
301
302    #[async_trait]
303    impl ExtensionHandler for DummyHandler {
304        fn id(&self) -> &str {
305            "dummy"
306        }
307
308        fn lifecycle_snapshot(&self) -> Option<ExtensionLifecycle> {
309            Some(ExtensionLifecycle {
310                health: ExtensionHealth::Running,
311                generation: 0,
312            })
313        }
314
315        async fn handle(&self, _event: &HookEvent) -> HookResult {
316            HookResult::default()
317        }
318
319        async fn shutdown(&self) {}
320    }
321}