Skip to content

Self-improving AI Employees for everyone

feat: Add provider-agnostic proxy template system

trohitg15c0f6fa01d5
diff --git a/client/src/nodeDefinitions/proxyNodes.ts b/client/src/nodeDefinitions/proxyNodes.ts
new file mode 100644
index 00000000..86ab8b24
--- /dev/null
+++ b/client/src/nodeDefinitions/proxyNodes.ts
@@ -0,0 +1,358 @@
+// Proxy Nodes - Proxy-aware HTTP requests and provider status
+import {
+ INodeTypeDescription,
+ NodeConnectionType
+} from '../types/INodeProperties';
+
+// ============================================================================
+// PROXY NODES
+// ============================================================================
+
+export const proxyNodes: Record<string, INodeTypeDescription> = {
+ proxyRequest: {
+ displayName: 'Proxy Request',
+ name: 'proxyRequest',
+ icon: 'πŸ›‘',
+ group: ['proxy', 'api'],
+ version: 1,
+ description: 'Make HTTP requests through residential proxy providers with geo-targeting and failover',
+ defaults: { name: 'Proxy Request', color: '#8B5CF6' },
+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Trigger input' }],
+ outputs: [{
+ name: 'main',
+ displayName: 'Response',
+ type: 'main' as NodeConnectionType,
+ description: 'status, data, headers, proxy_provider, proxy_country'
+ }],
+ properties: [
+ {
+ displayName: 'Method',
+ name: 'method',
+ type: 'options',
+ default: 'GET',
+ options: [
+ { name: 'GET', value: 'GET' },
+ { name: 'POST', value: 'POST' },
+ { name: 'PUT', value: 'PUT' },
+ { name: 'DELETE', value: 'DELETE' },
+ { name: 'PATCH', value: 'PATCH' }
+ ]
+ },
+ {
+ displayName: 'URL',
+ name: 'url',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'https://api.example.com/endpoint'
+ },
+ {
+ displayName: 'Headers',
+ name: 'headers',
+ type: 'string',
+ default: '{}',
+ typeOptions: { rows: 3 },
+ placeholder: '{"Authorization": "Bearer token"}'
+ },
+ {
+ displayName: 'Body',
+ name: 'body',
+ type: 'string',
+ default: '',
+ typeOptions: { rows: 4 },
+ placeholder: '{"key": "value"}',
+ displayOptions: { show: { method: ['POST', 'PUT', 'PATCH'] } }
+ },
+ {
+ displayName: 'Timeout (seconds)',
+ name: 'timeout',
+ type: 'number',
+ default: 30,
+ typeOptions: { minValue: 5, maxValue: 300 }
+ },
+
+ // ===== PROXY CONFIG =====
+ {
+ displayName: 'Proxy Provider',
+ name: 'proxyProvider',
+ type: 'string',
+ default: '',
+ placeholder: 'Auto-select (best score)',
+ description: 'Provider name to use, or leave empty for auto-selection'
+ },
+ {
+ displayName: 'Country',
+ name: 'proxyCountry',
+ type: 'string',
+ default: '',
+ placeholder: 'US',
+ description: 'ISO 3166-1 alpha-2 country code for geo-targeting (e.g., US, GB, DE)'
+ },
+ {
+ displayName: 'Session Type',
+ name: 'sessionType',
+ type: 'options',
+ default: 'rotating',
+ options: [
+ { name: 'Rotating', value: 'rotating' },
+ { name: 'Sticky', value: 'sticky' }
+ ],
+ description: 'Rotating: new IP per request. Sticky: same IP for duration.'
+ },
+ {
+ displayName: 'Sticky Duration (seconds)',
+ name: 'stickyDuration',
+ type: 'number',
+ default: 300,
+ typeOptions: { minValue: 30, maxValue: 3600 },
+ displayOptions: { show: { sessionType: ['sticky'] } },
+ description: 'How long to maintain the same IP address'
+ },
+ {
+ displayName: 'Max Retries',
+ name: 'maxRetries',
+ type: 'number',
+ default: 3,
+ typeOptions: { minValue: 0, maxValue: 10 },
+ description: 'Number of retry attempts on failure (with failover to other providers)'
+ },
+ {
+ displayName: 'Follow Redirects',
+ name: 'followRedirects',
+ type: 'boolean',
+ default: true,
+ description: 'Automatically follow HTTP redirects'
+ }
+ ]
+ },
+
+ proxyConfig: {
+ displayName: 'Proxy Config',
+ name: 'proxyConfig',
+ icon: 'πŸ”§',
+ group: ['proxy', 'tool'],
+ version: 1,
+ description: 'Configure proxy providers and routing rules. Works as workflow node or AI Agent tool.',
+ defaults: { name: 'Proxy Config', color: '#8B5CF6' },
+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Trigger input' }],
+ outputs: [{
+ name: 'main',
+ displayName: 'Result',
+ type: 'main' as NodeConnectionType,
+ description: 'Operation result'
+ }],
+ properties: [
+ {
+ displayName: 'Operation',
+ name: 'operation',
+ type: 'options',
+ default: 'list_providers',
+ required: true,
+ options: [
+ { name: 'List Providers', value: 'list_providers' },
+ { name: 'Add Provider', value: 'add_provider' },
+ { name: 'Update Provider', value: 'update_provider' },
+ { name: 'Remove Provider', value: 'remove_provider' },
+ { name: 'Set Credentials', value: 'set_credentials' },
+ { name: 'Test Provider', value: 'test_provider' },
+ { name: 'Get Stats', value: 'get_stats' },
+ { name: 'Add Routing Rule', value: 'add_routing_rule' },
+ { name: 'List Routing Rules', value: 'list_routing_rules' },
+ { name: 'Remove Routing Rule', value: 'remove_routing_rule' }
+ ]
+ },
+ // Provider fields
+ {
+ displayName: 'Provider Name',
+ name: 'name',
+ type: 'string',
+ default: '',
+ required: true,
+ placeholder: 'my_proxy_provider',
+ description: 'Unique name for the proxy provider',
+ displayOptions: { show: { operation: ['add_provider', 'update_provider', 'remove_provider', 'set_credentials', 'test_provider'] } }
+ },
+ {
+ displayName: 'Gateway Host',
+ name: 'gateway_host',
+ type: 'string',
+ default: '',
+ placeholder: 'gate.example.com',
+ description: 'Proxy gateway hostname',
+ displayOptions: { show: { operation: ['add_provider', 'update_provider'] } }
+ },
+ {
+ displayName: 'Gateway Port',
+ name: 'gateway_port',
+ type: 'number',
+ default: 0,
+ placeholder: '7777',
+ description: 'Proxy gateway port',
+ displayOptions: { show: { operation: ['add_provider', 'update_provider'] } }
+ },
+ {
+ displayName: 'URL Template (JSON)',
+ name: 'url_template',
+ type: 'string',
+ default: '{}',
+ typeOptions: { rows: 6 },
+ description: 'JSON template config for proxy URL encoding',
+ displayOptions: { show: { operation: ['add_provider', 'update_provider'] } }
+ },
+ {
+ displayName: 'Cost per GB (USD)',
+ name: 'cost_per_gb',
+ type: 'number',
+ default: 0,
+ typeOptions: { minValue: 0, maxValue: 100 },
+ description: 'Cost per gigabyte in USD',
+ displayOptions: { show: { operation: ['add_provider', 'update_provider'] } }
+ },
+ {
+ displayName: 'Priority',
+ name: 'priority',
+ type: 'number',
+ default: 50,
+ typeOptions: { minValue: 0, maxValue: 100 },
+ description: 'Provider priority (lower = preferred)',
+ displayOptions: { show: { operation: ['add_provider', 'update_provider'] } }
+ },
+ {
+ displayName: 'Enabled',
+ name: 'enabled',
+ type: 'boolean',
+ default: true,
+ displayOptions: { show: { operation: ['add_provider', 'update_provider'] } }
+ },
+ // Credential fields
+ {
+ displayName: 'Username',
+ name: 'username',
+ type: 'string',
+ default: '',
+ description: 'Proxy username',
+ displayOptions: { show: { operation: ['set_credentials'] } }
+ },
+ {
+ displayName: 'Password',
+ name: 'password',
+ type: 'string',
+ default: '',
+ description: 'Proxy password',
+ displayOptions: { show: { operation: ['set_credentials'] } }
+ },
+ // Routing rule fields
+ {
+ displayName: 'Domain Pattern',
+ name: 'domain_pattern',
+ type: 'string',
+ default: '',
+ placeholder: '*.linkedin.com',
+ description: 'Domain glob pattern for routing (e.g., *.linkedin.com, *)',
+ displayOptions: { show: { operation: ['add_routing_rule'] } }
+ },
+ {
+ displayName: 'Preferred Providers (JSON)',
+ name: 'preferred_providers',
+ type: 'string',
+ default: '[]',
+ placeholder: '["provider1", "provider2"]',
+ description: 'JSON array of preferred provider names',
+ displayOptions: { show: { operation: ['add_routing_rule'] } }
+ },
+ {
+ displayName: 'Required Country',
+ name: 'required_country',
+ type: 'string',
+ default: '',
+ placeholder: 'US',
+ description: 'ISO country code required for this domain',
+ displayOptions: { show: { operation: ['add_routing_rule'] } }
+ },
+ {
+ displayName: 'Session Type',
+ name: 'session_type',
+ type: 'options',
+ default: 'rotating',
+ options: [
+ { name: 'Rotating', value: 'rotating' },
+ { name: 'Sticky', value: 'sticky' }
+ ],
+ displayOptions: { show: { operation: ['add_routing_rule'] } }
+ },
+ {
+ displayName: 'Rule ID',
+ name: 'rule_id',
+ type: 'number',
+ default: 0,
+ description: 'ID of the routing rule to remove',
+ displayOptions: { show: { operation: ['remove_routing_rule'] } }
+ }
+ ]
+ },
+
+ proxyStatus: {
+ displayName: 'Proxy Status',
+ name: 'proxyStatus',
+ icon: 'πŸ“Š',
+ group: ['proxy', 'utility'],
+ version: 1,
+ description: 'View proxy provider health, scores, and usage statistics',
+ defaults: { name: 'Proxy Status', color: '#6366F1' },
+ inputs: [{ name: 'main', displayName: 'Input', type: 'main' as NodeConnectionType, description: 'Trigger input' }],
+ outputs: [{
+ name: 'main',
+ displayName: 'Stats',
+ type: 'main' as NodeConnectionType,
+ description: 'providers, routing_rules, stats'
+ }],
+ properties: [
+ {
+ displayName: 'Provider',
+ name: 'providerFilter',
+ type: 'string',
+ default: '',
+ placeholder: 'All providers',
+ description: 'Filter by specific provider name, or leave empty for all'
+ }
+ ]
+ }
+};
+
+// ============================================================================
+// PROXY PARAMETERS (shared, for injection into other nodes)
+// ============================================================================
+
+/**
+ * Common proxy parameters to add to existing nodes (httpRequest, search, scraper).
+ * These are appended to the node's properties array.
+ */
+export const PROXY_PARAMETERS = [
+ {
+ displayName: 'Use Proxy',
+ name: 'useProxy',
+ type: 'boolean' as const,
+ default: false,
+ description: 'Route request through a residential proxy provider'
+ },
+ {
+ displayName: 'Proxy Provider',
+ name: 'proxyProvider',
+ type: 'string' as const,
+ default: '',
+ placeholder: 'Auto-select',
+ description: 'Provider name, or leave empty for auto-selection',
+ displayOptions: { show: { useProxy: [true] } }
+ },
+ {
+ displayName: 'Proxy Country',
+ name: 'proxyCountry',
+ type: 'string' as const,
+ default: '',
+ placeholder: 'US',
+ description: 'ISO country code for geo-targeting',
+ displayOptions: { show: { useProxy: [true] } }
+ }
+];
+
+export const PROXY_NODE_TYPES = ['proxyRequest', 'proxyStatus', 'proxyConfig'];
diff --git a/server/services/handlers/proxy.py b/server/services/handlers/proxy.py
new file mode 100644
index 00000000..710a67d9
--- /dev/null
+++ b/server/services/handlers/proxy.py
@@ -0,0 +1,326 @@
+"""Proxy node handlers - proxyRequest, proxyStatus, proxyConfig.
+
+proxyRequest: HTTP request with full proxy controls, retry/failover loop.
+proxyStatus: Returns provider health stats for dashboard display.
+proxyConfig: Manage proxy providers and routing rules (dual-purpose tool).
+"""
+
+import json
+import time
+from datetime import datetime
+from typing import Dict, Any
+
+import httpx
+
+from core.logging import get_logger
+from services.proxy.models import ProxyResult
+from services.proxy.service import get_proxy_service
+
+logger = get_logger(__name__)
+
+
+async def _track_proxy_usage(
+ node_id: str,
+ provider_name: str,
+ bytes_transferred: int,
+ workflow_id: str = None,
+ session_id: str = "default",
+) -> Dict[str, float]:
+ """Track proxy usage and persist cost to database.
+
+ Cost is calculated as bytes_transferred / 1GB * cost_per_gb
+ from server/config/pricing.json proxy section.
+ """
+ from core.container import container
+ from services.pricing import get_pricing_service
+
+ pricing = get_pricing_service()
+
+ # Read cost_per_gb from pricing config
+ proxy_pricing = pricing._config.get("proxy", {})
+ provider_pricing = proxy_pricing.get(provider_name, {})
+ cost_per_gb = provider_pricing.get("cost_per_gb", 0.0)
+
+ gb_transferred = bytes_transferred / (1024 ** 3)
+ total_cost = round(gb_transferred * cost_per_gb, 8)
+
+ db = container.database()
+ await db.save_api_usage_metric({
+ "session_id": session_id,
+ "node_id": node_id,
+ "workflow_id": workflow_id,
+ "service": f"proxy_{provider_name}" if provider_name else "proxy",
+ "operation": "proxy_request",
+ "endpoint": "proxy",
+ "resource_count": 1,
+ "cost": total_cost,
+ })
+
+ logger.debug(
+ f"[Proxy] Tracked {provider_name} usage: {bytes_transferred} bytes = ${total_cost:.8f}"
+ )
+ return {"cost_per_gb": cost_per_gb, "bytes": bytes_transferred, "total_cost": total_cost}
+
+
+async def handle_proxy_request(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Handle proxyRequest node execution.
+
+ Makes HTTP requests through configured proxy providers with
+ retry/failover, geo-targeting, and result reporting.
+
+ Args:
+ node_id: The node ID
+ node_type: The node type (proxyRequest)
+ parameters: Resolved parameters
+ context: Execution context
+
+ Returns:
+ Execution result dict with response data
+ """
+ start_time = time.time()
+
+ try:
+ proxy_svc = get_proxy_service()
+ if not proxy_svc or not proxy_svc.is_enabled():
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "proxyRequest",
+ "error": "Proxy service is not enabled. Set PROXY_ENABLED=true in .env",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ method = parameters.get('method', 'GET')
+ url = parameters.get('url', '')
+ headers_str = parameters.get('headers', '{}')
+ body = parameters.get('body', '')
+ timeout = float(parameters.get('timeout', 30))
+ max_retries = int(parameters.get('maxRetries', parameters.get('proxyMaxRetries', 3)))
+ failover = parameters.get('proxyFailover', True)
+
+ if not url:
+ raise ValueError("URL is required")
+
+ # Parse headers JSON
+ try:
+ headers = json.loads(headers_str) if headers_str else {}
+ except json.JSONDecodeError:
+ headers = {}
+
+ # Get proxy URL
+ proxy_url = await proxy_svc.get_proxy_url(url, parameters)
+ if not proxy_url:
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "proxyRequest",
+ "error": "No proxy provider available",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ # Determine provider name for result reporting
+ provider_name = parameters.get('proxyProvider', '')
+
+ last_error = None
+ for attempt in range(max_retries + 1):
+ req_start = time.monotonic()
+ try:
+ async with httpx.AsyncClient(proxy=proxy_url, timeout=timeout) as client:
+ kwargs: Dict[str, Any] = {
+ 'method': method,
+ 'url': url,
+ 'headers': headers,
+ }
+ if method in ['POST', 'PUT', 'PATCH'] and body:
+ try:
+ kwargs['json'] = json.loads(body)
+ except json.JSONDecodeError:
+ kwargs['content'] = body
+
+ response = await client.request(**kwargs)
+
+ latency_ms = (time.monotonic() - req_start) * 1000
+ bytes_transferred = len(response.content) if response.content else 0
+
+ # Report success to health scorer
+ proxy_svc.report_result(provider_name, ProxyResult(
+ success=response.status_code < 400,
+ latency_ms=latency_ms,
+ bytes_transferred=bytes_transferred,
+ status_code=response.status_code,
+ ))
+
+ # Track cost in database
+ workflow_id = context.get("workflow_id")
+ session_id = context.get("session_id", "default")
+ await _track_proxy_usage(
+ node_id, provider_name, bytes_transferred,
+ workflow_id=workflow_id, session_id=session_id,
+ )
+
+ # Parse response
+ try:
+ response_data = response.json()
+ except Exception:
+ response_data = response.text
+
+ return {
+ "success": response.status_code < 400,
+ "node_id": node_id,
+ "node_type": "proxyRequest",
+ "result": {
+ "status": response.status_code,
+ "data": response_data,
+ "headers": dict(response.headers),
+ "url": str(response.url),
+ "method": method,
+ "proxy_provider": provider_name,
+ "latency_ms": round(latency_ms, 1),
+ "bytes_transferred": bytes_transferred,
+ "attempt": attempt + 1,
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ except Exception as e:
+ latency_ms = (time.monotonic() - req_start) * 1000
+ last_error = str(e)
+
+ # Report failure
+ proxy_svc.report_result(provider_name, ProxyResult(
+ success=False,
+ latency_ms=latency_ms,
+ error=last_error,
+ ))
+
+ logger.warning("Proxy request attempt failed",
+ node_id=node_id, attempt=attempt + 1,
+ max_retries=max_retries, error=last_error)
+
+ if not failover or attempt >= max_retries:
+ break
+
+ # Try a different proxy URL for failover
+ try:
+ proxy_url = await proxy_svc.get_proxy_url(url, parameters)
+ except Exception:
+ break
+
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "proxyRequest",
+ "error": f"All {max_retries + 1} attempts failed. Last error: {last_error}",
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ except Exception as e:
+ logger.error("Proxy request failed", node_id=node_id, error=str(e))
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "proxyRequest",
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+
+async def handle_proxy_status(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Handle proxyStatus node execution.
+
+ Returns provider health stats for dashboard display.
+ """
+ start_time = time.time()
+
+ try:
+ proxy_svc = get_proxy_service()
+ if not proxy_svc or not proxy_svc.is_enabled():
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "proxyStatus",
+ "result": {
+ "enabled": False,
+ "providers": [],
+ "stats": {},
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ stats = proxy_svc.get_stats()
+ providers = [p.model_dump() for p in proxy_svc.get_providers()]
+
+ return {
+ "success": True,
+ "node_id": node_id,
+ "node_type": "proxyStatus",
+ "result": {
+ "enabled": True,
+ "providers": providers,
+ "stats": stats,
+ },
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+ except Exception as e:
+ logger.error("Proxy status check failed", node_id=node_id, error=str(e))
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "proxyStatus",
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+
+
+async def handle_proxy_config(
+ node_id: str,
+ node_type: str,
+ parameters: Dict[str, Any],
+ context: Dict[str, Any],
+) -> Dict[str, Any]:
+ """Handle proxyConfig node execution (standalone workflow mode).
+
+ Routes to the tool handler for operation-based dispatch.
+ """
+ from services.handlers.tools import _execute_proxy_config
+
+ start_time = time.time()
+ try:
+ result = await _execute_proxy_config(parameters, parameters)
+ return {
+ "success": result.get("success", False),
+ "node_id": node_id,
+ "node_type": "proxyConfig",
+ "result": result,
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
+ except Exception as e:
+ logger.error("Proxy config failed", node_id=node_id, error=str(e))
+ return {
+ "success": False,
+ "node_id": node_id,
+ "node_type": "proxyConfig",
+ "error": str(e),
+ "execution_time": time.time() - start_time,
+ "timestamp": datetime.now().isoformat(),
+ }
diff --git a/server/services/proxy/__init__.py b/server/services/proxy/__init__.py
new file mode 100644
index 00000000..4297c048
--- /dev/null
+++ b/server/services/proxy/__init__.py
@@ -0,0 +1,9 @@
+"""ProxyForge - Universal proxy management service for MachinaOs.
+
+Routes HTTP requests through residential proxy providers with smart rotation,
+scoring, geo-targeting, sticky sessions, failover, and cost tracking.
+"""
+
+from services.proxy.service import ProxyService, get_proxy_service
+
+__all__ = ["ProxyService", "get_proxy_service"]
diff --git a/server/services/proxy/exceptions.py b/server/services/proxy/exceptions.py
new file mode 100644
index 00000000..dec9e5d7
--- /dev/null
+++ b/server/services/proxy/exceptions.py
@@ -0,0 +1,30 @@
+"""Proxy service exception hierarchy."""
+
+
+class ProxyError(Exception):
+ """Base exception for all proxy-related errors."""
+
+
+class ProviderError(ProxyError):
+ """Error from a specific proxy provider."""
+
+ def __init__(self, provider_name: str, message: str):
+ self.provider_name = provider_name
+ super().__init__(f"[{provider_name}] {message}")
+
+
+class NoHealthyProviderError(ProxyError):
+ """No healthy proxy providers available."""
+
+
+class BudgetExceededError(ProxyError):
+ """Daily proxy budget has been exceeded."""
+
+ def __init__(self, budget_usd: float, spent_usd: float):
+ self.budget_usd = budget_usd
+ self.spent_usd = spent_usd
+ super().__init__(f"Daily budget ${budget_usd:.2f} exceeded (spent ${spent_usd:.2f})")
+
+
+class ProxyConfigError(ProxyError):
+ """Invalid proxy configuration."""
diff --git a/server/services/proxy/models.py b/server/services/proxy/models.py
new file mode 100644
index 00000000..476fb9bf
--- /dev/null
+++ b/server/services/proxy/models.py
@@ -0,0 +1,68 @@
+"""Pydantic v2 domain models for the proxy service."""
+
+from enum import Enum
+from typing import Dict, List, Optional
+from pydantic import BaseModel, Field
+
+
+class SessionType(str, Enum):
+ """Proxy session type controlling IP rotation behavior."""
+ ROTATING = "rotating" # New IP per request (default)
+ STICKY = "sticky" # Same IP for duration
+
+
+class GeoTarget(BaseModel):
+ """Geographic targeting for proxy requests."""
+ country: Optional[str] = Field(default=None, description="ISO 3166-1 alpha-2 country code")
+ city: Optional[str] = Field(default=None, description="City name")
+ state: Optional[str] = Field(default=None, description="State/region name")
+
+
+class ProviderConfig(BaseModel):
+ """Configuration for a proxy provider loaded from database."""
+ name: str
+ enabled: bool = True
+ priority: int = 50 # Lower = preferred
+ weight: float = 1.0 # For weighted random selection
+ cost_per_gb: float = 0.0 # USD per GB
+ gateway_host: str = ""
+ gateway_port: int = 0
+ geo_coverage: List[str] = Field(default_factory=list) # ISO country codes
+ sticky_support: bool = True
+ max_sticky_seconds: int = 600
+ max_concurrent: int = 100
+ url_template: Dict = Field(default_factory=dict) # JSON template config
+
+
+class ProviderStats(BaseModel):
+ """Runtime health statistics for a proxy provider."""
+ name: str
+ score: float = 1.0 # 0.0 - 1.0 composite score
+ success_rate: float = 1.0 # 0.0 - 1.0
+ avg_latency_ms: float = 0.0
+ total_requests: int = 0
+ total_bytes: int = 0
+ healthy: bool = True
+
+
+class RoutingRule(BaseModel):
+ """Domain-based routing rule for proxy selection."""
+ id: Optional[int] = None
+ domain_pattern: str # fnmatch glob: "*.linkedin.com", "*"
+ preferred_providers: List[str] = Field(default_factory=list)
+ required_country: Optional[str] = None
+ session_type: SessionType = SessionType.ROTATING
+ sticky_duration_seconds: int = 300
+ max_retries: int = 3
+ failover: bool = True
+ min_success_rate: float = 0.7
+ priority: int = 0 # Lower = evaluated first
+
+
+class ProxyResult(BaseModel):
+ """Result of a proxied HTTP request, reported back for scoring."""
+ success: bool
+ latency_ms: float = 0.0
+ bytes_transferred: int = 0
+ status_code: Optional[int] = None
+ error: Optional[str] = None
diff --git a/server/services/proxy/providers.py b/server/services/proxy/providers.py
new file mode 100644
index 00000000..05901e14
--- /dev/null
+++ b/server/services/proxy/providers.py
@@ -0,0 +1,129 @@
+"""Template-driven proxy provider.
+
+Single class that formats proxy URLs from a JSON url_template config.
+Supports any residential proxy provider without code changes.
+The LLM generates url_template configs via python_code tool.
+"""
+
+import uuid
+from typing import Any, Dict, Optional
+
+from services.proxy.models import GeoTarget, SessionType
+
+
+class TemplateProxyProvider:
+ """Universal proxy provider that formats URLs from a JSON template.
+
+ Supports 3 encoding strategies via the ``param_field`` template key:
+ - ``"username"`` - params appended to username (most providers)
+ - ``"password"`` - params appended to password (IPRoyal, Rayobyte)
+ - ``"none"`` - no encoding, plain credentials (generic/custom)
+
+ Template schema (stored as JSON in DB ``url_template`` column)::
+
+ {
+ "param_field": "username",
+ "username_prefix": "{username}",
+ "username_param_separator": "-",
+ "param_separator": "-",
+ "param_keys": {
+ "country": "country-{v}",
+ "state": "state-{v}",
+ "city": "city-{v}",
+ "session_id": "session-{v}",
+ "session_duration": "sessionduration-{v}"
+ },
+ "country_case": "lower",
+ "city_separator": "_"
+ }
+ """
+
+ def __init__(self, name: str, template: Dict[str, Any]):
+ self.name = name
+ self._tpl = template
+
+ def format_proxy_url(
+ self,
+ username: str,
+ password: str,
+ host: str,
+ port: int,
+ geo: Optional[GeoTarget] = None,
+ session_type: SessionType = SessionType.ROTATING,
+ session_id: Optional[str] = None,
+ sticky_duration_minutes: Optional[int] = None,
+ ) -> str:
+ """Format a complete proxy URL using the template config.
+
+ Args:
+ username: Base username from credentials
+ password: Password from credentials
+ host: Gateway host
+ port: Gateway port
+ geo: Geographic targeting (country, city, state)
+ session_type: Rotating or sticky session
+ session_id: Sticky session identifier (auto-generated if None)
+ sticky_duration_minutes: Sticky session duration in minutes
+
+ Returns:
+ Complete proxy URL: http://encoded-user:pass@host:port
+ """
+ tpl = self._tpl
+ param_field = tpl.get("param_field", "username")
+ keys = tpl.get("param_keys", {})
+ country_case = tpl.get("country_case", "lower")
+ city_sep = tpl.get("city_separator", "_")
+
+ # Build param fragments
+ params: list[str] = []
+
+ if geo and geo.country and "country" in keys:
+ cc = _apply_case(geo.country, country_case)
+ params.append(keys["country"].replace("{v}", cc))
+
+ if geo and geo.state and "state" in keys:
+ state = geo.state.lower().replace(" ", city_sep)
+ params.append(keys["state"].replace("{v}", state))
+
+ if geo and geo.city and "city" in keys:
+ city = geo.city.lower().replace(" ", city_sep)
+ params.append(keys["city"].replace("{v}", city))
+
+ if session_type == SessionType.STICKY and "session_id" in keys:
+ sid = session_id or uuid.uuid4().hex[:12]
+ params.append(keys["session_id"].replace("{v}", sid))
+
+ if sticky_duration_minutes and "session_duration" in keys:
+ params.append(keys["session_duration"].replace("{v}", str(sticky_duration_minutes)))
+
+ param_str = tpl.get("param_separator", "-").join(params) if params else ""
+
+ # Format username from prefix template
+ prefix = tpl.get("username_prefix", "{username}").replace("{username}", username)
+
+ if param_field == "username" and param_str:
+ sep = tpl.get("username_param_separator", "-")
+ final_user = f"{prefix}{sep}{param_str}"
+ final_pass = password
+ elif param_field == "password" and param_str:
+ final_user = prefix
+ final_pass = f"{password}{param_str}"
+ else:
+ final_user = prefix
+ final_pass = password
+
+ if not host or not port:
+ raise ValueError(f"Provider '{self.name}' requires host and port")
+
+ if final_user and final_pass:
+ return f"http://{final_user}:{final_pass}@{host}:{port}"
+ return f"http://{host}:{port}"
+
+
+def _apply_case(value: str, case: str) -> str:
+ """Apply case transformation to a string value."""
+ if case == "lower":
+ return value.lower()
+ if case == "upper":
+ return value.upper()
+ return value
diff --git a/server/services/proxy/service.py b/server/services/proxy/service.py
new file mode 100644
index 00000000..038fc881
--- /dev/null
+++ b/server/services/proxy/service.py
@@ -0,0 +1,487 @@
+"""ProxyService facade - singleton service for proxy management.
+
+Routes HTTP requests through residential proxy providers with smart rotation,
+scoring, geo-targeting, sticky sessions, failover, and cost tracking.
+Follows the CompactionService singleton pattern.
+"""
+
+import json
+import time
+from collections import deque
+from fnmatch import fnmatch
+from typing import Any, Deque, Dict, List, Optional
+from urllib.parse import urlparse
+
+import httpx
+
+from core.logging import get_logger
+from services.proxy.exceptions import (
+ BudgetExceededError,
+ NoHealthyProviderError,
+ ProxyConfigError,
+ ProviderError,
+)
+from services.proxy.models import (
+ GeoTarget,
+ ProviderConfig,
+ ProviderStats,
+ ProxyResult,
+ RoutingRule,
+ SessionType,
+)
+from services.proxy.providers import TemplateProxyProvider
+
+logger = get_logger(__name__)
+
+# Scoring weights
+_WEIGHT_SUCCESS = 0.4
+_WEIGHT_LATENCY = 0.2
+_WEIGHT_COST = 0.3
+_WEIGHT_FRESHNESS = 0.1
+
+# Max results to keep for scoring per provider
+_MAX_HISTORY = 100
+
+
+class _ProviderRuntime:
+ """In-memory runtime state for a single provider."""
+
+ def __init__(self, config: ProviderConfig, provider: TemplateProxyProvider):
+ self.config = config
+ self.provider = provider
+ self.username: str = ""
+ self.password: str = ""
+ self.history: Deque[ProxyResult] = deque(maxlen=_MAX_HISTORY)
+ self.total_bytes: int = 0
+ self.total_requests: int = 0
+
+ @property
+ def has_credentials(self) -> bool:
+ return bool(self.username and self.password)
+
+ def compute_score(self) -> float:
+ """Compute composite health score (0.0 - 1.0)."""
+ if not self.history:
+ return 1.0 # No data = assume healthy
+
+ results = list(self.history)
+
+ # Success rate (0-1)
+ successes = sum(1 for r in results if r.success)
+ success_rate = successes / len(results)
+
+ # Latency score (0-1, lower latency = higher score)
+ latencies = [r.latency_ms for r in results if r.latency_ms > 0]
+ if latencies:
+ avg_latency = sum(latencies) / len(latencies)
+ latency_score = max(0.0, 1.0 - (avg_latency / 10000)) # 10s = 0 score
+ else:
+ latency_score = 1.0
+
+ # Cost score (0-1, lower cost = higher score)
+ cost = self.config.cost_per_gb
+ cost_score = max(0.0, 1.0 - (cost / 10.0)) # $10/GB = 0 score
+
+ # Freshness score (0-1, more recent data = higher score)
+ freshness_score = min(1.0, len(results) / 10)
+
+ score = (
+ _WEIGHT_SUCCESS * success_rate +
+ _WEIGHT_LATENCY * latency_score +
+ _WEIGHT_COST * cost_score +
+ _WEIGHT_FRESHNESS * freshness_score
+ )
+ return round(max(0.0, min(1.0, score)), 4)
+
+ def success_rate(self) -> float:
+ if not self.history:
+ return 1.0
+ return sum(1 for r in self.history if r.success) / len(self.history)
+
+ def avg_latency_ms(self) -> float:
+ latencies = [r.latency_ms for r in self.history if r.latency_ms > 0]
+ if not latencies:
+ return 0.0
+ return sum(latencies) / len(latencies)
+
+ def is_healthy(self, min_success_rate: float = 0.3) -> bool:
+ if not self.history:
+ return True
+ return self.success_rate() >= min_success_rate
+
+ def to_stats(self) -> ProviderStats:
+ return ProviderStats(
+ name=self.config.name,
+ score=self.compute_score(),
+ success_rate=self.success_rate(),
+ avg_latency_ms=self.avg_latency_ms(),
+ total_requests=self.total_requests,
+ total_bytes=self.total_bytes,
+ healthy=self.is_healthy(),
+ )
+
+
+class ProxyService:
+ """Singleton proxy management service.
+
+ Loads provider configs from DB, reads credentials from AuthService,
+ scores providers by health, matches domains to routing rules, and
+ formats proxy URLs for httpx.
+ """
+
+ def __init__(self, auth_service, database, settings):
+ self._auth_service = auth_service
+ self._database = database
+ self._settings = settings
+ self._providers: Dict[str, _ProviderRuntime] = {}
+ self._routing_rules: List[RoutingRule] = []
+ self._daily_spend_usd: float = 0.0
+ self._initialized = False
+
+ async def startup(self) -> None:
+ """Load provider configs from DB and credentials from AuthService."""
+ if not self._settings.proxy_enabled:
+ logger.info("Proxy service disabled (PROXY_ENABLED=false)")
+ return
+
+ try:
+ # Load provider configs from database
+ db_providers = await self._database.get_proxy_providers()
+ await self._load_providers(db_providers)
+
+ # Load routing rules from database
+ await self._reload_routing_rules()
+
+ self._initialized = True
+ provider_names = [p.config.name for p in self._providers.values() if p.config.enabled]
+ logger.info("Proxy service started",
+ providers=provider_names,
+ rules=len(self._routing_rules))
+
+ except Exception as e:
+ logger.error("Failed to start proxy service", error=str(e))
+ self._initialized = True # Mark as initialized to avoid retry loops
+
+ async def shutdown(self) -> None:
+ """Clean up resources."""
+ self._providers.clear()
+ self._routing_rules.clear()
+ self._initialized = False
+ logger.info("Proxy service stopped")
+
+ def is_enabled(self) -> bool:
+ return self._settings.proxy_enabled and self._initialized
+
+ async def get_proxy_url(
+ self,
+ url: str,
+ parameters: Dict[str, Any],
+ ) -> Optional[str]:
+ """Get a proxy URL for the given target URL and node parameters.
+
+ This is the main entry point. Returns None if proxy is not applicable.
+
+ Args:
+ url: Target URL to be proxied
+ parameters: Node parameters (may contain proxyProvider, proxyCountry, etc.)
+
+ Returns:
+ Proxy URL string for httpx, or None if no proxy should be used
+ """
+ if not self.is_enabled():
+ return None
+
+ # Check daily budget
+ budget = self._settings.proxy_budget_daily_usd
+ if budget is not None and self._daily_spend_usd >= budget:
+ raise BudgetExceededError(budget, self._daily_spend_usd)
+
+ # Extract target domain
+ try:
+ parsed = urlparse(url)
+ domain = parsed.hostname or ""
+ except Exception:
+ domain = ""
+
+ # Match routing rule
+ rule = self._match_routing_rule(domain)
+
+ # Determine provider
+ explicit_provider = parameters.get("proxyProvider")
+ if explicit_provider and explicit_provider in self._providers:
+ runtime = self._providers[explicit_provider]
+ elif rule and rule.preferred_providers:
+ runtime = self._pick_from_preferred(rule.preferred_providers, rule.min_success_rate)
+ else:
+ runtime = self._pick_best_provider()
+
+ if runtime is None:
+ raise NoHealthyProviderError("No healthy proxy providers available")
+
+ if not runtime.has_credentials:
+ raise ProviderError(runtime.config.name, "No credentials configured")
+
+ if not runtime.config.enabled:
+ raise ProviderError(runtime.config.name, "Provider is disabled")
+
+ # Build geo target
+ geo = GeoTarget(
+ country=parameters.get("proxyCountry") or
+ (rule.required_country if rule else None) or
+ self._settings.proxy_default_country,
+ city=parameters.get("proxyCity"),
+ state=parameters.get("proxyState"),
+ )
+
+ # Determine session type
+ session_type_str = parameters.get("proxySessionType", "rotating")
+ session_type = SessionType(session_type_str) if session_type_str else SessionType.ROTATING
+ if rule:
+ session_type = rule.session_type
+
+ session_id = parameters.get("proxySessionId")
+
+ # Format proxy URL
+ proxy_url = runtime.provider.format_proxy_url(
+ username=runtime.username,
+ password=runtime.password,
+ host=runtime.config.gateway_host,
+ port=runtime.config.gateway_port,
+ geo=geo if (geo.country or geo.city or geo.state) else None,
+ session_type=session_type,
+ session_id=session_id,
+ )
+
+ logger.debug("Proxy URL generated",
+ provider=runtime.config.name,
+ domain=domain,
+ country=geo.country)
+
+ return proxy_url
+
+ def report_result(self, provider_name: str, result: ProxyResult) -> None:
+ """Report the result of a proxied request for health scoring.
+
+ Args:
+ provider_name: Name of the provider used
+ result: Result of the request
+ """
+ runtime = self._providers.get(provider_name)
+ if runtime is None:
+ return
+
+ runtime.history.append(result)
+ runtime.total_requests += 1
+ runtime.total_bytes += result.bytes_transferred
+
+ # Track daily spend
+ if result.bytes_transferred > 0 and runtime.config.cost_per_gb > 0:
+ gb = result.bytes_transferred / (1024 ** 3)
+ self._daily_spend_usd += gb * runtime.config.cost_per_gb
+
+ def get_providers(self) -> List[ProviderStats]:
+ """Get health stats for all configured providers."""
+ return [rt.to_stats() for rt in self._providers.values()]
+
+ def get_routing_rules(self) -> List[RoutingRule]:
+ """Get all routing rules sorted by priority."""
+ return list(self._routing_rules)
+
+ async def save_routing_rule(self, rule_data: Dict[str, Any]) -> bool:
+ """Save a routing rule to database and refresh in-memory list."""
+ success = await self._database.save_proxy_routing_rule(rule_data)
+ if success:
+ await self._reload_routing_rules()
+ return success
+
+ async def delete_routing_rule(self, rule_id: int) -> bool:
+ """Delete a routing rule and refresh in-memory list."""
+ success = await self._database.delete_proxy_routing_rule(rule_id)
+ if success:
+ await self._reload_routing_rules()
+ return success
+
+ async def test_provider(self, provider_name: str) -> Dict[str, Any]:
+ """Health check a provider by making a request through it.
+
+ Returns dict with success, ip, latency_ms, error.
+ """
+ runtime = self._providers.get(provider_name)
+ if runtime is None:
+ return {"success": False, "error": f"Provider '{provider_name}' not found"}
+
+ if not runtime.has_credentials:
+ return {"success": False, "error": "No credentials configured"}
+
+ try:
+ proxy_url = runtime.provider.format_proxy_url(
+ username=runtime.username,
+ password=runtime.password,
+ host=runtime.config.gateway_host,
+ port=runtime.config.gateway_port,
+ )
+
+ start = time.monotonic()
+ async with httpx.AsyncClient(proxy=proxy_url, timeout=15.0) as client:
+ resp = await client.get("https://httpbin.org/ip")
+ latency_ms = (time.monotonic() - start) * 1000
+
+ data = resp.json()
+ result = ProxyResult(success=True, latency_ms=latency_ms, status_code=resp.status_code)
+ self.report_result(provider_name, result)
+
+ return {
+ "success": True,
+ "ip": data.get("origin", "unknown"),
+ "latency_ms": round(latency_ms, 1),
+ "status_code": resp.status_code,
+ }
+
+ except Exception as e:
+ result = ProxyResult(success=False, error=str(e))
+ self.report_result(provider_name, result)
+ return {"success": False, "error": str(e)}
+
+ def get_stats(self) -> Dict[str, Any]:
+ """Get aggregated proxy usage statistics."""
+ return {
+ "enabled": self.is_enabled(),
+ "provider_count": len(self._providers),
+ "active_providers": sum(1 for p in self._providers.values() if p.config.enabled and p.has_credentials),
+ "routing_rules": len(self._routing_rules),
+ "daily_spend_usd": round(self._daily_spend_usd, 4),
+ "daily_budget_usd": self._settings.proxy_budget_daily_usd,
+ "total_requests": sum(p.total_requests for p in self._providers.values()),
+ "total_bytes": sum(p.total_bytes for p in self._providers.values()),
+ "providers": {
+ name: rt.to_stats().model_dump()
+ for name, rt in self._providers.items()
+ },
+ }
+
+ def reset_daily_spend(self) -> None:
+ """Reset daily spend counter (called by scheduler at midnight)."""
+ self._daily_spend_usd = 0.0
+
+ async def reload_providers(self) -> None:
+ """Reload provider configs from database (called after tool/UI changes)."""
+ db_providers = await self._database.get_proxy_providers()
+ await self._load_providers(db_providers)
+ logger.info("Proxy providers reloaded",
+ count=len(self._providers))
+
+ async def _load_providers(self, db_providers: list) -> None:
+ """Build _ProviderRuntime instances from database rows."""
+ self._providers.clear()
+ for row in db_providers:
+ template = json.loads(row.get("url_template", "{}"))
+ provider = TemplateProxyProvider(name=row["name"], template=template)
+
+ config = ProviderConfig(
+ name=row["name"],
+ enabled=row.get("enabled", True),
+ priority=row.get("priority", 50),
+ weight=row.get("weight", 1.0),
+ cost_per_gb=row.get("cost_per_gb", 0.0),
+ gateway_host=row.get("gateway_host", ""),
+ gateway_port=row.get("gateway_port", 0),
+ geo_coverage=json.loads(row.get("geo_coverage", "[]")),
+ sticky_support=row.get("sticky_support", True),
+ max_sticky_seconds=row.get("max_sticky_seconds", 600),
+ max_concurrent=row.get("max_concurrent", 100),
+ url_template=template,
+ )
+
+ runtime = _ProviderRuntime(config, provider)
+
+ # Load credentials from AuthService
+ cred_key = f"proxy_{config.name}"
+ username = await self._auth_service.get_api_key(f"{cred_key}_username")
+ password = await self._auth_service.get_api_key(f"{cred_key}_password")
+ if username and password:
+ runtime.username = username
+ runtime.password = password
+ else:
+ logger.warning("No credentials for proxy provider",
+ name=config.name)
+
+ self._providers[config.name] = runtime
+
+ # ---- Internal helpers ----
+
+ def _match_routing_rule(self, domain: str) -> Optional[RoutingRule]:
+ """Find the first matching routing rule for a domain."""
+ for rule in self._routing_rules:
+ if fnmatch(domain, rule.domain_pattern):
+ return rule
+ return None
+
+ def _pick_from_preferred(
+ self,
+ preferred: List[str],
+ min_success_rate: float = 0.3,
+ ) -> Optional[_ProviderRuntime]:
+ """Pick the best provider from a preferred list."""
+ candidates = []
+ for name in preferred:
+ rt = self._providers.get(name)
+ if rt and rt.config.enabled and rt.has_credentials and rt.is_healthy(min_success_rate):
+ candidates.append(rt)
+
+ if not candidates:
+ # Fallback to any healthy provider
+ return self._pick_best_provider()
+
+ # Sort by score descending
+ candidates.sort(key=lambda r: r.compute_score(), reverse=True)
+ return candidates[0]
+
+ def _pick_best_provider(self) -> Optional[_ProviderRuntime]:
+ """Pick the best healthy provider by composite score."""
+ candidates = [
+ rt for rt in self._providers.values()
+ if rt.config.enabled and rt.has_credentials and rt.is_healthy()
+ ]
+
+ if not candidates:
+ return None
+
+ # Sort by score descending, then priority ascending (lower = better)
+ candidates.sort(key=lambda r: (-r.compute_score(), r.config.priority))
+ return candidates[0]
+
+ async def _reload_routing_rules(self) -> None:
+ """Reload routing rules from database."""
+ db_rules = await self._database.get_proxy_routing_rules()
+ self._routing_rules = []
+ for row in db_rules:
+ self._routing_rules.append(RoutingRule(
+ id=row.get("id"),
+ domain_pattern=row["domain_pattern"],
+ preferred_providers=json.loads(row.get("preferred_providers", "[]")),
+ required_country=row.get("required_country"),
+ session_type=SessionType(row.get("session_type", "rotating")),
+ sticky_duration_seconds=row.get("sticky_duration_seconds", 300),
+ max_retries=row.get("max_retries", 3),
+ failover=row.get("failover", True),
+ min_success_rate=row.get("min_success_rate", 0.7),
+ priority=row.get("priority", 0),
+ ))
+ self._routing_rules.sort(key=lambda r: r.priority)
+
+
+# ---- Singleton accessor (CompactionService pattern) ----
+
+_proxy_service: Optional[ProxyService] = None
+
+
+def init_proxy_service(auth_service, database, settings) -> ProxyService:
+ """Create the singleton ProxyService instance."""
+ global _proxy_service
+ _proxy_service = ProxyService(auth_service, database, settings)
+ return _proxy_service
+
+
+def get_proxy_service() -> Optional[ProxyService]:
+ """Get the singleton ProxyService instance, or None if not initialized."""
+ return _proxy_service
diff --git a/server/skills/web_agent/proxy-config-skill/SKILL.md b/server/skills/web_agent/proxy-config-skill/SKILL.md
new file mode 100644
index 00000000..2e9d74c1
--- /dev/null
+++ b/server/skills/web_agent/proxy-config-skill/SKILL.md
@@ -0,0 +1,400 @@
+---
+name: proxy-config-skill
+description: Configure any residential proxy provider using template-driven URL encoding. Generate url_template JSON from provider docs, save providers, set credentials, manage routing rules.
+allowed-tools: proxy_config python_code
+metadata:
+ author: machina
+ version: "1.0"
+ category: integration
+ icon: "πŸ›‘"
+ color: "#8B5CF6"
+---
+
+# Proxy Config Skill
+
+Configure any residential proxy provider in the world using the template-driven proxy system. No provider-specific code exists -- you generate a `url_template` JSON config that tells the system how to format proxy URLs for that provider.
+
+## How It Works
+
+1. User tells you which proxy provider they want to configure
+2. You use `python_code` to generate and validate the `url_template` JSON
+3. You use `proxy_config` to save the provider, set credentials, and optionally add routing rules
+4. You use `proxy_config(test_provider)` to verify the setup works
+
+## Tools
+
+- **proxy_config** -- Manage providers, credentials, and routing rules
+- **python_code** -- Generate and validate url_template JSON configs
+
+---
+
+## url_template JSON Schema
+
+The `url_template` is a JSON object that tells the proxy system how to encode geo-targeting, session, and other parameters into the proxy URL. Every residential proxy provider uses one of three encoding strategies.
+
+### Encoding Strategies (param_field)
+
+| Strategy | param_field | How it works | Providers using this |
+|----------|-------------|--------------|---------------------|
+| Username encoding | `"username"` | Parameters appended to username string | ~80% of providers |
+| Password encoding | `"password"` | Parameters appended to password string | A few providers |
+| No encoding | `"none"` | Plain credentials, no parameter encoding | Generic/custom setups |
+
+### Template Fields
+
+| Field | Type | Default | Description |
+|-------|------|---------|-------------|
+| `param_field` | string | `"username"` | Where to encode params: `"username"`, `"password"`, or `"none"` |
+| `username_prefix` | string | `"{username}"` | Template for the username base. `{username}` is replaced with the actual username |
+| `username_param_separator` | string | `"-"` | Separator between username prefix and first parameter |
+| `param_separator` | string | `"-"` | Separator between individual parameters |
+| `param_keys` | object | `{}` | Map of parameter names to format strings. `{v}` is replaced with the value |
+| `country_case` | string | `"lower"` | Case for country codes: `"lower"` or `"upper"` |
+| `city_separator` | string | `"_"` | Character replacing spaces in city/state names |
+
+### param_keys Reference
+
+| Key | Purpose | Example format string |
+|-----|---------|----------------------|
+| `country` | ISO country code | `"country-{v}"`, `"_country-{v}"`, `"cc-{v}"` |
+| `state` | State/region | `"state-{v}"`, `"_state-{v}"` |
+| `city` | City name | `"city-{v}"`, `"_city-{v}"` |
+| `session_id` | Sticky session ID | `"session-{v}"`, `"sessid-{v}"` |
+| `session_duration` | Session duration | `"sessTime-{v}"`, `"_lifetime-{v}"` |
+
+### How URL Formatting Works
+
+Given credentials `user123` / `pass456`, host `gate.example.com:7777`, country `US`:
+
+**Username encoding** (`param_field: "username"`):
+```
+http://user123-country-us:[email protected]:7777
+ ^^^^^^^^^^^^^^^^^^^^^^^
+ prefix + separator + params
+```
+
+**Password encoding** (`param_field: "password"`):
+```
+http://user123:[email protected]:7777
+ ^^^^^^^^^^^^^^^^^^^^^
+ password + params (no separator usually)
+```
+
+**No encoding** (`param_field: "none"`):
+```
+http://user123:[email protected]:7777
+```
+
+---
+
+## Workflow: Configure a New Provider
+
+### Step 1: Generate url_template with python_code
+
+Read the provider's documentation to identify:
+1. What the proxy gateway host and port are
+2. How parameters are encoded (username-based or password-based)
+3. What separator characters are used
+4. What the parameter format strings look like
+
+Then use `python_code` to generate and validate the template:
+
+```python
+import json
+
+# Build the url_template based on provider docs
+template = {
+ "param_field": "username",
+ "username_prefix": "{username}",
+ "username_param_separator": "-",
+ "param_separator": "-",
+ "param_keys": {
+ "country": "country-{v}",
+ "city": "city-{v}",
+ "session_id": "session-{v}",
+ "session_duration": "sessTime-{v}"
+ },
+ "country_case": "lower",
+ "city_separator": "_"
+}
+
+# Validate: simulate what the proxy system does
+username = "testuser"
+password = "testpass"
+country = "us"
+city = "new_york"
+session_id = "abc123"
+
+params = []
+if "country" in template["param_keys"]:
+ cc = country.lower() if template.get("country_case") == "lower" else country.upper()
+ params.append(template["param_keys"]["country"].replace("{v}", cc))
+if "city" in template["param_keys"]:
+ c = city.lower().replace(" ", template.get("city_separator", "_"))
+ params.append(template["param_keys"]["city"].replace("{v}", c))
+if "session_id" in template["param_keys"]:
+ params.append(template["param_keys"]["session_id"].replace("{v}", session_id))
+
+param_str = template.get("param_separator", "-").join(params)
+prefix = template.get("username_prefix", "{username}").replace("{username}", username)
+
+if template["param_field"] == "username" and param_str:
+ sep = template.get("username_param_separator", "-")
+ final_user = f"{prefix}{sep}{param_str}"
+ final_pass = password
+elif template["param_field"] == "password" and param_str:
+ final_user = prefix
+ final_pass = f"{password}{param_str}"
+else:
+ final_user = prefix
+ final_pass = password
+
+url = f"http://{final_user}:{final_pass}@gate.example.com:7777"
+print(f"Generated URL: {url}")
+
+# Assert the URL matches expected format from provider docs
+assert "country-us" in url, "Country encoding failed"
+assert "city-new_york" in url, "City encoding failed"
+assert "session-abc123" in url, "Session encoding failed"
+
+# Output the validated template
+result = json.dumps(template, indent=2)
+print(f"\nValidated template:\n{result}")
+output = result
+```
+
+### Step 2: Save the provider with proxy_config
+
+```json
+{
+ "operation": "add_provider",
+ "name": "my_provider",
+ "gateway_host": "gate.example.com",
+ "gateway_port": 7777,
+ "url_template": "{...the JSON template from step 1...}",
+ "cost_per_gb": 2.50,
+ "enabled": true,
+ "priority": 50
+}
+```
+
+### Step 3: Set credentials
+
+```json
+{
+ "operation": "set_credentials",
+ "name": "my_provider",
+ "username": "actual_username",
+ "password": "actual_password"
+}
+```
+
+### Step 4: Test the provider
+
+```json
+{
+ "operation": "test_provider",
+ "name": "my_provider"
+}
+```
+
+Expected response:
+```json
+{
+ "success": true,
+ "ip": "203.0.113.42",
+ "latency_ms": 1250.3,
+ "status_code": 200
+}
+```
+
+### Step 5 (Optional): Add routing rules
+
+Route specific domains through specific providers:
+
+```json
+{
+ "operation": "add_routing_rule",
+ "domain_pattern": "*.linkedin.com",
+ "preferred_providers": "[\"my_provider\"]",
+ "required_country": "US",
+ "session_type": "sticky"
+}
+```
+
+---
+
+## proxy_config Tool Reference
+
+### Operations
+
+| Operation | Description | Required Fields |
+|-----------|-------------|-----------------|
+| `list_providers` | List all configured providers | (none) |
+| `add_provider` | Add a new provider | name, gateway_host, gateway_port, url_template |
+| `update_provider` | Update provider settings | name, + fields to change |
+| `remove_provider` | Remove a provider | name |
+| `set_credentials` | Set provider username/password | name, username, password |
+| `test_provider` | Health check via httpbin.org/ip | name |
+| `get_stats` | Get usage statistics | (none) |
+| `add_routing_rule` | Add domain routing rule | domain_pattern |
+| `list_routing_rules` | List all routing rules | (none) |
+| `remove_routing_rule` | Remove a routing rule | rule_id |
+
+### add_provider Fields
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| operation | string | Yes | `"add_provider"` |
+| name | string | Yes | Unique provider name (e.g., `"smartproxy"`, `"brightdata"`) |
+| gateway_host | string | Yes | Gateway hostname |
+| gateway_port | integer | Yes | Gateway port |
+| url_template | string | Yes | JSON string of template config |
+| enabled | boolean | No | Active status (default: true) |
+| priority | integer | No | Lower = preferred (default: 50) |
+| cost_per_gb | float | No | USD per GB (default: 0) |
+| geo_coverage | string | No | JSON array of ISO country codes |
+
+### set_credentials Fields
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| operation | string | Yes | `"set_credentials"` |
+| name | string | Yes | Provider name |
+| username | string | Yes | Proxy username from provider dashboard |
+| password | string | Yes | Proxy password from provider dashboard |
+
+### add_routing_rule Fields
+
+| Field | Type | Required | Description |
+|-------|------|----------|-------------|
+| operation | string | Yes | `"add_routing_rule"` |
+| domain_pattern | string | Yes | Glob pattern: `"*.example.com"`, `"*"` (catch-all) |
+| preferred_providers | string | No | JSON array of provider names |
+| required_country | string | No | ISO country code |
+| session_type | string | No | `"rotating"` or `"sticky"` (default: rotating) |
+
+---
+
+## Reading Provider Documentation
+
+When the user gives you a provider name or documentation URL, look for these patterns:
+
+### What to Extract
+
+1. **Gateway endpoint**: Usually formatted as `host:port` (e.g., `gate.smartproxy.com:7777`)
+2. **Username format**: How parameters are appended (e.g., `user-country-us-session-abc123`)
+3. **Separator characters**: Dash `-`, underscore `_`, dot `.`, or custom
+4. **Parameter names**: What the provider calls country, city, session, etc.
+5. **Country code format**: Lowercase `us` vs uppercase `US`
+
+### Common Patterns to Recognize
+
+**Pattern A: Dash-separated username params (most common)**
+```
+username: user-country-us-city-new_york-session-abc123
+password: pass
+```
+Template: `param_field: "username"`, separators: `"-"`
+
+**Pattern B: Underscore prefix params**
+```
+username: user_country-us_city-new_york_session-abc123
+password: pass
+```
+Template: `username_param_separator: "_"`, keys use `"_country-{v}"`
+
+**Pattern C: Password-based encoding**
+```
+username: user
+password: pass_country-us_session-abc123
+```
+Template: `param_field: "password"`
+
+**Pattern D: Custom prefix**
+```
+username: customer-user-zone-us
+password: pass
+```
+Template: `username_prefix: "customer-{username}"`, keys: `"zone-{v}"`
+
+### Validation Checklist
+
+After generating a template, always verify with `python_code`:
+
+1. Country code appears correctly in the URL
+2. City names have spaces replaced with the right separator
+3. Session IDs are properly formatted
+4. The overall URL matches what the provider docs show
+5. Both rotating (no session) and sticky (with session) modes work
+
+---
+
+## Examples
+
+### Example: User says "Set up Smartproxy"
+
+1. Generate template with `python_code`:
+```python
+import json
+template = {
+ "param_field": "username",
+ "username_prefix": "{username}",
+ "username_param_separator": "-",
+ "param_separator": "-",
+ "param_keys": {
+ "country": "country-{v}",
+ "city": "city-{v}",
+ "state": "state-{v}",
+ "session_id": "session-{v}",
+ "session_duration": "sessTime-{v}"
+ },
+ "country_case": "lower",
+ "city_separator": "_"
+}
+output = json.dumps(template)
+```
+
+2. Save: `proxy_config(add_provider, name="smartproxy", gateway_host="gate.smartproxy.com", gateway_port=7777, url_template=<template>, cost_per_gb=4.00)`
+3. Credentials: `proxy_config(set_credentials, name="smartproxy", username="sp...", password="...")`
+4. Test: `proxy_config(test_provider, name="smartproxy")`
+
+### Example: User provides custom proxy docs
+
+If the user pastes documentation showing:
+```
+Proxy: proxy.example.com:8080
+Username: your_key
+Password: your_secret_cc-US_city-NewYork_sess-12345
+```
+
+You identify: password-based encoding, underscore prefix, dash key-value separator.
+
+```python
+import json
+template = {
+ "param_field": "password",
+ "username_prefix": "{username}",
+ "param_separator": "_",
+ "param_keys": {
+ "country": "cc-{v}",
+ "city": "city-{v}",
+ "session_id": "sess-{v}"
+ },
+ "country_case": "upper",
+ "city_separator": ""
+}
+output = json.dumps(template)
+```
+
+---
+
+## Guidelines
+
+1. **Always validate** the template with `python_code` before saving
+2. **Always test** the provider after setting credentials
+3. **Never hardcode** provider-specific logic -- the template handles everything
+4. If the user does not know their credentials, tell them to find username/password in their proxy provider's dashboard
+5. If test fails, check: credentials correct? Gateway host/port correct? Template encoding matches docs?
+6. Cost per GB is optional but helps the system prefer cheaper providers
+7. Priority lower = preferred; use 10-30 for primary, 50 for default, 70-90 for fallback