export { DEFAULT_MACHINE_SIZE, MACHINE_CONFIGS, MACHINE_MAX_INSTANCES, MACHINE_RESOURCE_REQUIREMENTS, MACHINE_SIZES, MachineConfig, MachineResourceRequirements, MachineTierResources, isMachineSize, parseMachineSize, resolveMachineConfig, resolveMachineMaxInstances, resolveMachineResources, resolveMachineTierResources, toPublicMachineSize } from '@sylphx/contract/compute';
import { ManagedWorkspace, CreateWorkspaceInput, ForkWorkspaceInput, WorkspaceCapacitySnapshot, PinWorkspaceInput, PinWorkspaceResult, ReclaimWorkspaceInput, ReclaimWorkspaceResult, ReclaimWorkspaceSubpathInput, ReclaimWorkspaceSubpathResult, SdkBillingPlan, SdkBillingSubscription, BillingCheckoutRequest, BillingCheckoutResponse, BillingPortalRequest, BillingPortalResponse, BillingBalanceResponse, BillingUsageResponse, ConsentHistoryResponse, SdkConsentType, LinkAnonymousConsentsRequest, UserConsent as UserConsent$1, AIModel as AIModel$1, GetModelsResponse, GetRateLimitResponse, GetUsageResponse, ReferralLeaderboardEntry, ReferralLeaderboardResponse, RedeemResponse, GetCodeResponse, GetStatsResponse, ReferralRewardDefaults as ReferralRewardDefaults$1, RegenerateCodeResponse as RegenerateCodeResponse$1, RuntimeWebhookDelivery, OAuthTokenResponse, OAuthTokenErrorResponse, OAuthClientCredentialsResponse, LogoutInput, RefreshTokenInput, RefreshTokenResult, OAuthIntrospectResponse, PlatformPasswordChangeRequest, PlatformPasswordChangeResponse, PlatformPasswordSetRequest, PlatformPasswordSetResponse, PlatformPasswordStatusResponse, PlatformSessionRenameRequest, PlatformSessionRenameResponse, PlatformSessionRevokeAllResponse, PlatformSessionRevokeRequest, PlatformSessionRevokeOtherResponse, PlatformSessionRevokeResponse, PlatformSessionsListResponse, AuthUserDeleteRequest, AuthUserDeleteResponse, AuthUserExportResponse, DeviceApproveRequest, DeviceApproveResponse, DeviceDenyRequest, DeviceDenyResponse, DeviceInitResponse, DeviceInitRequest, DevicePollResponse, LoginRequest as LoginRequest$1, LoginResponse as LoginResponse$1, UserFullProfile as UserFullProfile$1, RegisterRequest as RegisterRequest$1, RegisterResponse as RegisterResponse$1, ResendEmailVerificationRequest as ResendEmailVerificationRequest$1, ResendEmailVerificationResponse as ResendEmailVerificationResponse$1, AuthTokensResponse, TwoFactorVerifyRequest as TwoFactorVerifyRequest$1, PlatformAuditQueryRequest, PlatformAuditQueryResponse, PlatformRateLimitStatusRequest, PlatformRateLimitStatusResponse, PlatformRateLimitStrategiesListRequest, PlatformRateLimitStrategiesListResponse, PlatformRateLimitStrategyDeleteRequest, PlatformRateLimitStrategyDeleteResponse, PlatformRateLimitStrategyUpsertRequest, PlatformRateLimitStrategyUpsertResponse, File as File$1, UploadId, FileId, TakedownFileRequest, TakedownFileResult, FileVersion, FileVersionId, MachineSize, DurableWorkGetTaskRunResponse, DurableWorkTaskRunStep, CreateOrgInput as CreateOrgInput$1, InviteMemberInput as InviteMemberInput$1, OrgSdkRole, OrgInvitation, OrgMember, MembershipInfo, Organization, UpdateOrgInput as UpdateOrgInput$1, UserOrganizationMembership, UserOrganizationsResponse, SandboxCapabilitiesReport, PublishArtifactRequest, ArtifactResult, ListArtifactsResult, ArtifactDetail, ArtifactContent, DeleteArtifactResult, RestoreArtifactResult, ReshareArtifactResult, RenderRequest, RenderResult, GrantRequest, Grant, BalanceSummary, ReserveRequest, Reservation, ConsumeRequest, LedgerEntry, ReleaseRequest, VoidGrantRequest, CreateDeviceSessionInput, DeviceSessionResult, ListDeviceSessionsQuery, ListDeviceSessionsResult, InstallDeviceSessionAppInput, InstallDeviceSessionAppResult, DeviceSessionInput, DeviceSessionInputResult, LaunchDeviceSessionAppInput, LaunchDeviceSessionAppResult, DeviceSessionScreenshotResult, DeviceSessionLogcatQuery, DeviceSessionLogcatResult, DeviceSessionStreamConnectInput, DeviceSessionStreamConnectResult, DeleteDeviceSessionResult, DurableWorkRunCompletionMode, DistributedRun, DistributedRunShard, DistributedRunAggregateStatus } from '@sylphx/contract';
export { ArtifactResult, BillingBalanceResponse as BalanceResponse, CI_LINUX_RUNNER_SIZES, CI_MACOS_RUNNER_SIZES, CI_RUNNER_PROFILES, BillingCheckoutRequest as CheckoutRequest, BillingCheckoutResponse as CheckoutResponse, CiLinuxRunnerSize, CiMacosRunnerSize, CiRunnerPlatform, CiRunnerProfile, CiRunnerProfileId, CiRunnerWorkflowRunsOn, CreateDeviceSessionInput, CreateWorkspaceInput, DeleteDeviceSessionResult, DeviceSessionInput, DeviceSessionInputResult, DeviceSessionLogcatQuery, DeviceSessionLogcatResult, DeviceSessionResult, DeviceSessionScreenshotResult, DeviceSessionStreamConnectInput, DeviceSessionStreamConnectResult, DistributedRun, DistributedRunShard, DurableWorkRunCompletionMode, FileId, FileVersion, FileVersionId, FileVisibility, ForkWorkspaceInput, InstallDeviceSessionAppInput, InstallDeviceSessionAppResult, LaunchDeviceSessionAppInput, LaunchDeviceSessionAppResult, ListDeviceSessionsQuery, ListDeviceSessionsResult, Organization, PinWorkspaceInput, BillingPortalRequest as PortalRequest, BillingPortalResponse as PortalResponse, PublishArtifactRequest, ReclaimWorkspaceInput, ReclaimWorkspaceSubpathInput, RenderRequest, RenderResult, SandboxCapabilitiesReport, SignedUrlDisposition, File as StorageFile, UploadId, BillingUsageResponse as UsageResponse, WorkspaceCapacitySnapshot, formatCiRunnerWorkflowRunsOn, getCiRunnerProfileById } from '@sylphx/contract';

/**
 * Functions Admin namespace — Platform-plane function-bundle admin
 * (ADR-089 Phase 3a, Σ1 SoC rename).
 *
 * Function-bundle download for the Sylphx-internal edge-runtime
 * orchestrator. Unlike the sibling Platform namespaces this one
 * authenticates with a shared `internalToken` (service-internal secret)
 * rather than a platform-audience JWT, because the caller is another
 * Sylphx service (the edge-runtime that spawns V8 isolates to invoke
 * user functions) not an end user. The BaaS runtime
 * (`apps/runtime/src/server/runtime/routes/functions/admin.ts`)
 * owns the object-storage implementation — Platform callers dogfood through
 * this SDK surface and never touch backend storage credentials.
 *
 * Phase Σ1 SoC rename: this was previously exported out of `./auth`
 * as `functions` (re-exported at the package root as `functionsInternal`)
 * and spoke to `/auth/platform-functions/*`. The server-side surface
 * moved to `/v1/functions/admin/*` (function bundle admin is a
 * cross-cutting BaaS primitive — function bundle storage — not an auth
 * verb); this SDK module nests the admin verbs under
 * `functions.admin.*` at the package root.
 */
interface PlatformFunctionsDownloadBundleResult {
    readonly code: string;
}

/**
 * Realtime Admin namespace — Platform-plane channel-registration
 * admin (ADR-089 Phase 3a, Σ1 SoC rename).
 *
 * Channel-registration admin for the Platform plane (Console / CLI
 * operators). Like the sibling device / platform-sessions / platform-
 * password / platform-user namespaces, these endpoints accept a
 * `baseUrl + accessToken` rather than a `SylphxConfig` — the caller
 * authenticates with a platform-audience JWT, not a customer-app
 * `pk_`/`sk_` pair. The BaaS runtime
 * (`apps/runtime/src/server/runtime/routes/realtime/admin.ts`)
 * verifies the token against audience `'platform'`, confirms
 * `verifyProjectAccess(userId, projectId)`, and owns the channel
 * registration operations.
 *
 * Phase Σ1 SoC rename: this was previously exported out of `./auth`
 * as `realtime` (re-exported at the package root as `realtimeAdmin`)
 * and spoke to `/auth/platform-realtime/*`. The server-side surface
 * moved to `/v1/realtime/admin/*` (realtime admin is a cross-cutting
 * BaaS primitive, not an auth verb); this SDK module nests the admin
 * verbs under `realtime.admin.channels.*` at the package root so it
 * no longer collides with the customer-app `realtimeEmit` /
 * `getRealtimeHistory` data-plane surface.
 *
 * For the Sylphx platform itself, `baseUrl` is
 * `https://your-app.api.sylphx.com/v1` (configurable via SYLPHX_BAAS_URL
 * for dev/staging).
 */
interface PlatformRealtimeChannel {
    readonly name: string;
    readonly activeConnections: number;
    readonly messagesPerHour: number;
    readonly status: 'active' | 'empty';
}
interface PlatformRealtimeStatusResult {
    readonly available: boolean;
}
interface PlatformRealtimeListChannelsResult {
    readonly channels: readonly PlatformRealtimeChannel[];
    readonly count: number;
}
interface PlatformRealtimeCreateChannelResult {
    readonly name: string;
}
interface PlatformRealtimeDeleteChannelResult {
    readonly success: boolean;
}

/**
 * Database Pricing Configuration (SSOT)
 *
 * All database billing constants centralized here.
 * Used by billing calculations, usage tracking, and cost display.
 *
 * Pricing Strategy:
 * - Self-hosted infra on AX162-R: flat ~$270/month
 * - Competitive pricing with 75-99% margins
 *
 * Customer Prices (updated for self-hosted, 2026-02):
 * - Compute: $0.08/hour (25% below Neon $0.106/hr)
 * - Storage: $0.25/GB-month (29% below Neon $0.35/GB)
 * - Transfer: $0.09/GB (matches Supabase)
 */
/** Price per compute hour in microdollars ($0.08/hour = 80,000 microdollars) */
declare const COMPUTE_PRICE_PER_HOUR_MICRODOLLARS = 80000;
/** Free compute hours per month (platform free tier) */
declare const FREE_COMPUTE_HOURS = 3;
/** Price per GB-month in microdollars ($0.25/GB-month = 250,000 microdollars) */
declare const STORAGE_PRICE_PER_GB_MONTH_MICRODOLLARS = 250000;
/** Free storage in GB (256 MB) */
declare const FREE_STORAGE_GB = 0.25;
/** Price per GB data transfer ($0.09/GB = 90,000 microdollars) */
declare const TRANSFER_PRICE_PER_GB_MICRODOLLARS = 90000;
/** KV free storage in GB (256 MB) */
declare const KV_FREE_STORAGE_GB = 0.25;
/** Hours per month (AWS/GCP standard for billing) */
declare const HOURS_PER_MONTH = 730;

/**
 * Referrals Configuration (SSOT)
 *
 * Single source of truth for referral system configuration.
 * Used by: referral router, SDK referral endpoints
 */
/** Default points awarded per successful referral */
declare const DEFAULT_POINTS_REWARD = 100;
/** Number of months the referral discount is valid */
declare const DISCOUNT_DURATION_MONTHS = 3;
/** Default discount percentage */
declare const DISCOUNT_PERCENT = 20;
/** Premium trial days from referral */
declare const PREMIUM_TRIAL_DAYS = 7;
/**
 * Generate a cryptographically secure referral code
 *
 * Uses crypto.getRandomValues for uniform random bytes (0-255).
 * Since REFERRAL_CODE_CHARS has exactly 32 characters and 256 / 32 = 8,
 * byte % 32 produces perfectly uniform distribution with zero modulo bias.
 *
 * Entropy: 8 chars * log2(32) = 40 bits (~1.1 trillion possible codes)
 *
 * Format: 8 uppercase alphanumeric characters (excluding ambiguous: 0, O, I, L, 1)
 */
declare function generateReferralCode(): string;

declare function getErrorMessage$1(error: unknown, fallback?: string): string;
interface ErrorDetails$1 {
    message: string;
    code?: string;
    name?: string;
    stack?: string;
    status?: number;
    cause?: unknown;
}
declare function getErrorDetails$1(error: unknown, fallbackMessage?: string): ErrorDetails$1;

/**
 * Sylphx Connection URL — Single Source of Truth (ADR-123)
 *
 * Implements the canonical connection string format defined in ADR-055 §5.
 * This module is the SDK-owned SSOT per ADR-123 (SDK/application boundary).
 * Consuming applications MUST import from `@sylphx/sdk` rather than duplicating
 * this logic.
 *
 * Hosted format:
 *   sylphx://{credential}@{tenant-slug}.api.sylphx.com[:port][/v{version}]
 *
 * Custom/self-hosted domains are also accepted as long as the first DNS label
 * is the tenant slug.
 *
 * Examples:
 *   sylphx://pk_prod_f19e5cdc3cc54f7ff81bdc26ec5bfbad@bold-river-a1b2c3.api.sylphx.com
 *   sylphx://sk_prod_5120bfeb5120bfeb5120bfeb5120bfeb@bold-river-a1b2c3.api.sylphx.com/v1
 *   sylphx://pk_dev_abc12345abc12345abc12345abc12345@calm-peak-z9x4d5.sylphx.dev
 *
 * Invariants:
 *   - Protocol is always `sylphx:` (no exceptions)
 *   - Credential matches `(pk|sk)_(dev|stg|prod|prev)(_{ref})?_{hex}`
 *   - Host's first DNS label is the resource slug (validated by slug regex)
 *   - `apiBaseUrl` is always HTTPS, with `/v{version}` appended (default `v1`)
 *
 * Parsing uses the WHATWG `URL` constructor — custom regex parsing is banned
 * because it is notoriously brittle (ADR-055 §5.3).
 */
type ConnectionCredentialType = 'pk' | 'sk';
type ConnectionEnv = 'dev' | 'stg' | 'prod' | 'prev';
interface ParsedConnectionUrl {
    /** Full credential string, e.g. `pk_prod_f19e...` */
    readonly credential: string;
    /** Credential kind — `pk` (publishable) or `sk` (secret) */
    readonly credentialType: ConnectionCredentialType;
    /** Target environment encoded in the credential */
    readonly env: ConnectionEnv;
    /** First DNS label of the host — the resource slug (e.g. `bold-river-a1b2c3`) */
    readonly slug: string;
    /** Full host including port when present (e.g. `bold-river-a1b2c3.api.sylphx.com`) */
    readonly host: string;
    /** Ready-to-use SDK base URL, always HTTPS (e.g. `https://bold-river-a1b2c3.api.sylphx.com/v1`) */
    readonly apiBaseUrl: string;
}
interface BuildConnectionUrlInput {
    /** Credential — must match the credential format regex */
    readonly credential: string;
    /** Resource slug — validated DNS label */
    readonly slug: string;
    /** SDK API domain suffix; defaults to `api.sylphx.com`. Use `sylphx.dev` for dev. */
    readonly domain?: string;
    /** API version suffix, e.g. `v1`. Defaults to `v1`. Pass empty string to omit. */
    readonly version?: string;
}
/**
 * Credential format — opaque token with type, env, optional project ref, and
 * hex payload. Ref-scoped credentials are emitted by Platform app-env injection;
 * legacy credentials without the ref remain valid for existing deploys.
 */
declare const CREDENTIAL_REGEX: RegExp;
declare class InvalidConnectionUrlError extends Error {
    readonly code: "INVALID_CONNECTION_URL";
    constructor(message: string);
}
/**
 * Build a canonical Sylphx connection URL.
 *
 * Throws `InvalidConnectionUrlError` if any component is malformed.
 */
declare function buildConnectionUrl(input: BuildConnectionUrlInput): string;
/**
 * Parse a Sylphx connection URL into its structured components.
 *
 * Throws `InvalidConnectionUrlError` on any structural problem.
 */
declare function parseConnectionUrl(url: string): ParsedConnectionUrl;

/**
 * SDK Configuration — ADR-055 Connection URL API
 *
 * v0.5.0: The primary entry point is `createClient(url)` which accepts
 * a `sylphx://` connection URL. The old `createConfig({ ref, publicKey })`
 * API is removed.
 *
 * @example
 * ```typescript
 * import { createClient } from '@sylphx/sdk'
 *
 * const sylphx = createClient(process.env.SYLPHX_URL!)
 * // Parses: sylphx://pk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
 * ```
 */

/**
 * SDK Configuration object — immutable, frozen.
 *
 * Created by `createClient()` or `createServerClient()`.
 * Passed to all pure SDK functions (`track()`, `signIn()`, etc.).
 */
interface SylphxConfig {
    /** The credential string (pk_* or sk_*) */
    readonly credential: string;
    /** Credential type: 'pk' (publishable) or 'sk' (secret) */
    readonly credentialType: 'pk' | 'sk';
    /** Target environment: dev, stg, prod, or prev */
    readonly env: 'dev' | 'stg' | 'prod' | 'prev';
    /** Resource slug (first DNS label), e.g. 'bold-river-a1b2c3' */
    readonly slug: string;
    /** Pre-computed API base URL, e.g. 'https://bold-river-a1b2c3.api.sylphx.com/v1' */
    readonly baseUrl: string;
    /** Optional access token for authenticated requests */
    readonly accessToken?: string;
    /**
     * Secret key — populated when credentialType is 'sk'.
     * Backward-compatible alias for `credential` when credential is sk_*.
     */
    readonly secretKey?: string;
    /**
     * Publishable key — populated when credentialType is 'pk'.
     * Backward-compatible alias for `credential` when credential is pk_*.
     */
    readonly publicKey?: string;
    /**
     * @deprecated Use `slug`. Backward-compatible alias.
     */
    readonly ref: string;
}
/**
 * Explicit components input — alternative to connection URL string.
 *
 * For multi-tenant apps or cases where components are stored separately.
 */
interface SylphxClientInput {
    /** Resource slug, e.g. 'bold-river-a1b2c3' */
    slug?: string;
    /** Publishable key (pk_*) — client-safe */
    publicKey?: string;
    /** Secret key (sk_*) — server-side only */
    secretKey?: string;
    /** Optional access token */
    accessToken?: string;
    /** API domain override (default: api.sylphx.com) */
    domain?: string;
    /**
     * @deprecated Use `slug`. Accepted for backward compatibility during migration.
     */
    ref?: string;
    /**
     * @deprecated Use `domain`. Accepted for backward compatibility during migration.
     */
    platformUrl?: string;
}
/**
 * Create a Sylphx client from a connection URL or explicit components.
 *
 * This is the primary SDK entry point for client-side (browser) usage.
 * Accepts a `sylphx://` connection URL or an explicit components object.
 *
 * @example Connection URL (recommended)
 * ```typescript
 * const sylphx = createClient(process.env.NEXT_PUBLIC_SYLPHX_URL!)
 * // Parses: sylphx://pk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
 * ```
 *
 * @example Explicit components
 * ```typescript
 * const sylphx = createClient({
 *   slug: 'bold-river-a1b2c3',
 *   publicKey: 'pk_prod_f19e...',
 * })
 * ```
 */
declare function createClient(input: string | SylphxClientInput): SylphxConfig;
/**
 * Create a Sylphx server client from a connection URL or explicit components.
 *
 * Equivalent to `createClient()` but validates that a secret key (sk_*) is provided.
 * Use this for server-side operations that require elevated permissions.
 *
 * @example Connection URL (recommended)
 * ```typescript
 * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)
 * // Parses: sylphx://sk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com
 * ```
 *
 * @example Explicit components
 * ```typescript
 * const sylphx = createServerClient({
 *   slug: 'bold-river-a1b2c3',
 *   secretKey: 'sk_prod_5120...',
 * })
 * ```
 */
declare function createServerClient(input: string | SylphxClientInput): SylphxConfig;
/**
 * Create a new config with an updated access token.
 *
 * Returns a new frozen config — does not mutate the original.
 *
 * @example
 * ```typescript
 * const authenticatedConfig = withToken(config, 'access_token_here')
 * ```
 */
declare function withToken(config: SylphxConfig, accessToken: string): SylphxConfig;
/**
 * @deprecated Use `createClient()` or `createServerClient()` instead.
 * This function is kept temporarily for migration but will be removed.
 */
type SylphxConfigInput = string | SylphxClientInput;
/**
 * @deprecated Use `createClient()` instead. See ADR-055.
 */
declare const createConfig: typeof createClient;

/**
 * CSV utilities for browser and server SDK consumers.
 */
/**
 * Escape a CSV field to handle commas, quotes, and newlines.
 *
 * Handles null/undefined by returning an empty field. Wraps values containing
 * RFC 4180 special characters in double quotes and escapes internal quotes.
 */
declare function escapeCsvField(value: string | null | undefined): string;

/**
 * Formatting Utilities
 *
 * Shared formatting functions for consistent display across the project.
 */
/**
 * Calculate percentage with consistent rounding.
 * SSOT for all success rate, completion rate calculations.
 *
 * @param count - The numerator (e.g., successful count)
 * @param total - The denominator (e.g., total count)
 * @param decimals - Number of decimal places (default: 2)
 * @returns Percentage value (0-100)
 *
 * @example
 * ```ts
 * calculatePercentage(75, 100) // 75
 * calculatePercentage(1, 3)    // 33.33
 * calculatePercentage(0, 0)    // 100 (safe division)
 * ```
 */
declare function calculatePercentage(count: number, total: number, decimals?: number): number;
/**
 * Format microdollars to currency string
 * @param microdollars Amount in microdollars (1 dollar = 1,000,000 microdollars)
 * @param options Intl.NumberFormat options
 */
declare function formatMicrodollars(microdollars: number, options?: Intl.NumberFormatOptions): string;
/**
 * Format cents to currency string
 * @param cents Amount in cents (100 cents = 1 dollar)
 *
 * @example
 * ```ts
 * formatCents(1999)  // "$19.99"
 * formatCents(100)   // "$1.00"
 * ```
 */
declare function formatCents(cents: number): string;
/**
 * Format dollars to currency string with optional compact notation
 * @param amount Amount in dollars
 * @param compact Use compact notation for large amounts (default: false)
 *
 * @example
 * ```ts
 * formatCurrency(1999.99)              // "$1,999.99"
 * formatCurrency(1999.99, true)        // "$2.0K"
 * formatCurrency(1999.99, { currency: 'EUR' }) // "€1,999.99"
 * formatCurrency(1999.99, { compact: true })   // "$2.0K"
 * ```
 *
 * Second argument accepts either a bare `boolean` (back-compat for
 * the historical `compact` flag) or an options object with
 * `{ currency, compact }`. The options form is required for any UI
 * surface that displays multi-currency amounts (billing, invoices,
 * usage statements) — previously two local copies of this function
 * lived in `billing-management.tsx` to work around the missing
 * currency parameter.
 */
declare function formatCurrency(amount: number, optsOrCompact?: boolean | {
    compact?: boolean;
    currency?: string;
    decimals?: number;
}): string;
/**
 * Format percentage with sign for trend display
 * @param value Percentage value (not multiplied by 100)
 *
 * @example
 * ```ts
 * formatPercent(12.5)   // "+12.5%"
 * formatPercent(-5.2)   // "-5.2%"
 * formatPercent(0)      // "+0.0%"
 * ```
 */
declare function formatPercent(value: number): string;
/**
 * Format number with abbreviated suffix (K, M, B) or compact notation
 * @param num Number to format
 * @param compact Use Intl compact notation (default: false, uses K/M/B suffix)
 *
 * @example
 * ```ts
 * formatNumber(1234)           // "1,234"
 * formatNumber(1234567)        // "1.2M"
 * formatNumber(1234, true)     // "1.2K" (Intl compact)
 * ```
 */
declare function formatNumber(num: number, compact?: boolean): string;
/**
 * Format duration in milliseconds to human-readable string.
 * SSOT for latency display in traces, performance, and monitoring.
 *
 * @param ms Duration in milliseconds
 * @returns Formatted string (e.g., "<1ms", "42ms", "1.23s")
 *
 * @example
 * ```ts
 * formatDuration(0.5)    // "<1ms"
 * formatDuration(42)     // "42ms"
 * formatDuration(1500)   // "1.50s"
 * ```
 */
declare function formatDuration(ms: number): string;
/**
 * Format bytes to human-readable string
 * @param bytes Number of bytes
 * @param decimals Number of decimal places (default: 1)
 */
declare function formatBytes(bytes: number | null | undefined, decimals?: number): string;
/** Badge variant type for consistency */
type BadgeVariant = 'default' | 'secondary' | 'success' | 'warning' | 'error' | 'outline';
/**
 * Get billing status badge variant.
 * Pure function — no side effects, deterministic output.
 *
 * @param status Billing account status
 * @returns Badge variant for display
 */
declare function getBillingStatusVariant(status: string): BadgeVariant;
/**
 * Get invoice status badge variant.
 * Pure function — no side effects, deterministic output.
 *
 * @param status Invoice status
 * @returns Badge variant for display
 */
declare function getInvoiceStatusVariant(status: string): BadgeVariant;
/**
 * Format date for display
 * @param date Date to format (null returns fallback)
 * @param options Intl.DateTimeFormat options
 * @param fallback Value to return when date is null (default: '-')
 */
declare function formatDate(date: Date | string | null, options?: Intl.DateTimeFormatOptions, fallback?: string): string;
/**
 * Format date with time for display
 * @param date Date to format (null returns fallback)
 * @param options Override options
 * @param fallback Value to return when date is null (default: '-')
 */
declare function formatDateTime(date: Date | string | null, options?: Intl.DateTimeFormatOptions, fallback?: string): string;
/**
 * Format relative time (e.g., "2 hours ago")
 *
 * Uses native Intl.RelativeTimeFormat for proper localization.
 *
 * @param date Date to format (null returns 'Never')
 */
declare function formatRelativeTime(date: Date | string | null): string;
/**
 * Format relative time in compact form (e.g., "2h ago", "3d ago").
 * SSOT for dense UI contexts: tables, feeds, badges.
 *
 * Uses short suffixes (s/m/h/d/w) instead of Intl.RelativeTimeFormat words.
 * For prose contexts, use {@link formatRelativeTime} instead.
 *
 * @param date Date to format (null returns 'Never')
 *
 * @example
 * ```ts
 * formatRelativeTimeShort(new Date())               // "Just now"
 * formatRelativeTimeShort('2024-01-01T00:00:00Z')   // "3d ago"
 * formatRelativeTimeShort(null)                      // "Never"
 * ```
 */
declare function formatRelativeTimeShort(date: Date | string | null): string;
/**
 * Format month and year (e.g., "January 2024")
 * SSOT for billing period display, invoice headers.
 * @param date Date to format (null returns fallback)
 * @param fallback Value to return when date is null
 */
declare function formatMonthYear(date: Date | string | null, fallback?: string): string;
/**
 * Format time only (e.g., "2:30 PM")
 * SSOT for log timestamps, activity feeds.
 * @param date Date to format (null returns fallback)
 * @param fallback Value to return when date is null
 */
declare function formatTime(date: Date | string | null, fallback?: string): string;

/**
 * Safely parse a JSON string, returning a fallback value on failure instead of throwing.
 *
 * Use this when malformed input is a normal (non-exceptional) case — e.g. parsing
 * user-provided data, localStorage values, or Redis cache entries where the caller
 * simply wants a default on failure.
 *
 * For cases where parse failure is truly exceptional and the caller needs to handle
 * the error explicitly, use a standard try-catch with proper logging instead.
 */
declare function safeJsonParse<T = unknown>(input: string, fallback?: T): T | null;

/**
 * Utility Functions
 */
/**
 * Get the base URL for API requests
 *
 * Use cases:
 * - getBaseUrl(): For relative URLs in browser, absolute in SSR (tRPC, API calls)
 * - getBaseUrl('origin'): For absolute URLs that need the actual origin (auth, sharing)
 *
 * Priority: NEXT_PUBLIC_APP_URL > localhost
 */
declare function getBaseUrl(mode?: 'relative' | 'origin'): string;
/**
 * Escape HTML special characters to prevent XSS
 *
 * Uses single-pass regex replacement for efficiency.
 */
declare function escapeHtml(str: string): string;
/**
 * Generate a URL-friendly slug from text
 *
 * @param text - Text to convert to slug
 * @param maxLength - Optional maximum length (default: no limit)
 * @returns Lowercase slug with hyphens
 *
 * @example
 * generateSlug('My Awesome App') // 'my-awesome-app'
 * generateSlug('Hello   World!') // 'hello-world'
 * generateSlug('My Org Name', 48) // 'my-org-name' (max 48 chars)
 */
declare function generateSlug(text: string, maxLength?: number): string;

/**
 * User Agent Parsing Utilities
 *
 * Extracts browser, OS, and device type from user agent strings.
 * Simple implementation - no external dependencies.
 */
interface ParsedUserAgent {
    browser: string | null;
    os: string | null;
    deviceType: 'desktop' | 'mobile' | 'tablet' | null;
}
/**
 * Parse a user agent string to extract browser, OS, and device type.
 * Returns null values if unable to determine.
 */
declare function parseUserAgent(ua: string): ParsedUserAgent;

type WorkspaceRecord = ManagedWorkspace;

declare function listWorkspaces(config: SylphxConfig): Promise<readonly WorkspaceRecord[]>;
declare function getWorkspace(config: SylphxConfig, workspaceId: string): Promise<WorkspaceRecord>;
declare function getWorkspaceCapacity(config: SylphxConfig, workspaceId: string): Promise<WorkspaceCapacitySnapshot>;
declare function createWorkspace(config: SylphxConfig, input: CreateWorkspaceInput): Promise<WorkspaceRecord>;
declare function forkWorkspace(config: SylphxConfig, sourceWorkspaceId: string, input?: ForkWorkspaceInput): Promise<WorkspaceRecord>;
declare function pinWorkspace(config: SylphxConfig, workspaceId: string, input?: PinWorkspaceInput): Promise<PinWorkspaceResult>;
declare function reclaimWorkspace(config: SylphxConfig, workspaceId: string, input?: ReclaimWorkspaceInput): Promise<ReclaimWorkspaceResult>;
declare function reclaimWorkspaceSubpath(config: SylphxConfig, workspaceId: string, input: ReclaimWorkspaceSubpathInput): Promise<ReclaimWorkspaceSubpathResult>;
declare function deleteWorkspace(config: SylphxConfig, workspaceId: string): Promise<void>;

/**
 * Authentication Configuration (SSOT)
 *
 * Single source of truth for authentication-related constants.
 * Used by: validation schemas, auth forms, password policies
 */
/** Minimum password length */
declare const MIN_PASSWORD_LENGTH = 8;
/** Maximum password length */
declare const MAX_PASSWORD_LENGTH = 128;
/** Password requirements for display in UI */
declare const PASSWORD_REQUIREMENTS: {
    readonly minLength: 8;
    readonly maxLength: 128;
    readonly description: "Must be at least 8 characters";
    readonly placeholder: "Min. 8 characters";
};

/**
 * Billing Configuration (SSOT)
 *
 * Single source of truth for billing-related configuration.
 * Used by: billing pages, usage tracking, invoicing
 */
/** Bytes per gigabyte — use instead of hardcoding 1024*1024*1024 */
declare const BYTES_PER_GB: number;
/** Microdollars per cent ($0.01 = 10,000 microdollars) */
declare const MICRODOLLARS_PER_CENT = 10000;
/** Invoice payment due after billing period ends (days) */
declare const INVOICE_DUE_DAYS = 15;
/**
 * Billing metrics per service
 * These are user-facing metric names (NOT technical terms like 'commands')
 */
declare const SERVICE_METRICS: {
    readonly kv: {
        readonly operations: "operations";
        readonly storage: "storage";
    };
    readonly realtime: {
        readonly messages: "messages";
        readonly connections: "connections";
    };
    readonly ai: {
        readonly tokens: "tokens";
    };
    readonly email: {
        readonly emails: "emails";
        readonly marketingEmails: "marketing_emails";
    };
    readonly notifications: {
        readonly sends: "sends";
    };
    readonly analytics: {
        readonly events: "events";
        readonly forwarding: "forwarding";
    };
    readonly storage: {
        readonly capacity: "capacity";
        readonly uploads: "uploads";
        readonly egress: "egress";
    };
    readonly auth: {
        readonly mau: "mau";
    };
    readonly flags: {
        readonly evaluations: "evaluations";
    };
    readonly consent: {
        readonly records: "records";
    };
    readonly referrals: {
        readonly conversions: "conversions";
    };
    readonly engagement: {
        readonly operations: "operations";
    };
    readonly billing: {
        readonly subscriptions: "subscriptions";
        readonly usageRecords: "usage_records";
    };
    readonly search: {
        readonly documents: "documents";
        readonly searches: "searches";
    };
    readonly webhooks: {
        readonly deliveries: "deliveries";
    };
    readonly monitoring: {
        readonly errors: "errors";
    };
    readonly jobs: {
        readonly invocations: "invocations";
        readonly cronSchedules: "cron_schedules";
    };
    readonly database: {
        readonly computeSeconds: "compute_seconds";
        readonly storage: "storage";
        readonly dataTransferBytes: "data_transfer_bytes";
    };
    readonly deploy: {
        readonly buildMinutes: "build_minutes";
    };
};
/** Active vCPU rate: $0.024/hr = $0.0004/min = 400 microdollars/min (ADR-034) */
declare const COMPUTE_VCPU_ACTIVE_RATE_MICRODOLLARS = 400;
/** Idle vCPU rate: $0.003/hr = $0.00005/min = 50 microdollars/min — 1/8 of active (ADR-034) */
declare const COMPUTE_VCPU_IDLE_RATE_MICRODOLLARS = 50;
/** RAM rate: $0.010/GB-hr = $0.000167/GB-min = 167 microdollars/GB-min (ADR-034) */
declare const COMPUTE_RAM_RATE_MICRODOLLARS = 167;
/**
 * Build minute prices by machine type in microdollars per minute (ADR-034).
 *
 * `standard` repriced $0.014 → $0.006 per ADR-2571 to match the GitHub Actions
 * Jan-2026 Linux floor and resolve the SSOT conflict with the billed DB row
 * (migration 0062 was $0.008). The DB row is superseded to $0.006 in the same
 * change (migration 0084, effective 2026-07-20).
 */
declare const BUILD_MINUTE_PRICES: Record<string, number>;
/** Build minute size multipliers for quota tracking (ADR-034) */
declare const BUILD_SIZE_MULTIPLIERS: Record<string, number>;
/** Build minutes included per month by plan tier (ADR-034) */
declare const BUILD_MINUTES_INCLUDED: Record<string, number>;
/**
 * @deprecated Use BUILD_MINUTE_PRICES.standard instead (ADR-034).
 * Kept for backward compatibility with existing billing pipelines.
 *
 * CI compute-minute price in microdollars.
 * Now references the standard build machine rate from ADR-034.
 */
declare const CI_BUILD_MINUTE_PRICE_MICRODOLLARS: number;
/**
 * @deprecated Use BUILD_MINUTES_INCLUDED[plan] instead (ADR-034).
 * Kept for backward compatibility. Maps to the `team` tier as the
 * previous default (2,000 free minutes).
 */
declare const CI_FREE_MINUTES_PER_MONTH: number;
/**
 * Size multipliers for CI compute-minute accounting (legacy GitHub labels).
 *
 * Keys are **GitHub Actions runner labels** (not build machine type names).
 * These labels arrive on workflow_job webhooks and are stored as-is in
 * githubCiJobs.resourceClass. The billing pipeline maps them to multipliers
 * here; the build pipeline maps them to BuildMachineType via
 * normalizeBuildMachineType() in build-machine.ts.
 *
 * @see BUILD_SIZE_MULTIPLIERS for canonical build machine multipliers (ADR-034).
 */
declare const CI_SIZE_MULTIPLIERS: Record<string, number>;
/** macOS runner per-size multipliers (ADR-035: per-tier billing) */
declare const CI_MACOS_SIZE_MULTIPLIERS: Record<string, number>;
/** @deprecated Use CI_MACOS_SIZE_MULTIPLIERS[size] instead. */
declare const CI_MACOS_MULTIPLIER: number;
type ServiceMetrics = typeof SERVICE_METRICS;
type KvMetric = keyof typeof SERVICE_METRICS.kv;
type RealtimeMetric = keyof typeof SERVICE_METRICS.realtime;
/** Credit expiry period in months */
declare const CREDIT_EXPIRY_MONTHS = 12;
/** Maximum payment retry attempts before suspending account */
declare const MAX_PAYMENT_ATTEMPTS = 3;
/** Roles that can access billing pages */
declare const BILLING_ALLOWED_ROLES: readonly ["super_admin", "admin", "billing"];
type BillingAllowedRole = (typeof BILLING_ALLOWED_ROLES)[number];
/** Check if a role has billing access */
declare function hasBillingAccess(role: string): boolean;

/**
 * Console SDK Key Utilities
 *
 * The Platform Console is Customer Zero — it uses the exact same ADR-055 pure
 * entropy key format as every other customer.
 *
 * No special key construction. No legacy app_* format. No special lookup paths.
 *
 * Keys are set via environment variables, just like any customer app:
 *   NEXT_PUBLIC_SYLPHX_KEY   = pk_prod_97ef4f90c48e7378b0f00a1e2cb8c15e
 *   SYLPHX_SECRET_KEY        = sk_prod_edea406b7988099f5826c143b0f6bd94...
 */
/** Console project slug — must match bootstrap.ts PLATFORM_CONSOLE_APP.slug */
declare const CONSOLE_APP_SLUG = "sylphx-console";
/**
 * Determine environment prefix from build/runtime environment.
 * Used by sdk-cookies.ts for cookie naming until it migrates to SDK-native getCookieNames().
 * NOTE: still actively consumed by sdk-cookies.ts and sdk-login.ts — remove only after
 * those modules parse the env prefix from NEXT_PUBLIC_SYLPHX_KEY directly.
 */
declare function getEnvPrefix(): 'dev' | 'stg' | 'prod';

/**
 * Platform Plan Tiers — SSOT
 *
 * Defines the Sylphx Platform plan tier system (ADR-034).
 * NOTE: This is for *platform* plans (what the organization pays Sylphx for).
 *       It is separate from `plans` (which are in-app subscription products
 *       that customers create for their own end-users).
 *
 * All prices in cents (USD). Credits in microdollars (1 USD = 1,000,000 µ$).
 *
 * ADR-034 tiers: Free → Pro ($20/mo) → Team ($20/user/mo) → Enterprise (custom)
 * The 'starter' tier is deprecated but kept in the type union for backward
 * compatibility with existing database rows and API consumers.
 */
/**
 * Platform plan identifiers.
 * 'starter' is deprecated (ADR-034) — retained for backward compat with existing records.
 */
type PlatformPlanId = 'free' | 'starter' | 'pro' | 'team' | 'enterprise';
type BuildMachineTier = 'standard' | 'large' | 'xlarge';
interface PlatformPlanLimits {
    /** Max projects across all environments */
    maxProjects: number | null;
    /** Max organization members */
    maxMembers: number | null;
    /** Max custom domains */
    maxCustomDomains: number | null;
    /** Max concurrent CI runners */
    maxConcurrentRunners: number | null;
    /** Max concurrent macOS CI runners */
    maxMacosRunners: number | null;
    /** Max managed databases */
    maxDatabases: number | null;
    /** CI job max duration in seconds */
    ciMaxJobDurationSeconds: number;
    /** API rate limit (requests per minute) */
    apiRateLimitPerMin: number;
    /** Audit log retention in days (0 = off) */
    auditLogDays: number;
    /** Max instances per service (null = custom/negotiated) */
    maxInstances: number | null;
    /** Max active PR preview environments per project */
    maxActivePreviewsPerProject: number;
    /** Included build minutes per billing period */
    includedBuildMinutes: number;
    /** Included outbound bandwidth in GB per billing period */
    includedBandwidthGb: number;
    /** Log retention in days */
    logRetentionDays: number;
    /** Build machine tier determining build speed */
    buildMachineTier: BuildMachineTier;
}
interface PlatformPlanFeatures {
    /** Custom domain support */
    customDomains: boolean;
    /** SSO / SAML support */
    sso: boolean;
    /** Priority CI queue */
    priorityCi: boolean;
    /** macOS CI runners */
    macosCi: boolean;
    /** Shared / Priority / Dedicated */
    support: 'community' | 'email' | 'priority' | 'dedicated';
    /** SLA uptime guarantee string (e.g. '99.9%') */
    sla: string | null;
    /** Role-based access control */
    rbac: boolean;
    /** Advanced analytics / insights */
    advancedAnalytics: boolean;
    /** White-label branding removal */
    whiteLabel: boolean;
}
interface PlatformPlanDefinition {
    id: PlatformPlanId;
    name: string;
    /** Monthly price in cents (0 = free, null = custom) */
    priceMonthly: number | null;
    /** Annual price in cents, ~20% discount (null = custom or N/A) */
    priceAnnual: number | null;
    /** Included platform compute credits per billing period (microdollars) */
    includedCreditsMicrodollars: number;
    /** Whether price is per seat (per member) — Team plan */
    perSeat?: boolean;
    features: PlatformPlanFeatures;
    limits: PlatformPlanLimits;
    /** Marketing bullet points for pricing cards */
    highlights: string[];
    /** Optional badge label (e.g. "Most Popular") */
    badge?: string;
    /** CTA button text */
    cta: string;
    /** Whether this is a custom/enterprise plan with contact sales flow */
    isCustom?: boolean;
    /**
     * Deprecated plan — no longer available for new subscriptions.
     * Existing subscribers are grandfathered until they change plans.
     */
    deprecated?: boolean;
}
declare const PLATFORM_PLANS: Record<PlatformPlanId, PlatformPlanDefinition>;
/** Active (non-deprecated) plan IDs for display in pricing UI */
declare const PLATFORM_PLAN_ORDER: PlatformPlanId[];
/**
 * Full plan order including deprecated tiers.
 * Useful for admin screens and migration tooling that must handle legacy plans.
 */
declare const PLATFORM_PLAN_ORDER_ALL: PlatformPlanId[];
/** Check whether a plan is deprecated and should not be offered to new subscribers */
declare function isPlanDeprecated(planId: PlatformPlanId): boolean;
/** Get only active (non-deprecated) plan definitions, in display order */
declare function getActivePlans(): PlatformPlanDefinition[];
/** Convert microdollars to human-readable dollar string (e.g. "$5") */
declare function microsToDollars(microdollars: number): string;
/** Convert cents to human-readable dollar string (e.g. "$19") */
declare function centsToDollars(cents: number): string;
/** Get monthly price display string */
declare function getPlanMonthlyPrice(plan: PlatformPlanDefinition, annual?: boolean): string;

/**
 * Instance Type Catalog — SSOT
 *
 * Defines the compute instance types available for Sylphx platform workloads.
 * Each instance type maps to Kubernetes resource requests/limits for kata-clh
 * (Cloud Hypervisor) microVMs, along with billing rates and plan eligibility.
 *
 * Rates are in microdollars (1 USD = 1,000,000 µ$) per minute.
 *
 * Memory overcommit (ADR-028): CLH uses demand paging (mmap without MAP_POPULATE).
 * Host physical RAM is allocated on-demand as guest pages are touched, NOT pre-allocated
 * at VM boot. Verified 2026-03-30: a pod with limits=4Gi only consumed +8Mi host RAM
 * when idle. Memory requests are set to 50% of limits (2x overcommit) for efficient
 * scheduler bin-packing. CPU requests are 25% of limits (4x overcommit).
 *
 * ADR-034 T-shirt sizing: canonical names are xs/sm/md/lg/xl/2xl/4xl.
 * Legacy names (starter-1x, standard-1x, etc.) are kept as aliases for backward
 * compatibility with existing database values and API consumers.
 */

type InstanceTypeId = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | '2xl' | '4xl' | 'starter-1x' | 'standard-1x' | 'standard-2x' | 'performance-m' | 'performance-l' | 'performance-xl';
interface InstanceTypeDefinition {
    id: InstanceTypeId;
    name: string;
    /** Kubernetes CPU limit (e.g. '2000m') */
    cpuLimit: string;
    /** Kubernetes memory limit (e.g. '8Gi') */
    memoryLimit: string;
    /** Kubernetes CPU request (e.g. '500m') */
    cpuRequest: string;
    /** Kubernetes memory request (50% of limit — CLH demand paging, ADR-028) */
    memoryRequest: string;
    /** Billing vCPU count for metering denormalization */
    vcpus: number;
    /** Billing memory in MiB for metering denormalization */
    memoryMib: number;
    /** Rate per vCPU per minute in microdollars */
    vcpuMinuteRateMicrodollars: number;
    /** Rate per GiB per minute in microdollars */
    gbMinuteRateMicrodollars: number;
    /** Platform plans that may provision this instance type */
    allowedPlans: PlatformPlanId[];
    /**
     * Maximum platform-managed instance count for this instance type tier.
     * Caps horizontal scale-out on smaller tiers. Users can set a lower
     * per-service maximum through ScalePolicy, but never exceed this ceiling.
     */
    maxInstances: number;
    /** Marketing bullet points for instance type cards */
    highlights: string[];
    /** Whether this instance type is deprecated (legacy name) */
    deprecated?: boolean;
}
/**
 * Maps legacy instance type names to their canonical T-shirt size equivalents (ADR-034).
 *
 * Database values and API consumers may still use old names — this mapping lets
 * resolveInstanceType() transparently return the canonical definition without
 * requiring a data migration.
 */
declare const INSTANCE_TYPE_ALIASES: Record<string, string>;
/**
 * Resolve a potentially-aliased instance type ID to its canonical T-shirt size.
 * Returns the input unchanged if it is already canonical or unknown.
 *
 * Use for display/UI and when accepting user input for NEW configurations.
 * Do NOT use in runtime paths (billing, K8s reconciler) — both old and new names
 * exist in INSTANCE_TYPES with their original specs, so direct lookup is correct
 * and avoids changing billing/resource behavior for existing services.
 */
declare function resolveCanonicalInstanceType(id: string): string;
declare const INSTANCE_TYPES: Record<InstanceTypeId, InstanceTypeDefinition>;
/** Ordered list of canonical instance type IDs for display (smallest to largest) */
declare const INSTANCE_TYPE_ORDER: InstanceTypeId[];
/**
 * @deprecated Use INSTANCE_TYPE_ORDER instead.
 * Ordered list of legacy instance type IDs — kept for backward compat.
 */
declare const LEGACY_INSTANCE_TYPE_ORDER: InstanceTypeId[];
/** Get the default instance type for a given platform plan */
declare function getDefaultInstanceType(plan: PlatformPlanId): InstanceTypeId;
/** Get all canonical (non-deprecated) instance types available for a given platform plan, in display order */
declare function getAvailableInstanceTypes(plan: PlatformPlanId): InstanceTypeDefinition[];
/** Resolve Kubernetes resource spec for a given instance type (accepts aliases) */
declare function resolveResources(id: InstanceTypeId): {
    requests: {
        cpu: string;
        memory: string;
    };
    limits: {
        cpu: string;
        memory: string;
    };
};
/** Resolve the platform-managed instance ceiling for a given instance type. */
declare function resolveMaxInstances(id: InstanceTypeId): number;
/** Default instance ceiling when no instance type is resolved. */
declare const DEFAULT_MAX_INSTANCES = 10;
/** Type guard: check if an arbitrary string is a valid InstanceTypeId (including legacy aliases) */
declare function isValidInstanceType(id: string): id is InstanceTypeId;
/** Validate that an instance type exists and is permitted for the given plan */
declare function validateInstanceTypeForPlan(id: string, plan: PlatformPlanId): {
    valid: boolean;
    error?: string;
};

/**
 * SDK Debug Mode
 *
 * Centralized debug logging for the SDK.
 *
 * Enable via:
 * - Browser: `localStorage.setItem('sylphx_debug', 'true')`
 * - Node.js: `SYLPHX_DEBUG=true`
 *
 * Debug messages are namespaced with [Sylphx] prefix for easy filtering.
 */
/**
 * Whether debug mode is currently enabled
 *
 * Cached after first access for performance.
 */
declare function getDebugMode(): boolean;
/**
 * Reset debug mode cache (for testing)
 */
declare function resetDebugModeCache(): void;
/** Debug log categories */
type DebugCategory = 'auth' | 'api' | 'analytics' | 'flags' | 'storage' | 'cache' | 'token' | 'webhook' | 'error';
/**
 * Log a debug message with category prefix
 *
 * @example
 * ```ts
 * debugLog('auth', 'Token refreshed', { expiresIn: 300 })
 * // [Sylphx auth] Token refreshed { expiresIn: 300 }
 * ```
 */
declare function debugLog(category: DebugCategory, message: string, data?: unknown): void;
/**
 * Log a debug warning with category prefix
 */
declare function debugWarn(category: DebugCategory, message: string, data?: unknown): void;
/**
 * Log a debug error with category prefix
 *
 * Note: This always logs when debug mode is enabled, regardless of error severity.
 * Production error tracking should use the error tracking service, not this.
 */
declare function debugError(category: DebugCategory, message: string, error?: unknown): void;
/**
 * Create a debug timer for measuring operation duration
 *
 * @example
 * ```ts
 * const timer = debugTimer('api', 'Fetching user profile')
 * // ... operation ...
 * timer.end() // Logs duration if debug mode enabled
 * ```
 */
declare function debugTimer(category: DebugCategory, operation: string): {
    end: () => void;
};
/**
 * Enable debug mode from browser console
 *
 * Call this in the browser console to enable debug logging:
 * ```js
 * window.__sylphx?.enableDebug()
 * ```
 */
declare function enableDebug(): void;
/**
 * Disable debug mode from browser console
 */
declare function disableDebug(): void;
/**
 * Install debug helpers on window.__sylphx
 *
 * This is called automatically when the SDK is loaded in the browser,
 * providing developers easy console access to debug utilities.
 */
declare function installGlobalDebugHelpers(): void;

/**
 * REST Client for Sylphx Platform
 *
 * Type-safe REST API client built on plain `fetch` (no runtime `openapi-fetch`
 * dependency — ADR-084 routes types through `@sylphx/contract` so the codegen
 * layer no longer needs a transport library of its own). Public surface is
 * preserved: consumers still call `client.GET('/path')`, `client.POST(...)`,
 * etc. The middleware chain (deduplication → circuit breaker → ETag →
 * retry) runs in the same order as the previous implementation.
 *
 * @example
 * ```typescript
 * import { createRestClient } from '@sylphx/sdk'
 *
 * const client = createRestClient({
 *   secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 * })
 *
 * const { data: user, error } = await client.GET('/auth/me')
 * const { data: result } = await client.POST('/auth/login', {
 *   body: { email, password },
 * })
 * ```
 */
/**
 * Retry configuration for automatic request retries
 */
interface RetryConfig {
    /** Maximum number of retries (default: 3) */
    maxRetries?: number;
    /** Base delay in milliseconds (default: 1000) */
    baseDelay?: number;
    /** Maximum delay in milliseconds (default: 30000) */
    maxDelay?: number;
    /** Custom function to determine if error is retryable */
    shouldRetry?: (status: number, attempt: number) => boolean;
    /** Request timeout in milliseconds (default: 30000) */
    timeout?: number;
}
/**
 * Request deduplication configuration
 */
interface DeduplicationConfig {
    /** Enable request deduplication (default: true) */
    enabled?: boolean;
    /** HTTP methods to deduplicate (default: ['GET']) */
    methods?: ('GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH')[];
}
/**
 * Circuit breaker configuration (AWS/Resilience4j pattern)
 *
 * Prevents cascade failures by fast-failing when service is unhealthy.
 * States: CLOSED (normal) → OPEN (failing) → HALF_OPEN (testing)
 */
interface CircuitBreakerConfig {
    /** Enable circuit breaker (default: true) */
    enabled?: boolean;
    /** Number of failures before opening circuit (default: 5) */
    failureThreshold?: number;
    /** Time window for counting failures in ms (default: 10000) */
    windowMs?: number;
    /** How long circuit stays open in ms (default: 30000) */
    openDurationMs?: number;
    /** Custom function to determine if response is a failure */
    isFailure?: (status: number) => boolean;
}
/**
 * ETag/Conditional request configuration (HTTP caching pattern)
 *
 * Enables HTTP conditional requests with If-None-Match header
 * to avoid re-downloading unchanged data (saves bandwidth).
 */
interface ETagConfig {
    /** Enable ETag caching (default: true for GET requests) */
    enabled?: boolean;
    /** Maximum cache entries (default: 100) */
    maxEntries?: number;
    /** Cache TTL in milliseconds (default: 5 minutes) */
    ttlMs?: number;
}
/**
 * Configuration for the REST client
 *
 * The app key identifies the app — no separate app ID needed.
 */
interface RestClientConfig {
    /**
     * Your app key — identifies the app and environment.
     *
     * Accepts either:
     * - Secret key (sk_dev_, sk_stg_, sk_prod_) — full access, server-side only
     * - Publishable key (app_dev_, app_stg_, app_prod_) — limited access, safe for client
     */
    secretKey: string;
    /** Platform URL (default: https://sylphx.com) */
    platformUrl?: string;
    /** Retry configuration (default: 3 retries with exponential backoff) */
    retry?: RetryConfig | false;
    /**
     * Request deduplication configuration (default: enabled for GET)
     *
     * Prevents duplicate concurrent requests for the same resource.
     * When multiple components request the same data simultaneously,
     * only one API call is made and the result is shared.
     */
    deduplication?: DeduplicationConfig | false;
    /**
     * Circuit breaker configuration (default: enabled)
     *
     * Prevents cascade failures by fast-failing when service is unhealthy.
     * Opens after 5 failures in 10s, stays open for 30s, then allows test request.
     */
    circuitBreaker?: CircuitBreakerConfig | false;
    /**
     * ETag caching configuration (default: enabled for GET)
     *
     * Uses HTTP conditional requests to avoid re-downloading unchanged data.
     * Saves bandwidth by returning 304 Not Modified when content hasn't changed.
     */
    etag?: ETagConfig | false;
}
/**
 * Dynamic configuration that can change at runtime (e.g., access token)
 */
interface RestDynamicConfig {
    /** Your secret key (sk_* or app_*) — identifies the app */
    secretKey?: string;
    /** Platform URL (default: https://sylphx.com) */
    platformUrl?: string;
    /** Get the current access token (called on each request) */
    getAccessToken?: () => string | null | undefined;
    /** Retry configuration (default: 3 retries with exponential backoff) */
    retry?: RetryConfig | false;
    /** Request deduplication configuration (default: enabled for GET) */
    deduplication?: DeduplicationConfig | false;
    /** Circuit breaker configuration (default: enabled) */
    circuitBreaker?: CircuitBreakerConfig | false;
    /** ETag caching configuration (default: enabled for GET) */
    etag?: ETagConfig | false;
}
/**
 * Middleware contract — kept structurally identical to the previous
 * `openapi-fetch` shape so existing implementations (dedup / circuit breaker
 * / ETag / retry) compose without change.
 */
interface Middleware {
    onRequest?: (ctx: {
        request: Request;
    }) => Promise<Request | undefined> | Request | undefined;
    onFetch?: (ctx: {
        request: Request;
        next: (request: Request) => Promise<Response>;
    }) => Promise<Response | undefined> | Response | undefined;
    onResponse?: (ctx: {
        request: Request;
        response: Response;
    }) => Promise<Response | undefined> | Response | undefined;
}
/**
 * Options for an HTTP request — structural subset of `openapi-fetch`'s
 * `FetchOptions` so existing callsites (`client.GET('/path', { params: {...} })`)
 * continue to compile.
 */
interface RequestOptions {
    body?: unknown;
    params?: {
        path?: Record<string, string>;
        query?: Record<string, unknown>;
    };
    headers?: Record<string, string>;
}
/**
 * Response envelope — `{ data, error, response }` mirroring `openapi-fetch`.
 * `data` is present on 2xx, `error` on non-2xx; both carry the parsed JSON
 * body when the server returns one. `response` is always the raw `Response`
 * so consumers can read headers (Content-Type, Retry-After, etc.).
 */
interface FetchResponse<TOk, TError> {
    data?: TOk;
    error?: TError;
    response: Response;
}
/**
 * The typed method surface. Callers pass a path + options; return envelope
 * follows openapi-fetch's shape so migration is drop-in for the small number
 * of internal callers that relied on `.GET` / `.POST` etc.
 */
interface RestClient {
    GET<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    POST<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    PUT<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    PATCH<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    DELETE<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    HEAD<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    OPTIONS<TOk = unknown, TError = unknown>(path: string, options?: RequestOptions): Promise<FetchResponse<TOk, TError>>;
    use(...middleware: readonly Middleware[]): void;
}
type DynamicRestClient = RestClient;
/**
 * Circuit breaker state machine
 *
 * CLOSED: Normal operation, requests pass through
 * OPEN: Service unhealthy, all requests fast-fail
 * HALF_OPEN: Testing recovery, allows one request
 */
type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
/**
 * Error thrown when circuit is open
 */
declare class CircuitBreakerOpenError extends Error {
    readonly remainingMs: number;
    constructor(remainingMs: number);
}
/**
 * @deprecated Prefer creating a new `createRestClient()` for isolated state in tests.
 * Resets the most recently created circuit breaker and clears the reference,
 * so `getCircuitBreakerState()` returns null until the next client is created.
 */
declare function resetCircuitBreaker(): void;
/**
 * @deprecated Prefer `client.circuitBreaker.getState()` for per-instance state.
 * Returns state of the most recently created circuit breaker (test helper only).
 */
declare function getCircuitBreakerState(): {
    state: CircuitState;
    failures: number;
    openedAt: number | null;
} | null;
/**
 * Create a type-safe REST API client.
 *
 * Uses plain `fetch` with a configurable middleware chain (deduplication →
 * circuit breaker → ETag → retry). All endpoints accept a string path; the
 * return type is openapi-fetch-compatible (`{ data, error, response }`).
 *
 * @example
 * ```typescript
 * const client = createRestClient({
 *   secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 * })
 *
 * const { data: user } = await client.GET('/auth/me')
 * const { data: plans } = await client.GET('/billing/plans')
 * const { data: result } = await client.POST('/auth/login', {
 *   body: { email: 'test@example.com', password: 'secret' },
 * })
 * ```
 */
declare function createRestClient(config: RestClientConfig): RestClient;
/**
 * Create a dynamic REST client with runtime token injection.
 *
 * Use this when you need to inject an access token that may change. Tokens
 * should be read from HttpOnly cookies via a server endpoint, never from
 * localStorage (XSS vulnerability).
 *
 * @example
 * ```typescript
 * const client = createDynamicRestClient({
 *   secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 *   getAccessToken: async () => (await cookies()).get('session')?.value,
 * })
 * ```
 */
declare function createDynamicRestClient(config: RestDynamicConfig): DynamicRestClient;
/**
 * Check if a REST response has an error
 */
declare function hasError<T, E>(response: {
    data?: T;
    error?: E;
}): response is {
    data: undefined;
    error: E;
};
/**
 * Extract error message from REST error response
 */
declare function getRestErrorMessage(error: unknown): string;

/**
 * Sylphx SDK Error Classes
 *
 * Typed error classes for better error handling and debugging.
 * Compatible with tRPC error codes and provides rich context.
 *
 * @example
 * ```typescript
 * import { SylphxError, isRetryableError, getErrorMessage } from '@sylphx/sdk'
 *
 * try {
 *   await sylphx.auth.login.mutate({ email, password })
 * } catch (error) {
 *   if (error instanceof SylphxError) {
 *     console.log(error.code) // 'UNAUTHORIZED'
 *     console.log(error.isRetryable) // false
 *   }
 *   if (isRetryableError(error)) {
 *     // Safe to retry
 *   }
 * }
 * ```
 */
type SylphxErrorCode = 'BAD_REQUEST' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | 'CONFLICT' | 'PAYLOAD_TOO_LARGE' | 'UNPROCESSABLE_ENTITY' | 'TOO_MANY_REQUESTS' | 'QUOTA_EXCEEDED' | 'INTERNAL_SERVER_ERROR' | 'NOT_IMPLEMENTED' | 'BAD_GATEWAY' | 'SERVICE_UNAVAILABLE' | 'GATEWAY_TIMEOUT' | 'NETWORK_ERROR' | 'TIMEOUT' | 'ABORTED' | 'PARSE_ERROR' | 'UNKNOWN';
/**
 * Simplified semantic error codes (DX-friendly aliases).
 * Maps to the more granular SylphxErrorCode internally.
 *
 * @example
 * ```ts
 * if (SylphxError.isRateLimited(err)) {
 *   console.log(`Retry after ${err.retryAfter}s`)
 * }
 * ```
 */
type ErrorCode = 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | 'RATE_LIMITED' | 'QUOTA_EXCEEDED' | 'VALIDATION_ERROR' | 'NETWORK_ERROR' | 'UPSTREAM_ERROR' | 'INTERNAL_ERROR';
/**
 * HTTP status code mapping for error codes
 */
declare const ERROR_CODE_STATUS: Record<SylphxErrorCode, number>;
/**
 * Retryable error codes (safe to retry automatically)
 */
declare const RETRYABLE_CODES: Set<SylphxErrorCode>;
interface SylphxErrorOptions {
    /** Error code for programmatic handling */
    code?: SylphxErrorCode;
    /** HTTP status code (inferred from code if not provided) */
    status?: number;
    /** Additional context data */
    data?: Record<string, unknown>;
    /** Original error that caused this */
    cause?: Error;
    /** Retry-After header value (seconds) for rate limiting */
    retryAfter?: number;
}
/**
 * Base error class for all Sylphx SDK errors
 *
 * @example
 * ```typescript
 * throw new SylphxError('Invalid email format', {
 *   code: 'BAD_REQUEST',
 *   data: { field: 'email' }
 * })
 * ```
 */
declare class SylphxError extends Error {
    /** Error code for programmatic handling */
    readonly code: SylphxErrorCode;
    /** HTTP status code */
    readonly status: number;
    /** Additional context data */
    readonly data?: Record<string, unknown>;
    /** Whether this error is safe to retry */
    readonly isRetryable: boolean;
    /** Retry-After value in seconds (for rate limiting) */
    readonly retryAfter?: number;
    /** Timestamp when error occurred */
    readonly timestamp: Date;
    constructor(message: string, options?: SylphxErrorOptions);
    /**
     * Check if error is a rate-limit error (429 Too Many Requests)
     */
    static isRateLimited(err: unknown): err is SylphxError & {
        code: 'TOO_MANY_REQUESTS';
    };
    /**
     * Check if error is an account lockout error (too many failed login attempts).
     * When true, `error.data?.lockoutUntil` contains the ISO 8601 timestamp when the lockout expires.
     */
    static isAccountLocked(err: unknown): err is SylphxError & {
        code: 'TOO_MANY_REQUESTS';
        data: {
            lockoutUntil: string | null;
        };
    };
    /**
     * Check if error is a quota exceeded error (plan limit reached)
     */
    static isQuotaExceeded(err: unknown): err is SylphxError & {
        code: 'QUOTA_EXCEEDED';
    };
    /**
     * Check if error is an authentication error (401 Unauthorized)
     */
    static isUnauthorized(err: unknown): err is SylphxError & {
        code: 'UNAUTHORIZED';
    };
    /**
     * Check if error is a not-found error (404 Not Found)
     */
    static isNotFound(err: unknown): err is SylphxError & {
        code: 'NOT_FOUND';
    };
    /**
     * Check if error is an authorization error (403 Forbidden)
     */
    static isForbidden(err: unknown): err is SylphxError & {
        code: 'FORBIDDEN';
    };
    /**
     * Check if error is a validation error (422 Unprocessable Entity)
     */
    static isValidationError(err: unknown): err is SylphxError & {
        code: 'UNPROCESSABLE_ENTITY';
    };
    /**
     * Check if error is a network error (no response received)
     */
    static isNetworkError(err: unknown): err is SylphxError & {
        code: 'NETWORK_ERROR';
    };
    /**
     * Check if error is an upstream/gateway error (502/504)
     */
    static isUpstreamError(err: unknown): err is SylphxError;
    /**
     * Convert to JSON-serializable object
     */
    toJSON(): Record<string, unknown>;
}
/**
 * Network-related errors (no response received)
 */
declare class NetworkError extends SylphxError {
    constructor(message?: string, options?: Omit<SylphxErrorOptions, 'code'>);
}
/**
 * Request timeout errors
 */
declare class TimeoutError extends SylphxError {
    /** Timeout duration in milliseconds */
    readonly timeout: number;
    constructor(timeout: number, options?: Omit<SylphxErrorOptions, 'code'>);
}
/**
 * Authentication errors (401)
 */
declare class AuthenticationError extends SylphxError {
    constructor(message?: string, options?: Omit<SylphxErrorOptions, 'code'>);
}
/**
 * Authorization errors (403)
 */
declare class AuthorizationError extends SylphxError {
    constructor(message?: string, options?: Omit<SylphxErrorOptions, 'code'>);
}
/**
 * Validation errors (422)
 */
declare class ValidationError extends SylphxError {
    /** Field-specific errors */
    readonly fieldErrors?: Record<string, string[]>;
    constructor(message: string, options?: Omit<SylphxErrorOptions, 'code'> & {
        fieldErrors?: Record<string, string[]>;
    });
    /**
     * Get error message for a specific field
     */
    getFieldError(field: string): string | undefined;
}
/**
 * Rate limit metadata (Stripe SDK pattern)
 */
interface RateLimitInfo {
    /** Maximum requests allowed in window */
    limit?: number;
    /** Remaining requests in current window */
    remaining?: number;
    /** Unix timestamp (seconds) when limit resets */
    resetAt?: number;
    /** Seconds until limit resets (Retry-After header) */
    retryAfter?: number;
}
/**
 * Rate limit errors (429)
 *
 * Provides full rate limit metadata for consumer apps to implement
 * proper backoff UI (countdown timers, retry buttons, etc.)
 *
 * @example
 * ```typescript
 * try {
 *   await sendEmail(config, options)
 * } catch (error) {
 *   if (error instanceof RateLimitError) {
 *     const waitSeconds = error.retryAfter ?? 60
 *     console.log(`Rate limited. Retry after ${waitSeconds}s`)
 *     console.log(`Remaining: ${error.remaining}/${error.limit}`)
 *     console.log(`Resets at: ${new Date(error.resetAt! * 1000)}`)
 *   }
 * }
 * ```
 */
declare class RateLimitError extends SylphxError {
    /** Maximum requests allowed in window */
    readonly limit?: number;
    /** Remaining requests in current window */
    readonly remaining?: number;
    /** Unix timestamp (seconds) when limit resets */
    readonly resetAt?: number;
    constructor(message?: string, options?: Omit<SylphxErrorOptions, 'code'> & RateLimitInfo);
    /**
     * Get Date when rate limit resets
     */
    getResetDate(): Date | undefined;
    /**
     * Get human-readable retry message
     */
    getRetryMessage(): string;
}
/**
 * Resource not found errors (404)
 */
declare class NotFoundError extends SylphxError {
    /** Type of resource that wasn't found */
    readonly resourceType?: string;
    /** ID of the resource that wasn't found */
    readonly resourceId?: string;
    constructor(message?: string, options?: Omit<SylphxErrorOptions, 'code'> & {
        resourceType?: string;
        resourceId?: string;
    });
}
/**
 * Check if an error is a Sylphx SDK error
 */
declare function isSylphxError(error: unknown): error is SylphxError;
/**
 * Check if an error is safe to retry
 */
declare function isRetryableError(error: unknown): boolean;
/**
 * Extract error message from any error type
 */
declare function getErrorMessage(error: unknown, fallback?: string): string;
/**
 * Get error code from any error type
 */
declare function getErrorCode(error: unknown): SylphxErrorCode;
interface ErrorDetails {
    readonly message: string;
    readonly code?: string;
    readonly name?: string;
    readonly stack?: string;
    readonly status?: number;
    readonly cause?: unknown;
}
declare function getErrorDetails(error: unknown, fallbackMessage?: string): ErrorDetails;
declare function getSafeErrorMessage(error: unknown, fallback?: string): string;
declare function isChallengeRequired(err: unknown): boolean;
/**
 * Convert any error to SylphxError
 */
declare function toSylphxError(error: unknown): SylphxError;
/**
 * Calculate exponential backoff delay with jitter
 *
 * @param attempt - Retry attempt number (0-indexed)
 * @param baseDelay - Base delay in milliseconds (default: 1000)
 * @param maxDelay - Maximum delay in milliseconds (default: 30000)
 * @returns Delay in milliseconds with jitter
 */
declare function exponentialBackoff(attempt: number, baseDelay?: number, maxDelay?: number): number;

/**
 * Billing Functions
 *
 * Pure functions for billing and subscriptions.
 * Uses REST API at /api/sdk/billing/* for all operations.
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `GET /billing/plans`,
 * `/billing/subscription`, `POST /billing/checkout`, `/billing/portal`,
 * `GET /billing/balance`, `/billing/usage`.
 */

type Plan = SdkBillingPlan;
type Subscription = SdkBillingSubscription;

/**
 * Get available plans
 *
 * @example
 * ```typescript
 * const plans = await getPlans(config)
 * plans.forEach(plan => console.log(plan.name, plan.monthlyPrice))
 * ```
 */
declare function getPlans(config: SylphxConfig): Promise<Plan[]>;
/**
 * Get user's subscription
 *
 * @example
 * ```typescript
 * const sub = await getSubscription(config, 'user-123')
 * if (sub?.status === 'active') {
 *   console.log(`Active plan: ${sub.planSlug}`)
 * }
 * ```
 */
declare function getSubscription(config: SylphxConfig, userId: string): Promise<Subscription | null>;
/**
 * Create a checkout session
 *
 * @example
 * ```typescript
 * const { checkoutUrl } = await createCheckout(config, {
 *   userId: 'user-123',
 *   planSlug: 'pro',
 *   interval: 'monthly',
 *   successUrl: 'https://myapp.com/success',
 *   cancelUrl: 'https://myapp.com/pricing',
 * })
 *
 * window.location.href = checkoutUrl
 * ```
 */
declare function createCheckout(config: SylphxConfig, input: BillingCheckoutRequest): Promise<BillingCheckoutResponse>;
/**
 * Create a billing portal session
 *
 * @example
 * ```typescript
 * const { portalUrl } = await createPortalSession(config, {
 *   userId: 'user-123',
 *   returnUrl: window.location.href,
 * })
 *
 * window.location.href = portalUrl
 * ```
 */
declare function createPortalSession(config: SylphxConfig, input: BillingPortalRequest): Promise<BillingPortalResponse>;
/**
 * Get billing balance (credits, etc.)
 *
 * @example
 * ```typescript
 * const balance = await getBillingBalance(config)
 * console.log(`Balance: ${balance.balance.currentFormatted}`)
 * ```
 */
declare function getBillingBalance(config: SylphxConfig): Promise<BillingBalanceResponse>;
/**
 * Get billing usage
 *
 * @example
 * ```typescript
 * const usage = await getBillingUsage(config, { month: '2024-01' })
 * ```
 */
declare function getBillingUsage(config: SylphxConfig, options?: {
    month?: string;
}): Promise<BillingUsageResponse>;

/**
 * Consent Functions
 *
 * Pure functions for GDPR/CCPA consent management.
 *
 * ## Architecture (ADR-004)
 *
 * Consent uses **Inline Defaults + Auto-Discovery + Console Override**:
 * - Code provides optional inline defaults when checking consent
 * - Platform auto-discovers/creates consent types when first referenced
 * - Console can override names, descriptions, requirements without deployment
 *
 * Wire-shape types and endpoint paths are re-exported from
 * `@sylphx/contract` (ADR-084). The contract is the single source of truth
 * for `GET /consent/types`, `GET /consent`, `POST /consent`, and friends.
 * This module keeps ergonomic helper inputs only where the public SDK API
 * intentionally differs from the wire shape.
 *
 * @example
 * ```typescript
 * import { hasConsent, getUserConsents, setConsents } from '@sylphx/sdk'
 *
 * // Check consent with inline defaults (auto-discovered if doesn't exist)
 * if (await hasConsent(config, 'analytics', { userId: 'user-123' }, {
 *   name: 'Analytics Cookies',
 *   description: 'Help us understand how visitors use our site',
 *   category: 'analytics',
 *   required: false,
 * })) {
 *   track('pageview')
 * }
 *
 * // Get user's current consents
 * const consents = await getUserConsents(config, { userId: 'user-123' })
 *
 * // Set specific consents
 * await setConsents(config, {
 *   userId: 'user-123',
 *   consents: { analytics: true, marketing: false }
 * })
 * ```
 */

type ConsentType = SdkConsentType;
type UserConsent = UserConsent$1;
/** Consent category for grouping */
type ConsentCategory = 'necessary' | 'analytics' | 'marketing' | 'functional' | 'preferences';
interface SetConsentsInput {
    /** User ID (optional for anonymous users) */
    userId?: string;
    /** Anonymous ID (for guest users) */
    anonymousId?: string;
    /** Consent settings by type slug */
    consents: Record<string, boolean>;
    /** Source of the consent action (defaults server-side to banner) */
    source?: 'banner' | 'settings' | 'api';
    /** User agent to store with the consent audit trail */
    userAgent?: string;
}
type LinkAnonymousConsentsInput = LinkAnonymousConsentsRequest;
interface GetConsentHistoryInput {
    /** User ID (for authenticated users) */
    userId?: string;
    /** Anonymous ID (for anonymous users) */
    anonymousId?: string;
    /** Maximum records to return (default: 50) */
    limit?: number;
    /**
     * Opaque pagination cursor returned by a previous response.
     * Omit (or pass undefined) to fetch the first page.
     */
    cursor?: string;
}
type ConsentHistoryEntry = ConsentHistoryResponse['entries'][number];
type ConsentHistoryResult = ConsentHistoryResponse;
interface GetConsentsInput {
    /** User ID (optional for anonymous users) */
    userId?: string;
    /** Anonymous ID (for guest users) */
    anonymousId?: string;
}
/**
 * Inline defaults for consent purpose auto-discovery
 *
 * @example
 * ```typescript
 * await hasConsent(config, 'analytics', { userId: 'user-123' }, {
 *   name: 'Analytics Cookies',
 *   description: 'Help us understand how visitors use our site',
 *   category: 'analytics',
 *   required: false,
 * })
 * ```
 */
interface ConsentPurposeDefaults {
    /** Display name */
    name?: string;
    /** Description */
    description?: string;
    /** Category */
    category?: ConsentCategory;
    /** Whether consent is required (always granted) */
    required?: boolean;
    /** Whether enabled by default */
    defaultEnabled?: boolean;
    /** Sort order in UI */
    sortOrder?: number;
}
/**
 * Get all consent types configured for the app
 *
 * Returns GDPR-standard defaults if none configured.
 *
 * @example
 * ```typescript
 * const types = await getConsentTypes(config)
 * types.forEach(t => console.log(`${t.name}: ${t.required ? 'Required' : 'Optional'}`))
 * ```
 */
declare function getConsentTypes(config: SylphxConfig): Promise<ConsentType[]>;
/**
 * Check if user has granted consent for a specific purpose
 *
 * If the consent type doesn't exist, it will be auto-discovered with the provided defaults.
 * Console can override any values without deployment.
 *
 * @param config - SDK configuration
 * @param purposeSlug - Consent purpose slug (e.g., 'analytics', 'marketing')
 * @param input - User identification (userId or anonymousId)
 * @param defaults - Optional inline defaults for auto-discovery
 * @returns Whether consent is granted
 *
 * @example
 * ```typescript
 * // Check analytics consent with inline defaults
 * if (await hasConsent(config, 'analytics', { userId: 'user-123' }, {
 *   name: 'Analytics Cookies',
 *   description: 'Help us understand how visitors use our site',
 *   category: 'analytics',
 *   required: false,
 * })) {
 *   track('pageview')
 * }
 *
 * // Required consent always returns true
 * const hasNecessary = await hasConsent(config, 'necessary', { userId }, {
 *   name: 'Essential Cookies',
 *   description: 'Required for the website to function',
 *   category: 'necessary',
 *   required: true,
 * })
 * ```
 */
declare function hasConsent(config: SylphxConfig, purposeSlug: string, input: GetConsentsInput, defaults?: ConsentPurposeDefaults): Promise<boolean>;
/**
 * Get user's current consent settings
 *
 * @example
 * ```typescript
 * // For authenticated user
 * const consents = await getUserConsents(config, { userId: 'user-123' })
 *
 * // For anonymous user
 * const consents = await getUserConsents(config, { anonymousId: 'anon-456' })
 * ```
 */
declare function getUserConsents(config: SylphxConfig, input: GetConsentsInput): Promise<UserConsent[]>;
/**
 * Set user's consent preferences
 *
 * @example
 * ```typescript
 * await setConsents(config, {
 *   userId: 'user-123',
 *   consents: {
 *     analytics: true,
 *     marketing: false,
 *   },
 * })
 * ```
 */
declare function setConsents(config: SylphxConfig, input: SetConsentsInput): Promise<void>;
/**
 * Accept all consent types
 *
 * @example
 * ```typescript
 * await acceptAllConsents(config, { userId: 'user-123' })
 * ```
 */
declare function acceptAllConsents(config: SylphxConfig, input: GetConsentsInput): Promise<void>;
/**
 * Decline all optional consent types (keeps required ones)
 *
 * @example
 * ```typescript
 * await declineOptionalConsents(config, { anonymousId: 'anon-456' })
 * ```
 */
declare function declineOptionalConsents(config: SylphxConfig, input: GetConsentsInput): Promise<void>;
/**
 * Link anonymous user's consents to authenticated user
 *
 * Call this after user signs up/logs in to merge their anonymous consent history.
 *
 * @example
 * ```typescript
 * await linkAnonymousConsents(config, {
 *   userId: 'user-123',
 *   anonymousId: 'anon-456',
 * })
 * ```
 */
declare function linkAnonymousConsents(config: SylphxConfig, input: LinkAnonymousConsentsInput): Promise<void>;
/**
 * Get consent change history for GDPR audit trail
 *
 * Returns a paginated list of all consent state changes for a user.
 * Required for GDPR compliance - provides complete audit trail of consent decisions.
 *
 * @example
 * ```typescript
 * // Get consent history for authenticated user (first page)
 * const history = await getConsentHistory(config, { userId: 'user-123', limit: 20 })
 * history.entries.forEach(entry => {
 *   console.log(`${entry.consentType}: ${entry.previousGranted} → ${entry.newGranted}`)
 * })
 *
 * // Fetch next page using the cursor
 * if (history.nextCursor) {
 *   const page2 = await getConsentHistory(config, {
 *     userId: 'user-123',
 *     limit: 20,
 *     cursor: history.nextCursor,
 *   })
 * }
 * ```
 */
declare function getConsentHistory(config: SylphxConfig, input: GetConsentHistoryInput): Promise<ConsentHistoryResult>;

/**
 * AI Functions
 *
 * Pure functions for AI completions - Vercel AI SDK style.
 * Direct API calls with natural tree-shaking.
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `GET /ai/models`,
 * `/ai/usage`, `/ai/rate-limit`. Chat-completion / embedding envelopes
 * remain local to this module — they pass through the Vercel AI SDK
 * bridge and evolve independently of the platform contract.
 */

type AIUsageResponse = GetUsageResponse;
type AIRateLimitResponse = GetRateLimitResponse;
type AIModelsResponse = GetModelsResponse;
type AIModel = AIModel$1;
interface ChatMessage {
    role: 'system' | 'user' | 'assistant' | 'tool';
    content: string | ContentPart[];
    name?: string;
    tool_call_id?: string;
    tool_calls?: ToolCall[];
    /** Timestamp for UI display */
    timestamp?: Date;
}
interface ContentPart {
    type: 'text' | 'image_url';
    text?: string;
    image_url?: {
        url: string;
        detail?: 'auto' | 'low' | 'high';
    };
}
interface ToolCall {
    id: string;
    type: 'function';
    function: {
        name: string;
        arguments: string;
    };
}
interface Tool {
    type: 'function';
    function: {
        name: string;
        description?: string;
        parameters?: Record<string, unknown>;
    };
}
interface ChatInput {
    /** Model ID (e.g., 'gpt-4o', 'claude-sonnet-4-20250514') */
    model: string;
    /** Messages */
    messages: ChatMessage[];
    /** Temperature (0-2) */
    temperature?: number;
    /** Max tokens to generate */
    maxTokens?: number;
    /** Top P sampling */
    topP?: number;
    /** Frequency penalty */
    frequencyPenalty?: number;
    /** Presence penalty */
    presencePenalty?: number;
    /** Stop sequences */
    stop?: string[];
    /** Tools for function calling */
    tools?: Tool[];
    /** Tool choice */
    toolChoice?: 'auto' | 'none' | {
        type: 'function';
        function: {
            name: string;
        };
    };
}
interface ChatResult {
    id: string;
    model: string;
    choices: Array<{
        index: number;
        message: {
            role: 'assistant';
            content: string | null;
            tool_calls?: ToolCall[];
        };
        finishReason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null;
    }>;
    usage: {
        promptTokens: number;
        completionTokens: number;
        totalTokens: number;
    };
}
interface ChatStreamChunk {
    id: string;
    model: string;
    choices: Array<{
        index: number;
        delta: {
            role?: 'assistant';
            content?: string;
            tool_calls?: ToolCall[];
        };
        finishReason: 'stop' | 'length' | 'tool_calls' | 'content_filter' | null;
    }>;
}
interface EmbedInput {
    /** Model ID (e.g., 'text-embedding-3-small') */
    model: string;
    /** Text(s) to embed */
    input: string | string[];
    /** Dimensions (for models that support it) */
    dimensions?: number;
}
interface EmbedResult {
    model: string;
    data: Array<{
        index: number;
        embedding: number[];
    }>;
    usage: {
        promptTokens: number;
        totalTokens: number;
    };
}
/**
 * Create a chat completion
 *
 * @example
 * ```typescript
 * const response = await chat(config, {
 *   model: 'gpt-4o',
 *   messages: [
 *     { role: 'system', content: 'You are a helpful assistant.' },
 *     { role: 'user', content: 'Hello!' },
 *   ],
 * })
 *
 * console.log(response.choices[0].message.content)
 * ```
 */
declare function chat(config: SylphxConfig, input: ChatInput): Promise<ChatResult>;
/**
 * Create a streaming chat completion
 *
 * @example
 * ```typescript
 * const stream = chatStream(config, {
 *   model: 'gpt-4o',
 *   messages: [{ role: 'user', content: 'Write a poem' }],
 * })
 *
 * for await (const chunk of stream) {
 *   process.stdout.write(chunk.choices[0].delta.content ?? '')
 * }
 * ```
 */
declare function chatStream(config: SylphxConfig, input: ChatInput): AsyncIterable<ChatStreamChunk>;
/**
 * Create embeddings
 *
 * @example
 * ```typescript
 * const result = await embed(config, {
 *   model: 'text-embedding-3-small',
 *   input: ['Hello world', 'Goodbye world'],
 * })
 *
 * console.log(result.data[0].embedding) // [0.123, -0.456, ...]
 * ```
 */
declare function embed(config: SylphxConfig, input: EmbedInput): Promise<EmbedResult>;
/**
 * Simple text completion (convenience wrapper)
 *
 * @example
 * ```typescript
 * const text = await complete(config, 'gpt-4o', 'Explain quantum computing in one sentence.')
 * ```
 */
declare function complete(config: SylphxConfig, model: string, prompt: string, options?: Omit<ChatInput, 'model' | 'messages'>): Promise<string>;
/**
 * Stream text to string (collects all chunks)
 *
 * @example
 * ```typescript
 * const text = await streamToString(config, {
 *   model: 'gpt-4o',
 *   messages: [{ role: 'user', content: 'Write a haiku' }],
 * })
 * ```
 */
declare function streamToString(config: SylphxConfig, input: ChatInput): Promise<string>;

/**
 * Referrals Functions
 *
 * Pure functions for referral code management and tracking.
 *
 * ## Architecture (ADR-004)
 *
 * Referrals uses **Inline Defaults + Auto-Discovery + Console Override**:
 * - Code provides optional inline defaults when redeeming referral codes
 * - Platform uses defaults if no Console override exists
 * - Console can override reward values without deployment
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `GET /referrals/code`,
 * `/referrals/code/regenerate`, `/referrals/stats`, `/referrals/redeem`,
 * `/referrals/leaderboard`.
 *
 * @example
 * ```typescript
 * import { redeemReferralCode } from '@sylphx/sdk'
 *
 * // Redeem with inline defaults (overridable in Console)
 * const result = await redeemReferralCode(config, {
 *   code: 'ABC123',
 *   userId: 'new-user-456',
 * }, {
 *   referrerReward: { type: 'premium_trial', days: 7 },
 *   refereeReward: { type: 'premium_trial', days: 7 },
 * })
 * ```
 */

type RegenerateCodeResponse = RegenerateCodeResponse$1;
type ReferralRewardDefaults = ReferralRewardDefaults$1;
type LeaderboardEntry$1 = ReferralLeaderboardEntry;
type ReferralCode = GetCodeResponse;
type ReferralStats = GetStatsResponse;
type LeaderboardPeriod = 'all' | 'month' | 'week';
type LeaderboardResult$1 = ReferralLeaderboardResponse;
interface RedeemReferralInput {
    /** Referral code to redeem */
    code: string;
    /**
     * @deprecated Runtime referrals derive the actor from `config.accessToken`.
     * This field is retained for source compatibility and is not sent.
     */
    userId?: string;
}
type RedeemResult = RedeemResponse;
interface LeaderboardOptions {
    /** Number of entries to return (default: 10) */
    limit?: number;
    /** Time period for filtering (default: all) */
    period?: LeaderboardPeriod;
}
/**
 * Get current user's referral code
 *
 * Creates one if it doesn't exist.
 *
 * @example
 * ```typescript
 * const { code } = await getMyReferralCode(config)
 * console.log(`Share your code: ${code}`)
 * ```
 */
declare function getMyReferralCode(config: SylphxConfig, _userId?: string): Promise<ReferralCode>;
/**
 * Get referral statistics for a user
 *
 * @example
 * ```typescript
 * const stats = await getReferralStats(config)
 * console.log(`${stats.completedReferrals} successful referrals`)
 * ```
 */
declare function getReferralStats(config: SylphxConfig, _userId?: string): Promise<ReferralStats>;
/**
 * Redeem a referral code
 *
 * If the referral program rewards aren't configured in Console, the provided
 * defaults will be used. Console can override any values without deployment.
 *
 * @param config - SDK configuration
 * @param input - Referral redemption input. User identity comes from `config.accessToken`.
 * @param defaults - Optional inline defaults for reward configuration
 *
 * @example
 * ```typescript
 * // Basic redemption (uses Console-configured rewards)
 * const result = await redeemReferralCode(config, {
 *   code: 'ABC123',
 *   userId: 'new-user-456',
 * })
 *
 * // With inline defaults (auto-discovered if not in Console)
 * const result = await redeemReferralCode(config, {
 *   code: 'ABC123',
 *   userId: 'new-user-456',
 * }, {
 *   referrerReward: { type: 'premium_trial', days: 7 },
 *   refereeReward: { type: 'premium_trial', days: 7 },
 * })
 *
 * if (result.success) {
 *   console.log(`Reward: ${result.reward?.type}`)
 * }
 * ```
 */
declare function redeemReferralCode(config: SylphxConfig, input: RedeemReferralInput, defaults?: ReferralRewardDefaults): Promise<RedeemResult>;
/**
 * Get referral leaderboard
 *
 * @example
 * ```typescript
 * const { entries, currentUserRank } = await getReferralLeaderboard(config)
 *
 * entries.forEach(e => {
 *   console.log(`#${e.rank} ${e.displayName}: ${e.completedReferrals} referrals`)
 * })
 * ```
 */
declare function getReferralLeaderboard(config: SylphxConfig, _userId?: string, options?: LeaderboardOptions): Promise<LeaderboardResult$1>;
/**
 * Regenerate user's referral code
 *
 * Use this if the current code has been compromised or user wants a fresh start.
 *
 * @example
 * ```typescript
 * const { code } = await regenerateReferralCode(config)
 * console.log(`New code: ${code}`)
 * ```
 */
declare function regenerateReferralCode(config: SylphxConfig, _userId?: string): Promise<RegenerateCodeResponse>;

/**
 * Webhooks Functions
 *
 * Pure functions for webhook configuration and delivery management.
 *
 * Runtime endpoint paths and methods come from `webhooksRuntimeEndpoints`
 * (ADR-084). Management-plane webhook administration stays in
 * `webhooksEndpoints`; this module targets the BaaS runtime API mounted at
 * `/webhooks` for customer SDK calls.
 */

interface WebhookEnvironment {
    id: string;
    name: string;
    webhookUrl: string | null;
    webhookSecret?: string | null;
    hasSecret?: boolean;
    events?: string[];
    createdAt: string;
    updatedAt: string | null;
}
interface WebhookConfig {
    environments: WebhookEnvironment[];
    supportedEvents?: string[];
    enabled?: boolean;
    url?: string | null;
    secret?: string | null;
    events?: string[];
}
interface WebhookConfigUpdate {
    environmentId: string;
    webhookUrl: string | null;
}
interface WebhookDeliveriesResult {
    deliveries: WebhookDelivery[];
    total: number;
    hasMore?: boolean;
    limit?: number;
    offset?: number;
}
type WebhookDeliveryStatus = RuntimeWebhookDelivery['status'] | 'success';
interface WebhookDelivery {
    id: string;
    event: string;
    eventType?: string;
    url: string;
    status: WebhookDeliveryStatus;
    retryCount: number;
    responseStatus?: number | null;
    statusCode?: number;
    error?: string | null;
    payload?: Record<string, unknown>;
    messageId?: string | null;
    attempts?: number;
    response?: string | null;
    createdAt: string;
    queuedAt?: string | null;
    deliveredAt?: string | null;
    failedAt?: string | null;
    lastAttemptAt?: string | null;
    timestamp?: string;
    webhookId?: string;
    duration?: number;
}
interface WebhookStats {
    total: number;
    delivered: number;
    failed: number;
    pending: number;
    deliveryRate: number;
    avgLatencyMs: number | null;
    period?: string;
    totals?: {
        total: number;
        delivered: number;
        failed: number;
        pending: number;
        deliveryRate: number | string;
    };
    byEvent?: Array<{
        event: string;
        count: number;
    }>;
    byStatus?: Array<{
        status: string;
        count: number;
    }>;
}
interface ListDeliveriesOptions {
    environmentId?: string;
    status?: 'pending' | 'queued' | 'delivered' | 'failed';
    limit?: number;
    offset?: number;
}
/**
 * Get webhook configuration for the app
 *
 * @example
 * ```typescript
 * const config = await getWebhookConfig(sylphxConfig)
 * console.log(config.environments)
 * ```
 */
declare function getWebhookConfig(config: SylphxConfig): Promise<WebhookConfig>;
/**
 * Update webhook URL for an environment
 *
 * @example
 * ```typescript
 * await updateWebhookConfig(config, {
 *   environmentId: 'env-123',
 *   webhookUrl: 'https://myapp.com/webhooks',
 * })
 * ```
 */
declare function updateWebhookConfig(config: SylphxConfig, data: WebhookConfigUpdate): Promise<void>;
/**
 * Get webhook delivery history
 *
 * @example
 * ```typescript
 * const { deliveries, total } = await getWebhookDeliveries(config, {
 *   status: 'failed',
 *   limit: 20,
 * })
 * ```
 */
declare function getWebhookDeliveries(config: SylphxConfig, options?: ListDeliveriesOptions): Promise<WebhookDeliveriesResult>;
/**
 * Get a single webhook delivery by ID
 *
 * @example
 * ```typescript
 * const delivery = await getWebhookDelivery(config, 'del-123')
 * console.log(delivery.payload)
 * ```
 */
declare function getWebhookDelivery(config: SylphxConfig, deliveryId: string): Promise<WebhookDelivery>;
/**
 * Replay a failed webhook delivery
 *
 * @example
 * ```typescript
 * await replayWebhookDelivery(config, 'del-123')
 * ```
 */
declare function replayWebhookDelivery(config: SylphxConfig, deliveryId: string): Promise<void>;
/**
 * Get webhook statistics
 *
 * @example
 * ```typescript
 * const stats = await getWebhookStats(config)
 * console.log(`Delivery rate: ${stats.deliveryRate}%`)
 * ```
 */
declare function getWebhookStats(config: SylphxConfig, environmentId?: string): Promise<WebhookStats>;

/**
 * SDK-specific types — cross-layer helpers and server-first configuration.
 *
 * Wire-shape types (API request/response envelopes) live in
 * `@sylphx/contract` and are re-exported per namespace from their SDK
 * module (e.g. `Plan` / `Subscription` from `./billing`, `ConsentType`
 * from `./consent`, `TokenResponse` from `./auth`). React-hook wrapper
 * shapes live in `./react/types` (tRPC-like convenience shapes that
 * are not part of the platform wire).
 *
 * History: pre-ADR-084 this file mirrored every wire shape the SDK
 * exposed; those aliases now come directly from `@sylphx/contract`.
 */

declare const OAUTH_PROVIDERS: readonly ["google", "github", "apple", "microsoft", "facebook", "twitter", "discord", "linkedin", "slack", "gitlab", "bitbucket", "twitch", "spotify"];
type OAuthProviderId = (typeof OAUTH_PROVIDERS)[number];
/** SDK cookie/token shape. Richer authenticated surfaces live in `./react/types` `UserProfile`. */
interface User {
    id: string;
    email: string;
    name: string | null;
    image?: string | null;
    emailVerified?: boolean;
    role?: string;
    createdAt?: string;
}
interface AccessTokenPayload {
    /** Raw UUID (OAuth/OIDC spec). */
    sub: string;
    /** Prefixed platform ID (e.g. `user_xxx`). */
    pid?: string;
    email: string;
    name?: string;
    picture?: string;
    email_verified: boolean;
    app_id: string;
    role?: string;
    /** Project session id when the token was minted from a BaaS auth session. */
    sid?: string;
    /**
     * Org context claims — present on org-scoped tokens (switch-org exchanges
     * and service-account client-credentials grants; ADR-2062). Resource
     * servers MUST compare `org_id` against the addressed resource's org and
     * assert `org_role` against their allowlist before granting org-scoped
     * access. Absent on plain user tokens.
     *
     * `org_role` is one of `super_admin, admin, billing, analytics, developer,
     * viewer` (or a project-defined custom RBAC key). Service accounts emit
     * only their configured binding role ∈ `{admin, developer, viewer}`.
     * `owner` does not exist and is never emitted.
     */
    org_id?: string;
    org_slug?: string;
    org_role?: string;
    /**
     * RFC 7800 confirmation claim — present when the token is sender-
     * constrained (DPoP-bound, RFC 9449). `cnf.jkt` is the SHA-256 thumbprint
     * of the client's DPoP public key. Resource servers enforcing DPoP MUST
     * validate the inbound `DPoP` proof against this thumbprint. Narrowed to
     * `{ jkt? }` — never trust an unparsed claim shape.
     */
    cnf?: {
        jkt?: string;
    };
    iat: number;
    exp: number;
}
interface SuccessResponse {
    success: boolean;
    message?: string;
}
interface ErrorResponse {
    error: {
        code: string;
        message: string;
        details?: unknown;
    };
}
interface PaginationInput {
    limit?: number;
    offset?: number;
    cursor?: string;
}
interface PaginatedResponse<T> {
    items: T[];
    total: number;
    hasMore: boolean;
    nextCursor?: string;
}

/**
 * DPoP — Demonstration of Proof-of-Possession (RFC 9449 / ADR-089 Phase 5.1e).
 *
 * Client-side helpers for sender-constrained access tokens. Built on
 * `crypto.subtle` with no runtime dependencies.
 */
declare const dpop: {
    /**
     * Generate a fresh ES256 key pair. Private key is non-extractable
     * (`extractable: false`) so it can be stored but never serialised.
     */
    readonly generateKeyPair: () => Promise<{
        readonly privateKey: CryptoKey;
        readonly publicKey: CryptoKey;
        readonly thumbprint: string;
    }>;
    /**
     * Sign a DPoP proof JWT. When `accessToken` is provided, the proof
     * includes `ath = base64url(sha256(accessToken))` so the resource
     * server can bind the proof to the token being presented.
     */
    readonly generateProof: (opts: {
        readonly privateKey: CryptoKey;
        readonly publicKey: CryptoKey;
        readonly method: string;
        readonly uri: string;
        readonly accessToken?: string;
        readonly nonce?: string;
    }) => Promise<string>;
};

/**
 * OAuth token endpoint contract helpers.
 *
 * Keeps RFC 6749/8628 request encoding, success decoding, and error decoding
 * type-bound to `@sylphx/contract` while using SDK-local runtime guards so the
 * published Promise SDK does not import Effect internals.
 */

type OAuthTokenResult = OAuthTokenResponse;
type OAuthClientCredentialsResult = OAuthClientCredentialsResponse;
type OAuthTokenEndpointError = OAuthTokenErrorResponse['error'];
type OAuthPollError = OAuthTokenEndpointError | 'oauth_error';
type OAuthPollResult = {
    readonly ok: true;
    readonly tokens: OAuthTokenResult;
} | {
    readonly ok: false;
    readonly error: OAuthPollError;
    readonly status: number;
};

/**
 * Platform refresh-token rotation and logout SDK namespace.
 */

type PlatformRefreshInput = RefreshTokenInput;
type PlatformRefreshResult = RefreshTokenResult;
type PlatformLogoutInput = LogoutInput;
declare const platformAuth: {
    readonly refresh: (opts: {
        readonly baseUrl: string;
        readonly refreshToken: string;
        readonly userAgent?: string;
        /**
         * Path prefix between `baseUrl` and the resource path. Defaults
         * to `/api/v1` for back-compat with the admin-override host
         * (`sylphx.com`). Pass `/v1` when targeting the canonical host
         * (`api.sylphx.com`) per Rule 17.
         */
        readonly urlPrefix?: string;
    }) => Promise<PlatformRefreshResult>;
    readonly logout: (opts: {
        readonly baseUrl: string;
        readonly refreshToken: string;
        readonly userAgent?: string;
        /** See `refresh.urlPrefix`. */
        readonly urlPrefix?: string;
    }) => Promise<void>;
};

/**
 * Platform impersonation SDK namespace.
 *
 * Covers the ADR-089 Phase 3b legacy helpers and Phase 5.9 WebAuthn
 * step-up + target-consent workflow.
 */
interface ImpersonationStartResult {
    readonly success: true;
    readonly token: string;
    readonly sessionId: string;
    readonly expiresAt: string;
}
interface ImpersonationEndResult {
    readonly success: boolean;
    readonly sessionsEnded: number;
}
interface ImpersonationInfo {
    readonly isImpersonation: true;
    readonly adminUserId: string;
    readonly adminEmail: string;
    readonly adminName: string | null;
    readonly impersonatedAt: string;
}
interface ImpersonationActive {
    readonly sessionId: string;
    readonly adminUserId: string;
    readonly adminEmail: string;
    readonly adminName: string | null;
    readonly targetUserId: string;
    readonly targetEmail: string;
    readonly targetName: string | null;
    readonly impersonatedAt: string;
    readonly lastActiveAt: string;
}
interface ImpersonationStartChallengeInput {
    readonly baseUrl: string;
    readonly accessToken: string;
    readonly targetUserId: string;
    readonly reason: string;
    readonly userAgent?: string;
}
interface ImpersonationChallenge {
    readonly requestId: string;
    readonly challengeKey: string;
    readonly webauthnOptions: {
        readonly challenge: string;
        readonly rpId?: string;
        readonly allowCredentials: ReadonlyArray<{
            readonly id: string;
            readonly type: 'public-key';
            readonly transports?: readonly string[];
        }>;
        readonly userVerification: 'required';
        readonly timeout: number;
    };
}
interface ImpersonationStartStepupInput {
    readonly baseUrl: string;
    readonly accessToken: string;
    readonly requestId: string;
    readonly challengeKey: string;
    readonly assertion: unknown;
    readonly emergencyBypass?: boolean;
    readonly userAgent?: string;
}
type ImpersonationStartStepupResult = {
    readonly branch: 'emergency';
    readonly requestId: string;
    readonly token: string;
    readonly sessionId: string;
    readonly expiresAt: string;
} | {
    readonly branch: 'awaiting-consent';
    readonly requestId: string;
    readonly consentDeadline: string;
};
type ImpersonationConsentDecision = 'approve' | 'deny';
type ImpersonationConsentResponse = {
    readonly branch: 'approved';
    readonly requestId: string;
    readonly token: string;
    readonly sessionId: string;
    readonly expiresAt: string;
} | {
    readonly branch: 'denied';
    readonly requestId: string;
};
interface ImpersonationRequestRow {
    readonly id: string;
    readonly operatorId: string;
    readonly targetUserId: string;
    readonly reason: string;
    readonly status: 'awaiting-stepup' | 'awaiting-consent' | 'active' | 'denied' | 'expired' | 'ended' | 'revoked';
    readonly emergencyBypass: boolean;
    readonly sessionId: string | null;
    readonly consentDeadline: string | null;
    readonly startedAt: string | null;
    readonly endedAt: string | null;
    readonly createdAt: string;
}
declare const impersonation: {
    readonly start: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly targetUserId: string;
        readonly ipAddress?: string;
        readonly userAgent?: string;
    }) => Promise<ImpersonationStartResult>;
    readonly end: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly sessionId?: string;
        readonly userAgent?: string;
    }) => Promise<ImpersonationEndResult>;
    readonly info: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly sessionId: string;
        readonly userAgent?: string;
    }) => Promise<ImpersonationInfo | null>;
    readonly active: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly userAgent?: string;
    }) => Promise<readonly ImpersonationActive[]>;
    readonly startChallenge: (opts: ImpersonationStartChallengeInput) => Promise<ImpersonationChallenge>;
    readonly startStepup: (opts: ImpersonationStartStepupInput) => Promise<ImpersonationStartStepupResult>;
    readonly respondConsent: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly requestId: string;
        readonly decision: ImpersonationConsentDecision;
        readonly userAgent?: string;
    }) => Promise<ImpersonationConsentResponse>;
    readonly listRequests: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly filter?: {
            readonly operatorId?: string;
            readonly targetUserId?: string;
            readonly status?: ImpersonationRequestRow["status"];
            readonly limit?: number;
        };
        readonly userAgent?: string;
    }) => Promise<readonly ImpersonationRequestRow[]>;
    readonly endSession: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly requestId: string;
        readonly userAgent?: string;
    }) => Promise<{
        success: true;
        requestId: string;
        sessionId: string | null;
    }>;
};

/**
 * Platform JWT verification and cookie-session resolution.
 *
 * This module owns the SDK's hot-path Platform auth helpers: cached JWKS
 * verification for bearer tokens and cached cookie-based user resolution.
 */
/**
 * Reset the platform-JWKS cache. Tests should call this between cases
 * to avoid state bleed. Production code relies on the TTL-based
 * expiry.
 */
declare function resetPlatformJwksCache(): void;
interface PlatformAccessTokenClaims {
    readonly sub: string;
    readonly pid?: string;
    readonly email: string;
    readonly name?: string;
    readonly picture?: string;
    readonly email_verified: boolean;
    readonly app_id: string;
    readonly role: string;
    readonly org_id?: string;
    readonly org_slug?: string;
    readonly org_role?: string;
    readonly iat?: number;
    readonly exp?: number;
    /**
     * RFC 7800 confirmation claim — present when the token is sender-
     * constrained. Today we emit this for DPoP-bound tokens (RFC 9449)
     * where `cnf.jkt` is the SHA-256 thumbprint of the client's DPoP
     * public key.
     *
     * Resource servers (e.g. apps/api Management plane) that want to
     * enforce DPoP MUST:
     *   1. Look up `oauth_clients.dpop_bound_access_tokens` on the
     *      issuing client to know whether DPoP is required.
     *   2. If required AND `cnf.jkt` is absent, reject 401.
     *   3. If `cnf.jkt` is present, verify the inbound `DPoP` header's
     *      proof JWT and assert its public-key thumbprint matches `jkt`.
     *
     * Pre-Wave-5.3 this field was stripped from `verifyAccessToken`'s
     * return value, making resource-side enforcement impossible without
     * decoding the JWT a second time. Exposing it preserves the wire
     * format and unlocks the resource-server DPoP middleware.
     */
    readonly cnf?: {
        readonly jkt?: string;
    };
}
/**
 * `verifyAccessToken` — local JWT verification against cached JWKS.
 *
 * Designed for the Platform API's hot-path auth middleware: JWKS is
 * fetched once per process (1h TTL), signature/iss/aud/exp
 * verification is local `jose` — no per-request HTTPS hop.
 *
 * @example
 * ```typescript
 * const claims = await auth.verifyAccessToken(bearer, {
 *   baseUrl: 'https://your-app.api.sylphx.com/v1',
 *   audience: 'platform',
 * })
 * ```
 */
declare function verifyAccessToken(token: string, opts: {
    readonly baseUrl: string;
    readonly audience: string;
}): Promise<PlatformAccessTokenClaims>;
interface PlatformUserRecord {
    readonly id: string;
    readonly email: string;
    readonly name: string | null;
    readonly image: string | null;
    readonly emailVerified: boolean;
    readonly role: string;
    readonly twoFactorEnabled: boolean;
}
interface PlatformUserResolution {
    readonly user: PlatformUserRecord;
    readonly sessionId: string;
}
declare function resetPlatformCookieCache(): void;
/**
 * `cookies` namespace — Platform cookie / session resolution for the
 * Platform API's hot-path auth middleware (ADR-089 Phase 3b).
 */
declare const cookies: {
    /**
     * Resolve a platform user from a forwarded `Cookie:` header.
     *
     * Delegates to BaaS `/auth/platform-sessions/whoami`. Caches each
     * unique cookie string for 30s to avoid hammering BaaS on every
     * SSR request.
     *
     * @example
     * ```typescript
     * const result = await auth.cookies.resolvePlatformUser({
     *   baseUrl: 'https://your-app.api.sylphx.com/v1',
     *   cookieHeader: req.headers.get('cookie') ?? '',
     * })
     * if (!result) // unauthenticated
     * ```
     */
    readonly resolvePlatformUser: (opts: {
        readonly baseUrl: string;
        readonly cookieHeader: string;
        readonly userAgent?: string;
    }) => Promise<PlatformUserResolution | null>;
};

/**
 * Platform OAuth namespace.
 *
 * Backs `auth.oauth.*` while keeping OAuth AS protocol handling out of the
 * monolithic auth module. Public exports are re-exported from `auth.ts`.
 */

type OAuthIntrospectResult = OAuthIntrospectResponse;
interface MintAccessTokenClaims {
    readonly sub: string;
    readonly email: string;
    readonly name?: string;
    readonly email_verified: boolean;
    readonly app_id: string;
    readonly role: string;
    readonly org_id?: string;
    readonly org_slug?: string;
    readonly org_role?: string;
    readonly picture?: string;
    readonly pid?: string;
}
interface MintAccessTokenResult {
    readonly accessToken: string;
    readonly expiresIn: number;
}
interface OAuthClientCallOpts {
    readonly baseUrl: string;
    readonly clientId: string;
    readonly clientSecret?: string;
    readonly token: string;
    readonly tokenTypeHint?: 'access_token' | 'refresh_token';
    readonly userAgent?: string;
}
/**
 * `oauth` namespace — Platform OAuth operations backed by BaaS.
 *
 * Phase 3b adds `mintAccessToken` for the refresh handler migration;
 * Phase 5.1 layered in full authorization-server verbs
 * (`/oauth/token`, `/oauth/revoke`, `/oauth/introspect`).
 */
declare const oauth: {
    /**
     * Mint a platform-audience access token from supplied claims.
     *
     * Service-to-service call — authenticated via
     * `SYLPHX_INTERNAL_TOKEN` shared secret until ADR-068's
     * SPIFFE SVID mTLS platform-auth flip makes workload identity the
     * only accepted internal caller credential.
     */
    readonly mintAccessToken: (opts: {
        readonly baseUrl: string;
        readonly internalToken: string;
        readonly claims: MintAccessTokenClaims;
        readonly userAgent?: string;
    }) => Promise<MintAccessTokenResult>;
    readonly exchangeAuthorizationCode: (opts: {
        readonly baseUrl: string;
        readonly clientId: string;
        readonly clientSecret?: string;
        readonly code: string;
        readonly redirectUri: string;
        readonly codeVerifier: string;
    }) => Promise<OAuthTokenResult>;
    readonly refreshAccessToken: (opts: {
        readonly baseUrl: string;
        readonly clientId: string;
        readonly clientSecret?: string;
        readonly refreshToken: string;
        readonly scope?: string;
    }) => Promise<OAuthTokenResult>;
    readonly pollDeviceToken: (opts: {
        readonly baseUrl: string;
        readonly clientId: string;
        readonly deviceCode: string;
    }) => Promise<OAuthPollResult>;
    readonly clientCredentialsToken: (opts: {
        readonly baseUrl: string;
        readonly clientId: string;
        readonly clientSecret: string;
        readonly scope?: string;
    }) => Promise<OAuthClientCredentialsResult>;
    readonly revokeToken: (opts: OAuthClientCallOpts) => Promise<void>;
    readonly introspectToken: (opts: OAuthClientCallOpts) => Promise<OAuthIntrospectResult>;
};

/**
 * Platform password management SDK namespace.
 *
 * Backed by `/auth/platform-password/*` on the BaaS runtime. Crypto
 * primitives and breach checks stay server-side; callers only pass tokens
 * and plaintext password inputs over the established HTTPS boundary.
 */

type PlatformPasswordStatusResult = PlatformPasswordStatusResponse;
type PlatformPasswordSetInput = PlatformPasswordSetRequest;
type PlatformPasswordSetResult = PlatformPasswordSetResponse;
type PlatformPasswordChangeInput = PlatformPasswordChangeRequest;
type PlatformPasswordChangeResult = PlatformPasswordChangeResponse;
declare const password: {
    readonly status: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly userAgent?: string;
    }) => Promise<PlatformPasswordStatusResult>;
    readonly set: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly password: string;
        readonly userAgent?: string;
    }) => Promise<PlatformPasswordSetResult>;
    readonly change: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly currentPassword: string;
        readonly newPassword: string;
        readonly userAgent?: string;
    }) => Promise<PlatformPasswordChangeResult>;
};

/**
 * Platform session management SDK namespace.
 *
 * Backed by `/auth/platform-sessions/*` on the BaaS runtime. These helpers
 * accept platform-audience access tokens, not project `pk_`/`sk_` credentials.
 */

type PlatformSessionsListResult = PlatformSessionsListResponse;
type PlatformSessionRevokeInput = PlatformSessionRevokeRequest;
type PlatformSessionRevokeResult = PlatformSessionRevokeResponse;
type PlatformSessionRevokeOtherResult = PlatformSessionRevokeOtherResponse;
type PlatformSessionRevokeAllResult = PlatformSessionRevokeAllResponse;
type PlatformSessionRenameInput = PlatformSessionRenameRequest;
type PlatformSessionRenameResult = PlatformSessionRenameResponse;
declare const sessions: {
    readonly list: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly userAgent?: string;
    }) => Promise<PlatformSessionsListResult>;
    readonly revoke: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly sessionId: string;
        readonly userAgent?: string;
    }) => Promise<PlatformSessionRevokeResult>;
    readonly revokeOther: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly userAgent?: string;
    }) => Promise<PlatformSessionRevokeOtherResult>;
    readonly revokeAll: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly userAgent?: string;
    }) => Promise<PlatformSessionRevokeAllResult>;
    readonly rename: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly sessionId: string;
        readonly name: string;
        readonly userAgent?: string;
    }) => Promise<PlatformSessionRenameResult>;
};

/**
 * Platform user GDPR export and erasure SDK namespace.
 *
 * These helpers are backed by `/auth/platform-user/*` on the BaaS runtime
 * and keep account data operations separate from generic auth/session helpers.
 */

type PlatformUserExportResult = AuthUserExportResponse;
type PlatformUserDeleteInput = AuthUserDeleteRequest;
type PlatformUserDeleteResult = AuthUserDeleteResponse;
/**
 * `user` namespace — Platform-plane (Console / CLI) GDPR operations.
 * Backed by `/auth/platform-user/*` on the BaaS runtime (ADR-089 Phase
 * 2d). See module header for the full rationale.
 */
declare const user: {
    /**
     * Export every piece of personal data the platform holds about the
     * authenticated user (GDPR Article 20 — right to data portability).
     *
     * The returned record is deliberately loose — it contains the user
     * row, sessions, OAuth accounts, login history, security alerts,
     * organization memberships, subscriptions, per-project memberships,
     * and storage file metadata. Shape varies with customer provisioning.
     */
    readonly exportData: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly userAgent?: string;
    }) => Promise<PlatformUserExportResult>;
    /**
     * Permanently delete the authenticated user's account (GDPR Article
     * 17 — right to erasure). Cascades through every provisioned project
     * DB, cancels Stripe subscriptions, deletes S3 blobs, and anonymises
     * billing transactions.
     */
    readonly deleteAccount: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly reason?: string;
        readonly userAgent?: string;
    }) => Promise<PlatformUserDeleteResult>;
    /**
     * Async GDPR Article 20 export job API (ADR-089 Phase 5.5).
     *
     * `user.exportData` is the Phase 2d synchronous shortcut; production
     * callers should prefer the async flow for large accounts.
     */
    readonly exports: {
        /**
         * Kick off an export job. Poll `status({ id })` until
         * `status === 'complete'`.
         */
        readonly initiate: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly format?: "json" | "json-ld";
            readonly userAgent?: string;
        }) => Promise<DataExportJob>;
        /**
         * Read the current state of an in-flight or completed export job.
         */
        readonly status: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly id: string;
            readonly userAgent?: string;
        }) => Promise<DataExportJob>;
        /**
         * Download the completed export payload. The BaaS route returns a
         * 302 to a freshly-signed object-storage URL; `fetch` follows it
         * and resolves to the raw `Blob`.
         */
        readonly download: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly id: string;
            readonly userAgent?: string;
        }) => Promise<{
            blob: Blob;
            sha256: string | null;
            sizeBytes: number | null;
        }>;
    };
};
/**
 * Wire shape of a data-export job. `status` progresses through pending,
 * running, complete, or failed.
 */
interface DataExportJob {
    readonly id: string;
    readonly status: 'pending' | 'running' | 'complete' | 'failed';
    readonly format: 'json' | 'json-ld';
    readonly requestedAt: string;
    readonly completedAt: string | null;
    readonly downloadUrl: string | null;
    readonly sizeBytes: number | null;
    readonly sha256: string | null;
    readonly errorMessage: string | null;
}

/**
 * Service Accounts — OAuth 2.0 client-credentials grant (ADR-2062)
 *
 * Org-scoped machine identity. Pure functions — config is the first
 * parameter, no hidden state. Split out of `auth.ts` along the
 * client-credentials domain boundary (ADR-2062 S1).
 */

/** Credentials of a service account (org-scoped machine identity). */
interface ServiceCredentials {
    /** Service-account client id (`sa_…`) — stable across secret rotations. */
    clientId: string;
    /** Client secret — returned once at create/rotate; never log it. */
    clientSecret: string;
    /** Optional scope downgrade (RFC 6749 §3.3). Defaults to the client's registered scope. */
    scope?: string;
}
interface ServiceTokenResponse {
    /** Org-scoped access token (JWT). Verify with root `verifyAccessToken`. */
    token: string;
    /** Same token under the SDK's `accessToken` naming convention. */
    accessToken: string;
    /** Token lifetime in seconds. Re-mint before expiry — no refresh token exists (RFC 6749 §4.4.3). */
    expiresIn: number;
    tokenType: string;
    /** Granted scope, when returned by the server. */
    scope?: string;
}
/**
 * Authenticate AS a service account via the OAuth 2.0 client-credentials
 * grant (RFC 6749 §4.4, ADR-2062). Returns a short-lived org-scoped
 * access token carrying `org_id`, `org_slug`, and `org_role` claims —
 * resource servers verify it with the root `verifyAccessToken`.
 *
 * No refresh token is issued; call again before `expiresIn` elapses.
 *
 * @example
 * ```typescript
 * const { token, expiresIn } = await signInAsService(config, {
 *   clientId: process.env.SYLPHX_SERVICE_CLIENT_ID!,
 *   clientSecret: process.env.SYLPHX_SERVICE_CLIENT_SECRET!,
 * })
 * ```
 */
declare function signInAsService(config: SylphxConfig, credentials: ServiceCredentials): Promise<ServiceTokenResponse>;

/**
 * Auth Functions
 *
 * Pure functions for authentication - no hidden state.
 * Each function takes config as the first parameter.
 *
 * Uses REST API at /api/sdk/auth/* for all operations.
 *
 * Types are re-exported from `@sylphx/contract` (ADR-084). The contract is
 * the single source of truth for every wire shape — this module only adds
 * SDK-specific ergonomics (User brand swap, introspection result, invite
 * envelopes, org-token claims).
 */

type LoginRequest = LoginRequest$1;
type LoginResponse = LoginResponse$1;
type RegisterRequest = RegisterRequest$1;
type RegisterResponse = RegisterResponse$1;
type ResendEmailVerificationRequest = ResendEmailVerificationRequest$1;
type ResendEmailVerificationResponse = ResendEmailVerificationResponse$1;
/**
 * Token response — contract's `AuthTokensResponse.user` (optional `AuthUser`)
 * is re-mapped to the SDK's broader `User` type so legacy callers keep the
 * familiar brand. `AuthUser` and `User` are structurally identical, but
 * the SDK surface has wider reach (cookies, middleware, React hooks) and
 * renaming is out of scope for ADR-084 cleanup.
 */
type TokenResponse = Omit<AuthTokensResponse, 'user'> & {
    user: User;
};
type TwoFactorVerifyRequest = TwoFactorVerifyRequest$1;
/**
 * `GET /auth/me` — contract's `UserFullProfile` already includes the
 * optional `emailVerified` flag the backend returns, so the SDK can just
 * alias the contract type directly.
 */
type MeResponse = UserFullProfile$1;
/**
 * Token introspection result (RFC 7662)
 */
interface TokenIntrospectionResult {
    /** Whether the token is active/valid */
    active: boolean;
    /** Token type (access_token or refresh_token) */
    token_type?: 'access_token' | 'refresh_token';
    /** User ID */
    sub?: string;
    /** User email */
    email?: string;
    /** User name */
    name?: string;
    /** App ID */
    client_id?: string;
    /** Audience */
    aud?: string;
    /** Issuer */
    iss?: string;
    /** Expiration time (Unix timestamp) */
    exp?: number;
    /** Issued at time (Unix timestamp) */
    iat?: number;
    /** User role */
    role?: string;
    /** Email verification status */
    email_verified?: boolean;
}
/**
 * Token revocation options
 */
interface RevokeTokenOptions {
    /** Revoke all tokens for a user in this app */
    revokeAll?: boolean;
    /** User ID (required when revoking all) */
    userId?: string;
}
interface SessionResult {
    user: {
        id: string;
        email: string;
        name: string | null;
        image: string | null;
        emailVerified: boolean;
    } | null;
}
/**
 * Extended registration input with metadata and invitation token support.
 * Use extendedSignUp() when you need to pass metadata or an invitation token.
 */
interface RegisterInput {
    email: string;
    password: string;
    name?: string;
    /**
     * Server-verified CAPTCHA challenge token for projects that require
     * bot protection on email/password registration. Obtain this from the
     * public app metadata CAPTCHA config and never send provider secrets to
     * the browser.
     */
    captchaToken?: string;
    metadata?: Record<string, unknown>;
    invitationToken?: string;
}
/**
 * Org context claims present in org-scoped tokens (after switch-org).
 *
 * The JWT carries the role key only. Permissions are resolved server-side
 * via cached role→permissions lookup (WorkOS pattern). This keeps
 * tokens small and ensures permission changes take effect without token refresh.
 */
interface OrgTokenPayload {
    org_id: string;
    org_slug: string;
    /** RBAC role key (e.g. "hr_manager", "admin"). Permissions resolved server-side. */
    org_role: string;
}
interface OrgScopedTokenResponse {
    /** Org-scoped access token. */
    token: string;
    /** Org-scoped access token, matching the SDK's token naming convention. */
    accessToken: string;
    /** Token lifetime in seconds, when provided by the runtime. */
    expiresIn?: number;
    /** Bearer token type, when provided by the runtime. */
    tokenType?: string;
    /** User envelope returned by the runtime for session hydration. */
    user?: User;
}
/**
 * Invite a user request payload.
 */
interface InviteUserRequest {
    email: string;
    metadata?: Record<string, unknown>;
    redirectUrl?: string;
}
/**
 * Response from inviteUser.
 */
interface InviteUserResponse {
    invitationToken: string;
    expiresAt: string;
}
/**
 * Sign in with email and password
 *
 * @example
 * ```typescript
 * const result = await signIn(config, { email: 'user@example.com', password: 'secret' })
 * if (result.requiresTwoFactor) {
 *   // Handle 2FA flow
 * } else {
 *   // Save tokens
 *   const authenticatedConfig = withToken(config, result.accessToken!)
 * }
 * ```
 */
declare function signIn(config: SylphxConfig, input: LoginRequest): Promise<LoginResponse>;
/**
 * Sign up with email and password
 *
 * @example
 * ```typescript
 * const result = await signUp(config, {
 *   email: 'user@example.com',
 *   password: 'secret',
 *   name: 'John Doe',
 * })
 * // User needs to verify email
 * ```
 */
declare function signUp(config: SylphxConfig, input: RegisterRequest): Promise<RegisterResponse>;
/**
 * Sign out (revoke tokens)
 *
 * @example
 * ```typescript
 * await signOut(config)
 * ```
 */
declare function signOut(config: SylphxConfig): Promise<void>;
/**
 * Refresh access token
 *
 * @example
 * ```typescript
 * const tokens = await refreshToken(config, refreshTokenString)
 * const newConfig = withToken(config, tokens.accessToken)
 * ```
 */
declare function refreshToken(config: SylphxConfig, token: string): Promise<TokenResponse>;
/**
 * Verify email with token
 *
 * @example
 * ```typescript
 * await verifyEmail(config, token)
 * ```
 */
declare function verifyEmail(config: SylphxConfig, token: string): Promise<void>;
/**
 * Request password reset email
 *
 * @example
 * ```typescript
 * await forgotPassword(config, 'user@example.com', {
 *   redirectUrl: 'https://app.example.com/reset-password'
 * })
 * ```
 */
declare function forgotPassword(config: SylphxConfig, email: string, options?: {
    redirectUrl?: string;
}): Promise<void>;
/**
 * Request a verification email resend.
 *
 * The Platform response is intentionally privacy-preserving: it never
 * indicates whether the email exists or is already verified.
 *
 * @example
 * ```typescript
 * await resendVerificationEmail(config, 'user@example.com')
 * ```
 */
declare function resendVerificationEmail(config: SylphxConfig, email: string): Promise<void>;
/**
 * Reset password with token
 *
 * @example
 * ```typescript
 * await resetPassword(config, { token, password: 'newpassword' })
 * ```
 */
declare function resetPassword(config: SylphxConfig, input: {
    token: string;
    password: string;
}): Promise<void>;
/**
 * Get current session (requires authenticated config)
 *
 * @example
 * ```typescript
 * const session = await getSession(authenticatedConfig)
 * if (session.user) {
 *   console.log(`Logged in as ${session.user.email}`)
 * }
 * ```
 */
declare function getSession(config: SylphxConfig): Promise<SessionResult>;
/**
 * Verify 2FA code (when signIn returns requiresTwoFactor: true)
 *
 * @example
 * ```typescript
 * const result = await signIn(config, credentials)
 * if (result.requiresTwoFactor) {
 *   const tokens = await verifyTwoFactor(config, result.userId!, code)
 * }
 * ```
 */
declare function verifyTwoFactor(config: SylphxConfig, userId: string, code: string): Promise<TokenResponse>;
/**
 * Introspect a token to check its validity (RFC 7662)
 *
 * Use this to verify token status without decoding. Essential for:
 * - Checking if a token has been revoked
 * - Validating tokens at the edge
 * - Security-critical operations
 *
 * @example
 * ```typescript
 * const result = await introspectToken(config, accessToken)
 * if (!result.active) {
 *   // Token is invalid, revoked, or expired
 *   await refreshTokens()
 * }
 * ```
 */
declare function introspectToken(config: SylphxConfig, token: string, tokenTypeHint?: 'access_token' | 'refresh_token'): Promise<TokenIntrospectionResult>;
/**
 * Revoke a token (RFC 7009)
 *
 * Use cases:
 * - Sign out user from specific device
 * - Security response to compromised token
 * - User-initiated session termination
 *
 * @example
 * ```typescript
 * // Revoke single refresh token
 * await revokeToken(config, refreshToken)
 *
 * // Revoke all tokens for a user (logout everywhere)
 * await revokeToken(config, '', { revokeAll: true, userId: 'user-123' })
 * ```
 */
declare function revokeToken(config: SylphxConfig, token: string, options?: RevokeTokenOptions): Promise<void>;
/**
 * Revoke all tokens for a user (logout from all devices)
 *
 * Convenience wrapper around revokeToken with revokeAll option.
 *
 * @example
 * ```typescript
 * // After password change, revoke all sessions
 * await revokeAllTokens(config, userId)
 * ```
 */
declare function revokeAllTokens(config: SylphxConfig, userId: string): Promise<void>;
/**
 * Sign up with extended input (metadata + invitation token support).
 *
 * Use this instead of signUp() when you need to:
 * - Pass metadata on registration (e.g., org context, role, referral info)
 * - Register with an invitation token
 *
 * @example
 * ```typescript
 * const result = await extendedSignUp(config, {
 *   email: 'user@example.com',
 *   password: 'secret',
 *   name: 'John Doe',
 *   metadata: { orgId: 'org-123', role: 'employee' },
 *   invitationToken: 'inv_...',
 * })
 * ```
 */
declare function extendedSignUp(config: SylphxConfig, input: RegisterInput): Promise<RegisterResponse>;
/**
 * Invite a user to sign up for this project.
 * Server-side only (requires secretKey).
 * Sends an email invitation; user signs up via signUp() or extendedSignUp() with the invitation token.
 *
 * @example
 * ```typescript
 * const invite = await inviteUser(config, {
 *   email: 'newemployee@company.com',
 *   metadata: { role: 'employee', orgId: 'org-123' },
 *   redirectUrl: 'https://app.example.com/signup',
 * })
 * console.log(invite.invitationToken, invite.expiresAt)
 * ```
 */
declare function inviteUser(config: SylphxConfig, input: InviteUserRequest): Promise<InviteUserResponse>;
/**
 * Exchange current user token for an org-scoped token.
 * The returned access_token JWT includes org_id, org_slug, org_role claims.
 *
 * @example
 * const { token } = await getOrgScopedToken(withToken(config, currentToken), 'org_xxx')
 */
declare function getOrgScopedToken(config: SylphxConfig, orgId: string): Promise<OrgScopedTokenResponse>;
/**
 * @deprecated Use getOrgScopedToken(config, orgId). Kept as the shorter
 * organization switch alias for existing SDK callers.
 */
declare function switchOrg(config: SylphxConfig, orgId: string): Promise<OrgScopedTokenResponse>;

type DeviceInitInput = DeviceInitRequest;
type DeviceGrant = DeviceInitResponse;
type DevicePollResult = DevicePollResponse;
type DeviceApproveInput = DeviceApproveRequest;
type DeviceApproveResult = DeviceApproveResponse;
type DeviceDenyInput = DeviceDenyRequest;
type DeviceDenyResult = DeviceDenyResponse;
/**
 * `device` namespace — RFC 8628 device authorization grant.
 *
 * Used by headless clients (CLI, TV apps, IoT) to authorise via a
 * companion browser instead of reading credentials from env vars.
 */
declare const device: {
    /**
     * Start a device authorization grant.
     *
     * Returns a `DeviceGrant` with `verification_uri_complete` (open this
     * in the user's browser) and `device_code` (use for polling).
     *
     * @example
     * ```typescript
     * const grant = await device.init({
     *   baseUrl: 'https://your-app.api.sylphx.com/v1',
     *   clientId: 'sylphx-cli',
     *   scope: ['org:read', 'project:*'],
     * })
     * openBrowser(grant.verification_uri_complete)
     * ```
     */
    readonly init: (opts: {
        readonly baseUrl: string;
        readonly clientId: string;
        readonly scope?: readonly string[];
        readonly userAgent?: string;
    }) => Promise<DeviceGrant>;
    /**
     * Poll a pending grant. Returns `status: 'pending' | 'approved' |
     * 'denied' | 'expired'`. On `approved`, the result carries the OAuth
     * pair (access_token + refresh_token).
     *
     * Callers MUST respect the `interval` returned by `init()` — polling
     * faster than that may return 429 slow_down (RFC 8628 §5.5).
     */
    readonly poll: (opts: {
        readonly baseUrl: string;
        readonly deviceCode: string;
        readonly userAgent?: string;
    }) => Promise<DevicePollResult>;
    /**
     * Browser leg — the approving user confirms the grant.
     *
     * Requires a valid platform-issued access token (`Authorization:
     * Bearer <accessToken>`) proving the user is logged in on the
     * Console. Typically called by the Console's `/device` verification
     * page server-side, forwarding the user's session JWT.
     */
    readonly approve: (opts: {
        readonly baseUrl: string;
        readonly userCode: string;
        readonly accessToken: string;
        readonly userAgent?: string;
    }) => Promise<DeviceApproveResult>;
    /**
     * Browser leg — the user declines the grant.
     *
     * Requires a valid platform-issued access token just like `approve`.
     */
    readonly deny: (opts: {
        readonly baseUrl: string;
        readonly userCode: string;
        readonly accessToken: string;
        readonly userAgent?: string;
    }) => Promise<DeviceDenyResult>;
};

/**
 * Audit namespace — BaaS audit-log reader (ADR-089 Phase 5.3b,
 * Σ1 SoC rename).
 *
 * Scope-filtered reader for the tamper-evident audit-log chain. The
 * runtime enforces role-scoped visibility server-side so the caller
 * only needs to present their platform JWT. All filter fields are
 * optional; `limit` caps at 500 (default 100).
 *
 * Phase Σ1 SoC rename: this was previously exported out of `./auth`
 * as `audit` and spoke to `/auth/platform-audit/*`. The server-side
 * surface moved to `/v1/audit/*` (audit is a cross-cutting BaaS
 * primitive — compliance / observability — not an auth verb); this
 * SDK module mirrors the move.
 *
 * @example
 * ```typescript
 * import { audit } from '@sylphx/sdk'
 * const { events, nextCursor } = await audit.query({
 *   baseUrl: 'https://your-app.api.sylphx.com/v1',
 *   accessToken: platformJwt,
 *   filter: { scope: 'platform-ops', limit: 200 },
 * })
 * ```
 */

type AuditQueryFilter = PlatformAuditQueryRequest;
type AuditQueryResult = PlatformAuditQueryResponse;
declare const audit: {
    readonly query: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly filter?: AuditQueryFilter;
        readonly userAgent?: string;
    }) => Promise<AuditQueryResult>;
};

/**
 * Rate-Limits namespace — BaaS operator surface (ADR-089 Phase 5.2,
 * Σ1 SoC rename).
 *
 * Platform operators inspect + tune rate-limit enforcement without a
 * code deploy. All write paths are role-gated server-side
 * (`rate-limits.ts` on the runtime): super_admin/admin touch any
 * scope, project admins are narrowed to their project, regular users
 * to their own user row. Scope escalation returns 403.
 *
 * Phase Σ1 SoC rename: this was previously exported out of
 * `./auth` as `rateLimits` and spoke to `/auth/platform-rate-limits/*`.
 * The server-side surface moved to `/v1/rate-limits/*` (rate-limiting
 * is a cross-cutting BaaS primitive, not an auth verb); this SDK
 * module mirrors the move.
 *
 * @example
 * ```typescript
 * import { rateLimits } from '@sylphx/sdk'
 * await rateLimits.strategies.set({
 *   baseUrl: 'https://your-app.api.sylphx.com/v1',
 *   accessToken: platformJwt,
 *   namespace: 'login',
 *   body: {
 *     scope: 'project',
 *     scope_id: 'proj_abc',
 *     strategy: 'fixed-window',
 *     limit: 50,
 *     windowSeconds: 300,
 *   },
 * })
 * ```
 */

type RateLimitStatusFilter = PlatformRateLimitStatusRequest;
type RateLimitStatusResult = PlatformRateLimitStatusResponse;
type RateLimitStrategiesFilter = PlatformRateLimitStrategiesListRequest;
type RateLimitStrategiesResult = PlatformRateLimitStrategiesListResponse;
type RateLimitStrategyUpsertInput = PlatformRateLimitStrategyUpsertRequest;
type RateLimitStrategyUpsertResult = PlatformRateLimitStrategyUpsertResponse;
type RateLimitStrategyDeleteInput = PlatformRateLimitStrategyDeleteRequest;
type RateLimitStrategyDeleteResult = PlatformRateLimitStrategyDeleteResponse;
declare const rateLimits: {
    readonly status: (opts: {
        readonly baseUrl: string;
        readonly accessToken: string;
        readonly filter?: RateLimitStatusFilter;
        readonly userAgent?: string;
    }) => Promise<RateLimitStatusResult>;
    readonly strategies: {
        readonly list: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly filter?: RateLimitStrategiesFilter;
            readonly userAgent?: string;
        }) => Promise<RateLimitStrategiesResult>;
        readonly set: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly namespace: string;
            readonly body: RateLimitStrategyUpsertInput;
            readonly userAgent?: string;
        }) => Promise<RateLimitStrategyUpsertResult>;
        readonly delete: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly namespace: string;
            readonly body: RateLimitStrategyDeleteInput;
            readonly userAgent?: string;
        }) => Promise<RateLimitStrategyDeleteResult>;
    };
};

/**
 * Shared Realtime Types
 *
 * Single source of truth for types used by both:
 * - Server: streams.ts (createStreams)
 * - React: use-realtime.ts (useRealtime hook)
 */
/** A message from a stream */
interface StreamMessage<T = unknown> {
    /** Stream entry ID (e.g., "1234567890-0") */
    id: string;
    /** Event type */
    event: string;
    /** Channel the message was sent to */
    channel: string;
    /** Event data */
    data: T;
    /** Unix timestamp in milliseconds */
    timestamp?: number;
}

/**
 * Realtime Functions
 *
 * Pure functions for real-time messaging via managed durable streams.
 * Supports channel-based pub/sub with SSE delivery to browsers.
 *
 * @example
 * ```ts
 * import { createConfig, realtimeEmit } from '@sylphx/sdk'
 *
 * // Server: emit events to connected clients
 * const config = createConfig({ secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey! })
 * await realtimeEmit(config, {
 *   channel: 'orders',
 *   event: 'order.created',
 *   data: { orderId: '123', amount: 99 },
 * })
 * ```
 */

interface RealtimeEmitRequest {
    /** Channel to emit the event to */
    channel: string;
    /** Event type/name */
    event: string;
    /** Event data (any JSON-serializable value) */
    data: unknown;
}
interface RealtimeEmitResponse {
    /** Stream entry ID */
    id: string;
    /** Channel the event was emitted to */
    channel: string;
}
interface RealtimeHistoryRequest {
    /** Channel to get history for */
    channel: string;
    /** Maximum number of messages to return (default: 50) */
    limit?: number;
    /** Return messages after this stream entry ID */
    after?: string;
}
interface RealtimeHistoryResponse {
    /** List of historical messages */
    messages: StreamMessage[];
}
/**
 * Emit an event to a realtime channel.
 *
 * All clients subscribed to the channel (via `useRealtime` hook or SSE)
 * will receive the event instantly.
 *
 * @example
 * ```ts
 * // Notify all clients watching a document
 * await realtimeEmit(config, {
 *   channel: `doc:${documentId}`,
 *   event: 'doc.updated',
 *   data: { updatedBy: userId, timestamp: Date.now() },
 * })
 * ```
 */
declare function realtimeEmit(config: SylphxConfig, request: RealtimeEmitRequest): Promise<RealtimeEmitResponse>;
/**
 * Get historical messages from a channel.
 *
 * Useful for initializing state when a client first connects,
 * or for resuming from a known stream position.
 *
 * @example
 * ```ts
 * // Get last 20 messages when a user joins a chat
 * const { messages } = await getRealtimeHistory(config, {
 *   channel: 'chat:general',
 *   limit: 20,
 * })
 * ```
 */
declare function getRealtimeHistory(config: SylphxConfig, request: RealtimeHistoryRequest): Promise<RealtimeHistoryResponse>;

/**
 * Admin Functions — Server-side user management
 * Requires secretKey (PLATFORM_TOKEN). Never use on client-side.
 */

interface AdminUser {
    id: string;
    email: string;
    name: string | null;
    image: string | null;
    emailVerified: boolean;
    role: string;
    status: 'active' | 'suspended' | 'deleted';
    metadata: Record<string, unknown> | null;
    firstSeenAt: string;
    lastActiveAt: string;
    createdAt: string;
}
interface ListUsersOptions {
    email?: string;
    status?: 'active' | 'suspended';
    limit?: number;
    offset?: number;
}
interface ListUsersResult {
    users: AdminUser[];
    total: number;
    limit: number;
    offset: number;
}
/**
 * List users in this project (paginated).
 * Server-side only (requires secretKey).
 *
 * @example
 * ```typescript
 * const { users, total } = await listUsers(config, { status: 'active', limit: 20 })
 * ```
 */
declare function listUsers(config: SylphxConfig, opts?: ListUsersOptions): Promise<ListUsersResult>;
/**
 * Get a single user by ID.
 * Server-side only (requires secretKey).
 */
declare function getUser(config: SylphxConfig, userId: string): Promise<AdminUser>;
/**
 * Look up a user by email address. Returns null if not found.
 * Server-side only (requires secretKey).
 *
 * @example
 * ```typescript
 * const user = await getUserByEmail(config, 'user@example.com')
 * if (!user) console.log('User not found')
 * ```
 */
declare function getUserByEmail(config: SylphxConfig, email: string): Promise<AdminUser | null>;
/**
 * Update a user's profile fields.
 * Server-side only (requires secretKey).
 *
 * @example
 * ```typescript
 * const updated = await updateUser(config, userId, { role: 'admin', name: 'Jane' })
 * ```
 */
declare function updateUser(config: SylphxConfig, userId: string, input: {
    name?: string;
    metadata?: Record<string, unknown>;
    role?: string;
}): Promise<AdminUser>;
/**
 * Update only the metadata for a user (merge-style update).
 * Server-side only (requires secretKey).
 *
 * @example
 * ```typescript
 * await updateUserMetadata(config, userId, { employeeId: 'EMP-001', department: 'Engineering' })
 * ```
 */
declare function updateUserMetadata(config: SylphxConfig, userId: string, metadata: Record<string, unknown>): Promise<AdminUser>;
/**
 * Suspend a user account.
 * Server-side only (requires secretKey).
 *
 * @example
 * ```typescript
 * await suspendUser(config, userId, 'Violation of terms of service')
 * ```
 */
declare function suspendUser(config: SylphxConfig, userId: string, reason?: string): Promise<void>;
/**
 * Delete a user account.
 * Server-side only (requires secretKey).
 *
 * @example
 * ```typescript
 * await deleteUser(config, userId)
 * ```
 */
declare function deleteUser(config: SylphxConfig, userId: string): Promise<void>;

/**
 * Analytics Functions
 *
 * Pure functions for event tracking - no hidden state.
 * Events are sent directly to the platform.
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `/analytics/track`,
 * `/analytics/identify`, `/analytics/page`, and `/analytics/batch`. SDK-
 * specific convenience shapes (`BatchEvent`) stay local since they model
 * the multi-event tracker ergonomics, not the platform wire.
 */

interface TrackInput {
    /** Event name */
    event: string;
    /** Event properties */
    properties?: Record<string, unknown>;
    /** User ID (optional, for server-side tracking) */
    userId?: string;
    /** Anonymous ID (for tracking before user signs in) */
    anonymousId?: string;
    /** Timestamp (defaults to now) */
    timestamp?: string;
}
interface PageInput {
    /** Page name or title */
    name: string;
    /** Page properties */
    properties?: Record<string, unknown>;
    /** User ID (optional) */
    userId?: string;
    /** Anonymous ID */
    anonymousId?: string;
}
interface IdentifyInput {
    /** User ID */
    userId: string;
    /** User traits */
    traits?: Record<string, unknown>;
    /** Anonymous ID to link */
    anonymousId?: string;
}
interface BatchEvent {
    type: 'track' | 'page' | 'identify';
    event?: string;
    name?: string;
    userId?: string;
    anonymousId?: string;
    properties?: Record<string, unknown>;
    traits?: Record<string, unknown>;
    timestamp?: string;
}
/**
 * Track a custom event
 *
 * @example
 * ```typescript
 * await track(config, {
 *   event: 'purchase_completed',
 *   properties: { amount: 99.99, currency: 'USD' },
 *   userId: 'user-123',
 * })
 * ```
 */
declare function track(config: SylphxConfig, input: TrackInput): Promise<void>;
/**
 * Track a page view
 *
 * @example
 * ```typescript
 * await page(config, {
 *   name: 'Home',
 *   properties: { path: '/', referrer: document.referrer },
 * })
 * ```
 */
declare function page(config: SylphxConfig, input: PageInput): Promise<void>;
/**
 * Identify a user with traits
 *
 * @example
 * ```typescript
 * await identify(config, {
 *   userId: 'user-123',
 *   traits: { email: 'user@example.com', plan: 'pro' },
 *   anonymousId: 'anon-456', // Links anonymous activity to user
 * })
 * ```
 */
declare function identify(config: SylphxConfig, input: IdentifyInput): Promise<void>;
/**
 * Send multiple events in a single request (batch)
 *
 * @example
 * ```typescript
 * await trackBatch(config, [
 *   { type: 'track', event: 'item_viewed', properties: { id: '1' } },
 *   { type: 'track', event: 'item_added', properties: { id: '1' } },
 *   { type: 'track', event: 'checkout_started' },
 * ])
 * ```
 */
declare function trackBatch(config: SylphxConfig, events: BatchEvent[]): Promise<void>;
/**
 * Generate a random anonymous ID (Segment pattern: pure UUID)
 *
 * Uses UUID v4 format without timestamp component to prevent collision risk
 * in high-traffic applications where multiple users might generate IDs at
 * the same millisecond.
 *
 * @example
 * ```typescript
 * const anonId = generateAnonymousId()
 * await track(config, { event: 'page_view', anonymousId: anonId })
 * ```
 */
declare function generateAnonymousId(): string;
/**
 * Create a tracker bound to a specific config
 *
 * For convenience when making many calls with the same config.
 * This is optional - you can always use the individual functions.
 *
 * @example
 * ```typescript
 * const analytics = createTracker(config)
 *
 * // No need to pass config each time
 * analytics.track('event', { prop: 'value' })
 * analytics.page('Home')
 * analytics.identify('user-123', { email: 'user@example.com' })
 * ```
 */
declare function createTracker(config: SylphxConfig, defaultAnonymousId?: string): {
    track: (event: string, properties?: Record<string, unknown>, userId?: string) => Promise<void>;
    page: (name: string, properties?: Record<string, unknown>, userId?: string) => Promise<void>;
    identify: (userId: string, traits?: Record<string, unknown>) => Promise<void>;
    batch: (events: BatchEvent[]) => Promise<void>;
    /** Get the anonymous ID for this tracker */
    getAnonymousId: () => string;
};

/**
 * Storage SDK — pure functional, namespaced. Per ADR-100.
 *
 * Wire is the contract in `@sylphx/contract` (`schemas/storage.ts` +
 * `endpoints/storage.ts`). This module is the only public surface for
 * uploads / files; consumers import the `storage` namespace.
 *
 * Features (built-in defaults, ADR-100 §2.8):
 * - Idempotency-Key auto-generated (UUIDv7) on every POST
 * - Single-part PUT or multipart, picked server-side from `size`
 * - Streaming SHA-256 via the Web Crypto API
 * - Resumable: persists `(uploadId, completedParts[])` to localStorage when available
 * - AbortSignal cancellation; auto-DELETE upload session on abort
 * - Exponential backoff with full jitter (5 retries, 1s base, 30s cap)
 * - Progress: byte-accurate via XHR (browser) or stream sampling (node)
 *
 * No vendor SDKs. Pure `fetch` + `XMLHttpRequest`.
 */

interface UploadProgressEvent {
    loaded: number;
    total: number;
    partsCompleted: number;
    partsTotal: number;
}
interface UploadCreateOptions {
    /** Logical name; preserved as metadata. Defaults to `blob.name` if `File`. */
    filename?: string;
    /** MIME type override; defaults to `blob.type` or `application/octet-stream`. */
    contentType?: string;
    /** Logical folder path within the project namespace. */
    folder?: string;
    /** Defaults to `'private'`. */
    visibility?: 'public' | 'private';
    /** Arbitrary user-attached metadata. */
    metadata?: Record<string, unknown>;
    /** Pre-computed SHA-256 (hex). If absent, the SDK computes it. */
    checksumSha256?: string;
    /** Fail when a file already exists at `(folder, filename)`. */
    ifNoneMatch?: '*';
    /** Cancellation. Aborts in-flight PUTs and triggers `DELETE /uploads/{id}`. */
    signal?: AbortSignal;
    /** Override the auto-generated UUIDv7 idempotency key. */
    idempotencyKey?: string;
    /** Progress callback. */
    onProgress?: (event: UploadProgressEvent) => void;
}
interface ListFilesOptions {
    folder?: string;
    cursor?: string;
    limit?: number;
    includeDeleted?: boolean;
}
interface SignedUrlOptions {
    expiresIn?: number;
    disposition?: 'attachment' | 'inline';
    userId?: string;
}
interface CopyFileOptions {
    folder?: string;
    filename?: string;
    visibility?: 'public' | 'private';
    metadata?: Record<string, unknown>;
}
type TakedownFileOptions = TakedownFileRequest;
declare function uploadsCreate(config: SylphxConfig, blob: Blob | File, options: UploadCreateOptions): Promise<File$1>;
declare function uploadsAbort(config: SylphxConfig, uploadId: UploadId | string): Promise<void>;
interface ListPage {
    files: File$1[];
    nextCursor: string | null;
}
declare function filesList(config: SylphxConfig, options?: ListFilesOptions): AsyncIterable<File$1> & {
    fetchPage: (cursor?: string) => Promise<ListPage>;
};
declare function filesGet(config: SylphxConfig, fileId: FileId | string): Promise<File$1>;
declare function filesDelete(config: SylphxConfig, fileId: FileId | string): Promise<{
    id: FileId;
    isDeleted: true;
}>;
declare function filesTakedown(config: SylphxConfig, fileId: FileId | string, options: TakedownFileOptions): Promise<TakedownFileResult>;
declare function filesRestore(config: SylphxConfig, fileId: FileId | string): Promise<File$1>;
declare function filesSignedUrl(config: SylphxConfig, fileId: FileId | string, options?: SignedUrlOptions): Promise<{
    url: string;
    expiresAt: string;
    file: File$1;
}>;
declare function filesCopy(config: SylphxConfig, fileId: FileId | string, options: CopyFileOptions): Promise<File$1>;
declare function filesVersionsList(config: SylphxConfig, fileId: FileId | string): Promise<FileVersion[]>;
declare function filesVersionsRestore(config: SylphxConfig, fileId: FileId | string, versionId: FileVersionId | string): Promise<{
    file: File$1;
    version: FileVersion;
}>;
/**
 * `storage` namespace — the only public surface for storage in `@sylphx/sdk`.
 *
 * @example
 * ```ts
 * import { storage } from '@sylphx/sdk'
 *
 * const file = await storage.uploads.create(config, blob, {
 *   filename: 'report.pdf',
 *   folder: 'documents',
 *   onProgress: (e) => console.log(`${e.loaded}/${e.total}`),
 * })
 *
 * for await (const f of storage.files.list(config, { folder: 'documents' })) {
 *   console.log(f.id, f.filename)
 * }
 * ```
 */
declare const storage: {
    readonly uploads: {
        readonly create: typeof uploadsCreate;
        readonly abort: typeof uploadsAbort;
    };
    readonly files: {
        readonly list: typeof filesList;
        readonly get: typeof filesGet;
        readonly delete: typeof filesDelete;
        readonly takedown: typeof filesTakedown;
        readonly restore: typeof filesRestore;
        readonly signedUrl: typeof filesSignedUrl;
        readonly copy: typeof filesCopy;
        readonly versions: {
            readonly list: typeof filesVersionsList;
            readonly restore: typeof filesVersionsRestore;
        };
    };
};

/**
 * Push Notification Service Worker Template
 *
 * This module provides a service worker implementation for handling
 * push notifications. Apps should copy or import this into their
 * service worker file.
 *
 * ## Industry Patterns Implemented (OneSignal/FCM)
 * - Push event handling with notification display
 * - Notification click with deep link navigation
 * - Notification close tracking
 * - Token refresh handling
 * - Background sync for offline actions
 *
 * ## Usage
 *
 * Create a service worker file in your app's public directory:
 *
 * ```typescript
 * // public/sw.ts or src/service-worker.ts
 * import { initPushServiceWorker } from '@sylphx/platform-sdk/notifications'
 *
 * initPushServiceWorker({
 *   defaultIcon: '/icon-192.png',
 *   defaultBadge: '/badge-72.png',
 *   onNotificationClick: (data) => {
 *     // Custom click handling
 *     console.log('Notification clicked:', data)
 *   },
 * })
 * ```
 */
interface ServiceWorkerRegistration {
    showNotification(title: string, options?: NotificationOptions): Promise<void>;
}
/**
 * Notification payload from Sylphx platform
 */
interface PushNotificationPayload {
    /** Notification title */
    title: string;
    /** Notification body text */
    body: string;
    /** Icon URL (optional, falls back to default) */
    icon?: string;
    /** Badge URL for Android (optional) */
    badge?: string;
    /** Image URL for expanded notification (optional) */
    image?: string;
    /** Click action URL (optional) */
    url?: string;
    /** Action buttons (optional) */
    actions?: Array<{
        action: string;
        title: string;
        icon?: string;
    }>;
    /** Custom data payload */
    data?: Record<string, unknown>;
    /** Notification tag for grouping (optional) */
    tag?: string;
    /** Whether to require interaction (optional) */
    requireInteraction?: boolean;
    /** Vibration pattern (optional) */
    vibrate?: number[];
    /** Silent notification (optional) */
    silent?: boolean;
}
/**
 * Service worker configuration options
 */
interface PushServiceWorkerConfig {
    /** Default icon for notifications without an icon */
    defaultIcon?: string;
    /** Default badge for notifications without a badge */
    defaultBadge?: string;
    /** Called when notification is clicked */
    onNotificationClick?: (data: PushNotificationPayload) => void;
    /** Called when notification is closed without clicking */
    onNotificationClose?: (data: PushNotificationPayload) => void;
    /** Platform API URL for analytics/token refresh */
    platformUrl?: string;
    /** App ID for API calls */
    appId?: string;
}
/**
 * Initialize push notification handling in service worker
 *
 * Call this in your service worker file to enable push notification handling.
 *
 * NOTE: This function should only be called from within a service worker context.
 * The types are loosely defined to work in both browser and service worker contexts.
 *
 * @example
 * ```typescript
 * // In your service worker (e.g., public/sw.ts)
 * initPushServiceWorker({
 *   defaultIcon: '/icon-192.png',
 *   defaultBadge: '/badge-72.png',
 * })
 * ```
 */
declare function initPushServiceWorker(config?: PushServiceWorkerConfig): void;
/**
 * Helper to create a simple service worker script content
 *
 * For apps that want to dynamically generate their service worker,
 * this returns the JavaScript content as a string.
 *
 * @example
 * ```typescript
 * // In a route handler
 * export function GET() {
 *   const content = createServiceWorkerScript({
 *     defaultIcon: '/icon-192.png',
 *   })
 *   return new Response(content, {
 *     headers: { 'Content-Type': 'application/javascript' },
 *   })
 * }
 * ```
 */
declare function createServiceWorkerScript(config?: PushServiceWorkerConfig): string;
/**
 * Register the service worker from the client side
 *
 * Call this in your app's entry point to register the service worker.
 *
 * @example
 * ```typescript
 * // In your app's entry point (e.g., _app.tsx or layout.tsx)
 * import { registerPushServiceWorker } from '@sylphx/platform-sdk/notifications'
 *
 * useEffect(() => {
 *   registerPushServiceWorker('/sw.js')
 * }, [])
 * ```
 */
declare function registerPushServiceWorker(swPath?: string): Promise<ServiceWorkerRegistration | null>;

/**
 * Notifications Functions
 *
 * Pure functions for push notifications.
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `/notifications/register`,
 * `/unregister`, `/send`, `/preferences`, `/messages`, `/mobile/config`.
 */

interface PushSubscription {
    endpoint: string;
    keys: {
        p256dh: string;
        auth: string;
    };
}
interface PushNotification {
    title: string;
    body: string;
    icon?: string;
    url?: string;
}
interface PushDeliveryPlatformCounts {
    readonly web?: number;
    readonly ios?: number;
    readonly android?: number;
}
interface SendPushWireResult {
    readonly status?: 'delivered' | 'queued' | 'failed';
    readonly messageId?: string;
    readonly reason?: string;
    readonly sent?: number;
    readonly failed?: number;
    readonly platforms?: PushDeliveryPlatformCounts;
    readonly sentTo?: number;
    readonly expired?: number;
}
type SendPushResult = SendPushWireResult & {
    readonly sent: number;
    readonly failed: number;
    readonly sentTo: number;
    readonly expired: number;
};
/**
 * Register a push subscription
 *
 * @example
 * ```typescript
 * // Get subscription from browser
 * const registration = await navigator.serviceWorker.ready
 * const sub = await registration.pushManager.subscribe({
 *   userVisibleOnly: true,
 *   applicationServerKey: vapidPublicKey,
 * })
 *
 * // Register with platform
 * await registerPush(config, {
 *   endpoint: sub.endpoint,
 *   keys: {
 *     p256dh: sub.toJSON().keys!.p256dh,
 *     auth: sub.toJSON().keys!.auth,
 *   },
 * })
 * ```
 */
declare function registerPush(config: SylphxConfig, subscription: PushSubscription): Promise<void>;
/**
 * Unregister a push subscription
 *
 * @example
 * ```typescript
 * await unregisterPush(config, subscription.endpoint)
 * ```
 */
declare function unregisterPush(config: SylphxConfig, endpoint: string): Promise<void>;
/**
 * Send a push notification to a user (admin only)
 *
 * @example
 * ```typescript
 * await sendPush(config, 'user-123', {
 *   title: 'New message',
 *   body: 'You have a new message',
 *   url: '/messages',
 * })
 * ```
 */
declare function sendPush(config: SylphxConfig, userId: string, notification: PushNotification): Promise<SendPushResult>;
/**
 * Get push notification preferences
 *
 * @example
 * ```typescript
 * const prefs = await getPushPreferences(config)
 * ```
 */
declare function getPushPreferences(config: SylphxConfig): Promise<{
    enabled: boolean;
    categories: Record<string, boolean>;
}>;
/**
 * Update push notification preferences
 *
 * @example
 * ```typescript
 * await updatePushPreferences(config, {
 *   enabled: true,
 *   categories: { marketing: false, updates: true },
 * })
 * ```
 */
declare function updatePushPreferences(config: SylphxConfig, preferences: {
    enabled?: boolean;
    categories?: Record<string, boolean>;
}): Promise<void>;
/**
 * Structured filter DSL for segments. Matches the server-side shape
 * defined in `@sylphx/core/lib/push/filter-dsl.ts`.
 */
type PushSegmentFilter = {
    field: string;
    op: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';
    value: unknown;
} | {
    field: string;
    op: 'in';
    value: readonly unknown[];
} | {
    field: string;
    op: 'contains';
    value: unknown;
} | {
    all: readonly PushSegmentFilter[];
} | {
    any: readonly PushSegmentFilter[];
} | {
    not: PushSegmentFilter;
};
type PushSegment = {
    id: string;
    name: string;
    description: string | null;
    filter: PushSegmentFilter;
    memberCount: number | null;
    computedAt: string | null;
    createdAt: string;
    createdBy: string;
};
type PushCampaignVariant = {
    name: string;
    weight: number;
    title: string;
    body: string;
    url?: string;
    icon?: string;
    data?: Record<string, unknown>;
};
type PushCampaign = {
    id: string;
    name: string;
    segmentId: string | null;
    status: 'draft' | 'scheduled' | 'sending' | 'sent' | 'cancelled' | 'failed';
    variants: readonly PushCampaignVariant[];
    scheduledAt: string | null;
    sentAt: string | null;
    createdAt: string;
};
type PushCampaignStats = {
    campaignId: string;
    totalDeliveries: number;
    byVariant: Record<string, {
        pending: number;
        sent: number;
        delivered: number;
        failed: number;
        clicked: number;
    }>;
};
/**
 * Segment-management namespace. Requires secret-key auth — call from
 * trusted server contexts only.
 */
declare const segments: {
    create(config: SylphxConfig, input: {
        name: string;
        description?: string;
        filter: PushSegmentFilter;
    }): Promise<PushSegment>;
    list(config: SylphxConfig): Promise<{
        segments: PushSegment[];
    }>;
    get(config: SylphxConfig, id: string): Promise<PushSegment>;
    delete(config: SylphxConfig, id: string): Promise<void>;
};
/**
 * Campaign-management namespace. A/B variants assigned deterministically
 * per-user on the server; scheduled campaigns are picked up by the
 * scheduled-send worker.
 */
declare const campaigns: {
    create(config: SylphxConfig, input: {
        name: string;
        segmentId?: string;
        variants: readonly PushCampaignVariant[];
        scheduledAt?: string;
    }): Promise<PushCampaign>;
    get(config: SylphxConfig, id: string): Promise<PushCampaign>;
    schedule(config: SylphxConfig, id: string, scheduledAt: string): Promise<PushCampaign>;
    send(config: SylphxConfig, id: string): Promise<PushCampaign>;
    cancel(config: SylphxConfig, id: string): Promise<PushCampaign>;
    stats(config: SylphxConfig, id: string): Promise<PushCampaignStats>;
};

/**
 * task() / taskStub()
 *
 * Core compute primitives — Trigger.dev v4 inspired.
 *
 * task()     — define a TypeScript task handler that gets a typed TaskHandle
 * taskStub() — typed stub for cross-language tasks (Python, etc.)
 *
 * Both return a TaskHandle<TPayload, TResult> with:
 *   .trigger(payload)           → fire-and-forget, returns RunHandle
 *   .triggerAndWait(payload)    → dispatch + poll until complete
 *   .batchTrigger(payloads)     → parallel dispatch N runs
 *
 * RunHandle exposes waitForCompletion() and cancel().
 *
 * Config is auto-resolved from SYLPHX_SECRET_URL or passed explicitly via
 * TriggerOptions.config.
 *
 * @example TypeScript task (function mode — HTTP callback in running service)
 * ```typescript
 * export const sendEmail = task({
 *   id: 'send-email',
 *   run: async ({ to, subject }, { step }) => {
 *     const validated = await step.run('validate', () => validate(to))
 *     await step.sleep('cooldown', '5 minutes')
 *     return step.run('send', () => mailer.send(validated, subject))
 *   }
 * })
 *
 * // From anywhere — fully type-safe
 * const handle = await sendEmail.trigger({ to: 'kyle@...', subject: 'Hi' })
 * const result = await handle.waitForCompletion()
 * ```
 *
 * @example TypeScript task (job mode — isolated runtime, managed machine)
 * ```typescript
 * export const processVideo = task({
 *   id: 'process-video',
 *   machine: 'large',
 *   run: async ({ videoUrl }) => { ... }
 * })
 * ```
 *
 * @example Cross-language stub (Python ML training)
 * ```typescript
 * // Register in sylphx.toml, then stub here for type safety:
 * export const trainFold = taskStub<
 *   { fold: number; n_trials?: number },
 *   { best_icir: number }
 * >('train-fold')
 *
 * // Dispatch 5 parallel folds
 * const handles = await trainFold.batchTrigger(
 *   Array.from({ length: 5 }, (_, i) => ({ fold: i, n_trials: 200 }))
 * )
 * await Promise.all(handles.runs.map(h => h.waitForCompletion()))
 * ```
 */

type TaskMachineSize = MachineSize;
interface TaskRunContext {
    step: StepContext;
    /** Current attempt number (starts at 1) */
    attempt: number;
}
interface StepContext {
    /** Execute a named step. Replays from cache if already completed (durable). */
    run<T>(id: string, fn: () => T | Promise<T>): Promise<T>;
    /** Sleep for a duration. Replays instantly if already resolved. */
    sleep(id: string, duration: string): Promise<void>;
}
interface TriggerOptions {
    /** Override auto-resolved config (defaults to SYLPHX_SECRET_URL env var) */
    config?: SylphxConfig;
    /** Deduplication key — same key within 24h returns existing run */
    idempotencyKey?: string;
    /** Delay dispatch, e.g. '5m', '1h' */
    delay?: string;
    /** Dispatch at specific time */
    scheduledFor?: Date;
    /** Override max retry attempts */
    maxAttempts?: number;
    /** Queue name override */
    queue?: string;
}
interface RunHandle$1<TResult = unknown> {
    /** Task run UUID */
    id: string;
    /** Current status at time of trigger */
    status: string;
    /**
     * Poll until the run reaches a terminal state (completed/failed/cancelled).
     * Throws if failed or timed out.
     */
    waitForCompletion(options?: {
        timeoutMs?: number;
    }): Promise<TResult>;
    /**
     * Record durable cancellation for this run. Pending/running/waiting/failed
     * runs become terminal and job-mode cleanup is retried by Platform.
     */
    cancel(): Promise<boolean>;
}
interface BatchHandle<TResult = unknown> {
    runs: RunHandle$1<TResult>[];
}
/** Inline trigger configuration on a task definition (ADR-040) */
interface TaskTriggerConfig {
    /**
     * Cron schedule — automatically fires this task on the given schedule.
     * Standard 5-field cron expression: '0 2 * * *' (every day at 2am)
     * The platform registers this trigger on deploy via serve().
     */
    cron?: string;
    /**
     * Event name — automatically fires this task when the named event is published.
     * e.g. 'user.signup', 'order.created'
     * Future: event triggers are not yet dispatched by the platform.
     */
    event?: string;
}
interface TaskConfig<TPayload, TResult> {
    /** Stable task identifier — must not change across deploys */
    id: string;
    /**
     * Automatic trigger configuration (ADR-040).
     * If set, the platform registers this trigger when serve() is called.
     * trigger.cron → cron schedule fires task automatically
     * trigger.event → event fires task automatically
     */
    trigger?: TaskTriggerConfig;
    /**
     * Managed machine size. If set → task runs in an isolated runtime (job mode).
     * If absent → task runs as an HTTP callback in the running service (function mode).
     */
    machine?: TaskMachineSize;
    /** Queue config */
    queue?: {
        name?: string;
        concurrency?: number;
    };
    /** Retry policy */
    retry?: {
        maxAttempts?: number;
        backoff?: 'fixed' | 'exponential';
    };
    /** Timeout in seconds (default: 300 for function mode, 86400 for job mode) */
    timeout?: number;
    /** The task handler. In function mode: runs via HTTP dispatch. In job mode: runs in an isolated runtime. */
    run: (payload: TPayload, ctx: TaskRunContext) => Promise<TResult>;
}
interface TaskHandle<TPayload = unknown, TResult = unknown> {
    /** The stable task ID */
    readonly id: string;
    /** Trigger config if task has an automatic trigger (cron/event) */
    readonly _trigger?: TaskTriggerConfig;
    /** Managed machine size if job-mode task (undefined for function-mode or stubs) */
    readonly _machine?: TaskMachineSize;
    /**
     * The run function — used internally by serve() to register the handler.
     * undefined for taskStub (cross-language).
     */
    readonly _run?: (payload: TPayload, ctx: TaskRunContext) => Promise<TResult>;
    /** Dispatch the task. Returns immediately with a RunHandle. */
    trigger(payload: TPayload, options?: TriggerOptions): Promise<RunHandle$1<TResult>>;
    /** Dispatch and wait for result. Convenience wrapper over trigger + waitForCompletion. */
    triggerAndWait(payload: TPayload, options?: TriggerOptions): Promise<TResult>;
    /** Dispatch N runs in parallel. Returns handles for all. */
    batchTrigger(payloads: TPayload[], options?: TriggerOptions): Promise<BatchHandle<TResult>>;
}
/**
 * Define a typed task.
 *
 * Returns a TaskHandle<TPayload, TResult> that can be used to trigger the task
 * from anywhere (same service or different service) with full type safety.
 *
 * The returned handle's _run function is used by serve() to register the
 * HTTP handler for function-mode tasks.
 */
declare function task<TPayload = unknown, TResult = unknown>(config: TaskConfig<TPayload, TResult>): TaskHandle<TPayload, TResult>;
/**
 * Create a typed stub for a cross-language task (e.g. Python ML worker).
 *
 * The task must be registered separately via sylphx.toml manifest.
 * The stub provides type safety for the trigger call without requiring
 * a TypeScript handler.
 *
 * @example
 * ```typescript
 * export const trainFold = taskStub<
 *   { fold: number; n_trials?: number },
 *   { best_icir: number }
 * >('train-fold')
 *
 * const result = await trainFold.triggerAndWait({ fold: 0 })
 * console.log(result.best_icir) // typed!
 * ```
 */
declare function taskStub<TPayload = unknown, TResult = unknown>(id: string): TaskHandle<TPayload, TResult>;

/**
 * serve()
 *
 * Create a Web API-compatible route handler for a set of task definitions.
 * Supports Next.js App Router, Hono, and any Web API Request/Response handler.
 *
 * serve() wires up:
 *   - GET  → health check, returns registered task IDs + trigger sync status
 *   - POST → dispatch handler (receives from platform, routes to task run fn)
 *
 * On startup (first GET or POST), serve() automatically syncs all inline triggers
 * (task({ trigger: { cron: '...' } })) to the platform via TriggersClient.
 * This is idempotent — uses idempotencyKey = `task:{taskId}:{triggerType}:{value}`.
 *
 * Only function-mode tasks (no machine config) register HTTP handlers here.
 * Job-mode tasks are dispatched directly by the platform, but their
 * inline triggers are still synced.
 *
 * @example Next.js App Router
 * ```typescript
 * // app/api/tasks/route.ts
 * import { serve } from '@sylphx/sdk/tasks'
 * import { sendEmail, dailyCleanup } from '@/tasks'
 *
 * export const { GET, POST } = serve({ tasks: [sendEmail, dailyCleanup] })
 * ```
 *
 * @example Inline cron trigger
 * ```typescript
 * export const dailyCleanup = task({
 *   id: 'daily-cleanup',
 *   trigger: { cron: '0 2 * * *' },
 *   run: async () => { ... },
 * })
 * // No TriggersClient.create() call needed — serve() registers it automatically.
 * ```
 */

interface ServeOptions {
    /** Task handles to serve */
    tasks: TaskHandle<unknown, unknown>[];
    /** Platform signing secret for verifying dispatches. Defaults to SYLPHX_SIGNING_SECRET env var. */
    signingSecret?: string;
    /**
     * Server connection URL for trigger registration.
     * Defaults to SYLPHX_SECRET_URL env var.
     * Only required if any tasks have inline trigger config.
     */
    connectionUrl?: string;
}
interface ServeResult {
    GET: (req: Request) => Promise<Response>;
    POST: (req: Request) => Promise<Response>;
}
/**
 * Create a route handler that serves task definitions.
 *
 * Auto-syncs inline triggers (task({ trigger: { cron: '...' } })) on first request.
 * Task sync is idempotent and non-blocking — handler responds even if sync is in progress.
 */
declare function serve(options: ServeOptions): ServeResult;

/** Cron schedule */
interface CronSchedule {
    /** Cron expression */
    expression: string;
    /** Timezone */
    timezone?: string;
    /** Start date */
    startAt?: Date;
    /** End date */
    endAt?: Date;
    /** Max runs */
    maxRuns?: number;
}
/**
 * Step execution context injected into every task handler.
 * Methods implement the stateless-replay model:
 *   - Completed steps return from cache immediately.
 *   - Uncached steps execute and signal the platform.
 */
type NativeStepContext = {
    /**
     * Execute a named step with automatic checkpointing.
     *
     * On first run: executes fn and signals the platform to save the result.
     * On replay: returns the cached result without re-running fn.
     */
    run<T>(name: string, fn: () => T | Promise<T>): Promise<T>;
    /**
     * Execute an external side effect with a durable idempotency key.
     *
     * First encounter: signals Platform to persist a side-effect receipt before
     * the external call. Replay then invokes fn with that persisted key. If the
     * handler crashes after the external call but before completion settles, the
     * next replay reuses the same key so the downstream service suppresses duplicates.
     */
    sideEffect<T>(stepName: string, effectKey: string, externalService: string, fn: (idempotencyKey: string) => NativeSideEffectOutcome<T> | Promise<NativeSideEffectOutcome<T>>): Promise<T>;
    /**
     * Pause execution for the given duration.
     *
     * On first encounter: signals the platform to wait; stops execution.
     * After the wait resolves: returns immediately (no-op on replay).
     *
     * @param name      Step identifier (must be unique within the handler).
     * @param duration  Human-readable duration: '5s', '30m', '2h', '1d'.
     */
    sleep(name: string, duration: string): Promise<void>;
    /**
     * Pause execution until a named event is published via TriggersClient.publishEvent().
     *
     * On first encounter: signals the platform to wait for the event; stops execution.
     * After the event arrives: returns the event payload.
     * If timeout expires before event arrives: returns null.
     *
     * @param name      Step identifier (must be unique within the handler).
     * @param eventName The event name to listen for (e.g. 'user.approved').
     * @param options   Optional timeout ('24h', '7d') and payload filter.
     *
     * @example Human-in-the-loop approval
     * ```typescript
     * const approval = await step.waitForEvent<{ approvedBy: string }>(
     *   'wait-approval',
     *   'order.approved',
     *   { timeout: '48h', filter: { orderId: payload.orderId } },
     * )
     * if (!approval) throw new Error('Approval timed out')
     * await notifyCustomer(approval.approvedBy)
     * ```
     */
    waitForEvent<T = unknown>(name: string, eventName: string, options?: {
        timeout?: string;
        filter?: Record<string, unknown>;
    }): Promise<T | null>;
};
interface NativeSideEffectOutcome<T = unknown> {
    readonly handle?: string;
    readonly result: T;
}
interface NativeSideEffectReceipt {
    readonly stepName: string;
    readonly effectKey: string;
    readonly externalService: string;
    readonly idempotencyKey: string;
    readonly handle: string | null;
    readonly result: unknown;
    readonly completedAt: string | null;
    readonly createdAt: string;
}
/**
 * A named task definition registered with sylphx.tasks.define().
 */
interface NativeTaskDefinition<TPayload = unknown, TResult = unknown> {
    /** Unique task identifier — must match the taskName used in .trigger() */
    name: string;
    /** The task handler function. Runs with stateless-replay semantics. */
    handler: (payload: TPayload, ctx: {
        step: NativeStepContext;
    }) => Promise<TResult>;
    /** Optional task-level configuration */
    options?: {
        /** Cron expression for scheduled tasks, e.g. '0 9 * * 1-5' */
        cron?: string;
        /** Maximum execution attempts (default: 3) */
        maxAttempts?: number;
        /** Execution timeout, e.g. '5m', '1h' */
        timeout?: string;
    };
}
/**
 * The shape returned by GET/POST /tasks/:runId in the platform API.
 */
type TaskRunDispatchLeaseState = 'active' | 'expired' | 'legacy';
interface TaskRunDispatchLease {
    /**
     * Customer-safe dispatch claim state. Raw claim tokens and controller
     * identities are intentionally not exposed through the public SDK.
     */
    state: TaskRunDispatchLeaseState;
    claimedAt: string | null;
    expiresAt: string | null;
}
interface TaskRunStatus {
    id: string;
    taskName: string;
    status: 'pending' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled';
    payload?: unknown;
    result?: unknown;
    error?: string;
    attempt: number;
    maxAttempts: number;
    scheduledFor?: string;
    startedAt?: string;
    completedAt?: string;
    dispatchLease?: TaskRunDispatchLease | null;
    definition?: {
        id: string;
        version: number | null;
        hash: string | null;
        source: string | null;
    } | null;
    createdAt: string;
    updatedAt: string;
}

/**
 * Tasks Handler
 *
 * Server-side endpoint factory for user task definitions.
 * Implements the Sylphx stateless-replay model:
 *
 *   1. Platform dispatches POST to the app's /api/tasks endpoint.
 *   2. The handler replays from the beginning.
 *   3. Completed steps hit a cache and return immediately.
 *   4. The first uncached step executes, then throws StepCompleteSignal.
 *   5. The platform saves the result and re-dispatches.
 *   6. After all steps complete the handler returns normally.
 *
 * @example
 * ```typescript
 * // app/api/tasks/route.ts
 * import { sylphx } from '@/lib/sylphx'
 *
 * const sendEmail = sylphx.tasks.define('send-email', async (payload, { step }) => {
 *   const validated = await step.run('validate', () => validateEmail(payload.to))
 *   await step.sleep('cool-down', '5 minutes')
 *   return step.run('send', () => sendEmail(validated))
 * })
 *
 * export const { GET, POST } = sylphx.tasks.handler([sendEmail])
 * ```
 */

/**
 * Thrown by step.run() when a step's result is not yet cached.
 * The handler aborts; the platform saves the result and re-dispatches.
 */
declare class StepCompleteSignal {
    readonly stepName: string;
    readonly result: unknown;
    readonly _isStepCompleteSignal = true;
    constructor(stepName: string, result: unknown);
}
/**
 * Thrown by step.sleep() when the sleep is not yet resolved.
 * The handler aborts; the platform waits and re-dispatches.
 */
declare class StepSleepSignal {
    readonly stepName: string;
    readonly duration: string;
    readonly _isStepSleepSignal = true;
    constructor(stepName: string, duration: string);
}
/**
 * Build the step proxy for a single handler invocation.
 *
 * @param completedSteps  Map of stepName → cached result
 * @param resolvedWaits   Map of stepName → wait result (sleep = undefined, event = event payload)
 */
declare function createStepContext(completedSteps: Map<string, unknown>, resolvedWaits: Map<string, unknown>, sideEffectReceipts?: Map<string, NativeSideEffectReceipt>): NativeStepContext;
/**
 * Constant-time HMAC-SHA256 signature verification.
 * Accepts both raw hex and 'sha256={hex}' formats.
 */
declare function verifySignature(body: string, signature: string, secret: string): boolean;
interface TasksHandlerOptions {
    /** Platform signing secret. If not set, signature verification is skipped. */
    signingSecret?: string;
}
interface TasksHandlerResult {
    GET: (req: Request) => Promise<Response>;
    POST: (req: Request) => Promise<Response>;
}
/**
 * Create a Next.js-compatible route handler for a list of task definitions.
 *
 * @example
 * ```typescript
 * export const { GET, POST } = createTasksHandler([sendEmail, processOrder])
 * ```
 */
declare function createTasksHandler(taskDefs: NativeTaskDefinition[], options?: TasksHandlerOptions): TasksHandlerResult;

/**
 * Task API Functions
 *
 * Standalone functions for scheduling tasks and managing crons via the Sylphx API.
 * These are backward-compat exports preserved from the pre-refactor tasks.ts.
 */

interface TaskInput {
    /** Callback URL to call when task executes */
    callbackUrl: string;
    /** Task name/type */
    name?: string;
    /** Task type for categorization */
    type?: string;
    /** Task payload sent to callback */
    payload?: Record<string, unknown>;
    /** HTTP method for callback (default: POST) */
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    /** Additional headers for callback */
    headers?: Record<string, string>;
    /** Delay before executing (in seconds, max 604800 = 7 days) */
    delay?: number;
    /** Schedule for later (ISO timestamp) */
    scheduledFor?: string;
    /** Number of retries on failure (0-5, default: 3) */
    retries?: number;
    /** Request timeout in seconds (1-300, default: 30) */
    timeout?: number;
    /**
     * Idempotency key for safe retries (Stripe/Inngest pattern).
     *
     * When provided, prevents duplicate task execution if the same
     * key is used within a 24-hour window.
     */
    idempotencyKey?: string;
}
interface TaskResult {
    /** Task ID */
    taskId: string;
    /** Scheduled execution time */
    scheduledFor?: string;
}
interface TaskStatus {
    id: string;
    name?: string;
    status: 'pending' | 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
    payload?: Record<string, unknown>;
    result?: unknown;
    error?: string;
    createdAt: string;
    queuedAt?: string;
    startedAt?: string;
    completedAt?: string;
}
interface CronInput {
    /** Callback URL to call on each cron trigger */
    callbackUrl: string;
    /** Cron expression (e.g., '0 0 * * *' for daily at midnight) */
    cron: string;
    /** Task name (required, max 200 chars) */
    name: string;
    /** Task type for categorization */
    type?: string;
    /** Task payload sent to callback */
    payload?: Record<string, unknown>;
    /** HTTP method for callback (default: POST) */
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    /** Additional headers for callback */
    headers?: Record<string, string>;
    /** Number of retries on failure (0-5, default: 3) */
    retries?: number;
    /** Start in paused state */
    paused?: boolean;
    /**
     * Idempotency key for safe cron creation.
     *
     * When provided, prevents duplicate cron schedule creation if
     * the same key is used.
     */
    idempotencyKey?: string;
}
/**
 * Schedule a one-time task for execution
 */
declare function scheduleTask(config: SylphxConfig, input: TaskInput): Promise<TaskResult>;
/**
 * Get a task's status by ID
 */
declare function getTask(config: SylphxConfig, taskId: string): Promise<TaskStatus>;
/** The durable step ledger entry surfaced by `getTaskRun`. */
type TaskRunStep = DurableWorkTaskRunStep;
/** The full durable task-run view surfaced by `getTaskRun`. */
type TaskRunDetail = DurableWorkGetTaskRunResponse;
/**
 * Get the full durable view of a task run, including the step ledger.
 *
 * Each step carries an `executorToken` — the opaque-but-stable identity of the
 * worker that materialized it. The token changes across a pod-kill resume, so
 * comparing executor tokens across steps is the evidence that a run resumed on
 * a different worker (durable HA). `status` reads `executed` for every recorded
 * step (a step is persisted once, on the dispatch that executed it; later
 * dispatches replay it from cache and record nothing). The platform never
 * returns step result payloads — only identity, executor, and timing.
 */
declare function getTaskRun(config: SylphxConfig, runId: string): Promise<TaskRunDetail>;
/**
 * Cancel a pending, running, waiting, or failed task run.
 */
declare function cancelTask(config: SylphxConfig, taskId: string): Promise<boolean>;
/**
 * List tasks with optional filters
 */
declare function listTasks(config: SylphxConfig, options?: {
    status?: TaskStatus['status'];
    limit?: number;
    offset?: number;
}): Promise<{
    tasks: TaskStatus[];
    total: number;
}>;
/**
 * Create a recurring cron task
 */
declare function createCron(config: SylphxConfig, input: CronInput): Promise<CronSchedule>;
/**
 * Pause a cron schedule
 */
declare function pauseCron(config: SylphxConfig, scheduleId: string): Promise<boolean>;
/**
 * Resume a cron schedule
 */
declare function resumeCron(config: SylphxConfig, scheduleId: string): Promise<boolean>;
/**
 * Delete a cron schedule
 */
declare function deleteCron(config: SylphxConfig, scheduleId: string): Promise<boolean>;

/**
 * Feature Flags Functions
 *
 * Pure functions for feature flag evaluation.
 *
 * Pattern: LaunchDarkly/Statsig server-side evaluation
 * - Server-side: POST /flags/evaluate with context
 * - Returns evaluated results (enabled/disabled for this context)
 *
 * Types are derived from the OpenAPI spec (generated/api.d.ts).
 * Run `bun run generate:types:local` to regenerate after API changes.
 */

interface FlagResult {
    /** Flag key */
    key: string;
    /** Whether the flag is enabled for this context */
    enabled: boolean;
    /** Variant value (for multivariate flags) */
    variant?: string;
    /** Reason for the evaluation result */
    reason?: string;
    /** Additional payload data */
    payload?: Record<string, unknown>;
}
interface FlagContext {
    /** User ID for consistent targeting */
    userId?: string;
    /** Anonymous ID for pre-auth targeting */
    anonymousId?: string;
    /** User properties for targeting rules (plan, isAdmin, etc.) */
    properties?: Record<string, unknown>;
}
/**
 * Check a single feature flag (server-side evaluation)
 *
 * Uses POST /flags/evaluate for consistent, server-side targeting.
 * The server evaluates rollout percentage, premium targeting, etc.
 *
 * @example
 * ```typescript
 * const flag = await checkFlag(config, 'new-checkout', {
 *   userId: 'user-123',
 *   properties: { plan: 'pro' },
 * })
 *
 * if (flag.enabled) {
 *   // Show new checkout
 * }
 * ```
 */
declare function checkFlag(config: SylphxConfig, flagKey: string, context?: FlagContext): Promise<FlagResult>;
/**
 * Get multiple feature flags at once (batch evaluation)
 *
 * Evaluates all requested flags in a single API call.
 * More efficient than calling checkFlag() multiple times.
 *
 * @example
 * ```typescript
 * const flags = await getFlags(config, ['new-checkout', 'dark-mode', 'ai-features'], {
 *   userId: 'user-123',
 * })
 *
 * if (flags['new-checkout'].enabled) {
 *   // Show new checkout
 * }
 * ```
 */
declare function getFlags(config: SylphxConfig, flagKeys: string[], context?: FlagContext): Promise<Record<string, FlagResult>>;
/**
 * Get all feature flags for a context (bootstrap)
 *
 * Evaluates ALL flags for the app in a single API call.
 * Useful for bootstrapping the flag state on app load.
 *
 * @example
 * ```typescript
 * // Bootstrap all flags on app load
 * const allFlags = await getAllFlags(config, { userId: 'user-123' })
 *
 * // Use throughout the app
 * if (allFlags['new-checkout']?.enabled) {
 *   // Show new checkout
 * }
 * ```
 */
declare function getAllFlags(config: SylphxConfig, context?: FlagContext): Promise<Record<string, FlagResult>>;
/**
 * Check if a flag is enabled (boolean helper)
 *
 * @example
 * ```typescript
 * if (await isEnabled(config, 'new-checkout', { userId: 'user-123' })) {
 *   // Show new checkout
 * }
 * ```
 */
declare function isEnabled(config: SylphxConfig, flagKey: string, context?: FlagContext): Promise<boolean>;
/**
 * Get flag variant (for A/B tests)
 *
 * @example
 * ```typescript
 * const variant = await getVariant(config, 'checkout-experiment', {
 *   userId: 'user-123',
 * })
 *
 * switch (variant) {
 *   case 'control':
 *     // Show original checkout
 *     break
 *   case 'variant-a':
 *     // Show variant A
 *     break
 *   case 'variant-b':
 *     // Show variant B
 *     break
 * }
 * ```
 */
declare function getVariant(config: SylphxConfig, flagKey: string, context?: FlagContext): Promise<string | undefined>;
/**
 * Get flag payload (for remote config)
 *
 * @example
 * ```typescript
 * const payload = await getFlagPayload<{ maxItems: number }>(config, 'cart-config', {
 *   userId: 'user-123',
 * })
 *
 * console.log(payload?.maxItems) // 10
 * ```
 */
declare function getFlagPayload<T extends Record<string, unknown>>(config: SylphxConfig, flagKey: string, context?: FlagContext): Promise<T | undefined>;

/**
 * Email Functions
 *
 * Pure functions for transactional email operations.
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). The
 * contract is the single source of truth for `/email/configured`,
 * `/email/send`, `/email/send-templated`, and `/email/send-to-user`. SDK-
 * specific convenience shapes (scheduling options, domain management) stay
 * local — their routes are served by the Console plane and live alongside
 * the BaaS `emailEndpoints` in the contract's `emailAdmin` namespace.
 */

interface SendEmailOptions {
    /** Recipient email address */
    to: string;
    /** Email subject line */
    subject: string;
    /** HTML content */
    html: string;
    /** Plain text content (optional fallback) */
    text?: string;
    /** Reply-to address */
    replyTo?: string;
    /**
     * Sender email address (must be from a verified domain).
     * Falls back to the app environment default, then the platform FROM_EMAIL.
     *
     * @example `support@yourdomain.com`
     */
    fromEmail?: string;
    /**
     * Sender display name (used together with fromEmail).
     *
     * @example `Acme Support`
     */
    fromName?: string;
    /**
     * Idempotency key for safe retries (Stripe pattern)
     *
     * When provided, prevents duplicate email sends if the same request
     * is retried within 24 hours. Use a unique key per logical operation.
     *
     * @example `welcome-email-${userId}`
     */
    idempotencyKey?: string;
    /**
     * Custom email headers passed directly to the provider.
     * Use for email threading (In-Reply-To, References) or other RFC 5322 headers.
     * Do not override From, To, or Subject here.
     *
     * @example `{ 'In-Reply-To': '<abc@cubeage.com>', References: '<abc@cubeage.com>' }`
     */
    headers?: Record<string, string>;
}
interface SendTemplatedEmailOptions {
    /** Template name: 'welcome', 'verification', 'password_reset', 'security_alert' */
    template: 'welcome' | 'verification' | 'password_reset' | 'security_alert';
    /** Recipient email address */
    to: string;
    /** Template variables */
    data?: Record<string, unknown>;
    /**
     * Idempotency key for safe retries (Stripe pattern)
     *
     * @example `verification-email-${userId}`
     */
    idempotencyKey?: string;
}
interface SendToUserOptions {
    /** User ID to send to */
    userId: string;
    /** Email subject line */
    subject: string;
    /** HTML content */
    html: string;
    /** Plain text content (optional fallback) */
    text?: string;
    /**
     * Idempotency key for safe retries (Stripe pattern)
     *
     * @example `notification-${userId}-${Date.now()}`
     */
    idempotencyKey?: string;
}
interface ScheduleEmailOptions {
    /** Recipient email address */
    to: string;
    /** Recipient name (optional) */
    toName?: string;
    /** Email subject line */
    subject: string;
    /** HTML content */
    html?: string;
    /** Plain text content */
    text?: string;
    /** Reply-to address */
    replyTo?: string;
    /** From email (defaults to app's configured sender) */
    fromEmail?: string;
    /** From name */
    fromName?: string;
    /** ISO timestamp for when to send */
    scheduledFor: string;
    /** Template key for templated emails */
    templateKey?: string;
    /** Template variables */
    templateData?: Record<string, unknown>;
    /** Idempotency key to prevent duplicates */
    idempotencyKey?: string;
    /** Custom metadata */
    metadata?: Record<string, unknown>;
}
interface ScheduledEmail {
    id: string;
    to: string;
    toName: string | null;
    subject: string;
    status: 'pending' | 'queued' | 'sent' | 'cancelled' | 'failed';
    scheduledFor: string;
    sentAt: string | null;
    createdAt: string;
}
interface ScheduledEmailsResult {
    emails: ScheduledEmail[];
    total: number;
    hasMore: boolean;
}
interface ScheduledEmailStats {
    total: number;
    pending: number;
    queued: number;
    sent: number;
    cancelled: number;
    failed: number;
}
interface ListScheduledEmailsOptions {
    status?: 'pending' | 'queued' | 'sent' | 'cancelled' | 'failed' | 'all';
    limit?: number;
    offset?: number;
}
interface SendResult {
    id: string;
    success: boolean;
}
/**
 * Check if email service is configured for the app
 *
 * @example
 * ```typescript
 * const configured = await isEmailConfigured(config)
 * if (!configured) console.log('Please configure email settings')
 * ```
 */
declare function isEmailConfigured(config: SylphxConfig): Promise<boolean>;
/**
 * Send a custom email
 *
 * @example
 * ```typescript
 * const result = await sendEmail(config, {
 *   to: 'user@example.com',
 *   subject: 'Hello!',
 *   html: '<p>Welcome to our app!</p>',
 *   idempotencyKey: `welcome-${userId}`, // Safe retry
 * })
 * ```
 */
declare function sendEmail(config: SylphxConfig, options: SendEmailOptions): Promise<SendResult>;
/**
 * Send a templated email
 *
 * @example
 * ```typescript
 * await sendTemplatedEmail(config, {
 *   template: 'welcome',
 *   to: 'user@example.com',
 *   data: { name: 'John' },
 *   idempotencyKey: `welcome-${userId}`, // Safe retry
 * })
 * ```
 */
declare function sendTemplatedEmail(config: SylphxConfig, options: SendTemplatedEmailOptions): Promise<SendResult>;
/**
 * Send email to a user by their ID
 *
 * @example
 * ```typescript
 * await sendEmailToUser(config, {
 *   userId: 'user-123',
 *   subject: 'Account Update',
 *   html: '<p>Your account has been updated.</p>',
 *   idempotencyKey: `update-${userId}-${timestamp}`, // Safe retry
 * })
 * ```
 */
declare function sendEmailToUser(config: SylphxConfig, options: SendToUserOptions): Promise<SendResult>;
/**
 * Schedule an email for future delivery
 *
 * @example
 * ```typescript
 * const scheduled = await scheduleEmail(config, {
 *   to: 'user@example.com',
 *   subject: 'Reminder',
 *   html: '<p>Don\'t forget!</p>',
 *   scheduledFor: new Date(Date.now() + 86400000).toISOString(), // 24 hours
 * })
 * ```
 */
declare function scheduleEmail(config: SylphxConfig, options: ScheduleEmailOptions): Promise<ScheduledEmail>;
/**
 * List scheduled emails
 *
 * @example
 * ```typescript
 * const { emails, total } = await listScheduledEmails(config, {
 *   status: 'pending',
 *   limit: 20,
 * })
 * ```
 */
declare function listScheduledEmails(config: SylphxConfig, options?: ListScheduledEmailsOptions): Promise<ScheduledEmailsResult>;
/**
 * Get a scheduled email by ID
 *
 * @example
 * ```typescript
 * const email = await getScheduledEmail(config, 'email-123')
 * console.log(email.status)
 * ```
 */
declare function getScheduledEmail(config: SylphxConfig, emailId: string): Promise<ScheduledEmail>;
/**
 * Cancel a scheduled email
 *
 * @example
 * ```typescript
 * await cancelScheduledEmail(config, 'email-123')
 * ```
 */
declare function cancelScheduledEmail(config: SylphxConfig, emailId: string): Promise<void>;
/**
 * Reschedule an email
 *
 * @example
 * ```typescript
 * await rescheduleEmail(config, 'email-123', new Date(Date.now() + 3600000).toISOString())
 * ```
 */
declare function rescheduleEmail(config: SylphxConfig, emailId: string, scheduledFor: string): Promise<ScheduledEmail>;
/**
 * Get scheduled email statistics
 *
 * @example
 * ```typescript
 * const stats = await getScheduledEmailStats(config)
 * console.log(`${stats.pending} emails pending`)
 * ```
 */
declare function getScheduledEmailStats(config: SylphxConfig): Promise<ScheduledEmailStats>;

/**
 * Engagement Service Types
 *
 * Core types for streaks, leaderboards, and achievements.
 *
 * ## Architecture (ADR-004)
 *
 * Engagement uses **Inline Defaults + Auto-Discovery + Console Override**:
 * - Code provides optional inline defaults when calling APIs
 * - Platform auto-discovers/creates entities when first referenced
 * - Console can override names, descriptions, values without deployment
 */
/** Streak activity frequency */
type StreakFrequency = 'daily' | 'weekly' | 'custom';
/** Streak definition (auto-discovered or from Console) */
interface StreakDefinition {
    /** Unique identifier */
    id: string;
    /** Display name */
    name: string;
    /** Description */
    description?: string;
    /** Activity frequency */
    frequency: StreakFrequency;
    /** Grace period in hours (default: 0) */
    gracePeriodHours?: number;
    /** Whether streak resets on miss (default: true) */
    resetOnMiss?: boolean;
    /** Maximum streak value (optional cap) */
    maxValue?: number;
    /** Custom interval in hours (only for 'custom' frequency) */
    customIntervalHours?: number;
}
/** User's streak state (from platform) */
interface StreakState {
    /** Streak definition ID */
    streakId: string;
    /** Current streak count */
    current: number;
    /** Longest streak ever */
    longest: number;
    /** Last activity timestamp */
    lastActivityAt: string | null;
    /** When current streak will expire */
    expiresAt: string | null;
    /** Whether streak can be recovered (within grace period) */
    canRecover: boolean;
    /** Time remaining until expiry in ms */
    timeRemainingMs: number | null;
    /** User's timezone preference for streak expiry (IANA timezone, e.g., 'America/New_York') */
    userTimezone: string | null;
}
/** Activity recording input */
interface RecordActivityInput {
    /** Streak ID */
    streakId: string;
    /** User's IANA timezone (e.g., 'America/New_York') for calculating streak expiry at user's local midnight */
    userTimezone?: string;
    /** Optional metadata */
    metadata?: Record<string, unknown>;
    /**
     * Idempotency key for safe retries (Stripe pattern)
     *
     * Prevents duplicate streak recordings if the same request is retried.
     * Use a unique key per logical activity (e.g., `streak-${userId}-${date}`).
     */
    idempotencyKey?: string;
}
/** Activity recording result */
interface RecordActivityResult {
    /** Updated streak state */
    streak: StreakState;
    /** Whether this activity extended the streak */
    extended: boolean;
    /** Whether a new personal best was achieved */
    newPersonalBest: boolean;
    /** Previous streak value (for animation) */
    previousValue: number;
}
/** Leaderboard sort direction */
type LeaderboardSortDirection = 'asc' | 'desc';
/** Leaderboard reset period */
type LeaderboardResetPeriod = 'hourly' | 'daily' | 'weekly' | 'monthly' | 'never';
/** Score aggregation method */
type LeaderboardAggregation = 'max' | 'sum' | 'latest' | 'count' | 'min' | 'avg';
/** Leaderboard definition (auto-discovered or from Console) */
interface LeaderboardDefinition {
    /** Unique identifier */
    id: string;
    /** Display name */
    name: string;
    /** Description */
    description?: string;
    /** Sort direction (desc = higher is better) */
    sortDirection: LeaderboardSortDirection;
    /** Reset period */
    resetPeriod: LeaderboardResetPeriod;
    /** How to aggregate multiple scores from same user */
    aggregation: LeaderboardAggregation;
    /** Default privacy for entries */
    defaultPrivacy?: 'public' | 'friends' | 'anonymous';
    /** Maximum entries to keep per period */
    maxEntries?: number;
}
/** Leaderboard entry */
interface LeaderboardEntry {
    /** Rank (1-indexed) */
    rank: number;
    /** User ID (may be null for anonymous) */
    userId: string | null;
    /** Display name */
    displayName: string;
    /** Avatar URL */
    avatarUrl: string | null;
    /** Score/value */
    value: number;
    /** Whether this is the current user */
    isCurrentUser: boolean;
    /** Entry metadata */
    metadata?: Record<string, unknown>;
    /** When the score was submitted */
    submittedAt: string;
}
/** Leaderboard query options */
interface LeaderboardQueryOptions {
    /** Number of entries to return (default: 10) */
    limit?: number;
    /** Offset for pagination */
    offset?: number;
    /** Include surrounding entries for current user */
    includeSurrounding?: boolean;
    /** Number of surrounding entries (default: 2) */
    surroundingCount?: number;
}
/** Leaderboard query result */
interface LeaderboardResult {
    /** Leaderboard definition ID */
    leaderboardId: string;
    /** Period (for periodic leaderboards) */
    period?: string;
    /** Entries (top N or paginated) */
    entries: LeaderboardEntry[];
    /** Current user's entry (may not be in top entries) */
    currentUserEntry: LeaderboardEntry | null;
    /** Entries surrounding the current user (when includeSurrounding=true and user is outside main entries) */
    surroundingEntries?: LeaderboardEntry[];
    /** Total participants */
    totalParticipants: number;
    /** Next reset time (for periodic leaderboards) */
    nextResetAt: string | null;
}
/** Score submission input */
interface SubmitScoreInput {
    /** Leaderboard ID */
    leaderboardId: string;
    /** Score value */
    value: number;
    /** Optional metadata */
    metadata?: Record<string, unknown>;
}
/** Score submission result */
interface SubmitScoreResult {
    /** Whether submission was accepted */
    accepted: boolean;
    /** New rank (if in leaderboard) */
    rank: number | null;
    /** Previous best (if any) */
    previousBest: number | null;
    /** Whether this is a new personal best */
    newPersonalBest: boolean;
    /** Rank change (positive = improved) */
    rankChange: number | null;
}
/** Achievement type */
type AchievementType = 'standard' | 'hidden' | 'incremental';
/** Achievement tier */
type AchievementTier = 'bronze' | 'silver' | 'gold' | 'platinum' | 'diamond';
/** Achievement category */
type AchievementCategory = string;
/** Achievement criteria operator */
type CriteriaOperator = 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'contains';
/** Single criterion */
interface AchievementCriterion {
    /** Property to check (e.g., 'event', 'count', 'streak.daily') */
    property: string;
    /** Comparison operator */
    operator: CriteriaOperator;
    /** Value to compare against */
    value: string | number | boolean | string[] | number[];
}
/** Achievement criteria (AND logic within, OR between arrays) */
interface AchievementCriteria {
    /** Event name to track (for event-based achievements) */
    event?: string;
    /** Required count of events */
    count?: number;
    /** Additional conditions */
    conditions?: AchievementCriterion[];
}
/** Achievement definition (auto-discovered or from Console) */
interface AchievementDefinition {
    /** Unique identifier */
    id: string;
    /** Display name */
    name: string;
    /** Description (shown before unlock) */
    description: string;
    /** Description shown after unlock (optional) */
    unlockedDescription?: string;
    /** Achievement type */
    type: AchievementType;
    /** Tier/rarity */
    tier: AchievementTier;
    /** Category (app-defined) */
    category: AchievementCategory;
    /** Icon (Iconify name or URL) */
    icon: string;
    /** Points awarded */
    points?: number;
    /** Unlock criteria */
    criteria: AchievementCriteria;
    /** Target value for incremental achievements */
    target?: number;
    /** Whether to show in list before unlock */
    secret?: boolean;
    /** Order in list */
    order?: number;
}
/** User's achievement state */
interface UserAchievement {
    /** Achievement definition ID */
    achievementId: string;
    /** Whether unlocked */
    unlocked: boolean;
    /** Unlock timestamp */
    unlockedAt: string | null;
    /** Progress (for incremental) */
    progress: number;
    /** Target (for incremental) */
    target: number | null;
    /** Progress percentage (0-100) */
    progressPercent: number;
}
/** Achievement unlock event */
interface AchievementUnlockEvent {
    /** Achievement definition */
    achievement: AchievementDefinition;
    /** User achievement state */
    userAchievement: UserAchievement;
    /** Whether this is a new unlock (vs already unlocked) */
    isNew: boolean;
}
declare const ACHIEVEMENT_TIER_CONFIG: {
    readonly bronze: {
        readonly color: "#CD7F32";
        readonly points: 10;
    };
    readonly silver: {
        readonly color: "#C0C0C0";
        readonly points: 25;
    };
    readonly gold: {
        readonly color: "#FFD700";
        readonly points: 50;
    };
    readonly platinum: {
        readonly color: "#00CED1";
        readonly points: 100;
    };
    readonly diamond: {
        readonly color: "#B9F2FF";
        readonly points: 200;
    };
};
/**
 * Inline defaults for streak auto-discovery
 *
 * @example
 * ```typescript
 * await recordStreakActivity(config, { streakId: 'daily-login' }, userId, {
 *   name: 'Daily Login',
 *   frequency: 'daily',
 *   gracePeriodHours: 12,
 * })
 * ```
 */
interface StreakDefaults {
    /** Display name */
    name?: string;
    /** Description */
    description?: string;
    /** Activity frequency */
    frequency?: StreakFrequency;
    /** Grace period in hours (default: 0) */
    gracePeriodHours?: number;
    /** Whether streak resets on miss (default: true) */
    resetOnMiss?: boolean;
    /** Maximum streak value (optional cap) */
    maxValue?: number;
    /** Custom interval in hours (only for 'custom' frequency) */
    customIntervalHours?: number;
}
/**
 * Inline defaults for leaderboard auto-discovery
 *
 * @example
 * ```typescript
 * await submitScore(config, { leaderboardId: 'high-scores', value: 1500 }, userId, {
 *   name: 'High Scores',
 *   sortDirection: 'desc',
 *   resetPeriod: 'weekly',
 * })
 * ```
 */
interface LeaderboardDefaults {
    /** Display name */
    name?: string;
    /** Description */
    description?: string;
    /** Sort direction (desc = higher is better) */
    sortDirection?: LeaderboardSortDirection;
    /** Reset period */
    resetPeriod?: LeaderboardResetPeriod;
    /** How to aggregate multiple scores from same user */
    aggregation?: LeaderboardAggregation;
    /** Maximum entries to keep per period */
    maxEntries?: number;
}
/**
 * Inline defaults for achievement auto-discovery
 *
 * @example
 * ```typescript
 * await unlockAchievement(config, 'first-purchase', userId, {
 *   name: 'First Purchase',
 *   description: 'Made your first purchase',
 *   points: 100,
 *   tier: 'bronze',
 * })
 * ```
 */
interface AchievementDefaults {
    /** Display name */
    name?: string;
    /** Description (shown before unlock) */
    description?: string;
    /** Description shown after unlock */
    unlockedDescription?: string;
    /** Achievement type */
    type?: AchievementType;
    /** Tier/rarity */
    tier?: AchievementTier;
    /** Category (app-defined) */
    category?: AchievementCategory;
    /** Icon (Iconify name or URL) */
    icon?: string;
    /** Points awarded */
    points?: number;
    /** Target value for incremental achievements */
    target?: number;
    /** Whether to show in list before unlock */
    secret?: boolean;
}

/**
 * Engagement Functions
 *
 * Pure functions for streaks, leaderboards, and achievements.
 *
 * ## Architecture (ADR-004)
 *
 * Engagement uses **Inline Defaults + Auto-Discovery + Console Override**:
 * - Code provides optional inline defaults when calling functions
 * - Platform auto-discovers/creates entities when first referenced
 * - Console can override names, descriptions, values without deployment
 *
 * @example
 * ```typescript
 * import { unlockAchievement, recordStreakActivity, submitScore } from '@sylphx/sdk'
 *
 * // Unlock achievement with inline defaults (auto-discovered if doesn't exist)
 * await unlockAchievement(config, 'first-win', userId, {
 *   name: 'First Win',
 *   description: 'Won your first game',
 *   points: 100,
 *   tier: 'bronze',
 * })
 *
 * // Record streak activity with inline defaults
 * await recordStreakActivity(config, { streakId: 'daily-login' }, userId, {
 *   name: 'Daily Login',
 *   frequency: 'daily',
 *   gracePeriodHours: 12,
 * })
 *
 * // Submit leaderboard score with inline defaults
 * await submitScore(config, { leaderboardId: 'high-scores', value: 1500 }, userId, {
 *   name: 'High Scores',
 *   sortDirection: 'desc',
 *   resetPeriod: 'weekly',
 * })
 * ```
 */

/**
 * Get current streak state for a user
 *
 * @example
 * ```typescript
 * const streak = await getStreak(config, 'daily-challenge', userId)
 * console.log(`Current streak: ${streak.current}`)
 * console.log(`Expires in: ${streak.timeRemainingMs}ms`)
 * ```
 */
declare function getStreak(config: SylphxConfig, streakId: string, userId: string): Promise<StreakState>;
/**
 * Get all streak states for a user
 *
 * @example
 * ```typescript
 * const streaks = await getAllStreaks(config, userId)
 * for (const streak of streaks) {
 *   console.log(`${streak.streakId}: ${streak.current}`)
 * }
 * ```
 */
declare function getAllStreaks(config: SylphxConfig, userId: string): Promise<StreakState[]>;
/**
 * Record an activity to extend/maintain a streak
 *
 * If the streak doesn't exist, it will be auto-discovered with the provided defaults.
 * Console can override any values without deployment.
 *
 * @param config - SDK configuration
 * @param input - Activity input (streakId required)
 * @param userId - User ID
 * @param defaults - Optional inline defaults for auto-discovery
 *
 * @example
 * ```typescript
 * const result = await recordStreakActivity(config, {
 *   streakId: 'daily-challenge',
 * }, userId, {
 *   name: 'Daily Challenge',
 *   frequency: 'daily',
 *   gracePeriodHours: 12,
 * })
 *
 * if (result.extended) {
 *   console.log(`Streak extended to ${result.streak.current}!`)
 * }
 * if (result.newPersonalBest) {
 *   console.log('New personal best!')
 * }
 * ```
 */
declare function recordStreakActivity(config: SylphxConfig, input: RecordActivityInput, userId: string, defaults?: StreakDefaults): Promise<RecordActivityResult>;
/**
 * Recover a streak within grace period (may require payment/reward)
 *
 * @example
 * ```typescript
 * const result = await recoverStreak(config, 'daily-challenge', userId)
 * if (result.success) {
 *   console.log(`Streak recovered at ${result.streak.current}`)
 * }
 * ```
 */
declare function recoverStreak(config: SylphxConfig, streakId: string, userId: string): Promise<{
    success: boolean;
    streak: StreakState;
}>;

/**
 * Get leaderboard entries
 *
 * @example
 * ```typescript
 * const result = await getLeaderboard(config, 'high-scores', userId, {
 *   limit: 10,
 *   includeSurrounding: true,
 * })
 *
 * for (const entry of result.entries) {
 *   console.log(`#${entry.rank} ${entry.displayName}: ${entry.value}`)
 * }
 *
 * if (result.currentUserEntry) {
 *   console.log(`Your rank: #${result.currentUserEntry.rank}`)
 * }
 * ```
 */
declare function getLeaderboard(config: SylphxConfig, leaderboardId: string, userId: string | null, options?: LeaderboardQueryOptions): Promise<LeaderboardResult>;
/**
 * Submit a score to a leaderboard
 *
 * If the leaderboard doesn't exist, it will be auto-discovered with the provided defaults.
 * Console can override any values without deployment.
 *
 * @param config - SDK configuration
 * @param input - Score submission input (leaderboardId, value required)
 * @param userId - User ID
 * @param defaults - Optional inline defaults for auto-discovery
 *
 * @example
 * ```typescript
 * const result = await submitScore(config, {
 *   leaderboardId: 'high-scores',
 *   value: 1500,
 *   metadata: { level: 'hard' },
 * }, userId, {
 *   name: 'High Scores',
 *   sortDirection: 'desc',
 *   resetPeriod: 'weekly',
 *   aggregation: 'max',
 * })
 *
 * if (result.newPersonalBest) {
 *   console.log('New personal best!')
 * }
 * if (result.rank !== null) {
 *   console.log(`Ranked #${result.rank}`)
 * }
 * ```
 */
declare function submitScore(config: SylphxConfig, input: SubmitScoreInput, userId: string, defaults?: LeaderboardDefaults): Promise<SubmitScoreResult>;
/**
 * Get user's rank on a leaderboard (even if not in top entries)
 *
 * @example
 * ```typescript
 * const rank = await getUserRank(config, 'high-scores', userId)
 * if (rank) {
 *   console.log(`You are ranked #${rank.rank} with score ${rank.value}`)
 * }
 * ```
 */
declare function getUserLeaderboardRank(config: SylphxConfig, leaderboardId: string, userId: string): Promise<{
    rank: number;
    value: number;
} | null>;

/**
 * Get all achievements with user progress
 *
 * @example
 * ```typescript
 * const achievements = await getAchievements(config, userId)
 *
 * const unlocked = achievements.filter(a => a.unlocked)
 * console.log(`${unlocked.length} achievements unlocked`)
 *
 * const inProgress = achievements.filter(a => !a.unlocked && a.progress > 0)
 * for (const a of inProgress) {
 *   console.log(`${a.achievementId}: ${a.progress}/${a.target}`)
 * }
 * ```
 */
declare function getAchievements(config: SylphxConfig, userId: string): Promise<UserAchievement[]>;
/**
 * Get a single achievement with user progress
 *
 * @example
 * ```typescript
 * const achievement = await getAchievement(config, 'first-win', userId)
 * if (achievement?.unlocked) {
 *   console.log(`Unlocked at ${achievement.unlockedAt}`)
 * }
 * ```
 */
declare function getAchievement(config: SylphxConfig, achievementId: string, userId: string): Promise<UserAchievement | null>;
/**
 * Manually unlock an achievement
 *
 * If the achievement doesn't exist, it will be auto-discovered with the provided defaults.
 * Console can override any values without deployment.
 *
 * @param config - SDK configuration
 * @param achievementId - Achievement ID
 * @param userId - User ID
 * @param defaults - Optional inline defaults for auto-discovery
 *
 * @example
 * ```typescript
 * const result = await unlockAchievement(config, 'first-purchase', userId, {
 *   name: 'First Purchase',
 *   description: 'Made your first purchase',
 *   points: 100,
 *   tier: 'bronze',
 * })
 * if (result.isNew) {
 *   showAchievementToast(result.achievement)
 * }
 * ```
 */
declare function unlockAchievement(config: SylphxConfig, achievementId: string, userId: string, defaults?: AchievementDefaults): Promise<AchievementUnlockEvent>;
/**
 * Increment progress on an incremental achievement
 *
 * If the achievement doesn't exist, it will be auto-discovered with the provided defaults.
 * Console can override any values without deployment.
 *
 * @param config - SDK configuration
 * @param achievementId - Achievement ID
 * @param amount - Amount to increment
 * @param userId - User ID
 * @param defaults - Optional inline defaults for auto-discovery
 *
 * @example
 * ```typescript
 * // User collected an item
 * const result = await incrementAchievementProgress(config, 'collector-100', 1, userId, {
 *   name: 'Collector',
 *   description: 'Collect 100 items',
 *   type: 'incremental',
 *   target: 100,
 *   tier: 'silver',
 * })
 *
 * if (result.unlocked) {
 *   console.log('Achievement unlocked!')
 * } else {
 *   console.log(`Progress: ${result.progress}/${result.target}`)
 * }
 * ```
 */
declare function incrementAchievementProgress(config: SylphxConfig, achievementId: string, amount: number, userId: string, defaults?: AchievementDefaults): Promise<UserAchievement>;
/**
 * Get total achievement points for a user
 *
 * @example
 * ```typescript
 * const points = await getAchievementPoints(config, userId)
 * console.log(`Total points: ${points.total}`)
 * console.log(`This month: ${points.thisMonth}`)
 * ```
 */
declare function getAchievementPoints(config: SylphxConfig, userId: string): Promise<{
    total: number;
    thisMonth: number;
    rank: number | null;
}>;

/**
 * Organization Functions
 *
 * Pure functions for organization management - no hidden state.
 * Each function takes config as the first parameter.
 *
 * Uses REST API at /api/sdk/orgs/* for all operations.
 *
 * Types are re-exported from `@sylphx/contract` (ADR-084). The contract is
 * the single source of truth for every wire shape — this module only adds
 * ergonomic aliases (`Organization*` wrappers) and inline envelopes for
 * request bodies + member role updates.
 */

/**
 * The contract types `OrgMember.role` as a permissive `string` so it can
 * absorb any role stored in the DB (including legacy `'member'`). The SDK
 * surface is narrower — components key off the six-value role union — so
 * re-narrow here to keep `member.role` valid in existing call sites.
 */
type OrganizationMember = Omit<OrgMember, 'role'> & {
    role: OrgSdkRole;
};
type OrganizationInvitation = OrgInvitation;
/**
 * Membership info returned inline with `GET /orgs/:idOrSlug`. The endpoint
 * may return `null` when the caller has no role on the org (platform-admin
 * path) — SDK callers get the union on the response envelope, not here.
 */
type OrganizationMembership = MembershipInfo;
type UserOrganization = UserOrganizationMembership;
type OrganizationsListResult = {
    organizations: Organization[];
    total: number;
    limit: number;
    offset: number;
};
type OrgRole = OrgSdkRole;
type CreateOrgInput = CreateOrgInput$1;
type UpdateOrgInput = UpdateOrgInput$1 & {
    metadata?: Record<string, unknown> | null;
};
type InviteMemberInput = InviteMemberInput$1;
/**
 * Get all organizations the current user belongs to
 *
 * @example
 * ```typescript
 * const { organizations } = await getOrganizations(config)
 * ```
 */
declare function getOrganizations(config: SylphxConfig): Promise<UserOrganizationsResponse>;
/**
 * Admin-only organization list.
 *
 * `getOrganizations()` is intentionally user-scoped. Use this function only
 * from Platform operator contexts that are allowed to enumerate every org.
 *
 * @example
 * ```typescript
 * const { organizations, total } = await listOrganizations(adminConfig)
 * ```
 */
declare function listOrganizations(config: SylphxConfig, options?: {
    limit?: number;
    offset?: number;
}): Promise<OrganizationsListResult>;
/**
 * Get organization by ID or slug
 *
 * @example
 * ```typescript
 * const { organization, membership } = await getOrganization(config, 'my-org')
 * ```
 */
declare function getOrganization(config: SylphxConfig, orgIdOrSlug: string): Promise<{
    organization: Organization;
    membership: OrganizationMembership | null;
}>;
/**
 * Create a new organization
 *
 * @example
 * ```typescript
 * const { organization } = await createOrganization(config, {
 *   name: 'My Company',
 *   slug: 'my-company',
 * })
 * ```
 */
declare function createOrganization(config: SylphxConfig, input: CreateOrgInput): Promise<{
    organization: Organization;
}>;
/**
 * Update an organization
 *
 * @example
 * ```typescript
 * const { organization } = await updateOrganization(config, 'my-org', {
 *   name: 'New Name',
 * })
 * ```
 */
declare function updateOrganization(config: SylphxConfig, orgIdOrSlug: string, input: UpdateOrgInput): Promise<{
    organization: Organization;
}>;
/**
 * Delete an organization
 *
 * Requires super_admin role.
 *
 * @example
 * ```typescript
 * await deleteOrganization(config, 'my-org')
 * ```
 */
declare function deleteOrganization(config: SylphxConfig, orgIdOrSlug: string): Promise<{
    success: boolean;
}>;
/**
 * Get organization members
 *
 * @example
 * ```typescript
 * const { members } = await getOrganizationMembers(config, 'my-org')
 * ```
 */
declare function getOrganizationMembers(config: SylphxConfig, orgIdOrSlug: string): Promise<{
    members: OrganizationMember[];
}>;
/**
 * Invite a member to an organization
 *
 * Requires admin or super_admin role.
 *
 * @example
 * ```typescript
 * const { invitation } = await inviteOrganizationMember(config, 'my-org', {
 *   email: 'user@example.com',
 *   role: 'developer',
 * })
 * ```
 */
declare function inviteOrganizationMember(config: SylphxConfig, orgIdOrSlug: string, input: InviteMemberInput): Promise<{
    invitation: OrganizationInvitation;
}>;
/**
 * Update a member's role
 *
 * Requires admin or super_admin role.
 *
 * @example
 * ```typescript
 * const { member } = await updateOrganizationMemberRole(config, 'my-org', userId, 'admin')
 * ```
 */
declare function updateOrganizationMemberRole(config: SylphxConfig, orgIdOrSlug: string, memberId: string, role: OrgRole): Promise<{
    member: OrganizationMember;
}>;
/**
 * Remove a member from an organization
 *
 * Requires admin or super_admin role.
 *
 * @example
 * ```typescript
 * await removeOrganizationMember(config, 'my-org', userId)
 * ```
 */
declare function removeOrganizationMember(config: SylphxConfig, orgIdOrSlug: string, memberId: string): Promise<{
    success: boolean;
}>;
/**
 * Leave an organization
 *
 * @example
 * ```typescript
 * await leaveOrganization(config, 'my-org')
 * ```
 */
declare function leaveOrganization(config: SylphxConfig, orgIdOrSlug: string): Promise<{
    success: boolean;
}>;
/**
 * Get pending invitations for an organization
 *
 * Requires admin or super_admin role.
 *
 * @example
 * ```typescript
 * const { invitations } = await getOrganizationInvitations(config, 'my-org')
 * ```
 */
declare function getOrganizationInvitations(config: SylphxConfig, orgIdOrSlug: string): Promise<{
    invitations: OrganizationInvitation[];
}>;
/**
 * Accept an organization invitation
 *
 * @example
 * ```typescript
 * const { organization } = await acceptOrganizationInvitation(config, invitationToken)
 * ```
 */
declare function acceptOrganizationInvitation(config: SylphxConfig, token: string): Promise<{
    organization: Organization;
}>;
/**
 * Revoke a pending invitation
 *
 * Requires admin or super_admin role.
 *
 * @example
 * ```typescript
 * await revokeOrganizationInvitation(config, 'my-org', invitationId)
 * ```
 */
declare function revokeOrganizationInvitation(config: SylphxConfig, orgIdOrSlug: string, invitationId: string): Promise<{
    success: boolean;
}>;
/**
 * Check if user has a specific role or higher in the organization
 */
declare function hasRole(membership: OrganizationMembership | null, minimumRole: OrgRole): boolean;
/**
 * Check if user can manage members (invite, remove, change roles)
 */
declare function canManageMembers(membership: OrganizationMembership | null): boolean;
/**
 * Check if user can manage organization settings
 */
declare function canManageSettings(membership: OrganizationMembership | null): boolean;
/**
 * Check if user can delete the organization
 */
declare function canDeleteOrganization(membership: OrganizationMembership | null): boolean;

/**
 * Permission Functions
 *
 * Pure functions for permission management — no hidden state.
 * Each function takes config as the first parameter.
 *
 * Uses REST API at /permissions/* for project-scoped operations.
 * Uses REST API at /orgs/{orgId}/members/{memberId}/permissions for member checks.
 *
 * Types are self-contained (not dependent on generated OpenAPI spec) because
 * the RBAC routes were added after the last spec generation.
 */

/**
 * A permission definition within a project.
 *
 * Permissions are the atomic building blocks of RBAC roles.
 * They use colon-separated keys (e.g. "org:members:read", "payroll:approve").
 */
interface Permission {
    /** Prefixed permission ID (e.g. "perm_xxx") */
    id: string;
    /** Unique key within the project (e.g. "org:members:read") */
    key: string;
    /** Human-readable name */
    name: string;
    /** Optional description */
    description: string | null;
    /** Whether this is a system-defined permission (immutable) */
    isSystem: boolean;
    /** ISO 8601 creation timestamp */
    createdAt: string;
}
/**
 * Input for creating a custom permission.
 */
interface CreatePermissionInput {
    /** Unique key — colon-separated lowercase segments (e.g. "org:leave:approve") */
    key: string;
    /** Human-readable name */
    name: string;
    /** Optional description */
    description?: string;
}
/**
 * Resolved permissions for a member, including their assigned role.
 */
interface MemberPermissionsResult {
    /** Prefixed user ID of the member */
    memberId: string;
    /** Assigned role (null if no role assigned) */
    role: {
        key: string;
        name: string;
    } | null;
    /** Flattened, deduplicated permission keys from all assigned roles */
    permissions: string[];
}
/**
 * List all permissions for the current project.
 *
 * Returns both system-defined and custom permissions.
 * Requires a secret key (server-side only).
 *
 * @example
 * ```typescript
 * const { permissions } = await listPermissions(config)
 * console.log(permissions.map(p => p.key))
 * // ['org:members:read', 'org:members:manage', 'payroll:view', ...]
 * ```
 */
declare function listPermissions(config: SylphxConfig): Promise<{
    permissions: Permission[];
}>;
/**
 * Create a custom permission for the project.
 *
 * Permission keys must be colon-separated lowercase segments
 * (e.g. "org:leave:approve", "payroll:run").
 * Requires a secret key (server-side only).
 *
 * @example
 * ```typescript
 * const { permission } = await createPermission(config, {
 *   key: 'payroll:approve',
 *   name: 'Approve Payroll',
 *   description: 'Can approve payroll runs for the organization',
 * })
 * ```
 */
declare function createPermission(config: SylphxConfig, input: CreatePermissionInput): Promise<{
    permission: Permission;
}>;
/**
 * Delete a custom permission by key.
 *
 * System permissions cannot be deleted.
 * Role-permission assignments are removed automatically via cascading delete.
 * Requires a secret key (server-side only).
 *
 * @example
 * ```typescript
 * const { success } = await deletePermission(config, 'payroll:approve')
 * ```
 */
declare function deletePermission(config: SylphxConfig, permissionKey: string): Promise<{
    success: boolean;
}>;
/**
 * Get a member's resolved permissions within an organization.
 *
 * Returns the flattened, deduplicated set of permission keys from all
 * roles assigned to the member. Also returns their current role info.
 * Requires the caller to be a member of the same organization.
 *
 * @example
 * ```typescript
 * const result = await getMemberPermissions(config, 'my-org', 'usr_abc123')
 * console.log(result.permissions)
 * // ['org:members:read', 'payroll:view', 'payroll:approve']
 * console.log(result.role)
 * // { key: 'hr_manager', name: 'HR Manager' }
 * ```
 */
declare function getMemberPermissions(config: SylphxConfig, orgIdOrSlug: string, memberId: string): Promise<MemberPermissionsResult>;
/**
 * Check if a permission set includes a specific permission.
 *
 * Pure function — no API call. Use with permissions from JWT claims
 * (org_permissions) or from getMemberPermissions().
 *
 * @example
 * ```typescript
 * const permissions = ['org:members:read', 'payroll:view']
 * hasPermission(permissions, 'payroll:view')    // true
 * hasPermission(permissions, 'payroll:approve') // false
 * ```
 */
declare function hasPermission(permissions: string[], required: string): boolean;
/**
 * Check if a permission set includes ANY of the required permissions.
 *
 * Pure function — no API call. Returns true if at least one of the
 * required permissions is present.
 *
 * @example
 * ```typescript
 * const permissions = ['org:members:read', 'payroll:view']
 * hasAnyPermission(permissions, ['payroll:view', 'payroll:approve']) // true
 * hasAnyPermission(permissions, ['admin:full', 'super:admin'])       // false
 * ```
 */
declare function hasAnyPermission(permissions: string[], required: string[]): boolean;
/**
 * Check if a permission set includes ALL of the required permissions.
 *
 * Pure function — no API call. Returns true only if every required
 * permission is present.
 *
 * @example
 * ```typescript
 * const permissions = ['org:members:read', 'payroll:view', 'payroll:approve']
 * hasAllPermissions(permissions, ['payroll:view', 'payroll:approve']) // true
 * hasAllPermissions(permissions, ['payroll:view', 'admin:full'])      // false
 * ```
 */
declare function hasAllPermissions(permissions: string[], required: string[]): boolean;

/**
 * Role Functions
 *
 * Pure functions for role management — no hidden state.
 * Each function takes config as the first parameter.
 *
 * Uses REST API at /roles/* for project-scoped operations.
 * Uses REST API at /orgs/{orgId}/members/{memberId}/assign-role for assignment.
 *
 * Types are self-contained (not dependent on generated OpenAPI spec) because
 * the RBAC routes were added after the last spec generation.
 */

/**
 * A role definition within a project.
 *
 * Roles bundle permissions into named groups that can be assigned to
 * organization members (e.g. "HR Manager", "Payroll Admin").
 */
interface Role {
    /** Prefixed role ID (e.g. "role_xxx") */
    id: string;
    /** Unique key within the project (e.g. "hr_manager") */
    key: string;
    /** Human-readable name */
    name: string;
    /** Optional description */
    description: string | null;
    /** Whether this is a system-defined role (metadata immutable) */
    isSystem: boolean;
    /** Whether this role is automatically assigned to new org members */
    isDefault: boolean;
    /** Display order (lower = higher priority) */
    sortOrder: number;
    /** Permission keys assigned to this role */
    permissions: string[];
    /** ISO 8601 creation timestamp */
    createdAt: string;
    /** ISO 8601 update timestamp (present on roles route response) */
    updatedAt?: string;
}
/**
 * Input for creating a custom role.
 */
interface CreateRoleInput {
    /** Unique key — lowercase alphanumeric with underscores (e.g. "hr_manager") */
    key: string;
    /** Human-readable name */
    name: string;
    /** Optional description */
    description?: string;
    /** Permission keys to assign to this role */
    permissions?: string[];
    /** Whether to auto-assign to new org members */
    isDefault?: boolean;
    /** Display order (lower = higher priority) */
    sortOrder?: number;
}
/**
 * Input for updating an existing role.
 *
 * System role metadata (name, description) is immutable, but their
 * permissions can be changed.
 */
interface UpdateRoleInput {
    /** Human-readable name (ignored for system roles) */
    name?: string;
    /** Description (ignored for system roles) */
    description?: string | null;
    /** Permission keys to assign (replaces existing) */
    permissions?: string[];
    /** Whether to auto-assign to new org members */
    isDefault?: boolean;
    /** Display order */
    sortOrder?: number;
}
/**
 * List all roles for the current project.
 *
 * Returns both system-defined and custom roles, each with their
 * assigned permission keys. Requires a secret key (server-side only).
 *
 * @example
 * ```typescript
 * const { roles } = await listRoles(config)
 * for (const role of roles) {
 *   console.log(`${role.name}: ${role.permissions.join(', ')}`)
 * }
 * ```
 */
declare function listRoles(config: SylphxConfig): Promise<{
    roles: Role[];
}>;
/**
 * Get a single role by key, including its assigned permission keys.
 *
 * Requires a secret key (server-side only).
 *
 * @example
 * ```typescript
 * const { role } = await getRole(config, 'hr_manager')
 * console.log(role.permissions)
 * // ['org:members:read', 'payroll:view', 'payroll:approve']
 * ```
 */
declare function getRole(config: SylphxConfig, roleKey: string): Promise<{
    role: Role;
}>;
/**
 * Create a custom role with optional permission assignments.
 *
 * Role keys must be lowercase alphanumeric with underscores
 * (e.g. "hr_manager", "payroll_admin").
 * Requires a secret key (server-side only).
 *
 * @example
 * ```typescript
 * const { role } = await createRole(config, {
 *   key: 'hr_manager',
 *   name: 'HR Manager',
 *   description: 'Can manage employees and approve leave',
 *   permissions: ['org:members:read', 'leave:approve', 'payroll:view'],
 * })
 * ```
 */
declare function createRole(config: SylphxConfig, input: CreateRoleInput): Promise<{
    role: Role;
}>;
/**
 * Update a role's metadata and/or permission assignments.
 *
 * System role metadata (name, description) is immutable, but their
 * permissions can be changed. Passing `permissions` replaces the
 * entire permission set for the role.
 * Requires a secret key (server-side only).
 *
 * @example
 * ```typescript
 * const { role } = await updateRole(config, 'hr_manager', {
 *   permissions: ['org:members:read', 'org:members:manage', 'leave:approve'],
 * })
 * ```
 */
declare function updateRole(config: SylphxConfig, roleKey: string, input: UpdateRoleInput): Promise<{
    role: Role;
}>;
/**
 * Delete a custom role by key.
 *
 * System roles cannot be deleted. Roles with active member assignments
 * cannot be deleted — reassign members first.
 * Requires a secret key (server-side only).
 *
 * @example
 * ```typescript
 * const { success } = await deleteRole(config, 'hr_manager')
 * ```
 */
declare function deleteRole(config: SylphxConfig, roleKey: string): Promise<{
    success: boolean;
}>;
/**
 * Assign an RBAC role to an organization member.
 *
 * Replaces any existing role assignment (single-role mode).
 * Requires admin access to the organization.
 *
 * @example
 * ```typescript
 * const { success } = await assignMemberRole(config, 'my-org', 'usr_abc123', 'hr_manager')
 * ```
 */
declare function assignMemberRole(config: SylphxConfig, orgIdOrSlug: string, memberId: string, roleKey: string): Promise<{
    success: boolean;
}>;

/**
 * Secrets SDK
 *
 * Secure secrets management for applications.
 * Secrets are encrypted at rest with AES-256-GCM.
 *
 * @example
 * ```typescript
 * import { createConfig, getSecret, getSecrets, listSecretKeys } from '@sylphx/sdk'
 *
 * const config = createConfig({
 *   secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 * })
 *
 * // Get a single secret
 * const dbUrl = await getSecret(config, { key: 'DATABASE_URL' })
 * console.log(dbUrl.value) // postgres://...
 *
 * // Get multiple secrets at once
 * const secrets = await getSecrets(config, {
 *   keys: ['DATABASE_URL', 'API_KEY', 'JWT_SECRET']
 * })
 * console.log(secrets.DATABASE_URL) // postgres://...
 *
 * // List all secret keys (without values)
 * const keys = await listSecretKeys(config)
 * keys.forEach(k => console.log(k.key, k.description))
 * ```
 */

interface GetSecretInput {
    /** Secret key (uppercase, underscores allowed) */
    key: string;
    /** Optional environment ID override */
    environmentId?: string;
}
interface GetSecretResult {
    /** Secret key */
    key: string;
    /** Decrypted secret value */
    value: string;
    /** Version number */
    version: string;
}
interface GetSecretsInput {
    /** Array of secret keys to retrieve */
    keys: string[];
    /** Optional environment ID override */
    environmentId?: string;
}
/** Map of key -> decrypted value */
type GetSecretsResult = Record<string, string>;
interface ListSecretKeysInput {
    /** Optional environment ID filter */
    environmentId?: string;
}
interface SecretKeyInfo {
    /** Secret key name */
    key: string;
    /** Human-readable description */
    description: string | null;
    /** Current version */
    version: string;
    /** Whether this is environment-specific */
    isEnvironmentSpecific: boolean;
}
/**
 * Get a single secret value by key.
 *
 * @param config - SDK configuration
 * @param input - Secret key and optional environment ID
 * @returns Decrypted secret value
 * @throws Error if secret not found or access denied
 *
 * @example
 * ```typescript
 * const secret = await getSecret(config, { key: 'DATABASE_URL' })
 * const dbConnection = createPool(secret.value)
 * ```
 */
declare function getSecret(config: SylphxConfig, input: GetSecretInput): Promise<GetSecretResult>;
/**
 * Get multiple secrets at once.
 *
 * More efficient than multiple getSecret calls.
 *
 * @param config - SDK configuration
 * @param input - Array of secret keys
 * @returns Map of key -> decrypted value
 *
 * @example
 * ```typescript
 * const secrets = await getSecrets(config, {
 *   keys: ['DATABASE_URL', 'CACHE_URL', 'JWT_SECRET']
 * })
 *
 * const db = createPool(secrets.DATABASE_URL)
 * const cache = createCacheClient(secrets.CACHE_URL)
 * ```
 */
declare function getSecrets(config: SylphxConfig, input: GetSecretsInput): Promise<GetSecretsResult>;
/**
 * List all secret keys (without values).
 *
 * Useful for showing available secrets in UI or debugging.
 *
 * @param config - SDK configuration
 * @param input - Optional environment filter
 * @returns Array of secret key info
 *
 * @example
 * ```typescript
 * const keys = await listSecretKeys(config)
 * console.log('Available secrets:')
 * keys.forEach(k => console.log(`  ${k.key}: ${k.description}`))
 * ```
 */
declare function listSecretKeys(config: SylphxConfig, input?: ListSecretKeysInput): Promise<SecretKeyInfo[]>;
/**
 * Check if a secret exists without retrieving its value.
 *
 * @param config - SDK configuration
 * @param key - Secret key to check
 * @returns true if the secret exists
 *
 * @example
 * ```typescript
 * if (await hasSecret(config, 'STRIPE_SECRET_KEY')) {
 *   // Stripe is configured, enable payment features
 * }
 * ```
 */
declare function hasSecret(config: SylphxConfig, key: string): Promise<boolean>;
/**
 * Get all secrets for an environment as an object.
 *
 * Useful for loading all secrets into process.env at startup.
 *
 * @param config - SDK configuration
 * @param environmentId - Optional environment ID
 * @returns Object with all secrets
 *
 * @example
 * ```typescript
 * // Load all secrets into process.env at app startup
 * const secrets = await getAllSecrets(config)
 * Object.assign(process.env, secrets)
 * ```
 */
declare function getAllSecrets(config: SylphxConfig, environmentId?: string): Promise<GetSecretsResult>;

/**
 * Search SDK
 *
 * State-of-the-art search with full-text, semantic, and hybrid modes.
 * Powered by PostgreSQL tsvector + pgvector.
 *
 * @example
 * ```typescript
 * import { createConfig, indexDocument, search, batchIndex } from '@sylphx/sdk'
 *
 * const config = createConfig({
 *   secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey!,
 * })
 *
 * // Index a document
 * await indexDocument(config, {
 *   content: 'How to reset your password...',
 *   title: 'Password Reset Guide',
 *   namespace: 'help-articles',
 *   category: 'account',
 *   tags: ['password', 'security'],
 * })
 *
 * // Search (hybrid mode by default)
 * const results = await search(config, {
 *   query: 'forgot my login credentials',
 *   namespace: 'help-articles',
 *   searchType: 'hybrid',
 *   highlight: true,
 * })
 *
 * results.results.forEach(r => console.log(r.title, r.score, r.highlight))
 * ```
 */

interface IndexDocumentInput {
    /** Document title (weighted higher in search) */
    title?: string;
    /** Document content to index */
    content: string;
    /** Namespace for data isolation (e.g., 'products', 'articles') */
    namespace?: string;
    /** External document ID (your system's ID) */
    externalId?: string;
    /** URL or path */
    url?: string;
    /** Searchable metadata */
    metadata?: Record<string, unknown>;
    /** Category facet for filtering */
    category?: string;
    /** Type facet for filtering */
    type?: string;
    /** Tags facet for filtering */
    tags?: string[];
    /** Language for full-text search (default: english) */
    language?: string;
    /** Skip embedding generation (for keyword-only search) */
    skipEmbedding?: boolean;
    /** Embedding model to use */
    embeddingModel?: string;
}
interface IndexDocumentResult {
    /** Generated document ID */
    id: string;
    /** External ID if provided */
    externalId: string | null;
    /** Namespace */
    namespace: string;
}
interface BatchIndexInput {
    /** Documents to index (max 100) */
    documents: Array<{
        title?: string;
        content: string;
        externalId?: string;
        url?: string;
        metadata?: Record<string, unknown>;
        category?: string;
        type?: string;
        tags?: string[];
    }>;
    /** Namespace for all documents */
    namespace?: string;
    /** Language for full-text search */
    language?: string;
    /** Skip embedding generation */
    skipEmbedding?: boolean;
    /** Embedding model to use */
    embeddingModel?: string;
}
interface BatchIndexResult {
    /** Number of documents indexed */
    indexed: number;
    /** Generated document IDs */
    ids: string[];
}
type SearchType = 'keyword' | 'semantic' | 'hybrid';
interface SearchInput {
    /** Search query text */
    query: string;
    /** Namespace to search within */
    namespace?: string;
    /** Search type: keyword, semantic, or hybrid (default) */
    searchType?: SearchType;
    /** Maximum results to return (default: 10, max: 100) */
    limit?: number;
    /** Offset for pagination */
    offset?: number;
    /** Minimum similarity threshold (0-1) for semantic search */
    minSimilarity?: number;
    /** Enable typo tolerance (default: true) */
    typoTolerance?: boolean;
    /** Language for full-text search */
    language?: string;
    /** Facet filters */
    filters?: {
        category?: string;
        type?: string;
        tags?: string[];
        metadata?: Record<string, unknown>;
    };
    /** Include highlighted snippets (default: true) */
    highlight?: boolean;
    /** Embedding model for semantic search */
    embeddingModel?: string;
    /** Track this query for analytics (default: true) */
    trackQuery?: boolean;
    /** Session ID for analytics */
    sessionId?: string;
    /** User ID for analytics */
    userId?: string;
}
interface SearchResultItem {
    /** Document ID */
    id: string;
    /** External ID if set */
    externalId: string | null;
    /** Document title */
    title: string | null;
    /** Document content */
    content: string;
    /** Document URL */
    url: string | null;
    /** Document metadata */
    metadata: Record<string, unknown> | null;
    /** Category facet */
    category: string | null;
    /** Type facet */
    type: string | null;
    /** Tags facet */
    tags: string[] | null;
    /** Combined score */
    score: number;
    /** Keyword search score (if hybrid) */
    keywordScore?: number;
    /** Semantic search score (if hybrid) */
    semanticScore?: number;
    /** Highlighted snippet (if enabled) */
    highlight?: string;
}
interface SearchResponse {
    /** Search results */
    results: SearchResultItem[];
    /** Total results found */
    total: number;
    /** Original query */
    query: string;
    /** Search type used */
    searchType: SearchType;
    /** Query processing time in ms */
    latencyMs: number;
}
interface GetFacetsInput {
    /** Namespace to get facets from */
    namespace?: string;
    /** Facets to retrieve */
    facets?: Array<'category' | 'type' | 'tags'>;
    /** Filter facets by category or type */
    filters?: {
        category?: string;
        type?: string;
    };
}
interface FacetsResponse {
    facets: {
        category?: Array<{
            value: string;
            count: number;
        }>;
        type?: Array<{
            value: string;
            count: number;
        }>;
        tags?: Array<{
            value: string;
            count: number;
        }>;
    };
}
interface DeleteDocumentInput {
    /** Document ID to delete */
    id?: string;
    /** Or delete by external ID */
    externalId?: string;
    /** Namespace (required if using externalId) */
    namespace?: string;
}
interface UpsertDocumentInput extends IndexDocumentInput {
    /** External ID is required for upsert */
    externalId: string;
}
interface UpsertDocumentResult extends IndexDocumentResult {
    /** Whether the document was created (true) or updated (false) */
    created: boolean;
}
interface SearchStatsResult {
    /** Total documents indexed */
    totalDocuments: number;
    /** Documents with embeddings */
    documentsWithEmbedding: number;
    /** Documents by namespace */
    byNamespace: Array<{
        namespace: string;
        count: number;
    }>;
}
interface TrackClickInput {
    /** Search query ID */
    queryId: string;
    /** Clicked document ID */
    documentId: string;
    /** Position in results (1-indexed) */
    position: number;
}
/**
 * Index a document for search.
 *
 * Automatically generates tsvector for full-text search and
 * optional embedding for semantic search.
 *
 * @param config - SDK configuration
 * @param input - Document to index
 * @returns Indexed document info
 *
 * @example
 * ```typescript
 * const result = await indexDocument(config, {
 *   title: 'Getting Started Guide',
 *   content: 'Welcome to our platform...',
 *   namespace: 'docs',
 *   category: 'tutorials',
 *   tags: ['beginner', 'setup'],
 * })
 * ```
 */
declare function indexDocument(config: SylphxConfig, input: IndexDocumentInput): Promise<IndexDocumentResult>;
/**
 * Index multiple documents in a single batch.
 *
 * More efficient than multiple indexDocument calls.
 * Max 100 documents per batch.
 *
 * @param config - SDK configuration
 * @param input - Documents to index
 * @returns Batch index result
 *
 * @example
 * ```typescript
 * const result = await batchIndex(config, {
 *   namespace: 'products',
 *   documents: products.map(p => ({
 *     title: p.name,
 *     content: p.description,
 *     externalId: p.id,
 *     category: p.category,
 *   }))
 * })
 * console.log(`Indexed ${result.indexed} products`)
 * ```
 */
declare function batchIndex(config: SylphxConfig, input: BatchIndexInput): Promise<BatchIndexResult>;
/**
 * Search documents.
 *
 * Supports three search modes:
 * - `keyword`: Full-text search with typo tolerance
 * - `semantic`: AI-powered vector search
 * - `hybrid`: Combined ranking (default, best results)
 *
 * @param config - SDK configuration
 * @param input - Search query and options
 * @returns Search results with scores
 *
 * @example
 * ```typescript
 * // Hybrid search (recommended)
 * const results = await search(config, {
 *   query: 'how to change email address',
 *   namespace: 'help',
 *   searchType: 'hybrid',
 *   highlight: true,
 * })
 *
 * results.results.forEach(r => {
 *   console.log(`[${r.score.toFixed(3)}] ${r.title}`)
 *   console.log(r.highlight)
 * })
 * ```
 */
declare function search(config: SylphxConfig, input: SearchInput): Promise<SearchResponse>;
/**
 * Get facet counts for filtering.
 *
 * Returns counts of documents by category, type, and tags.
 *
 * @param config - SDK configuration
 * @param input - Facet options
 * @returns Facet counts
 *
 * @example
 * ```typescript
 * const facets = await getFacets(config, {
 *   namespace: 'products',
 *   facets: ['category', 'type'],
 * })
 *
 * facets.facets.category?.forEach(f => {
 *   console.log(`${f.value}: ${f.count} products`)
 * })
 * ```
 */
declare function getFacets(config: SylphxConfig, input?: GetFacetsInput): Promise<FacetsResponse>;
/**
 * Delete a document from the search index.
 *
 * @param config - SDK configuration
 * @param input - Document ID or external ID
 * @returns Deletion result
 *
 * @example
 * ```typescript
 * // Delete by internal ID
 * await deleteDocument(config, { id: 'doc-uuid-123' })
 *
 * // Delete by external ID
 * await deleteDocument(config, {
 *   externalId: 'product-456',
 *   namespace: 'products'
 * })
 * ```
 */
declare function deleteDocument(config: SylphxConfig, input: DeleteDocumentInput): Promise<{
    deleted: number;
}>;
/**
 * Upsert a document (insert or update by externalId).
 *
 * If a document with the same externalId exists, it will be replaced.
 * Otherwise, a new document is created.
 *
 * @param config - SDK configuration
 * @param input - Document to upsert (externalId required)
 * @returns Upsert result
 *
 * @example
 * ```typescript
 * const result = await upsertDocument(config, {
 *   externalId: 'product-123',
 *   title: 'Updated Product Name',
 *   content: 'New description...',
 *   namespace: 'products',
 * })
 * console.log(result.created ? 'Created' : 'Updated')
 * ```
 */
declare function upsertDocument(config: SylphxConfig, input: UpsertDocumentInput): Promise<UpsertDocumentResult>;
/**
 * Get search index statistics.
 *
 * @param config - SDK configuration
 * @param namespace - Optional namespace filter
 * @returns Index statistics
 *
 * @example
 * ```typescript
 * const stats = await getSearchStats(config)
 * console.log(`Total docs: ${stats.totalDocuments}`)
 * console.log(`With embeddings: ${stats.documentsWithEmbedding}`)
 * ```
 */
declare function getSearchStats(config: SylphxConfig, namespace?: string): Promise<SearchStatsResult>;
/**
 * Track a click on a search result.
 *
 * Use this to improve search quality over time.
 *
 * @param config - SDK configuration
 * @param input - Click information
 * @returns Success status
 *
 * @example
 * ```typescript
 * await trackClick(config, {
 *   queryId: searchResponse.queryId,
 *   documentId: clickedResult.id,
 *   position: 3,
 * })
 * ```
 */
declare function trackClick(config: SylphxConfig, input: TrackClickInput): Promise<{
    success: boolean;
}>;

/**
 * Database Functions
 *
 * Pure functions for retrieving Platform-provisioned database connection strings.
 * Server-side only (requires secret key `sk_*`).
 *
 * The Platform provisions a PostgreSQL database for each app and encrypts
 * the connection string. These functions retrieve and decrypt the connection
 * string at startup, so your app never needs to store it.
 *
 * @example
 * ```ts
 * import { createConfig, getDatabaseConnectionString } from '@sylphx/sdk'
 *
 * const config = createConfig({ secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey! })
 * const { connectionString } = await getDatabaseConnectionString(config)
 *
 * const pool = new Pool({ connectionString })
 * ```
 */

type DatabaseStatus = 'provisioning' | 'ready' | 'suspended' | 'failed' | 'deleted' | 'not_provisioned';
interface DatabaseConnectionInfo {
    /** Decrypted PostgreSQL connection string */
    connectionString: string;
    /** Database name */
    databaseName: string;
    /** Database role/user name */
    roleName: string;
    /** Database provisioning status */
    status: Exclude<DatabaseStatus, 'not_provisioned'>;
}
interface DatabaseStatusInfo {
    /** Current database status */
    status: DatabaseStatus;
    /** Provisioned region */
    region: string | null;
    /** PostgreSQL major version */
    pgVersion: number | null;
    /** Database name */
    databaseName: string | null;
}
/**
 * Get the provisioned PostgreSQL connection string for this app.
 *
 * Requires secret key authentication (server-side only).
 * The connection string is decrypted on the Platform and returned in plaintext.
 *
 * @throws `NOT_FOUND` if no database has been provisioned for this app
 * @throws `UNPROCESSABLE_ENTITY` if database is not yet ready
 *
 * @example
 * ```ts
 * const { connectionString } = await getDatabaseConnectionString(config)
 * const pool = new Pool({ connectionString })
 * ```
 */
declare function getDatabaseConnectionString(config: SylphxConfig): Promise<DatabaseConnectionInfo>;
/**
 * Get the current status of the provisioned database.
 *
 * Use this to check if the database is ready before attempting to connect.
 * Requires secret key authentication (server-side only).
 *
 * @example
 * ```ts
 * const { status } = await getDatabaseStatus(config)
 * if (status === 'ready') {
 *   // Connect to database
 * }
 * ```
 */
declare function getDatabaseStatus(config: SylphxConfig): Promise<DatabaseStatusInfo>;

/**
 * KV (Key-Value Store) Types
 *
 * Shared type definitions for KV operations.
 * Used by both server-side client (server/kv.ts) and React hooks (react/hooks/use-kv.ts).
 *
 * Single Source of Truth — never duplicate these types.
 */
/** TTL options for SET operations */
interface KvSetOptions {
    /** Expire time in seconds */
    ex?: number;
    /** Expire time in milliseconds */
    px?: number;
    /** Unix timestamp (seconds) at which the key will expire */
    exat?: number;
    /** Unix timestamp (milliseconds) at which the key will expire */
    pxat?: number;
    /** Only set the key if it does not already exist */
    nx?: boolean;
    /** Only set the key if it already exists */
    xx?: boolean;
}
/** Rate limit result */
interface KvRateLimitResult {
    /** Whether the request is allowed (under rate limit) */
    success: boolean;
    /** The rate limit maximum */
    limit: number;
    /** Remaining requests in current window */
    remaining: number;
    /** Unix timestamp (ms) when the rate limit resets */
    reset: number;
}
/** Sorted set member */
interface KvZMember {
    /** Member identifier */
    member: string;
    /** Score for ranking */
    score?: number;
}

/**
 * KV (Key-Value Store) Functions
 *
 * Pure functions for managed key-value storage.
 * Supports strings, hashes, lists, sorted sets, and built-in rate limiting.
 *
 * Keys are automatically namespaced per app, so no key collisions occur
 * between different apps on the same Platform.
 *
 * @example
 * ```ts
 * import { createConfig, kvSet, kvGet, kvDelete } from '@sylphx/sdk'
 *
 * const config = createConfig({ secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey! })
 *
 * // Basic key-value operations
 * await kvSet(config, { key: 'user:123', value: { name: 'Alice' }, ex: 3600 })
 * const user = await kvGet(config, 'user:123')
 * await kvDelete(config, 'user:123')
 * ```
 */

interface KvSetRequest extends KvSetOptions {
    /** Key to store */
    key: string;
    /** Value to store (any JSON-serializable value) */
    value: unknown;
    /** @deprecated Use `ex`. Kept for compatibility with early SDK adopters. */
    ttl?: number;
}
interface KvMsetRequest {
    /** Key-value pairs to set in a single atomic operation */
    entries: Array<{
        key: string;
        value: unknown;
    }>;
}
interface KvMgetRequest {
    /** Keys to retrieve */
    keys: string[];
}
interface KvHsetRequest {
    /** Hash key */
    key: string;
    /** Field-value pairs to set on the hash */
    fields: Record<string, unknown>;
}
interface KvHgetRequest {
    /** Hash key */
    key: string;
    /** Field to get */
    field: string;
}
interface KvHgetallRequest {
    /** Hash key */
    key: string;
}
interface KvLpushRequest {
    /** List key */
    key: string;
    /** Values to prepend (left push) */
    values: unknown[];
}
interface KvLrangeRequest {
    /** List key */
    key: string;
    /** Start index (0-based, negative counts from end) */
    start: number;
    /** Stop index (inclusive, negative counts from end) */
    stop: number;
}
interface KvZaddRequest {
    /** Sorted set key */
    key: string;
    /** Members with scores to add */
    members: KvZMember[];
}
interface KvZrangeRequest {
    /** Sorted set key */
    key: string;
    /** Start index or score */
    start: number | string;
    /** Stop index or score */
    stop: number | string;
    /** Return scores alongside members */
    withScores?: boolean;
    /** Reverse order */
    rev?: boolean;
    /** Treat start/stop as scores (BYSCORE) */
    byScore?: boolean;
}
interface KvIncrRequest {
    /** Key to increment */
    key: string;
    /** Amount to increment by (default: 1) */
    by?: number;
}
interface KvExpireRequest {
    /** Key to set expiry on */
    key: string;
    /** TTL in seconds */
    seconds: number;
}
interface KvRateLimitRequest {
    /** Rate limit key (e.g., userId, IP) */
    key?: string;
    /** @deprecated Use `key`. Kept for compatibility with early SDK adopters. */
    identifier?: string;
    /** Maximum requests allowed in the window */
    limit: number;
    /** Window duration in seconds */
    window: number | string;
}
/**
 * Set a key-value pair, with optional TTL and conditional flags.
 *
 * @example
 * ```ts
 * // Simple set
 * await kvSet(config, { key: 'session:abc', value: { userId: '123' }, ex: 86400 })
 *
 * // Set only if not exists (NX)
 * await kvSet(config, { key: 'lock:task', value: '1', ex: 30, nx: true })
 * ```
 */
declare function kvSet(config: SylphxConfig, request: KvSetRequest): Promise<{
    ok: boolean;
}>;
/**
 * Get a value by key.
 *
 * Returns `null` if the key does not exist or has expired.
 *
 * @example
 * ```ts
 * const session = await kvGet<{ userId: string }>(config, 'session:abc')
 * if (session) {
 *   console.log(session.userId)
 * }
 * ```
 */
declare function kvGet<T = unknown>(config: SylphxConfig, key: string): Promise<T | null>;
/**
 * Delete one or more keys.
 *
 * @example
 * ```ts
 * const { deleted } = await kvDelete(config, 'session:abc')
 * console.log(`Deleted ${deleted} keys`)
 * ```
 */
declare function kvDelete(config: SylphxConfig, key: string): Promise<{
    deleted: number;
}>;
/**
 * Check if a key exists.
 *
 * @example
 * ```ts
 * const { exists } = await kvExists(config, 'session:abc')
 * ```
 */
declare function kvExists(config: SylphxConfig, key: string): Promise<{
    exists: boolean;
}>;
/**
 * Set expiry on an existing key.
 *
 * @example
 * ```ts
 * await kvExpire(config, { key: 'session:abc', seconds: 3600 })
 * ```
 */
declare function kvExpire(config: SylphxConfig, request: KvExpireRequest): Promise<{
    ok: boolean;
}>;
/**
 * Increment a numeric value.
 *
 * @example
 * ```ts
 * const { value } = await kvIncr(config, { key: 'page:views', by: 1 })
 * ```
 */
declare function kvIncr(config: SylphxConfig, request: KvIncrRequest): Promise<{
    value: number;
}>;
/**
 * Set multiple key-value pairs atomically.
 */
declare function kvMset(config: SylphxConfig, request: KvMsetRequest): Promise<{
    ok: boolean;
}>;
/**
 * Get multiple values by keys in a single request.
 *
 * Returns `null` for keys that don't exist.
 */
declare function kvMget<T = unknown>(config: SylphxConfig, request: KvMgetRequest): Promise<Array<T | null>>;
/**
 * Set fields on a hash key.
 *
 * @example
 * ```ts
 * await kvHset(config, { key: 'user:123', fields: { name: 'Alice', age: 30 } })
 * ```
 */
declare function kvHset(config: SylphxConfig, request: KvHsetRequest): Promise<{
    count: number;
}>;
/**
 * Get a single field from a hash key.
 */
declare function kvHget<T = unknown>(config: SylphxConfig, request: KvHgetRequest): Promise<T | null>;
/**
 * Get all fields from a hash key.
 */
declare function kvHgetall<T extends Record<string, unknown> = Record<string, unknown>>(config: SylphxConfig, request: KvHgetallRequest): Promise<T | null>;
/**
 * Left-push values onto a list.
 *
 * @example
 * ```ts
 * const { length } = await kvLpush(config, { key: 'events', values: [event] })
 * ```
 */
declare function kvLpush(config: SylphxConfig, request: KvLpushRequest): Promise<{
    length: number;
}>;
/**
 * Get a range of elements from a list.
 *
 * @example
 * ```ts
 * // Get last 10 events
 * const items = await kvLrange(config, { key: 'events', start: 0, stop: 9 })
 * ```
 */
declare function kvLrange<T = unknown>(config: SylphxConfig, request: KvLrangeRequest): Promise<T[]>;
/**
 * Add members to a sorted set.
 *
 * @example
 * ```ts
 * // Add to leaderboard
 * await kvZadd(config, {
 *   key: 'leaderboard',
 *   members: [{ member: 'user:123', score: 1500 }],
 * })
 * ```
 */
declare function kvZadd(config: SylphxConfig, request: KvZaddRequest): Promise<{
    added: number;
}>;
/**
 * Get a range of members from a sorted set.
 *
 * @example
 * ```ts
 * // Get top 10 leaderboard entries
 * const entries = await kvZrange(config, {
 *   key: 'leaderboard',
 *   start: 0,
 *   stop: 9,
 *   rev: true,
 *   withScores: true,
 * })
 * ```
 */
declare function kvZrange(config: SylphxConfig, request: KvZrangeRequest): Promise<Array<{
    member: string;
    score?: number;
}>>;
/**
 * Check and consume a rate limit token using the platform sliding window.
 *
 * This is a built-in rate limiter — no external service needed.
 *
 * @example
 * ```ts
 * // 10 requests per 60 seconds per user
 * const result = await kvRateLimit(config, {
 *   key: `user:${userId}`,
 *   limit: 10,
 *   window: '60s',
 * })
 *
 * if (!result.success) {
 *   return Response.json({ error: 'Rate limit exceeded' }, { status: 429 })
 * }
 * ```
 */
declare function kvRateLimit(config: SylphxConfig, request: KvRateLimitRequest): Promise<KvRateLimitResult>;
interface KvScanOptions {
    /** Key pattern to match (e.g. 'user:*'). Defaults to '*' (all keys). */
    pattern?: string;
    /** Cursor for pagination. Use '0' to start a new scan (default). */
    cursor?: string;
    /** Hint for how many keys to return per iteration (1–1000). Default: 100. */
    count?: number;
}
interface KvScanResult {
    /** Keys matching the pattern (namespace prefix stripped). */
    keys: string[];
    /** Cursor for the next page. Pass this as `cursor` in the next call. */
    nextCursor: string;
    /** True when the full keyspace has been scanned (nextCursor is '0'). */
    done: boolean;
}
/**
 * Scan keys matching a pattern using cursor-based pagination.
 *
 * Unlike `KEYS`, SCAN is safe to use in production — it iterates incrementally.
 * Call repeatedly with the returned `nextCursor` until `done` is true.
 *
 * @example
 * ```ts
 * // Iterate all user keys
 * let cursor = '0'
 * do {
 *   const result = await kvScan(config, { pattern: 'user:*', cursor })
 *   for (const key of result.keys) console.log(key)
 *   cursor = result.nextCursor
 * } while (!result.done)
 * ```
 */
declare function kvScan(config: SylphxConfig, options?: KvScanOptions): Promise<KvScanResult>;
/**
 * Get a JSON value by key. Automatically parses the stored JSON string.
 *
 * Returns `null` if the key does not exist or has expired.
 *
 * @example
 * ```ts
 * const profile = await kvGetJSON<UserProfile>(config, 'user:123:profile')
 * if (profile) console.log(profile.name)
 * ```
 */
declare function kvGetJSON<T = unknown>(config: SylphxConfig, key: string): Promise<T | null>;
/**
 * Set a JSON value by key. Automatically serializes the value to JSON.
 *
 * @example
 * ```ts
 * await kvSetJSON(config, 'user:123:profile', { name: 'Alice', plan: 'pro' }, { ex: 3600 })
 * ```
 */
declare function kvSetJSON<T>(config: SylphxConfig, key: string, value: T, options?: KvSetOptions): Promise<{
    ok: boolean;
}>;

/**
 * Deploy Functions
 *
 * Pure functions for managing app deployments, environment variables,
 * and custom domains via the Platform Deploy API.
 *
 * Requires secret key authentication (`sk_*`).
 *
 * @example
 * ```ts
 * import { createConfig, triggerDeploy, getDeployStatus } from '@sylphx/sdk'
 *
 * const config = createConfig({ secretKey: createServerClient(process.env.SYLPHX_SECRET_URL!).secretKey! })
 *
 * // Trigger a deployment
 * const deploy = await triggerDeploy(config, { envId: 'env_prod_xxx' })
 *
 * // Poll for completion
 * const status = await getDeployStatus(config, deploy.envId)
 * console.log(status.status) // 'building' | 'deploying' | 'success' | 'failed'
 * ```
 */

type DeployStatus = 'queued' | 'building' | 'deploying' | 'success' | 'failed' | 'cancelled';
interface DeployInfo {
    /** Deployment ID */
    deploymentId: string;
    /** Environment ID */
    envId: string;
    /** Current deployment status */
    status: DeployStatus;
    /** Deployment URL */
    url?: string;
    /** Git commit SHA */
    commitSha?: string;
    /** Git branch */
    branch?: string;
    /** Deployment started at (ISO timestamp) */
    startedAt?: string;
    /** Deployment completed at (ISO timestamp) */
    completedAt?: string;
    /** Error message if failed */
    error?: string;
}
interface TriggerDeployRequest {
    /** Environment ID to deploy */
    envId: string;
    /** Force rebuild without cache */
    forceRebuild?: boolean;
}
interface RollbackDeployRequest {
    /** Environment ID to rollback */
    envId: string;
    /** Deployment ID to rollback to */
    deploymentId: string;
}
interface EnvVar {
    /** Environment variable key */
    key: string;
    /** Environment variable value */
    value: string;
    /** Whether value is sensitive (masked in logs) */
    sensitive?: boolean;
}
interface SetEnvVarRequest {
    /** Environment variable key */
    key: string;
    /** Environment variable value */
    value: string;
    /** Whether value is sensitive/secret */
    sensitive?: boolean;
}
interface DeployHistoryResponse {
    /** List of past deployments */
    deployments: DeployInfo[];
}
interface BuildLog {
    /** Log line text */
    text: string;
    /** Log timestamp (ISO) */
    timestamp?: string;
    /** Log level */
    level?: 'info' | 'warn' | 'error';
}
interface BuildLogHistoryResponse {
    /** Log lines */
    logs: BuildLog[];
}
/**
 * Trigger a new deployment for an environment.
 *
 * @example
 * ```ts
 * const deploy = await triggerDeploy(config, { envId: 'env_prod_xxx' })
 * console.log(`Deployment ${deploy.deploymentId} started`)
 * ```
 */
declare function triggerDeploy(config: SylphxConfig, request: TriggerDeployRequest): Promise<DeployInfo>;
/**
 * Get the current deployment status for an environment.
 *
 * @example
 * ```ts
 * const { status } = await getDeployStatus(config, 'env_prod_xxx')
 * if (status === 'success') {
 *   console.log('Deployment succeeded!')
 * }
 * ```
 */
declare function getDeployStatus(config: SylphxConfig, envId: string): Promise<DeployInfo>;
/**
 * Get deployment history for an environment.
 *
 * @example
 * ```ts
 * const { deployments } = await getDeployHistory(config, 'env_prod_xxx')
 * const lastDeploy = deployments[0]
 * ```
 */
declare function getDeployHistory(config: SylphxConfig, envId: string): Promise<DeployHistoryResponse>;
/**
 * Rollback an environment to a previous deployment.
 *
 * @example
 * ```ts
 * await rollbackDeploy(config, {
 *   envId: 'env_prod_xxx',
 *   deploymentId: 'dep_abc123',
 * })
 * ```
 */
declare function rollbackDeploy(config: SylphxConfig, request: RollbackDeployRequest): Promise<DeployInfo>;
/**
 * Get stored build log history for an environment.
 *
 * For live log streaming during an active build, use the SSE endpoint
 * directly or the `useDeployLogs` React hook.
 *
 * @example
 * ```ts
 * const { logs } = await getBuildLogHistory(config, 'env_prod_xxx')
 * for (const log of logs) {
 *   console.log(log.text)
 * }
 * ```
 */
declare function getBuildLogHistory(config: SylphxConfig, envId: string): Promise<BuildLogHistoryResponse>;
/**
 * List environment variables for a deployment environment.
 *
 * Sensitive values are masked in the response.
 *
 * @example
 * ```ts
 * const envVars = await listEnvVars(config, 'env_prod_xxx')
 * ```
 */
declare function listEnvVars(config: SylphxConfig, envId: string): Promise<EnvVar[]>;
/**
 * Set (create or update) an environment variable.
 *
 * @example
 * ```ts
 * await setEnvVar(config, 'env_prod_xxx', {
 *   key: 'DATABASE_URL',
 *   value: 'postgresql://...',
 *   sensitive: true,
 * })
 * ```
 */
declare function setEnvVar(config: SylphxConfig, envId: string, request: SetEnvVarRequest): Promise<EnvVar>;
/**
 * Delete an environment variable.
 *
 * @example
 * ```ts
 * await deleteEnvVar(config, 'env_prod_xxx', 'DATABASE_URL')
 * ```
 */
declare function deleteEnvVar(config: SylphxConfig, envId: string, key: string): Promise<{
    deleted: boolean;
}>;

/**
 * Monitoring Functions
 *
 * Pure functions for error tracking and log capture.
 * Works client-side and server-side.
 *
 * ## Industry Patterns
 * - **Error grouping via fingerprinting** — Same error only billed once (Sentry pattern)
 * - **Adaptive sampling** — Automatic sample rate adjustment based on quota usage
 * - **Breadcrumb trails** — Contextual trail leading to errors
 *
 * @example
 * ```ts
 * import { createConfig, captureException, captureMessage } from '@sylphx/sdk'
 *
 * const config = createConfig({ appId: process.env.NEXT_PUBLIC_SYLPHX_APP_ID! })
 *
 * // Capture errors
 * try {
 *   await riskyOperation()
 * } catch (err) {
 *   await captureException(config, err as Error)
 * }
 *
 * // Capture log messages
 * await captureMessage(config, 'User completed onboarding', { level: 'info' })
 * ```
 */

type MonitoringSeverity = 'fatal' | 'error' | 'warning' | 'info';
interface ExceptionFrame {
    /** Source filename */
    filename?: string;
    /** Function name */
    function?: string;
    /** Line number */
    lineno?: number;
    /** Column number */
    colno?: number;
}
interface ExceptionValue {
    /** Exception class/type (e.g., "TypeError") */
    type: string;
    /** Exception message */
    value: string;
    /** Stack trace frames (innermost first) */
    stacktrace?: {
        frames?: ExceptionFrame[];
    };
}
interface Breadcrumb {
    /** Breadcrumb type (e.g., "navigation", "http", "ui.click") */
    type?: string;
    /** Log level */
    level?: MonitoringSeverity;
    /** Breadcrumb message */
    message?: string;
    /** Breadcrumb data */
    data?: Record<string, unknown>;
    /** Unix timestamp (seconds) */
    timestamp?: number;
}
interface CaptureExceptionRequest {
    /** Exception value(s) — first is primary, rest are chained causes */
    exception: {
        values: ExceptionValue[];
    };
    /** Severity level (default: "error") */
    level?: MonitoringSeverity;
    /** Current page route */
    route?: string;
    /** User agent string */
    userAgent?: string;
    /** App release version */
    release?: string;
    /** Environment name (e.g., "production", "staging") */
    environment?: string;
    /** Custom tags for filtering */
    tags?: Record<string, string>;
    /** Extra context data */
    extra?: Record<string, unknown>;
    /** Breadcrumb trail leading to the error */
    breadcrumbs?: Breadcrumb[];
    /** Custom fingerprint for grouping (overrides automatic grouping) */
    fingerprint?: string[];
}
interface CaptureMessageRequest {
    /** Log message */
    message: string;
    /** Severity level (default: "info") */
    level?: MonitoringSeverity;
    /** Current page route */
    route?: string;
    /** App release version */
    release?: string;
    /** Custom tags for filtering */
    tags?: Record<string, string>;
    /** Extra context data */
    extra?: Record<string, unknown>;
}
interface MonitoringResponse {
    /** Internal event ID */
    eventId: string;
    /** Whether this is a new unique error (true = billed, false = duplicate = free) */
    isNewError: boolean;
    /** Current quota usage percentage (0-100+). Present when >= 50%. */
    quotaUsage?: number;
    /**
     * Recommended client-side sample rate (0.0-1.0).
     * Reduce your error capture rate to this value when quota is high.
     * Present when quotaUsage >= 50%.
     */
    recommendedSampleRate?: number;
}
/**
 * Capture an exception for error tracking.
 *
 * Errors with the same fingerprint are grouped automatically.
 * Duplicate occurrences of the same error are FREE (only new unique
 * errors count against your quota).
 *
 * @example
 * ```ts
 * try {
 *   await processPayment(amount)
 * } catch (err) {
 *   const result = await captureException(config, err as Error, {
 *     tags: { paymentProvider: 'stripe' },
 *     extra: { amount, userId },
 *   })
 * }
 * ```
 */
declare function captureException(config: SylphxConfig, error: Error, options?: Omit<CaptureExceptionRequest, 'exception'>): Promise<MonitoringResponse>;
/**
 * Capture an exception with full control over the exception payload.
 *
 * Use this for structured exception capture with custom types, chained
 * causes, or when not working with native Error objects.
 */
declare function captureExceptionRaw(config: SylphxConfig, request: CaptureExceptionRequest): Promise<MonitoringResponse>;
/**
 * Capture a log message for monitoring.
 *
 * Like `captureException` but for non-error events (warnings, info, etc.).
 * Messages with the same content are grouped automatically.
 *
 * @example
 * ```ts
 * // Info log
 * await captureMessage(config, 'Payment webhook received', {
 *   level: 'info',
 *   tags: { provider: 'stripe', event: 'payment.succeeded' },
 * })
 *
 * // Warning
 * await captureMessage(config, 'Slow query detected', {
 *   level: 'warning',
 *   extra: { queryMs: 2400, query: sql },
 * })
 * ```
 */
declare function captureMessage(config: SylphxConfig, message: string, options?: Omit<CaptureMessageRequest, 'message'>): Promise<MonitoringResponse>;

/**
 * Sandbox Client
 *
 * Ephemeral compute sandbox API — SOTA direct-connection design.
 *
 * ## Architecture
 *
 * POST /sandboxes → Platform provisions sandbox, waits for runtime readiness,
 * returns { endpoint, token }. All subsequent exec/files/pty operations
 * go DIRECTLY to the sandbox exec-server — Platform is not in the data path.
 *
 * ```
 * SDK.create() ──→ Platform API (lifecycle only)
 *                       ↓ returns endpoint + token
 * SDK.exec()  ──→ sandbox exec-server (direct, SSE stream)
 * SDK.files   ──→ sandbox exec-server (direct, REST)
 * SDK.pty()   ──→ sandbox exec-server (direct, WebSocket)
 * ```
 *
 * ## Usage
 *
 * ```typescript
 * import { createServerClient, SandboxClient } from '@sylphx/sdk'
 *
 * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *
 * // Create sandbox (Platform waits for the runtime before returning)
 * const sandbox = await SandboxClient.create(config)
 *
 * // Stream exec output in real-time
 * for await (const event of sandbox.exec(['npm', 'install'])) {
 *   if (event.type === 'stdout') process.stdout.write(event.data)
 *   if (event.type === 'exit') console.log('exit', event.exitCode)
 * }
 *
 * // File operations
 * await sandbox.files.write('/workspace/app.py', 'print("hello")')
 * const content = await sandbox.files.read('/workspace/output.txt')
 *
 * // Terminate when done
 * await sandbox.terminate()
 * ```
 *
 * ## Auth
 *   Requires sk_* secret key (server-side only).
 */

interface SandboxOptions {
    /** OCI image from a connected registry. Omit to use the environment default. */
    image?: string;
    /**
     * Request timeout for the create lifecycle call.
     * Defaults to the SDK's sandbox-create budget, which matches the Runtime
     * API readiness wait plus transport margin.
     */
    createTimeoutMs?: number;
    /** Idle timeout in ms before auto-termination (default: 300_000 = 5 min) */
    idleTimeoutMs?: number;
    /** Scratch storage size in GiB at /data, scoped to the sandbox lifecycle. */
    storageGi?: number;
    /** Managed machine size. Defaults to `standard`. */
    machine?: SandboxMachineSize;
    /** Environment variables injected into the sandbox container */
    env?: Record<string, string>;
    /**
     * Shared volume mounts from org-level managed volumes.
     * Use volumes created with sharing="shared" when multiple sandboxes need
     * concurrent filesystem access.
     */
    volumeMounts?: Array<{
        /** Volume resource ID (from `sylphx volumes list`) */
        volumeId: string;
        /** Absolute path inside the container (e.g. "/shared") */
        mountPath: string;
        /** Optional sub-path within the volume */
        subPath?: string;
        /** Read-only mount (default: false) */
        readOnly?: boolean;
    }>;
    /**
     * Platform-managed workspace mounts.
     * Prefer this over raw volumeMounts for agent/IDE durable filesystems: the
     * Platform resolves the workspace's backing volume, PVC, quota, and lineage.
     */
    workspaceMounts?: Array<{
        /** Workspace ID from the managed workspaces API. */
        workspaceId: string;
        /** Absolute path inside the container (e.g. "/workspace") */
        mountPath: string;
        /** Optional workspace-relative sub-path view. */
        subPath?: string;
        /** Read-only mount (default: false) */
        readOnly?: boolean;
    }>;
    /**
     * Per-sandbox network egress policy. Omit for today's default: unrestricted
     * outbound network access. Opt into `mode: 'allowlist'` to confine the
     * sandbox's outbound connections to a fixed set of domains (exact, e.g.
     * `"api.openai.com"`) or wildcard subdomains (e.g. `"*.github.com"` —
     * matches subdomains only, never the bare domain). Allowlist sandboxes
     * bypass the warm pool (cold create only).
     */
    egress?: {
        mode: 'open';
    } | {
        mode: 'allowlist';
        allowDomains: string[];
    };
}
type SandboxMachineSize = MachineSize;
/** SSE event emitted by sandbox.exec() */
type ExecEvent = {
    type: 'stdout';
    data: string;
} | {
    type: 'stderr';
    data: string;
} | {
    type: 'exit';
    exitCode: number;
    durationMs: number;
    timedOut?: boolean;
} | {
    type: 'error';
    message: string;
};
/** Non-streaming exec result (all output collected, returned at once) */
interface ExecResult {
    stdout: string;
    stderr: string;
    exitCode: number;
    durationMs: number;
}
/** @deprecated Use ExecResult */
type CommandResult = ExecResult;
/** @deprecated File operations are now handled by SandboxFiles class */
interface SandboxFile {
    path: string;
    content: string;
    encoding?: 'utf8' | 'base64';
}
interface ExecOptions {
    cwd?: string;
    env?: Record<string, string>;
    timeout?: number;
    stdin?: string;
}
interface ProcessStartOptions {
    /** Command + args (e.g. ['npm', 'install']) */
    command: string[];
    /** Working directory */
    cwd?: string;
    /** Environment variables */
    env?: Record<string, string>;
    /** Hard timeout in seconds (0 = no timeout) */
    timeoutSeconds?: number;
    /** Open stdin pipe for writing */
    stdin?: boolean;
}
interface ProcessInfo {
    id: string;
    pid: number;
    command: string[];
    cwd: string;
    status: 'running' | 'exited' | 'killed' | 'timeout';
    exitCode: number | null;
    signal: string | null;
    startedAt: string;
    exitedAt: string | null;
    durationMs: number | null;
    stdout: string;
    stderr: string;
}
interface ProcessSummary {
    id: string;
    pid: number;
    command: string[];
    status: 'running' | 'exited' | 'killed' | 'timeout';
    exitCode: number | null;
    startedAt: string;
    exitedAt: string | null;
    durationMs: number | null;
}
/** SSE event from a process stream */
type ProcessEvent = {
    type: 'stdout';
    pid: number;
    data: string;
} | {
    type: 'stderr';
    pid: number;
    data: string;
} | {
    type: 'exit';
    pid: number;
    exitCode: number;
};
interface WatchOptions {
    /** Path to watch (relative to /workspace or absolute) */
    path: string;
    /** Watch subdirectories recursively (default: true) */
    recursive?: boolean;
    /** Additional patterns to ignore */
    ignore?: string[];
}
interface WatchEntry {
    path: string;
    recursive: boolean;
    createdAt: string;
}
/** File change event delivered via SSE /events stream */
interface FileEvent {
    type: 'file';
    path: string;
    event: 'created' | 'modified' | 'deleted';
}
type BrowserSessionStatus = 'starting' | 'ready' | 'exited';
/** Persistent headful browser session running inside the sandbox. */
interface BrowserSessionInfo {
    id: string;
    status: BrowserSessionStatus;
    /** OS pid of the Chrome browser process (0 if not surfaced). */
    pid: number;
    /** Remote-debugging port the headful Chrome listens on (loopback, private to the sandbox). */
    debugPort: number;
    /**
     * Sandbox-internal loopback CDP/DevTools WebSocket endpoint (ws://127.0.0.1:…).
     * NOT reachable from outside the sandbox — connect via `connectUrl()` /
     * `connect()` which route through the authenticated proxy. Surfaced for
     * introspection only.
     */
    cdpEndpoint: string | null;
    /** Persistent profile directory on the workspace volume. */
    userDataDir: string;
    /** Virtual display Chrome renders to. */
    display: string;
    startedAt: string;
    exitedAt: string | null;
}
interface BrowserCreateOptions {
    /**
     * Persistent profile to attach (defaults to the new session id). Pass an
     * explicit, stable value to deliberately reuse cookies/localStorage/auth
     * across sessions — the profile lives on the workspace volume and survives
     * session teardown.
     */
    profile?: string;
}
type ComputerSessionStatus = 'starting' | 'ready' | 'exited';
/** Persistent desktop (computer-use) session running inside the sandbox. */
interface ComputerSessionInfo {
    id: string;
    status: ComputerSessionStatus;
    /** OS pid of the Xvfb X-server process. */
    pid: number;
    /** The X display the desktop renders to (e.g. ":100"), private to the sandbox. */
    display: string;
    /** Screen geometry the desktop renders at (e.g. "1280x800x24"). */
    screen: string;
    /** Per-session scratch directory on the workspace volume. */
    workspaceDir: string;
    startedAt: string;
    exitedAt: string | null;
}
/** Image-encoding format for a desktop screenshot. */
type ComputerScreenshotFormat = 'png' | 'jpeg';
/**
 * A computer-use input action (mirrors Anthropic Computer Use / OpenAI CUA).
 * Coordinates are device pixels on the session display. The exec-server
 * validates every action structurally before executing it.
 */
type ComputerInputAction = {
    action: 'mouse_move';
    x: number;
    y: number;
} | {
    action: 'left_click';
    x?: number;
    y?: number;
} | {
    action: 'right_click';
    x?: number;
    y?: number;
} | {
    action: 'middle_click';
    x?: number;
    y?: number;
} | {
    action: 'double_click';
    x?: number;
    y?: number;
} | {
    action: 'type';
    text: string;
} | {
    action: 'key';
    keys: string;
} | {
    action: 'scroll';
    x: number;
    y: number;
    dx: number;
    dy: number;
} | {
    action: 'drag';
    x: number;
    y: number;
    toX: number;
    toY: number;
};
/**
 * Live introspection of a desktop session (what the agent would otherwise have
 * to guess from a screenshot). Every field is best-effort on the server: an
 * unavailable piece is null / empty rather than failing the whole status.
 */
interface ComputerDesktopStatus {
    /** The X display the desktop renders to (e.g. ":100"). */
    display: string;
    /** Screen geometry the desktop was launched at (e.g. "1280x800x24"). */
    screen: string;
    /** Whether the window manager (openbox) process is running. */
    windowManagerRunning: boolean;
    /** Current display resolution in pixels, or null if it could not be read. */
    resolution: {
        width: number;
        height: number;
    } | null;
    /** The focused window, or null if there is no active window. */
    activeWindow: {
        id: number;
        title: string;
        pid: number | null;
    } | null;
    /** Visible top-level windows (capped), with geometry. */
    windows: Array<{
        id: number;
        title: string;
        x: number;
        y: number;
        width: number;
        height: number;
    }>;
    /** Current mouse cursor position, or null if it could not be read. */
    cursor: {
        x: number;
        y: number;
    } | null;
    /** Known GUI apps currently running (best-effort, by process name). */
    runningApps: string[];
}
/**
 * One OCR-detected on-screen text run, with its pixel bounding box. The
 * perception layer (ADR-207) that lets the agent target UI *text* precisely
 * instead of guessing pixel coordinates.
 */
interface ComputerUiElement {
    /** The recognised text run (trimmed). */
    text: string;
    /** Left edge of the bounding box, in device pixels on the session display. */
    left: number;
    /** Top edge of the bounding box, in device pixels. */
    top: number;
    /** Bounding-box width in pixels. */
    width: number;
    /** Bounding-box height in pixels. */
    height: number;
    /** OCR confidence for this run (0–100). */
    confidence: number;
}
/**
 * An OCR snapshot of the live desktop: every recognised text run with its
 * bounding box, plus the screen geometry the boxes are relative to. Best-effort
 * on the server — on OCR timeout/failure `elements` is empty (with the real
 * screen size) rather than an error. Click-by-text matching belongs in the
 * caller's harness; this surfaces only the text + boxes.
 */
interface ComputerUiSnapshot {
    /** Recognised text runs (capped at 500), each with a pixel bounding box. */
    elements: ComputerUiElement[];
    /** Screen geometry the bounding boxes are relative to, in pixels. */
    screen: {
        width: number;
        height: number;
    };
    /** ISO-8601 timestamp the snapshot was captured at. */
    capturedAt: string;
}

interface SandboxRecord {
    id: string;
    status: 'starting' | 'running' | 'idle' | 'terminated' | 'error';
    image: string;
    /** Managed machine size selected for this sandbox. */
    machine: SandboxMachineSize | null;
    /** Public HTTPS endpoint: https://sbx-xxx.sandboxes.sylphx.app */
    endpoint: string | null;
    /** Per-sandbox RS256 JWT for direct exec-server authentication */
    token: string | null;
    projectId: string;
    idleTimeoutMs: number;
    createdAt: string;
    startedAt: string | null;
    expiresAt: string | null;
    terminatedAt: string | null;
    /** Effective egress policy. Null for legacy rows — treat as `{ mode: 'open' }`. */
    egress: {
        mode: 'open';
    } | {
        mode: 'allowlist';
        allowDomains: string[];
    } | null;
}
declare class SandboxFiles {
    private readonly endpoint;
    private readonly token;
    constructor(endpoint: string, token: string);
    private authHeader;
    /** Write a file to the sandbox filesystem. */
    write(path: string, content: string | Buffer, encoding?: 'utf8' | 'base64'): Promise<void>;
    /** Read a file from the sandbox filesystem. Returns content as string. */
    read(path: string): Promise<string>;
    /** Delete a file from the sandbox filesystem. */
    delete(path: string): Promise<void>;
    /** List files in a directory. */
    list(path?: string): Promise<string[]>;
}
declare class SandboxProcesses {
    private readonly endpoint;
    private readonly token;
    constructor(endpoint: string, token: string);
    private authHeader;
    /** Spawn a new tracked process. Returns processId + pid immediately. */
    start(opts: ProcessStartOptions): Promise<{
        id: string;
        pid: number;
    }>;
    /** List all tracked processes. */
    list(): Promise<ProcessSummary[]>;
    /** Get full process info including buffered output. */
    get(processId: string): Promise<ProcessInfo>;
    /** Send a signal to a process. */
    kill(processId: string, signal?: string): Promise<void>;
    /** Write to process stdin. */
    writeStdin(processId: string, data: string): Promise<void>;
    /**
     * Wait for a process to complete and return its final info.
     * Polls every 500ms until status is no longer 'running'.
     *
     * For real-time output, use stream() instead.
     */
    wait(processId: string, timeoutMs?: number): Promise<ProcessInfo>;
    /** Stream process output as async iterable SSE events. */
    stream(processId: string): AsyncGenerator<ProcessEvent>;
}
declare class SandboxWatch {
    private readonly endpoint;
    private readonly token;
    constructor(endpoint: string, token: string);
    private authHeader;
    /** Start watching a path. Events delivered via sandbox.events() SSE stream. */
    add(opts: WatchOptions): Promise<WatchEntry>;
    /** List active watches. */
    list(): Promise<WatchEntry[]>;
    /** Stop watching a path. */
    remove(path: string): Promise<void>;
}
declare class SandboxCapabilities {
    private readonly endpoint;
    private readonly token;
    constructor(endpoint: string, token: string);
    private authHeader;
    /**
     * Fetch the typed capability catalog for this sandbox image.
     *
     * Use this before selecting heavyweight toolchain paths. For example,
     * default sandboxes report Android emulator/device-test as `not-local`, so
     * agents can hand APK/AAB artifacts to a managed device runtime instead of
     * filling `/workspace` with emulator images.
     */
    get(): Promise<SandboxCapabilitiesReport>;
}
/**
 * Provision and drive persistent, headful, stealth browser sessions inside the
 * sandbox. The Platform owns the connectable browser primitive; the customer
 * app owns session→task mapping, navigation, and scraping — it drives the live
 * session over the Chrome DevTools Protocol (CDP).
 *
 * Lifecycle is thin pass-through to the sandbox exec-server's `/browser` routes
 * (direct connection, per-sandbox JWT — Platform is not in the data path). The
 * browser's CDP port is bound to loopback inside the sandbox; `connectUrl()` /
 * `connect()` reach it ONLY through the exec-server's authenticated CDP proxy.
 *
 * @example
 * ```typescript
 * const session = await sandbox.browser!.create({ profile: 'acme-login' })
 * // Drive it with your CDP client of choice:
 * import { chromium } from 'playwright'
 * const browser = await chromium.connectOverCDP(sandbox.browser!.connectUrl(session.id))
 * // ... navigate / scrape ...
 * await sandbox.browser!.destroy(session.id)
 * ```
 */
declare class SandboxBrowser {
    private readonly endpoint;
    private readonly token;
    constructor(endpoint: string, token: string);
    private authHeader;
    /**
     * Create + start a persistent headful browser session. Resolves once the
     * session's CDP endpoint is available (201 from the exec-server).
     */
    create(opts?: BrowserCreateOptions): Promise<BrowserSessionInfo>;
    /** List live browser sessions in this sandbox. */
    list(): Promise<BrowserSessionInfo[]>;
    /** Get full info for a session, or null if it does not exist. */
    get(sessionId: string): Promise<BrowserSessionInfo | null>;
    /**
     * Build the authenticated CDP connect URL for a session — a `wss://…` URL on
     * the sandbox's public endpoint that proxies to the sandbox-internal loopback CDP. Pass
     * it to any CDP client (`chromium.connectOverCDP(url)` / raw `WebSocket`).
     *
     * The token is carried as a query param because WebSocket clients cannot set
     * custom headers in browsers (equally secure over TLS). The URL is derived
     * locally from the session id, so this is synchronous and does no I/O. For a
     * not-yet-ready session the upstream proxy returns HTTP 409 at connect time.
     */
    connectUrl(sessionId: string): string;
    /**
     * Open a raw WebSocket to a session's CDP endpoint through the authenticated
     * proxy. Most callers want `connectUrl()` to hand to a higher-level CDP
     * client; use this only for a hand-rolled CDP connection.
     */
    connect(sessionId: string): WebSocket;
    /**
     * Fetch the CDP connection details from the exec-server: the sandbox-internal loopback
     * `cdpEndpoint` (introspection only), the `debugPort`, and the authenticated
     * `connectUrl`. Throws 409 if the session is not ready yet, 404 if unknown.
     */
    cdp(sessionId: string): Promise<{
        cdpEndpoint: string;
        debugPort: number;
        connectUrl: string;
    }>;
    /**
     * Destroy a session. The browser is torn down; its persistent profile on the
     * workspace volume is preserved (reuse it via `create({ profile })`).
     * Returns false if the session did not exist.
     */
    destroy(sessionId: string): Promise<boolean>;
}
/**
 * Provision and drive persistent desktop (computer-use) sessions inside the
 * sandbox — the full-GUI sibling of {@link SandboxBrowser} (ADR-207). The
 * Platform owns the connectable, drivable desktop primitive (Xvfb display +
 * window manager + screenshot + input); the customer app owns the agent harness
 * — the screenshot → reason → action loop — exactly the shape Anthropic Computer
 * Use / OpenAI CUA expect the developer to supply.
 *
 * Lifecycle + screenshot + input are thin pass-throughs to the sandbox
 * exec-server's `/computer` routes (direct connection, per-sandbox JWT —
 * Platform is not in the data path). The desktop display + input are
 * RCE-equivalent and stay LOCAL to the sandbox; the only external surface is the
 * exec-server's authenticated HTTP routes (screenshot/input are request/
 * response, not a socket).
 *
 * @example
 * ```typescript
 * const session = await sandbox.computer!.create()
 * const png = await sandbox.computer!.screenshot(session.id)        // Uint8Array
 * await sandbox.computer!.input(session.id, { action: 'left_click', x: 100, y: 200 })
 * await sandbox.computer!.input(session.id, { action: 'type', text: 'hello' })
 * await sandbox.computer!.destroy(session.id)
 * ```
 */
declare class SandboxComputer {
    private readonly endpoint;
    private readonly token;
    constructor(endpoint: string, token: string);
    private authHeader;
    /**
     * Create + start a persistent desktop session. Resolves once the desktop
     * (Xvfb + window manager) is up (201 from the exec-server).
     */
    create(): Promise<ComputerSessionInfo>;
    /** List live desktop sessions in this sandbox. */
    list(): Promise<ComputerSessionInfo[]>;
    /** Get full info for a session, or null if it does not exist. */
    get(sessionId: string): Promise<ComputerSessionInfo | null>;
    /**
     * Capture the desktop framebuffer as encoded image bytes. Returns the raw
     * PNG (default) or JPEG body. Pass `'jpeg'` for a smaller, lossy capture.
     */
    screenshot(sessionId: string, format?: ComputerScreenshotFormat): Promise<Uint8Array>;
    /**
     * Execute a single input action against the desktop (mouse / keyboard /
     * scroll / drag). The exec-server validates the action structurally before
     * executing it; an invalid action throws.
     */
    input(sessionId: string, action: ComputerInputAction): Promise<void>;
    /**
     * Launch a GUI app on the session's VISIBLE desktop display, detached. Returns
     * the spawned pid. The agent's own shell defaults to a different (invisible)
     * display, so apps must be launched through this endpoint to appear on the
     * desktop the agent screenshots. RCE-equivalent (identical trust to exec).
     */
    launch(sessionId: string, command: string): Promise<{
        pid: number;
    }>;
    /**
     * Introspect the live desktop (active window, window list, cursor, window
     * manager state, resolution, running apps) so the agent can reason about the
     * desktop without guessing from a screenshot. Read-only; best-effort fields.
     */
    status(sessionId: string): Promise<ComputerDesktopStatus>;
    /**
     * OCR the live desktop into text runs + bounding boxes (perception layer,
     * ADR-207) so the agent can target UI *text* precisely instead of guessing
     * pixel coordinates — the highest-value, no-GPU lever against miscliks.
     * Best-effort on the server: OCR timeout/failure yields an empty element list
     * (with the real screen size), never an error. Click-by-text matching belongs
     * in the caller's harness; this returns only the text + boxes.
     */
    readUi(sessionId: string): Promise<ComputerUiSnapshot>;
    /**
     * Destroy a session. The desktop is torn down; its per-session scratch dir on
     * the workspace volume is preserved. Returns false if the session did not
     * exist.
     */
    destroy(sessionId: string): Promise<boolean>;
}
declare class SandboxClient {
    readonly id: string;
    private readonly config;
    /** Public endpoint from Platform (may be null for sandboxes from pool pre-v2) */
    readonly endpoint: string | null;
    /** Per-sandbox JWT for direct exec-server auth */
    readonly token: string | null;
    /** File operations (direct to exec-server) */
    readonly files: SandboxFiles | null;
    /** Concurrent process management (direct to exec-server) */
    readonly processes: SandboxProcesses | null;
    /** Filesystem watch management (direct to exec-server) */
    readonly watch: SandboxWatch | null;
    /** Typed capability catalog (direct to exec-server) */
    readonly capabilities: SandboxCapabilities | null;
    /** Persistent headful browser sessions (direct to exec-server — ADR-205) */
    readonly browser: SandboxBrowser | null;
    /** Persistent desktop (computer-use) sessions (direct to exec-server — ADR-207) */
    readonly computer: SandboxComputer | null;
    private constructor();
    /**
     * Create a new sandbox.
     *
     * Platform provisions the sandbox runtime, waits for readiness, and returns
     * { endpoint, token } once the sandbox is fully ready to accept traffic.
     * No client-side polling required.
     */
    static create(config: SylphxConfig, options?: SandboxOptions): Promise<SandboxClient>;
    /**
     * Reconnect to an existing sandbox by ID.
     * Fetches the current status to get the endpoint + token.
     */
    static fromId(config: SylphxConfig, sandboxId: string): Promise<SandboxClient>;
    getStatus(): Promise<SandboxRecord>;
    terminate(): Promise<void>;
    /**
     * Execute a command and stream output as async iterable SSE events.
     *
     * **Stateless mode**: each exec() call runs in an isolated bash invocation.
     * Shell state (CWD changes, exported env vars, functions) is NOT preserved
     * between calls.
     *
     * For state-preserving execution (CWD, env), use `run()` which runs in the
     * persistent active shell and returns the result once complete.
     *
     * For streaming + state-preserving (advanced), combine `sandbox.events()` with `run()`:
     * ```typescript
     * const eventStream = sandbox.events({ type: 'stdout' })
     * sandbox.run(['npm', 'install']) // don't await yet
     * for await (const ev of eventStream) { ... }
     * ```
     *
     * @example
     * ```typescript
     * for await (const event of sandbox.exec(['npm', 'install'])) {
     *   if (event.type === 'stdout') process.stdout.write(event.data)
     *   if (event.type === 'exit') console.log('Done:', event.exitCode)
     * }
     * ```
     */
    exec(command: string[], options?: ExecOptions): AsyncGenerator<ExecEvent>;
    /**
     * Execute a command and collect all output (non-streaming).
     * Convenience wrapper over exec() for simple use cases.
     *
     * For long-running commands, prefer exec() to stream output incrementally.
     */
    run(command: string[], options?: ExecOptions): Promise<ExecResult>;
    /**
     * Subscribe to the unified event stream (SSE).
     *
     * Receives all sandbox events: stdout, stderr, exit, port, file, shell, resource.
     * Filter by type/pid/shellId using query params.
     *
     * @example
     * ```typescript
     * for await (const event of sandbox.events({ type: 'file' })) {
     *   console.log('File changed:', event.path, event.event)
     * }
     * ```
     */
    events(filter?: {
        type?: 'stdout' | 'stderr' | 'exit' | 'port' | 'file' | 'shell' | 'resource';
        pid?: number;
        shellId?: string;
    }): AsyncGenerator<Record<string, unknown>>;
    /**
     * Open an interactive PTY session (WebSocket).
     *
     * Returns a WebSocket connected to a bash shell in the sandbox.
     * Token is passed as a query param (WebSocket doesn't support custom headers in browsers).
     *
     * @example
     * ```typescript
     * const ws = await sandbox.pty()
     * ws.on('message', (data) => process.stdout.write(JSON.parse(data).data))
     * ws.send(JSON.stringify({ type: 'input', data: 'ls -la\n' }))
     * ws.send(JSON.stringify({ type: 'resize', cols: 120, rows: 40 }))
     * ```
     */
    pty(): WebSocket;
    private assertDirect;
}

/**
 * Artifacts — publish + manage agent-authored interactive web content at a safe
 * shareable URL.
 *
 * Org-scoped client over the BaaS plane `/artifacts`. The Platform stores the
 * self-contained HTML, isolates it on a separate per-artifact content origin, and
 * returns a signed, expiring (or durable / auth-gated) shareable URL (ADR-2564).
 * Slice 2 adds the management plane: list / get / delete (soft) / restore /
 * reshare. Complement to `RenderClient`: render returns a fixed-format image, an
 * artifact is a live interactive page at a URL.
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). Type-only
 * imports keep the Effect runtime out of the published `.d.ts` surface
 * (check-published-sdk-effect-leak).
 */

/**
 * Artifact client — publish + manage a self-contained HTML page at a safe,
 * shareable URL.
 *
 * @example
 * ```typescript
 * import { createServerClient, ArtifactClient } from '@sylphx/sdk'
 *
 * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *
 * const result = await ArtifactClient.publish(config, {
 *   title: '10-minute timer',
 *   html: '<!doctype html><meta charset="utf-8"><body>…</body>',
 * })
 *
 * if (result.ok) {
 *   console.log(result.url) // share this link; expires at result.expiresAt
 *   // later: list / inspect / delete / restore / reshare
 *   const { artifacts } = await ArtifactClient.list(config)
 *   await ArtifactClient.delete(config, result.id) // soft-delete (reversible)
 * }
 * ```
 */
declare const ArtifactClient: {
    /**
     * Publish a self-contained HTML document to a safe, shareable URL. Returns a
     * signed expiring link by default (`access: 'signed-link'`) — click-to-view, no
     * login, leaked links decay; `public` for a durable URL. On success returns
     * `{ id, url, expiresAt?, version }`; on failure a structured `error` with a
     * `code` (e.g. `blocked_unsafe`) and `diagnostics`.
     *
     * **Update in place (ADR-2564 v2):** pass `artifactId` (the `id` from a prior
     * publish) to REVISE that artifact — the id and the shareable URL are preserved
     * and `version` increments. The caller must own the artifact (`forbidden`
     * otherwise), it must still exist (`not_found`), and it must be a versioned
     * artifact (`conflict` for pre-versioning artifacts). Omit `artifactId` to
     * create a fresh artifact.
     */
    publish(config: SylphxConfig, request: PublishArtifactRequest): Promise<ArtifactResult>;
    /**
     * List the calling project's published artifacts, newest-first. Returns
     * metadata only — `{ artifacts: [{ id, title?, access, currentVersion,
     * createdAt, updatedAt, expiresAt? }] }`.
     *
     * Excludes soft-deleted artifacts by default. Pass `{ includeDeleted: true }`
     * to ALSO list tombstoned ones (each carrying `deleted: true` + `deletedAt`),
     * so you can find a soft-deleted artifact's id and {@link ArtifactClient.restore}
     * it before the grace-window cleanup erases it.
     */
    list(config: SylphxConfig, options?: {
        includeDeleted?: boolean;
    }): Promise<ListArtifactsResult>;
    /**
     * Get one artifact's metadata and its immutable version history. Throws
     * `NOT_FOUND` if the artifact does not exist (or is soft-deleted), `FORBIDDEN`
     * if it belongs to another project.
     */
    get(config: SylphxConfig, id: string): Promise<ArtifactDetail>;
    /**
     * Get an artifact's CURRENT HTML source so you can EDIT it, then re-{@link
     * ArtifactClient.publish} with `artifactId` to update it in place — instead of
     * rewriting it blind from a fresh session. Returns `{ id, version, html }`.
     * Throws `NOT_FOUND` if it does not exist (or is soft-deleted), `FORBIDDEN` if
     * it belongs to another project. `get` returns metadata only; this returns the
     * bytes.
     */
    getContent(config: SylphxConfig, id: string): Promise<ArtifactContent>;
    /**
     * Soft-delete an artifact (reversible). The shareable URL begins returning
     * `410 Gone`; the bytes are retained until a later grace-window cleanup, so
     * {@link ArtifactClient.restore} can bring it back. Throws `NOT_FOUND` /
     * `FORBIDDEN` as for {@link ArtifactClient.get}.
     */
    delete(config: SylphxConfig, id: string): Promise<DeleteArtifactResult>;
    /**
     * Restore a soft-deleted artifact. Pass `version` to roll a prior version
     * FORWARD as a new current version (history is never rewritten) — the returned
     * `version` is then the new current. Omit it to simply clear the tombstone.
     */
    restore(config: SylphxConfig, id: string, options?: {
        version?: number;
    }): Promise<RestoreArtifactResult>;
    /**
     * Re-mint a fresh signed share link (a new capability URL + TTL) for an
     * artifact — e.g. to extend or rotate a link. Returns `{ url, expiresAt? }`.
     * For a `public` artifact the durable URL is returned as-is. Pass `ttlSeconds`
     * to set the new link's lifetime (clamped to the allowed window).
     */
    reshare(config: SylphxConfig, id: string, options?: {
        ttlSeconds?: number;
    }): Promise<ReshareArtifactResult>;
};

/**
 * Render — declarative spec → image (charts via Vega-Lite, diagrams via Graphviz).
 *
 * Org-scoped client over the BaaS plane `POST /render`. The render engine runs the
 * spec in a per-render egress-denied microVM and returns the image bytes (ADR-2358).
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). Type-only
 * imports keep the Effect runtime out of the published `.d.ts` surface
 * (check-published-sdk-effect-leak).
 */

/**
 * Render client — turn a declarative spec into an image.
 *
 * @example
 * ```typescript
 * import { createServerClient, RenderClient } from '@sylphx/sdk'
 *
 * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *
 * const result = await RenderClient.render(config, {
 *   engine: 'vega-lite',
 *   spec: JSON.stringify({
 *     $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
 *     mark: 'bar',
 *     data: { values: [{ a: 'A', b: 28 }, { a: 'B', b: 55 }] },
 *     encoding: { x: { field: 'a', type: 'nominal' }, y: { field: 'b', type: 'quantitative' } },
 *   }),
 *   format: 'png',
 * })
 *
 * if (result.ok) {
 *   const png = Buffer.from(result.bytesBase64, 'base64') // deliver / save
 * } else {
 *   console.error(`render ${result.error.code}: ${result.error.message}`)
 * }
 * ```
 */
declare const RenderClient: {
    /**
     * Render a chart (`engine: 'vega-lite'`, Vega-Lite JSON in `spec`) or a diagram
     * (`engine: 'graphviz'`, DOT in `spec`) to an image. The engine validates and
     * repairs the spec before rendering; on success returns base64 image bytes, on
     * failure a structured `error` with a `code` and `diagnostics`.
     */
    render(config: SylphxConfig, request: RenderRequest): Promise<RenderResult>;
};

/**
 * Wallet & Credits — tenant-neutral end-user credits for a project's own users
 * (daily-free grants, rewarded-ad/top-up/referral credits, two-phase
 * reserve→consume per action). Org-scoped client over the BaaS plane
 * `POST /wallet/*` (ADR-2623).
 *
 * Wire-shape types are re-exported from `@sylphx/contract` (ADR-084). Type-only
 * imports keep the Effect runtime out of the published `.d.ts` surface.
 */

/**
 * Wallet client — grant, meter, and charge credits to your end users.
 *
 * @example
 * ```typescript
 * import { createServerClient, WalletClient } from '@sylphx/sdk'
 *
 * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *
 * // Grant a daily free allowance:
 * await WalletClient.grant(config, { appUserId: 'u_123', amount: 5, category: 'free' })
 *
 * // Two-phase debit around a generation:
 * const r = await WalletClient.reserve(config, { appUserId: 'u_123', amount: 1 })
 * // …do the work…
 * await WalletClient.consume(config, { reservationId: r.id })
 *
 * const balance = await WalletClient.getBalance(config, { appUserId: 'u_123' })
 * ```
 */
declare const WalletClient: {
    /** Mint a grant block of credits for an end user. */
    grant(config: SylphxConfig, request: GrantRequest): Promise<Grant>;
    /** Get an end user's derived balance (`available = posted − reserved`). */
    getBalance(config: SylphxConfig, request: {
        appUserId: string;
        balance?: string;
    }): Promise<BalanceSummary>;
    /** Reserve credits (two-phase hold with a mandatory TTL). */
    reserve(config: SylphxConfig, request: ReserveRequest): Promise<Reservation>;
    /** Capture a reservation (≤ reserved; releases the remainder). */
    consume(config: SylphxConfig, request: ConsumeRequest): Promise<LedgerEntry>;
    /** Release a reservation (return the held credits). */
    release(config: SylphxConfig, request: ReleaseRequest): Promise<Reservation>;
    /** Void/claw back a specific grant block (audited ledger entry). */
    voidGrant(config: SylphxConfig, request: VoidGrantRequest): Promise<Grant>;
};

/**
 * Device sessions — interactive, long-lived Android devices an agent drives
 * (ADR-2560). Boot once, then install → input (tap/swipe/key/text) →
 * screenshot → launch, polling the session handle until `ready`; delete when
 * done. A session may also be booted stream-capable (ADR-2566): `streamConnect`
 * mints a short-lived signed descriptor for a browser to join a live WebRTC view.
 *
 * Management-plane client over the device-session control plane: project-scoped
 * `create`/`list`; top-level `get`/control/`delete` by session id. Mirrors the
 * routes in `apps/api/src/server/platform/routes/management/device-sessions.ts`;
 * paths sourced from the `@sylphx/contract` device-session endpoints (ADR-084).
 *
 * This is the "implement once" typed surface (Principle 18 dogfooding): the CLI's
 * `authedFetch` passthrough and the Spiron agent tool consume this client rather
 * than re-deriving the wire shapes.
 *
 * Wire-shape types are type-only imports from `@sylphx/contract` so the Effect
 * runtime never leaks into the published `.d.ts` (check-published-sdk-effect-leak).
 */

/**
 * Device-session client — drive an interactive Android device, the agent-native
 * loop (boot → install → input/screenshot → delete).
 *
 * @example
 * ```typescript
 * import { createServerClient, DeviceSessionClient } from '@sylphx/sdk'
 *
 * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *
 * // Boot, then poll to ready.
 * let { session } = await DeviceSessionClient.create(config, projectId, {})
 * while (session.status === 'booting') {
 *   await new Promise((r) => setTimeout(r, 2000))
 *   ;({ session } = await DeviceSessionClient.get(config, session.id))
 * }
 *
 * // Install an APK, then act + perceive.
 * await DeviceSessionClient.install(config, session.id, { apkUri: 's3://bucket/app.apk' })
 * await DeviceSessionClient.input(config, session.id, { type: 'tap', x: 540, y: 1200 })
 * const shot = await DeviceSessionClient.screenshot(config, session.id) // base64 PNG
 *
 * await DeviceSessionClient.delete(config, session.id) // always release the device
 * ```
 */
declare const DeviceSessionClient: {
    /** Boot a long-lived interactive device session in a project (poll to `ready`). */
    create(config: SylphxConfig, projectId: string, body: CreateDeviceSessionInput): Promise<DeviceSessionResult>;
    /** List interactive device sessions for a project. */
    list(config: SylphxConfig, projectId: string, query?: ListDeviceSessionsQuery): Promise<ListDeviceSessionsResult>;
    /** Get one device session by id — poll for `booting` → `ready`. */
    get(config: SylphxConfig, sessionId: string): Promise<DeviceSessionResult>;
    /** Install an APK handle (`http(s)://`, `s3://`, or a storage key) onto the device. */
    install(config: SylphxConfig, sessionId: string, body: InstallDeviceSessionAppInput): Promise<InstallDeviceSessionAppResult>;
    /** Send an input event (tap / swipe / key / text) — how the agent acts on the device. */
    input(config: SylphxConfig, sessionId: string, body: DeviceSessionInput): Promise<DeviceSessionInputResult>;
    /** Launch an installed app (defaults to the most-recently installed package). */
    launch(config: SylphxConfig, sessionId: string, body?: LaunchDeviceSessionAppInput): Promise<LaunchDeviceSessionAppResult>;
    /** Capture a PNG screenshot — how the agent "sees" the device (base64 always present). */
    screenshot(config: SylphxConfig, sessionId: string): Promise<DeviceSessionScreenshotResult>;
    /** Read recent logcat output from the device session. */
    logcat(config: SylphxConfig, sessionId: string, query?: DeviceSessionLogcatQuery): Promise<DeviceSessionLogcatResult>;
    /**
     * Mint a short-lived signed descriptor for a browser to join the session's live
     * WebRTC view (ADR-2566). Requires the session to be booted stream-capable
     * (`create` with `stream: true`).
     */
    streamConnect(config: SylphxConfig, sessionId: string, body?: DeviceSessionStreamConnectInput): Promise<DeviceSessionStreamConnectResult>;
    /** Terminate a device session and release its device. */
    delete(config: SylphxConfig, sessionId: string): Promise<DeleteDeviceSessionResult>;
};

/**
 * Runs Client (ADR-040, formerly Workers)
 *
 * Fire-and-forget batch compute API (Modal-style run-to-completion jobs).
 *
 * Runs are ephemeral isolated jobs that run to completion. Use them for:
 * - ML training folds (walk-forward cross-validation)
 * - Data processing pipelines
 * - Batch inference
 * - Any parallelisable CPU-heavy work
 *
 * ## Usage
 *
 * ### Single worker
 * ```typescript
 * import { createServerClient, RunsClient } from '@sylphx/sdk'
 *
 * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *
 * const run = await RunsClient.run(config, {
 *   image: 'ghcr.io/acme/my-trainer:sha-abc123',
 *   command: ['python', 'train.py', '--fold', '0'],
 *   machine: 'large',
 *   timeoutSeconds: 3600,
 * })
 *
 * const result = await run.wait()
 * console.log(result.exitCode)   // 0
 * console.log(result.stdout)     // captured stdout
 * ```
 *
 * ### Parallel workers (walk-forward training)
 *
 * One logical job that fans out to N indexed shards, owned end-to-end by the
 * platform (ADR distributed-batch-compute). No client-side `Promise.all`
 * orchestration, no per-app concurrency budget, no hand-rolled partial-failure
 * merge — the platform gang-admits all shards or none and rolls the per-shard
 * status up into one aggregate. Each shard self-selects its partition from the
 * injected `SYLPHX_SHARD_INDEX` (0..N-1) + `SYLPHX_SHARD_COUNT` env vars.
 *
 * ```typescript
 * const run = await RunsClient.runDistributed(config, {
 *   image: 'ghcr.io/acme/trainer:sha-abc123',
 *   command: ['python', 'train.py'], // reads SYLPHX_SHARD_INDEX to pick its fold
 *   parallelism: folds.length,
 *   machine: 'large',
 *   volumeMounts: [{ volumeId: sharedCacheVolumeId, mountPath: '/cache' }],
 *   timeoutSeconds: 7200,
 * })
 *
 * const status = await run.wait() // resolves on aggregate terminal
 * const failures = (await run.shards()).filter((s) => s.status === 'failed')
 * ```
 *
 * ## Architecture
 *
 * - Workers are isolated one-shot runs with no automatic restarts
 * - A Distributed Run is one logical job fanned out to N indexed shards;
 *   `parallelism` defaults to 1, so a single-shard `run()` is the N=1 case
 *   (zero breaking change)
 * - Images come from connected registries and are scanned before execution
 * - Volumes: org-level volume resources mounted into the run
 *   - single-writer for one active writer at a time
 *   - shared for concurrent runs and shared feature caches (one shared
 *     volume mounted into every shard is the result-aggregation convention)
 * - Auth: sk_* secret key (server-side only)
 * - Quota: per-job parallelism budget + an org-level aggregate shard budget
 *
 * @module
 */

type RunStatus = 'pending' | 'running' | 'succeeded' | 'failed' | 'cancelled' | 'timeout';
type RunMachineSize = MachineSize;
interface RunVolumeMount {
    /** UUID of the volumeResource to mount (must belong to this org) */
    volumeId: string;
    /** Absolute mount path inside the container (e.g. '/cache') */
    mountPath: string;
    /** Optional sub-path within the volume (e.g. 'fold-3') */
    subPath?: string;
    /** Mount as read-only (default: false) */
    readOnly?: boolean;
}
type RunImageSource = {
    /**
     * OCI image to run from a connected registry.
     *
     * @example 'ghcr.io/acme/my-trainer:sha-abc123'
     */
    image: string;
    imageFromService?: never;
} | {
    /**
     * Name of a service in the same project environment. The platform resolves
     * the service's current deployment artifact to an immutable image digest
     * before creating the Run.
     *
     * @example 'trainer'
     */
    imageFromService: string;
    image?: never;
};
interface CreateRunBaseOptions {
    /**
     * Command + args to execute.
     *
     * @example ['python', 'train.py', '--fold', '3']
     * @example ['node', 'dist/process.js']
     */
    command: string[];
    /**
     * Environment variables to inject.
     * Use for fold IDs, feature flags, DB URLs, etc.
     */
    env?: Record<string, string>;
    /**
     * Managed machine size. The platform owns CPU, memory, scheduling, and isolation details.
     * Defaults to `standard`.
     */
    machine?: RunMachineSize;
    /**
     * Hard timeout in seconds (default: 3600 = 1 hour, max: 86400 = 24 hours).
     * The platform terminates the run when the deadline is reached (status: 'timeout').
     */
    timeoutSeconds?: number;
    /**
     * Volume mounts from org-level volumeResources.
     * Shared volumes allow concurrent access by multiple parallel workers.
     */
    volumeMounts?: RunVolumeMount[];
}
type CreateRunOptions = CreateRunBaseOptions & RunImageSource;
interface Run {
    /** Worker run ID (e.g. 'worker_Vh3kJ9mNpQ2wXsL1') */
    id: string;
    /** Current lifecycle status */
    status: RunStatus;
    /** Docker image */
    image: string;
    /** Command being executed */
    command: string[];
    /** Environment variables */
    env: Record<string, string> | null;
    /** Managed machine size selected for this run. */
    machine: RunMachineSize | null;
    /** Hard timeout in seconds */
    timeoutSeconds: number;
    /** Volume mounts */
    volumeMounts: RunVolumeMount[] | null;
    /** Exit code (only when succeeded or failed) */
    exitCode: number | null;
    /** Captured stdout (up to 1 MiB) */
    stdout: string | null;
    /** Captured stderr (up to 1 MiB) */
    stderr: string | null;
    /** Error message (e.g. OOMKilled, image pull failure) */
    errorMessage: string | null;
    /** Duration in milliseconds (only when completed) */
    durationMs: number | null;
    /** When the worker runtime started */
    startedAt: string | null;
    /** When the worker completed */
    completedAt: string | null;
    /** When this run was created */
    createdAt: string;
    /** Last update timestamp */
    updatedAt: string;
}
interface RunResult {
    /** Exit code (0 = success) */
    exitCode: number | null;
    /** Status at completion */
    status: RunStatus;
    /** Captured stdout */
    stdout: string | null;
    /** Captured stderr */
    stderr: string | null;
    /** Error message (OOMKilled, DeadlineExceeded, etc.) */
    errorMessage: string | null;
    /** Wall-clock duration in milliseconds */
    durationMs: number | null;
}
interface RunLogsResult {
    /** Captured stdout (up to 1 MiB) */
    stdout: string;
    /** Captured stderr (up to 1 MiB) */
    stderr: string;
    /** Whether logs are still being captured (worker is running) */
    live: boolean;
}
interface ListRunsOptions {
    /** Filter by status */
    status?: RunStatus;
}
/** OpenAI/Stripe-style list response */
interface ListRunsResult {
    object: 'list';
    data: Run[];
    /** True if there are more results (limit was hit) */
    has_more: boolean;
}
/** Aggregate lifecycle status of a Distributed Run (SSOT: `@sylphx/contract`). */
type DistributedRunStatus = DistributedRunAggregateStatus;

/**
 * Options for {@link RunsClient.runDistributed}. A strict superset of
 * {@link CreateRunOptions} plus the distribution knobs. `parallelism` is the
 * shard count (1..256); each shard self-selects its partition from the
 * injected `SYLPHX_SHARD_INDEX` / `SYLPHX_SHARD_COUNT` env vars.
 */
type CreateDistributedRunOptions = CreateRunBaseOptions & RunImageSource & {
    /**
     * Number of indexed shards to fan out to (1..256). `1` is equivalent to a
     * single-shard {@link RunsClient.run}; `> 1` distributes the job.
     */
    parallelism: number;
    /**
     * Shard completion mode. `Indexed` (default when sharded) gives each shard a
     * stable `SYLPHX_SHARD_INDEX`; `NonIndexed` is the interchangeable-worker mode.
     */
    completionMode?: DurableWorkRunCompletionMode;
    /**
     * Gang scheduling — all shards are admitted together or none (default `true`
     * when sharded), so a shard never assumes-then-waits for absent peers.
     */
    gangScheduling?: boolean;
    /**
     * Per-index retry budget for opportunistic sharded runs. Only valid together
     * with `parallelism > 1` and `gangScheduling: false`; defaults to the platform
     * contract's opportunistic retry budget when omitted.
     */
    backoffLimitPerIndex?: number;
};
/**
 * Handle to a running (or completed) worker.
 * Use `.wait()` to poll until completion, `.logs()` to stream logs, `.cancel()` to abort.
 */
declare class RunHandle {
    readonly id: string;
    private readonly config;
    constructor(id: string, config: SylphxConfig);
    /**
     * Get the current status of this worker.
     */
    status(): Promise<Run>;
    /**
     * Poll the worker until it reaches a terminal state (succeeded, failed, cancelled, timeout).
     *
     * @param options.pollIntervalMs - How often to poll in ms (default: 3000)
     * @param options.timeoutMs - Max time to wait before throwing (default: 7_200_000 = 2h)
     * @returns RunResult with exit code, status, stdout/stderr
     * @throws Error if waitTimeout is exceeded
     *
     * @example
     * ```typescript
     * const result = await run.wait()
     * if (result.exitCode !== 0) {
     *   throw new Error(`Worker failed: ${result.errorMessage ?? result.stderr}`)
     * }
     * ```
     */
    wait(options?: {
        pollIntervalMs?: number;
        timeoutMs?: number;
    }): Promise<RunResult>;
    /**
     * Fetch captured logs for this worker.
     *
     * - For a running worker: returns live logs streamed from the runtime (may be incomplete)
     * - For a completed worker: returns the full captured output stored in DB
     *
     * @example
     * ```typescript
     * const { stdout, stderr, live } = await worker.logs()
     * console.log(stdout)
     * if (live) console.log('(worker still running, logs may be incomplete)')
     * ```
     */
    logs(): Promise<RunLogsResult>;
    /**
     * Cancel this worker.
     *
     * - If still pending: immediately cancelled
     * - If running: runtime is terminated
     * - If already completed: no-op
     */
    cancel(): Promise<void>;
}
/**
 * Handle to a distributed (multi-shard) run — one logical job fanned out to N
 * indexed shards (ADR distributed-batch-compute).
 *
 * Use `.status()` / `.shards()` for the aggregate + per-shard drill-down,
 * `.wait()` to poll until the aggregate reaches a terminal state
 * (succeeded / failed / partial / cancelled / timed_out), `.logs({ shard })` to
 * stream one shard's logs, and `.cancel()` to cancel the whole set.
 */
declare class DistributedRunHandle {
    readonly id: string;
    /** Submitted shard count — used to request + render the N-shard aggregate. */
    readonly parallelism: number;
    private readonly config;
    private readonly completionMode;
    constructor(id: string, config: SylphxConfig, parallelism: number, completionMode: DurableWorkRunCompletionMode);
    /**
     * Get the current aggregate status + per-shard drill-down for this run.
     *
     * Hits `GET /runs/:id?view=distributed` — the additive superset of the
     * single-shard read model — passing the submitted `parallelism` so the platform
     * lays the observed status out across the N indexed shards.
     */
    status(): Promise<DistributedRun>;
    /** Get the per-shard status list (index, status, exitCode, timings). */
    shards(): Promise<DistributedRunShard[]>;
    /**
     * Poll until the aggregate reaches a terminal state (succeeded, failed,
     * partial, cancelled, timed_out) and return the final {@link DistributedRun}.
     *
     * @param options.pollIntervalMs - How often to poll in ms (default: 3000)
     * @param options.timeoutMs - Max time to wait before throwing (default: 2h)
     * @throws Error if the wait timeout is exceeded
     */
    wait(options?: {
        pollIntervalMs?: number;
        timeoutMs?: number;
    }): Promise<DistributedRun>;
    /**
     * Fetch captured logs for one shard (default: shard 0).
     *
     * @param options.shard - Shard index (0..parallelism-1). Defaults to 0.
     */
    logs(options?: {
        shard?: number;
    }): Promise<RunLogsResult>;
    /** Cancel the whole run (all shards). */
    cancel(): Promise<void>;
}
/**
 * Static client for the Workers BaaS service.
 *
 * @example
 * ```typescript
 * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *
 * // Run a worker and wait for completion
 * const result = await RunsClient.run(config, { ... }).then((run) => run.wait())
 *
 * // Run N workers in parallel, wait for all
 * const handles = await Promise.all(folds.map((fold) => RunsClient.run(config, { ... })))
 * const results = await Promise.all(handles.map(h => h.wait()))
 * ```
 */
declare const RunsClient: {
    /**
     * Spawn a new worker and return a handle.
     *
     * The run is created immediately and starts pulling the image.
     * Use the returned handle to `.wait()` for completion or `.cancel()`.
     *
     * @example
     * ```typescript
     * const run = await RunsClient.run(config, {
     *   image: 'ghcr.io/acme/trainer:sha-abc123',
     *   command: ['python', 'train.py', '--fold', '3'],
     *   machine: 'large',
     *   volumeMounts: [{ volumeId: cacheVolumeId, mountPath: '/cache' }],
     * })
     * const result = await run.wait()
     * ```
     */
    run(config: SylphxConfig, options: CreateRunOptions): Promise<RunHandle>;
    /**
     * Spawn a Distributed Run — one logical job fanned out to N indexed shards —
     * and return a {@link DistributedRunHandle} (ADR distributed-batch-compute).
     *
     * The platform owns sharding, gang start (all shards admitted together or
     * none), the per-org concurrency budget, and the aggregate/per-shard rollup.
     * Each shard self-selects its partition from the injected
     * `SYLPHX_SHARD_INDEX` (0..parallelism-1) + `SYLPHX_SHARD_COUNT` env vars — no
     * coordinator code for the embarrassingly-parallel case.
     *
     * `parallelism: 1` is equivalent to {@link RunsClient.run} (the single-shard
     * N=1 case); the single-shard `run()` ergonomic path is unchanged.
     *
     * @example
     * ```typescript
     * const run = await RunsClient.runDistributed(config, {
     *   image: 'ghcr.io/acme/trainer:sha-abc123',
     *   command: ['python', 'train.py'],
     *   parallelism: 16,
     *   machine: 'large',
     * })
     * const result = await run.wait()
     * if (result.status !== 'succeeded') {
     *   const failed = result.shards.filter((s) => s.status === 'failed')
     *   throw new Error(`${failed.length}/${run.parallelism} shards failed`)
     * }
     * ```
     */
    runDistributed(config: SylphxConfig, options: CreateDistributedRunOptions): Promise<DistributedRunHandle>;
    /**
     * Get a {@link DistributedRunHandle} for an existing distributed run by ID.
     *
     * Pass the `parallelism` the run was created with so the handle requests +
     * renders the correct N-shard aggregate. Useful for resuming monitoring (e.g.
     * a CLI `runs get <id> --parallelism N`) across processes.
     *
     * @example
     * ```typescript
     * const handle = RunsClient.runDistributedFromId(config, storedRunId, 16)
     * const result = await handle.wait()
     * ```
     */
    runDistributedFromId(config: SylphxConfig, runId: string, parallelism: number, completionMode?: DurableWorkRunCompletionMode): DistributedRunHandle;
    /**
     * Get a RunHandle for an existing run by ID.
     *
     * Useful for resuming monitoring across requests.
     *
     * @example
     * ```typescript
     * // Store the worker ID, retrieve later
     * const handle = RunsClient.fromId(config, storedWorkerId)
     * const result = await handle.wait()
     * ```
     */
    fromId(config: SylphxConfig, workerId: string): RunHandle;
    /**
     * List worker runs for this environment.
     *
     * @example
     * ```typescript
     * const { data } = await RunsClient.list(config, { status: 'running' })
     * console.log(`${data.length} runs currently running`)
     * ```
     */
    list(config: SylphxConfig, options?: ListRunsOptions): Promise<ListRunsResult>;
    /**
     * Spawn a worker and wait for it to complete in one call.
     *
     * Equivalent to `(await RunsClient.run(config, options)).wait(waitOptions)`.
     *
     * @example
     * ```typescript
     * const result = await RunsClient.runAndWait(config, {
     *   image: 'ghcr.io/acme/process:sha-abc123',
     *   command: ['node', 'dist/process.js'],
     * })
     * if (result.exitCode !== 0) throw new Error(result.errorMessage ?? 'worker failed')
     * ```
     */
    runAndWait(config: SylphxConfig, options: CreateRunOptions, waitOptions?: {
        pollIntervalMs?: number;
        timeoutMs?: number;
    }): Promise<RunResult>;
};
/** @deprecated Use RunsClient */
declare const WorkersClient: {
    /**
     * Spawn a new worker and return a handle.
     *
     * The run is created immediately and starts pulling the image.
     * Use the returned handle to `.wait()` for completion or `.cancel()`.
     *
     * @example
     * ```typescript
     * const run = await RunsClient.run(config, {
     *   image: 'ghcr.io/acme/trainer:sha-abc123',
     *   command: ['python', 'train.py', '--fold', '3'],
     *   machine: 'large',
     *   volumeMounts: [{ volumeId: cacheVolumeId, mountPath: '/cache' }],
     * })
     * const result = await run.wait()
     * ```
     */
    run(config: SylphxConfig, options: CreateRunOptions): Promise<RunHandle>;
    /**
     * Spawn a Distributed Run — one logical job fanned out to N indexed shards —
     * and return a {@link DistributedRunHandle} (ADR distributed-batch-compute).
     *
     * The platform owns sharding, gang start (all shards admitted together or
     * none), the per-org concurrency budget, and the aggregate/per-shard rollup.
     * Each shard self-selects its partition from the injected
     * `SYLPHX_SHARD_INDEX` (0..parallelism-1) + `SYLPHX_SHARD_COUNT` env vars — no
     * coordinator code for the embarrassingly-parallel case.
     *
     * `parallelism: 1` is equivalent to {@link RunsClient.run} (the single-shard
     * N=1 case); the single-shard `run()` ergonomic path is unchanged.
     *
     * @example
     * ```typescript
     * const run = await RunsClient.runDistributed(config, {
     *   image: 'ghcr.io/acme/trainer:sha-abc123',
     *   command: ['python', 'train.py'],
     *   parallelism: 16,
     *   machine: 'large',
     * })
     * const result = await run.wait()
     * if (result.status !== 'succeeded') {
     *   const failed = result.shards.filter((s) => s.status === 'failed')
     *   throw new Error(`${failed.length}/${run.parallelism} shards failed`)
     * }
     * ```
     */
    runDistributed(config: SylphxConfig, options: CreateDistributedRunOptions): Promise<DistributedRunHandle>;
    /**
     * Get a {@link DistributedRunHandle} for an existing distributed run by ID.
     *
     * Pass the `parallelism` the run was created with so the handle requests +
     * renders the correct N-shard aggregate. Useful for resuming monitoring (e.g.
     * a CLI `runs get <id> --parallelism N`) across processes.
     *
     * @example
     * ```typescript
     * const handle = RunsClient.runDistributedFromId(config, storedRunId, 16)
     * const result = await handle.wait()
     * ```
     */
    runDistributedFromId(config: SylphxConfig, runId: string, parallelism: number, completionMode?: DurableWorkRunCompletionMode): DistributedRunHandle;
    /**
     * Get a RunHandle for an existing run by ID.
     *
     * Useful for resuming monitoring across requests.
     *
     * @example
     * ```typescript
     * // Store the worker ID, retrieve later
     * const handle = RunsClient.fromId(config, storedWorkerId)
     * const result = await handle.wait()
     * ```
     */
    fromId(config: SylphxConfig, workerId: string): RunHandle;
    /**
     * List worker runs for this environment.
     *
     * @example
     * ```typescript
     * const { data } = await RunsClient.list(config, { status: 'running' })
     * console.log(`${data.length} runs currently running`)
     * ```
     */
    list(config: SylphxConfig, options?: ListRunsOptions): Promise<ListRunsResult>;
    /**
     * Spawn a worker and wait for it to complete in one call.
     *
     * Equivalent to `(await RunsClient.run(config, options)).wait(waitOptions)`.
     *
     * @example
     * ```typescript
     * const result = await RunsClient.runAndWait(config, {
     *   image: 'ghcr.io/acme/process:sha-abc123',
     *   command: ['node', 'dist/process.js'],
     * })
     * if (result.exitCode !== 0) throw new Error(result.errorMessage ?? 'worker failed')
     * ```
     */
    runAndWait(config: SylphxConfig, options: CreateRunOptions, waitOptions?: {
        pollIntervalMs?: number;
        timeoutMs?: number;
    }): Promise<RunResult>;
};

/**
 * Triggers Client (ADR-040)
 *
 * Unified scheduling + event dispatch API.
 * Create cron schedules and event triggers that dispatch to Tasks, Runs, or HTTP URLs.
 *
 * ## Usage
 *
 * ### Cron → Task
 * ```typescript
 * import { createServerClient, TriggersClient } from '@sylphx/sdk'
 * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)
 *
 * const trigger = await TriggersClient.create(config, {
 *   name: 'daily-cleanup',
 *   source: { type: 'cron', expression: '0 2 * * *' },
 *   target: { type: 'task', taskName: 'daily-cleanup' },
 * })
 * ```
 *
 * ### Event → Task (fires when event is published via publishEvent)
 * ```typescript
 * const trigger = await TriggersClient.create(config, {
 *   name: 'welcome-email-on-signup',
 *   source: { type: 'event', eventName: 'user.signup' },
 *   target: { type: 'task', taskName: 'send-welcome-email' },
 * })
 * // Publish from your app:
 * await TriggersClient.publishEvent(config, 'user.signup', { userId: '123' })
 * ```
 *
 * ### Cron → HTTP URL (any language, no code required)
 * ```typescript
 * const trigger = await TriggersClient.create(config, {
 *   name: 'nightly-backup',
 *   source: { type: 'cron', expression: '0 3 * * *' },
 *   target: { type: 'http', url: 'https://myapp.com/api/backup', payload: { type: 'full' } },
 * })
 * ```
 */

type TriggerTargetType = 'task' | 'run' | 'http';
type TriggerSourceType = 'cron' | 'event';
type TriggerStatus = 'active' | 'paused' | 'deleted';
type TriggerRunMachineSize = MachineSize;
interface TaskTarget {
    type: 'task';
    taskName: string;
    handlerPath?: string;
    payload?: Record<string, unknown>;
}
interface HttpTarget {
    type: 'http';
    url: string;
    method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
    headers?: Record<string, string>;
    payload?: Record<string, unknown>;
}
interface RunTarget {
    type: 'run';
    image: string;
    command: string[];
    machine?: TriggerRunMachineSize;
}
type TriggerTarget = TaskTarget | HttpTarget | RunTarget;
interface CronSource {
    type: 'cron';
    expression: string;
}
interface EventSource {
    type: 'event';
    /** The event name to listen for. e.g. 'user.signup', 'order.paid' */
    eventName: string;
}
type TriggerSource = CronSource | EventSource;
interface CreateTriggerOptions {
    name?: string;
    source: TriggerSource;
    target: TriggerTarget;
    paused?: boolean;
    /** Idempotency key — prevents duplicate trigger creation per project+environment */
    idempotencyKey?: string;
}
interface UpdateTriggerOptions {
    name?: string;
    source?: TriggerSource;
    paused?: boolean;
}
interface Trigger {
    id: string;
    name: string;
    targetType: TriggerTargetType;
    sourceType: TriggerSourceType;
    cronExpression: string | null;
    eventName: string | null;
    handlerPath: string | null;
    callbackUrl: string | null;
    payload: unknown;
    status: TriggerStatus;
    nextRunAt: string | null;
    lastRunAt: string | null;
    createdAt: string;
    updatedAt: string;
}
interface ListTriggersResult {
    triggers: Trigger[];
}
interface PublishEventResult {
    dispatched: number;
    waitResolved: number;
    eventName: string;
}
/** Create a new trigger (cron or event source, task/run/http target) */
declare function createTrigger(config: SylphxConfig, options: CreateTriggerOptions): Promise<Trigger>;
/** List all triggers for the project */
declare function listTriggers(config: SylphxConfig): Promise<ListTriggersResult>;
/** Get a trigger by ID */
declare function getTrigger(config: SylphxConfig, triggerId: string): Promise<Trigger>;
/** Update a trigger */
declare function updateTrigger(config: SylphxConfig, triggerId: string, options: UpdateTriggerOptions): Promise<Trigger>;
/** Delete a trigger */
declare function deleteTrigger(config: SylphxConfig, triggerId: string): Promise<{
    success: boolean;
}>;
/** Pause a trigger */
declare function pauseTrigger(config: SylphxConfig, triggerId: string): Promise<Trigger>;
/** Resume a paused trigger */
declare function resumeTrigger(config: SylphxConfig, triggerId: string): Promise<Trigger>;
/** Fire a trigger immediately (one-shot, regardless of schedule) */
declare function fireTrigger(config: SylphxConfig, triggerId: string): Promise<{
    success: boolean;
    message: string;
}>;
/**
 * Publish an event — dispatches all active event triggers matching the event name.
 * Endpoint: POST /triggers/events
 *
 * @example
 * ```typescript
 * await TriggersClient.publishEvent(config, 'user.signup', { userId: '123', plan: 'pro' })
 * ```
 */
declare function publishEvent(config: SylphxConfig, eventName: string, payload?: Record<string, unknown>): Promise<PublishEventResult>;
/**
 * Triggers client — namespace object exposing all trigger operations.
 * Use via `TriggersClient.create(...)`, `TriggersClient.publishEvent(...)`, etc.
 */
declare const TriggersClient: {
    readonly create: typeof createTrigger;
    readonly list: typeof listTriggers;
    readonly get: typeof getTrigger;
    readonly update: typeof updateTrigger;
    readonly delete: typeof deleteTrigger;
    readonly pause: typeof pauseTrigger;
    readonly resume: typeof resumeTrigger;
    readonly fire: typeof fireTrigger;
    readonly publishEvent: typeof publishEvent;
};

/**
 * Application Logs SDK (ADR-089 Phase 4a)
 *
 * Pure functions for runtime application log ingestion and querying,
 * backed by `apps/runtime/src/server/runtime/routes/logs.ts`:
 *
 *   POST /logs  — ingest log entries (requires secret key / serverAuth)
 *   GET  /logs  — query logs            (requires any key / configAuth)
 *
 * Logs are persisted in the project's `appLogs` table. Ingestion is
 * batched via `{ logs: [...] }` — do not call once per line in a loop.
 */

type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal';
interface LogEntry {
    readonly level: LogLevel;
    readonly message: string;
    readonly timestamp?: string;
    readonly metadata?: Record<string, unknown>;
    readonly source?: string;
    readonly traceId?: string;
}
interface StoredLogEntry {
    readonly id: string;
    readonly level: LogLevel;
    readonly message: string;
    readonly timestamp: string;
    readonly metadata: Record<string, unknown> | null;
    readonly traceId: string | null;
    readonly source: string | null;
    readonly userId: string | null;
}
interface IngestLogsResult {
    readonly ingested: number;
}
interface QueryLogsOptions {
    /** Minimum level to return (levels at or above this are included). */
    readonly level?: LogLevel;
    /** ISO 8601 lower bound (inclusive). */
    readonly since?: string;
    /** ISO 8601 upper bound (inclusive). */
    readonly until?: string;
    /** Max entries (default 100, server-enforced cap 1000). */
    readonly limit?: number;
    /** Full-text search against `message` (case-insensitive). */
    readonly search?: string;
    /** Filter by a specific trace correlation ID. */
    readonly traceId?: string;
}
interface QueryLogsResult {
    readonly logs: readonly StoredLogEntry[];
    readonly total: number;
}
/**
 * Ingest one or more log entries for the current project.
 *
 * @example
 * ```typescript
 * await ingestLogs(config, [
 *   { level: 'info', message: 'user signed in', metadata: { userId } },
 *   { level: 'warn', message: 'stripe webhook retry' },
 * ])
 * ```
 */
declare function ingestLogs(config: SylphxConfig, entries: readonly LogEntry[]): Promise<IngestLogsResult>;
/**
 * Query stored application logs with optional filtering.
 * Returns newest-first, capped at the server's limit (1000).
 *
 * @example
 * ```typescript
 * const { logs } = await queryLogs(config, { level: 'error', limit: 50 })
 * ```
 */
declare function queryLogs(config: SylphxConfig, options?: QueryLogsOptions): Promise<QueryLogsResult>;

/**
 * Miscellaneous SDK endpoints (ADR-089 Phase 4a)
 *
 * Backed by `apps/runtime/src/server/runtime/routes/misc.ts`:
 *
 *   GET  /app               — project metadata (configAuth)
 *   POST /challenge/verify  — step-up identity verification (userAuth)
 */

interface ProjectMetadata {
    readonly id: string;
    readonly name: string;
    readonly slug: string;
    readonly captcha?: {
        readonly enabled: true;
        readonly provider: 'turnstile' | 'hcaptcha';
        readonly siteKey: string;
        readonly action: 'register';
    };
    readonly [key: string]: unknown;
}
type ChallengeMethod = 'password' | 'email' | 'totp' | 'backup';
type ChallengeType = 'identity' | 'mfa';
interface ChallengeVerifyInput {
    /** Verification method to use. */
    readonly method: ChallengeMethod;
    /** Verification value matching `method` (password, email code, TOTP code, backup code). */
    readonly value: string;
}
interface ChallengeVerifyResult {
    readonly verified: boolean;
    readonly method: ChallengeMethod;
    readonly type: ChallengeType;
}
/**
 * Get app metadata for the current project (id, name, slug).
 * Cacheable — the BaaS emits `Cache-Control` headers for CDN reuse.
 */
declare function getProjectMetadata(config: SylphxConfig): Promise<ProjectMetadata>;
/**
 * Verify the authenticated user's identity for step-up authentication.
 *
 * Lockout is enforced server-side after repeated failures — respect the
 * `429` response. Methods accepted: password, email OTP, TOTP, backup code.
 *
 * @example
 * ```typescript
 * await verifyChallenge(config, { method: 'password', value: pw })
 * ```
 */
declare function verifyChallenge(config: SylphxConfig, input: ChallengeVerifyInput): Promise<ChallengeVerifyResult>;

/**
 * User SDK — customer-app-facing user management (ADR-089 Phase 4a)
 *
 * Backed by `apps/runtime/src/server/runtime/routes/user.ts`:
 *
 *   GET    /user/profile              — full profile
 *   PUT    /user/profile              — update profile
 *   GET    /user/security             — 2FA / password status
 *   GET    /user/sessions             — list active sessions
 *   PUT    /user/sessions/{id}        — rename session device
 *   DELETE /user/sessions/{id}        — revoke session
 *   GET    /user/export               — GDPR export
 *   DELETE /user/account              — GDPR erasure
 *
 * These routes are authenticated with a **user access token** (bearer) —
 * distinct from the platform-user namespace in `auth.ts` which targets
 * `/auth/platform-user/*` for Console / CLI operators. Customer apps
 * should use these; platform tooling should use `auth.user.*`.
 */

interface UserFullProfile {
    readonly id: string;
    readonly email: string;
    readonly name: string | null;
    readonly image: string | null;
    readonly emailVerified: boolean;
    readonly createdAt: string;
    readonly updatedAt: string;
    readonly [key: string]: unknown;
}
interface UserUpdateProfileInput {
    readonly name?: string;
    readonly image?: string;
    readonly metadata?: Record<string, unknown>;
}
interface UserSecuritySettings {
    readonly hasPassword: boolean;
    readonly twoFactorEnabled: boolean;
    readonly passkeyCount: number;
    readonly oauthProviders: readonly string[];
    readonly [key: string]: unknown;
}
interface UserSession {
    readonly id: string;
    readonly deviceName: string | null;
    readonly ipAddress: string | null;
    readonly userAgent: string | null;
    readonly createdAt: string;
    readonly lastActiveAt: string | null;
    readonly expiresAt: string;
    readonly current: boolean;
}
interface UserSessionsList {
    readonly sessions: readonly UserSession[];
}
interface UserDataExport {
    readonly exportedAt: string;
    readonly user: Record<string, unknown>;
    readonly [key: string]: unknown;
}
interface DeleteAccountResult {
    readonly success: boolean;
    readonly deletedData: readonly string[];
}
declare function getUserProfile(config: SylphxConfig): Promise<UserFullProfile>;
declare function updateUserProfile(config: SylphxConfig, input: UserUpdateProfileInput): Promise<UserFullProfile>;
declare function getUserSecurity(config: SylphxConfig): Promise<UserSecuritySettings>;
declare function listUserSessions(config: SylphxConfig): Promise<UserSessionsList>;
declare function revokeUserSession(config: SylphxConfig, sessionId: string): Promise<{
    success: boolean;
}>;
declare function renameUserSession(config: SylphxConfig, sessionId: string, deviceName: string): Promise<{
    success: boolean;
}>;
/**
 * Export every piece of personal data the platform holds about the
 * authenticated user (GDPR Article 20 — data portability).
 */
declare function exportUserData(config: SylphxConfig): Promise<UserDataExport>;
/**
 * Permanently delete the authenticated user's account and all
 * associated data (GDPR Article 17 — right to erasure). Callers
 * SHOULD gate this behind a `verifyChallenge()` step-up.
 */
declare function deleteUserAccount(config: SylphxConfig): Promise<DeleteAccountResult>;

/**
 * Security SDK — customer-app-facing account security management (ADR-089 Phase 4a)
 *
 * Backed by `apps/runtime/src/server/runtime/routes/security/*`:
 *
 *   /security/password/set              — set or replace password
 *   /security/oauth/disconnect          — remove linked OAuth provider
 *   /security/score                     — security posture score
 *   /security/email/change + confirm    — verified email change flow
 *   /security/passkeys (+ register)     — WebAuthn passkey CRUD
 *   /security/2fa/setup|verify|disable  — TOTP 2FA lifecycle
 *   /security/backup-codes              — view / regenerate recovery codes
 *   /security/alerts                    — security alert inbox
 *
 * All routes require a user access token (bearer). Destructive verbs
 * (disable 2FA, delete passkey, disconnect OAuth) SHOULD be gated
 * behind a `verifyChallenge()` step-up from `@sylphx/sdk/misc`.
 */

interface SecurityScoreResult {
    readonly score: number;
    readonly maxScore: number;
    readonly factors: readonly {
        readonly key: string;
        readonly label: string;
        readonly satisfied: boolean;
        readonly weight: number;
    }[];
}
interface PasswordSetInput {
    readonly password: string;
    /** Current password — required if one is already set. */
    readonly currentPassword?: string;
}
interface EmailChangeInput {
    readonly newEmail: string;
}
interface EmailConfirmInput {
    readonly code: string;
}
interface PasskeySummary {
    readonly id: string;
    readonly name: string | null;
    readonly createdAt: string;
    readonly lastUsedAt: string | null;
}
interface PasskeysList {
    readonly passkeys: readonly PasskeySummary[];
}
interface PasskeyRegistrationOptions {
    /** WebAuthn `PublicKeyCredentialCreationOptions` — pass to `navigator.credentials.create()`. */
    readonly [key: string]: unknown;
}
interface PasskeyRegistrationInput {
    /** WebAuthn credential response from `navigator.credentials.create()`. */
    readonly credential: Record<string, unknown>;
    readonly deviceName?: string;
}
interface TwoFactorSetupResult {
    readonly secret: string;
    readonly qrCodeUri: string;
    readonly recoveryHint?: string;
}
interface TwoFactorEnableResult {
    readonly success: boolean;
    readonly backupCodes: readonly string[];
}
interface BackupCodesResult {
    readonly codes: readonly string[];
    readonly remaining: number;
}
interface SecurityAlert {
    readonly id: string;
    readonly type: string;
    readonly severity: 'info' | 'warning' | 'critical';
    readonly message: string;
    readonly createdAt: string;
    readonly readAt: string | null;
    readonly metadata: Record<string, unknown> | null;
}
interface SecurityAlertsList {
    readonly alerts: readonly SecurityAlert[];
    readonly unread: number;
}
declare function setPassword(config: SylphxConfig, input: PasswordSetInput): Promise<{
    success: boolean;
}>;
declare function disconnectOAuthProvider(config: SylphxConfig, provider: string): Promise<{
    success: boolean;
}>;
declare function getSecurityScore(config: SylphxConfig): Promise<SecurityScoreResult>;
declare function requestEmailChange(config: SylphxConfig, input: EmailChangeInput): Promise<{
    success: boolean;
}>;
declare function confirmEmailChange(config: SylphxConfig, input: EmailConfirmInput): Promise<{
    success: boolean;
}>;
declare function listPasskeys(config: SylphxConfig): Promise<PasskeysList>;
declare function startPasskeyRegistration(config: SylphxConfig): Promise<PasskeyRegistrationOptions>;
declare function verifyPasskeyRegistration(config: SylphxConfig, input: PasskeyRegistrationInput): Promise<{
    success: boolean;
    passkey: PasskeySummary;
}>;
declare function renamePasskey(config: SylphxConfig, passkeyId: string, name: string): Promise<{
    success: boolean;
}>;
declare function deletePasskey(config: SylphxConfig, passkeyId: string): Promise<{
    success: boolean;
}>;
declare function setupTwoFactor(config: SylphxConfig): Promise<TwoFactorSetupResult>;
declare function verifyTwoFactorEnable(config: SylphxConfig, code: string): Promise<TwoFactorEnableResult>;
declare function disableTwoFactor(config: SylphxConfig): Promise<{
    success: boolean;
}>;
declare function getBackupCodes(config: SylphxConfig): Promise<BackupCodesResult>;
declare function regenerateBackupCodes(config: SylphxConfig): Promise<BackupCodesResult>;
declare function listSecurityAlerts(config: SylphxConfig): Promise<SecurityAlertsList>;
declare function markSecurityAlertRead(config: SylphxConfig, alertId: string): Promise<{
    success: boolean;
}>;
declare function markAllSecurityAlertsRead(config: SylphxConfig): Promise<{
    success: boolean;
    updated: number;
}>;

/**
 * OAuth SDK — customer-app-facing social login (ADR-089 Phase 4a)
 *
 * Backed by `apps/runtime/src/server/runtime/routes/oauth.ts`:
 *
 *   POST /oauth/authorize   — initiate OAuth flow, returns provider URL
 *
 * The per-provider callback handler is a browser-side redirect endpoint
 * on the runtime (`GET /oauth/callback/{provider}`); SDK consumers
 * redirect the user to `authorizationUrl`, then receive a `code` on
 * their own `redirect_uri` which they exchange via `signIn()` or
 * `auth/login` with grant_type=authorization_code.
 *
 * PKCE is required per OAuth 2.1. Callers MUST generate `code_verifier`
 * + `code_challenge` and persist the verifier in session / cookie for
 * the subsequent token exchange — this SDK does not retain state.
 *
 * ## Distinction from `auth.oauth`
 *
 * `auth.oauth.*` (from `./auth`) targets platform-plane admin mint
 * (`/auth/platform-jwt/mint`) used by Console / CLI. The functions
 * here target the customer-app social-login flow.
 */

/**
 * OIDC Discovery document shape (OIDC-Core §4). Every published field is
 * optional from the SDK's perspective because different providers
 * advertise different subsets; Sylphx's own doc is shipped fully
 * populated by {@link buildOidcDiscoveryDocument}.
 */
interface OidcDiscoveryDocument {
    readonly issuer: string;
    readonly authorization_endpoint?: string;
    readonly token_endpoint?: string;
    readonly userinfo_endpoint?: string;
    readonly jwks_uri?: string;
    readonly introspection_endpoint?: string;
    readonly revocation_endpoint?: string;
    readonly device_authorization_endpoint?: string;
    readonly response_types_supported?: readonly string[];
    readonly subject_types_supported?: readonly string[];
    readonly id_token_signing_alg_values_supported?: readonly string[];
    readonly grant_types_supported?: readonly string[];
    readonly scopes_supported?: readonly string[];
    readonly claims_supported?: readonly string[];
    readonly token_endpoint_auth_methods_supported?: readonly string[];
    readonly code_challenge_methods_supported?: readonly string[];
    readonly dpop_signing_alg_values_supported?: readonly string[];
    readonly frontchannel_logout_supported?: boolean;
    readonly backchannel_logout_supported?: boolean;
    readonly [k: string]: unknown;
}
interface OidcUserInfoResponse {
    readonly sub: string;
    readonly email?: string;
    readonly email_verified?: boolean;
    readonly name?: string;
    readonly picture?: string;
    readonly updated_at?: number;
    readonly [k: string]: unknown;
}
/**
 * Fetch the provider's OIDC discovery document. Works against any
 * spec-compliant provider (Sylphx, Okta, Azure AD, etc.) — pass the
 * issuer URL (scheme + host, no path) as `baseUrl`.
 *
 * @example
 * ```ts
 * const doc = await getOidcDiscoveryDocument({ baseUrl: 'https://api.sylphx.com' })
 * console.log(doc.token_endpoint)
 * ```
 */
declare function getOidcDiscoveryDocument(opts: {
    baseUrl: string;
}): Promise<OidcDiscoveryDocument>;
/**
 * Call the OIDC UserInfo endpoint (OIDC-Core §5.3). Returns identity
 * claims for the subject identified by `accessToken`. The token MUST
 * have been granted `openid` scope; otherwise the endpoint returns 403
 * `insufficient_scope`.
 *
 * @example
 * ```ts
 * const info = await userInfo({
 *   baseUrl: 'https://api.sylphx.com',
 *   accessToken: token.access_token,
 * })
 * console.log(info.sub, info.email)
 * ```
 */
declare function userInfo(opts: {
    baseUrl: string;
    accessToken: string;
    /** Override the discovered endpoint (e.g. when testing against a staging AS). */
    endpoint?: string;
}): Promise<OidcUserInfoResponse>;
type OAuthProvider = OAuthProviderId | (string & {});
type PkceMethod = 'S256' | 'plain';
interface OAuthAuthorizeInput {
    readonly provider: OAuthProvider;
    /** Where the OAuth provider sends the user after consent. */
    readonly redirectUri: string;
    /** PKCE code challenge derived from `code_verifier` (S256 recommended). */
    readonly codeChallenge: string;
    readonly codeChallengeMethod?: PkceMethod;
    /** Override the default scopes for the provider. */
    readonly scopes?: readonly string[];
    /** Opaque state for CSRF protection. */
    readonly state?: string;
}
interface OAuthAuthorizeResult {
    /** Fully-qualified URL to redirect the user to. */
    readonly authorizationUrl: string;
    /** Opaque server-side state — echo on callback handler if present. */
    readonly state: string;
}
interface OAuthProvidersResult {
    readonly providers: readonly OAuthProvider[];
}
interface OAuthCodeExchangeInput {
    readonly code: string;
    readonly codeVerifier: string;
    readonly anonymousId?: string;
}
/**
 * Initiate an OAuth flow with the given provider. Returns the provider's
 * authorization URL — redirect the user to it.
 *
 * @example
 * ```typescript
 * import { generatePkce } from '@sylphx/sdk'
 * const { verifier, challenge } = await generatePkce()
 * sessionStorage.setItem('pkce_verifier', verifier)
 * const { authorizationUrl } = await authorizeOAuth(config, {
 *   provider: 'google',
 *   redirectUri: 'https://app.example.com/auth/callback',
 *   codeChallenge: challenge,
 *   codeChallengeMethod: 'S256',
 * })
 * window.location.href = authorizationUrl
 * ```
 */
declare function authorizeOAuth(config: SylphxConfig, input: OAuthAuthorizeInput): Promise<OAuthAuthorizeResult>;
/**
 * List OAuth providers enabled for the current customer app/environment.
 *
 * Uses the same `SylphxConfig` routing surface as every other BaaS call, so
 * customer apps do not need a second app-id or platformUrl configuration path.
 */
declare function listOAuthProviders(config: SylphxConfig): Promise<OAuthProvidersResult>;
/**
 * Exchange a social-login authorization code for Platform session tokens.
 *
 * This is the customer-app counterpart to {@link authorizeOAuth}. It uses the
 * app's publishable connection URL as the OAuth client id and keeps PKCE in
 * the caller's control.
 */
declare function exchangeOAuthCode(config: SylphxConfig, input: OAuthCodeExchangeInput): Promise<TokenResponse>;
/**
 * Parse an OAuth callback URL (e.g. `window.location.href`) into the
 * fields a customer app needs to complete sign-in.
 *
 * Pure function — no network. Does NOT validate `state` against your
 * session store; callers MUST compare `parsed.state` to the opaque
 * value they persisted before redirect (CSRF mitigation).
 */
declare function parseOAuthCallback(url: string): {
    readonly code: string | null;
    readonly state: string | null;
    readonly error: string | null;
    readonly errorDescription: string | null;
};
/**
 * Generate a cryptographically random PKCE verifier + S256 challenge
 * pair (RFC 7636 §4.1-4.2). Works in browsers (Web Crypto) and Bun /
 * Node 18+ (`globalThis.crypto`).
 */
declare function generatePkce(): Promise<{
    verifier: string;
    challenge: string;
}>;

/**
 * Promo Code SDK (ADR-089 Phase 4a)
 *
 * Backed by `apps/runtime/src/server/runtime/routes/promo.ts`:
 *
 *   POST /promo/validate       — check code validity (projectAuth)
 *   POST /promo/redeem         — redeem for current user (userAuth)
 *   GET  /admin/promo          — list codes       (serverAuth)
 *   POST /admin/promo          — create code      (serverAuth)
 *   GET  /admin/promo/{id}     — get single code  (serverAuth)
 *   PATCH  /admin/promo/{id}   — update code      (serverAuth)
 *   DELETE /admin/promo/{id}   — archive code     (serverAuth)
 *   GET  /admin/promo/redemptions — redemption history (serverAuth)
 */

type PromoType = 'percent_off' | 'fixed_off' | 'free_trial' | 'feature_unlock';
type PromoStatus = 'active' | 'paused' | 'expired' | 'archived';
interface PromoCode {
    readonly id: string;
    readonly code: string;
    readonly name: string;
    readonly description: string | null;
    readonly type: PromoType;
    readonly value: number;
    readonly maxUses: number | null;
    readonly maxUsesPerUser: number | null;
    readonly usedCount: number;
    readonly status: PromoStatus;
    readonly expiresAt: string | null;
    readonly startsAt: string | null;
    readonly minPurchaseAmount: number | null;
    readonly applicablePlanIds: readonly string[] | null;
    readonly metadata: Record<string, unknown> | null;
    readonly createdAt: string;
    readonly updatedAt: string;
}
interface PromoValidationPreview {
    readonly code: string;
    readonly name: string;
    readonly description: string | null;
    readonly type: PromoType;
    readonly value: number;
    readonly expiresAt: string | null;
}
interface ValidatePromoInput {
    readonly code: string;
    readonly planId?: string;
    readonly purchaseAmount?: number;
}
interface ValidatePromoResult {
    readonly valid: boolean;
    readonly promo: PromoValidationPreview | null;
    readonly error?: string;
}
interface RedeemPromoInput {
    readonly code: string;
    readonly planId?: string;
    readonly purchaseAmount?: number;
}
interface RedeemPromoResult {
    readonly success: boolean;
    readonly redemption: {
        readonly id: string;
        readonly code: string;
        readonly type: PromoType;
        readonly appliedValue: number;
        readonly discountAmount: number | null;
        readonly trialDays: number | null;
        readonly featureId: string | null;
    };
}
interface CreatePromoInput {
    readonly code: string;
    readonly name: string;
    readonly description?: string;
    readonly type: PromoType;
    readonly value: number;
    readonly maxUses?: number;
    readonly maxUsesPerUser?: number;
    readonly expiresAt?: string;
    readonly startsAt?: string;
    readonly minPurchaseAmount?: number;
    readonly applicablePlanIds?: readonly string[];
    readonly metadata?: Record<string, unknown>;
}
interface UpdatePromoInput {
    readonly name?: string;
    readonly description?: string | null;
    readonly status?: PromoStatus;
    readonly maxUses?: number | null;
    readonly maxUsesPerUser?: number | null;
    readonly expiresAt?: string | null;
    readonly startsAt?: string | null;
    readonly minPurchaseAmount?: number | null;
    readonly applicablePlanIds?: readonly string[] | null;
    readonly metadata?: Record<string, unknown>;
}
interface ListPromosOptions {
    readonly status?: PromoStatus;
    readonly limit?: number;
    readonly offset?: number;
}
interface ListPromosResult {
    readonly promos: readonly PromoCode[];
    readonly total: number;
}
interface PromoRedemption {
    readonly id: string;
    readonly promoId: string;
    readonly code: string;
    readonly userId: string;
    readonly appliedValue: number;
    readonly createdAt: string;
}
interface ListRedemptionsOptions {
    readonly promoId?: string;
    readonly userId?: string;
    readonly limit?: number;
    readonly offset?: number;
}
interface ListRedemptionsResult {
    readonly redemptions: readonly PromoRedemption[];
    readonly total: number;
}
/** Validate a promo code — safe to call with a publishable key. */
declare function validatePromo(config: SylphxConfig, input: ValidatePromoInput): Promise<ValidatePromoResult>;
/** Redeem a promo for the authenticated user. Requires a user access token. */
declare function redeemPromo(config: SylphxConfig, input: RedeemPromoInput): Promise<RedeemPromoResult>;
declare function listPromos(config: SylphxConfig, options?: ListPromosOptions): Promise<ListPromosResult>;
declare function getPromo(config: SylphxConfig, promoId: string): Promise<{
    promo: PromoCode;
}>;
declare function createPromo(config: SylphxConfig, input: CreatePromoInput): Promise<{
    promo: PromoCode;
}>;
declare function updatePromo(config: SylphxConfig, promoId: string, input: UpdatePromoInput): Promise<{
    promo: PromoCode;
}>;
declare function deletePromo(config: SylphxConfig, promoId: string): Promise<{
    success: boolean;
}>;
declare function listPromoRedemptions(config: SylphxConfig, options?: ListRedemptionsOptions): Promise<ListRedemptionsResult>;

/**
 * React-layer SDK types — the tRPC-like wrapper shapes used by
 * `services-context.ts`, `react/hooks/*`, and `react/ui/*`. Kept separate
 * from `../types` so the main `@sylphx/sdk` entry stays tree-shakeable
 * and free of React-specific surface.
 *
 * Wire-shape types (request/response envelopes) come from `@sylphx/contract`
 * via each SDK module. The types here model the React-hook convenience
 * shapes — close to OpenAI's chat format, Stripe's idempotency semantics,
 * and the SDK's own security-scoring layer — that aren't part of the
 * platform wire.
 */

type AIProvider = 'openai' | 'anthropic' | 'google' | 'mistral' | 'groq' | 'together';
type AIRequestType = 'chat' | 'completion' | 'embedding' | 'image' | 'vision' | 'audio' | 'tts';
type AIMessageRole = 'system' | 'user' | 'assistant' | 'tool';
interface AIMessage {
    role: AIMessageRole;
    content: string;
    name?: string;
    tool_calls?: AIToolCall[];
    tool_call_id?: string;
}
interface AITool {
    type: 'function';
    function: {
        name: string;
        description?: string;
        parameters?: Record<string, unknown>;
    };
}
interface AIToolCall {
    id: string;
    type: 'function';
    function: {
        name: string;
        arguments: string;
    };
}
interface ChatCompletionInput {
    model?: string;
    messages: AIMessage[];
    temperature?: number;
    maxTokens?: number;
    topP?: number;
    stop?: string | string[];
    tools?: AITool[];
    toolChoice?: 'auto' | 'none' | {
        type: 'function';
        function: {
            name: string;
        };
    };
    stream?: boolean;
    frequencyPenalty?: number;
    presencePenalty?: number;
}
interface ChatCompletionResponse {
    id: string;
    model: string;
    choices: Array<{
        index: number;
        message: AIMessage;
        finishReason: string | null;
    }>;
    usage: {
        promptTokens: number;
        completionTokens: number;
        totalTokens: number;
    };
}
interface TextCompletionInput {
    model?: string;
    prompt: string;
    maxTokens?: number;
    temperature?: number;
    topP?: number;
    stop?: string[];
}
interface TextCompletionResponse {
    id: string;
    model: string;
    choices: Array<{
        index: number;
        text: string;
        finishReason: string | null;
    }>;
    usage: {
        promptTokens: number;
        completionTokens: number;
        totalTokens: number;
    };
}
interface EmbeddingInput {
    model?: string;
    input: string | string[];
    dimensions?: number;
}
interface EmbeddingResponse {
    model: string;
    embeddings: number[][];
    data: Array<{
        embedding: number[];
        index: number;
    }>;
    usage: {
        promptTokens: number;
        totalTokens: number;
    };
}
interface VisionInput {
    model?: string;
    messages: Array<{
        role: AIMessageRole;
        content: string | Array<{
            type: 'text';
            text: string;
        } | {
            type: 'image_url';
            image_url: {
                url: string;
            };
        }>;
    }>;
    maxTokens?: number;
}
interface AIStreamChunk {
    id: string;
    model: string;
    delta?: {
        content?: string;
        tool_calls?: AIToolCall[];
    };
    finishReason?: string | null;
    choices?: Array<{
        index: number;
        delta: {
            content?: string;
            tool_calls?: AIToolCall[];
        };
        finishReason: string | null;
    }>;
}
/** Richer than contract `AIModel` — adds capability/cost metadata for the model-selector UI. */
interface AIModelInfo {
    id: string;
    name: string;
    description?: string;
    provider: AIProvider;
    capabilities: string[];
    contextWindow: number;
    maxOutputTokens: number;
    inputCostPer1M?: number;
    outputCostPer1M?: number;
}
interface AIUsageStats {
    period: {
        start: string;
        end: string;
    };
    totalRequests: number;
    totalTokens: number;
    totalCostMicrodollars: number;
    byModel: Record<string, {
        requests: number;
        tokens: number;
        cost: number;
    }>;
}
interface AIRateLimitInfo {
    requestsRemaining: number;
    requestsLimit: number;
    tokensRemaining: number;
    tokensLimit: number;
    resetAt: string;
}
interface AIListModelsOptions {
    provider?: AIProvider;
    capability?: string;
    search?: string;
    limit?: number;
    offset?: number;
}
interface AIListModelsResponse {
    models: AIModelInfo[];
    total: number;
    hasMore: boolean;
}
interface UserProfile {
    id: string;
    email: string;
    name: string | null;
    image: string | null;
    emailVerified?: boolean;
    twoFactorEnabled: boolean;
    createdAt: string;
}
interface SecuritySettings {
    twoFactorEnabled: boolean;
    backupCodesRemaining: number;
    passwordSet: boolean;
    lastPasswordChange: string | null;
}
interface LoginHistoryEntry {
    id: string;
    ipAddress: string | null;
    userAgent: string | null;
    location: string | null;
    device: string | null;
    browser: string | null;
    os: string | null;
    loginAt: string;
    success: boolean;
}

/**
 * `realtime` top-level namespace — customer-app data plane exposes
 * `realtime.emit` / `realtime.history`, Platform admin surface nests
 * at `realtime.admin.channels.*` (ADR-089 Phase 3a / Σ1 SoC rename).
 */
declare const realtime: {
    readonly admin: {
        readonly status: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly projectId: string;
            readonly userAgent?: string;
        }) => Promise<PlatformRealtimeStatusResult>;
        readonly list: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly projectId: string;
            readonly userAgent?: string;
        }) => Promise<PlatformRealtimeListChannelsResult>;
        readonly create: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly projectId: string;
            readonly name: string;
            readonly userAgent?: string;
        }) => Promise<PlatformRealtimeCreateChannelResult>;
        readonly delete: (opts: {
            readonly baseUrl: string;
            readonly accessToken: string;
            readonly projectId: string;
            readonly channelName: string;
            readonly userAgent?: string;
        }) => Promise<PlatformRealtimeDeleteChannelResult>;
    };
    readonly emit: typeof realtimeEmit;
    readonly history: typeof getRealtimeHistory;
};
/**
 * `functions` top-level namespace — Platform admin surface nests at
 * `functions.admin.downloadBundle` (ADR-089 Phase 3a / Σ1 SoC rename).
 * Customer-app function invocation surface is TBD.
 */
declare const functions: {
    readonly admin: {
        readonly downloadBundle: (opts: {
            readonly baseUrl: string;
            readonly internalToken: string;
            readonly storagePath: string;
            readonly userAgent?: string;
        }) => Promise<PlatformFunctionsDownloadBundleResult>;
    };
};

export { ACHIEVEMENT_TIER_CONFIG, type AIListModelsOptions, type AIListModelsResponse, type AIMessage, type AIMessageRole, type AIModel, type AIModelInfo, type AIModelsResponse, type AIProvider, type AIRateLimitInfo, type AIRateLimitResponse, type AIRequestType, type AIStreamChunk, type AITool, type AIToolCall, type AIUsageResponse, type AIUsageStats, type AccessTokenPayload, type AchievementCategory, type AchievementCriteria, type AchievementCriterion, type AchievementDefinition, type AchievementTier, type AchievementType, type AchievementUnlockEvent, type AdminUser, ArtifactClient, type AuditQueryFilter, type AuditQueryResult, AuthenticationError, AuthorizationError, BILLING_ALLOWED_ROLES, BUILD_MINUTES_INCLUDED, BUILD_MINUTE_PRICES, BUILD_SIZE_MULTIPLIERS, BYTES_PER_GB, type BackupCodesResult, type BatchEvent, type BatchIndexInput, type BatchIndexResult, type BillingAllowedRole, type Breadcrumb, type BrowserCreateOptions, type BrowserSessionInfo, type BrowserSessionStatus, type BuildConnectionUrlInput, type BuildLog, type BuildLogHistoryResponse, type BuildMachineTier, CI_BUILD_MINUTE_PRICE_MICRODOLLARS, CI_FREE_MINUTES_PER_MONTH, CI_MACOS_MULTIPLIER, CI_MACOS_SIZE_MULTIPLIERS, CI_SIZE_MULTIPLIERS, COMPUTE_PRICE_PER_HOUR_MICRODOLLARS, COMPUTE_RAM_RATE_MICRODOLLARS, COMPUTE_VCPU_ACTIVE_RATE_MICRODOLLARS, COMPUTE_VCPU_IDLE_RATE_MICRODOLLARS, CONSOLE_APP_SLUG, CREDENTIAL_REGEX, CREDIT_EXPIRY_MONTHS, type CaptureExceptionRequest, type CaptureMessageRequest, type ChallengeMethod, type ChallengeType, type ChallengeVerifyInput, type ChallengeVerifyResult, type ChatCompletionInput, type ChatCompletionResponse, type ChatInput, type ChatMessage, type ChatResult, type ChatStreamChunk, type CircuitBreakerConfig, CircuitBreakerOpenError, type CircuitState, type CommandResult, type ComputerDesktopStatus, type ComputerInputAction, type ComputerScreenshotFormat, type ComputerSessionInfo, type ComputerSessionStatus, type ComputerUiElement, type ComputerUiSnapshot, type ConnectionCredentialType, type ConnectionEnv, type ConsentCategory, type ConsentHistoryEntry, type ConsentHistoryResult, type ConsentPurposeDefaults, type ConsentType, type ContentPart, type CopyFileOptions, type CreateDistributedRunOptions, type CreateOrgInput, type CreatePermissionInput, type CreatePromoInput, type CreateRoleInput, type CreateRunOptions, type CreateTriggerOptions, type CriteriaOperator, type CronInput, type CronSchedule, type CronSource, DEFAULT_MAX_INSTANCES, DEFAULT_POINTS_REWARD, DISCOUNT_DURATION_MONTHS, DISCOUNT_PERCENT, type DatabaseConnectionInfo, type DatabaseStatus, type DatabaseStatusInfo, type DebugCategory, type DeduplicationConfig, type DeleteAccountResult, type DeleteDocumentInput, type DeployHistoryResponse, type DeployInfo, type DeployStatus, type DeviceApproveInput, type DeviceApproveResult, type DeviceDenyInput, type DeviceDenyResult, type DeviceGrant, type DeviceInitInput, type DevicePollResult, DeviceSessionClient, DistributedRunHandle, type DistributedRunStatus, type DynamicRestClient, ERROR_CODE_STATUS, type EmailChangeInput, type EmailConfirmInput, type EmbedInput, type EmbedResult, type EmbeddingInput, type EmbeddingResponse, type LeaderboardEntry as EngagementLeaderboardEntry, type LeaderboardResult as EngagementLeaderboardResult, type EnvVar, type ErrorCode, type ErrorResponse, type EventSource, type ExceptionFrame, type ExceptionValue, type ExecEvent, type ExecOptions, type ExecResult, type ErrorDetails$1 as ExtractedErrorDetails, FREE_COMPUTE_HOURS, FREE_STORAGE_GB, type FacetsResponse, type FileEvent, type FlagContext, type FlagResult, type GetConsentHistoryInput, type GetConsentsInput, type GetFacetsInput, type GetSecretInput, type GetSecretResult, type GetSecretsInput, type GetSecretsResult, HOURS_PER_MONTH, type HttpTarget, INSTANCE_TYPES, INSTANCE_TYPE_ALIASES, INSTANCE_TYPE_ORDER, INVOICE_DUE_DAYS, type IdentifyInput, type ImpersonationActive, type ImpersonationEndResult, type ImpersonationInfo, type ImpersonationStartResult, type IndexDocumentInput, type IndexDocumentResult, type IngestLogsResult, type InstanceTypeDefinition, type InstanceTypeId, InvalidConnectionUrlError, type InviteMemberInput, type InviteUserRequest, type InviteUserResponse, KV_FREE_STORAGE_GB, type KvExpireRequest, type KvHgetRequest, type KvHgetallRequest, type KvHsetRequest, type KvIncrRequest, type KvLpushRequest, type KvLrangeRequest, type KvMetric, type KvMgetRequest, type KvMsetRequest, type KvRateLimitRequest, type KvRateLimitResult, type KvScanOptions, type KvScanResult, type KvSetOptions, type KvSetRequest, type KvZMember, type KvZaddRequest, type KvZrangeRequest, LEGACY_INSTANCE_TYPE_ORDER, type LeaderboardAggregation, type LeaderboardDefinition, type LeaderboardEntry$1 as LeaderboardEntry, type LeaderboardOptions, type LeaderboardQueryOptions, type LeaderboardResetPeriod, type LeaderboardResult$1 as LeaderboardResult, type LeaderboardSortDirection, type LinkAnonymousConsentsInput, type ListFilesOptions, type ListPromosOptions, type ListPromosResult, type ListRedemptionsOptions, type ListRedemptionsResult, type ListRunsOptions, type ListRunsResult, type ListScheduledEmailsOptions, type ListSecretKeysInput, type ListTriggersResult, type ListUsersOptions, type ListUsersResult, type LogEntry, type LogLevel, type LoginHistoryEntry, type LoginRequest, type LoginResponse, MAX_PASSWORD_LENGTH, MAX_PAYMENT_ATTEMPTS, MICRODOLLARS_PER_CENT, MIN_PASSWORD_LENGTH, type MeResponse, type MemberPermissionsResult, type MintAccessTokenClaims, type MintAccessTokenResult, type MonitoringResponse, type MonitoringSeverity, type NativeStepContext, type NativeTaskDefinition, type TaskRunStatus as NativeTaskRunStatus, NetworkError, NotFoundError, type OAuthAuthorizeInput, type OAuthAuthorizeResult, type OAuthCodeExchangeInput, type OAuthProvider, type OAuthProvidersResult, type OidcDiscoveryDocument, type OidcUserInfoResponse, type OrgRole, type OrgScopedTokenResponse, type OrgTokenPayload, type OrganizationInvitation, type OrganizationMember, type OrganizationMembership, type OrganizationsListResult, PASSWORD_REQUIREMENTS, PLATFORM_PLANS, PLATFORM_PLAN_ORDER, PLATFORM_PLAN_ORDER_ALL, PREMIUM_TRIAL_DAYS, type PageInput, type PaginatedResponse, type PaginationInput, type ParsedConnectionUrl, type ParsedUserAgent, type PasskeyRegistrationInput, type PasskeyRegistrationOptions, type PasskeySummary, type PasskeysList, type PasswordSetInput, type Permission, type PkceMethod, type Plan, type PlatformAccessTokenClaims, type PlatformFunctionsDownloadBundleResult, type PlatformLogoutInput, type PlatformPasswordChangeInput, type PlatformPasswordChangeResult, type PlatformPasswordSetInput, type PlatformPasswordSetResult, type PlatformPasswordStatusResult, type PlatformPlanDefinition, type PlatformPlanFeatures, type PlatformPlanId, type PlatformPlanLimits, type PlatformRealtimeChannel, type PlatformRealtimeCreateChannelResult, type PlatformRealtimeDeleteChannelResult, type PlatformRealtimeListChannelsResult, type PlatformRealtimeStatusResult, type PlatformRefreshInput, type PlatformRefreshResult, type PlatformSessionRenameInput, type PlatformSessionRenameResult, type PlatformSessionRevokeAllResult, type PlatformSessionRevokeInput, type PlatformSessionRevokeOtherResult, type PlatformSessionRevokeResult, type PlatformSessionsListResult, type PlatformUserDeleteInput, type PlatformUserDeleteResult, type PlatformUserExportResult, type PlatformUserRecord, type PlatformUserResolution, type ProcessEvent, type ProcessInfo, type ProcessStartOptions, type ProcessSummary, type ProjectMetadata, type PromoCode, type PromoRedemption, type PromoStatus, type PromoType, type PromoValidationPreview, type PublishEventResult, type PushCampaign, type PushCampaignStats, type PushCampaignVariant, type PushNotification, type PushNotificationPayload, type PushSegment, type PushSegmentFilter, type PushServiceWorkerConfig, type PushSubscription, type QueryLogsOptions, type QueryLogsResult, RETRYABLE_CODES, RateLimitError, type RateLimitStatusFilter, type RateLimitStatusResult, type RateLimitStrategiesFilter, type RateLimitStrategiesResult, type RateLimitStrategyDeleteInput, type RateLimitStrategyDeleteResult, type RateLimitStrategyUpsertInput, type RateLimitStrategyUpsertResult, type RealtimeEmitRequest, type RealtimeEmitResponse, type RealtimeHistoryRequest, type RealtimeHistoryResponse, type RealtimeMetric, type RecordActivityInput, type RecordActivityResult, type RedeemPromoInput, type RedeemPromoResult, type RedeemReferralInput, type RedeemResult, type ReferralCode, type ReferralStats, type RegisterInput, type RegisterRequest, type RegisterResponse, RenderClient, type ResendEmailVerificationRequest, type ResendEmailVerificationResponse, type RestClient, type RestClientConfig, type RestDynamicConfig, type RetryConfig, type RevokeTokenOptions, type Role, type RollbackDeployRequest, type Run, RunHandle, type RunLogsResult, type RunMachineSize, type RunResult, type RunStatus, type RunTarget, type RunVolumeMount, type CreateRunOptions as RunWorkerOptions, RunsClient, SERVICE_METRICS, STORAGE_PRICE_PER_GB_MONTH_MICRODOLLARS, SandboxBrowser, SandboxCapabilities, SandboxClient, SandboxComputer, type SandboxFile, SandboxFiles, type SandboxMachineSize, type SandboxOptions, SandboxProcesses, type SandboxRecord, SandboxWatch, type ScheduleEmailOptions, type ScheduledEmail, type ScheduledEmailStats, type ScheduledEmailsResult, type SearchInput, type SearchResponse, type SearchResultItem, type SearchStatsResult, type SearchType, type SecretKeyInfo, type SecurityAlert, type SecurityAlertsList, type SecurityScoreResult, type SecuritySettings, type SendEmailOptions, type SendResult, type SendTemplatedEmailOptions, type SendToUserOptions, type ServeOptions, type ServeResult, type ServiceCredentials, type ServiceMetrics, type ServiceTokenResponse, type SessionResult, type SetConsentsInput, type SetEnvVarRequest, type SignedUrlOptions, StepCompleteSignal, StepSleepSignal, type StoredLogEntry, type StreakDefinition, type StreakFrequency, type StreakState, type StreamMessage, type SubmitScoreInput, type SubmitScoreResult, type Subscription, type SuccessResponse, type SylphxClientInput, type SylphxConfig, type SylphxConfigInput, SylphxError, type SylphxErrorCode, type SylphxErrorOptions, TRANSFER_PRICE_PER_GB_MICRODOLLARS, type TaskConfig, type TaskHandle, type TaskInput, type TaskMachineSize, type TaskResult, type TaskRunContext, type TaskRunDetail, type TaskRunStep, type TaskStatus, type TaskTarget, type TextCompletionInput, type TextCompletionResponse, TimeoutError, type TokenIntrospectionResult, type TokenResponse, type Tool, type ToolCall, type TrackClickInput, type TrackInput, type Trigger, type TriggerDeployRequest, type TriggerOptions, type TriggerRunMachineSize, type TriggerSource, type TriggerSourceType, type TriggerStatus, type TriggerTarget, type TriggerTargetType, TriggersClient, type TwoFactorEnableResult, type TwoFactorSetupResult, type TwoFactorVerifyRequest, type UpdateOrgInput, type UpdatePromoInput, type UpdateRoleInput, type UpdateTriggerOptions, type UploadCreateOptions, type UploadProgressEvent, type UpsertDocumentInput, type UpsertDocumentResult, type User, type UserAchievement, type UserConsent, type UserDataExport, type UserFullProfile, type UserOrganization, type UserProfile, type UserSecuritySettings, type UserSession, type UserSessionsList, type UserUpdateProfileInput, type ValidatePromoInput, type ValidatePromoResult, ValidationError, type VisionInput, WalletClient, type WatchEntry, type WatchOptions, type WebhookConfig, type WebhookConfigUpdate, type WebhookDeliveriesResult, type WebhookDelivery, type WebhookStats, RunHandle as WorkerHandle, type RunLogsResult as WorkerLogsResult, type RunResult as WorkerResult, type Run as WorkerRun, type RunStatus as WorkerStatus, type RunVolumeMount as WorkerVolumeMount, WorkersClient, type WorkspaceRecord, acceptAllConsents, acceptOrganizationInvitation, assignMemberRole, audit, authorizeOAuth, batchIndex, buildConnectionUrl, calculatePercentage, canDeleteOrganization, canManageMembers, canManageSettings, cancelScheduledEmail, cancelTask, captureException, captureExceptionRaw, captureMessage, centsToDollars, chat, chatStream, checkFlag, complete, confirmEmailChange, cookies, createCheckout, createClient, createConfig, createCron, createDynamicRestClient, createOrganization, createPermission, createPortalSession, createPromo, createRestClient, createRole, createServerClient, createServiceWorkerScript, createStepContext, createTasksHandler, createTracker, createWorkspace, debugError, debugLog, debugTimer, debugWarn, declineOptionalConsents, deleteCron, deleteDocument, deleteEnvVar, deleteOrganization, deletePasskey, deletePermission, deletePromo, deleteRole, deleteUser, deleteUserAccount, deleteWorkspace, device, disableDebug, disableTwoFactor, disconnectOAuthProvider, dpop, embed, enableDebug, escapeCsvField, escapeHtml, exchangeOAuthCode, exponentialBackoff, exportUserData, extendedSignUp, getErrorDetails$1 as extractErrorDetails, getErrorMessage$1 as extractErrorMessage, forgotPassword, forkWorkspace, formatBytes, formatCents, formatCurrency, formatDate, formatDateTime, formatDuration, formatMicrodollars, formatMonthYear, formatNumber, formatPercent, formatRelativeTime, formatRelativeTimeShort, formatTime, functions, generateAnonymousId, generatePkce, generateReferralCode, generateSlug, getAchievement, getAchievementPoints, getAchievements, getActivePlans, getAllFlags, getAllSecrets, getAllStreaks, getAvailableInstanceTypes, getBackupCodes, getBaseUrl, getBillingBalance, getBillingStatusVariant, getBillingUsage, getBuildLogHistory, getCircuitBreakerState, getConsentHistory, getConsentTypes, getDatabaseConnectionString, getDatabaseStatus, getDebugMode, getDefaultInstanceType, getDeployHistory, getDeployStatus, getEnvPrefix, getErrorCode, getErrorDetails, getErrorMessage, getFacets, getFlagPayload, getFlags, getInvoiceStatusVariant, getLeaderboard, getMemberPermissions, getMyReferralCode, getOidcDiscoveryDocument, getOrgScopedToken, getOrganization, getOrganizationInvitations, getOrganizationMembers, getOrganizations, getPlanMonthlyPrice, getPlans, getProjectMetadata, getPromo, getPushPreferences, getRealtimeHistory, getReferralLeaderboard, getReferralStats, getRestErrorMessage, getRole, getSafeErrorMessage, getScheduledEmail, getScheduledEmailStats, getSearchStats, getSecret, getSecrets, getSecurityScore, getSession, getStreak, getSubscription, getTask, getTaskRun, getUser, getUserByEmail, getUserConsents, getUserLeaderboardRank, getUserProfile, getUserSecurity, getVariant, getWebhookConfig, getWebhookDeliveries, getWebhookDelivery, getWebhookStats, getWorkspace, getWorkspaceCapacity, hasAllPermissions, hasAnyPermission, hasBillingAccess, hasConsent, hasError, hasPermission, hasRole, hasSecret, identify, impersonation, incrementAchievementProgress, indexDocument, ingestLogs, initPushServiceWorker, installGlobalDebugHelpers, introspectToken, inviteOrganizationMember, inviteUser, isChallengeRequired, isEmailConfigured, isEnabled, isPlanDeprecated, isRetryableError, isSylphxError, isValidInstanceType, kvDelete, kvExists, kvExpire, kvGet, kvGetJSON, kvHget, kvHgetall, kvHset, kvIncr, kvLpush, kvLrange, kvMget, kvMset, kvRateLimit, kvScan, kvSet, kvSetJSON, kvZadd, kvZrange, leaveOrganization, linkAnonymousConsents, listEnvVars, listOAuthProviders, listOrganizations, listPasskeys, listPermissions, listPromoRedemptions, listPromos, listRoles, listScheduledEmails, listSecretKeys, listSecurityAlerts, listTasks, listUserSessions, listUsers, listWorkspaces, markAllSecurityAlertsRead, markSecurityAlertRead, microsToDollars, oauth, page, parseConnectionUrl, parseOAuthCallback, parseUserAgent, password, pauseCron, pinWorkspace, platformAuth, campaigns as pushCampaigns, segments as pushSegments, queryLogs, rateLimits, realtime, realtimeEmit, reclaimWorkspace, reclaimWorkspaceSubpath, recordStreakActivity, recoverStreak, redeemPromo, redeemReferralCode, refreshToken, regenerateBackupCodes, regenerateReferralCode, registerPush, registerPushServiceWorker, removeOrganizationMember, renamePasskey, renameUserSession, replayWebhookDelivery, requestEmailChange, rescheduleEmail, resendVerificationEmail, resetCircuitBreaker, resetDebugModeCache, resetPassword, resetPlatformCookieCache, resetPlatformJwksCache, resolveCanonicalInstanceType, resolveMaxInstances, resolveResources, resumeCron, revokeAllTokens, revokeOrganizationInvitation, revokeToken, revokeUserSession, rollbackDeploy, safeJsonParse, scheduleEmail, scheduleTask, search, sendEmail, sendEmailToUser, sendPush, sendTemplatedEmail, serve, sessions, setConsents, setEnvVar, setPassword, setupTwoFactor, signIn, signInAsService, signOut, signUp, startPasskeyRegistration, storage, streamToString, submitScore, suspendUser, switchOrg, task, taskStub, toSylphxError, track, trackBatch, trackClick, triggerDeploy, unlockAchievement, unregisterPush, updateOrganization, updateOrganizationMemberRole, updatePromo, updatePushPreferences, updateRole, updateUser, updateUserMetadata, updateUserProfile, updateWebhookConfig, upsertDocument, user, userInfo, validateInstanceTypeForPlan, validatePromo, verifyAccessToken, verifyChallenge, verifyEmail, verifyPasskeyRegistration, verifySignature as verifyTaskSignature, verifyTwoFactor, verifyTwoFactorEnable, withToken };
