@cadraos/sdk 0.3.15 → 0.3.16-dev.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/resources/base.ts","../src/errors/sdk-errors.ts","../src/errors/ai-function-errors.ts","../src/utils/retry.ts","../src/utils/http.ts","../src/streaming/sse-client.ts","../src/streaming/extract-images.ts","../src/streaming/poll-policy.ts","../src/streaming/stream-controller.ts","../src/streaming/collect-images.ts","../src/utils/api-paths.ts","../src/resources/agents.ts","../src/resources/skills.ts","../src/resources/tools.ts","../src/resources/artifacts.ts","../src/resources/attachments.ts","../src/resources/sessions.ts","../src/resources/kanban.ts","../src/resources/teams.ts","../src/resources/remote-agents.ts","../src/resources/remote-runners.ts","../src/resources/ai-functions.ts","../src/client.ts"],"names":["value"],"mappings":";;;AAaO,IAAe,kBAAf,MAA+B;AAAA,EACjB,IAAA;AAAA,EACA,QAAA;AAAA,EAEnB,WAAA,CAAY,MAAkB,QAAA,EAAkB;AAC9C,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,QAAA,GAAW,QAAA;AAAA,EAClB;AAAA;AAAA;AAAA;AAAA,EAKU,eAAe,OAAA,EAA8E;AACrG,IAAA,IAAI,CAAC,OAAA,EAAS,OAAO,EAAC;AAEtB,IAAA,OAAO;AAAA,MACL,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,QAAQ,OAAA,CAAQ,MAAA;AAAA,MAChB,MAAM,OAAA,CAAQ,IAAA;AAAA,MACd,OAAO,OAAA,CAAQ;AAAA,KACjB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAgB,OAAA,CACd,IAAA,EACA,KAAA,EACY;AACZ,IAAA,OAAO,IAAA,CAAK,KAAK,GAAA,CAAO,CAAA,EAAG,KAAK,QAAQ,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,KAAK,CAAA;AAAA,EAC1D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AQ,UAAU,IAAA,EAAM;AACzD,MAAA,MAAM,IAAI,MAAM,sCAAsC,CAAA;AAAA,IACxD;AAEA,IAAA,IAAI,OAAO,OAAA,CAAQ,KAAA,KAAU,QAAA,EAAU;AACrC,MAAA,MAAM,IAAI,MAAM,2CAA2C,CAAA;AAAA,IAC7D;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Base Resource API\n *\n * Abstract base class for all resource APIs.\n * Provides common HTTP methods and path handling.\n */\n\nimport type { HttpClient } from '../utils/http.js';\nimport type { ListOptions, PaginatedResponse } from '../types/index.js';\n\n/**\n * Base Resource API class\n */\nexport abstract class BaseResourceAPI {\n protected readonly http: HttpClient;\n protected readonly basePath: string;\n\n constructor(http: HttpClient, basePath: string) {\n this.http = http;\n this.basePath = basePath;\n }\n\n /**\n * Build query parameters from list options\n */\n protected buildListQuery(options?: ListOptions): Record<string, string | number | boolean | undefined> {\n if (!options) return {};\n\n return {\n limit: options.limit,\n offset: options.offset,\n sort: options.sort,\n order: options.order,\n };\n }\n\n /**\n * HTTP GET request helper\n */\n protected async httpGet<T>(\n path: string,\n query?: Record<string, string | number | boolean | undefined>\n ): Promise<T> {\n return this.http.get<T>(`${this.basePath}${path}`, query);\n }\n\n /**\n * HTTP POST request helper\n */\n protected async httpPost<T>(\n path: string,\n body?: unknown,\n options?: { idempotencyKey?: string; skipRetry?: boolean; timeoutMs?: number }\n ): Promise<T> {\n return this.http.post<T>(`${this.basePath}${path}`, body, options);\n }\n\n /**\n * HTTP PATCH request helper\n */\n protected async httpPatch<T>(\n path: string,\n body?: unknown,\n options?: { idempotencyKey?: string; skipRetry?: boolean }\n ): Promise<T> {\n return this.http.patch<T>(`${this.basePath}${path}`, body, options);\n }\n\n /**\n * HTTP DELETE request helper\n */\n protected async httpDelete<T>(path: string): Promise<T> {\n return this.http.delete<T>(`${this.basePath}${path}`);\n }\n\n /**\n * List resources with pagination\n */\n protected async listResources<T>(\n path: string,\n options?: ListOptions\n ): Promise<PaginatedResponse<T>> {\n const query = this.buildListQuery(options);\n // The API returns { data: T[], pagination: ... } which we unwrap\n return this.httpGet<PaginatedResponse<T>>(path, query);\n }\n}\n","/**\n * SDK Error Classes\n *\n * Typed error hierarchy for all SDK operations.\n * All errors extend CadraError and include code, status, and optional details.\n */\n\n/**\n * Base error class for all SDK errors\n */\nexport class CadraError extends Error {\n /** Error code */\n readonly code: string;\n /** HTTP status code */\n readonly status: number;\n /** Additional error details */\n readonly details?: Record<string, unknown>;\n /** Request ID from server (for debugging) */\n readonly requestId?: string;\n /**\n * The server's own `error.code` exactly as sent on the wire (e.g.\n * `FUNCTION_NOT_PUBLISHED`, `DUPLICATE_REQUEST`, `VARIABLE_TYPE`).\n * Populated by `parseApiError` for EVERY status. `code` keeps its historic\n * per-class values (`conflict`, `server_error`, `validation_error`, …) for\n * compatibility; branch on `serverCode` when you need the precise reason.\n */\n serverCode?: string;\n\n constructor(\n message: string,\n code: string,\n status: number,\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message);\n this.name = 'CadraError';\n this.code = code;\n this.status = status;\n this.details = details;\n this.requestId = requestId;\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Authentication error (401)\n * Thrown when API key is invalid, expired, or missing\n */\nexport class AuthenticationError extends CadraError {\n constructor(\n message: string = 'Authentication failed',\n code: string = 'authentication_error',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, code, 401, details, requestId);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Authorization error (403)\n * Thrown when user lacks permission for the requested operation\n */\nexport class AuthorizationError extends CadraError {\n constructor(\n message: string = 'Access denied',\n code: string = 'authorization_error',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, code, 403, details, requestId);\n this.name = 'AuthorizationError';\n }\n}\n\n/**\n * Not found error (404)\n * Thrown when requested resource does not exist\n */\nexport class NotFoundError extends CadraError {\n constructor(\n message: string = 'Resource not found',\n code: string = 'not_found',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, code, 404, details, requestId);\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Validation error (400/422)\n * Thrown when request input is invalid\n */\nexport class ValidationError extends CadraError {\n /** Field-level validation errors */\n readonly errors: Array<{ field: string; message: string }>;\n\n constructor(\n message: string = 'Validation failed',\n errors: Array<{ field: string; message: string }> = [],\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'validation_error', 400, details, requestId);\n this.name = 'ValidationError';\n this.errors = errors;\n }\n}\n\n/**\n * Rate limit error (429)\n * Thrown when rate limit is exceeded\n */\nexport class RateLimitError extends CadraError {\n /** Seconds until rate limit resets */\n readonly retryAfter?: number;\n\n constructor(\n message: string = 'Rate limit exceeded',\n retryAfter?: number,\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'rate_limit_error', 429, details, requestId);\n this.name = 'RateLimitError';\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Server error (5xx)\n * Thrown for server-side errors\n */\nexport class ServerError extends CadraError {\n constructor(\n message: string = 'Server error',\n status: number = 500,\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'server_error', status, details, requestId);\n this.name = 'ServerError';\n }\n}\n\n/**\n * Conflict error (409)\n * Thrown when there is a resource conflict\n */\nexport class ConflictError extends CadraError {\n constructor(\n message: string = 'Resource conflict',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'conflict', 409, details, requestId);\n this.name = 'ConflictError';\n }\n}\n\n/**\n * Timeout error\n * Thrown when a request or operation times out\n */\nexport class TimeoutError extends CadraError {\n constructor(\n message: string = 'Request timed out',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'timeout', 408, details, requestId);\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Network error\n * Thrown when there is a network connectivity issue\n */\nexport class NetworkError extends CadraError {\n constructor(\n message: string = 'Network error',\n details?: Record<string, unknown>\n ) {\n super(message, 'network_error', 0, details);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Parse error from API response to appropriate error class\n */\nexport function parseApiError(\n status: number,\n body: unknown,\n requestId?: string\n): CadraError {\n const errorBody = body as {\n error?: {\n code?: string;\n message?: string;\n details?: Record<string, unknown>;\n };\n } | null;\n\n const message = errorBody?.error?.message ?? 'An error occurred';\n const code = errorBody?.error?.code ?? 'unknown_error';\n const details = errorBody?.error?.details;\n const serverCode =\n typeof errorBody?.error?.code === 'string' ? errorBody.error.code : undefined;\n\n const error = buildApiError(status, message, code, details, requestId);\n if (serverCode !== undefined) error.serverCode = serverCode;\n return error;\n}\n\nfunction buildApiError(\n status: number,\n message: string,\n code: string,\n details: Record<string, unknown> | undefined,\n requestId: string | undefined\n): CadraError {\n switch (status) {\n case 400:\n case 422: {\n // Check if it's a validation error with field errors\n const fieldErrors = details?.errors as Record<string, string[]> | undefined;\n if (fieldErrors) {\n const errors: Array<{ field: string; message: string }> = [];\n for (const [field, messages] of Object.entries(fieldErrors)) {\n for (const msg of messages) {\n errors.push({ field, message: msg });\n }\n }\n return new ValidationError(message, errors, details, requestId);\n }\n return new ValidationError(message, [], details, requestId);\n }\n\n case 401:\n return new AuthenticationError(message, code, details, requestId);\n\n case 403:\n return new AuthorizationError(message, code, details, requestId);\n\n case 404:\n return new NotFoundError(message, code, details, requestId);\n\n case 409:\n return new ConflictError(message, details, requestId);\n\n case 429: {\n const retryAfter = details?.retryAfter as number | undefined;\n return new RateLimitError(message, retryAfter, details, requestId);\n }\n\n default:\n if (status >= 500) {\n return new ServerError(message, status, details, requestId);\n }\n return new CadraError(message, code, status, details, requestId);\n }\n}\n","/**\n * AI function errors (p93 AIF-010, specs §9 + D27c).\n *\n * All extend the existing hierarchy so `instanceof CadraError` (and, where it\n * applies, `ConflictError` / `ValidationError`) keeps working.\n */\n\nimport type { AiFunctionParameterIssue } from '../types/ai-functions.js';\nimport { CadraError, ConflictError, ValidationError } from './sdk-errors.js';\n\n/**\n * 409 `DUPLICATE_REQUEST`: a run with the same idempotency key already exists.\n * No provider call was made. A retry after `abandoned` or a failure needs a NEW key.\n */\nexport class AiFunctionDuplicateError extends ConflictError {\n /** The existing run's execution id. */\n readonly executionId?: string;\n /** The existing run's status (`running`, a terminal status, or `abandoned`). */\n readonly runStatus?: string;\n\n constructor(\n message: string,\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, details, requestId);\n this.name = 'AiFunctionDuplicateError';\n this.serverCode = 'DUPLICATE_REQUEST';\n this.executionId = typeof details?.executionId === 'string' ? details.executionId : undefined;\n this.runStatus = typeof details?.status === 'string' ? details.status : undefined;\n }\n}\n\n/**\n * The provider answered 2xx and the run WAS metered, but the output then failed\n * (`OUTPUT_INVALID`, `DELIVERY_FAILED` — `details.charged: true`). Never retry\n * automatically: a retry is a second paid call.\n */\nexport class AiFunctionChargedError extends CadraError {\n constructor(source: CadraError) {\n super(source.message, source.code, source.status, source.details, source.requestId);\n this.name = 'AiFunctionChargedError';\n this.serverCode = source.serverCode;\n }\n}\n\n/**\n * The client-side parameter check failed (D27c). No run request was sent.\n * Also a `ValidationError`, with one `errors[]` entry per issue.\n */\nexport class AiFunctionParameterError extends ValidationError {\n readonly functionKey: string;\n readonly issues: AiFunctionParameterIssue[];\n\n constructor(functionKey: string, issues: AiFunctionParameterIssue[]) {\n super(\n `Invalid parameters for AI function \"${functionKey}\": ` +\n issues.map((i) => `${i.name} (${i.code})`).join(', '),\n issues.map((i) => ({ field: i.name, message: i.code })),\n { functionKey, issues }\n );\n this.name = 'AiFunctionParameterError';\n this.functionKey = functionKey;\n this.issues = issues;\n }\n}\n","/**\n * Retry utility with exponential backoff\n */\n\nimport { RateLimitError, ServerError } from '../errors/index.js';\n\n/**\n * Retry configuration\n */\nexport interface RetryConfig {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries: number;\n /** Base delay in milliseconds (default: 1000) */\n baseDelayMs: number;\n /** Maximum delay in milliseconds (default: 30000) */\n maxDelayMs: number;\n /** Jitter factor (0-1, default: 0.1) */\n jitterFactor: number;\n}\n\n/**\n * Default retry configuration\n */\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 3,\n baseDelayMs: 1000,\n maxDelayMs: 30000,\n jitterFactor: 0.1,\n};\n\n/**\n * Determine if an error should be retried\n */\nexport function shouldRetry(error: unknown, attempt: number, maxRetries: number): boolean {\n if (attempt >= maxRetries) {\n return false;\n }\n\n // Retry on rate limit errors\n if (error instanceof RateLimitError) {\n return true;\n }\n\n // Retry on 5xx server errors\n if (error instanceof ServerError) {\n return true;\n }\n\n // Retry on network errors\n if (error instanceof Error && error.name === 'NetworkError') {\n return true;\n }\n\n // Retry on timeout errors\n if (error instanceof Error && error.name === 'TimeoutError') {\n return true;\n }\n\n // Don't retry other errors (4xx except 429)\n return false;\n}\n\n/**\n * Calculate delay before next retry with exponential backoff and jitter\n */\nexport function calculateRetryDelay(\n attempt: number,\n config: RetryConfig,\n retryAfter?: number\n): number {\n // If server specified retry-after, use it\n if (retryAfter !== undefined && retryAfter > 0) {\n return retryAfter * 1000; // Convert seconds to milliseconds\n }\n\n // Exponential backoff: delay = base * 2^attempt\n const exponentialDelay = config.baseDelayMs * Math.pow(2, attempt);\n\n // Cap at max delay\n const cappedDelay = Math.min(exponentialDelay, config.maxDelayMs);\n\n // Add jitter to prevent thundering herd\n const jitter = cappedDelay * config.jitterFactor * Math.random();\n\n return cappedDelay + jitter;\n}\n\n/**\n * Sleep for specified milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry wrapper for async operations\n */\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n config: Partial<RetryConfig> = {}\n): Promise<T> {\n const fullConfig: RetryConfig = { ...DEFAULT_RETRY_CONFIG, ...config };\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= fullConfig.maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error;\n\n if (!shouldRetry(error, attempt, fullConfig.maxRetries)) {\n throw error;\n }\n\n // Get retry-after from rate limit error if available\n const retryAfter = error instanceof RateLimitError ? error.retryAfter : undefined;\n const delay = calculateRetryDelay(attempt, fullConfig, retryAfter);\n\n await sleep(delay);\n }\n }\n\n // Should never reach here, but TypeScript needs this\n throw lastError;\n}\n","/**\n * HTTP Client\n *\n * Handles all HTTP requests with authentication, retry logic, and error handling.\n */\n\nimport {\n parseApiError,\n NetworkError,\n TimeoutError,\n} from '../errors/index.js';\nimport type { ApiResponse, ApiSuccessResponse } from '../types/index.js';\nimport { withRetry, type RetryConfig } from './retry.js';\n\n/**\n * HTTP Client configuration\n */\nexport interface HttpClientConfig {\n /** Base URL for API requests */\n baseUrl: string;\n /** API key for authentication */\n apiKey?: string;\n /** OAuth token for authentication */\n token?: string;\n /** Token provider callback (called before each request) */\n tokenProvider?: () => Promise<string>;\n /** Organization ID */\n orgId: number;\n /** Request timeout in milliseconds (default: 30000) */\n timeout: number;\n /** Retry configuration */\n retry: RetryConfig;\n /** Custom headers */\n headers?: Record<string, string>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Request options\n */\nexport interface RequestOptions {\n /** HTTP method */\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';\n /** Request path (appended to base URL) */\n path: string;\n /** Request body */\n body?: unknown;\n /** Query parameters */\n query?: Record<string, string | number | boolean | undefined>;\n /** Additional headers */\n headers?: Record<string, string>;\n /** Skip retry (for non-idempotent operations) */\n skipRetry?: boolean;\n /** Idempotency key */\n idempotencyKey?: string;\n /**\n * Per-request timeout in milliseconds. Overrides the client-wide\n * `config.timeout` for this call only (p93 AIF-010: a paid AI-function run\n * waits for the server's route ceiling while every other call keeps the\n * 30 s default).\n */\n timeoutMs?: number;\n}\n\n/**\n * HTTP Client class\n */\nexport class HttpClient {\n private config: HttpClientConfig;\n private tokenRefreshAttempts = 0;\n private readonly maxTokenRefreshAttempts = 2;\n\n constructor(config: HttpClientConfig) {\n this.config = config;\n }\n\n /** The client-wide request timeout (ms) this client was configured with. */\n get timeoutMs(): number {\n return this.config.timeout;\n }\n\n /**\n * Get authorization header value\n */\n private async getAuthHeader(): Promise<string> {\n if (this.config.apiKey) {\n return `Bearer ${this.config.apiKey}`;\n }\n\n if (this.config.tokenProvider) {\n const token = await this.config.tokenProvider();\n return `Bearer ${token}`;\n }\n\n if (this.config.token) {\n return `Bearer ${this.config.token}`;\n }\n\n throw new Error('No authentication configured. Provide apiKey, token, or tokenProvider.');\n }\n\n /**\n * Build full URL with query parameters\n */\n private buildUrl(path: string, query?: Record<string, string | number | boolean | undefined>): string {\n // Simple concatenation — baseUrl is the origin (e.g., \"https://api.cadraos.com\"),\n // path already includes the full route (e.g., \"/api/v1/agents\").\n const base = this.config.baseUrl.replace(/\\/+$/, '');\n let url = `${base}${path}`;\n\n if (query) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n params.set(key, String(value));\n }\n }\n const qs = params.toString();\n if (qs) {\n url += `?${qs}`;\n }\n }\n\n return url;\n }\n\n /**\n * Make an HTTP request\n */\n async request<T>(options: RequestOptions): Promise<T> {\n const makeRequest = async (): Promise<T> => {\n const url = this.buildUrl(options.path, options.query);\n const authHeader = await this.getAuthHeader();\n\n const headers: Record<string, string> = {\n 'Authorization': authHeader,\n 'X-Org-Id': String(this.config.orgId),\n 'Content-Type': 'application/json',\n ...this.config.headers,\n ...options.headers,\n };\n\n // Add idempotency key for mutating operations\n if (options.idempotencyKey) {\n headers['Idempotency-Key'] = options.idempotencyKey;\n }\n\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutMs = options.timeoutMs ?? this.config.timeout;\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const doFetch = this.config.fetch ?? fetch;\n const response = await doFetch(url, {\n method: options.method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Get request ID from response headers\n const requestId = response.headers.get('X-Request-Id') ?? undefined;\n\n // Parse response body\n let body: unknown;\n const contentType = response.headers.get('Content-Type');\n if (contentType?.includes('application/json')) {\n body = await response.json();\n } else {\n body = await response.text();\n }\n\n // Handle errors\n if (!response.ok) {\n // Check for 401 and token provider - try refresh\n if (response.status === 401 && this.config.tokenProvider) {\n this.tokenRefreshAttempts++;\n if (this.tokenRefreshAttempts < this.maxTokenRefreshAttempts) {\n // Token provider should return a fresh token\n // Retry the request (token provider will be called again)\n return this.request(options);\n }\n }\n\n throw parseApiError(response.status, body, requestId);\n }\n\n // Reset token refresh attempts on success\n this.tokenRefreshAttempts = 0;\n\n // Handle success response\n const apiResponse = body as ApiResponse<T>;\n if ('success' in apiResponse && apiResponse.success) {\n return (apiResponse as ApiSuccessResponse<T>).data;\n }\n\n // If response doesn't match expected format, return as-is\n return body as T;\n\n } catch (error) {\n clearTimeout(timeoutId);\n\n // Handle abort (timeout)\n if (error instanceof Error && error.name === 'AbortError') {\n throw new TimeoutError(`Request timed out after ${options.timeoutMs ?? this.config.timeout}ms`);\n }\n\n // Handle fetch errors (network issues)\n if (error instanceof TypeError && error.message.includes('fetch')) {\n throw new NetworkError(`Network error: ${error.message}`);\n }\n\n throw error;\n }\n };\n\n // Use retry wrapper for idempotent operations\n if (options.skipRetry) {\n return makeRequest();\n }\n\n return withRetry(makeRequest, this.config.retry);\n }\n\n /**\n * GET request\n */\n async get<T>(\n path: string,\n query?: Record<string, string | number | boolean | undefined>\n ): Promise<T> {\n return this.request<T>({\n method: 'GET',\n path,\n query,\n });\n }\n\n /**\n * POST request\n */\n async post<T>(\n path: string,\n body?: unknown,\n options?: { idempotencyKey?: string; skipRetry?: boolean; timeoutMs?: number }\n ): Promise<T> {\n return this.request<T>({\n method: 'POST',\n path,\n body,\n idempotencyKey: options?.idempotencyKey,\n skipRetry: options?.skipRetry,\n timeoutMs: options?.timeoutMs,\n });\n }\n\n /**\n * PATCH request\n */\n async patch<T>(\n path: string,\n body?: unknown,\n options?: { idempotencyKey?: string; skipRetry?: boolean }\n ): Promise<T> {\n return this.request<T>({\n method: 'PATCH',\n path,\n body,\n idempotencyKey: options?.idempotencyKey,\n skipRetry: options?.skipRetry,\n });\n }\n\n /**\n * DELETE request\n */\n async delete<T>(path: string): Promise<T> {\n return this.request<T>({\n method: 'DELETE',\n path,\n skipRetry: true, // Don't retry deletes\n });\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<HttpClientConfig>): void {\n this.config = { ...this.config, ...config };\n }\n}\n\n/**\n * Generate a random idempotency key\n */\nexport function generateIdempotencyKey(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 15);\n return `idem_${timestamp}_${random}`;\n}\n\n/**\n * Generate an RFC-4122 v4 UUID for a client-prepared executionId.\n *\n * The `Idempotency-Key` HEADER is opaque, but cadra-web dedupes a duplicate\n * remote dispatch on the body `executionId` (a UUID). So to make the SDK's\n * automatic retries idempotent end-to-end, execute() must send a STABLE\n * executionId — not just the header. Prefers the platform `crypto.randomUUID()`\n * (modern browsers, Node 19+); falls back to a Math.random v4 only so the SDK\n * never hard-fails in unusual environments (the server accepts any valid UUID).\n */\nexport function generateExecutionId(): string {\n const g =\n typeof globalThis !== 'undefined'\n ? (globalThis as { crypto?: { randomUUID?: () => string } })\n : undefined;\n if (g?.crypto?.randomUUID) {\n return g.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n","/**\n * SSE Client\n *\n * Handles Server-Sent Events connections with automatic reconnection.\n * Uses fetch + ReadableStream for cross-platform compatibility.\n */\n\nimport type { SSEEvent, StreamEventType } from '../types/streaming.js';\n\n/**\n * SSE Client configuration\n */\nexport interface SSEClientConfig {\n /** Stream URL */\n url: string;\n /** Authorization header */\n authHeader: string;\n /** Organization ID */\n orgId: number;\n /** Event callback */\n onEvent: (event: SSEEvent) => void;\n /** Error callback */\n onError: (error: Error) => void;\n /** Connection state callback */\n onConnectionChange: (connected: boolean) => void;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n /**\n * Last event id seen on a previous connection. Sent as `Last-Event-ID` so the\n * server can replay only what was missed instead of the whole backlog. The\n * controller dedupes by event id regardless, so this is an optimisation, not\n * a correctness requirement.\n */\n lastEventId?: string | null;\n}\n\n/**\n * SSE Client class\n *\n * Implements SSE parsing using fetch + ReadableStream for compatibility\n * with both Node.js and browser environments.\n */\nexport class SSEClient {\n private config: SSEClientConfig;\n private abortController: AbortController | null = null;\n private connected = false;\n\n constructor(config: SSEClientConfig) {\n this.config = config;\n }\n\n /**\n * Connect to SSE endpoint\n */\n async connect(): Promise<void> {\n this.abortController = new AbortController();\n\n // Debug logging for SSE connection\n console.log('[SDK:SSE] Connecting to:', this.config.url);\n console.log('[SDK:SSE] Auth header:', this.config.authHeader ? `${this.config.authHeader.substring(0, 30)}...` : 'MISSING');\n console.log('[SDK:SSE] Org ID:', this.config.orgId);\n\n try {\n const doFetch = this.config.fetch ?? fetch;\n const response = await doFetch(this.config.url, {\n method: 'GET',\n headers: {\n 'Authorization': this.config.authHeader,\n 'X-Org-Id': String(this.config.orgId),\n 'Accept': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n ...(this.config.lastEventId ? { 'Last-Event-ID': this.config.lastEventId } : {}),\n },\n signal: this.abortController.signal,\n });\n\n console.log('[SDK:SSE] Response status:', response.status, response.statusText);\n console.log('[SDK:SSE] Response headers:', {\n contentType: response.headers.get('content-type'),\n cacheControl: response.headers.get('cache-control'),\n });\n\n if (!response.ok) {\n // Try to get error body for better debugging\n let errorBody = '';\n try {\n errorBody = await response.text();\n console.error('[SDK:SSE] Error response body:', errorBody);\n } catch (e) {\n console.error('[SDK:SSE] Could not read error body');\n }\n throw new Error(`SSE connection failed: ${response.status} ${response.statusText} - ${errorBody}`);\n }\n\n if (!response.body) {\n throw new Error('Response body not available');\n }\n\n console.log('[SDK:SSE] Connection successful, starting stream parsing');\n this.connected = true;\n this.config.onConnectionChange(true);\n\n // Parse SSE stream\n await this.parseStream(response.body);\n\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n // Intentional disconnect\n console.log('[SDK:SSE] Connection aborted (intentional)');\n return;\n }\n console.error('[SDK:SSE] Connection error:', error);\n this.config.onError(error instanceof Error ? error : new Error(String(error)));\n } finally {\n this.connected = false;\n this.config.onConnectionChange(false);\n console.log('[SDK:SSE] Connection closed');\n }\n }\n\n /**\n * Disconnect from SSE endpoint\n */\n disconnect(): void {\n if (this.abortController) {\n this.abortController.abort();\n this.abortController = null;\n }\n this.connected = false;\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.connected;\n }\n\n /**\n * Parse SSE stream\n */\n private async parseStream(body: ReadableStream<Uint8Array>): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n\n let buffer = '';\n let currentEvent: Partial<{ type: string; id: string; data: string }> = {};\n let chunkCount = 0;\n let eventCount = 0;\n\n console.log('[SDK:SSE] Starting to parse stream');\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n console.log('[SDK:SSE] Stream reading complete. Total chunks:', chunkCount, 'events:', eventCount);\n break;\n }\n\n chunkCount++;\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // Debug: Log raw chunk (first 200 chars)\n if (chunkCount <= 5) {\n console.log(`[SDK:SSE] Chunk ${chunkCount} (${value.length} bytes):`, chunk.substring(0, 200));\n }\n\n // Process complete lines\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? ''; // Keep incomplete line in buffer\n\n for (const line of lines) {\n // Empty line signals end of event\n if (line === '') {\n if (currentEvent.type && currentEvent.data !== undefined) {\n eventCount++;\n console.log(`[SDK:SSE] Event ${eventCount}:`, currentEvent.type, '- data length:', currentEvent.data.length);\n this.dispatchEvent(currentEvent as { type: string; id?: string; data: string });\n }\n currentEvent = {};\n continue;\n }\n\n // Skip comments (keepalive)\n if (line.startsWith(':')) {\n continue;\n }\n\n // Parse SSE fields\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) {\n continue;\n }\n\n const field = line.substring(0, colonIndex);\n // Value starts after colon, skip optional leading space\n let value = line.substring(colonIndex + 1);\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n\n switch (field) {\n case 'event':\n currentEvent.type = value;\n break;\n case 'id':\n currentEvent.id = value;\n break;\n case 'data':\n // Append to existing data (multiple data lines)\n currentEvent.data = currentEvent.data\n ? currentEvent.data + '\\n' + value\n : value;\n break;\n }\n }\n }\n } finally {\n console.log('[SDK:SSE] parseStream finished. Releasing reader lock.');\n reader.releaseLock();\n }\n }\n\n /**\n * Dispatch parsed event\n */\n private dispatchEvent(event: { type: string; id?: string; data: string }): void {\n console.log('[SDK:SSE] dispatchEvent called:', event.type, 'id:', event.id);\n\n try {\n // Parse JSON data\n let data: unknown;\n try {\n data = JSON.parse(event.data);\n console.log('[SDK:SSE] Parsed event data:', typeof data, data && typeof data === 'object' ? Object.keys(data as object) : '');\n } catch {\n // If not JSON, use raw string\n data = event.data;\n }\n\n const sseEvent: SSEEvent = {\n type: event.type as StreamEventType,\n id: event.id,\n data,\n };\n\n this.config.onEvent(sseEvent);\n } catch (error) {\n this.config.onError(\n error instanceof Error ? error : new Error(`Failed to parse event: ${String(error)}`)\n );\n }\n }\n}\n","/**\n * Image extraction utilities\n *\n * Pure, environment-agnostic functions for pulling image URLs out of agent\n * tool results and execution outputs. Works in Node and the browser, no\n * React or DOM dependencies.\n *\n * Used by:\n * - ExecutionStreamController — derives 'image' events from tool_result events\n * so any consumer can subscribe to images as they're generated.\n * - useAgentChat — renders image artifacts inline in chat messages.\n * - Server-side workers (Node) — persist images progressively without React.\n *\n * Recognised result shapes (in priority order):\n * 1. { images: [{ url, thumbnailUrl?, filename?, mimeType?, dimensions?, prompt? }, ...] }\n * Emitted by cadra-api's response-transformer for create_ad_images, edit_image,\n * and any tool that produces image artifacts.\n * 2. { url: '...png' } — single image with image extension.\n * 3. { imageUrl: '...' } — alternate single-image shape.\n * 4. JSON string wrapping any of the above (with optional ```json fence).\n * 5. Bare image URL string or data: URL.\n */\n\n/**\n * Image extracted from a tool result or execution output.\n *\n * Shape is a superset of historical chat ImageData — all extra fields are\n * optional, so existing chat consumers keep working unchanged.\n */\nexport interface ImageData {\n /** Full-size image URL (https) */\n url: string;\n /** Optional thumbnail URL (smaller, for chat / preview display) */\n thumbnailUrl?: string;\n /** Original filename */\n filename?: string;\n /** MIME type (e.g. image/png) */\n mimeType?: string;\n /** Alt text — falls back to the agent's prompt if no explicit alt was provided */\n alt?: string;\n /** Image width in pixels */\n width?: number;\n /** Image height in pixels */\n height?: number;\n /** ID of the tool call that produced this image (when extracted from a tool_result) */\n sourceToolCallId?: string;\n /** Execution UUID this image came from (when extracted via the streaming pipeline) */\n executionId?: string;\n}\n\n/**\n * Optional context applied to every extracted image.\n * Use this to attach the originating tool-call and execution IDs.\n */\nexport interface ExtractContext {\n sourceToolCallId?: string;\n executionId?: string;\n}\n\nconst IMAGE_EXT_RE = /\\.(png|jpg|jpeg|gif|webp|svg|bmp)(\\?.*)?$/i;\n\n/**\n * Extract images from a single tool result.\n *\n * @param result The tool result. May be an object, an already-parsed value,\n * or a JSON / URL string.\n * @param ctx Optional sourceToolCallId / executionId to attach to each\n * extracted image.\n */\nexport function extractImagesFromResult(\n result: unknown,\n ctx: ExtractContext = {}\n): ImageData[] {\n if (!result) return [];\n\n let data: unknown = result;\n\n if (typeof result === 'string') {\n // Bare image URL or data: URL? treat as a single image.\n if (IMAGE_EXT_RE.test(result) || result.startsWith('data:image/')) {\n return [{ url: normalizeUrl(result), sourceToolCallId: ctx.sourceToolCallId, executionId: ctx.executionId }];\n }\n // Otherwise try to parse as JSON (possibly wrapped in a code fence).\n const fence = result.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n const jsonStr = fence?.[1] ?? result;\n try {\n data = JSON.parse(jsonStr.trim());\n } catch {\n return [];\n }\n }\n\n if (typeof data !== 'object' || data === null) return [];\n const obj = data as Record<string, unknown>;\n\n // Pattern 1: { images: [...] } — preferred (cadra-api ResponseTransformer)\n if (Array.isArray(obj.images)) {\n return (obj.images as Array<Record<string, unknown>>)\n .filter((img) => img && typeof img.url === 'string')\n .map((img) => mapImage(img, ctx));\n }\n\n // Pattern 2: { url: \"...png\" }\n if (typeof obj.url === 'string' && IMAGE_EXT_RE.test(obj.url)) {\n return [mapImage(obj, ctx)];\n }\n\n // Pattern 3: { imageUrl: \"...\" }\n if (typeof obj.imageUrl === 'string') {\n return [{\n url: normalizeUrl(obj.imageUrl),\n thumbnailUrl: typeof obj.thumbnailUrl === 'string' ? normalizeUrl(obj.thumbnailUrl) : undefined,\n alt: (obj.alt as string) || (obj.prompt as string) || undefined,\n sourceToolCallId: ctx.sourceToolCallId,\n executionId: ctx.executionId,\n }];\n }\n\n return [];\n}\n\n/**\n * Extract images from a final execution output.\n *\n * Execution outputs are often JSON strings, sometimes wrapped in a markdown\n * `json` code fence. This helper unwraps + parses + delegates to\n * extractImagesFromResult.\n *\n * Use this when an execution has already completed and you have its\n * `output` field — for live executions, prefer subscribing to the\n * stream's `image` event.\n */\nexport function extractImagesFromExecutionOutput(\n output: unknown,\n ctx: ExtractContext = {}\n): ImageData[] {\n let parsed: unknown = output;\n\n if (typeof output === 'string') {\n const fence = output.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n const jsonStr = fence?.[1] ?? output;\n try {\n parsed = JSON.parse(jsonStr.trim());\n } catch {\n // Not JSON — try the bare-URL / data-URL fallbacks via extractImagesFromResult.\n return extractImagesFromResult(output, ctx);\n }\n }\n\n return extractImagesFromResult(parsed, ctx);\n}\n\n/**\n * Aggregate images from a list of completed tool calls.\n *\n * Used by chat-style consumers that maintain an ordered list of tool calls\n * and want a single source of truth for the displayed image list.\n */\nexport function deriveImagesFromToolCalls<\n T extends { id?: string; status?: string; result?: unknown }\n>(toolCalls: T[] | undefined, ctx: Omit<ExtractContext, 'sourceToolCallId'> = {}): ImageData[] {\n if (!toolCalls) return [];\n const images: ImageData[] = [];\n for (const tc of toolCalls) {\n if (tc.status === 'completed' && tc.result) {\n images.push(...extractImagesFromResult(tc.result, { ...ctx, sourceToolCallId: tc.id }));\n }\n }\n return images;\n}\n\n// =============================================================================\n// INTERNAL\n// =============================================================================\n\nfunction mapImage(img: Record<string, unknown>, ctx: ExtractContext): ImageData {\n const dims = img.dimensions as Record<string, unknown> | undefined;\n return {\n url: normalizeUrl(img.url as string),\n thumbnailUrl: typeof img.thumbnailUrl === 'string' ? normalizeUrl(img.thumbnailUrl) : undefined,\n filename: img.filename as string | undefined,\n mimeType: img.mimeType as string | undefined,\n alt: (img.alt as string) || (img.prompt as string) || undefined,\n width: typeof dims?.width === 'number' ? (dims.width as number) : (img.width as number | undefined),\n height: typeof dims?.height === 'number' ? (dims.height as number) : (img.height as number | undefined),\n sourceToolCallId: ctx.sourceToolCallId,\n executionId: ctx.executionId,\n };\n}\n\n/**\n * Cadra agents sometimes emit `LINK://` URLs to defeat auto-link rendering\n * in chat UIs. Convert those back to https for downstream consumers.\n */\nfunction normalizeUrl(url: string): string {\n if (url.startsWith('LINK://')) return url.replace('LINK://', 'https://');\n return url;\n}\n","/**\n * Poll Policy\n *\n * Backpressure helpers for the SSE fallback polling loop.\n *\n * The fallback loop talks to an API key that is shared with every other feature\n * on the same key. A loop that ignores 429 does not just fail itself — it burns\n * the shared quota and takes unrelated features down with it. These helpers give\n * the loop the two things it needs to be a good citizen: a structural way to\n * recognise \"the server told me to stop\", and a delay schedule that grows when\n * the loop is failing or learning nothing.\n *\n * Everything here is pure and synchronous so the loop's timing can be asserted\n * under fake timers.\n */\n\n/** Delay a rate-limited loop waits when the server named no reset (ms). */\nexport const UNNAMED_RATE_LIMIT_WAIT_MS = 60_000;\n\ntype Dict = Record<string, unknown>;\n\nfunction asDict(value: unknown): Dict | null {\n return typeof value === 'object' && value !== null ? (value as Dict) : null;\n}\n\n/** Error codes different layers use for the same 429 condition. */\nconst RATE_LIMIT_CODES = new Set([\n 'rate_limit_error',\n 'rate_limited',\n 'rate_limit_exceeded',\n 'too_many_requests',\n]);\n\n/**\n * Is this error a rate limit (429)?\n *\n * Detected STRUCTURALLY — by status/code/name — never with `instanceof`.\n * Consumers link this package rather than depending on a single installed copy,\n * so a `RateLimitError` thrown by their copy of the SDK is not `instanceof` our\n * copy's class. Identity checks silently return false across that boundary,\n * which is exactly how a 429 ends up looking like a transient blip.\n */\nexport function isRateLimited(error: unknown): boolean {\n if (typeof error === 'string') return /\\b429\\b/.test(error);\n\n const err = asDict(error);\n if (!err) return false;\n\n for (const key of ['status', 'statusCode', 'httpStatus', 'code']) {\n if (err[key] === 429 || err[key] === '429') return true;\n }\n\n const response = asDict(err.response);\n if (response && (response.status === 429 || response.statusCode === 429)) return true;\n\n if (typeof err.code === 'string' && RATE_LIMIT_CODES.has(err.code.toLowerCase())) return true;\n if (err.name === 'RateLimitError') return true;\n\n const message = typeof err.message === 'string' ? err.message : '';\n return /\\b429\\b/.test(message)\n || /rate[\\s_-]?limit/i.test(message)\n || /too many requests/i.test(message);\n}\n\n/**\n * Read a header off whatever shape carries it — a `Headers` instance, a plain\n * object, or a lower/mixed-case bag.\n */\nfunction readHeader(bag: unknown, name: string): string | null {\n if (bag === null || bag === undefined) return null;\n\n const getter = (bag as { get?: unknown }).get;\n if (typeof getter === 'function') {\n try {\n const value = (getter as (n: string) => unknown).call(bag, name);\n if (value !== null && value !== undefined) return String(value);\n } catch {\n // Not Headers-like after all — fall through to the plain-object scan.\n }\n }\n\n const dict = asDict(bag);\n if (!dict) return null;\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(dict)) {\n if (key.toLowerCase() === wanted && value !== null && value !== undefined) {\n return String(value);\n }\n }\n return null;\n}\n\n/**\n * Parse a `Retry-After`-style value into milliseconds.\n * Accepts a delta in seconds (number or numeric string) or an HTTP-date.\n */\nfunction parseRetryAfter(raw: unknown, now: number): number | null {\n if (raw === null || raw === undefined) return null;\n\n if (typeof raw === 'number') {\n return Number.isFinite(raw) && raw >= 0 ? raw * 1000 : null;\n }\n if (typeof raw !== 'string') return null;\n\n const trimmed = raw.trim();\n if (trimmed === '') return null;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) return Number(trimmed) * 1000;\n\n const at = Date.parse(trimmed);\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n}\n\n/**\n * Parse an `X-RateLimit-Reset`-style value into milliseconds from now.\n * Accepts epoch seconds, epoch milliseconds, an ISO date, or a plain delta in\n * seconds — every one of which appears in the wild under this header name.\n */\nfunction parseResetAt(raw: unknown, now: number): number | null {\n if (raw === null || raw === undefined) return null;\n\n const numeric = typeof raw === 'number'\n ? raw\n : typeof raw === 'string' && /^\\d+(\\.\\d+)?$/.test(raw.trim())\n ? Number(raw.trim())\n : null;\n\n if (numeric !== null) {\n if (!Number.isFinite(numeric) || numeric < 0) return null;\n // Epoch milliseconds (~1.7e12) vs epoch seconds (~1.7e9) vs a small delta.\n if (numeric > 1e11) return Math.max(0, numeric - now);\n if (numeric > 1e9) return Math.max(0, numeric * 1000 - now);\n return numeric * 1000;\n }\n\n if (typeof raw !== 'string') return null;\n const at = Date.parse(raw.trim());\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n}\n\n/**\n * How long the server asked us to wait, in milliseconds, or `null` if it said\n * nothing usable.\n *\n * Checked in order of authority: the SDK's own `RateLimitError.retryAfter`\n * (seconds) first, then the error envelope's details, then the raw\n * `Retry-After` / `X-RateLimit-Reset` headers the API actually sets.\n */\nexport function getRetryAfterMs(error: unknown, now: number = Date.now()): number | null {\n const err = asDict(error);\n if (!err) return null;\n\n const details = asDict(err.details);\n const response = asDict(err.response);\n const body = asDict(err.body) ?? asDict(response?.data);\n const bodyError = asDict(body?.error);\n const bodyDetails = asDict(bodyError?.details) ?? asDict(body?.details);\n\n // Already-in-milliseconds fields win outright — no unit guessing.\n for (const source of [err, details, bodyDetails]) {\n const ms = source?.retryAfterMs;\n if (typeof ms === 'number' && Number.isFinite(ms) && ms >= 0) return ms;\n }\n\n // `retryAfter` is seconds everywhere it appears in this stack.\n for (const source of [err, details, bodyDetails, bodyError]) {\n const parsed = parseRetryAfter(source?.retryAfter, now);\n if (parsed !== null) return parsed;\n }\n\n const headerBags = [err.headers, response?.headers, details?.headers, body?.headers];\n for (const bag of headerBags) {\n const parsed = parseRetryAfter(readHeader(bag, 'retry-after'), now);\n if (parsed !== null) return parsed;\n }\n\n for (const source of [details, bodyDetails, err]) {\n for (const key of ['resetAt', 'reset', 'rateLimitReset']) {\n const parsed = parseResetAt(source?.[key], now);\n if (parsed !== null) return parsed;\n }\n }\n\n for (const bag of headerBags) {\n for (const header of ['x-ratelimit-reset', 'ratelimit-reset']) {\n const parsed = parseResetAt(readHeader(bag, header), now);\n if (parsed !== null) return parsed;\n }\n }\n\n return null;\n}\n\n/**\n * The HTTP status carried by an error, however the thrower spelled it.\n */\nexport function getHttpStatus(error: unknown): number | null {\n const err = asDict(error);\n if (!err) return null;\n\n for (const key of ['status', 'statusCode', 'httpStatus']) {\n const value = err[key];\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'string' && /^\\d{3}$/.test(value)) return Number(value);\n }\n\n const response = asDict(err.response);\n for (const key of ['status', 'statusCode']) {\n const value = response?.[key];\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n }\n\n return null;\n}\n\n/**\n * A 4xx that will not fix itself by asking again.\n *\n * Mirrors the SSE side's \"any 4xx is terminal\" rule, with two carve-outs:\n * 429 is backpressure (wait, don't quit) and 408 is a timeout (transient).\n * A 404 lands here — which is what a wrong path looks like, and previously it\n * was swallowed by a blanket catch and retried until the tab closed.\n */\nexport function isTerminalClientError(error: unknown): boolean {\n const status = getHttpStatus(error);\n if (status === null) return false;\n return status >= 400 && status < 500 && status !== 429 && status !== 408;\n}\n\n/** Growth applied to the delay after a failed poll. */\nexport const FAILURE_GROWTH_FACTOR = 2;\n\n/** Growth applied to the delay after a poll that learned nothing new. */\nexport const IDLE_GROWTH_FACTOR = 1.5;\n\n/**\n * Next delay after a poll that failed for a reason other than rate limiting.\n * Exponential, capped.\n */\nexport function nextFailureDelayMs(currentMs: number, maxMs: number): number {\n return Math.min(Math.max(currentMs, 1) * FAILURE_GROWTH_FACTOR, maxMs);\n}\n\n/**\n * Next delay after a successful poll that observed nothing new — no new logs\n * and no status change. This is the incident's exact shape: an execution that\n * finished long ago, polled at full rate for the lifetime of the tab. Decaying\n * toward the ceiling makes an idle tab cheap without making an active one slow.\n */\nexport function nextIdleDelayMs(currentMs: number, maxMs: number): number {\n return Math.min(Math.ceil(Math.max(currentMs, 1) * IDLE_GROWTH_FACTOR), maxMs);\n}\n\n/**\n * Add positive-only jitter so tabs that fell back together do not re-converge\n * into a synchronised wave. Positive-only matters: jitter must never shorten a\n * delay below what the server asked for.\n */\nexport function applyJitter(delayMs: number, ratio: number, random: () => number = Math.random): number {\n if (ratio <= 0) return delayMs;\n return Math.round(delayMs * (1 + random() * ratio));\n}\n","/**\n * Stream Controller\n *\n * Manages execution streaming with automatic reconnection and fallback to polling.\n * Implements the StreamController interface for type-safe event handling.\n */\n\nimport { SSEClient } from './sse-client.js';\nimport { extractImagesFromResult } from './extract-images.js';\nimport {\n isRateLimited,\n getRetryAfterMs,\n nextFailureDelayMs,\n nextIdleDelayMs,\n applyJitter,\n isTerminalClientError,\n getHttpStatus,\n UNNAMED_RATE_LIMIT_WAIT_MS,\n} from './poll-policy.js';\nimport { CadraError } from '../errors/index.js';\nimport type {\n StreamController,\n StreamEventMap,\n SSEEvent,\n StreamingStatus,\n StreamingConfig,\n CompleteEvent,\n ErrorEvent,\n} from '../types/streaming.js';\nimport type { AgentExecution, ExecutionLog, LogType } from '../types/agents.js';\n\n/**\n * Default streaming configuration\n *\n * `pollingIntervalMs` is deliberately 5000, not the 2000 it used to be. The\n * pressure is AGGREGATE — many concurrent executions in fallback, not one\n * runaway tab — so what matters is polls-per-execution across the fleet. On the\n * observed distribution (519 executions/24h in one org, mean 146s), a 2s cadence\n * costs ~73 requests per mean-length run; if those runs fall back, that alone\n * exceeds a 1000/hour key's entire daily budget. At 5s it is ~29, which fits\n * with headroom, while a median-length run still gets ~7 updates. Going slower\n * still (10s) would leave a median run with 3 updates and the user waiting up to\n * 10s past completion — a bad trade, because in fallback polling is the ONLY\n * channel the session has.\n *\n * 5s is a floor, not a period: the loop backs off from here toward\n * `pollingMaxIntervalMs` whenever it fails or learns nothing (see poll-policy),\n * so the cadence stays responsive exactly while there is something to report.\n */\nconst DEFAULT_STREAMING_CONFIG: StreamingConfig = {\n maxReconnectAttempts: 5,\n reconnectBaseDelayMs: 1000,\n reconnectMaxDelayMs: 10000,\n // NOTE (unchanged, deliberately): this watchdog force-disconnects a HEALTHY\n // SSE connection after 30s of silence and routes it through the same\n // handleConnectionError path as a real transport failure. Ordinary LLM\n // latency exceeds 30s routinely, so it fires against working streams — that\n // is what drives sessions into the polling fallback in the first place. The\n // fix is a server-side SSE heartbeat, not a bigger number here; raising this\n // is a guess against a moving target. Everything below only bounds what the\n // fallback costs once it has been entered.\n activityTimeoutMs: 30000,\n pollingIntervalMs: 5000,\n pollingMaxIntervalMs: 30000,\n pollingMaxConsecutiveFailures: 10,\n pollingMaxConsecutiveRateLimits: 3,\n pollingMaxConsecutiveClientErrors: 3,\n pollingMaxDurationMs: 1800000,\n pollingMaxRetryAfterMs: 300000,\n pollingJitterRatio: 0.1,\n sseRetryIntervalMs: 60000,\n};\n\n/**\n * Default polling enabled state — polling fallback activates automatically\n * when SSE reconnection attempts are exhausted.\n */\nconst DEFAULT_POLLING_ENABLED = true;\n\n/**\n * Stream controller creation options\n */\nexport interface ExecutionStreamControllerOptions {\n /** Execution ID to stream */\n executionId: string;\n /** Session ID for conversation continuity */\n sessionId?: string;\n /** Base URL for API */\n baseUrl: string;\n /** API key or token */\n apiKey?: string;\n /** Token provider callback for dynamic auth */\n tokenProvider?: () => Promise<string>;\n /** Organization ID */\n orgId: number;\n /** Function to get execution status (for polling fallback) */\n getExecution: (executionId: string) => Promise<AgentExecution>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n /** Streaming configuration */\n config?: Partial<StreamingConfig>;\n /** Whether polling fallback is enabled (default: true) */\n pollingEnabled?: boolean;\n}\n\n/**\n * Execution Stream Controller\n *\n * Manages the lifecycle of an execution stream, including:\n * - SSE connection management\n * - Automatic reconnection with exponential backoff\n * - Fallback to polling on connection failure\n * - Event deduplication\n */\nexport interface ExecutionStreamController extends StreamController {\n /** Connect to the stream */\n connect(): Promise<void>;\n /** Get the execution ID */\n readonly executionId: string;\n /** Get the session ID (if available) */\n readonly sessionId: string | undefined;\n}\n\n/**\n * Internal implementation of ExecutionStreamController\n */\nclass ExecutionStreamControllerImpl implements ExecutionStreamController {\n private options: ExecutionStreamControllerOptions;\n private config: StreamingConfig;\n private pollingEnabled: boolean;\n private sseClient: SSEClient | null = null;\n private status: StreamingStatus = 'connecting';\n private reconnectAttempts = 0;\n private seenEventIds = new Set<string>();\n private _lastEventId: string | null = null;\n private activityTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private finalExecution: AgentExecution | null = null;\n private finalError: ErrorEvent | null = null;\n\n // --- Fallback polling state ---\n // A self-rescheduling timeout, not setInterval: the delay has to change\n // between ticks (that is what backoff IS), and a timeout chain also cannot\n // stack overlapping requests the way a fixed interval does when the API is\n // slow to answer.\n private pollTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private pollDelayMs = 0;\n private pollConsecutiveFailures = 0;\n private pollConsecutiveRateLimits = 0;\n private pollConsecutiveClientErrors = 0;\n /** When the loop last observed anything new — the clock the give-up bound runs on. */\n private pollLastProgressAt = 0;\n private pollInFlight = false;\n private lastPolledStatus: string | null = null;\n private sseRetryTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private sseRetryInFlight = false;\n\n // Event callbacks\n private listeners: {\n log: Array<(log: ExecutionLog) => void>;\n toolCall: Array<(data: StreamEventMap['toolCall']) => void>;\n toolResult: Array<(data: StreamEventMap['toolResult']) => void>;\n image: Array<(data: StreamEventMap['image']) => void>;\n plan: Array<(data: StreamEventMap['plan']) => void>;\n paused: Array<(data: StreamEventMap['paused']) => void>;\n started: Array<(data: StreamEventMap['started']) => void>;\n progress: Array<(data: StreamEventMap['progress']) => void>;\n taskListUpdate: Array<(data: StreamEventMap['taskListUpdate']) => void>;\n delegationStarted: Array<(data: StreamEventMap['delegationStarted']) => void>;\n delegationCompleted: Array<(data: StreamEventMap['delegationCompleted']) => void>;\n textDelta: Array<(data: StreamEventMap['textDelta']) => void>;\n narration: Array<(data: StreamEventMap['narration']) => void>;\n complete: Array<(data: CompleteEvent) => void>;\n error: Array<(error: ErrorEvent) => void>;\n connectionChange: Array<(data: StreamEventMap['connectionChange']) => void>;\n } = {\n log: [],\n toolCall: [],\n toolResult: [],\n image: [],\n plan: [],\n paused: [],\n started: [],\n progress: [],\n taskListUpdate: [],\n delegationStarted: [],\n delegationCompleted: [],\n textDelta: [],\n narration: [],\n complete: [],\n error: [],\n connectionChange: [],\n };\n\n // Promise for wait()\n private waitPromise: Promise<AgentExecution> | null = null;\n private waitResolve: ((execution: AgentExecution) => void) | null = null;\n private waitReject: ((error: Error) => void) | null = null;\n\n constructor(options: ExecutionStreamControllerOptions) {\n this.options = options;\n this.config = { ...DEFAULT_STREAMING_CONFIG, ...options.config };\n this.pollingEnabled = options.pollingEnabled ?? DEFAULT_POLLING_ENABLED;\n }\n\n // Resolved fallback-poll settings. Read through `??` rather than off the\n // spread config so an explicit `undefined` in a caller's partial config still\n // lands on the default instead of NaN-ing the arithmetic.\n private get pollBaseIntervalMs(): number {\n return this.config.pollingIntervalMs ?? DEFAULT_STREAMING_CONFIG.pollingIntervalMs;\n }\n private get pollMaxIntervalMs(): number {\n return Math.max(\n this.config.pollingMaxIntervalMs ?? DEFAULT_STREAMING_CONFIG.pollingMaxIntervalMs!,\n this.pollBaseIntervalMs\n );\n }\n private get pollMaxConsecutiveFailures(): number {\n return this.config.pollingMaxConsecutiveFailures ?? DEFAULT_STREAMING_CONFIG.pollingMaxConsecutiveFailures!;\n }\n private get pollMaxConsecutiveRateLimits(): number {\n return this.config.pollingMaxConsecutiveRateLimits ?? DEFAULT_STREAMING_CONFIG.pollingMaxConsecutiveRateLimits!;\n }\n private get pollMaxConsecutiveClientErrors(): number {\n return this.config.pollingMaxConsecutiveClientErrors ?? DEFAULT_STREAMING_CONFIG.pollingMaxConsecutiveClientErrors!;\n }\n private get pollMaxDurationMs(): number {\n return this.config.pollingMaxDurationMs ?? DEFAULT_STREAMING_CONFIG.pollingMaxDurationMs!;\n }\n private get pollMaxRetryAfterMs(): number {\n return this.config.pollingMaxRetryAfterMs ?? DEFAULT_STREAMING_CONFIG.pollingMaxRetryAfterMs!;\n }\n private get pollJitterRatio(): number {\n return this.config.pollingJitterRatio ?? DEFAULT_STREAMING_CONFIG.pollingJitterRatio!;\n }\n private get sseRetryIntervalMs(): number {\n return this.config.sseRetryIntervalMs ?? DEFAULT_STREAMING_CONFIG.sseRetryIntervalMs!;\n }\n\n /**\n * Get the last event ID (for resume support)\n */\n get lastEventId(): string | null {\n return this._lastEventId;\n }\n\n /**\n * Get the execution ID\n */\n get executionId(): string {\n return this.options.executionId;\n }\n\n /**\n * Get the session ID (if available)\n */\n get sessionId(): string | undefined {\n return this.options.sessionId;\n }\n\n /**\n * Connect to the execution stream\n */\n async connect(): Promise<void> {\n this.status = 'connecting';\n this.reconnectAttempts = 0;\n\n try {\n await this.connectSSE();\n } catch (error) {\n await this.handleConnectionError(error);\n }\n }\n\n /**\n * Register event listener\n */\n on<K extends keyof StreamEventMap>(\n event: K,\n callback: (data: StreamEventMap[K]) => void\n ): void {\n const listeners = this.listeners[event];\n if (listeners) {\n // Type assertion needed due to variance issues\n (listeners as Array<(data: StreamEventMap[K]) => void>).push(callback);\n }\n }\n\n /**\n * Cancel the stream\n */\n cancel(): void {\n this.status = 'closed';\n this.stopActivityTimeout();\n this.stopPolling();\n\n if (this.sseClient) {\n this.sseClient.disconnect();\n this.sseClient = null;\n }\n }\n\n /**\n * Wait for completion\n */\n wait(): Promise<AgentExecution> {\n // If already complete, return immediately\n if (this.finalExecution) {\n return Promise.resolve(this.finalExecution);\n }\n if (this.finalError) {\n return Promise.reject(new CadraError(\n this.finalError.error,\n this.finalError.errorCode ?? 'execution_error',\n 500\n ));\n }\n\n // Create promise if not exists\n if (!this.waitPromise) {\n this.waitPromise = new Promise((resolve, reject) => {\n this.waitResolve = resolve;\n this.waitReject = reject;\n });\n }\n\n return this.waitPromise;\n }\n\n // ===== Private methods =====\n\n /**\n * Connect to SSE endpoint\n */\n private async connectSSE(): Promise<void> {\n const base = this.options.baseUrl.replace(/\\/+$/, '');\n const url = `${base}/api/v1/agents/runs/${this.options.executionId}/stream`;\n\n // Resolve auth token: apiKey takes priority, then tokenProvider\n let authToken = this.options.apiKey;\n if (!authToken && this.options.tokenProvider) {\n authToken = await this.options.tokenProvider();\n }\n\n console.log('[SDK:StreamController] Connecting to SSE');\n console.log('[SDK:StreamController] URL:', url);\n console.log('[SDK:StreamController] baseUrl:', this.options.baseUrl);\n console.log('[SDK:StreamController] executionId:', this.options.executionId);\n console.log('[SDK:StreamController] orgId:', this.options.orgId);\n console.log('[SDK:StreamController] apiKey:', authToken ? `${authToken.substring(0, 20)}...` : 'MISSING');\n\n // Never leave a previous client subscribed. Reconnects and the fallback's\n // periodic SSE re-attempt both land here, and two live SSEClients on one\n // execution means every event arrives twice.\n if (this.sseClient) {\n this.sseClient.disconnect();\n this.sseClient = null;\n }\n\n // Callbacks are gated on `client` still being the current one. A replaced\n // client's teardown emits one last onConnectionChange(false) as its stream\n // unwinds; without this gate that stale report lands after the replacement\n // has already reported connected, and stale events would be injected too.\n const client: SSEClient = new SSEClient({\n url,\n authHeader: `Bearer ${authToken}`,\n orgId: this.options.orgId,\n fetch: this.options.fetch,\n // Resume from where this session left off. On a first connect this is\n // null and the header is omitted.\n lastEventId: this._lastEventId,\n onEvent: (event) => {\n if (this.sseClient !== client) return;\n this.handleEvent(event);\n },\n onError: (error) => {\n if (this.sseClient !== client) return;\n console.error('[SDK:StreamController] SSE error:', error);\n this.handleConnectionError(error);\n },\n onConnectionChange: (connected) => {\n if (this.sseClient !== client) return;\n console.log('[SDK:StreamController] SSE connection change:', connected);\n if (connected) {\n // The single place a live SSE stream is observed — so the single\n // place the fallback loop is retired. Whether this connection came\n // from connect(), the reconnect ladder, or the fallback's periodic\n // re-attempt, polling must not survive alongside a working stream.\n this.status = 'connected';\n this.reconnectAttempts = 0;\n this.stopPolling();\n this.resetActivityTimeout();\n }\n this.emit('connectionChange', {\n connected,\n usingFallback: this.status === 'fallback_polling',\n });\n },\n });\n\n this.sseClient = client;\n\n try {\n // Resolves when the stream ENDS, not when it opens — the open is reported\n // through onConnectionChange above.\n await client.connect();\n console.log('[SDK:StreamController] SSE connect() completed');\n } catch (error) {\n console.error('[SDK:StreamController] SSE connect() threw:', error);\n throw error;\n }\n }\n\n /**\n * Handle incoming SSE event\n */\n private handleEvent(event: SSEEvent): void {\n console.log('[SDK:StreamController] handleEvent called:', event.type, 'id:', event.id);\n\n // Reset activity timeout\n this.resetActivityTimeout();\n\n // Deduplicate by event ID\n if (event.id) {\n if (this.seenEventIds.has(event.id)) {\n console.log('[SDK:StreamController] Skipping duplicate event:', event.id);\n return;\n }\n this.seenEventIds.add(event.id);\n this._lastEventId = event.id;\n\n // Limit set size to prevent memory leaks\n if (this.seenEventIds.size > 1000) {\n const ids = Array.from(this.seenEventIds);\n this.seenEventIds = new Set(ids.slice(-500));\n }\n }\n\n // Map wire format (snake_case) to SDK format (camelCase)\n const data = event.data as Record<string, unknown>;\n console.log('[SDK:StreamController] Event data keys:', Object.keys(data));\n\n switch (event.type) {\n case 'log': {\n // Transform log-collector format to ExecutionLog format\n // Log-collector sends: { stepIndex, logType, message, metadata, timestamp, durationMs }\n // ExecutionLog expects: { uuid, type, title, content, metadata, timestamp, durationMs }\n const rawLog = data.log as Record<string, unknown> | undefined;\n if (!rawLog) {\n console.warn('[StreamController] Received log event without log data');\n break;\n }\n\n // Get the log type - log-collector uses 'logType', fallback to 'type'\n const logTypeValue = (rawLog.logType as string) || (rawLog.type as string) || 'info';\n\n const transformedLog: ExecutionLog = {\n uuid: (rawLog.uuid as string) || `log-${rawLog.stepIndex || Date.now()}`,\n type: logTypeValue as LogType,\n title: (rawLog.message as string) || (rawLog.title as string) || '',\n content: rawLog.content as string | undefined,\n metadata: {\n ...(rawLog.metadata as Record<string, unknown> || {}),\n // Include stepIndex in metadata for deduplication\n stepIndex: rawLog.stepIndex as number ?? 0,\n },\n timestamp: rawLog.timestamp as string || new Date().toISOString(),\n durationMs: rawLog.durationMs as number | undefined,\n // Pass through forwarded-from flag (set by cadra-api's\n // subscribeAndForwardEvents on sub-agent events). Wire field\n // is `_forwardedFrom` at the top of event.data.\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n };\n\n this.emit('log', transformedLog);\n break;\n }\n\n case 'tool_call':\n // Fix: Handle undefined toolName gracefully (defensive coding)\n this.emit('toolCall', {\n toolCallId: data.toolCallId as string || `tool-call-${Date.now()}`,\n toolName: (data.toolName as string) || 'Unknown Tool',\n inputs: (data.args as Record<string, unknown>) || {},\n stepIndex: data.stepIndex as number ?? 0,\n // Pass through forwarded-from flag (set by cadra-api's\n // subscribeAndForwardEvents on sub-agent events). Wire field\n // is `_forwardedFrom` per redis-manager.ts:232.\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n // CAD-87 S1-001 EventIdentity → (execId, seq) reducer dedup (S1-003).\n sourceExecutionId: (data.sourceExecutionId as string) ?? (data.executionId as string | undefined),\n seq: data.seq as number | undefined,\n });\n break;\n\n case 'tool_result': {\n // Fix: Handle undefined toolName gracefully (defensive coding)\n const toolCallId = (data.toolCallId as string) || `tool-result-${Date.now()}`;\n const toolName = (data.toolName as string) || 'Unknown Tool';\n this.emit('toolResult', {\n toolCallId,\n toolName,\n result: data.result,\n durationMs: data.durationMs as number ?? 0,\n // CAD-243: pass the producer's failure verdict through.\n ...(data.isError === true ? { isError: true } : {}),\n ...(typeof data.status === 'string' ? { status: data.status } : {}),\n ...(typeof data.error === 'string' ? { error: data.error } : {}),\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n // CAD-87 S1-001 EventIdentity → (execId, seq) reducer dedup (S1-003).\n sourceExecutionId: (data.sourceExecutionId as string) ?? (data.executionId as string | undefined),\n seq: data.seq as number | undefined,\n });\n\n // Derived event: emit one `image` per image found in the result.\n // Lets any consumer (chat UI, server worker) react to images progressively\n // without parsing tool results themselves.\n const images = extractImagesFromResult(data.result, {\n sourceToolCallId: toolCallId,\n executionId: this.options.executionId,\n });\n for (const img of images) {\n this.emit('image', {\n ...img,\n executionId: this.options.executionId,\n sourceToolCallId: toolCallId,\n toolName,\n });\n }\n break;\n }\n\n case 'execution_paused':\n // Handle ask_user paused event\n this.emit('paused', {\n question: data.question as string || data.output as string || '',\n options: data.options as string[] | undefined,\n reason: 'waiting_user_input',\n });\n break;\n\n case 'complete':\n this.handleComplete(data);\n break;\n\n case 'error':\n this.handleError({\n error: data.error as string,\n errorCode: data.errorCode as string | undefined,\n });\n break;\n case 'failed':\n // Some SSE endpoints emit \"failed\" instead of \"error\"\n this.handleError({\n error: (data.error as string) || (data.message as string) || 'Execution failed',\n errorCode: (data.errorCode as string | undefined) || 'execution_failed',\n });\n break;\n\n case 'timeout':\n if ((data as { retryable?: boolean }).retryable) {\n this.handleConnectionError(new Error('Stream timeout'));\n } else {\n this.handleError({\n error: data.error as string,\n errorCode: 'timeout',\n });\n }\n break;\n\n // Handle started event - immediate feedback that execution began\n case 'started':\n this.emit('started', {\n executionId: data.executionId as string,\n agentUuid: data.agentUuid as string,\n status: 'initializing',\n currentStep: data.currentStep as string | undefined,\n });\n break;\n\n // Handle progress event - status updates during execution\n case 'progress':\n this.emit('progress', {\n status: data.status as 'initializing' | 'thinking' | 'acting' | 'observing' | 'planning' | 'paused',\n iteration: data.iteration as number ?? 0,\n currentStep: data.currentStep as string | undefined,\n tokenUsage: data.tokenUsage as { prompt: number; completion: number; total: number } | undefined,\n cost: data.cost as number | undefined,\n toolCalls: data.toolCalls as number | undefined,\n // Forwarded specialist activity → rolling line attribution. Wire\n // fields `_forwardedFrom` / `_subagentName` sit at event.data top level.\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n subagentName: (event.data as Record<string, unknown>)._subagentName as string | undefined,\n });\n break;\n\n // Handle task list update event from TaskTracker\n case 'task_list_update':\n this.emit('taskListUpdate', {\n executionId: data.executionId as string,\n tasks: data.tasks as Array<{\n id: string;\n content: string;\n activeForm?: string | null;\n status: 'pending' | 'in_progress' | 'completed';\n }>,\n timestamp: data.timestamp as string,\n });\n break;\n\n // Handle delegation started event (handoff_to_agent initiated)\n case 'delegation_started':\n this.emit('delegationStarted', {\n type: 'delegation_started',\n handoffId: data.handoffId as string,\n targetAgentUuid: data.targetAgentUuid as string,\n targetAgentName: data.targetAgentName as string | undefined,\n taskPreview: data.taskPreview as string,\n timestamp: data.timestamp as string || new Date().toISOString(),\n });\n break;\n\n // Handle delegation completed event (handoff_to_agent finished)\n case 'delegation_completed':\n this.emit('delegationCompleted', {\n type: 'delegation_completed',\n handoffId: data.handoffId as string,\n status: data.status as 'completed' | 'failed',\n resultPreview: data.resultPreview as string | undefined,\n error: data.error as string | undefined,\n durationMs: data.durationMs as number,\n timestamp: data.timestamp as string || new Date().toISOString(),\n });\n break;\n\n // Handle status_update event - immediate feedback (e.g., \"thinking\")\n // Map to progress event for consistency\n case 'status_update':\n this.emit('progress', {\n status: (data.status as 'thinking' | 'initializing' | 'acting' | 'observing' | 'planning' | 'paused') || 'thinking',\n iteration: 0,\n currentStep: data.message as string | undefined,\n // Forwarded specialist status → rolling line attribution.\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n subagentName: (event.data as Record<string, unknown>)._subagentName as string | undefined,\n });\n break;\n\n // Handle text_delta event - token-by-token streaming\n case 'text_delta':\n this.emit('textDelta', {\n delta: data.delta as string,\n executionId: data.executionId as string,\n timestamp: data.timestamp as string || new Date().toISOString(),\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n // CAD-87 S1-001 EventIdentity → (execId, seq) reducer dedup (S1-003).\n sourceExecutionId: (data.sourceExecutionId as string) ?? (data.executionId as string | undefined),\n seq: data.seq as number | undefined,\n });\n break;\n\n // Handle narration event - clean per-step narration sentence (CAD\n // forwarded-narration). Native events (no forwardedFrom) mirror the\n // parent's own text_delta and are ignored by the chat hook; FORWARDED\n // events carry a specialist's narration during a handoff (its text_delta\n // is intentionally not forwarded) tagged `_subagentName`.\n case 'narration':\n this.emit('narration', {\n text: data.text as string,\n executionId: data.executionId as string | undefined,\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n subagentName: (event.data as Record<string, unknown>)._subagentName as string | undefined,\n iteration: data.iteration as number | undefined,\n timestamp: (data.timestamp as string) || new Date().toISOString(),\n // CAD-87 S1-001 EventIdentity → (execId, seq) reducer dedup (S1-003).\n // The FORWARDED specialist narration keeps the CHILD's sourceExecutionId\n // + seq (preserved through the forward), so its resume replay dedups too.\n sourceExecutionId: (data.sourceExecutionId as string) ?? (data.executionId as string | undefined),\n seq: data.seq as number | undefined,\n // CAD-87 S1-002: the producer role — the reducer renders a native\n // `terminal_answer` as the answer (text), not a narration block.\n role: data.role as StreamEventMap['narration']['role'],\n });\n break;\n\n // Ignore connection-related and intermediate events\n case 'connected':\n case 'subscribed':\n case 'step':\n case 'step_complete':\n break;\n }\n }\n\n /**\n * Handle completion\n */\n private handleComplete(data: Record<string, unknown>): void {\n this.status = 'closed';\n this.stopActivityTimeout();\n // Any terminal observation retires the fallback loop, no matter which path\n // observed it (SSE, state recovery, or a poll tick).\n this.stopPolling();\n\n // sessionId can come from SSE event data or from the initial execute response\n const sessionId = (data.sessionId as string | undefined) ?? this.options.sessionId;\n\n const execution: AgentExecution = {\n uuid: this.options.executionId,\n agentUuid: '',\n sessionId,\n status: 'completed',\n input: { task: '' },\n output: data.output as string | undefined,\n logs: [],\n tokenUsage: data.tokenUsage as AgentExecution['tokenUsage'],\n cost: data.cost as number | undefined,\n queuedAt: '',\n ...data,\n };\n\n this.finalExecution = execution;\n this.emit('complete', { execution });\n\n if (this.waitResolve) {\n this.waitResolve(execution);\n }\n }\n\n /**\n * Handle error\n */\n private handleError(error: ErrorEvent): void {\n this.status = 'closed';\n this.stopActivityTimeout();\n this.stopPolling();\n\n this.finalError = error;\n this.emit('error', error);\n\n if (this.waitReject) {\n this.waitReject(new CadraError(\n error.error,\n error.errorCode ?? 'execution_error',\n 500\n ));\n }\n }\n\n /**\n * Handle connection error\n */\n private async handleConnectionError(error: unknown): Promise<void> {\n if (this.status === 'closed') {\n return;\n }\n\n // Permanent (4xx) failures won't fix themselves — auth rejected, bad/expired\n // run id, missing scope. Retrying floods the server and leaks connections\n // (each retry holds a privileged-DB connection on the stream route). Treat\n // any 4xx as terminal: stop, surface the error, and close.\n const msg = error instanceof Error ? error.message : String(error);\n if (/\\b4\\d\\d\\b/.test(msg) || /INVALID_API_KEY|INVALID_REQUEST/.test(msg)) {\n // Tear down the SSE then surface a terminal error (no reconnect).\n if (this.sseClient) {\n this.sseClient.disconnect();\n this.sseClient = null;\n }\n this.handleError({ error: msg, errorCode: 'stream_unrecoverable' });\n return;\n }\n\n // Already in fallback: the poll loop plus its periodic SSE re-attempt own\n // recovery from here. Re-entering the reconnect ladder would spawn a second\n // poll loop and a second connectionChange storm for every failed re-attempt.\n if (this.status === 'fallback_polling') {\n this.startPolling(); // no-op when the loop is already running\n return;\n }\n\n // Attempt reconnection\n if (this.reconnectAttempts < this.config.maxReconnectAttempts) {\n this.status = 'reconnecting';\n this.reconnectAttempts++;\n\n const delay = Math.min(\n this.config.reconnectBaseDelayMs * Math.pow(2, this.reconnectAttempts),\n this.config.reconnectMaxDelayMs\n );\n\n await new Promise(resolve => setTimeout(resolve, delay));\n\n // Check if cancelled during delay (cancel() sets status to 'closed')\n if (this.status === 'closed' as StreamingStatus) {\n return;\n }\n\n // Before reconnecting SSE, check execution status to recover missed state.\n // This prevents missed events during the reconnection gap.\n await this.recoverState();\n\n // If state recovery found the execution is already done, don't reconnect\n if (this.status === 'closed' as StreamingStatus) {\n return;\n }\n\n try {\n await this.connectSSE();\n } catch {\n await this.handleConnectionError(error);\n }\n } else {\n // Fall back to polling (if enabled)\n if (this.pollingEnabled) {\n this.status = 'fallback_polling';\n this.emit('connectionChange', { connected: false, usingFallback: true });\n this.startPolling();\n } else {\n // Polling disabled — emit error and close\n this.handleError({\n error: 'SSE connection failed and polling is disabled',\n errorCode: 'connection_failed',\n });\n }\n }\n }\n\n /**\n * Recover state by checking execution status.\n *\n * Called during reconnection to catch any events missed while SSE was down.\n * If the execution completed while disconnected, emits completion immediately.\n * Otherwise, emits any new logs that weren't seen via SSE.\n */\n private async recoverState(): Promise<void> {\n try {\n const execution = await this.options.getExecution(this.options.executionId);\n\n // Emit any logs we haven't seen yet\n if (execution.logs) {\n for (const log of execution.logs) {\n if (!this.seenEventIds.has(log.uuid)) {\n this.seenEventIds.add(log.uuid);\n this.emit('log', log);\n }\n }\n }\n\n // If execution completed while we were disconnected, handle it\n if (execution.status === 'completed') {\n this.stopPolling();\n this.handleComplete(execution as unknown as Record<string, unknown>);\n return;\n }\n\n if (execution.status === 'failed' || execution.status === 'cancelled') {\n this.stopPolling();\n this.handleError({\n error: execution.error ?? `Execution ${execution.status}`,\n errorCode: execution.status,\n });\n return;\n }\n\n } catch (err) {\n // State recovery is best-effort — continue with reconnection\n console.warn('[SDK:StreamController] State recovery failed (non-fatal):', err);\n }\n }\n\n /**\n * Start polling fallback.\n *\n * Idempotent — calling it while a loop is already running is a no-op, so no\n * path can end up with two loops racing the same execution.\n */\n private startPolling(): void {\n if (this.pollTimeoutId !== null || this.pollInFlight) {\n return;\n }\n\n this.pollLastProgressAt = Date.now();\n this.pollDelayMs = this.pollBaseIntervalMs;\n this.pollConsecutiveFailures = 0;\n this.pollConsecutiveRateLimits = 0;\n this.pollConsecutiveClientErrors = 0;\n this.lastPolledStatus = null;\n\n // SSE is down; the activity watchdog has nothing left to watch and would\n // only re-enter handleConnectionError on a timer.\n this.stopActivityTimeout();\n\n this.scheduleSSERetry();\n this.schedulePoll(this.pollDelayMs);\n }\n\n /**\n * Queue the next poll tick.\n */\n private schedulePoll(delayMs: number): void {\n if (this.status !== 'fallback_polling') {\n return;\n }\n this.pollTimeoutId = setTimeout(() => {\n this.pollTimeoutId = null;\n void this.runPoll();\n }, Math.max(0, Math.round(delayMs)));\n }\n\n /**\n * One poll tick: fetch state, emit what is new, then decide how long to wait\n * before the next one — or whether there should be a next one at all.\n */\n private async runPoll(): Promise<void> {\n if (this.status !== 'fallback_polling') {\n return;\n }\n\n // The give-up bound, measured from the last thing the loop LEARNED rather\n // than from when it started. A loop still delivering logs is doing its job\n // and gets to keep going; a loop re-reading the same unchanged state has\n // proven it will not learn anything, and surfacing an error beats outliving\n // the tab. (The incident's session last did anything at 11:05 and was still\n // polling at 11:20 — squarely this branch.)\n if (Date.now() - this.pollLastProgressAt >= this.pollMaxDurationMs) {\n this.failPolling(\n `Streaming fallback gave up: no execution progress for ${Math.round(this.pollMaxDurationMs / 1000)}s`,\n 'polling_timeout'\n );\n return;\n }\n\n this.pollInFlight = true;\n try {\n const execution = await this.options.getExecution(this.options.executionId);\n\n this.pollConsecutiveFailures = 0;\n this.pollConsecutiveRateLimits = 0;\n this.pollConsecutiveClientErrors = 0;\n\n // Emit new logs\n let sawNewInfo = false;\n for (const log of execution.logs ?? []) {\n if (!this.seenEventIds.has(log.uuid)) {\n this.seenEventIds.add(log.uuid);\n this.emit('log', log);\n sawNewInfo = true;\n }\n }\n if (execution.status !== this.lastPolledStatus) {\n this.lastPolledStatus = execution.status;\n sawNewInfo = true;\n }\n if (sawNewInfo) {\n this.pollLastProgressAt = Date.now();\n }\n\n // Check for completion\n if (execution.status === 'completed') {\n this.stopPolling();\n this.handleComplete(execution as unknown as Record<string, unknown>);\n return;\n }\n if (execution.status === 'failed' || execution.status === 'cancelled') {\n this.stopPolling();\n this.handleError({\n error: execution.error ?? `Execution ${execution.status}`,\n errorCode: execution.status,\n });\n return;\n }\n\n // Active execution keeps the fast cadence; an idle one decays toward the\n // ceiling so a forgotten tab costs a request every 30s, not every 2s.\n this.pollDelayMs = sawNewInfo\n ? this.pollBaseIntervalMs\n : nextIdleDelayMs(this.pollDelayMs, this.pollMaxIntervalMs);\n } catch (error) {\n if (!this.handlePollError(error)) {\n return; // handlePollError already terminated the loop\n }\n } finally {\n this.pollInFlight = false;\n }\n\n this.schedulePoll(applyJitter(this.pollDelayMs, this.pollJitterRatio));\n }\n\n /**\n * Apply backpressure for a failed poll.\n *\n * @returns `true` to keep polling (with `pollDelayMs` updated), `false` when\n * the loop has been terminated.\n */\n private handlePollError(error: unknown): boolean {\n const retryAfterMs = getRetryAfterMs(error);\n const rateLimited = isRateLimited(error) || retryAfterMs !== null;\n\n if (rateLimited) {\n this.pollConsecutiveRateLimits++;\n console.warn(\n '[SDK:StreamController] Poll rate-limited',\n retryAfterMs !== null ? `(server asked for ${Math.round(retryAfterMs / 1000)}s)` : '(no reset named)'\n );\n\n // A reset this far out is not something to sit on holding a stream open.\n if (retryAfterMs !== null && retryAfterMs > this.pollMaxRetryAfterMs) {\n this.failPolling(\n `Rate limited: the API asked for ${Math.round(retryAfterMs / 1000)}s, longer than this stream will wait`,\n 'rate_limited'\n );\n return false;\n }\n\n // 429 is not transient noise — it means the quota window is spent. Probing\n // it further starves every other feature sharing the key, which is the\n // collateral damage that made this worth fixing in the first place.\n if (this.pollConsecutiveRateLimits >= this.pollMaxConsecutiveRateLimits) {\n this.failPolling(\n 'Rate limited by the API; stopped the streaming fallback rather than keep spending the key quota',\n 'rate_limited'\n );\n return false;\n }\n\n // Never sooner than the server said. When it named nothing, assume a\n // window measured in minutes — retrying inside one is pure waste.\n // Deliberately NOT clamped by pollMaxIntervalMs: the server's number wins.\n this.pollDelayMs = Math.max(retryAfterMs ?? UNNAMED_RATE_LIMIT_WAIT_MS, this.pollDelayMs);\n return true;\n }\n\n // A 4xx will not fix itself by asking again — wrong path, dead run id,\n // rejected auth, missing scope. Mirrors the SSE side's terminal-4xx rule,\n // but with a small tolerance rather than instant death: a poll issued\n // immediately after dispatch can legitimately 404 before the execution row\n // is readable. Blanket catch-and-continue meant a permanently wrong URL\n // (which is what the bare `/executions/{id}` path was) looked exactly like\n // a transient blip, forever.\n if (isTerminalClientError(error)) {\n this.pollConsecutiveClientErrors++;\n const status = getHttpStatus(error);\n console.warn(\n `[SDK:StreamController] Poll got HTTP ${status} (${this.pollConsecutiveClientErrors}/${this.pollMaxConsecutiveClientErrors})`\n );\n if (this.pollConsecutiveClientErrors >= this.pollMaxConsecutiveClientErrors) {\n this.failPolling(\n `Execution status endpoint returned HTTP ${status} ${this.pollConsecutiveClientErrors} times — cannot track this run`,\n 'polling_unrecoverable'\n );\n return false;\n }\n this.pollDelayMs = nextFailureDelayMs(this.pollDelayMs, this.pollMaxIntervalMs);\n return true;\n }\n\n this.pollConsecutiveFailures++;\n console.warn(\n `[SDK:StreamController] Poll failed (${this.pollConsecutiveFailures}/${this.pollMaxConsecutiveFailures}):`,\n error\n );\n\n if (this.pollConsecutiveFailures >= this.pollMaxConsecutiveFailures) {\n this.failPolling(\n `Streaming fallback failed ${this.pollConsecutiveFailures} times in a row`,\n 'polling_failed'\n );\n return false;\n }\n\n this.pollDelayMs = nextFailureDelayMs(this.pollDelayMs, this.pollMaxIntervalMs);\n return true;\n }\n\n /**\n * Terminate the fallback loop and surface the reason.\n */\n private failPolling(error: string, errorCode: string): void {\n this.stopPolling();\n this.handleError({ error, errorCode });\n }\n\n /**\n * Stop polling, including the periodic SSE re-attempt that belongs to it.\n */\n private stopPolling(): void {\n if (this.pollTimeoutId !== null) {\n clearTimeout(this.pollTimeoutId);\n this.pollTimeoutId = null;\n }\n if (this.sseRetryTimeoutId !== null) {\n clearTimeout(this.sseRetryTimeoutId);\n this.sseRetryTimeoutId = null;\n }\n }\n\n /**\n * Queue the next attempt to get the real stream back.\n */\n private scheduleSSERetry(): void {\n if (this.sseRetryTimeoutId !== null || this.status !== 'fallback_polling') {\n return;\n }\n this.sseRetryTimeoutId = setTimeout(() => {\n this.sseRetryTimeoutId = null;\n this.attemptSSERecovery();\n }, this.sseRetryIntervalMs);\n }\n\n /**\n * Re-attempt SSE from inside the fallback, so a transient outage costs the\n * session a few polls rather than its stream for the lifetime of the tab.\n *\n * Success is NOT observed here: `SSEClient.connect()` resolves when the\n * stream ENDS, not when it opens. The open is observed by\n * `onConnectionChange(true)`, which flips status and stops this loop. The\n * promise below only tells us the attempt is over so the next one can be\n * queued.\n */\n private attemptSSERecovery(): void {\n if (this.status !== 'fallback_polling') {\n return;\n }\n if (this.sseRetryInFlight) {\n this.scheduleSSERetry();\n return;\n }\n\n this.sseRetryInFlight = true;\n void this.connectSSE()\n .catch(() => {\n // Still down — the poll loop keeps carrying the session.\n })\n .finally(() => {\n this.sseRetryInFlight = false;\n this.scheduleSSERetry();\n });\n }\n\n /**\n * Reset activity timeout\n */\n private resetActivityTimeout(): void {\n this.stopActivityTimeout();\n\n this.activityTimeoutId = setTimeout(() => {\n // Force reconnect on inactivity\n if (this.sseClient) {\n this.sseClient.disconnect();\n }\n this.handleConnectionError(new Error('Activity timeout'));\n }, this.config.activityTimeoutMs);\n }\n\n /**\n * Stop activity timeout\n */\n private stopActivityTimeout(): void {\n if (this.activityTimeoutId) {\n clearTimeout(this.activityTimeoutId);\n this.activityTimeoutId = null;\n }\n }\n\n /**\n * Emit event to listeners\n */\n private emit<K extends keyof StreamEventMap>(event: K, data: StreamEventMap[K]): void {\n const listeners = this.listeners[event];\n console.log(`[SDK:StreamController] Emitting '${event}' to ${listeners?.length || 0} listeners`);\n if (listeners) {\n for (const listener of listeners) {\n try {\n (listener as (data: StreamEventMap[K]) => void)(data);\n } catch (error) {\n console.error(`Error in ${event} listener:`, error);\n }\n }\n }\n }\n}\n\n/**\n * Create an execution stream controller\n */\nexport function createExecutionStreamController(\n options: ExecutionStreamControllerOptions\n): ExecutionStreamController {\n return new ExecutionStreamControllerImpl(options);\n}\n","/**\n * Collect images from an execution stream.\n *\n * Awaitable wrapper around ExecutionStreamController that:\n * - Subscribes to `image` events and accumulates them in arrival order.\n * - On `complete`, falls back to parsing `execution.output` for any images\n * that didn't arrive via streaming (older agents, missed events on reconnect).\n * - Returns a Promise<{ images, output, executionId }> that resolves on\n * `complete` or rejects on `error`.\n *\n * Optional callbacks let the caller react progressively as images arrive\n * (e.g. persist to a DB, push to React state, log to disk) without having\n * to wait for the final result.\n *\n * Works in Node and the browser — the controller is environment-agnostic.\n */\n\nimport type { ExecutionStreamController } from './stream-controller.js';\nimport { extractImagesFromExecutionOutput, type ImageData } from './extract-images.js';\nimport type { ImageEvent } from '../types/streaming.js';\n\n/**\n * Options for collectImagesFromStream / streamImages / streamImagesFromExecution.\n */\nexport interface CollectImagesOptions {\n /**\n * Callback fired once per image as it arrives. Receives the full ImageEvent\n * (including executionId, sourceToolCallId, toolName).\n *\n * Returning a Promise is allowed but not awaited — collection does not\n * block on the callback. If you need ordering guarantees (e.g. sequential\n * DB inserts), serialise inside the callback yourself.\n */\n onImage?: (image: ImageEvent) => void | Promise<void>;\n\n /**\n * Callback fired once when the execution completes. Receives the same\n * value the returned Promise resolves with.\n */\n onComplete?: (result: StreamImagesResult) => void;\n\n /**\n * Callback fired if the execution errors. The returned Promise also rejects.\n */\n onError?: (error: Error) => void;\n\n /**\n * AbortSignal. When aborted: cancels the stream and rejects the Promise.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Result of a streamImages / collectImagesFromStream call.\n */\nexport interface StreamImagesResult {\n /** All images collected, in arrival order */\n images: ImageData[];\n /** The agent's final execution output (raw — may be a JSON string) */\n output: unknown;\n /** The execution UUID */\n executionId: string;\n}\n\n/**\n * Collect images from an already-created stream controller.\n *\n * The caller is responsible for calling `stream.connect()` — this helper\n * only attaches listeners and awaits completion.\n *\n * Most callers should use the higher-level `client.agents.streamImages()` or\n * `client.agents.streamImagesFromExecution()` instead, which handle the\n * connect step too.\n */\nexport async function collectImagesFromStream(\n stream: ExecutionStreamController,\n options: CollectImagesOptions = {}\n): Promise<StreamImagesResult> {\n const { onImage, onComplete, onError, signal } = options;\n\n const images: ImageData[] = [];\n const seenUrls = new Set<string>();\n\n if (signal?.aborted) {\n stream.cancel();\n throw new Error('Aborted');\n }\n\n return new Promise<StreamImagesResult>((resolve, reject) => {\n let settled = false;\n\n const settleResolve = (result: StreamImagesResult): void => {\n if (settled) return;\n settled = true;\n try {\n onComplete?.(result);\n } catch (err) {\n // Don't let consumer callbacks break the Promise contract.\n // Fire-and-forget — they can still see errors via onError.\n // eslint-disable-next-line no-console\n console.error('[SDK:collectImages] onComplete threw:', err);\n }\n resolve(result);\n };\n\n const settleReject = (err: Error): void => {\n if (settled) return;\n settled = true;\n try {\n onError?.(err);\n } catch (cbErr) {\n // eslint-disable-next-line no-console\n console.error('[SDK:collectImages] onError threw:', cbErr);\n }\n reject(err);\n };\n\n stream.on('image', (img) => {\n if (seenUrls.has(img.url)) return;\n seenUrls.add(img.url);\n images.push(img);\n try {\n const ret = onImage?.(img);\n if (ret && typeof (ret as Promise<void>).catch === 'function') {\n (ret as Promise<void>).catch((err) => {\n // eslint-disable-next-line no-console\n console.error('[SDK:collectImages] onImage rejected:', err);\n });\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[SDK:collectImages] onImage threw:', err);\n }\n });\n\n stream.on('error', (err) => {\n settleReject(new Error(err.error || 'Stream error'));\n });\n\n stream.on('complete', ({ execution }) => {\n // Fallback: backfill from execution.output if streaming didn't surface\n // any images (older agents, non-streaming tool paths, missed events).\n if (images.length === 0 && execution.output) {\n const fromOutput = extractImagesFromExecutionOutput(execution.output, {\n executionId: stream.executionId,\n });\n for (const img of fromOutput) {\n if (seenUrls.has(img.url)) continue;\n seenUrls.add(img.url);\n images.push(img);\n // Also fire onImage so progressive consumers see fallback images.\n try {\n onImage?.({\n ...img,\n executionId: stream.executionId,\n sourceToolCallId: img.sourceToolCallId ?? '',\n toolName: '',\n });\n } catch {\n // ignore\n }\n }\n }\n\n settleResolve({\n images: [...images],\n output: execution.output,\n executionId: stream.executionId,\n });\n });\n\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n stream.cancel();\n settleReject(new Error('Aborted'));\n },\n { once: true }\n );\n }\n });\n}\n","/**\n * API paths for TOP-LEVEL resources\n *\n * `BaseResourceAPI.httpGet/httpPost/...` prefix a resource's own `basePath`\n * (e.g. `/api/v1/agents`), which is right for sub-resources but wrong for\n * resources that live at the root of the API. Those call `this.http.*`\n * directly — and every place that did so had dropped the `/api/v1` prefix\n * entirely, producing requests that resolve on NO host:\n *\n * - cadra-web (what every chat/copilot consumer passes as `baseUrl`) serves\n * `/api/v1/executions/{id}`. A bare `/executions/{id}` falls through to the\n * Next.js page router and returns 404 HTML — it never reaches `withApiAuth`,\n * so it is invisible to auth, quota and logging alike.\n * - cadra-api mounts the equivalent Fastify route under `/internal/v1`, behind\n * the web↔api internal key that SDK consumers do not hold. Its public\n * `/api/v1` surface carries only the session routes.\n *\n * Centralised here so the prefix is stated once instead of being re-typed (and\n * re-dropped) at each call site.\n */\n\n/** Root of the versioned public API. */\nexport const API_V1 = '/api/v1';\n\n/** Executions are a top-level resource, NOT a sub-resource of agents. */\nexport const EXECUTION_PATH = `${API_V1}/executions`;\n\n/** `GET /api/v1/executions/{id}` — execution status, output and logs. */\nexport function executionPath(executionId: string): string {\n return `${EXECUTION_PATH}/${executionId}`;\n}\n\n/** `POST /api/v1/executions/{id}/cancel` — request cancellation. */\nexport function executionCancelPath(executionId: string): string {\n return `${EXECUTION_PATH}/${executionId}/cancel`;\n}\n","/**\n * Agents Resource API\n *\n * Provides all agent-related operations:\n * - List: list(), get()\n * - Execute: execute(), executeSync(), stream()\n * - Receive: getExecution()\n * - Edit: update(), updateConfig(), cancelExecution()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type {\n Agent,\n AgentListOptions,\n AgentExecution,\n AgentUpdateInput,\n AgentConfigUpdateInput,\n ExecuteInput,\n ExecuteResponse,\n PaginatedResponse,\n} from '../types/index.js';\nimport type { ExecutionStreamController } from '../streaming/stream-controller.js';\nimport { createExecutionStreamController } from '../streaming/stream-controller.js';\nimport {\n collectImagesFromStream,\n type CollectImagesOptions,\n type StreamImagesResult,\n} from '../streaming/collect-images.js';\nimport { executionPath, executionCancelPath } from '../utils/api-paths.js';\n\n/**\n * Agents API class\n */\nexport class AgentsAPI extends BaseResourceAPI {\n constructor(http: HttpClient, private readonly getStreamConfig: () => StreamConfig) {\n super(http, '/api/v1/agents');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List all agents in the organization\n *\n * @param options - List options (pagination, filtering)\n * @returns Paginated list of agents\n *\n * @example\n * ```typescript\n * const { data: agents, pagination } = await client.agents.list({ limit: 10 });\n * ```\n */\n async list(options?: AgentListOptions): Promise<PaginatedResponse<Agent>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n status: options?.status,\n type: options?.type,\n };\n return this.httpGet<PaginatedResponse<Agent>>('', query);\n }\n\n /**\n * Get a single agent by UUID\n *\n * @param uuid - Agent UUID\n * @returns Agent with configuration\n *\n * @example\n * ```typescript\n * const agent = await client.agents.get('agent-uuid');\n * console.log(agent.config);\n * ```\n */\n async get(uuid: string): Promise<Agent> {\n return this.httpGet<Agent>(`/${uuid}`);\n }\n\n // ===== EXECUTE Operations =====\n\n /**\n * Start an agent execution (async)\n *\n * Returns immediately with execution ID. Use getExecution() to poll\n * for results, or use stream() for real-time updates.\n *\n * @param uuid - Agent UUID\n * @param input - Execution input (task, context, options)\n * @returns Execution ID and initial status\n *\n * @example\n * ```typescript\n * const { executionId, status } = await client.agents.execute('agent-uuid', {\n * task: 'Summarize the latest news about AI',\n * });\n * ```\n */\n async execute(uuid: string, input: ExecuteInput): Promise<ExecuteResponse> {\n const idempotencyKey = input.options?.idempotencyKey ?? generateIdempotencyKey();\n // Use SDK flat format: { task, context, attachmentIds, teamUuid, executionId, options }\n // This matches cadra-web's sdkFormatSchema which preserves teamUuid.\n //\n // `executionId`, when present, is a client-prepared UUID v4 (P25 — Action 5).\n // cadra-web's executions router accepts it (validated as UUID) and uses it\n // as the new execution row's UUID so the SDK can pre-open SSE.\n return this.httpPost<ExecuteResponse>(\n `/${uuid}/execute`,\n {\n task: input.task,\n context: input.context ?? {},\n attachmentIds: input.attachmentIds,\n options: input.options,\n ...(input.teamUuid ? { teamUuid: input.teamUuid } : {}),\n ...(input.executionId ? { executionId: input.executionId } : {}),\n },\n { idempotencyKey }\n );\n }\n\n /**\n * Execute an agent and wait for completion (sync)\n *\n * Polls the execution status until completion or failure.\n *\n * @param uuid - Agent UUID\n * @param input - Execution input\n * @param pollInterval - Polling interval in ms (default: 1000)\n * @returns Final execution result\n *\n * @example\n * ```typescript\n * const execution = await client.agents.executeSync('agent-uuid', {\n * task: 'Write a haiku about coding',\n * });\n * console.log(execution.output);\n * ```\n */\n async executeSync(\n uuid: string,\n input: ExecuteInput,\n pollInterval: number = 1000\n ): Promise<AgentExecution> {\n // Start the execution\n const { executionId } = await this.execute(uuid, input);\n\n // Poll until completion\n return this.pollExecution(executionId, pollInterval);\n }\n\n /**\n * Stream an agent execution\n *\n * Returns a StreamController for real-time event handling.\n *\n * @param uuid - Agent UUID\n * @param input - Execution input\n * @returns Stream controller for event handling\n *\n * @example\n * ```typescript\n * const stream = await client.agents.stream('agent-uuid', {\n * task: 'Research climate change',\n * });\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('toolCall', ({ toolName }) => console.log(`Calling ${toolName}`));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * const result = await stream.wait();\n * ```\n */\n async stream(uuid: string, input: ExecuteInput): Promise<ExecutionStreamController> {\n console.log('[SDK:Agents] stream() called for agent:', uuid);\n\n // Start the execution first\n const { executionId, sessionId } = await this.execute(uuid, input);\n console.log('[SDK:Agents] Execution started:', { executionId, sessionId });\n\n // Create and connect stream controller\n const config = this.getStreamConfig();\n console.log('[SDK:Agents] Stream config:', {\n baseUrl: config.baseUrl,\n apiKey: config.apiKey ? `${config.apiKey.substring(0, 20)}...` : 'MISSING',\n orgId: config.orgId,\n });\n\n const controller = createExecutionStreamController({\n executionId,\n sessionId,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n tokenProvider: config.tokenProvider,\n orgId: config.orgId,\n fetch: config.fetch,\n getExecution: (id) => this.getExecution(id),\n });\n\n // IMPORTANT: Do NOT call connect() here!\n // The caller must register event listeners with .on() FIRST, then call .connect()\n // Otherwise events will be emitted to 0 listeners (race condition)\n console.log('[SDK:Agents] Stream controller created - caller must call connect() after registering listeners');\n\n return controller;\n }\n\n /**\n * Connect to an existing execution's stream\n *\n * Use this when the execution was started externally (e.g., via tRPC for team executions)\n * and you need to connect to its SSE stream for real-time updates.\n *\n * @param executionId - Execution UUID (already running)\n * @param sessionId - Optional session ID for conversation continuity\n * @returns Stream controller for the execution\n *\n * @example\n * ```typescript\n * // Execution started via tRPC\n * const executionId = await trpc.executions.start.mutate({ teamUuid, task });\n *\n * // Connect to SSE stream for real-time updates\n * const stream = client.agents.streamExecution(executionId);\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('delegationStarted', (data) => console.log('Subagent:', data.targetAgentName));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * await stream.connect();\n * const result = await stream.wait();\n * ```\n */\n streamExecution(executionId: string, sessionId?: string): ExecutionStreamController {\n console.log('[SDK:Agents] streamExecution() called for execution:', executionId);\n\n // Create stream controller for existing execution\n const config = this.getStreamConfig();\n console.log('[SDK:Agents] Stream config:', {\n baseUrl: config.baseUrl,\n apiKey: config.apiKey ? `${config.apiKey.substring(0, 20)}...` : 'MISSING',\n orgId: config.orgId,\n });\n\n const controller = createExecutionStreamController({\n executionId,\n sessionId,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n tokenProvider: config.tokenProvider,\n orgId: config.orgId,\n fetch: config.fetch,\n getExecution: (id) => this.getExecution(id),\n });\n\n // IMPORTANT: Do NOT call connect() here!\n // The caller must register event listeners with .on() FIRST, then call .connect()\n console.log('[SDK:Agents] Stream controller created for existing execution - caller must call connect() after registering listeners');\n\n return controller;\n }\n\n /**\n * Stream image generation — kicks off an execution and resolves with all\n * images once the agent completes, while firing per-image callbacks as\n * each one arrives.\n *\n * Use this for one-shot image generation from agents whose primary output\n * is images (`create_ad_images`, `edit_image`, etc.). Works in Node and\n * the browser.\n *\n * @example\n * ```typescript\n * // Server-side: persist each image as it arrives, then return creative IDs\n * const { images, executionId } = await client.agents.streamImages(\n * batchAgentUuid,\n * { task: 'Generate 4 ads for new product launch', attachmentIds },\n * { onImage: async (img) => { await persist(img); } }\n * );\n * ```\n *\n * @example\n * ```typescript\n * // Browser-side: progressive UI without polling\n * const result = await client.agents.streamImages(uuid, input, {\n * onImage: (img) => setImages((prev) => [...prev, img]),\n * signal: abortController.signal,\n * });\n * ```\n */\n async streamImages(\n uuid: string,\n input: ExecuteInput,\n options?: CollectImagesOptions\n ): Promise<StreamImagesResult> {\n const stream = await this.stream(uuid, input);\n const collectionPromise = collectImagesFromStream(stream, options);\n // Connect AFTER collectImagesFromStream attaches listeners to avoid race.\n stream.connect().catch(() => {\n // connectionError surfaces via the stream's 'error' event; the\n // collection promise will reject through that path. Swallow here so\n // we don't trigger unhandled-rejection.\n });\n return collectionPromise;\n }\n\n /**\n * Connect to an already-started execution, stream image events, and\n * resolve with the collected images on completion.\n *\n * Useful when execution is started elsewhere (e.g. via tRPC mutation\n * that returns `executionId`) and the consumer wants to wait for images.\n *\n * @example\n * ```typescript\n * // After a tRPC mutation returns { executionId }\n * const { images } = await client.agents.streamImagesFromExecution(executionId, {\n * onImage: (img) => appendToUI(img),\n * });\n * ```\n */\n async streamImagesFromExecution(\n executionId: string,\n options?: CollectImagesOptions & { sessionId?: string }\n ): Promise<StreamImagesResult> {\n const { sessionId, ...collectOptions } = options ?? {};\n const stream = this.streamExecution(executionId, sessionId);\n const collectionPromise = collectImagesFromStream(stream, collectOptions);\n stream.connect().catch(() => {\n // see streamImages — error path reaches the promise via 'error' event\n });\n return collectionPromise;\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Get execution result by ID\n *\n * @param executionId - Execution UUID\n * @returns Execution details including status, output, logs\n *\n * @example\n * ```typescript\n * const execution = await client.agents.getExecution('exec-uuid');\n * if (execution.status === 'completed') {\n * console.log(execution.output);\n * }\n * ```\n */\n async getExecution(executionId: string): Promise<AgentExecution> {\n // Executions are a TOP-LEVEL resource (`/api/v1/executions/...`), not a\n // sub-resource of `/api/v1/agents`, so this cannot go through `httpGet`\n // (which would prefix this resource's basePath). It still needs the\n // `/api/v1` prefix: a bare `/executions/{id}` resolves on NO host — on\n // cadra-web it lands on the Next page router (404 HTML, never reaching\n // auth), and on cadra-api the equivalent route is mounted under\n // `/internal/v1` behind the internal key. See EXECUTION_PATH.\n return this.http.get<AgentExecution>(executionPath(executionId));\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Update agent details\n *\n * @param uuid - Agent UUID\n * @param data - Fields to update\n * @returns Updated agent\n *\n * @example\n * ```typescript\n * const agent = await client.agents.update('agent-uuid', {\n * name: 'My Updated Agent',\n * description: 'New description',\n * });\n * ```\n */\n async update(uuid: string, data: AgentUpdateInput): Promise<Agent> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Agent>(`/${uuid}`, data, { idempotencyKey });\n }\n\n /**\n * Update agent configuration\n *\n * @param uuid - Agent UUID\n * @param config - Configuration fields to update\n * @returns Updated agent\n *\n * @example\n * ```typescript\n * const agent = await client.agents.updateConfig('agent-uuid', {\n * temperature: 0.7,\n * maxIterations: 5,\n * });\n * ```\n */\n async updateConfig(uuid: string, config: AgentConfigUpdateInput): Promise<Agent> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Agent>(`/${uuid}/config`, config, { idempotencyKey });\n }\n\n /**\n * Cancel a running execution\n *\n * @param executionId - Execution UUID\n * @returns Updated execution with cancelled status\n *\n * @example\n * ```typescript\n * const execution = await client.agents.cancelExecution('exec-uuid');\n * console.log(execution.status); // 'cancelled'\n * ```\n */\n async cancelExecution(executionId: string): Promise<AgentExecution> {\n return this.http.post<AgentExecution>(\n executionCancelPath(executionId),\n undefined,\n { skipRetry: true }\n );\n }\n\n // ===== Private helpers =====\n\n /**\n * Poll execution until completion\n */\n private async pollExecution(\n executionId: string,\n pollInterval: number\n ): Promise<AgentExecution> {\n while (true) {\n const execution = await this.getExecution(executionId);\n\n if (\n execution.status === 'completed' ||\n execution.status === 'failed' ||\n execution.status === 'cancelled'\n ) {\n return execution;\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n}\n\n/**\n * Stream configuration passed from client\n */\nexport interface StreamConfig {\n baseUrl: string;\n apiKey?: string;\n token?: string;\n tokenProvider?: () => Promise<string>;\n orgId: number;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n","/**\n * Skills Resource API\n *\n * Provides all skill-related operations:\n * - List: list(), get(), getTools()\n * - Execute: execute()\n * - Receive: getExecution()\n * - Edit: update(), updatePrompt()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type {\n Skill,\n SkillDetails,\n SkillListOptions,\n SkillTool,\n SkillExecuteInput,\n SkillExecution,\n SkillUpdateInput,\n PaginatedResponse,\n} from '../types/index.js';\n\n/**\n * Skills API class\n */\nexport class SkillsAPI extends BaseResourceAPI {\n constructor(http: HttpClient) {\n super(http, '/api/v1/skills');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List all skills in the organization\n *\n * @param options - List options (pagination, filtering by category/tags)\n * @returns Paginated list of skills\n *\n * @example\n * ```typescript\n * const { data: skills } = await client.skills.list({\n * category: 'writing',\n * tags: ['seo', 'blog'],\n * });\n * ```\n */\n async list(options?: SkillListOptions): Promise<PaginatedResponse<Skill>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n category: options?.category,\n tags: options?.tags?.join(','),\n };\n return this.httpGet<PaginatedResponse<Skill>>('', query);\n }\n\n /**\n * Get a single skill by UUID with full details\n *\n * @param uuid - Skill UUID\n * @returns Skill with prompt template and tools\n *\n * @example\n * ```typescript\n * const skill = await client.skills.get('skill-uuid');\n * console.log(skill.promptTemplate);\n * ```\n */\n async get(uuid: string): Promise<SkillDetails> {\n return this.httpGet<SkillDetails>(`/${uuid}`);\n }\n\n /**\n * Get tools associated with a skill\n *\n * @param uuid - Skill UUID\n * @returns Array of tools used by the skill\n *\n * @example\n * ```typescript\n * const tools = await client.skills.getTools('skill-uuid');\n * tools.forEach(tool => console.log(tool.name));\n * ```\n */\n async getTools(uuid: string): Promise<SkillTool[]> {\n return this.httpGet<SkillTool[]>(`/${uuid}/tools`);\n }\n\n // ===== EXECUTE Operations =====\n\n /**\n * Execute a skill with variables\n *\n * @param uuid - Skill UUID\n * @param input - Variables and context for execution\n * @returns Skill execution result\n *\n * @example\n * ```typescript\n * const result = await client.skills.execute('skill-uuid', {\n * variables: {\n * topic: 'AI in healthcare',\n * tone: 'professional',\n * },\n * });\n * console.log(result.output);\n * ```\n */\n async execute(uuid: string, input: SkillExecuteInput): Promise<SkillExecution> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<SkillExecution>(\n `/${uuid}/execute`,\n {\n variables: input.variables,\n context: input.context,\n },\n { idempotencyKey }\n );\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Get skill execution result by ID\n *\n * @param executionId - Execution UUID\n * @returns Skill execution details\n *\n * @example\n * ```typescript\n * const execution = await client.skills.getExecution('exec-uuid');\n * ```\n */\n async getExecution(executionId: string): Promise<SkillExecution> {\n // KNOWN BROKEN (not fixed here — no verified target route): this bare\n // path drops the `/api/v1` prefix and resolves on no host. Unlike the\n // execution endpoints, cadra-web exposes no public skill-execution route to\n // point it at, so correcting it needs a server-side route first.\n // See utils/api-paths.ts.\n return this.http.get<SkillExecution>(`/executions/${executionId}`);\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Update skill details\n *\n * @param uuid - Skill UUID\n * @param data - Fields to update\n * @returns Updated skill\n *\n * @example\n * ```typescript\n * const skill = await client.skills.update('skill-uuid', {\n * name: 'Updated Skill Name',\n * tags: ['new-tag'],\n * });\n * ```\n */\n async update(uuid: string, data: SkillUpdateInput): Promise<Skill> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Skill>(`/${uuid}`, data, { idempotencyKey });\n }\n\n /**\n * Update skill prompt template\n *\n * @param uuid - Skill UUID\n * @param prompt - New prompt template\n * @returns Updated skill with new version\n *\n * @example\n * ```typescript\n * const skill = await client.skills.updatePrompt('skill-uuid',\n * 'Write a {{tone}} article about {{topic}}...'\n * );\n * console.log(skill.version); // Version incremented\n * ```\n */\n async updatePrompt(uuid: string, prompt: string): Promise<SkillDetails> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<SkillDetails>(`/${uuid}/prompt`, { promptTemplate: prompt }, { idempotencyKey });\n }\n}\n","/**\n * Tools Resource API\n *\n * Provides all tool-related operations:\n * - List: list(), get()\n * - Execute: execute(), validateInput()\n * - Receive: getExecution()\n * - Edit: update(), updateConfig()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type {\n Tool,\n ToolListOptions,\n ToolExecution,\n ToolValidationResult,\n ToolUpdateInput,\n ToolConfigUpdateInput,\n PaginatedResponse,\n ExecuteToolDirectRequest,\n ExecuteToolDirectResponse,\n} from '../types/index.js';\n\n/**\n * Tools API class\n */\nexport class ToolsAPI extends BaseResourceAPI {\n constructor(http: HttpClient) {\n super(http, '/api/v1/tools');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List all tools in the organization\n *\n * @param options - List options (pagination, filtering)\n * @returns Paginated list of tools\n *\n * @example\n * ```typescript\n * const { data: tools } = await client.tools.list({\n * category: 'data',\n * isEnabled: true,\n * });\n * ```\n */\n async list(options?: ToolListOptions): Promise<PaginatedResponse<Tool>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n category: options?.category,\n isEnabled: options?.isEnabled,\n };\n return this.httpGet<PaginatedResponse<Tool>>('', query);\n }\n\n /**\n * Get a single tool by UUID with schema\n *\n * @param uuid - Tool UUID\n * @returns Tool with input/output schemas\n *\n * @example\n * ```typescript\n * const tool = await client.tools.get('tool-uuid');\n * console.log(tool.inputSchema);\n * ```\n */\n async get(uuid: string): Promise<Tool> {\n return this.httpGet<Tool>(`/${uuid}`);\n }\n\n // ===== EXECUTE Operations =====\n\n /**\n * Execute a tool directly\n *\n * @param uuid - Tool UUID\n * @param input - Tool input (validated against inputSchema)\n * @returns Tool execution result\n *\n * @example\n * ```typescript\n * const result = await client.tools.execute('tool-uuid', {\n * query: 'weather in London',\n * limit: 5,\n * });\n * console.log(result.output);\n * ```\n */\n async execute(uuid: string, input: Record<string, unknown>): Promise<ToolExecution> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<ToolExecution>(`/${uuid}/execute`, { input }, { idempotencyKey });\n }\n\n /**\n * Execute a tool directly, bypassing the agent runtime.\n *\n * Enqueues the tool for async processing via BullMQ (no LLM, no ReAct loop).\n * Use SSE or polling with the returned executionId to get the result.\n *\n * @param request - Direct execution request\n * @returns Queued execution response with executionId for tracking\n *\n * @example\n * ```typescript\n * const result = await client.tools.executeDirect({\n * toolUuid: 'tool-uuid',\n * parameters: { prompt: 'Generate an image of a sunset' },\n * });\n * console.log(result.executionId); // Use for polling/SSE\n * console.log(result.status); // 'queued'\n * ```\n */\n async executeDirect(request: ExecuteToolDirectRequest): Promise<ExecuteToolDirectResponse> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<ExecuteToolDirectResponse>('/execute-direct', request, { idempotencyKey });\n }\n\n /**\n * Validate input against tool schema\n *\n * @param uuid - Tool UUID\n * @param input - Input to validate\n * @returns Validation result with errors if invalid\n *\n * @example\n * ```typescript\n * const validation = await client.tools.validateInput('tool-uuid', {\n * query: 'test',\n * });\n * if (!validation.valid) {\n * console.log(validation.errors);\n * }\n * ```\n */\n async validateInput(uuid: string, input: Record<string, unknown>): Promise<ToolValidationResult> {\n return this.httpPost<ToolValidationResult>(`/${uuid}/validate`, { input }, { skipRetry: false });\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Get tool execution result by ID\n *\n * @param executionId - Execution UUID\n * @returns Tool execution details\n *\n * @example\n * ```typescript\n * const execution = await client.tools.getExecution('exec-uuid');\n * ```\n */\n async getExecution(executionId: string): Promise<ToolExecution> {\n // KNOWN BROKEN (not fixed here — no verified target route): this bare\n // path drops the `/api/v1` prefix and resolves on no host. Unlike the\n // execution endpoints, cadra-web exposes no public tool-execution route to\n // point it at, so correcting it needs a server-side route first.\n // See utils/api-paths.ts.\n return this.http.get<ToolExecution>(`/executions/${executionId}`);\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Update tool details\n *\n * @param uuid - Tool UUID\n * @param data - Fields to update\n * @returns Updated tool\n *\n * @example\n * ```typescript\n * const tool = await client.tools.update('tool-uuid', {\n * name: 'Updated Tool Name',\n * description: 'New description',\n * });\n * ```\n */\n async update(uuid: string, data: ToolUpdateInput): Promise<Tool> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Tool>(`/${uuid}`, data, { idempotencyKey });\n }\n\n /**\n * Update tool configuration\n *\n * @param uuid - Tool UUID\n * @param config - Configuration to update\n * @returns Updated tool\n *\n * @example\n * ```typescript\n * const tool = await client.tools.updateConfig('tool-uuid', {\n * isEnabled: false,\n * config: { apiKey: 'new-key' },\n * });\n * ```\n */\n async updateConfig(uuid: string, config: ToolConfigUpdateInput): Promise<Tool> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Tool>(`/${uuid}/config`, config, { idempotencyKey });\n }\n}\n","/**\n * Artifacts Resource API\n *\n * Provides all artifact-related operations:\n * - List: list(), get()\n * - Receive: download(), downloadStream(), getSignedUrl()\n * - Edit: upload(), delete()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport type {\n Artifact,\n ArtifactListOptions,\n ArtifactDownloadOptions,\n SignedUrlResponse,\n ArtifactUploadInput,\n PaginatedResponse,\n} from '../types/index.js';\n\n/**\n * Artifacts API class\n */\nexport class ArtifactsAPI extends BaseResourceAPI {\n constructor(http: HttpClient) {\n super(http, '/api/v1/artifacts');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List artifacts for an execution\n *\n * @param executionId - Execution UUID\n * @param options - List options (pagination, filtering by type)\n * @returns Paginated list of artifacts\n *\n * @example\n * ```typescript\n * const { data: artifacts } = await client.artifacts.list('exec-uuid', {\n * type: 'file',\n * });\n * ```\n */\n async list(executionId: string, options?: ArtifactListOptions): Promise<PaginatedResponse<Artifact>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n type: options?.type,\n };\n // KNOWN BROKEN (not fixed here — no verified target route): this bare\n // path drops the `/api/v1` prefix and resolves on no host. Unlike the\n // execution endpoints, cadra-web exposes no public artifacts-by-execution route to\n // point it at, so correcting it needs a server-side route first.\n // See utils/api-paths.ts.\n return this.http.get<PaginatedResponse<Artifact>>(`/executions/${executionId}/artifacts`, query);\n }\n\n /**\n * Get artifact metadata by UUID\n *\n * @param uuid - Artifact UUID\n * @returns Artifact metadata\n *\n * @example\n * ```typescript\n * const artifact = await client.artifacts.get('artifact-uuid');\n * console.log(artifact.name, artifact.size);\n * ```\n */\n async get(uuid: string): Promise<Artifact> {\n return this.httpGet<Artifact>(`/${uuid}`);\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Download artifact content\n *\n * In Node.js returns Buffer, in browser returns Blob.\n *\n * @param uuid - Artifact UUID\n * @returns Artifact content as Buffer (Node.js) or Blob (browser)\n *\n * @example\n * ```typescript\n * const content = await client.artifacts.download('artifact-uuid');\n * // Node.js: Buffer\n * // Browser: Blob\n * ```\n */\n async download(uuid: string): Promise<Buffer | Blob> {\n // Make request expecting binary response\n const response = await this.http.request<Response>({\n method: 'GET',\n path: `${this.basePath}/${uuid}/download`,\n headers: {\n 'Accept': '*/*',\n },\n });\n\n // Handle response based on environment\n if (typeof window !== 'undefined') {\n // Browser environment - return Blob\n return response.blob();\n } else {\n // Node.js environment - return Buffer\n const arrayBuffer = await response.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n }\n\n /**\n * Download artifact as a stream\n *\n * In Node.js returns Readable stream, in browser returns ReadableStream.\n *\n * @param uuid - Artifact UUID\n * @returns Readable stream\n *\n * @example\n * ```typescript\n * const stream = await client.artifacts.downloadStream('artifact-uuid');\n * // Pipe to file or process incrementally\n * ```\n */\n async downloadStream(uuid: string): Promise<ReadableStream<Uint8Array>> {\n const response = await this.http.request<Response>({\n method: 'GET',\n path: `${this.basePath}/${uuid}/stream`,\n headers: {\n 'Accept': '*/*',\n },\n });\n\n if (!response.body) {\n throw new Error('Response body is not available');\n }\n\n return response.body;\n }\n\n /**\n * Get a signed URL for direct download\n *\n * @param uuid - Artifact UUID\n * @param options - Options including expiration time\n * @returns Signed URL and expiration time\n *\n * @example\n * ```typescript\n * const { url, expiresAt } = await client.artifacts.getSignedUrl('artifact-uuid', {\n * expiresIn: 3600, // 1 hour\n * });\n * // Use URL for direct download\n * ```\n */\n async getSignedUrl(uuid: string, options?: ArtifactDownloadOptions): Promise<SignedUrlResponse> {\n return this.httpPost<SignedUrlResponse>(`/${uuid}/signed-url`, {\n expiresIn: options?.expiresIn ?? 3600,\n });\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Upload a new artifact for an execution\n *\n * @param executionId - Execution UUID\n * @param input - Upload input (name, content, mime type)\n * @returns Created artifact metadata\n *\n * @example\n * ```typescript\n * const artifact = await client.artifacts.upload('exec-uuid', {\n * name: 'report.pdf',\n * content: fileBuffer,\n * mimeType: 'application/pdf',\n * });\n * ```\n */\n async upload(executionId: string, input: ArtifactUploadInput): Promise<Artifact> {\n // For multipart upload, we need to use FormData\n const formData = new FormData();\n\n // Handle different content types\n if (input.content instanceof Blob) {\n formData.append('file', input.content, input.name);\n } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(input.content)) {\n // Node.js Buffer - slice to create a new ArrayBuffer (ensures proper ArrayBuffer type for BlobPart)\n const arrayBuffer = input.content.buffer.slice(\n input.content.byteOffset,\n input.content.byteOffset + input.content.byteLength\n ) as ArrayBuffer;\n const blob = new Blob([arrayBuffer], { type: input.mimeType ?? 'application/octet-stream' });\n formData.append('file', blob, input.name);\n } else if (input.content instanceof ReadableStream) {\n // Stream - need to collect into buffer first, then concatenate for Blob compatibility\n const chunks: Uint8Array[] = [];\n const reader = input.content.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(new Uint8Array(value));\n }\n // Concatenate chunks into ArrayBuffer for proper BlobPart typing\n const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n // Use the underlying ArrayBuffer directly for Blob (proper ArrayBuffer type)\n const blob = new Blob([combined.buffer as ArrayBuffer], { type: input.mimeType ?? 'application/octet-stream' });\n formData.append('file', blob, input.name);\n }\n\n if (input.type) {\n formData.append('type', input.type);\n }\n if (input.metadata) {\n formData.append('metadata', JSON.stringify(input.metadata));\n }\n\n // Make request with FormData (no Content-Type header - fetch sets it automatically with boundary)\n return this.http.request<Artifact>({\n method: 'POST',\n // KNOWN BROKEN — same missing `/api/v1` prefix as listArtifacts above.\n path: `/executions/${executionId}/artifacts`,\n body: formData as unknown,\n headers: {\n // Remove Content-Type to let fetch set it with proper boundary\n },\n });\n }\n\n /**\n * Delete an artifact\n *\n * @param uuid - Artifact UUID\n *\n * @example\n * ```typescript\n * await client.artifacts.delete('artifact-uuid');\n * ```\n */\n async delete(uuid: string): Promise<void> {\n return this.httpDelete<void>(`/${uuid}`);\n }\n}\n","/**\n * Attachments Resource API\n *\n * Provides attachment operations for uploading files (images, documents)\n * that can be referenced in agent executions via attachmentIds.\n *\n * - Upload flow: getUploadUrl() → PUT to presigned URL → confirm()\n * - Download: getDownloadUrl()\n */\n\nimport { BaseResourceAPI } from './base.js';\n\n/**\n * Input for requesting a presigned upload URL\n */\nexport interface AttachmentUploadUrlInput {\n /** Original filename */\n filename: string;\n /** MIME type of the file */\n mimeType: string;\n /** File size in bytes */\n size: number;\n}\n\n/**\n * Response from requesting an upload URL\n */\nexport interface AttachmentUploadUrlResponse {\n /** UUID assigned to the attachment */\n attachmentUuid: string;\n /** Presigned S3 PUT URL for uploading the file */\n uploadUrl: string;\n /** ISO timestamp when the upload URL expires */\n expiresAt?: string;\n}\n\n/**\n * Attachments API class\n */\nexport class AttachmentsAPI extends BaseResourceAPI {\n constructor(http: import('../utils/http.js').HttpClient) {\n super(http, '/api/v1/attachments');\n }\n\n /**\n * Get a presigned URL for uploading a file\n *\n * After receiving the URL, upload the file directly to S3 using a PUT request,\n * then call confirm() to mark it as ready.\n *\n * @param input - File metadata (filename, mimeType, size)\n * @returns Presigned upload URL and attachment UUID\n *\n * @example\n * ```typescript\n * // 1. Get presigned URL\n * const { attachmentUuid, uploadUrl } = await client.attachments.getUploadUrl({\n * filename: 'photo.jpg',\n * mimeType: 'image/jpeg',\n * size: 102400,\n * });\n *\n * // 2. Upload file to S3\n * await fetch(uploadUrl, { method: 'PUT', body: fileBuffer });\n *\n * // 3. Confirm upload\n * await client.attachments.confirm(attachmentUuid);\n *\n * // 4. Use in execution\n * await client.agents.execute('agent-uuid', {\n * task: 'Describe this image',\n * attachmentIds: [attachmentUuid],\n * });\n * ```\n */\n async getUploadUrl(input: AttachmentUploadUrlInput): Promise<AttachmentUploadUrlResponse> {\n return this.httpPost<AttachmentUploadUrlResponse>('/upload-url', {\n filename: input.filename,\n mimeType: input.mimeType,\n size: input.size,\n });\n }\n\n /**\n * Confirm that a file upload has completed\n *\n * Must be called after successfully uploading the file to the presigned URL.\n *\n * @param uuid - Attachment UUID returned from getUploadUrl()\n */\n async confirm(uuid: string): Promise<void> {\n await this.httpPost<void>(`/${uuid}/confirm`);\n }\n\n /**\n * Get a download URL for an attachment\n *\n * @param uuid - Attachment UUID\n * @returns Presigned download URL\n */\n async getDownloadUrl(uuid: string): Promise<string> {\n const result = await this.httpGet<{ url: string }>(`/${uuid}/download-url`);\n return result.url;\n }\n}\n","/**\n * Sessions Resource API\n *\n * Provides all session-related operations:\n * - List: list(), get()\n * - Execute: sendMessage(), stream()\n * - Receive: getHistory(), listArtifacts()\n * - Edit: create(), delete()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type {\n Session,\n SessionListOptions,\n SessionHistory,\n SessionCreateInput,\n SendMessageInput,\n PaginatedResponse,\n SessionArtifact,\n SessionArtifactListOptions,\n} from '../types/index.js';\nimport type { AgentExecution, ExecuteResponse } from '../types/agents.js';\nimport type { ExecutionStreamController } from '../streaming/stream-controller.js';\nimport { createExecutionStreamController } from '../streaming/stream-controller.js';\nimport type { StreamConfig } from './agents.js';\nimport { executionPath } from '../utils/api-paths.js';\n\n/**\n * Sessions API class\n */\nexport class SessionsAPI extends BaseResourceAPI {\n constructor(http: HttpClient, private readonly getStreamConfig: () => StreamConfig) {\n super(http, '/api/v1/sessions');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List all sessions in the organization\n *\n * @param options - List options (pagination, filtering by agent)\n * @returns Paginated list of sessions\n *\n * @example\n * ```typescript\n * const { data: sessions } = await client.sessions.list({\n * agentUuid: 'agent-uuid',\n * });\n * ```\n */\n async list(options?: SessionListOptions): Promise<PaginatedResponse<Session>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n agentUuid: options?.agentUuid,\n };\n return this.httpGet<PaginatedResponse<Session>>('', query);\n }\n\n /**\n * Get session details by ID\n *\n * @param sessionId - Session ID\n * @returns Session details\n *\n * @example\n * ```typescript\n * const session = await client.sessions.get('session-id');\n * console.log(session.messageCount);\n * ```\n */\n async get(sessionId: string): Promise<Session> {\n return this.httpGet<Session>(`/${sessionId}`);\n }\n\n // ===== EXECUTE Operations =====\n\n /**\n * Send a message to a session\n *\n * Triggers an agent execution in the context of the session.\n * Returns immediately with execution ID. Use getHistory() to get\n * the response, or use stream() for real-time updates.\n *\n * @param sessionId - Session ID\n * @param input - Message content and optional context\n * @returns Execution ID and status\n *\n * @example\n * ```typescript\n * const { executionId } = await client.sessions.sendMessage('session-id', {\n * message: 'What is the capital of France?',\n * });\n * ```\n */\n async sendMessage(sessionId: string, input: SendMessageInput): Promise<ExecuteResponse> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<ExecuteResponse>(\n `/${sessionId}/messages`,\n {\n message: input.message,\n context: input.context,\n // Pass attachment IDs for multi-modal messages (images, documents, etc.)\n attachmentIds: input.attachmentIds,\n // Optional client-prepared execution UUID v4 (P25 — Action 5).\n ...(input.executionId ? { executionId: input.executionId } : {}),\n },\n { idempotencyKey }\n );\n }\n\n /**\n * Send a message and wait for response (sync)\n *\n * @param sessionId - Session ID\n * @param input - Message content and optional context\n * @param pollInterval - Polling interval in ms (default: 1000)\n * @returns Final execution result\n *\n * @example\n * ```typescript\n * const execution = await client.sessions.sendMessageSync('session-id', {\n * message: 'What is the capital of France?',\n * });\n * console.log(execution.output);\n * ```\n */\n async sendMessageSync(\n sessionId: string,\n input: SendMessageInput,\n pollInterval: number = 1000\n ): Promise<AgentExecution> {\n const { executionId } = await this.sendMessage(sessionId, input);\n return this.pollExecution(executionId, pollInterval);\n }\n\n /**\n * Stream a message response\n *\n * Returns a StreamController for real-time event handling.\n *\n * @param sessionId - Session ID\n * @param input - Message content and optional context\n * @returns Stream controller\n *\n * @example\n * ```typescript\n * const stream = await client.sessions.stream('session-id', {\n * message: 'Tell me more about that',\n * });\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * const result = await stream.wait();\n * ```\n */\n async stream(sessionId: string, input: SendMessageInput): Promise<ExecutionStreamController> {\n const { executionId } = await this.sendMessage(sessionId, input);\n\n const config = this.getStreamConfig();\n const controller = createExecutionStreamController({\n executionId,\n sessionId,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n orgId: config.orgId,\n fetch: config.fetch,\n getExecution: (id) => this.getExecution(id),\n });\n\n await controller.connect();\n return controller;\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Get session conversation history\n *\n * @param sessionId - Session ID\n * @returns Session with all messages\n *\n * @example\n * ```typescript\n * const history = await client.sessions.getHistory('session-id');\n * history.messages.forEach(msg => {\n * console.log(`${msg.role}: ${msg.content}`);\n * });\n * ```\n */\n async getHistory(sessionId: string): Promise<SessionHistory> {\n return this.httpGet<SessionHistory>(`/${sessionId}/history`);\n }\n\n /**\n * List artifacts for a session\n *\n * Returns all artifacts generated across all executions in the session.\n * Useful for retrieving images, files, and other outputs created during\n * agent interactions.\n *\n * @param sessionId - Session ID\n * @param options - List options (filtering by type, pagination)\n * @returns Paginated list of session artifacts\n *\n * @example\n * ```typescript\n * // Get all images from a session\n * const { data: artifacts } = await client.sessions.listArtifacts('session-id', {\n * type: 'image',\n * });\n *\n * artifacts.forEach(artifact => {\n * console.log(artifact.filename, artifact.url);\n * });\n * ```\n */\n async listArtifacts(\n sessionId: string,\n options?: SessionArtifactListOptions\n ): Promise<PaginatedResponse<SessionArtifact>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n type: options?.type,\n includeVariants: options?.includeVariants,\n };\n return this.httpGet<PaginatedResponse<SessionArtifact>>(`/${sessionId}/artifacts`, query);\n }\n\n /**\n * Get execution result\n */\n private async getExecution(executionId: string): Promise<AgentExecution> {\n return this.http.get<AgentExecution>(executionPath(executionId));\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Create a new session for an agent\n *\n * @param agentUuid - Agent UUID to associate with session\n * @param options - Optional system message\n * @returns Created session\n *\n * @example\n * ```typescript\n * const session = await client.sessions.create({\n * agentUuid: 'agent-uuid',\n * systemMessage: 'You are a helpful assistant.',\n * });\n * console.log(session.id);\n * ```\n */\n async create(input: SessionCreateInput): Promise<Session> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<Session>('', input, { idempotencyKey });\n }\n\n /**\n * Delete a session and all its messages\n *\n * @param sessionId - Session ID\n *\n * @example\n * ```typescript\n * await client.sessions.delete('session-id');\n * ```\n */\n async delete(sessionId: string): Promise<void> {\n return this.httpDelete<void>(`/${sessionId}`);\n }\n\n // ===== Private helpers =====\n\n /**\n * Poll execution until completion\n */\n private async pollExecution(\n executionId: string,\n pollInterval: number\n ): Promise<AgentExecution> {\n while (true) {\n const execution = await this.getExecution(executionId);\n\n if (\n execution.status === 'completed' ||\n execution.status === 'failed' ||\n execution.status === 'cancelled'\n ) {\n return execution;\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n}\n","/**\n * Kanban Resource API\n *\n * Provides the org-scoped board operations against `/api/v1/kanban/*`:\n * - Board: getBoard()\n * - Cards: listCards(), createCard(), getCard(), transitionCard()\n * - Run: streamCardRun() — reuses the EXISTING execution-stream controller\n * keyed on the card's executionId (no bespoke kanban stream).\n *\n * Mirrors `SessionsAPI` / `AgentsAPI` resource shape and is wired onto\n * `CadraClient` as `client.kanban`.\n *\n * @module @cadraos/sdk\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type { ExecutionStreamController } from '../streaming/stream-controller.js';\nimport { createExecutionStreamController } from '../streaming/stream-controller.js';\nimport type { StreamConfig } from './agents.js';\nimport type { AgentExecution } from '../types/agents.js';\nimport type {\n CardList,\n CreateCardInput,\n KanbanBoard,\n KanbanCard,\n KanbanHandlerType,\n KanbanLane,\n KanbanRunSummary,\n KanbanTransition,\n ListCardsInput,\n TransitionCardInput,\n} from '../kanban/types.js';\nimport { executionPath } from '../utils/api-paths.js';\n\n// ---------------------------------------------------------------------------\n// API → SDK mappers\n//\n// The `/api/v1/kanban/*` endpoints return a richer wire envelope than the flat\n// SDK types the hook/components consume: lanes are nested under `lifecycle`,\n// cards use `currentLane`/`uuid`, and lane fields are snake_cased. These\n// mappers adapt the wire shape to the public `KanbanBoard`/`KanbanCard`\n// contract. Without them the board renders \"No lanes configured\" (the raw\n// envelope has no top-level `.lanes`) and cards land in undefined lanes.\n// ---------------------------------------------------------------------------\n\ninterface RawLane {\n id?: string;\n key: string;\n name: string;\n handler?: { handler_type?: string; agent_ref?: string } | null;\n is_initial?: boolean;\n is_terminal?: boolean;\n}\n\ninterface RawTransition {\n id: string;\n from_lane_id: string;\n to_lane_id: string;\n manual_allowed?: boolean;\n}\n\ninterface RawBoardResponse {\n board: { id: number; uuid: string; orgId: number };\n lifecycle?: {\n id: number;\n uuid: string;\n slug: string;\n name: string;\n version: number;\n lanes?: RawLane[];\n transitions?: RawTransition[];\n };\n}\n\ninterface RawCard {\n id: number;\n uuid: string;\n currentLane: string;\n title: string;\n description?: string | null;\n type?: string | null;\n sharedContext?: Record<string, unknown> | null;\n executionId?: string | null;\n /** Run status of the linked execution (board listing) — drives card animation. */\n runStatus?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n}\n\nfunction mapLane(l: RawLane, index: number): KanbanLane {\n return {\n key: l.key,\n label: l.name,\n order: index,\n handler: l.handler\n ? {\n type: (l.handler.handler_type ?? 'cadra_agent') as KanbanHandlerType,\n agentRef: l.handler.agent_ref,\n }\n : undefined,\n terminal: l.is_terminal ?? false,\n initial: l.is_initial ?? false,\n };\n}\n\nfunction mapTransition(t: RawTransition): KanbanTransition {\n return {\n id: t.id,\n fromLane: t.from_lane_id,\n toLane: t.to_lane_id,\n manualAllowed: t.manual_allowed ?? false,\n };\n}\n\n/** Normalize a raw execution status string onto the board's KanbanRunStatus. */\nfunction mapExecStatus(s?: string | null): KanbanRunSummary['status'] {\n switch ((s ?? '').toLowerCase()) {\n case 'running':\n case 'in_progress':\n case 'processing':\n return 'running';\n case 'queued':\n case 'pending':\n case 'created':\n return 'pending';\n case 'completed':\n case 'success':\n case 'succeeded':\n return 'completed';\n case 'failed':\n case 'error':\n return 'failed';\n case 'cancelled':\n case 'canceled':\n return 'cancelled';\n default:\n return 'pending';\n }\n}\n\nfunction mapBoard(data: RawBoardResponse): KanbanBoard {\n return {\n id: data.board.uuid,\n orgId: data.board.orgId,\n lifecycleId: data.lifecycle?.uuid,\n lifecycleVersion: data.lifecycle?.version,\n name: data.lifecycle?.name,\n lanes: (data.lifecycle?.lanes ?? []).map(mapLane),\n transitions: (data.lifecycle?.transitions ?? []).map(mapTransition),\n };\n}\n\nfunction mapCard(c: RawCard, run?: KanbanRunSummary): KanbanCard {\n return {\n // The `/cards/:id` + `/cards/:id/transition` routes key on the integer PK\n // (`Number(id)`), so the card handle the board passes back MUST be that id,\n // not the uuid (a uuid → `Number(uuid)` = NaN → \"Invalid card id\").\n id: String(c.id),\n boardId: '',\n lane: c.currentLane,\n title: c.title,\n description: c.description ?? undefined,\n type: c.type ?? undefined,\n sharedContext: c.sharedContext ?? undefined,\n // Streaming key: the run-stream route (/api/v1/agents/runs/{id}/stream)\n // validates a UUID. Prefer the run summary's execution UUID; the raw card's\n // executionId is now the execution UUID too (board + card routes return it).\n executionId: run?.executionId ?? c.executionId ?? undefined,\n // Board-listing cards carry only `runStatus` (no full run summary). Synthesize\n // a minimal run so the card can render its \"agent working\" animation without\n // a detail fetch. getCard supplies the full `run` (takes precedence).\n run:\n run ??\n (c.runStatus\n ? {\n executionId: c.executionId ?? '',\n status: mapExecStatus(c.runStatus),\n }\n : undefined),\n createdAt: c.createdAt ?? undefined,\n updatedAt: c.updatedAt ?? undefined,\n };\n}\n\n/**\n * Kanban API class.\n */\nexport class KanbanAPI extends BaseResourceAPI {\n constructor(http: HttpClient, private readonly getStreamConfig: () => StreamConfig) {\n super(http, '/api/v1/kanban');\n }\n\n // ===== BOARD =====\n\n /**\n * Get the current org's board (lanes in declared order). Auto-provisions\n * the board server-side on first access.\n *\n * @returns The board with its lanes.\n *\n * @example\n * ```typescript\n * const board = await client.kanban.getBoard();\n * console.log(board.lanes.map((l) => l.label));\n * ```\n */\n async getBoard(): Promise<KanbanBoard> {\n const data = await this.httpGet<RawBoardResponse>('/boards/current');\n return mapBoard(data);\n }\n\n // ===== CARDS =====\n\n /**\n * List cards on the board (optionally filtered by lane/type).\n *\n * @param input - Optional list filters.\n * @returns The card list.\n */\n async listCards(input?: ListCardsInput): Promise<CardList> {\n const query: Record<string, string | number | boolean | undefined> = {\n lane: input?.lane,\n type: input?.type,\n limit: input?.limit,\n offset: input?.offset,\n };\n const data = await this.httpGet<{ cards: RawCard[]; total?: number }>(\n '/cards',\n query\n );\n return { cards: (data.cards ?? []).map((c) => mapCard(c)), total: data.total };\n }\n\n /**\n * Create a card. The server engine places it in the initial lane and fires\n * the lane's handler.\n *\n * @param input - Card creation input.\n * @returns The created card.\n */\n async createCard(input: CreateCardInput): Promise<KanbanCard> {\n const idempotencyKey = generateIdempotencyKey();\n const data = await this.httpPost<{ card: RawCard }>(\n '/cards',\n {\n title: input.title,\n type: input.type,\n description: input.description,\n sharedContext: input.sharedContext,\n lane: input.lane,\n },\n // Card creation is NON-idempotent and dispatches an agent run; a client\n // retry (e.g. on a slow create) would create a DUPLICATE card + a second\n // agent run (token waste). The server does not honor Idempotency-Key, so\n // never auto-retry this mutation.\n { idempotencyKey, skipRetry: true }\n );\n return mapCard(data.card);\n }\n\n /**\n * Get a single card by id, including its current run (`executionId` + run\n * summary) so the live run can be streamed.\n *\n * @param cardId - Card UUID.\n * @returns The card with its current/last run.\n */\n async getCard(cardId: string): Promise<KanbanCard> {\n // cadra-web returns the run as { executionId: <integer PK>, executionUuid,\n // status, error }. The SDK's KanbanRunSummary.executionId is the UUID that\n // drives the stream, so normalize executionUuid -> executionId here.\n const data = await this.httpGet<{\n card: RawCard;\n run?: {\n executionId?: number | string;\n executionUuid?: string;\n status?: KanbanRunSummary['status'];\n output?: string;\n error?: string | null;\n } | null;\n }>(`/cards/${cardId}`);\n const run: KanbanRunSummary | undefined = data.run\n ? {\n executionId:\n data.run.executionUuid ?? String(data.run.executionId ?? ''),\n status: data.run.status ?? 'pending',\n output: data.run.output,\n error: data.run.error ?? undefined,\n }\n : undefined;\n return mapCard(data.card, run);\n }\n\n /**\n * Patch a card's mutable fields (title/description/sharedContext). Maps the\n * `{ card: RawCard }` response back to a `KanbanCard`.\n *\n * @param cardId - Card id (the integer PK string the routes key on).\n * @param patch - The fields to update (all optional).\n * @returns The updated card.\n */\n async updateCard(\n cardId: string,\n patch: {\n title?: string;\n description?: string;\n sharedContext?: Record<string, unknown>;\n }\n ): Promise<KanbanCard> {\n // Non-idempotent-ish but safe; skipRetry to stay consistent with create.\n const data = await this.httpPatch<{ card: RawCard }>(\n `/cards/${cardId}`,\n patch,\n { skipRetry: true }\n );\n return mapCard(data.card);\n }\n\n /**\n * Manually transition a card to another lane (validated by the server\n * engine).\n *\n * @param input - Transition input.\n * @returns The updated card.\n */\n async transitionCard(input: TransitionCardInput): Promise<KanbanCard> {\n const idempotencyKey = generateIdempotencyKey();\n const data = await this.httpPost<{\n card: { uuid: string; currentLane: string; executionId?: string | null } | null;\n newLane?: string;\n }>(\n `/cards/${input.cardId}/transition`,\n {\n // The cadra-web route reads `toLane` (not `targetLane`). When omitted,\n // the engine auto-advances single-edge lanes.\n toLane: input.targetLane,\n contextPatch: input.contextPatch,\n },\n // Non-idempotent state change — don't auto-retry (a retry could\n // double-advance or re-fire a lane handler).\n { idempotencyKey, skipRetry: true }\n );\n // The transition endpoint returns a minimal card; surface the updated lane\n // (callers typically refetch the board/cards after a transition).\n return {\n id: data.card?.uuid ?? input.cardId,\n boardId: '',\n lane: data.card?.currentLane ?? data.newLane ?? input.targetLane ?? '',\n title: '',\n executionId: data.card?.executionId ?? undefined,\n };\n }\n\n // ===== RUN (reuses the existing execution-stream controller) =====\n\n /**\n * Get the card's current run as an execution. Thin convenience over the\n * existing agents/runs surface, used for polling fallback in the run view.\n *\n * @param executionId - The card's execution UUID.\n * @returns Execution details.\n */\n async getCardRun(executionId: string): Promise<AgentExecution> {\n return this.http.get<AgentExecution>(executionPath(executionId));\n }\n\n /**\n * Create a stream controller for a card's run, keyed on the card's\n * `executionId`.\n *\n * This reuses the SAME `ExecutionStreamController` the chat/agents modules\n * use against `GET /api/v1/agents/runs/{executionId}/stream` — automatic\n * reconnection, polling fallback, event dedup, and state recovery. There is\n * NO bespoke kanban stream (design.md §4.3).\n *\n * IMPORTANT: Do NOT call `.connect()` here — the caller must register\n * event listeners with `.on()` FIRST, then call `.connect()` (same contract\n * as `AgentsAPI.streamExecution`).\n *\n * @param executionId - The card's execution UUID.\n * @returns A stream controller.\n */\n streamCardRun(executionId: string): ExecutionStreamController {\n const config = this.getStreamConfig();\n return createExecutionStreamController({\n executionId,\n baseUrl: config.baseUrl,\n // The stream controller sends `Bearer <apiKey>`. Board consumers (yobo\n // copilot) construct the client with `token` (not `apiKey`), so fall back\n // to the token here — otherwise the SSE request sends `Bearer undefined`\n // and the stream route (withApiAuth) rejects it with INVALID_API_KEY.\n apiKey: config.apiKey ?? config.token,\n tokenProvider: config.tokenProvider,\n orgId: config.orgId,\n getExecution: (id) => this.getCardRun(id),\n });\n }\n}\n","/**\n * Teams Resource API\n *\n * Provides team-related operations:\n * - List: list(), get()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { ListOptions, PaginatedResponse } from '../types/index.js';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/** Agent classification within a team */\nexport type TeamAgentType = 'ORCHESTRATOR' | 'SPECIALIST';\n\n/** Agent operational status */\nexport type TeamAgentStatus = 'ACTIVE' | 'IDLE' | 'BUSY' | 'OFFLINE' | 'DRAFT';\n\n/** Agent summary within a team member entry */\nexport interface TeamMemberAgent {\n uuid: string;\n name: string;\n agentType: TeamAgentType;\n roleTemplate: string | null;\n status: TeamAgentStatus;\n description?: string | null;\n}\n\n/**\n * STORY-014 (CAD-70): TeamMemberRef discriminated union.\n *\n * A team member reference is either:\n * - cadra_agent — a native Cadra agent (resolved by agentUuid)\n * - remote_agent — a remote external agent (resolved by remoteAgentUuid)\n *\n * The discriminator is `memberType` — IDENTICAL to TeamMemberData.memberType and\n * cadra-api's SpecialistAgentInfo.memberType / the cadra-web specialists route, so\n * this union narrows the same shape the runtime actually produces (not a separate\n * `type`-keyed config dialect).\n *\n * MVP: remote_agent is always a LEAF/specialist. The orchestrator/lead is always a\n * native cadra_agent (teams.leadAgentId); leaf-only is enforced structurally in\n * cadra-api (a remote dispatch only ever routes to RemoteExecutionBroker and never\n * constructs a native AgentRuntime), not by a runtime flag.\n */\nexport type TeamMemberRef =\n | { memberType: 'cadra_agent'; agentUuid: string }\n | { memberType: 'remote_agent'; remoteAgentUuid: string };\n\n/** A team member with their agent details */\nexport interface TeamMemberData {\n id: number | string;\n isLead: boolean;\n agent: TeamMemberAgent;\n /**\n * STORY-014: Member type discriminator.\n * - 'cadra_agent' — native Cadra agent (default, backward-compatible)\n * - 'remote_agent' — remote external agent; remoteAgentUuid identifies the record\n */\n memberType?: 'cadra_agent' | 'remote_agent';\n /**\n * STORY-014: UUID of the remote_agents record (cadra-web).\n * Set when memberType === 'remote_agent'.\n */\n remoteAgentUuid?: string;\n}\n\n/** Lead agent summary */\nexport interface TeamLeadAgentData {\n uuid: string;\n name: string;\n agentType: TeamAgentType;\n status: TeamAgentStatus;\n}\n\n/** Team detail returned by the API */\nexport interface Team {\n uuid: string;\n name: string;\n description?: string | null;\n isActive: boolean;\n leadAgent: TeamLeadAgentData | null;\n members: TeamMemberData[];\n}\n\n/** List options for teams */\nexport interface TeamListOptions extends ListOptions {\n /** Filter by active status */\n isActive?: boolean;\n}\n\n// =============================================================================\n// API CLASS\n// =============================================================================\n\n/**\n * Teams API class\n */\nexport class TeamsAPI extends BaseResourceAPI {\n constructor(http: import('../utils/http.js').HttpClient) {\n super(http, '/api/v1/teams');\n }\n\n /**\n * List all teams in the organization\n */\n async list(options?: TeamListOptions): Promise<PaginatedResponse<Team>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n isActive: options?.isActive,\n };\n return this.httpGet<PaginatedResponse<Team>>('', query);\n }\n\n /**\n * Get a single team by UUID\n *\n * @param uuid - Team UUID\n * @param includeMembers - Whether to include team members (default: true)\n */\n async get(uuid: string, includeMembers = true): Promise<Team> {\n return this.httpGet<Team>(`/${uuid}`, { includeMembers });\n }\n}\n","/**\n * Remote Agents Resource API\n *\n * Provides operations for remote agent management and execution:\n * - List: list(), get()\n * - Manage: create(), update(), delete(), deploy()\n * - Execute: execute(), stream()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey, generateExecutionId } from '../utils/http.js';\nimport type {\n RemoteAgent,\n RemoteAgentListOptions,\n RemoteAgentCreateInput,\n RemoteAgentUpdateInput,\n RemoteAgentExecuteResponse,\n} from '../types/remote-agents.js';\nimport type { PaginatedResponse, ExecuteInput } from '../types/index.js';\nimport type { ExecutionStreamController } from '../streaming/stream-controller.js';\nimport { createExecutionStreamController } from '../streaming/stream-controller.js';\nimport type { AgentExecution } from '../types/agents.js';\nimport type { StreamConfig } from './agents.js';\nimport { executionPath } from '../utils/api-paths.js';\n\n/**\n * Remote Agents API class\n */\nexport class RemoteAgentsAPI extends BaseResourceAPI {\n constructor(http: HttpClient, private readonly getStreamConfig: () => StreamConfig) {\n super(http, '/api/v1/remote-agents');\n }\n\n /**\n * List all remote agents in the organization\n *\n * @param options - List options (pagination, filtering)\n * @returns Paginated list of remote agents\n *\n * @example\n * ```typescript\n * const { data: agents, pagination } = await client.remoteAgents.list({ status: 'active' });\n * ```\n */\n async list(options?: RemoteAgentListOptions): Promise<PaginatedResponse<RemoteAgent>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n status: options?.status,\n adapterType: options?.adapterType,\n };\n return this.httpGet<PaginatedResponse<RemoteAgent>>('', query);\n }\n\n /**\n * Get a single remote agent by UUID\n *\n * @param uuid - Remote agent UUID\n * @returns Remote agent details\n */\n async get(uuid: string): Promise<RemoteAgent> {\n return this.httpGet<RemoteAgent>(`/${uuid}`);\n }\n\n /**\n * Create a new remote agent\n *\n * @param data - Remote agent creation input\n * @returns Created remote agent\n */\n async create(data: RemoteAgentCreateInput): Promise<RemoteAgent> {\n return this.httpPost<RemoteAgent>('', data);\n }\n\n /**\n * Update a remote agent\n *\n * @param uuid - Remote agent UUID\n * @param data - Fields to update\n * @returns Updated remote agent\n */\n async update(uuid: string, data: RemoteAgentUpdateInput): Promise<RemoteAgent> {\n return this.httpPatch<RemoteAgent>(`/${uuid}`, data);\n }\n\n /**\n * Delete a remote agent\n *\n * @param uuid - Remote agent UUID\n * @returns Success response\n */\n async delete(uuid: string): Promise<{ success: boolean }> {\n return this.httpDelete<{ success: boolean }>(`/${uuid}`);\n }\n\n /**\n * Deploy a remote agent (make it available for execution)\n *\n * @param uuid - Remote agent UUID\n * @returns Updated remote agent with deployed visibility\n */\n async deploy(uuid: string): Promise<RemoteAgent> {\n return this.httpPost<RemoteAgent>(`/${uuid}/deploy`);\n }\n\n /**\n * Start a remote agent execution (async)\n *\n * Returns immediately with executionId and streamUrl.\n * Use stream() for real-time updates.\n *\n * @param uuid - Remote agent UUID\n * @param input - Execution input (task, context, options)\n * @returns Execution ID and stream URL\n *\n * @example\n * ```typescript\n * const { executionId, streamUrl } = await client.remoteAgents.execute('agent-uuid', {\n * task: 'Process the uploaded dataset',\n * });\n * ```\n */\n async execute(uuid: string, input: ExecuteInput): Promise<RemoteAgentExecuteResponse> {\n // STORY-017: mirror AgentsAPI.execute — an idempotency key + a client-prepared\n // executionId make remote dispatch safe under HttpClient's automatic retries\n // (a timeout/5xx after the server already enqueued must not double-dispatch\n // remote runner work).\n const idempotencyKey = input.options?.idempotencyKey ?? generateIdempotencyKey();\n // STORY-017 (re-review): cadra-web dedupes a duplicate dispatch on the BODY\n // executionId, not the idempotency-key header. Default a stable client UUID so\n // the SDK's automatic retries hit the same row instead of double-dispatching.\n const executionId = input.executionId ?? generateExecutionId();\n return this.httpPost<RemoteAgentExecuteResponse>(\n `/${uuid}/execute`,\n {\n task: input.task,\n context: input.context ?? {},\n attachmentIds: input.attachmentIds,\n options: input.options,\n // Review #10: forward sessionId so multi-turn remote sessions are possible.\n // The cadra-web execute route's Zod schema already accepts sessionId.\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n executionId,\n },\n { idempotencyKey }\n );\n }\n\n /**\n * Stream a remote agent execution\n *\n * Returns a StreamController for real-time event handling.\n * IMPORTANT: Do NOT call connect() inside this method — caller must register\n * listeners first, THEN call connect().\n *\n * @param uuid - Remote agent UUID\n * @param input - Execution input\n * @returns Stream controller (caller must call connect() after registering listeners)\n *\n * @example\n * ```typescript\n * const stream = await client.remoteAgents.stream('agent-uuid', {\n * task: 'Process the dataset',\n * });\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * await stream.connect();\n * const result = await stream.wait();\n * ```\n */\n async stream(uuid: string, input: ExecuteInput): Promise<ExecutionStreamController> {\n const { executionId } = await this.execute(uuid, input);\n\n const config = this.getStreamConfig();\n const controller = createExecutionStreamController({\n executionId,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n tokenProvider: config.tokenProvider,\n orgId: config.orgId,\n getExecution: (id) => this.http.get<AgentExecution>(executionPath(id)),\n });\n\n // DO NOT call connect() here - caller registers listeners first, then connects\n return controller;\n }\n}\n","/**\n * Remote Runners Resource API\n *\n * Provides operations for remote runner management:\n * - List: list()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type {\n RemoteRunner,\n RemoteRunnerListOptions,\n} from '../types/remote-agents.js';\nimport type { PaginatedResponse } from '../types/index.js';\n\n/**\n * Remote Runners API class\n */\nexport class RemoteRunnersAPI extends BaseResourceAPI {\n constructor(http: import('../utils/http.js').HttpClient) {\n super(http, '/api/v1/remote-runners');\n }\n\n /**\n * List all remote runners in the organization\n *\n * @param options - List options (pagination, filtering)\n * @returns Paginated list of remote runners\n *\n * @example\n * ```typescript\n * const { data: runners, pagination } = await client.remoteRunners.list({ status: 'connected' });\n * ```\n */\n async list(options?: RemoteRunnerListOptions): Promise<PaginatedResponse<RemoteRunner>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n status: options?.status,\n };\n return this.httpGet<PaginatedResponse<RemoteRunner>>('', query);\n }\n}\n","/**\n * AI Functions API (p93 AIF-010 — specs §9, D27).\n *\n * @example\n * ```typescript\n * // Discover what the org can call, and with which parameters\n * const functions = await client.aiFunctions.list();\n * const fn = await client.aiFunctions.get('summarise_ticket');\n *\n * // Call it — parameters are checked against the live version before sending\n * const result = await client.aiFunctions.run('summarise_ticket', { ticket_text: '…' });\n * if (result.output.type === 'text') console.log(result.output.text);\n * ```\n */\n\nimport {\n AiFunctionChargedError,\n AiFunctionDuplicateError,\n AiFunctionParameterError,\n CadraError,\n} from '../errors/index.js';\nimport type {\n AiFunctionDescriptor,\n AiFunctionParameter,\n AiFunctionParameterIssue,\n AiFunctionRef,\n AiFunctionRun,\n AiFunctionRunOptions,\n AiFunctionRunResult,\n AiFunctionRunShorthandOptions,\n AiFunctionVariables,\n} from '../types/ai-functions.js';\nimport { generateExecutionId, type HttpClient } from '../utils/http.js';\nimport { BaseResourceAPI } from './base.js';\n\n/**\n * How long the client waits for a paid run. It tracks cadra-web\n * `AI_FUNCTION_ROUTE_MAX_MS` (300 s, the Vercel `maxDuration` of the run\n * routes) plus 10 s, so the server always answers first — with the result or\n * with its own `failed_timeout` — and the client never abandons a run the\n * server is still finishing. A larger client-wide `timeout` wins.\n * (Was 60 s, from the old p93 D6 route budget.)\n */\nexport const AI_FUNCTION_RUN_TIMEOUT_MS = 310_000;\n\n/** Descriptors used by the client-side check are cached per client for 60 s (D27c). */\nexport const AI_FUNCTION_DESCRIPTOR_TTL_MS = 60_000;\n\ninterface DescriptorCacheEntry {\n descriptor: AiFunctionDescriptor;\n expiresAt: number;\n}\n\n/**\n * Check `variables` against a descriptor's parameters (D27c). Returns the issues,\n * in parameter order, then unknown names. Empty array = OK.\n */\nexport function checkAiFunctionParameters(\n parameters: AiFunctionParameter[],\n variables: AiFunctionVariables\n): AiFunctionParameterIssue[] {\n const issues: AiFunctionParameterIssue[] = [];\n const declared = new Set<string>();\n\n for (const p of parameters) {\n declared.add(p.name);\n const has = Object.prototype.hasOwnProperty.call(variables, p.name);\n const value = has ? variables[p.name] : undefined;\n\n if (value === undefined || value === null) {\n if (p.required) issues.push({ name: p.name, code: 'missing' });\n continue;\n }\n\n switch (p.type) {\n case 'number':\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n issues.push({ name: p.name, code: 'type' });\n }\n break;\n case 'boolean':\n if (typeof value !== 'boolean') issues.push({ name: p.name, code: 'type' });\n break;\n case 'enum':\n if (typeof value !== 'string') issues.push({ name: p.name, code: 'type' });\n else if (p.options && !p.options.includes(value)) {\n issues.push({ name: p.name, code: 'option' });\n }\n break;\n case 'string':\n case 'text':\n if (typeof value !== 'string') issues.push({ name: p.name, code: 'type' });\n else if (typeof p.maxLength === 'number' && value.length > p.maxLength) {\n issues.push({ name: p.name, code: 'too_long' });\n }\n break;\n case 'image':\n if (typeof value !== 'string') issues.push({ name: p.name, code: 'type' });\n break;\n default:\n // Unknown future type — leave it to the server (the authority).\n break;\n }\n }\n\n for (const name of Object.keys(variables)) {\n if (!declared.has(name)) issues.push({ name, code: 'unknown' });\n }\n\n return issues;\n}\n\n/**\n * AI Functions API\n */\nexport class AiFunctionsAPI extends BaseResourceAPI {\n private readonly descriptorCache = new Map<string, DescriptorCacheEntry>();\n\n constructor(http: HttpClient) {\n super(http, '/api/v1/ai-functions');\n }\n\n /**\n * List the functions this org can call — the index (D27a). Each entry carries\n * the live version's typed parameters; never prompt text.\n */\n async list(): Promise<AiFunctionDescriptor[]> {\n const data = await this.httpGet<{ functions?: AiFunctionDescriptor[] } | AiFunctionDescriptor[]>('');\n const functions = Array.isArray(data) ? data : (data?.functions ?? []);\n for (const d of functions) this.cacheDescriptor(d);\n return functions;\n }\n\n /**\n * Get one function's descriptor by key (D27a).\n * `NotFoundError` (`FUNCTION_NOT_FOUND`) / `ConflictError` (`FUNCTION_NOT_PUBLISHED`).\n */\n async get(functionKey: string): Promise<AiFunctionDescriptor> {\n const data = await this.httpGet<AiFunctionDescriptor | { function: AiFunctionDescriptor }>(\n `/${encodeURIComponent(functionKey)}`\n );\n const descriptor =\n data && typeof data === 'object' && 'function' in data && !('functionKey' in data)\n ? data.function\n : (data as AiFunctionDescriptor);\n this.cacheDescriptor(descriptor, functionKey);\n return descriptor;\n }\n\n /**\n * Read one of this org's own runs (safe projection, §6.5).\n */\n async getRun(executionId: string): Promise<AiFunctionRun> {\n return this.httpGet<AiFunctionRun>(`/runs/${encodeURIComponent(executionId)}`);\n }\n\n /** Forget cached descriptors (one key, or all). */\n clearDescriptorCache(functionKey?: string): void {\n if (functionKey) this.descriptorCache.delete(functionKey);\n else this.descriptorCache.clear();\n }\n\n /**\n * Run an AI function — one paid provider call.\n *\n * - `run('function_key', parameters, opts?)` — shorthand for `{ functionKey }`.\n * - `run({ functionKey | promptUuid | slot }, { variables, version?, idempotencyKey?, params?, validate? })`.\n *\n * For a `functionKey` ref without a pinned `version`, parameters are checked\n * against the live version first (D27c); a problem throws\n * `AiFunctionParameterError` and NO run request is sent. Paid runs are never\n * auto-retried; an idempotency key is generated when omitted.\n *\n * @throws AiFunctionParameterError — client-side check failed (nothing sent)\n * @throws AiFunctionDuplicateError — 409 `DUPLICATE_REQUEST`\n * @throws AiFunctionChargedError — the run was metered but its output failed (`details.charged`)\n */\n async run<TOutput = unknown>(\n functionKey: string,\n parameters: AiFunctionVariables,\n opts?: AiFunctionRunShorthandOptions\n ): Promise<AiFunctionRunResult<TOutput>>;\n async run<TOutput = unknown>(\n ref: AiFunctionRef,\n options: AiFunctionRunOptions\n ): Promise<AiFunctionRunResult<TOutput>>;\n async run<TOutput = unknown>(\n refOrKey: AiFunctionRef | string,\n parametersOrOptions: AiFunctionVariables | AiFunctionRunOptions,\n shorthandOpts?: AiFunctionRunShorthandOptions\n ): Promise<AiFunctionRunResult<TOutput>> {\n let ref: AiFunctionRef;\n let options: AiFunctionRunOptions;\n if (typeof refOrKey === 'string') {\n ref = { functionKey: refOrKey };\n options = { ...(shorthandOpts ?? {}), variables: parametersOrOptions as AiFunctionVariables };\n } else {\n ref = refOrKey;\n options = parametersOrOptions as AiFunctionRunOptions;\n }\n const variables = options.variables ?? {};\n\n const functionKey = 'functionKey' in ref ? ref.functionKey : undefined;\n const shouldCheck =\n functionKey !== undefined && options.version === undefined && options.validate !== false;\n\n if (shouldCheck) {\n const descriptor = await this.getCachedDescriptor(functionKey);\n const issues = checkAiFunctionParameters(descriptor.parameters, variables);\n if (issues.length > 0) {\n throw new AiFunctionParameterError(functionKey, issues);\n }\n }\n\n const body = {\n ref,\n variables,\n version: options.version,\n idempotencyKey: options.idempotencyKey ?? generateExecutionId(),\n params: options.params,\n };\n\n try {\n return await this.httpPost<AiFunctionRunResult<TOutput>>('/run', body, {\n skipRetry: true,\n timeoutMs: Math.max(AI_FUNCTION_RUN_TIMEOUT_MS, this.http.timeoutMs ?? 0),\n });\n } catch (error) {\n throw this.mapRunError(error, functionKey);\n }\n }\n\n // ── internals ──────────────────────────────────────────────────────────────\n\n private cacheDescriptor(descriptor: AiFunctionDescriptor | undefined, key?: string): void {\n if (!descriptor || typeof descriptor !== 'object') return;\n const cacheKey = key ?? descriptor.functionKey;\n if (!cacheKey) return;\n this.descriptorCache.set(cacheKey, {\n descriptor,\n expiresAt: Date.now() + AI_FUNCTION_DESCRIPTOR_TTL_MS,\n });\n }\n\n private async getCachedDescriptor(functionKey: string): Promise<AiFunctionDescriptor> {\n const hit = this.descriptorCache.get(functionKey);\n if (hit && hit.expiresAt > Date.now()) return hit.descriptor;\n return this.get(functionKey);\n }\n\n private mapRunError(error: unknown, functionKey: string | undefined): unknown {\n if (!(error instanceof CadraError)) return error;\n\n if (error.serverCode === 'DUPLICATE_REQUEST') {\n return new AiFunctionDuplicateError(error.message, error.details, error.requestId);\n }\n if (error.details?.charged === true) {\n return new AiFunctionChargedError(error);\n }\n // The server disagreed with our (cached) view of the parameters: the live\n // version probably changed. Drop the descriptor so the next run re-reads it.\n if (functionKey && error.serverCode?.startsWith('VARIABLE_')) {\n this.descriptorCache.delete(functionKey);\n }\n return error;\n }\n}\n","/**\n * Cadra Client\n *\n * Main entry point for the SDK. Provides access to all resource APIs.\n *\n * @example\n * ```typescript\n * import { CadraClient } from '@cadraos/sdk';\n *\n * const client = new CadraClient({\n * apiKey: process.env.CADRA_API_KEY,\n * orgId: Number(process.env.CADRA_ORG_ID),\n * });\n *\n * // List agents\n * const { data: agents } = await client.agents.list();\n *\n * // Execute an agent\n * const execution = await client.agents.executeSync(agents[0].uuid, {\n * task: 'Summarize the latest news',\n * });\n *\n * // Stream an agent execution\n * const stream = await client.agents.stream(agents[0].uuid, {\n * task: 'Research climate change',\n * });\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * const result = await stream.wait();\n * ```\n */\n\nimport { AgentsAPI, AiFunctionsAPI, ArtifactsAPI, AttachmentsAPI, KanbanAPI, RemoteAgentsAPI, RemoteRunnersAPI, SessionsAPI, SkillsAPI, TeamsAPI, ToolsAPI, type StreamConfig } from './resources/index.js';\nimport { HttpClient, type HttpClientConfig } from './utils/http.js';\nimport { DEFAULT_RETRY_CONFIG, type RetryConfig } from './utils/retry.js';\n\n/**\n * Default API base URL\n */\nconst DEFAULT_BASE_URL = 'https://api.cadraos.com';\n\n/**\n * Default request timeout (30 seconds)\n */\nconst DEFAULT_TIMEOUT = 30000;\n\n/**\n * Client options for API key authentication\n */\nexport interface CadraClientOptionsApiKey {\n /** API key for authentication */\n apiKey: string;\n /** Organization ID */\n orgId: number;\n /** Base URL for API (default: https://api.cadraos.com) */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts (default: 3) */\n maxRetries?: number;\n /** Custom headers to include in all requests */\n headers?: Record<string, string>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Client options for OAuth token authentication\n */\nexport interface CadraClientOptionsToken {\n /** OAuth token for authentication */\n token: string;\n /** Organization ID */\n orgId: number;\n /** Base URL for API (default: https://api.cadraos.com) */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts (default: 3) */\n maxRetries?: number;\n /** Custom headers to include in all requests */\n headers?: Record<string, string>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Client options for token provider authentication\n */\nexport interface CadraClientOptionsTokenProvider {\n /** Token provider callback (called before each request) */\n tokenProvider: () => Promise<string>;\n /** Organization ID */\n orgId: number;\n /** Base URL for API (default: https://api.cadraos.com) */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts (default: 3) */\n maxRetries?: number;\n /** Custom headers to include in all requests */\n headers?: Record<string, string>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * All client options\n */\nexport type CadraClientOptions =\n | CadraClientOptionsApiKey\n | CadraClientOptionsToken\n | CadraClientOptionsTokenProvider;\n\n/**\n * AI SaaS Client\n *\n * Main class for interacting with the AI SaaS API.\n * Provides access to all resource APIs (agents, skills, tools, artifacts, sessions).\n */\nexport class CadraClient {\n private readonly httpClient: HttpClient;\n private readonly config: {\n baseUrl: string;\n apiKey?: string;\n token?: string;\n tokenProvider?: () => Promise<string>;\n orgId: number;\n timeout: number;\n headers?: Record<string, string>;\n fetch?: typeof fetch;\n };\n\n /**\n * Agent operations (list, execute, stream, update)\n */\n readonly agents: AgentsAPI;\n\n /**\n * Skill operations (list, get, execute, update)\n */\n readonly skills: SkillsAPI;\n\n /**\n * Tool operations (list, get, execute, validate, update)\n */\n readonly tools: ToolsAPI;\n\n /**\n * Artifact operations (list, get, download, upload, delete)\n */\n readonly artifacts: ArtifactsAPI;\n\n /**\n * Attachment operations (upload, confirm, download)\n */\n readonly attachments: AttachmentsAPI;\n\n /**\n * Session operations (list, get, create, message, delete)\n */\n readonly sessions: SessionsAPI;\n\n /**\n * Team operations (list, get)\n */\n readonly teams: TeamsAPI;\n\n /**\n * Kanban operations (board, cards, transitions, card-run stream)\n */\n readonly kanban: KanbanAPI;\n\n /**\n * Remote agent operations (list, get, create, update, delete, deploy, execute, stream)\n */\n readonly remoteAgents: RemoteAgentsAPI;\n\n /**\n * Remote runner operations (list)\n */\n readonly remoteRunners: RemoteRunnersAPI;\n\n /**\n * AI function operations (list, get, run, getRun) — p93\n */\n readonly aiFunctions: AiFunctionsAPI;\n\n /**\n * Create a new AI SaaS client\n *\n * @param options - Client configuration options\n *\n * @example\n * ```typescript\n * // API key authentication\n * const client = new CadraClient({\n * apiKey: 'sk_...',\n * orgId: 123,\n * });\n *\n * // OAuth token authentication\n * const client = new CadraClient({\n * token: 'eyJ...',\n * orgId: 123,\n * });\n *\n * // Token provider (for automatic refresh)\n * const client = new CadraClient({\n * tokenProvider: async () => myAuth.getAccessToken(),\n * orgId: 123,\n * });\n * ```\n */\n constructor(options: CadraClientOptions) {\n // Validate options\n this.validateOptions(options);\n\n // Warn if baseUrl looks like it includes a path prefix (check path portion only)\n if (options.baseUrl) {\n try {\n const parsed = new URL(options.baseUrl);\n if (/\\/(api|v\\d)/.test(parsed.pathname)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n '[CadraOS SDK] baseUrl should be the origin only (e.g., \"https://api.cadraos.com\" or \"http://localhost:3000\"). ' +\n 'The SDK automatically prepends \"/api/v1/\" to all requests. ' +\n `Received: \"${options.baseUrl}\"`\n );\n }\n }\n } catch {\n // Invalid URL — will be caught later during requests\n }\n }\n\n // Store configuration\n this.config = {\n baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,\n orgId: options.orgId,\n timeout: options.timeout ?? DEFAULT_TIMEOUT,\n headers: options.headers,\n fetch: options.fetch,\n };\n\n // Set auth based on options type\n if ('apiKey' in options) {\n this.config.apiKey = options.apiKey;\n } else if ('token' in options) {\n this.config.token = options.token;\n } else if ('tokenProvider' in options) {\n this.config.tokenProvider = options.tokenProvider;\n }\n\n // Create retry configuration\n const retryConfig: RetryConfig = {\n ...DEFAULT_RETRY_CONFIG,\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries,\n };\n\n // Create HTTP client configuration\n const httpConfig: HttpClientConfig = {\n baseUrl: this.config.baseUrl,\n apiKey: this.config.apiKey,\n token: this.config.token,\n tokenProvider: this.config.tokenProvider,\n orgId: this.config.orgId,\n timeout: this.config.timeout,\n retry: retryConfig,\n headers: this.config.headers,\n fetch: this.config.fetch,\n };\n\n // Create HTTP client\n this.httpClient = new HttpClient(httpConfig);\n\n // Create stream config getter\n const getStreamConfig = (): StreamConfig => ({\n baseUrl: this.config.baseUrl,\n apiKey: this.config.apiKey,\n token: this.config.token,\n tokenProvider: this.config.tokenProvider,\n orgId: this.config.orgId,\n fetch: this.config.fetch,\n });\n\n // Initialize resource APIs\n this.agents = new AgentsAPI(this.httpClient, getStreamConfig);\n this.skills = new SkillsAPI(this.httpClient);\n this.tools = new ToolsAPI(this.httpClient);\n this.artifacts = new ArtifactsAPI(this.httpClient);\n this.attachments = new AttachmentsAPI(this.httpClient);\n this.sessions = new SessionsAPI(this.httpClient, getStreamConfig);\n this.teams = new TeamsAPI(this.httpClient);\n this.kanban = new KanbanAPI(this.httpClient, getStreamConfig);\n this.remoteAgents = new RemoteAgentsAPI(this.httpClient, getStreamConfig);\n this.remoteRunners = new RemoteRunnersAPI(this.httpClient);\n this.aiFunctions = new AiFunctionsAPI(this.httpClient);\n }\n\n /**\n * Validate client options\n */\n private validateOptions(options: CadraClientOptions): void {\n // Check for auth\n const hasApiKey = 'apiKey' in options && options.apiKey;\n const hasToken = 'token' in options && options.token;\n const hasTokenProvider = 'tokenProvider' in options && options.tokenProvider;\n\n if (!hasApiKey && !hasToken && !hasTokenProvider) {\n throw new Error(\n 'Authentication required. Provide apiKey, token, or tokenProvider.'\n );\n }\n\n // Check for orgId\n if (options.orgId === undefined || options.orgId === null) {\n throw new Error('Organization ID (orgId) is required.');\n }\n\n if (typeof options.orgId !== 'number') {\n throw new Error('Organization ID (orgId) must be a number.');\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/resources/base.ts","../src/errors/sdk-errors.ts","../src/errors/ai-function-errors.ts","../src/utils/retry.ts","../src/utils/http.ts","../src/streaming/sse-client.ts","../src/streaming/extract-images.ts","../src/streaming/poll-policy.ts","../src/streaming/stream-controller.ts","../src/streaming/collect-images.ts","../src/utils/api-paths.ts","../src/utils/message-key.ts","../src/resources/agent-messages.ts","../src/resources/agents.ts","../src/resources/skills.ts","../src/resources/tools.ts","../src/resources/artifacts.ts","../src/resources/attachments.ts","../src/resources/sessions.ts","../src/resources/kanban.ts","../src/resources/teams.ts","../src/resources/remote-agents.ts","../src/resources/remote-runners.ts","../src/resources/ai-functions.ts","../src/client.ts"],"names":["value"],"mappings":";;;AAaO,IAAe,kBAAf,MAA+B;AAAA,EACjB,IAAA;AAAA,EACA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AAe,CAAA;AACxE,IAAA,IAAA,CAAK,aAAA,GAAgB,IAAI,gBAAA,CAAiB,IAAA,CAAK,UAAU,CAAA;AACzD,IAAA,IAAA,CAAK,WAAA,GAAc,IAAI,cAAA,CAAe,IAAA,CAAK,UAAU,CAAA;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA,EAKQ,gBAAgB,OAAA,EAAmC;AAEzD,IAAA,MAAM,SAAA,GAAY,QAAA,IAAY,OAAA,IAAW,OAAA,CAAQ,MAAA;AACjD,IAAA,MAAM,QAAA,GAAW,OAAA,IAAW,OAAA,IAAW,OAAA,CAAQ,KAAA;AAC/C,IAAA,MAAM,gBAAA,GAAmB,eAAA,IAAmB,OAAA,IAAW,OAAA,CAAQ,aAAA;AAE/D,IAAA,IAAI,CAAC,SAAA,IAAa,CAAC,QAAA,IAAY,CAAC,gBAAA,EAAkB;AAChD,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAGA,IAAA,IAAI,OAAA,CAAQ,KAAA,KAAU,MAAA,IAAa,OAAA,CAAQ,UAAU,IAAA,EAAM;AACzD,MAAA,MAAM,IAAI,MAAM,sCAAsC,CAAA;AAAA,IACxD;AAEA,IAAA,IAAI,OAAO,OAAA,CAAQ,KAAA,KAAU,QAAA,EAAU;AACrC,MAAA,MAAM,IAAI,MAAM,2CAA2C,CAAA;AAAA,IAC7D;AAAA,EACF;AACF","file":"index.cjs","sourcesContent":["/**\n * Base Resource API\n *\n * Abstract base class for all resource APIs.\n * Provides common HTTP methods and path handling.\n */\n\nimport type { HttpClient } from '../utils/http.js';\nimport type { ListOptions, PaginatedResponse } from '../types/index.js';\n\n/**\n * Base Resource API class\n */\nexport abstract class BaseResourceAPI {\n protected readonly http: HttpClient;\n protected readonly basePath: string;\n\n constructor(http: HttpClient, basePath: string) {\n this.http = http;\n this.basePath = basePath;\n }\n\n /**\n * Build query parameters from list options\n */\n protected buildListQuery(options?: ListOptions): Record<string, string | number | boolean | undefined> {\n if (!options) return {};\n\n return {\n limit: options.limit,\n offset: options.offset,\n sort: options.sort,\n order: options.order,\n };\n }\n\n /**\n * HTTP GET request helper\n */\n protected async httpGet<T>(\n path: string,\n query?: Record<string, string | number | boolean | undefined>\n ): Promise<T> {\n return this.http.get<T>(`${this.basePath}${path}`, query);\n }\n\n /**\n * HTTP POST request helper\n */\n protected async httpPost<T>(\n path: string,\n body?: unknown,\n options?: { idempotencyKey?: string; skipRetry?: boolean; timeoutMs?: number }\n ): Promise<T> {\n return this.http.post<T>(`${this.basePath}${path}`, body, options);\n }\n\n /**\n * HTTP PATCH request helper\n */\n protected async httpPatch<T>(\n path: string,\n body?: unknown,\n options?: { idempotencyKey?: string; skipRetry?: boolean }\n ): Promise<T> {\n return this.http.patch<T>(`${this.basePath}${path}`, body, options);\n }\n\n /**\n * HTTP DELETE request helper\n */\n protected async httpDelete<T>(path: string): Promise<T> {\n return this.http.delete<T>(`${this.basePath}${path}`);\n }\n\n /**\n * List resources with pagination\n */\n protected async listResources<T>(\n path: string,\n options?: ListOptions\n ): Promise<PaginatedResponse<T>> {\n const query = this.buildListQuery(options);\n // The API returns { data: T[], pagination: ... } which we unwrap\n return this.httpGet<PaginatedResponse<T>>(path, query);\n }\n}\n","/**\n * SDK Error Classes\n *\n * Typed error hierarchy for all SDK operations.\n * All errors extend CadraError and include code, status, and optional details.\n */\n\n/**\n * Base error class for all SDK errors\n */\nexport class CadraError extends Error {\n /** Error code */\n readonly code: string;\n /** HTTP status code */\n readonly status: number;\n /** Additional error details */\n readonly details?: Record<string, unknown>;\n /** Request ID from server (for debugging) */\n readonly requestId?: string;\n /**\n * The server's own `error.code` exactly as sent on the wire (e.g.\n * `FUNCTION_NOT_PUBLISHED`, `DUPLICATE_REQUEST`, `VARIABLE_TYPE`).\n * Populated by `parseApiError` for EVERY status. `code` keeps its historic\n * per-class values (`conflict`, `server_error`, `validation_error`, …) for\n * compatibility; branch on `serverCode` when you need the precise reason.\n */\n serverCode?: string;\n\n constructor(\n message: string,\n code: string,\n status: number,\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message);\n this.name = 'CadraError';\n this.code = code;\n this.status = status;\n this.details = details;\n this.requestId = requestId;\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n}\n\n/**\n * Authentication error (401)\n * Thrown when API key is invalid, expired, or missing\n */\nexport class AuthenticationError extends CadraError {\n constructor(\n message: string = 'Authentication failed',\n code: string = 'authentication_error',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, code, 401, details, requestId);\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * Authorization error (403)\n * Thrown when user lacks permission for the requested operation\n */\nexport class AuthorizationError extends CadraError {\n constructor(\n message: string = 'Access denied',\n code: string = 'authorization_error',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, code, 403, details, requestId);\n this.name = 'AuthorizationError';\n }\n}\n\n/**\n * Not found error (404)\n * Thrown when requested resource does not exist\n */\nexport class NotFoundError extends CadraError {\n constructor(\n message: string = 'Resource not found',\n code: string = 'not_found',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, code, 404, details, requestId);\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * Validation error (400/422)\n * Thrown when request input is invalid\n */\nexport class ValidationError extends CadraError {\n /** Field-level validation errors */\n readonly errors: Array<{ field: string; message: string }>;\n\n constructor(\n message: string = 'Validation failed',\n errors: Array<{ field: string; message: string }> = [],\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'validation_error', 400, details, requestId);\n this.name = 'ValidationError';\n this.errors = errors;\n }\n}\n\n/**\n * Rate limit error (429)\n * Thrown when rate limit is exceeded\n */\nexport class RateLimitError extends CadraError {\n /** Seconds until rate limit resets */\n readonly retryAfter?: number;\n\n constructor(\n message: string = 'Rate limit exceeded',\n retryAfter?: number,\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'rate_limit_error', 429, details, requestId);\n this.name = 'RateLimitError';\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * Server error (5xx)\n * Thrown for server-side errors\n */\nexport class ServerError extends CadraError {\n constructor(\n message: string = 'Server error',\n status: number = 500,\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'server_error', status, details, requestId);\n this.name = 'ServerError';\n }\n}\n\n/**\n * Conflict error (409)\n * Thrown when there is a resource conflict\n */\nexport class ConflictError extends CadraError {\n constructor(\n message: string = 'Resource conflict',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'conflict', 409, details, requestId);\n this.name = 'ConflictError';\n }\n}\n\n/**\n * Timeout error\n * Thrown when a request or operation times out\n */\nexport class TimeoutError extends CadraError {\n constructor(\n message: string = 'Request timed out',\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, 'timeout', 408, details, requestId);\n this.name = 'TimeoutError';\n }\n}\n\n/**\n * Network error\n * Thrown when there is a network connectivity issue\n */\nexport class NetworkError extends CadraError {\n constructor(\n message: string = 'Network error',\n details?: Record<string, unknown>\n ) {\n super(message, 'network_error', 0, details);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Parse error from API response to appropriate error class\n */\nexport function parseApiError(\n status: number,\n body: unknown,\n requestId?: string\n): CadraError {\n const errorBody = body as {\n error?: {\n code?: string;\n message?: string;\n details?: Record<string, unknown>;\n };\n } | null;\n\n const message = errorBody?.error?.message ?? 'An error occurred';\n const code = errorBody?.error?.code ?? 'unknown_error';\n const details = errorBody?.error?.details;\n const serverCode =\n typeof errorBody?.error?.code === 'string' ? errorBody.error.code : undefined;\n\n const error = buildApiError(status, message, code, details, requestId);\n if (serverCode !== undefined) error.serverCode = serverCode;\n return error;\n}\n\nfunction buildApiError(\n status: number,\n message: string,\n code: string,\n details: Record<string, unknown> | undefined,\n requestId: string | undefined\n): CadraError {\n switch (status) {\n case 400:\n case 422: {\n // Check if it's a validation error with field errors\n const fieldErrors = details?.errors as Record<string, string[]> | undefined;\n if (fieldErrors) {\n const errors: Array<{ field: string; message: string }> = [];\n for (const [field, messages] of Object.entries(fieldErrors)) {\n for (const msg of messages) {\n errors.push({ field, message: msg });\n }\n }\n return new ValidationError(message, errors, details, requestId);\n }\n return new ValidationError(message, [], details, requestId);\n }\n\n case 401:\n return new AuthenticationError(message, code, details, requestId);\n\n case 403:\n return new AuthorizationError(message, code, details, requestId);\n\n case 404:\n return new NotFoundError(message, code, details, requestId);\n\n case 409:\n return new ConflictError(message, details, requestId);\n\n case 429: {\n const retryAfter = details?.retryAfter as number | undefined;\n return new RateLimitError(message, retryAfter, details, requestId);\n }\n\n default:\n if (status >= 500) {\n return new ServerError(message, status, details, requestId);\n }\n return new CadraError(message, code, status, details, requestId);\n }\n}\n","/**\n * AI function errors (p93 AIF-010, specs §9 + D27c).\n *\n * All extend the existing hierarchy so `instanceof CadraError` (and, where it\n * applies, `ConflictError` / `ValidationError`) keeps working.\n */\n\nimport type { AiFunctionParameterIssue } from '../types/ai-functions.js';\nimport { CadraError, ConflictError, ValidationError } from './sdk-errors.js';\n\n/**\n * 409 `DUPLICATE_REQUEST`: a run with the same idempotency key already exists.\n * No provider call was made. A retry after `abandoned` or a failure needs a NEW key.\n */\nexport class AiFunctionDuplicateError extends ConflictError {\n /** The existing run's execution id. */\n readonly executionId?: string;\n /** The existing run's status (`running`, a terminal status, or `abandoned`). */\n readonly runStatus?: string;\n\n constructor(\n message: string,\n details?: Record<string, unknown>,\n requestId?: string\n ) {\n super(message, details, requestId);\n this.name = 'AiFunctionDuplicateError';\n this.serverCode = 'DUPLICATE_REQUEST';\n this.executionId = typeof details?.executionId === 'string' ? details.executionId : undefined;\n this.runStatus = typeof details?.status === 'string' ? details.status : undefined;\n }\n}\n\n/**\n * The provider answered 2xx and the run WAS metered, but the output then failed\n * (`OUTPUT_INVALID`, `DELIVERY_FAILED` — `details.charged: true`). Never retry\n * automatically: a retry is a second paid call.\n */\nexport class AiFunctionChargedError extends CadraError {\n constructor(source: CadraError) {\n super(source.message, source.code, source.status, source.details, source.requestId);\n this.name = 'AiFunctionChargedError';\n this.serverCode = source.serverCode;\n }\n}\n\n/**\n * The client-side parameter check failed (D27c). No run request was sent.\n * Also a `ValidationError`, with one `errors[]` entry per issue.\n */\nexport class AiFunctionParameterError extends ValidationError {\n readonly functionKey: string;\n readonly issues: AiFunctionParameterIssue[];\n\n constructor(functionKey: string, issues: AiFunctionParameterIssue[]) {\n super(\n `Invalid parameters for AI function \"${functionKey}\": ` +\n issues.map((i) => `${i.name} (${i.code})`).join(', '),\n issues.map((i) => ({ field: i.name, message: i.code })),\n { functionKey, issues }\n );\n this.name = 'AiFunctionParameterError';\n this.functionKey = functionKey;\n this.issues = issues;\n }\n}\n","/**\n * Retry utility with exponential backoff\n */\n\nimport { RateLimitError, ServerError } from '../errors/index.js';\n\n/**\n * Retry configuration\n */\nexport interface RetryConfig {\n /** Maximum number of retry attempts (default: 3) */\n maxRetries: number;\n /** Base delay in milliseconds (default: 1000) */\n baseDelayMs: number;\n /** Maximum delay in milliseconds (default: 30000) */\n maxDelayMs: number;\n /** Jitter factor (0-1, default: 0.1) */\n jitterFactor: number;\n}\n\n/**\n * Default retry configuration\n */\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxRetries: 3,\n baseDelayMs: 1000,\n maxDelayMs: 30000,\n jitterFactor: 0.1,\n};\n\n/**\n * Determine if an error should be retried\n */\nexport function shouldRetry(error: unknown, attempt: number, maxRetries: number): boolean {\n if (attempt >= maxRetries) {\n return false;\n }\n\n // Retry on rate limit errors\n if (error instanceof RateLimitError) {\n return true;\n }\n\n // Retry on 5xx server errors\n if (error instanceof ServerError) {\n return true;\n }\n\n // Retry on network errors\n if (error instanceof Error && error.name === 'NetworkError') {\n return true;\n }\n\n // Retry on timeout errors\n if (error instanceof Error && error.name === 'TimeoutError') {\n return true;\n }\n\n // Don't retry other errors (4xx except 429)\n return false;\n}\n\n/**\n * Calculate delay before next retry with exponential backoff and jitter\n */\nexport function calculateRetryDelay(\n attempt: number,\n config: RetryConfig,\n retryAfter?: number\n): number {\n // If server specified retry-after, use it\n if (retryAfter !== undefined && retryAfter > 0) {\n return retryAfter * 1000; // Convert seconds to milliseconds\n }\n\n // Exponential backoff: delay = base * 2^attempt\n const exponentialDelay = config.baseDelayMs * Math.pow(2, attempt);\n\n // Cap at max delay\n const cappedDelay = Math.min(exponentialDelay, config.maxDelayMs);\n\n // Add jitter to prevent thundering herd\n const jitter = cappedDelay * config.jitterFactor * Math.random();\n\n return cappedDelay + jitter;\n}\n\n/**\n * Sleep for specified milliseconds\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Retry wrapper for async operations\n */\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n config: Partial<RetryConfig> = {}\n): Promise<T> {\n const fullConfig: RetryConfig = { ...DEFAULT_RETRY_CONFIG, ...config };\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= fullConfig.maxRetries; attempt++) {\n try {\n return await operation();\n } catch (error) {\n lastError = error;\n\n if (!shouldRetry(error, attempt, fullConfig.maxRetries)) {\n throw error;\n }\n\n // Get retry-after from rate limit error if available\n const retryAfter = error instanceof RateLimitError ? error.retryAfter : undefined;\n const delay = calculateRetryDelay(attempt, fullConfig, retryAfter);\n\n await sleep(delay);\n }\n }\n\n // Should never reach here, but TypeScript needs this\n throw lastError;\n}\n","/**\n * HTTP Client\n *\n * Handles all HTTP requests with authentication, retry logic, and error handling.\n */\n\nimport {\n parseApiError,\n NetworkError,\n TimeoutError,\n} from '../errors/index.js';\nimport type { ApiResponse, ApiSuccessResponse } from '../types/index.js';\nimport { withRetry, type RetryConfig } from './retry.js';\n\n/**\n * HTTP Client configuration\n */\nexport interface HttpClientConfig {\n /** Base URL for API requests */\n baseUrl: string;\n /** API key for authentication */\n apiKey?: string;\n /** OAuth token for authentication */\n token?: string;\n /** Token provider callback (called before each request) */\n tokenProvider?: () => Promise<string>;\n /** Organization ID */\n orgId: number;\n /** Request timeout in milliseconds (default: 30000) */\n timeout: number;\n /** Retry configuration */\n retry: RetryConfig;\n /** Custom headers */\n headers?: Record<string, string>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Request options\n */\nexport interface RequestOptions {\n /** HTTP method */\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE' | 'PUT';\n /** Request path (appended to base URL) */\n path: string;\n /** Request body */\n body?: unknown;\n /** Query parameters */\n query?: Record<string, string | number | boolean | undefined>;\n /** Additional headers */\n headers?: Record<string, string>;\n /** Skip retry (for non-idempotent operations) */\n skipRetry?: boolean;\n /** Idempotency key */\n idempotencyKey?: string;\n /**\n * Per-request timeout in milliseconds. Overrides the client-wide\n * `config.timeout` for this call only (p93 AIF-010: a paid AI-function run\n * waits for the server's route ceiling while every other call keeps the\n * 30 s default).\n */\n timeoutMs?: number;\n}\n\n/**\n * HTTP Client class\n */\nexport class HttpClient {\n private config: HttpClientConfig;\n private tokenRefreshAttempts = 0;\n private readonly maxTokenRefreshAttempts = 2;\n\n constructor(config: HttpClientConfig) {\n this.config = config;\n }\n\n /** The client-wide request timeout (ms) this client was configured with. */\n get timeoutMs(): number {\n return this.config.timeout;\n }\n\n /**\n * Get authorization header value\n */\n private async getAuthHeader(): Promise<string> {\n if (this.config.apiKey) {\n return `Bearer ${this.config.apiKey}`;\n }\n\n if (this.config.tokenProvider) {\n const token = await this.config.tokenProvider();\n return `Bearer ${token}`;\n }\n\n if (this.config.token) {\n return `Bearer ${this.config.token}`;\n }\n\n throw new Error('No authentication configured. Provide apiKey, token, or tokenProvider.');\n }\n\n /**\n * Build full URL with query parameters\n */\n private buildUrl(path: string, query?: Record<string, string | number | boolean | undefined>): string {\n // Simple concatenation — baseUrl is the origin (e.g., \"https://api.cadraos.com\"),\n // path already includes the full route (e.g., \"/api/v1/agents\").\n const base = this.config.baseUrl.replace(/\\/+$/, '');\n let url = `${base}${path}`;\n\n if (query) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n params.set(key, String(value));\n }\n }\n const qs = params.toString();\n if (qs) {\n url += `?${qs}`;\n }\n }\n\n return url;\n }\n\n /**\n * Make an HTTP request\n */\n async request<T>(options: RequestOptions): Promise<T> {\n const makeRequest = async (): Promise<T> => {\n const url = this.buildUrl(options.path, options.query);\n const authHeader = await this.getAuthHeader();\n\n const headers: Record<string, string> = {\n 'Authorization': authHeader,\n 'X-Org-Id': String(this.config.orgId),\n 'Content-Type': 'application/json',\n ...this.config.headers,\n ...options.headers,\n };\n\n // Add idempotency key for mutating operations\n if (options.idempotencyKey) {\n headers['Idempotency-Key'] = options.idempotencyKey;\n }\n\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutMs = options.timeoutMs ?? this.config.timeout;\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n\n try {\n const doFetch = this.config.fetch ?? fetch;\n const response = await doFetch(url, {\n method: options.method,\n headers,\n body: options.body !== undefined ? JSON.stringify(options.body) : undefined,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n\n // Get request ID from response headers\n const requestId = response.headers.get('X-Request-Id') ?? undefined;\n\n // Parse response body\n let body: unknown;\n const contentType = response.headers.get('Content-Type');\n if (contentType?.includes('application/json')) {\n body = await response.json();\n } else {\n body = await response.text();\n }\n\n // Handle errors\n if (!response.ok) {\n // Check for 401 and token provider - try refresh\n if (response.status === 401 && this.config.tokenProvider) {\n this.tokenRefreshAttempts++;\n if (this.tokenRefreshAttempts < this.maxTokenRefreshAttempts) {\n // Token provider should return a fresh token\n // Retry the request (token provider will be called again)\n return this.request(options);\n }\n }\n\n throw parseApiError(response.status, body, requestId);\n }\n\n // Reset token refresh attempts on success\n this.tokenRefreshAttempts = 0;\n\n // Handle success response\n const apiResponse = body as ApiResponse<T>;\n if ('success' in apiResponse && apiResponse.success) {\n return (apiResponse as ApiSuccessResponse<T>).data;\n }\n\n // If response doesn't match expected format, return as-is\n return body as T;\n\n } catch (error) {\n clearTimeout(timeoutId);\n\n // Handle abort (timeout)\n if (error instanceof Error && error.name === 'AbortError') {\n throw new TimeoutError(`Request timed out after ${options.timeoutMs ?? this.config.timeout}ms`);\n }\n\n // Handle fetch errors (network issues)\n if (error instanceof TypeError && error.message.includes('fetch')) {\n throw new NetworkError(`Network error: ${error.message}`);\n }\n\n throw error;\n }\n };\n\n // Use retry wrapper for idempotent operations\n if (options.skipRetry) {\n return makeRequest();\n }\n\n return withRetry(makeRequest, this.config.retry);\n }\n\n /**\n * GET request\n */\n async get<T>(\n path: string,\n query?: Record<string, string | number | boolean | undefined>\n ): Promise<T> {\n return this.request<T>({\n method: 'GET',\n path,\n query,\n });\n }\n\n /**\n * POST request\n */\n async post<T>(\n path: string,\n body?: unknown,\n options?: { idempotencyKey?: string; skipRetry?: boolean; timeoutMs?: number }\n ): Promise<T> {\n return this.request<T>({\n method: 'POST',\n path,\n body,\n idempotencyKey: options?.idempotencyKey,\n skipRetry: options?.skipRetry,\n timeoutMs: options?.timeoutMs,\n });\n }\n\n /**\n * PATCH request\n */\n async patch<T>(\n path: string,\n body?: unknown,\n options?: { idempotencyKey?: string; skipRetry?: boolean }\n ): Promise<T> {\n return this.request<T>({\n method: 'PATCH',\n path,\n body,\n idempotencyKey: options?.idempotencyKey,\n skipRetry: options?.skipRetry,\n });\n }\n\n /**\n * DELETE request\n */\n async delete<T>(path: string): Promise<T> {\n return this.request<T>({\n method: 'DELETE',\n path,\n skipRetry: true, // Don't retry deletes\n });\n }\n\n /**\n * Update configuration\n */\n updateConfig(config: Partial<HttpClientConfig>): void {\n this.config = { ...this.config, ...config };\n }\n}\n\n/**\n * Generate a random idempotency key\n */\nexport function generateIdempotencyKey(): string {\n const timestamp = Date.now().toString(36);\n const random = Math.random().toString(36).substring(2, 15);\n return `idem_${timestamp}_${random}`;\n}\n\n/**\n * Generate an RFC-4122 v4 UUID for a client-prepared executionId.\n *\n * The `Idempotency-Key` HEADER is opaque, but cadra-web dedupes a duplicate\n * remote dispatch on the body `executionId` (a UUID). So to make the SDK's\n * automatic retries idempotent end-to-end, execute() must send a STABLE\n * executionId — not just the header. Prefers the platform `crypto.randomUUID()`\n * (modern browsers, Node 19+); falls back to a Math.random v4 only so the SDK\n * never hard-fails in unusual environments (the server accepts any valid UUID).\n */\nexport function generateExecutionId(): string {\n const g =\n typeof globalThis !== 'undefined'\n ? (globalThis as { crypto?: { randomUUID?: () => string } })\n : undefined;\n if (g?.crypto?.randomUUID) {\n return g.crypto.randomUUID();\n }\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n","/**\n * SSE Client\n *\n * Handles Server-Sent Events connections with automatic reconnection.\n * Uses fetch + ReadableStream for cross-platform compatibility.\n */\n\nimport type { SSEEvent, StreamEventType } from '../types/streaming.js';\n\n/**\n * SSE Client configuration\n */\nexport interface SSEClientConfig {\n /** Stream URL */\n url: string;\n /** Authorization header */\n authHeader: string;\n /** Organization ID */\n orgId: number;\n /** Event callback */\n onEvent: (event: SSEEvent) => void;\n /** Error callback */\n onError: (error: Error) => void;\n /** Connection state callback */\n onConnectionChange: (connected: boolean) => void;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n /**\n * Last event id seen on a previous connection. Sent as `Last-Event-ID` so the\n * server can replay only what was missed instead of the whole backlog. The\n * controller dedupes by event id regardless, so this is an optimisation, not\n * a correctness requirement.\n */\n lastEventId?: string | null;\n}\n\n/**\n * SSE Client class\n *\n * Implements SSE parsing using fetch + ReadableStream for compatibility\n * with both Node.js and browser environments.\n */\nexport class SSEClient {\n private config: SSEClientConfig;\n private abortController: AbortController | null = null;\n private connected = false;\n\n constructor(config: SSEClientConfig) {\n this.config = config;\n }\n\n /**\n * Connect to SSE endpoint\n */\n async connect(): Promise<void> {\n this.abortController = new AbortController();\n\n // Debug logging for SSE connection\n console.log('[SDK:SSE] Connecting to:', this.config.url);\n console.log('[SDK:SSE] Auth header:', this.config.authHeader ? `${this.config.authHeader.substring(0, 30)}...` : 'MISSING');\n console.log('[SDK:SSE] Org ID:', this.config.orgId);\n\n try {\n const doFetch = this.config.fetch ?? fetch;\n const response = await doFetch(this.config.url, {\n method: 'GET',\n headers: {\n 'Authorization': this.config.authHeader,\n 'X-Org-Id': String(this.config.orgId),\n 'Accept': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n ...(this.config.lastEventId ? { 'Last-Event-ID': this.config.lastEventId } : {}),\n },\n signal: this.abortController.signal,\n });\n\n console.log('[SDK:SSE] Response status:', response.status, response.statusText);\n console.log('[SDK:SSE] Response headers:', {\n contentType: response.headers.get('content-type'),\n cacheControl: response.headers.get('cache-control'),\n });\n\n if (!response.ok) {\n // Try to get error body for better debugging\n let errorBody = '';\n try {\n errorBody = await response.text();\n console.error('[SDK:SSE] Error response body:', errorBody);\n } catch (e) {\n console.error('[SDK:SSE] Could not read error body');\n }\n throw new Error(`SSE connection failed: ${response.status} ${response.statusText} - ${errorBody}`);\n }\n\n if (!response.body) {\n throw new Error('Response body not available');\n }\n\n console.log('[SDK:SSE] Connection successful, starting stream parsing');\n this.connected = true;\n this.config.onConnectionChange(true);\n\n // Parse SSE stream\n await this.parseStream(response.body);\n\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n // Intentional disconnect\n console.log('[SDK:SSE] Connection aborted (intentional)');\n return;\n }\n console.error('[SDK:SSE] Connection error:', error);\n this.config.onError(error instanceof Error ? error : new Error(String(error)));\n } finally {\n this.connected = false;\n this.config.onConnectionChange(false);\n console.log('[SDK:SSE] Connection closed');\n }\n }\n\n /**\n * Disconnect from SSE endpoint\n */\n disconnect(): void {\n if (this.abortController) {\n this.abortController.abort();\n this.abortController = null;\n }\n this.connected = false;\n }\n\n /**\n * Check if connected\n */\n isConnected(): boolean {\n return this.connected;\n }\n\n /**\n * Parse SSE stream\n */\n private async parseStream(body: ReadableStream<Uint8Array>): Promise<void> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n\n let buffer = '';\n let currentEvent: Partial<{ type: string; id: string; data: string }> = {};\n let chunkCount = 0;\n let eventCount = 0;\n\n console.log('[SDK:SSE] Starting to parse stream');\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n\n if (done) {\n console.log('[SDK:SSE] Stream reading complete. Total chunks:', chunkCount, 'events:', eventCount);\n break;\n }\n\n chunkCount++;\n const chunk = decoder.decode(value, { stream: true });\n buffer += chunk;\n\n // Debug: Log raw chunk (first 200 chars)\n if (chunkCount <= 5) {\n console.log(`[SDK:SSE] Chunk ${chunkCount} (${value.length} bytes):`, chunk.substring(0, 200));\n }\n\n // Process complete lines\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? ''; // Keep incomplete line in buffer\n\n for (const line of lines) {\n // Empty line signals end of event\n if (line === '') {\n if (currentEvent.type && currentEvent.data !== undefined) {\n eventCount++;\n console.log(`[SDK:SSE] Event ${eventCount}:`, currentEvent.type, '- data length:', currentEvent.data.length);\n this.dispatchEvent(currentEvent as { type: string; id?: string; data: string });\n }\n currentEvent = {};\n continue;\n }\n\n // Skip comments (keepalive)\n if (line.startsWith(':')) {\n continue;\n }\n\n // Parse SSE fields\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) {\n continue;\n }\n\n const field = line.substring(0, colonIndex);\n // Value starts after colon, skip optional leading space\n let value = line.substring(colonIndex + 1);\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n\n switch (field) {\n case 'event':\n currentEvent.type = value;\n break;\n case 'id':\n currentEvent.id = value;\n break;\n case 'data':\n // Append to existing data (multiple data lines)\n currentEvent.data = currentEvent.data\n ? currentEvent.data + '\\n' + value\n : value;\n break;\n }\n }\n }\n } finally {\n console.log('[SDK:SSE] parseStream finished. Releasing reader lock.');\n reader.releaseLock();\n }\n }\n\n /**\n * Dispatch parsed event\n */\n private dispatchEvent(event: { type: string; id?: string; data: string }): void {\n console.log('[SDK:SSE] dispatchEvent called:', event.type, 'id:', event.id);\n\n try {\n // Parse JSON data\n let data: unknown;\n try {\n data = JSON.parse(event.data);\n console.log('[SDK:SSE] Parsed event data:', typeof data, data && typeof data === 'object' ? Object.keys(data as object) : '');\n } catch {\n // If not JSON, use raw string\n data = event.data;\n }\n\n const sseEvent: SSEEvent = {\n type: event.type as StreamEventType,\n id: event.id,\n data,\n };\n\n this.config.onEvent(sseEvent);\n } catch (error) {\n this.config.onError(\n error instanceof Error ? error : new Error(`Failed to parse event: ${String(error)}`)\n );\n }\n }\n}\n","/**\n * Image extraction utilities\n *\n * Pure, environment-agnostic functions for pulling image URLs out of agent\n * tool results and execution outputs. Works in Node and the browser, no\n * React or DOM dependencies.\n *\n * Used by:\n * - ExecutionStreamController — derives 'image' events from tool_result events\n * so any consumer can subscribe to images as they're generated.\n * - useAgentChat — renders image artifacts inline in chat messages.\n * - Server-side workers (Node) — persist images progressively without React.\n *\n * Recognised result shapes (in priority order):\n * 1. { images: [{ url, thumbnailUrl?, filename?, mimeType?, dimensions?, prompt? }, ...] }\n * Emitted by cadra-api's response-transformer for create_ad_images, edit_image,\n * and any tool that produces image artifacts.\n * 2. { url: '...png' } — single image with image extension.\n * 3. { imageUrl: '...' } — alternate single-image shape.\n * 4. JSON string wrapping any of the above (with optional ```json fence).\n * 5. Bare image URL string or data: URL.\n */\n\n/**\n * Image extracted from a tool result or execution output.\n *\n * Shape is a superset of historical chat ImageData — all extra fields are\n * optional, so existing chat consumers keep working unchanged.\n */\nexport interface ImageData {\n /** Full-size image URL (https) */\n url: string;\n /** Optional thumbnail URL (smaller, for chat / preview display) */\n thumbnailUrl?: string;\n /** Original filename */\n filename?: string;\n /** MIME type (e.g. image/png) */\n mimeType?: string;\n /** Alt text — falls back to the agent's prompt if no explicit alt was provided */\n alt?: string;\n /** Image width in pixels */\n width?: number;\n /** Image height in pixels */\n height?: number;\n /** ID of the tool call that produced this image (when extracted from a tool_result) */\n sourceToolCallId?: string;\n /** Execution UUID this image came from (when extracted via the streaming pipeline) */\n executionId?: string;\n}\n\n/**\n * Optional context applied to every extracted image.\n * Use this to attach the originating tool-call and execution IDs.\n */\nexport interface ExtractContext {\n sourceToolCallId?: string;\n executionId?: string;\n}\n\nconst IMAGE_EXT_RE = /\\.(png|jpg|jpeg|gif|webp|svg|bmp)(\\?.*)?$/i;\n\n/**\n * Extract images from a single tool result.\n *\n * @param result The tool result. May be an object, an already-parsed value,\n * or a JSON / URL string.\n * @param ctx Optional sourceToolCallId / executionId to attach to each\n * extracted image.\n */\nexport function extractImagesFromResult(\n result: unknown,\n ctx: ExtractContext = {}\n): ImageData[] {\n if (!result) return [];\n\n let data: unknown = result;\n\n if (typeof result === 'string') {\n // Bare image URL or data: URL? treat as a single image.\n if (IMAGE_EXT_RE.test(result) || result.startsWith('data:image/')) {\n return [{ url: normalizeUrl(result), sourceToolCallId: ctx.sourceToolCallId, executionId: ctx.executionId }];\n }\n // Otherwise try to parse as JSON (possibly wrapped in a code fence).\n const fence = result.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n const jsonStr = fence?.[1] ?? result;\n try {\n data = JSON.parse(jsonStr.trim());\n } catch {\n return [];\n }\n }\n\n if (typeof data !== 'object' || data === null) return [];\n const obj = data as Record<string, unknown>;\n\n // Pattern 1: { images: [...] } — preferred (cadra-api ResponseTransformer)\n if (Array.isArray(obj.images)) {\n return (obj.images as Array<Record<string, unknown>>)\n .filter((img) => img && typeof img.url === 'string')\n .map((img) => mapImage(img, ctx));\n }\n\n // Pattern 2: { url: \"...png\" }\n if (typeof obj.url === 'string' && IMAGE_EXT_RE.test(obj.url)) {\n return [mapImage(obj, ctx)];\n }\n\n // Pattern 3: { imageUrl: \"...\" }\n if (typeof obj.imageUrl === 'string') {\n return [{\n url: normalizeUrl(obj.imageUrl),\n thumbnailUrl: typeof obj.thumbnailUrl === 'string' ? normalizeUrl(obj.thumbnailUrl) : undefined,\n alt: (obj.alt as string) || (obj.prompt as string) || undefined,\n sourceToolCallId: ctx.sourceToolCallId,\n executionId: ctx.executionId,\n }];\n }\n\n return [];\n}\n\n/**\n * Extract images from a final execution output.\n *\n * Execution outputs are often JSON strings, sometimes wrapped in a markdown\n * `json` code fence. This helper unwraps + parses + delegates to\n * extractImagesFromResult.\n *\n * Use this when an execution has already completed and you have its\n * `output` field — for live executions, prefer subscribing to the\n * stream's `image` event.\n */\nexport function extractImagesFromExecutionOutput(\n output: unknown,\n ctx: ExtractContext = {}\n): ImageData[] {\n let parsed: unknown = output;\n\n if (typeof output === 'string') {\n const fence = output.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/);\n const jsonStr = fence?.[1] ?? output;\n try {\n parsed = JSON.parse(jsonStr.trim());\n } catch {\n // Not JSON — try the bare-URL / data-URL fallbacks via extractImagesFromResult.\n return extractImagesFromResult(output, ctx);\n }\n }\n\n return extractImagesFromResult(parsed, ctx);\n}\n\n/**\n * Aggregate images from a list of completed tool calls.\n *\n * Used by chat-style consumers that maintain an ordered list of tool calls\n * and want a single source of truth for the displayed image list.\n */\nexport function deriveImagesFromToolCalls<\n T extends { id?: string; status?: string; result?: unknown }\n>(toolCalls: T[] | undefined, ctx: Omit<ExtractContext, 'sourceToolCallId'> = {}): ImageData[] {\n if (!toolCalls) return [];\n const images: ImageData[] = [];\n for (const tc of toolCalls) {\n if (tc.status === 'completed' && tc.result) {\n images.push(...extractImagesFromResult(tc.result, { ...ctx, sourceToolCallId: tc.id }));\n }\n }\n return images;\n}\n\n// =============================================================================\n// INTERNAL\n// =============================================================================\n\nfunction mapImage(img: Record<string, unknown>, ctx: ExtractContext): ImageData {\n const dims = img.dimensions as Record<string, unknown> | undefined;\n return {\n url: normalizeUrl(img.url as string),\n thumbnailUrl: typeof img.thumbnailUrl === 'string' ? normalizeUrl(img.thumbnailUrl) : undefined,\n filename: img.filename as string | undefined,\n mimeType: img.mimeType as string | undefined,\n alt: (img.alt as string) || (img.prompt as string) || undefined,\n width: typeof dims?.width === 'number' ? (dims.width as number) : (img.width as number | undefined),\n height: typeof dims?.height === 'number' ? (dims.height as number) : (img.height as number | undefined),\n sourceToolCallId: ctx.sourceToolCallId,\n executionId: ctx.executionId,\n };\n}\n\n/**\n * Cadra agents sometimes emit `LINK://` URLs to defeat auto-link rendering\n * in chat UIs. Convert those back to https for downstream consumers.\n */\nfunction normalizeUrl(url: string): string {\n if (url.startsWith('LINK://')) return url.replace('LINK://', 'https://');\n return url;\n}\n","/**\n * Poll Policy\n *\n * Backpressure helpers for the SSE fallback polling loop.\n *\n * The fallback loop talks to an API key that is shared with every other feature\n * on the same key. A loop that ignores 429 does not just fail itself — it burns\n * the shared quota and takes unrelated features down with it. These helpers give\n * the loop the two things it needs to be a good citizen: a structural way to\n * recognise \"the server told me to stop\", and a delay schedule that grows when\n * the loop is failing or learning nothing.\n *\n * Everything here is pure and synchronous so the loop's timing can be asserted\n * under fake timers.\n */\n\n/** Delay a rate-limited loop waits when the server named no reset (ms). */\nexport const UNNAMED_RATE_LIMIT_WAIT_MS = 60_000;\n\ntype Dict = Record<string, unknown>;\n\nfunction asDict(value: unknown): Dict | null {\n return typeof value === 'object' && value !== null ? (value as Dict) : null;\n}\n\n/** Error codes different layers use for the same 429 condition. */\nconst RATE_LIMIT_CODES = new Set([\n 'rate_limit_error',\n 'rate_limited',\n 'rate_limit_exceeded',\n 'too_many_requests',\n]);\n\n/**\n * Is this error a rate limit (429)?\n *\n * Detected STRUCTURALLY — by status/code/name — never with `instanceof`.\n * Consumers link this package rather than depending on a single installed copy,\n * so a `RateLimitError` thrown by their copy of the SDK is not `instanceof` our\n * copy's class. Identity checks silently return false across that boundary,\n * which is exactly how a 429 ends up looking like a transient blip.\n */\nexport function isRateLimited(error: unknown): boolean {\n if (typeof error === 'string') return /\\b429\\b/.test(error);\n\n const err = asDict(error);\n if (!err) return false;\n\n for (const key of ['status', 'statusCode', 'httpStatus', 'code']) {\n if (err[key] === 429 || err[key] === '429') return true;\n }\n\n const response = asDict(err.response);\n if (response && (response.status === 429 || response.statusCode === 429)) return true;\n\n if (typeof err.code === 'string' && RATE_LIMIT_CODES.has(err.code.toLowerCase())) return true;\n if (err.name === 'RateLimitError') return true;\n\n const message = typeof err.message === 'string' ? err.message : '';\n return /\\b429\\b/.test(message)\n || /rate[\\s_-]?limit/i.test(message)\n || /too many requests/i.test(message);\n}\n\n/**\n * Read a header off whatever shape carries it — a `Headers` instance, a plain\n * object, or a lower/mixed-case bag.\n */\nfunction readHeader(bag: unknown, name: string): string | null {\n if (bag === null || bag === undefined) return null;\n\n const getter = (bag as { get?: unknown }).get;\n if (typeof getter === 'function') {\n try {\n const value = (getter as (n: string) => unknown).call(bag, name);\n if (value !== null && value !== undefined) return String(value);\n } catch {\n // Not Headers-like after all — fall through to the plain-object scan.\n }\n }\n\n const dict = asDict(bag);\n if (!dict) return null;\n const wanted = name.toLowerCase();\n for (const [key, value] of Object.entries(dict)) {\n if (key.toLowerCase() === wanted && value !== null && value !== undefined) {\n return String(value);\n }\n }\n return null;\n}\n\n/**\n * Parse a `Retry-After`-style value into milliseconds.\n * Accepts a delta in seconds (number or numeric string) or an HTTP-date.\n */\nfunction parseRetryAfter(raw: unknown, now: number): number | null {\n if (raw === null || raw === undefined) return null;\n\n if (typeof raw === 'number') {\n return Number.isFinite(raw) && raw >= 0 ? raw * 1000 : null;\n }\n if (typeof raw !== 'string') return null;\n\n const trimmed = raw.trim();\n if (trimmed === '') return null;\n if (/^\\d+(\\.\\d+)?$/.test(trimmed)) return Number(trimmed) * 1000;\n\n const at = Date.parse(trimmed);\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n}\n\n/**\n * Parse an `X-RateLimit-Reset`-style value into milliseconds from now.\n * Accepts epoch seconds, epoch milliseconds, an ISO date, or a plain delta in\n * seconds — every one of which appears in the wild under this header name.\n */\nfunction parseResetAt(raw: unknown, now: number): number | null {\n if (raw === null || raw === undefined) return null;\n\n const numeric = typeof raw === 'number'\n ? raw\n : typeof raw === 'string' && /^\\d+(\\.\\d+)?$/.test(raw.trim())\n ? Number(raw.trim())\n : null;\n\n if (numeric !== null) {\n if (!Number.isFinite(numeric) || numeric < 0) return null;\n // Epoch milliseconds (~1.7e12) vs epoch seconds (~1.7e9) vs a small delta.\n if (numeric > 1e11) return Math.max(0, numeric - now);\n if (numeric > 1e9) return Math.max(0, numeric * 1000 - now);\n return numeric * 1000;\n }\n\n if (typeof raw !== 'string') return null;\n const at = Date.parse(raw.trim());\n return Number.isNaN(at) ? null : Math.max(0, at - now);\n}\n\n/**\n * How long the server asked us to wait, in milliseconds, or `null` if it said\n * nothing usable.\n *\n * Checked in order of authority: the SDK's own `RateLimitError.retryAfter`\n * (seconds) first, then the error envelope's details, then the raw\n * `Retry-After` / `X-RateLimit-Reset` headers the API actually sets.\n */\nexport function getRetryAfterMs(error: unknown, now: number = Date.now()): number | null {\n const err = asDict(error);\n if (!err) return null;\n\n const details = asDict(err.details);\n const response = asDict(err.response);\n const body = asDict(err.body) ?? asDict(response?.data);\n const bodyError = asDict(body?.error);\n const bodyDetails = asDict(bodyError?.details) ?? asDict(body?.details);\n\n // Already-in-milliseconds fields win outright — no unit guessing.\n for (const source of [err, details, bodyDetails]) {\n const ms = source?.retryAfterMs;\n if (typeof ms === 'number' && Number.isFinite(ms) && ms >= 0) return ms;\n }\n\n // `retryAfter` is seconds everywhere it appears in this stack.\n for (const source of [err, details, bodyDetails, bodyError]) {\n const parsed = parseRetryAfter(source?.retryAfter, now);\n if (parsed !== null) return parsed;\n }\n\n const headerBags = [err.headers, response?.headers, details?.headers, body?.headers];\n for (const bag of headerBags) {\n const parsed = parseRetryAfter(readHeader(bag, 'retry-after'), now);\n if (parsed !== null) return parsed;\n }\n\n for (const source of [details, bodyDetails, err]) {\n for (const key of ['resetAt', 'reset', 'rateLimitReset']) {\n const parsed = parseResetAt(source?.[key], now);\n if (parsed !== null) return parsed;\n }\n }\n\n for (const bag of headerBags) {\n for (const header of ['x-ratelimit-reset', 'ratelimit-reset']) {\n const parsed = parseResetAt(readHeader(bag, header), now);\n if (parsed !== null) return parsed;\n }\n }\n\n return null;\n}\n\n/**\n * The HTTP status carried by an error, however the thrower spelled it.\n */\nexport function getHttpStatus(error: unknown): number | null {\n const err = asDict(error);\n if (!err) return null;\n\n for (const key of ['status', 'statusCode', 'httpStatus']) {\n const value = err[key];\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n if (typeof value === 'string' && /^\\d{3}$/.test(value)) return Number(value);\n }\n\n const response = asDict(err.response);\n for (const key of ['status', 'statusCode']) {\n const value = response?.[key];\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n }\n\n return null;\n}\n\n/**\n * A 4xx that will not fix itself by asking again.\n *\n * Mirrors the SSE side's \"any 4xx is terminal\" rule, with two carve-outs:\n * 429 is backpressure (wait, don't quit) and 408 is a timeout (transient).\n * A 404 lands here — which is what a wrong path looks like, and previously it\n * was swallowed by a blanket catch and retried until the tab closed.\n */\nexport function isTerminalClientError(error: unknown): boolean {\n const status = getHttpStatus(error);\n if (status === null) return false;\n return status >= 400 && status < 500 && status !== 429 && status !== 408;\n}\n\n/** Growth applied to the delay after a failed poll. */\nexport const FAILURE_GROWTH_FACTOR = 2;\n\n/** Growth applied to the delay after a poll that learned nothing new. */\nexport const IDLE_GROWTH_FACTOR = 1.5;\n\n/**\n * Next delay after a poll that failed for a reason other than rate limiting.\n * Exponential, capped.\n */\nexport function nextFailureDelayMs(currentMs: number, maxMs: number): number {\n return Math.min(Math.max(currentMs, 1) * FAILURE_GROWTH_FACTOR, maxMs);\n}\n\n/**\n * Next delay after a successful poll that observed nothing new — no new logs\n * and no status change. This is the incident's exact shape: an execution that\n * finished long ago, polled at full rate for the lifetime of the tab. Decaying\n * toward the ceiling makes an idle tab cheap without making an active one slow.\n */\nexport function nextIdleDelayMs(currentMs: number, maxMs: number): number {\n return Math.min(Math.ceil(Math.max(currentMs, 1) * IDLE_GROWTH_FACTOR), maxMs);\n}\n\n/**\n * Add positive-only jitter so tabs that fell back together do not re-converge\n * into a synchronised wave. Positive-only matters: jitter must never shorten a\n * delay below what the server asked for.\n */\nexport function applyJitter(delayMs: number, ratio: number, random: () => number = Math.random): number {\n if (ratio <= 0) return delayMs;\n return Math.round(delayMs * (1 + random() * ratio));\n}\n","/**\n * Stream Controller\n *\n * Manages execution streaming with automatic reconnection and fallback to polling.\n * Implements the StreamController interface for type-safe event handling.\n */\n\nimport { SSEClient } from './sse-client.js';\nimport { extractImagesFromResult } from './extract-images.js';\nimport {\n isRateLimited,\n getRetryAfterMs,\n nextFailureDelayMs,\n nextIdleDelayMs,\n applyJitter,\n isTerminalClientError,\n getHttpStatus,\n UNNAMED_RATE_LIMIT_WAIT_MS,\n} from './poll-policy.js';\nimport { CadraError } from '../errors/index.js';\nimport type {\n StreamController,\n StreamEventMap,\n SSEEvent,\n StreamingStatus,\n StreamingConfig,\n CompleteEvent,\n ErrorEvent,\n} from '../types/streaming.js';\nimport type { AgentExecution, ExecutionLog, LogType } from '../types/agents.js';\n\n/**\n * Default streaming configuration\n *\n * `pollingIntervalMs` is deliberately 5000, not the 2000 it used to be. The\n * pressure is AGGREGATE — many concurrent executions in fallback, not one\n * runaway tab — so what matters is polls-per-execution across the fleet. On the\n * observed distribution (519 executions/24h in one org, mean 146s), a 2s cadence\n * costs ~73 requests per mean-length run; if those runs fall back, that alone\n * exceeds a 1000/hour key's entire daily budget. At 5s it is ~29, which fits\n * with headroom, while a median-length run still gets ~7 updates. Going slower\n * still (10s) would leave a median run with 3 updates and the user waiting up to\n * 10s past completion — a bad trade, because in fallback polling is the ONLY\n * channel the session has.\n *\n * 5s is a floor, not a period: the loop backs off from here toward\n * `pollingMaxIntervalMs` whenever it fails or learns nothing (see poll-policy),\n * so the cadence stays responsive exactly while there is something to report.\n */\nconst DEFAULT_STREAMING_CONFIG: StreamingConfig = {\n maxReconnectAttempts: 5,\n reconnectBaseDelayMs: 1000,\n reconnectMaxDelayMs: 10000,\n // NOTE (unchanged, deliberately): this watchdog force-disconnects a HEALTHY\n // SSE connection after 30s of silence and routes it through the same\n // handleConnectionError path as a real transport failure. Ordinary LLM\n // latency exceeds 30s routinely, so it fires against working streams — that\n // is what drives sessions into the polling fallback in the first place. The\n // fix is a server-side SSE heartbeat, not a bigger number here; raising this\n // is a guess against a moving target. Everything below only bounds what the\n // fallback costs once it has been entered.\n activityTimeoutMs: 30000,\n pollingIntervalMs: 5000,\n pollingMaxIntervalMs: 30000,\n pollingMaxConsecutiveFailures: 10,\n pollingMaxConsecutiveRateLimits: 3,\n pollingMaxConsecutiveClientErrors: 3,\n pollingMaxDurationMs: 1800000,\n pollingMaxRetryAfterMs: 300000,\n pollingJitterRatio: 0.1,\n sseRetryIntervalMs: 60000,\n};\n\n/**\n * Default polling enabled state — polling fallback activates automatically\n * when SSE reconnection attempts are exhausted.\n */\nconst DEFAULT_POLLING_ENABLED = true;\n\n/**\n * Stream controller creation options\n */\nexport interface ExecutionStreamControllerOptions {\n /** Execution ID to stream */\n executionId: string;\n /** Session ID for conversation continuity */\n sessionId?: string;\n /** Base URL for API */\n baseUrl: string;\n /** API key or token */\n apiKey?: string;\n /** Token provider callback for dynamic auth */\n tokenProvider?: () => Promise<string>;\n /** Organization ID */\n orgId: number;\n /** Function to get execution status (for polling fallback) */\n getExecution: (executionId: string) => Promise<AgentExecution>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n /** Streaming configuration */\n config?: Partial<StreamingConfig>;\n /** Whether polling fallback is enabled (default: true) */\n pollingEnabled?: boolean;\n}\n\n/**\n * Execution Stream Controller\n *\n * Manages the lifecycle of an execution stream, including:\n * - SSE connection management\n * - Automatic reconnection with exponential backoff\n * - Fallback to polling on connection failure\n * - Event deduplication\n */\nexport interface ExecutionStreamController extends StreamController {\n /** Connect to the stream */\n connect(): Promise<void>;\n /** Get the execution ID */\n readonly executionId: string;\n /** Get the session ID (if available) */\n readonly sessionId: string | undefined;\n}\n\n/**\n * Internal implementation of ExecutionStreamController\n */\nclass ExecutionStreamControllerImpl implements ExecutionStreamController {\n private options: ExecutionStreamControllerOptions;\n private config: StreamingConfig;\n private pollingEnabled: boolean;\n private sseClient: SSEClient | null = null;\n private status: StreamingStatus = 'connecting';\n private reconnectAttempts = 0;\n private seenEventIds = new Set<string>();\n private _lastEventId: string | null = null;\n private activityTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private finalExecution: AgentExecution | null = null;\n private finalError: ErrorEvent | null = null;\n\n // --- Fallback polling state ---\n // A self-rescheduling timeout, not setInterval: the delay has to change\n // between ticks (that is what backoff IS), and a timeout chain also cannot\n // stack overlapping requests the way a fixed interval does when the API is\n // slow to answer.\n private pollTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private pollDelayMs = 0;\n private pollConsecutiveFailures = 0;\n private pollConsecutiveRateLimits = 0;\n private pollConsecutiveClientErrors = 0;\n /** When the loop last observed anything new — the clock the give-up bound runs on. */\n private pollLastProgressAt = 0;\n private pollInFlight = false;\n private lastPolledStatus: string | null = null;\n private sseRetryTimeoutId: ReturnType<typeof setTimeout> | null = null;\n private sseRetryInFlight = false;\n\n // Event callbacks\n private listeners: {\n log: Array<(log: ExecutionLog) => void>;\n toolCall: Array<(data: StreamEventMap['toolCall']) => void>;\n toolResult: Array<(data: StreamEventMap['toolResult']) => void>;\n image: Array<(data: StreamEventMap['image']) => void>;\n plan: Array<(data: StreamEventMap['plan']) => void>;\n paused: Array<(data: StreamEventMap['paused']) => void>;\n started: Array<(data: StreamEventMap['started']) => void>;\n progress: Array<(data: StreamEventMap['progress']) => void>;\n taskListUpdate: Array<(data: StreamEventMap['taskListUpdate']) => void>;\n delegationStarted: Array<(data: StreamEventMap['delegationStarted']) => void>;\n delegationCompleted: Array<(data: StreamEventMap['delegationCompleted']) => void>;\n textDelta: Array<(data: StreamEventMap['textDelta']) => void>;\n narration: Array<(data: StreamEventMap['narration']) => void>;\n complete: Array<(data: CompleteEvent) => void>;\n error: Array<(error: ErrorEvent) => void>;\n connectionChange: Array<(data: StreamEventMap['connectionChange']) => void>;\n } = {\n log: [],\n toolCall: [],\n toolResult: [],\n image: [],\n plan: [],\n paused: [],\n started: [],\n progress: [],\n taskListUpdate: [],\n delegationStarted: [],\n delegationCompleted: [],\n textDelta: [],\n narration: [],\n complete: [],\n error: [],\n connectionChange: [],\n };\n\n // Promise for wait()\n private waitPromise: Promise<AgentExecution> | null = null;\n private waitResolve: ((execution: AgentExecution) => void) | null = null;\n private waitReject: ((error: Error) => void) | null = null;\n\n constructor(options: ExecutionStreamControllerOptions) {\n this.options = options;\n this.config = { ...DEFAULT_STREAMING_CONFIG, ...options.config };\n this.pollingEnabled = options.pollingEnabled ?? DEFAULT_POLLING_ENABLED;\n }\n\n // Resolved fallback-poll settings. Read through `??` rather than off the\n // spread config so an explicit `undefined` in a caller's partial config still\n // lands on the default instead of NaN-ing the arithmetic.\n private get pollBaseIntervalMs(): number {\n return this.config.pollingIntervalMs ?? DEFAULT_STREAMING_CONFIG.pollingIntervalMs;\n }\n private get pollMaxIntervalMs(): number {\n return Math.max(\n this.config.pollingMaxIntervalMs ?? DEFAULT_STREAMING_CONFIG.pollingMaxIntervalMs!,\n this.pollBaseIntervalMs\n );\n }\n private get pollMaxConsecutiveFailures(): number {\n return this.config.pollingMaxConsecutiveFailures ?? DEFAULT_STREAMING_CONFIG.pollingMaxConsecutiveFailures!;\n }\n private get pollMaxConsecutiveRateLimits(): number {\n return this.config.pollingMaxConsecutiveRateLimits ?? DEFAULT_STREAMING_CONFIG.pollingMaxConsecutiveRateLimits!;\n }\n private get pollMaxConsecutiveClientErrors(): number {\n return this.config.pollingMaxConsecutiveClientErrors ?? DEFAULT_STREAMING_CONFIG.pollingMaxConsecutiveClientErrors!;\n }\n private get pollMaxDurationMs(): number {\n return this.config.pollingMaxDurationMs ?? DEFAULT_STREAMING_CONFIG.pollingMaxDurationMs!;\n }\n private get pollMaxRetryAfterMs(): number {\n return this.config.pollingMaxRetryAfterMs ?? DEFAULT_STREAMING_CONFIG.pollingMaxRetryAfterMs!;\n }\n private get pollJitterRatio(): number {\n return this.config.pollingJitterRatio ?? DEFAULT_STREAMING_CONFIG.pollingJitterRatio!;\n }\n private get sseRetryIntervalMs(): number {\n return this.config.sseRetryIntervalMs ?? DEFAULT_STREAMING_CONFIG.sseRetryIntervalMs!;\n }\n\n /**\n * Get the last event ID (for resume support)\n */\n get lastEventId(): string | null {\n return this._lastEventId;\n }\n\n /**\n * Get the execution ID\n */\n get executionId(): string {\n return this.options.executionId;\n }\n\n /**\n * Get the session ID (if available)\n */\n get sessionId(): string | undefined {\n return this.options.sessionId;\n }\n\n /**\n * Connect to the execution stream\n */\n async connect(): Promise<void> {\n this.status = 'connecting';\n this.reconnectAttempts = 0;\n\n try {\n await this.connectSSE();\n } catch (error) {\n await this.handleConnectionError(error);\n }\n }\n\n /**\n * Register event listener\n */\n on<K extends keyof StreamEventMap>(\n event: K,\n callback: (data: StreamEventMap[K]) => void\n ): void {\n const listeners = this.listeners[event];\n if (listeners) {\n // Type assertion needed due to variance issues\n (listeners as Array<(data: StreamEventMap[K]) => void>).push(callback);\n }\n }\n\n /**\n * Cancel the stream\n */\n cancel(): void {\n this.status = 'closed';\n this.stopActivityTimeout();\n this.stopPolling();\n\n if (this.sseClient) {\n this.sseClient.disconnect();\n this.sseClient = null;\n }\n }\n\n /**\n * Wait for completion\n */\n wait(): Promise<AgentExecution> {\n // If already complete, return immediately\n if (this.finalExecution) {\n return Promise.resolve(this.finalExecution);\n }\n if (this.finalError) {\n return Promise.reject(new CadraError(\n this.finalError.error,\n this.finalError.errorCode ?? 'execution_error',\n 500\n ));\n }\n\n // Create promise if not exists\n if (!this.waitPromise) {\n this.waitPromise = new Promise((resolve, reject) => {\n this.waitResolve = resolve;\n this.waitReject = reject;\n });\n }\n\n return this.waitPromise;\n }\n\n // ===== Private methods =====\n\n /**\n * Connect to SSE endpoint\n */\n private async connectSSE(): Promise<void> {\n const base = this.options.baseUrl.replace(/\\/+$/, '');\n const url = `${base}/api/v1/agents/runs/${this.options.executionId}/stream`;\n\n // Resolve auth token: apiKey takes priority, then tokenProvider\n let authToken = this.options.apiKey;\n if (!authToken && this.options.tokenProvider) {\n authToken = await this.options.tokenProvider();\n }\n\n console.log('[SDK:StreamController] Connecting to SSE');\n console.log('[SDK:StreamController] URL:', url);\n console.log('[SDK:StreamController] baseUrl:', this.options.baseUrl);\n console.log('[SDK:StreamController] executionId:', this.options.executionId);\n console.log('[SDK:StreamController] orgId:', this.options.orgId);\n console.log('[SDK:StreamController] apiKey:', authToken ? `${authToken.substring(0, 20)}...` : 'MISSING');\n\n // Never leave a previous client subscribed. Reconnects and the fallback's\n // periodic SSE re-attempt both land here, and two live SSEClients on one\n // execution means every event arrives twice.\n if (this.sseClient) {\n this.sseClient.disconnect();\n this.sseClient = null;\n }\n\n // Callbacks are gated on `client` still being the current one. A replaced\n // client's teardown emits one last onConnectionChange(false) as its stream\n // unwinds; without this gate that stale report lands after the replacement\n // has already reported connected, and stale events would be injected too.\n const client: SSEClient = new SSEClient({\n url,\n authHeader: `Bearer ${authToken}`,\n orgId: this.options.orgId,\n fetch: this.options.fetch,\n // Resume from where this session left off. On a first connect this is\n // null and the header is omitted.\n lastEventId: this._lastEventId,\n onEvent: (event) => {\n if (this.sseClient !== client) return;\n this.handleEvent(event);\n },\n onError: (error) => {\n if (this.sseClient !== client) return;\n console.error('[SDK:StreamController] SSE error:', error);\n this.handleConnectionError(error);\n },\n onConnectionChange: (connected) => {\n if (this.sseClient !== client) return;\n console.log('[SDK:StreamController] SSE connection change:', connected);\n if (connected) {\n // The single place a live SSE stream is observed — so the single\n // place the fallback loop is retired. Whether this connection came\n // from connect(), the reconnect ladder, or the fallback's periodic\n // re-attempt, polling must not survive alongside a working stream.\n this.status = 'connected';\n this.reconnectAttempts = 0;\n this.stopPolling();\n this.resetActivityTimeout();\n }\n this.emit('connectionChange', {\n connected,\n usingFallback: this.status === 'fallback_polling',\n });\n },\n });\n\n this.sseClient = client;\n\n try {\n // Resolves when the stream ENDS, not when it opens — the open is reported\n // through onConnectionChange above.\n await client.connect();\n console.log('[SDK:StreamController] SSE connect() completed');\n } catch (error) {\n console.error('[SDK:StreamController] SSE connect() threw:', error);\n throw error;\n }\n }\n\n /**\n * Handle incoming SSE event\n */\n private handleEvent(event: SSEEvent): void {\n console.log('[SDK:StreamController] handleEvent called:', event.type, 'id:', event.id);\n\n // Reset activity timeout\n this.resetActivityTimeout();\n\n // Deduplicate by event ID\n if (event.id) {\n if (this.seenEventIds.has(event.id)) {\n console.log('[SDK:StreamController] Skipping duplicate event:', event.id);\n return;\n }\n this.seenEventIds.add(event.id);\n this._lastEventId = event.id;\n\n // Limit set size to prevent memory leaks\n if (this.seenEventIds.size > 1000) {\n const ids = Array.from(this.seenEventIds);\n this.seenEventIds = new Set(ids.slice(-500));\n }\n }\n\n // Map wire format (snake_case) to SDK format (camelCase)\n const data = event.data as Record<string, unknown>;\n console.log('[SDK:StreamController] Event data keys:', Object.keys(data));\n\n switch (event.type) {\n case 'log': {\n // Transform log-collector format to ExecutionLog format\n // Log-collector sends: { stepIndex, logType, message, metadata, timestamp, durationMs }\n // ExecutionLog expects: { uuid, type, title, content, metadata, timestamp, durationMs }\n const rawLog = data.log as Record<string, unknown> | undefined;\n if (!rawLog) {\n console.warn('[StreamController] Received log event without log data');\n break;\n }\n\n // Get the log type - log-collector uses 'logType', fallback to 'type'\n const logTypeValue = (rawLog.logType as string) || (rawLog.type as string) || 'info';\n\n const transformedLog: ExecutionLog = {\n uuid: (rawLog.uuid as string) || `log-${rawLog.stepIndex || Date.now()}`,\n type: logTypeValue as LogType,\n title: (rawLog.message as string) || (rawLog.title as string) || '',\n content: rawLog.content as string | undefined,\n metadata: {\n ...(rawLog.metadata as Record<string, unknown> || {}),\n // Include stepIndex in metadata for deduplication\n stepIndex: rawLog.stepIndex as number ?? 0,\n },\n timestamp: rawLog.timestamp as string || new Date().toISOString(),\n durationMs: rawLog.durationMs as number | undefined,\n // Pass through forwarded-from flag (set by cadra-api's\n // subscribeAndForwardEvents on sub-agent events). Wire field\n // is `_forwardedFrom` at the top of event.data.\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n };\n\n this.emit('log', transformedLog);\n break;\n }\n\n case 'tool_call':\n // Fix: Handle undefined toolName gracefully (defensive coding)\n this.emit('toolCall', {\n toolCallId: data.toolCallId as string || `tool-call-${Date.now()}`,\n toolName: (data.toolName as string) || 'Unknown Tool',\n inputs: (data.args as Record<string, unknown>) || {},\n stepIndex: data.stepIndex as number ?? 0,\n // Pass through forwarded-from flag (set by cadra-api's\n // subscribeAndForwardEvents on sub-agent events). Wire field\n // is `_forwardedFrom` per redis-manager.ts:232.\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n // CAD-87 S1-001 EventIdentity → (execId, seq) reducer dedup (S1-003).\n sourceExecutionId: (data.sourceExecutionId as string) ?? (data.executionId as string | undefined),\n seq: data.seq as number | undefined,\n });\n break;\n\n case 'tool_result': {\n // Fix: Handle undefined toolName gracefully (defensive coding)\n const toolCallId = (data.toolCallId as string) || `tool-result-${Date.now()}`;\n const toolName = (data.toolName as string) || 'Unknown Tool';\n this.emit('toolResult', {\n toolCallId,\n toolName,\n result: data.result,\n durationMs: data.durationMs as number ?? 0,\n // CAD-243: pass the producer's failure verdict through.\n ...(data.isError === true ? { isError: true } : {}),\n ...(typeof data.status === 'string' ? { status: data.status } : {}),\n ...(typeof data.error === 'string' ? { error: data.error } : {}),\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n // CAD-87 S1-001 EventIdentity → (execId, seq) reducer dedup (S1-003).\n sourceExecutionId: (data.sourceExecutionId as string) ?? (data.executionId as string | undefined),\n seq: data.seq as number | undefined,\n });\n\n // Derived event: emit one `image` per image found in the result.\n // Lets any consumer (chat UI, server worker) react to images progressively\n // without parsing tool results themselves.\n const images = extractImagesFromResult(data.result, {\n sourceToolCallId: toolCallId,\n executionId: this.options.executionId,\n });\n for (const img of images) {\n this.emit('image', {\n ...img,\n executionId: this.options.executionId,\n sourceToolCallId: toolCallId,\n toolName,\n });\n }\n break;\n }\n\n case 'execution_paused':\n // Handle ask_user paused event\n this.emit('paused', {\n question: data.question as string || data.output as string || '',\n options: data.options as string[] | undefined,\n reason: 'waiting_user_input',\n });\n break;\n\n case 'complete':\n this.handleComplete(data);\n break;\n\n case 'error':\n this.handleError({\n error: data.error as string,\n errorCode: data.errorCode as string | undefined,\n });\n break;\n case 'failed':\n // Some SSE endpoints emit \"failed\" instead of \"error\"\n this.handleError({\n error: (data.error as string) || (data.message as string) || 'Execution failed',\n errorCode: (data.errorCode as string | undefined) || 'execution_failed',\n });\n break;\n\n case 'timeout':\n if ((data as { retryable?: boolean }).retryable) {\n this.handleConnectionError(new Error('Stream timeout'));\n } else {\n this.handleError({\n error: data.error as string,\n errorCode: 'timeout',\n });\n }\n break;\n\n // Handle started event - immediate feedback that execution began\n case 'started':\n this.emit('started', {\n executionId: data.executionId as string,\n agentUuid: data.agentUuid as string,\n status: 'initializing',\n currentStep: data.currentStep as string | undefined,\n });\n break;\n\n // Handle progress event - status updates during execution\n case 'progress':\n this.emit('progress', {\n status: data.status as 'initializing' | 'thinking' | 'acting' | 'observing' | 'planning' | 'paused',\n iteration: data.iteration as number ?? 0,\n currentStep: data.currentStep as string | undefined,\n tokenUsage: data.tokenUsage as { prompt: number; completion: number; total: number } | undefined,\n cost: data.cost as number | undefined,\n toolCalls: data.toolCalls as number | undefined,\n // Forwarded specialist activity → rolling line attribution. Wire\n // fields `_forwardedFrom` / `_subagentName` sit at event.data top level.\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n subagentName: (event.data as Record<string, unknown>)._subagentName as string | undefined,\n });\n break;\n\n // Handle task list update event from TaskTracker\n case 'task_list_update':\n this.emit('taskListUpdate', {\n executionId: data.executionId as string,\n tasks: data.tasks as Array<{\n id: string;\n content: string;\n activeForm?: string | null;\n status: 'pending' | 'in_progress' | 'completed';\n }>,\n timestamp: data.timestamp as string,\n });\n break;\n\n // Handle delegation started event (handoff_to_agent initiated)\n case 'delegation_started':\n this.emit('delegationStarted', {\n type: 'delegation_started',\n handoffId: data.handoffId as string,\n targetAgentUuid: data.targetAgentUuid as string,\n targetAgentName: data.targetAgentName as string | undefined,\n taskPreview: data.taskPreview as string,\n timestamp: data.timestamp as string || new Date().toISOString(),\n });\n break;\n\n // Handle delegation completed event (handoff_to_agent finished)\n case 'delegation_completed':\n this.emit('delegationCompleted', {\n type: 'delegation_completed',\n handoffId: data.handoffId as string,\n status: data.status as 'completed' | 'failed',\n resultPreview: data.resultPreview as string | undefined,\n error: data.error as string | undefined,\n durationMs: data.durationMs as number,\n timestamp: data.timestamp as string || new Date().toISOString(),\n });\n break;\n\n // Handle status_update event - immediate feedback (e.g., \"thinking\")\n // Map to progress event for consistency\n case 'status_update':\n this.emit('progress', {\n status: (data.status as 'thinking' | 'initializing' | 'acting' | 'observing' | 'planning' | 'paused') || 'thinking',\n iteration: 0,\n currentStep: data.message as string | undefined,\n // Forwarded specialist status → rolling line attribution.\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n subagentName: (event.data as Record<string, unknown>)._subagentName as string | undefined,\n });\n break;\n\n // Handle text_delta event - token-by-token streaming\n case 'text_delta':\n this.emit('textDelta', {\n delta: data.delta as string,\n executionId: data.executionId as string,\n timestamp: data.timestamp as string || new Date().toISOString(),\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n // CAD-87 S1-001 EventIdentity → (execId, seq) reducer dedup (S1-003).\n sourceExecutionId: (data.sourceExecutionId as string) ?? (data.executionId as string | undefined),\n seq: data.seq as number | undefined,\n });\n break;\n\n // Handle narration event - clean per-step narration sentence (CAD\n // forwarded-narration). Native events (no forwardedFrom) mirror the\n // parent's own text_delta and are ignored by the chat hook; FORWARDED\n // events carry a specialist's narration during a handoff (its text_delta\n // is intentionally not forwarded) tagged `_subagentName`.\n case 'narration':\n this.emit('narration', {\n text: data.text as string,\n executionId: data.executionId as string | undefined,\n forwardedFrom: (event.data as Record<string, unknown>)._forwardedFrom as string | undefined,\n subagentName: (event.data as Record<string, unknown>)._subagentName as string | undefined,\n iteration: data.iteration as number | undefined,\n timestamp: (data.timestamp as string) || new Date().toISOString(),\n // CAD-87 S1-001 EventIdentity → (execId, seq) reducer dedup (S1-003).\n // The FORWARDED specialist narration keeps the CHILD's sourceExecutionId\n // + seq (preserved through the forward), so its resume replay dedups too.\n sourceExecutionId: (data.sourceExecutionId as string) ?? (data.executionId as string | undefined),\n seq: data.seq as number | undefined,\n // CAD-87 S1-002: the producer role — the reducer renders a native\n // `terminal_answer` as the answer (text), not a narration block.\n role: data.role as StreamEventMap['narration']['role'],\n });\n break;\n\n // Ignore connection-related and intermediate events\n case 'connected':\n case 'subscribed':\n case 'step':\n case 'step_complete':\n break;\n }\n }\n\n /**\n * Handle completion\n */\n private handleComplete(data: Record<string, unknown>): void {\n this.status = 'closed';\n this.stopActivityTimeout();\n // Any terminal observation retires the fallback loop, no matter which path\n // observed it (SSE, state recovery, or a poll tick).\n this.stopPolling();\n\n // sessionId can come from SSE event data or from the initial execute response\n const sessionId = (data.sessionId as string | undefined) ?? this.options.sessionId;\n\n const execution: AgentExecution = {\n uuid: this.options.executionId,\n agentUuid: '',\n sessionId,\n status: 'completed',\n input: { task: '' },\n output: data.output as string | undefined,\n logs: [],\n tokenUsage: data.tokenUsage as AgentExecution['tokenUsage'],\n cost: data.cost as number | undefined,\n queuedAt: '',\n ...data,\n };\n\n this.finalExecution = execution;\n this.emit('complete', { execution });\n\n if (this.waitResolve) {\n this.waitResolve(execution);\n }\n }\n\n /**\n * Handle error\n */\n private handleError(error: ErrorEvent): void {\n this.status = 'closed';\n this.stopActivityTimeout();\n this.stopPolling();\n\n this.finalError = error;\n this.emit('error', error);\n\n if (this.waitReject) {\n this.waitReject(new CadraError(\n error.error,\n error.errorCode ?? 'execution_error',\n 500\n ));\n }\n }\n\n /**\n * Handle connection error\n */\n private async handleConnectionError(error: unknown): Promise<void> {\n if (this.status === 'closed') {\n return;\n }\n\n // Permanent (4xx) failures won't fix themselves — auth rejected, bad/expired\n // run id, missing scope. Retrying floods the server and leaks connections\n // (each retry holds a privileged-DB connection on the stream route). Treat\n // any 4xx as terminal: stop, surface the error, and close.\n const msg = error instanceof Error ? error.message : String(error);\n if (/\\b4\\d\\d\\b/.test(msg) || /INVALID_API_KEY|INVALID_REQUEST/.test(msg)) {\n // Tear down the SSE then surface a terminal error (no reconnect).\n if (this.sseClient) {\n this.sseClient.disconnect();\n this.sseClient = null;\n }\n this.handleError({ error: msg, errorCode: 'stream_unrecoverable' });\n return;\n }\n\n // Already in fallback: the poll loop plus its periodic SSE re-attempt own\n // recovery from here. Re-entering the reconnect ladder would spawn a second\n // poll loop and a second connectionChange storm for every failed re-attempt.\n if (this.status === 'fallback_polling') {\n this.startPolling(); // no-op when the loop is already running\n return;\n }\n\n // Attempt reconnection\n if (this.reconnectAttempts < this.config.maxReconnectAttempts) {\n this.status = 'reconnecting';\n this.reconnectAttempts++;\n\n const delay = Math.min(\n this.config.reconnectBaseDelayMs * Math.pow(2, this.reconnectAttempts),\n this.config.reconnectMaxDelayMs\n );\n\n await new Promise(resolve => setTimeout(resolve, delay));\n\n // Check if cancelled during delay (cancel() sets status to 'closed')\n if (this.status === 'closed' as StreamingStatus) {\n return;\n }\n\n // Before reconnecting SSE, check execution status to recover missed state.\n // This prevents missed events during the reconnection gap.\n await this.recoverState();\n\n // If state recovery found the execution is already done, don't reconnect\n if (this.status === 'closed' as StreamingStatus) {\n return;\n }\n\n try {\n await this.connectSSE();\n } catch {\n await this.handleConnectionError(error);\n }\n } else {\n // Fall back to polling (if enabled)\n if (this.pollingEnabled) {\n this.status = 'fallback_polling';\n this.emit('connectionChange', { connected: false, usingFallback: true });\n this.startPolling();\n } else {\n // Polling disabled — emit error and close\n this.handleError({\n error: 'SSE connection failed and polling is disabled',\n errorCode: 'connection_failed',\n });\n }\n }\n }\n\n /**\n * Recover state by checking execution status.\n *\n * Called during reconnection to catch any events missed while SSE was down.\n * If the execution completed while disconnected, emits completion immediately.\n * Otherwise, emits any new logs that weren't seen via SSE.\n */\n private async recoverState(): Promise<void> {\n try {\n const execution = await this.options.getExecution(this.options.executionId);\n\n // Emit any logs we haven't seen yet\n if (execution.logs) {\n for (const log of execution.logs) {\n if (!this.seenEventIds.has(log.uuid)) {\n this.seenEventIds.add(log.uuid);\n this.emit('log', log);\n }\n }\n }\n\n // If execution completed while we were disconnected, handle it\n if (execution.status === 'completed') {\n this.stopPolling();\n this.handleComplete(execution as unknown as Record<string, unknown>);\n return;\n }\n\n if (execution.status === 'failed' || execution.status === 'cancelled') {\n this.stopPolling();\n this.handleError({\n error: execution.error ?? `Execution ${execution.status}`,\n errorCode: execution.status,\n });\n return;\n }\n\n } catch (err) {\n // State recovery is best-effort — continue with reconnection\n console.warn('[SDK:StreamController] State recovery failed (non-fatal):', err);\n }\n }\n\n /**\n * Start polling fallback.\n *\n * Idempotent — calling it while a loop is already running is a no-op, so no\n * path can end up with two loops racing the same execution.\n */\n private startPolling(): void {\n if (this.pollTimeoutId !== null || this.pollInFlight) {\n return;\n }\n\n this.pollLastProgressAt = Date.now();\n this.pollDelayMs = this.pollBaseIntervalMs;\n this.pollConsecutiveFailures = 0;\n this.pollConsecutiveRateLimits = 0;\n this.pollConsecutiveClientErrors = 0;\n this.lastPolledStatus = null;\n\n // SSE is down; the activity watchdog has nothing left to watch and would\n // only re-enter handleConnectionError on a timer.\n this.stopActivityTimeout();\n\n this.scheduleSSERetry();\n this.schedulePoll(this.pollDelayMs);\n }\n\n /**\n * Queue the next poll tick.\n */\n private schedulePoll(delayMs: number): void {\n if (this.status !== 'fallback_polling') {\n return;\n }\n this.pollTimeoutId = setTimeout(() => {\n this.pollTimeoutId = null;\n void this.runPoll();\n }, Math.max(0, Math.round(delayMs)));\n }\n\n /**\n * One poll tick: fetch state, emit what is new, then decide how long to wait\n * before the next one — or whether there should be a next one at all.\n */\n private async runPoll(): Promise<void> {\n if (this.status !== 'fallback_polling') {\n return;\n }\n\n // The give-up bound, measured from the last thing the loop LEARNED rather\n // than from when it started. A loop still delivering logs is doing its job\n // and gets to keep going; a loop re-reading the same unchanged state has\n // proven it will not learn anything, and surfacing an error beats outliving\n // the tab. (The incident's session last did anything at 11:05 and was still\n // polling at 11:20 — squarely this branch.)\n if (Date.now() - this.pollLastProgressAt >= this.pollMaxDurationMs) {\n this.failPolling(\n `Streaming fallback gave up: no execution progress for ${Math.round(this.pollMaxDurationMs / 1000)}s`,\n 'polling_timeout'\n );\n return;\n }\n\n this.pollInFlight = true;\n try {\n const execution = await this.options.getExecution(this.options.executionId);\n\n this.pollConsecutiveFailures = 0;\n this.pollConsecutiveRateLimits = 0;\n this.pollConsecutiveClientErrors = 0;\n\n // Emit new logs\n let sawNewInfo = false;\n for (const log of execution.logs ?? []) {\n if (!this.seenEventIds.has(log.uuid)) {\n this.seenEventIds.add(log.uuid);\n this.emit('log', log);\n sawNewInfo = true;\n }\n }\n if (execution.status !== this.lastPolledStatus) {\n this.lastPolledStatus = execution.status;\n sawNewInfo = true;\n }\n if (sawNewInfo) {\n this.pollLastProgressAt = Date.now();\n }\n\n // Check for completion\n if (execution.status === 'completed') {\n this.stopPolling();\n this.handleComplete(execution as unknown as Record<string, unknown>);\n return;\n }\n if (execution.status === 'failed' || execution.status === 'cancelled') {\n this.stopPolling();\n this.handleError({\n error: execution.error ?? `Execution ${execution.status}`,\n errorCode: execution.status,\n });\n return;\n }\n\n // Active execution keeps the fast cadence; an idle one decays toward the\n // ceiling so a forgotten tab costs a request every 30s, not every 2s.\n this.pollDelayMs = sawNewInfo\n ? this.pollBaseIntervalMs\n : nextIdleDelayMs(this.pollDelayMs, this.pollMaxIntervalMs);\n } catch (error) {\n if (!this.handlePollError(error)) {\n return; // handlePollError already terminated the loop\n }\n } finally {\n this.pollInFlight = false;\n }\n\n this.schedulePoll(applyJitter(this.pollDelayMs, this.pollJitterRatio));\n }\n\n /**\n * Apply backpressure for a failed poll.\n *\n * @returns `true` to keep polling (with `pollDelayMs` updated), `false` when\n * the loop has been terminated.\n */\n private handlePollError(error: unknown): boolean {\n const retryAfterMs = getRetryAfterMs(error);\n const rateLimited = isRateLimited(error) || retryAfterMs !== null;\n\n if (rateLimited) {\n this.pollConsecutiveRateLimits++;\n console.warn(\n '[SDK:StreamController] Poll rate-limited',\n retryAfterMs !== null ? `(server asked for ${Math.round(retryAfterMs / 1000)}s)` : '(no reset named)'\n );\n\n // A reset this far out is not something to sit on holding a stream open.\n if (retryAfterMs !== null && retryAfterMs > this.pollMaxRetryAfterMs) {\n this.failPolling(\n `Rate limited: the API asked for ${Math.round(retryAfterMs / 1000)}s, longer than this stream will wait`,\n 'rate_limited'\n );\n return false;\n }\n\n // 429 is not transient noise — it means the quota window is spent. Probing\n // it further starves every other feature sharing the key, which is the\n // collateral damage that made this worth fixing in the first place.\n if (this.pollConsecutiveRateLimits >= this.pollMaxConsecutiveRateLimits) {\n this.failPolling(\n 'Rate limited by the API; stopped the streaming fallback rather than keep spending the key quota',\n 'rate_limited'\n );\n return false;\n }\n\n // Never sooner than the server said. When it named nothing, assume a\n // window measured in minutes — retrying inside one is pure waste.\n // Deliberately NOT clamped by pollMaxIntervalMs: the server's number wins.\n this.pollDelayMs = Math.max(retryAfterMs ?? UNNAMED_RATE_LIMIT_WAIT_MS, this.pollDelayMs);\n return true;\n }\n\n // A 4xx will not fix itself by asking again — wrong path, dead run id,\n // rejected auth, missing scope. Mirrors the SSE side's terminal-4xx rule,\n // but with a small tolerance rather than instant death: a poll issued\n // immediately after dispatch can legitimately 404 before the execution row\n // is readable. Blanket catch-and-continue meant a permanently wrong URL\n // (which is what the bare `/executions/{id}` path was) looked exactly like\n // a transient blip, forever.\n if (isTerminalClientError(error)) {\n this.pollConsecutiveClientErrors++;\n const status = getHttpStatus(error);\n console.warn(\n `[SDK:StreamController] Poll got HTTP ${status} (${this.pollConsecutiveClientErrors}/${this.pollMaxConsecutiveClientErrors})`\n );\n if (this.pollConsecutiveClientErrors >= this.pollMaxConsecutiveClientErrors) {\n this.failPolling(\n `Execution status endpoint returned HTTP ${status} ${this.pollConsecutiveClientErrors} times — cannot track this run`,\n 'polling_unrecoverable'\n );\n return false;\n }\n this.pollDelayMs = nextFailureDelayMs(this.pollDelayMs, this.pollMaxIntervalMs);\n return true;\n }\n\n this.pollConsecutiveFailures++;\n console.warn(\n `[SDK:StreamController] Poll failed (${this.pollConsecutiveFailures}/${this.pollMaxConsecutiveFailures}):`,\n error\n );\n\n if (this.pollConsecutiveFailures >= this.pollMaxConsecutiveFailures) {\n this.failPolling(\n `Streaming fallback failed ${this.pollConsecutiveFailures} times in a row`,\n 'polling_failed'\n );\n return false;\n }\n\n this.pollDelayMs = nextFailureDelayMs(this.pollDelayMs, this.pollMaxIntervalMs);\n return true;\n }\n\n /**\n * Terminate the fallback loop and surface the reason.\n */\n private failPolling(error: string, errorCode: string): void {\n this.stopPolling();\n this.handleError({ error, errorCode });\n }\n\n /**\n * Stop polling, including the periodic SSE re-attempt that belongs to it.\n */\n private stopPolling(): void {\n if (this.pollTimeoutId !== null) {\n clearTimeout(this.pollTimeoutId);\n this.pollTimeoutId = null;\n }\n if (this.sseRetryTimeoutId !== null) {\n clearTimeout(this.sseRetryTimeoutId);\n this.sseRetryTimeoutId = null;\n }\n }\n\n /**\n * Queue the next attempt to get the real stream back.\n */\n private scheduleSSERetry(): void {\n if (this.sseRetryTimeoutId !== null || this.status !== 'fallback_polling') {\n return;\n }\n this.sseRetryTimeoutId = setTimeout(() => {\n this.sseRetryTimeoutId = null;\n this.attemptSSERecovery();\n }, this.sseRetryIntervalMs);\n }\n\n /**\n * Re-attempt SSE from inside the fallback, so a transient outage costs the\n * session a few polls rather than its stream for the lifetime of the tab.\n *\n * Success is NOT observed here: `SSEClient.connect()` resolves when the\n * stream ENDS, not when it opens. The open is observed by\n * `onConnectionChange(true)`, which flips status and stops this loop. The\n * promise below only tells us the attempt is over so the next one can be\n * queued.\n */\n private attemptSSERecovery(): void {\n if (this.status !== 'fallback_polling') {\n return;\n }\n if (this.sseRetryInFlight) {\n this.scheduleSSERetry();\n return;\n }\n\n this.sseRetryInFlight = true;\n void this.connectSSE()\n .catch(() => {\n // Still down — the poll loop keeps carrying the session.\n })\n .finally(() => {\n this.sseRetryInFlight = false;\n this.scheduleSSERetry();\n });\n }\n\n /**\n * Reset activity timeout\n */\n private resetActivityTimeout(): void {\n this.stopActivityTimeout();\n\n this.activityTimeoutId = setTimeout(() => {\n // Force reconnect on inactivity\n if (this.sseClient) {\n this.sseClient.disconnect();\n }\n this.handleConnectionError(new Error('Activity timeout'));\n }, this.config.activityTimeoutMs);\n }\n\n /**\n * Stop activity timeout\n */\n private stopActivityTimeout(): void {\n if (this.activityTimeoutId) {\n clearTimeout(this.activityTimeoutId);\n this.activityTimeoutId = null;\n }\n }\n\n /**\n * Emit event to listeners\n */\n private emit<K extends keyof StreamEventMap>(event: K, data: StreamEventMap[K]): void {\n const listeners = this.listeners[event];\n console.log(`[SDK:StreamController] Emitting '${event}' to ${listeners?.length || 0} listeners`);\n if (listeners) {\n for (const listener of listeners) {\n try {\n (listener as (data: StreamEventMap[K]) => void)(data);\n } catch (error) {\n console.error(`Error in ${event} listener:`, error);\n }\n }\n }\n }\n}\n\n/**\n * Create an execution stream controller\n */\nexport function createExecutionStreamController(\n options: ExecutionStreamControllerOptions\n): ExecutionStreamController {\n return new ExecutionStreamControllerImpl(options);\n}\n","/**\n * Collect images from an execution stream.\n *\n * Awaitable wrapper around ExecutionStreamController that:\n * - Subscribes to `image` events and accumulates them in arrival order.\n * - On `complete`, falls back to parsing `execution.output` for any images\n * that didn't arrive via streaming (older agents, missed events on reconnect).\n * - Returns a Promise<{ images, output, executionId }> that resolves on\n * `complete` or rejects on `error`.\n *\n * Optional callbacks let the caller react progressively as images arrive\n * (e.g. persist to a DB, push to React state, log to disk) without having\n * to wait for the final result.\n *\n * Works in Node and the browser — the controller is environment-agnostic.\n */\n\nimport type { ExecutionStreamController } from './stream-controller.js';\nimport { extractImagesFromExecutionOutput, type ImageData } from './extract-images.js';\nimport type { ImageEvent } from '../types/streaming.js';\n\n/**\n * Options for collectImagesFromStream / streamImages / streamImagesFromExecution.\n */\nexport interface CollectImagesOptions {\n /**\n * Callback fired once per image as it arrives. Receives the full ImageEvent\n * (including executionId, sourceToolCallId, toolName).\n *\n * Returning a Promise is allowed but not awaited — collection does not\n * block on the callback. If you need ordering guarantees (e.g. sequential\n * DB inserts), serialise inside the callback yourself.\n */\n onImage?: (image: ImageEvent) => void | Promise<void>;\n\n /**\n * Callback fired once when the execution completes. Receives the same\n * value the returned Promise resolves with.\n */\n onComplete?: (result: StreamImagesResult) => void;\n\n /**\n * Callback fired if the execution errors. The returned Promise also rejects.\n */\n onError?: (error: Error) => void;\n\n /**\n * AbortSignal. When aborted: cancels the stream and rejects the Promise.\n */\n signal?: AbortSignal;\n}\n\n/**\n * Result of a streamImages / collectImagesFromStream call.\n */\nexport interface StreamImagesResult {\n /** All images collected, in arrival order */\n images: ImageData[];\n /** The agent's final execution output (raw — may be a JSON string) */\n output: unknown;\n /** The execution UUID */\n executionId: string;\n}\n\n/**\n * Collect images from an already-created stream controller.\n *\n * The caller is responsible for calling `stream.connect()` — this helper\n * only attaches listeners and awaits completion.\n *\n * Most callers should use the higher-level `client.agents.streamImages()` or\n * `client.agents.streamImagesFromExecution()` instead, which handle the\n * connect step too.\n */\nexport async function collectImagesFromStream(\n stream: ExecutionStreamController,\n options: CollectImagesOptions = {}\n): Promise<StreamImagesResult> {\n const { onImage, onComplete, onError, signal } = options;\n\n const images: ImageData[] = [];\n const seenUrls = new Set<string>();\n\n if (signal?.aborted) {\n stream.cancel();\n throw new Error('Aborted');\n }\n\n return new Promise<StreamImagesResult>((resolve, reject) => {\n let settled = false;\n\n const settleResolve = (result: StreamImagesResult): void => {\n if (settled) return;\n settled = true;\n try {\n onComplete?.(result);\n } catch (err) {\n // Don't let consumer callbacks break the Promise contract.\n // Fire-and-forget — they can still see errors via onError.\n // eslint-disable-next-line no-console\n console.error('[SDK:collectImages] onComplete threw:', err);\n }\n resolve(result);\n };\n\n const settleReject = (err: Error): void => {\n if (settled) return;\n settled = true;\n try {\n onError?.(err);\n } catch (cbErr) {\n // eslint-disable-next-line no-console\n console.error('[SDK:collectImages] onError threw:', cbErr);\n }\n reject(err);\n };\n\n stream.on('image', (img) => {\n if (seenUrls.has(img.url)) return;\n seenUrls.add(img.url);\n images.push(img);\n try {\n const ret = onImage?.(img);\n if (ret && typeof (ret as Promise<void>).catch === 'function') {\n (ret as Promise<void>).catch((err) => {\n // eslint-disable-next-line no-console\n console.error('[SDK:collectImages] onImage rejected:', err);\n });\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('[SDK:collectImages] onImage threw:', err);\n }\n });\n\n stream.on('error', (err) => {\n settleReject(new Error(err.error || 'Stream error'));\n });\n\n stream.on('complete', ({ execution }) => {\n // Fallback: backfill from execution.output if streaming didn't surface\n // any images (older agents, non-streaming tool paths, missed events).\n if (images.length === 0 && execution.output) {\n const fromOutput = extractImagesFromExecutionOutput(execution.output, {\n executionId: stream.executionId,\n });\n for (const img of fromOutput) {\n if (seenUrls.has(img.url)) continue;\n seenUrls.add(img.url);\n images.push(img);\n // Also fire onImage so progressive consumers see fallback images.\n try {\n onImage?.({\n ...img,\n executionId: stream.executionId,\n sourceToolCallId: img.sourceToolCallId ?? '',\n toolName: '',\n });\n } catch {\n // ignore\n }\n }\n }\n\n settleResolve({\n images: [...images],\n output: execution.output,\n executionId: stream.executionId,\n });\n });\n\n if (signal) {\n signal.addEventListener(\n 'abort',\n () => {\n stream.cancel();\n settleReject(new Error('Aborted'));\n },\n { once: true }\n );\n }\n });\n}\n","/**\n * API paths for TOP-LEVEL resources\n *\n * `BaseResourceAPI.httpGet/httpPost/...` prefix a resource's own `basePath`\n * (e.g. `/api/v1/agents`), which is right for sub-resources but wrong for\n * resources that live at the root of the API. Those call `this.http.*`\n * directly — and every place that did so had dropped the `/api/v1` prefix\n * entirely, producing requests that resolve on NO host:\n *\n * - cadra-web (what every chat/copilot consumer passes as `baseUrl`) serves\n * `/api/v1/executions/{id}`. A bare `/executions/{id}` falls through to the\n * Next.js page router and returns 404 HTML — it never reaches `withApiAuth`,\n * so it is invisible to auth, quota and logging alike.\n * - cadra-api mounts the equivalent Fastify route under `/internal/v1`, behind\n * the web↔api internal key that SDK consumers do not hold. Its public\n * `/api/v1` surface carries only the session routes.\n *\n * Centralised here so the prefix is stated once instead of being re-typed (and\n * re-dropped) at each call site.\n */\n\n/** Root of the versioned public API. */\nexport const API_V1 = '/api/v1';\n\n/** Executions are a top-level resource, NOT a sub-resource of agents. */\nexport const EXECUTION_PATH = `${API_V1}/executions`;\n\n/** `GET /api/v1/executions/{id}` — execution status, output and logs. */\nexport function executionPath(executionId: string): string {\n return `${EXECUTION_PATH}/${executionId}`;\n}\n\n/** `POST /api/v1/executions/{id}/cancel` — request cancellation. */\nexport function executionCancelPath(executionId: string): string {\n return `${EXECUTION_PATH}/${executionId}/cancel`;\n}\n","/**\n * Agent message keys (p13) — lowercase dotted, e.g. `chat.welcome`.\n *\n * Same rule cadra-web enforces on `/api/v1/agents/:id/messages/render`, so an\n * invalid key fails client-side before a request is made. Kept free of any\n * client import so the chat entry can use it without pulling in the client.\n */\nexport const MESSAGE_KEY_PATTERN = /^[a-z][a-z0-9_]*(\\.[a-z0-9_]+)+$/;\n\n/** True when `key` is a valid lowercase dotted agent message key. */\nexport function isValidMessageKey(key: string): boolean {\n return MESSAGE_KEY_PATTERN.test(key);\n}\n","/**\n * Agent Messages Resource API (p13)\n *\n * Read-only access to an agent's saved messages (welcome, handoff, fallback\n * copy, ...). Reached as `client.agents.messages`.\n * - list(): the agent's saved messages, every known key, the agent's languages\n * - render(): one message filled with vars, in a language (server falls back:\n * exact, base, agent default, en, first non-empty; `lang` says which was used)\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { ValidationError } from '../errors/index.js';\nimport { isValidMessageKey } from '../utils/message-key.js';\nimport type {\n AgentMessageList,\n AgentMessageRenderOptions,\n AgentMessageRenderResult,\n} from '../types/index.js';\n\nexport class AgentMessagesAPI extends BaseResourceAPI {\n constructor(http: HttpClient) {\n super(http, '/api/v1/agents');\n }\n\n /**\n * List an agent's saved messages and the known keys\n *\n * @param agentUuid - Agent UUID (a team UUID resolves to its lead agent)\n *\n * @example\n * ```typescript\n * const { messages, knownKeys, languages, defaultLanguage } = await client.agents.messages.list('agent-uuid');\n * ```\n */\n async list(agentUuid: string): Promise<AgentMessageList> {\n return this.httpGet<AgentMessageList>(`/${agentUuid}/messages`);\n }\n\n /**\n * Render one message with placeholders filled\n *\n * Resolves with `text: null` when the agent has no message for the key.\n * Throws `ValidationError` before any request when the key is not a\n * lowercase dotted key (see `MESSAGE_KEY_PATTERN`).\n *\n * @example\n * ```typescript\n * const { text } = await client.agents.messages.render('agent-uuid', 'handoff.requested', {\n * lang: 'es',\n * vars: { agentName: 'Ana' },\n * });\n * ```\n */\n async render(\n agentUuid: string,\n key: string,\n options: AgentMessageRenderOptions = {}\n ): Promise<AgentMessageRenderResult> {\n if (!isValidMessageKey(key)) {\n throw new ValidationError(`Invalid message key \"${key}\"`, [\n { field: 'key', message: 'Must be a lowercase dotted key, e.g. chat.welcome' },\n ]);\n }\n return this.httpPost<AgentMessageRenderResult>(`/${agentUuid}/messages/render`, {\n key,\n ...(options.lang ? { lang: options.lang } : {}),\n ...(options.vars ? { vars: options.vars } : {}),\n });\n }\n}\n","/**\n * Agents Resource API\n *\n * Provides all agent-related operations:\n * - List: list(), get()\n * - Execute: execute(), executeSync(), stream()\n * - Receive: getExecution()\n * - Edit: update(), updateConfig(), cancelExecution()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type {\n Agent,\n AgentListOptions,\n AgentExecution,\n AgentUpdateInput,\n AgentConfigUpdateInput,\n ExecuteInput,\n ExecuteResponse,\n PaginatedResponse,\n} from '../types/index.js';\nimport type { ExecutionStreamController } from '../streaming/stream-controller.js';\nimport { createExecutionStreamController } from '../streaming/stream-controller.js';\nimport {\n collectImagesFromStream,\n type CollectImagesOptions,\n type StreamImagesResult,\n} from '../streaming/collect-images.js';\nimport { executionPath, executionCancelPath } from '../utils/api-paths.js';\nimport { AgentMessagesAPI } from './agent-messages.js';\n\n/**\n * Agents API class\n */\nexport class AgentsAPI extends BaseResourceAPI {\n /** Saved agent messages (p13): `list()` and `render()` */\n readonly messages: AgentMessagesAPI;\n\n constructor(http: HttpClient, private readonly getStreamConfig: () => StreamConfig) {\n super(http, '/api/v1/agents');\n this.messages = new AgentMessagesAPI(http);\n }\n\n // ===== LIST Operations =====\n\n /**\n * List all agents in the organization\n *\n * @param options - List options (pagination, filtering)\n * @returns Paginated list of agents\n *\n * @example\n * ```typescript\n * const { data: agents, pagination } = await client.agents.list({ limit: 10 });\n * ```\n */\n async list(options?: AgentListOptions): Promise<PaginatedResponse<Agent>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n status: options?.status,\n type: options?.type,\n };\n return this.httpGet<PaginatedResponse<Agent>>('', query);\n }\n\n /**\n * Get a single agent by UUID\n *\n * @param uuid - Agent UUID\n * @returns Agent with configuration\n *\n * @example\n * ```typescript\n * const agent = await client.agents.get('agent-uuid');\n * console.log(agent.config);\n * ```\n */\n async get(uuid: string): Promise<Agent> {\n return this.httpGet<Agent>(`/${uuid}`);\n }\n\n // ===== EXECUTE Operations =====\n\n /**\n * Start an agent execution (async)\n *\n * Returns immediately with execution ID. Use getExecution() to poll\n * for results, or use stream() for real-time updates.\n *\n * @param uuid - Agent UUID\n * @param input - Execution input (task, context, options)\n * @returns Execution ID and initial status\n *\n * @example\n * ```typescript\n * const { executionId, status } = await client.agents.execute('agent-uuid', {\n * task: 'Summarize the latest news about AI',\n * });\n * ```\n */\n async execute(uuid: string, input: ExecuteInput): Promise<ExecuteResponse> {\n const idempotencyKey = input.options?.idempotencyKey ?? generateIdempotencyKey();\n // Use SDK flat format: { task, context, attachmentIds, teamUuid, executionId, options }\n // This matches cadra-web's sdkFormatSchema which preserves teamUuid.\n //\n // `executionId`, when present, is a client-prepared UUID v4 (P25 — Action 5).\n // cadra-web's executions router accepts it (validated as UUID) and uses it\n // as the new execution row's UUID so the SDK can pre-open SSE.\n return this.httpPost<ExecuteResponse>(\n `/${uuid}/execute`,\n {\n task: input.task,\n context: input.context ?? {},\n attachmentIds: input.attachmentIds,\n options: input.options,\n ...(input.teamUuid ? { teamUuid: input.teamUuid } : {}),\n ...(input.executionId ? { executionId: input.executionId } : {}),\n },\n { idempotencyKey }\n );\n }\n\n /**\n * Execute an agent and wait for completion (sync)\n *\n * Polls the execution status until completion or failure.\n *\n * @param uuid - Agent UUID\n * @param input - Execution input\n * @param pollInterval - Polling interval in ms (default: 1000)\n * @returns Final execution result\n *\n * @example\n * ```typescript\n * const execution = await client.agents.executeSync('agent-uuid', {\n * task: 'Write a haiku about coding',\n * });\n * console.log(execution.output);\n * ```\n */\n async executeSync(\n uuid: string,\n input: ExecuteInput,\n pollInterval: number = 1000\n ): Promise<AgentExecution> {\n // Start the execution\n const { executionId } = await this.execute(uuid, input);\n\n // Poll until completion\n return this.pollExecution(executionId, pollInterval);\n }\n\n /**\n * Stream an agent execution\n *\n * Returns a StreamController for real-time event handling.\n *\n * @param uuid - Agent UUID\n * @param input - Execution input\n * @returns Stream controller for event handling\n *\n * @example\n * ```typescript\n * const stream = await client.agents.stream('agent-uuid', {\n * task: 'Research climate change',\n * });\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('toolCall', ({ toolName }) => console.log(`Calling ${toolName}`));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * const result = await stream.wait();\n * ```\n */\n async stream(uuid: string, input: ExecuteInput): Promise<ExecutionStreamController> {\n console.log('[SDK:Agents] stream() called for agent:', uuid);\n\n // Start the execution first\n const { executionId, sessionId } = await this.execute(uuid, input);\n console.log('[SDK:Agents] Execution started:', { executionId, sessionId });\n\n // Create and connect stream controller\n const config = this.getStreamConfig();\n console.log('[SDK:Agents] Stream config:', {\n baseUrl: config.baseUrl,\n apiKey: config.apiKey ? `${config.apiKey.substring(0, 20)}...` : 'MISSING',\n orgId: config.orgId,\n });\n\n const controller = createExecutionStreamController({\n executionId,\n sessionId,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n tokenProvider: config.tokenProvider,\n orgId: config.orgId,\n fetch: config.fetch,\n getExecution: (id) => this.getExecution(id),\n });\n\n // IMPORTANT: Do NOT call connect() here!\n // The caller must register event listeners with .on() FIRST, then call .connect()\n // Otherwise events will be emitted to 0 listeners (race condition)\n console.log('[SDK:Agents] Stream controller created - caller must call connect() after registering listeners');\n\n return controller;\n }\n\n /**\n * Connect to an existing execution's stream\n *\n * Use this when the execution was started externally (e.g., via tRPC for team executions)\n * and you need to connect to its SSE stream for real-time updates.\n *\n * @param executionId - Execution UUID (already running)\n * @param sessionId - Optional session ID for conversation continuity\n * @returns Stream controller for the execution\n *\n * @example\n * ```typescript\n * // Execution started via tRPC\n * const executionId = await trpc.executions.start.mutate({ teamUuid, task });\n *\n * // Connect to SSE stream for real-time updates\n * const stream = client.agents.streamExecution(executionId);\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('delegationStarted', (data) => console.log('Subagent:', data.targetAgentName));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * await stream.connect();\n * const result = await stream.wait();\n * ```\n */\n streamExecution(executionId: string, sessionId?: string): ExecutionStreamController {\n console.log('[SDK:Agents] streamExecution() called for execution:', executionId);\n\n // Create stream controller for existing execution\n const config = this.getStreamConfig();\n console.log('[SDK:Agents] Stream config:', {\n baseUrl: config.baseUrl,\n apiKey: config.apiKey ? `${config.apiKey.substring(0, 20)}...` : 'MISSING',\n orgId: config.orgId,\n });\n\n const controller = createExecutionStreamController({\n executionId,\n sessionId,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n tokenProvider: config.tokenProvider,\n orgId: config.orgId,\n fetch: config.fetch,\n getExecution: (id) => this.getExecution(id),\n });\n\n // IMPORTANT: Do NOT call connect() here!\n // The caller must register event listeners with .on() FIRST, then call .connect()\n console.log('[SDK:Agents] Stream controller created for existing execution - caller must call connect() after registering listeners');\n\n return controller;\n }\n\n /**\n * Stream image generation — kicks off an execution and resolves with all\n * images once the agent completes, while firing per-image callbacks as\n * each one arrives.\n *\n * Use this for one-shot image generation from agents whose primary output\n * is images (`create_ad_images`, `edit_image`, etc.). Works in Node and\n * the browser.\n *\n * @example\n * ```typescript\n * // Server-side: persist each image as it arrives, then return creative IDs\n * const { images, executionId } = await client.agents.streamImages(\n * batchAgentUuid,\n * { task: 'Generate 4 ads for new product launch', attachmentIds },\n * { onImage: async (img) => { await persist(img); } }\n * );\n * ```\n *\n * @example\n * ```typescript\n * // Browser-side: progressive UI without polling\n * const result = await client.agents.streamImages(uuid, input, {\n * onImage: (img) => setImages((prev) => [...prev, img]),\n * signal: abortController.signal,\n * });\n * ```\n */\n async streamImages(\n uuid: string,\n input: ExecuteInput,\n options?: CollectImagesOptions\n ): Promise<StreamImagesResult> {\n const stream = await this.stream(uuid, input);\n const collectionPromise = collectImagesFromStream(stream, options);\n // Connect AFTER collectImagesFromStream attaches listeners to avoid race.\n stream.connect().catch(() => {\n // connectionError surfaces via the stream's 'error' event; the\n // collection promise will reject through that path. Swallow here so\n // we don't trigger unhandled-rejection.\n });\n return collectionPromise;\n }\n\n /**\n * Connect to an already-started execution, stream image events, and\n * resolve with the collected images on completion.\n *\n * Useful when execution is started elsewhere (e.g. via tRPC mutation\n * that returns `executionId`) and the consumer wants to wait for images.\n *\n * @example\n * ```typescript\n * // After a tRPC mutation returns { executionId }\n * const { images } = await client.agents.streamImagesFromExecution(executionId, {\n * onImage: (img) => appendToUI(img),\n * });\n * ```\n */\n async streamImagesFromExecution(\n executionId: string,\n options?: CollectImagesOptions & { sessionId?: string }\n ): Promise<StreamImagesResult> {\n const { sessionId, ...collectOptions } = options ?? {};\n const stream = this.streamExecution(executionId, sessionId);\n const collectionPromise = collectImagesFromStream(stream, collectOptions);\n stream.connect().catch(() => {\n // see streamImages — error path reaches the promise via 'error' event\n });\n return collectionPromise;\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Get execution result by ID\n *\n * @param executionId - Execution UUID\n * @returns Execution details including status, output, logs\n *\n * @example\n * ```typescript\n * const execution = await client.agents.getExecution('exec-uuid');\n * if (execution.status === 'completed') {\n * console.log(execution.output);\n * }\n * ```\n */\n async getExecution(executionId: string): Promise<AgentExecution> {\n // Executions are a TOP-LEVEL resource (`/api/v1/executions/...`), not a\n // sub-resource of `/api/v1/agents`, so this cannot go through `httpGet`\n // (which would prefix this resource's basePath). It still needs the\n // `/api/v1` prefix: a bare `/executions/{id}` resolves on NO host — on\n // cadra-web it lands on the Next page router (404 HTML, never reaching\n // auth), and on cadra-api the equivalent route is mounted under\n // `/internal/v1` behind the internal key. See EXECUTION_PATH.\n return this.http.get<AgentExecution>(executionPath(executionId));\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Update agent details\n *\n * @param uuid - Agent UUID\n * @param data - Fields to update\n * @returns Updated agent\n *\n * @example\n * ```typescript\n * const agent = await client.agents.update('agent-uuid', {\n * name: 'My Updated Agent',\n * description: 'New description',\n * });\n * ```\n */\n async update(uuid: string, data: AgentUpdateInput): Promise<Agent> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Agent>(`/${uuid}`, data, { idempotencyKey });\n }\n\n /**\n * Update agent configuration\n *\n * @param uuid - Agent UUID\n * @param config - Configuration fields to update\n * @returns Updated agent\n *\n * @example\n * ```typescript\n * const agent = await client.agents.updateConfig('agent-uuid', {\n * temperature: 0.7,\n * maxIterations: 5,\n * });\n * ```\n */\n async updateConfig(uuid: string, config: AgentConfigUpdateInput): Promise<Agent> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Agent>(`/${uuid}/config`, config, { idempotencyKey });\n }\n\n /**\n * Cancel a running execution\n *\n * @param executionId - Execution UUID\n * @returns Updated execution with cancelled status\n *\n * @example\n * ```typescript\n * const execution = await client.agents.cancelExecution('exec-uuid');\n * console.log(execution.status); // 'cancelled'\n * ```\n */\n async cancelExecution(executionId: string): Promise<AgentExecution> {\n return this.http.post<AgentExecution>(\n executionCancelPath(executionId),\n undefined,\n { skipRetry: true }\n );\n }\n\n // ===== Private helpers =====\n\n /**\n * Poll execution until completion\n */\n private async pollExecution(\n executionId: string,\n pollInterval: number\n ): Promise<AgentExecution> {\n while (true) {\n const execution = await this.getExecution(executionId);\n\n if (\n execution.status === 'completed' ||\n execution.status === 'failed' ||\n execution.status === 'cancelled'\n ) {\n return execution;\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n}\n\n/**\n * Stream configuration passed from client\n */\nexport interface StreamConfig {\n baseUrl: string;\n apiKey?: string;\n token?: string;\n tokenProvider?: () => Promise<string>;\n orgId: number;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n","/**\n * Skills Resource API\n *\n * Provides all skill-related operations:\n * - List: list(), get(), getTools()\n * - Execute: execute()\n * - Receive: getExecution()\n * - Edit: update(), updatePrompt()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type {\n Skill,\n SkillDetails,\n SkillListOptions,\n SkillTool,\n SkillExecuteInput,\n SkillExecution,\n SkillUpdateInput,\n PaginatedResponse,\n} from '../types/index.js';\n\n/**\n * Skills API class\n */\nexport class SkillsAPI extends BaseResourceAPI {\n constructor(http: HttpClient) {\n super(http, '/api/v1/skills');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List all skills in the organization\n *\n * @param options - List options (pagination, filtering by category/tags)\n * @returns Paginated list of skills\n *\n * @example\n * ```typescript\n * const { data: skills } = await client.skills.list({\n * category: 'writing',\n * tags: ['seo', 'blog'],\n * });\n * ```\n */\n async list(options?: SkillListOptions): Promise<PaginatedResponse<Skill>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n category: options?.category,\n tags: options?.tags?.join(','),\n };\n return this.httpGet<PaginatedResponse<Skill>>('', query);\n }\n\n /**\n * Get a single skill by UUID with full details\n *\n * @param uuid - Skill UUID\n * @returns Skill with prompt template and tools\n *\n * @example\n * ```typescript\n * const skill = await client.skills.get('skill-uuid');\n * console.log(skill.promptTemplate);\n * ```\n */\n async get(uuid: string): Promise<SkillDetails> {\n return this.httpGet<SkillDetails>(`/${uuid}`);\n }\n\n /**\n * Get tools associated with a skill\n *\n * @param uuid - Skill UUID\n * @returns Array of tools used by the skill\n *\n * @example\n * ```typescript\n * const tools = await client.skills.getTools('skill-uuid');\n * tools.forEach(tool => console.log(tool.name));\n * ```\n */\n async getTools(uuid: string): Promise<SkillTool[]> {\n return this.httpGet<SkillTool[]>(`/${uuid}/tools`);\n }\n\n // ===== EXECUTE Operations =====\n\n /**\n * Execute a skill with variables\n *\n * @param uuid - Skill UUID\n * @param input - Variables and context for execution\n * @returns Skill execution result\n *\n * @example\n * ```typescript\n * const result = await client.skills.execute('skill-uuid', {\n * variables: {\n * topic: 'AI in healthcare',\n * tone: 'professional',\n * },\n * });\n * console.log(result.output);\n * ```\n */\n async execute(uuid: string, input: SkillExecuteInput): Promise<SkillExecution> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<SkillExecution>(\n `/${uuid}/execute`,\n {\n variables: input.variables,\n context: input.context,\n },\n { idempotencyKey }\n );\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Get skill execution result by ID\n *\n * @param executionId - Execution UUID\n * @returns Skill execution details\n *\n * @example\n * ```typescript\n * const execution = await client.skills.getExecution('exec-uuid');\n * ```\n */\n async getExecution(executionId: string): Promise<SkillExecution> {\n // KNOWN BROKEN (not fixed here — no verified target route): this bare\n // path drops the `/api/v1` prefix and resolves on no host. Unlike the\n // execution endpoints, cadra-web exposes no public skill-execution route to\n // point it at, so correcting it needs a server-side route first.\n // See utils/api-paths.ts.\n return this.http.get<SkillExecution>(`/executions/${executionId}`);\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Update skill details\n *\n * @param uuid - Skill UUID\n * @param data - Fields to update\n * @returns Updated skill\n *\n * @example\n * ```typescript\n * const skill = await client.skills.update('skill-uuid', {\n * name: 'Updated Skill Name',\n * tags: ['new-tag'],\n * });\n * ```\n */\n async update(uuid: string, data: SkillUpdateInput): Promise<Skill> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Skill>(`/${uuid}`, data, { idempotencyKey });\n }\n\n /**\n * Update skill prompt template\n *\n * @param uuid - Skill UUID\n * @param prompt - New prompt template\n * @returns Updated skill with new version\n *\n * @example\n * ```typescript\n * const skill = await client.skills.updatePrompt('skill-uuid',\n * 'Write a {{tone}} article about {{topic}}...'\n * );\n * console.log(skill.version); // Version incremented\n * ```\n */\n async updatePrompt(uuid: string, prompt: string): Promise<SkillDetails> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<SkillDetails>(`/${uuid}/prompt`, { promptTemplate: prompt }, { idempotencyKey });\n }\n}\n","/**\n * Tools Resource API\n *\n * Provides all tool-related operations:\n * - List: list(), get()\n * - Execute: execute(), validateInput()\n * - Receive: getExecution()\n * - Edit: update(), updateConfig()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type {\n Tool,\n ToolListOptions,\n ToolExecution,\n ToolValidationResult,\n ToolUpdateInput,\n ToolConfigUpdateInput,\n PaginatedResponse,\n ExecuteToolDirectRequest,\n ExecuteToolDirectResponse,\n} from '../types/index.js';\n\n/**\n * Tools API class\n */\nexport class ToolsAPI extends BaseResourceAPI {\n constructor(http: HttpClient) {\n super(http, '/api/v1/tools');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List all tools in the organization\n *\n * @param options - List options (pagination, filtering)\n * @returns Paginated list of tools\n *\n * @example\n * ```typescript\n * const { data: tools } = await client.tools.list({\n * category: 'data',\n * isEnabled: true,\n * });\n * ```\n */\n async list(options?: ToolListOptions): Promise<PaginatedResponse<Tool>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n category: options?.category,\n isEnabled: options?.isEnabled,\n };\n return this.httpGet<PaginatedResponse<Tool>>('', query);\n }\n\n /**\n * Get a single tool by UUID with schema\n *\n * @param uuid - Tool UUID\n * @returns Tool with input/output schemas\n *\n * @example\n * ```typescript\n * const tool = await client.tools.get('tool-uuid');\n * console.log(tool.inputSchema);\n * ```\n */\n async get(uuid: string): Promise<Tool> {\n return this.httpGet<Tool>(`/${uuid}`);\n }\n\n // ===== EXECUTE Operations =====\n\n /**\n * Execute a tool directly\n *\n * @param uuid - Tool UUID\n * @param input - Tool input (validated against inputSchema)\n * @returns Tool execution result\n *\n * @example\n * ```typescript\n * const result = await client.tools.execute('tool-uuid', {\n * query: 'weather in London',\n * limit: 5,\n * });\n * console.log(result.output);\n * ```\n */\n async execute(uuid: string, input: Record<string, unknown>): Promise<ToolExecution> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<ToolExecution>(`/${uuid}/execute`, { input }, { idempotencyKey });\n }\n\n /**\n * Execute a tool directly, bypassing the agent runtime.\n *\n * Enqueues the tool for async processing via BullMQ (no LLM, no ReAct loop).\n * Use SSE or polling with the returned executionId to get the result.\n *\n * @param request - Direct execution request\n * @returns Queued execution response with executionId for tracking\n *\n * @example\n * ```typescript\n * const result = await client.tools.executeDirect({\n * toolUuid: 'tool-uuid',\n * parameters: { prompt: 'Generate an image of a sunset' },\n * });\n * console.log(result.executionId); // Use for polling/SSE\n * console.log(result.status); // 'queued'\n * ```\n */\n async executeDirect(request: ExecuteToolDirectRequest): Promise<ExecuteToolDirectResponse> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<ExecuteToolDirectResponse>('/execute-direct', request, { idempotencyKey });\n }\n\n /**\n * Validate input against tool schema\n *\n * @param uuid - Tool UUID\n * @param input - Input to validate\n * @returns Validation result with errors if invalid\n *\n * @example\n * ```typescript\n * const validation = await client.tools.validateInput('tool-uuid', {\n * query: 'test',\n * });\n * if (!validation.valid) {\n * console.log(validation.errors);\n * }\n * ```\n */\n async validateInput(uuid: string, input: Record<string, unknown>): Promise<ToolValidationResult> {\n return this.httpPost<ToolValidationResult>(`/${uuid}/validate`, { input }, { skipRetry: false });\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Get tool execution result by ID\n *\n * @param executionId - Execution UUID\n * @returns Tool execution details\n *\n * @example\n * ```typescript\n * const execution = await client.tools.getExecution('exec-uuid');\n * ```\n */\n async getExecution(executionId: string): Promise<ToolExecution> {\n // KNOWN BROKEN (not fixed here — no verified target route): this bare\n // path drops the `/api/v1` prefix and resolves on no host. Unlike the\n // execution endpoints, cadra-web exposes no public tool-execution route to\n // point it at, so correcting it needs a server-side route first.\n // See utils/api-paths.ts.\n return this.http.get<ToolExecution>(`/executions/${executionId}`);\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Update tool details\n *\n * @param uuid - Tool UUID\n * @param data - Fields to update\n * @returns Updated tool\n *\n * @example\n * ```typescript\n * const tool = await client.tools.update('tool-uuid', {\n * name: 'Updated Tool Name',\n * description: 'New description',\n * });\n * ```\n */\n async update(uuid: string, data: ToolUpdateInput): Promise<Tool> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Tool>(`/${uuid}`, data, { idempotencyKey });\n }\n\n /**\n * Update tool configuration\n *\n * @param uuid - Tool UUID\n * @param config - Configuration to update\n * @returns Updated tool\n *\n * @example\n * ```typescript\n * const tool = await client.tools.updateConfig('tool-uuid', {\n * isEnabled: false,\n * config: { apiKey: 'new-key' },\n * });\n * ```\n */\n async updateConfig(uuid: string, config: ToolConfigUpdateInput): Promise<Tool> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPatch<Tool>(`/${uuid}/config`, config, { idempotencyKey });\n }\n}\n","/**\n * Artifacts Resource API\n *\n * Provides all artifact-related operations:\n * - List: list(), get()\n * - Receive: download(), downloadStream(), getSignedUrl()\n * - Edit: upload(), delete()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport type {\n Artifact,\n ArtifactListOptions,\n ArtifactDownloadOptions,\n SignedUrlResponse,\n ArtifactUploadInput,\n PaginatedResponse,\n} from '../types/index.js';\n\n/**\n * Artifacts API class\n */\nexport class ArtifactsAPI extends BaseResourceAPI {\n constructor(http: HttpClient) {\n super(http, '/api/v1/artifacts');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List artifacts for an execution\n *\n * @param executionId - Execution UUID\n * @param options - List options (pagination, filtering by type)\n * @returns Paginated list of artifacts\n *\n * @example\n * ```typescript\n * const { data: artifacts } = await client.artifacts.list('exec-uuid', {\n * type: 'file',\n * });\n * ```\n */\n async list(executionId: string, options?: ArtifactListOptions): Promise<PaginatedResponse<Artifact>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n type: options?.type,\n };\n // KNOWN BROKEN (not fixed here — no verified target route): this bare\n // path drops the `/api/v1` prefix and resolves on no host. Unlike the\n // execution endpoints, cadra-web exposes no public artifacts-by-execution route to\n // point it at, so correcting it needs a server-side route first.\n // See utils/api-paths.ts.\n return this.http.get<PaginatedResponse<Artifact>>(`/executions/${executionId}/artifacts`, query);\n }\n\n /**\n * Get artifact metadata by UUID\n *\n * @param uuid - Artifact UUID\n * @returns Artifact metadata\n *\n * @example\n * ```typescript\n * const artifact = await client.artifacts.get('artifact-uuid');\n * console.log(artifact.name, artifact.size);\n * ```\n */\n async get(uuid: string): Promise<Artifact> {\n return this.httpGet<Artifact>(`/${uuid}`);\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Download artifact content\n *\n * In Node.js returns Buffer, in browser returns Blob.\n *\n * @param uuid - Artifact UUID\n * @returns Artifact content as Buffer (Node.js) or Blob (browser)\n *\n * @example\n * ```typescript\n * const content = await client.artifacts.download('artifact-uuid');\n * // Node.js: Buffer\n * // Browser: Blob\n * ```\n */\n async download(uuid: string): Promise<Buffer | Blob> {\n // Make request expecting binary response\n const response = await this.http.request<Response>({\n method: 'GET',\n path: `${this.basePath}/${uuid}/download`,\n headers: {\n 'Accept': '*/*',\n },\n });\n\n // Handle response based on environment\n if (typeof window !== 'undefined') {\n // Browser environment - return Blob\n return response.blob();\n } else {\n // Node.js environment - return Buffer\n const arrayBuffer = await response.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n }\n\n /**\n * Download artifact as a stream\n *\n * In Node.js returns Readable stream, in browser returns ReadableStream.\n *\n * @param uuid - Artifact UUID\n * @returns Readable stream\n *\n * @example\n * ```typescript\n * const stream = await client.artifacts.downloadStream('artifact-uuid');\n * // Pipe to file or process incrementally\n * ```\n */\n async downloadStream(uuid: string): Promise<ReadableStream<Uint8Array>> {\n const response = await this.http.request<Response>({\n method: 'GET',\n path: `${this.basePath}/${uuid}/stream`,\n headers: {\n 'Accept': '*/*',\n },\n });\n\n if (!response.body) {\n throw new Error('Response body is not available');\n }\n\n return response.body;\n }\n\n /**\n * Get a signed URL for direct download\n *\n * @param uuid - Artifact UUID\n * @param options - Options including expiration time\n * @returns Signed URL and expiration time\n *\n * @example\n * ```typescript\n * const { url, expiresAt } = await client.artifacts.getSignedUrl('artifact-uuid', {\n * expiresIn: 3600, // 1 hour\n * });\n * // Use URL for direct download\n * ```\n */\n async getSignedUrl(uuid: string, options?: ArtifactDownloadOptions): Promise<SignedUrlResponse> {\n return this.httpPost<SignedUrlResponse>(`/${uuid}/signed-url`, {\n expiresIn: options?.expiresIn ?? 3600,\n });\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Upload a new artifact for an execution\n *\n * @param executionId - Execution UUID\n * @param input - Upload input (name, content, mime type)\n * @returns Created artifact metadata\n *\n * @example\n * ```typescript\n * const artifact = await client.artifacts.upload('exec-uuid', {\n * name: 'report.pdf',\n * content: fileBuffer,\n * mimeType: 'application/pdf',\n * });\n * ```\n */\n async upload(executionId: string, input: ArtifactUploadInput): Promise<Artifact> {\n // For multipart upload, we need to use FormData\n const formData = new FormData();\n\n // Handle different content types\n if (input.content instanceof Blob) {\n formData.append('file', input.content, input.name);\n } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(input.content)) {\n // Node.js Buffer - slice to create a new ArrayBuffer (ensures proper ArrayBuffer type for BlobPart)\n const arrayBuffer = input.content.buffer.slice(\n input.content.byteOffset,\n input.content.byteOffset + input.content.byteLength\n ) as ArrayBuffer;\n const blob = new Blob([arrayBuffer], { type: input.mimeType ?? 'application/octet-stream' });\n formData.append('file', blob, input.name);\n } else if (input.content instanceof ReadableStream) {\n // Stream - need to collect into buffer first, then concatenate for Blob compatibility\n const chunks: Uint8Array[] = [];\n const reader = input.content.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n chunks.push(new Uint8Array(value));\n }\n // Concatenate chunks into ArrayBuffer for proper BlobPart typing\n const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);\n const combined = new Uint8Array(totalLength);\n let offset = 0;\n for (const chunk of chunks) {\n combined.set(chunk, offset);\n offset += chunk.length;\n }\n // Use the underlying ArrayBuffer directly for Blob (proper ArrayBuffer type)\n const blob = new Blob([combined.buffer as ArrayBuffer], { type: input.mimeType ?? 'application/octet-stream' });\n formData.append('file', blob, input.name);\n }\n\n if (input.type) {\n formData.append('type', input.type);\n }\n if (input.metadata) {\n formData.append('metadata', JSON.stringify(input.metadata));\n }\n\n // Make request with FormData (no Content-Type header - fetch sets it automatically with boundary)\n return this.http.request<Artifact>({\n method: 'POST',\n // KNOWN BROKEN — same missing `/api/v1` prefix as listArtifacts above.\n path: `/executions/${executionId}/artifacts`,\n body: formData as unknown,\n headers: {\n // Remove Content-Type to let fetch set it with proper boundary\n },\n });\n }\n\n /**\n * Delete an artifact\n *\n * @param uuid - Artifact UUID\n *\n * @example\n * ```typescript\n * await client.artifacts.delete('artifact-uuid');\n * ```\n */\n async delete(uuid: string): Promise<void> {\n return this.httpDelete<void>(`/${uuid}`);\n }\n}\n","/**\n * Attachments Resource API\n *\n * Provides attachment operations for uploading files (images, documents)\n * that can be referenced in agent executions via attachmentIds.\n *\n * - Upload flow: getUploadUrl() → PUT to presigned URL → confirm()\n * - Download: getDownloadUrl()\n */\n\nimport { BaseResourceAPI } from './base.js';\n\n/**\n * Input for requesting a presigned upload URL\n */\nexport interface AttachmentUploadUrlInput {\n /** Original filename */\n filename: string;\n /** MIME type of the file */\n mimeType: string;\n /** File size in bytes */\n size: number;\n}\n\n/**\n * Response from requesting an upload URL\n */\nexport interface AttachmentUploadUrlResponse {\n /** UUID assigned to the attachment */\n attachmentUuid: string;\n /** Presigned S3 PUT URL for uploading the file */\n uploadUrl: string;\n /** ISO timestamp when the upload URL expires */\n expiresAt?: string;\n}\n\n/**\n * Attachments API class\n */\nexport class AttachmentsAPI extends BaseResourceAPI {\n constructor(http: import('../utils/http.js').HttpClient) {\n super(http, '/api/v1/attachments');\n }\n\n /**\n * Get a presigned URL for uploading a file\n *\n * After receiving the URL, upload the file directly to S3 using a PUT request,\n * then call confirm() to mark it as ready.\n *\n * @param input - File metadata (filename, mimeType, size)\n * @returns Presigned upload URL and attachment UUID\n *\n * @example\n * ```typescript\n * // 1. Get presigned URL\n * const { attachmentUuid, uploadUrl } = await client.attachments.getUploadUrl({\n * filename: 'photo.jpg',\n * mimeType: 'image/jpeg',\n * size: 102400,\n * });\n *\n * // 2. Upload file to S3\n * await fetch(uploadUrl, { method: 'PUT', body: fileBuffer });\n *\n * // 3. Confirm upload\n * await client.attachments.confirm(attachmentUuid);\n *\n * // 4. Use in execution\n * await client.agents.execute('agent-uuid', {\n * task: 'Describe this image',\n * attachmentIds: [attachmentUuid],\n * });\n * ```\n */\n async getUploadUrl(input: AttachmentUploadUrlInput): Promise<AttachmentUploadUrlResponse> {\n return this.httpPost<AttachmentUploadUrlResponse>('/upload-url', {\n filename: input.filename,\n mimeType: input.mimeType,\n size: input.size,\n });\n }\n\n /**\n * Confirm that a file upload has completed\n *\n * Must be called after successfully uploading the file to the presigned URL.\n *\n * @param uuid - Attachment UUID returned from getUploadUrl()\n */\n async confirm(uuid: string): Promise<void> {\n await this.httpPost<void>(`/${uuid}/confirm`);\n }\n\n /**\n * Get a download URL for an attachment\n *\n * @param uuid - Attachment UUID\n * @returns Presigned download URL\n */\n async getDownloadUrl(uuid: string): Promise<string> {\n const result = await this.httpGet<{ url: string }>(`/${uuid}/download-url`);\n return result.url;\n }\n}\n","/**\n * Sessions Resource API\n *\n * Provides all session-related operations:\n * - List: list(), get()\n * - Execute: sendMessage(), stream()\n * - Receive: getHistory(), listArtifacts()\n * - Edit: create(), delete()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type {\n Session,\n SessionListOptions,\n SessionHistory,\n SessionCreateInput,\n SendMessageInput,\n PaginatedResponse,\n SessionArtifact,\n SessionArtifactListOptions,\n} from '../types/index.js';\nimport type { AgentExecution, ExecuteResponse } from '../types/agents.js';\nimport type { ExecutionStreamController } from '../streaming/stream-controller.js';\nimport { createExecutionStreamController } from '../streaming/stream-controller.js';\nimport type { StreamConfig } from './agents.js';\nimport { executionPath } from '../utils/api-paths.js';\n\n/**\n * Sessions API class\n */\nexport class SessionsAPI extends BaseResourceAPI {\n constructor(http: HttpClient, private readonly getStreamConfig: () => StreamConfig) {\n super(http, '/api/v1/sessions');\n }\n\n // ===== LIST Operations =====\n\n /**\n * List all sessions in the organization\n *\n * @param options - List options (pagination, filtering by agent)\n * @returns Paginated list of sessions\n *\n * @example\n * ```typescript\n * const { data: sessions } = await client.sessions.list({\n * agentUuid: 'agent-uuid',\n * });\n * ```\n */\n async list(options?: SessionListOptions): Promise<PaginatedResponse<Session>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n agentUuid: options?.agentUuid,\n };\n return this.httpGet<PaginatedResponse<Session>>('', query);\n }\n\n /**\n * Get session details by ID\n *\n * @param sessionId - Session ID\n * @returns Session details\n *\n * @example\n * ```typescript\n * const session = await client.sessions.get('session-id');\n * console.log(session.messageCount);\n * ```\n */\n async get(sessionId: string): Promise<Session> {\n return this.httpGet<Session>(`/${sessionId}`);\n }\n\n // ===== EXECUTE Operations =====\n\n /**\n * Send a message to a session\n *\n * Triggers an agent execution in the context of the session.\n * Returns immediately with execution ID. Use getHistory() to get\n * the response, or use stream() for real-time updates.\n *\n * @param sessionId - Session ID\n * @param input - Message content and optional context\n * @returns Execution ID and status\n *\n * @example\n * ```typescript\n * const { executionId } = await client.sessions.sendMessage('session-id', {\n * message: 'What is the capital of France?',\n * });\n * ```\n */\n async sendMessage(sessionId: string, input: SendMessageInput): Promise<ExecuteResponse> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<ExecuteResponse>(\n `/${sessionId}/messages`,\n {\n message: input.message,\n context: input.context,\n // Pass attachment IDs for multi-modal messages (images, documents, etc.)\n attachmentIds: input.attachmentIds,\n // Optional client-prepared execution UUID v4 (P25 — Action 5).\n ...(input.executionId ? { executionId: input.executionId } : {}),\n },\n { idempotencyKey }\n );\n }\n\n /**\n * Send a message and wait for response (sync)\n *\n * @param sessionId - Session ID\n * @param input - Message content and optional context\n * @param pollInterval - Polling interval in ms (default: 1000)\n * @returns Final execution result\n *\n * @example\n * ```typescript\n * const execution = await client.sessions.sendMessageSync('session-id', {\n * message: 'What is the capital of France?',\n * });\n * console.log(execution.output);\n * ```\n */\n async sendMessageSync(\n sessionId: string,\n input: SendMessageInput,\n pollInterval: number = 1000\n ): Promise<AgentExecution> {\n const { executionId } = await this.sendMessage(sessionId, input);\n return this.pollExecution(executionId, pollInterval);\n }\n\n /**\n * Stream a message response\n *\n * Returns a StreamController for real-time event handling.\n *\n * @param sessionId - Session ID\n * @param input - Message content and optional context\n * @returns Stream controller\n *\n * @example\n * ```typescript\n * const stream = await client.sessions.stream('session-id', {\n * message: 'Tell me more about that',\n * });\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * const result = await stream.wait();\n * ```\n */\n async stream(sessionId: string, input: SendMessageInput): Promise<ExecutionStreamController> {\n const { executionId } = await this.sendMessage(sessionId, input);\n\n const config = this.getStreamConfig();\n const controller = createExecutionStreamController({\n executionId,\n sessionId,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n orgId: config.orgId,\n fetch: config.fetch,\n getExecution: (id) => this.getExecution(id),\n });\n\n await controller.connect();\n return controller;\n }\n\n // ===== RECEIVE Operations =====\n\n /**\n * Get session conversation history\n *\n * @param sessionId - Session ID\n * @returns Session with all messages\n *\n * @example\n * ```typescript\n * const history = await client.sessions.getHistory('session-id');\n * history.messages.forEach(msg => {\n * console.log(`${msg.role}: ${msg.content}`);\n * });\n * ```\n */\n async getHistory(sessionId: string): Promise<SessionHistory> {\n return this.httpGet<SessionHistory>(`/${sessionId}/history`);\n }\n\n /**\n * List artifacts for a session\n *\n * Returns all artifacts generated across all executions in the session.\n * Useful for retrieving images, files, and other outputs created during\n * agent interactions.\n *\n * @param sessionId - Session ID\n * @param options - List options (filtering by type, pagination)\n * @returns Paginated list of session artifacts\n *\n * @example\n * ```typescript\n * // Get all images from a session\n * const { data: artifacts } = await client.sessions.listArtifacts('session-id', {\n * type: 'image',\n * });\n *\n * artifacts.forEach(artifact => {\n * console.log(artifact.filename, artifact.url);\n * });\n * ```\n */\n async listArtifacts(\n sessionId: string,\n options?: SessionArtifactListOptions\n ): Promise<PaginatedResponse<SessionArtifact>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n type: options?.type,\n includeVariants: options?.includeVariants,\n };\n return this.httpGet<PaginatedResponse<SessionArtifact>>(`/${sessionId}/artifacts`, query);\n }\n\n /**\n * Get execution result\n */\n private async getExecution(executionId: string): Promise<AgentExecution> {\n return this.http.get<AgentExecution>(executionPath(executionId));\n }\n\n // ===== EDIT Operations =====\n\n /**\n * Create a new session for an agent\n *\n * @param agentUuid - Agent UUID to associate with session\n * @param options - Optional system message\n * @returns Created session\n *\n * @example\n * ```typescript\n * const session = await client.sessions.create({\n * agentUuid: 'agent-uuid',\n * systemMessage: 'You are a helpful assistant.',\n * });\n * console.log(session.id);\n * ```\n */\n async create(input: SessionCreateInput): Promise<Session> {\n const idempotencyKey = generateIdempotencyKey();\n return this.httpPost<Session>('', input, { idempotencyKey });\n }\n\n /**\n * Delete a session and all its messages\n *\n * @param sessionId - Session ID\n *\n * @example\n * ```typescript\n * await client.sessions.delete('session-id');\n * ```\n */\n async delete(sessionId: string): Promise<void> {\n return this.httpDelete<void>(`/${sessionId}`);\n }\n\n // ===== Private helpers =====\n\n /**\n * Poll execution until completion\n */\n private async pollExecution(\n executionId: string,\n pollInterval: number\n ): Promise<AgentExecution> {\n while (true) {\n const execution = await this.getExecution(executionId);\n\n if (\n execution.status === 'completed' ||\n execution.status === 'failed' ||\n execution.status === 'cancelled'\n ) {\n return execution;\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollInterval));\n }\n }\n}\n","/**\n * Kanban Resource API\n *\n * Provides the org-scoped board operations against `/api/v1/kanban/*`:\n * - Board: getBoard()\n * - Cards: listCards(), createCard(), getCard(), transitionCard()\n * - Run: streamCardRun() — reuses the EXISTING execution-stream controller\n * keyed on the card's executionId (no bespoke kanban stream).\n *\n * Mirrors `SessionsAPI` / `AgentsAPI` resource shape and is wired onto\n * `CadraClient` as `client.kanban`.\n *\n * @module @cadraos/sdk\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey } from '../utils/http.js';\nimport type { ExecutionStreamController } from '../streaming/stream-controller.js';\nimport { createExecutionStreamController } from '../streaming/stream-controller.js';\nimport type { StreamConfig } from './agents.js';\nimport type { AgentExecution } from '../types/agents.js';\nimport type {\n CardList,\n CreateCardInput,\n KanbanBoard,\n KanbanCard,\n KanbanHandlerType,\n KanbanLane,\n KanbanRunSummary,\n KanbanTransition,\n ListCardsInput,\n TransitionCardInput,\n} from '../kanban/types.js';\nimport { executionPath } from '../utils/api-paths.js';\n\n// ---------------------------------------------------------------------------\n// API → SDK mappers\n//\n// The `/api/v1/kanban/*` endpoints return a richer wire envelope than the flat\n// SDK types the hook/components consume: lanes are nested under `lifecycle`,\n// cards use `currentLane`/`uuid`, and lane fields are snake_cased. These\n// mappers adapt the wire shape to the public `KanbanBoard`/`KanbanCard`\n// contract. Without them the board renders \"No lanes configured\" (the raw\n// envelope has no top-level `.lanes`) and cards land in undefined lanes.\n// ---------------------------------------------------------------------------\n\ninterface RawLane {\n id?: string;\n key: string;\n name: string;\n handler?: { handler_type?: string; agent_ref?: string } | null;\n is_initial?: boolean;\n is_terminal?: boolean;\n}\n\ninterface RawTransition {\n id: string;\n from_lane_id: string;\n to_lane_id: string;\n manual_allowed?: boolean;\n}\n\ninterface RawBoardResponse {\n board: { id: number; uuid: string; orgId: number };\n lifecycle?: {\n id: number;\n uuid: string;\n slug: string;\n name: string;\n version: number;\n lanes?: RawLane[];\n transitions?: RawTransition[];\n };\n}\n\ninterface RawCard {\n id: number;\n uuid: string;\n currentLane: string;\n title: string;\n description?: string | null;\n type?: string | null;\n sharedContext?: Record<string, unknown> | null;\n executionId?: string | null;\n /** Run status of the linked execution (board listing) — drives card animation. */\n runStatus?: string | null;\n createdAt?: string | null;\n updatedAt?: string | null;\n}\n\nfunction mapLane(l: RawLane, index: number): KanbanLane {\n return {\n key: l.key,\n label: l.name,\n order: index,\n handler: l.handler\n ? {\n type: (l.handler.handler_type ?? 'cadra_agent') as KanbanHandlerType,\n agentRef: l.handler.agent_ref,\n }\n : undefined,\n terminal: l.is_terminal ?? false,\n initial: l.is_initial ?? false,\n };\n}\n\nfunction mapTransition(t: RawTransition): KanbanTransition {\n return {\n id: t.id,\n fromLane: t.from_lane_id,\n toLane: t.to_lane_id,\n manualAllowed: t.manual_allowed ?? false,\n };\n}\n\n/** Normalize a raw execution status string onto the board's KanbanRunStatus. */\nfunction mapExecStatus(s?: string | null): KanbanRunSummary['status'] {\n switch ((s ?? '').toLowerCase()) {\n case 'running':\n case 'in_progress':\n case 'processing':\n return 'running';\n case 'queued':\n case 'pending':\n case 'created':\n return 'pending';\n case 'completed':\n case 'success':\n case 'succeeded':\n return 'completed';\n case 'failed':\n case 'error':\n return 'failed';\n case 'cancelled':\n case 'canceled':\n return 'cancelled';\n default:\n return 'pending';\n }\n}\n\nfunction mapBoard(data: RawBoardResponse): KanbanBoard {\n return {\n id: data.board.uuid,\n orgId: data.board.orgId,\n lifecycleId: data.lifecycle?.uuid,\n lifecycleVersion: data.lifecycle?.version,\n name: data.lifecycle?.name,\n lanes: (data.lifecycle?.lanes ?? []).map(mapLane),\n transitions: (data.lifecycle?.transitions ?? []).map(mapTransition),\n };\n}\n\nfunction mapCard(c: RawCard, run?: KanbanRunSummary): KanbanCard {\n return {\n // The `/cards/:id` + `/cards/:id/transition` routes key on the integer PK\n // (`Number(id)`), so the card handle the board passes back MUST be that id,\n // not the uuid (a uuid → `Number(uuid)` = NaN → \"Invalid card id\").\n id: String(c.id),\n boardId: '',\n lane: c.currentLane,\n title: c.title,\n description: c.description ?? undefined,\n type: c.type ?? undefined,\n sharedContext: c.sharedContext ?? undefined,\n // Streaming key: the run-stream route (/api/v1/agents/runs/{id}/stream)\n // validates a UUID. Prefer the run summary's execution UUID; the raw card's\n // executionId is now the execution UUID too (board + card routes return it).\n executionId: run?.executionId ?? c.executionId ?? undefined,\n // Board-listing cards carry only `runStatus` (no full run summary). Synthesize\n // a minimal run so the card can render its \"agent working\" animation without\n // a detail fetch. getCard supplies the full `run` (takes precedence).\n run:\n run ??\n (c.runStatus\n ? {\n executionId: c.executionId ?? '',\n status: mapExecStatus(c.runStatus),\n }\n : undefined),\n createdAt: c.createdAt ?? undefined,\n updatedAt: c.updatedAt ?? undefined,\n };\n}\n\n/**\n * Kanban API class.\n */\nexport class KanbanAPI extends BaseResourceAPI {\n constructor(http: HttpClient, private readonly getStreamConfig: () => StreamConfig) {\n super(http, '/api/v1/kanban');\n }\n\n // ===== BOARD =====\n\n /**\n * Get the current org's board (lanes in declared order). Auto-provisions\n * the board server-side on first access.\n *\n * @returns The board with its lanes.\n *\n * @example\n * ```typescript\n * const board = await client.kanban.getBoard();\n * console.log(board.lanes.map((l) => l.label));\n * ```\n */\n async getBoard(): Promise<KanbanBoard> {\n const data = await this.httpGet<RawBoardResponse>('/boards/current');\n return mapBoard(data);\n }\n\n // ===== CARDS =====\n\n /**\n * List cards on the board (optionally filtered by lane/type).\n *\n * @param input - Optional list filters.\n * @returns The card list.\n */\n async listCards(input?: ListCardsInput): Promise<CardList> {\n const query: Record<string, string | number | boolean | undefined> = {\n lane: input?.lane,\n type: input?.type,\n limit: input?.limit,\n offset: input?.offset,\n };\n const data = await this.httpGet<{ cards: RawCard[]; total?: number }>(\n '/cards',\n query\n );\n return { cards: (data.cards ?? []).map((c) => mapCard(c)), total: data.total };\n }\n\n /**\n * Create a card. The server engine places it in the initial lane and fires\n * the lane's handler.\n *\n * @param input - Card creation input.\n * @returns The created card.\n */\n async createCard(input: CreateCardInput): Promise<KanbanCard> {\n const idempotencyKey = generateIdempotencyKey();\n const data = await this.httpPost<{ card: RawCard }>(\n '/cards',\n {\n title: input.title,\n type: input.type,\n description: input.description,\n sharedContext: input.sharedContext,\n lane: input.lane,\n },\n // Card creation is NON-idempotent and dispatches an agent run; a client\n // retry (e.g. on a slow create) would create a DUPLICATE card + a second\n // agent run (token waste). The server does not honor Idempotency-Key, so\n // never auto-retry this mutation.\n { idempotencyKey, skipRetry: true }\n );\n return mapCard(data.card);\n }\n\n /**\n * Get a single card by id, including its current run (`executionId` + run\n * summary) so the live run can be streamed.\n *\n * @param cardId - Card UUID.\n * @returns The card with its current/last run.\n */\n async getCard(cardId: string): Promise<KanbanCard> {\n // cadra-web returns the run as { executionId: <integer PK>, executionUuid,\n // status, error }. The SDK's KanbanRunSummary.executionId is the UUID that\n // drives the stream, so normalize executionUuid -> executionId here.\n const data = await this.httpGet<{\n card: RawCard;\n run?: {\n executionId?: number | string;\n executionUuid?: string;\n status?: KanbanRunSummary['status'];\n output?: string;\n error?: string | null;\n } | null;\n }>(`/cards/${cardId}`);\n const run: KanbanRunSummary | undefined = data.run\n ? {\n executionId:\n data.run.executionUuid ?? String(data.run.executionId ?? ''),\n status: data.run.status ?? 'pending',\n output: data.run.output,\n error: data.run.error ?? undefined,\n }\n : undefined;\n return mapCard(data.card, run);\n }\n\n /**\n * Patch a card's mutable fields (title/description/sharedContext). Maps the\n * `{ card: RawCard }` response back to a `KanbanCard`.\n *\n * @param cardId - Card id (the integer PK string the routes key on).\n * @param patch - The fields to update (all optional).\n * @returns The updated card.\n */\n async updateCard(\n cardId: string,\n patch: {\n title?: string;\n description?: string;\n sharedContext?: Record<string, unknown>;\n }\n ): Promise<KanbanCard> {\n // Non-idempotent-ish but safe; skipRetry to stay consistent with create.\n const data = await this.httpPatch<{ card: RawCard }>(\n `/cards/${cardId}`,\n patch,\n { skipRetry: true }\n );\n return mapCard(data.card);\n }\n\n /**\n * Manually transition a card to another lane (validated by the server\n * engine).\n *\n * @param input - Transition input.\n * @returns The updated card.\n */\n async transitionCard(input: TransitionCardInput): Promise<KanbanCard> {\n const idempotencyKey = generateIdempotencyKey();\n const data = await this.httpPost<{\n card: { uuid: string; currentLane: string; executionId?: string | null } | null;\n newLane?: string;\n }>(\n `/cards/${input.cardId}/transition`,\n {\n // The cadra-web route reads `toLane` (not `targetLane`). When omitted,\n // the engine auto-advances single-edge lanes.\n toLane: input.targetLane,\n contextPatch: input.contextPatch,\n },\n // Non-idempotent state change — don't auto-retry (a retry could\n // double-advance or re-fire a lane handler).\n { idempotencyKey, skipRetry: true }\n );\n // The transition endpoint returns a minimal card; surface the updated lane\n // (callers typically refetch the board/cards after a transition).\n return {\n id: data.card?.uuid ?? input.cardId,\n boardId: '',\n lane: data.card?.currentLane ?? data.newLane ?? input.targetLane ?? '',\n title: '',\n executionId: data.card?.executionId ?? undefined,\n };\n }\n\n // ===== RUN (reuses the existing execution-stream controller) =====\n\n /**\n * Get the card's current run as an execution. Thin convenience over the\n * existing agents/runs surface, used for polling fallback in the run view.\n *\n * @param executionId - The card's execution UUID.\n * @returns Execution details.\n */\n async getCardRun(executionId: string): Promise<AgentExecution> {\n return this.http.get<AgentExecution>(executionPath(executionId));\n }\n\n /**\n * Create a stream controller for a card's run, keyed on the card's\n * `executionId`.\n *\n * This reuses the SAME `ExecutionStreamController` the chat/agents modules\n * use against `GET /api/v1/agents/runs/{executionId}/stream` — automatic\n * reconnection, polling fallback, event dedup, and state recovery. There is\n * NO bespoke kanban stream (design.md §4.3).\n *\n * IMPORTANT: Do NOT call `.connect()` here — the caller must register\n * event listeners with `.on()` FIRST, then call `.connect()` (same contract\n * as `AgentsAPI.streamExecution`).\n *\n * @param executionId - The card's execution UUID.\n * @returns A stream controller.\n */\n streamCardRun(executionId: string): ExecutionStreamController {\n const config = this.getStreamConfig();\n return createExecutionStreamController({\n executionId,\n baseUrl: config.baseUrl,\n // The stream controller sends `Bearer <apiKey>`. Board consumers (yobo\n // copilot) construct the client with `token` (not `apiKey`), so fall back\n // to the token here — otherwise the SSE request sends `Bearer undefined`\n // and the stream route (withApiAuth) rejects it with INVALID_API_KEY.\n apiKey: config.apiKey ?? config.token,\n tokenProvider: config.tokenProvider,\n orgId: config.orgId,\n getExecution: (id) => this.getCardRun(id),\n });\n }\n}\n","/**\n * Teams Resource API\n *\n * Provides team-related operations:\n * - List: list(), get()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { ListOptions, PaginatedResponse } from '../types/index.js';\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\n/** Agent classification within a team */\nexport type TeamAgentType = 'ORCHESTRATOR' | 'SPECIALIST';\n\n/** Agent operational status */\nexport type TeamAgentStatus = 'ACTIVE' | 'IDLE' | 'BUSY' | 'OFFLINE' | 'DRAFT';\n\n/** Agent summary within a team member entry */\nexport interface TeamMemberAgent {\n uuid: string;\n name: string;\n agentType: TeamAgentType;\n roleTemplate: string | null;\n status: TeamAgentStatus;\n description?: string | null;\n}\n\n/**\n * STORY-014 (CAD-70): TeamMemberRef discriminated union.\n *\n * A team member reference is either:\n * - cadra_agent — a native Cadra agent (resolved by agentUuid)\n * - remote_agent — a remote external agent (resolved by remoteAgentUuid)\n *\n * The discriminator is `memberType` — IDENTICAL to TeamMemberData.memberType and\n * cadra-api's SpecialistAgentInfo.memberType / the cadra-web specialists route, so\n * this union narrows the same shape the runtime actually produces (not a separate\n * `type`-keyed config dialect).\n *\n * MVP: remote_agent is always a LEAF/specialist. The orchestrator/lead is always a\n * native cadra_agent (teams.leadAgentId); leaf-only is enforced structurally in\n * cadra-api (a remote dispatch only ever routes to RemoteExecutionBroker and never\n * constructs a native AgentRuntime), not by a runtime flag.\n */\nexport type TeamMemberRef =\n | { memberType: 'cadra_agent'; agentUuid: string }\n | { memberType: 'remote_agent'; remoteAgentUuid: string };\n\n/** A team member with their agent details */\nexport interface TeamMemberData {\n id: number | string;\n isLead: boolean;\n agent: TeamMemberAgent;\n /**\n * STORY-014: Member type discriminator.\n * - 'cadra_agent' — native Cadra agent (default, backward-compatible)\n * - 'remote_agent' — remote external agent; remoteAgentUuid identifies the record\n */\n memberType?: 'cadra_agent' | 'remote_agent';\n /**\n * STORY-014: UUID of the remote_agents record (cadra-web).\n * Set when memberType === 'remote_agent'.\n */\n remoteAgentUuid?: string;\n}\n\n/** Lead agent summary */\nexport interface TeamLeadAgentData {\n uuid: string;\n name: string;\n agentType: TeamAgentType;\n status: TeamAgentStatus;\n}\n\n/** Team detail returned by the API */\nexport interface Team {\n uuid: string;\n name: string;\n description?: string | null;\n isActive: boolean;\n leadAgent: TeamLeadAgentData | null;\n members: TeamMemberData[];\n}\n\n/** List options for teams */\nexport interface TeamListOptions extends ListOptions {\n /** Filter by active status */\n isActive?: boolean;\n}\n\n// =============================================================================\n// API CLASS\n// =============================================================================\n\n/**\n * Teams API class\n */\nexport class TeamsAPI extends BaseResourceAPI {\n constructor(http: import('../utils/http.js').HttpClient) {\n super(http, '/api/v1/teams');\n }\n\n /**\n * List all teams in the organization\n */\n async list(options?: TeamListOptions): Promise<PaginatedResponse<Team>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n isActive: options?.isActive,\n };\n return this.httpGet<PaginatedResponse<Team>>('', query);\n }\n\n /**\n * Get a single team by UUID\n *\n * @param uuid - Team UUID\n * @param includeMembers - Whether to include team members (default: true)\n */\n async get(uuid: string, includeMembers = true): Promise<Team> {\n return this.httpGet<Team>(`/${uuid}`, { includeMembers });\n }\n}\n","/**\n * Remote Agents Resource API\n *\n * Provides operations for remote agent management and execution:\n * - List: list(), get()\n * - Manage: create(), update(), delete(), deploy()\n * - Execute: execute(), stream()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type { HttpClient } from '../utils/http.js';\nimport { generateIdempotencyKey, generateExecutionId } from '../utils/http.js';\nimport type {\n RemoteAgent,\n RemoteAgentListOptions,\n RemoteAgentCreateInput,\n RemoteAgentUpdateInput,\n RemoteAgentExecuteResponse,\n} from '../types/remote-agents.js';\nimport type { PaginatedResponse, ExecuteInput } from '../types/index.js';\nimport type { ExecutionStreamController } from '../streaming/stream-controller.js';\nimport { createExecutionStreamController } from '../streaming/stream-controller.js';\nimport type { AgentExecution } from '../types/agents.js';\nimport type { StreamConfig } from './agents.js';\nimport { executionPath } from '../utils/api-paths.js';\n\n/**\n * Remote Agents API class\n */\nexport class RemoteAgentsAPI extends BaseResourceAPI {\n constructor(http: HttpClient, private readonly getStreamConfig: () => StreamConfig) {\n super(http, '/api/v1/remote-agents');\n }\n\n /**\n * List all remote agents in the organization\n *\n * @param options - List options (pagination, filtering)\n * @returns Paginated list of remote agents\n *\n * @example\n * ```typescript\n * const { data: agents, pagination } = await client.remoteAgents.list({ status: 'active' });\n * ```\n */\n async list(options?: RemoteAgentListOptions): Promise<PaginatedResponse<RemoteAgent>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n status: options?.status,\n adapterType: options?.adapterType,\n };\n return this.httpGet<PaginatedResponse<RemoteAgent>>('', query);\n }\n\n /**\n * Get a single remote agent by UUID\n *\n * @param uuid - Remote agent UUID\n * @returns Remote agent details\n */\n async get(uuid: string): Promise<RemoteAgent> {\n return this.httpGet<RemoteAgent>(`/${uuid}`);\n }\n\n /**\n * Create a new remote agent\n *\n * @param data - Remote agent creation input\n * @returns Created remote agent\n */\n async create(data: RemoteAgentCreateInput): Promise<RemoteAgent> {\n return this.httpPost<RemoteAgent>('', data);\n }\n\n /**\n * Update a remote agent\n *\n * @param uuid - Remote agent UUID\n * @param data - Fields to update\n * @returns Updated remote agent\n */\n async update(uuid: string, data: RemoteAgentUpdateInput): Promise<RemoteAgent> {\n return this.httpPatch<RemoteAgent>(`/${uuid}`, data);\n }\n\n /**\n * Delete a remote agent\n *\n * @param uuid - Remote agent UUID\n * @returns Success response\n */\n async delete(uuid: string): Promise<{ success: boolean }> {\n return this.httpDelete<{ success: boolean }>(`/${uuid}`);\n }\n\n /**\n * Deploy a remote agent (make it available for execution)\n *\n * @param uuid - Remote agent UUID\n * @returns Updated remote agent with deployed visibility\n */\n async deploy(uuid: string): Promise<RemoteAgent> {\n return this.httpPost<RemoteAgent>(`/${uuid}/deploy`);\n }\n\n /**\n * Start a remote agent execution (async)\n *\n * Returns immediately with executionId and streamUrl.\n * Use stream() for real-time updates.\n *\n * @param uuid - Remote agent UUID\n * @param input - Execution input (task, context, options)\n * @returns Execution ID and stream URL\n *\n * @example\n * ```typescript\n * const { executionId, streamUrl } = await client.remoteAgents.execute('agent-uuid', {\n * task: 'Process the uploaded dataset',\n * });\n * ```\n */\n async execute(uuid: string, input: ExecuteInput): Promise<RemoteAgentExecuteResponse> {\n // STORY-017: mirror AgentsAPI.execute — an idempotency key + a client-prepared\n // executionId make remote dispatch safe under HttpClient's automatic retries\n // (a timeout/5xx after the server already enqueued must not double-dispatch\n // remote runner work).\n const idempotencyKey = input.options?.idempotencyKey ?? generateIdempotencyKey();\n // STORY-017 (re-review): cadra-web dedupes a duplicate dispatch on the BODY\n // executionId, not the idempotency-key header. Default a stable client UUID so\n // the SDK's automatic retries hit the same row instead of double-dispatching.\n const executionId = input.executionId ?? generateExecutionId();\n return this.httpPost<RemoteAgentExecuteResponse>(\n `/${uuid}/execute`,\n {\n task: input.task,\n context: input.context ?? {},\n attachmentIds: input.attachmentIds,\n options: input.options,\n // Review #10: forward sessionId so multi-turn remote sessions are possible.\n // The cadra-web execute route's Zod schema already accepts sessionId.\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n executionId,\n },\n { idempotencyKey }\n );\n }\n\n /**\n * Stream a remote agent execution\n *\n * Returns a StreamController for real-time event handling.\n * IMPORTANT: Do NOT call connect() inside this method — caller must register\n * listeners first, THEN call connect().\n *\n * @param uuid - Remote agent UUID\n * @param input - Execution input\n * @returns Stream controller (caller must call connect() after registering listeners)\n *\n * @example\n * ```typescript\n * const stream = await client.remoteAgents.stream('agent-uuid', {\n * task: 'Process the dataset',\n * });\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * await stream.connect();\n * const result = await stream.wait();\n * ```\n */\n async stream(uuid: string, input: ExecuteInput): Promise<ExecutionStreamController> {\n const { executionId } = await this.execute(uuid, input);\n\n const config = this.getStreamConfig();\n const controller = createExecutionStreamController({\n executionId,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n tokenProvider: config.tokenProvider,\n orgId: config.orgId,\n getExecution: (id) => this.http.get<AgentExecution>(executionPath(id)),\n });\n\n // DO NOT call connect() here - caller registers listeners first, then connects\n return controller;\n }\n}\n","/**\n * Remote Runners Resource API\n *\n * Provides operations for remote runner management:\n * - List: list()\n */\n\nimport { BaseResourceAPI } from './base.js';\nimport type {\n RemoteRunner,\n RemoteRunnerListOptions,\n} from '../types/remote-agents.js';\nimport type { PaginatedResponse } from '../types/index.js';\n\n/**\n * Remote Runners API class\n */\nexport class RemoteRunnersAPI extends BaseResourceAPI {\n constructor(http: import('../utils/http.js').HttpClient) {\n super(http, '/api/v1/remote-runners');\n }\n\n /**\n * List all remote runners in the organization\n *\n * @param options - List options (pagination, filtering)\n * @returns Paginated list of remote runners\n *\n * @example\n * ```typescript\n * const { data: runners, pagination } = await client.remoteRunners.list({ status: 'connected' });\n * ```\n */\n async list(options?: RemoteRunnerListOptions): Promise<PaginatedResponse<RemoteRunner>> {\n const query: Record<string, string | number | boolean | undefined> = {\n ...this.buildListQuery(options),\n status: options?.status,\n };\n return this.httpGet<PaginatedResponse<RemoteRunner>>('', query);\n }\n}\n","/**\n * AI Functions API (p93 AIF-010 — specs §9, D27).\n *\n * @example\n * ```typescript\n * // Discover what the org can call, and with which parameters\n * const functions = await client.aiFunctions.list();\n * const fn = await client.aiFunctions.get('summarise_ticket');\n *\n * // Call it — parameters are checked against the live version before sending\n * const result = await client.aiFunctions.run('summarise_ticket', { ticket_text: '…' });\n * if (result.output.type === 'text') console.log(result.output.text);\n * ```\n */\n\nimport {\n AiFunctionChargedError,\n AiFunctionDuplicateError,\n AiFunctionParameterError,\n CadraError,\n} from '../errors/index.js';\nimport type {\n AiFunctionDescriptor,\n AiFunctionParameter,\n AiFunctionParameterIssue,\n AiFunctionRef,\n AiFunctionRun,\n AiFunctionRunOptions,\n AiFunctionRunResult,\n AiFunctionRunShorthandOptions,\n AiFunctionVariables,\n} from '../types/ai-functions.js';\nimport { generateExecutionId, type HttpClient } from '../utils/http.js';\nimport { BaseResourceAPI } from './base.js';\n\n/**\n * How long the client waits for a paid run. It tracks cadra-web\n * `AI_FUNCTION_ROUTE_MAX_MS` (300 s, the Vercel `maxDuration` of the run\n * routes) plus 10 s, so the server always answers first — with the result or\n * with its own `failed_timeout` — and the client never abandons a run the\n * server is still finishing. A larger client-wide `timeout` wins.\n * (Was 60 s, from the old p93 D6 route budget.)\n */\nexport const AI_FUNCTION_RUN_TIMEOUT_MS = 310_000;\n\n/** Descriptors used by the client-side check are cached per client for 60 s (D27c). */\nexport const AI_FUNCTION_DESCRIPTOR_TTL_MS = 60_000;\n\ninterface DescriptorCacheEntry {\n descriptor: AiFunctionDescriptor;\n expiresAt: number;\n}\n\n/**\n * Check `variables` against a descriptor's parameters (D27c). Returns the issues,\n * in parameter order, then unknown names. Empty array = OK.\n */\nexport function checkAiFunctionParameters(\n parameters: AiFunctionParameter[],\n variables: AiFunctionVariables\n): AiFunctionParameterIssue[] {\n const issues: AiFunctionParameterIssue[] = [];\n const declared = new Set<string>();\n\n for (const p of parameters) {\n declared.add(p.name);\n const has = Object.prototype.hasOwnProperty.call(variables, p.name);\n const value = has ? variables[p.name] : undefined;\n\n if (value === undefined || value === null) {\n if (p.required) issues.push({ name: p.name, code: 'missing' });\n continue;\n }\n\n switch (p.type) {\n case 'number':\n if (typeof value !== 'number' || !Number.isFinite(value)) {\n issues.push({ name: p.name, code: 'type' });\n }\n break;\n case 'boolean':\n if (typeof value !== 'boolean') issues.push({ name: p.name, code: 'type' });\n break;\n case 'enum':\n if (typeof value !== 'string') issues.push({ name: p.name, code: 'type' });\n else if (p.options && !p.options.includes(value)) {\n issues.push({ name: p.name, code: 'option' });\n }\n break;\n case 'string':\n case 'text':\n if (typeof value !== 'string') issues.push({ name: p.name, code: 'type' });\n else if (typeof p.maxLength === 'number' && value.length > p.maxLength) {\n issues.push({ name: p.name, code: 'too_long' });\n }\n break;\n case 'image':\n if (typeof value !== 'string') issues.push({ name: p.name, code: 'type' });\n break;\n default:\n // Unknown future type — leave it to the server (the authority).\n break;\n }\n }\n\n for (const name of Object.keys(variables)) {\n if (!declared.has(name)) issues.push({ name, code: 'unknown' });\n }\n\n return issues;\n}\n\n/**\n * AI Functions API\n */\nexport class AiFunctionsAPI extends BaseResourceAPI {\n private readonly descriptorCache = new Map<string, DescriptorCacheEntry>();\n\n constructor(http: HttpClient) {\n super(http, '/api/v1/ai-functions');\n }\n\n /**\n * List the functions this org can call — the index (D27a). Each entry carries\n * the live version's typed parameters; never prompt text.\n */\n async list(): Promise<AiFunctionDescriptor[]> {\n const data = await this.httpGet<{ functions?: AiFunctionDescriptor[] } | AiFunctionDescriptor[]>('');\n const functions = Array.isArray(data) ? data : (data?.functions ?? []);\n for (const d of functions) this.cacheDescriptor(d);\n return functions;\n }\n\n /**\n * Get one function's descriptor by key (D27a).\n * `NotFoundError` (`FUNCTION_NOT_FOUND`) / `ConflictError` (`FUNCTION_NOT_PUBLISHED`).\n */\n async get(functionKey: string): Promise<AiFunctionDescriptor> {\n const data = await this.httpGet<AiFunctionDescriptor | { function: AiFunctionDescriptor }>(\n `/${encodeURIComponent(functionKey)}`\n );\n const descriptor =\n data && typeof data === 'object' && 'function' in data && !('functionKey' in data)\n ? data.function\n : (data as AiFunctionDescriptor);\n this.cacheDescriptor(descriptor, functionKey);\n return descriptor;\n }\n\n /**\n * Read one of this org's own runs (safe projection, §6.5).\n */\n async getRun(executionId: string): Promise<AiFunctionRun> {\n return this.httpGet<AiFunctionRun>(`/runs/${encodeURIComponent(executionId)}`);\n }\n\n /** Forget cached descriptors (one key, or all). */\n clearDescriptorCache(functionKey?: string): void {\n if (functionKey) this.descriptorCache.delete(functionKey);\n else this.descriptorCache.clear();\n }\n\n /**\n * Run an AI function — one paid provider call.\n *\n * - `run('function_key', parameters, opts?)` — shorthand for `{ functionKey }`.\n * - `run({ functionKey | promptUuid | slot }, { variables, version?, idempotencyKey?, params?, validate? })`.\n *\n * For a `functionKey` ref without a pinned `version`, parameters are checked\n * against the live version first (D27c); a problem throws\n * `AiFunctionParameterError` and NO run request is sent. Paid runs are never\n * auto-retried; an idempotency key is generated when omitted.\n *\n * @throws AiFunctionParameterError — client-side check failed (nothing sent)\n * @throws AiFunctionDuplicateError — 409 `DUPLICATE_REQUEST`\n * @throws AiFunctionChargedError — the run was metered but its output failed (`details.charged`)\n */\n async run<TOutput = unknown>(\n functionKey: string,\n parameters: AiFunctionVariables,\n opts?: AiFunctionRunShorthandOptions\n ): Promise<AiFunctionRunResult<TOutput>>;\n async run<TOutput = unknown>(\n ref: AiFunctionRef,\n options: AiFunctionRunOptions\n ): Promise<AiFunctionRunResult<TOutput>>;\n async run<TOutput = unknown>(\n refOrKey: AiFunctionRef | string,\n parametersOrOptions: AiFunctionVariables | AiFunctionRunOptions,\n shorthandOpts?: AiFunctionRunShorthandOptions\n ): Promise<AiFunctionRunResult<TOutput>> {\n let ref: AiFunctionRef;\n let options: AiFunctionRunOptions;\n if (typeof refOrKey === 'string') {\n ref = { functionKey: refOrKey };\n options = { ...(shorthandOpts ?? {}), variables: parametersOrOptions as AiFunctionVariables };\n } else {\n ref = refOrKey;\n options = parametersOrOptions as AiFunctionRunOptions;\n }\n const variables = options.variables ?? {};\n\n const functionKey = 'functionKey' in ref ? ref.functionKey : undefined;\n const shouldCheck =\n functionKey !== undefined && options.version === undefined && options.validate !== false;\n\n if (shouldCheck) {\n const descriptor = await this.getCachedDescriptor(functionKey);\n const issues = checkAiFunctionParameters(descriptor.parameters, variables);\n if (issues.length > 0) {\n throw new AiFunctionParameterError(functionKey, issues);\n }\n }\n\n const body = {\n ref,\n variables,\n version: options.version,\n idempotencyKey: options.idempotencyKey ?? generateExecutionId(),\n params: options.params,\n };\n\n try {\n return await this.httpPost<AiFunctionRunResult<TOutput>>('/run', body, {\n skipRetry: true,\n timeoutMs: Math.max(AI_FUNCTION_RUN_TIMEOUT_MS, this.http.timeoutMs ?? 0),\n });\n } catch (error) {\n throw this.mapRunError(error, functionKey);\n }\n }\n\n // ── internals ──────────────────────────────────────────────────────────────\n\n private cacheDescriptor(descriptor: AiFunctionDescriptor | undefined, key?: string): void {\n if (!descriptor || typeof descriptor !== 'object') return;\n const cacheKey = key ?? descriptor.functionKey;\n if (!cacheKey) return;\n this.descriptorCache.set(cacheKey, {\n descriptor,\n expiresAt: Date.now() + AI_FUNCTION_DESCRIPTOR_TTL_MS,\n });\n }\n\n private async getCachedDescriptor(functionKey: string): Promise<AiFunctionDescriptor> {\n const hit = this.descriptorCache.get(functionKey);\n if (hit && hit.expiresAt > Date.now()) return hit.descriptor;\n return this.get(functionKey);\n }\n\n private mapRunError(error: unknown, functionKey: string | undefined): unknown {\n if (!(error instanceof CadraError)) return error;\n\n if (error.serverCode === 'DUPLICATE_REQUEST') {\n return new AiFunctionDuplicateError(error.message, error.details, error.requestId);\n }\n if (error.details?.charged === true) {\n return new AiFunctionChargedError(error);\n }\n // The server disagreed with our (cached) view of the parameters: the live\n // version probably changed. Drop the descriptor so the next run re-reads it.\n if (functionKey && error.serverCode?.startsWith('VARIABLE_')) {\n this.descriptorCache.delete(functionKey);\n }\n return error;\n }\n}\n","/**\n * Cadra Client\n *\n * Main entry point for the SDK. Provides access to all resource APIs.\n *\n * @example\n * ```typescript\n * import { CadraClient } from '@cadraos/sdk';\n *\n * const client = new CadraClient({\n * apiKey: process.env.CADRA_API_KEY,\n * orgId: Number(process.env.CADRA_ORG_ID),\n * });\n *\n * // List agents\n * const { data: agents } = await client.agents.list();\n *\n * // Execute an agent\n * const execution = await client.agents.executeSync(agents[0].uuid, {\n * task: 'Summarize the latest news',\n * });\n *\n * // Stream an agent execution\n * const stream = await client.agents.stream(agents[0].uuid, {\n * task: 'Research climate change',\n * });\n *\n * stream.on('log', (log) => console.log(log.title));\n * stream.on('complete', ({ execution }) => console.log(execution.output));\n *\n * const result = await stream.wait();\n * ```\n */\n\nimport { AgentsAPI, AiFunctionsAPI, ArtifactsAPI, AttachmentsAPI, KanbanAPI, RemoteAgentsAPI, RemoteRunnersAPI, SessionsAPI, SkillsAPI, TeamsAPI, ToolsAPI, type StreamConfig } from './resources/index.js';\nimport { HttpClient, type HttpClientConfig } from './utils/http.js';\nimport { DEFAULT_RETRY_CONFIG, type RetryConfig } from './utils/retry.js';\n\n/**\n * Default API base URL\n */\nconst DEFAULT_BASE_URL = 'https://api.cadraos.com';\n\n/**\n * Default request timeout (30 seconds)\n */\nconst DEFAULT_TIMEOUT = 30000;\n\n/**\n * Client options for API key authentication\n */\nexport interface CadraClientOptionsApiKey {\n /** API key for authentication */\n apiKey: string;\n /** Organization ID */\n orgId: number;\n /** Base URL for API (default: https://api.cadraos.com) */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts (default: 3) */\n maxRetries?: number;\n /** Custom headers to include in all requests */\n headers?: Record<string, string>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Client options for OAuth token authentication\n */\nexport interface CadraClientOptionsToken {\n /** OAuth token for authentication */\n token: string;\n /** Organization ID */\n orgId: number;\n /** Base URL for API (default: https://api.cadraos.com) */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts (default: 3) */\n maxRetries?: number;\n /** Custom headers to include in all requests */\n headers?: Record<string, string>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * Client options for token provider authentication\n */\nexport interface CadraClientOptionsTokenProvider {\n /** Token provider callback (called before each request) */\n tokenProvider: () => Promise<string>;\n /** Organization ID */\n orgId: number;\n /** Base URL for API (default: https://api.cadraos.com) */\n baseUrl?: string;\n /** Request timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Maximum retry attempts (default: 3) */\n maxRetries?: number;\n /** Custom headers to include in all requests */\n headers?: Record<string, string>;\n /** Optional fetch implementation — inject `expo/fetch` for React Native streaming. Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\n/**\n * All client options\n */\nexport type CadraClientOptions =\n | CadraClientOptionsApiKey\n | CadraClientOptionsToken\n | CadraClientOptionsTokenProvider;\n\n/**\n * AI SaaS Client\n *\n * Main class for interacting with the AI SaaS API.\n * Provides access to all resource APIs (agents, skills, tools, artifacts, sessions).\n */\nexport class CadraClient {\n private readonly httpClient: HttpClient;\n private readonly config: {\n baseUrl: string;\n apiKey?: string;\n token?: string;\n tokenProvider?: () => Promise<string>;\n orgId: number;\n timeout: number;\n headers?: Record<string, string>;\n fetch?: typeof fetch;\n };\n\n /**\n * Agent operations (list, execute, stream, update)\n */\n readonly agents: AgentsAPI;\n\n /**\n * Skill operations (list, get, execute, update)\n */\n readonly skills: SkillsAPI;\n\n /**\n * Tool operations (list, get, execute, validate, update)\n */\n readonly tools: ToolsAPI;\n\n /**\n * Artifact operations (list, get, download, upload, delete)\n */\n readonly artifacts: ArtifactsAPI;\n\n /**\n * Attachment operations (upload, confirm, download)\n */\n readonly attachments: AttachmentsAPI;\n\n /**\n * Session operations (list, get, create, message, delete)\n */\n readonly sessions: SessionsAPI;\n\n /**\n * Team operations (list, get)\n */\n readonly teams: TeamsAPI;\n\n /**\n * Kanban operations (board, cards, transitions, card-run stream)\n */\n readonly kanban: KanbanAPI;\n\n /**\n * Remote agent operations (list, get, create, update, delete, deploy, execute, stream)\n */\n readonly remoteAgents: RemoteAgentsAPI;\n\n /**\n * Remote runner operations (list)\n */\n readonly remoteRunners: RemoteRunnersAPI;\n\n /**\n * AI function operations (list, get, run, getRun) — p93\n */\n readonly aiFunctions: AiFunctionsAPI;\n\n /**\n * Create a new AI SaaS client\n *\n * @param options - Client configuration options\n *\n * @example\n * ```typescript\n * // API key authentication\n * const client = new CadraClient({\n * apiKey: 'sk_...',\n * orgId: 123,\n * });\n *\n * // OAuth token authentication\n * const client = new CadraClient({\n * token: 'eyJ...',\n * orgId: 123,\n * });\n *\n * // Token provider (for automatic refresh)\n * const client = new CadraClient({\n * tokenProvider: async () => myAuth.getAccessToken(),\n * orgId: 123,\n * });\n * ```\n */\n constructor(options: CadraClientOptions) {\n // Validate options\n this.validateOptions(options);\n\n // Warn if baseUrl looks like it includes a path prefix (check path portion only)\n if (options.baseUrl) {\n try {\n const parsed = new URL(options.baseUrl);\n if (/\\/(api|v\\d)/.test(parsed.pathname)) {\n if (typeof process !== 'undefined' && process.env?.NODE_ENV !== 'production') {\n console.warn(\n '[CadraOS SDK] baseUrl should be the origin only (e.g., \"https://api.cadraos.com\" or \"http://localhost:3000\"). ' +\n 'The SDK automatically prepends \"/api/v1/\" to all requests. ' +\n `Received: \"${options.baseUrl}\"`\n );\n }\n }\n } catch {\n // Invalid URL — will be caught later during requests\n }\n }\n\n // Store configuration\n this.config = {\n baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,\n orgId: options.orgId,\n timeout: options.timeout ?? DEFAULT_TIMEOUT,\n headers: options.headers,\n fetch: options.fetch,\n };\n\n // Set auth based on options type\n if ('apiKey' in options) {\n this.config.apiKey = options.apiKey;\n } else if ('token' in options) {\n this.config.token = options.token;\n } else if ('tokenProvider' in options) {\n this.config.tokenProvider = options.tokenProvider;\n }\n\n // Create retry configuration\n const retryConfig: RetryConfig = {\n ...DEFAULT_RETRY_CONFIG,\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_CONFIG.maxRetries,\n };\n\n // Create HTTP client configuration\n const httpConfig: HttpClientConfig = {\n baseUrl: this.config.baseUrl,\n apiKey: this.config.apiKey,\n token: this.config.token,\n tokenProvider: this.config.tokenProvider,\n orgId: this.config.orgId,\n timeout: this.config.timeout,\n retry: retryConfig,\n headers: this.config.headers,\n fetch: this.config.fetch,\n };\n\n // Create HTTP client\n this.httpClient = new HttpClient(httpConfig);\n\n // Create stream config getter\n const getStreamConfig = (): StreamConfig => ({\n baseUrl: this.config.baseUrl,\n apiKey: this.config.apiKey,\n token: this.config.token,\n tokenProvider: this.config.tokenProvider,\n orgId: this.config.orgId,\n fetch: this.config.fetch,\n });\n\n // Initialize resource APIs\n this.agents = new AgentsAPI(this.httpClient, getStreamConfig);\n this.skills = new SkillsAPI(this.httpClient);\n this.tools = new ToolsAPI(this.httpClient);\n this.artifacts = new ArtifactsAPI(this.httpClient);\n this.attachments = new AttachmentsAPI(this.httpClient);\n this.sessions = new SessionsAPI(this.httpClient, getStreamConfig);\n this.teams = new TeamsAPI(this.httpClient);\n this.kanban = new KanbanAPI(this.httpClient, getStreamConfig);\n this.remoteAgents = new RemoteAgentsAPI(this.httpClient, getStreamConfig);\n this.remoteRunners = new RemoteRunnersAPI(this.httpClient);\n this.aiFunctions = new AiFunctionsAPI(this.httpClient);\n }\n\n /**\n * Validate client options\n */\n private validateOptions(options: CadraClientOptions): void {\n // Check for auth\n const hasApiKey = 'apiKey' in options && options.apiKey;\n const hasToken = 'token' in options && options.token;\n const hasTokenProvider = 'tokenProvider' in options && options.tokenProvider;\n\n if (!hasApiKey && !hasToken && !hasTokenProvider) {\n throw new Error(\n 'Authentication required. Provide apiKey, token, or tokenProvider.'\n );\n }\n\n // Check for orgId\n if (options.orgId === undefined || options.orgId === null) {\n throw new Error('Organization ID (orgId) is required.');\n }\n\n if (typeof options.orgId !== 'number') {\n throw new Error('Organization ID (orgId) must be a number.');\n }\n }\n}\n"]}