Shared Types
@divinci-ai/types is the shared type vocabulary for the entire SDK. The client,
server, and MCP packages all depend on it, so a ChatMessage is the same shape
everywhere. It ships as a transitive dependency — you rarely install it directly,
but you can import its types for your own function signatures.
npm install @divinci-ai/typesimport type { ChatMessage, Release, RagDocument } from "@divinci-ai/types";The package also re-exports runtime helpers under subpaths:
| Import | Provides |
|---|---|
@divinci-ai/types | All the type definitions on this page. |
@divinci-ai/types/schemas | Zod schemas mirroring the types (import { schemas } or named e.g. ChatMessageSchema). |
@divinci-ai/types/validation | validate, validateOrThrow runtime validators. |
@divinci-ai/types/guards | Type guards: isChatMessage, isUser, … |
From common.ts — primitives and wrappers shared by every resource.
/** MongoDB ObjectId rendered as a string. */type ObjectId = string;/** Milliseconds since epoch. */type Timestamp = number;/** ISO 8601 date string. */type ISODateString = string;
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
interface PaginationOptions { limit?: number; cursor?: string; page?: number; // alternative to cursor}
interface PaginatedResponse<T> { data: T[]; hasMore: boolean; nextCursor?: string; total?: number;}
interface DateRange { startDate?: string; // ISO 8601 endDate?: string;}
interface SortOptions { field: string; direction: "asc" | "desc";}
interface ApiResponse<T> { success: boolean; data?: T; error?: { code: string; message: string; details?: Record<string, unknown> };}
/** Created/updated/createdBy stamps attached to most resources. */interface ResourceMetadata { createdAt: ISODateString; updatedAt: ISODateString; createdBy?: ObjectId;}From chat.ts — messages, threads, and send options. See the
Client Chat guide for usage.
type MessageRole = "user" | "assistant" | "system";type MessageContentType = "text" | "image" | "audio" | "file";type ChatVisibility = "private" | "shared" | "public";
interface ChatMessage { id: ObjectId; chatId?: ObjectId; role: MessageRole; content: string; contentType?: MessageContentType; timestamp: ISODateString; tokenCount?: number; context?: ChatMessageContext[]; // RAG sources (context bubbles) products?: ProductRecommendation[]; // catalog matches reactions?: MessageReaction[]; metadata?: Record<string, unknown>; arenaVariants?: ArenaResponseVariant[]; arenaSelectedIndex?: number; arenaStreamingStatus?: ArenaStreamingStatus; arenaExpectedVariants?: number;}
interface ChatThread { id: ObjectId; title?: string; releaseId: ObjectId; ownerId: ObjectId; workspaceId?: ObjectId; messageCount: number; lastMessageAt?: ISODateString; visibility: ChatVisibility; archived: boolean; metadata: ResourceMetadata;}
interface SendMessageOptions { content: string; contentType?: MessageContentType; attachments?: MessageAttachment[]; stream?: boolean; metadata?: Record<string, unknown>; assistantName?: string; // pick a specific assistant replyTo?: string; // reply to a message id override?: SendMessageOverride; // BYOK-pinned releases only}
interface ChatResponse { message: ChatMessage; usage: ChatUsage; context?: ChatMessageContext[];}
interface ChatUsage { promptTokens: number; completionTokens: number; totalTokens: number; estimatedCostUsd?: number;}
interface CreateChatOptions { releaseId: ObjectId; title?: string; systemMessage?: string; visibility?: ChatVisibility; metadata?: Record<string, unknown>;}Also exported: ChatMessageContext, ProductRecommendation, MessageReaction,
MessageAttachment, MessageSentiment, MessageFeedbackInput,
AnonymousFeedbackInput, SendMessageOverride, ChatStreamChunk,
ListChatsOptions.
Releases
Section titled “Releases”From release.ts — the deployable assistant configuration. See
Server Releases.
type ReleaseStatus = "draft" | "active" | "archived";type ReleaseAuthMode = "anonymous" | "required" | "optional";
/** A model reference used for the primary assistant and each fallback. */interface WhiteLabelReleaseAssistant { id: string; // catalog model id finetune: boolean; // true if `id` is a fine-tuned model}
interface Release { id: ObjectId; name: string; status: ReleaseStatus; workspaceId: ObjectId; authMode: ReleaseAuthMode; config: ReleaseConfig; theme?: ReleaseTheme; allowedOrigins: string[]; /** Ordered fallback chain; first success wins on retryable primary failure. */ fallbackAssistants?: WhiteLabelReleaseAssistant[]; /** MCP server exposure (see Release as an MCP Server). */ mcpConfig?: ReleaseMcpConfig; metadata: ResourceMetadata;}
interface ReleaseMcpConfig { enabled: boolean; exposedTools?: string[]; allowedScopes?: string[]; mcpRateLimit?: { requestsPerMinute: number; requestsPerDay: number }; allowAnonymousMcp?: boolean; maxSpendPerTokenCents?: number;}
interface ReleaseConfig { model?: string; systemPrompt?: string; maxTokens?: number; temperature?: number; // 0–2 ragCollectionIds?: ObjectId[]; contextBubbles?: boolean; productRecommendations?: boolean; helpRequests?: boolean; notifications?: boolean; metrics?: boolean; welcomeMessage?: string; chatDisclaimer?: string; conversationStarters?: string[]; byokId?: ObjectId; // route inference through a BYOK provider}
interface ReleaseTheme { primaryColor?: string; secondaryColor?: string; backgroundColor?: string; textColor?: string; fontFamily?: string; logoUrl?: string; faviconUrl?: string; darkMode?: boolean; customCss?: string;}
interface CreateReleaseOptions { name: string; workspaceId: ObjectId; authMode?: ReleaseAuthMode; config?: Partial<ReleaseConfig>; theme?: Partial<ReleaseTheme>; allowedOrigins?: string[]; fallbackAssistants?: WhiteLabelReleaseAssistant[];}Also exported: ContextCacheMode, ContextCacheUpdate, UpdateReleaseOptions,
ListReleasesOptions.
Workspaces
Section titled “Workspaces”From workspace.ts — the top-level container (white-label). See
Server Workspaces.
type WorkspaceMemberRole = "owner" | "admin" | "editor" | "viewer";
interface Workspace { id: ObjectId; name: string; slug: string; description?: string; ownerId: ObjectId; settings: WorkspaceSettings; limits: WorkspaceLimits; metadata: ResourceMetadata;}
interface WorkspaceSettings { defaultModel?: string; defaultTemperature?: number; analyticsEnabled?: boolean; webhooksEnabled?: boolean; notificationEmail?: string;}
interface WorkspaceLimits { maxReleases: number; maxRagCollections: number; maxRagStorageBytes: number; maxMonthlyApiCalls: number; maxConcurrentChats: number;}
interface WorkspaceMember { userId: ObjectId; role: WorkspaceMemberRole; permissions: string[]; joinedAt: string;}Also exported: CreateWorkspaceOptions, UpdateWorkspaceOptions,
ListWorkspacesOptions.
Users & tiers
Section titled “Users & tiers”From user.ts — end-user identity and membership tiers.
type MembershipTier = "free" | "basic" | "premium" | "enterprise" | "unlimited";
interface User { id: ObjectId; email?: string; name?: string; nickname?: string; picture?: string; emailVerified?: boolean; metadata?: UserMetadata;}
interface ApiKeyUser { id: ObjectId; apiKeyId: ObjectId; externalUserId?: string; // id from your system email?: string; nickname?: string; picture?: string; membershipTier: MembershipTier; lastUsedAt?: ISODateString; createdAt: ISODateString;}
interface TierConfig { tier: MembershipTier; limits: TierLimits;}
interface TierLimits { messagesPerMonth: number; messagesPerDay: number; maxTokensPerMessage: number; maxConcurrentChats: number;}
interface QuotaStatus { tier: MembershipTier; usage: { messagesThisMonth: number; messagesToday: number }; remaining: { messagesThisMonth: number; messagesToday: number }; exceeded: boolean;}DEFAULT_TIER_LIMITS: Record<MembershipTier, TierLimits> is exported as a runtime
constant with the built-in defaults for each tier. Also exported: UserMetadata.
API keys
Section titled “API keys”From api-key.ts — workspace-scoped keys. See Server API Keys.
type ApiKeyStatus = "active" | "revoked" | "expired";
interface ApiKey { id: ObjectId; workspaceId: ObjectId; name: string; keyPrefix: string; // first 8 chars, for identification status: ApiKeyStatus; allowedOrigins: string[]; permissions: string[]; allowedTiers?: MembershipTier[]; customTierLimits?: Record<MembershipTier, Partial<TierLimits>>; rateLimit?: number; // requests per minute lastUsedAt?: ISODateString; expiresAt?: ISODateString; createdAt: ISODateString;}
/** Only returned once, on creation/rotation. */interface ApiKeyWithSecret extends ApiKey { secret: string;}Also exported: CreateApiKeyOptions, UpdateApiKeyOptions, ListApiKeysOptions,
ApiKeyUsageStats.
From rag.ts — collections, documents, and search results. See
Server RAG.
type RagCollectionStatus = "active" | "processing" | "error" | "archived";
type RagDocumentStatus = | "pending" | "uploading" | "processing" | "chunking" | "embedding" | "completed" | "error";
interface RagCollection { id: ObjectId; name: string; description?: string; workspaceId: ObjectId; status: RagCollectionStatus; documentCount: number; chunkCount: number; storageSizeBytes: number; embeddingModel: string; settings: RagCollectionSettings; metadata: ResourceMetadata;}
interface RagCollectionSettings { chunkSize: number; // tokens chunkOverlap: number; // tokens maxChunksPerQuery: number; similarityThreshold: number; // 0–1}
interface RagDocument { id: ObjectId; collectionId: ObjectId; originalName: string; fileType: string; mimeType: string; fileSizeBytes: number; status: RagDocumentStatus; chunkCount: number; error?: string; sourceUrl?: string; // backlink shown on chat context bubbles documentMetadata?: Record<string, unknown>; metadata: ResourceMetadata;}
interface RagSearchResult { chunk: RagChunk; score: number; // 0–1 document: { id: ObjectId; originalName: string; fileType: string };}Compression strategies are exported as a runtime constant + union:
const COMPRESSION_STRATEGIES = [ "none", "exit", "llmlingua2", "recomp-extractive", "recomp-abstractive", "pisco", "clara", "core-rag",] as const;type CompressionStrategy = typeof COMPRESSION_STRATEGIES[number];
const COMPRESSION_RATIO_MIN = 2; // keep 50% of tokensconst COMPRESSION_RATIO_MAX = 128; // keep ~0.8% of tokensAlso exported: RagChunk, CreateRagCollectionOptions, UploadDocumentOptions,
RagSearchOptions, ListDocumentsOptions.
Configuration & x402
Section titled “Configuration & x402”From config.ts — SDK constructor options and the x402 payment surface.
interface DivinciConfig { apiKey?: string; baseUrl?: string; apiVersion?: string; timeout?: number; maxRetries?: number; headers?: Record<string, string>; debug?: boolean;}
interface DivinciClientConfig extends DivinciConfig { releaseId: string; // required streaming?: boolean; externalUser?: ExternalUserConfig; userToken?: string; wsBaseUrl?: string; workspaceId?: string;}
interface DivinciServerConfig extends DivinciConfig { apiKey: string; // required unless accessToken is set accessToken?: string; defaultWorkspaceId?: string; x402?: X402Config;}
interface ExternalUserConfig { userId: string; // required email?: string; name?: string; nickname?: string; picture?: string; membershipTier?: string; metadata?: Record<string, unknown>;}
interface X402Config { enabled?: boolean; wallet?: X402Wallet; autoPayment?: boolean; maxPaymentUsd?: number; network?: "base" | "base-sepolia";}
/** Signs (does not broadcast) an EIP-3009 transfer authorization. */interface X402Wallet { getAddress(): Promise<string>; pay(details: X402PaymentDetails): Promise<X402PaymentReceipt>;}DEFAULT_CONFIG (default baseUrl, apiVersion, timeout, maxRetries) and
API_ENDPOINTS are exported as runtime constants. Also exported:
X402PaymentDetails, X402Authorization, X402PaymentReceipt.
Errors
Section titled “Errors”From errors.ts — the data shapes behind the SDK error classes (see
Error Handling).
interface DivinciErrorData { code: string; message: string; status?: number; details?: Record<string, unknown>; requestId?: string;}
/** Stable machine-readable codes (e.g. "rate_limited", "payment_required"). */const ErrorCodes = { /* UNAUTHORIZED, VALIDATION_ERROR, RATE_LIMITED, … */ } as const;type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
interface RateLimitErrorDetails { limit: number; remaining: number; resetAt: number; // Unix timestamp retryAfter: number; // seconds}
interface PaymentRequiredDetails { x402Version: string; amountUsd: number; amountMicro: number; network: string; // base | base-sepolia asset: string; // USDC recipient: string; resource: string; facilitatorUrl: string;}Also exported: FieldValidationError, ValidationErrorDetails.
From arena.ts — model A/B comparison. This is a large surface; see
Server Arena for usage and the
source
for full definitions.
Key exports: ArenaMode, ArenaConfig, ArenaVariant, ArenaResponseVariant,
ArenaStreamingStatus, ArenaInlineScores, PipelineTimingMetrics,
ArenaEnableBody / ArenaEnableResponse, ArenaResultsResponse,
ArenaSelectResponse, ArenaTestBody / ArenaTestResponse,
ArenaCostEstimateBody / ArenaCostEstimateResponse, ArenaPreset,
CreateArenaPresetBody / UpdateArenaPresetBody, ArenaPresetExportFormat,
ArenaRoutingEstimateBody / ArenaRoutingEstimateResponse.
Meta-harness
Section titled “Meta-harness”From meta-harness.ts — autonomous orchestration loops. See the
source.
Key exports: AutonomyLevel, OrchestrationLoopStatus, IterationStatus,
ProposalKind, ProposalStatus, MetaHarnessLoop, MetaHarnessLoopConfig,
UpdateLoopConfigOptions, MetaHarnessIteration, IterationReport,
MetaHarnessProposal, ListIterationsOptions, ListProposalsOptions,
RejectProposalOptions.