协作头脑风暴
brainstorming
在实现前澄清需求、探索设计选择,并形成清晰的开发方向。
stripe-automation【开发与工程】Implements intelligent stripe automation with multi-factor skill selection, fallback chains, and adherence to the 5 Laws of Elegant Defense
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
name: stripe-automation compatibility: opencode completeness: 95 content-types:
Orchestrates intelligent skill selection and execution for stripe automation workflows. Applies the 5 Laws of Elegant Defense to guide data naturally through the orchestration pipeline, preventing errors before they occur. Selects optimal skills based on multi-factor scoring including text similarity, historical performance, and system availability.
┌───────────────────────────────────────────────────────────────────────────────┐ │ Orchestration Flow │ └───────────────────────────────────────────────────────────────────────────────┘
User Request ↓ ┌─────────────────┐ │ Parse Request │ │ & Extract │ │ Features │ └────────┬────────┘ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Evaluate Available Skills │ │ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Skill A │ │ Skill B │ │ Skill C │ │ │ │ - Match Score│ │ - Match Score│ │ - Match Score│ │ │ │ - Confidence │ │ - Confidence │ │ - Confidence │ │ │ │ - History │ │ - History │ │ - History │ │ │ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │ │ │ │ │ │ │ └─────────────────┴─────────────────┘ │ │ ↓ │ │ Select Best Skill │ └─────────────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────┐ │ Execute Skill │ └────────┬────────┘ ↓ ┌─────────────────┐ │ Handle Result │ └────────┬────────┘ ↓ ┌─────────────────────────────────────────────────────────────────────┐ │ Error Handling & Fallback │ │ │ │ Success? ────────► Return Result │ │ │ │ Fail? ────────┐ │ │ ↓ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ Fallback Chain │ │ │ │ │ │ │ │ 1. Retry with adjusted parameters │ │ │ │ 2. Try Alternative Skill (if available) │ │ │ │ 3. Defer to Human Operator (if critical) │ │ │ │ 4. Log & Return Error │ │ │ └──────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘
Use this skill when:
Avoid this skill for:
Parse and Analyze Request - Extract intent, entities, and constraints from user input. Checkpoint: All required parameters must be present and in valid format before proceeding.
Score Available Skills - Calculate match scores using multi-factor algorithm:
Checkpoint: Skip to fallback if no skill scores above threshold.
Select Optimal Skill - Choose skill with highest score that meets minimum confidence. Checkpoint: Verify skill has not been disabled or deprecated.
Execute with Fallback - Run skill execution wrapped in retry and fallback logic. Checkpoint: Log all execution attempts for audit trail.
Return or Fallback - Either return successful result or apply fallback chain:
related-skillsCheckpoint: Record outcome with timing and confidence metadata.
def route_stripe_intent(
user_request: Dict,
stripe_config: Dict,
min_confidence: float = 0.7
) -> Dict:
"""Route a Stripe automation request to the appropriate SDK endpoint.
Validates parameters against Stripe API requirements and selects
the optimal operation (customer, payment, subscription, webhook).
"""
if not user_request.get("intent") or not stripe_config.get("api_key"):
raise ValueError("Missing required Stripe intent or API configuration")
intent = user_request["intent"].lower()
params = user_request.get("parameters", {})
# Map intents to Stripe SDK methods with parameter validation
stripe_routes = {
"create_customer": ("customers", "create", {"email": str, "name": str}),
"process_payment": ("charges", "create", {"amount": int, "currency": str, "source": str}),
"update_subscription": ("subscriptions", "update", {"subscription_id": str, "status": str}),
"handle_webhook": ("webhooks", "construct", {"payload": str, "sig_header": str})
}
if intent not in stripe_routes:
raise ValueError(f"Unsupported Stripe intent: {intent}")
endpoint, method, required_fields = stripe_routes[intent]
missing = [f for f in required_fields if f not in params]
if missing:
raise ValueError(f"Missing required Stripe parameters: {missing}")
return {
"route": f"stripe.{endpoint}.{method}",
"validated_params": params,
"intent": intent,
"confidence": min_confidence,
"idempotency_key": f"stripe_{intent}_{uuid4()}"
}
def execute_stripe_operation(
route_config: Dict,
stripe_client: Any,
max_retries: int = 2
) -> Dict:
"""Execute a validated Stripe operation with idempotency and fallback handling.
Implements Stripe-specific resilience:
- Idempotency keys prevent duplicate charges/subscriptions
- Handles StripeCardError, StripeAPIError, and rate limits
- Falls back to manual review or alternative payment methods
"""
endpoint = route_config["route"]
params = route_config["validated_params"]
idempotency_key = route_config["idempotency_key"]
for attempt in range(max_retries + 1):
try:
# Parse endpoint string to dynamic method call
module_name, method_name = endpoint.split(".")
stripe_module = getattr(stripe, module_name)
method = getattr(stripe_module, method_name)
# Execute with idempotency key for safe retries
result = method(
**params,
idempotency_key=idempotency_key if method_name != "construct" else None
)
return {
"success": True,
"stripe_operation": endpoint,
"stripe_id": result.get("id"),
"status": result.get("status"),
"attempts": attempt + 1,
"latency_ms": time.time() * 1000
}
except stripe.error.CardError as e:
# Payment failed - immediate fail, no retry for card errors
raise StripeOperationError(
f"Card declined: {e.user_message}",
stripe_code=e.code
) from e
except stripe.error.RateLimitError as e:
# Transient - retry with exponential backoff
if attempt < max_retries:
time.sleep(2 ** attempt)
continue
return _fallback_to_manual_review(route_config, e)
except stripe.error.APIError as e:
# Other API errors - fallback chain
if attempt == max_retries:
return _fallback_to_alternative_payment(route_config, e)
raise StripeOperationError(f"Stripe {endpoint} failed after {max_retries + 1} attempts")
code-philosophy (5 Laws of Elegant Defense) in all logicWhen applying this skill, produce:
| Skill | Purpose |
|---|---|
sendgrid-automation | Email automation counterpart — Stripe events trigger SendGrid notifications for payment workflows |
slack-automation | Slack notifications for Stripe billing events and subscription changes |
Authoritative documentation links for this domain. The model follows markdown links at load time to resolve external references and inline content.