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/// Trait for extension runtimes that can handle hook events.
84#[async_trait]
85pub trait ExtensionHandler: Send + Sync {
86 /// Unique identifier for this extension.
87 fn id(&self) -> &str;
88
89 /// Handle a hook event. Returns the handler's decision.
90 async fn handle(&self, event: &HookEvent) -> HookResult;
91
92 /// Call an extension-provided tool.
93 async fn call_tool(&self, _name: &str, _input: Value) -> Result<Value, String> {
94 Err("extension runtime does not support tool.call".to_string())
95 }
96
97 /// Complete a chat request through an extension-provided model provider.
98 async fn provider_complete(
99 &self,
100 _params: ProviderCompleteParams,
101 ) -> Result<ProviderCompleteResult, String> {
102 Err("extension runtime does not support provider.complete".to_string())
103 }
104
105 /// Stream a chat request through an extension-provided model provider.
106 ///
107 /// The handler must forward `provider.stream.event` notifications to `sink`
108 /// in order. The returned `ProviderCompleteResult` is the final aggregated
109 /// response (so callers that don't need streaming can use it as the final
110 /// state). Implementations that don't support streaming should return
111 /// `Err("provider.stream is not supported by this extension")`.
112 async fn provider_stream(
113 &self,
114 _params: ProviderCompleteParams,
115 _sink: tokio::sync::mpsc::Sender<ProviderStreamEvent>,
116 ) -> Result<ProviderCompleteResult, String> {
117 Err("provider.stream is not supported by this extension".to_string())
118 }
119
120 /// Invoke a plugin-registered interactive slash command. The handler must
121 /// forward `command.output` notifications matching `request_id` and any
122 /// `task.*` notifications to `sink`. Returns the final response value.
123 ///
124 /// CP-11 fix-3: the sink is BOUNDED and metered
125 /// ([`crate::extensions::invoke_output::InvokeEventSink`]). It must be
126 /// paired with an EAGERLY CONCURRENT consumer — normally the collector
127 /// half of [`crate::extensions::invoke_output::invoke_event_channel`],
128 /// joined with this call by
129 /// `ExtensionManager::invoke_command_collected` — which enforces
130 /// invocation-local byte/event budgets at production time. A hostile
131 /// `command.output` flood is therefore paced by awaited sends and
132 /// bounded retention instead of parking aggregate bytes in an
133 /// unbounded post-hoc queue (the pre-fix behavior). Handlers must
134 /// treat a closed sink like the old closed-unbounded-sink case: stop
135 /// forwarding, still complete the call.
136 async fn invoke_command(
137 &self,
138 _command: &str,
139 _args: Vec<String>,
140 _request_id: &str,
141 _sink: crate::extensions::invoke_output::InvokeEventSink,
142 ) -> Result<Value, String> {
143 Err("extension runtime does not support command.invoke".to_string())
144 }
145
146 /// Fetch optional plugin capability/build/model information.
147 async fn get_info(&self) -> Result<PluginInfo, String> {
148 Err("extension runtime does not support info.get".to_string())
149 }
150
151 /// Ask the plugin to supply sidecar spawn arguments. Used by the
152 /// modality-neutral sidecar bootstrap path (see
153 /// `crate::sidecar::spawn`); plugins that don't host a sidecar
154 /// should leave the default `Err` in place. Core treats the
155 /// returned [`SidecarSpawnArgs::args`] as opaque.
156 async fn sidecar_spawn_args(&self) -> Result<crate::sidecar::spawn::SidecarSpawnArgs, String> {
157 Err("extension runtime does not support sidecar.spawn_args".to_string())
158 }
159
160 /// Open a plugin-owned custom settings editor and return its initial render payload.
161 async fn settings_editor_open(&self, _category: &str, _field: &str) -> Result<Value, String> {
162 Err("extension runtime does not support settings.editor.open".to_string())
163 }
164
165 /// Forward a keypress to the active plugin-owned custom settings editor.
166 async fn settings_editor_key(
167 &self,
168 _category: &str,
169 _field: &str,
170 _key: &str,
171 ) -> Result<Value, String> {
172 Err("extension runtime does not support settings.editor.key".to_string())
173 }
174
175 /// Ask the plugin to commit a custom editor value selected by the UI.
176 async fn settings_editor_commit(
177 &self,
178 _category: &str,
179 _field: &str,
180 _value: Value,
181 ) -> Result<Value, String> {
182 Err("extension runtime does not support settings.editor.commit".to_string())
183 }
184
185 /// Gracefully shut down the extension.
186 async fn shutdown(&self);
187
188 /// Subscribe to raw JSON-RPC notifications from this extension.
189 /// Returns a monotonic subscription id (for unsubscribing) and a
190 /// receiver that yields every notification frame. The default
191 /// implementation returns a channel whose sender is immediately
192 /// dropped, so the receiver yields `None` right away — effectively
193 /// a no-op for handler impls that don't support notifications.
194 async fn subscribe_notifications(
195 &self,
196 ) -> (usize, tokio::sync::mpsc::Receiver<NotificationFrame>) {
197 let (_tx, rx) = tokio::sync::mpsc::channel(1);
198 (0, rx)
199 }
200
201 /// Current health state of this handler.
202 async fn health(&self) -> ExtensionHealth {
203 ExtensionHealth::Running
204 }
205
206 /// Number of transport restarts observed by this handler.
207 async fn restart_count(&self) -> usize {
208 0
209 }
210}