|
| 1 | +"""Claude Code Routine adapter — offloads tasks to Anthropic cloud via /fire API.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import time |
| 6 | +from dataclasses import dataclass, field |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +# Routine API constants |
| 10 | +ROUTINE_API_BASE = "https://api.anthropic.com/v1/claude_code/routines" |
| 11 | +ROUTINE_BETA_HEADER = "experimental-cc-routine-2026-04-01" |
| 12 | +ROUTINE_API_VERSION = "2023-06-01" |
| 13 | + |
| 14 | + |
| 15 | +@dataclass(frozen=True) |
| 16 | +class RoutineTriggerInfo: |
| 17 | + """Connection info for a pre-configured Routine.""" |
| 18 | + |
| 19 | + trigger_id: str |
| 20 | + token: str |
| 21 | + role: str = "" |
| 22 | + description: str = "" |
| 23 | + |
| 24 | + |
| 25 | +@dataclass |
| 26 | +class RoutineFireResult: |
| 27 | + """Result of firing a Routine via the /fire API.""" |
| 28 | + |
| 29 | + session_id: str |
| 30 | + session_url: str |
| 31 | + fired_at: float = field(default_factory=time.time) |
| 32 | + |
| 33 | + |
| 34 | +@dataclass |
| 35 | +class RoutineAdapterConfig: |
| 36 | + """Configuration for the Claude Code Routine adapter.""" |
| 37 | + |
| 38 | + enabled: bool = False |
| 39 | + routine_triggers: dict[str, RoutineTriggerInfo] = field(default_factory=dict) |
| 40 | + default_trigger_id: str = "" |
| 41 | + default_trigger_token: str = "" |
| 42 | + poll_interval_seconds: int = 30 |
| 43 | + max_wait_minutes: int = 60 |
| 44 | + branch_prefix: str = "claude/bernstein-" |
| 45 | + max_daily_fires: int = 20 |
| 46 | + |
| 47 | + |
| 48 | +@dataclass |
| 49 | +class RoutineCostTracker: |
| 50 | + """Track daily Routine fires to prevent runaway billing.""" |
| 51 | + |
| 52 | + daily_fires: int = 0 |
| 53 | + max_daily_fires: int = 20 |
| 54 | + _day_start: float = field(default_factory=time.time) |
| 55 | + |
| 56 | + def check_budget(self) -> bool: |
| 57 | + """Return True if within daily fire limit.""" |
| 58 | + now = time.time() |
| 59 | + if now - self._day_start > 86400: |
| 60 | + self.daily_fires = 0 |
| 61 | + self._day_start = now |
| 62 | + return self.daily_fires < self.max_daily_fires |
| 63 | + |
| 64 | + def record_fire(self) -> None: |
| 65 | + """Record a fire event.""" |
| 66 | + now = time.time() |
| 67 | + if now - self._day_start > 86400: |
| 68 | + self.daily_fires = 0 |
| 69 | + self._day_start = now |
| 70 | + self.daily_fires += 1 |
| 71 | + |
| 72 | + |
| 73 | +def build_fire_payload( |
| 74 | + *, |
| 75 | + goal: str, |
| 76 | + role: str, |
| 77 | + task_id: str = "", |
| 78 | + repo: str = "", |
| 79 | + base_branch: str = "main", |
| 80 | + context_files: list[str] | None = None, |
| 81 | + test_command: str = "", |
| 82 | +) -> dict[str, str]: |
| 83 | + """Build the /fire API request payload. |
| 84 | +
|
| 85 | + The `text` field is appended to the Routine's saved prompt |
| 86 | + as a one-shot user turn. |
| 87 | + """ |
| 88 | + parts = [ |
| 89 | + "## Bernstein Task Assignment\n", |
| 90 | + f"**Goal**: {goal}", |
| 91 | + f"**Role**: {role}", |
| 92 | + ] |
| 93 | + if task_id: |
| 94 | + parts.append(f"**Task ID**: {task_id}") |
| 95 | + if repo: |
| 96 | + parts.append(f"\n### Repository: {repo}") |
| 97 | + parts.append(f"Base branch: {base_branch}") |
| 98 | + if context_files: |
| 99 | + parts.append(f"Related files: {', '.join(context_files[:10])}") |
| 100 | + if test_command: |
| 101 | + parts.append(f"\n### Verification\nRun before pushing: `{test_command}`") |
| 102 | + |
| 103 | + parts.append(f"\nWork on branch `claude/bernstein-{task_id or role}`") |
| 104 | + |
| 105 | + return {"text": "\n".join(parts)} |
| 106 | + |
| 107 | + |
| 108 | +def build_fire_headers(token: str) -> dict[str, str]: |
| 109 | + """Build HTTP headers for the /fire API call.""" |
| 110 | + return { |
| 111 | + "Authorization": f"Bearer {token}", |
| 112 | + "anthropic-beta": ROUTINE_BETA_HEADER, |
| 113 | + "anthropic-version": ROUTINE_API_VERSION, |
| 114 | + "Content-Type": "application/json", |
| 115 | + } |
| 116 | + |
| 117 | + |
| 118 | +def build_fire_url(trigger_id: str) -> str: |
| 119 | + """Build the /fire endpoint URL for a given trigger ID.""" |
| 120 | + return f"{ROUTINE_API_BASE}/{trigger_id}/fire" |
| 121 | + |
| 122 | + |
| 123 | +def parse_fire_response(data: dict[str, Any]) -> RoutineFireResult: |
| 124 | + """Parse the /fire API response into a RoutineFireResult.""" |
| 125 | + return RoutineFireResult( |
| 126 | + session_id=str(data.get("claude_code_session_id", "")), |
| 127 | + session_url=str(data.get("claude_code_session_url", "")), |
| 128 | + ) |
| 129 | + |
| 130 | + |
| 131 | +def select_trigger( |
| 132 | + config: RoutineAdapterConfig, |
| 133 | + role: str, |
| 134 | +) -> tuple[str, str]: |
| 135 | + """Select the appropriate trigger ID and token for a given role. |
| 136 | +
|
| 137 | + Returns (trigger_id, token) tuple. |
| 138 | + Falls back to default trigger if no role-specific one is configured. |
| 139 | + """ |
| 140 | + if role in config.routine_triggers: |
| 141 | + trigger = config.routine_triggers[role] |
| 142 | + return trigger.trigger_id, trigger.token |
| 143 | + return config.default_trigger_id, config.default_trigger_token |
0 commit comments