TypeGraphTypeGraphTypeGraphDocs
Back to Dashboard
IntroductionGuidesDatabase AdaptersEmbeddersExtraction LLMs
SetupBucketsDocumentsEventsThreadsSearchMemoryGraphJobsPolicyTypes

Types

Full TypeScript type definitions exported by the TypeGraph SDK.

typeTenantId
export type TenantId = Brand<string, 'TenantId'>;
typeGroupId
export type GroupId = Brand<string, 'GroupId'>;
typeUserId
export type UserId = Brand<string, 'UserId'>;
typeAgentId
export type AgentId = Brand<string, 'AgentId'>;
typeThreadId
export type ThreadId = Brand<string, 'ThreadId'>;
typeEntityId
export type EntityId = Brand<string, 'EntityId'>;
interfaceEntityRef
export interface EntityRef {
    type: string;
    id: string;
}
interfaceTypeGraphContext
/**
 * Public request context for TypeGraph operations.
 *
 * The TypeGraph client configuration owns the hard tenant namespace boundary.
 * Graph configuration owns read/write access. Context identifies the actor.
 */
export interface TypeGraphContext {
    organizationId?: OrganizationId | string | undefined;
    groupId?: GroupId | string | undefined;
    userId?: UserId | string | undefined;
    agentId?: AgentId | string | undefined;
    threadId?: ThreadId | string | undefined;
    /** Human-readable agent name. Maps to gen_ai.agent.name in OpenTelemetry. */
    agentName?: string | undefined;
    /** Agent description. Maps to gen_ai.agent.description in OpenTelemetry. */
    agentDescription?: string | undefined;
    /** Agent version string. Maps to gen_ai.agent.version in OpenTelemetry. */
    agentVersion?: string | undefined;
    /** OpenTelemetry trace ID for distributed tracing correlation. */
    traceId?: string | undefined;
    /** OpenTelemetry span ID for distributed tracing correlation. */
    spanId?: string | undefined;
}
interfaceTypeGraphOptions
export interface TypeGraphOptions {
    context?: TypeGraphContext | undefined;
    abortSignal?: AbortSignal | undefined;
}
interfaceTypeGraphWriteOptions
export interface TypeGraphWriteOptions extends TypeGraphOptions {
    bucketId?: string | undefined;
    graphExtraction?: boolean | undefined;
    idempotencyKey?: string | undefined;
}
interfacetypegraphConfig
export interface typegraphConfig {
    /** API key for typegraph cloud. When provided, vectorStore and embedding are not required. */
    apiKey?: string | undefined;
    /** Base URL for the cloud API. Defaults to 'https://api.typegraph.dev'. */
    baseUrl?: string | undefined;
    /** Request timeout in milliseconds for cloud mode. Default: 30000. */
    timeout?: number | undefined;
    vectorStore?: VectorStoreAdapter | undefined;
    /** Default embedder for ingest and search. Required in self-hosted mode. */
    embedding?: EmbeddingConfig | undefined;
    /** Optional separate default search embedding. Must embed into the same vector space as `embedding`.
     *  When set, all buckets use this for search unless overridden per-bucket. */
    searchEmbedding?: EmbeddingConfig | undefined;
    /** Register additional embedders for per-bucket overrides.
     *  Each provider is keyed by its `.model` string. Buckets reference these by model name. */
    additionalEmbeddings?: EmbeddingConfig[] | undefined;
    tenantId?: string | undefined;
    tokenizer?: ((text: string) => number) | undefined;
    hooks?: typegraphHooks | undefined;
    /** Optional LLM provider for triple extraction, query classification, and memory operations. */
    llm?: LLMConfig | undefined;
    /** Optional custom extractor. When omitted, TypeGraph uses its internal default extractor. */
    extractor?: Extractor | undefined;
    /** Named graph overlays. The public graph is created automatically when omitted. */
    graphs?: Record<string, GraphConfig> | undefined;
    /** Optional bucket definitions loaded during deploy/init. Buckets route writes to graphs. */
    buckets?: Record<string, Omit<CreateBucketInput, 'id'> & {
        id?: string | undefined;
    }> | undefined;
    /** Optional short-lived cache for cross-source entity coreference context. */
    extractionCoreferenceCache?: ExtractionCoreferenceCache | undefined;
    /** Optional reranker for search result post-processing. */
    reranker?: Reranker | undefined;
    /** Config-driven ontology for deploy/init; cloud can cache this, self-hosted can pass it at process init. */
    ontology?: OntologyConfig | undefined;
    /** Optional event sink for observability. Events are emitted fire-and-forget. */
    eventSink?: typegraphEventSink | undefined;
    /** Optional policy store for governance. When provided, actions are checked against active policy. */
    policyStore?: PolicyStoreAdapter | undefined;
    /** Optional logger for debugging. */
    logger?: typegraphLogger | undefined;
}
interfaceCloudConfig
export interface CloudConfig {
    /** API key for the typegraph cloud service. */
    apiKey: string;
    /** Base URL for the cloud API. Defaults to 'https://typegraph.ai/api'. */
    baseUrl?: string | undefined;
    /** Default tenant ID for all operations. */
    tenantId?: string | undefined;
    /** Request timeout in milliseconds. Default: 30000. */
    timeout?: number | undefined;
}
interfacetypegraphInstance
/** The typegraph instance interface — all public methods. */
export interface typegraphInstance {
    /** One-off infrastructure provisioning. Creates all tables/extensions. Idempotent. */
    deploy(config: typegraphConfig): Promise<this>;
    /** Lightweight runtime init. Registers jobs, loads state. No DDL. */
    initialize(config: typegraphConfig): Promise<this>;
    /** Remove all typegraph infrastructure. Refuses if any table contains data. */
    undeploy(): Promise<UndeployResult>;
    bucket: BucketsApi;
    document: DocumentsApi;
    event: EventsApi;
    thread: ThreadsApi;
    job: JobsApi;
    memory: MemoryApi;
    /** Graph exploration API. Requires graph storage. */
    graph: GraphApi;
    getEmbeddingForBucket(bucketId: string): Embedder;
    getSearchEmbeddingForBucket(bucketId: string): Embedder;
    getDistinctEmbeddings(bucketIds?: string[]): Map<string, Embedder>;
    groupBucketsByModel(bucketIds?: string[]): Map<string, string[]>;
    /** Search across buckets. Optionally build an LLM-ready prompt via opts.promptBuilder. */
    search(text: string, opts?: SearchOptions | null): Promise<QueryResponse>;
    policy: {
        create(input: CreatePolicyInput, opts?: TelemetryOpts | null): Promise<Policy>;
        get(id: string): Promise<Policy | null>;
        list(filter?: {
            tenantId?: string;
            policyType?: PolicyType;
            enabled?: boolean;
        } | null): Promise<Policy[]>;
        update(id: string, input: UpdatePolicyInput, opts?: TelemetryOpts | null): Promise<Policy>;
        delete(id: string, opts?: TelemetryOpts | null): Promise<void>;
    };
    /**
     * Drain any buffered telemetry events to the event sink. Safe to call from
     * the end of a request handler or before a short-lived script exits to
     * avoid losing fire-and-forget events that are still in-buffer.
     */
    flush(): Promise<void>;
    destroy(): Promise<void>;
}
interfaceBucketsApi
export interface BucketsApi {
    create(input: CreateBucketInput, opts?: TypeGraphOptions | null): Promise<Bucket>;
    upsert(input: CreateBucketInput & {
        id: string;
    }, opts?: TypeGraphOptions | null): Promise<Bucket>;
    get(bucketId: string, opts?: TypeGraphOptions | null): Promise<Bucket | undefined>;
    list(filter?: BucketListFilter | null, opts?: TypeGraphOptions | null, pagination?: PaginationOpts | null): Promise<Bucket[] | PaginatedResult<Bucket>>;
    update(bucketId: string, input: Partial<Pick<Bucket, 'name' | 'description' | 'status' | 'indexDefaults' | 'graph' | 'graphExtraction'>>, opts?: TypeGraphOptions | null): Promise<Bucket>;
    delete(bucketId: string, opts?: TypeGraphOptions | null): Promise<void>;
}
interfaceDocumentsApi
export interface DocumentsApi {
    ingest(input: DocumentInput | DocumentInput[], opts: DocumentIngestOptions): Promise<IndexResult>;
    ingestPreChunked(input: DocumentInput, chunks: Chunk[], opts: DocumentIngestOptions): Promise<IndexResult>;
    get(id: string, opts?: TypeGraphOptions | null): Promise<typegraphDocument | null>;
    list(filter?: DocumentFilter | null, opts?: TypeGraphOptions | null, pagination?: PaginationOpts | null): Promise<typegraphDocument[] | PaginatedResult<typegraphDocument>>;
    update(id: string, input: Partial<Pick<typegraphDocument, 'name' | 'description' | 'url' | 'metadata'>>, opts?: TypeGraphOptions | null): Promise<typegraphDocument>;
    delete(filter: DocumentFilter | null, opts?: TypeGraphOptions | null): Promise<number>;
}
interfaceEventsApi
export interface EventsApi {
    ingest(input: EventInput | EventInput[], opts: EventIngestOptions): Promise<typegraphEventRecord | EventBatchIngestResult>;
    get(id: string, opts?: TypeGraphOptions | null): Promise<typegraphEventRecord | null>;
    list(filter?: EventFilter | null, opts?: TypeGraphOptions | null): Promise<typegraphEventRecord[]>;
}
interfaceThreadsApi
export interface ThreadsApi {
    upsert(input: ThreadInput, opts?: TypeGraphWriteOptions | null): Promise<typegraphThread>;
    get(id: string, opts?: TypeGraphOptions | null): Promise<typegraphThread | null>;
    list(filter?: ThreadFilter | null, opts?: TypeGraphOptions | null): Promise<typegraphThread[]>;
    addTurn(threadId: string, turn: ThreadTurnInput, opts?: TypeGraphWriteOptions | null): Promise<GraphThreadTurnResult>;
}
interfaceGraphApi
export interface GraphApi {
    upsertEntity(input: UpsertGraphEntityInput, opts?: TypeGraphGraphOptions | null): Promise<EntityDetail>;
    upsertEntities(inputs: UpsertGraphEntityInput[], opts?: TypeGraphGraphOptions | null): Promise<EntityDetail[]>;
    resolveEntity(ref: GraphEntityRef | string, opts?: TypeGraphGraphOptions | null): Promise<EntityDetail | null>;
    linkExternalIds(entityId: string, externalIds: ExternalId[], opts?: TypeGraphGraphOptions | null): Promise<EntityDetail>;
    mergeEntities(input: MergeGraphEntitiesInput, opts?: TypeGraphGraphOptions | null): Promise<MergeGraphEntitiesResult>;
    deleteEntity(entityId: string, opts?: (DeleteGraphEntityOpts & TypeGraphGraphOptions) | null): Promise<DeleteGraphEntityResult>;
    upsertEdge(input: UpsertGraphEdgeInput, opts?: TypeGraphGraphOptions | null): Promise<EdgeResult>;
    upsertEdges(inputs: UpsertGraphEdgeInput[], opts?: TypeGraphGraphOptions | null): Promise<EdgeResult[]>;
    upsertFact(input: UpsertGraphFactInput, opts?: TypeGraphGraphOptions | null): Promise<FactResult>;
    upsertFacts(inputs: UpsertGraphFactInput[], opts?: TypeGraphGraphOptions | null): Promise<FactResult[]>;
    searchEntities(query: string, opts?: ({
        limit?: number;
        entityType?: string;
        minConnections?: number;
    } & TypeGraphGraphOptions) | null): Promise<EntityResult[]>;
    getEntity(id: string, opts?: TypeGraphGraphOptions | null): Promise<EntityDetail | null>;
    getEdges(entityId: string, opts?: ({
        direction?: 'in' | 'out' | 'both';
        relation?: string;
        limit?: number;
    } & TypeGraphGraphOptions) | null): Promise<EdgeResult[]>;
    searchFacts(query: string, opts?: (FactSearchOpts & TypeGraphGraphOptions) | null): Promise<FactResult[]>;
    explore(query: string, opts?: (GraphExploreOpts & TypeGraphGraphOptions) | null): Promise<GraphExploreResult>;
    getChunksForEntity(entityId: string, opts?: ({
        bucketIds?: string[] | undefined;
        limit?: number | undefined;
    } & TypeGraphGraphOptions) | null): Promise<ChunkResult[]>;
    explainQuery(query: string, opts?: (GraphExplainOpts & TypeGraphGraphOptions) | null): Promise<GraphSearchTrace>;
    backfill(opts?: (GraphBackfillOpts & TypeGraphGraphOptions) | null): Promise<GraphBackfillResult>;
    getSubgraph(opts: GraphSubgraphOptions): Promise<SubgraphResult>;
    stats(opts?: TypeGraphGraphOptions | null): Promise<GraphStats>;
    getRelationTypes(opts?: TypeGraphGraphOptions | null): Promise<Array<{
        relation: string;
        count: number;
    }>>;
    getEntityTypes(opts?: TypeGraphGraphOptions | null): Promise<Array<{
        entityType: string;
        count: number;
    }>>;
}
interfaceJobsApi
export interface JobsApi {
    get(id: string): Promise<Job | null>;
    list(filter?: JobFilter | null): Promise<Job[]>;
    /** Create or replace a job row (caller-provided id). Writers use this from background workers. */
    upsert(input: UpsertJobInput): Promise<Job>;
    /** Apply a partial status/result/error/progress patch. */
    updateStatus(id: string, patch: JobStatusPatch): Promise<void>;
    /** Atomically increment the `progress_processed` counter. */
    incrementProgress(id: string, processedDelta: number): Promise<void>;
}
typeLLMConfig
/** Union type: pass a native LLMProvider, a bare AI SDK model, or an AISDKLLMInput ({ model, providerOptions? }). */
export type LLMConfig = LLMProvider | LanguageModelV3 | AISDKLLMInput;
interfaceLLMProvider
export interface LLMProvider {
    /**
     * Generate text from a prompt. Returns the raw text response.
     */
    generateText(prompt: string, systemPrompt?: string, options?: LLMGenerateOptions): Promise<string>;
    /**
     * Generate structured JSON output from a prompt.
     * The provider should parse and return the JSON object.
     */
    generateJSON<T = unknown>(prompt: string, systemPrompt?: string, options?: LLMGenerateOptions): Promise<T>;
}
interfaceLLMGenerateOptions
/**
 * Structural type for an LLM provider.
 * Any object matching this shape works (AI SDK models, custom implementations, test mocks).
 *
 * The provider must support structured JSON output for memory extraction.
 */
export interface LLMGenerateOptions {
    /**
     * Provider-specific options passed through to the underlying model.
     * Example: `{ openai: { reasoningEffort: 'high' } }`
     */
    providerOptions?: Record<string, Record<string, unknown>>;
    /**
     * Maximum number of output tokens the model may generate.
     * When omitted, the model's default applies. generateJSON sets 16384
     * as a default to prevent truncation of structured output.
     */
    maxOutputTokens?: number;
    /**
     * Zod schema for structured output validation.
     * When provided alongside a generateObject-capable adapter, enables
     * model-level schema-constrained output with validation.
     * When omitted, the adapter uses JSON mode without schema validation.
     */
    schema?: unknown;
}
interfaceAISDKLLMInput
/**
 * Configuration for using an AI SDK language model with typegraph.
 *
 * @example
 * ```ts
 * import { gateway } from '@ai-sdk/gateway'
 *
 * const llm = aiSdkLlmProvider({
 *   model: gateway('openai/gpt-5.4-mini'),
 * })
 * ```
 *
 * @example Provider-specific options (gateway fallbacks, reasoning, thinking):
 * ```ts
 * const llm = aiSdkLlmProvider({
 *   model: gateway('openai/gpt-5.4-mini'),
 *   providerOptions: {
 *     gateway: { models: ['google/gemini-3-flash', 'openai/gpt-5.4-mini'] },
 *     openai:  { reasoningEffort: 'medium', reasoningSummary: 'concise' },
 *     google:  { thinkingConfig: { thinkingLevel: 'medium', includeThoughts: false } },
 *     xai:     { reasoningEffort: 'low' },
 *   },
 * })
 * ```
 */
export interface AISDKLLMInput {
    model: LanguageModelV3;
    /**
     * Provider-specific options applied to every generateText / generateJSON call.
     * Merged per-namespace with any options passed at call time (call-level wins).
     */
    providerOptions?: Record<string, Record<string, unknown>>;
}
typeEmbeddingConfig
export type EmbeddingConfig = Embedder | AISDKEmbeddingInput;
interfaceEmbedder
export interface Embedder {
    name: string;
    dimensions: number;
    maxBatchSize?: number | undefined;
    supportsAsymmetric?: boolean | undefined;
    embed(input: EmbedInput): Promise<number[][]>;
}
interfaceEmbedInput
export interface EmbedInput {
    texts: string[];
    inputType?: 'document' | 'search' | undefined;
    outputDimensions?: number | undefined;
    abortSignal?: AbortSignal | undefined;
}
interfaceAISDKEmbeddingInput
/**
 * Configuration for using an AI SDK embedding model with typegraph.
 *
 * @example
 * ```ts
 * import { gateway } from '@ai-sdk/gateway'
 *
 * const embedding: AISDKEmbeddingInput = {
 *   model: gateway.embeddingModel('openai/text-embedding-3-small'),
 *   dimensions: 1536,
 * }
 * ```
 *
 * @example Provider-specific options (e.g., Voyage input type):
 * ```ts
 * const embedding: AISDKEmbeddingInput = {
 *   model: gateway.embeddingModel('voyage/voyage-4-large'),
 *   dimensions: 512,
 *   providerOptions: { voyage: { outputDimension: 512, inputType: 'document' } },
 * }
 * ```
 */
export interface AISDKEmbeddingInput {
    model: EmbeddingModelV3;
    dimensions: number;
    /** Provider-specific options passed to every embed call (e.g., Voyage outputDimension/inputType). */
    providerOptions?: Record<string, Record<string, unknown>>;
}
interfaceExtractor
export interface Extractor {
    name: string;
    capabilities: ExtractorCapabilities;
    extract(input: ExtractorInput, ctx: ExtractorContext): Promise<ExtractionResult>;
}
interfaceExtractorCapabilities
export interface ExtractorCapabilities {
    supportsBatch: boolean;
    supportsStreaming: boolean;
    requiresStructuredOutput: boolean;
    multimodal: Array<'text' | 'image' | 'audio' | 'video' | 'pdf'>;
    preservesOntology: boolean;
}
interfaceExtractorInput
export interface ExtractorInput {
    id: string;
    kind: 'document' | 'event' | 'thread_turn' | 'memory' | 'correction';
    name?: string | undefined;
    description?: string | undefined;
    content: string;
    occurredAt?: Date | undefined;
    metadata?: Record<string, unknown> | undefined;
    ontology?: OntologyConfig | undefined;
    participants?: EntityRef[] | undefined;
}
interfaceExtractorContext
export interface ExtractorContext {
    abortSignal?: AbortSignal | undefined;
    coreferenceCache?: ExtractionCoreferenceCache | undefined;
    log?: {
        debug?: (message: string, data?: Record<string, unknown>) => void;
        warn?: (message: string, data?: Record<string, unknown>) => void;
        error?: (message: string, data?: Record<string, unknown>) => void;
    } | undefined;
}
interfaceExtractionResult
export interface ExtractionResult {
    entities: ExtractedEntity[];
    relations: ExtractedRelation[];
    warnings?: string[] | undefined;
    rawModelOutput?: unknown;
}
interfaceReranker
export interface Reranker<TCandidate = unknown> {
    name: string;
    rerank(query: string, candidates: TCandidate[], opts?: RerankerOptions): Promise<TCandidate[]>;
}
interfaceRerankerOptions
export interface RerankerOptions {
    topK?: number | undefined;
    domain?: 'general' | 'legal' | 'code' | 'medical' | undefined;
    abortSignal?: AbortSignal | undefined;
}
interfaceCreateBucketInput
export interface CreateBucketInput {
    id?: string | undefined;
    name: string;
    description?: string | undefined;
    /** Embedding model for this bucket (ingest). Once set, cannot be changed. Defaults to the instance's default embedding. */
    embeddingModel?: string | undefined;
    /** Search embedding model for this bucket. Must embed into same vector space as embeddingModel.
     *  Defaults to the instance's searchEmbedding, or the ingest embeddingModel if not set. */
    searchEmbeddingModel?: string | undefined;
    /** Write graph for this bucket. Defaults to "public". */
    graph?: string | undefined;
    /** Bucket default for graph extraction. Equivalent to indexDefaults.graphExtraction. */
    graphExtraction?: boolean | undefined;
    indexDefaults?: IndexDefaults | undefined;
}
interfaceBucketListFilter
export interface BucketListFilter {
    name?: string | undefined;
}
interfaceIndexDefaults
/**
 * Bucket-level index defaults. These are applied to every ingest() call
 * targeting the bucket unless overridden per-call via IngestOptions.
 *
 * This is the bucket-mergeable slice of IngestOptions — fields that identify
 * the caller (tenantId, userId, etc.) or control batch behavior (dryRun,
 * concurrency, traceId) are runtime-only and never live here.
 */
export interface IndexDefaults {
    chunkSize?: number | undefined;
    chunkOverlap?: number | undefined;
    deduplicateBy?: string[] | ((document: DocumentInput) => string) | undefined;
    stripMarkdownForEmbedding?: boolean | undefined;
    preprocessForEmbedding?: ((content: string) => string) | undefined;
    propagateMetadata?: string[] | undefined;
    /**
     * Whether entity/relationship triples are extracted during ingestion for this bucket.
     * Requires the TypeGraph instance to be configured with both `llm` and `knowledgeGraph`.
     * Default: false. Can be overridden per-call via IngestOptions.graphExtraction.
     */
    graphExtraction?: boolean | undefined;
}
interfaceDocumentInput
export interface DocumentInput<TMeta extends Record<string, unknown> = Record<string, unknown>> {
    id?: string | undefined;
    name: string;
    description?: string | undefined;
    content: string;
    updatedAt?: Date | undefined;
    url?: string | null | undefined;
    createdAt?: Date | undefined;
    mimeType?: string | undefined;
    language?: string | undefined;
    metadata?: TMeta | undefined;
}
interfaceDocumentFilter
export interface DocumentFilter {
    bucketId?: string | undefined;
    status?: DocumentStatus | DocumentStatus[] | undefined;
    documentIds?: string[] | undefined;
}
typeDocumentStatus
export type DocumentStatus = 'pending' | 'processing' | 'complete' | 'failed';
interfaceEventInput
export interface EventInput<TMeta extends Record<string, unknown> = Record<string, unknown>> {
    id?: string | undefined;
    name: string;
    description?: string | undefined;
    occurredAt: Date;
    participants?: EntityRef[] | undefined;
    documents?: DocumentInput[] | undefined;
    content?: string | undefined;
    metadata?: TMeta | undefined;
}
interfaceEventFilter
export interface EventFilter {
    eventIds?: string[] | undefined;
}
interfaceThreadInput
export interface ThreadInput<TMeta extends Record<string, unknown> = Record<string, unknown>> {
    id?: string | undefined;
    name: string;
    description?: string | undefined;
    metadata?: TMeta | undefined;
}
interfaceThreadTurnInput
export interface ThreadTurnInput<TMeta extends Record<string, unknown> = Record<string, unknown>> {
    role: string;
    content: string;
    timestamp?: Date | undefined;
    metadata?: TMeta | undefined;
}
interfaceThreadTurnResult
export interface ThreadTurnResult {
    thread: typegraphThread;
    event: typegraphEventRecord;
}
interfaceThreadFilter
export interface ThreadFilter {
    threadIds?: string[] | undefined;
}
interfaceSearchOptions
export interface SearchOptions {
    graph?: string | undefined;
    /** Internal resolved graph closure. Public callers should pass `graph`, not this field. */
    graphIds?: string[] | undefined;
    context?: TypeGraphContext | undefined;
    resources?: SearchResource[] | undefined;
    weights?: SearchWeights | undefined;
    fusion?: SearchFusion | undefined;
    rerank?: SearchRerankOptions | undefined;
    buckets?: string[] | undefined;
    limit?: number | undefined;
    offset?: number | undefined;
    abortSignal?: AbortSignal | undefined;
    /** Filter results by document-level fields. */
    documentFilter?: DocumentFilter | undefined;
    /** Relevance scope by TypeGraph entity IDs or deterministic external IDs. */
    entityScope?: QueryEntityScope | undefined;
    /** When true, automatically adjust score weights based on query type classification.
     *  Uses pure heuristics (no LLM call) to detect factual-lookup, entity-centric,
     *  relational, temporal, or exploratory queries and applies optimized weight profiles.
     *  This never enables or disables resources; `resources` remains the source of truth.
     *  User-provided `weights` always override. Default: false. */
    autoWeights?: boolean | undefined;
    /** Controls how graph results interact with indexed results.
     *  - 'off': include all graph results as-is (default)
     *  - 'prefer': boost matching results, but keep novel graph results at lower weight
     *  - 'only': keep graph results only if they also appear in indexed results */
    graphReinforcement?: 'only' | 'prefer' | 'off' | undefined;
    /** Heterogeneous graph traversal options. */
    graphOptions?: GraphSearchOpts | undefined;
    /** Timeouts per retrieval path (milliseconds). */
    timeouts?: {
        /** Timeout for semantic/keyword indexed search. Default: 30000. */
        indexed?: number | undefined;
        /** Timeout for graph PPR traversal. Default: 30000. */
        graph?: number | undefined;
    } | undefined;
    /** How to handle errors from individual buckets.
     *  - 'throw': abort query on any bucket error (default)
     *  - 'warn': continue with other buckets, add warning
     *  - 'omit': silently skip failed buckets */
    onBucketError?: 'omit' | 'warn' | 'throw' | undefined;
    /** Point-in-time query: only return results indexed before this timestamp. */
    asOf?: Date | 'now' | undefined;
    validBetween?: [
        Date,
        Date
    ] | undefined;
    /** Include invalidated/expired graph edges. Default: false. */
    includeInvalidated?: boolean | undefined;
    /** Build an LLM-ready prompt string from query results. When set, response includes `prompt`. */
    promptBuilder?: true | PromptBuilderOptions | undefined;
    explain?: boolean | undefined;
}
typeSearchResource
export type SearchResource = 'documents' | 'events' | 'threads' | 'entities' | 'facts';
typeSearchWeights
export type SearchWeights = {
    semantic?: number | false | undefined;
    bm25?: number | false | undefined;
    graph?: number | false | undefined;
    recency?: number | false | undefined;
};
typeSearchFusion
export type SearchFusion = {
    method?: 'rrf' | undefined;
    k?: number | undefined;
};
typeSearchRerankOptions
export type SearchRerankOptions = boolean | {
    topK?: number | undefined;
    domain?: 'general' | 'legal' | 'code' | 'medical' | undefined;
};
interfaceSearchExplanation
export interface SearchExplanation {
    requestedGraph: string;
    graphClosure: string[];
    deniedGraphs?: string[] | undefined;
    activeResources: SearchResource[];
    activeWeights: Required<Record<keyof SearchWeights, number | false>>;
    fusion: Required<SearchFusion>;
    candidateCounts: Partial<Record<SearchResource, number>>;
    timings: Record<string, number>;
    graphTrace?: GraphSearchTrace | undefined;
    warnings?: string[] | undefined;
    skippedResources?: Partial<Record<SearchResource, string>> | undefined;
}
typePromptFormat
export type PromptFormat = 'xml' | 'markdown' | 'plain';
typePromptSection
export type PromptSection = 'facts' | 'entities' | 'chunks';
interfacePromptBuilderOptions
export interface PromptBuilderOptions {
    format?: PromptFormat | undefined;
    sections?: PromptSection[] | undefined;
    includeAttributes?: boolean | undefined;
    maxTotalTokens?: number | undefined;
    maxChunkTokens?: number | undefined;
    maxFactTokens?: number | undefined;
    maxEntityTokens?: number | undefined;
}
interfacePromptStats
export interface PromptStats {
    format: PromptFormat;
    totalTokens: number;
    truncated: boolean;
    sections: Partial<Record<PromptSection, {
        available: number;
        included: number;
        tokens: number;
        truncated: boolean;
    }>>;
}
interfaceQueryResponse
export interface QueryResponse {
    results: QueryResults;
    buckets: Record<string, {
        mode: 'indexed' | 'graph';
        resultCount: number;
        durationMs: number;
        status: 'ok' | 'timeout' | 'error';
        error?: Error | undefined;
    }>;
    query: {
        text: string;
        durationMs: number;
        mergeStrategy: string;
    };
    /** Formatted prompt string. Present when `promptBuilder` is specified in search opts. */
    prompt?: string | undefined;
    promptStats?: PromptStats | undefined;
    explanation?: SearchExplanation | undefined;
    warnings?: string[] | undefined;
}
interfaceOutputScores
export interface OutputScores {
    semantic?: number | undefined;
    bm25?: number | undefined;
    graph?: number | undefined;
    recency?: number | undefined;
    fused: number;
    reranker?: number | undefined;
}
typeEntityType
export type EntityType = typeof ENTITY_TYPES[number];
interfaceEntityTypeSpec
export interface EntityTypeSpec {
    name: EntityType;
    description: string;
    examples: string[];
}
interfacePredicateSpec
export interface PredicateSpec {
    name: string;
    description: string;
    category: string;
    domain: readonly EntityType[] | readonly [
        '*'
    ];
    range: readonly EntityType[] | readonly [
        '*'
    ];
    aliases?: readonly PredicateAliasSpec[] | undefined;
    symmetric?: boolean | undefined;
    inverse?: string | undefined;
}
interfacePredicateAliasSpec
export interface PredicateAliasSpec {
    name: string;
    swap?: boolean | undefined;
    temporalStatus?: PredicateTemporalStatus | undefined;
}
typePredicateTemporalStatus
export type PredicateTemporalStatus = 'current' | 'former' | 'historical' | 'unknown';
interfacePredicateNormalization
export interface PredicateNormalization {
    original: string;
    predicate: string;
    valid: boolean;
    swapSubjectObject: boolean;
    symmetric: boolean;
    temporalStatus?: PredicateTemporalStatus | undefined;
}
interfacePredicateTypeValidation
export interface PredicateTypeValidation {
    valid: boolean;
    domainValid: boolean;
    rangeValid: boolean;
    reason?: string | undefined;
}
interfaceGraphEntityRef
export interface GraphEntityRef {
    /** Existing TypeGraph entity ID. */
    id?: string | undefined;
    /** Deterministic identifier lookup. Takes priority over name/fuzzy matching. */
    externalId?: ExternalId | undefined;
    /** Deterministic identifiers to attach or use for lookup. */
    externalIds?: ExternalId[] | undefined;
    /** Entity name. Required when the reference must create a new entity. */
    name?: string | undefined;
    entityType?: string | undefined;
    typeCandidates?: TypeCandidate[] | undefined;
    aliases?: string[] | undefined;
    description?: string | undefined;
    metadata?: Record<string, unknown> | undefined;
}
interfaceUpsertGraphEntityInput
export interface UpsertGraphEntityInput {
    id?: string | undefined;
    name: string;
    entityType?: string | undefined;
    typeCandidates?: TypeCandidate[] | undefined;
    aliases?: string[] | undefined;
    description?: string | undefined;
    metadata?: Record<string, unknown> | undefined;
    externalIds?: ExternalId[] | undefined;
}
interfaceUpsertGraphEdgeInput
export interface UpsertGraphEdgeInput {
    /** Entity ref. A bare string reuses an existing entity ID when found, otherwise seeds by name. */
    source: GraphEntityRef | string;
    /** Entity ref. A bare string reuses an existing entity ID when found, otherwise seeds by name. */
    target: GraphEntityRef | string;
    relation: string;
    weight?: number | undefined;
    metadata?: Record<string, unknown> | undefined;
    description?: string | undefined;
    evidenceText?: string | undefined;
    temporalStatus?: PredicateTemporalStatus | undefined;
    validFrom?: string | undefined;
    validTo?: string | undefined;
    chunkId?: string | undefined;
}
interfaceUpsertGraphFactInput
export interface UpsertGraphFactInput {
    /** Entity ref. A bare string reuses an existing entity ID when found, otherwise seeds by name. */
    source: GraphEntityRef | string;
    /** Entity ref. A bare string reuses an existing entity ID when found, otherwise seeds by name. */
    target: GraphEntityRef | string;
    relation: string;
    description?: string | undefined;
    evidenceText?: string | undefined;
    temporalStatus?: PredicateTemporalStatus | undefined;
    validFrom?: string | undefined;
    validTo?: string | undefined;
    chunkId?: string | undefined;
    confidence?: number | undefined;
    metadata?: Record<string, unknown> | undefined;
}
interfaceMergeGraphEntitiesInput
export interface MergeGraphEntitiesInput {
    sourceEntityId: string;
    targetEntityId: string;
    metadata?: Record<string, unknown> | undefined;
}
interfaceMergeGraphEntitiesResult
export interface MergeGraphEntitiesResult {
    target: EntityDetail;
    sourceEntityId: string;
    targetEntityId: string;
    redirectedEdges: number;
    redirectedFacts: number;
    redirectedGraphEdges: number;
    movedMentions: number;
    movedExternalIds: number;
    removedSelfEdges: number;
}
interfaceDeleteGraphEntityOpts
export interface DeleteGraphEntityOpts {
    mode?: 'invalidate' | 'purge' | undefined;
}
interfaceDeleteGraphEntityResult
export interface DeleteGraphEntityResult {
    entityId: string;
    mode: 'invalidate' | 'purge';
    deletedEdges: number;
    deletedFacts: number;
    deletedGraphEdges: number;
    deletedMentions: number;
    deletedExternalIds: number;
}
interfaceEntityResult
export interface EntityResult {
    id: string;
    name: string;
    entityType: string;
    aliases: string[];
    externalIds?: ExternalId[] | undefined;
    /** Present when searched by query. */
    similarity?: number | undefined;
    /** Number of edges (degree centrality). */
    edgeCount: number;
    metadata?: Record<string, unknown> | undefined;
}
interfaceEntityDetail
export interface EntityDetail extends EntityResult {
    description?: string | undefined;
    createdAt: Date;
    validAt?: Date | undefined;
    invalidAt?: Date | undefined;
    /** Top edges by weight. */
    topEdges: EdgeResult[];
}
interfaceEdgeResult
export interface EdgeResult {
    id: string;
    sourceEntityId: string;
    sourceEntityName: string;
    targetEntityId: string;
    targetEntityName: string;
    relation: string;
    weight: number;
    metadata?: Record<string, unknown> | undefined;
}
interfaceFactResult
export interface FactResult {
    id: string;
    edgeId: string;
    sourceEntityId: string;
    sourceEntityName?: string | undefined;
    targetEntityId: string;
    targetEntityName?: string | undefined;
    relation: string;
    description?: string | undefined;
    evidenceText?: string | undefined;
    chunkId?: string | undefined;
    weight: number;
    similarity?: number | undefined;
    metadata?: Record<string, unknown> | undefined;
}
interfaceFactSearchOpts
export interface FactSearchOpts extends TypeGraphOptions {
    limit?: number | undefined;
}
interfaceChunkResult
export interface ChunkResult extends ChunkRef {
    content: string;
    totalChunks?: number | undefined;
    score: number;
    metadata?: Record<string, unknown> | undefined;
    tenantId?: string | undefined;
    groupId?: string | undefined;
    userId?: string | undefined;
    agentId?: string | undefined;
    threadId?: string | undefined;
}
typeGraphSearchProfile
export type GraphSearchProfile = 'fact-filtered-narrow';
interfaceGraphSearchOpts
export interface GraphSearchOpts {
    intentParser?: GraphIntentParserMode | undefined;
    profile?: GraphSearchProfile | undefined;
    count?: number | undefined;
    bucketIds?: string[] | undefined;
    entityScope?: QueryEntityScope | undefined;
    resolvedEntityIds?: string[] | undefined;
    restartProbability?: number | undefined;
    chunkSeedWeight?: number | undefined;
    entitySeedWeight?: number | undefined;
    factCandidateLimit?: number | undefined;
    factFilterInputLimit?: number | undefined;
    factSeedLimit?: number | undefined;
    chunkSeedLimit?: number | undefined;
    maxExpansionEdgesPerEntity?: number | undefined;
    maxPprIterations?: number | undefined;
    minPprScore?: number | undefined;
    factFilter?: boolean | undefined;
    factChainLimit?: number | undefined;
}
typeGraphExplainOpts
export type GraphExplainOpts = GraphSearchOpts & TypeGraphOptions;
interfaceGraphSearchTrace
export interface GraphSearchTrace {
    intent?: GraphQueryIntent | undefined;
    parser?: 'deterministic' | 'llm' | 'none' | undefined;
    intentParseMs?: number | undefined;
    intentMatchedPatterns?: string[] | undefined;
    rejectedPredicates?: string[] | undefined;
    entitySeedCount: number;
    factSeedCount: number;
    chunkSeedCount: number;
    graphNodeCount: number;
    graphEdgeCount: number;
    pprNonzeroCount: number;
    candidatesBeforeMerge: number;
    candidatesAfterMerge: number;
    topGraphScores: number[];
    selectedFactIds: string[];
    selectedEntityIds: string[];
    selectedChunkIds: string[];
    finalChunkIds?: string[] | undefined;
    selectedFactTexts?: Array<{
        id: string;
        content: string;
    }> | undefined;
    selectedEntityNames?: Array<{
        id: string;
        content: string;
    }> | undefined;
    selectedFactChains?: Array<{
        content: string;
        score: number;
        factIds: string[];
    }> | undefined;
}
interfaceGraphSearchResult
export interface GraphSearchResult {
    results: ChunkResult[];
    facts: FactResult[];
    entities: EntityResult[];
    factChains?: FactChainResult[] | undefined;
    trace: GraphSearchTrace;
}
interfaceGraphExploreOptions
export interface GraphExploreOptions {
    intentParser?: GraphIntentParserMode | undefined;
    include?: {
        entities?: boolean | undefined;
        facts?: boolean | undefined;
        chunks?: boolean | undefined;
    } | undefined;
    bucketIds?: string[] | undefined;
    anchorLimit?: number | undefined;
    entityLimit?: number | undefined;
    factLimit?: number | undefined;
    chunkLimit?: number | undefined;
    depth?: 1 | 2 | undefined;
    explain?: boolean | undefined;
}
typeGraphExploreOpts
export type GraphExploreOpts = GraphExploreOptions & TypeGraphOptions;
typeGraphIntentParserMode
export type GraphIntentParserMode = 'deterministic' | 'llm' | 'none';
typeGraphExploreIntent
export type GraphExploreIntent = GraphQueryIntent;
interfaceGraphExploreTrace
export interface GraphExploreTrace {
    parser: 'deterministic' | 'llm' | 'none';
    mode: GraphQueryIntent['mode'];
    strictness: GraphQueryIntent['strictness'];
    selectedPredicates: string[];
    sourceEntityQueries: string[];
    targetEntityQueries: string[];
    subqueries: string[];
    intentParseMs?: number | undefined;
    intentMatchedPatterns?: string[] | undefined;
    rejectedPredicates?: string[] | undefined;
    anchorCandidates: EntityResult[];
    selectedAnchorIds: string[];
    matchedEdgeIds: string[];
    matchedRelations: string[];
    droppedByPredicate: number;
    droppedByDirection: number;
    droppedByType: number;
}
interfaceGraphExploreResult
export interface GraphExploreResult {
    intent: GraphExploreIntent;
    anchors: EntityResult[];
    entities: EntityResult[];
    facts: FactResult[];
    chunks?: ChunkResult[] | undefined;
    trace?: GraphExploreTrace | undefined;
}
interfaceGraphBackfillOpts
export interface GraphBackfillOpts {
    bucketIds?: string[] | undefined;
    batchSize?: number | undefined;
    entityChunkEdges?: boolean | undefined;
    facts?: boolean | undefined;
    entityProfiles?: boolean | undefined;
}
interfaceGraphBackfillResult
export interface GraphBackfillResult {
    entityChunkEdgesUpserted: number;
    factRecordsUpserted: number;
    entityProfilesUpdated: number;
    batches: number;
}
interfaceSubgraphResult
export interface SubgraphResult {
    entities: Array<EntityResult & {
        /** Visual size based on degree centrality. */
        size: number;
    }>;
    edges: Array<EdgeResult & {
        /** Visual thickness based on weight. */
        thickness: number;
    }>;
    stats: {
        entityCount: number;
        edgeCount: number;
        avgDegree: number;
        /** Number of connected components. */
        components: number;
    };
}
interfaceGraphStats
export interface GraphStats {
    totalEntities: number;
    totalEdges: number;
    avgEdgesPerEntity: number;
    topEntityTypes: Array<{
        entityType: string;
        count: number;
    }>;
    topRelations: Array<{
        relation: string;
        count: number;
    }>;
    degreeDistribution: Array<{
        degree: number;
        count: number;
    }>;
}
interfaceMemorySubject
export interface MemorySubject {
    entityId?: string | undefined;
    externalIds?: ExternalId[] | undefined;
    name?: string | undefined;
    entityType?: string | undefined;
    typeCandidates?: TypeCandidate[] | undefined;
    aliases?: string[] | undefined;
    metadata?: Record<string, unknown> | undefined;
}
interfaceRememberOpts
export interface RememberOpts extends TypeGraphOptions {
    category?: string | undefined;
    importance?: number | undefined;
    metadata?: Record<string, unknown> | undefined;
    subject?: MemorySubject | undefined;
    relatedEntities?: MemorySubject[] | undefined;
    graphExtraction?: boolean | undefined;
}
interfaceForgetOpts
export interface ForgetOpts extends TypeGraphOptions {
}
interfaceCorrectOpts
export interface CorrectOpts extends TypeGraphOptions {
    subject?: MemorySubject | undefined;
    relatedEntities?: MemorySubject[] | undefined;
    graphExtraction?: boolean | undefined;
}
interfaceRecallOpts
export interface RecallOpts extends TypeGraphOptions {
    limit?: number | undefined;
    types?: string[] | undefined;
    /** Only return memories valid at this timestamp. */
    temporalAt?: Date | undefined;
    /** Include invalidated/expired memories. Default: false. */
    includeInvalidated?: boolean | undefined;
    entityScope?: QueryEntityScope | undefined;
    /** Format results as a string instead of an array. When set, `recall` returns `Promise<string>`. */
    format?: 'xml' | 'markdown' | 'plain' | undefined;
}
typeMemoryCategory
export type MemoryCategory = 'episodic' | 'semantic' | 'procedural';
typeMemoryStatus
export type MemoryStatus = 'pending' | 'active' | 'consolidated' | 'invalidated' | 'archived' | 'expired';
interfaceMemoryHealthReport
/** Memory system health statistics. */
export interface MemoryHealthReport {
    totalMemories: number;
    activeMemories: number;
    invalidatedMemories: number;
    consolidatedMemories: number;
    /** Fraction of active memories (active / (active + invalidated)), 0-1. */
    memoryPrecision: number;
    totalEntities: number;
    totalEdges: number;
    edgesPerEntity: number;
    /** Fraction of active memories below decay threshold. */
    stalenessIndex: number;
}
interfaceJob
/** A tracked async operation (primarily used in cloud mode). */
export interface Job {
    id: string;
    status: JobStatus;
    type: JobType;
    bucketId?: string | undefined;
    /** Populated on completion. Shape depends on `type`. */
    result?: IndexResult | MemoryRecord | ThreadTurnResult | undefined;
    /** Error message if status is 'failed'. */
    error?: string | undefined;
    createdAt: Date;
    completedAt?: Date | undefined;
    progress?: {
        processed: number;
        total: number;
    } | undefined;
}
interfaceJobFilter
export interface JobFilter {
    bucketId?: string | undefined;
    status?: JobStatus | undefined;
    type?: JobType | undefined;
}
typeJobStatus
export type JobStatus = 'pending' | 'processing' | 'complete' | 'failed';
typeJobType
export type JobType = 'ingest' | 'remember' | 'thread_turn' | 'correct' | 'forget';
interfacePolicy
export interface Policy {
    id: string;
    name: string;
    policyType: PolicyType;
    tenantId?: string | undefined;
    groupId?: string | undefined;
    userId?: string | undefined;
    agentId?: string | undefined;
    rules: PolicyRule[];
    enabled: boolean;
    createdAt: Date;
    updatedAt: Date;
}
typePolicyAction
export type PolicyAction = 'query' | 'index' | 'memory.write' | 'memory.read' | 'memory.delete' | 'document.delete' | 'bucket.delete';
interfacePolicyRule
export interface PolicyRule {
    /** What SDK action this rule applies to. */
    action: PolicyAction;
    /** Whether the action is allowed or denied. */
    effect: 'allow' | 'deny';
    /** Optional conditions — identity field matchers, bucket patterns, etc. */
    conditions?: Record<string, unknown>;
}
interfacePolicyDecision
export interface PolicyDecision {
    allowed: boolean;
    violations: PolicyViolation[];
}
typePolicyType
export type PolicyType = 'access' | 'retention' | 'data_flow';
interfacePaginationOpts
/** Pagination options for list operations. */
export interface PaginationOpts {
    /** Maximum number of items to return. Default: 100. */
    limit?: number | undefined;
    /** Number of items to skip. Default: 0. */
    offset?: number | undefined;
}
interfacePaginatedResult
/** Paginated result set. */
export interface PaginatedResult<T> {
    items: T[];
    total: number;
    limit: number;
    offset: number;
}