# Personal Access Tokens

Complete guide to creating and using Personal Access Tokens for API authentication

# Personal Access Tokens

Personal Access Tokens (PATs) enable programmatic access to the TeamDay API for automation, CI/CD pipelines, and agent authentication.

## Quick Start

### 1. Create Your Token

1. Navigate to **Settings → Profile**
2. Scroll to **Personal Access Tokens**
3. Click **Create Token**
4. Give it a descriptive name (e.g., "CI Pipeline", "Production Automation")
5. Choose an expiration period (90 days recommended)
6. **Copy the token immediately** - it will only be shown once!

### 2. Use Your Token

Include your token in the `Authorization` header:

```bash
curl -H "Authorization: Bearer td_your-token-here" \
     https://cc.teamday.ai/api/v1/agents
```

Or set it as an environment variable:

```bash
export TEAMDAY_TOKEN="td_your-token-here"

curl -H "Authorization: Bearer $TEAMDAY_TOKEN" \
     https://cc.teamday.ai/api/v1/agents
```

## Security Best Practices

:::warning Important Security Guidelines
- **Never commit tokens to version control** - Use environment variables or secret managers
- **Rotate tokens regularly** - Set appropriate expiration dates
- **Use separate tokens per integration** - Makes revocation easier
- **Name tokens descriptively** - Know where each token is used
- **Revoke unused tokens immediately** - Reduce security surface area
- **Never share tokens** - Each team member should have their own
:::

### Storage Recommendations

**✅ Secure Storage:**
- Environment variables: `export TEAMDAY_TOKEN="..."`
- Secret managers: AWS Secrets Manager, HashiCorp Vault, 1Password
- CI/CD secrets: GitHub Secrets, GitLab CI/CD variables
- `.env` files (with `.gitignore`)

**❌ Insecure Storage:**
- Hardcoded in source code
- Committed to git repositories
- Shared via Slack/email
- Stored in plain text files in shared drives

## Token Permissions

Personal Access Tokens have the same permissions as the user who created them:

- **Organization Access:** Token is scoped to your current organization
- **User Permissions:** Inherits your role permissions (admin, member, viewer)
- **Resource Access:** Can access all resources you can access via the UI
- **Private Resources:** Access your private agents, spaces, and chats

**Note:** Granular scopes (e.g., read-only, write-only) are not yet implemented. All tokens have full access matching the user's permissions. Scoped tokens are planned for a future release.

## API Endpoints with PAT

Once authenticated, you can access these endpoints:

### Agents
```bash
# List all agents
GET /api/v1/agents

# Create an agent
POST /api/v1/agents

# Get agent details
GET /api/v1/agents/{agentId}

# Update agent
PATCH /api/v1/agents/{agentId}

# Delete agent
DELETE /api/v1/agents/{agentId}

# Execute agent
POST /api/v1/agents/{agentId}/execute
```

### Tasks
```bash
# List tasks
GET /api/v1/tasks

# Create task
POST /api/v1/tasks
```

### Executions
```bash
# List executions
GET /api/v1/executions

# Get execution details
GET /api/v1/executions/{executionId}

# Get execution tree (with delegations)
GET /api/v1/executions/{executionId}/tree

# Cancel execution
POST /api/v1/executions/{executionId}/cancel
```

### Spaces
```bash
# List spaces
GET /api/v1/spaces

# Get space
GET /api/v1/spaces/{id}

# Create space
POST /api/v1/spaces

# Update space
PATCH /api/v1/spaces/{id}

# Delete space
DELETE /api/v1/spaces/{id}
```

See our [API Reference](https://docs.teamday.ai/api/endpoints) for complete endpoint documentation.

## Example: Create and Execute an Agent

```typescript
const TEAMDAY_TOKEN = process.env.TEAMDAY_TOKEN!

// 1. Create an agent
const agent = await fetch('https://cc.teamday.ai/api/v1/agents', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${TEAMDAY_TOKEN}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'Code Reviewer',
    role: 'Senior Developer',
    systemPrompt: 'You review code for quality, security, and best practices.',
    visibility: 'organization',
  }),
}).then(r => r.json())

console.log(`Agent created: ${agent.id}`)

// 2. Execute the agent
const execution = await fetch(`https://cc.teamday.ai/api/v1/agents/${agent.id}/execute`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${TEAMDAY_TOKEN}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    message: 'Review the authentication code in src/auth.ts',
    spaceId: 'space_your-workspace',
    stream: false, // Get full response when complete
  }),
}).then(r => r.json())

console.log(`Review completed:`, execution.messages)
```

## Using Tokens in CI/CD

### GitHub Actions

```yaml
name: Deploy with TeamDay Agent

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Deploy via TeamDay Agent
        env:
          TEAMDAY_TOKEN: ${{ secrets.TEAMDAY_TOKEN }}
        run: |
          curl -X POST https://cc.teamday.ai/api/v1/agents/char_deploy_bot/execute \
            -H "Authorization: Bearer $TEAMDAY_TOKEN" \
            -H "Content-Type: application/json" \
            -d '{
              "message": "Deploy commit ${{ github.sha }} to production",
              "spaceId": "space_production",
              "stream": false
            }'
```

### GitLab CI

```yaml
deploy:
  stage: deploy
  script:
    - |
      curl -X POST https://cc.teamday.ai/api/v1/agents/${AGENT_ID}/execute \
        -H "Authorization: Bearer ${TEAMDAY_TOKEN}" \
        -H "Content-Type: application/json" \
        -d "{\"message\": \"Deploy ${CI_COMMIT_SHA}\"}"
  only:
    - main
```

## Using Tokens in Virtual Environments

When using agents in isolated virtual environments (like Docker containers or cloud functions), pass the token as an environment variable:

```bash
# In Space Settings → Environment Variables
TEAMDAY_TOKEN=td_your-token-here
```

Your agent can then use this token to call other TeamDay APIs or delegate work to other agents.

## Token Management

### Viewing Your Tokens

Go to **Settings → Profile → Personal Access Tokens** to see:
- Token name and creation date
- Last usage timestamp
- Expiration date
- Masked token value (for identification)

### Revoking Tokens

Click the **trash icon** next to any token to revoke it immediately. This will:
- Invalidate the token permanently
- Stop all API requests using that token
- Remove the token from your account

:::warning Warning
Revoking a token will break any scripts, CI/CD pipelines, or integrations using it. Make sure to update those systems before revoking.
:::

### Token Expiration

Tokens automatically expire based on the expiration period you selected:
- **7 days** - For testing and short-term use
- **30 days** - For monthly automation
- **90 days** - **Recommended** for production use
- **180 days** - For long-running integrations
- **365 days** - Maximum expiration (requires careful security management)

You'll need to create a new token when the old one expires.

## Rate Limits

Currently, the API does not enforce rate limits. This may change in the future.

**Best practices:**
- Use reasonable request rates
- Implement exponential backoff for retries
- Cache responses when appropriate

## Error Handling

Always handle authentication errors gracefully:

```typescript
async function callTeamDayAPI(endpoint: string, options: RequestInit) {
  const response = await fetch(`https://cc.teamday.ai${endpoint}`, {
    ...options,
    headers: {
      'Authorization': `Bearer ${process.env.TEAMDAY_TOKEN}`,
      'Content-Type': 'application/json',
      ...options.headers,
    },
  })

  if (response.status === 401) {
    throw new Error('Invalid or expired token. Create a new token in Settings → Profile.')
  }

  if (response.status === 403) {
    throw new Error('Token lacks permission for this operation.')
  }

  if (response.status === 429) {
    throw new Error('Rate limit exceeded. Please retry after a delay.')
  }

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: response.statusText }))
    throw new Error(`TeamDay API error: ${error.message}`)
  }

  return response.json()
}
```

## Migrating from OAuth to PAT

If you're currently using OAuth tokens from the CLI, consider migrating to Personal Access Tokens:

**OAuth (CLI):**
- ✅ Interactive authentication flow
- ✅ Automatic token refresh
- ❌ Requires browser for initial auth
- ❌ Tokens expire (15 min access, 90 day refresh)

**Personal Access Tokens:**
- ✅ Long-lived (up to 1 year)
- ✅ No browser required
- ✅ Perfect for server-side automation
- ❌ Manual token management
- ❌ No automatic refresh

Choose PATs for:
- CI/CD pipelines
- Server-side automation
- Docker containers
- Cloud functions
- Cron jobs

Choose OAuth for:
- CLI interactive use
- Local development
- Desktop applications

## Troubleshooting

### "Invalid token" error

**Possible causes:**
- Token has expired
- Token was revoked
- Token was copied incorrectly (missing prefix or characters)

**Solution:** Create a new token and update your environment variables.

### "Forbidden" error

**Possible causes:**
- Your account doesn't have permission for the requested operation
- Token is from a different organization

**Solution:** Check your organization membership and role permissions.

### Token not working in requests

**Checklist:**
- ✅ Include the full token with `td_` prefix
- ✅ Use `Authorization: Bearer` header (not just `Authorization`)
- ✅ No extra spaces or newlines in the token value
- ✅ Token has not expired
- ✅ Token belongs to the correct organization

## Related Documentation

- [API Reference](https://docs.teamday.ai/api/endpoints) - Complete API endpoint documentation
- [Authentication Architecture](https://docs.teamday.ai/api/authentication) - Overview of all auth methods
- [CLI Tool Guide](https://docs.teamday.ai/guides/cli-tool) - Using the TeamDay CLI
- [Workflow Automation](https://docs.teamday.ai/guides/missions-user-guide) - Building automated workflows

## Need Help?

If you're experiencing issues with Personal Access Tokens:
- Check our [Troubleshooting Guide](https://docs.teamday.ai/guides/troubleshooting)
- Contact support at support at teamday.ai
- Report bugs at [GitHub Issues](https://github.com/TeamDay-AI/teamday/issues)
