Outlook calendar automation

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

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

How to use this skill

Skill file

Outlook Calendar Automation

Orchestrates intelligent skill selection and execution for outlook calendar automation 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 prepare_calendar_event(
    user_email: str,
    request_params: Dict[str, Any],
    available_slots: List[Dict]
) -> Dict[str, Any]:
    """Prepare and validate an Outlook calendar event before execution.
    
    Handles timezone normalization, conflict detection, and attendee validation
    using Microsoft Graph API patterns. Implements early validation and
    immutable data structures per Elegant Defense principles.
    
    Args:
        user_email: Primary organizer email
        request_params: Parsed request with subject, start, end, attendees
        available_slots: Pre-fetched free/busy slots from Graph API
        
    Returns:
        Validated event payload ready for Graph API submission
    """
    # Guard clause - Early Exit (Law 1)
    if not user_email or not request_params.get("subject"):
        raise ValueError("Missing required organizer email or event subject")
        
    # Parse & normalize inputs - Make Illegal States Unrepresentable (Law 2)
    start_dt = _parse_iso_datetime(request_params["start"])
    end_dt = _parse_iso_datetime(request_params["end"])
    if end_dt <= start_dt:
        raise ValueError("Event end time must be after start time")
        
    # Validate against free/busy data (Domain Logic)
    conflicts = _check_graph_free_busy(user_email, start_dt, end_dt, available_slots)
    if conflicts:
        return {
            "status": "conflict_detected",
            "conflicting_events": conflicts,
            "suggested_alternatives": _find_alternative_slots(available_slots, start_dt, end_dt)
        }
        
    # Validate attendees via Graph API directory lookup
    validated_attendees = []
    for attendee in request_params.get("attendees", []):
        if not _validate_graph_user(attendee):
            raise ValueError(f"Invalid attendee email: {attendee}")
        validated_attendees.append({"email": attendee, "type": "required"})
        
    # Atomic Predictability (Law 3) - Return new dict, never mutate inputs
    event_payload = {
        "subject": request_params["subject"],
        "body": {"contentType": "HTML", "content": request_params.get("body", "")},
        "start": {"dateTime": start_dt.isoformat(), "timeZone": request_params.get("timezone", "UTC")},
        "end": {"dateTime": end_dt.isoformat(), "timeZone": request_params.get("timezone", "UTC")},
        "attendees": validated_attendees,
        "allowNewTimeProposals": True,
        "responseRequested": True
    }
    return event_payload

Pattern 2: Execution with Fallback

def execute_calendar_operation(
    event_payload: Dict[str, Any],
    graph_client: Any,
    fallback_strategy: str = "suggest_alternatives"
) -> Dict[str, Any]:
    """Execute Outlook calendar event creation/update with domain-specific fallbacks.
    
    Implements resilient Graph API calls with automatic conflict resolution,
    retry logic for transient network errors, and graceful degradation.
    
    Args:
        event_payload: Validated event dictionary from prepare_calendar_event
        graph_client: Authenticated Microsoft Graph SDK client
        fallback_strategy: How to handle conflicts (suggest_alternatives, defer_human, etc.)
        
    Returns:
        Execution result with event ID, status, and fallback metadata
    """
    # Guard clause - validate client state (Early Exit)
    if not graph_client or not graph_client.api_version:
        raise RuntimeError("Graph client not initialized or invalid")
        
    max_retries = 3
    last_error = None
    
    for attempt in range(max_retries):
        try:
            # Domain-specific Graph API call
            response = graph_client.me.events.post(event_payload)
            
            # Atomic Predictability (Law 3) - Return immutable result structure
            return {
                "success": True,
                "event_id": response.id,
                "status": "created",
                "attendee_responses": [],
                "attempts": attempt + 1,
                "latency_ms": _measure_execution_time()
            }
            
        except GraphAPIError as e:
            last_error = e
            # Fail Fast - Don't retry on invalid state (Law 4)
            if e.status_code in (400, 403, 404):
                raise CalendarOperationError(f"Permanent Graph API error: {e.message}") from e
                
            # Transient error - exponential backoff retry
            if attempt < max_retries - 1:
                time.sleep(2 ** attempt)
                continue
                
    # All retries exhausted - Apply domain fallback (Law 4)
    if fallback_strategy == "suggest_alternatives":
        return {
            "success": False,
            "fallback_applied": True,
            "reason": "graph_api_unavailable",
            "next_steps": "trigger_alternative_time_slot_search",
            "original_payload": event_payload
        }
    elif fallback_strategy == "defer_human":
        return {
            "success": False,
            "fallback_applied": True,
            "reason": "requires_manual_review",
            "next_steps": "escalate_to_human_organizer",
            "original_payload": event_payload
        }
        
    raise CalendarOperationError(f"Calendar operation failed after {max_retries} attempts: {last_error}")

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

Related Skills

| Skill | Purpose |

|



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.

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.