# Kuan Yin — SDK Usage Guide

> Technical doc 32.16.1.3. Surface defined in
> `@kuanyin/sdk-api/typescript-sdk.ts`.

The TypeScript SDK is the supported way to call Kuan Yin from Node and the edge.
It is a thin, fully-typed layer over the REST/event surface with built-in auth,
retry, rate-limiting, caching, webhooks, and realtime subscriptions.

## Client construction

```ts
import {
  sdkDesignArchitecture,
  sdkCreateClientFactory,
  sdkImplementAuthentication,
} from '@kuanyin/sdk-api';

const auth = sdkImplementAuthentication({
  method: 'oauth2_pkce',
  credentials: {
    clientId: 'my-app',
    codeVerifier: '<43–128 chars>',
    mfaToken: '123456',
  },
  scopes: ['intent:analyze', 'intervention:trigger'],
  tokenRefreshEnabled: true,
  mfaRequired: true,
});
// auth.authenticated, auth.grantedScopes, auth.securityLevel (0–1), auth.warnings
```

### Auth methods (`TsSdkAuthMethod`)

`api_key`, `bearer_token`, `oauth2_code`, `oauth2_client_credentials`,
`oauth2_pkce`, `hmac_signature`, `mutual_tls`. Security level rises with the
method strength and MFA; sensitive scopes (`admin`, `write:users`, `delete`,
`write:config`) require `securityLevel ≥ 0.8` or they are withheld with a
warning. **Credential keys are camelCase** (`clientId`, `clientSecret`,
`redirectUri`, `codeVerifier`, `apiKey`, `mfaToken`).

## Domain clients

Each engine has a typed client builder:

| Builder                            | Engine                      |
| ---------------------------------- | --------------------------- |
| `sdkCreateIntentAnalysisClient`    | precognition intent/emotion |
| `sdkImplementInterventionClient`   | mindful friction            |
| `sdkCreateProtectionClient`        | performer protection        |
| `sdkImplementRehabilitationClient` | rehabilitation              |
| `sdkCreateMeritClient`             | merit & karma               |
| `sdkImplementAnalyticsClient`      | dharma analytics            |

## Resilience primitives

- **Retry** — `sdkImplementRetryLogic` with strategies `none`, `fixed_delay`,
  `linear_backoff`, `exponential_backoff`, `exponential_with_jitter`,
  `circuit_breaker`.
- **Rate limiting** — `sdkCreateRateLimiting` is a token-bucket gate; pass
  `{ clientId, endpoint, currentTokens, lastRefillTimestamp, requestTimestamp, adaptiveLoad }`
  and read `allowed`, `throttled`, `remainingTokens`, `retryAfterMs`,
  `adaptiveCapacity`. Adaptive load shrinks capacity under stress.
- **Errors** — `sdkCreateErrorHandling` maps transport + domain errors to a
  stable taxonomy.

## Webhooks

```ts
import { sdkCreateWebhookHandling } from '@kuanyin/sdk-api';

const hook = sdkCreateWebhookHandling({
  eventType: 'intervention.triggered',
  targetUrl: 'https://hooks.example.com/kuanyin',
  secret: '<≥32 chars>',
  retryPolicy: 'exponential_with_jitter',
  filterExpression: 'severity >= high',
  payloadVersion: 'v1',
});
// hook.registered, hook.verificationStatus ('active' iff HTTPS + 32-char secret)
```

HTTP (non-TLS) or short-secret webhooks register as `pending_verification`/
`error` and are never marked `active`.

## Realtime

`sdkImplementRealtimeSubscriptions` opens a multiplexed subscription over
`/v1/realtime` for shield status, community temperature, and alerts. Pair with
the event bus (`05-event-system.md`) for server-side fan-out.

## Caching

The SDK ships a caching layer keyed by request shape; reputation and health
reads are cached with short TTLs and invalidated on the corresponding
`merit.awarded` / `community.alert` events. See `11-performance-tuning.md`.

All builders are deterministic given their inputs, so SDK behaviour can be unit
tested without a live backend — see `@kuanyin/evaluation` integration tests.
