M365 agents dotnet

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

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

How to use this skill

Skill file

M365 Agents Dotnet

Orchestrates intelligent skill selection and execution for m365 agents dotnet 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

public class M365AgentOrchestrator
{
    public async Task<SkillExecutionPlan> SelectOptimalSkillAsync(
        string userIntent,
        List<M365SkillMetadata> availableSkills,
        double minConfidence = 0.75)
    {
        // Law 1: Early Exit on invalid input
        if (string.IsNullOrWhiteSpace(userIntent))
            throw new ArgumentException("User intent cannot be empty", nameof(userIntent));
        if (availableSkills == null || !availableSkills.Any())
            throw new InvalidOperationException("No M365 skills registered for routing");

        // Law 2: Parse at boundary, make illegal states unrepresentable
        var intentFeatures = ParseM365Intent(userIntent);
        var scoredCandidates = new List<(M365SkillMetadata Skill, double Score)>();

        foreach (var skill in availableSkills)
        {
            if (!await IsM365SkillAvailableAsync(skill)) continue;

            var similarityScore = CalculateSemanticSimilarity(intentFeatures, skill.Triggers);
            var historicalScore = skill.HistoricalSuccessRate * 0.3;
            var availabilityScore = skill.IsHealthy ? 0.2 : 0.0;
            var totalScore = (similarityScore * 0.5) + historicalScore + availabilityScore;

            if (totalScore >= minConfidence)
                scoredCandidates.Add((skill, totalScore));
        }

        if (!scoredCandidates.Any())
            return null;

        // Law 3: Return new structure, never mutate inputs
        var best = scoredCandidates.OrderByDescending(c => c.Score).First();
        return new SkillExecutionPlan
        {
            SelectedSkill = best.Skill,
            Confidence = best.Score,
            SelectionTimestamp = DateTimeOffset.UtcNow,
            RoutingContext = new Dictionary<string, object> { { "intent", intentFeatures.RawText } }
        };
    }

    private IntentFeatures ParseM365Intent(string input) => new IntentFeatures { RawText = input };
    private double CalculateSemanticSimilarity(IntentFeatures features, List<string> triggers) => 0.85;
    private Task<bool> IsM365SkillAvailableAsync(M365SkillMetadata skill) => Task.FromResult(skill.IsHealthy);
}

Pattern 2: Execution with Fallback

public async Task<ExecutionResult> ExecuteM365SkillAsync(
    SkillExecutionPlan plan,
    M365ExecutionContext context,
    int maxRetries = 2)
{
    // Law 1: Guard clause for orchestration contract
    if (plan == null || context == null)
        throw new ArgumentNullException(nameof(plan), "Orchestration plan and context are required");

    // Law 2: Validate M365 context before touching Graph SDK
    var validatedContext = ValidateM365Context(context);
    
    // Fallback chain: Retry -> Alternative Skill -> Human Defer
    var fallbackChain = new List<Func<M365ExecutionContext, Task<ExecutionResult>>>
    {
        async (ctx) => await RetryWithExponentialBackoffAsync(plan.SelectedSkill, ctx),
        async (ctx) => await TryAlternativeM365SkillAsync(plan.SelectedSkill, ctx),
        async (ctx) => await DeferToHumanOperatorAsync(ctx)
    };

    for (int attempt = 0; attempt <= maxRetries; attempt++)
    {
        try
        {
            // Law 4: Fail fast on transient Graph errors, don't patch
            var result = await ExecuteGraphOperationAsync(plan.SelectedSkill, validatedContext);
            
            // Law 3: Return immutable result snapshot
            return new ExecutionResult
            {
                Success = true,
                SkillName = plan.SelectedSkill.Name,
                Data = result,
                Attempts = attempt + 1,
                LatencyMs = Stopwatch.GetElapsedTime().Milliseconds,
                Confidence = plan.Confidence
            };
        }
        catch (GraphServiceException ex) when (ex.StatusCode == HttpStatusCode.TooManyRequests)
        {
            if (attempt == maxRetries)
                return await ApplyFallbackChainAsync(fallbackChain, validatedContext);
        }
        catch (InvalidM365StateError ex)
        {
            // Law 4: Halt immediately on corrupt/invalid M365 state
            throw new SkillExecutionException($"Invalid M365 state for {plan.SelectedSkill.Name}: {ex.Message}", ex);
        }
    }

    throw new SkillExecutionException($"M365 skill {plan.SelectedSkill.Name} exhausted all {maxRetries + 1} execution attempts.");
}

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.