@nexusm/sdk 1.3.0 → 1.3.2
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.
- package/dist/index.js.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +17 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/http/client.ts","../src/errors/base.ts","../src/errors/api.ts","../src/http/cache.ts","../src/http/retry.ts","../src/http/queue.ts","../src/services/base.ts","../src/types/context.ts","../src/schemas/context.ts","../src/errors/validation.ts","../src/services/context.ts","../src/schemas/memory.ts","../src/services/memories.ts","../src/schemas/conversation.ts","../src/services/conversations.ts","../src/schemas/knowledge.ts","../src/services/knowledge.ts","../src/services/activities.ts","../src/services/tenants.ts","../src/services/feedback.ts","../src/services/errors.ts","../src/client.ts","../src/schemas/tenant.ts"],"sourcesContent":["/**\n * @nexusm/sdk - Nexus AI Cognitive Services SDK\n *\n * Unified entry point that re-exports the public API surface:\n * - {@link NexusClient} - Main client class (primary entry point)\n * - Service classes - For advanced / standalone usage\n * - Configuration helpers and types\n * - Error hierarchy\n * - Domain type definitions\n *\n * @example\n * ```typescript\n * import { NexusClient } from '@nexusm/sdk';\n *\n * const nexus = new NexusClient({\n * apiKey: process.env.NEXUS_API_KEY!,\n * });\n *\n * const ctx = await nexus.context.retrieve({\n * user_id: 'user123',\n * query: '用户偏好',\n * });\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Main client\n// ---------------------------------------------------------------------------\nexport { NexusClient } from './client';\n\n// ---------------------------------------------------------------------------\n// Configuration\n// ---------------------------------------------------------------------------\nexport { resolveConfig, DEFAULT_CONFIG } from './config';\nexport type {\n NexusConfig,\n ResolvedConfig,\n CacheConfig,\n RetryConfig,\n ResolvedCacheConfig,\n ResolvedRetryConfig,\n} from './config';\n\n// ---------------------------------------------------------------------------\n// Services (for advanced / standalone usage)\n// ---------------------------------------------------------------------------\nexport { ContextService } from './services/context';\nexport { MemoryService } from './services/memories';\nexport { ConversationService } from './services/conversations';\nexport { KnowledgeService } from './services/knowledge';\nexport { ActivityService } from './services/activities';\nexport { TenantService } from './services/tenants';\nexport { FeedbackService } from './services/feedback';\nexport { ErrorService } from './services/errors';\n\n// Service parameter types (defined in service files)\nexport type { MemoryListParams, MemoryJournalParams } from './services/memories';\nexport type { ConversationListParams, MessageListParams } from './services/conversations';\nexport type { EntityCreate, EntityListParams } from './services/knowledge';\nexport type { FeedbackListParams } from './services/feedback';\nexport type { RequestOptions } from './services/base';\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\nexport {\n NexusError,\n ConfigurationError,\n NetworkError,\n TimeoutError,\n} from './errors';\nexport {\n ApiError,\n AuthenticationError,\n RateLimitError,\n ValidationError,\n NotFoundError,\n InputValidationError,\n} from './errors';\n\n// ---------------------------------------------------------------------------\n// Types\n//\n// Note: The `ApiError` interface from `./types` is intentionally excluded\n// to avoid a naming collision with the `ApiError` class from `./errors`.\n// Consumers who need the raw API error *shape* can import `ApiErrorDetail`\n// instead, or import `ApiError` directly from `@nexusm/sdk/types`.\n// ---------------------------------------------------------------------------\n\n// Common types (excluding ApiError to avoid collision with errors/ApiError class)\nexport type {\n Pagination,\n PaginatedResponse,\n ApiResponse,\n ApiErrorDetail,\n HealthResponse,\n HealthStatus,\n ServiceStatus,\n CompoundId,\n SortOrder,\n OfflineConfig,\n} from './types';\n\n// Context types\nexport type {\n ContextLayer,\n ContextDepth,\n ContextDepthPreset,\n ContextRequest,\n ContextMemory,\n ContextProfile,\n ContextMessage,\n ContextHistory,\n ContextEntity,\n ContextRelation,\n ContextGraph,\n ContextMeta,\n ContextRetrieveResponse,\n OwnerType,\n} from './types';\nexport { DEPTH_PRESETS } from './types';\n\n// Memory types\nexport type {\n Memory,\n MemoryCreate,\n MemoryUpdate,\n MemorySearch,\n MemorySearchResult,\n MemoryList,\n JournalEntry,\n JournalResponse,\n MemoryType,\n} from './types';\n\n// Conversation types\nexport type {\n Conversation,\n ConversationCreate,\n ConversationDetail,\n ConversationList,\n Message,\n MessageCreate,\n MessageList,\n ConversationSummary,\n MessageRole,\n ConversationStatus,\n} from './types';\n\n// Knowledge types\nexport type {\n KnowledgeEntity,\n KnowledgeRelationship,\n ExtractionRequest,\n ExtractionResult,\n EntityListResponse,\n GraphQueryRequest,\n GraphPathEntity,\n GraphPathRelationship,\n GraphPath,\n GraphQueryResponse,\n} from './types';\n\n// Activity types\nexport type {\n Activity,\n ActivityStreamRequest,\n ActivityStreamResponse,\n ActivityStatusResponse,\n ActivityStats,\n ActivityType,\n ActivityProcessingStatus,\n} from './types';\n\n// Tenant types\nexport type {\n Tenant,\n TenantQuotas,\n TenantUsage,\n ApiKey,\n ApiKeyCreate,\n ApiKeyCreated,\n UsageStats,\n TenantTier,\n ApiKeyScope,\n} from './types';\n\n// Feedback types\nexport type {\n FeedbackItemRequest,\n FeedbackSubmitRequest,\n FeedbackResponse,\n FeedbackListItem,\n FeedbackListResponse,\n} from './types';\n\n// Error reporting types\nexport type {\n ErrorType,\n ErrorSeverity,\n ErrorReportRequest,\n ErrorReportResponse,\n} from './types';\n\n// ---------------------------------------------------------------------------\n// HTTP utilities\n// ---------------------------------------------------------------------------\nexport { OfflineQueue } from './http';\nexport type { QueuedRequest } from './http';\n\n// ---------------------------------------------------------------------------\n// Zod Schemas (runtime validation)\n// ---------------------------------------------------------------------------\nexport {\n contextRequestSchema,\n memoryCreateSchema,\n memoryUpdateSchema,\n memorySearchSchema,\n conversationCreateSchema,\n messageCreateSchema,\n entityCreateSchema,\n graphQueryRequestSchema,\n extractionRequestSchema,\n apiKeyCreateSchema,\n} from './schemas';\n","/**\n * @module config\n * @description Configuration management for the Nexus SDK.\n *\n * Provides sensible defaults, deep-merges user overrides, and exposes a\n * fully-resolved configuration object where every field is guaranteed to\n * be present.\n */\n\nimport type { OfflineConfig } from './types/common';\n\n// ---------------------------------------------------------------------------\n// Public configuration interfaces\n// ---------------------------------------------------------------------------\n\n/** Cache layer configuration. */\nexport interface CacheConfig {\n /** Maximum number of entries in the LRU cache. */\n max?: number;\n /** Time-to-live for cached entries, in **seconds**. */\n ttl?: number;\n}\n\n/** Automatic retry configuration with exponential back-off. */\nexport interface RetryConfig {\n /** Maximum number of retry attempts (excluding the initial request). */\n maxRetries?: number;\n /** Delay before the first retry, in **milliseconds**. */\n initialDelay?: number;\n /** Upper bound for the retry delay, in **milliseconds**. */\n maxDelay?: number;\n /** Multiplier applied to the delay after each attempt. */\n backoffFactor?: number;\n}\n\n/**\n * User-facing SDK configuration.\n *\n * Only `apiKey` is strictly required; every other field falls back to a\n * sensible default (see {@link DEFAULT_CONFIG}).\n */\nexport interface NexusConfig {\n /** API key used for authentication. */\n apiKey: string;\n /**\n * Tenant identifier for multi-tenant isolation.\n * When provided, it is sent as the `X-Tenant-ID` header on every request.\n */\n tenantId?: string;\n /** Base URL of the Nexus API (without trailing slash). */\n baseUrl?: string;\n /** Request timeout in **milliseconds**. */\n timeout?: number;\n /** LRU cache settings. Pass `false` to disable caching entirely. */\n cache?: CacheConfig | false;\n /** Retry behaviour. Pass `false` to disable retries entirely. */\n retry?: RetryConfig | false;\n /** Offline queue configuration. */\n offline?: OfflineConfig;\n /**\n * Automatically report HTTP 4xx/5xx errors to the Nexus error tracking API.\n * Defaults to `false`. When enabled, failed API responses are submitted to\n * `POST /v1/errors` in the background (fire-and-forget).\n */\n autoErrorReport?: boolean;\n}\n\n/** Fully-resolved cache configuration (all fields required). */\nexport interface ResolvedCacheConfig {\n /** Maximum number of entries in the LRU cache. */\n max: number;\n /** Time-to-live for cached entries, in **seconds**. */\n ttl: number;\n}\n\n/** Fully-resolved retry configuration (all fields required). */\nexport interface ResolvedRetryConfig {\n /** Maximum number of retry attempts. */\n maxRetries: number;\n /** Delay before the first retry, in **milliseconds**. */\n initialDelay: number;\n /** Upper bound for the retry delay, in **milliseconds**. */\n maxDelay: number;\n /** Multiplier applied to the delay after each attempt. */\n backoffFactor: number;\n}\n\n/**\n * Fully-resolved SDK configuration.\n *\n * Every field is guaranteed to be present after calling\n * {@link resolveConfig}.\n */\nexport interface ResolvedConfig {\n /** API key used for authentication. */\n apiKey: string;\n /** Tenant identifier (may be `undefined` if not provided). */\n tenantId?: string;\n /** Base URL of the Nexus API (without trailing slash). */\n baseUrl: string;\n /** Request timeout in **milliseconds**. */\n timeout: number;\n /** Resolved cache settings, or `false` if caching is disabled. */\n cache: ResolvedCacheConfig | false;\n /** Resolved retry settings, or `false` if retries are disabled. */\n retry: ResolvedRetryConfig | false;\n /** Offline queue configuration (undefined if not provided). */\n offline?: OfflineConfig;\n /** Whether to auto-report HTTP 4xx/5xx errors. */\n autoErrorReport: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Defaults\n// ---------------------------------------------------------------------------\n\n/** @internal Default cache configuration. */\nconst DEFAULT_CACHE: ResolvedCacheConfig = {\n max: 1000,\n ttl: 300, // 5 minutes\n};\n\n/** @internal Default retry configuration. */\nconst DEFAULT_RETRY: ResolvedRetryConfig = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 10_000,\n backoffFactor: 2,\n};\n\n/**\n * Default SDK configuration values.\n *\n * These are used as the base when merging user-provided overrides.\n */\nexport const DEFAULT_CONFIG = {\n baseUrl: 'http://localhost:8001/v1',\n timeout: 30_000, // 30 seconds\n cache: DEFAULT_CACHE,\n retry: DEFAULT_RETRY,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Resolver\n// ---------------------------------------------------------------------------\n\n/**\n * Deep-merge user configuration with defaults and return a fully-resolved\n * configuration object.\n *\n * @param userConfig - Partial configuration provided by the SDK consumer.\n * @returns A {@link ResolvedConfig} with every field populated.\n *\n * @throws {Error} If `apiKey` is missing or empty.\n *\n * @example\n * ```typescript\n * const resolved = resolveConfig({\n * apiKey: 'sk-...',\n * timeout: 5000,\n * retry: { maxRetries: 5 },\n * });\n *\n * resolved.timeout; // 5000\n * resolved.retry.maxRetries; // 5\n * resolved.retry.initialDelay; // 1000 (default)\n * ```\n */\nexport function resolveConfig(userConfig: NexusConfig): ResolvedConfig {\n if (!userConfig.apiKey) {\n throw new Error(\n 'NexusConfig: \"apiKey\" is required and must be a non-empty string.',\n );\n }\n\n // -- Cache: honour explicit `false` to disable --\n let cache: ResolvedCacheConfig | false;\n if (userConfig.cache === false) {\n cache = false;\n } else if (userConfig.cache) {\n cache = { ...DEFAULT_CACHE, ...userConfig.cache };\n } else {\n cache = { ...DEFAULT_CACHE };\n }\n\n // -- Retry: honour explicit `false` to disable --\n let retry: ResolvedRetryConfig | false;\n if (userConfig.retry === false) {\n retry = false;\n } else if (userConfig.retry) {\n retry = { ...DEFAULT_RETRY, ...userConfig.retry };\n } else {\n retry = { ...DEFAULT_RETRY };\n }\n\n // -- Strip trailing slash from baseUrl --\n const rawBaseUrl = userConfig.baseUrl ?? DEFAULT_CONFIG.baseUrl;\n const baseUrl = rawBaseUrl.replace(/\\/+$/, '');\n\n return {\n apiKey: userConfig.apiKey,\n tenantId: userConfig.tenantId,\n baseUrl,\n timeout: userConfig.timeout ?? DEFAULT_CONFIG.timeout,\n cache,\n retry,\n offline: userConfig.offline,\n autoErrorReport: userConfig.autoErrorReport ?? false,\n };\n}\n","/**\n * @module http/client\n * @description Low-level HTTP client for the Nexus SDK.\n *\n * Wraps an Axios instance with automatic authentication headers,\n * request/response interceptors, and error normalisation so that\n * every failure surfaces as a typed {@link NexusError} subclass.\n */\n\nimport axios, {\n type AxiosInstance,\n type AxiosRequestConfig,\n type AxiosError,\n} from 'axios';\n\nimport type { ResolvedConfig } from '../config';\nimport type { OfflineConfig } from '../types/common';\nimport { NetworkError, TimeoutError } from '../errors/base';\nimport { ApiError } from '../errors/api';\nimport { CacheManager, isCacheablePost } from './cache';\nimport { RetryManager } from './retry';\nimport { OfflineQueue } from './queue';\n\n/**\n * HTTP client that communicates with the Nexus API.\n *\n * All service-level modules (Memory, Conversation, Knowledge, Context)\n * delegate their network calls to a shared `HttpClient` instance, which\n * guarantees consistent authentication, timeout handling, and error\n * mapping across the entire SDK surface.\n *\n * @example\n * ```typescript\n * import { resolveConfig } from '../config';\n * import { HttpClient } from './client';\n *\n * const config = resolveConfig({ apiKey: 'nx_test_abc123' });\n * const http = new HttpClient(config);\n *\n * const memories = await http.get<Memory[]>('/memory/search', { query: 'hello' });\n * ```\n */\nexport class HttpClient {\n /** Underlying Axios instance. */\n private readonly axios: AxiosInstance;\n\n /** Fully-resolved SDK configuration snapshot. */\n private readonly config: ResolvedConfig;\n\n /** LRU cache for read requests. */\n private readonly cache: CacheManager;\n\n /** Retry manager for transient failures. */\n private readonly retry: RetryManager;\n\n /** Offline request queue (only created when offline config is provided). */\n private readonly offlineQueue?: OfflineQueue;\n\n /** Whether the client is currently considered online. */\n private _isOnline: boolean = true;\n\n /**\n * Optional callback to auto-report API errors to POST /v1/errors.\n * Set by NexusClient after ErrorService is initialized.\n * @internal\n */\n public onApiError?: (\n statusCode: number,\n method: string,\n url: string,\n detail: string,\n ) => void;\n\n /**\n * Create a new HTTP client.\n *\n * @param config - Fully-resolved SDK configuration (see {@link resolveConfig}).\n */\n constructor(config: ResolvedConfig) {\n this.config = config;\n this.cache = new CacheManager(config.cache);\n this.retry = new RetryManager(config.retry);\n\n if (config.offline?.enabled) {\n this.offlineQueue = new OfflineQueue(config.offline.maxQueueSize ?? 100);\n }\n\n this.axios = axios.create({\n baseURL: config.baseUrl,\n timeout: config.timeout,\n });\n\n this.setupRequestInterceptor();\n this.setupResponseInterceptor();\n }\n\n // -----------------------------------------------------------------------\n // Offline queue support\n // -----------------------------------------------------------------------\n\n /**\n * Set the online/offline status of the client.\n *\n * When transitioning from offline to online, the queued requests are\n * automatically flushed.\n *\n * @param online - `true` if the client is online, `false` if offline.\n */\n setOnline(online: boolean): void {\n const wasOffline = !this._isOnline;\n this._isOnline = online;\n\n if (wasOffline && online && this.offlineQueue) {\n void this.offlineQueue.flush(async (req) => {\n switch (req.method) {\n case 'POST':\n return this.post(req.path, req.data);\n case 'PUT':\n return this.put(req.path, req.data);\n case 'PATCH':\n return this.patch(req.path, req.data);\n case 'DELETE':\n return this.delete(req.path);\n default:\n return this.get(req.path);\n }\n });\n }\n }\n\n /**\n * Access the offline queue instance (if offline mode is enabled).\n */\n get queue(): OfflineQueue | undefined {\n return this.offlineQueue;\n }\n\n // -----------------------------------------------------------------------\n // Public request methods\n // -----------------------------------------------------------------------\n\n /**\n * Send a GET request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL (e.g. `/memory/search`).\n * @param params - Optional query parameters.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async get<T>(\n path: string,\n params?: Record<string, unknown>,\n signal?: AbortSignal,\n ): Promise<T> {\n const cacheKey = this.cache.generateKey('GET', path, params);\n const cached = this.cache.get<T>(cacheKey);\n if (cached !== undefined) return cached;\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.get<T>(path, { params, signal });\n return response.data;\n });\n this.cache.set(cacheKey, result);\n return result;\n }\n\n /**\n * Send a POST request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL.\n * @param data - Optional request body.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async post<T>(\n path: string,\n data?: unknown,\n signal?: AbortSignal,\n ): Promise<T> {\n // Offline queue: enqueue write requests when offline\n if (this.offlineQueue && !this._isOnline) {\n return this.offlineQueue.enqueue<T>({ method: 'POST', path, data });\n }\n\n // Cacheable POST endpoints (read-only semantics)\n if (isCacheablePost(path)) {\n const cacheKey = this.cache.generateKey('POST', path, data);\n const cached = this.cache.get<T>(cacheKey);\n if (cached !== undefined) return cached;\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.post<T>(path, data, { signal });\n return response.data;\n });\n this.cache.set(cacheKey, result);\n return result;\n }\n\n // Write POST: execute + invalidate related cache\n const result = await this.retry.execute(async () => {\n const response = await this.axios.post<T>(path, data, { signal });\n return response.data;\n });\n this.cache.invalidate(path.split('/').filter(Boolean)[0] ?? path);\n return result;\n }\n\n /**\n * Send a PUT request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL.\n * @param data - Optional request body.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async put<T>(\n path: string,\n data?: unknown,\n signal?: AbortSignal,\n ): Promise<T> {\n if (this.offlineQueue && !this._isOnline) {\n return this.offlineQueue.enqueue<T>({ method: 'PUT', path, data });\n }\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.put<T>(path, data, { signal });\n return response.data;\n });\n this.cache.invalidate(path.split('/').filter(Boolean)[0] ?? path);\n return result;\n }\n\n /**\n * Send a PATCH request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL.\n * @param data - Optional request body.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async patch<T>(\n path: string,\n data?: unknown,\n signal?: AbortSignal,\n ): Promise<T> {\n if (this.offlineQueue && !this._isOnline) {\n return this.offlineQueue.enqueue<T>({ method: 'PATCH', path, data });\n }\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.patch<T>(path, data, { signal });\n return response.data;\n });\n this.cache.invalidate(path.split('/').filter(Boolean)[0] ?? path);\n return result;\n }\n\n /**\n * Send a DELETE request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async delete<T>(path: string, signal?: AbortSignal): Promise<T> {\n if (this.offlineQueue && !this._isOnline) {\n return this.offlineQueue.enqueue<T>({ method: 'DELETE', path });\n }\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.delete<T>(path, { signal });\n return response.data;\n });\n this.cache.invalidate(path.split('/').filter(Boolean)[0] ?? path);\n return result;\n }\n\n // -----------------------------------------------------------------------\n // Interceptors\n // -----------------------------------------------------------------------\n\n /**\n * Attach the request interceptor.\n *\n * Responsibilities:\n * - Set `X-API-Key` authentication header.\n * - Set `X-Tenant-ID` header when a tenant identifier is configured.\n * - Ensure `Content-Type` is `application/json`.\n */\n private setupRequestInterceptor(): void {\n this.axios.interceptors.request.use((requestConfig) => {\n // Authentication\n requestConfig.headers.set('X-API-Key', this.config.apiKey);\n\n // Multi-tenant isolation\n if (this.config.tenantId) {\n requestConfig.headers.set('X-Tenant-ID', this.config.tenantId);\n }\n\n // Content negotiation\n requestConfig.headers.set('Content-Type', 'application/json');\n\n return requestConfig;\n });\n }\n\n /**\n * Attach the response interceptor.\n *\n * Successful responses pass through unchanged. Errors are normalised\n * into the appropriate {@link NexusError} subclass:\n *\n * | Condition | Error class |\n * |------------------------|--------------------|\n * | Request cancelled | *(re-thrown as-is)*|\n * | Timeout (`ECONNABORTED`, `ETIMEDOUT`) | {@link TimeoutError} |\n * | No response received | {@link NetworkError} |\n * | HTTP 4xx / 5xx | {@link ApiError} (or subclass) |\n */\n private setupResponseInterceptor(): void {\n this.axios.interceptors.response.use(\n // Success handler -- pass through\n (response) => response,\n\n // Error handler -- normalise into NexusError hierarchy\n (error: AxiosError) => {\n // 1. Cancelled requests: re-throw without wrapping so callers\n // can detect cancellation via `axios.isCancel()`.\n if (axios.isCancel(error)) {\n return Promise.reject(error);\n }\n\n // 2. Timeout errors (ECONNABORTED is used by axios for timeouts,\n // ETIMEDOUT may come from the underlying socket).\n if (\n error.code === 'ECONNABORTED' ||\n error.code === 'ETIMEDOUT'\n ) {\n return Promise.reject(\n new TimeoutError(\n `Request to ${error.config?.url ?? 'unknown'} timed out after ${this.config.timeout}ms`,\n error,\n ),\n );\n }\n\n // 3. Server responded with an error status code.\n if (error.response) {\n const apiError = ApiError.fromResponse(error.response);\n\n // Auto-report to POST /v1/errors (fire-and-forget).\n // Skip reporting errors from the /errors endpoint itself to\n // avoid infinite loops.\n const reqUrl = error.config?.url ?? '';\n if (this.onApiError && !reqUrl.includes('/errors')) {\n try {\n this.onApiError(\n error.response.status,\n error.config?.method?.toUpperCase() ?? 'UNKNOWN',\n reqUrl,\n apiError.message,\n );\n } catch {\n // Never let auto-report failure break the main flow.\n }\n }\n\n return Promise.reject(apiError);\n }\n\n // 4. No response at all -- network-level failure\n // (DNS resolution, connection refused, etc.)\n return Promise.reject(\n new NetworkError(\n error.message || 'A network error occurred',\n error,\n ),\n );\n },\n );\n }\n}\n","/**\n * @module errors/base\n * @description Base error classes for the Nexus SDK.\n */\n\n/**\n * Base error class for all Nexus SDK errors.\n *\n * All SDK-specific errors extend this class, providing a consistent\n * `code` field for programmatic error handling.\n *\n * @example\n * ```typescript\n * try {\n * await client.context.retrieve({ ... });\n * } catch (err) {\n * if (err instanceof NexusError) {\n * console.error(`[${err.code}] ${err.message}`);\n * }\n * }\n * ```\n */\nexport class NexusError extends Error {\n /** Machine-readable error code (e.g. `NEXUS_API_ERROR`). */\n public readonly code: string;\n\n /** The original error that caused this error, if any. */\n public readonly cause?: Error;\n\n constructor(message: string, code: string, cause?: Error) {\n super(message);\n // Restore prototype chain — required when extending built-ins in TS\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = 'NexusError';\n this.code = code;\n this.cause = cause;\n }\n}\n\n/**\n * Thrown when the SDK is configured with invalid options.\n *\n * @example\n * ```typescript\n * // Missing required `apiKey`\n * new NexusClient({}) // throws ConfigurationError\n * ```\n */\nexport class ConfigurationError extends NexusError {\n constructor(message: string, cause?: Error) {\n super(message, 'NEXUS_CONFIGURATION_ERROR', cause);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Thrown when a network-level failure occurs (timeout, DNS, connection refused, etc.).\n */\nexport class NetworkError extends NexusError {\n constructor(message: string, cause?: Error) {\n super(message, 'NEXUS_NETWORK_ERROR', cause);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Thrown when an operation exceeds its configured timeout.\n */\nexport class TimeoutError extends NexusError {\n constructor(message: string, cause?: Error) {\n super(message, 'NEXUS_TIMEOUT_ERROR', cause);\n this.name = 'TimeoutError';\n }\n}\n","/**\n * @module errors/api\n * @description API-level error classes mapped to HTTP status codes.\n */\n\nimport type { AxiosResponse } from 'axios';\n\nimport { NexusError } from './base';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Shape of the standard Nexus API error response body. */\ninterface ApiErrorBody {\n detail?: string;\n message?: string;\n errors?: Record<string, string[]>;\n}\n\n/**\n * Extract a human-readable message from an API response body.\n */\nfunction extractMessage(data: unknown, fallback: string): string {\n if (data && typeof data === 'object') {\n const body = data as ApiErrorBody;\n return body.detail ?? body.message ?? fallback;\n }\n return fallback;\n}\n\n// ---------------------------------------------------------------------------\n// ApiError\n// ---------------------------------------------------------------------------\n\n/**\n * Represents an error returned by the Nexus HTTP API.\n *\n * Use the static factory `ApiError.fromResponse()` to construct the most\n * specific subclass based on the HTTP status code.\n *\n * @example\n * ```typescript\n * try {\n * await client.memory.search({ ... });\n * } catch (err) {\n * if (err instanceof ApiError) {\n * console.error(`HTTP ${err.statusCode}: ${err.message}`);\n * }\n * }\n * ```\n */\nexport class ApiError extends NexusError {\n /** HTTP status code returned by the server. */\n public readonly statusCode: number;\n\n /** Raw response body, if available. */\n public readonly response?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n response?: unknown,\n code: string = 'NEXUS_API_ERROR',\n ) {\n super(message, code);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = 'ApiError';\n this.statusCode = statusCode;\n this.response = response;\n }\n\n /**\n * Create the most specific `ApiError` subclass from an Axios response.\n *\n * | Status | Error class |\n * |--------|------------------------|\n * | 400 | `ValidationError` |\n * | 401 | `AuthenticationError` |\n * | 404 | `NotFoundError` |\n * | 429 | `RateLimitError` |\n * | other | `ApiError` |\n */\n static fromResponse(response: AxiosResponse): ApiError {\n const { status, data, headers } = response;\n\n switch (status) {\n case 400: {\n const msg = extractMessage(data, 'Validation failed');\n const details =\n data && typeof data === 'object'\n ? (data as ApiErrorBody).errors\n : undefined;\n return new ValidationError(msg, details, data);\n }\n\n case 401: {\n const msg = extractMessage(data, 'Authentication failed');\n return new AuthenticationError(msg, data);\n }\n\n case 404: {\n const msg = extractMessage(data, 'Resource not found');\n return new NotFoundError(msg, data);\n }\n\n case 429: {\n const msg = extractMessage(data, 'Rate limit exceeded');\n const retryAfter = headers?.['retry-after']\n ? Number(headers['retry-after'])\n : undefined;\n return new RateLimitError(msg, retryAfter, data);\n }\n\n default: {\n const msg = extractMessage(\n data,\n `API request failed with status ${status}`,\n );\n return new ApiError(msg, status, data);\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Specific API errors\n// ---------------------------------------------------------------------------\n\n/**\n * HTTP 401 -- the request lacks valid authentication credentials.\n */\nexport class AuthenticationError extends ApiError {\n constructor(message: string, response?: unknown) {\n super(message, 401, response, 'NEXUS_AUTHENTICATION_ERROR');\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * HTTP 429 -- the client has sent too many requests in a given time window.\n *\n * When the server provides a `Retry-After` header, it is exposed via\n * {@link RateLimitError.retryAfter} (in seconds).\n */\nexport class RateLimitError extends ApiError {\n /** Seconds to wait before retrying, parsed from the `Retry-After` header. */\n public readonly retryAfter?: number;\n\n constructor(message: string, retryAfter?: number, response?: unknown) {\n super(message, 429, response, 'NEXUS_RATE_LIMIT_ERROR');\n this.name = 'RateLimitError';\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * HTTP 400 -- the request body or query parameters failed validation.\n *\n * When the server returns field-level errors they are available via\n * {@link ValidationError.details}.\n */\nexport class ValidationError extends ApiError {\n /** Per-field validation error messages, if provided by the server. */\n public readonly details?: Record<string, string[]>;\n\n constructor(\n message: string,\n details?: Record<string, string[]>,\n response?: unknown,\n ) {\n super(message, 400, response, 'NEXUS_VALIDATION_ERROR');\n this.name = 'ValidationError';\n this.details = details;\n }\n}\n\n/**\n * HTTP 404 -- the requested resource does not exist.\n */\nexport class NotFoundError extends ApiError {\n constructor(message: string, response?: unknown) {\n super(message, 404, response, 'NEXUS_NOT_FOUND_ERROR');\n this.name = 'NotFoundError';\n }\n}\n","/**\n * @module http/cache\n * @description LRU cache layer for the Nexus SDK HTTP client.\n *\n * Provides transparent caching for GET requests and specific read-oriented\n * POST endpoints (e.g. `/context/retrieve`, `/memories/search`,\n * `/knowledge/query`). Write operations automatically invalidate related\n * cache entries by path prefix.\n *\n * When caching is disabled (`config === false`), every method is a no-op\n * with zero overhead.\n */\n\nimport { LRUCache } from 'lru-cache';\n\nimport type { ResolvedCacheConfig } from '../config';\n\n// ---------------------------------------------------------------------------\n// Cacheable POST endpoints\n// ---------------------------------------------------------------------------\n\n/**\n * POST paths that are semantically read-only and therefore safe to cache.\n * These endpoints perform search / retrieval operations via POST bodies.\n */\nconst CACHEABLE_POST_PATHS: ReadonlySet<string> = new Set([\n '/context/retrieve',\n '/memories/search',\n '/knowledge/query',\n]);\n\n/**\n * Check whether a POST request to the given path is eligible for caching.\n */\nexport function isCacheablePost(path: string): boolean {\n return CACHEABLE_POST_PATHS.has(path);\n}\n\n// ---------------------------------------------------------------------------\n// Stable hashing\n// ---------------------------------------------------------------------------\n\n/**\n * Produce a deterministic hash string from an arbitrary value.\n *\n * The value is first serialised to JSON with sorted keys so that\n * `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` yield the same hash.\n * The hash itself is a simple DJB2-style numeric hash converted to\n * a base-36 string -- fast and collision-resistant enough for cache keys.\n */\nfunction stableHash(value: unknown): string {\n const json = JSON.stringify(value, (_key, val) => {\n // Sort object keys for deterministic serialisation\n if (val !== null && typeof val === 'object' && !Array.isArray(val)) {\n return Object.keys(val as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((sorted, k) => {\n sorted[k] = (val as Record<string, unknown>)[k];\n return sorted;\n }, {});\n }\n return val;\n });\n\n // DJB2 hash\n let hash = 5381;\n for (let i = 0; i < json.length; i++) {\n // hash * 33 + charCode\n hash = ((hash << 5) + hash + json.charCodeAt(i)) | 0;\n }\n\n // Convert to unsigned 32-bit then base-36 for a compact string\n return (hash >>> 0).toString(36);\n}\n\n// ---------------------------------------------------------------------------\n// CacheManager\n// ---------------------------------------------------------------------------\n\n/**\n * LRU cache manager for the Nexus SDK.\n *\n * Wraps the `lru-cache` library and adds:\n * - Stable key generation from method + path + params/body\n * - Pattern-based invalidation for write-after-read consistency\n * - Hit / miss counters for observability\n * - Graceful no-op behaviour when caching is disabled\n *\n * @example\n * ```typescript\n * const cache = new CacheManager({ max: 500, ttl: 120 });\n *\n * const key = cache.generateKey('GET', '/memories', { user_id: 'u1' });\n * cache.set(key, [{ id: '1', content: 'hello' }]);\n *\n * const hit = cache.get<Memory[]>(key); // => [{ id: '1', ... }]\n * console.log(cache.stats); // { size: 1, hits: 1, misses: 0 }\n * ```\n */\nexport class CacheManager {\n /** Underlying LRU cache instance. */\n private readonly cache: LRUCache<string, unknown>;\n\n /** Whether caching is active. */\n private readonly enabled: boolean;\n\n /** Running hit counter. */\n private _hits = 0;\n\n /** Running miss counter. */\n private _misses = 0;\n\n /**\n * Create a new cache manager.\n *\n * @param config - Resolved cache configuration, or `false` to disable.\n */\n constructor(config: ResolvedCacheConfig | false) {\n if (config === false) {\n this.enabled = false;\n // Minimal placeholder -- never actually used\n this.cache = new LRUCache<string, unknown>({ max: 1 });\n } else {\n this.enabled = true;\n this.cache = new LRUCache<string, unknown>({\n max: config.max,\n ttl: config.ttl * 1000, // seconds -> milliseconds\n });\n }\n }\n\n // -----------------------------------------------------------------------\n // Key generation\n // -----------------------------------------------------------------------\n\n /**\n * Generate a deterministic cache key from the request signature.\n *\n * Format: `METHOD:path:hash(params)`\n *\n * @param method - HTTP method (e.g. `GET`, `POST`).\n * @param path - Request path (e.g. `/memories/search`).\n * @param params - Query parameters or request body (optional).\n * @returns A string suitable for use as a cache key.\n */\n generateKey(method: string, path: string, params?: unknown): string {\n const base = `${method.toUpperCase()}:${path}`;\n if (params === undefined || params === null) {\n return base;\n }\n return `${base}:${stableHash(params)}`;\n }\n\n // -----------------------------------------------------------------------\n // Core operations\n // -----------------------------------------------------------------------\n\n /**\n * Retrieve a cached value.\n *\n * @typeParam T - Expected type of the cached value.\n * @param key - Cache key (as returned by {@link generateKey}).\n * @returns The cached value, or `undefined` on a miss.\n */\n get<T>(key: string): T | undefined {\n if (!this.enabled) {\n return undefined;\n }\n\n const value = this.cache.get(key);\n if (value !== undefined) {\n this._hits++;\n return value as T;\n }\n\n this._misses++;\n return undefined;\n }\n\n /**\n * Store a value in the cache.\n *\n * @param key - Cache key.\n * @param value - Value to cache.\n */\n set(key: string, value: unknown): void {\n if (!this.enabled) {\n return;\n }\n this.cache.set(key, value);\n }\n\n /**\n * Invalidate all cache entries whose key contains the given pattern.\n *\n * This is typically called after a write operation to evict stale\n * read results. For example, after `POST /memories`, calling\n * `invalidate('/memories')` removes all cached memory queries.\n *\n * @param pattern - Substring to match against cache keys.\n */\n invalidate(pattern: string): void {\n if (!this.enabled) {\n return;\n }\n\n // Iterate over all keys and delete those that contain the pattern.\n // LRUCache exposes keys via the keys() iterator.\n for (const key of this.cache.keys()) {\n if (key.includes(pattern)) {\n this.cache.delete(key);\n }\n }\n }\n\n /**\n * Remove all entries from the cache and reset counters.\n */\n clear(): void {\n if (!this.enabled) {\n return;\n }\n this.cache.clear();\n this._hits = 0;\n this._misses = 0;\n }\n\n // -----------------------------------------------------------------------\n // Observability\n // -----------------------------------------------------------------------\n\n /**\n * Current cache statistics.\n *\n * Useful for logging, health checks, and dashboards.\n */\n get stats(): { size: number; hits: number; misses: number } {\n return {\n size: this.enabled ? this.cache.size : 0,\n hits: this._hits,\n misses: this._misses,\n };\n }\n}\n","/**\n * @module http/retry\n * @description Retry manager with exponential back-off and jitter.\n *\n * Wraps an async operation and transparently retries on transient failures\n * (network errors, timeouts, 429 rate-limits, 5xx server errors) using\n * configurable exponential back-off with ±10% jitter to prevent thundering\n * herd problems.\n */\n\nimport type { ResolvedRetryConfig } from '../config';\nimport { NetworkError, TimeoutError } from '../errors/base';\nimport { ApiError, RateLimitError } from '../errors/api';\n\n/**\n * Manages retry logic for HTTP requests.\n *\n * When retries are disabled (`config === false`), {@link execute} delegates\n * directly to the provided function with zero overhead.\n *\n * @example\n * ```typescript\n * const retry = new RetryManager({ maxRetries: 3, initialDelay: 1000, maxDelay: 10000, backoffFactor: 2 });\n *\n * const result = await retry.execute(() => httpClient.get('/context/retrieve'));\n * ```\n */\nexport class RetryManager {\n /** Resolved retry configuration, or `false` when retries are disabled. */\n private readonly config: ResolvedRetryConfig | false;\n\n /**\n * Create a new retry manager.\n *\n * @param config - Fully-resolved retry settings, or `false` to disable retries entirely.\n */\n constructor(config: ResolvedRetryConfig | false) {\n this.config = config;\n }\n\n /**\n * Determine whether a given error is eligible for retry.\n *\n * Retryable conditions:\n * - {@link NetworkError} -- transient connectivity issues\n * - {@link TimeoutError} -- request exceeded its deadline\n * - {@link RateLimitError} (HTTP 429) -- server asks us to slow down\n * - Any {@link ApiError} with a 5xx status code -- server-side failures\n *\n * Non-retryable conditions:\n * - 4xx errors other than 429 (client errors that won't resolve on retry)\n * - Cancelled / aborted requests\n * - Any non-Nexus error (unknown failures are not assumed to be transient)\n *\n * @param error - The error to evaluate.\n * @returns `true` if the operation should be retried.\n */\n isRetryable(error: unknown): boolean {\n // Network-level failures are always transient\n if (error instanceof NetworkError) {\n return true;\n }\n\n // Timeouts are transient\n if (error instanceof TimeoutError) {\n return true;\n }\n\n // Rate-limit (429) -- the server explicitly expects us to retry later\n if (error instanceof RateLimitError) {\n return true;\n }\n\n // Other API errors: only 5xx (server errors) are retryable\n if (error instanceof ApiError) {\n return error.statusCode >= 500 && error.statusCode < 600;\n }\n\n // Cancelled requests and unknown errors are not retryable\n return false;\n }\n\n /**\n * Calculate the delay (in milliseconds) before the next retry attempt.\n *\n * Uses exponential back-off: `delay = initialDelay * backoffFactor ^ attempt`.\n *\n * Special cases:\n * - If the error is a {@link RateLimitError} with a `retryAfter` value,\n * that value (converted to ms) takes precedence over the computed delay.\n * - A random jitter of ±10% is applied to prevent thundering herd.\n * - The result is clamped to {@link ResolvedRetryConfig.maxDelay}.\n *\n * @param attempt - Zero-based attempt index (0 = first retry).\n * @param error - The error that triggered the retry (optional).\n * @returns Delay in milliseconds before the next attempt.\n */\n getDelay(attempt: number, error?: unknown): number {\n if (this.config === false) {\n return 0;\n }\n\n const { initialDelay, backoffFactor, maxDelay } = this.config;\n\n // If the server told us exactly when to retry, honour that\n if (error instanceof RateLimitError && error.retryAfter != null) {\n // retryAfter is in seconds; convert to ms and apply jitter\n const serverDelay = error.retryAfter * 1000;\n return Math.min(this.applyJitter(serverDelay), maxDelay);\n }\n\n // Exponential back-off: initialDelay * backoffFactor ^ attempt\n const exponentialDelay = initialDelay * Math.pow(backoffFactor, attempt);\n\n // Apply jitter and clamp\n return Math.min(this.applyJitter(exponentialDelay), maxDelay);\n }\n\n /**\n * Execute an async function with automatic retries on transient failures.\n *\n * If retries are disabled (`config === false`), the function is invoked\n * exactly once with no retry logic.\n *\n * @typeParam T - Return type of the wrapped function.\n * @param fn - The async operation to execute (and potentially retry).\n * @returns The resolved value of `fn`.\n * @throws The last error encountered if all retry attempts are exhausted,\n * or immediately if the error is not retryable.\n *\n * @example\n * ```typescript\n * const manager = new RetryManager({ maxRetries: 3, initialDelay: 500, maxDelay: 5000, backoffFactor: 2 });\n *\n * const data = await manager.execute(async () => {\n * return fetch('/api/data').then(r => r.json());\n * });\n * ```\n */\n async execute<T>(fn: () => Promise<T>): Promise<T> {\n // Retries disabled -- single attempt, no overhead\n if (this.config === false) {\n return fn();\n }\n\n const { maxRetries } = this.config;\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error: unknown) {\n lastError = error;\n\n // If the error is not retryable, fail immediately\n if (!this.isRetryable(error)) {\n throw error;\n }\n\n // If we've exhausted all retries, throw the last error\n if (attempt >= maxRetries) {\n throw error;\n }\n\n // Wait before the next attempt\n const delay = this.getDelay(attempt, error);\n await this.sleep(delay);\n }\n }\n\n // TypeScript: this line is technically unreachable, but satisfies the compiler\n throw lastError;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Apply ±10% random jitter to a delay value.\n *\n * @param delay - Base delay in milliseconds.\n * @returns Jittered delay in milliseconds.\n */\n private applyJitter(delay: number): number {\n // jitterFactor is in the range [0.9, 1.1]\n const jitterFactor = 0.9 + Math.random() * 0.2;\n return Math.round(delay * jitterFactor);\n }\n\n /**\n * Sleep for the specified duration.\n *\n * @param ms - Duration in milliseconds.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * @module http/queue\n * @description Offline request queue for the Nexus SDK.\n *\n * When the network is unavailable, requests can be enqueued and later\n * flushed (replayed) once connectivity is restored. Each enqueued request\n * returns a `Promise` so callers can `await` the eventual result\n * transparently.\n */\n\nimport { NexusError } from '../errors/base';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A request that has been queued for later execution.\n *\n * The `resolve` and `reject` callbacks are wired to the `Promise` returned\n * by {@link OfflineQueue.enqueue}, allowing the original caller to `await`\n * the result even though the actual HTTP call is deferred.\n */\nexport interface QueuedRequest {\n /** Unique identifier for this queued request. */\n id: string;\n /** HTTP method (e.g. `GET`, `POST`, `PUT`, `DELETE`). */\n method: string;\n /** URL path relative to the base URL. */\n path: string;\n /** Optional request body. */\n data?: unknown;\n /** Resolve the caller's deferred promise with the response. */\n resolve: (value: unknown) => void;\n /** Reject the caller's deferred promise with an error. */\n reject: (error: unknown) => void;\n /** Unix timestamp (ms) when the request was enqueued. */\n timestamp: number;\n}\n\n// ---------------------------------------------------------------------------\n// OfflineQueue\n// ---------------------------------------------------------------------------\n\n/**\n * Queues HTTP requests while the client is offline and replays them\n * when connectivity is restored.\n *\n * Each call to {@link enqueue} returns a `Promise` that resolves (or\n * rejects) only after the request has been successfully flushed via\n * {@link flush}. This allows consuming code to `await` the result as\n * if the request were executed immediately.\n *\n * @example\n * ```typescript\n * const queue = new OfflineQueue(50);\n *\n * // While offline -- the promise won't settle until flush()\n * const pending = queue.enqueue({ method: 'POST', path: '/memory/add', data: { text: 'hello' } });\n *\n * // Later, when online again\n * await queue.flush(async (req) => httpClient.post(req.path, req.data));\n *\n * // Now `pending` has resolved with the server response\n * const result = await pending;\n * ```\n */\nexport class OfflineQueue {\n /** Internal FIFO queue of deferred requests. */\n private readonly queue: QueuedRequest[] = [];\n\n /** Maximum number of requests the queue will hold. */\n private readonly maxSize: number;\n\n /** Guard flag to prevent concurrent flush operations. */\n private processing = false;\n\n /** Auto-incrementing counter used to generate unique request IDs. */\n private idCounter = 0;\n\n /**\n * Create a new offline queue.\n *\n * @param maxSize - Maximum number of requests to buffer. When the queue\n * is full, subsequent {@link enqueue} calls will reject\n * immediately. Defaults to `100`.\n */\n constructor(maxSize = 100) {\n this.maxSize = maxSize;\n }\n\n /**\n * Add a request to the queue.\n *\n * The returned `Promise` settles only when the request is eventually\n * executed during a {@link flush} call.\n *\n * @param request - The request descriptor (method, path, and optional data).\n * @returns A `Promise` that resolves with the executor's return value\n * once the request is flushed, or rejects if the queue is full\n * or the executor fails.\n *\n * @throws {NexusError} If the queue has reached its maximum capacity.\n */\n enqueue<T = unknown>(\n request: Omit<QueuedRequest, 'id' | 'resolve' | 'reject' | 'timestamp'>,\n ): Promise<T> {\n if (this.queue.length >= this.maxSize) {\n return Promise.reject(\n new NexusError(\n `Offline queue is full (max ${this.maxSize}). Request to ${request.method} ${request.path} was rejected.`,\n 'NEXUS_QUEUE_FULL',\n ),\n );\n }\n\n return new Promise<T>((resolve, reject) => {\n this.idCounter += 1;\n\n const queued: QueuedRequest = {\n id: `oq_${this.idCounter}_${Date.now()}`,\n method: request.method,\n path: request.path,\n data: request.data,\n resolve: resolve as (value: unknown) => void,\n reject,\n timestamp: Date.now(),\n };\n\n this.queue.push(queued);\n });\n }\n\n /**\n * Process all queued requests in FIFO order.\n *\n * Each request is passed to the provided `executor` function. On success\n * the caller's deferred promise is resolved; on failure it is rejected.\n *\n * Requests are processed sequentially to preserve ordering guarantees.\n * If a flush is already in progress, subsequent calls are silently ignored.\n *\n * @param executor - An async function that performs the actual HTTP call\n * for a given queued request and returns the response.\n *\n * @example\n * ```typescript\n * await queue.flush(async (req) => {\n * return httpClient.request(req.method, req.path, req.data);\n * });\n * ```\n */\n async flush(\n executor: (req: QueuedRequest) => Promise<unknown>,\n ): Promise<void> {\n // Prevent concurrent flushes\n if (this.processing) {\n return;\n }\n\n this.processing = true;\n\n try {\n while (this.queue.length > 0) {\n // Shift from the front to maintain FIFO order\n const request = this.queue.shift()!;\n\n try {\n const result = await executor(request);\n request.resolve(result);\n } catch (error: unknown) {\n request.reject(error);\n }\n }\n } finally {\n this.processing = false;\n }\n }\n\n /**\n * The number of requests currently waiting in the queue.\n */\n get size(): number {\n return this.queue.length;\n }\n\n /**\n * Remove all pending requests from the queue.\n *\n * Every deferred promise is rejected with a cancellation error so that\n * callers are not left hanging indefinitely.\n */\n clear(): void {\n while (this.queue.length > 0) {\n const request = this.queue.shift()!;\n request.reject(\n new NexusError(\n 'Request cancelled: offline queue was cleared.',\n 'NEXUS_QUEUE_CLEARED',\n ),\n );\n }\n }\n}\n","/**\n * @module services/base\n * @description Abstract base class for all Nexus service modules.\n *\n * Every service (Context, Memory, Conversation, Knowledge) extends this\n * class to gain access to the shared {@link HttpClient} instance, which\n * handles authentication, error normalisation, and timeout management.\n */\n\nimport type { HttpClient } from '../http/client';\n\n/**\n * Options that can be passed to any service method.\n */\nexport interface RequestOptions {\n /** Optional AbortSignal to cancel the request. */\n signal?: AbortSignal;\n}\n\n/**\n * Abstract base class that all Nexus service classes extend.\n *\n * Provides a protected reference to the SDK's {@link HttpClient} so that\n * subclasses can issue HTTP requests without managing connection details.\n *\n * @example\n * ```typescript\n * class MyService extends BaseService {\n * async ping(): Promise<string> {\n * return this.http.get<string>('/ping');\n * }\n * }\n * ```\n */\nexport abstract class BaseService {\n /** Shared HTTP client instance configured with API key and tenant headers. */\n protected readonly http: HttpClient;\n\n /**\n * @param http - Fully-configured {@link HttpClient} instance.\n */\n constructor(http: HttpClient) {\n this.http = http;\n }\n}\n","/**\n * @nexusm/sdk - Context Types\n *\n * Type definitions for the Context Service - the core aggregated context\n * retrieval API used in Chat main flows.\n *\n * v2.0 DX Enhanced temporal-anchored multi-layer retrieval.\n *\n * Based on Nexus API v2.0 OpenAPI specification.\n */\n\n// ============== Context Layers (v2.0 DX Enhancement) ==============\n\n/**\n * Available context retrieval layers for multi-layer parallel retrieval.\n * - \"recent\": Time-anchored activities from the activity stream\n * - \"semantic\": Vector similarity search against memory store (Mem0)\n * - \"graph\": Knowledge graph traversal (Fast GraphRAG)\n */\nexport type ContextLayer = 'recent' | 'semantic' | 'graph';\n\n// ============== Context Depth Presets ==============\n\n/**\n * Convenience depth levels for context retrieval.\n *\n * | Level | Profile | History | Graph | Layers |\n * |-------|---------|---------|-------|-------------------|\n * | L0 | 1 mem | off | off | [] |\n * | L1 | 3 mems | off | off | [] |\n * | L2 | 10 mems | off | off | [\"semantic\"] |\n * | L3 | 20 mems | on | on | [\"semantic\",\"graph\"] |\n *\n * Use with the `depth` parameter on {@link ContextRequest}.\n * Explicit fields always override the preset values.\n */\nexport type ContextDepth = 'L0' | 'L1' | 'L2' | 'L3';\n\n/** @internal Partial ContextRequest overrides applied for each depth preset. */\nexport type ContextDepthPreset = Pick<\n ContextRequest,\n 'include_profile' | 'profile_limit' | 'include_history' | 'include_graph' | 'layers'\n>;\n\n/**\n * Preset field overrides for each {@link ContextDepth} level.\n * Applied before user-supplied options so explicit values always win.\n */\nexport const DEPTH_PRESETS: Record<ContextDepth, ContextDepthPreset> = {\n L0: { include_profile: true, profile_limit: 1, include_history: false, include_graph: false, layers: [] },\n L1: { include_profile: true, profile_limit: 3, include_history: false, include_graph: false, layers: [] },\n L2: { include_profile: true, profile_limit: 10, include_history: false, include_graph: false, layers: ['semantic'] },\n L3: { include_profile: true, profile_limit: 20, include_history: true, include_graph: true, layers: ['semantic', 'graph'] },\n};\n\n// ============== Context Request (v2.0 DX Enhanced) ==============\n\n/**\n * Request payload for the v2.0 DX Enhanced context retrieval endpoint.\n * Supports multi-layer parallel retrieval with temporal anchoring (US-014).\n *\n * POST /context/retrieve\n *\n * The optional `depth` field is a client-side convenience shorthand.\n * It is resolved to concrete field values before the request is sent to the\n * backend, so it never appears in the wire payload.\n */\nexport interface ContextRequest {\n /**\n * Convenience depth preset. When set, applies a predefined combination of\n * `include_profile`, `profile_limit`, `include_history`, `include_graph`,\n * and `layers`. Any field you supply explicitly overrides the preset value.\n *\n * @see {@link DEPTH_PRESETS} for exact values per level.\n */\n depth?: ContextDepth;\n /** User ID within the tenant (Nexus auto-prefixes tenant ID) */\n user_id: string;\n /** Optional semantic query text (used for the semantic layer) */\n query?: string;\n /**\n * Context layers to retrieve in parallel.\n * @default [\"semantic\", \"graph\"]\n */\n layers?: ContextLayer[];\n /**\n * Time window for the recent layer in hours.\n * @default 4\n */\n recent_hours?: number;\n /**\n * Maximum number of recent activities to return.\n * @default 10\n */\n recent_limit?: number;\n /**\n * Whether to include memory profile (semantic layer).\n * @default true\n */\n include_profile?: boolean;\n /**\n * Maximum number of profile memories to return.\n * @default 5\n */\n profile_limit?: number;\n /**\n * Whether to include conversation history.\n * @default true\n */\n include_history?: boolean;\n /**\n * Maximum number of conversation history messages to return.\n * @default 10\n */\n history_limit?: number;\n /**\n * Whether to include knowledge graph entities (graph layer).\n * @default true\n */\n include_graph?: boolean;\n /**\n * Maximum number of knowledge graph entities to return.\n * @default 5\n */\n graph_limit?: number;\n /**\n * Optional point-in-time anchor for temporal-aware retrieval.\n * RFC 3339 datetime **with timezone offset** (e.g.\n * `\"2026-01-01T00:00:00+00:00\"` or `\"2026-01-01T00:00:00Z\"`).\n * When set, layers that support temporal anchoring (semantic, recent)\n * scope their retrieval to facts known to the system at that\n * timestamp — useful for replaying past states (debugging,\n * compliance) or running deterministic evaluations against\n * a historical snapshot.\n *\n * Naive datetimes (no timezone) are rejected client-side by the\n * zod schema to prevent silent UTC vs local-time mismatches at\n * the ingest boundary.\n *\n * @since 1.3.0 (US-037 Wave 1 TASK-005)\n */\n as_of?: string;\n}\n\n// ============== Context Response Sub-types ==============\n\n/**\n * A single memory item within the context profile.\n * Sourced from Mem0 memory store.\n */\nexport interface ContextMemory {\n /** Unique memory identifier (UUID) */\n id: string;\n /** Memory content text */\n content: string;\n /** Type of memory */\n memory_type: 'episodic' | 'semantic' | 'procedural';\n /** Relevance score from similarity search */\n score?: number;\n /** Timestamp when the memory was created (ISO 8601) */\n created_at: string;\n}\n\n/**\n * User profile memories section of the context response.\n * Contains memories retrieved from Mem0.\n */\nexport interface ContextProfile {\n /** List of relevant memories */\n memories: ContextMemory[];\n /** Total number of memories the user has */\n total_count: number;\n}\n\n/** A single message within conversation history. */\nexport interface ContextMessage {\n /** Message role */\n role: 'user' | 'assistant' | 'system' | 'tool';\n /** Message content text */\n content: string;\n /** Timestamp when the message was created (ISO 8601) */\n created_at: string;\n}\n\n/**\n * Conversation history section of the context response.\n * Sourced from Zep conversation store.\n */\nexport interface ContextHistory {\n /** List of recent messages */\n messages: ContextMessage[];\n /** Auto-generated conversation summary (if available) */\n summary?: string;\n /** Session identifier */\n session_id?: string;\n}\n\n/** Entity ownership type in the knowledge graph */\nexport type OwnerType = 'agent' | 'user';\n\n/**\n * A knowledge entity within the graph context.\n * Sourced from Fast GraphRAG.\n */\nexport interface ContextEntity {\n /** Unique entity identifier (UUID) */\n id: string;\n /** Entity display name */\n name: string;\n /** Entity type classification (e.g., Person, Organization) */\n entity_type: string;\n /** Entity description */\n description?: string;\n /** Additional entity properties */\n properties?: Record<string, unknown>;\n /** Ownership type: agent=public knowledge, user=private social graph */\n owner_type?: OwnerType;\n}\n\n/** A relationship between two entities in the knowledge graph. */\nexport interface ContextRelation {\n /** Source entity name */\n source: string;\n /** Relationship type label */\n relation: string;\n /** Target entity name */\n target: string;\n /** Relationship weight/strength */\n weight?: number;\n}\n\n/**\n * Knowledge graph section of the context response.\n * Sourced from Fast GraphRAG.\n */\nexport interface ContextGraph {\n /** List of relevant entities */\n entities: ContextEntity[];\n /** List of relationships between entities */\n relations: ContextRelation[];\n}\n\n/**\n * Retrieval performance metadata.\n * Provides timing information for each retrieval layer.\n */\nexport interface ContextMeta {\n /** Total retrieval time in milliseconds */\n took_ms: number;\n /** Memory retrieval time in milliseconds */\n memory_took_ms?: number;\n /** History retrieval time in milliseconds */\n history_took_ms?: number;\n /** Graph retrieval time in milliseconds */\n graph_took_ms?: number;\n /** Original query text */\n query?: string;\n}\n\n// ============== Context Retrieve Response ==============\n\n/**\n * Aggregated context response from the retrieve endpoint.\n * Contains parallel-fetched results from all requested layers.\n */\nexport interface ContextRetrieveResponse {\n /** User profile memories from Mem0 */\n profile?: ContextProfile;\n /** Conversation history from Zep */\n history?: ContextHistory;\n /** Knowledge graph data from GraphRAG */\n graph?: ContextGraph;\n /** Retrieval performance metadata */\n meta?: ContextMeta;\n}\n","import { z } from 'zod';\r\n\r\nconst contextLayerSchema = z.enum(['recent', 'semantic', 'graph']);\r\n\r\nexport const contextRequestSchema = z.object({\r\n user_id: z.string().min(1),\r\n query: z.string().optional(),\r\n layers: z.array(contextLayerSchema).optional(),\r\n recent_hours: z.number().positive().optional(),\r\n recent_limit: z.number().int().positive().optional(),\r\n include_profile: z.boolean().optional(),\r\n profile_limit: z.number().int().positive().optional(),\r\n include_history: z.boolean().optional(),\r\n history_limit: z.number().int().positive().optional(),\r\n include_graph: z.boolean().optional(),\r\n graph_limit: z.number().int().positive().optional(),\r\n // RFC 3339 with required timezone offset (`offset: true`). Rejects naive\r\n // datetimes like `\"2026-01-01T00:00:00\"` to surface ingest-boundary\r\n // ambiguity early — see ContextRequest.as_of JSDoc.\r\n // Added in v1.3.0 (US-037 Wave 1 TASK-005).\r\n as_of: z.string().datetime({ offset: true }).optional(),\r\n});\r\n","import { NexusError } from './base';\r\nimport type { ZodError } from 'zod';\r\n\r\n/**\r\n * Thrown when client-side input validation fails (zod schema).\r\n * Distinct from the API ValidationError (HTTP 400).\r\n */\r\nexport class InputValidationError extends NexusError {\r\n public readonly fieldErrors: Record<string, string[]>;\r\n\r\n constructor(zodError: ZodError) {\r\n const message = `Validation failed: ${zodError.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`;\r\n super(message, 'NEXUS_INPUT_VALIDATION_ERROR');\r\n Object.setPrototypeOf(this, new.target.prototype);\r\n this.name = 'InputValidationError';\r\n this.fieldErrors = zodError.flatten().fieldErrors as Record<string, string[]>;\r\n }\r\n}\r\n","/**\n * @module services/context\n * @description Context Service - Aggregated context retrieval for Chat main flows.\n *\n * The Context Service is the primary entry point for AI agents to fetch\n * all relevant user context in a single call. It orchestrates parallel\n * retrieval across Memory (Mem0), Conversation (Zep), and Knowledge\n * (GraphRAG) layers.\n *\n * Based on Nexus API v2.0 - POST /context/retrieve\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type { ContextRequest, ContextRetrieveResponse } from '../types/context';\nimport { DEPTH_PRESETS } from '../types/context';\nimport { contextRequestSchema } from '../schemas/context';\nimport { InputValidationError } from '../errors/validation';\n\n/**\n * Service for aggregated context retrieval.\n *\n * This is the core API surface for Chat main flows. A single call to\n * {@link ContextService.retrieve} fetches user profile memories,\n * conversation history, and knowledge graph data in parallel.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * const context = await nexus.context.retrieve({\n * user_id: 'user_42',\n * query: 'What did we discuss about the project?',\n * layers: ['recent', 'semantic', 'graph'],\n * });\n *\n * console.log(context.profile?.memories);\n * console.log(context.history?.messages);\n * console.log(context.graph?.entities);\n * ```\n */\nexport class ContextService extends BaseService {\n /**\n * Retrieve aggregated context for a user across multiple layers.\n *\n * Performs v2.0 three-layer parallel retrieval:\n * - **recent**: Time-anchored activities from the activity stream\n * - **semantic**: Vector similarity search against Mem0 memory store\n * - **graph**: Knowledge graph traversal via Fast GraphRAG\n *\n * @param request - Context retrieval parameters including user_id, query, and layer configuration.\n * @returns Aggregated context containing profile, history, graph, and performance metadata.\n */\n async retrieve(request: ContextRequest, options?: RequestOptions): Promise<ContextRetrieveResponse> {\n // Resolve depth preset: preset values are the base, explicit caller fields win.\n let resolved: ContextRequest;\n if (request.depth !== undefined && DEPTH_PRESETS[request.depth]) {\n const { depth, ...rest } = request;\n resolved = { ...DEPTH_PRESETS[depth], ...rest };\n } else {\n const { depth: _depth, ...rest } = request;\n resolved = rest;\n }\n\n const parsed = contextRequestSchema.safeParse(resolved);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<ContextRetrieveResponse>('/context/retrieve', resolved, options?.signal);\n }\n}\n","import { z } from 'zod';\r\n\r\nconst memoryTypeSchema = z.enum(['episodic', 'semantic', 'procedural']);\r\n\r\nexport const memoryCreateSchema = z.object({\r\n user_id: z.string().min(1),\r\n content: z.string().min(1).max(10000),\r\n memory_type: memoryTypeSchema.optional(),\r\n metadata: z.record(z.unknown()).optional(),\r\n});\r\n\r\nexport const memoryUpdateSchema = z.object({\r\n content: z.string().optional(),\r\n memory_type: memoryTypeSchema.optional(),\r\n metadata: z.record(z.unknown()).optional(),\r\n});\r\n\r\nexport const memorySearchSchema = z.object({\r\n user_id: z.string().min(1),\r\n query: z.string().min(1),\r\n memory_type: memoryTypeSchema.optional(),\r\n limit: z.number().int().min(1).max(50).optional(),\r\n threshold: z.number().min(0).max(1).optional(),\r\n});\r\n","/**\n * @module services/memories\n * @description Memory Service - Long-term memory management with semantic retrieval.\n *\n * Wraps the Nexus Memory API powered by Mem0. Supports CRUD operations\n * on episodic, semantic, and procedural memories, vector similarity\n * search, and the Memory Journal view (US-015).\n *\n * Based on Nexus API v2.0 - /memories endpoints\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n Memory,\n MemoryCreate,\n MemoryUpdate,\n MemorySearch,\n MemorySearchResult,\n MemoryList,\n JournalResponse,\n MemoryType,\n} from '../types/memory';\nimport { memoryCreateSchema, memoryUpdateSchema, memorySearchSchema } from '../schemas/memory';\nimport { InputValidationError } from '../errors/validation';\n\n/**\n * Parameters for listing memories with optional filtering and pagination.\n */\nexport interface MemoryListParams {\n /** Filter memories by user ID */\n user_id?: string;\n /** Filter by memory type classification */\n memory_type?: MemoryType;\n /** Maximum number of results per page */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Parameters for the Memory Journal view (US-015).\n */\nexport interface MemoryJournalParams {\n /** Response format: markdown for display, json for programmatic use */\n format?: 'markdown' | 'json';\n /** Start date filter (ISO 8601 date, e.g. \"2026-01-01\") */\n start_date?: string;\n /** End date filter (ISO 8601 date, e.g. \"2026-01-31\") */\n end_date?: string;\n /** Filter journal entries by user ID */\n user_id?: string;\n}\n\n/**\n * Service for managing long-term memories via Mem0.\n *\n * Provides full CRUD operations, semantic search, and the chronological\n * Memory Journal view for reviewing memories over time.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Create a memory\n * const memory = await nexus.memories.create({\n * user_id: 'user_42',\n * content: 'User prefers dark mode',\n * memory_type: 'semantic',\n * });\n *\n * // Semantic search\n * const results = await nexus.memories.search({\n * user_id: 'user_42',\n * query: 'UI preferences',\n * });\n * ```\n */\nexport class MemoryService extends BaseService {\n /**\n * Create a new memory record.\n *\n * @param data - Memory creation payload including user_id, content, and optional type/metadata.\n * @returns The newly created memory with generated ID and timestamps.\n */\n async create(data: MemoryCreate, options?: RequestOptions): Promise<Memory> {\n const parsed = memoryCreateSchema.safeParse(data);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<Memory>('/memories', data, options?.signal);\n }\n\n /**\n * List memories with optional filtering and pagination.\n *\n * @param params - Optional filters for user_id, memory_type, and pagination controls.\n * @returns Paginated list of memory records.\n */\n async list(params?: MemoryListParams, options?: RequestOptions): Promise<MemoryList> {\n return this.http.get<MemoryList>('/memories', params as Record<string, unknown>, options?.signal);\n }\n\n /**\n * Retrieve a single memory by its ID.\n *\n * @param memoryId - UUID of the memory to retrieve.\n * @returns The memory record.\n * @throws {ApiError} 404 if the memory does not exist.\n */\n async get(memoryId: string, options?: RequestOptions): Promise<Memory> {\n return this.http.get<Memory>(`/memories/${memoryId}`, undefined, options?.signal);\n }\n\n /**\n * Update an existing memory record.\n *\n * Supports partial updates -- only the provided fields are modified.\n *\n * @param memoryId - UUID of the memory to update.\n * @param data - Fields to update (content, memory_type, metadata).\n * @returns The updated memory record.\n * @throws {ApiError} 404 if the memory does not exist.\n */\n async update(memoryId: string, data: MemoryUpdate, options?: RequestOptions): Promise<Memory> {\n const parsed = memoryUpdateSchema.safeParse(data);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.patch<Memory>(`/memories/${memoryId}`, data, options?.signal);\n }\n\n /**\n * Delete a memory record.\n *\n * @param memoryId - UUID of the memory to delete.\n * @throws {ApiError} 404 if the memory does not exist.\n */\n async delete(memoryId: string, options?: RequestOptions): Promise<void> {\n return this.http.delete<void>(`/memories/${memoryId}`, options?.signal);\n }\n\n /**\n * Perform semantic similarity search across memories.\n *\n * Uses Mem0's vector search to find memories relevant to the query text.\n * Results are ranked by similarity score and filtered by optional thresholds.\n *\n * @param request - Search parameters including user_id, query, and optional filters.\n * @returns Search results with scored memories and timing metadata.\n */\n async search(request: MemorySearch, options?: RequestOptions): Promise<MemorySearchResult> {\n const parsed = memorySearchSchema.safeParse(request);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<MemorySearchResult>('/memories/search', request, options?.signal);\n }\n\n /**\n * Retrieve the Memory Journal view (US-015).\n *\n * Groups memories chronologically by date for review. Supports both\n * markdown (human-readable) and JSON (programmatic) output formats.\n *\n * @param params - Optional filters for format, date range, and user_id.\n * @returns Journal response with memories grouped by date.\n */\n async journal(params?: MemoryJournalParams, options?: RequestOptions): Promise<JournalResponse> {\n return this.http.get<JournalResponse>('/memories/journal', params as Record<string, unknown>, options?.signal);\n }\n}\n","import { z } from 'zod';\r\n\r\nconst messageRoleSchema = z.enum(['user', 'assistant', 'system', 'tool']);\r\n\r\nexport const conversationCreateSchema = z.object({\r\n user_id: z.string().min(1),\r\n session_id: z.string().optional(),\r\n metadata: z.record(z.unknown()).optional(),\r\n});\r\n\r\nexport const messageCreateSchema = z.object({\r\n role: messageRoleSchema,\r\n content: z.string().min(1).max(50000),\r\n metadata: z.record(z.unknown()).optional(),\r\n});\r\n","/**\n * @module services/conversations\n * @description Conversation Service - Conversation history and auto-summary management.\n *\n * Wraps the Nexus Conversation API powered by Zep OSS. Supports\n * conversation lifecycle management, message operations, and\n * auto-generated summaries via temporal graph analysis.\n *\n * Based on Nexus API v2.0 - /conversations endpoints\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n Conversation,\n ConversationCreate,\n ConversationDetail,\n ConversationList,\n Message,\n MessageCreate,\n MessageList,\n ConversationSummary,\n} from '../types/conversation';\nimport { conversationCreateSchema, messageCreateSchema } from '../schemas/conversation';\nimport { InputValidationError } from '../errors/validation';\n\n/**\n * Parameters for listing conversations with optional filtering and pagination.\n */\nexport interface ConversationListParams {\n /** Filter conversations by user ID */\n user_id?: string;\n /** Maximum number of results per page */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Parameters for listing messages within a conversation.\n */\nexport interface MessageListParams {\n /** Maximum number of messages to return */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Service for managing conversations and messages via Zep OSS.\n *\n * Provides conversation lifecycle management (create, list, get, delete),\n * message operations (add, list), and access to auto-generated summaries\n * produced by Zep's temporal graph analysis.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Create a conversation\n * const conv = await nexus.conversations.create({\n * user_id: 'user_42',\n * metadata: { topic: 'project planning' },\n * });\n *\n * // Add a message\n * await nexus.conversations.addMessage(conv.id, {\n * role: 'user',\n * content: 'Let us discuss the roadmap.',\n * });\n *\n * // Get auto-generated summary\n * const summary = await nexus.conversations.getSummary(conv.id);\n * ```\n */\nexport class ConversationService extends BaseService {\n /**\n * Create a new conversation session.\n *\n * @param data - Conversation creation payload including user_id and optional metadata.\n * @returns The newly created conversation with generated ID and timestamps.\n */\n async create(data: ConversationCreate, options?: RequestOptions): Promise<Conversation> {\n const parsed = conversationCreateSchema.safeParse(data);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<Conversation>('/conversations', data, options?.signal);\n }\n\n /**\n * List conversations with optional filtering and pagination.\n *\n * @param params - Optional filters for user_id and pagination controls.\n * @returns Paginated list of conversation records.\n */\n async list(params?: ConversationListParams, options?: RequestOptions): Promise<ConversationList> {\n return this.http.get<ConversationList>('/conversations', params as Record<string, unknown>, options?.signal);\n }\n\n /**\n * Retrieve a conversation with its messages included.\n *\n * @param conversationId - UUID of the conversation to retrieve.\n * @returns Conversation detail including the full message list.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async get(conversationId: string, options?: RequestOptions): Promise<ConversationDetail> {\n return this.http.get<ConversationDetail>(`/conversations/${conversationId}`, undefined, options?.signal);\n }\n\n /**\n * Add a message to an existing conversation.\n *\n * The message is appended to the conversation's message sequence.\n * Zep will asynchronously update the conversation summary after\n * new messages are added.\n *\n * @param conversationId - UUID of the target conversation.\n * @param message - Message payload including role and content.\n * @returns The newly created message with generated ID and sequence number.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async addMessage(conversationId: string, message: MessageCreate, options?: RequestOptions): Promise<Message> {\n const parsed = messageCreateSchema.safeParse(message);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<Message>(`/conversations/${conversationId}/messages`, message, options?.signal);\n }\n\n /**\n * List messages within a conversation with optional pagination.\n *\n * Messages are returned in chronological order (oldest first).\n *\n * @param conversationId - UUID of the conversation.\n * @param params - Optional pagination controls (limit, offset).\n * @returns Paginated list of messages.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async getMessages(conversationId: string, params?: MessageListParams, options?: RequestOptions): Promise<MessageList> {\n return this.http.get<MessageList>(\n `/conversations/${conversationId}/messages`,\n params as Record<string, unknown>,\n options?.signal,\n );\n }\n\n /**\n * Retrieve the auto-generated summary of a conversation.\n *\n * Summaries are produced by Zep OSS temporal graph analysis and\n * include key points extracted from the conversation history.\n *\n * @param conversationId - UUID of the conversation.\n * @returns The conversation summary with key points and generation timestamp.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async getSummary(conversationId: string, options?: RequestOptions): Promise<ConversationSummary> {\n return this.http.get<ConversationSummary>(`/conversations/${conversationId}/summary`, undefined, options?.signal);\n }\n\n /**\n * Delete a conversation and all its messages.\n *\n * This operation is irreversible. The conversation, all associated\n * messages, and the generated summary will be permanently removed.\n *\n * @param conversationId - UUID of the conversation to delete.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async delete(conversationId: string, options?: RequestOptions): Promise<void> {\n return this.http.delete<void>(`/conversations/${conversationId}`, options?.signal);\n }\n}\n","import { z } from 'zod';\r\n\r\nexport const entityCreateSchema = z.object({\r\n name: z.string().min(1),\r\n entity_type: z.string().min(1),\r\n description: z.string().optional(),\r\n properties: z.record(z.unknown()).optional(),\r\n});\r\n\r\nexport const graphQueryRequestSchema = z.object({\r\n entity_name: z.string().min(1),\r\n depth: z.number().int().min(1).max(3).optional(),\r\n relationship_types: z.array(z.string()).optional(),\r\n});\r\n\r\nexport const extractionRequestSchema = z.object({\r\n text: z.string().min(1).max(10000),\r\n agent_id: z.string().optional(),\r\n owner_user_id: z.string().optional(),\r\n});\r\n","/**\n * @module services/knowledge\n * @description Knowledge Service - Knowledge graph construction and query.\n *\n * Wraps the Nexus Knowledge API powered by Fast GraphRAG. Supports\n * entity management, graph traversal queries (BFS), and automatic\n * entity/relationship extraction from unstructured text.\n *\n * Based on Nexus API v2.0 - /knowledge endpoints\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n KnowledgeEntity,\n ExtractionRequest,\n ExtractionResult,\n EntityListResponse,\n GraphQueryRequest,\n GraphQueryResponse,\n} from '../types/knowledge';\nimport { entityCreateSchema, graphQueryRequestSchema, extractionRequestSchema } from '../schemas/knowledge';\nimport { InputValidationError } from '../errors/validation';\n\n/**\n * Request payload for creating a new knowledge entity.\n *\n * POST /knowledge/entities\n */\nexport interface EntityCreate {\n /** Entity display name */\n name: string;\n /** Entity type classification (e.g., Person, Organization, Concept) */\n entity_type: string;\n /** Entity description */\n description?: string;\n /** Additional entity properties */\n properties?: Record<string, unknown>;\n}\n\n/**\n * Parameters for listing knowledge entities with optional filtering.\n */\nexport interface EntityListParams {\n /** Filter entities by user ID (owner) */\n user_id?: string;\n /** Filter by entity type classification */\n entity_type?: string;\n /** Maximum number of results to return */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Service for managing the knowledge graph via Fast GraphRAG.\n *\n * Provides entity CRUD, BFS graph traversal queries, and automatic\n * entity/relationship extraction from unstructured text. Supports\n * both public (agent-owned) and private (user-owned) knowledge.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Extract entities from text\n * const extraction = await nexus.knowledge.extract({\n * text: 'Alice works at Acme Corp on the Phoenix project.',\n * owner_user_id: 'user_42',\n * });\n *\n * // Query the graph\n * const graph = await nexus.knowledge.query({\n * entity_name: 'Alice',\n * depth: 2,\n * });\n *\n * console.log(graph.paths);\n * ```\n */\nexport class KnowledgeService extends BaseService {\n /**\n * Create a new knowledge entity in the graph.\n *\n * @param data - Entity creation payload including name, type, and optional description/properties.\n * @returns The newly created entity with generated entity_id.\n */\n async createEntity(data: EntityCreate, options?: RequestOptions): Promise<KnowledgeEntity> {\n const parsed = entityCreateSchema.safeParse(data);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<KnowledgeEntity>('/knowledge/entities', data, options?.signal);\n }\n\n /**\n * List knowledge entities with optional filtering.\n *\n * @param params - Optional filters for user_id, entity_type, and pagination controls.\n * @returns Paginated list of knowledge entities.\n */\n async listEntities(params?: EntityListParams, options?: RequestOptions): Promise<EntityListResponse> {\n return this.http.get<EntityListResponse>('/knowledge/entities', params as Record<string, unknown>, options?.signal);\n }\n\n /**\n * Query the knowledge graph using BFS traversal.\n *\n * Starts from a named entity and traverses outward up to the specified\n * depth, collecting all reachable entities and relationships along\n * the traversal paths.\n *\n * @param request - Graph query parameters including starting entity name, depth, and optional relationship type filters.\n * @returns Graph query response with the start entity, traversal paths, and total path count.\n */\n async query(request: GraphQueryRequest, options?: RequestOptions): Promise<GraphQueryResponse> {\n const parsed = graphQueryRequestSchema.safeParse(request);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<GraphQueryResponse>('/knowledge/query', request, options?.signal);\n }\n\n /**\n * Extract entities and relationships from unstructured text.\n *\n * Uses Fast GraphRAG's NLP pipeline to identify named entities and\n * their relationships in Triplex format (Subject, Relation, Object).\n * Extracted items are automatically persisted to the knowledge graph.\n *\n * @param request - Extraction request including the source text and ownership (agent_id or owner_user_id).\n * @returns Extraction result with lists of created entities and relationships.\n */\n async extract(request: ExtractionRequest, options?: RequestOptions): Promise<ExtractionResult> {\n const parsed = extractionRequestSchema.safeParse(request);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<ExtractionResult>('/knowledge/extract', request, options?.signal);\n }\n}\n","/**\n * @module services/activities\n * @description Activity stream service for passive memory ingestion.\n *\n * AI Agents report their actions (file edits, test runs, API calls, etc.)\n * through the activity stream. These activities are asynchronously converted\n * into semantic memories by the Nexus backend (Arq workers).\n *\n * @see {@link https://docs.nexus.10cg.pub/api/activities | Activity API Reference}\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n Activity,\n ActivityStreamRequest,\n ActivityStreamResponse,\n} from '../types/activity';\n\n/**\n * Service for ingesting activity streams from AI Agents.\n *\n * Activities are the primary mechanism for **passive memory** collection:\n * agents report what they do, and Nexus converts those actions into\n * searchable, contextual memories in the background.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_live_...' });\n *\n * // Log a single activity\n * await nexus.activities.log({\n * action: 'edit_file',\n * activity_data: { path: 'src/index.ts', lines_changed: 42 },\n * });\n *\n * // Batch-ingest multiple activities\n * await nexus.activities.stream({\n * agent_id: 'cursor-agent',\n * activities: [\n * { action: 'read_file', activity_data: { path: 'README.md' } },\n * { action: 'edit_file', activity_data: { path: 'src/app.ts' } },\n * ],\n * });\n * ```\n */\nexport class ActivityService extends BaseService {\n /**\n * Batch-ingest an activity stream.\n *\n * Accepts up to 1000 activities per request. Activities are queued for\n * asynchronous processing by Arq workers on the Nexus backend.\n *\n * @param request - The activity stream payload containing agent ID and activities.\n * @returns Processing summary with accepted / processed / queued counts.\n */\n async stream(request: ActivityStreamRequest, options?: RequestOptions): Promise<ActivityStreamResponse> {\n return this.http.post<ActivityStreamResponse>('/activities/stream', request, options?.signal);\n }\n\n /**\n * Convenience method to log a single activity.\n *\n * Wraps {@link stream} for the common case of reporting one event at a time.\n *\n * @param activity - The activity event to record.\n * @param agentId - Agent identifier (defaults to `'default'`).\n * @returns Processing summary with accepted / processed / queued counts.\n */\n async log(activity: Activity, agentId?: string, options?: RequestOptions): Promise<ActivityStreamResponse> {\n return this.stream({\n agent_id: agentId || 'default',\n activities: [activity],\n }, options);\n }\n}\n","/**\n * @module services/tenants\n * @description Tenant management service for the Nexus platform.\n *\n * Provides access to the current tenant's profile, quota configuration,\n * and usage statistics. Tenant identity is derived from the API key\n * used to authenticate requests.\n *\n * @see {@link https://docs.nexus.10cg.pub/api/tenants | Tenant API Reference}\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type { Tenant, TenantUsage, ApiKey, ApiKeyCreate, ApiKeyCreated } from '../types/tenant';\n\n/**\n * Service for managing the current tenant's profile and usage.\n *\n * The tenant is automatically identified by the API key provided\n * to the {@link NexusClient}. All methods operate on the\n * authenticated tenant's data.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_live_...' });\n *\n * // Get tenant profile\n * const tenant = await nexus.tenants.me();\n * console.log(`Tenant: ${tenant.name} (${tenant.tier})`);\n *\n * // Check resource usage\n * const usage = await nexus.tenants.usage();\n * console.log(`Memories: ${usage.memories_count}`);\n * ```\n */\nexport class TenantService extends BaseService {\n /**\n * Retrieve the current tenant's profile.\n *\n * Returns the tenant record associated with the API key,\n * including name, tier, quotas, and current usage snapshot.\n *\n * @returns The authenticated tenant's profile.\n */\n async me(options?: RequestOptions): Promise<Tenant> {\n return this.http.get<Tenant>('/tenants/me', undefined, options?.signal);\n }\n\n /**\n * Retrieve the current tenant's resource usage statistics.\n *\n * Returns counts for memories, conversations, and today's API calls.\n * Useful for monitoring quota consumption and building dashboards.\n *\n * @returns Current resource usage for the authenticated tenant.\n */\n async usage(options?: RequestOptions): Promise<TenantUsage> {\n return this.http.get<TenantUsage>('/tenants/me/usage', undefined, options?.signal);\n }\n\n /**\n * List all API keys for the current tenant.\n *\n * @returns Array of API key records (without full key values).\n */\n async listApiKeys(options?: RequestOptions): Promise<ApiKey[]> {\n return this.http.get<ApiKey[]>('/tenants/me/api-keys', undefined, options?.signal);\n }\n\n /**\n * Create a new API key for the current tenant.\n *\n * @param data - API key creation parameters (name, scopes, expiry).\n * @returns The newly created API key, including the full key value (shown only once).\n */\n async createApiKey(data: ApiKeyCreate, options?: RequestOptions): Promise<ApiKeyCreated> {\n return this.http.post<ApiKeyCreated>('/tenants/me/api-keys', data, options?.signal);\n }\n\n /**\n * Revoke (delete) an API key.\n *\n * @param id - The UUID of the API key to revoke.\n */\n async revokeApiKey(id: string, options?: RequestOptions): Promise<void> {\n return this.http.delete<void>(`/tenants/me/api-keys/${id}`, options?.signal);\n }\n}\n","/**\n * @module services/feedback\n * @description Feedback Service — submit and query context-retrieval feedback.\n *\n * Wraps the Nexus Feedback Loop API (v5.0):\n * - PUT /v1/feedback/{retrieve_id} — submit an explicit rating (L2 signal)\n * - GET /v1/feedback — list feedback records for reporting\n *\n * The `retrieve_id` in each submission links back to a prior\n * `/context/retrieve` response, enabling the quality scoring pipeline to\n * correlate explicit feedback with L0 telemetry.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Submit feedback after a context retrieval\n * const result = await nexus.feedback.submit('retrieve-uuid', {\n * rating: 4,\n * item_feedback: [{ memory_id: 'mem-uuid', useful: true }],\n * });\n *\n * // List recent feedback\n * const list = await nexus.feedback.list({ user_id: 'user_42', limit: 20 });\n * ```\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n FeedbackSubmitRequest,\n FeedbackResponse,\n FeedbackListResponse,\n} from '../types/feedback';\n\n/**\n * Query parameters for listing feedback records.\n */\nexport interface FeedbackListParams {\n /** Filter feedback records by user ID. */\n user_id?: string;\n /** Maximum number of records to return. */\n limit?: number;\n /** Zero-based offset for pagination. */\n offset?: number;\n}\n\n/**\n * Service for submitting and querying context-retrieval feedback.\n *\n * Exposes the Nexus Feedback Loop v5.0 endpoints. Feedback submissions\n * are processed asynchronously by the QualityScoreWorker and feed into\n * memory re-ranking.\n */\nexport class FeedbackService extends BaseService {\n /**\n * Submit explicit feedback for a prior context retrieval (L2 signal).\n *\n * The backend accepts the submission immediately (HTTP 202) and processes\n * quality scoring asynchronously via QualityScoreWorker.\n *\n * @param retrieveId - The `retrieve_id` returned by `/context/retrieve`.\n * @param data - Rating and optional per-item feedback.\n * @param options - Optional request options (e.g. AbortSignal).\n * @returns The created feedback record metadata.\n */\n async submit(\n retrieveId: string,\n data: FeedbackSubmitRequest,\n options?: RequestOptions,\n ): Promise<FeedbackResponse> {\n return this.http.put<FeedbackResponse>(\n `/feedback/${retrieveId}`,\n data,\n options?.signal,\n );\n }\n\n /**\n * List feedback records with optional filtering and pagination.\n *\n * @param params - Optional filters: `user_id`, `limit`, `offset`.\n * @param options - Optional request options (e.g. AbortSignal).\n * @returns Paginated list of feedback records.\n */\n async list(\n params?: FeedbackListParams,\n options?: RequestOptions,\n ): Promise<FeedbackListResponse> {\n const query = new URLSearchParams();\n if (params?.user_id) query.set('user_id', params.user_id);\n if (params?.limit !== undefined) query.set('limit', String(params.limit));\n if (params?.offset !== undefined) query.set('offset', String(params.offset));\n const qs = query.toString();\n return this.http.get<FeedbackListResponse>(\n `/feedback${qs ? `?${qs}` : ''}`,\n undefined,\n options?.signal,\n );\n }\n}\n","/**\n * @module services/errors\n * @description Error Reporting Service — submit structured error reports.\n *\n * Wraps the Nexus Error Reporting API (US-031):\n * - POST /v1/errors — submit a structured error/bug report\n *\n * Errors are automatically deduplicated server-side by fingerprint\n * (SHA256 of error_type + endpoint + status_code).\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Manual error report\n * const report = await nexus.errors.submit({\n * error_type: 'api_error',\n * severity: 'major',\n * description: 'Context retrieval returned empty despite known data',\n * retrieve_id: 'uuid-from-retrieve-call',\n * });\n * ```\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type { ErrorReportRequest, ErrorReportResponse } from '../types/error';\n\n/**\n * Service for submitting structured error reports.\n *\n * Reports are deduplicated server-side: repeated submissions with the\n * same fingerprint increment `occurrence_count` instead of creating\n * new records.\n */\nexport class ErrorService extends BaseService {\n /**\n * Submit a structured error report.\n *\n * @param data - Error report payload.\n * @param options - Optional request options (e.g. AbortSignal).\n * @returns The created or updated error report metadata.\n */\n async submit(\n data: ErrorReportRequest,\n options?: RequestOptions,\n ): Promise<ErrorReportResponse> {\n return this.http.post<ErrorReportResponse>(\n '/errors',\n data,\n options?.signal,\n );\n }\n}\n","/**\n * @module client\n * @description Main entry point for the Nexus SDK.\n *\n * The {@link NexusClient} class is the single object that SDK consumers\n * instantiate. It resolves configuration, creates a shared HTTP transport,\n * and exposes every domain service as a readonly property.\n */\n\nimport { resolveConfig } from './config';\nimport type { NexusConfig } from './config';\nimport { HttpClient } from './http';\nimport { OfflineQueue } from './http/queue';\nimport { ContextService } from './services/context';\nimport { MemoryService } from './services/memories';\nimport { ConversationService } from './services/conversations';\nimport { KnowledgeService } from './services/knowledge';\nimport { ActivityService } from './services/activities';\nimport { TenantService } from './services/tenants';\nimport { FeedbackService } from './services/feedback';\nimport { ErrorService } from './services/errors';\n\n/**\n * Nexus AI Cognitive Services SDK client.\n *\n * Create a single instance and use the service properties to interact\n * with the Nexus platform.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({\n * apiKey: process.env.NEXUS_API_KEY!,\n * });\n *\n * // Aggregated context retrieval (Chat main flow)\n * const ctx = await nexus.context.retrieve({\n * user_id: 'user123',\n * query: '用户偏好',\n * });\n *\n * // Memory search\n * const memories = await nexus.memories.search({\n * user_id: 'user123',\n * query: 'favourite colour',\n * });\n * ```\n */\nexport class NexusClient {\n /** Aggregated context retrieval (Chat main flow). */\n public readonly context: ContextService;\n\n /** Memory CRUD, search, and journal. */\n public readonly memories: MemoryService;\n\n /** Conversation lifecycle and messages. */\n public readonly conversations: ConversationService;\n\n /** Knowledge graph entities and queries. */\n public readonly knowledge: KnowledgeService;\n\n /** Activity stream ingestion for passive memory. */\n public readonly activities: ActivityService;\n\n /** Tenant profile and usage management. */\n public readonly tenants: TenantService;\n\n /** Feedback loop — submit ratings and query feedback records (v5.0). */\n public readonly feedback: FeedbackService;\n\n /** Error reporting — submit structured error reports (US-031). */\n public readonly errors: ErrorService;\n\n /** @internal Shared HTTP transport. */\n private readonly http: HttpClient;\n\n /**\n * Create a new Nexus SDK client.\n *\n * @param config - SDK configuration. Only `apiKey` is required; all other\n * fields fall back to sensible defaults (see {@link resolveConfig}).\n *\n * @throws {Error} If `apiKey` is missing or empty.\n */\n constructor(config: NexusConfig) {\n const resolved = resolveConfig(config);\n this.http = new HttpClient(resolved);\n\n this.context = new ContextService(this.http);\n this.memories = new MemoryService(this.http);\n this.conversations = new ConversationService(this.http);\n this.knowledge = new KnowledgeService(this.http);\n this.activities = new ActivityService(this.http);\n this.tenants = new TenantService(this.http);\n this.feedback = new FeedbackService(this.http);\n this.errors = new ErrorService(this.http);\n\n // Wire up auto error reporting if enabled.\n if (resolved.autoErrorReport) {\n this.http.onApiError = (statusCode, method, url, detail) => {\n this.errors\n .submit({\n error_type: 'api_error',\n severity: statusCode >= 500 ? 'major' : 'minor',\n description: `${method} ${url} → ${statusCode}: ${detail}`,\n request_context: { method, url, status_code: statusCode },\n })\n .catch(() => {\n // Fire-and-forget: never propagate auto-report failures.\n });\n };\n }\n }\n\n /**\n * Access the offline queue instance (if offline mode is enabled).\n */\n get queue(): OfflineQueue | undefined {\n return this.http.queue;\n }\n\n /**\n * Set the online/offline status of the client.\n *\n * When transitioning from offline to online, queued requests are\n * automatically flushed.\n */\n setOnline(online: boolean): void {\n this.http.setOnline(online);\n }\n}\n","import { z } from 'zod';\r\n\r\nconst apiKeyScopeSchema = z.enum(['read', 'write', 'admin']);\r\n\r\nexport const apiKeyCreateSchema = z.object({\r\n name: z.string().min(1).max(100),\r\n scopes: z.array(apiKeyScopeSchema).optional(),\r\n expires_days: z.number().int().min(1).max(365).optional(),\r\n});\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqHA,IAAM,gBAAqC;AAAA,EACzC,KAAK;AAAA,EACL,KAAK;AAAA;AACP;AAGA,IAAM,gBAAqC;AAAA,EACzC,YAAY;AAAA,EACZ,cAAc;AAAA,EACd,UAAU;AAAA,EACV,eAAe;AACjB;AAOO,IAAM,iBAAiB;AAAA,EAC5B,SAAS;AAAA,EACT,SAAS;AAAA;A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UAAU,KAAK,MAAM;AAAA,UACxD,iBAAiB,EAAE,QAAQ,KAAK,aAAa,WAAW;AAAA,QAC1D,CAAC,EACA,MAAM,MAAM;AAAA,QAEb,CAAC;AAAA,MACL;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,QAAkC;AACpC,WAAO,KAAK,KAAK;AAAA,EACnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,UAAU,QAAuB;AAC/B,SAAK,KAAK,UAAU,MAAM;AAAA,EAC5B;AACF;;;ACjIA,IAAAC,cAAkB;AAElB,IAAM,oBAAoB,cAAE,KAAK,CAAC,QAAQ,SAAS,OAAO,CAAC;AAEpD,IAAM,qBAAqB,cAAE,OAAO;AAAA,EACzC,MAAM,cAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG;AAAA,EAC/B,QAAQ,cAAE,MAAM,iBAAiB,EAAE,SAAS;AAAA,EAC5C,cAAc,cAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS;AAC1D,CAAC;","names":["axios","result","import_zod","import_zod","import_zod","import_zod"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/config.ts","../src/http/client.ts","../src/errors/base.ts","../src/errors/api.ts","../src/http/cache.ts","../src/http/retry.ts","../src/http/queue.ts","../src/services/base.ts","../src/types/context.ts","../src/schemas/context.ts","../src/errors/validation.ts","../src/services/context.ts","../src/schemas/memory.ts","../src/services/memories.ts","../src/schemas/conversation.ts","../src/services/conversations.ts","../src/schemas/knowledge.ts","../src/services/knowledge.ts","../src/services/activities.ts","../src/services/tenants.ts","../src/services/feedback.ts","../src/services/errors.ts","../src/client.ts","../src/schemas/tenant.ts"],"sourcesContent":["/**\n * @nexusm/sdk - Nexus AI Cognitive Services SDK\n *\n * Unified entry point that re-exports the public API surface:\n * - {@link NexusClient} - Main client class (primary entry point)\n * - Service classes - For advanced / standalone usage\n * - Configuration helpers and types\n * - Error hierarchy\n * - Domain type definitions\n *\n * @example\n * ```typescript\n * import { NexusClient } from '@nexusm/sdk';\n *\n * const nexus = new NexusClient({\n * apiKey: process.env.NEXUS_API_KEY!,\n * });\n *\n * const ctx = await nexus.context.retrieve({\n * user_id: 'user123',\n * query: '用户偏好',\n * });\n * ```\n */\n\n// ---------------------------------------------------------------------------\n// Main client\n// ---------------------------------------------------------------------------\nexport { NexusClient } from './client';\n\n// ---------------------------------------------------------------------------\n// Configuration\n// ---------------------------------------------------------------------------\nexport { resolveConfig, DEFAULT_CONFIG } from './config';\nexport type {\n NexusConfig,\n ResolvedConfig,\n CacheConfig,\n RetryConfig,\n ResolvedCacheConfig,\n ResolvedRetryConfig,\n} from './config';\n\n// ---------------------------------------------------------------------------\n// Services (for advanced / standalone usage)\n// ---------------------------------------------------------------------------\nexport { ContextService } from './services/context';\nexport { MemoryService } from './services/memories';\nexport { ConversationService } from './services/conversations';\nexport { KnowledgeService } from './services/knowledge';\nexport { ActivityService } from './services/activities';\nexport { TenantService } from './services/tenants';\nexport { FeedbackService } from './services/feedback';\nexport { ErrorService } from './services/errors';\n\n// Service parameter types (defined in service files)\nexport type { MemoryListParams, MemoryJournalParams } from './services/memories';\nexport type { ConversationListParams, MessageListParams } from './services/conversations';\nexport type { EntityCreate, EntityListParams } from './services/knowledge';\nexport type { FeedbackListParams } from './services/feedback';\nexport type { RequestOptions } from './services/base';\n\n// ---------------------------------------------------------------------------\n// Errors\n// ---------------------------------------------------------------------------\nexport {\n NexusError,\n ConfigurationError,\n NetworkError,\n TimeoutError,\n} from './errors';\nexport {\n ApiError,\n AuthenticationError,\n RateLimitError,\n ValidationError,\n NotFoundError,\n InputValidationError,\n} from './errors';\n\n// ---------------------------------------------------------------------------\n// Types\n//\n// Note: The `ApiError` interface from `./types` is intentionally excluded\n// to avoid a naming collision with the `ApiError` class from `./errors`.\n// Consumers who need the raw API error *shape* can import `ApiErrorDetail`\n// instead, or import `ApiError` directly from `@nexusm/sdk/types`.\n// ---------------------------------------------------------------------------\n\n// Common types (excluding ApiError to avoid collision with errors/ApiError class)\nexport type {\n Pagination,\n PaginatedResponse,\n ApiResponse,\n ApiErrorDetail,\n HealthResponse,\n HealthStatus,\n ServiceStatus,\n CompoundId,\n SortOrder,\n OfflineConfig,\n} from './types';\n\n// Context types\nexport type {\n ContextLayer,\n ContextDepth,\n ContextDepthPreset,\n ContextRequest,\n ContextMemory,\n ContextProfile,\n ContextMessage,\n ContextHistory,\n ContextEntity,\n ContextRelation,\n ContextGraph,\n ContextMeta,\n ContextRetrieveResponse,\n OwnerType,\n} from './types';\nexport { DEPTH_PRESETS } from './types';\n\n// Memory types\nexport type {\n Memory,\n MemoryCreate,\n MemoryUpdate,\n MemorySearch,\n MemorySearchResult,\n MemoryList,\n JournalEntry,\n JournalResponse,\n MemoryType,\n} from './types';\n\n// Conversation types\nexport type {\n Conversation,\n ConversationCreate,\n ConversationDetail,\n ConversationList,\n Message,\n MessageCreate,\n MessageList,\n ConversationSummary,\n MessageRole,\n ConversationStatus,\n} from './types';\n\n// Knowledge types\nexport type {\n KnowledgeEntity,\n KnowledgeRelationship,\n ExtractionRequest,\n ExtractionResult,\n EntityListResponse,\n GraphQueryRequest,\n GraphPathEntity,\n GraphPathRelationship,\n GraphPath,\n GraphQueryResponse,\n} from './types';\n\n// Activity types\nexport type {\n Activity,\n ActivityStreamRequest,\n ActivityStreamResponse,\n ActivityStatusResponse,\n ActivityStats,\n ActivityType,\n ActivityProcessingStatus,\n} from './types';\n\n// Tenant types\nexport type {\n Tenant,\n TenantQuotas,\n TenantUsage,\n ApiKey,\n ApiKeyCreate,\n ApiKeyCreated,\n UsageStats,\n TenantTier,\n ApiKeyScope,\n} from './types';\n\n// Feedback types\nexport type {\n FeedbackItemRequest,\n FeedbackSubmitRequest,\n FeedbackResponse,\n FeedbackListItem,\n FeedbackListResponse,\n} from './types';\n\n// Error reporting types\nexport type {\n ErrorType,\n ErrorSeverity,\n ErrorReportRequest,\n ErrorReportResponse,\n} from './types';\n\n// ---------------------------------------------------------------------------\n// HTTP utilities\n// ---------------------------------------------------------------------------\nexport { OfflineQueue } from './http';\nexport type { QueuedRequest } from './http';\n\n// ---------------------------------------------------------------------------\n// Zod Schemas (runtime validation)\n// ---------------------------------------------------------------------------\nexport {\n contextRequestSchema,\n memoryCreateSchema,\n memoryUpdateSchema,\n memorySearchSchema,\n conversationCreateSchema,\n messageCreateSchema,\n entityCreateSchema,\n graphQueryRequestSchema,\n extractionRequestSchema,\n apiKeyCreateSchema,\n} from './schemas';\n","/**\n * @module config\n * @description Configuration management for the Nexus SDK.\n *\n * Provides sensible defaults, deep-merges user overrides, and exposes a\n * fully-resolved configuration object where every field is guaranteed to\n * be present.\n */\n\nimport type { OfflineConfig } from './types/common';\n\n// ---------------------------------------------------------------------------\n// Public configuration interfaces\n// ---------------------------------------------------------------------------\n\n/** Cache layer configuration. */\nexport interface CacheConfig {\n /** Maximum number of entries in the LRU cache. */\n max?: number;\n /** Time-to-live for cached entries, in **seconds**. */\n ttl?: number;\n}\n\n/** Automatic retry configuration with exponential back-off. */\nexport interface RetryConfig {\n /** Maximum number of retry attempts (excluding the initial request). */\n maxRetries?: number;\n /** Delay before the first retry, in **milliseconds**. */\n initialDelay?: number;\n /** Upper bound for the retry delay, in **milliseconds**. */\n maxDelay?: number;\n /** Multiplier applied to the delay after each attempt. */\n backoffFactor?: number;\n}\n\n/**\n * User-facing SDK configuration.\n *\n * Only `apiKey` is strictly required; every other field falls back to a\n * sensible default (see {@link DEFAULT_CONFIG}).\n */\nexport interface NexusConfig {\n /** API key used for authentication. */\n apiKey: string;\n /**\n * Tenant identifier for multi-tenant isolation.\n * When provided, it is sent as the `X-Tenant-ID` header on every request.\n */\n tenantId?: string;\n /** Base URL of the Nexus API (without trailing slash). */\n baseUrl?: string;\n /** Request timeout in **milliseconds**. */\n timeout?: number;\n /** LRU cache settings. Pass `false` to disable caching entirely. */\n cache?: CacheConfig | false;\n /** Retry behaviour. Pass `false` to disable retries entirely. */\n retry?: RetryConfig | false;\n /** Offline queue configuration. */\n offline?: OfflineConfig;\n /**\n * Automatically report HTTP 4xx/5xx errors to the Nexus error tracking API.\n * Defaults to `false`. When enabled, failed API responses are submitted to\n * `POST /v1/errors` in the background (fire-and-forget).\n */\n autoErrorReport?: boolean;\n}\n\n/** Fully-resolved cache configuration (all fields required). */\nexport interface ResolvedCacheConfig {\n /** Maximum number of entries in the LRU cache. */\n max: number;\n /** Time-to-live for cached entries, in **seconds**. */\n ttl: number;\n}\n\n/** Fully-resolved retry configuration (all fields required). */\nexport interface ResolvedRetryConfig {\n /** Maximum number of retry attempts. */\n maxRetries: number;\n /** Delay before the first retry, in **milliseconds**. */\n initialDelay: number;\n /** Upper bound for the retry delay, in **milliseconds**. */\n maxDelay: number;\n /** Multiplier applied to the delay after each attempt. */\n backoffFactor: number;\n}\n\n/**\n * Fully-resolved SDK configuration.\n *\n * Every field is guaranteed to be present after calling\n * {@link resolveConfig}.\n */\nexport interface ResolvedConfig {\n /** API key used for authentication. */\n apiKey: string;\n /** Tenant identifier (may be `undefined` if not provided). */\n tenantId?: string;\n /** Base URL of the Nexus API (without trailing slash). */\n baseUrl: string;\n /** Request timeout in **milliseconds**. */\n timeout: number;\n /** Resolved cache settings, or `false` if caching is disabled. */\n cache: ResolvedCacheConfig | false;\n /** Resolved retry settings, or `false` if retries are disabled. */\n retry: ResolvedRetryConfig | false;\n /** Offline queue configuration (undefined if not provided). */\n offline?: OfflineConfig;\n /** Whether to auto-report HTTP 4xx/5xx errors. */\n autoErrorReport: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Defaults\n// ---------------------------------------------------------------------------\n\n/** @internal Default cache configuration. */\nconst DEFAULT_CACHE: ResolvedCacheConfig = {\n max: 1000,\n ttl: 300, // 5 minutes\n};\n\n/** @internal Default retry configuration. */\nconst DEFAULT_RETRY: ResolvedRetryConfig = {\n maxRetries: 3,\n initialDelay: 1000,\n maxDelay: 10_000,\n backoffFactor: 2,\n};\n\n/**\n * Default SDK configuration values.\n *\n * These are used as the base when merging user-provided overrides.\n */\nexport const DEFAULT_CONFIG = {\n baseUrl: 'http://localhost:8001/v1',\n timeout: 30_000, // 30 seconds\n cache: DEFAULT_CACHE,\n retry: DEFAULT_RETRY,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Resolver\n// ---------------------------------------------------------------------------\n\n/**\n * Deep-merge user configuration with defaults and return a fully-resolved\n * configuration object.\n *\n * @param userConfig - Partial configuration provided by the SDK consumer.\n * @returns A {@link ResolvedConfig} with every field populated.\n *\n * @throws {Error} If `apiKey` is missing or empty.\n *\n * @example\n * ```typescript\n * const resolved = resolveConfig({\n * apiKey: 'sk-...',\n * timeout: 5000,\n * retry: { maxRetries: 5 },\n * });\n *\n * resolved.timeout; // 5000\n * resolved.retry.maxRetries; // 5\n * resolved.retry.initialDelay; // 1000 (default)\n * ```\n */\nexport function resolveConfig(userConfig: NexusConfig): ResolvedConfig {\n if (!userConfig.apiKey) {\n throw new Error(\n 'NexusConfig: \"apiKey\" is required and must be a non-empty string.',\n );\n }\n\n // -- Cache: honour explicit `false` to disable --\n let cache: ResolvedCacheConfig | false;\n if (userConfig.cache === false) {\n cache = false;\n } else if (userConfig.cache) {\n cache = { ...DEFAULT_CACHE, ...userConfig.cache };\n } else {\n cache = { ...DEFAULT_CACHE };\n }\n\n // -- Retry: honour explicit `false` to disable --\n let retry: ResolvedRetryConfig | false;\n if (userConfig.retry === false) {\n retry = false;\n } else if (userConfig.retry) {\n retry = { ...DEFAULT_RETRY, ...userConfig.retry };\n } else {\n retry = { ...DEFAULT_RETRY };\n }\n\n // -- Strip trailing slash from baseUrl --\n const rawBaseUrl = userConfig.baseUrl ?? DEFAULT_CONFIG.baseUrl;\n const baseUrl = rawBaseUrl.replace(/\\/+$/, '');\n\n return {\n apiKey: userConfig.apiKey,\n tenantId: userConfig.tenantId,\n baseUrl,\n timeout: userConfig.timeout ?? DEFAULT_CONFIG.timeout,\n cache,\n retry,\n offline: userConfig.offline,\n autoErrorReport: userConfig.autoErrorReport ?? false,\n };\n}\n","/**\n * @module http/client\n * @description Low-level HTTP client for the Nexus SDK.\n *\n * Wraps an Axios instance with automatic authentication headers,\n * request/response interceptors, and error normalisation so that\n * every failure surfaces as a typed {@link NexusError} subclass.\n */\n\nimport axios, { type AxiosInstance, type AxiosError } from 'axios';\n\nimport type { ResolvedConfig } from '../config';\nimport { NetworkError, TimeoutError } from '../errors/base';\nimport { ApiError } from '../errors/api';\nimport { CacheManager, isCacheablePost } from './cache';\nimport { RetryManager } from './retry';\nimport { OfflineQueue } from './queue';\n\n/**\n * HTTP client that communicates with the Nexus API.\n *\n * All service-level modules (Memory, Conversation, Knowledge, Context)\n * delegate their network calls to a shared `HttpClient` instance, which\n * guarantees consistent authentication, timeout handling, and error\n * mapping across the entire SDK surface.\n *\n * @example\n * ```typescript\n * import { resolveConfig } from '../config';\n * import { HttpClient } from './client';\n *\n * const config = resolveConfig({ apiKey: 'nx_test_abc123' });\n * const http = new HttpClient(config);\n *\n * const memories = await http.get<Memory[]>('/memory/search', { query: 'hello' });\n * ```\n */\nexport class HttpClient {\n /** Underlying Axios instance. */\n private readonly axios: AxiosInstance;\n\n /** Fully-resolved SDK configuration snapshot. */\n private readonly config: ResolvedConfig;\n\n /** LRU cache for read requests. */\n private readonly cache: CacheManager;\n\n /** Retry manager for transient failures. */\n private readonly retry: RetryManager;\n\n /** Offline request queue (only created when offline config is provided). */\n private readonly offlineQueue?: OfflineQueue;\n\n /** Whether the client is currently considered online. */\n private _isOnline: boolean = true;\n\n /**\n * Optional callback to auto-report API errors to POST /v1/errors.\n * Set by NexusClient after ErrorService is initialized.\n * @internal\n */\n public onApiError?: (\n statusCode: number,\n method: string,\n url: string,\n detail: string,\n ) => void;\n\n /**\n * Create a new HTTP client.\n *\n * @param config - Fully-resolved SDK configuration (see {@link resolveConfig}).\n */\n constructor(config: ResolvedConfig) {\n this.config = config;\n this.cache = new CacheManager(config.cache);\n this.retry = new RetryManager(config.retry);\n\n if (config.offline?.enabled) {\n this.offlineQueue = new OfflineQueue(config.offline.maxQueueSize ?? 100);\n }\n\n this.axios = axios.create({\n baseURL: config.baseUrl,\n timeout: config.timeout,\n });\n\n this.setupRequestInterceptor();\n this.setupResponseInterceptor();\n }\n\n // -----------------------------------------------------------------------\n // Offline queue support\n // -----------------------------------------------------------------------\n\n /**\n * Set the online/offline status of the client.\n *\n * When transitioning from offline to online, the queued requests are\n * automatically flushed.\n *\n * @param online - `true` if the client is online, `false` if offline.\n */\n setOnline(online: boolean): void {\n const wasOffline = !this._isOnline;\n this._isOnline = online;\n\n if (wasOffline && online && this.offlineQueue) {\n void this.offlineQueue.flush(async (req) => {\n switch (req.method) {\n case 'POST':\n return this.post(req.path, req.data);\n case 'PUT':\n return this.put(req.path, req.data);\n case 'PATCH':\n return this.patch(req.path, req.data);\n case 'DELETE':\n return this.delete(req.path);\n default:\n return this.get(req.path);\n }\n });\n }\n }\n\n /**\n * Access the offline queue instance (if offline mode is enabled).\n */\n get queue(): OfflineQueue | undefined {\n return this.offlineQueue;\n }\n\n // -----------------------------------------------------------------------\n // Public request methods\n // -----------------------------------------------------------------------\n\n /**\n * Send a GET request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL (e.g. `/memory/search`).\n * @param params - Optional query parameters.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async get<T>(\n path: string,\n params?: Record<string, unknown>,\n signal?: AbortSignal,\n ): Promise<T> {\n const cacheKey = this.cache.generateKey('GET', path, params);\n const cached = this.cache.get<T>(cacheKey);\n if (cached !== undefined) return cached;\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.get<T>(path, { params, signal });\n return response.data;\n });\n this.cache.set(cacheKey, result);\n return result;\n }\n\n /**\n * Send a POST request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL.\n * @param data - Optional request body.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async post<T>(\n path: string,\n data?: unknown,\n signal?: AbortSignal,\n ): Promise<T> {\n // Offline queue: enqueue write requests when offline\n if (this.offlineQueue && !this._isOnline) {\n return this.offlineQueue.enqueue<T>({ method: 'POST', path, data });\n }\n\n // Cacheable POST endpoints (read-only semantics)\n if (isCacheablePost(path)) {\n const cacheKey = this.cache.generateKey('POST', path, data);\n const cached = this.cache.get<T>(cacheKey);\n if (cached !== undefined) return cached;\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.post<T>(path, data, { signal });\n return response.data;\n });\n this.cache.set(cacheKey, result);\n return result;\n }\n\n // Write POST: execute + invalidate related cache\n const result = await this.retry.execute(async () => {\n const response = await this.axios.post<T>(path, data, { signal });\n return response.data;\n });\n this.cache.invalidate(path.split('/').filter(Boolean)[0] ?? path);\n return result;\n }\n\n /**\n * Send a PUT request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL.\n * @param data - Optional request body.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async put<T>(\n path: string,\n data?: unknown,\n signal?: AbortSignal,\n ): Promise<T> {\n if (this.offlineQueue && !this._isOnline) {\n return this.offlineQueue.enqueue<T>({ method: 'PUT', path, data });\n }\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.put<T>(path, data, { signal });\n return response.data;\n });\n this.cache.invalidate(path.split('/').filter(Boolean)[0] ?? path);\n return result;\n }\n\n /**\n * Send a PATCH request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL.\n * @param data - Optional request body.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async patch<T>(\n path: string,\n data?: unknown,\n signal?: AbortSignal,\n ): Promise<T> {\n if (this.offlineQueue && !this._isOnline) {\n return this.offlineQueue.enqueue<T>({ method: 'PATCH', path, data });\n }\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.patch<T>(path, data, { signal });\n return response.data;\n });\n this.cache.invalidate(path.split('/').filter(Boolean)[0] ?? path);\n return result;\n }\n\n /**\n * Send a DELETE request.\n *\n * @typeParam T - Expected shape of the response body.\n * @param path - URL path relative to the base URL.\n * @param signal - Optional {@link AbortSignal} to cancel the request.\n * @returns The parsed response body.\n */\n async delete<T>(path: string, signal?: AbortSignal): Promise<T> {\n if (this.offlineQueue && !this._isOnline) {\n return this.offlineQueue.enqueue<T>({ method: 'DELETE', path });\n }\n\n const result = await this.retry.execute(async () => {\n const response = await this.axios.delete<T>(path, { signal });\n return response.data;\n });\n this.cache.invalidate(path.split('/').filter(Boolean)[0] ?? path);\n return result;\n }\n\n // -----------------------------------------------------------------------\n // Interceptors\n // -----------------------------------------------------------------------\n\n /**\n * Attach the request interceptor.\n *\n * Responsibilities:\n * - Set `X-API-Key` authentication header.\n * - Set `X-Tenant-ID` header when a tenant identifier is configured.\n * - Ensure `Content-Type` is `application/json`.\n */\n private setupRequestInterceptor(): void {\n this.axios.interceptors.request.use((requestConfig) => {\n // Authentication\n requestConfig.headers.set('X-API-Key', this.config.apiKey);\n\n // Multi-tenant isolation\n if (this.config.tenantId) {\n requestConfig.headers.set('X-Tenant-ID', this.config.tenantId);\n }\n\n // Content negotiation\n requestConfig.headers.set('Content-Type', 'application/json');\n\n return requestConfig;\n });\n }\n\n /**\n * Attach the response interceptor.\n *\n * Successful responses pass through unchanged. Errors are normalised\n * into the appropriate {@link NexusError} subclass:\n *\n * | Condition | Error class |\n * |------------------------|--------------------|\n * | Request cancelled | *(re-thrown as-is)*|\n * | Timeout (`ECONNABORTED`, `ETIMEDOUT`) | {@link TimeoutError} |\n * | No response received | {@link NetworkError} |\n * | HTTP 4xx / 5xx | {@link ApiError} (or subclass) |\n */\n private setupResponseInterceptor(): void {\n this.axios.interceptors.response.use(\n // Success handler -- pass through\n (response) => response,\n\n // Error handler -- normalise into NexusError hierarchy\n (error: AxiosError) => {\n // 1. Cancelled requests: re-throw without wrapping so callers\n // can detect cancellation via `axios.isCancel()`.\n if (axios.isCancel(error)) {\n return Promise.reject(error);\n }\n\n // 2. Timeout errors (ECONNABORTED is used by axios for timeouts,\n // ETIMEDOUT may come from the underlying socket).\n if (\n error.code === 'ECONNABORTED' ||\n error.code === 'ETIMEDOUT'\n ) {\n return Promise.reject(\n new TimeoutError(\n `Request to ${error.config?.url ?? 'unknown'} timed out after ${this.config.timeout}ms`,\n error,\n ),\n );\n }\n\n // 3. Server responded with an error status code.\n if (error.response) {\n const apiError = ApiError.fromResponse(error.response);\n\n // Auto-report to POST /v1/errors (fire-and-forget).\n // Skip reporting errors from the /errors endpoint itself to\n // avoid infinite loops.\n const reqUrl = error.config?.url ?? '';\n if (this.onApiError && !reqUrl.includes('/errors')) {\n try {\n this.onApiError(\n error.response.status,\n error.config?.method?.toUpperCase() ?? 'UNKNOWN',\n reqUrl,\n apiError.message,\n );\n } catch {\n // Never let auto-report failure break the main flow.\n }\n }\n\n return Promise.reject(apiError);\n }\n\n // 4. No response at all -- network-level failure\n // (DNS resolution, connection refused, etc.)\n return Promise.reject(\n new NetworkError(\n error.message || 'A network error occurred',\n error,\n ),\n );\n },\n );\n }\n}\n","/**\n * @module errors/base\n * @description Base error classes for the Nexus SDK.\n */\n\n/**\n * Base error class for all Nexus SDK errors.\n *\n * All SDK-specific errors extend this class, providing a consistent\n * `code` field for programmatic error handling.\n *\n * @example\n * ```typescript\n * try {\n * await client.context.retrieve({ ... });\n * } catch (err) {\n * if (err instanceof NexusError) {\n * console.error(`[${err.code}] ${err.message}`);\n * }\n * }\n * ```\n */\nexport class NexusError extends Error {\n /** Machine-readable error code (e.g. `NEXUS_API_ERROR`). */\n public readonly code: string;\n\n /** The original error that caused this error, if any. */\n public readonly cause?: Error;\n\n constructor(message: string, code: string, cause?: Error) {\n super(message);\n // Restore prototype chain — required when extending built-ins in TS\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = 'NexusError';\n this.code = code;\n this.cause = cause;\n }\n}\n\n/**\n * Thrown when the SDK is configured with invalid options.\n *\n * @example\n * ```typescript\n * // Missing required `apiKey`\n * new NexusClient({}) // throws ConfigurationError\n * ```\n */\nexport class ConfigurationError extends NexusError {\n constructor(message: string, cause?: Error) {\n super(message, 'NEXUS_CONFIGURATION_ERROR', cause);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Thrown when a network-level failure occurs (timeout, DNS, connection refused, etc.).\n */\nexport class NetworkError extends NexusError {\n constructor(message: string, cause?: Error) {\n super(message, 'NEXUS_NETWORK_ERROR', cause);\n this.name = 'NetworkError';\n }\n}\n\n/**\n * Thrown when an operation exceeds its configured timeout.\n */\nexport class TimeoutError extends NexusError {\n constructor(message: string, cause?: Error) {\n super(message, 'NEXUS_TIMEOUT_ERROR', cause);\n this.name = 'TimeoutError';\n }\n}\n","/**\n * @module errors/api\n * @description API-level error classes mapped to HTTP status codes.\n */\n\nimport type { AxiosResponse } from 'axios';\n\nimport { NexusError } from './base';\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Shape of the standard Nexus API error response body. */\ninterface ApiErrorBody {\n detail?: string;\n message?: string;\n errors?: Record<string, string[]>;\n}\n\n/**\n * Extract a human-readable message from an API response body.\n */\nfunction extractMessage(data: unknown, fallback: string): string {\n if (data && typeof data === 'object') {\n const body = data as ApiErrorBody;\n return body.detail ?? body.message ?? fallback;\n }\n return fallback;\n}\n\n// ---------------------------------------------------------------------------\n// ApiError\n// ---------------------------------------------------------------------------\n\n/**\n * Represents an error returned by the Nexus HTTP API.\n *\n * Use the static factory `ApiError.fromResponse()` to construct the most\n * specific subclass based on the HTTP status code.\n *\n * @example\n * ```typescript\n * try {\n * await client.memory.search({ ... });\n * } catch (err) {\n * if (err instanceof ApiError) {\n * console.error(`HTTP ${err.statusCode}: ${err.message}`);\n * }\n * }\n * ```\n */\nexport class ApiError extends NexusError {\n /** HTTP status code returned by the server. */\n public readonly statusCode: number;\n\n /** Raw response body, if available. */\n public readonly response?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n response?: unknown,\n code: string = 'NEXUS_API_ERROR',\n ) {\n super(message, code);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = 'ApiError';\n this.statusCode = statusCode;\n this.response = response;\n }\n\n /**\n * Create the most specific `ApiError` subclass from an Axios response.\n *\n * | Status | Error class |\n * |--------|------------------------|\n * | 400 | `ValidationError` |\n * | 401 | `AuthenticationError` |\n * | 404 | `NotFoundError` |\n * | 429 | `RateLimitError` |\n * | other | `ApiError` |\n */\n static fromResponse(response: AxiosResponse): ApiError {\n const { status, data, headers } = response;\n\n switch (status) {\n case 400: {\n const msg = extractMessage(data, 'Validation failed');\n const details =\n data && typeof data === 'object'\n ? (data as ApiErrorBody).errors\n : undefined;\n return new ValidationError(msg, details, data);\n }\n\n case 401: {\n const msg = extractMessage(data, 'Authentication failed');\n return new AuthenticationError(msg, data);\n }\n\n case 404: {\n const msg = extractMessage(data, 'Resource not found');\n return new NotFoundError(msg, data);\n }\n\n case 429: {\n const msg = extractMessage(data, 'Rate limit exceeded');\n const retryAfter = headers?.['retry-after']\n ? Number(headers['retry-after'])\n : undefined;\n return new RateLimitError(msg, retryAfter, data);\n }\n\n default: {\n const msg = extractMessage(\n data,\n `API request failed with status ${status}`,\n );\n return new ApiError(msg, status, data);\n }\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Specific API errors\n// ---------------------------------------------------------------------------\n\n/**\n * HTTP 401 -- the request lacks valid authentication credentials.\n */\nexport class AuthenticationError extends ApiError {\n constructor(message: string, response?: unknown) {\n super(message, 401, response, 'NEXUS_AUTHENTICATION_ERROR');\n this.name = 'AuthenticationError';\n }\n}\n\n/**\n * HTTP 429 -- the client has sent too many requests in a given time window.\n *\n * When the server provides a `Retry-After` header, it is exposed via\n * {@link RateLimitError.retryAfter} (in seconds).\n */\nexport class RateLimitError extends ApiError {\n /** Seconds to wait before retrying, parsed from the `Retry-After` header. */\n public readonly retryAfter?: number;\n\n constructor(message: string, retryAfter?: number, response?: unknown) {\n super(message, 429, response, 'NEXUS_RATE_LIMIT_ERROR');\n this.name = 'RateLimitError';\n this.retryAfter = retryAfter;\n }\n}\n\n/**\n * HTTP 400 -- the request body or query parameters failed validation.\n *\n * When the server returns field-level errors they are available via\n * {@link ValidationError.details}.\n */\nexport class ValidationError extends ApiError {\n /** Per-field validation error messages, if provided by the server. */\n public readonly details?: Record<string, string[]>;\n\n constructor(\n message: string,\n details?: Record<string, string[]>,\n response?: unknown,\n ) {\n super(message, 400, response, 'NEXUS_VALIDATION_ERROR');\n this.name = 'ValidationError';\n this.details = details;\n }\n}\n\n/**\n * HTTP 404 -- the requested resource does not exist.\n */\nexport class NotFoundError extends ApiError {\n constructor(message: string, response?: unknown) {\n super(message, 404, response, 'NEXUS_NOT_FOUND_ERROR');\n this.name = 'NotFoundError';\n }\n}\n","/**\n * @module http/cache\n * @description LRU cache layer for the Nexus SDK HTTP client.\n *\n * Provides transparent caching for GET requests and specific read-oriented\n * POST endpoints (e.g. `/context/retrieve`, `/memories/search`,\n * `/knowledge/query`). Write operations automatically invalidate related\n * cache entries by path prefix.\n *\n * When caching is disabled (`config === false`), every method is a no-op\n * with zero overhead.\n */\n\nimport { LRUCache } from 'lru-cache';\n\nimport type { ResolvedCacheConfig } from '../config';\n\n// ---------------------------------------------------------------------------\n// Cacheable POST endpoints\n// ---------------------------------------------------------------------------\n\n/**\n * POST paths that are semantically read-only and therefore safe to cache.\n * These endpoints perform search / retrieval operations via POST bodies.\n */\nconst CACHEABLE_POST_PATHS: ReadonlySet<string> = new Set([\n '/context/retrieve',\n '/memories/search',\n '/knowledge/query',\n]);\n\n/**\n * Check whether a POST request to the given path is eligible for caching.\n */\nexport function isCacheablePost(path: string): boolean {\n return CACHEABLE_POST_PATHS.has(path);\n}\n\n// ---------------------------------------------------------------------------\n// Stable hashing\n// ---------------------------------------------------------------------------\n\n/**\n * Produce a deterministic hash string from an arbitrary value.\n *\n * The value is first serialised to JSON with sorted keys so that\n * `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` yield the same hash.\n * The hash itself is a simple DJB2-style numeric hash converted to\n * a base-36 string -- fast and collision-resistant enough for cache keys.\n */\nfunction stableHash(value: unknown): string {\n const json = JSON.stringify(value, (_key, val) => {\n // Sort object keys for deterministic serialisation\n if (val !== null && typeof val === 'object' && !Array.isArray(val)) {\n return Object.keys(val as Record<string, unknown>)\n .sort()\n .reduce<Record<string, unknown>>((sorted, k) => {\n sorted[k] = (val as Record<string, unknown>)[k];\n return sorted;\n }, {});\n }\n return val;\n });\n\n // DJB2 hash\n let hash = 5381;\n for (let i = 0; i < json.length; i++) {\n // hash * 33 + charCode\n hash = ((hash << 5) + hash + json.charCodeAt(i)) | 0;\n }\n\n // Convert to unsigned 32-bit then base-36 for a compact string\n return (hash >>> 0).toString(36);\n}\n\n// ---------------------------------------------------------------------------\n// CacheManager\n// ---------------------------------------------------------------------------\n\n/**\n * LRU cache manager for the Nexus SDK.\n *\n * Wraps the `lru-cache` library and adds:\n * - Stable key generation from method + path + params/body\n * - Pattern-based invalidation for write-after-read consistency\n * - Hit / miss counters for observability\n * - Graceful no-op behaviour when caching is disabled\n *\n * @example\n * ```typescript\n * const cache = new CacheManager({ max: 500, ttl: 120 });\n *\n * const key = cache.generateKey('GET', '/memories', { user_id: 'u1' });\n * cache.set(key, [{ id: '1', content: 'hello' }]);\n *\n * const hit = cache.get<Memory[]>(key); // => [{ id: '1', ... }]\n * console.log(cache.stats); // { size: 1, hits: 1, misses: 0 }\n * ```\n */\nexport class CacheManager {\n /** Underlying LRU cache instance. */\n private readonly cache: LRUCache<string, unknown>;\n\n /** Whether caching is active. */\n private readonly enabled: boolean;\n\n /** Running hit counter. */\n private _hits = 0;\n\n /** Running miss counter. */\n private _misses = 0;\n\n /**\n * Create a new cache manager.\n *\n * @param config - Resolved cache configuration, or `false` to disable.\n */\n constructor(config: ResolvedCacheConfig | false) {\n if (config === false) {\n this.enabled = false;\n // Minimal placeholder -- never actually used\n this.cache = new LRUCache<string, unknown>({ max: 1 });\n } else {\n this.enabled = true;\n this.cache = new LRUCache<string, unknown>({\n max: config.max,\n ttl: config.ttl * 1000, // seconds -> milliseconds\n });\n }\n }\n\n // -----------------------------------------------------------------------\n // Key generation\n // -----------------------------------------------------------------------\n\n /**\n * Generate a deterministic cache key from the request signature.\n *\n * Format: `METHOD:path:hash(params)`\n *\n * @param method - HTTP method (e.g. `GET`, `POST`).\n * @param path - Request path (e.g. `/memories/search`).\n * @param params - Query parameters or request body (optional).\n * @returns A string suitable for use as a cache key.\n */\n generateKey(method: string, path: string, params?: unknown): string {\n const base = `${method.toUpperCase()}:${path}`;\n if (params === undefined || params === null) {\n return base;\n }\n return `${base}:${stableHash(params)}`;\n }\n\n // -----------------------------------------------------------------------\n // Core operations\n // -----------------------------------------------------------------------\n\n /**\n * Retrieve a cached value.\n *\n * @typeParam T - Expected type of the cached value.\n * @param key - Cache key (as returned by {@link generateKey}).\n * @returns The cached value, or `undefined` on a miss.\n */\n get<T>(key: string): T | undefined {\n if (!this.enabled) {\n return undefined;\n }\n\n const value = this.cache.get(key);\n if (value !== undefined) {\n this._hits++;\n return value as T;\n }\n\n this._misses++;\n return undefined;\n }\n\n /**\n * Store a value in the cache.\n *\n * @param key - Cache key.\n * @param value - Value to cache.\n */\n set(key: string, value: unknown): void {\n if (!this.enabled) {\n return;\n }\n this.cache.set(key, value);\n }\n\n /**\n * Invalidate all cache entries whose key contains the given pattern.\n *\n * This is typically called after a write operation to evict stale\n * read results. For example, after `POST /memories`, calling\n * `invalidate('/memories')` removes all cached memory queries.\n *\n * @param pattern - Substring to match against cache keys.\n */\n invalidate(pattern: string): void {\n if (!this.enabled) {\n return;\n }\n\n // Iterate over all keys and delete those that contain the pattern.\n // LRUCache exposes keys via the keys() iterator.\n for (const key of this.cache.keys()) {\n if (key.includes(pattern)) {\n this.cache.delete(key);\n }\n }\n }\n\n /**\n * Remove all entries from the cache and reset counters.\n */\n clear(): void {\n if (!this.enabled) {\n return;\n }\n this.cache.clear();\n this._hits = 0;\n this._misses = 0;\n }\n\n // -----------------------------------------------------------------------\n // Observability\n // -----------------------------------------------------------------------\n\n /**\n * Current cache statistics.\n *\n * Useful for logging, health checks, and dashboards.\n */\n get stats(): { size: number; hits: number; misses: number } {\n return {\n size: this.enabled ? this.cache.size : 0,\n hits: this._hits,\n misses: this._misses,\n };\n }\n}\n","/**\n * @module http/retry\n * @description Retry manager with exponential back-off and jitter.\n *\n * Wraps an async operation and transparently retries on transient failures\n * (network errors, timeouts, 429 rate-limits, 5xx server errors) using\n * configurable exponential back-off with ±10% jitter to prevent thundering\n * herd problems.\n */\n\nimport type { ResolvedRetryConfig } from '../config';\nimport { NetworkError, TimeoutError } from '../errors/base';\nimport { ApiError, RateLimitError } from '../errors/api';\n\n/**\n * Manages retry logic for HTTP requests.\n *\n * When retries are disabled (`config === false`), {@link execute} delegates\n * directly to the provided function with zero overhead.\n *\n * @example\n * ```typescript\n * const retry = new RetryManager({ maxRetries: 3, initialDelay: 1000, maxDelay: 10000, backoffFactor: 2 });\n *\n * const result = await retry.execute(() => httpClient.get('/context/retrieve'));\n * ```\n */\nexport class RetryManager {\n /** Resolved retry configuration, or `false` when retries are disabled. */\n private readonly config: ResolvedRetryConfig | false;\n\n /**\n * Create a new retry manager.\n *\n * @param config - Fully-resolved retry settings, or `false` to disable retries entirely.\n */\n constructor(config: ResolvedRetryConfig | false) {\n this.config = config;\n }\n\n /**\n * Determine whether a given error is eligible for retry.\n *\n * Retryable conditions:\n * - {@link NetworkError} -- transient connectivity issues\n * - {@link TimeoutError} -- request exceeded its deadline\n * - {@link RateLimitError} (HTTP 429) -- server asks us to slow down\n * - Any {@link ApiError} with a 5xx status code -- server-side failures\n *\n * Non-retryable conditions:\n * - 4xx errors other than 429 (client errors that won't resolve on retry)\n * - Cancelled / aborted requests\n * - Any non-Nexus error (unknown failures are not assumed to be transient)\n *\n * @param error - The error to evaluate.\n * @returns `true` if the operation should be retried.\n */\n isRetryable(error: unknown): boolean {\n // Network-level failures are always transient\n if (error instanceof NetworkError) {\n return true;\n }\n\n // Timeouts are transient\n if (error instanceof TimeoutError) {\n return true;\n }\n\n // Rate-limit (429) -- the server explicitly expects us to retry later\n if (error instanceof RateLimitError) {\n return true;\n }\n\n // Other API errors: only 5xx (server errors) are retryable\n if (error instanceof ApiError) {\n return error.statusCode >= 500 && error.statusCode < 600;\n }\n\n // Cancelled requests and unknown errors are not retryable\n return false;\n }\n\n /**\n * Calculate the delay (in milliseconds) before the next retry attempt.\n *\n * Uses exponential back-off: `delay = initialDelay * backoffFactor ^ attempt`.\n *\n * Special cases:\n * - If the error is a {@link RateLimitError} with a `retryAfter` value,\n * that value (converted to ms) takes precedence over the computed delay.\n * - A random jitter of ±10% is applied to prevent thundering herd.\n * - The result is clamped to {@link ResolvedRetryConfig.maxDelay}.\n *\n * @param attempt - Zero-based attempt index (0 = first retry).\n * @param error - The error that triggered the retry (optional).\n * @returns Delay in milliseconds before the next attempt.\n */\n getDelay(attempt: number, error?: unknown): number {\n if (this.config === false) {\n return 0;\n }\n\n const { initialDelay, backoffFactor, maxDelay } = this.config;\n\n // If the server told us exactly when to retry, honour that\n if (error instanceof RateLimitError && error.retryAfter != null) {\n // retryAfter is in seconds; convert to ms and apply jitter\n const serverDelay = error.retryAfter * 1000;\n return Math.min(this.applyJitter(serverDelay), maxDelay);\n }\n\n // Exponential back-off: initialDelay * backoffFactor ^ attempt\n const exponentialDelay = initialDelay * Math.pow(backoffFactor, attempt);\n\n // Apply jitter and clamp\n return Math.min(this.applyJitter(exponentialDelay), maxDelay);\n }\n\n /**\n * Execute an async function with automatic retries on transient failures.\n *\n * If retries are disabled (`config === false`), the function is invoked\n * exactly once with no retry logic.\n *\n * @typeParam T - Return type of the wrapped function.\n * @param fn - The async operation to execute (and potentially retry).\n * @returns The resolved value of `fn`.\n * @throws The last error encountered if all retry attempts are exhausted,\n * or immediately if the error is not retryable.\n *\n * @example\n * ```typescript\n * const manager = new RetryManager({ maxRetries: 3, initialDelay: 500, maxDelay: 5000, backoffFactor: 2 });\n *\n * const data = await manager.execute(async () => {\n * return fetch('/api/data').then(r => r.json());\n * });\n * ```\n */\n async execute<T>(fn: () => Promise<T>): Promise<T> {\n // Retries disabled -- single attempt, no overhead\n if (this.config === false) {\n return fn();\n }\n\n const { maxRetries } = this.config;\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error: unknown) {\n lastError = error;\n\n // If the error is not retryable, fail immediately\n if (!this.isRetryable(error)) {\n throw error;\n }\n\n // If we've exhausted all retries, throw the last error\n if (attempt >= maxRetries) {\n throw error;\n }\n\n // Wait before the next attempt\n const delay = this.getDelay(attempt, error);\n await this.sleep(delay);\n }\n }\n\n // TypeScript: this line is technically unreachable, but satisfies the compiler\n throw lastError;\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n /**\n * Apply ±10% random jitter to a delay value.\n *\n * @param delay - Base delay in milliseconds.\n * @returns Jittered delay in milliseconds.\n */\n private applyJitter(delay: number): number {\n // jitterFactor is in the range [0.9, 1.1]\n const jitterFactor = 0.9 + Math.random() * 0.2;\n return Math.round(delay * jitterFactor);\n }\n\n /**\n * Sleep for the specified duration.\n *\n * @param ms - Duration in milliseconds.\n */\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * @module http/queue\n * @description Offline request queue for the Nexus SDK.\n *\n * When the network is unavailable, requests can be enqueued and later\n * flushed (replayed) once connectivity is restored. Each enqueued request\n * returns a `Promise` so callers can `await` the eventual result\n * transparently.\n */\n\nimport { NexusError } from '../errors/base';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * A request that has been queued for later execution.\n *\n * The `resolve` and `reject` callbacks are wired to the `Promise` returned\n * by {@link OfflineQueue.enqueue}, allowing the original caller to `await`\n * the result even though the actual HTTP call is deferred.\n */\nexport interface QueuedRequest {\n /** Unique identifier for this queued request. */\n id: string;\n /** HTTP method (e.g. `GET`, `POST`, `PUT`, `DELETE`). */\n method: string;\n /** URL path relative to the base URL. */\n path: string;\n /** Optional request body. */\n data?: unknown;\n /** Resolve the caller's deferred promise with the response. */\n resolve: (value: unknown) => void;\n /** Reject the caller's deferred promise with an error. */\n reject: (error: unknown) => void;\n /** Unix timestamp (ms) when the request was enqueued. */\n timestamp: number;\n}\n\n// ---------------------------------------------------------------------------\n// OfflineQueue\n// ---------------------------------------------------------------------------\n\n/**\n * Queues HTTP requests while the client is offline and replays them\n * when connectivity is restored.\n *\n * Each call to {@link enqueue} returns a `Promise` that resolves (or\n * rejects) only after the request has been successfully flushed via\n * {@link flush}. This allows consuming code to `await` the result as\n * if the request were executed immediately.\n *\n * @example\n * ```typescript\n * const queue = new OfflineQueue(50);\n *\n * // While offline -- the promise won't settle until flush()\n * const pending = queue.enqueue({ method: 'POST', path: '/memory/add', data: { text: 'hello' } });\n *\n * // Later, when online again\n * await queue.flush(async (req) => httpClient.post(req.path, req.data));\n *\n * // Now `pending` has resolved with the server response\n * const result = await pending;\n * ```\n */\nexport class OfflineQueue {\n /** Internal FIFO queue of deferred requests. */\n private readonly queue: QueuedRequest[] = [];\n\n /** Maximum number of requests the queue will hold. */\n private readonly maxSize: number;\n\n /** Guard flag to prevent concurrent flush operations. */\n private processing = false;\n\n /** Auto-incrementing counter used to generate unique request IDs. */\n private idCounter = 0;\n\n /**\n * Create a new offline queue.\n *\n * @param maxSize - Maximum number of requests to buffer. When the queue\n * is full, subsequent {@link enqueue} calls will reject\n * immediately. Defaults to `100`.\n */\n constructor(maxSize = 100) {\n this.maxSize = maxSize;\n }\n\n /**\n * Add a request to the queue.\n *\n * The returned `Promise` settles only when the request is eventually\n * executed during a {@link flush} call.\n *\n * @param request - The request descriptor (method, path, and optional data).\n * @returns A `Promise` that resolves with the executor's return value\n * once the request is flushed, or rejects if the queue is full\n * or the executor fails.\n *\n * @throws {NexusError} If the queue has reached its maximum capacity.\n */\n enqueue<T = unknown>(\n request: Omit<QueuedRequest, 'id' | 'resolve' | 'reject' | 'timestamp'>,\n ): Promise<T> {\n if (this.queue.length >= this.maxSize) {\n return Promise.reject(\n new NexusError(\n `Offline queue is full (max ${this.maxSize}). Request to ${request.method} ${request.path} was rejected.`,\n 'NEXUS_QUEUE_FULL',\n ),\n );\n }\n\n return new Promise<T>((resolve, reject) => {\n this.idCounter += 1;\n\n const queued: QueuedRequest = {\n id: `oq_${this.idCounter}_${Date.now()}`,\n method: request.method,\n path: request.path,\n data: request.data,\n resolve: resolve as (value: unknown) => void,\n reject,\n timestamp: Date.now(),\n };\n\n this.queue.push(queued);\n });\n }\n\n /**\n * Process all queued requests in FIFO order.\n *\n * Each request is passed to the provided `executor` function. On success\n * the caller's deferred promise is resolved; on failure it is rejected.\n *\n * Requests are processed sequentially to preserve ordering guarantees.\n * If a flush is already in progress, subsequent calls are silently ignored.\n *\n * @param executor - An async function that performs the actual HTTP call\n * for a given queued request and returns the response.\n *\n * @example\n * ```typescript\n * await queue.flush(async (req) => {\n * return httpClient.request(req.method, req.path, req.data);\n * });\n * ```\n */\n async flush(\n executor: (req: QueuedRequest) => Promise<unknown>,\n ): Promise<void> {\n // Prevent concurrent flushes\n if (this.processing) {\n return;\n }\n\n this.processing = true;\n\n try {\n while (this.queue.length > 0) {\n // Shift from the front to maintain FIFO order\n const request = this.queue.shift()!;\n\n try {\n const result = await executor(request);\n request.resolve(result);\n } catch (error: unknown) {\n request.reject(error);\n }\n }\n } finally {\n this.processing = false;\n }\n }\n\n /**\n * The number of requests currently waiting in the queue.\n */\n get size(): number {\n return this.queue.length;\n }\n\n /**\n * Remove all pending requests from the queue.\n *\n * Every deferred promise is rejected with a cancellation error so that\n * callers are not left hanging indefinitely.\n */\n clear(): void {\n while (this.queue.length > 0) {\n const request = this.queue.shift()!;\n request.reject(\n new NexusError(\n 'Request cancelled: offline queue was cleared.',\n 'NEXUS_QUEUE_CLEARED',\n ),\n );\n }\n }\n}\n","/**\n * @module services/base\n * @description Abstract base class for all Nexus service modules.\n *\n * Every service (Context, Memory, Conversation, Knowledge) extends this\n * class to gain access to the shared {@link HttpClient} instance, which\n * handles authentication, error normalisation, and timeout management.\n */\n\nimport type { HttpClient } from '../http/client';\n\n/**\n * Options that can be passed to any service method.\n */\nexport interface RequestOptions {\n /** Optional AbortSignal to cancel the request. */\n signal?: AbortSignal;\n}\n\n/**\n * Abstract base class that all Nexus service classes extend.\n *\n * Provides a protected reference to the SDK's {@link HttpClient} so that\n * subclasses can issue HTTP requests without managing connection details.\n *\n * @example\n * ```typescript\n * class MyService extends BaseService {\n * async ping(): Promise<string> {\n * return this.http.get<string>('/ping');\n * }\n * }\n * ```\n */\nexport abstract class BaseService {\n /** Shared HTTP client instance configured with API key and tenant headers. */\n protected readonly http: HttpClient;\n\n /**\n * @param http - Fully-configured {@link HttpClient} instance.\n */\n constructor(http: HttpClient) {\n this.http = http;\n }\n}\n","/**\n * @nexusm/sdk - Context Types\n *\n * Type definitions for the Context Service - the core aggregated context\n * retrieval API used in Chat main flows.\n *\n * v2.0 DX Enhanced temporal-anchored multi-layer retrieval.\n *\n * Based on Nexus API v2.0 OpenAPI specification.\n */\n\n// ============== Context Layers (v2.0 DX Enhancement) ==============\n\n/**\n * Available context retrieval layers for multi-layer parallel retrieval.\n * - \"recent\": Time-anchored activities from the activity stream\n * - \"semantic\": Vector similarity search against memory store (Mem0)\n * - \"graph\": Knowledge graph traversal (Fast GraphRAG)\n */\nexport type ContextLayer = 'recent' | 'semantic' | 'graph';\n\n// ============== Context Depth Presets ==============\n\n/**\n * Convenience depth levels for context retrieval.\n *\n * | Level | Profile | History | Graph | Layers |\n * |-------|---------|---------|-------|-------------------|\n * | L0 | 1 mem | off | off | [] |\n * | L1 | 3 mems | off | off | [] |\n * | L2 | 10 mems | off | off | [\"semantic\"] |\n * | L3 | 20 mems | on | on | [\"semantic\",\"graph\"] |\n *\n * Use with the `depth` parameter on {@link ContextRequest}.\n * Explicit fields always override the preset values.\n */\nexport type ContextDepth = 'L0' | 'L1' | 'L2' | 'L3';\n\n/** @internal Partial ContextRequest overrides applied for each depth preset. */\nexport type ContextDepthPreset = Pick<\n ContextRequest,\n 'include_profile' | 'profile_limit' | 'include_history' | 'include_graph' | 'layers'\n>;\n\n/**\n * Preset field overrides for each {@link ContextDepth} level.\n * Applied before user-supplied options so explicit values always win.\n */\nexport const DEPTH_PRESETS: Record<ContextDepth, ContextDepthPreset> = {\n L0: { include_profile: true, profile_limit: 1, include_history: false, include_graph: false, layers: [] },\n L1: { include_profile: true, profile_limit: 3, include_history: false, include_graph: false, layers: [] },\n L2: { include_profile: true, profile_limit: 10, include_history: false, include_graph: false, layers: ['semantic'] },\n L3: { include_profile: true, profile_limit: 20, include_history: true, include_graph: true, layers: ['semantic', 'graph'] },\n};\n\n// ============== Context Request (v2.0 DX Enhanced) ==============\n\n/**\n * Request payload for the v2.0 DX Enhanced context retrieval endpoint.\n * Supports multi-layer parallel retrieval with temporal anchoring (US-014).\n *\n * POST /context/retrieve\n *\n * The optional `depth` field is a client-side convenience shorthand.\n * It is resolved to concrete field values before the request is sent to the\n * backend, so it never appears in the wire payload.\n */\nexport interface ContextRequest {\n /**\n * Convenience depth preset. When set, applies a predefined combination of\n * `include_profile`, `profile_limit`, `include_history`, `include_graph`,\n * and `layers`. Any field you supply explicitly overrides the preset value.\n *\n * @see {@link DEPTH_PRESETS} for exact values per level.\n */\n depth?: ContextDepth;\n /** User ID within the tenant (Nexus auto-prefixes tenant ID) */\n user_id: string;\n /** Optional semantic query text (used for the semantic layer) */\n query?: string;\n /**\n * Context layers to retrieve in parallel.\n * @default [\"semantic\", \"graph\"]\n */\n layers?: ContextLayer[];\n /**\n * Time window for the recent layer in hours.\n * @default 4\n */\n recent_hours?: number;\n /**\n * Maximum number of recent activities to return.\n * @default 10\n */\n recent_limit?: number;\n /**\n * Whether to include memory profile (semantic layer).\n * @default true\n */\n include_profile?: boolean;\n /**\n * Maximum number of profile memories to return.\n * @default 5\n */\n profile_limit?: number;\n /**\n * Whether to include conversation history.\n * @default true\n */\n include_history?: boolean;\n /**\n * Maximum number of conversation history messages to return.\n * @default 10\n */\n history_limit?: number;\n /**\n * Whether to include knowledge graph entities (graph layer).\n * @default true\n */\n include_graph?: boolean;\n /**\n * Maximum number of knowledge graph entities to return.\n * @default 5\n */\n graph_limit?: number;\n /**\n * Optional point-in-time anchor for temporal-aware retrieval.\n * RFC 3339 datetime **with timezone offset** (e.g.\n * `\"2026-01-01T00:00:00+00:00\"` or `\"2026-01-01T00:00:00Z\"`).\n * When set, layers that support temporal anchoring (semantic, recent)\n * scope their retrieval to facts known to the system at that\n * timestamp — useful for replaying past states (debugging,\n * compliance) or running deterministic evaluations against\n * a historical snapshot.\n *\n * Naive datetimes (no timezone) are rejected client-side by the\n * zod schema to prevent silent UTC vs local-time mismatches at\n * the ingest boundary.\n *\n * @since 1.3.0 (US-037 Wave 1 TASK-005)\n */\n as_of?: string;\n}\n\n// ============== Context Response Sub-types ==============\n\n/**\n * A single memory item within the context profile.\n * Sourced from Mem0 memory store.\n */\nexport interface ContextMemory {\n /** Unique memory identifier (UUID) */\n id: string;\n /** Memory content text */\n content: string;\n /** Type of memory */\n memory_type: 'episodic' | 'semantic' | 'procedural';\n /** Relevance score from similarity search */\n score?: number;\n /** Timestamp when the memory was created (ISO 8601) */\n created_at: string;\n}\n\n/**\n * User profile memories section of the context response.\n * Contains memories retrieved from Mem0.\n */\nexport interface ContextProfile {\n /** List of relevant memories */\n memories: ContextMemory[];\n /** Total number of memories the user has */\n total_count: number;\n}\n\n/** A single message within conversation history. */\nexport interface ContextMessage {\n /** Message role */\n role: 'user' | 'assistant' | 'system' | 'tool';\n /** Message content text */\n content: string;\n /** Timestamp when the message was created (ISO 8601) */\n created_at: string;\n}\n\n/**\n * Conversation history section of the context response.\n * Sourced from Zep conversation store.\n */\nexport interface ContextHistory {\n /** List of recent messages */\n messages: ContextMessage[];\n /** Auto-generated conversation summary (if available) */\n summary?: string;\n /** Session identifier */\n session_id?: string;\n}\n\n/** Entity ownership type in the knowledge graph */\nexport type OwnerType = 'agent' | 'user';\n\n/**\n * A knowledge entity within the graph context.\n * Sourced from Fast GraphRAG.\n */\nexport interface ContextEntity {\n /** Unique entity identifier (UUID) */\n id: string;\n /** Entity display name */\n name: string;\n /** Entity type classification (e.g., Person, Organization) */\n entity_type: string;\n /** Entity description */\n description?: string;\n /** Additional entity properties */\n properties?: Record<string, unknown>;\n /** Ownership type: agent=public knowledge, user=private social graph */\n owner_type?: OwnerType;\n}\n\n/** A relationship between two entities in the knowledge graph. */\nexport interface ContextRelation {\n /** Source entity name */\n source: string;\n /** Relationship type label */\n relation: string;\n /** Target entity name */\n target: string;\n /** Relationship weight/strength */\n weight?: number;\n}\n\n/**\n * Knowledge graph section of the context response.\n * Sourced from Fast GraphRAG.\n */\nexport interface ContextGraph {\n /** List of relevant entities */\n entities: ContextEntity[];\n /** List of relationships between entities */\n relations: ContextRelation[];\n}\n\n/**\n * Retrieval performance metadata.\n * Provides timing information for each retrieval layer.\n */\nexport interface ContextMeta {\n /** Total retrieval time in milliseconds */\n took_ms: number;\n /** Memory retrieval time in milliseconds */\n memory_took_ms?: number;\n /** History retrieval time in milliseconds */\n history_took_ms?: number;\n /** Graph retrieval time in milliseconds */\n graph_took_ms?: number;\n /** Original query text */\n query?: string;\n}\n\n// ============== Context Retrieve Response ==============\n\n/**\n * Aggregated context response from the retrieve endpoint.\n * Contains parallel-fetched results from all requested layers.\n */\nexport interface ContextRetrieveResponse {\n /** User profile memories from Mem0 */\n profile?: ContextProfile;\n /** Conversation history from Zep */\n history?: ContextHistory;\n /** Knowledge graph data from GraphRAG */\n graph?: ContextGraph;\n /** Retrieval performance metadata */\n meta?: ContextMeta;\n}\n","import { z } from 'zod';\r\n\r\nconst contextLayerSchema = z.enum(['recent', 'semantic', 'graph']);\r\n\r\nexport const contextRequestSchema = z.object({\r\n user_id: z.string().min(1),\r\n query: z.string().optional(),\r\n layers: z.array(contextLayerSchema).optional(),\r\n recent_hours: z.number().positive().optional(),\r\n recent_limit: z.number().int().positive().optional(),\r\n include_profile: z.boolean().optional(),\r\n profile_limit: z.number().int().positive().optional(),\r\n include_history: z.boolean().optional(),\r\n history_limit: z.number().int().positive().optional(),\r\n include_graph: z.boolean().optional(),\r\n graph_limit: z.number().int().positive().optional(),\r\n // RFC 3339 with required timezone offset (`offset: true`). Rejects naive\r\n // datetimes like `\"2026-01-01T00:00:00\"` to surface ingest-boundary\r\n // ambiguity early — see ContextRequest.as_of JSDoc.\r\n // Added in v1.3.0 (US-037 Wave 1 TASK-005).\r\n as_of: z.string().datetime({ offset: true }).optional(),\r\n});\r\n","import { NexusError } from './base';\r\nimport type { ZodError } from 'zod';\r\n\r\n/**\r\n * Thrown when client-side input validation fails (zod schema).\r\n * Distinct from the API ValidationError (HTTP 400).\r\n */\r\nexport class InputValidationError extends NexusError {\r\n public readonly fieldErrors: Record<string, string[]>;\r\n\r\n constructor(zodError: ZodError) {\r\n const message = `Validation failed: ${zodError.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`;\r\n super(message, 'NEXUS_INPUT_VALIDATION_ERROR');\r\n Object.setPrototypeOf(this, new.target.prototype);\r\n this.name = 'InputValidationError';\r\n this.fieldErrors = zodError.flatten().fieldErrors as Record<string, string[]>;\r\n }\r\n}\r\n","/**\n * @module services/context\n * @description Context Service - Aggregated context retrieval for Chat main flows.\n *\n * The Context Service is the primary entry point for AI agents to fetch\n * all relevant user context in a single call. It orchestrates parallel\n * retrieval across Memory (Mem0), Conversation (Zep), and Knowledge\n * (GraphRAG) layers.\n *\n * Based on Nexus API v2.0 - POST /context/retrieve\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type { ContextRequest, ContextRetrieveResponse } from '../types/context';\nimport { DEPTH_PRESETS } from '../types/context';\nimport { contextRequestSchema } from '../schemas/context';\nimport { InputValidationError } from '../errors/validation';\n\n/**\n * Service for aggregated context retrieval.\n *\n * This is the core API surface for Chat main flows. A single call to\n * {@link ContextService.retrieve} fetches user profile memories,\n * conversation history, and knowledge graph data in parallel.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * const context = await nexus.context.retrieve({\n * user_id: 'user_42',\n * query: 'What did we discuss about the project?',\n * layers: ['recent', 'semantic', 'graph'],\n * });\n *\n * console.log(context.profile?.memories);\n * console.log(context.history?.messages);\n * console.log(context.graph?.entities);\n * ```\n */\nexport class ContextService extends BaseService {\n /**\n * Retrieve aggregated context for a user across multiple layers.\n *\n * Performs v2.0 three-layer parallel retrieval:\n * - **recent**: Time-anchored activities from the activity stream\n * - **semantic**: Vector similarity search against Mem0 memory store\n * - **graph**: Knowledge graph traversal via Fast GraphRAG\n *\n * @param request - Context retrieval parameters including user_id, query, and layer configuration.\n * @returns Aggregated context containing profile, history, graph, and performance metadata.\n */\n async retrieve(request: ContextRequest, options?: RequestOptions): Promise<ContextRetrieveResponse> {\n // Resolve depth preset: preset values are the base, explicit caller fields win.\n let resolved: ContextRequest;\n if (request.depth !== undefined && DEPTH_PRESETS[request.depth]) {\n const { depth, ...rest } = request;\n resolved = { ...DEPTH_PRESETS[depth], ...rest };\n } else {\n const { depth: _depth, ...rest } = request;\n resolved = rest;\n }\n\n const parsed = contextRequestSchema.safeParse(resolved);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<ContextRetrieveResponse>('/context/retrieve', resolved, options?.signal);\n }\n}\n","import { z } from 'zod';\r\n\r\nconst memoryTypeSchema = z.enum(['episodic', 'semantic', 'procedural']);\r\n\r\nexport const memoryCreateSchema = z.object({\r\n user_id: z.string().min(1),\r\n content: z.string().min(1).max(10000),\r\n memory_type: memoryTypeSchema.optional(),\r\n metadata: z.record(z.unknown()).optional(),\r\n});\r\n\r\nexport const memoryUpdateSchema = z.object({\r\n content: z.string().optional(),\r\n memory_type: memoryTypeSchema.optional(),\r\n metadata: z.record(z.unknown()).optional(),\r\n});\r\n\r\nexport const memorySearchSchema = z.object({\r\n user_id: z.string().min(1),\r\n query: z.string().min(1),\r\n memory_type: memoryTypeSchema.optional(),\r\n limit: z.number().int().min(1).max(50).optional(),\r\n threshold: z.number().min(0).max(1).optional(),\r\n});\r\n","/**\n * @module services/memories\n * @description Memory Service - Long-term memory management with semantic retrieval.\n *\n * Wraps the Nexus Memory API powered by Mem0. Supports CRUD operations\n * on episodic, semantic, and procedural memories, vector similarity\n * search, and the Memory Journal view (US-015).\n *\n * Based on Nexus API v2.0 - /memories endpoints\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n Memory,\n MemoryCreate,\n MemoryUpdate,\n MemorySearch,\n MemorySearchResult,\n MemoryList,\n JournalResponse,\n MemoryType,\n} from '../types/memory';\nimport { memoryCreateSchema, memoryUpdateSchema, memorySearchSchema } from '../schemas/memory';\nimport { InputValidationError } from '../errors/validation';\n\n/**\n * Parameters for listing memories with optional filtering and pagination.\n */\nexport interface MemoryListParams {\n /** Filter memories by user ID */\n user_id?: string;\n /** Filter by memory type classification */\n memory_type?: MemoryType;\n /** Maximum number of results per page */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Parameters for the Memory Journal view (US-015).\n */\nexport interface MemoryJournalParams {\n /** Response format: markdown for display, json for programmatic use */\n format?: 'markdown' | 'json';\n /** Start date filter (ISO 8601 date, e.g. \"2026-01-01\") */\n start_date?: string;\n /** End date filter (ISO 8601 date, e.g. \"2026-01-31\") */\n end_date?: string;\n /** Filter journal entries by user ID */\n user_id?: string;\n}\n\n/**\n * Service for managing long-term memories via Mem0.\n *\n * Provides full CRUD operations, semantic search, and the chronological\n * Memory Journal view for reviewing memories over time.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Create a memory\n * const memory = await nexus.memories.create({\n * user_id: 'user_42',\n * content: 'User prefers dark mode',\n * memory_type: 'semantic',\n * });\n *\n * // Semantic search\n * const results = await nexus.memories.search({\n * user_id: 'user_42',\n * query: 'UI preferences',\n * });\n * ```\n */\nexport class MemoryService extends BaseService {\n /**\n * Create a new memory record.\n *\n * @param data - Memory creation payload including user_id, content, and optional type/metadata.\n * @returns The newly created memory with generated ID and timestamps.\n */\n async create(data: MemoryCreate, options?: RequestOptions): Promise<Memory> {\n const parsed = memoryCreateSchema.safeParse(data);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<Memory>('/memories', data, options?.signal);\n }\n\n /**\n * List memories with optional filtering and pagination.\n *\n * @param params - Optional filters for user_id, memory_type, and pagination controls.\n * @returns Paginated list of memory records.\n */\n async list(params?: MemoryListParams, options?: RequestOptions): Promise<MemoryList> {\n return this.http.get<MemoryList>('/memories', params as Record<string, unknown>, options?.signal);\n }\n\n /**\n * Retrieve a single memory by its ID.\n *\n * @param memoryId - UUID of the memory to retrieve.\n * @returns The memory record.\n * @throws {ApiError} 404 if the memory does not exist.\n */\n async get(memoryId: string, options?: RequestOptions): Promise<Memory> {\n return this.http.get<Memory>(`/memories/${memoryId}`, undefined, options?.signal);\n }\n\n /**\n * Update an existing memory record.\n *\n * Supports partial updates -- only the provided fields are modified.\n *\n * @param memoryId - UUID of the memory to update.\n * @param data - Fields to update (content, memory_type, metadata).\n * @returns The updated memory record.\n * @throws {ApiError} 404 if the memory does not exist.\n */\n async update(memoryId: string, data: MemoryUpdate, options?: RequestOptions): Promise<Memory> {\n const parsed = memoryUpdateSchema.safeParse(data);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.patch<Memory>(`/memories/${memoryId}`, data, options?.signal);\n }\n\n /**\n * Delete a memory record.\n *\n * @param memoryId - UUID of the memory to delete.\n * @throws {ApiError} 404 if the memory does not exist.\n */\n async delete(memoryId: string, options?: RequestOptions): Promise<void> {\n return this.http.delete<void>(`/memories/${memoryId}`, options?.signal);\n }\n\n /**\n * Perform semantic similarity search across memories.\n *\n * Uses Mem0's vector search to find memories relevant to the query text.\n * Results are ranked by similarity score and filtered by optional thresholds.\n *\n * @param request - Search parameters including user_id, query, and optional filters.\n * @returns Search results with scored memories and timing metadata.\n */\n async search(request: MemorySearch, options?: RequestOptions): Promise<MemorySearchResult> {\n const parsed = memorySearchSchema.safeParse(request);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<MemorySearchResult>('/memories/search', request, options?.signal);\n }\n\n /**\n * Retrieve the Memory Journal view (US-015).\n *\n * Groups memories chronologically by date for review. Supports both\n * markdown (human-readable) and JSON (programmatic) output formats.\n *\n * @param params - Optional filters for format, date range, and user_id.\n * @returns Journal response with memories grouped by date.\n */\n async journal(params?: MemoryJournalParams, options?: RequestOptions): Promise<JournalResponse> {\n return this.http.get<JournalResponse>('/memories/journal', params as Record<string, unknown>, options?.signal);\n }\n}\n","import { z } from 'zod';\r\n\r\nconst messageRoleSchema = z.enum(['user', 'assistant', 'system', 'tool']);\r\n\r\nexport const conversationCreateSchema = z.object({\r\n user_id: z.string().min(1),\r\n session_id: z.string().optional(),\r\n metadata: z.record(z.unknown()).optional(),\r\n});\r\n\r\nexport const messageCreateSchema = z.object({\r\n role: messageRoleSchema,\r\n content: z.string().min(1).max(50000),\r\n metadata: z.record(z.unknown()).optional(),\r\n});\r\n","/**\n * @module services/conversations\n * @description Conversation Service - Conversation history and auto-summary management.\n *\n * Wraps the Nexus Conversation API powered by Zep OSS. Supports\n * conversation lifecycle management, message operations, and\n * auto-generated summaries via temporal graph analysis.\n *\n * Based on Nexus API v2.0 - /conversations endpoints\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n Conversation,\n ConversationCreate,\n ConversationDetail,\n ConversationList,\n Message,\n MessageCreate,\n MessageList,\n ConversationSummary,\n} from '../types/conversation';\nimport { conversationCreateSchema, messageCreateSchema } from '../schemas/conversation';\nimport { InputValidationError } from '../errors/validation';\n\n/**\n * Parameters for listing conversations with optional filtering and pagination.\n */\nexport interface ConversationListParams {\n /** Filter conversations by user ID */\n user_id?: string;\n /** Maximum number of results per page */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Parameters for listing messages within a conversation.\n */\nexport interface MessageListParams {\n /** Maximum number of messages to return */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Service for managing conversations and messages via Zep OSS.\n *\n * Provides conversation lifecycle management (create, list, get, delete),\n * message operations (add, list), and access to auto-generated summaries\n * produced by Zep's temporal graph analysis.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Create a conversation\n * const conv = await nexus.conversations.create({\n * user_id: 'user_42',\n * metadata: { topic: 'project planning' },\n * });\n *\n * // Add a message\n * await nexus.conversations.addMessage(conv.id, {\n * role: 'user',\n * content: 'Let us discuss the roadmap.',\n * });\n *\n * // Get auto-generated summary\n * const summary = await nexus.conversations.getSummary(conv.id);\n * ```\n */\nexport class ConversationService extends BaseService {\n /**\n * Create a new conversation session.\n *\n * @param data - Conversation creation payload including user_id and optional metadata.\n * @returns The newly created conversation with generated ID and timestamps.\n */\n async create(data: ConversationCreate, options?: RequestOptions): Promise<Conversation> {\n const parsed = conversationCreateSchema.safeParse(data);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<Conversation>('/conversations', data, options?.signal);\n }\n\n /**\n * List conversations with optional filtering and pagination.\n *\n * @param params - Optional filters for user_id and pagination controls.\n * @returns Paginated list of conversation records.\n */\n async list(params?: ConversationListParams, options?: RequestOptions): Promise<ConversationList> {\n return this.http.get<ConversationList>('/conversations', params as Record<string, unknown>, options?.signal);\n }\n\n /**\n * Retrieve a conversation with its messages included.\n *\n * @param conversationId - UUID of the conversation to retrieve.\n * @returns Conversation detail including the full message list.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async get(conversationId: string, options?: RequestOptions): Promise<ConversationDetail> {\n return this.http.get<ConversationDetail>(`/conversations/${conversationId}`, undefined, options?.signal);\n }\n\n /**\n * Add a message to an existing conversation.\n *\n * The message is appended to the conversation's message sequence.\n * Zep will asynchronously update the conversation summary after\n * new messages are added.\n *\n * @param conversationId - UUID of the target conversation.\n * @param message - Message payload including role and content.\n * @returns The newly created message with generated ID and sequence number.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async addMessage(conversationId: string, message: MessageCreate, options?: RequestOptions): Promise<Message> {\n const parsed = messageCreateSchema.safeParse(message);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<Message>(`/conversations/${conversationId}/messages`, message, options?.signal);\n }\n\n /**\n * List messages within a conversation with optional pagination.\n *\n * Messages are returned in chronological order (oldest first).\n *\n * @param conversationId - UUID of the conversation.\n * @param params - Optional pagination controls (limit, offset).\n * @returns Paginated list of messages.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async getMessages(conversationId: string, params?: MessageListParams, options?: RequestOptions): Promise<MessageList> {\n return this.http.get<MessageList>(\n `/conversations/${conversationId}/messages`,\n params as Record<string, unknown>,\n options?.signal,\n );\n }\n\n /**\n * Retrieve the auto-generated summary of a conversation.\n *\n * Summaries are produced by Zep OSS temporal graph analysis and\n * include key points extracted from the conversation history.\n *\n * @param conversationId - UUID of the conversation.\n * @returns The conversation summary with key points and generation timestamp.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async getSummary(conversationId: string, options?: RequestOptions): Promise<ConversationSummary> {\n return this.http.get<ConversationSummary>(`/conversations/${conversationId}/summary`, undefined, options?.signal);\n }\n\n /**\n * Delete a conversation and all its messages.\n *\n * This operation is irreversible. The conversation, all associated\n * messages, and the generated summary will be permanently removed.\n *\n * @param conversationId - UUID of the conversation to delete.\n * @throws {ApiError} 404 if the conversation does not exist.\n */\n async delete(conversationId: string, options?: RequestOptions): Promise<void> {\n return this.http.delete<void>(`/conversations/${conversationId}`, options?.signal);\n }\n}\n","import { z } from 'zod';\r\n\r\nexport const entityCreateSchema = z.object({\r\n name: z.string().min(1),\r\n entity_type: z.string().min(1),\r\n description: z.string().optional(),\r\n properties: z.record(z.unknown()).optional(),\r\n});\r\n\r\nexport const graphQueryRequestSchema = z.object({\r\n entity_name: z.string().min(1),\r\n depth: z.number().int().min(1).max(3).optional(),\r\n relationship_types: z.array(z.string()).optional(),\r\n});\r\n\r\nexport const extractionRequestSchema = z.object({\r\n text: z.string().min(1).max(10000),\r\n agent_id: z.string().optional(),\r\n owner_user_id: z.string().optional(),\r\n});\r\n","/**\n * @module services/knowledge\n * @description Knowledge Service - Knowledge graph construction and query.\n *\n * Wraps the Nexus Knowledge API powered by Fast GraphRAG. Supports\n * entity management, graph traversal queries (BFS), and automatic\n * entity/relationship extraction from unstructured text.\n *\n * Based on Nexus API v2.0 - /knowledge endpoints\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n KnowledgeEntity,\n ExtractionRequest,\n ExtractionResult,\n EntityListResponse,\n GraphQueryRequest,\n GraphQueryResponse,\n} from '../types/knowledge';\nimport { entityCreateSchema, graphQueryRequestSchema, extractionRequestSchema } from '../schemas/knowledge';\nimport { InputValidationError } from '../errors/validation';\n\n/**\n * Request payload for creating a new knowledge entity.\n *\n * POST /knowledge/entities\n */\nexport interface EntityCreate {\n /** Entity display name */\n name: string;\n /** Entity type classification (e.g., Person, Organization, Concept) */\n entity_type: string;\n /** Entity description */\n description?: string;\n /** Additional entity properties */\n properties?: Record<string, unknown>;\n}\n\n/**\n * Parameters for listing knowledge entities with optional filtering.\n */\nexport interface EntityListParams {\n /** Filter entities by user ID (owner) */\n user_id?: string;\n /** Filter by entity type classification */\n entity_type?: string;\n /** Maximum number of results to return */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\n/**\n * Service for managing the knowledge graph via Fast GraphRAG.\n *\n * Provides entity CRUD, BFS graph traversal queries, and automatic\n * entity/relationship extraction from unstructured text. Supports\n * both public (agent-owned) and private (user-owned) knowledge.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Extract entities from text\n * const extraction = await nexus.knowledge.extract({\n * text: 'Alice works at Acme Corp on the Phoenix project.',\n * owner_user_id: 'user_42',\n * });\n *\n * // Query the graph\n * const graph = await nexus.knowledge.query({\n * entity_name: 'Alice',\n * depth: 2,\n * });\n *\n * console.log(graph.paths);\n * ```\n */\nexport class KnowledgeService extends BaseService {\n /**\n * Create a new knowledge entity in the graph.\n *\n * @param data - Entity creation payload including name, type, and optional description/properties.\n * @returns The newly created entity with generated entity_id.\n */\n async createEntity(data: EntityCreate, options?: RequestOptions): Promise<KnowledgeEntity> {\n const parsed = entityCreateSchema.safeParse(data);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<KnowledgeEntity>('/knowledge/entities', data, options?.signal);\n }\n\n /**\n * List knowledge entities with optional filtering.\n *\n * @param params - Optional filters for user_id, entity_type, and pagination controls.\n * @returns Paginated list of knowledge entities.\n */\n async listEntities(params?: EntityListParams, options?: RequestOptions): Promise<EntityListResponse> {\n return this.http.get<EntityListResponse>('/knowledge/entities', params as Record<string, unknown>, options?.signal);\n }\n\n /**\n * Query the knowledge graph using BFS traversal.\n *\n * Starts from a named entity and traverses outward up to the specified\n * depth, collecting all reachable entities and relationships along\n * the traversal paths.\n *\n * @param request - Graph query parameters including starting entity name, depth, and optional relationship type filters.\n * @returns Graph query response with the start entity, traversal paths, and total path count.\n */\n async query(request: GraphQueryRequest, options?: RequestOptions): Promise<GraphQueryResponse> {\n const parsed = graphQueryRequestSchema.safeParse(request);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<GraphQueryResponse>('/knowledge/query', request, options?.signal);\n }\n\n /**\n * Extract entities and relationships from unstructured text.\n *\n * Uses Fast GraphRAG's NLP pipeline to identify named entities and\n * their relationships in Triplex format (Subject, Relation, Object).\n * Extracted items are automatically persisted to the knowledge graph.\n *\n * @param request - Extraction request including the source text and ownership (agent_id or owner_user_id).\n * @returns Extraction result with lists of created entities and relationships.\n */\n async extract(request: ExtractionRequest, options?: RequestOptions): Promise<ExtractionResult> {\n const parsed = extractionRequestSchema.safeParse(request);\n if (!parsed.success) {\n throw new InputValidationError(parsed.error);\n }\n return this.http.post<ExtractionResult>('/knowledge/extract', request, options?.signal);\n }\n}\n","/**\n * @module services/activities\n * @description Activity stream service for passive memory ingestion.\n *\n * AI Agents report their actions (file edits, test runs, API calls, etc.)\n * through the activity stream. These activities are asynchronously converted\n * into semantic memories by the Nexus backend (Arq workers).\n *\n * @see {@link https://docs.nexus.10cg.pub/api/activities | Activity API Reference}\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n Activity,\n ActivityStreamRequest,\n ActivityStreamResponse,\n} from '../types/activity';\n\n/**\n * Service for ingesting activity streams from AI Agents.\n *\n * Activities are the primary mechanism for **passive memory** collection:\n * agents report what they do, and Nexus converts those actions into\n * searchable, contextual memories in the background.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_live_...' });\n *\n * // Log a single activity\n * await nexus.activities.log({\n * action: 'edit_file',\n * activity_data: { path: 'src/index.ts', lines_changed: 42 },\n * });\n *\n * // Batch-ingest multiple activities\n * await nexus.activities.stream({\n * agent_id: 'cursor-agent',\n * activities: [\n * { action: 'read_file', activity_data: { path: 'README.md' } },\n * { action: 'edit_file', activity_data: { path: 'src/app.ts' } },\n * ],\n * });\n * ```\n */\nexport class ActivityService extends BaseService {\n /**\n * Batch-ingest an activity stream.\n *\n * Accepts up to 1000 activities per request. Activities are queued for\n * asynchronous processing by Arq workers on the Nexus backend.\n *\n * @param request - The activity stream payload containing agent ID and activities.\n * @returns Processing summary with accepted / processed / queued counts.\n */\n async stream(request: ActivityStreamRequest, options?: RequestOptions): Promise<ActivityStreamResponse> {\n return this.http.post<ActivityStreamResponse>('/activities/stream', request, options?.signal);\n }\n\n /**\n * Convenience method to log a single activity.\n *\n * Wraps {@link stream} for the common case of reporting one event at a time.\n *\n * @param activity - The activity event to record.\n * @param agentId - Agent identifier (defaults to `'default'`).\n * @returns Processing summary with accepted / processed / queued counts.\n */\n async log(activity: Activity, agentId?: string, options?: RequestOptions): Promise<ActivityStreamResponse> {\n return this.stream({\n agent_id: agentId || 'default',\n activities: [activity],\n }, options);\n }\n}\n","/**\n * @module services/tenants\n * @description Tenant management service for the Nexus platform.\n *\n * Provides access to the current tenant's profile, quota configuration,\n * and usage statistics. Tenant identity is derived from the API key\n * used to authenticate requests.\n *\n * @see {@link https://docs.nexus.10cg.pub/api/tenants | Tenant API Reference}\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type { Tenant, TenantUsage, ApiKey, ApiKeyCreate, ApiKeyCreated } from '../types/tenant';\n\n/**\n * Service for managing the current tenant's profile and usage.\n *\n * The tenant is automatically identified by the API key provided\n * to the {@link NexusClient}. All methods operate on the\n * authenticated tenant's data.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_live_...' });\n *\n * // Get tenant profile\n * const tenant = await nexus.tenants.me();\n * console.log(`Tenant: ${tenant.name} (${tenant.tier})`);\n *\n * // Check resource usage\n * const usage = await nexus.tenants.usage();\n * console.log(`Memories: ${usage.memories_count}`);\n * ```\n */\nexport class TenantService extends BaseService {\n /**\n * Retrieve the current tenant's profile.\n *\n * Returns the tenant record associated with the API key,\n * including name, tier, quotas, and current usage snapshot.\n *\n * @returns The authenticated tenant's profile.\n */\n async me(options?: RequestOptions): Promise<Tenant> {\n return this.http.get<Tenant>('/tenants/me', undefined, options?.signal);\n }\n\n /**\n * Retrieve the current tenant's resource usage statistics.\n *\n * Returns counts for memories, conversations, and today's API calls.\n * Useful for monitoring quota consumption and building dashboards.\n *\n * @returns Current resource usage for the authenticated tenant.\n */\n async usage(options?: RequestOptions): Promise<TenantUsage> {\n return this.http.get<TenantUsage>('/tenants/me/usage', undefined, options?.signal);\n }\n\n /**\n * List all API keys for the current tenant.\n *\n * @returns Array of API key records (without full key values).\n */\n async listApiKeys(options?: RequestOptions): Promise<ApiKey[]> {\n return this.http.get<ApiKey[]>('/tenants/me/api-keys', undefined, options?.signal);\n }\n\n /**\n * Create a new API key for the current tenant.\n *\n * @param data - API key creation parameters (name, scopes, expiry).\n * @returns The newly created API key, including the full key value (shown only once).\n */\n async createApiKey(data: ApiKeyCreate, options?: RequestOptions): Promise<ApiKeyCreated> {\n return this.http.post<ApiKeyCreated>('/tenants/me/api-keys', data, options?.signal);\n }\n\n /**\n * Revoke (delete) an API key.\n *\n * @param id - The UUID of the API key to revoke.\n */\n async revokeApiKey(id: string, options?: RequestOptions): Promise<void> {\n return this.http.delete<void>(`/tenants/me/api-keys/${id}`, options?.signal);\n }\n}\n","/**\n * @module services/feedback\n * @description Feedback Service — submit and query context-retrieval feedback.\n *\n * Wraps the Nexus Feedback Loop API (v5.0):\n * - PUT /v1/feedback/{retrieve_id} — submit an explicit rating (L2 signal)\n * - GET /v1/feedback — list feedback records for reporting\n *\n * The `retrieve_id` in each submission links back to a prior\n * `/context/retrieve` response, enabling the quality scoring pipeline to\n * correlate explicit feedback with L0 telemetry.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Submit feedback after a context retrieval\n * const result = await nexus.feedback.submit('retrieve-uuid', {\n * rating: 4,\n * item_feedback: [{ memory_id: 'mem-uuid', useful: true }],\n * });\n *\n * // List recent feedback\n * const list = await nexus.feedback.list({ user_id: 'user_42', limit: 20 });\n * ```\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type {\n FeedbackSubmitRequest,\n FeedbackResponse,\n FeedbackListResponse,\n} from '../types/feedback';\n\n/**\n * Query parameters for listing feedback records.\n */\nexport interface FeedbackListParams {\n /** Filter feedback records by user ID. */\n user_id?: string;\n /** Maximum number of records to return. */\n limit?: number;\n /** Zero-based offset for pagination. */\n offset?: number;\n}\n\n/**\n * Service for submitting and querying context-retrieval feedback.\n *\n * Exposes the Nexus Feedback Loop v5.0 endpoints. Feedback submissions\n * are processed asynchronously by the QualityScoreWorker and feed into\n * memory re-ranking.\n */\nexport class FeedbackService extends BaseService {\n /**\n * Submit explicit feedback for a prior context retrieval (L2 signal).\n *\n * The backend accepts the submission immediately (HTTP 202) and processes\n * quality scoring asynchronously via QualityScoreWorker.\n *\n * @param retrieveId - The `retrieve_id` returned by `/context/retrieve`.\n * @param data - Rating and optional per-item feedback.\n * @param options - Optional request options (e.g. AbortSignal).\n * @returns The created feedback record metadata.\n */\n async submit(\n retrieveId: string,\n data: FeedbackSubmitRequest,\n options?: RequestOptions,\n ): Promise<FeedbackResponse> {\n return this.http.put<FeedbackResponse>(\n `/feedback/${retrieveId}`,\n data,\n options?.signal,\n );\n }\n\n /**\n * List feedback records with optional filtering and pagination.\n *\n * @param params - Optional filters: `user_id`, `limit`, `offset`.\n * @param options - Optional request options (e.g. AbortSignal).\n * @returns Paginated list of feedback records.\n */\n async list(\n params?: FeedbackListParams,\n options?: RequestOptions,\n ): Promise<FeedbackListResponse> {\n const query = new URLSearchParams();\n if (params?.user_id) query.set('user_id', params.user_id);\n if (params?.limit !== undefined) query.set('limit', String(params.limit));\n if (params?.offset !== undefined) query.set('offset', String(params.offset));\n const qs = query.toString();\n return this.http.get<FeedbackListResponse>(\n `/feedback${qs ? `?${qs}` : ''}`,\n undefined,\n options?.signal,\n );\n }\n}\n","/**\n * @module services/errors\n * @description Error Reporting Service — submit structured error reports.\n *\n * Wraps the Nexus Error Reporting API (US-031):\n * - POST /v1/errors — submit a structured error/bug report\n *\n * Errors are automatically deduplicated server-side by fingerprint\n * (SHA256 of error_type + endpoint + status_code).\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({ apiKey: 'nx_test_abc123' });\n *\n * // Manual error report\n * const report = await nexus.errors.submit({\n * error_type: 'api_error',\n * severity: 'major',\n * description: 'Context retrieval returned empty despite known data',\n * retrieve_id: 'uuid-from-retrieve-call',\n * });\n * ```\n */\n\nimport { BaseService } from './base';\nimport type { RequestOptions } from './base';\nimport type { ErrorReportRequest, ErrorReportResponse } from '../types/error';\n\n/**\n * Service for submitting structured error reports.\n *\n * Reports are deduplicated server-side: repeated submissions with the\n * same fingerprint increment `occurrence_count` instead of creating\n * new records.\n */\nexport class ErrorService extends BaseService {\n /**\n * Submit a structured error report.\n *\n * @param data - Error report payload.\n * @param options - Optional request options (e.g. AbortSignal).\n * @returns The created or updated error report metadata.\n */\n async submit(\n data: ErrorReportRequest,\n options?: RequestOptions,\n ): Promise<ErrorReportResponse> {\n return this.http.post<ErrorReportResponse>(\n '/errors',\n data,\n options?.signal,\n );\n }\n}\n","/**\n * @module client\n * @description Main entry point for the Nexus SDK.\n *\n * The {@link NexusClient} class is the single object that SDK consumers\n * instantiate. It resolves configuration, creates a shared HTTP transport,\n * and exposes every domain service as a readonly property.\n */\n\nimport { resolveConfig } from './config';\nimport type { NexusConfig } from './config';\nimport { HttpClient } from './http';\nimport { OfflineQueue } from './http/queue';\nimport { ContextService } from './services/context';\nimport { MemoryService } from './services/memories';\nimport { ConversationService } from './services/conversations';\nimport { KnowledgeService } from './services/knowledge';\nimport { ActivityService } from './services/activities';\nimport { TenantService } from './services/tenants';\nimport { FeedbackService } from './services/feedback';\nimport { ErrorService } from './services/errors';\n\n/**\n * Nexus AI Cognitive Services SDK client.\n *\n * Create a single instance and use the service properties to interact\n * with the Nexus platform.\n *\n * @example\n * ```typescript\n * const nexus = new NexusClient({\n * apiKey: process.env.NEXUS_API_KEY!,\n * });\n *\n * // Aggregated context retrieval (Chat main flow)\n * const ctx = await nexus.context.retrieve({\n * user_id: 'user123',\n * query: '用户偏好',\n * });\n *\n * // Memory search\n * const memories = await nexus.memories.search({\n * user_id: 'user123',\n * query: 'favourite colour',\n * });\n * ```\n */\nexport class NexusClient {\n /** Aggregated context retrieval (Chat main flow). */\n public readonly context: ContextService;\n\n /** Memory CRUD, search, and journal. */\n public readonly memories: MemoryService;\n\n /** Conversation lifecycle and messages. */\n public readonly conversations: ConversationService;\n\n /** Knowledge graph entities and queries. */\n public readonly knowledge: KnowledgeService;\n\n /** Activity stream ingestion for passive memory. */\n public readonly activities: ActivityService;\n\n /** Tenant profile and usage management. */\n public readonly tenants: TenantService;\n\n /** Feedback loop — submit ratings and query feedback records (v5.0). */\n public readonly feedback: FeedbackService;\n\n /** Error reporting — submit structured error reports (US-031). */\n public readonly errors: ErrorService;\n\n /** @internal Shared HTTP transport. */\n private readonly http: HttpClient;\n\n /**\n * Create a new Nexus SDK client.\n *\n * @param config - SDK configuration. Only `apiKey` is required; all other\n * fields fall back to sensible defaults (see {@link resolveConfig}).\n *\n * @throws {Error} If `apiKey` is missing or empty.\n */\n constructor(config: NexusConfig) {\n const resolved = resolveConfig(config);\n this.http = new HttpClient(resolved);\n\n this.context = new ContextService(this.http);\n this.memories = new MemoryService(this.http);\n this.conversations = new ConversationService(this.http);\n this.knowledge = new KnowledgeService(this.http);\n this.activities = new ActivityService(this.http);\n this.tenants = new TenantService(this.http);\n this.feedback = new FeedbackService(this.http);\n this.errors = new ErrorService(this.http);\n\n // Wire up auto error reporting if enabled.\n if (resolved.autoErrorReport) {\n this.http.onApiError = (statusCode, method, url, detail) => {\n this.errors\n .submit({\n error_type: 'api_error',\n severity: statusCode >= 500 ? 'major' : 'minor',\n description: `${method} ${url} → ${statusCode}: ${detail}`,\n request_context: { method, url, status_code: statusCode },\n })\n .catch(() => {\n // Fire-and-forget: never propagate auto-report failures.\n });\n };\n }\n }\n\n /**\n * Access the offline queue instance (if offline mode is enabled).\n */\n get queue(): OfflineQueue | undefined {\n return this.http.queue;\n }\n\n /**\n * Set the online/offline status of the client.\n *\n * When transitioning from offline to online, queued requests are\n * automatically flushed.\n */\n setOnline(online: boolean): void {\n this.http.setOnline(online);\n }\n}\n","import { z } from 'zod';\r\n\r\nconst apiKeyScopeSchema = z.enum(['read', 'write', 'admin']);\r\n\r\nexport const apiKeyCreateSchema = z.object({\r\n name: z.string().min(1).max(100),\r\n scopes: z.array(apiKeyScopeSchema).optional(),\r\n expires_days: z.number().int().min(1).max(365).optional(),\r\n});\r\n"],"mappings":";;;;;;;;;;;;;;;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