@juspay/neurolink
Version:
Universal AI Development Platform with working MCP integration, multi-provider support, voice (TTS/STT/realtime), and professional CLI. 58+ external MCP servers discoverable, multimodal file processing, RAG pipelines. Build, test, and deploy AI applicatio
472 lines (471 loc) • 15 kB
TypeScript
/**
* Context Types for NeuroLink - Factory Pattern Implementation
* Provides type-safe context integration for AI generation
*/
import type { ExecutionContext } from "../types/tools.js";
import type { JsonObject } from "./common.js";
import type { ChatMessage, ConversationMemoryConfig } from "./conversation.js";
/**
* Base context type for all AI operations
*/
export type BaseContext = {
userId?: string;
sessionId?: string;
requestId?: string;
userRole?: string;
userPreferences?: JsonObject;
userMetadata?: JsonObject;
applicationContext?: {
name: string;
version?: string;
environment?: "development" | "staging" | "production";
};
organizationId?: string;
departmentId?: string;
projectId?: string;
[key: string]: unknown;
};
/**
* Context integration mode types
*/
type ContextIntegrationMode = "prompt_prefix" | "prompt_suffix" | "system_prompt" | "metadata_only" | "structured_prompt" | "none";
/**
* Context configuration for AI generation
*/
export type ContextConfig = {
mode: ContextIntegrationMode;
includeInPrompt?: boolean;
includeInAnalytics?: boolean;
includeInEvaluation?: boolean;
template?: string;
maxLength?: number;
};
/**
* Context processing result
*/
type ProcessedContext = {
originalContext: BaseContext;
processedContext: string | null;
config: ContextConfig;
metadata: {
truncated: boolean;
processingTime: number;
template: string;
mode: ContextIntegrationMode;
};
};
/**
* Configuration for framework fields exclusion
* Can be customized per application or environment
*/
export type FrameworkFieldsConfig = {
defaultFields: string[];
additionalFields?: string[];
overrideFields?: string[];
includeFields?: string[];
};
/**
* Factory for context processing
*/
export declare class ContextFactory {
/**
* Default framework fields configuration
*/
static readonly DEFAULT_FRAMEWORK_FIELDS: FrameworkFieldsConfig;
/**
* Current framework fields configuration
*/
private static frameworkFieldsConfig;
/**
* Flag to track if framework fields have been initialized
*/
private static isFrameworkFieldsInitialized;
/**
* Configure framework fields for exclusion from custom data
*/
static configureFrameworkFields(config: Partial<FrameworkFieldsConfig>): void;
/**
* Get current framework fields configuration
* Ensures lazy initialization if not already loaded
*/
static getFrameworkFieldsConfig(): FrameworkFieldsConfig;
/**
* Reset framework fields configuration to default
*/
static resetFrameworkFieldsConfig(): void;
/**
* Load framework fields configuration from environment variables
* Supports NEUROLINK_CONTEXT_EXCLUDE_FIELDS and NEUROLINK_CONTEXT_INCLUDE_FIELDS
*/
static loadFrameworkFieldsFromEnv(): void;
/**
* Add additional fields to exclude
*/
static addFrameworkFieldsToExclude(fields: string[]): void;
/**
* Add fields to include (override exclusion)
*/
static addFrameworkFieldsToInclude(fields: string[]): void;
/**
* Default context configuration
*/
static readonly DEFAULT_CONFIG: ContextConfig;
/**
* Validate and normalize context data
*/
static validateContext(context: unknown): BaseContext | null;
/**
* Process context for AI generation based on configuration
*/
static processContext(context: BaseContext, config?: Partial<ContextConfig>): ProcessedContext;
/**
* Format context for prompt integration
*/
private static formatContextForPrompt;
/**
* Format context as prompt prefix
*/
private static formatAsPrefix;
/**
* Format context as prompt suffix
*/
private static formatAsSuffix;
/**
* Format context for system prompt
*/
private static formatForSystemPrompt;
/**
* Format context in structured format
*/
private static formatStructured;
/**
* Extract analytics data from context
*/
static extractAnalyticsContext(context: BaseContext): JsonObject;
/**
* Extract evaluation context
*/
static extractEvaluationContext(context: BaseContext): JsonObject;
}
/**
* Context conversion utilities for domain-specific data
* Replaces hardcoded business context with generic domain context
*/
type ContextConversionOptions = {
preserveLegacyFields?: boolean;
validateDomainData?: boolean;
includeMetadata?: boolean;
};
export declare class ContextConverter {
/**
* Convert legacy business context to generic domain context
* Based on business context patterns
*/
static convertBusinessContext(legacyContext: Record<string, unknown>, domainType: string, options?: ContextConversionOptions): ExecutionContext;
/**
* Create execution context for required domain
*/
static createDomainContext(domainType: string, domainData: Record<string, unknown>, sessionInfo?: {
sessionId?: string;
userId?: string;
}): ExecutionContext;
private static inferProvider;
private static extractCustomData;
}
/** Stages available in the compaction pipeline. */
export type CompactionStage = "prune" | "deduplicate" | "summarize" | "truncate";
/** Result of multi-stage context compaction. */
export type CompactionResult = {
compacted: boolean;
stagesUsed: CompactionStage[];
tokensBefore: number;
tokensAfter: number;
tokensSaved: number;
messages: ChatMessage[];
};
/** Configuration for the context compaction pipeline. */
export type CompactionConfig = {
enablePrune?: boolean;
enableDeduplicate?: boolean;
enableSummarize?: boolean;
enableTruncate?: boolean;
pruneProtectTokens?: number;
pruneMinimumSavings?: number;
pruneProtectedTools?: string[];
summarizationProvider?: string;
summarizationModel?: string;
keepRecentRatio?: number;
truncationFraction?: number;
provider?: string;
};
/** Result of a context budget check. */
export type BudgetCheckResult = {
/** Whether the request fits within the context window */
withinBudget: boolean;
/** Estimated total input tokens */
estimatedInputTokens: number;
/** Available input tokens for this model */
availableInputTokens: number;
/** Usage ratio (0.0 - 1.0+) */
usageRatio: number;
/** Whether auto-compaction should trigger */
shouldCompact: boolean;
/** Breakdown of token usage by category */
breakdown: {
systemPrompt: number;
conversationHistory: number;
currentPrompt: number;
toolDefinitions: number;
fileAttachments: number;
};
};
/** Parameters for budget checking. */
export type BudgetCheckParams = {
provider: string;
model?: string;
maxTokens?: number;
systemPrompt?: string;
conversationMessages?: Array<{
role: string;
content: string;
}>;
currentPrompt?: string;
toolDefinitions?: unknown[];
fileAttachments?: Array<{
content: string;
}>;
/** Compaction trigger threshold (0.0-1.0). Default: 0.80 */
compactionThreshold?: number;
};
/** A file prepared for potential summarization. */
export type FileForSummarization = {
/** Display name (e.g. "report.pdf") */
fileName: string;
/** Human-readable type label (e.g. "PDF Document") */
fileType: string;
/** Extracted text content */
content: string;
/** Estimated token count (provider-adjusted) */
estimatedTokens: number;
/** Optional MIME type */
mimeType?: string;
/** Original byte size on disk */
originalSize?: number;
};
/** Parameters for `shouldSummarizeFiles()`. */
export type FileSummarizationCheckParams = {
/** AI provider name (e.g. "vertex", "anthropic") */
provider: string;
/** Model name (optional -- falls back to provider default) */
model?: string;
/** Token estimate for the system prompt */
systemPromptTokens: number;
/** Token estimate for conversation history */
conversationHistoryTokens: number;
/** Token estimate for the current user prompt */
currentPromptTokens: number;
/** Token estimate for tool definitions */
toolDefinitionTokens: number;
/** Token estimate for all attached files (sum) */
fileTokens: number;
/** Number of attached files */
fileCount?: number;
/** Explicit maxTokens (output reserve) from user config */
maxTokens?: number;
/** Context usage fraction that triggers summarization (0.0-1.0, default 0.80) */
threshold?: number;
/** Minimum tokens per file in the summarization plan */
minTokensPerFile?: number;
/** Maximum tokens per file in the summarization plan */
maxTokensPerFile?: number;
};
/** Result of `shouldSummarizeFiles()`. */
export type FileSummarizationCheckResult = {
/** Whether summarization is needed */
needsSummarization: boolean;
/** Total estimated input tokens (all categories) */
totalEstimatedTokens: number;
/** Available input tokens for the model */
availableInputTokens: number;
/** Budget remaining for files after non-file content */
availableBudgetForFiles: number;
/** If summarizing, the per-file token budget (undefined when not needed) */
perFileBudget?: number;
};
/** Parameters for `buildFileSummarizationPrompt()`. */
export type FileSummarizationPromptParams = {
/** File display name */
fileName: string;
/** File type label */
fileType: string;
/** Full extracted text of the file */
fileContent: string;
/** The user's original prompt / question */
userPrompt: string;
/** Target output token count for the summary */
targetTokens: number;
};
/** Result item from `planFileSummarization()`. */
export type SummarizedFile = {
/** File display name */
fileName: string;
/** File type label */
fileType: string;
/** Summary text (or original content if not summarized) */
summary: string;
/** Original token estimate */
originalTokens: number;
/** Token estimate of the summary */
summaryTokens: number;
/** Whether this file was actually summarized */
wasSummarized: boolean;
};
/** Plan entry for a single file. */
export type FileSummarizationPlanEntry = {
file: FileForSummarization;
action: "summarize" | "keep";
targetTokens?: number;
};
/** Raw file input before text extraction. */
export type RawFileInput = {
/** File content -- either a UTF-8 string or a raw Buffer */
content: string | Buffer;
/** MIME type (e.g. "application/pdf", "text/plain") */
mimeType: string;
/** Display file name */
fileName: string;
/** Original byte size on disk (optional) */
originalSize?: number;
};
/** Input file for aggregate budget enforcement. */
export type BudgetFileInput = {
name: string;
sizeBytes: number;
/** Optional file type hint for type-aware token estimation */
fileType?: string;
};
/**
* @deprecated Use ToolOutputPreviewOptions instead.
*/
export type TruncateOptions = {
maxBytes?: number;
maxLines?: number;
direction?: "head" | "tail";
saveToDisk?: boolean;
saveDir?: string;
};
/**
* @deprecated Use ToolOutputPreviewResult instead.
*/
export type TruncateResult = {
content: string;
truncated: boolean;
savedPath?: string;
originalSize: number;
};
/** Options for tool output preview generation. */
export type ToolOutputPreviewOptions = {
/** Maximum bytes for the preview (default: 50KB) */
maxBytes?: number;
/** Maximum lines for the preview (default: 2000) */
maxLines?: number;
/** Fraction of preview budget allocated to the head (default: 0.25) */
headRatio?: number;
/** Fraction of preview budget allocated to the tail (default: 0.75) */
tailRatio?: number;
};
/** Result of tool output preview generation. */
export type ToolOutputPreviewResult = {
/** The preview string (or full output if under limits) */
preview: string;
/** Whether truncation was applied */
truncated: boolean;
/** Original byte size of the full output */
originalSize: number;
};
/** Result of tool pair repair. */
export type RepairResult = {
repaired: boolean;
messages: ChatMessage[];
orphanedCallsFixed: number;
orphanedResultsFixed: number;
};
/** Options for summarization prompt building. */
export type SummarizationPromptOptions = {
/**
* Whether this is an incremental update to an existing summary
*/
isIncremental: boolean;
/**
* The previous summary to merge with (required for incremental mode)
*/
previousSummary?: string;
/**
* List of files that have been read during the conversation
*/
filesRead?: string[];
/**
* List of files that have been modified during the conversation
*/
filesModified?: string[];
};
/** Configuration for tool output pruning (Stage 1). */
export type PruneConfig = {
protectTokens?: number;
minimumSavings?: number;
protectedTools?: string[];
provider?: string;
};
/** Result of tool output pruning (Stage 1). */
export type PruneResult = {
pruned: boolean;
messages: ChatMessage[];
tokensSaved: number;
};
/** Configuration for sliding window truncation (Stage 4). */
export type TruncationConfig = {
fraction?: number;
/** Current estimated tokens (enables adaptive mode) */
currentTokens?: number;
/** Target token budget (enables adaptive mode) */
targetTokens?: number;
/** Provider for token estimation (enables adaptive mode) */
provider?: string;
/** Buffer above required reduction (default: 0.15 = 15%) */
adaptiveBuffer?: number;
/** Maximum iterations for adaptive truncation (default: 3) */
maxIterations?: number;
};
/** Result of sliding window truncation (Stage 4). */
export type TruncationResult = {
truncated: boolean;
messages: ChatMessage[];
messagesRemoved: number;
};
/** Configuration for structured LLM summarization (Stage 3). */
export type SummarizeConfig = {
provider?: string;
model?: string;
keepRecentRatio?: number;
memoryConfig?: Partial<ConversationMemoryConfig>;
/** Target token budget — when set, split uses token counting instead of message count */
targetTokens?: number;
};
/** Result of structured LLM summarization (Stage 3). */
export type SummarizeResult = {
summarized: boolean;
messages: ChatMessage[];
summaryText?: string;
};
/** Result of file read deduplication (Stage 2). */
export type DeduplicationResult = {
deduplicated: boolean;
messages: ChatMessage[];
filesDeduped: number;
};
/** Options for FileSummarizationService. */
export type FileSummarizationServiceOptions = {
provider?: string;
model?: string;
};
export {};