1use async_trait::async_trait;
2use eoka_protocol::{
3 all_operations, input_schema_for_operation, request_from_cmd, tags_for_operation,
4 OperationCapability, OperationExposure, OperationSpec,
5};
6use eoka_sdk::EokaClient;
7use std::collections::BTreeSet;
8use std::sync::Arc;
9use tack_core::{
10 CatalogError, Tool, ToolAnnotations, ToolCall, ToolCallError, ToolCallOutput, ToolCatalog,
11 ToolDescriptor, ToolSet, ToolSetError,
12};
13
14#[derive(Clone, Debug)]
15pub struct EokaToolFilter {
16 include_exposures: BTreeSet<ExposureKey>,
17 include_capabilities: BTreeSet<CapabilityKey>,
18}
19
20impl EokaToolFilter {
21 pub fn default_agent() -> Self {
22 let mut include_exposures = BTreeSet::new();
23 include_exposures.insert(ExposureKey::DefaultAgent);
24 Self {
25 include_exposures,
26 include_capabilities: BTreeSet::new(),
27 }
28 }
29
30 pub fn all_non_lifecycle() -> Self {
31 let mut include_exposures = BTreeSet::new();
32 include_exposures.insert(ExposureKey::DefaultAgent);
33 include_exposures.insert(ExposureKey::OptIn);
34 Self {
35 include_exposures,
36 include_capabilities: BTreeSet::new(),
37 }
38 }
39
40 pub fn include_capability(mut self, capability: OperationCapability) -> Self {
41 self.include_capabilities
42 .insert(CapabilityKey::from(capability));
43 self
44 }
45
46 fn includes(&self, operation: &OperationSpec) -> bool {
47 if self
48 .include_capabilities
49 .contains(&CapabilityKey::from(operation.capability))
50 {
51 return operation.exposure != OperationExposure::Lifecycle;
52 }
53 self.include_exposures
54 .contains(&ExposureKey::from(operation.exposure))
55 }
56}
57
58impl Default for EokaToolFilter {
59 fn default() -> Self {
60 Self::default_agent()
61 }
62}
63
64#[derive(Clone)]
65pub struct EokaToolSet {
66 client: Arc<EokaClient>,
67 filter: EokaToolFilter,
68}
69
70impl EokaToolSet {
71 pub fn new(client: EokaClient) -> Self {
72 Self {
73 client: Arc::new(client),
74 filter: EokaToolFilter::default_agent(),
75 }
76 }
77
78 pub fn with_filter(mut self, filter: EokaToolFilter) -> Self {
79 self.filter = filter;
80 self
81 }
82
83 pub fn catalog(&self, namespace: &str) -> Result<ToolCatalog, CatalogError> {
84 let mut catalog = ToolCatalog::new();
85 catalog.mount(namespace, self)?;
86 Ok(catalog)
87 }
88
89 pub fn operations(&self) -> impl Iterator<Item = &'static OperationSpec> + '_ {
90 all_operations()
91 .iter()
92 .filter(|operation| self.filter.includes(operation))
93 }
94}
95
96impl ToolSet for EokaToolSet {
97 fn tools(&self) -> Result<Vec<Arc<dyn Tool>>, ToolSetError> {
98 Ok(self
99 .operations()
100 .map(|operation| {
101 Arc::new(EokaTool::new(Arc::clone(&self.client), operation)) as Arc<dyn Tool>
102 })
103 .collect())
104 }
105}
106
107struct EokaTool {
108 client: Arc<EokaClient>,
109 operation: &'static OperationSpec,
110 descriptor: ToolDescriptor,
111}
112
113impl EokaTool {
114 fn new(client: Arc<EokaClient>, operation: &'static OperationSpec) -> Self {
115 let descriptor = ToolDescriptor::new(operation.path, operation.name)
116 .with_description(operation.description)
117 .with_input_schema(input_schema_for_operation(operation))
118 .with_tags(tags_for_operation(operation))
119 .with_annotations(
120 ToolAnnotations::new()
121 .read_only(operation.read_only)
122 .destructive(operation.destructive)
123 .capability(operation.capability.as_str()),
124 );
125 Self {
126 client,
127 operation,
128 descriptor,
129 }
130 }
131}
132
133#[async_trait]
134impl Tool for EokaTool {
135 fn descriptor(&self) -> &ToolDescriptor {
136 &self.descriptor
137 }
138
139 async fn call(&self, call: ToolCall) -> ToolCallOutput {
140 let request = match request_from_cmd(self.operation.cmd, call.input) {
141 Ok(request) => request,
142 Err(error) => return failed_tool("invalid_input", error),
143 };
144 match self.client.call(request).await {
145 Ok(response) if response.ok => ToolCallOutput {
146 ok: true,
147 data: Some(response.data.unwrap_or(serde_json::Value::Null)),
148 text: None,
149 raw: None,
150 error: None,
151 },
152 Ok(response) => failed_response(response),
153 Err(error) => failed_tool("transport_error", error.to_string()),
154 }
155 }
156}
157
158fn failed_response(response: eoka_sdk::Response) -> ToolCallOutput {
159 let mut message = response
160 .error
161 .unwrap_or_else(|| "Eoka command failed".to_string());
162 let detail = response.error_detail;
163 if let Some(hint) = detail.as_ref().and_then(|detail| detail.hint.as_deref()) {
164 message.push_str(" Hint: ");
165 message.push_str(hint);
166 }
167 ToolCallOutput {
168 ok: false,
169 data: response.data,
170 text: None,
171 raw: None,
172 error: Some(ToolCallError {
173 message,
174 code: Some(
175 detail
176 .as_ref()
177 .map_or("eoka_error", |detail| detail.code.as_str())
178 .to_string(),
179 ),
180 details: detail.and_then(|detail| serde_json::to_value(detail).ok()),
181 }),
182 }
183}
184
185fn failed_tool(code: &'static str, message: String) -> ToolCallOutput {
186 ToolCallOutput {
187 ok: false,
188 data: None,
189 text: None,
190 raw: None,
191 error: Some(ToolCallError {
192 message,
193 code: Some(code.to_string()),
194 details: None,
195 }),
196 }
197}
198
199#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
200enum ExposureKey {
201 DefaultAgent,
202 OptIn,
203 Lifecycle,
204}
205
206impl From<OperationExposure> for ExposureKey {
207 fn from(value: OperationExposure) -> Self {
208 match value {
209 OperationExposure::DefaultAgent => Self::DefaultAgent,
210 OperationExposure::OptIn => Self::OptIn,
211 OperationExposure::Lifecycle => Self::Lifecycle,
212 }
213 }
214}
215
216#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
217enum CapabilityKey {
218 Navigation,
219 Observation,
220 Interaction,
221 JavaScript,
222 BrowserState,
223 Tabs,
224 Spa,
225 Wasm,
226 Network,
227 Policy,
228 Media,
229 Captcha,
230 Lifecycle,
231}
232
233impl From<OperationCapability> for CapabilityKey {
234 fn from(value: OperationCapability) -> Self {
235 match value {
236 OperationCapability::Navigation => Self::Navigation,
237 OperationCapability::Observation => Self::Observation,
238 OperationCapability::Interaction => Self::Interaction,
239 OperationCapability::JavaScript => Self::JavaScript,
240 OperationCapability::BrowserState => Self::BrowserState,
241 OperationCapability::Tabs => Self::Tabs,
242 OperationCapability::Spa => Self::Spa,
243 OperationCapability::Wasm => Self::Wasm,
244 OperationCapability::Network => Self::Network,
245 OperationCapability::Policy => Self::Policy,
246 OperationCapability::Media => Self::Media,
247 OperationCapability::Captcha => Self::Captcha,
248 OperationCapability::Lifecycle => Self::Lifecycle,
249 }
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::*;
256 use eoka_protocol::manifest_for_operations;
257 use eoka_sdk::LaunchSpec;
258
259 fn test_set() -> EokaToolSet {
260 EokaToolSet::new(EokaClient::new(
261 "test",
262 LaunchSpec::Launch {
263 headless: true,
264 from_profile: None,
265 clone_state_from: None,
266 no_stealth: false,
267 proxy: None,
268 no_js: false,
269 js_allow: Vec::new(),
270 js_block: Vec::new(),
271 persist: false,
272 geo_align: false,
273 auto_solve_cloudflare: false,
274 sandbox: true,
275 },
276 ))
277 }
278
279 #[test]
280 fn a_failed_tool_keeps_its_error_code_and_next_step() {
281 let failed = failed_response(eoka_sdk::Response::err_detail(
282 eoka_protocol::ErrorDetail::new("dialog_open", "A JavaScript alert dialog is open.")
283 .hint("Run `dialog.accept` or `dialog.dismiss`."),
284 ));
285 let error = failed.error.unwrap();
286 assert!(!failed.ok);
287 assert_eq!(error.code.as_deref(), Some("dialog_open"));
288 assert!(error.message.contains("A JavaScript alert dialog is open."));
289 assert!(error.message.contains("Hint: Run `dialog.accept`"));
290 assert_eq!(error.details.unwrap()["code"], "dialog_open");
291 let plain = failed_response(eoka_sdk::Response {
292 ok: false,
293 data: None,
294 error: None,
295 error_detail: None,
296 meta: None,
297 });
298 let error = plain.error.unwrap();
299 assert_eq!(error.code.as_deref(), Some("eoka_error"));
300 assert_eq!(error.message, "Eoka command failed");
301 }
302
303 #[test]
304 fn default_catalog_uses_stable_nested_paths() {
305 let catalog = test_set().catalog("eoka").unwrap();
306 assert!(catalog.contains_path("eoka.tab.list"));
307 assert!(catalog.contains_path("eoka.spa.navigate"));
308 assert!(catalog.contains_path("eoka.double_click"));
309 assert!(!catalog.contains_path("eoka.network.log"));
310 assert!(!catalog.contains_path("eoka.close"));
311 }
312
313 #[test]
314 fn opt_in_filter_adds_network_without_lifecycle() {
315 let set = test_set().with_filter(
316 EokaToolFilter::default_agent().include_capability(OperationCapability::Network),
317 );
318 let catalog = set.catalog("eoka").unwrap();
319 assert!(catalog.contains_path("eoka.network.log"));
320 assert!(!catalog.contains_path("eoka.close"));
321 }
322
323 #[test]
324 fn captcha_opt_in_exposes_turnstile() {
325 assert!(!test_set()
326 .catalog("eoka")
327 .unwrap()
328 .contains_path("eoka.captcha.turnstile"));
329 let set = test_set().with_filter(
330 EokaToolFilter::default_agent().include_capability(OperationCapability::Captcha),
331 );
332 assert!(set
333 .catalog("eoka")
334 .unwrap()
335 .contains_path("eoka.captcha.turnstile"));
336 }
337
338 #[test]
339 fn default_descriptors_match_protocol_manifest_projection() {
340 let catalog = test_set().catalog("eoka").unwrap();
341 let manifest = manifest_for_operations("eoka", false);
342
343 for entry in manifest {
344 let descriptor = catalog.by_path(&entry.path).unwrap().descriptor();
345 assert_eq!(descriptor.path(), entry.path);
346 assert_eq!(descriptor.name(), entry.name);
347 assert_eq!(descriptor.description(), Some(entry.description));
348 assert_eq!(descriptor.input_schema(), &entry.input_schema);
349 assert_eq!(
350 descriptor.tags(),
351 &entry
352 .tags
353 .iter()
354 .map(|tag| tag.to_string())
355 .collect::<Vec<_>>()
356 );
357 assert_eq!(
358 descriptor.annotations().capability.as_deref(),
359 Some(entry.capability)
360 );
361 assert_eq!(descriptor.annotations().read_only, Some(entry.read_only));
362 assert_eq!(
363 descriptor.annotations().destructive,
364 Some(entry.destructive)
365 );
366 }
367 }
368}