---
name: discover-actions
description: |
  Trigger this skill when the user wants to discover API actions for a provider:

  **Triggers:**
  - "discover actions for [provider]"
  - "find all [provider] API endpoints"
  - "research [provider] API actions"
  - "what actions does [provider] support"
  - Starting a new connector build (automatic as part of research phase)

  **What it does:**
  1. Checks S3 for indexed action data first
  2. Falls back to autonomous AI research if no data exists
  3. Launches async `discover_actions` subagent (5-15 minutes)
  4. Polls status every 60-90 seconds
  5. Returns comprehensive JSON report with ~100 discovered actions
  6. Auto-saves results to S3 for future use
---

# Action Discovery Skill

## Overview

This skill automates the discovery of API actions for a provider using a two-tier approach: indexed data from S3 (fast) or autonomous AI research (comprehensive).

## When to Use

**Automatic triggers:**
- Part of Research Phase when building new connectors
- User explicitly asks to discover actions
- Checking API coverage for existing connector

**Prerequisites:**
- Provider name (e.g., `zendesk`, `workday`, `bamboohr`)
- Optional: API version to focus on (e.g., `v2`, `latest`)

## Execution Flow

### Step 1: Check for Indexed Data (ALWAYS DO THIS FIRST)

```bash
# Get exact provider key
map_provider_key("provider_name")
# Example: "slack" → "slack_web_api"

# Check for indexed actions
get_provider_actions("provider_key")
```

**If data exists:**
- ✅ Use indexed data immediately (comprehensive, pre-researched)
- ⏭️ Skip autonomous discovery
- 📊 Data includes: actions, endpoints, use cases, prerequisites

**If no data exists:**
- ⚠️ Proceed to autonomous discovery (Step 2)

### Step 2: Launch Autonomous Discovery

**ONLY if S3 data doesn't exist.**

```typescript
// Launch async task (returns immediately)
const result = discover_actions({
  provider: "provider_name",
  apiVersion: "v2",  // Optional
  maxIterations: 30   // Default: 30 (allows 20+ tool calls)
});

// Extract taskId
const taskId = result.taskId;
// Example: "rpc_01ABC123..."
```

### Step 3: Poll for Status (Every 60-90 seconds)

```typescript
// Check status
const status = get_discover_actions_task_status(taskId, "provider_name");

// Status progression:
// "pending" → Task queued
// "running" → Active research (shows iteration/maxIterations)
// "complete" → Finished successfully
// "error" → Failed (check error field)
```

**Expected Timeline:**
- **Minute 0:** Launch task
- **Minutes 0-2:** Status = "pending"
- **Minutes 2-15:** Status = "running" (shows progress)
- **Minute 15:** Status = "complete"

**While waiting:**
- Continue with other research tasks (auth, docs, external repos)
- Update user on progress: "Discovery running (iteration 12/30)..."
- DO NOT block - work on parallel tasks

### Step 4: Extract Results

```typescript
// When status = "complete"
const report = status.result;

// Report structure:
{
  "provider": "provider_name",
  "total_actions": 98,
  "api_version": "v2",
  "categories": [
    {
      "category": "User Management",
      "actions": [
        {
          "actionId": "list_users",
          "endpoint": "/api/v2/users",
          "method": "GET",
          "description": "Retrieve list of all users...",
          "use_cases": ["User sync", "Directory listing"],
          "prerequisites": ["users:read scope"],
          "parameters": [...]
        }
      ]
    }
  ],
  "research_metadata": {
    "tool_calls": 23,
    "sources": ["official_docs", "openapi_spec", "external_repos"],
    "duration_seconds": 847
  }
}
```

### Step 5: Use Results

**Immediate actions:**
1. Save report to project directory: `/tmp/<provider>_discovered_actions.json`
2. Extract endpoints for version validation: `report.categories[].actions[].endpoint`
3. Count total actions: `report.total_actions`
4. Group by category for config building

**For config building:**
- Use discovered `actionId`, `endpoint`, `method`, `description`
- Map actions to StackOne unified operations where applicable
- Include all discovered actions in YAML config

## Key Features

### Autonomous Research (20+ Tool Calls)

The subagent automatically:
- ✅ Fetches official API documentation
- ✅ Parses OpenAPI specifications
- ✅ Analyzes external integration repositories
- ✅ Searches developer forums and guides
- ✅ Identifies authentication requirements
- ✅ Discovers rate limits and pagination
- ✅ Categorizes actions by domain

### Data Sources Analyzed

1. **Official Documentation**
   - Provider API reference docs
   - Developer guides
   - Quickstart tutorials

2. **OpenAPI Specifications**
   - Public OpenAPI/Swagger specs
   - Postman collections
   - API Blueprint files

3. **External Repositories**
   - Open-source integrations
   - SDK implementations
   - Client libraries

4. **Community Resources**
   - Stack Overflow discussions
   - GitHub issues/PRs
   - Developer blogs

### Persistence & Caching

- ✅ Results auto-saved to S3 after completion
- ✅ Future calls use cached data (instant)
- ✅ No need to re-discover for same provider
- ✅ Data indexed by provider key

## Error Handling

### Common Issues

**Issue: Task stuck in "pending"**
```
Resolution: Wait 2-3 minutes, then check again
Cause: Task queue backlog
```

**Issue: Task fails with "error" status**
```
Resolution: Read error message, check provider name spelling
Cause: Invalid provider name or API unavailable
```

**Issue: Incomplete results (< 20 actions)**
```
Resolution: Increase maxIterations to 50
Cause: Complex API requiring more research
```

### Retry Strategy

```typescript
// If task fails
if (status.status === "error") {
  // Check error message
  console.log(status.error);

  // Retry with higher iterations
  discover_actions({
    provider: "provider_name",
    maxIterations: 50  // Increased from 30
  });
}
```

## Integration with Workflow

### Part of Research Phase (Parallel Execution)

**Minute 0:**
```typescript
// Launch discovery (async)
const { taskId } = discover_actions({ provider: "provider_name" });

// Continue with other research (parallel)
get_stackone_actions("hris");
vector_search(["authentication", "scopes"], "provider_name");
get_external_repos();
```

**Minutes 5-15:**
```typescript
// Poll status every 60-90 seconds
while (status !== "complete") {
  status = get_discover_actions_task_status(taskId, provider);
  await sleep(60000);
}
```

**Minute 15:**
```typescript
// Synchronize results
const discoveredActions = status.result;

// Proceed to version validation
analyze_versioning({
  provider: "provider_name",
  endpoints: discoveredActions.categories[].actions[].endpoint
});
```

## Success Criteria

### Minimum Requirements

- [ ] S3 check performed first
- [ ] Task launched successfully (taskId received)
- [ ] Status polled until "complete"
- [ ] Results extracted and saved
- [ ] Actions count ≥ 50 for major providers
- [ ] All action categories identified
- [ ] Endpoints ready for version validation

### Quality Indicators

**Good Coverage:**
- Major providers: 80-150 actions
- Niche providers: 30-80 actions
- Specialized APIs: 20-50 actions

**Red Flags:**
- < 20 actions for major provider → Increase iterations
- No CRUD operations → Check API availability
- Missing authentication → Review auth docs

## Output Report

```markdown
## Action Discovery: <provider>

### Summary
- Total actions discovered: 98
- API version: v2
- Categories: 8
- Research duration: 14 minutes
- Tool calls: 23
- Data sources: 5

### Categories
| Category | Actions | Examples |
|----------|---------|----------|
| User Management | 15 | list_users, get_user, create_user |
| Groups | 12 | list_groups, add_member |
| Content | 25 | list_posts, create_post |
| Analytics | 10 | get_stats, export_data |
| Webhooks | 8 | list_webhooks, create_webhook |
| Settings | 18 | get_settings, update_config |
| Files | 6 | upload_file, list_files |
| Search | 4 | search_content, search_users |

### Next Steps
- [x] Actions discovered (98 total)
- [ ] Version validation needed (run analyze_versioning)
- [ ] Config building ready
- [ ] Action tracking setup required

### Files Created
- `/tmp/<provider>_discovered_actions.json` - Full report
```

## Key Principles

1. **Always check S3 first** - Don't waste time re-discovering
2. **Run in parallel** - Don't block other research tasks
3. **Poll patiently** - Takes 5-15 minutes, check every 60-90s
4. **Use results immediately** - Feed into version validation
5. **Save for later** - Store report for config building phase

## Anti-Patterns (NEVER DO THESE)

- ❌ Skipping S3 check (wasting time)
- ❌ Blocking workflow waiting for results
- ❌ Polling every 10 seconds (unnecessary load)
- ❌ Ignoring discovered actions in config
- ❌ Not validating versions after discovery
- ❌ Assuming indexed data is outdated (it's curated)
