@sylphx/sdk 0.19.2 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/connection-url.ts","../src/constants.ts","../src/errors.ts","../src/config.ts","../src/lib/triggers/index.ts","../src/lib/tasks/connection.ts","../src/lib/tasks/handler.ts","../src/lib/tasks/serve.ts","../src/lib/tasks/task.ts","../src/lib/tasks/api-functions.ts","../src/lib/tasks/types.ts","../src/lib/tasks/legacy.ts","../src/lib/tasks/workflow-builder.ts"],"sourcesContent":["/**\n * Sylphx Connection URL — Single Source of Truth (ADR-123)\n *\n * Implements the canonical connection string format defined in ADR-055 §5.\n * This module is the SDK-owned SSOT per ADR-123 (SDK/application boundary).\n * Consuming applications MUST import from `@sylphx/sdk` rather than duplicating\n * this logic.\n *\n * Hosted format:\n * sylphx://{credential}@{tenant-slug}.api.sylphx.com[:port][/v{version}]\n *\n * Custom/self-hosted domains are also accepted as long as the first DNS label\n * is the tenant slug.\n *\n * Examples:\n * sylphx://pk_prod_f19e5cdc3cc54f7ff81bdc26ec5bfbad@bold-river-a1b2c3.api.sylphx.com\n * sylphx://sk_prod_5120bfeb5120bfeb5120bfeb5120bfeb@bold-river-a1b2c3.api.sylphx.com/v1\n * sylphx://pk_dev_abc12345abc12345abc12345abc12345@calm-peak-z9x4d5.sylphx.dev\n *\n * Invariants:\n * - Protocol is always `sylphx:` (no exceptions)\n * - Credential matches `(pk|sk)_(dev|stg|prod|prev)(_{ref})?_{hex}`\n * - Host's first DNS label is the resource slug (validated by slug regex)\n * - `apiBaseUrl` is always HTTPS, with `/v{version}` appended (default `v1`)\n *\n * Parsing uses the WHATWG `URL` constructor — custom regex parsing is banned\n * because it is notoriously brittle (ADR-055 §5.3).\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type ConnectionCredentialType = 'pk' | 'sk'\nexport type ConnectionEnv = 'dev' | 'stg' | 'prod' | 'prev'\n\nexport interface ParsedConnectionUrl {\n\t/** Full credential string, e.g. `pk_prod_f19e...` */\n\treadonly credential: string\n\t/** Credential kind — `pk` (publishable) or `sk` (secret) */\n\treadonly credentialType: ConnectionCredentialType\n\t/** Target environment encoded in the credential */\n\treadonly env: ConnectionEnv\n\t/** First DNS label of the host — the resource slug (e.g. `bold-river-a1b2c3`) */\n\treadonly slug: string\n\t/** Full host including port when present (e.g. `bold-river-a1b2c3.api.sylphx.com`) */\n\treadonly host: string\n\t/** Ready-to-use SDK base URL, always HTTPS (e.g. `https://bold-river-a1b2c3.api.sylphx.com/v1`) */\n\treadonly apiBaseUrl: string\n}\n\nexport interface BuildConnectionUrlInput {\n\t/** Credential — must match the credential format regex */\n\treadonly credential: string\n\t/** Resource slug — validated DNS label */\n\treadonly slug: string\n\t/** SDK API domain suffix; defaults to `api.sylphx.com`. Use `sylphx.dev` for dev. */\n\treadonly domain?: string\n\t/** API version suffix, e.g. `v1`. Defaults to `v1`. Pass empty string to omit. */\n\treadonly version?: string\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\nconst SYLPHX_PROTOCOL = 'sylphx:'\nconst DEFAULT_DOMAIN = 'api.sylphx.com'\nconst DEFAULT_VERSION = 'v1'\n\n/**\n * Credential format — opaque token with type, env, optional project ref, and\n * hex payload. Ref-scoped credentials are emitted by Platform app-env injection;\n * legacy credentials without the ref remain valid for existing deploys.\n */\nexport const CREDENTIAL_REGEX = /^(pk|sk)_(dev|stg|prod|prev)(?:_[a-z0-9]{12})?_[a-f0-9]{32,64}$/\n\n/** Version segment, e.g. `v1`, `v2`, `v10`. */\nconst VERSION_REGEX = /^v[0-9]+$/\n\n/**\n * Slug validation regex — RFC 1035 DNS label.\n * Lowercase letters, numbers, and hyphens; must start and end with alnum.\n * Length 1–63.\n */\nconst SLUG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/\n\n// ============================================================================\n// Errors\n// ============================================================================\n\nexport class InvalidConnectionUrlError extends Error {\n\treadonly code = 'INVALID_CONNECTION_URL' as const\n\n\tconstructor(message: string) {\n\t\tsuper(message)\n\t\tthis.name = 'InvalidConnectionUrlError'\n\t\tObject.setPrototypeOf(this, InvalidConnectionUrlError.prototype)\n\t}\n}\n\n// ============================================================================\n// Internal helpers\n// ============================================================================\n\nfunction fail(reason: string): never {\n\tthrow new InvalidConnectionUrlError(`Invalid Sylphx connection URL: ${reason}`)\n}\n\nfunction parseCredential(raw: string): {\n\tcredentialType: ConnectionCredentialType\n\tenv: ConnectionEnv\n} {\n\tconst match = CREDENTIAL_REGEX.exec(raw)\n\tif (!match) {\n\t\tfail(`credential must match (pk|sk)_(dev|stg|prod|prev)(_{ref})?_{hex}, got \"${raw}\"`)\n\t}\n\treturn {\n\t\tcredentialType: match[1] as ConnectionCredentialType,\n\t\tenv: match[2] as ConnectionEnv,\n\t}\n}\n\nfunction validateSlug(candidate: string): string {\n\tif (!candidate || candidate.length > 63 || !SLUG_REGEX.test(candidate)) {\n\t\tfail(`slug \"${candidate}\" is not a valid DNS label (lowercase alnum + hyphens, 1-63 chars)`)\n\t}\n\treturn candidate\n}\n\nfunction validateDomain(domain: string): string {\n\tif (!domain || domain.includes('/') || domain.includes('@') || domain.includes(' ')) {\n\t\tfail(`domain \"${domain}\" is not a valid hostname suffix`)\n\t}\n\t// Reject schemes — domain is just a hostname suffix\n\tif (domain.includes('://')) {\n\t\tfail(`domain \"${domain}\" must not contain a scheme`)\n\t}\n\treturn domain.toLowerCase()\n}\n\nfunction normaliseVersion(version: string | undefined): string {\n\tif (version === undefined) return DEFAULT_VERSION\n\tif (version === '') return ''\n\tif (!VERSION_REGEX.test(version)) {\n\t\tfail(`version \"${version}\" must match /^v[0-9]+$/`)\n\t}\n\treturn version\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Build a canonical Sylphx connection URL.\n *\n * Throws `InvalidConnectionUrlError` if any component is malformed.\n */\nexport function buildConnectionUrl(input: BuildConnectionUrlInput): string {\n\tconst { credential, slug, domain = DEFAULT_DOMAIN, version = DEFAULT_VERSION } = input\n\n\tparseCredential(credential)\n\tconst safeSlug = validateSlug(slug)\n\tconst safeDomain = validateDomain(domain)\n\tconst safeVersion = normaliseVersion(version)\n\n\tconst host = `${safeSlug}.${safeDomain}`\n\tconst pathSuffix = safeVersion ? `/${safeVersion}` : ''\n\treturn `${SYLPHX_PROTOCOL}//${credential}@${host}${pathSuffix}`\n}\n\n/**\n * Parse a Sylphx connection URL into its structured components.\n *\n * Throws `InvalidConnectionUrlError` on any structural problem.\n */\nexport function parseConnectionUrl(url: string): ParsedConnectionUrl {\n\tif (typeof url !== 'string' || url.length === 0) {\n\t\tfail('url must be a non-empty string')\n\t}\n\n\tlet parsed: URL\n\ttry {\n\t\tparsed = new URL(url)\n\t} catch {\n\t\tfail(`not a valid URL: \"${url}\"`)\n\t}\n\n\tif (parsed.protocol !== SYLPHX_PROTOCOL) {\n\t\tfail(`protocol must be \"sylphx:\", got \"${parsed.protocol}\"`)\n\t}\n\n\t// URL parses `sylphx://cred@host/path` but places `cred` in `username` only\n\t// when the authority is parsed. For non-special schemes, browsers/Node parse\n\t// the authority uniformly — we defensively read both `username` and `host`.\n\tconst credential = decodeURIComponent(parsed.username)\n\tif (!credential) {\n\t\tfail('missing credential (expected `sylphx://<credential>@<host>`)')\n\t}\n\tif (parsed.password) {\n\t\tfail('connection URL must not contain a password component')\n\t}\n\n\tconst { credentialType, env } = parseCredential(credential)\n\n\tconst host = parsed.host\n\tif (!host) {\n\t\tfail('missing host')\n\t}\n\n\t// Extract slug from the first DNS label\n\tconst hostname = parsed.hostname\n\tconst firstDot = hostname.indexOf('.')\n\tif (firstDot <= 0) {\n\t\tfail(`host \"${hostname}\" must contain at least one dot (slug.domain)`)\n\t}\n\tconst slugCandidate = hostname.slice(0, firstDot)\n\tconst domainSuffix = hostname.slice(firstDot + 1)\n\tif (!domainSuffix) {\n\t\tfail(`host \"${hostname}\" has empty domain suffix`)\n\t}\n\tconst slug = validateSlug(slugCandidate)\n\n\t// Path is either empty, `/`, or `/v{N}`\n\tconst rawPath = parsed.pathname.replace(/^\\/+/, '').replace(/\\/+$/, '')\n\tlet version = DEFAULT_VERSION\n\tif (rawPath !== '') {\n\t\tif (!VERSION_REGEX.test(rawPath)) {\n\t\t\tfail(`path \"${parsed.pathname}\" must be empty or match /v{N}`)\n\t\t}\n\t\tversion = rawPath\n\t}\n\n\tif (parsed.search) {\n\t\tfail('connection URL must not contain a query string')\n\t}\n\tif (parsed.hash) {\n\t\tfail('connection URL must not contain a fragment')\n\t}\n\n\tconst apiBaseUrl = `https://${host}/${version}`\n\n\treturn {\n\t\tcredential,\n\t\tcredentialType,\n\t\tenv,\n\t\tslug,\n\t\thost,\n\t\tapiBaseUrl,\n\t}\n}\n","/**\n * SDK Constants — Single Source of Truth\n *\n * Shared constants used across the SDK. Centralizing these\n * prevents magic number duplication and makes changes easier.\n *\n * IMPORTANT: All time-based constants should be used consistently\n * across the SDK. Never hardcode magic numbers like 30000, 5 * 60 * 1000, etc.\n */\n\n// =============================================================================\n// API Configuration\n// =============================================================================\n\n/**\n * Canonical environment variable name for the client connection URL.\n *\n * Format: sylphx://pk_prod_{hex}@tenant-slug.api.sylphx.com\n * Browser-safe (publishable key only).\n */\nexport const ENV_URL = 'SYLPHX_URL'\n\n/**\n * Canonical environment variable name for the Next.js public connection URL.\n *\n * Same format as ENV_URL, browser-safe.\n */\nexport const ENV_PUBLIC_URL = 'NEXT_PUBLIC_SYLPHX_URL'\n\n/**\n * Canonical environment variable name for the server secret connection URL.\n *\n * Format: sylphx://sk_prod_{hex}@tenant-slug.api.sylphx.com\n * Server-side only — never expose to client.\n */\nexport const ENV_SECRET_URL = 'SYLPHX_SECRET_URL'\n\n/**\n * Resolve the secret connection URL from environment variables.\n */\nexport function resolveSecretUrl(explicit?: string): string | undefined {\n\treturn explicit || process.env[ENV_SECRET_URL]\n}\n\n/**\n * SDK API path for the per-project subdomain-based SDK server.\n *\n * The full base URL is built as: https://{tenant-slug}.api.sylphx.com/v1\n */\nexport const SDK_API_PATH = `/v1`\nexport const SDK_API_VERSION = 'v1'\n\n/**\n * Default SDK API host.\n *\n * Management API: https://api.sylphx.com/v1/*\n * BaaS/SDK API: https://{tenant-slug}.api.sylphx.com/v1/*\n */\nexport const DEFAULT_SDK_API_HOST = 'api.sylphx.com'\nexport const DEFAULT_PLATFORM_URL = 'https://sylphx.com'\n\n/**\n * Default auth route prefix\n *\n * Used for OAuth callbacks and signout routes.\n * Must match the middleware's authPrefix config.\n */\nexport const DEFAULT_AUTH_PREFIX = '/auth'\n\n/**\n * SDK package version\n *\n * Sent in X-SDK-Version header for debugging and analytics.\n * Update this when releasing new SDK versions.\n */\nexport const SDK_VERSION = '0.5.0'\n\n/**\n * SDK platform identifier\n *\n * Sent in X-SDK-Platform header to identify the runtime environment.\n */\ntype SdkRuntimeGlobal = typeof globalThis & {\n\treadonly EdgeRuntime?: string\n}\n\nfunction detectSdkPlatform(): 'browser' | 'edge' | 'node' {\n\tif (typeof window !== 'undefined') return 'browser'\n\tconst runtimeGlobal = globalThis as SdkRuntimeGlobal\n\tif (typeof runtimeGlobal.EdgeRuntime !== 'undefined') return 'edge'\n\treturn 'node'\n}\n\nexport const SDK_PLATFORM = detectSdkPlatform()\n\n// =============================================================================\n// Timeouts & Durations\n// =============================================================================\n\n/** Default request timeout in milliseconds (30 seconds) */\nexport const DEFAULT_TIMEOUT_MS = 30_000\n\n/**\n * Sandbox create waits for the Runtime API to provision runtime resources and for\n * the exec-server readiness probe to pass. The server-side readiness budget is\n * 120s; this client budget adds transport margin without changing the default\n * timeout for ordinary API calls.\n */\nexport const SANDBOX_CREATE_TIMEOUT_MS = 150_000\n\n/**\n * Token expiry buffer in milliseconds (30 seconds)\n *\n * Refresh tokens this many milliseconds BEFORE they expire\n * to account for network latency and clock skew.\n */\nexport const TOKEN_EXPIRY_BUFFER_MS = 30_000\n\n/**\n * Session token lifetime in seconds (5 minutes)\n *\n * Matches Clerk's short-lived access token pattern.\n * Used for cookie maxAge and React Query staleTime.\n */\nexport const SESSION_TOKEN_LIFETIME_SECONDS = 5 * 60\n\n/** Session token lifetime in milliseconds (for React Query staleTime) */\nexport const SESSION_TOKEN_LIFETIME_MS = SESSION_TOKEN_LIFETIME_SECONDS * 1000\n\n/**\n * Refresh token lifetime in seconds (30 days)\n *\n * Long-lived token for silent refresh.\n */\nexport const REFRESH_TOKEN_LIFETIME_SECONDS = 30 * 24 * 60 * 60\n\n// =============================================================================\n// Feature Flags Cache\n// =============================================================================\n\n/**\n * Feature flags cache TTL in milliseconds (5 minutes)\n *\n * How long to cache flags before fetching fresh values.\n * Matches LaunchDarkly's default streaming connection behavior.\n */\nexport const FLAGS_CACHE_TTL_MS = 5 * 60 * 1000\n\n/**\n * Feature flags stale-while-revalidate window in milliseconds (1 minute)\n *\n * Allow serving stale flags while fetching fresh values.\n */\nexport const FLAGS_STALE_WHILE_REVALIDATE_MS = 60 * 1000\n\n// =============================================================================\n// Retry & Backoff\n// =============================================================================\n\n/** Maximum retry delay for exponential backoff (30 seconds) */\nexport const MAX_RETRY_DELAY_MS = 30_000\n\n/** Base retry delay for exponential backoff (1 second) */\nexport const BASE_RETRY_DELAY_MS = 1_000\n\n/** Maximum number of retries for network requests */\nexport const MAX_RETRIES = 3\n\n// =============================================================================\n// Analytics\n// =============================================================================\n\n/**\n * Analytics session timeout in milliseconds (30 minutes)\n *\n * After this much inactivity, a new session is started.\n */\nexport const ANALYTICS_SESSION_TIMEOUT_MS = 30 * 60 * 1000\n\n// =============================================================================\n// Webhooks\n// =============================================================================\n\n/**\n * Maximum age for webhook signature validation (5 minutes)\n *\n * Reject webhooks with timestamps older than this.\n */\nexport const WEBHOOK_MAX_AGE_MS = 5 * 60 * 1000\n\n/**\n * Clock skew allowance for webhook validation (30 seconds)\n *\n * Allow timestamps this far in the future.\n */\nexport const WEBHOOK_CLOCK_SKEW_MS = 30 * 1000\n\n// =============================================================================\n// PKCE (OAuth)\n// =============================================================================\n\n/**\n * PKCE code verifier TTL in milliseconds (10 minutes)\n *\n * How long the code verifier is stored during OAuth flow.\n */\nexport const PKCE_CODE_TTL_MS = 10 * 60 * 1000\n\n// =============================================================================\n// Jobs\n// =============================================================================\n\n/**\n * Job dead-letter queue retention in milliseconds (7 days)\n */\nexport const JOBS_DLQ_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000\n\n// =============================================================================\n// Session Replay\n// =============================================================================\n\n/**\n * Maximum session replay recording duration in milliseconds (60 minutes)\n */\nexport const SESSION_REPLAY_MAX_DURATION_MS = 60 * 60 * 1000\n\n/**\n * Session replay upload interval in milliseconds (5 seconds)\n */\nexport const SESSION_REPLAY_UPLOAD_INTERVAL_MS = 5_000\n\n/**\n * Session replay scroll event throttle interval (150 ms)\n */\nexport const SESSION_REPLAY_SCROLL_THROTTLE_MS = 150\n\n/**\n * Session replay media time update throttle interval (800 ms)\n */\nexport const SESSION_REPLAY_MEDIA_THROTTLE_MS = 800\n\n/**\n * Session replay rage click detection window (1 second)\n */\nexport const SESSION_REPLAY_RAGE_CLICK_WINDOW_MS = 1_000\n\n/**\n * Session replay dead click detection timeout (500 ms)\n */\nexport const SESSION_REPLAY_DEAD_CLICK_TIMEOUT_MS = 500\n\n/**\n * Session replay scroll heat detection window (2 seconds)\n */\nexport const SESSION_REPLAY_SCROLL_HEAT_WINDOW_MS = 2_000\n\n/**\n * Session replay status check interval (5 seconds)\n */\nexport const SESSION_REPLAY_STATUS_CHECK_MS = 5_000\n\n// =============================================================================\n// Analytics (Extended)\n// =============================================================================\n\n/**\n * Analytics event flush interval in milliseconds (5 seconds)\n */\nexport const ANALYTICS_FLUSH_INTERVAL_MS = 5_000\n\n/**\n * Analytics maximum text length for autocapture (100 characters)\n */\nexport const ANALYTICS_MAX_TEXT_LENGTH = 100\n\n/**\n * Analytics flush timeout in milliseconds (1 second)\n */\nexport const ANALYTICS_FLUSH_TIMEOUT_MS = 1_000\n\n/**\n * Analytics interval check in milliseconds (1 second)\n */\nexport const ANALYTICS_INTERVAL_CHECK_MS = 1_000\n\n/**\n * Analytics retry base delay in milliseconds (1 second)\n * Exponential backoff: delay = base * 2^retries (with jitter)\n */\nexport const ANALYTICS_RETRY_BASE_DELAY_MS = 1_000\n\n/**\n * Analytics retry max delay in milliseconds (30 seconds)\n */\nexport const ANALYTICS_RETRY_MAX_DELAY_MS = 30_000\n\n/**\n * Analytics retry jitter factor (±20%)\n * Prevents thundering herd when multiple clients retry simultaneously\n */\nexport const ANALYTICS_RETRY_JITTER = 0.2\n\n/**\n * Analytics maximum retries before dropping event (Segment pattern: 10)\n */\nexport const ANALYTICS_MAX_RETRIES = 10\n\n// =============================================================================\n// Feature Flags (Extended)\n// =============================================================================\n\n/**\n * Feature flags exposure deduplication window (1 hour)\n *\n * Prevents duplicate exposure events for A/B tests within this window.\n */\nexport const FLAGS_EXPOSURE_DEDUPE_WINDOW_MS = 60 * 60 * 1000\n\n/**\n * Flag stream initial reconnection delay (1 second)\n */\nexport const FLAGS_STREAM_INITIAL_RECONNECT_MS = 1_000\n\n/**\n * Flag stream maximum reconnection delay (30 seconds)\n */\nexport const FLAGS_STREAM_MAX_RECONNECT_MS = 30_000\n\n/**\n * Flag stream heartbeat timeout (45 seconds)\n */\nexport const FLAGS_STREAM_HEARTBEAT_TIMEOUT_MS = 45_000\n\n/**\n * Flag HTTP polling interval fallback (60 seconds)\n */\nexport const FLAGS_HTTP_POLLING_INTERVAL_MS = 60_000\n\n// =============================================================================\n// Jobs (Extended)\n// =============================================================================\n\n/**\n * Default retry delay sequence for exponential backoff (ms)\n */\nexport const DEFAULT_RETRY_DELAYS_MS = [1_000, 5_000, 15_000, 30_000, 60_000] as const\n\n/**\n * Default job timeout in milliseconds (60 seconds)\n */\nexport const JOB_DEFAULT_TIMEOUT_MS = 60_000\n\n/**\n * Default job status polling interval (2 seconds)\n */\nexport const JOB_POLL_INTERVAL_MS = 2_000\n\n// =============================================================================\n// Storage Keys & Prefixes\n// =============================================================================\n\n/**\n * Storage key prefix for SDK data\n */\nexport const STORAGE_KEY_PREFIX = 'sylphx_'\n\n/**\n * localStorage key for cached feature flags\n */\nexport const FLAGS_CACHE_KEY = 'sylphx_feature_flags'\n\n/**\n * localStorage key for feature flags cache timestamp\n */\nexport const FLAGS_CACHE_TIMESTAMP_KEY = 'sylphx_feature_flags_ts'\n\n/**\n * localStorage key for feature flags overrides\n */\nexport const FLAGS_OVERRIDES_KEY = 'sylphx_feature_flags_overrides'\n\n/**\n * localStorage key for active organization\n */\nexport const ORG_STORAGE_KEY = 'sylphx_active_org'\n\n/**\n * BroadcastChannel name for cross-tab org sync\n */\nexport const ORG_BROADCAST_CHANNEL = 'sylphx_org_sync'\n\n/**\n * Storage prefix for PKCE verifiers\n */\nexport const PKCE_STORAGE_PREFIX = 'sylphx_pkce_'\n\n/**\n * Test key for checking storage availability\n */\nexport const STORAGE_TEST_KEY = '__sylphx_test__'\n\n/**\n * Cookie/storage name for analytics sessions\n */\nexport const ANALYTICS_SESSION_KEY = 'sylphx_session'\n\n/**\n * Default storage key for flags persistence\n */\nexport const FLAGS_STORAGE_KEY = 'sylphx_flags'\n\n// =============================================================================\n// Click ID & Attribution\n// =============================================================================\n\n/**\n * Click ID attribution window in milliseconds (90 days)\n *\n * How long click IDs are stored for conversion attribution.\n */\nexport const CLICK_ID_EXPIRY_MS = 90 * 24 * 60 * 60 * 1000\n\n// =============================================================================\n// React Query Stale Times\n// =============================================================================\n\n/**\n * React Query staleTime for frequently-changing data (1 minute)\n *\n * Use for: real-time metrics, live feeds, active sessions\n */\nexport const STALE_TIME_FREQUENT_MS = 60 * 1_000\n\n/**\n * React Query staleTime for moderately-changing data (2 minutes)\n *\n * Use for: subscriptions, user profiles, preferences\n */\nexport const STALE_TIME_MODERATE_MS = 2 * 60 * 1_000\n\n/**\n * React Query staleTime for stable/config data (5 minutes)\n *\n * Use for: plans, feature flags, app config\n */\nexport const STALE_TIME_STABLE_MS = 5 * 60 * 1_000\n\n/**\n * React Query staleTime for webhook stats (30 seconds)\n */\nexport const STALE_TIME_STATS_MS = 30 * 1_000\n\n// =============================================================================\n// UI Component Timeouts\n// =============================================================================\n\n/**\n * Copy-to-clipboard feedback display duration (2 seconds)\n */\nexport const UI_COPY_FEEDBACK_MS = 2_000\n\n/**\n * Form success message display duration (3 seconds)\n */\nexport const UI_FORM_SUCCESS_MS = 3_000\n\n/**\n * General notification display duration (5 seconds)\n */\nexport const UI_NOTIFICATION_MS = 5_000\n\n/**\n * Prompt auto-show delay (3 seconds)\n */\nexport const UI_PROMPT_DELAY_MS = 3_000\n\n/**\n * Redirect delay after action (3 seconds)\n */\nexport const UI_REDIRECT_DELAY_MS = 3_000\n\n/**\n * Animation out duration (200 ms)\n */\nexport const UI_ANIMATION_OUT_MS = 200\n\n/**\n * Animation in duration (300 ms)\n */\nexport const UI_ANIMATION_IN_MS = 300\n\n// =============================================================================\n// Email & Verification\n// =============================================================================\n\n/**\n * Email resend cooldown tick interval (1 second)\n */\nexport const EMAIL_RESEND_COOLDOWN_TICK_MS = 1_000\n\n/**\n * New user detection threshold (1 minute)\n *\n * Users created within this window are considered \"new\" for signup tracking.\n */\nexport const NEW_USER_THRESHOLD_MS = 60 * 1_000\n\n// =============================================================================\n// Web Vitals Thresholds\n// =============================================================================\n\n/**\n * FCP (First Contentful Paint) \"good\" threshold (1800 ms)\n */\nexport const WEB_VITALS_FCP_GOOD_MS = 1_800\n\n/**\n * FCP (First Contentful Paint) \"poor\" threshold (3000 ms)\n */\nexport const WEB_VITALS_FCP_POOR_MS = 3_000\n\n// =============================================================================\n// Storage Sizes\n// =============================================================================\n\n/**\n * Multipart upload threshold (5 MB)\n *\n * Files larger than this use multipart upload for better reliability.\n */\nexport const STORAGE_MULTIPART_THRESHOLD_BYTES = 5 * 1024 * 1024\n\n/**\n * Default max file size for uploads (5 MB)\n */\nexport const STORAGE_DEFAULT_MAX_SIZE_BYTES = 5 * 1024 * 1024\n\n/**\n * Avatar max file size (2 MB)\n */\nexport const STORAGE_AVATAR_MAX_SIZE_BYTES = 2 * 1024 * 1024\n\n/**\n * Large file max size for file uploads (10 MB)\n */\nexport const STORAGE_LARGE_MAX_SIZE_BYTES = 10 * 1024 * 1024\n\n// =============================================================================\n// Cache TTLs\n// =============================================================================\n\n/**\n * JWK cache TTL (1 hour)\n */\nexport const JWK_CACHE_TTL_MS = 60 * 60 * 1000\n\n// =============================================================================\n// Analytics Event Tracking\n// =============================================================================\n\n/**\n * Max tracked event IDs to keep in memory\n */\nexport const ANALYTICS_MAX_TRACKED_EVENT_IDS = 1000\n\n/**\n * Number of event IDs to keep after cleanup\n */\nexport const ANALYTICS_TRACKED_IDS_KEEP = 500\n\n/**\n * Analytics queue limit before force flush\n */\nexport const ANALYTICS_QUEUE_LIMIT = 100\n\n// =============================================================================\n// Session Replay (Extended)\n// =============================================================================\n\n/**\n * Session replay check interval (1 second)\n */\nexport const SESSION_REPLAY_CHECK_INTERVAL_MS = 1_000\n\n/**\n * Success feedback delay for invite/account actions (1.5 seconds)\n */\nexport const UI_SUCCESS_REDIRECT_MS = 1_500\n\n// =============================================================================\n// String Truncation Limits\n// =============================================================================\n\n/**\n * Max message length for logging (1000 chars)\n */\nexport const LOG_MESSAGE_MAX_LENGTH = 1_000\n\n/**\n * Max DOM snapshot length for debugging (1000 chars)\n */\nexport const DOM_SNAPSHOT_MAX_LENGTH = 1_000\n\n/**\n * Max stack trace length for error tracking (500 chars)\n */\nexport const STACK_TRACE_MAX_LENGTH = 500\n\n/**\n * Google Consent Mode wait for update timeout (500 ms)\n */\nexport const CONSENT_WAIT_FOR_UPDATE_MS = 500\n\n// =============================================================================\n// Time Unit Conversions\n// =============================================================================\n\n/** Milliseconds per minute (60,000) */\nexport const MS_PER_MINUTE = 60_000\n\n/** Milliseconds per hour (3,600,000) */\nexport const MS_PER_HOUR = 3_600_000\n\n/** Milliseconds per day (86,400,000) */\nexport const MS_PER_DAY = 86_400_000\n\n/** Seconds per minute (60) */\nexport const SECONDS_PER_MINUTE = 60\n\n/** Seconds per hour (3,600) */\nexport const SECONDS_PER_HOUR = 3_600\n\n// =============================================================================\n// Z-Index Values\n// =============================================================================\n\n/** Z-index for modal overlays (9999) */\nexport const Z_INDEX_OVERLAY = 9999\n\n/** Z-index for critical overlays like feature gates (99999) */\nexport const Z_INDEX_CRITICAL_OVERLAY = 99999\n\n// =============================================================================\n// API Key Expiry (seconds)\n// =============================================================================\n\n/** API key expiry: 1 day (86,400 seconds) */\nexport const API_KEY_EXPIRY_1_DAY = 86_400\n\n/** API key expiry: 7 days (604,800 seconds) */\nexport const API_KEY_EXPIRY_7_DAYS = 604_800\n\n/** API key expiry: 30 days (2,592,000 seconds) */\nexport const API_KEY_EXPIRY_30_DAYS = 2_592_000\n\n/** API key expiry: 90 days (7,776,000 seconds) */\nexport const API_KEY_EXPIRY_90_DAYS = 7_776_000\n\n/** API key expiry: 1 year (31,536,000 seconds) */\nexport const API_KEY_EXPIRY_1_YEAR = 31_536_000\n\n// =============================================================================\n// Web Vitals Thresholds (Google standards)\n// =============================================================================\n\n/** LCP (Largest Contentful Paint) \"good\" threshold (2500 ms) */\nexport const WEB_VITALS_LCP_GOOD_MS = 2_500\n\n/** LCP (Largest Contentful Paint) \"poor\" threshold (4000 ms) */\nexport const WEB_VITALS_LCP_POOR_MS = 4_000\n\n/** INP (Interaction to Next Paint) \"good\" threshold (200 ms) */\nexport const WEB_VITALS_INP_GOOD_MS = 200\n\n/** INP (Interaction to Next Paint) \"poor\" threshold (500 ms) */\nexport const WEB_VITALS_INP_POOR_MS = 500\n\n/** TTFB (Time to First Byte) \"good\" threshold (800 ms) */\nexport const WEB_VITALS_TTFB_GOOD_MS = 800\n\n/** TTFB (Time to First Byte) \"poor\" threshold (1800 ms) */\nexport const WEB_VITALS_TTFB_POOR_MS = 1_800\n\n// =============================================================================\n// Security\n// =============================================================================\n\n/** Minimum password length (NIST SP 800-63B recommends 12+) */\nexport const MIN_PASSWORD_LENGTH = 12\n\n// =============================================================================\n// AI\n// =============================================================================\n\n/** Default context window for AI models (4096 tokens) */\nexport const DEFAULT_CONTEXT_WINDOW = 4_096\n\n// =============================================================================\n// Circuit Breaker (AWS/Resilience4j pattern)\n// =============================================================================\n\n/**\n * Circuit breaker failure threshold\n *\n * Number of failures in the window before circuit opens.\n */\nexport const CIRCUIT_BREAKER_FAILURE_THRESHOLD = 5\n\n/**\n * Circuit breaker failure window in milliseconds (10 seconds)\n *\n * Time window for counting failures.\n */\nexport const CIRCUIT_BREAKER_WINDOW_MS = 10_000\n\n/**\n * Circuit breaker open duration in milliseconds (30 seconds)\n *\n * How long the circuit stays open before allowing a test request.\n */\nexport const CIRCUIT_BREAKER_OPEN_DURATION_MS = 30_000\n\n// =============================================================================\n// ETag Cache (HTTP conditional requests)\n// =============================================================================\n\n/**\n * Maximum ETag cache entries\n *\n * LRU eviction when exceeded.\n */\nexport const ETAG_CACHE_MAX_ENTRIES = 100\n\n/**\n * ETag cache TTL in milliseconds (5 minutes)\n *\n * How long cached responses are valid.\n */\nexport const ETAG_CACHE_TTL_MS = 5 * 60 * 1000\n","/**\n * Sylphx SDK Error Classes\n *\n * Typed error classes for better error handling and debugging.\n * Compatible with tRPC error codes and provides rich context.\n *\n * @example\n * ```typescript\n * import { SylphxError, isRetryableError, getErrorMessage } from '@sylphx/sdk'\n *\n * try {\n * await sylphx.auth.login.mutate({ email, password })\n * } catch (error) {\n * if (error instanceof SylphxError) {\n * console.log(error.code) // 'UNAUTHORIZED'\n * console.log(error.isRetryable) // false\n * }\n * if (isRetryableError(error)) {\n * // Safe to retry\n * }\n * }\n * ```\n */\n\nimport { BASE_RETRY_DELAY_MS, DEFAULT_TIMEOUT_MS, MAX_RETRY_DELAY_MS } from './constants'\n\n// ============================================================================\n// Error Codes (aligned with tRPC and HTTP semantics)\n// ============================================================================\n\nexport type SylphxErrorCode =\n\t// Client errors (4xx)\n\t| 'BAD_REQUEST' // 400 - Invalid input\n\t| 'UNAUTHORIZED' // 401 - Not authenticated\n\t| 'FORBIDDEN' // 403 - Not authorized\n\t| 'NOT_FOUND' // 404 - Resource not found\n\t| 'CONFLICT' // 409 - Resource conflict (e.g., duplicate)\n\t| 'PAYLOAD_TOO_LARGE' // 413 - Request too large\n\t| 'UNPROCESSABLE_ENTITY' // 422 - Validation failed\n\t| 'TOO_MANY_REQUESTS' // 429 - Rate limited\n\t| 'QUOTA_EXCEEDED' // 402/429 - Quota/plan limit exceeded\n\t// Server errors (5xx)\n\t| 'INTERNAL_SERVER_ERROR' // 500 - Server error\n\t| 'NOT_IMPLEMENTED' // 501 - Feature not available\n\t| 'BAD_GATEWAY' // 502 - Upstream error\n\t| 'SERVICE_UNAVAILABLE' // 503 - Temporarily unavailable\n\t| 'GATEWAY_TIMEOUT' // 504 - Upstream timeout\n\t// Network/Client errors\n\t| 'NETWORK_ERROR' // Network failure\n\t| 'TIMEOUT' // Request timeout\n\t| 'ABORTED' // Request aborted\n\t// SDK-specific\n\t| 'PARSE_ERROR' // JSON/response parse error\n\t| 'UNKNOWN' // Unknown error\n\n/**\n * Simplified semantic error codes (DX-friendly aliases).\n * Maps to the more granular SylphxErrorCode internally.\n *\n * @example\n * ```ts\n * if (SylphxError.isRateLimited(err)) {\n * console.log(`Retry after ${err.retryAfter}s`)\n * }\n * ```\n */\nexport type ErrorCode =\n\t| 'UNAUTHORIZED'\n\t| 'FORBIDDEN'\n\t| 'NOT_FOUND'\n\t| 'RATE_LIMITED'\n\t| 'QUOTA_EXCEEDED'\n\t| 'VALIDATION_ERROR'\n\t| 'NETWORK_ERROR'\n\t| 'UPSTREAM_ERROR'\n\t| 'INTERNAL_ERROR'\n\n/**\n * HTTP status code mapping for error codes\n */\nexport const ERROR_CODE_STATUS: Record<SylphxErrorCode, number> = {\n\tBAD_REQUEST: 400,\n\tUNAUTHORIZED: 401,\n\tFORBIDDEN: 403,\n\tNOT_FOUND: 404,\n\tCONFLICT: 409,\n\tPAYLOAD_TOO_LARGE: 413,\n\tUNPROCESSABLE_ENTITY: 422,\n\tTOO_MANY_REQUESTS: 429,\n\tQUOTA_EXCEEDED: 402,\n\tINTERNAL_SERVER_ERROR: 500,\n\tNOT_IMPLEMENTED: 501,\n\tBAD_GATEWAY: 502,\n\tSERVICE_UNAVAILABLE: 503,\n\tGATEWAY_TIMEOUT: 504,\n\tNETWORK_ERROR: 0,\n\tTIMEOUT: 0,\n\tABORTED: 0,\n\tPARSE_ERROR: 0,\n\tUNKNOWN: 0,\n}\n\n/**\n * Retryable error codes (safe to retry automatically)\n */\nexport const RETRYABLE_CODES: Set<SylphxErrorCode> = new Set([\n\t'NETWORK_ERROR',\n\t'TIMEOUT',\n\t'BAD_GATEWAY',\n\t'SERVICE_UNAVAILABLE',\n\t'GATEWAY_TIMEOUT',\n\t'TOO_MANY_REQUESTS', // With backoff\n\t'INTERNAL_SERVER_ERROR', // Sometimes transient\n])\n\n// ============================================================================\n// Error Classes\n// ============================================================================\n\nexport interface SylphxErrorOptions {\n\t/** Error code for programmatic handling */\n\tcode?: SylphxErrorCode\n\t/** HTTP status code (inferred from code if not provided) */\n\tstatus?: number\n\t/** Additional context data */\n\tdata?: Record<string, unknown>\n\t/** Original error that caused this */\n\tcause?: Error\n\t/** Retry-After header value (seconds) for rate limiting */\n\tretryAfter?: number\n}\n\n/**\n * Base error class for all Sylphx SDK errors\n *\n * @example\n * ```typescript\n * throw new SylphxError('Invalid email format', {\n * code: 'BAD_REQUEST',\n * data: { field: 'email' }\n * })\n * ```\n */\nexport class SylphxError extends Error {\n\t/** Error code for programmatic handling */\n\treadonly code: SylphxErrorCode\n\n\t/** HTTP status code */\n\treadonly status: number\n\n\t/** Additional context data */\n\treadonly data?: Record<string, unknown>\n\n\t/** Whether this error is safe to retry */\n\treadonly isRetryable: boolean\n\n\t/** Retry-After value in seconds (for rate limiting) */\n\treadonly retryAfter?: number\n\n\t/** Timestamp when error occurred */\n\treadonly timestamp: Date\n\n\tconstructor(message: string, options: SylphxErrorOptions = {}) {\n\t\tsuper(message, { cause: options.cause })\n\t\tthis.name = 'SylphxError'\n\t\tthis.code = options.code ?? 'UNKNOWN'\n\t\tthis.status = options.status ?? ERROR_CODE_STATUS[this.code]\n\t\tthis.data = options.data\n\t\tthis.isRetryable = RETRYABLE_CODES.has(this.code)\n\t\tthis.retryAfter = options.retryAfter\n\t\tthis.timestamp = new Date()\n\n\t\t// Maintain proper stack trace in V8\n\t\tif (Error.captureStackTrace) {\n\t\t\tError.captureStackTrace(this, SylphxError)\n\t\t}\n\t}\n\n\t// ============================================================================\n\t// Static Type Guards (DX helpers)\n\t// ============================================================================\n\n\t/**\n\t * Check if error is a rate-limit error (429 Too Many Requests)\n\t */\n\tstatic isRateLimited(err: unknown): err is SylphxError & { code: 'TOO_MANY_REQUESTS' } {\n\t\treturn err instanceof SylphxError && err.code === 'TOO_MANY_REQUESTS'\n\t}\n\n\t/**\n\t * Check if error is an account lockout error (too many failed login attempts).\n\t * When true, `error.data?.lockoutUntil` contains the ISO 8601 timestamp when the lockout expires.\n\t */\n\tstatic isAccountLocked(\n\t\terr: unknown,\n\t): err is SylphxError & { code: 'TOO_MANY_REQUESTS'; data: { lockoutUntil: string | null } } {\n\t\treturn (\n\t\t\terr instanceof SylphxError &&\n\t\t\terr.code === 'TOO_MANY_REQUESTS' &&\n\t\t\terr.data?.code === 'ACCOUNT_LOCKED'\n\t\t)\n\t}\n\n\t/**\n\t * Check if error is a quota exceeded error (plan limit reached)\n\t */\n\tstatic isQuotaExceeded(err: unknown): err is SylphxError & { code: 'QUOTA_EXCEEDED' } {\n\t\treturn err instanceof SylphxError && err.code === 'QUOTA_EXCEEDED'\n\t}\n\n\t/**\n\t * Check if error is an authentication error (401 Unauthorized)\n\t */\n\tstatic isUnauthorized(err: unknown): err is SylphxError & { code: 'UNAUTHORIZED' } {\n\t\treturn err instanceof SylphxError && err.code === 'UNAUTHORIZED'\n\t}\n\n\t/**\n\t * Check if error is a not-found error (404 Not Found)\n\t */\n\tstatic isNotFound(err: unknown): err is SylphxError & { code: 'NOT_FOUND' } {\n\t\treturn err instanceof SylphxError && err.code === 'NOT_FOUND'\n\t}\n\n\t/**\n\t * Check if error is an authorization error (403 Forbidden)\n\t */\n\tstatic isForbidden(err: unknown): err is SylphxError & { code: 'FORBIDDEN' } {\n\t\treturn err instanceof SylphxError && err.code === 'FORBIDDEN'\n\t}\n\n\t/**\n\t * Check if error is a validation error (422 Unprocessable Entity)\n\t */\n\tstatic isValidationError(err: unknown): err is SylphxError & { code: 'UNPROCESSABLE_ENTITY' } {\n\t\treturn err instanceof SylphxError && err.code === 'UNPROCESSABLE_ENTITY'\n\t}\n\n\t/**\n\t * Check if error is a network error (no response received)\n\t */\n\tstatic isNetworkError(err: unknown): err is SylphxError & { code: 'NETWORK_ERROR' } {\n\t\treturn err instanceof SylphxError && err.code === 'NETWORK_ERROR'\n\t}\n\n\t/**\n\t * Check if error is an upstream/gateway error (502/504)\n\t */\n\tstatic isUpstreamError(err: unknown): err is SylphxError {\n\t\treturn (\n\t\t\terr instanceof SylphxError &&\n\t\t\t(err.code === 'BAD_GATEWAY' ||\n\t\t\t\terr.code === 'GATEWAY_TIMEOUT' ||\n\t\t\t\terr.code === 'SERVICE_UNAVAILABLE')\n\t\t)\n\t}\n\n\t/**\n\t * Convert to JSON-serializable object\n\t */\n\ttoJSON(): Record<string, unknown> {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tcode: this.code,\n\t\t\tstatus: this.status,\n\t\t\tdata: this.data,\n\t\t\tisRetryable: this.isRetryable,\n\t\t\tretryAfter: this.retryAfter,\n\t\t\ttimestamp: this.timestamp.toISOString(),\n\t\t}\n\t}\n}\n\n/**\n * Network-related errors (no response received)\n */\nexport class NetworkError extends SylphxError {\n\tconstructor(message = 'Network request failed', options?: Omit<SylphxErrorOptions, 'code'>) {\n\t\tsuper(message, { ...options, code: 'NETWORK_ERROR' })\n\t\tthis.name = 'NetworkError'\n\t}\n}\n\n/**\n * Request timeout errors\n */\nexport class TimeoutError extends SylphxError {\n\t/** Timeout duration in milliseconds */\n\treadonly timeout: number\n\n\tconstructor(timeout: number, options?: Omit<SylphxErrorOptions, 'code'>) {\n\t\tsuper(`Request timed out after ${timeout}ms`, {\n\t\t\t...options,\n\t\t\tcode: 'TIMEOUT',\n\t\t})\n\t\tthis.name = 'TimeoutError'\n\t\tthis.timeout = timeout\n\t}\n}\n\n/**\n * Authentication errors (401)\n */\nexport class AuthenticationError extends SylphxError {\n\tconstructor(message = 'Authentication required', options?: Omit<SylphxErrorOptions, 'code'>) {\n\t\tsuper(message, { ...options, code: 'UNAUTHORIZED' })\n\t\tthis.name = 'AuthenticationError'\n\t}\n}\n\n/**\n * Authorization errors (403)\n */\nexport class AuthorizationError extends SylphxError {\n\tconstructor(message = 'Permission denied', options?: Omit<SylphxErrorOptions, 'code'>) {\n\t\tsuper(message, { ...options, code: 'FORBIDDEN' })\n\t\tthis.name = 'AuthorizationError'\n\t}\n}\n\n/**\n * Validation errors (422)\n */\nexport class ValidationError extends SylphxError {\n\t/** Field-specific errors */\n\treadonly fieldErrors?: Record<string, string[]>\n\n\tconstructor(\n\t\tmessage: string,\n\t\toptions?: Omit<SylphxErrorOptions, 'code'> & {\n\t\t\tfieldErrors?: Record<string, string[]>\n\t\t},\n\t) {\n\t\tsuper(message, { ...options, code: 'UNPROCESSABLE_ENTITY' })\n\t\tthis.name = 'ValidationError'\n\t\tthis.fieldErrors = options?.fieldErrors\n\t}\n\n\t/**\n\t * Get error message for a specific field\n\t */\n\tgetFieldError(field: string): string | undefined {\n\t\treturn this.fieldErrors?.[field]?.[0]\n\t}\n}\n\n/**\n * Rate limit metadata (Stripe SDK pattern)\n */\nexport interface RateLimitInfo {\n\t/** Maximum requests allowed in window */\n\tlimit?: number\n\t/** Remaining requests in current window */\n\tremaining?: number\n\t/** Unix timestamp (seconds) when limit resets */\n\tresetAt?: number\n\t/** Seconds until limit resets (Retry-After header) */\n\tretryAfter?: number\n}\n\n/**\n * Rate limit errors (429)\n *\n * Provides full rate limit metadata for consumer apps to implement\n * proper backoff UI (countdown timers, retry buttons, etc.)\n *\n * @example\n * ```typescript\n * try {\n * await sendEmail(config, options)\n * } catch (error) {\n * if (error instanceof RateLimitError) {\n * const waitSeconds = error.retryAfter ?? 60\n * console.log(`Rate limited. Retry after ${waitSeconds}s`)\n * console.log(`Remaining: ${error.remaining}/${error.limit}`)\n * console.log(`Resets at: ${new Date(error.resetAt! * 1000)}`)\n * }\n * }\n * ```\n */\nexport class RateLimitError extends SylphxError {\n\t/** Maximum requests allowed in window */\n\treadonly limit?: number\n\n\t/** Remaining requests in current window */\n\treadonly remaining?: number\n\n\t/** Unix timestamp (seconds) when limit resets */\n\treadonly resetAt?: number\n\n\tconstructor(\n\t\tmessage = 'Too many requests',\n\t\toptions?: Omit<SylphxErrorOptions, 'code'> & RateLimitInfo,\n\t) {\n\t\tsuper(message, { ...options, code: 'TOO_MANY_REQUESTS' })\n\t\tthis.name = 'RateLimitError'\n\t\tthis.limit = options?.limit\n\t\tthis.remaining = options?.remaining\n\t\tthis.resetAt = options?.resetAt\n\t}\n\n\t/**\n\t * Get Date when rate limit resets\n\t */\n\tgetResetDate(): Date | undefined {\n\t\treturn this.resetAt ? new Date(this.resetAt * 1000) : undefined\n\t}\n\n\t/**\n\t * Get human-readable retry message\n\t */\n\tgetRetryMessage(): string {\n\t\tif (this.retryAfter) {\n\t\t\treturn `Please retry after ${this.retryAfter} seconds`\n\t\t}\n\t\tif (this.resetAt) {\n\t\t\tconst seconds = Math.max(0, this.resetAt - Math.floor(Date.now() / 1000))\n\t\t\treturn `Rate limit resets in ${seconds} seconds`\n\t\t}\n\t\treturn 'Please wait before retrying'\n\t}\n}\n\n/**\n * Resource not found errors (404)\n */\nexport class NotFoundError extends SylphxError {\n\t/** Type of resource that wasn't found */\n\treadonly resourceType?: string\n\n\t/** ID of the resource that wasn't found */\n\treadonly resourceId?: string\n\n\tconstructor(\n\t\tmessage = 'Resource not found',\n\t\toptions?: Omit<SylphxErrorOptions, 'code'> & {\n\t\t\tresourceType?: string\n\t\t\tresourceId?: string\n\t\t},\n\t) {\n\t\tsuper(message, { ...options, code: 'NOT_FOUND' })\n\t\tthis.name = 'NotFoundError'\n\t\tthis.resourceType = options?.resourceType\n\t\tthis.resourceId = options?.resourceId\n\t}\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Check if an error is a Sylphx SDK error\n */\nexport function isSylphxError(error: unknown): error is SylphxError {\n\treturn error instanceof SylphxError\n}\n\n/**\n * Check if an error is safe to retry\n */\nexport function isRetryableError(error: unknown): boolean {\n\tif (error instanceof SylphxError) {\n\t\treturn error.isRetryable\n\t}\n\n\t// Check for network errors\n\tif (error instanceof Error) {\n\t\tconst message = error.message.toLowerCase()\n\t\tconst name = error.name.toLowerCase()\n\n\t\t// Network errors\n\t\tif (name === 'typeerror' && message.includes('fetch')) return true\n\t\tif (name === 'networkerror') return true\n\n\t\t// Timeout patterns\n\t\tif (message.includes('timeout')) return true\n\t\tif (message.includes('timed out')) return true\n\n\t\t// Connection errors\n\t\tif (message.includes('econnrefused')) return true\n\t\tif (message.includes('econnreset')) return true\n\t\tif (message.includes('socket')) return true\n\n\t\t// Server errors that might be transient\n\t\tif (message.includes('502')) return true\n\t\tif (message.includes('503')) return true\n\t\tif (message.includes('504')) return true\n\t}\n\n\treturn false\n}\n\n/**\n * Extract error message from any error type\n */\nexport function getErrorMessage(error: unknown, fallback = 'An unknown error occurred'): string {\n\tif (error instanceof Error) {\n\t\treturn error.message\n\t}\n\tif (typeof error === 'string') {\n\t\treturn error\n\t}\n\tif (error && typeof error === 'object' && 'message' in error) {\n\t\tconst message = (error as { message: unknown }).message\n\t\tif (typeof message === 'string') return message\n\t}\n\tif (error && typeof error === 'object' && 'response' in error) {\n\t\tconst response = (error as { response?: { data?: { message?: string; error?: string } } })\n\t\t\t.response\n\t\tif (response?.data?.message) return response.data.message\n\t\tif (response?.data?.error) return response.data.error\n\t}\n\treturn fallback\n}\n\n/**\n * Get error code from any error type\n */\nexport function getErrorCode(error: unknown): SylphxErrorCode {\n\tif (error instanceof SylphxError) {\n\t\treturn error.code\n\t}\n\treturn 'UNKNOWN'\n}\n\nfunction getErrorStatus(error: unknown): number | undefined {\n\tif (!error || typeof error !== 'object') return undefined\n\tif ('status' in error && typeof (error as { status: unknown }).status === 'number') {\n\t\treturn (error as { status: number }).status\n\t}\n\tif ('statusCode' in error && typeof (error as { statusCode: unknown }).statusCode === 'number') {\n\t\treturn (error as { statusCode: number }).statusCode\n\t}\n\treturn undefined\n}\n\nfunction getSafeErrorKey(error: unknown): string | undefined {\n\tif (error instanceof SylphxError) return error.code\n\tif (!error || typeof error !== 'object') return undefined\n\tif ('code' in error && typeof (error as { code: unknown }).code === 'string') {\n\t\treturn (error as { code: string }).code\n\t}\n\tconst status = getErrorStatus(error)\n\treturn status == null ? undefined : String(status)\n}\n\nexport interface ErrorDetails {\n\treadonly message: string\n\treadonly code?: string\n\treadonly name?: string\n\treadonly stack?: string\n\treadonly status?: number\n\treadonly cause?: unknown\n}\n\nexport function getErrorDetails(\n\terror: unknown,\n\tfallbackMessage = 'An unknown error occurred',\n): ErrorDetails {\n\tconst details: ErrorDetails = {\n\t\tmessage: getErrorMessage(error, fallbackMessage),\n\t}\n\tconst code = getSafeErrorKey(error)\n\tif (code) {\n\t\tObject.assign(details, { code })\n\t}\n\tconst status = getErrorStatus(error)\n\tif (status != null) {\n\t\tObject.assign(details, { status })\n\t}\n\tif (error instanceof Error) {\n\t\tObject.assign(details, {\n\t\t\tname: error.name,\n\t\t\tstack: error.stack,\n\t\t\t...(error.cause ? { cause: error.cause } : {}),\n\t\t})\n\t}\n\treturn details\n}\n\nconst INTERNAL_ERROR_PATTERNS = [\n\t/sql/i,\n\t/database/i,\n\t/postgres/i,\n\t/neon/i,\n\t/drizzle/i,\n\t/prisma/i,\n\t/constraint/i,\n\t/foreign key/i,\n\t/unique violation/i,\n\t/null value/i,\n\t/column/i,\n\t/table/i,\n\t/relation/i,\n\t/trpc/i,\n\t/internal server/i,\n\t/unexpected/i,\n\t/cannot read propert/i,\n\t/undefined is not/i,\n\t/null is not/i,\n\t/cannot find module/i,\n\t/econnrefused/i,\n\t/etimedout/i,\n\t/enotfound/i,\n]\n\nconst SAFE_ERROR_MESSAGES: Record<string, string> = {\n\t'400': 'Invalid request. Please check your input and try again.',\n\t'401': 'Please sign in to continue.',\n\t'403': \"You don't have permission to perform this action.\",\n\t'404': 'The requested resource was not found.',\n\t'409': 'This action conflicts with existing data. Please refresh and try again.',\n\t'429': 'Too many requests. Please wait a moment and try again.',\n\t'500': 'Something went wrong on our end. Please try again later.',\n\t'502': 'Service temporarily unavailable. Please try again in a moment.',\n\t'503': 'Service temporarily unavailable. Please try again in a moment.',\n\tBAD_REQUEST: 'Invalid request. Please check your input.',\n\tUNAUTHORIZED: 'Please sign in to continue.',\n\tFORBIDDEN: \"You don't have permission to perform this action.\",\n\tNOT_FOUND: 'The requested item was not found.',\n\tCONFLICT: 'This action conflicts with existing data.',\n\tTOO_MANY_REQUESTS: 'Too many requests. Please wait a moment.',\n\tINTERNAL_SERVER_ERROR: 'Something went wrong. Please try again later.',\n\tTIMEOUT: 'Request timed out. Please try again.',\n\tPRECONDITION_FAILED: 'This action cannot be completed right now.',\n\tQUOTA_EXCEEDED: \"You've reached your usage limit. Please upgrade your plan.\",\n\tPAYMENT_REQUIRED: 'Payment is required to continue.',\n\tINVALID_CREDENTIALS: 'Invalid email or password.',\n\tEMAIL_NOT_VERIFIED: 'Please verify your email address.',\n\tACCOUNT_LOCKED: 'Your account has been locked. Please contact support.',\n\tSESSION_EXPIRED: 'Your session has expired. Please sign in again.',\n}\n\nexport function getSafeErrorMessage(\n\terror: unknown,\n\tfallback = 'Something went wrong. Please try again.',\n): string {\n\tconst errorCode = getSafeErrorKey(error)\n\tif (errorCode && SAFE_ERROR_MESSAGES[errorCode]) return SAFE_ERROR_MESSAGES[errorCode]\n\n\tif (error && typeof error === 'object') {\n\t\tconst coded = error as { data?: { code?: string } }\n\t\tif (coded.data?.code && SAFE_ERROR_MESSAGES[coded.data.code]) {\n\t\t\treturn SAFE_ERROR_MESSAGES[coded.data.code]\n\t\t}\n\t}\n\n\tconst rawMessage = getErrorMessage(error, '')\n\tif (\n\t\trawMessage &&\n\t\trawMessage.length < 200 &&\n\t\t!rawMessage.includes('\\n') &&\n\t\t!rawMessage.includes('at ') &&\n\t\t!INTERNAL_ERROR_PATTERNS.some((pattern) => pattern.test(rawMessage))\n\t) {\n\t\treturn rawMessage\n\t}\n\n\treturn fallback\n}\n\nexport function isChallengeRequired(err: unknown): boolean {\n\tif (!(err instanceof Error)) return false\n\tif (err.message.includes('challenge')) return true\n\tconst errWithData = err as { data?: { code?: string } }\n\treturn errWithData.data?.code === 'FORBIDDEN'\n}\n\n/**\n * Convert any error to SylphxError\n */\nexport function toSylphxError(error: unknown): SylphxError {\n\tif (error instanceof SylphxError) {\n\t\treturn error\n\t}\n\n\tif (error instanceof Error) {\n\t\t// Try to infer error type from message/name\n\t\tconst message = error.message.toLowerCase()\n\t\tconst name = error.name.toLowerCase()\n\n\t\t// Network errors\n\t\tif (name === 'typeerror' && message.includes('fetch')) {\n\t\t\treturn new NetworkError(error.message, { cause: error })\n\t\t}\n\t\tif (name === 'aborterror' || message.includes('aborted')) {\n\t\t\treturn new SylphxError(error.message, { code: 'ABORTED', cause: error })\n\t\t}\n\n\t\t// Timeout\n\t\tif (message.includes('timeout')) {\n\t\t\treturn new TimeoutError(DEFAULT_TIMEOUT_MS, { cause: error })\n\t\t}\n\n\t\t// HTTP status codes in message\n\t\tif (message.includes('401') || message.includes('unauthorized')) {\n\t\t\treturn new AuthenticationError(error.message, { cause: error })\n\t\t}\n\t\tif (message.includes('403') || message.includes('forbidden')) {\n\t\t\treturn new AuthorizationError(error.message, { cause: error })\n\t\t}\n\t\tif (message.includes('404') || message.includes('not found')) {\n\t\t\treturn new NotFoundError(error.message, { cause: error })\n\t\t}\n\t\tif (message.includes('429') || message.includes('rate limit')) {\n\t\t\treturn new RateLimitError(error.message, { cause: error })\n\t\t}\n\n\t\treturn new SylphxError(error.message, { cause: error })\n\t}\n\n\treturn new SylphxError(getErrorMessage(error))\n}\n\n/**\n * Calculate exponential backoff delay with jitter\n *\n * @param attempt - Retry attempt number (0-indexed)\n * @param baseDelay - Base delay in milliseconds (default: 1000)\n * @param maxDelay - Maximum delay in milliseconds (default: 30000)\n * @returns Delay in milliseconds with jitter\n */\nexport function exponentialBackoff(\n\tattempt: number,\n\tbaseDelay = BASE_RETRY_DELAY_MS,\n\tmaxDelay = MAX_RETRY_DELAY_MS,\n): number {\n\t// Calculate exponential delay: baseDelay * 2^attempt\n\tconst exponentialDelay = baseDelay * 2 ** attempt\n\n\t// Cap at maxDelay\n\tconst cappedDelay = Math.min(exponentialDelay, maxDelay)\n\n\t// Add jitter (±25% randomness)\n\tconst jitter = cappedDelay * 0.25 * (Math.random() * 2 - 1)\n\n\treturn Math.round(cappedDelay + jitter)\n}\n","/**\n * SDK Configuration — ADR-055 Connection URL API\n *\n * v0.5.0: The primary entry point is `createClient(url)` which accepts\n * a `sylphx://` connection URL. The old `createConfig({ ref, publicKey })`\n * API is removed.\n *\n * @example\n * ```typescript\n * import { createClient } from '@sylphx/sdk'\n *\n * const sylphx = createClient(process.env.SYLPHX_URL!)\n * // Parses: sylphx://pk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com\n * ```\n */\n\nimport {\n\tCREDENTIAL_REGEX,\n\tInvalidConnectionUrlError,\n\ttype ParsedConnectionUrl,\n\tparseConnectionUrl,\n} from './connection-url'\nimport { DEFAULT_SDK_API_HOST, DEFAULT_TIMEOUT_MS } from './constants'\nimport {\n\tNetworkError,\n\tRateLimitError,\n\tSylphxError,\n\ttype SylphxErrorCode,\n\tTimeoutError,\n} from './errors'\n\nexport type {\n\tBuildConnectionUrlInput,\n\tConnectionCredentialType,\n\tConnectionEnv,\n\tParsedConnectionUrl,\n} from './connection-url'\n// Re-export connection URL primitives for consumers (ADR-123 SSOT)\nexport {\n\tbuildConnectionUrl,\n\tCREDENTIAL_REGEX,\n\tInvalidConnectionUrlError,\n\tparseConnectionUrl,\n} from './connection-url'\n\n// =============================================================================\n// Legacy format detection — produces clear migration errors\n// =============================================================================\n\n/** Matches a bare ref-scoped credential mistakenly passed without the `sylphx://` URL wrapper. */\nconst LEGACY_EMBEDDED_REF_PATTERN = /^(pk|sk)_(dev|stg|prod|prev)_[a-z0-9]{12}_[a-f0-9]+$/\n\n/** Matches old app_* format: app_{env}_{anything} */\nconst LEGACY_APP_KEY_PATTERN = /^app_(dev|stg|prod|prev)_/\n\nconst MIGRATION_MESSAGE =\n\t'API key format has changed. Use a sylphx:// connection URL instead.\\n\\n' +\n\t'New format: sylphx://pk_prod_{ref?}_{hex}@your-slug.api.sylphx.com\\n\\n' +\n\t'Generate new credentials from the Sylphx Console → Your App → Environments.\\n' +\n\t'See https://docs.sylphx.com/migration for details.'\n\n/**\n * Detect legacy key formats and throw a helpful migration error.\n */\nfunction rejectLegacyKeyFormat(input: string): void {\n\tconst trimmed = input.trim().toLowerCase()\n\n\tif (LEGACY_APP_KEY_PATTERN.test(trimmed)) {\n\t\tthrow new SylphxError(`[Sylphx] ${MIGRATION_MESSAGE}`, { code: 'BAD_REQUEST' })\n\t}\n\n\tif (LEGACY_EMBEDDED_REF_PATTERN.test(trimmed)) {\n\t\tthrow new SylphxError(`[Sylphx] ${MIGRATION_MESSAGE}`, { code: 'BAD_REQUEST' })\n\t}\n}\n\n// =============================================================================\n// Config types\n// =============================================================================\n\n/**\n * SDK Configuration object — immutable, frozen.\n *\n * Created by `createClient()` or `createServerClient()`.\n * Passed to all pure SDK functions (`track()`, `signIn()`, etc.).\n */\nexport interface SylphxConfig {\n\t/** The credential string (pk_* or sk_*) */\n\treadonly credential: string\n\t/** Credential type: 'pk' (publishable) or 'sk' (secret) */\n\treadonly credentialType: 'pk' | 'sk'\n\t/** Target environment: dev, stg, prod, or prev */\n\treadonly env: 'dev' | 'stg' | 'prod' | 'prev'\n\t/** Resource slug (first DNS label), e.g. 'bold-river-a1b2c3' */\n\treadonly slug: string\n\t/** Pre-computed API base URL, e.g. 'https://bold-river-a1b2c3.api.sylphx.com/v1' */\n\treadonly baseUrl: string\n\t/** Optional access token for authenticated requests */\n\treadonly accessToken?: string\n\t/**\n\t * Secret key — populated when credentialType is 'sk'.\n\t * Backward-compatible alias for `credential` when credential is sk_*.\n\t */\n\treadonly secretKey?: string\n\t/**\n\t * Publishable key — populated when credentialType is 'pk'.\n\t * Backward-compatible alias for `credential` when credential is pk_*.\n\t */\n\treadonly publicKey?: string\n\t/**\n\t * @deprecated Use `slug`. Backward-compatible alias.\n\t */\n\treadonly ref: string\n}\n\n/**\n * Explicit components input — alternative to connection URL string.\n *\n * For multi-tenant apps or cases where components are stored separately.\n */\nexport interface SylphxClientInput {\n\t/** Resource slug, e.g. 'bold-river-a1b2c3' */\n\tslug?: string\n\t/** Publishable key (pk_*) — client-safe */\n\tpublicKey?: string\n\t/** Secret key (sk_*) — server-side only */\n\tsecretKey?: string\n\t/** Optional access token */\n\taccessToken?: string\n\t/** API domain override (default: api.sylphx.com) */\n\tdomain?: string\n\t/**\n\t * @deprecated Use `slug`. Accepted for backward compatibility during migration.\n\t */\n\tref?: string\n\t/**\n\t * @deprecated Use `domain`. Accepted for backward compatibility during migration.\n\t */\n\tplatformUrl?: string\n}\n\n/**\n * Build a frozen SylphxConfig with backward-compat fields (secretKey, publicKey, ref).\n */\nfunction freezeConfig(opts: {\n\tcredential: string\n\tcredentialType: 'pk' | 'sk'\n\tenv: 'dev' | 'stg' | 'prod' | 'prev'\n\tslug: string\n\tbaseUrl: string\n\taccessToken?: string\n}): SylphxConfig {\n\treturn Object.freeze({\n\t\tcredential: opts.credential,\n\t\tcredentialType: opts.credentialType,\n\t\tenv: opts.env,\n\t\tslug: opts.slug,\n\t\tbaseUrl: opts.baseUrl,\n\t\taccessToken: opts.accessToken,\n\t\t// Backward-compat aliases\n\t\tsecretKey: opts.credentialType === 'sk' ? opts.credential : undefined,\n\t\tpublicKey: opts.credentialType === 'pk' ? opts.credential : undefined,\n\t\tref: opts.slug,\n\t})\n}\n\n// =============================================================================\n// createClient — primary entry point (ADR-055)\n// =============================================================================\n\n/**\n * Create a Sylphx client from a connection URL or explicit components.\n *\n * This is the primary SDK entry point for client-side (browser) usage.\n * Accepts a `sylphx://` connection URL or an explicit components object.\n *\n * @example Connection URL (recommended)\n * ```typescript\n * const sylphx = createClient(process.env.NEXT_PUBLIC_SYLPHX_URL!)\n * // Parses: sylphx://pk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com\n * ```\n *\n * @example Explicit components\n * ```typescript\n * const sylphx = createClient({\n * slug: 'bold-river-a1b2c3',\n * publicKey: 'pk_prod_f19e...',\n * })\n * ```\n */\nexport function createClient(input: string | SylphxClientInput): SylphxConfig {\n\tif (typeof input === 'string') {\n\t\treturn createConfigFromUrl(input)\n\t}\n\treturn createConfigFromComponents(input)\n}\n\n/**\n * Create a Sylphx server client from a connection URL or explicit components.\n *\n * Equivalent to `createClient()` but validates that a secret key (sk_*) is provided.\n * Use this for server-side operations that require elevated permissions.\n *\n * @example Connection URL (recommended)\n * ```typescript\n * const sylphx = createServerClient(process.env.SYLPHX_SECRET_URL!)\n * // Parses: sylphx://sk_prod_{ref?}_{hex}@bold-river-a1b2c3.api.sylphx.com\n * ```\n *\n * @example Explicit components\n * ```typescript\n * const sylphx = createServerClient({\n * slug: 'bold-river-a1b2c3',\n * secretKey: 'sk_prod_5120...',\n * })\n * ```\n */\nexport function createServerClient(input: string | SylphxClientInput): SylphxConfig {\n\tconst config = createClient(input)\n\n\tif (config.credentialType !== 'sk') {\n\t\tthrow new SylphxError(\n\t\t\t'[Sylphx] createServerClient() requires a secret key (sk_*). ' +\n\t\t\t\t'Use a SYLPHX_SECRET_URL with an sk_ credential, or pass { secretKey } in the components object.',\n\t\t\t{ code: 'BAD_REQUEST' },\n\t\t)\n\t}\n\n\treturn config\n}\n\n// =============================================================================\n// Internal construction\n// =============================================================================\n\nfunction createConfigFromUrl(url: string): SylphxConfig {\n\tif (!url || typeof url !== 'string') {\n\t\tthrow new SylphxError(\n\t\t\t'[Sylphx] Connection URL is required. Set SYLPHX_URL or NEXT_PUBLIC_SYLPHX_URL environment variable.\\n\\n' +\n\t\t\t\t'Format: sylphx://pk_prod_{hex}@your-slug.api.sylphx.com',\n\t\t\t{ code: 'BAD_REQUEST' },\n\t\t)\n\t}\n\n\tconst trimmed = url.trim()\n\n\t// Detect legacy key formats passed as the URL string\n\trejectLegacyKeyFormat(trimmed)\n\n\t// If someone passes a bare key instead of a URL, give a helpful error\n\tif (!trimmed.startsWith('sylphx://')) {\n\t\t// Check if it looks like a new-format bare credential\n\t\tif (CREDENTIAL_REGEX.test(trimmed)) {\n\t\t\tthrow new SylphxError(\n\t\t\t\t'[Sylphx] Received a bare credential instead of a connection URL.\\n\\n' +\n\t\t\t\t\t'Wrap it in a connection URL: sylphx://<credential>@<slug>.api.sylphx.com\\n' +\n\t\t\t\t\t'Or use createClient({ slug, publicKey }) for explicit components.',\n\t\t\t\t{ code: 'BAD_REQUEST' },\n\t\t\t)\n\t\t}\n\t\tthrow new SylphxError(\n\t\t\t`[Sylphx] Invalid connection URL — must start with \"sylphx://\". Got: \"${trimmed.slice(0, 30)}...\"`,\n\t\t\t{ code: 'BAD_REQUEST' },\n\t\t)\n\t}\n\n\tlet parsed: ParsedConnectionUrl\n\ttry {\n\t\tparsed = parseConnectionUrl(trimmed)\n\t} catch (err) {\n\t\tif (err instanceof InvalidConnectionUrlError) {\n\t\t\tthrow new SylphxError(err.message, { code: 'BAD_REQUEST', cause: err })\n\t\t}\n\t\tthrow err\n\t}\n\n\treturn freezeConfig({\n\t\tcredential: parsed.credential,\n\t\tcredentialType: parsed.credentialType,\n\t\tenv: parsed.env,\n\t\tslug: parsed.slug,\n\t\tbaseUrl: parsed.apiBaseUrl,\n\t})\n}\n\nfunction createConfigFromComponents(input: SylphxClientInput): SylphxConfig {\n\tconst credential = input.secretKey || input.publicKey\n\tif (!credential) {\n\t\tthrow new SylphxError('[Sylphx] Either publicKey or secretKey must be provided.', {\n\t\t\tcode: 'BAD_REQUEST',\n\t\t})\n\t}\n\n\t// Accept deprecated `ref` as fallback for `slug` during migration\n\tconst resolvedSlug = input.slug || input.ref\n\n\tif (!resolvedSlug) {\n\t\tthrow new SylphxError('[Sylphx] slug is required when using explicit components.', {\n\t\t\tcode: 'BAD_REQUEST',\n\t\t})\n\t}\n\n\t// Try to validate as ADR-055 credential first; if invalid, check for legacy\n\tconst trimmedCred = credential.trim().toLowerCase()\n\n\tif (CREDENTIAL_REGEX.test(trimmedCred)) {\n\t\t// Connection credential: pk/sk_{env}_{optional ref}_{hex}\n\t\tconst match = CREDENTIAL_REGEX.exec(trimmedCred)!\n\t\tconst credentialType = match[1] as 'pk' | 'sk'\n\t\tconst env = match[2] as 'dev' | 'stg' | 'prod' | 'prev'\n\n\t\tconst slug = resolvedSlug.trim().toLowerCase()\n\t\t// Default to `api.sylphx.com` (DNS-only) — `sylphx.com` is Cloudflare-\n\t\t// proxied with no per-slug origin mapping and returns 404 for any\n\t\t// `<slug>.sylphx.com` request. The legacy components path below\n\t\t// (4-segment credentials) already defaults to `api.sylphx.com`; this\n\t\t// brings the new-format path in line so both behave consistently and\n\t\t// match the ADR-055 SYLPHX_URL injected by the platform.\n\t\tconst domain = input.domain?.trim() || DEFAULT_SDK_API_HOST\n\t\tconst baseUrl = `https://${slug}.${domain}/v1`\n\n\t\treturn freezeConfig({\n\t\t\tcredential: trimmedCred,\n\t\t\tcredentialType,\n\t\t\tenv,\n\t\t\tslug,\n\t\t\tbaseUrl,\n\t\t\taccessToken: input.accessToken,\n\t\t})\n\t}\n\n\t\t// Backward-compat legacy embedded-ref keys have 4 underscore-delimited\n\t\t// segments. Extract env from segment 1; ADR-055 routing resolves server-side.\n\tconst parts = trimmedCred.split('_')\n\tconst prefix = parts[0] as 'pk' | 'sk'\n\tif ((prefix === 'pk' || prefix === 'sk') && parts.length >= 3) {\n\t\tconst envSegment = parts[1]\n\t\tconst validEnvs = ['dev', 'stg', 'prod', 'prev']\n\t\tconst env = validEnvs.includes(envSegment)\n\t\t\t? (envSegment as 'dev' | 'stg' | 'prod' | 'prev')\n\t\t\t: 'prod'\n\n\t\tconst slug = resolvedSlug.trim().toLowerCase()\n\t\t// Accept deprecated platformUrl for base URL construction\n\t\tlet baseUrl: string\n\t\tif (input.platformUrl) {\n\t\t\tconst platform = input.platformUrl.trim().replace(/\\/$/, '')\n\t\t\tbaseUrl = platform.includes('/v1') ? platform : `${platform}/v1`\n\t\t} else {\n\t\t\tconst domain = input.domain?.trim() || DEFAULT_SDK_API_HOST\n\t\t\tbaseUrl = `https://${slug}.${domain}/v1`\n\t\t}\n\n\t\treturn freezeConfig({\n\t\t\tcredential: trimmedCred,\n\t\t\tcredentialType: prefix,\n\t\t\tenv,\n\t\t\tslug,\n\t\t\tbaseUrl,\n\t\t\taccessToken: input.accessToken,\n\t\t})\n\t}\n\n\tthrow new SylphxError(\n\t\t`[Sylphx] Invalid credential format. Expected (pk|sk)_(dev|stg|prod|prev)(_{ref})?_{hex}. Got: \"${trimmedCred.slice(0, 30)}...\"`,\n\t\t{ code: 'BAD_REQUEST' },\n\t)\n}\n\n// =============================================================================\n// Config utilities\n// =============================================================================\n\n/**\n * Create a new config with an updated access token.\n *\n * Returns a new frozen config — does not mutate the original.\n *\n * @example\n * ```typescript\n * const authenticatedConfig = withToken(config, 'access_token_here')\n * ```\n */\nexport function withToken(config: SylphxConfig, accessToken: string): SylphxConfig {\n\treturn Object.freeze({\n\t\t...config,\n\t\taccessToken,\n\t})\n}\n\n// =============================================================================\n// Backward compatibility — createConfig (deprecated, will be removed)\n// =============================================================================\n\n/**\n * @deprecated Use `createClient()` or `createServerClient()` instead.\n * This function is kept temporarily for migration but will be removed.\n */\nexport type SylphxConfigInput = string | SylphxClientInput\n\n/**\n * @deprecated Use `createClient()` instead. See ADR-055.\n */\nexport const createConfig = createClient\n\n// =============================================================================\n// Request helpers — internal SDK plumbing\n// =============================================================================\n\n/**\n * Map HTTP status code to SylphxErrorCode\n */\nfunction httpStatusToErrorCode(status: number): SylphxErrorCode {\n\tswitch (status) {\n\t\tcase 400:\n\t\t\treturn 'BAD_REQUEST'\n\t\tcase 401:\n\t\t\treturn 'UNAUTHORIZED'\n\t\tcase 403:\n\t\t\treturn 'FORBIDDEN'\n\t\tcase 404:\n\t\t\treturn 'NOT_FOUND'\n\t\tcase 409:\n\t\t\treturn 'CONFLICT'\n\t\tcase 413:\n\t\t\treturn 'PAYLOAD_TOO_LARGE'\n\t\tcase 422:\n\t\t\treturn 'UNPROCESSABLE_ENTITY'\n\t\tcase 429:\n\t\t\treturn 'TOO_MANY_REQUESTS'\n\t\tcase 500:\n\t\t\treturn 'INTERNAL_SERVER_ERROR'\n\t\tcase 501:\n\t\t\treturn 'NOT_IMPLEMENTED'\n\t\tcase 502:\n\t\t\treturn 'BAD_GATEWAY'\n\t\tcase 503:\n\t\t\treturn 'SERVICE_UNAVAILABLE'\n\t\tcase 504:\n\t\t\treturn 'GATEWAY_TIMEOUT'\n\t\tdefault:\n\t\t\treturn status >= 500 ? 'INTERNAL_SERVER_ERROR' : 'BAD_REQUEST'\n\t}\n}\n\n/**\n * Internal: Build headers for API requests.\n *\n * Sends the credential as `x-app-secret` header.\n */\nexport function buildHeaders(config: SylphxConfig): Record<string, string> {\n\tconst headers: Record<string, string> = {\n\t\t'Content-Type': 'application/json',\n\t}\n\n\tif (config.credential) {\n\t\theaders['x-app-secret'] = config.credential\n\t}\n\tif (config.accessToken) {\n\t\theaders.Authorization = `Bearer ${config.accessToken}`\n\t}\n\n\treturn headers\n}\n\n/**\n * Internal: Build REST API URL.\n *\n * Appends path to the pre-computed base URL.\n */\nexport function buildApiUrl(config: SylphxConfig, path: string): string {\n\tconst base = config.baseUrl.replace(/\\/$/, '')\n\tconst cleanPath = path.startsWith('/') ? path : `/${path}`\n\treturn `${base}${cleanPath}`\n}\n\n/**\n * Internal: Call REST API endpoint.\n *\n * Features:\n * - Request timeout (default 30s) prevents infinite hangs\n * - Proper HTTP status code mapping to error codes\n * - Safe JSON parsing with error handling\n * - Idempotency key support (Stripe pattern)\n */\nexport async function callApi<TOutput>(\n\tconfig: SylphxConfig,\n\tpath: string,\n\toptions: {\n\t\tmethod?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\t\tbody?: unknown\n\t\tquery?: Record<string, string | number | boolean | undefined>\n\t\ttimeout?: number\n\t\tsignal?: AbortSignal\n\t\tidempotencyKey?: string\n\t\theaders?: Record<string, string>\n\t} = {},\n): Promise<TOutput> {\n\tconst {\n\t\tmethod = 'GET',\n\t\tbody,\n\t\tquery,\n\t\ttimeout = DEFAULT_TIMEOUT_MS,\n\t\tsignal,\n\t\tidempotencyKey,\n\t\theaders: extraHeaders,\n\t} = options\n\n\tlet url = buildApiUrl(config, path)\n\n\t// Add query parameters\n\tif (query) {\n\t\tconst params = new URLSearchParams()\n\t\tfor (const [key, value] of Object.entries(query)) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tparams.set(key, String(value))\n\t\t\t}\n\t\t}\n\t\tconst queryString = params.toString()\n\t\tif (queryString) {\n\t\t\turl += `?${queryString}`\n\t\t}\n\t}\n\n\t// Create AbortController for timeout\n\tconst controller = new AbortController()\n\tconst timeoutId = setTimeout(() => controller.abort(), timeout)\n\n\t// Combine user signal with timeout signal\n\tconst combinedSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal\n\n\tconst headers = buildHeaders(config)\n\n\t// Add idempotency key header for safe retries (Stripe pattern)\n\tif (idempotencyKey) {\n\t\theaders['Idempotency-Key'] = idempotencyKey\n\t}\n\n\t// Merge user-supplied headers\n\tif (extraHeaders) {\n\t\tfor (const [k, v] of Object.entries(extraHeaders)) {\n\t\t\theaders[k] = v\n\t\t}\n\t}\n\n\tconst fetchOptions: RequestInit = {\n\t\tmethod,\n\t\theaders,\n\t\tsignal: combinedSignal,\n\t}\n\n\tif (body) {\n\t\tfetchOptions.body = JSON.stringify(body)\n\t}\n\n\tlet response: Response\n\ttry {\n\t\tresponse = await fetch(url, fetchOptions)\n\t} catch (error) {\n\t\tclearTimeout(timeoutId)\n\n\t\t// Handle abort/timeout\n\t\tif (error instanceof Error) {\n\t\t\tif (error.name === 'AbortError') {\n\t\t\t\t// Check if it was our timeout or user cancellation\n\t\t\t\tif (controller.signal.aborted && !signal?.aborted) {\n\t\t\t\t\tthrow new TimeoutError(timeout)\n\t\t\t\t}\n\t\t\t\tthrow new SylphxError('Request aborted', {\n\t\t\t\t\tcode: 'ABORTED',\n\t\t\t\t\tcause: error,\n\t\t\t\t})\n\t\t\t}\n\t\t\t// Network errors\n\t\t\tthrow new NetworkError(error.message, { cause: error })\n\t\t}\n\t\tthrow new NetworkError('Network request failed')\n\t} finally {\n\t\tclearTimeout(timeoutId)\n\t}\n\n\tif (!response.ok) {\n\t\tconst errorBody = await response.text().catch(() => '')\n\t\tlet errorMessage = 'Request failed'\n\t\tlet errorData: Record<string, unknown> | undefined\n\n\t\t// Safe JSON parsing\n\t\tif (errorBody) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(errorBody) as {\n\t\t\t\t\terror?: { message?: string }\n\t\t\t\t\tmessage?: string\n\t\t\t\t}\n\t\t\t\terrorMessage = parsed.error?.message ?? parsed.message ?? errorMessage\n\t\t\t\terrorData = parsed.error as Record<string, unknown> | undefined\n\t\t\t} catch {\n\t\t\t\terrorMessage = response.statusText || errorMessage\n\t\t\t}\n\t\t}\n\n\t\tconst errorCode = httpStatusToErrorCode(response.status)\n\n\t\t// Extract rate limit headers (Stripe SDK pattern)\n\t\tconst retryAfterHeader = response.headers.get('Retry-After')\n\t\tconst rateLimitLimit = response.headers.get('X-RateLimit-Limit')\n\t\tconst rateLimitRemaining = response.headers.get('X-RateLimit-Remaining')\n\t\tconst rateLimitReset = response.headers.get('X-RateLimit-Reset')\n\n\t\tconst retryAfter = retryAfterHeader ? Number.parseInt(retryAfterHeader, 10) : undefined\n\n\t\t// Use specialized RateLimitError for 429 responses\n\t\tif (response.status === 429) {\n\t\t\tthrow new RateLimitError(errorMessage || 'Too many requests', {\n\t\t\t\tstatus: response.status,\n\t\t\t\tdata: errorData,\n\t\t\t\tretryAfter,\n\t\t\t\tlimit: rateLimitLimit ? Number.parseInt(rateLimitLimit, 10) : undefined,\n\t\t\t\tremaining: rateLimitRemaining ? Number.parseInt(rateLimitRemaining, 10) : undefined,\n\t\t\t\tresetAt: rateLimitReset ? Number.parseInt(rateLimitReset, 10) : undefined,\n\t\t\t})\n\t\t}\n\n\t\tthrow new SylphxError(errorMessage, {\n\t\t\tcode: errorCode,\n\t\t\tstatus: response.status,\n\t\t\tdata: errorData,\n\t\t\tretryAfter,\n\t\t})\n\t}\n\n\t// Handle empty responses (204 No Content)\n\tconst text = await response.text()\n\tif (!text) {\n\t\treturn {} as TOutput\n\t}\n\n\t// Safe JSON parsing for response body\n\ttry {\n\t\treturn JSON.parse(text) as TOutput\n\t} catch (error) {\n\t\tthrow new SylphxError('Failed to parse response', {\n\t\t\tcode: 'PARSE_ERROR',\n\t\t\tcause: error instanceof Error ? error : undefined,\n\t\t\tdata: { body: text.slice(0, 200) },\n\t\t})\n\t}\n}\n","/**\n * Triggers Client (ADR-040)\n *\n * Unified scheduling + event dispatch API.\n * Create cron schedules and event triggers that dispatch to Tasks, Runs, or HTTP URLs.\n *\n * ## Usage\n *\n * ### Cron → Task\n * ```typescript\n * import { createServerClient, TriggersClient } from '@sylphx/sdk'\n * const config = createServerClient(process.env.SYLPHX_SECRET_URL!)\n *\n * const trigger = await TriggersClient.create(config, {\n * name: 'daily-cleanup',\n * source: { type: 'cron', expression: '0 2 * * *' },\n * target: { type: 'task', taskName: 'daily-cleanup' },\n * })\n * ```\n *\n * ### Event → Task (fires when event is published via publishEvent)\n * ```typescript\n * const trigger = await TriggersClient.create(config, {\n * name: 'welcome-email-on-signup',\n * source: { type: 'event', eventName: 'user.signup' },\n * target: { type: 'task', taskName: 'send-welcome-email' },\n * })\n * // Publish from your app:\n * await TriggersClient.publishEvent(config, 'user.signup', { userId: '123' })\n * ```\n *\n * ### Cron → HTTP URL (any language, no code required)\n * ```typescript\n * const trigger = await TriggersClient.create(config, {\n * name: 'nightly-backup',\n * source: { type: 'cron', expression: '0 3 * * *' },\n * target: { type: 'http', url: 'https://myapp.com/api/backup', payload: { type: 'full' } },\n * })\n * ```\n */\n\nimport type { MachineSize } from '@sylphx/contract'\nimport type { SylphxConfig } from '../../config'\nimport { callApi } from '../../config'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type TriggerTargetType = 'task' | 'run' | 'http'\nexport type TriggerSourceType = 'cron' | 'event'\nexport type TriggerStatus = 'active' | 'paused' | 'deleted'\nexport type TriggerRunMachineSize = MachineSize\n\nexport interface TaskTarget {\n\ttype: 'task'\n\ttaskName: string\n\thandlerPath?: string\n\tpayload?: Record<string, unknown>\n}\n\nexport interface HttpTarget {\n\ttype: 'http'\n\turl: string\n\tmethod?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\theaders?: Record<string, string>\n\tpayload?: Record<string, unknown>\n}\n\nexport interface RunTarget {\n\ttype: 'run'\n\timage: string\n\tcommand: string[]\n\tmachine?: TriggerRunMachineSize\n}\n\nexport type TriggerTarget = TaskTarget | HttpTarget | RunTarget\n\nexport interface CronSource {\n\ttype: 'cron'\n\texpression: string\n}\n\nexport interface EventSource {\n\ttype: 'event'\n\t/** The event name to listen for. e.g. 'user.signup', 'order.paid' */\n\teventName: string\n}\n\nexport type TriggerSource = CronSource | EventSource\n\nexport interface CreateTriggerOptions {\n\tname?: string\n\tsource: TriggerSource\n\ttarget: TriggerTarget\n\tpaused?: boolean\n\t/** Idempotency key — prevents duplicate trigger creation per project+environment */\n\tidempotencyKey?: string\n}\n\nexport interface UpdateTriggerOptions {\n\tname?: string\n\tsource?: TriggerSource\n\tpaused?: boolean\n}\n\nexport interface Trigger {\n\tid: string\n\tname: string\n\ttargetType: TriggerTargetType\n\tsourceType: TriggerSourceType\n\tcronExpression: string | null\n\teventName: string | null\n\thandlerPath: string | null\n\tcallbackUrl: string | null\n\tpayload: unknown\n\tstatus: TriggerStatus\n\tnextRunAt: string | null\n\tlastRunAt: string | null\n\tcreatedAt: string\n\tupdatedAt: string\n}\n\nexport interface ListTriggersResult {\n\ttriggers: Trigger[]\n}\n\nexport interface PublishEventResult {\n\tdispatched: number\n\twaitResolved: number\n\teventName: string\n}\n\n// ============================================================================\n// Client\n// ============================================================================\n\n/** Create a new trigger (cron or event source, task/run/http target) */\nasync function createTrigger(\n\tconfig: SylphxConfig,\n\toptions: CreateTriggerOptions,\n): Promise<Trigger> {\n\treturn callApi<Trigger>(config, '/triggers', {\n\t\tmethod: 'POST',\n\t\tbody: options,\n\t})\n}\n\n/** List all triggers for the project */\nasync function listTriggers(config: SylphxConfig): Promise<ListTriggersResult> {\n\treturn callApi<ListTriggersResult>(config, '/triggers')\n}\n\n/** Get a trigger by ID */\nasync function getTrigger(config: SylphxConfig, triggerId: string): Promise<Trigger> {\n\treturn callApi<Trigger>(config, `/triggers/${triggerId}`)\n}\n\n/** Update a trigger */\nasync function updateTrigger(\n\tconfig: SylphxConfig,\n\ttriggerId: string,\n\toptions: UpdateTriggerOptions,\n): Promise<Trigger> {\n\treturn callApi<Trigger>(config, `/triggers/${triggerId}`, {\n\t\tmethod: 'PATCH',\n\t\tbody: options,\n\t})\n}\n\n/** Delete a trigger */\nasync function deleteTrigger(\n\tconfig: SylphxConfig,\n\ttriggerId: string,\n): Promise<{ success: boolean }> {\n\treturn callApi<{ success: boolean }>(config, `/triggers/${triggerId}`, { method: 'DELETE' })\n}\n\n/** Pause a trigger */\nasync function pauseTrigger(config: SylphxConfig, triggerId: string): Promise<Trigger> {\n\treturn callApi<Trigger>(config, `/triggers/${triggerId}/pause`, { method: 'POST' })\n}\n\n/** Resume a paused trigger */\nasync function resumeTrigger(config: SylphxConfig, triggerId: string): Promise<Trigger> {\n\treturn callApi<Trigger>(config, `/triggers/${triggerId}/resume`, { method: 'POST' })\n}\n\n/** Fire a trigger immediately (one-shot, regardless of schedule) */\nasync function fireTrigger(\n\tconfig: SylphxConfig,\n\ttriggerId: string,\n): Promise<{ success: boolean; message: string }> {\n\treturn callApi<{ success: boolean; message: string }>(config, `/triggers/${triggerId}/fire`, {\n\t\tmethod: 'POST',\n\t})\n}\n\n/**\n * Publish an event — dispatches all active event triggers matching the event name.\n * Endpoint: POST /triggers/events\n *\n * @example\n * ```typescript\n * await TriggersClient.publishEvent(config, 'user.signup', { userId: '123', plan: 'pro' })\n * ```\n */\nasync function publishEvent(\n\tconfig: SylphxConfig,\n\teventName: string,\n\tpayload?: Record<string, unknown>,\n): Promise<PublishEventResult> {\n\treturn callApi<PublishEventResult>(config, '/triggers/events', {\n\t\tmethod: 'POST',\n\t\tbody: { eventName, payload: payload ?? {} },\n\t})\n}\n\n/**\n * Triggers client — namespace object exposing all trigger operations.\n * Use via `TriggersClient.create(...)`, `TriggersClient.publishEvent(...)`, etc.\n */\nexport const TriggersClient = {\n\tcreate: createTrigger,\n\tlist: listTriggers,\n\tget: getTrigger,\n\tupdate: updateTrigger,\n\tdelete: deleteTrigger,\n\tpause: pauseTrigger,\n\tresume: resumeTrigger,\n\tfire: fireTrigger,\n\tpublishEvent,\n} as const\n","import { ENV_SECRET_URL } from '../../constants'\n\nexport interface ResolveTaskServerConnectionUrlOptions {\n\treadonly explicitConnectionUrl?: string\n}\n\n/**\n * Task dispatch and trigger sync are server-side operations. They require the\n * server-only connection URL; the public SYLPHX_URL is intentionally ignored.\n */\nexport function resolveTaskServerConnectionUrl(\n\toptions: ResolveTaskServerConnectionUrlOptions = {},\n): string | null {\n\tconst explicit = options.explicitConnectionUrl?.trim()\n\tif (explicit) return explicit\n\n\tif (typeof process === 'undefined') return null\n\n\treturn process.env[ENV_SECRET_URL]?.trim() || null\n}\n\nexport function requireTaskServerConnectionUrl(\n\toptions: ResolveTaskServerConnectionUrlOptions = {},\n): string {\n\tconst connectionUrl = resolveTaskServerConnectionUrl(options)\n\tif (!connectionUrl) {\n\t\tthrow new Error(\n\t\t\t`[sylphx/tasks] No server connection URL found. Set ${ENV_SECRET_URL} env var or pass config to trigger options.`,\n\t\t)\n\t}\n\treturn connectionUrl\n}\n","/**\n * Tasks Handler\n *\n * Server-side endpoint factory for user task definitions.\n * Implements the Sylphx stateless-replay model:\n *\n * 1. Platform dispatches POST to the app's /api/tasks endpoint.\n * 2. The handler replays from the beginning.\n * 3. Completed steps hit a cache and return immediately.\n * 4. The first uncached step executes, then throws StepCompleteSignal.\n * 5. The platform saves the result and re-dispatches.\n * 6. After all steps complete the handler returns normally.\n *\n * @example\n * ```typescript\n * // app/api/tasks/route.ts\n * import { sylphx } from '@/lib/sylphx'\n *\n * const sendEmail = sylphx.tasks.define('send-email', async (payload, { step }) => {\n * const validated = await step.run('validate', () => validateEmail(payload.to))\n * await step.sleep('cool-down', '5 minutes')\n * return step.run('send', () => sendEmail(validated))\n * })\n *\n * export const { GET, POST } = sylphx.tasks.handler([sendEmail])\n * ```\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto'\nimport type {\n\tNativeSideEffectOutcome,\n\tNativeSideEffectReceipt,\n\tNativeStepContext,\n\tNativeTaskDefinition,\n} from './types'\n\n// ============================================================================\n// Signals (control flow via throw)\n// ============================================================================\n\n/**\n * Thrown by step.run() when a step's result is not yet cached.\n * The handler aborts; the platform saves the result and re-dispatches.\n */\nexport class StepCompleteSignal {\n\treadonly _isStepCompleteSignal = true\n\n\tconstructor(\n\t\tpublic readonly stepName: string,\n\t\tpublic readonly result: unknown,\n\t) {}\n}\n\nexport class StepSideEffectStartSignal {\n\treadonly _isStepSideEffectStartSignal = true\n\n\tconstructor(\n\t\tpublic readonly stepName: string,\n\t\tpublic readonly effectKey: string,\n\t\tpublic readonly externalService: string,\n\t) {}\n}\n\nexport class StepSideEffectCompleteSignal {\n\treadonly _isStepSideEffectCompleteSignal = true\n\n\tconstructor(\n\t\tpublic readonly stepName: string,\n\t\tpublic readonly effectKey: string,\n\t\tpublic readonly handle: string | undefined,\n\t\tpublic readonly result: unknown,\n\t) {}\n}\n\n/**\n * Thrown by step.sleep() when the sleep is not yet resolved.\n * The handler aborts; the platform waits and re-dispatches.\n */\nexport class StepSleepSignal {\n\treadonly _isStepSleepSignal = true\n\n\tconstructor(\n\t\tpublic readonly stepName: string,\n\t\tpublic readonly duration: string,\n\t) {}\n}\n\n/**\n * Thrown by step.waitForEvent() when the event has not yet been received.\n * The handler aborts; the platform persists the wait record.\n * When the event arrives (via TriggersClient.publishEvent()), the platform\n * resolves the wait and re-dispatches with the event payload in context.waits.\n */\nexport class StepWaitEventSignal {\n\treadonly _isStepWaitEventSignal = true\n\n\tconstructor(\n\t\tpublic readonly stepName: string,\n\t\tpublic readonly eventName: string,\n\t\tpublic readonly options: {\n\t\t\t/** Timeout duration, e.g. '24h', '7d'. Task fails if event not received in time. */\n\t\t\ttimeout?: string\n\t\t\t/** Optional JSON filter — only resolve if event payload matches */\n\t\t\tfilter?: Record<string, unknown>\n\t\t} = {},\n\t) {}\n}\n\n// ============================================================================\n// Step context factory\n// ============================================================================\n\n/**\n * Build the step proxy for a single handler invocation.\n *\n * @param completedSteps Map of stepName → cached result\n * @param resolvedWaits Map of stepName → wait result (sleep = undefined, event = event payload)\n */\nexport function createStepContext(\n\tcompletedSteps: Map<string, unknown>,\n\tresolvedWaits: Map<string, unknown>,\n\tsideEffectReceipts: Map<string, NativeSideEffectReceipt> = new Map(),\n): NativeStepContext {\n\treturn {\n\t\t/**\n\t\t * Execute a named step.\n\t\t *\n\t\t * - If cached: return the cached value immediately (replay).\n\t\t * - If not cached: execute fn, then throw StepCompleteSignal with the result.\n\t\t */\n\t\tasync run<T>(name: string, fn: () => T | Promise<T>): Promise<T> {\n\t\t\tif (completedSteps.has(name)) {\n\t\t\t\treturn completedSteps.get(name) as T\n\t\t\t}\n\n\t\t\tconst result = await fn()\n\t\t\tthrow new StepCompleteSignal(name, result)\n\t\t},\n\n\t\tasync sideEffect<T>(\n\t\t\tstepName: string,\n\t\t\teffectKey: string,\n\t\t\texternalService: string,\n\t\t\tfn: (\n\t\t\t\tidempotencyKey: string,\n\t\t\t) => NativeSideEffectOutcome<T> | Promise<NativeSideEffectOutcome<T>>,\n\t\t): Promise<T> {\n\t\t\tconst receipt = sideEffectReceipts.get(sideEffectReceiptKey(stepName, effectKey))\n\t\t\tif (!receipt) {\n\t\t\t\tthrow new StepSideEffectStartSignal(stepName, effectKey, externalService)\n\t\t\t}\n\n\t\t\tif (receipt.externalService !== externalService) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Side-effect external service mismatch for ${stepName}/${effectKey}: receipt=${receipt.externalService} handler=${externalService}`,\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (receipt.completedAt) {\n\t\t\t\treturn receipt.result as T\n\t\t\t}\n\n\t\t\tconst outcome = await fn(receipt.idempotencyKey)\n\t\t\tthrow new StepSideEffectCompleteSignal(\n\t\t\t\tstepName,\n\t\t\t\teffectKey,\n\t\t\t\tnormalizeOptionalStepKey(outcome.handle),\n\t\t\t\toutcome.result,\n\t\t\t)\n\t\t},\n\n\t\t/**\n\t\t * Sleep for the given duration.\n\t\t *\n\t\t * - If resolved (platform woke us up): return immediately.\n\t\t * - If not resolved: throw StepSleepSignal to pause execution.\n\t\t */\n\t\tasync sleep(name: string, duration: string): Promise<void> {\n\t\t\tif (resolvedWaits.has(name)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tthrow new StepSleepSignal(name, duration)\n\t\t},\n\n\t\t/**\n\t\t * Pause execution until a named event is published via TriggersClient.publishEvent().\n\t\t *\n\t\t * - If event already arrived (platform re-dispatched with result): return event payload.\n\t\t * - If not yet arrived: throw StepWaitEventSignal to pause execution.\n\t\t *\n\t\t * @param name Step identifier (unique within handler).\n\t\t * @param eventName The event name to listen for (e.g. 'user.approved').\n\t\t * @param options Optional timeout ('24h', '7d') and payload filter.\n\t\t *\n\t\t * @example Human-in-the-loop approval\n\t\t * ```typescript\n\t\t * const approval = await step.waitForEvent('wait-approval', 'order.approved', {\n\t\t * timeout: '48h',\n\t\t * filter: { orderId: payload.orderId },\n\t\t * })\n\t\t * if (!approval) throw new Error('Approval timed out')\n\t\t * await sendConfirmation(approval.approvedBy)\n\t\t * ```\n\t\t */\n\t\tasync waitForEvent<T = unknown>(\n\t\t\tname: string,\n\t\t\teventName: string,\n\t\t\toptions: { timeout?: string; filter?: Record<string, unknown> } = {},\n\t\t): Promise<T | null> {\n\t\t\tif (resolvedWaits.has(name)) {\n\t\t\t\t// Platform resolved the wait — return the event payload (null if timed out)\n\t\t\t\treturn (resolvedWaits.get(name) as T | null) ?? null\n\t\t\t}\n\n\t\t\tthrow new StepWaitEventSignal(name, eventName, options)\n\t\t},\n\t}\n}\n\nfunction normalizeOptionalStepKey(value: string | undefined): string | undefined {\n\tconst trimmed = value?.trim()\n\treturn trimmed ? trimmed.slice(0, 500) : undefined\n}\n\nfunction sideEffectReceiptKey(stepName: string, effectKey: string): string {\n\treturn `${stepName}\\u0000${effectKey}`\n}\n\n// ============================================================================\n// Signature verification\n// ============================================================================\n\n/**\n * Constant-time HMAC-SHA256 signature verification.\n * Accepts both raw hex and 'sha256={hex}' formats.\n */\nexport function verifySignature(body: string, signature: string, secret: string): boolean {\n\ttry {\n\t\tconst hmac = createHmac('sha256', secret).update(body, 'utf8').digest('hex')\n\t\tconst normalised = signature.replace(/^sha256=/, '')\n\n\t\tconst expected = Buffer.from(hmac, 'hex')\n\t\tconst provided = Buffer.from(normalised, 'hex')\n\n\t\tif (expected.length !== provided.length) return false\n\t\treturn timingSafeEqual(expected, provided)\n\t} catch {\n\t\treturn false\n\t}\n}\n\n// ============================================================================\n// Request / response types\n// ============================================================================\n\ninterface DispatchStepEntry {\n\tname: string\n\tresult: unknown\n\tcompletedAt: string\n}\n\ninterface DispatchWaitEntry {\n\tname: string\n\tresolvedAt: string\n\tresult?: unknown\n}\n\ninterface DispatchContext {\n\tattempt: number\n\tsteps: DispatchStepEntry[]\n\twaits: DispatchWaitEntry[]\n\tsideEffects?: NativeSideEffectReceipt[]\n}\n\ninterface DispatchBody {\n\ttaskRunId: string\n\ttaskName: string\n\tpayload: unknown\n\tcontext: DispatchContext\n}\n\n// ============================================================================\n// Handler factory\n// ============================================================================\n\nexport interface TasksHandlerOptions {\n\t/** Platform signing secret. If not set, signature verification is skipped. */\n\tsigningSecret?: string\n}\n\nexport interface TasksHandlerResult {\n\tGET: (req: Request) => Promise<Response>\n\tPOST: (req: Request) => Promise<Response>\n}\n\n/**\n * Create a Next.js-compatible route handler for a list of task definitions.\n *\n * @example\n * ```typescript\n * export const { GET, POST } = createTasksHandler([sendEmail, processOrder])\n * ```\n */\nexport function createTasksHandler(\n\ttaskDefs: NativeTaskDefinition[],\n\toptions: TasksHandlerOptions = {},\n): TasksHandlerResult {\n\tconst taskMap = new Map<string, NativeTaskDefinition>()\n\tfor (const def of taskDefs) {\n\t\ttaskMap.set(def.name, def)\n\t}\n\n\t// GET: health/discovery — returns registered task names\n\tconst GET = async (_req: Request): Promise<Response> => {\n\t\treturn Response.json({\n\t\t\tok: true,\n\t\t\ttasks: Array.from(taskMap.keys()),\n\t\t})\n\t}\n\n\t// POST: dispatch handler\n\tconst POST = async (req: Request): Promise<Response> => {\n\t\t// ------------------------------------------------------------------\n\t\t// 1. Read raw body as text\n\t\t// ------------------------------------------------------------------\n\t\tlet rawBody: string\n\t\ttry {\n\t\t\trawBody = await req.text()\n\t\t} catch {\n\t\t\treturn Response.json(\n\t\t\t\t{ status: 'error', message: 'Failed to read request body' },\n\t\t\t\t{ status: 400 },\n\t\t\t)\n\t\t}\n\n\t\t// ------------------------------------------------------------------\n\t\t// 2. Verify signature if configured\n\t\t// ------------------------------------------------------------------\n\t\tconst signingSecret = options.signingSecret ?? process.env.SYLPHX_SIGNING_SECRET ?? ''\n\n\t\tif (signingSecret) {\n\t\t\tconst signature = req.headers.get('x-sylphx-signature') ?? ''\n\t\t\tif (!signature) {\n\t\t\t\treturn Response.json(\n\t\t\t\t\t{ status: 'error', message: 'Missing X-Sylphx-Signature header' },\n\t\t\t\t\t{ status: 401 },\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (!verifySignature(rawBody, signature, signingSecret)) {\n\t\t\t\treturn Response.json({ status: 'error', message: 'Invalid signature' }, { status: 401 })\n\t\t\t}\n\t\t}\n\n\t\t// ------------------------------------------------------------------\n\t\t// 3. Parse body\n\t\t// ------------------------------------------------------------------\n\t\tlet dispatch: DispatchBody\n\t\ttry {\n\t\t\tdispatch = JSON.parse(rawBody) as DispatchBody\n\t\t} catch {\n\t\t\treturn Response.json(\n\t\t\t\t{ status: 'error', message: 'Request body is not valid JSON' },\n\t\t\t\t{ status: 400 },\n\t\t\t)\n\t\t}\n\n\t\tconst { taskName, payload, context } = dispatch\n\n\t\tif (!taskName || typeof taskName !== 'string') {\n\t\t\treturn Response.json(\n\t\t\t\t{ status: 'error', message: 'Missing or invalid \"taskName\" field' },\n\t\t\t\t{ status: 400 },\n\t\t\t)\n\t\t}\n\n\t\t// ------------------------------------------------------------------\n\t\t// 4. Find task definition\n\t\t// ------------------------------------------------------------------\n\t\tconst taskDef = taskMap.get(taskName)\n\t\tif (!taskDef) {\n\t\t\treturn Response.json(\n\t\t\t\t{\n\t\t\t\t\tstatus: 'error',\n\t\t\t\t\tmessage: `Task \"${taskName}\" not found. Registered tasks: ${Array.from(taskMap.keys()).join(', ')}`,\n\t\t\t\t},\n\t\t\t\t{ status: 404 },\n\t\t\t)\n\t\t}\n\n\t\t// ------------------------------------------------------------------\n\t\t// 5. Build step context from dispatch context\n\t\t// ------------------------------------------------------------------\n\t\tconst completedSteps = new Map<string, unknown>()\n\t\tfor (const step of context?.steps ?? []) {\n\t\t\tcompletedSteps.set(step.name, step.result)\n\t\t}\n\n\t\t// resolvedWaits: stepName → result (sleep=undefined, event=payload, timeout=null)\n\t\tconst resolvedWaits = new Map<string, unknown>()\n\t\tfor (const wait of context?.waits ?? []) {\n\t\t\tresolvedWaits.set(wait.name, wait.result ?? undefined)\n\t\t}\n\n\t\tconst sideEffectReceipts = new Map<string, NativeSideEffectReceipt>()\n\t\tfor (const receipt of context?.sideEffects ?? []) {\n\t\t\tsideEffectReceipts.set(sideEffectReceiptKey(receipt.stepName, receipt.effectKey), receipt)\n\t\t}\n\n\t\tconst stepCtx = createStepContext(completedSteps, resolvedWaits, sideEffectReceipts)\n\n\t\t// ------------------------------------------------------------------\n\t\t// 6. Invoke the handler\n\t\t// ------------------------------------------------------------------\n\t\ttry {\n\t\t\tconst result = await taskDef.handler(payload, { step: stepCtx })\n\n\t\t\t// Handler returned normally → task is complete\n\t\t\treturn Response.json({ status: 'complete', result })\n\t\t} catch (err: unknown) {\n\t\t\t// ------------------------------------------------------------------\n\t\t\t// 7a. Step completed — save result and re-dispatch\n\t\t\t// ------------------------------------------------------------------\n\t\t\tif (err instanceof StepCompleteSignal || (err as StepCompleteSignal)?._isStepCompleteSignal) {\n\t\t\t\tconst signal = err as StepCompleteSignal\n\t\t\t\treturn Response.json({\n\t\t\t\t\tstatus: 'step_complete',\n\t\t\t\t\tstepName: signal.stepName,\n\t\t\t\t\tresult: signal.result,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\terr instanceof StepSideEffectStartSignal ||\n\t\t\t\t(err as StepSideEffectStartSignal)?._isStepSideEffectStartSignal\n\t\t\t) {\n\t\t\t\tconst signal = err as StepSideEffectStartSignal\n\t\t\t\treturn Response.json({\n\t\t\t\t\tstatus: 'side_effect_start',\n\t\t\t\t\tstepName: signal.stepName,\n\t\t\t\t\teffectKey: signal.effectKey,\n\t\t\t\t\texternalService: signal.externalService,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\terr instanceof StepSideEffectCompleteSignal ||\n\t\t\t\t(err as StepSideEffectCompleteSignal)?._isStepSideEffectCompleteSignal\n\t\t\t) {\n\t\t\t\tconst signal = err as StepSideEffectCompleteSignal\n\t\t\t\treturn Response.json({\n\t\t\t\t\tstatus: 'side_effect_complete',\n\t\t\t\t\tstepName: signal.stepName,\n\t\t\t\t\teffectKey: signal.effectKey,\n\t\t\t\t\thandle: signal.handle ?? null,\n\t\t\t\t\tresult: signal.result,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// ------------------------------------------------------------------\n\t\t\t// 7b. Step sleep — create wait record\n\t\t\t// ------------------------------------------------------------------\n\t\t\tif (err instanceof StepSleepSignal || (err as StepSleepSignal)?._isStepSleepSignal) {\n\t\t\t\tconst signal = err as StepSleepSignal\n\t\t\t\treturn Response.json({\n\t\t\t\t\tstatus: 'step_sleep',\n\t\t\t\t\tstepName: signal.stepName,\n\t\t\t\t\tduration: signal.duration,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// ------------------------------------------------------------------\n\t\t\t// 7c. Step waitForEvent — suspend until named event arrives\n\t\t\t// ------------------------------------------------------------------\n\t\t\tif (\n\t\t\t\terr instanceof StepWaitEventSignal ||\n\t\t\t\t(err as StepWaitEventSignal)?._isStepWaitEventSignal\n\t\t\t) {\n\t\t\t\tconst signal = err as StepWaitEventSignal\n\t\t\t\treturn Response.json({\n\t\t\t\t\tstatus: 'step_wait_event',\n\t\t\t\t\tstepName: signal.stepName,\n\t\t\t\t\teventName: signal.eventName,\n\t\t\t\t\ttimeout: signal.options.timeout ?? null,\n\t\t\t\t\tfilter: signal.options.filter ?? null,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// ------------------------------------------------------------------\n\t\t\t// 7d. Unexpected error\n\t\t\t// ------------------------------------------------------------------\n\t\t\tconst message = err instanceof Error ? err.message : String(err)\n\t\t\tconsole.error(`[sylphx/tasks] Task \"${taskName}\" threw an error:`, err)\n\t\t\treturn Response.json(\n\t\t\t\t{\n\t\t\t\t\tstatus: 'error',\n\t\t\t\t\tmessage,\n\t\t\t\t\tretriable: true,\n\t\t\t\t},\n\t\t\t\t{ status: 500 },\n\t\t\t)\n\t\t}\n\t}\n\n\treturn { GET, POST }\n}\n","/**\n * serve()\n *\n * Create a Web API-compatible route handler for a set of task definitions.\n * Supports Next.js App Router, Hono, and any Web API Request/Response handler.\n *\n * serve() wires up:\n * - GET → health check, returns registered task IDs + trigger sync status\n * - POST → dispatch handler (receives from platform, routes to task run fn)\n *\n * On startup (first GET or POST), serve() automatically syncs all inline triggers\n * (task({ trigger: { cron: '...' } })) to the platform via TriggersClient.\n * This is idempotent — uses idempotencyKey = `task:{taskId}:{triggerType}:{value}`.\n *\n * Only function-mode tasks (no machine config) register HTTP handlers here.\n * Job-mode tasks are dispatched directly by the platform, but their\n * inline triggers are still synced.\n *\n * @example Next.js App Router\n * ```typescript\n * // app/api/tasks/route.ts\n * import { serve } from '@sylphx/sdk/tasks'\n * import { sendEmail, dailyCleanup } from '@/tasks'\n *\n * export const { GET, POST } = serve({ tasks: [sendEmail, dailyCleanup] })\n * ```\n *\n * @example Inline cron trigger\n * ```typescript\n * export const dailyCleanup = task({\n * id: 'daily-cleanup',\n * trigger: { cron: '0 2 * * *' },\n * run: async () => { ... },\n * })\n * // No TriggersClient.create() call needed — serve() registers it automatically.\n * ```\n */\n\nimport { createServerClient } from '../../config'\nimport { TriggersClient } from '../triggers'\nimport { resolveTaskServerConnectionUrl } from './connection'\nimport { createTasksHandler, type TasksHandlerOptions } from './handler'\nimport type { TaskHandle } from './task'\nimport type { NativeStepContext, NativeTaskDefinition } from './types'\n\nexport interface ServeOptions {\n\t/** Task handles to serve */\n\ttasks: TaskHandle<unknown, unknown>[]\n\t/** Platform signing secret for verifying dispatches. Defaults to SYLPHX_SIGNING_SECRET env var. */\n\tsigningSecret?: string\n\t/**\n\t * Server connection URL for trigger registration.\n\t * Defaults to SYLPHX_SECRET_URL env var.\n\t * Only required if any tasks have inline trigger config.\n\t */\n\tconnectionUrl?: string\n}\n\nexport interface ServeResult {\n\tGET: (req: Request) => Promise<Response>\n\tPOST: (req: Request) => Promise<Response>\n}\n\n// ── Trigger sync (idempotent) ────────────────────────────────────────────────\n\nlet triggerSyncDone = false\nlet triggerSyncPromise: Promise<void> | null = null\n\nasync function syncTriggers(\n\ttasks: TaskHandle<unknown, unknown>[],\n\toptions: ServeOptions,\n): Promise<void> {\n\tconst connectionUrl = resolveTaskServerConnectionUrl({\n\t\texplicitConnectionUrl: options.connectionUrl,\n\t})\n\n\tif (!connectionUrl) {\n\t\t// No credentials — skip trigger sync (local dev, tests)\n\t\treturn\n\t}\n\n\tconst tasksWithTriggers = tasks.filter((t) => t._trigger)\n\tif (tasksWithTriggers.length === 0) return\n\n\tconst config = createServerClient(connectionUrl)\n\n\tconst results = await Promise.allSettled(\n\t\ttasksWithTriggers.flatMap((t) => {\n\t\t\tconst promises: Promise<unknown>[] = []\n\n\t\t\tif (t._trigger?.cron) {\n\t\t\t\tpromises.push(\n\t\t\t\t\tTriggersClient.create(config, {\n\t\t\t\t\t\tname: `${t.id}:cron`,\n\t\t\t\t\t\tsource: { type: 'cron', expression: t._trigger.cron },\n\t\t\t\t\t\ttarget: { type: 'task', taskName: t.id },\n\t\t\t\t\t\tidempotencyKey: `task:${t.id}:cron:${t._trigger.cron}`,\n\t\t\t\t\t}).catch((err) => {\n\t\t\t\t\t\t// 409 Conflict = already exists (idempotent) — not an error\n\t\t\t\t\t\tif (err?.status === 409 || err?.message?.includes('already exists')) return\n\t\t\t\t\t\tthrow err\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (t._trigger?.event) {\n\t\t\t\tpromises.push(\n\t\t\t\t\tTriggersClient.create(config, {\n\t\t\t\t\t\tname: `${t.id}:event:${t._trigger.event}`,\n\t\t\t\t\t\tsource: { type: 'event', eventName: t._trigger.event },\n\t\t\t\t\t\ttarget: { type: 'task', taskName: t.id },\n\t\t\t\t\t\tidempotencyKey: `task:${t.id}:event:${t._trigger.event}`,\n\t\t\t\t\t}).catch((err) => {\n\t\t\t\t\t\tif (err?.status === 409 || err?.message?.includes('already exists')) return\n\t\t\t\t\t\tthrow err\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t}\n\n\t\t\treturn promises\n\t\t}),\n\t)\n\n\t// Log failures but don't throw — trigger sync failures must not break request handling\n\tfor (const result of results) {\n\t\tif (result.status === 'rejected') {\n\t\t\tconsole.warn('[sylphx/tasks] Warning: trigger sync failed', result.reason)\n\t\t}\n\t}\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Create a route handler that serves task definitions.\n *\n * Auto-syncs inline triggers (task({ trigger: { cron: '...' } })) on first request.\n * Task sync is idempotent and non-blocking — handler responds even if sync is in progress.\n */\nexport function serve(options: ServeOptions): ServeResult {\n\t// Only function-mode tasks have HTTP handlers\n\tconst functionModeTasks = options.tasks.filter((t) => !t._machine && t._run != null)\n\n\tconst defs: NativeTaskDefinition[] = functionModeTasks.map((t) => ({\n\t\tname: t.id,\n\t\thandler: t._run as unknown as (\n\t\t\tpayload: unknown,\n\t\t\tctx: { step: NativeStepContext },\n\t\t) => Promise<unknown>,\n\t}))\n\n\tconst handlerOptions: TasksHandlerOptions = {\n\t\tsigningSecret: options.signingSecret,\n\t}\n\n\tconst { GET: baseGET, POST: basePOST } = createTasksHandler(defs, handlerOptions)\n\n\t// Lazy trigger sync — fires on first request, once per process lifetime\n\tfunction ensureTriggerSync(): void {\n\t\tif (triggerSyncDone || triggerSyncPromise) return\n\t\ttriggerSyncPromise = syncTriggers(options.tasks, options)\n\t\t\t.then(() => {\n\t\t\t\ttriggerSyncDone = true\n\t\t\t})\n\t\t\t.catch((err) => {\n\t\t\t\t// Reset so it retries on next request\n\t\t\t\ttriggerSyncPromise = null\n\t\t\t\tconsole.warn('[sylphx/tasks] Trigger sync error:', err)\n\t\t\t})\n\t}\n\n\treturn {\n\t\tasync GET(req: Request): Promise<Response> {\n\t\t\tensureTriggerSync()\n\t\t\treturn baseGET(req)\n\t\t},\n\t\tasync POST(req: Request): Promise<Response> {\n\t\t\tensureTriggerSync()\n\t\t\treturn basePOST(req)\n\t\t},\n\t}\n}\n","/**\n * task() / taskStub()\n *\n * Core compute primitives — Trigger.dev v4 inspired.\n *\n * task() — define a TypeScript task handler that gets a typed TaskHandle\n * taskStub() — typed stub for cross-language tasks (Python, etc.)\n *\n * Both return a TaskHandle<TPayload, TResult> with:\n * .trigger(payload) → fire-and-forget, returns RunHandle\n * .triggerAndWait(payload) → dispatch + poll until complete\n * .batchTrigger(payloads) → parallel dispatch N runs\n *\n * RunHandle exposes waitForCompletion() and cancel().\n *\n * Config is auto-resolved from SYLPHX_SECRET_URL or passed explicitly via\n * TriggerOptions.config.\n *\n * @example TypeScript task (function mode — HTTP callback in running service)\n * ```typescript\n * export const sendEmail = task({\n * id: 'send-email',\n * run: async ({ to, subject }, { step }) => {\n * const validated = await step.run('validate', () => validate(to))\n * await step.sleep('cooldown', '5 minutes')\n * return step.run('send', () => mailer.send(validated, subject))\n * }\n * })\n *\n * // From anywhere — fully type-safe\n * const handle = await sendEmail.trigger({ to: 'kyle@...', subject: 'Hi' })\n * const result = await handle.waitForCompletion()\n * ```\n *\n * @example TypeScript task (job mode — isolated runtime, managed machine)\n * ```typescript\n * export const processVideo = task({\n * id: 'process-video',\n * machine: 'large',\n * run: async ({ videoUrl }) => { ... }\n * })\n * ```\n *\n * @example Cross-language stub (Python ML training)\n * ```typescript\n * // Register in sylphx.toml, then stub here for type safety:\n * export const trainFold = taskStub<\n * { fold: number; n_trials?: number },\n * { best_icir: number }\n * >('train-fold')\n *\n * // Dispatch 5 parallel folds\n * const handles = await trainFold.batchTrigger(\n * Array.from({ length: 5 }, (_, i) => ({ fold: i, n_trials: 200 }))\n * )\n * await Promise.all(handles.runs.map(h => h.waitForCompletion()))\n * ```\n */\n\nimport type { MachineSize } from '@sylphx/contract'\nimport type { SylphxConfig } from '../../config'\nimport { callApi, createServerClient } from '../../config'\nimport { requireTaskServerConnectionUrl } from './connection'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type TaskMachineSize = MachineSize\n\nexport interface TaskRunContext {\n\tstep: StepContext\n\t/** Current attempt number (starts at 1) */\n\tattempt: number\n}\n\nexport interface StepContext {\n\t/** Execute a named step. Replays from cache if already completed (durable). */\n\trun<T>(id: string, fn: () => T | Promise<T>): Promise<T>\n\t/** Sleep for a duration. Replays instantly if already resolved. */\n\tsleep(id: string, duration: string): Promise<void>\n}\n\nexport interface TriggerOptions {\n\t/** Override auto-resolved config (defaults to SYLPHX_SECRET_URL env var) */\n\tconfig?: SylphxConfig\n\t/** Deduplication key — same key within 24h returns existing run */\n\tidempotencyKey?: string\n\t/** Delay dispatch, e.g. '5m', '1h' */\n\tdelay?: string\n\t/** Dispatch at specific time */\n\tscheduledFor?: Date\n\t/** Override max retry attempts */\n\tmaxAttempts?: number\n\t/** Queue name override */\n\tqueue?: string\n}\n\nexport interface RunHandle<TResult = unknown> {\n\t/** Task run UUID */\n\tid: string\n\t/** Current status at time of trigger */\n\tstatus: string\n\t/**\n\t * Poll until the run reaches a terminal state (completed/failed/cancelled).\n\t * Throws if failed or timed out.\n\t */\n\twaitForCompletion(options?: { timeoutMs?: number }): Promise<TResult>\n\t/**\n\t * Record durable cancellation for this run. Pending/running/waiting/failed\n\t * runs become terminal and job-mode cleanup is retried by Platform.\n\t */\n\tcancel(): Promise<boolean>\n}\n\nexport interface BatchHandle<TResult = unknown> {\n\truns: RunHandle<TResult>[]\n}\n\n/** Inline trigger configuration on a task definition (ADR-040) */\nexport interface TaskTriggerConfig {\n\t/**\n\t * Cron schedule — automatically fires this task on the given schedule.\n\t * Standard 5-field cron expression: '0 2 * * *' (every day at 2am)\n\t * The platform registers this trigger on deploy via serve().\n\t */\n\tcron?: string\n\t/**\n\t * Event name — automatically fires this task when the named event is published.\n\t * e.g. 'user.signup', 'order.created'\n\t * Future: event triggers are not yet dispatched by the platform.\n\t */\n\tevent?: string\n}\n\nexport interface TaskConfig<TPayload, TResult> {\n\t/** Stable task identifier — must not change across deploys */\n\tid: string\n\t/**\n\t * Automatic trigger configuration (ADR-040).\n\t * If set, the platform registers this trigger when serve() is called.\n\t * trigger.cron → cron schedule fires task automatically\n\t * trigger.event → event fires task automatically\n\t */\n\ttrigger?: TaskTriggerConfig\n\t/**\n\t * Managed machine size. If set → task runs in an isolated runtime (job mode).\n\t * If absent → task runs as an HTTP callback in the running service (function mode).\n\t */\n\tmachine?: TaskMachineSize\n\t/** Queue config */\n\tqueue?: { name?: string; concurrency?: number }\n\t/** Retry policy */\n\tretry?: { maxAttempts?: number; backoff?: 'fixed' | 'exponential' }\n\t/** Timeout in seconds (default: 300 for function mode, 86400 for job mode) */\n\ttimeout?: number\n\t/** The task handler. In function mode: runs via HTTP dispatch. In job mode: runs in an isolated runtime. */\n\trun: (payload: TPayload, ctx: TaskRunContext) => Promise<TResult>\n}\n\nexport interface TaskHandle<TPayload = unknown, TResult = unknown> {\n\t/** The stable task ID */\n\treadonly id: string\n\t/** Trigger config if task has an automatic trigger (cron/event) */\n\treadonly _trigger?: TaskTriggerConfig\n\t/** Managed machine size if job-mode task (undefined for function-mode or stubs) */\n\treadonly _machine?: TaskMachineSize\n\t/**\n\t * The run function — used internally by serve() to register the handler.\n\t * undefined for taskStub (cross-language).\n\t */\n\treadonly _run?: (payload: TPayload, ctx: TaskRunContext) => Promise<TResult>\n\n\t/** Dispatch the task. Returns immediately with a RunHandle. */\n\ttrigger(payload: TPayload, options?: TriggerOptions): Promise<RunHandle<TResult>>\n\n\t/** Dispatch and wait for result. Convenience wrapper over trigger + waitForCompletion. */\n\ttriggerAndWait(payload: TPayload, options?: TriggerOptions): Promise<TResult>\n\n\t/** Dispatch N runs in parallel. Returns handles for all. */\n\tbatchTrigger(payloads: TPayload[], options?: TriggerOptions): Promise<BatchHandle<TResult>>\n}\n\n// ============================================================================\n// Config resolution\n// ============================================================================\n\nfunction resolveConfig(options?: TriggerOptions): SylphxConfig {\n\tif (options?.config) return options.config\n\tconst connectionUrl = requireTaskServerConnectionUrl()\n\treturn createServerClient(connectionUrl)\n}\n\n// ============================================================================\n// Polling\n// ============================================================================\n\nasync function pollUntilComplete<TResult>(\n\tconfig: SylphxConfig,\n\ttaskRunId: string,\n\ttimeoutMs: number,\n): Promise<TResult> {\n\tconst deadline = Date.now() + timeoutMs\n\tlet delay = 500\n\twhile (Date.now() < deadline) {\n\t\tconst run = await callApi<{ status: string; result?: TResult; error?: string }>(\n\t\t\tconfig,\n\t\t\t`/tasks/${taskRunId}`,\n\t\t\t{ method: 'GET' },\n\t\t)\n\t\tif (run.status === 'completed') return run.result as TResult\n\t\tif (run.status === 'failed' || run.status === 'cancelled') {\n\t\t\tthrow new Error(run.error ?? `Task run ${taskRunId} ${run.status}`)\n\t\t}\n\t\tawait new Promise<void>((r) => setTimeout(r, delay))\n\t\tdelay = Math.min(delay * 1.5, 5_000)\n\t}\n\tthrow new Error(`Task run ${taskRunId} timed out after ${timeoutMs}ms`)\n}\n\n// ============================================================================\n// Internal trigger\n// ============================================================================\n\nasync function dispatchTask<TPayload, TResult>(\n\tid: string,\n\tpayload: TPayload,\n\tmachine: TaskMachineSize | undefined,\n\toptions: TriggerOptions | undefined,\n): Promise<RunHandle<TResult>> {\n\tconst config = resolveConfig(options)\n\tconst body: Record<string, unknown> = {\n\t\ttaskName: id,\n\t\tpayload,\n\t}\n\tif (options?.idempotencyKey) body.idempotencyKey = options.idempotencyKey\n\tif (options?.delay) body.delay = options.delay\n\tif (options?.scheduledFor) body.scheduledFor = options.scheduledFor.toISOString()\n\tif (options?.maxAttempts) body.maxAttempts = options.maxAttempts\n\tif (options?.queue) body.queue = options.queue\n\tif (machine) body.machine = machine\n\n\tconst result = await callApi<{ taskRunId: string; status: string }>(config, '/tasks/trigger', {\n\t\tmethod: 'POST',\n\t\tbody,\n\t})\n\n\tconst runId = result.taskRunId\n\tconst defaultTimeoutMs = machine ? 24 * 3600 * 1000 : 300_000\n\n\treturn {\n\t\tid: runId,\n\t\tstatus: result.status,\n\t\twaitForCompletion(waitOptions) {\n\t\t\treturn pollUntilComplete<TResult>(config, runId, waitOptions?.timeoutMs ?? defaultTimeoutMs)\n\t\t},\n\t\tasync cancel() {\n\t\t\tconst cancelled = await callApi<{ success: boolean }>(config, `/tasks/${runId}/cancel`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t})\n\t\t\treturn cancelled.success\n\t\t},\n\t}\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Define a typed task.\n *\n * Returns a TaskHandle<TPayload, TResult> that can be used to trigger the task\n * from anywhere (same service or different service) with full type safety.\n *\n * The returned handle's _run function is used by serve() to register the\n * HTTP handler for function-mode tasks.\n */\nexport function task<TPayload = unknown, TResult = unknown>(\n\tconfig: TaskConfig<TPayload, TResult>,\n): TaskHandle<TPayload, TResult> {\n\treturn {\n\t\tid: config.id,\n\t\t_trigger: config.trigger,\n\t\t_machine: config.machine,\n\t\t_run: config.run,\n\n\t\tasync trigger(payload, options) {\n\t\t\treturn dispatchTask<TPayload, TResult>(config.id, payload, config.machine, options)\n\t\t},\n\n\t\tasync triggerAndWait(payload, options) {\n\t\t\tconst handle = await dispatchTask<TPayload, TResult>(\n\t\t\t\tconfig.id,\n\t\t\t\tpayload,\n\t\t\t\tconfig.machine,\n\t\t\t\toptions,\n\t\t\t)\n\t\t\treturn handle.waitForCompletion()\n\t\t},\n\n\t\tasync batchTrigger(payloads, options) {\n\t\t\tconst handles = await Promise.all(\n\t\t\t\tpayloads.map((p) => dispatchTask<TPayload, TResult>(config.id, p, config.machine, options)),\n\t\t\t)\n\t\t\treturn { runs: handles }\n\t\t},\n\t}\n}\n\n/**\n * Create a typed stub for a cross-language task (e.g. Python ML worker).\n *\n * The task must be registered separately via sylphx.toml manifest.\n * The stub provides type safety for the trigger call without requiring\n * a TypeScript handler.\n *\n * @example\n * ```typescript\n * export const trainFold = taskStub<\n * { fold: number; n_trials?: number },\n * { best_icir: number }\n * >('train-fold')\n *\n * const result = await trainFold.triggerAndWait({ fold: 0 })\n * console.log(result.best_icir) // typed!\n * ```\n */\nexport function taskStub<TPayload = unknown, TResult = unknown>(\n\tid: string,\n): TaskHandle<TPayload, TResult> {\n\treturn {\n\t\tid,\n\t\t_machine: undefined,\n\t\t_run: undefined,\n\n\t\tasync trigger(payload, options) {\n\t\t\treturn dispatchTask<TPayload, TResult>(id, payload, undefined, options)\n\t\t},\n\n\t\tasync triggerAndWait(payload, options) {\n\t\t\tconst handle = await dispatchTask<TPayload, TResult>(id, payload, undefined, options)\n\t\t\treturn handle.waitForCompletion()\n\t\t},\n\n\t\tasync batchTrigger(payloads, options) {\n\t\t\tconst handles = await Promise.all(\n\t\t\t\tpayloads.map((p) => dispatchTask<TPayload, TResult>(id, p, undefined, options)),\n\t\t\t)\n\t\t\treturn { runs: handles }\n\t\t},\n\t}\n}\n","/**\n * Task API Functions\n *\n * Standalone functions for scheduling tasks and managing crons via the Sylphx API.\n * These are backward-compat exports preserved from the pre-refactor tasks.ts.\n */\n\nimport type {\n\tDurableWorkGetTaskRunResponse,\n\tDurableWorkTaskDlqEntry,\n\tDurableWorkTaskDlqListResponse,\n\tDurableWorkTaskReplayRequestBody,\n\tDurableWorkTaskReplayResponse,\n\tDurableWorkTaskRunStep,\n} from '@sylphx/contract'\nimport { callApi, type SylphxConfig } from '../../config'\nimport type { CronSchedule } from './types'\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface TaskInput {\n\t/** Callback URL to call when task executes */\n\tcallbackUrl: string\n\t/** Task name/type */\n\tname?: string\n\t/** Task type for categorization */\n\ttype?: string\n\t/** Task payload sent to callback */\n\tpayload?: Record<string, unknown>\n\t/** HTTP method for callback (default: POST) */\n\tmethod?: 'GET' | 'POST' | 'PUT' | 'DELETE'\n\t/** Additional headers for callback */\n\theaders?: Record<string, string>\n\t/** Delay before executing (in seconds, max 604800 = 7 days) */\n\tdelay?: number\n\t/** Schedule for later (ISO timestamp) */\n\tscheduledFor?: string\n\t/** Number of retries on failure (0-5, default: 3) */\n\tretries?: number\n\t/** Request timeout in seconds (1-300, default: 30) */\n\ttimeout?: number\n\t/**\n\t * Idempotency key for safe retries (Stripe/Inngest pattern).\n\t *\n\t * When provided, prevents duplicate task execution if the same\n\t * key is used within a 24-hour window.\n\t */\n\tidempotencyKey?: string\n}\n\nexport interface TaskResult {\n\t/** Task ID */\n\ttaskId: string\n\t/** Scheduled execution time */\n\tscheduledFor?: string\n}\n\nexport interface TaskStatus {\n\tid: string\n\tname?: string\n\tstatus: 'pending' | 'queued' | 'running' | 'completed' | 'failed' | 'cancelled'\n\tpayload?: Record<string, unknown>\n\tresult?: unknown\n\terror?: string\n\tcreatedAt: string\n\tqueuedAt?: string\n\tstartedAt?: string\n\tcompletedAt?: string\n}\n\nexport type TaskRunDlqEntry = DurableWorkTaskDlqEntry\nexport type TaskRunDlqListResponse = DurableWorkTaskDlqListResponse\nexport type TaskRunReplayInput = DurableWorkTaskReplayRequestBody\nexport type TaskRunReplayResponse = DurableWorkTaskReplayResponse\n\nexport interface ListTaskRunDlqOptions {\n\t/** Filter DLQ entries to a single task name. */\n\ttaskName?: string\n\t/** Page size. Platform caps this at 100. */\n\tlimit?: number\n\t/** Page offset. */\n\toffset?: number\n}\n\nexport interface CronInput {\n\t/** Callback URL to call on each cron trigger */\n\tcallbackUrl: string\n\t/** Cron expression (e.g., '0 0 * * *' for daily at midnight) */\n\tcron: string\n\t/** Task name (required, max 200 chars) */\n\tname: string\n\t/** Task type for categorization */\n\ttype?: string\n\t/** Task payload sent to callback */\n\tpayload?: Record<string, unknown>\n\t/** HTTP method for callback (default: POST) */\n\tmethod?: 'GET' | 'POST' | 'PUT' | 'DELETE'\n\t/** Additional headers for callback */\n\theaders?: Record<string, string>\n\t/** Number of retries on failure (0-5, default: 3) */\n\tretries?: number\n\t/** Start in paused state */\n\tpaused?: boolean\n\t/**\n\t * Idempotency key for safe cron creation.\n\t *\n\t * When provided, prevents duplicate cron schedule creation if\n\t * the same key is used.\n\t */\n\tidempotencyKey?: string\n}\n\n// ============================================================================\n// Functions\n// ============================================================================\n\n/**\n * Schedule a one-time task for execution\n */\nexport async function scheduleTask(config: SylphxConfig, input: TaskInput): Promise<TaskResult> {\n\treturn callApi<TaskResult>(config, '/tasks/schedule', {\n\t\tmethod: 'POST',\n\t\tbody: input,\n\t})\n}\n\n/**\n * Get a task's status by ID\n */\nexport async function getTask(config: SylphxConfig, taskId: string): Promise<TaskStatus> {\n\treturn callApi<TaskStatus>(config, `/tasks/${taskId}`, { method: 'GET' })\n}\n\n/** The durable step ledger entry surfaced by `getTaskRun`. */\nexport type TaskRunStep = DurableWorkTaskRunStep\n/** The full durable task-run view surfaced by `getTaskRun`. */\nexport type TaskRunDetail = DurableWorkGetTaskRunResponse\n\n/**\n * Get the full durable view of a task run, including the step ledger.\n *\n * Each step carries an `executorToken` — the opaque-but-stable identity of the\n * worker that materialized it. The token changes across a pod-kill resume, so\n * comparing executor tokens across steps is the evidence that a run resumed on\n * a different worker (durable HA). `status` reads `executed` for every recorded\n * step (a step is persisted once, on the dispatch that executed it; later\n * dispatches replay it from cache and record nothing). The platform never\n * returns step result payloads — only identity, executor, and timing.\n */\nexport async function getTaskRun(config: SylphxConfig, runId: string): Promise<TaskRunDetail> {\n\treturn callApi<TaskRunDetail>(config, `/tasks/${runId}`, { method: 'GET' })\n}\n\n/**\n * Cancel a pending, running, waiting, or failed task run.\n */\nexport async function cancelTask(config: SylphxConfig, taskId: string): Promise<boolean> {\n\tconst result = await callApi<{ success: boolean }>(config, `/tasks/${taskId}/cancel`, {\n\t\tmethod: 'POST',\n\t})\n\treturn result.success\n}\n\n/**\n * List terminal failed task runs eligible for customer-safe replay.\n */\nexport async function listTaskRunDlq(\n\tconfig: SylphxConfig,\n\toptions?: ListTaskRunDlqOptions,\n): Promise<TaskRunDlqListResponse> {\n\treturn callApi<TaskRunDlqListResponse>(config, '/tasks/dlq', {\n\t\tmethod: 'GET',\n\t\tquery: options as Record<string, string | number | undefined> | undefined,\n\t})\n}\n\n/**\n * Replay a terminal failed task run with an explicit idempotency key.\n */\nexport async function replayTaskRun(\n\tconfig: SylphxConfig,\n\ttaskId: string,\n\tinput: TaskRunReplayInput,\n): Promise<TaskRunReplayResponse> {\n\treturn callApi<TaskRunReplayResponse>(config, `/tasks/${taskId}/replay`, {\n\t\tmethod: 'POST',\n\t\tbody: input,\n\t})\n}\n\n/**\n * List tasks with optional filters\n */\nexport async function listTasks(\n\tconfig: SylphxConfig,\n\toptions?: { status?: TaskStatus['status']; limit?: number; offset?: number },\n): Promise<{ tasks: TaskStatus[]; total: number }> {\n\treturn callApi(config, '/tasks', {\n\t\tmethod: 'GET',\n\t\tquery: options as Record<string, string | number | undefined>,\n\t})\n}\n\n/**\n * Create a recurring cron task\n */\nexport async function createCron(config: SylphxConfig, input: CronInput): Promise<CronSchedule> {\n\treturn callApi<CronSchedule>(config, '/tasks/cron', {\n\t\tmethod: 'POST',\n\t\tbody: input,\n\t})\n}\n\n/**\n * Pause a cron schedule\n */\nexport async function pauseCron(config: SylphxConfig, scheduleId: string): Promise<boolean> {\n\tconst result = await callApi<{ success: boolean }>(config, `/tasks/cron/${scheduleId}/pause`, {\n\t\tmethod: 'POST',\n\t})\n\treturn result.success\n}\n\n/**\n * Resume a cron schedule\n */\nexport async function resumeCron(config: SylphxConfig, scheduleId: string): Promise<boolean> {\n\tconst result = await callApi<{ success: boolean }>(config, `/tasks/cron/${scheduleId}/resume`, {\n\t\tmethod: 'POST',\n\t})\n\treturn result.success\n}\n\n/**\n * Delete a cron schedule\n */\nexport async function deleteCron(config: SylphxConfig, scheduleId: string): Promise<boolean> {\n\tconst result = await callApi<{ success: boolean }>(config, `/tasks/cron/${scheduleId}`, {\n\t\tmethod: 'DELETE',\n\t})\n\treturn result.success\n}\n","/**\n * Tasks Types\n *\n * Type definitions for background job scheduling and workflows.\n * Supports durable execution, retries, and workflow composition.\n */\n\nimport {\n\tBASE_RETRY_DELAY_MS,\n\tDEFAULT_RETRY_DELAYS_MS,\n\tJOB_DEFAULT_TIMEOUT_MS,\n\tJOBS_DLQ_MAX_AGE_MS,\n\tMAX_RETRY_DELAY_MS,\n} from '../../constants'\n\n// ==========================================\n// Core Types\n// ==========================================\n\n/** Task status */\nexport type TaskStatus =\n\t| 'pending'\n\t| 'scheduled'\n\t| 'running'\n\t| 'completed'\n\t| 'failed'\n\t| 'cancelled'\n\t| 'retrying'\n\t| 'dead' // In DLQ\n\n/** Job priority */\nexport type TaskPriority = 'low' | 'normal' | 'high' | 'critical'\n\n/** Job payload - must be JSON serializable */\nexport type TaskPayload = Record<string, unknown>\n\n/** Job result */\nexport type TaskResult = unknown\n\n// ==========================================\n// Job Definition\n// ==========================================\n\n/** Job definition */\nexport interface TaskDefinition<TPayload extends TaskPayload = TaskPayload, TResult = TaskResult> {\n\t/** Unique job type identifier */\n\ttype: string\n\t/** Human-readable name */\n\tname?: string\n\t/** Description */\n\tdescription?: string\n\t/** Job handler (server-side) */\n\thandler?: (payload: TPayload, context: TaskContext) => Promise<TResult>\n\t/** Default options */\n\tdefaults?: TaskOptions\n\t/** Validation schema */\n\tvalidate?: (payload: TPayload) => boolean | string\n}\n\n/** Job options */\nexport interface TaskOptions {\n\t/** Priority */\n\tpriority?: TaskPriority\n\t/** Max retry attempts */\n\tmaxRetries?: number\n\t/** Retry delay strategy */\n\tretryDelay?: RetryDelayStrategy\n\t/** Timeout in ms */\n\ttimeout?: number\n\t/** Delay execution */\n\tdelay?: number | Date\n\t/** Cron schedule */\n\tcron?: string\n\t/** Unique job ID (for deduplication) */\n\tuniqueId?: string\n\t/** Unique key TTL in ms (how long to prevent duplicates) */\n\tuniqueTtl?: number\n\t/** Dead letter queue options */\n\tdlq?: DLQOptions\n\t/** Tags for filtering */\n\ttags?: string[]\n\t/** Custom metadata */\n\tmetadata?: Record<string, unknown>\n}\n\n/** Retry delay strategy */\nexport type RetryDelayStrategy =\n\t| { type: 'fixed'; delay: number }\n\t| { type: 'exponential'; base: number; maxDelay?: number }\n\t| { type: 'linear'; initial: number; increment: number; maxDelay?: number }\n\t| { type: 'custom'; delays: number[] }\n\n/** DLQ options */\nexport interface DLQOptions {\n\t/** Enable DLQ */\n\tenabled?: boolean\n\t/** Max age before auto-discard (ms) */\n\tmaxAge?: number\n\t/** Auto-retry from DLQ */\n\tautoRetry?: boolean\n\t/** Auto-retry interval (ms) */\n\tautoRetryInterval?: number\n\t/** Max auto-retry attempts from DLQ */\n\tmaxAutoRetries?: number\n}\n\n// ==========================================\n// Job Instance\n// ==========================================\n\n/** Job instance */\nexport interface TaskInstance<TPayload extends TaskPayload = TaskPayload, TResult = TaskResult> {\n\t/** Unique job ID */\n\tid: string\n\t/** Job type */\n\ttype: string\n\t/** Job payload */\n\tpayload: TPayload\n\t/** Current status */\n\tstatus: TaskStatus\n\t/** Priority */\n\tpriority: TaskPriority\n\t/** Created timestamp */\n\tcreatedAt: number\n\t/** Scheduled execution time */\n\tscheduledAt?: number\n\t/** Started timestamp */\n\tstartedAt?: number\n\t/** Completed timestamp */\n\tcompletedAt?: number\n\t/** Current attempt number */\n\tattempt: number\n\t/** Max retry attempts */\n\tmaxRetries: number\n\t/** Job result (if completed) */\n\tresult?: TResult\n\t/** Error message (if failed) */\n\terror?: string\n\t/** Error stack trace */\n\terrorStack?: string\n\t/** Progress (0-100) */\n\tprogress?: number\n\t/** Progress message */\n\tprogressMessage?: string\n\t/** Tags */\n\ttags?: string[]\n\t/** Custom metadata */\n\tmetadata?: Record<string, unknown>\n\t/** Parent job ID (for workflows) */\n\tparentId?: string\n\t/** Workflow step name (for workflows) */\n\tstepName?: string\n}\n\n/** Job context passed to handlers */\nexport interface TaskContext {\n\t/** Job ID */\n\tjobId: string\n\t/** Current attempt number */\n\tattempt: number\n\t/** Signal for cancellation */\n\tsignal?: AbortSignal\n\t/** Update progress */\n\tsetProgress: (progress: number, message?: string) => void\n\t/** Log message */\n\tlog: (message: string, level?: 'info' | 'warn' | 'error') => void\n\t/** Check if should continue (for long-running jobs) */\n\tshouldContinue: () => boolean\n\t/** Schedule a child job */\n\tscheduleChild: <T extends TaskPayload>(\n\t\ttype: string,\n\t\tpayload: T,\n\t\toptions?: TaskOptions,\n\t) => Promise<string>\n\t/** Sleep (durable) */\n\tsleep: (ms: number) => Promise<void>\n}\n\n// ==========================================\n// Workflow Types\n// ==========================================\n\n/** Workflow definition */\nexport interface WorkflowDefinition<\n\t__TInput extends TaskPayload = TaskPayload,\n\tTOutput = TaskResult,\n> {\n\t/** Unique workflow type */\n\ttype: string\n\t/** Human-readable name */\n\tname?: string\n\t/** Description */\n\tdescription?: string\n\t/** Workflow steps */\n\tsteps: WorkflowStep[]\n\t/** Default options */\n\tdefaults?: WorkflowOptions\n\t/** On complete callback */\n\tonComplete?: (result: TOutput) => void\n\t/** On error callback */\n\tonError?: (error: Error, step: string) => void\n}\n\n/** Workflow options */\nexport interface WorkflowOptions extends TaskOptions {\n\t/** Continue on step failure */\n\tcontinueOnFailure?: boolean\n\t/** Max concurrent steps (for parallel) */\n\tmaxConcurrency?: number\n}\n\n/** Workflow step */\nexport type WorkflowStep =\n\t| TaskStep\n\t| ConditionalStep\n\t| ParallelStep\n\t| LoopStep\n\t| WaitStep\n\t| SubworkflowStep\n\n/** Job step */\nexport interface TaskStep {\n\ttype: 'job'\n\tname: string\n\t/** Job type to execute */\n\tjobType: string\n\t/** Payload transform (receives workflow input + previous results) */\n\tpayload?: (context: StepContext) => TaskPayload\n\t/** Step options */\n\toptions?: TaskOptions\n\t/** Condition to run this step */\n\tif?: (context: StepContext) => boolean\n\t/** On complete transform */\n\tonComplete?: (result: TaskResult, context: StepContext) => unknown\n}\n\n/** Conditional step */\nexport interface ConditionalStep {\n\ttype: 'conditional'\n\tname: string\n\t/** Condition function */\n\tcondition: (context: StepContext) => boolean\n\t/** Steps if condition is true */\n\tthen: WorkflowStep[]\n\t/** Steps if condition is false */\n\telse?: WorkflowStep[]\n}\n\n/** Parallel step */\nexport interface ParallelStep {\n\ttype: 'parallel'\n\tname: string\n\t/** Steps to run in parallel */\n\tsteps: WorkflowStep[]\n\t/** Wait for all or any */\n\twaitFor?: 'all' | 'any'\n\t/** Max concurrent */\n\tmaxConcurrency?: number\n}\n\n/** Loop step */\nexport interface LoopStep {\n\ttype: 'loop'\n\tname: string\n\t/** Array to iterate over, or function to get items */\n\titems: unknown[] | ((context: StepContext) => unknown[])\n\t/** Step to execute for each item */\n\tstep: WorkflowStep\n\t/** Max concurrent iterations */\n\tmaxConcurrency?: number\n\t/** Break condition */\n\tbreakIf?: (item: unknown, index: number, context: StepContext) => boolean\n}\n\n/** Wait step */\nexport interface WaitStep {\n\ttype: 'wait'\n\tname: string\n\t/** Duration in ms, Date, or function */\n\tuntil: number | Date | ((context: StepContext) => number | Date)\n}\n\n/** Sub-workflow step */\nexport interface SubworkflowStep {\n\ttype: 'subworkflow'\n\tname: string\n\t/** Workflow type to execute */\n\tworkflowType: string\n\t/** Payload transform */\n\tpayload?: (context: StepContext) => TaskPayload\n\t/** Options */\n\toptions?: WorkflowOptions\n}\n\n/** Step context */\nexport interface StepContext {\n\t/** Workflow input */\n\tinput: TaskPayload\n\t/** Results from previous steps */\n\tresults: Record<string, TaskResult>\n\t/** Current step name */\n\tcurrentStep: string\n\t/** Workflow metadata */\n\tmetadata: Record<string, unknown>\n}\n\n// ==========================================\n// Workflow Instance\n// ==========================================\n\n/** Workflow instance */\nexport interface Workflow<_TInput extends TaskPayload = TaskPayload, TOutput = TaskResult> {\n\t/** Unique workflow ID */\n\tid: string\n\t/** Workflow type */\n\ttype: string\n\t/** Input payload */\n\tinput: _TInput\n\t/** Current status */\n\tstatus: TaskStatus\n\t/** Created timestamp */\n\tcreatedAt: number\n\t/** Started timestamp */\n\tstartedAt?: number\n\t/** Completed timestamp */\n\tcompletedAt?: number\n\t/** Current step name */\n\tcurrentStep?: string\n\t/** Step results */\n\tstepResults: Record<string, TaskResult>\n\t/** Step statuses */\n\tstepStatuses: Record<string, TaskStatus>\n\t/** Final output */\n\toutput?: TOutput\n\t/** Error */\n\terror?: string\n\t/** Metadata */\n\tmetadata?: Record<string, unknown>\n}\n\n// ==========================================\n// Scheduling\n// ==========================================\n\n/** Cron schedule */\nexport interface CronSchedule {\n\t/** Cron expression */\n\texpression: string\n\t/** Timezone */\n\ttimezone?: string\n\t/** Start date */\n\tstartAt?: Date\n\t/** End date */\n\tendAt?: Date\n\t/** Max runs */\n\tmaxRuns?: number\n}\n\n/** Scheduled job */\nexport interface ScheduledTask {\n\t/** Schedule ID */\n\tid: string\n\t/** Job type */\n\ttype: string\n\t/** Job payload */\n\tpayload: TaskPayload\n\t/** Cron schedule */\n\tcron: CronSchedule\n\t/** Current status */\n\tstatus: 'active' | 'paused' | 'completed'\n\t/** Run count */\n\trunCount: number\n\t/** Next run timestamp */\n\tnextRunAt?: number\n\t/** Last run timestamp */\n\tlastRunAt?: number\n\t/** Created timestamp */\n\tcreatedAt: number\n}\n\n// ==========================================\n// Events\n// ==========================================\n\n/** Job event */\nexport type TaskEvent =\n\t| { type: 'job:created'; job: Job }\n\t| { type: 'job:started'; job: Job }\n\t| { type: 'job:progress'; job: Job; progress: number; message?: string }\n\t| { type: 'job:completed'; job: Job; result: TaskResult }\n\t| { type: 'job:failed'; job: Job; error: string }\n\t| { type: 'job:retrying'; job: Job; attempt: number }\n\t| { type: 'job:dead'; job: Job }\n\t| { type: 'job:cancelled'; job: Job }\n\n/** Workflow event */\nexport type WorkflowEvent =\n\t| { type: 'workflow:started'; workflow: Workflow }\n\t| { type: 'workflow:step:started'; workflow: Workflow; step: string }\n\t| {\n\t\t\ttype: 'workflow:step:completed'\n\t\t\tworkflow: Workflow\n\t\t\tstep: string\n\t\t\tresult: TaskResult\n\t }\n\t| {\n\t\t\ttype: 'workflow:step:failed'\n\t\t\tworkflow: Workflow\n\t\t\tstep: string\n\t\t\terror: string\n\t }\n\t| { type: 'workflow:completed'; workflow: Workflow; output: TaskResult }\n\t| { type: 'workflow:failed'; workflow: Workflow; error: string }\n\n// ==========================================\n// Configuration\n// ==========================================\n\n/** Jobs client configuration */\nexport interface TasksConfig {\n\t/** API endpoint */\n\tapiEndpoint?: string\n\t/** API key */\n\tapiKey?: string\n\t/** Default job options */\n\tdefaultOptions?: TaskOptions\n\t/** Enable debug logging */\n\tdebug?: boolean\n\t/** Event callbacks */\n\tonTaskEvent?: (event: TaskEvent) => void\n\tonWorkflowEvent?: (event: WorkflowEvent) => void\n}\n\n/** Default configuration */\nexport const DEFAULT_JOBS_CONFIG: Required<Pick<TasksConfig, 'defaultOptions' | 'debug'>> = {\n\tdefaultOptions: {\n\t\tpriority: 'normal',\n\t\tmaxRetries: 3,\n\t\tretryDelay: {\n\t\t\ttype: 'exponential',\n\t\t\tbase: BASE_RETRY_DELAY_MS,\n\t\t\tmaxDelay: MAX_RETRY_DELAY_MS,\n\t\t},\n\t\ttimeout: JOB_DEFAULT_TIMEOUT_MS,\n\t\tdlq: {\n\t\t\tenabled: true,\n\t\t\tmaxAge: JOBS_DLQ_MAX_AGE_MS, // 7 days\n\t\t},\n\t},\n\tdebug: false,\n}\n\n/** Default retry delays (ms) */\nexport const DEFAULT_RETRY_DELAYS = DEFAULT_RETRY_DELAYS_MS\n\n// ============================================================================\n// Backward-compat type aliases (Jobs → Tasks rename)\n// ============================================================================\nexport type Job<TPayload extends TaskPayload = TaskPayload, TResult = TaskResult> = TaskInstance<\n\tTPayload,\n\tTResult\n>\nexport type JobContext = TaskContext\nexport type JobDefinition<\n\tTPayload extends TaskPayload = TaskPayload,\n\tTResult = TaskResult,\n> = TaskDefinition<TPayload, TResult>\nexport type JobEvent = TaskEvent\nexport type JobOptions = TaskOptions\nexport type JobPayload = TaskPayload\nexport type JobPriority = TaskPriority\nexport type JobResult = TaskResult\n/** @deprecated use TaskStatus */\nexport type JobStatus = TaskStatus\nexport type JobStep = TaskStep\nexport type ScheduledJob = ScheduledTask\n/** Jobs status check result */\nexport type TasksStatusResult = {\n\tavailable: boolean\n}\n/** @deprecated Use TasksConfig.onTaskEvent */\nexport type onJobEvent = TasksConfig['onTaskEvent']\n\n// ============================================================================\n// Native Task Engine — Handler API Types\n// ============================================================================\n\n/**\n * Step execution context injected into every task handler.\n * Methods implement the stateless-replay model:\n * - Completed steps return from cache immediately.\n * - Uncached steps execute and signal the platform.\n */\nexport type NativeStepContext = {\n\t/**\n\t * Execute a named step with automatic checkpointing.\n\t *\n\t * On first run: executes fn and signals the platform to save the result.\n\t * On replay: returns the cached result without re-running fn.\n\t */\n\trun<T>(name: string, fn: () => T | Promise<T>): Promise<T>\n\n\t/**\n\t * Execute an external side effect with a durable idempotency key.\n\t *\n\t * First encounter: signals Platform to persist a side-effect receipt before\n\t * the external call. Replay then invokes fn with that persisted key. If the\n\t * handler crashes after the external call but before completion settles, the\n\t * next replay reuses the same key so the downstream service suppresses duplicates.\n\t */\n\tsideEffect<T>(\n\t\tstepName: string,\n\t\teffectKey: string,\n\t\texternalService: string,\n\t\tfn: (\n\t\t\tidempotencyKey: string,\n\t\t) => NativeSideEffectOutcome<T> | Promise<NativeSideEffectOutcome<T>>,\n\t): Promise<T>\n\n\t/**\n\t * Pause execution for the given duration.\n\t *\n\t * On first encounter: signals the platform to wait; stops execution.\n\t * After the wait resolves: returns immediately (no-op on replay).\n\t *\n\t * @param name Step identifier (must be unique within the handler).\n\t * @param duration Human-readable duration: '5s', '30m', '2h', '1d'.\n\t */\n\tsleep(name: string, duration: string): Promise<void>\n\n\t/**\n\t * Pause execution until a named event is published via TriggersClient.publishEvent().\n\t *\n\t * On first encounter: signals the platform to wait for the event; stops execution.\n\t * After the event arrives: returns the event payload.\n\t * If timeout expires before event arrives: returns null.\n\t *\n\t * @param name Step identifier (must be unique within the handler).\n\t * @param eventName The event name to listen for (e.g. 'user.approved').\n\t * @param options Optional timeout ('24h', '7d') and payload filter.\n\t *\n\t * @example Human-in-the-loop approval\n\t * ```typescript\n\t * const approval = await step.waitForEvent<{ approvedBy: string }>(\n\t * 'wait-approval',\n\t * 'order.approved',\n\t * { timeout: '48h', filter: { orderId: payload.orderId } },\n\t * )\n\t * if (!approval) throw new Error('Approval timed out')\n\t * await notifyCustomer(approval.approvedBy)\n\t * ```\n\t */\n\twaitForEvent<T = unknown>(\n\t\tname: string,\n\t\teventName: string,\n\t\toptions?: { timeout?: string; filter?: Record<string, unknown> },\n\t): Promise<T | null>\n}\n\nexport interface NativeSideEffectOutcome<T = unknown> {\n\treadonly handle?: string\n\treadonly result: T\n}\n\nexport interface NativeSideEffectReceipt {\n\treadonly stepName: string\n\treadonly effectKey: string\n\treadonly externalService: string\n\treadonly idempotencyKey: string\n\treadonly handle: string | null\n\treadonly result: unknown\n\treadonly completedAt: string | null\n\treadonly createdAt: string\n}\n\n/**\n * A named task definition registered with sylphx.tasks.define().\n */\nexport interface NativeTaskDefinition<TPayload = unknown, TResult = unknown> {\n\t/** Unique task identifier — must match the taskName used in .trigger() */\n\tname: string\n\t/** The task handler function. Runs with stateless-replay semantics. */\n\thandler: (payload: TPayload, ctx: { step: NativeStepContext }) => Promise<TResult>\n\t/** Optional task-level configuration */\n\toptions?: {\n\t\t/** Cron expression for scheduled tasks, e.g. '0 9 * * 1-5' */\n\t\tcron?: string\n\t\t/** Maximum execution attempts (default: 3) */\n\t\tmaxAttempts?: number\n\t\t/** Execution timeout, e.g. '5m', '1h' */\n\t\ttimeout?: string\n\t}\n}\n\n/**\n * The shape returned by GET/POST /tasks/:runId in the platform API.\n */\nexport type TaskRunDispatchLeaseState = 'active' | 'expired' | 'legacy'\n\nexport interface TaskRunDispatchLease {\n\t/**\n\t * Customer-safe dispatch claim state. Raw claim tokens and controller\n\t * identities are intentionally not exposed through the public SDK.\n\t */\n\tstate: TaskRunDispatchLeaseState\n\tclaimedAt: string | null\n\texpiresAt: string | null\n}\n\nexport interface TaskRunStatus {\n\tid: string\n\ttaskName: string\n\tstatus: 'pending' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled'\n\tpayload?: unknown\n\tresult?: unknown\n\terror?: string\n\tattempt: number\n\tmaxAttempts: number\n\tscheduledFor?: string\n\tstartedAt?: string\n\tcompletedAt?: string\n\tdispatchLease?: TaskRunDispatchLease | null\n\tdefinition?: {\n\t\tid: string\n\t\tversion: number | null\n\t\thash: string | null\n\t\tsource: string | null\n\t} | null\n\tcreatedAt: string\n\tupdatedAt: string\n}\n","/**\n * Tasks Legacy Client\n *\n * @deprecated Use task() / taskStub() / serve() from the tasks module instead.\n *\n * This file preserves backward compatibility for consumers of the old TasksClient API.\n * The TasksClient class is unchanged — it is imported by ./index.ts under the 'legacy' export group.\n */\n\nimport { createTasksHandler, type TasksHandlerOptions, type TasksHandlerResult } from './handler'\nimport type {\n\tCronSchedule,\n\tJob,\n\tJobEvent,\n\tJobOptions,\n\tJobPayload,\n\tJobResult,\n\tNativeStepContext,\n\tNativeTaskDefinition,\n\tScheduledJob,\n\tTaskRunStatus,\n\tTasksConfig,\n\tWorkflow,\n\tWorkflowDefinition,\n\tWorkflowEvent,\n} from './types'\nimport { DEFAULT_JOBS_CONFIG } from './types'\n\n/**\n * Jobs Client\n *\n * Client for scheduling jobs and workflows via the Sylph API.\n */\nexport class TasksClient {\n\tprivate config: TasksConfig\n\tprivate eventHandlers: {\n\t\tjob: ((event: JobEvent) => void)[]\n\t\tworkflow: ((event: WorkflowEvent) => void)[]\n\t} = { job: [], workflow: [] }\n\n\tconstructor(config: TasksConfig) {\n\t\tthis.config = {\n\t\t\t...config,\n\t\t\tdefaultOptions: {\n\t\t\t\t...DEFAULT_JOBS_CONFIG.defaultOptions,\n\t\t\t\t...config.defaultOptions,\n\t\t\t},\n\t\t}\n\n\t\t// Register initial event handlers\n\t\tif (config.onTaskEvent) {\n\t\t\tthis.eventHandlers.job.push(config.onTaskEvent)\n\t\t}\n\t\tif (config.onWorkflowEvent) {\n\t\t\tthis.eventHandlers.workflow.push(config.onWorkflowEvent)\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Job Scheduling\n\t// =========================================================================\n\n\t/**\n\t * Schedule a job for execution\n\t */\n\tasync schedule<TPayload extends JobPayload = JobPayload>(\n\t\ttype: string,\n\t\tpayload: TPayload,\n\t\toptions?: JobOptions,\n\t): Promise<Job<TPayload>> {\n\t\tconst response = await this.fetch<{ job: Job<TPayload> }>('/jobs', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttype,\n\t\t\t\tpayload,\n\t\t\t\toptions: {\n\t\t\t\t\t...this.config.defaultOptions,\n\t\t\t\t\t...options,\n\t\t\t\t},\n\t\t\t}),\n\t\t})\n\n\t\treturn response.job\n\t}\n\n\t/**\n\t * Schedule a job with delay\n\t */\n\tasync scheduleDelayed<TPayload extends JobPayload = JobPayload>(\n\t\ttype: string,\n\t\tpayload: TPayload,\n\t\tdelay: number | Date,\n\t\toptions?: JobOptions,\n\t): Promise<Job<TPayload>> {\n\t\treturn this.schedule(type, payload, {\n\t\t\t...options,\n\t\t\tdelay: delay instanceof Date ? delay.getTime() - Date.now() : delay,\n\t\t})\n\t}\n\n\t/**\n\t * Schedule a recurring job (cron)\n\t */\n\tasync scheduleCron<TPayload extends JobPayload = JobPayload>(\n\t\ttype: string,\n\t\tpayload: TPayload,\n\t\tcron: string | CronSchedule,\n\t\toptions?: JobOptions,\n\t): Promise<ScheduledJob> {\n\t\tconst response = await this.fetch<{ scheduled: ScheduledJob }>('/jobs/scheduled', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: JSON.stringify({\n\t\t\t\ttype,\n\t\t\t\tpayload,\n\t\t\t\tcron: typeof cron === 'string' ? { expression: cron } : cron,\n\t\t\t\toptions: {\n\t\t\t\t\t...this.config.defaultOptions,\n\t\t\t\t\t...options,\n\t\t\t\t},\n\t\t\t}),\n\t\t})\n\n\t\treturn response.scheduled\n\t}\n\n\t// =========================================================================\n\t// Job Management\n\t// =========================================================================\n\n\t/**\n\t * Get a job by ID\n\t */\n\tasync getJob<TPayload extends JobPayload = JobPayload, TResult = JobResult>(\n\t\tjobId: string,\n\t): Promise<Job<TPayload, TResult> | null> {\n\t\tconst response = await this.fetch<{ job: Job<TPayload, TResult> | null }>(`/jobs/${jobId}`)\n\t\treturn response.job\n\t}\n\n\t/**\n\t * Cancel a job\n\t */\n\tasync cancelJob(jobId: string): Promise<boolean> {\n\t\tconst response = await this.fetch<{ cancelled: boolean }>(`/jobs/${jobId}/cancel`, {\n\t\t\tmethod: 'POST',\n\t\t})\n\t\treturn response.cancelled\n\t}\n\n\t/**\n\t * Retry a failed job\n\t */\n\tasync retryJob(jobId: string): Promise<Job> {\n\t\tconst response = await this.fetch<{ job: Job }>(`/jobs/${jobId}/retry`, {\n\t\t\tmethod: 'POST',\n\t\t})\n\t\treturn response.job\n\t}\n\n\t/**\n\t * List jobs with filters\n\t */\n\tasync listJobs(options?: {\n\t\ttype?: string\n\t\tstatus?: string\n\t\tlimit?: number\n\t\toffset?: number\n\t}): Promise<{ jobs: Job[]; total: number }> {\n\t\tconst params = new URLSearchParams()\n\t\tif (options?.type) params.set('type', options.type)\n\t\tif (options?.status) params.set('status', options.status)\n\t\tif (options?.limit) params.set('limit', String(options.limit))\n\t\tif (options?.offset) params.set('offset', String(options.offset))\n\n\t\tconst response = await this.fetch<{ jobs: Job[]; total: number }>(`/jobs?${params.toString()}`)\n\t\treturn { jobs: response.jobs, total: response.total }\n\t}\n\n\t// =========================================================================\n\t// Dead Letter Queue\n\t// =========================================================================\n\n\t/**\n\t * List DLQ entries\n\t */\n\tasync listDLQ(options?: {\n\t\tlimit?: number\n\t\toffset?: number\n\t}): Promise<{ entries: Job[]; total: number }> {\n\t\tconst params = new URLSearchParams()\n\t\tif (options?.limit) params.set('limit', String(options.limit))\n\t\tif (options?.offset) params.set('offset', String(options.offset))\n\n\t\tconst response = await this.fetch<{ entries: Job[]; total: number }>(\n\t\t\t`/jobs/dlq?${params.toString()}`,\n\t\t)\n\t\treturn { entries: response.entries, total: response.total }\n\t}\n\n\t/**\n\t * Retry a DLQ entry\n\t */\n\tasync retryDLQEntry(entryId: string): Promise<Job> {\n\t\tconst response = await this.fetch<{ job: Job }>(`/jobs/dlq/${entryId}/retry`, {\n\t\t\tmethod: 'POST',\n\t\t})\n\t\treturn response.job\n\t}\n\n\t/**\n\t * Discard a DLQ entry\n\t */\n\tasync discardDLQEntry(entryId: string): Promise<boolean> {\n\t\tconst response = await this.fetch<{ discarded: boolean }>(`/jobs/dlq/${entryId}`, {\n\t\t\tmethod: 'DELETE',\n\t\t})\n\t\treturn response.discarded\n\t}\n\n\t// =========================================================================\n\t// Workflows\n\t// =========================================================================\n\n\t/**\n\t * Start a workflow\n\t */\n\tasync startWorkflow<TInput extends JobPayload = JobPayload, TOutput = JobResult>(\n\t\tworkflow: WorkflowDefinition<TInput, TOutput>,\n\t\tinput: TInput,\n\t\toptions?: JobOptions,\n\t): Promise<Workflow<TInput, TOutput>> {\n\t\tconst response = await this.fetch<{ workflow: Workflow<TInput, TOutput> }>('/workflows', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: JSON.stringify({\n\t\t\t\tworkflow,\n\t\t\t\tinput,\n\t\t\t\toptions: {\n\t\t\t\t\t...this.config.defaultOptions,\n\t\t\t\t\t...options,\n\t\t\t\t},\n\t\t\t}),\n\t\t})\n\n\t\treturn response.workflow\n\t}\n\n\t/**\n\t * Get a workflow by ID\n\t */\n\tasync getWorkflow<TInput extends JobPayload = JobPayload, TOutput = JobResult>(\n\t\tworkflowId: string,\n\t): Promise<Workflow<TInput, TOutput> | null> {\n\t\tconst response = await this.fetch<{ workflow: Workflow<TInput, TOutput> | null }>(\n\t\t\t`/workflows/${workflowId}`,\n\t\t)\n\t\treturn response.workflow\n\t}\n\n\t/**\n\t * Cancel a workflow\n\t */\n\tasync cancelWorkflow(workflowId: string): Promise<boolean> {\n\t\tconst response = await this.fetch<{ cancelled: boolean }>(`/workflows/${workflowId}/cancel`, {\n\t\t\tmethod: 'POST',\n\t\t})\n\t\treturn response.cancelled\n\t}\n\n\t/**\n\t * List workflows\n\t */\n\tasync listWorkflows(options?: {\n\t\ttype?: string\n\t\tstatus?: string\n\t\tlimit?: number\n\t\toffset?: number\n\t}): Promise<{ workflows: Workflow[]; total: number }> {\n\t\tconst params = new URLSearchParams()\n\t\tif (options?.type) params.set('type', options.type)\n\t\tif (options?.status) params.set('status', options.status)\n\t\tif (options?.limit) params.set('limit', String(options.limit))\n\t\tif (options?.offset) params.set('offset', String(options.offset))\n\n\t\tconst response = await this.fetch<{ workflows: Workflow[]; total: number }>(\n\t\t\t`/workflows?${params.toString()}`,\n\t\t)\n\t\treturn { workflows: response.workflows, total: response.total }\n\t}\n\n\t// =========================================================================\n\t// Scheduled Jobs\n\t// =========================================================================\n\n\t/**\n\t * List scheduled jobs\n\t */\n\tasync listScheduledJobs(options?: {\n\t\tstatus?: 'active' | 'paused' | 'completed'\n\t\tlimit?: number\n\t\toffset?: number\n\t}): Promise<{ scheduled: ScheduledJob[]; total: number }> {\n\t\tconst params = new URLSearchParams()\n\t\tif (options?.status) params.set('status', options.status)\n\t\tif (options?.limit) params.set('limit', String(options.limit))\n\t\tif (options?.offset) params.set('offset', String(options.offset))\n\n\t\tconst response = await this.fetch<{ scheduled: ScheduledJob[]; total: number }>(\n\t\t\t`/jobs/scheduled?${params.toString()}`,\n\t\t)\n\t\treturn { scheduled: response.scheduled, total: response.total }\n\t}\n\n\t/**\n\t * Pause a scheduled job\n\t */\n\tasync pauseScheduledJob(scheduleId: string): Promise<ScheduledJob> {\n\t\tconst response = await this.fetch<{ scheduled: ScheduledJob }>(\n\t\t\t`/jobs/scheduled/${scheduleId}/pause`,\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t},\n\t\t)\n\t\treturn response.scheduled\n\t}\n\n\t/**\n\t * Resume a scheduled job\n\t */\n\tasync resumeScheduledJob(scheduleId: string): Promise<ScheduledJob> {\n\t\tconst response = await this.fetch<{ scheduled: ScheduledJob }>(\n\t\t\t`/jobs/scheduled/${scheduleId}/resume`,\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t},\n\t\t)\n\t\treturn response.scheduled\n\t}\n\n\t/**\n\t * Delete a scheduled job\n\t */\n\tasync deleteScheduledJob(scheduleId: string): Promise<boolean> {\n\t\tconst response = await this.fetch<{ deleted: boolean }>(`/jobs/scheduled/${scheduleId}`, {\n\t\t\tmethod: 'DELETE',\n\t\t})\n\t\treturn response.deleted\n\t}\n\n\t// =========================================================================\n\t// Events\n\t// =========================================================================\n\n\t/**\n\t * Subscribe to job events\n\t */\n\tonJobEvent(handler: (event: JobEvent) => void): () => void {\n\t\tthis.eventHandlers.job.push(handler)\n\t\treturn () => {\n\t\t\tconst index = this.eventHandlers.job.indexOf(handler)\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventHandlers.job.splice(index, 1)\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Subscribe to workflow events\n\t */\n\tonWorkflowEvent(handler: (event: WorkflowEvent) => void): () => void {\n\t\tthis.eventHandlers.workflow.push(handler)\n\t\treturn () => {\n\t\t\tconst index = this.eventHandlers.workflow.indexOf(handler)\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventHandlers.workflow.splice(index, 1)\n\t\t\t}\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Internal\n\t// =========================================================================\n\n\tprivate async fetch<TResponse>(path: string, options?: RequestInit): Promise<TResponse> {\n\t\tconst url = `${this.config.apiEndpoint}${path}`\n\t\tconst response = await fetch(url, {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t\t...(this.config.apiKey && {\n\t\t\t\t\tAuthorization: `Bearer ${this.config.apiKey}`,\n\t\t\t\t}),\n\t\t\t\t...options?.headers,\n\t\t\t},\n\t\t})\n\n\t\tif (!response.ok) {\n\t\t\tconst errorPayload: unknown = await response\n\t\t\t\t.json()\n\t\t\t\t.catch(() => ({ message: response.statusText }))\n\t\t\tconst message =\n\t\t\t\ttypeof errorPayload === 'object' &&\n\t\t\t\terrorPayload !== null &&\n\t\t\t\t'message' in errorPayload &&\n\t\t\t\ttypeof errorPayload.message === 'string'\n\t\t\t\t\t? errorPayload.message\n\t\t\t\t\t: response.statusText\n\t\t\tthrow new Error(message || `HTTP ${response.status}`)\n\t\t}\n\n\t\tconst payload: unknown = await response.json()\n\t\treturn payload as TResponse\n\t}\n\n\t// =========================================================================\n\t// Native Task Engine — Handler API\n\t// =========================================================================\n\n\t/**\n\t * Define a named task handler.\n\t *\n\t * Returns a TaskDefinition that can be passed to tasks.handler([...]).\n\t * The handler runs with stateless-replay semantics — each dispatch\n\t * replays from the beginning with completed steps injected from cache.\n\t *\n\t * @example\n\t * ```typescript\n\t * const sendEmail = sylphx.tasks.define('send-email', async (payload, { step }) => {\n\t * const validated = await step.run('validate', () => validate(payload.to))\n\t * await step.sleep('cool-down', '5 minutes')\n\t * return step.run('send', () => send(validated))\n\t * })\n\t * ```\n\t */\n\tdefine<TPayload = unknown, TResult = unknown>(\n\t\tname: string,\n\t\tfn: (payload: TPayload, ctx: { step: NativeStepContext }) => Promise<TResult>,\n\t\toptions?: NativeTaskDefinition<TPayload, TResult>['options'],\n\t): NativeTaskDefinition<TPayload, TResult> {\n\t\treturn { name, handler: fn, options }\n\t}\n\n\t/**\n\t * Create a Next.js / Web-API-compatible route handler for a set of task definitions.\n\t *\n\t * @example\n\t * ```typescript\n\t * // app/api/tasks/route.ts\n\t * export const { GET, POST } = sylphx.tasks.handler([sendEmail, processOrder])\n\t * ```\n\t */\n\thandler(tasks: NativeTaskDefinition[], handlerOptions?: TasksHandlerOptions): TasksHandlerResult {\n\t\treturn createTasksHandler(tasks, handlerOptions)\n\t}\n\n\t/**\n\t * Trigger a task run on the Sylphx platform.\n\t *\n\t * The platform will dispatch the task to the app's handler endpoint.\n\t * Returns the taskRunId which can be used to poll status.\n\t */\n\tasync trigger<TPayload = unknown>(\n\t\ttaskName: string,\n\t\tpayload?: TPayload,\n\t\toptions?: {\n\t\t\tdelay?: string\n\t\t\tscheduledFor?: Date\n\t\t\tidempotencyKey?: string\n\t\t\tmaxAttempts?: number\n\t\t},\n\t): Promise<{ taskRunId: string; status: string; createdAt: string }> {\n\t\tconst response = await this.fetch<{ taskRunId: string; status: string; createdAt: string }>(\n\t\t\t'/tasks/trigger',\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\ttaskName,\n\t\t\t\t\tpayload,\n\t\t\t\t\tdelay: options?.delay,\n\t\t\t\t\tscheduledFor: options?.scheduledFor?.toISOString(),\n\t\t\t\t\tidempotencyKey: options?.idempotencyKey,\n\t\t\t\t\tmaxAttempts: options?.maxAttempts,\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\t\treturn response\n\t}\n\n\t/**\n\t * Fetch the current status of a task run.\n\t */\n\tasync getTaskRun(taskRunId: string): Promise<TaskRunStatus> {\n\t\treturn this.fetch<TaskRunStatus>(`/tasks/${taskRunId}`)\n\t}\n\n\t/**\n\t * Cancel a pending, running, waiting, or failed task run.\n\t */\n\tasync cancelTaskRun(taskRunId: string): Promise<boolean> {\n\t\tconst response = await this.fetch<{ success: boolean }>(`/tasks/${taskRunId}/cancel`, {\n\t\t\tmethod: 'POST',\n\t\t})\n\t\treturn response.success\n\t}\n\n\t/**\n\t * List task runs for the current project/environment.\n\t */\n\tasync listTaskRuns(options?: {\n\t\ttaskName?: string\n\t\tstatus?: TaskRunStatus['status']\n\t\tlimit?: number\n\t\toffset?: number\n\t}): Promise<{ runs: TaskRunStatus[]; total: number }> {\n\t\tconst params = new URLSearchParams()\n\t\tif (options?.taskName) params.set('taskName', options.taskName)\n\t\tif (options?.status) params.set('status', options.status)\n\t\tif (options?.limit) params.set('limit', String(options.limit))\n\t\tif (options?.offset) params.set('offset', String(options.offset))\n\n\t\treturn this.fetch<{ runs: TaskRunStatus[]; total: number }>(`/tasks?${params.toString()}`)\n\t}\n}\n\n/**\n * Create a Jobs client instance\n */\nexport function createTasksClient(config: TasksConfig): TasksClient {\n\treturn new TasksClient(config)\n}\n\n// Backward-compat aliases (Jobs → Tasks rename)\n/** @deprecated Use TasksClient */\nexport class JobsClient extends TasksClient {}\n/** @deprecated Use createTasksClient */\nexport const createJobsClient = createTasksClient\nexport type { TasksConfig as JobsConfig }\n","/**\n * Workflow Builder DSL\n *\n * Fluent API for defining workflows with type safety.\n *\n * @example\n * ```typescript\n * const workflow = createWorkflow('onboarding')\n * .name('User Onboarding')\n * .step('create-account', task('create-user'))\n * .step('send-welcome', task('send-email', (ctx) => ({\n * to: ctx.results['create-account'].email,\n * template: 'welcome',\n * })))\n * .step('wait-verification', wait(24 * 60 * 60 * 1000))\n * .step('check-verified', conditional(\n * (ctx) => ctx.results['create-account'].verified,\n * [task('activate-account')],\n * [task('send-reminder')]\n * ))\n * .build()\n * ```\n */\n\nimport type {\n\tConditionalStep,\n\tLoopStep,\n\tParallelStep,\n\tStepContext,\n\tSubworkflowStep,\n\tTaskOptions,\n\tTaskPayload,\n\tTaskResult,\n\tTaskStep,\n\tWaitStep,\n\tWorkflowDefinition,\n\tWorkflowOptions,\n\tWorkflowStep,\n} from './types'\n\n// ==========================================\n// Workflow Builder\n// ==========================================\n\n/**\n * Create a new workflow builder\n */\nexport function createWorkflow<TInput extends TaskPayload = TaskPayload, TOutput = TaskResult>(\n\ttype: string,\n): WorkflowBuilder<TInput, TOutput> {\n\treturn new WorkflowBuilder<TInput, TOutput>(type)\n}\n\n/**\n * Workflow Builder\n *\n * Fluent API for building workflow definitions.\n */\nexport class WorkflowBuilder<TInput extends TaskPayload = TaskPayload, TOutput = TaskResult> {\n\tprivate definition: Partial<WorkflowDefinition<TInput, TOutput>> = {}\n\tprivate _steps: WorkflowStep[] = []\n\n\tconstructor(type: string) {\n\t\tthis.definition.type = type\n\t}\n\n\t/**\n\t * Set workflow name\n\t */\n\tname(name: string): this {\n\t\tthis.definition.name = name\n\t\treturn this\n\t}\n\n\t/**\n\t * Set workflow description\n\t */\n\tdescription(description: string): this {\n\t\tthis.definition.description = description\n\t\treturn this\n\t}\n\n\t/**\n\t * Set default options\n\t */\n\tdefaults(options: WorkflowOptions): this {\n\t\tthis.definition.defaults = options\n\t\treturn this\n\t}\n\n\t/**\n\t * Add a step to the workflow\n\t */\n\tstep(name: string, step: WorkflowStep): this {\n\t\t// Override step name\n\t\tconst namedStep = { ...step, name }\n\t\tthis._steps.push(namedStep)\n\t\treturn this\n\t}\n\n\t/**\n\t * Add multiple steps\n\t */\n\tsteps(...steps: Array<[string, WorkflowStep]>): this {\n\t\tfor (const [name, step] of steps) {\n\t\t\tthis.step(name, step)\n\t\t}\n\t\treturn this\n\t}\n\n\t/**\n\t * Add on complete callback\n\t */\n\tonComplete(callback: (result: TOutput) => void): this {\n\t\tthis.definition.onComplete = callback\n\t\treturn this\n\t}\n\n\t/**\n\t * Add on error callback\n\t */\n\tonError(callback: (error: Error, step: string) => void): this {\n\t\tthis.definition.onError = callback\n\t\treturn this\n\t}\n\n\t/**\n\t * Build the workflow definition\n\t */\n\tbuild(): WorkflowDefinition<TInput, TOutput> {\n\t\treturn {\n\t\t\ttype: this.definition.type!,\n\t\t\tname: this.definition.name,\n\t\t\tdescription: this.definition.description,\n\t\t\tsteps: this._steps,\n\t\t\tdefaults: this.definition.defaults,\n\t\t\tonComplete: this.definition.onComplete,\n\t\t\tonError: this.definition.onError,\n\t\t}\n\t}\n}\n\n// ==========================================\n// Step Builders\n// ==========================================\n\n/**\n * Create a job step\n */\nexport function task(\n\ttaskType: string,\n\tpayload?: TaskPayload | ((context: StepContext) => TaskPayload),\n\toptions?: TaskOptions,\n): TaskStep {\n\treturn {\n\t\ttype: 'job',\n\t\tname: taskType,\n\t\tjobType: taskType,\n\t\tpayload: typeof payload === 'function' ? payload : payload ? () => payload : undefined,\n\t\toptions,\n\t}\n}\n\n/**\n * Create a conditional step\n */\nexport function conditional(\n\tcondition: (context: StepContext) => boolean,\n\tthenSteps: WorkflowStep[],\n\telseSteps?: WorkflowStep[],\n): ConditionalStep {\n\treturn {\n\t\ttype: 'conditional',\n\t\tname: 'conditional',\n\t\tcondition,\n\t\t// biome-ignore lint/suspicious/noThenProperty: workflow step field name\n\t\tthen: thenSteps,\n\t\telse: elseSteps,\n\t}\n}\n\n/**\n * Create a parallel step\n */\nexport function parallel(\n\tsteps: WorkflowStep[],\n\toptions?: { waitFor?: 'all' | 'any'; maxConcurrency?: number },\n): ParallelStep {\n\treturn {\n\t\ttype: 'parallel',\n\t\tname: 'parallel',\n\t\tsteps,\n\t\twaitFor: options?.waitFor || 'all',\n\t\tmaxConcurrency: options?.maxConcurrency,\n\t}\n}\n\n/**\n * Create a loop step\n */\nexport function loop(\n\titems: unknown[] | ((context: StepContext) => unknown[]),\n\tstep: WorkflowStep,\n\toptions?: {\n\t\tmaxConcurrency?: number\n\t\tbreakIf?: (item: unknown, index: number, context: StepContext) => boolean\n\t},\n): LoopStep {\n\treturn {\n\t\ttype: 'loop',\n\t\tname: 'loop',\n\t\titems,\n\t\tstep,\n\t\tmaxConcurrency: options?.maxConcurrency,\n\t\tbreakIf: options?.breakIf,\n\t}\n}\n\n/**\n * Create a wait step\n */\nexport function wait(until: number | Date | ((context: StepContext) => number | Date)): WaitStep {\n\treturn {\n\t\ttype: 'wait',\n\t\tname: 'wait',\n\t\tuntil,\n\t}\n}\n\n/**\n * Create a sub-workflow step\n */\nexport function subworkflow(\n\tworkflowType: string,\n\tpayload?: TaskPayload | ((context: StepContext) => TaskPayload),\n\toptions?: WorkflowOptions,\n): SubworkflowStep {\n\treturn {\n\t\ttype: 'subworkflow',\n\t\tname: workflowType,\n\t\tworkflowType,\n\t\tpayload: typeof payload === 'function' ? payload : payload ? () => payload : undefined,\n\t\toptions,\n\t}\n}\n\n// ==========================================\n// Step Helpers\n// ==========================================\n\n/**\n * Create a job step with conditional execution\n */\nexport function jobIf(\n\tcondition: (context: StepContext) => boolean,\n\ttaskType: string,\n\tpayload?: TaskPayload | ((context: StepContext) => TaskPayload),\n\toptions?: TaskOptions,\n): TaskStep {\n\tconst step = task(taskType, payload, options)\n\treturn {\n\t\t...step,\n\t\tif: condition,\n\t}\n}\n\n/**\n * Create a delay step (alias for wait)\n */\nexport function delay(ms: number): WaitStep {\n\treturn wait(ms)\n}\n\n/**\n * Create a step that sleeps until a specific time\n */\nexport function sleepUntil(date: Date | ((context: StepContext) => Date)): WaitStep {\n\treturn wait(date)\n}\n\n/**\n * Create a retry wrapper for a step\n */\nexport function withRetry(\n\tstep: TaskStep,\n\toptions: { maxRetries: number; retryDelay?: number },\n): TaskStep {\n\treturn {\n\t\t...step,\n\t\toptions: {\n\t\t\t...step.options,\n\t\t\tmaxRetries: options.maxRetries,\n\t\t\tretryDelay: options.retryDelay ? { type: 'fixed', delay: options.retryDelay } : undefined,\n\t\t},\n\t}\n}\n\n/**\n * Create a timeout wrapper for a step\n */\nexport function withTimeout(step: TaskStep, timeoutMs: number): TaskStep {\n\treturn {\n\t\t...step,\n\t\toptions: {\n\t\t\t...step.options,\n\t\t\ttimeout: timeoutMs,\n\t\t},\n\t}\n}\n\n// ==========================================\n// Workflow Composition\n// ==========================================\n\n/**\n * Compose multiple workflows sequentially\n */\nexport function sequence(...workflows: WorkflowDefinition[]): WorkflowStep[] {\n\treturn workflows.map((workflow, index) => ({\n\t\ttype: 'subworkflow' as const,\n\t\tname: `sequence-${index}-${workflow.type}`,\n\t\tworkflowType: workflow.type,\n\t}))\n}\n\n/**\n * Fan-out pattern: Execute same job for multiple items\n */\nexport function fanOut(\n\titems: unknown[] | ((context: StepContext) => unknown[]),\n\ttaskType: string,\n\tpayloadMapper: (item: unknown, index: number) => TaskPayload,\n\toptions?: { maxConcurrency?: number },\n): LoopStep {\n\treturn loop(\n\t\titems,\n\t\t{\n\t\t\ttype: 'job',\n\t\t\tname: `fanout-${taskType}`,\n\t\t\tjobType: taskType,\n\t\t\tpayload: (ctx) => {\n\t\t\t\t// This is a simplified version - real implementation needs item context\n\t\t\t\treturn {} as TaskPayload\n\t\t\t},\n\t\t},\n\t\t{ maxConcurrency: options?.maxConcurrency },\n\t)\n}\n\n/**\n * Saga pattern: Define compensating actions for each step\n */\nexport interface SagaStep {\n\tforward: TaskStep\n\tcompensate: TaskStep\n}\n\nexport function saga(steps: SagaStep[]): WorkflowStep[] {\n\t// Build forward steps with compensation tracking\n\tconst workflowSteps: WorkflowStep[] = []\n\n\tfor (let i = 0; i < steps.length; i++) {\n\t\tconst step = steps[i]!\n\n\t\t// Add forward step with error handling\n\t\tconst forwardStep: TaskStep = {\n\t\t\t...step.forward,\n\t\t\tname: `saga-forward-${i}-${step.forward.jobType}`,\n\t\t\tonComplete: (result, ctx) => {\n\t\t\t\t// Track completed step for potential compensation\n\t\t\t\tctx.metadata.completedSagaSteps = [\n\t\t\t\t\t...((ctx.metadata.completedSagaSteps as number[]) || []),\n\t\t\t\t\ti,\n\t\t\t\t]\n\t\t\t\treturn result\n\t\t\t},\n\t\t}\n\n\t\tworkflowSteps.push(forwardStep)\n\t}\n\n\t// Note: Actual saga compensation logic would be handled by the executor\n\t// This is a simplified client-side representation\n\n\treturn workflowSteps\n}\n\n// ==========================================\n// Validation\n// ==========================================\n\n/**\n * Validate a workflow definition\n */\nexport function validateWorkflow(workflow: WorkflowDefinition): string[] {\n\tconst errors: string[] = []\n\n\tif (!workflow.type) {\n\t\terrors.push('Workflow type is required')\n\t}\n\n\tif (!workflow.steps || workflow.steps.length === 0) {\n\t\terrors.push('Workflow must have at least one step')\n\t}\n\n\t// Check for duplicate step names\n\tconst stepNames = new Set<string>()\n\tconst checkSteps = (steps: WorkflowStep[]) => {\n\t\tfor (const step of steps) {\n\t\t\tif (stepNames.has(step.name)) {\n\t\t\t\terrors.push(`Duplicate step name: ${step.name}`)\n\t\t\t}\n\t\t\tstepNames.add(step.name)\n\n\t\t\t// Recursively check nested steps\n\t\t\tif (step.type === 'conditional') {\n\t\t\t\tcheckSteps(step.then)\n\t\t\t\tif (step.else) checkSteps(step.else)\n\t\t\t} else if (step.type === 'parallel') {\n\t\t\t\tcheckSteps(step.steps)\n\t\t\t} else if (step.type === 'loop') {\n\t\t\t\tcheckSteps([step.step])\n\t\t\t}\n\t\t}\n\t}\n\n\tif (workflow.steps) {\n\t\tcheckSteps(workflow.steps)\n\t}\n\n\treturn errors\n}\n\n// Backward-compat aliases\n/** @deprecated Use task() instead */\nexport const job = task\n"],"mappings":";AAkEA,IAAM,kBAAkB;AAExB,IAAM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