AWS Pricing과 Cost Explorer를 MCP로 조회하여 agent별 비용 귀속을 집계하고 예산 alert을 발행하며, 사용 패턴이 정당하면 Opus → Sonnet → Haiku 모델 다운그레이드를 권고한다. 월간 예산 ceiling을 초과할 것으로 예상되는 배포는 veto하여 autopilot-deploy의 pre-flight gate로 작동한다.
AWS Pricing과 Cost Explorer를 MCP로 조회하여 agent별 비용 귀속을 집계하고 예산 alert을 발행하며, 사용 패턴이 정당하면 Opus → Sonnet → Haiku 모델 다운그레이드를 권고한다. 월간 예산 ceiling을 초과할 것으로 예상되는 배포는 veto하여 autopilot-deploy의 pre-flight gate로 작동한다.
집계 결과는 {agent, daily_usd, mtd_usd, projected_monthly_usd} 구조로 정리합니다.
Phase 2: Budget Alert — 임계 도달 감지
월간 누적(mtd_usd) vs 월간 예산(monthly_ceiling_usd) 비율을 계산하여 alert를 발행합니다.
import yaml, json
from datetime import datetime
budget = yaml.safe_load(open(".omao/plans/cost/budget.yaml"))
cost = json.load(open(f".omao/plans/cost/daily-{yesterday}.json"))
for agent, data in cost.items():
ceiling = budget["monthly_ceiling_usd"]["per_agent"].get(agent)
ifnot ceiling:
continue
pct = (data["mtd_usd"] / ceiling) * 100for alert in budget["alerts"]:
if pct >= alert["at_percent"]:
emit_alert(agent, pct, alert["action"])
notify — Slack/Email 알림만 발송.
veto-new-deploys — autopilot-deploy의 pre-flight gate 상태 파일을 vetoed로 마킹.
freeze-and-escalate — 모든 신규 배포 freeze + FinOps 팀 호출.
Phase 3: Model Downgrade Recommendation
Langfuse trace에서 agent별 avg_complexity_score, avg_token_output 메트릭을 계산하여 downgrade 기회를 탐지합니다.
⚠️ 보안 — rule["when"] 은 사용자 편집 가능한 .omao/plans/cost/budget.yaml 에서 온 문자열입니다. 절대 Python eval() / exec() 에 넣지 마세요.budget.yaml 을 수정할 수 있는 누구든 임의 코드를 실행할 수 있게 되며 (IAM credential, /.aws/credentials, Bedrock 토큰 모두 노출) 이는 RCE 벡터입니다. 반드시 sandboxed expression evaluator — simpleeval 또는 asteval — 를 사용해 표현식을 AST 로 파싱하고 산술·비교 연산자, 허용된 이름(complexity, output) 만 노출합니다.
# pip install simpleevalfrom simpleeval import SimpleEval, NameNotDefined, InvalidExpression
defeval_condition(expression: str, **context) -> bool:
"""Evaluate a budget.yaml `when:` expression safely.
Uses simpleeval's AST-walking sandbox — NO builtins, NO imports, NO attribute
access, NO function calls except those we explicitly allowlist. Raises on
unknown names instead of silently returning False.
"""
evaluator = SimpleEval(names=context, functions={}) # zero callables exposedtry:
result = evaluator.eval(expression)
except (NameNotDefined, InvalidExpression, SyntaxError) as e:
raise ValueError(f"invalid budget rule {expression!r}: {e}") from e
returnbool(result)
defevaluate_downgrade(agent: str) -> list[dict]:
# Query traces via MCP tool mcp__langfuse__query_traces (configured in observability.trace_mcp)# Cost data itself comes from mcp__cost-explorer; trace-derived metrics are optional# If observability.trace_mcp is null, skip trace-derived analysis
traces = query_traces_via_mcp(agent=agent, days=7)
ifnot traces:
return [] # No trace MCP configured, skip downgrade recommendations
complexity = mean([t["complexity_score"] for t in traces])
output_tokens = mean([t["output_tokens"] for t in traces])
recs = []
for rule in budget["downgrade_recommendations"]["models"]:
if eval_condition(rule["when"], complexity=complexity, output=output_tokens):
savings = estimate_monthly_savings(agent, rule["from"], rule["to"])
recs.append({
"agent": agent,
"from": rule["from"],
"to": rule["to"],
"estimated_monthly_savings_usd": savings,
"evidence": {"complexity": complexity, "output_tokens": output_tokens},
})
return recs
Bad Example — 절대 하지 말 것
# ❌ 절대 금지: budget.yaml 은 사용자 편집 가능 → RCE 벡터.defeval_condition(expression: str, **context) -> bool:
returnbool(eval(expression, {"__builtins__": {}}, context)) # noqa: S307
아래 같은 budget.yaml 한 줄로 AWS credential 이 공격자 S3 버킷으로 유출됩니다 (__builtins__ 를 비워도 우회 가능):
eval() / exec() / compile() 는 절대 신뢰 경계 밖 문자열에 사용하지 않습니다. 허용 리스트 기반 AST evaluator 만 사용합니다.
권고는 Draft PR로 자동 생성됩니다. 승인은 플랫폼 팀이 직접 수행합니다.
## Model Downgrade Recommendation**Agent**: `code-reviewer-agent`**Current**: `claude-opus-4-7`**Recommended**: `claude-sonnet-4-6`### Evidence (7-day window)- Average complexity score: 0.32 (threshold < 0.4)
- Average output tokens: 180 (threshold < 200)
- Tool invocation variety: 3/12 available tools actually used
### Estimated Impact- Monthly savings: $1,840
- Expected quality delta (based on continuous-eval regression test):
- faithfulness: -0.01 (within noise)
- answer_relevancy: +0.00
### Verification Plan
1. Shadow test with Sonnet for 48h at 10% traffic
2. `continuous-eval` full run on golden dataset
3. If regression < 2pp, approve full downgrade
Phase 4: Deploy Veto — Pre-flight Gate
autopilot-deploy가 새 배포를 시작하기 전에 본 skill에 pre-flight 승인을 요청합니다.