Skill: leo9/brek-ai (version 1.0.2)

--- name: brek-ai-skill description: Integrate with Brek Partner Core Chat API for hotel-search and booking assistant flows. Use when an agent needs to create or continue Brek chat sessions, send user events safely, enforce anti-abuse call controls, and run payment setup or payment confirmation without collecting raw card data. metadata: required_env_vars: BREK_BASE_URL,BREK_PARTNER_API_KEY primary_credential: BREK_PARTNER_API_KEY required_runtime_inputs: actorId,workspaceId,partnerId,clientActionId storage_requirements: durable idempotency dedupe store,budget counter store,usage metering log autonomous_invocation: "false" always_on_presence: "false" config_paths: none --- # Brek AI Partner Core Chat Execute Brek through `/api/partner/v1/core-chat`. Use this execution order: 1. Create one session per end user (`POST /sessions`) with a stable `actor.actorId`. 2. Reuse that session for all follow-up messages (`POST /events`). 3. Read the latest state when needed (`GET /sessions/{sessionId}`). Do not share one session across different users. ## Required runtime inputs Require these inputs before calling Brek: - `BREK_BASE_URL` - `BREK_PARTNER_API_KEY` - `actorId` (stable partner-side end-user ID) - `workspaceId` or tenant context if your product uses workspaces - `partnerId` (stable partner tenant ID for idempotency and billing grouping) - `clientActionId` for each write-like event kind If one required input is missing, stop and request it. If `BREK_PARTNER_API_KEY` is missing: - stop outbound calls - ask the user to get the key from their internal owner or approved support channel - never request secrets through unapproved channels ## Call safety guardrails Apply these guardrails before every upstream call: 1. Enforce local budget limits from `references/call-control.md`. 2. Attach a deterministic `idempotencyKey` for all write-like event kinds. 3. Respect `429` with `retry-after` and exponential backoff. 4. Open a circuit breaker after repeated 5xx or timeout failures. 5. Log `x-request-id`, `x-partner-id`, `x-ratelimit-limit`, and `x-ratelimit-remaining`. Never retry booking or payment-confirm actions without the same `idempotencyKey`. ## Event-kind rules When `kind` is one of: - `command_book_by_option_id` - `action_book_option` - `action_confirm_price_change` - `action_confirm_payment_card` - `action_cancel_booking` Always include `idempotencyKey`. Generate `idempotencyKey` as: - `<partnerId>:<sessionId>:<kind>:<clientActionId>` If `partnerId` is unavailable in your runtime, use stable tenant context (for example `workspaceId`) and keep the key format deterministic. ## Payment handling Handle payment in two layers: 1. End-user card setup and confirmation in secure portal flow. 2. Agent-to-agent usage billing and settlement. Follow `references/payment-and-billing.md` for both layers. Hard rules: - Never request or store raw card number, CVV, or full PAN in chat. - Accept only tokenized `paymentMethodId` from provider-hosted fields. - Require explicit user confirmation before `action_confirm_payment_card` and booking actions. ## Response mapping Map Brek response as: - `data.result.status` -> state machine key for UI and orchestration - `data.result.message.text` -> user-visible assistant text - `data.result.artifacts` -> structured payload (shortlist, payment setup URL, booking metadata) ## Error handling - `400`: request validation failed. Fix payload. - `401/403`: API key issue. Stop calls. Tell user to rotate or provision key through their internal owner or approved support channel. - `404`: session not found or wrong tenant. - `409`: actor/session mismatch. Recreate correct session. - `429`: throttle locally and retry by `retry-after`. - `5xx`: retry with backoff, then open breaker. ## References Read only what you need: - API payload templates: `references/api-templates.md` - Call-control and anti-abuse policy: `references/call-control.md` - Payment and billing orchestration: `references/payment-and-billing.md`

path: agents/openai.yaml
content: interface:
  display_name: "Brek Partner Core Chat"
  short_description: "Run Brek hotel-booking core-chat flows safely"
  default_prompt: "Use $brek-ai-skill to execute Brek core-chat session/event and payment-safe booking flows."

policy:
  allow_implicit_invocation: false


path: references/call-control.md
content: # Call Control and Anti-Abuse

Use a local gate in front of Brek API. Do not rely only on upstream limits.

## Recommended default limits

Apply all limits together:
- Per `actorId`: max 12 `/events` calls per minute.
- Per `actorId`: max 200 `/events` calls per day.
- Per partner key: max 3000 total calls per day.
- Concurrent in-flight calls per `actorId`: max 2.
- Maximum active sessions per `actorId` per 24h: 3.

Tune these numbers by real traffic and budget.

## Retry policy

- On `429`: respect `retry-after`; then retry with exponential backoff and jitter.
- On timeouts/`5xx`: retry at most 2 times.
- On `400/401/403/404/409`: no blind retry.

## Circuit breaker

Open breaker when either condition is met:
- 5 failures in 60 seconds for same partner key.
- 50%+ failure ratio over last 20 requests.

During open breaker:
- Reject new writes for 60 seconds.
- Allow only a small probe flow (for example, 1 request every 10 seconds).

## Idempotency policy

For write-like kinds, persist a dedupe record:
- Key: `partnerId + sessionId + kind + clientActionId`
- TTL: 24 hours
- If duplicate key appears, return cached outcome or block duplicate call.

## Budget kill switch

Track estimated spend and enforce hard stop:
- Daily budget per partner key (USD).
- Monthly budget per partner key (USD).
- Trigger alert at 70%, 85%, 100%.
- At 100%, deny write-like events and require operator override.


path: references/api-templates.md
content: # API Templates

Base path:
- `/api/partner/v1/core-chat`

Auth header (use one):
- `x-partner-api-key: <key>`
- `Authorization: Bearer <key>`

## Create session

`POST /sessions`

```json
{
  "actor": {
    "actorId": "partner_user_001",
    "timezoneOffsetMinutes": -480
  },
  "channel": {
    "workspaceId": "partner-workspace"
  },
  "conversation": {
    "channelId": "partner-chat"
  }
}
```

## Send event

`POST /events`

```json
{
  "sessionId": "sess_xxx",
  "actor": {
    "actorId": "partner_user_001"
  },
  "text": "Seattle Mar 20-23 1 room refundable",
  "kind": "action_book_option",
  "payload": {
    "optionId": "opt_123"
  },
  "idempotencyKey": "partner:sess_xxx:action_book_option:click_001"
}
```

## Get session

`GET /sessions/{sessionId}`

## Minimal transport wrapper

```ts
async function brekRequest(path: string, init?: RequestInit) {
  const response = await fetch(`${BREK_BASE_URL}${path}`, {
    ...init,
    headers: {
      'content-type': 'application/json',
      'x-partner-api-key': BREK_PARTNER_API_KEY,
      ...(init?.headers || {})
    }
  });

  const body = await response.json().catch(() => ({}));
  const requestId = response.headers.get('x-request-id') || '';

  return { response, body, requestId };
}
```


path: references/payment-and-billing.md
content: # Payment and Billing

Handle two different payment problems:
- End-user card input for booking.
- B2B settlement for agent-to-agent usage.

## A) End-user card input (booking flow)

Use this state machine:
1. Receive `status=payment_setup_required` with `artifacts.payment.setupUrl`.
2. Return setup URL to human user and ask them to complete setup in Brek portal.
3. Human completes card setup in portal (provider-hosted fields only).
4. User returns and confirms completion (for example, "done").
5. Refresh session state and verify payment method is available.
6. Ask explicit final confirmation.
7. Send `action_confirm_payment_card` with `idempotencyKey`.

Never collect raw PAN/CVV in agent chat.
Agent must not attempt to perform card setup on behalf of user.

## Payment setup prompt template

Use this short prompt when setup is required:

```text
Payment setup is required before booking.
Please open this secure Brek portal link and complete card setup: <setupUrl>
After you finish, reply "done" and I will continue.
```

## B) Agent-to-agent billing (usage settlement)

Implement metering per API call.

## Usage event schema

Store one immutable event per call:

```json
{
  "eventId": "uuid",
  "timestamp": "2026-02-23T10:20:30Z",
  "partnerId": "acme",
  "actorId": "partner_user_001",
  "sessionId": "sess_xxx",
  "endpoint": "POST /events",
  "requestId": "x-request-id from Brek",
  "statusCode": 200,
  "tokensIn": 0,
  "tokensOut": 0,
  "providerCostUsd": 0.0000,
  "markupMultiplier": 1.00,
  "billableAmountUsd": 0.0000
}
```

Use `requestId` + endpoint as dedupe key for retries.

## Settlement models

Choose one model first, keep it simple:
1. Prepaid wallet: partner prepays credits; reject calls when balance is below threshold.
2. Postpaid monthly invoice: aggregate usage events daily; invoice monthly.
3. Hybrid: prepaid for high-risk tenants, postpaid for approved partners.

## Booking-transaction fee (optional)

If your business is booking-led, add a second meter:
- Fixed fee per successful booking.
- Or percentage of booking value.

Record only after final confirmed booking event.

## Reconciliation

Run daily reconciliation job:
1. Group by `partnerId` and UTC date.
2. Sum `billableAmountUsd`.
3. Compare with gateway logs by `x-request-id`.
4. Flag drift above 0.5% for manual review.

## Abuse-resistant billing rules

- Do not charge duplicate idempotent writes.
- Do not charge requests that fail auth (`401/403`).
- Optionally charge for valid but bad input (`400`) only if abuse controls detect intentional spam.


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: suspicious | SkillSpector: clean (LOW)