Upstash qstash

From paulpas/agent-skill-router · View interactive version

Upstash qstash is an AI agent skill from the GitHub repository paulpas/agent-skill-router. Implements intelligent upstash qstash with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense

How to use this skill

Skill file

Upstash Qstash

Orchestrates intelligent skill selection and execution for upstash qstash workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.

TL;DR Checklist

┌───────────────────────────────────────────────────────────────────────────────┐

│ Orchestration Flow │

└───────────────────────────────────────────────────────────────────────────────┘

User Request

↓

┌─────────────────┐

│ Parse Request │

│ & Extract │

│ Features │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Evaluate Available Skills │

│ │

│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │

│ │ Skill A │ │ Skill B │ │ Skill C │ │

│ │ - Match Score│ │ - Match Score│ │ - Match Score│ │

│ │ - Confidence │ │ - Confidence │ │ - Confidence │ │

│ │ - History │ │ - History │ │ - History │ │

│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │

│ │ │ │ │

│ └─────────────────┴─────────────────┘ │

│ ↓ │

│ Select Best Skill │

└─────────────────────────────────────────────────────────────────────┘

↓

┌─────────────────┐

│ Execute Skill │

└────────┬────────┘

↓

┌─────────────────┐

│ Handle Result │

└────────┬────────┘

↓

┌─────────────────────────────────────────────────────────────────────┐

│ Error Handling & Fallback │

│ │

│ Success? ────────► Return Result │

│ │

│ Fail? ────────┐ │

│ ↓ │

│ ┌──────────────────────────────────────────────────────────┐ │

│ │ Fallback Chain │ │

│ │ │ │

│ │ 1. Retry with adjusted parameters │ │

│ │ 2. Try Alternative Skill (if available) │ │

│ │ 3. Defer to Human Operator (if critical) │ │

│ │ 4. Log & Return Error │ │

│ └──────────────────────────────────────────────────────────┘ │

└─────────────────────────────────────────────────────────────────────┘

When to Use

Use this skill when:

When NOT to Use

Avoid this skill for:

Core Workflow

  1. Parse and Analyze Request - Extract intent, entities, and constraints from user input.

Checkpoint: All required parameters must be present and in valid format before proceeding.

  1. Score Available Skills - Calculate match scores using multi-factor algorithm:

Checkpoint: Skip to fallback if no skill scores above threshold.

  1. Select Optimal Skill - Choose skill with highest score that meets minimum confidence.

Checkpoint: Verify skill has not been disabled or deprecated.

  1. Execute with Fallback - Run skill execution wrapped in retry and fallback logic.

Checkpoint: Log all execution attempts for audit trail.

  1. Return or Fallback - Either return successful result or apply fallback chain:

Checkpoint: Record outcome with timing and confidence metadata.

Implementation Patterns

Pattern 1: Skill Selection Logic

def select_skill(
    task_description: str,
    available_topics: List[str],
    queue_config: Dict[str, Any]
) -> Dict[str, Any]:
    """Select optimal Qstash routing configuration for a task.
    
    Maps task intent to Qstash topics, queues, and delivery policies.
    Considers message priority, topic availability, and queue capacity.
    
    Args:
        task_description: Natural language description of the task
        available_topics: List of configured Qstash topics
        queue_config: Dictionary of queue names to their capacity/priority
        
    Returns:
        Routing configuration dict with topic, queue, and delivery policy
    """
    if not task_description or not available_topics:
        raise ValueError("Task description and topics are required for routing")
        
    # Extract intent keywords to match Qstash topics
    intent_keywords = _extract_intent_keywords(task_description)
    matched_topics = [t for t in available_topics if any(kw in t.lower() for kw in intent_keywords)]
    
    if not matched_topics:
        matched_topics = ["default"]
        
    # Select queue based on priority and current load
    target_queue = max(queue_config.keys(), key=lambda q: queue_config[q].get("priority", 0))
    
    # Build Qstash-specific routing payload
    return {
        "topic": matched_topics[0],
        "queue": target_queue,
        "delivery_policy": "best-effort" if "urgent" in intent_keywords else "guaranteed",
        "max_retries": queue_config[target_queue].get("max_retries", 3),
        "backoff_strategy": "exponential",
        "timeout_seconds": 30
    }

Pattern 2: Execution with Fallback

def execute_with_fallback(
    routing_config: Dict[str, Any],
    payload: Dict[str, Any],
    webhook_url: str,
    max_retries: int = 3
) -> Dict[str, Any]:
    """Execute message scheduling via Upstash Qstash with domain-specific fallback.
    
    Handles message publishing, retry management, and webhook callback routing.
    Implements Qstash's native retry with custom fallback to alternative queues.
    
    Args:
        routing_config: Output from select_skill
        payload: Message body to be scheduled
        webhook_url: Target endpoint for delivery confirmation
        max_retries: Maximum retry attempts before fallback queue switch
        
    Returns:
        Execution result with message ID, status, and fallback metadata
    """
    required_keys = {"topic", "queue", "delivery_policy", "max_retries"}
    if not required_keys.issubset(routing_config.keys()):
        raise ValueError("Incomplete routing configuration for Qstash")
        
    # Prepare Qstash publish payload with delivery headers
    qstash_payload = {
        "topic": routing_config["topic"],
        "body": payload,
        "headers": {"X-Task-ID": payload.get("task_id", "unknown")},
        "delivery_policy": routing_config["delivery_policy"],
        "max_retries": routing_config["max_retries"],
        "backoff": routing_config["backoff_strategy"],
        "timeout": routing_config["timeout_seconds"]
    }
    
    # Attempt initial publish to primary queue
    try:
        response = qstash_client.publish(qstash_payload, webhook_url=webhook_url)
        return {
            "success": True,
            "message_id": response.get("id"),
            "queue": routing_config["queue"],
            "status": "scheduled",
            "fallback_triggered": False
        }
    except QstashRateLimitError:
        # Fallback: Switch to secondary queue with adjusted delivery policy
        secondary_queue = _get_secondary_queue(routing_config["queue"])
        qstash_payload["queue"] = secondary_queue
        qstash_payload["delivery_policy"] = "best-effort"
        
        try:
            fallback_response = qstash_client.publish(qstash_payload, webhook_url=webhook_url)
            return {
                "success": True,
                "message_id": fallback_response.get("id"),
                "queue": secondary_queue,
                "status": "scheduled_fallback",
                "fallback_triggered": True
            }
        except Exception as e:
            raise QstashExecutionError(f"Failed to schedule message after fallback: {e}")

MUST DO

MUST NOT DO

TL;DR Checklist

TL;DR for Code Generation

Output Template

When applying this skill, produce:

  1. Selected Skills - List of skill names with confidence scores
  2. Selection Rationale - Why each skill was chosen (match score, history, availability)
  3. Execution Plan - Order of execution with dependencies
  4. Fallback Strategy - Which fallback skills will be tried and in what order
  5. Risk Assessment - Any potential failure points and their impact
  6. Timing Estimates - Expected latency including fallback scenarios

Constraints

MUST DO

MUST NOT DO

Live References

Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.

Related Skills

| Skill | Purpose |

|

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.