1use async_trait::async_trait;
11use everruns_core::ToolHints;
12use everruns_core::capabilities::{
13 Capability, CapabilityLocalization, CapabilityStatus, RiskLevel,
14};
15use everruns_core::payment::{MachinePaymentRequest, PaymentMethod, PaymentRail};
16use everruns_core::tool_narration::{
17 generic_phrase, labeled_phrase, safe_arg_str, truncate, url_display,
18};
19use everruns_core::tools::{Tool, ToolExecutionResult};
20use everruns_core::traits::ToolContext;
21use serde::Deserialize;
22use serde_json::{Value, json};
23
24const PARALLEL_BASE_URL: &str = "https://parallelmpp.dev";
25
26pub struct ParallelPaymentsCapability;
27
28#[async_trait]
29impl Capability for ParallelPaymentsCapability {
30 fn id(&self) -> &str {
31 "parallel"
32 }
33
34 fn name(&self) -> &str {
35 "Parallel (Machine Payments)"
36 }
37
38 fn description(&self) -> &str {
39 "Paid Parallel search, extract, and async task tools backed by Everruns machine payments."
40 }
41
42 fn status(&self) -> CapabilityStatus {
43 CapabilityStatus::Available
44 }
45
46 fn risk_level(&self) -> RiskLevel {
47 RiskLevel::High
48 }
49
50 fn icon(&self) -> Option<&str> {
51 Some("wallet")
52 }
53
54 fn category(&self) -> Option<&str> {
55 Some("Machine Payments")
56 }
57
58 fn system_prompt_addition(&self) -> Option<&str> {
59 Some(
60 "When web research is needed and Parallel tools are available, prefer the Parallel tools for structured paid search/extract/task work. Use `parallel_task_status` to poll async task run IDs until complete.",
61 )
62 }
63
64 fn tools(&self) -> Vec<Box<dyn Tool>> {
65 vec![
66 Box::new(ParallelSearchTool),
67 Box::new(ParallelExtractTool),
68 Box::new(ParallelTaskTool),
69 Box::new(ParallelTaskStatusTool),
70 ]
71 }
72
73 fn features(&self) -> Vec<&'static str> {
74 vec!["machine_payments"]
75 }
76
77 fn localizations(&self) -> Vec<CapabilityLocalization> {
78 vec![CapabilityLocalization::text(
79 "uk",
80 "Parallel (машинні платежі)",
81 "Платні інструменти Parallel для пошуку, вилучення даних та асинхронних завдань \
82 на основі машинних платежів Everruns.",
83 )]
84 }
85}
86
87#[derive(Debug, Deserialize)]
88struct SearchArgs {
89 query: String,
90 #[serde(default = "default_search_mode")]
91 mode: String,
92}
93
94fn default_search_mode() -> String {
95 "one-shot".to_string()
96}
97
98pub struct ParallelSearchTool;
99
100#[async_trait]
101impl Tool for ParallelSearchTool {
102 fn narrate(
103 &self,
104 tool_call: &everruns_core::tool_types::ToolCall,
105 phase: everruns_core::tool_narration::ToolNarrationPhase,
106 _locale: Option<&str>,
107 _ctx: everruns_core::tool_narration::ToolNarrationContext<'_>,
108 ) -> Option<String> {
109 let query = safe_arg_str(&tool_call.arguments, &["query", "q", "objective"])
110 .map(|value| truncate(value, 48));
111 Some(labeled_phrase(
112 "Searching Parallel",
113 "Searched Parallel",
114 "Could not search Parallel",
115 query,
116 phase,
117 ))
118 }
119
120 fn name(&self) -> &str {
121 "parallel_search"
122 }
123
124 fn display_name(&self) -> Option<&str> {
125 Some("Parallel Search")
126 }
127
128 fn description(&self) -> &str {
129 "Search the web through Parallel's paid API. Costs up to $0.01 per call."
130 }
131
132 fn parameters_schema(&self) -> Value {
133 json!({
134 "type": "object",
135 "properties": {
136 "query": { "type": "string", "description": "Search query." },
137 "mode": {
138 "type": "string",
139 "enum": ["one-shot", "fast"],
140 "description": "Use one-shot for comprehensive results or fast for lower latency.",
141 "default": "one-shot"
142 }
143 },
144 "required": ["query"],
145 "additionalProperties": false
146 })
147 }
148
149 fn requires_context(&self) -> bool {
150 true
151 }
152
153 fn hints(&self) -> ToolHints {
154 ToolHints::default()
155 .with_readonly(true)
156 .with_open_world(true)
157 .with_requires_secrets(true)
158 }
159
160 async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
161 missing_payment_authority()
162 }
163
164 async fn execute_with_context(
165 &self,
166 arguments: Value,
167 context: &ToolContext,
168 ) -> ToolExecutionResult {
169 let args: SearchArgs = match serde_json::from_value(arguments) {
170 Ok(args) => args,
171 Err(error) => return invalid_args(error),
172 };
173 if !matches!(args.mode.as_str(), "one-shot" | "fast") {
174 return ToolExecutionResult::tool_error("mode must be one of: one-shot, fast");
175 }
176 execute_paid_parallel(
177 context,
178 "search",
179 "/api/search",
180 json!({ "query": args.query, "mode": args.mode }),
181 0.01,
182 )
183 .await
184 }
185}
186
187#[derive(Debug, Deserialize)]
188struct ExtractArgs {
189 urls: Vec<String>,
190 objective: String,
191}
192
193pub struct ParallelExtractTool;
194
195#[async_trait]
196impl Tool for ParallelExtractTool {
197 fn narrate(
198 &self,
199 tool_call: &everruns_core::tool_types::ToolCall,
200 phase: everruns_core::tool_narration::ToolNarrationPhase,
201 _locale: Option<&str>,
202 _ctx: everruns_core::tool_narration::ToolNarrationContext<'_>,
203 ) -> Option<String> {
204 let url = safe_arg_str(&tool_call.arguments, &["url"])
208 .map(str::to_string)
209 .or_else(|| {
210 tool_call
211 .arguments
212 .get("urls")
213 .and_then(Value::as_array)
214 .and_then(|items| items.first())
215 .and_then(Value::as_str)
216 .map(str::to_string)
217 })
218 .map(|value| url_display(&value))
219 .filter(|value| !value.is_empty());
220 Some(labeled_phrase(
221 "Extracting URL",
222 "Extracted URL",
223 "Could not extract URL",
224 url,
225 phase,
226 ))
227 }
228
229 fn name(&self) -> &str {
230 "parallel_extract"
231 }
232
233 fn display_name(&self) -> Option<&str> {
234 Some("Parallel Extract")
235 }
236
237 fn description(&self) -> &str {
238 "Extract structured facts from URLs through Parallel's paid API. Costs up to $0.01 per URL, minimum $0.01."
239 }
240
241 fn parameters_schema(&self) -> Value {
242 json!({
243 "type": "object",
244 "properties": {
245 "urls": {
246 "type": "array",
247 "items": { "type": "string" },
248 "minItems": 1,
249 "description": "URLs to extract from."
250 },
251 "objective": { "type": "string", "description": "What facts to extract." }
252 },
253 "required": ["urls", "objective"],
254 "additionalProperties": false
255 })
256 }
257
258 fn requires_context(&self) -> bool {
259 true
260 }
261
262 fn hints(&self) -> ToolHints {
263 ToolHints::default()
264 .with_readonly(true)
265 .with_open_world(true)
266 .with_requires_secrets(true)
267 }
268
269 async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
270 missing_payment_authority()
271 }
272
273 async fn execute_with_context(
274 &self,
275 arguments: Value,
276 context: &ToolContext,
277 ) -> ToolExecutionResult {
278 let args: ExtractArgs = match serde_json::from_value(arguments) {
279 Ok(args) => args,
280 Err(error) => return invalid_args(error),
281 };
282 if args.urls.is_empty() {
283 return ToolExecutionResult::tool_error("urls must contain at least one URL");
284 }
285 let max_amount_usd = (args.urls.len() as f64 * 0.01).max(0.01);
286 execute_paid_parallel(
287 context,
288 "extract",
289 "/api/extract",
290 json!({ "urls": args.urls, "objective": args.objective }),
291 max_amount_usd,
292 )
293 .await
294 }
295}
296
297#[derive(Debug, Deserialize)]
298struct TaskArgs {
299 input: String,
300 #[serde(default = "default_processor")]
301 processor: String,
302}
303
304fn default_processor() -> String {
305 "ultra".to_string()
306}
307
308pub struct ParallelTaskTool;
309
310#[async_trait]
311impl Tool for ParallelTaskTool {
312 fn narrate(
313 &self,
314 tool_call: &everruns_core::tool_types::ToolCall,
315 phase: everruns_core::tool_narration::ToolNarrationPhase,
316 _locale: Option<&str>,
317 _ctx: everruns_core::tool_narration::ToolNarrationContext<'_>,
318 ) -> Option<String> {
319 let objective = safe_arg_str(&tool_call.arguments, &["input", "objective"])
320 .map(|value| truncate(value, 48));
321 Some(labeled_phrase(
322 "Running Parallel task",
323 "Ran Parallel task",
324 "Failed to run Parallel task",
325 objective,
326 phase,
327 ))
328 }
329
330 fn name(&self) -> &str {
331 "parallel_task"
332 }
333
334 fn display_name(&self) -> Option<&str> {
335 Some("Parallel Task")
336 }
337
338 fn description(&self) -> &str {
339 "Start a deep async Parallel task. Costs up to $0.10 for pro or $0.30 for ultra; poll with parallel_task_status."
340 }
341
342 fn parameters_schema(&self) -> Value {
343 json!({
344 "type": "object",
345 "properties": {
346 "input": { "type": "string", "description": "Task input." },
347 "processor": {
348 "type": "string",
349 "enum": ["pro", "ultra"],
350 "default": "ultra"
351 }
352 },
353 "required": ["input"],
354 "additionalProperties": false
355 })
356 }
357
358 fn requires_context(&self) -> bool {
359 true
360 }
361
362 fn hints(&self) -> ToolHints {
363 ToolHints::default()
364 .with_readonly(true)
365 .with_open_world(true)
366 .with_requires_secrets(true)
367 .with_long_running(true)
368 }
369
370 async fn execute(&self, _arguments: Value) -> ToolExecutionResult {
371 missing_payment_authority()
372 }
373
374 async fn execute_with_context(
375 &self,
376 arguments: Value,
377 context: &ToolContext,
378 ) -> ToolExecutionResult {
379 let args: TaskArgs = match serde_json::from_value(arguments) {
380 Ok(args) => args,
381 Err(error) => return invalid_args(error),
382 };
383 let max_amount_usd = match args.processor.as_str() {
384 "pro" => 0.10,
385 "ultra" => 0.30,
386 _ => return ToolExecutionResult::tool_error("processor must be one of: pro, ultra"),
387 };
388 execute_paid_parallel(
389 context,
390 "task",
391 "/api/task",
392 json!({ "input": args.input, "processor": args.processor }),
393 max_amount_usd,
394 )
395 .await
396 }
397}
398
399#[derive(Debug, Deserialize)]
400struct TaskStatusArgs {
401 run_id: String,
402}
403
404pub struct ParallelTaskStatusTool;
405
406#[async_trait]
407impl Tool for ParallelTaskStatusTool {
408 fn narrate(
409 &self,
410 _tool_call: &everruns_core::tool_types::ToolCall,
411 phase: everruns_core::tool_narration::ToolNarrationPhase,
412 _locale: Option<&str>,
413 _ctx: everruns_core::tool_narration::ToolNarrationContext<'_>,
414 ) -> Option<String> {
415 Some(generic_phrase(
417 "Checking task status",
418 "Checked task status",
419 "Failed to check task status",
420 None,
421 phase,
422 ))
423 }
424
425 fn name(&self) -> &str {
426 "parallel_task_status"
427 }
428
429 fn display_name(&self) -> Option<&str> {
430 Some("Parallel Task Status")
431 }
432
433 fn description(&self) -> &str {
434 "Poll a Parallel task run. This endpoint is free and does not require payment."
435 }
436
437 fn parameters_schema(&self) -> Value {
438 json!({
439 "type": "object",
440 "properties": {
441 "run_id": { "type": "string", "description": "Run ID returned by parallel_task." }
442 },
443 "required": ["run_id"],
444 "additionalProperties": false
445 })
446 }
447
448 fn hints(&self) -> ToolHints {
449 ToolHints::default()
450 .with_readonly(true)
451 .with_idempotent(true)
452 .with_open_world(true)
453 }
454
455 async fn execute(&self, arguments: Value) -> ToolExecutionResult {
456 let args: TaskStatusArgs = match serde_json::from_value(arguments) {
457 Ok(args) => args,
458 Err(error) => return invalid_args(error),
459 };
460 let run_id = args.run_id.trim();
461 if run_id.is_empty() || run_id.contains('/') {
462 return ToolExecutionResult::tool_error("run_id is invalid");
463 }
464 let url = format!("{PARALLEL_BASE_URL}/api/task/{run_id}");
465 match reqwest::Client::new().get(url).send().await {
466 Ok(response) => match response.json::<Value>().await {
467 Ok(value) => ToolExecutionResult::success(value),
468 Err(error) => ToolExecutionResult::tool_error(format!(
469 "Parallel task status response was not valid JSON: {error}"
470 )),
471 },
472 Err(error) => ToolExecutionResult::tool_error(format!(
473 "Failed to poll Parallel task status: {error}"
474 )),
475 }
476 }
477}
478
479async fn execute_paid_parallel(
480 context: &ToolContext,
481 operation: &str,
482 path: &str,
483 body: Value,
484 max_amount_usd: f64,
485) -> ToolExecutionResult {
486 let Some(authority) = context.payment_authority.as_ref() else {
487 return missing_payment_authority();
488 };
489
490 let request = MachinePaymentRequest {
491 capability: "parallel".to_string(),
492 operation: operation.to_string(),
493 method: PaymentMethod::Post,
494 url: format!("{PARALLEL_BASE_URL}{path}"),
495 body: Some(body),
496 max_amount_usd,
497 rail_preference: vec![PaymentRail::X402Base],
498 metadata: json!({
499 "provider": "parallel",
500 "host": "parallelmpp.dev",
501 "path": path,
502 }),
503 };
504
505 match authority
506 .execute_machine_payment(context.session_id, request)
507 .await
508 {
509 Ok(response) => ToolExecutionResult::success(json!({
510 "result": response.response,
511 "payment": {
512 "attempt_id": response.attempt_id.map(|id| id.to_string()),
513 "amount_usd": response.amount_usd,
514 "rail": response.rail.map(|rail| rail.to_string()),
515 "receipt": response.receipt,
516 }
517 })),
518 Err(error) => ToolExecutionResult::tool_error(format!("Machine payment failed: {error}")),
519 }
520}
521
522fn missing_payment_authority() -> ToolExecutionResult {
523 ToolExecutionResult::tool_error(
524 "Machine payments are not configured for this session. Configure a payment wallet and policy before using Parallel paid tools.",
525 )
526}
527
528fn invalid_args(error: serde_json::Error) -> ToolExecutionResult {
529 ToolExecutionResult::tool_error(format!("Invalid arguments: {error}"))
530}
531
532#[cfg(test)]
533mod tests {
534 use super::*;
535
536 #[test]
537 fn metadata() {
538 let cap = ParallelPaymentsCapability;
539 assert_eq!(cap.id(), "parallel");
540 assert_eq!(cap.category(), Some("Machine Payments"));
541 assert_eq!(cap.risk_level(), RiskLevel::High);
542 assert_eq!(cap.tools().len(), 4);
543 assert_eq!(cap.features(), vec!["machine_payments"]);
544 }
545
546 #[tokio::test]
547 async fn paid_tools_fail_closed_without_authority() {
548 let result = ParallelSearchTool
550 .execute(json!({ "query": "hello" }))
551 .await;
552 assert!(result.is_error());
553 }
554
555 use everruns_core::tool_narration::{ToolNarrationContext, ToolNarrationPhase};
560 use everruns_core::tool_types::ToolCall;
561
562 fn narrate(tool: &dyn Tool, arguments: Value, phase: ToolNarrationPhase) -> Option<String> {
563 let call = ToolCall {
564 id: "call-1".to_string(),
565 name: tool.name().to_string(),
566 arguments,
567 };
568 tool.narrate(&call, phase, None, ToolNarrationContext::default())
569 }
570
571 #[test]
572 fn narrate_search_all_phases_and_truncation() {
573 let tool = ParallelSearchTool;
574 assert_eq!(
575 narrate(
576 &tool,
577 json!({"query": "rust async"}),
578 ToolNarrationPhase::Started
579 )
580 .as_deref(),
581 Some("Searching Parallel: rust async")
582 );
583 assert_eq!(
584 narrate(
585 &tool,
586 json!({"query": "rust async"}),
587 ToolNarrationPhase::Completed
588 )
589 .as_deref(),
590 Some("Searched Parallel: rust async")
591 );
592 assert_eq!(
593 narrate(
594 &tool,
595 json!({"query": "rust async"}),
596 ToolNarrationPhase::Failed
597 )
598 .as_deref(),
599 Some("Could not search Parallel: rust async")
600 );
601 let long = "a".repeat(80);
603 let narration =
604 narrate(&tool, json!({ "query": long }), ToolNarrationPhase::Started).unwrap();
605 assert!(narration.starts_with("Searching Parallel: "));
606 assert!(narration.ends_with("..."));
607 assert_eq!(
609 narrate(&tool, json!({}), ToolNarrationPhase::Started).as_deref(),
610 Some("Searching Parallel")
611 );
612 }
613
614 #[test]
615 fn narrate_extract_uses_first_url_and_strips_scheme() {
616 let tool = ParallelExtractTool;
617 assert_eq!(
618 narrate(
619 &tool,
620 json!({"urls": ["https://example.com/a?x=1", "https://example.com/b"], "objective": "facts"}),
621 ToolNarrationPhase::Started
622 )
623 .as_deref(),
624 Some("Extracting URL: example.com/a")
625 );
626 assert_eq!(
628 narrate(&tool, json!({}), ToolNarrationPhase::Failed).as_deref(),
629 Some("Could not extract URL")
630 );
631 }
632
633 #[test]
634 fn narrate_task_status_is_bare() {
635 let tool = ParallelTaskStatusTool;
636 assert_eq!(
637 narrate(
638 &tool,
639 json!({"run_id": "abc123"}),
640 ToolNarrationPhase::Started
641 )
642 .as_deref(),
643 Some("Checking task status")
644 );
645 assert_eq!(
646 narrate(
647 &tool,
648 json!({"run_id": "abc123"}),
649 ToolNarrationPhase::Completed
650 )
651 .as_deref(),
652 Some("Checked task status")
653 );
654 }
655}