Types
Full TypeScript type definitions exported by the TypeGraph SDK.
type
TenantIdexport type TenantId = Brand<string, 'TenantId'>;
type
GroupIdexport type GroupId = Brand<string, 'GroupId'>;
type
UserIdexport type UserId = Brand<string, 'UserId'>;
type
AgentIdexport type AgentId = Brand<string, 'AgentId'>;
type
ThreadIdexport type ThreadId = Brand<string, 'ThreadId'>;
type
EntityIdexport type EntityId = Brand<string, 'EntityId'>;
interface
EntityRefexport interface EntityRef {
type: string;
id: string;
}interface
TypeGraphContext/**
* 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;
}interface
TypeGraphOptionsexport interface TypeGraphOptions {
context?: TypeGraphContext | undefined;
abortSignal?: AbortSignal | undefined;
}interface
TypeGraphWriteOptionsexport interface TypeGraphWriteOptions extends TypeGraphOptions {
bucketId?: string | undefined;
graphExtraction?: boolean | undefined;
idempotencyKey?: string | undefined;
}interface
typegraphConfigexport 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;
}interface
CloudConfigexport 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;
}interface
typegraphInstance/** 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>;
}interface
BucketsApiexport 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>;
}interface
DocumentsApiexport 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>;
}interface
EventsApiexport 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[]>;
}interface
ThreadsApiexport 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>;
}interface
GraphApiexport 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;
}>>;
}interface
JobsApiexport 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>;
}type
LLMConfig/** Union type: pass a native LLMProvider, a bare AI SDK model, or an AISDKLLMInput ({ model, providerOptions? }). */
export type LLMConfig = LLMProvider | LanguageModelV3 | AISDKLLMInput;interface
LLMProviderexport 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>;
}interface
LLMGenerateOptions/**
* 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;
}interface
AISDKLLMInput/**
* 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>>;
}type
EmbeddingConfigexport type EmbeddingConfig = Embedder | AISDKEmbeddingInput;
interface
Embedderexport interface Embedder {
name: string;
dimensions: number;
maxBatchSize?: number | undefined;
supportsAsymmetric?: boolean | undefined;
embed(input: EmbedInput): Promise<number[][]>;
}interface
EmbedInputexport interface EmbedInput {
texts: string[];
inputType?: 'document' | 'search' | undefined;
outputDimensions?: number | undefined;
abortSignal?: AbortSignal | undefined;
}interface
AISDKEmbeddingInput/**
* 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>>;
}interface
Extractorexport interface Extractor {
name: string;
capabilities: ExtractorCapabilities;
extract(input: ExtractorInput, ctx: ExtractorContext): Promise<ExtractionResult>;
}interface
ExtractorCapabilitiesexport interface ExtractorCapabilities {
supportsBatch: boolean;
supportsStreaming: boolean;
requiresStructuredOutput: boolean;
multimodal: Array<'text' | 'image' | 'audio' | 'video' | 'pdf'>;
preservesOntology: boolean;
}interface
ExtractorInputexport 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;
}interface
ExtractorContextexport 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;
}interface
ExtractionResultexport interface ExtractionResult {
entities: ExtractedEntity[];
relations: ExtractedRelation[];
warnings?: string[] | undefined;
rawModelOutput?: unknown;
}interface
Rerankerexport interface Reranker<TCandidate = unknown> {
name: string;
rerank(query: string, candidates: TCandidate[], opts?: RerankerOptions): Promise<TCandidate[]>;
}interface
RerankerOptionsexport interface RerankerOptions {
topK?: number | undefined;
domain?: 'general' | 'legal' | 'code' | 'medical' | undefined;
abortSignal?: AbortSignal | undefined;
}interface
CreateBucketInputexport 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;
}interface
BucketListFilterexport interface BucketListFilter {
name?: string | undefined;
}interface
IndexDefaults/**
* 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;
}interface
DocumentInputexport 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;
}interface
DocumentFilterexport interface DocumentFilter {
bucketId?: string | undefined;
status?: DocumentStatus | DocumentStatus[] | undefined;
documentIds?: string[] | undefined;
}type
DocumentStatusexport type DocumentStatus = 'pending' | 'processing' | 'complete' | 'failed';
interface
EventInputexport 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;
}interface
EventFilterexport interface EventFilter {
eventIds?: string[] | undefined;
}interface
ThreadInputexport interface ThreadInput<TMeta extends Record<string, unknown> = Record<string, unknown>> {
id?: string | undefined;
name: string;
description?: string | undefined;
metadata?: TMeta | undefined;
}interface
ThreadTurnInputexport interface ThreadTurnInput<TMeta extends Record<string, unknown> = Record<string, unknown>> {
role: string;
content: string;
timestamp?: Date | undefined;
metadata?: TMeta | undefined;
}interface
ThreadTurnResultexport interface ThreadTurnResult {
thread: typegraphThread;
event: typegraphEventRecord;
}interface
ThreadFilterexport interface ThreadFilter {
threadIds?: string[] | undefined;
}interface
SearchOptionsexport 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;
}type
SearchResourceexport type SearchResource = 'documents' | 'events' | 'threads' | 'entities' | 'facts';
type
SearchWeightsexport type SearchWeights = {
semantic?: number | false | undefined;
bm25?: number | false | undefined;
graph?: number | false | undefined;
recency?: number | false | undefined;
};type
SearchFusionexport type SearchFusion = {
method?: 'rrf' | undefined;
k?: number | undefined;
};type
SearchRerankOptionsexport type SearchRerankOptions = boolean | {
topK?: number | undefined;
domain?: 'general' | 'legal' | 'code' | 'medical' | undefined;
};interface
SearchExplanationexport 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;
}type
PromptFormatexport type PromptFormat = 'xml' | 'markdown' | 'plain';
type
PromptSectionexport type PromptSection = 'facts' | 'entities' | 'chunks';
interface
PromptBuilderOptionsexport interface PromptBuilderOptions {
format?: PromptFormat | undefined;
sections?: PromptSection[] | undefined;
includeAttributes?: boolean | undefined;
maxTotalTokens?: number | undefined;
maxChunkTokens?: number | undefined;
maxFactTokens?: number | undefined;
maxEntityTokens?: number | undefined;
}interface
PromptStatsexport interface PromptStats {
format: PromptFormat;
totalTokens: number;
truncated: boolean;
sections: Partial<Record<PromptSection, {
available: number;
included: number;
tokens: number;
truncated: boolean;
}>>;
}interface
QueryResponseexport 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;
}interface
OutputScoresexport interface OutputScores {
semantic?: number | undefined;
bm25?: number | undefined;
graph?: number | undefined;
recency?: number | undefined;
fused: number;
reranker?: number | undefined;
}type
EntityTypeexport type EntityType = typeof ENTITY_TYPES[number];
interface
EntityTypeSpecexport interface EntityTypeSpec {
name: EntityType;
description: string;
examples: string[];
}interface
PredicateSpecexport 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;
}interface
PredicateAliasSpecexport interface PredicateAliasSpec {
name: string;
swap?: boolean | undefined;
temporalStatus?: PredicateTemporalStatus | undefined;
}type
PredicateTemporalStatusexport type PredicateTemporalStatus = 'current' | 'former' | 'historical' | 'unknown';
interface
PredicateNormalizationexport interface PredicateNormalization {
original: string;
predicate: string;
valid: boolean;
swapSubjectObject: boolean;
symmetric: boolean;
temporalStatus?: PredicateTemporalStatus | undefined;
}interface
PredicateTypeValidationexport interface PredicateTypeValidation {
valid: boolean;
domainValid: boolean;
rangeValid: boolean;
reason?: string | undefined;
}interface
GraphEntityRefexport 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;
}interface
UpsertGraphEntityInputexport 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;
}interface
UpsertGraphEdgeInputexport 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;
}interface
UpsertGraphFactInputexport 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;
}interface
MergeGraphEntitiesInputexport interface MergeGraphEntitiesInput {
sourceEntityId: string;
targetEntityId: string;
metadata?: Record<string, unknown> | undefined;
}interface
MergeGraphEntitiesResultexport interface MergeGraphEntitiesResult {
target: EntityDetail;
sourceEntityId: string;
targetEntityId: string;
redirectedEdges: number;
redirectedFacts: number;
redirectedGraphEdges: number;
movedMentions: number;
movedExternalIds: number;
removedSelfEdges: number;
}interface
DeleteGraphEntityOptsexport interface DeleteGraphEntityOpts {
mode?: 'invalidate' | 'purge' | undefined;
}interface
DeleteGraphEntityResultexport interface DeleteGraphEntityResult {
entityId: string;
mode: 'invalidate' | 'purge';
deletedEdges: number;
deletedFacts: number;
deletedGraphEdges: number;
deletedMentions: number;
deletedExternalIds: number;
}interface
EntityResultexport 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;
}interface
EntityDetailexport interface EntityDetail extends EntityResult {
description?: string | undefined;
createdAt: Date;
validAt?: Date | undefined;
invalidAt?: Date | undefined;
/** Top edges by weight. */
topEdges: EdgeResult[];
}interface
EdgeResultexport interface EdgeResult {
id: string;
sourceEntityId: string;
sourceEntityName: string;
targetEntityId: string;
targetEntityName: string;
relation: string;
weight: number;
metadata?: Record<string, unknown> | undefined;
}interface
FactResultexport 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;
}interface
FactSearchOptsexport interface FactSearchOpts extends TypeGraphOptions {
limit?: number | undefined;
}interface
ChunkResultexport 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;
}type
GraphSearchProfileexport type GraphSearchProfile = 'fact-filtered-narrow';
interface
GraphSearchOptsexport 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;
}type
GraphExplainOptsexport type GraphExplainOpts = GraphSearchOpts & TypeGraphOptions;
interface
GraphSearchTraceexport 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;
}interface
GraphSearchResultexport interface GraphSearchResult {
results: ChunkResult[];
facts: FactResult[];
entities: EntityResult[];
factChains?: FactChainResult[] | undefined;
trace: GraphSearchTrace;
}interface
GraphExploreOptionsexport 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;
}type
GraphExploreOptsexport type GraphExploreOpts = GraphExploreOptions & TypeGraphOptions;
type
GraphIntentParserModeexport type GraphIntentParserMode = 'deterministic' | 'llm' | 'none';
type
GraphExploreIntentexport type GraphExploreIntent = GraphQueryIntent;
interface
GraphExploreTraceexport 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;
}interface
GraphExploreResultexport interface GraphExploreResult {
intent: GraphExploreIntent;
anchors: EntityResult[];
entities: EntityResult[];
facts: FactResult[];
chunks?: ChunkResult[] | undefined;
trace?: GraphExploreTrace | undefined;
}interface
GraphBackfillOptsexport interface GraphBackfillOpts {
bucketIds?: string[] | undefined;
batchSize?: number | undefined;
entityChunkEdges?: boolean | undefined;
facts?: boolean | undefined;
entityProfiles?: boolean | undefined;
}interface
GraphBackfillResultexport interface GraphBackfillResult {
entityChunkEdgesUpserted: number;
factRecordsUpserted: number;
entityProfilesUpdated: number;
batches: number;
}interface
SubgraphResultexport 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;
};
}interface
GraphStatsexport 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;
}>;
}interface
MemorySubjectexport 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;
}interface
RememberOptsexport interface RememberOpts extends TypeGraphOptions {
category?: string | undefined;
importance?: number | undefined;
metadata?: Record<string, unknown> | undefined;
subject?: MemorySubject | undefined;
relatedEntities?: MemorySubject[] | undefined;
graphExtraction?: boolean | undefined;
}interface
ForgetOptsexport interface ForgetOpts extends TypeGraphOptions {
}interface
CorrectOptsexport interface CorrectOpts extends TypeGraphOptions {
subject?: MemorySubject | undefined;
relatedEntities?: MemorySubject[] | undefined;
graphExtraction?: boolean | undefined;
}interface
RecallOptsexport 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;
}type
MemoryCategoryexport type MemoryCategory = 'episodic' | 'semantic' | 'procedural';
type
MemoryStatusexport type MemoryStatus = 'pending' | 'active' | 'consolidated' | 'invalidated' | 'archived' | 'expired';
interface
MemoryHealthReport/** 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;
}interface
Job/** 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;
}interface
JobFilterexport interface JobFilter {
bucketId?: string | undefined;
status?: JobStatus | undefined;
type?: JobType | undefined;
}type
JobStatusexport type JobStatus = 'pending' | 'processing' | 'complete' | 'failed';
type
JobTypeexport type JobType = 'ingest' | 'remember' | 'thread_turn' | 'correct' | 'forget';
interface
Policyexport 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;
}type
PolicyActionexport type PolicyAction = 'query' | 'index' | 'memory.write' | 'memory.read' | 'memory.delete' | 'document.delete' | 'bucket.delete';
interface
PolicyRuleexport 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>;
}interface
PolicyDecisionexport interface PolicyDecision {
allowed: boolean;
violations: PolicyViolation[];
}type
PolicyTypeexport type PolicyType = 'access' | 'retention' | 'data_flow';
interface
PaginationOpts/** 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;
}interface
PaginatedResult/** Paginated result set. */
export interface PaginatedResult<T> {
items: T[];
total: number;
limit: number;
offset: number;
}