Skip to content

Auto-assign subscription to new agents (round-robin) #74

@vybe

Description

@vybe

Summary

When a new agent is created, automatically assign it to a subscription using round-robin distribution across all registered subscriptions. This removes the manual step of assigning subscriptions after agent creation.

Current Behavior

Agents are created with ANTHROPIC_API_KEY (platform API key). Subscriptions must be manually assigned afterwards via Settings UI or MCP tool.

Desired Behavior

On agent creation:

  1. Query all registered subscriptions
  2. Pick the one with fewest assigned agents (round-robin). On tie, pick first alphabetically.
  3. Set CLAUDE_CODE_OAUTH_TOKEN env var on the container (instead of ANTHROPIC_API_KEY)
  4. Persist the assignment in agent_ownership.subscription_id
  5. If no subscriptions exist, fall back to current behavior (platform API key)

System agents (trinity-system) are excluded from auto-assignment.

Implementation Notes

Files to modify

  • src/backend/db/subscriptions.py — Add get_least_used_subscription() method (SQL: LEFT JOIN + GROUP BY + ORDER BY count ASC, name ASC)
  • src/backend/database.py — Expose via delegate
  • src/backend/services/agent_service/crud.py — Look up subscription before building env_vars (~line 280), set CLAUDE_CODE_OAUTH_TOKEN instead of ANTHROPIC_API_KEY, then persist assignment after register_agent_owner()

Key constraint

The subscription lookup and token injection must happen before container creation (line 337+) since env vars are set at container creation time. The DB assignment must happen after register_agent_owner() (line 489) since it updates the agent_ownership row.

Edge cases

  • No subscriptions registered → skip, use platform API key
  • Token decryption fails → fall back to platform API key, log warning
  • All subscriptions have equal agent count → pick first alphabetically
  • Subscription deleted later → existing cascade-clear behavior handles this

Verification

  1. Register a subscription in Settings
  2. Create a new agent → auth status should show "subscription"
  3. docker exec agent-{name} env | grep CLAUDE_CODE_OAUTH_TOKEN → set
  4. docker exec agent-{name} env | grep ANTHROPIC_API_KEY → not set
  5. Register second subscription, create 2 more agents → verify round-robin
  6. Create with no subscriptions → falls back to API key

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions