🚀. Socket Launch Week Day 2:Introducing Manifest Alerts.Learn more
Sign In

@atomicmemory/sdk

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@atomicmemory/sdk - npm Package Compare versions

Comparing version
1.0.3
to
1.1.0
+30
dist/chunk-4CP57UR3.js
// src/memory/capability-profiles.ts
function capabilityGaps(caps, profile) {
const gaps = [];
for (const mode of profile.ingestModes) {
if (!caps.ingestModes.includes(mode)) {
gaps.push({
kind: "ingestMode",
requirement: mode,
detail: `ingestModes must include '${mode}'`
});
}
}
for (const extension of profile.extensions) {
if (caps.extensions[extension] !== true) {
gaps.push({
kind: "extension",
requirement: extension,
detail: `extensions.${extension} must be true`
});
}
}
return gaps;
}
function satisfiesProfile(caps, profile) {
return capabilityGaps(caps, profile).length === 0;
}
export { capabilityGaps, satisfiesProfile };
//# sourceMappingURL=chunk-4CP57UR3.js.map
//# sourceMappingURL=chunk-4CP57UR3.js.map
{"version":3,"sources":["../src/memory/capability-profiles.ts"],"names":[],"mappings":";AAgDO,SAAS,cAAA,CAAe,MAAoB,OAAA,EAA6C;AAC9F,EAAA,MAAM,OAAwB,EAAC;AAE/B,EAAA,KAAA,MAAW,IAAA,IAAQ,QAAQ,WAAA,EAAa;AACtC,IAAA,IAAI,CAAC,IAAA,CAAK,WAAA,CAAY,QAAA,CAAS,IAAI,CAAA,EAAG;AACpC,MAAA,IAAA,CAAK,IAAA,CAAK;AAAA,QACR,IAAA,EAAM,YAAA;AAAA,QACN,WAAA,EAAa,IAAA;AAAA,QACb,MAAA,EAAQ,6BAA6B,IAAI,CAAA,CAAA;AAAA,OAC1C,CAAA;AAAA,IACH;AAAA,EACF;AAEA,EAAA,KAAA,MAAW,SAAA,IAAa,QAAQ,UAAA,EAAY;AAC1C,IAAA,IAAI,IAAA,CAAK,UAAA,CAAW,SAAS,CAAA,KAAM,IAAA,EAAM;AACvC,MAAA,IAAA,CAAK,IAAA,CAAK;AAAA,QACR,IAAA,EAAM,WAAA;AAAA,QACN,WAAA,EAAa,SAAA;AAAA,QACb,MAAA,EAAQ,cAAc,SAAS,CAAA,aAAA;AAAA,OAChC,CAAA;AAAA,IACH;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT;AAGO,SAAS,gBAAA,CAAiB,MAAoB,OAAA,EAAqC;AACxF,EAAA,OAAO,cAAA,CAAe,IAAA,EAAM,OAAO,CAAA,CAAE,MAAA,KAAW,CAAA;AAClD","file":"chunk-4CP57UR3.js","sourcesContent":["/**\n * @file Capability profiles\n *\n * A capability profile is the minimum {@link Capabilities} a\n * {@link MemoryProvider} must satisfy for a given consumer's needs (for\n * example, an audited ingest→search→replay path that requires deterministic\n * verbatim storage and version pinning). It is expressed as a typed, partial\n * requirement set so a caller can gate a provider at wiring time with an\n * actionable diff instead of an opaque boolean.\n *\n * The SDK ships the generic mechanism; each consumer defines its own profile\n * constant against this type. Pure runtime code — no I/O, no provider\n * construction.\n */\n\nimport type { Capabilities, IngestInput } from './types';\n\n/** A minimum capability requirement set a provider must satisfy. */\nexport interface CapabilityProfile {\n /** Ingest modes the provider must support (e.g. `'text'`, `'verbatim'`). */\n ingestModes: ReadonlyArray<IngestInput['mode']>;\n /**\n * Extension flags the provider must expose (`extensions.<flag> === true`).\n * `search` is not listed here — it is a core method every `MemoryProvider`\n * implements, so it is implied rather than gated.\n */\n extensions: ReadonlyArray<keyof Capabilities['extensions']>;\n}\n\n/**\n * A single unmet capability requirement, for actionable provider-rejection\n * errors.\n */\nexport interface CapabilityGap {\n /** Which requirement category is unmet. */\n kind: 'ingestMode' | 'extension';\n /** The specific ingest mode or extension flag that is missing. */\n requirement: string;\n /** Human-readable reason the requirement is unmet. */\n detail: string;\n}\n\n/**\n * Return every requirement in `profile` that `caps` fails to satisfy. An empty\n * array means the provider satisfies the profile. Use this to build actionable\n * errors (\"provider X is missing verbatim ingest, missing versioning\n * extension\") instead of an opaque boolean rejection.\n */\nexport function capabilityGaps(caps: Capabilities, profile: CapabilityProfile): CapabilityGap[] {\n const gaps: CapabilityGap[] = [];\n\n for (const mode of profile.ingestModes) {\n if (!caps.ingestModes.includes(mode)) {\n gaps.push({\n kind: 'ingestMode',\n requirement: mode,\n detail: `ingestModes must include '${mode}'`,\n });\n }\n }\n\n for (const extension of profile.extensions) {\n if (caps.extensions[extension] !== true) {\n gaps.push({\n kind: 'extension',\n requirement: extension,\n detail: `extensions.${extension} must be true`,\n });\n }\n }\n\n return gaps;\n}\n\n/** Whether `caps` satisfies every requirement in `profile`. */\nexport function satisfiesProfile(caps: Capabilities, profile: CapabilityProfile): boolean {\n return capabilityGaps(caps, profile).length === 0;\n}\n"]}
'use strict';
var chunkNULA3B6E_cjs = require('./chunk-NULA3B6E.cjs');
// src/memory/providers/registry.ts
var defaultRegistry = {
atomicmemory: (config) => ({
provider: new chunkNULA3B6E_cjs.AtomicMemoryProvider(config)
}),
mem0: (config) => ({
provider: new chunkNULA3B6E_cjs.Mem0Provider(config)
}),
hindsight: (config) => ({
provider: new chunkNULA3B6E_cjs.HindsightProvider(config)
})
};
// src/memory/memory-service.ts
var MemoryService = class {
constructor(config) {
this.config = config;
this.defaultProviderName = config.defaultProvider;
}
config;
providers = /* @__PURE__ */ new Map();
pipelines = /* @__PURE__ */ new Map();
defaultProviderName;
async initialize(registry = defaultRegistry) {
const stagedProviders = /* @__PURE__ */ new Map();
const stagedPipelines = /* @__PURE__ */ new Map();
try {
for (const [name, providerConfig] of Object.entries(
this.config.providerConfigs
)) {
const factory = registry[name];
if (!factory) continue;
const registration = await factory(providerConfig);
stagedProviders.set(name, registration.provider);
stagedPipelines.set(
name,
registration.pipeline ?? chunkNULA3B6E_cjs.noopMemoryPipeline
);
if (registration.provider.initialize) {
await registration.provider.initialize();
}
}
} catch (cause) {
await Promise.allSettled(
[...stagedProviders.values()].map((p) => p.close?.())
);
throw cause;
}
for (const [name, provider] of stagedProviders) this.providers.set(name, provider);
for (const [name, pipeline] of stagedPipelines) this.pipelines.set(name, pipeline);
}
getProvider(name) {
const providerName = name ?? this.defaultProviderName;
const provider = this.providers.get(providerName);
if (!provider) {
throw new Error(
`Provider "${providerName}" is not registered`
);
}
return provider;
}
getAvailableProviders() {
return Array.from(this.providers.keys());
}
/**
* Provider names declared in the SDK configuration, regardless of whether
* they have been initialized yet. Useful for UI and getter paths that
* need to advertise capabilities before `initialize()` has run.
*/
getConfiguredProviders() {
return Object.keys(this.config.providerConfigs);
}
// -----------------------------------------------------------------------
// Core operations
// -----------------------------------------------------------------------
async ingest(input, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
if (pipeline.preprocessIngest) {
const inputs = await pipeline.preprocessIngest(input);
const results = [];
for (const i of inputs) {
const result2 = await provider.ingest(i);
if (pipeline.postprocessIngest) {
await pipeline.postprocessIngest(result2, i);
}
results.push(result2);
}
return mergeIngestResults(results);
}
const result = await provider.ingest(input);
if (pipeline.postprocessIngest) {
await pipeline.postprocessIngest(result, input);
}
return result;
}
async search(request, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const processedRequest = pipeline.preprocessSearch ? await pipeline.preprocessSearch(request) : request;
const page = await provider.search(processedRequest);
return pipeline.postprocessSearch ? await pipeline.postprocessSearch(page, processedRequest) : page;
}
async get(ref, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const processedRef = pipeline.preprocessGet ? await pipeline.preprocessGet(ref) : ref;
const memory = await provider.get(processedRef);
return pipeline.postprocessGet ? await pipeline.postprocessGet(memory, processedRef) : memory;
}
async delete(ref, providerName) {
const provider = this.getProvider(providerName);
await provider.delete(ref);
}
async list(request, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const page = await provider.list(request);
return pipeline.postprocessList ? await pipeline.postprocessList(page, request) : page;
}
async package(request, providerName) {
const provider = this.getProvider(providerName);
const packager = provider.getExtension?.("package");
if (!packager) {
throw new chunkNULA3B6E_cjs.UnsupportedOperationError(
provider.name,
"package"
);
}
return packager.package(request);
}
// -----------------------------------------------------------------------
// Internals
// -----------------------------------------------------------------------
getPipeline(name) {
const providerName = name ?? this.defaultProviderName;
return this.pipelines.get(providerName) ?? chunkNULA3B6E_cjs.noopMemoryPipeline;
}
};
function mergeIngestResults(results) {
return {
created: results.flatMap((r) => r.created),
updated: results.flatMap((r) => r.updated),
unchanged: results.flatMap((r) => r.unchanged)
};
}
// src/client/memory-client.ts
var MemoryClient = class {
service;
initialized = false;
initPromise;
constructor(config) {
const providerConfigs = { ...config.providers };
const defaultProvider = config.defaultProvider ?? pickFirstProviderKey(providerConfigs);
if (!defaultProvider) {
throw new Error(
'MemoryClient requires at least one provider config. Pass e.g. { providers: { atomicmemory: { apiUrl: "..." } } }.'
);
}
this.service = new MemoryService({
defaultProvider,
providerConfigs
});
}
/**
* Initialize all configured providers. Must be called before any memory
* operation. Idempotent and concurrency-safe: concurrent and subsequent
* calls share a single initialization run. The `registry` argument of the
* first call wins; later calls share that run and their argument is ignored.
* A REJECTED initialization is sticky — retrying on the same instance
* re-throws the original error (partial provider state from a failed run is
* never reused); resolve the cause (e.g. install a missing optional peer)
* and construct a new client.
*/
async initialize(registry = defaultRegistry) {
this.initPromise ??= this.service.initialize(registry).then(() => {
this.initialized = true;
});
return this.initPromise;
}
/**
* Write memory(ies). Input supports `text`, `messages`, or `memory` modes.
*/
async ingest(input) {
this.assertInitialized();
return this.service.ingest(input);
}
/**
* Ingest without any application-layer gating. Equivalent to `ingest()`
* on the core client; application wrappers override the gated variant
* while delegating this path straight through.
*/
async ingestDirect(input) {
this.assertInitialized();
return this.service.ingest(input);
}
/**
* Search for memories matching the request.
*/
async search(request) {
this.assertInitialized();
return this.service.search(request);
}
/**
* Search without application-layer gating. See `ingestDirect` for the
* rationale.
*/
async searchDirect(request) {
this.assertInitialized();
return this.service.search(request);
}
/**
* Build an injection-ready context package from a scoped request.
* Provider must implement the `package` extension.
*/
async package(request) {
this.assertInitialized();
return this.service.package(request);
}
/**
* Package without application-layer gating.
*/
async packageDirect(request) {
this.assertInitialized();
return this.service.package(request);
}
/**
* Fetch a single memory by reference.
*/
async get(ref) {
this.assertInitialized();
return this.service.get(ref);
}
/**
* Delete a single memory by reference.
*/
async delete(ref) {
this.assertInitialized();
return this.service.delete(ref);
}
/**
* List memories within a scope.
*/
async list(request) {
this.assertInitialized();
return this.service.list(request);
}
/**
* Report the capability surface of the default (or named) provider.
*
* @throws if the named provider is unknown or not initialized.
*/
capabilities(providerName) {
this.assertInitialized();
return this.service.getProvider(providerName).capabilities();
}
/**
* Resolve a named extension on the default (or named) provider.
* Returns `undefined` when the provider does not advertise the
* extension.
*
* @throws if the named provider is unknown or not initialized.
*
* @example
* ```ts
* const pkg = memory.getExtension<Packager>('package');
* ```
*/
getExtension(extensionName, providerName) {
this.assertInitialized();
const provider = this.service.getProvider(providerName);
return provider.getExtension?.(extensionName);
}
/**
* Aggregate status of all configured providers. Never throws:
* uninitialized providers report `initialized: false` and
* `capabilities: null`.
*/
getProviderStatus() {
const configured = this.service.getConfiguredProviders();
const available = new Set(this.service.getAvailableProviders());
return configured.map((name) => {
if (!available.has(name)) {
return { name, initialized: false, capabilities: null };
}
return {
name,
initialized: true,
capabilities: this.service.getProvider(name).capabilities()
};
});
}
/**
* Access the full AtomicMemory namespace handle (lifecycle, audit,
* lessons, config, agents). Returns `undefined` when the client is
* not yet initialized, the `atomicmemory` provider was not included
* in the `providers` config, or that provider does not advertise the
* namespace handle. This getter intentionally never throws — callers
* can guard with a truthy check and let the handle's own methods
* raise if used incorrectly.
*/
get atomicmemory() {
if (!this.initialized) return void 0;
if (!this.service.getConfiguredProviders().includes("atomicmemory")) {
return void 0;
}
const provider = this.service.getProvider("atomicmemory");
return provider.getExtension?.("atomicmemory.base");
}
/**
* Low-level escape hatch for callers that need the concrete provider.
*/
getProvider(name) {
this.assertInitialized();
return this.service.getProvider(name);
}
assertInitialized() {
if (!this.initialized) {
throw new Error(
"MemoryClient is not initialized. Call `await client.initialize()` first."
);
}
}
};
function pickFirstProviderKey(providers) {
for (const [key, value] of Object.entries(providers)) {
if (value !== void 0 && key !== "default") return key;
}
return void 0;
}
exports.MemoryClient = MemoryClient;
//# sourceMappingURL=chunk-KIUVJBBH.cjs.map
//# sourceMappingURL=chunk-KIUVJBBH.cjs.map
{"version":3,"sources":["../src/memory/providers/registry.ts","../src/memory/memory-service.ts","../src/client/memory-client.ts"],"names":["AtomicMemoryProvider","Mem0Provider","HindsightProvider","noopMemoryPipeline","result","UnsupportedOperationError"],"mappings":";;;;;AAoBO,IAAM,eAAA,GAAoC;AAAA,EAC/C,YAAA,EAAc,CAAC,MAAA,MAAoE;AAAA,IACjF,QAAA,EAAU,IAAIA,sCAAA,CAAqB,MAAM;AAAA,GAC3C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,MAAA,MAA4D;AAAA,IACjE,QAAA,EAAU,IAAIC,8BAAA,CAAa,MAAM;AAAA,GACnC,CAAA;AAAA,EACA,SAAA,EAAW,CAAC,MAAA,MAAiE;AAAA,IAC3E,QAAA,EAAU,IAAIC,mCAAA,CAAkB,MAAM;AAAA,GACxC;AACF,CAAA;;;ACIO,IAAM,gBAAN,MAAoB;AAAA,EAKzB,YAA6B,MAAA,EAA6B;AAA7B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAC3B,IAAA,IAAA,CAAK,sBAAsB,MAAA,CAAO,eAAA;AAAA,EACpC;AAAA,EAF6B,MAAA;AAAA,EAJrB,SAAA,uBAAgB,GAAA,EAA4B;AAAA,EAC5C,SAAA,uBAAgB,GAAA,EAAsC;AAAA,EACtD,mBAAA;AAAA,EAMR,MAAM,UAAA,CACJ,QAAA,GAA6B,eAAA,EACd;AAIf,IAAA,MAAM,eAAA,uBAAsB,GAAA,EAA4B;AACxD,IAAA,MAAM,eAAA,uBAAsB,GAAA,EAAsC;AAClE,IAAA,IAAI;AACF,MAAA,KAAA,MAAW,CAAC,IAAA,EAAM,cAAc,CAAA,IAAK,MAAA,CAAO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A,EAAG;AACnE,MAAA,OAAO,MAAA;AAAA,IACT;AACA,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,WAAA,CAAY,cAAc,CAAA;AACxD,IAAA,OAAO,QAAA,CAAS,eAAmC,mBAAmB,CAAA;AAAA,EACxE;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY,IAAA,EAA+B;AACzC,IAAA,IAAA,CAAK,iBAAA,EAAkB;AACvB,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,WAAA,CAAY,IAAI,CAAA;AAAA,EACtC;AAAA,EAEQ,iBAAA,GAA0B;AAChC,IAAA,IAAI,CAAC,KAAK,WAAA,EAAa;AACrB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,qBAAqB,SAAA,EAAwD;AACpF,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,SAAS,CAAA,EAAG;AACpD,IAAA,IAAI,KAAA,KAAU,MAAA,IAAa,GAAA,KAAQ,SAAA,EAAW,OAAO,GAAA;AAAA,EACvD;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-KIUVJBBH.cjs","sourcesContent":["/**\n * @file Memory Provider Registry\n *\n * Maps provider names to factory functions that create\n * MemoryProviderRegistration instances from configuration.\n */\n\nimport type { MemoryProviderRegistration } from '../registration';\nimport type { AtomicMemoryProviderConfig } from '../atomicmemory-provider/types';\nimport { AtomicMemoryProvider } from '../atomicmemory-provider/atomicmemory-provider';\nimport type { Mem0ProviderConfig } from '../mem0-provider/types';\nimport { Mem0Provider } from '../mem0-provider/mem0-provider';\nimport type { HindsightProviderConfig } from '../hindsight-provider/types';\nimport { HindsightProvider } from '../hindsight-provider/hindsight-provider';\n\nexport type ProviderRegistry = Record<\n string,\n (config: any) => MemoryProviderRegistration | Promise<MemoryProviderRegistration>\n>;\n\nexport const defaultRegistry: ProviderRegistry = {\n atomicmemory: (config: AtomicMemoryProviderConfig): MemoryProviderRegistration => ({\n provider: new AtomicMemoryProvider(config),\n }),\n mem0: (config: Mem0ProviderConfig): MemoryProviderRegistration => ({\n provider: new Mem0Provider(config),\n }),\n hindsight: (config: HindsightProviderConfig): MemoryProviderRegistration => ({\n provider: new HindsightProvider(config),\n }),\n};\n","/**\n * @file Memory Service\n *\n * Replaces UnifiedContextService. Routes operations to the correct\n * provider and applies optional processing pipelines.\n */\n\nimport type { MemoryProvider, Packager } from './provider';\nimport type { MemoryProcessingPipeline } from './pipeline';\nimport { noopMemoryPipeline } from './pipeline';\nimport type { MemoryProviderRegistration } from './registration';\nimport { UnsupportedOperationError } from './errors';\nimport type {\n IngestInput,\n IngestResult,\n SearchRequest,\n SearchResultPage,\n MemoryRef,\n Memory,\n ListRequest,\n ListResultPage,\n PackageRequest,\n ContextPackage,\n} from './types';\nimport {\n defaultRegistry,\n type ProviderRegistry,\n} from './providers/registry';\n\nexport interface MemoryServiceConfig {\n defaultProvider: string;\n providerConfigs: Record<string, unknown>;\n}\n\nexport class MemoryService {\n private providers = new Map<string, MemoryProvider>();\n private pipelines = new Map<string, MemoryProcessingPipeline>();\n private defaultProviderName: string;\n\n constructor(private readonly config: MemoryServiceConfig) {\n this.defaultProviderName = config.defaultProvider;\n }\n\n async initialize(\n registry: ProviderRegistry = defaultRegistry\n ): Promise<void> {\n // Stage registrations locally and commit only on full success, so a\n // mid-loop failure can never leave partially registered providers\n // observable via getProviderStatus()/getAvailableProviders().\n const stagedProviders = new Map<string, MemoryProvider>();\n const stagedPipelines = new Map<string, MemoryProcessingPipeline>();\n try {\n for (const [name, providerConfig] of Object.entries(\n this.config.providerConfigs\n )) {\n const factory = registry[name];\n if (!factory) continue;\n const registration: MemoryProviderRegistration = await factory(providerConfig);\n stagedProviders.set(name, registration.provider);\n stagedPipelines.set(\n name,\n registration.pipeline ?? noopMemoryPipeline\n );\n if (registration.provider.initialize) {\n await registration.provider.initialize();\n }\n }\n } catch (cause) {\n // Best-effort teardown of providers that already initialized during\n // staging, so a failed init doesn't leak connections. The original\n // error still propagates.\n await Promise.allSettled(\n [...stagedProviders.values()].map((p) => p.close?.()),\n );\n throw cause;\n }\n for (const [name, provider] of stagedProviders) this.providers.set(name, provider);\n for (const [name, pipeline] of stagedPipelines) this.pipelines.set(name, pipeline);\n }\n\n getProvider(name?: string): MemoryProvider {\n const providerName = name ?? this.defaultProviderName;\n const provider = this.providers.get(providerName);\n if (!provider) {\n throw new Error(\n `Provider \"${providerName}\" is not registered`\n );\n }\n return provider;\n }\n\n getAvailableProviders(): string[] {\n return Array.from(this.providers.keys());\n }\n\n /**\n * Provider names declared in the SDK configuration, regardless of whether\n * they have been initialized yet. Useful for UI and getter paths that\n * need to advertise capabilities before `initialize()` has run.\n */\n getConfiguredProviders(): string[] {\n return Object.keys(this.config.providerConfigs);\n }\n\n // -----------------------------------------------------------------------\n // Core operations\n // -----------------------------------------------------------------------\n\n async ingest(\n input: IngestInput,\n providerName?: string\n ): Promise<IngestResult> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n if (pipeline.preprocessIngest) {\n const inputs = await pipeline.preprocessIngest(input);\n const results: IngestResult[] = [];\n for (const i of inputs) {\n const result = await provider.ingest(i);\n if (pipeline.postprocessIngest) {\n await pipeline.postprocessIngest(result, i);\n }\n results.push(result);\n }\n return mergeIngestResults(results);\n }\n\n const result = await provider.ingest(input);\n if (pipeline.postprocessIngest) {\n await pipeline.postprocessIngest(result, input);\n }\n return result;\n }\n\n async search(\n request: SearchRequest,\n providerName?: string\n ): Promise<SearchResultPage> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const processedRequest = pipeline.preprocessSearch\n ? await pipeline.preprocessSearch(request)\n : request;\n\n const page = await provider.search(processedRequest);\n\n return pipeline.postprocessSearch\n ? await pipeline.postprocessSearch(page, processedRequest)\n : page;\n }\n\n async get(\n ref: MemoryRef,\n providerName?: string\n ): Promise<Memory | null> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const processedRef = pipeline.preprocessGet\n ? await pipeline.preprocessGet(ref)\n : ref;\n\n const memory = await provider.get(processedRef);\n\n return pipeline.postprocessGet\n ? await pipeline.postprocessGet(memory, processedRef)\n : memory;\n }\n\n async delete(\n ref: MemoryRef,\n providerName?: string\n ): Promise<void> {\n const provider = this.getProvider(providerName);\n await provider.delete(ref);\n }\n\n async list(\n request: ListRequest,\n providerName?: string\n ): Promise<ListResultPage> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const page = await provider.list(request);\n\n return pipeline.postprocessList\n ? await pipeline.postprocessList(page, request)\n : page;\n }\n\n async package(\n request: PackageRequest,\n providerName?: string\n ): Promise<ContextPackage> {\n const provider = this.getProvider(providerName);\n const packager = provider.getExtension?.<Packager>('package');\n if (!packager) {\n throw new UnsupportedOperationError(\n provider.name,\n 'package'\n );\n }\n return packager.package(request);\n }\n\n // -----------------------------------------------------------------------\n // Internals\n // -----------------------------------------------------------------------\n\n private getPipeline(\n name?: string\n ): MemoryProcessingPipeline {\n const providerName = name ?? this.defaultProviderName;\n return (\n this.pipelines.get(providerName) ?? noopMemoryPipeline\n );\n }\n}\n\nfunction mergeIngestResults(\n results: IngestResult[]\n): IngestResult {\n return {\n created: results.flatMap((r) => r.created),\n updated: results.flatMap((r) => r.updated),\n unchanged: results.flatMap((r) => r.unchanged),\n };\n}\n","/**\n * @file MemoryClient — primary public API for the memory-layer SDK\n *\n * Pure memory operations: ingest, search, package, list, get, delete,\n * capability inspection, and provider namespace handles. No policy\n * gating, no platform/targetDomain parameters — applications that need\n * those layer them on top of this client.\n */\n\nimport { MemoryService } from '../memory/memory-service';\nimport type { MemoryProvider } from '../memory/provider';\nimport type { AtomicMemoryProviderConfig } from '../memory/atomicmemory-provider/types';\nimport type { AtomicMemoryHandle } from '../memory/atomicmemory-provider/handle';\nimport type { Mem0ProviderConfig } from '../memory/mem0-provider/types';\nimport type { HindsightProviderConfig } from '../memory/hindsight-provider/types';\nimport type {\n IngestInput,\n IngestResult,\n SearchRequest,\n SearchResultPage,\n MemoryRef,\n Memory,\n ListRequest,\n ListResultPage,\n PackageRequest,\n ContextPackage,\n Capabilities,\n} from '../memory/types';\nimport {\n defaultRegistry,\n type ProviderRegistry,\n} from '../memory/providers/registry';\n\n/**\n * Provider configuration map. Each key names a provider; the value is\n * that provider's configuration object.\n */\nexport interface MemoryProviderConfigs {\n atomicmemory?: AtomicMemoryProviderConfig;\n mem0?: Mem0ProviderConfig;\n hindsight?: HindsightProviderConfig;\n [providerName: string]: unknown;\n}\n\n/**\n * MemoryClient configuration.\n */\nexport interface MemoryClientConfig {\n /** Provider configurations keyed by provider name. */\n providers: MemoryProviderConfigs;\n /** Name of the default provider. If omitted, the first configured provider wins. */\n defaultProvider?: string;\n}\n\n/**\n * Status summary for each configured provider.\n */\nexport interface ProviderStatus {\n name: string;\n initialized: boolean;\n capabilities: Capabilities | null;\n}\n\n/**\n * MemoryClient — pure memory-layer API.\n *\n * @example\n * ```ts\n * const memory = new MemoryClient({\n * providers: { atomicmemory: { apiUrl: 'http://localhost:17350' } },\n * });\n * await memory.initialize();\n * await memory.ingest({ mode: 'text', content: 'hi', scope: { user: 'u1' } });\n * const results = await memory.search({ query: 'hi', scope: { user: 'u1' } });\n * ```\n */\nexport class MemoryClient {\n private readonly service: MemoryService;\n private initialized = false;\n private initPromise?: Promise<void>;\n\n constructor(config: MemoryClientConfig) {\n const providerConfigs: Record<string, unknown> = { ...config.providers };\n const defaultProvider =\n config.defaultProvider ?? pickFirstProviderKey(providerConfigs);\n\n if (!defaultProvider) {\n throw new Error(\n 'MemoryClient requires at least one provider config. ' +\n 'Pass e.g. { providers: { atomicmemory: { apiUrl: \"...\" } } }.'\n );\n }\n\n this.service = new MemoryService({\n defaultProvider,\n providerConfigs,\n });\n }\n\n /**\n * Initialize all configured providers. Must be called before any memory\n * operation. Idempotent and concurrency-safe: concurrent and subsequent\n * calls share a single initialization run. The `registry` argument of the\n * first call wins; later calls share that run and their argument is ignored.\n * A REJECTED initialization is sticky — retrying on the same instance\n * re-throws the original error (partial provider state from a failed run is\n * never reused); resolve the cause (e.g. install a missing optional peer)\n * and construct a new client.\n */\n async initialize(registry: ProviderRegistry = defaultRegistry): Promise<void> {\n this.initPromise ??= this.service.initialize(registry).then(() => {\n this.initialized = true;\n });\n return this.initPromise;\n }\n\n /**\n * Write memory(ies). Input supports `text`, `messages`, or `memory` modes.\n */\n async ingest(input: IngestInput): Promise<IngestResult> {\n this.assertInitialized();\n return this.service.ingest(input);\n }\n\n /**\n * Ingest without any application-layer gating. Equivalent to `ingest()`\n * on the core client; application wrappers override the gated variant\n * while delegating this path straight through.\n */\n async ingestDirect(input: IngestInput): Promise<IngestResult> {\n this.assertInitialized();\n return this.service.ingest(input);\n }\n\n /**\n * Search for memories matching the request.\n */\n async search(request: SearchRequest): Promise<SearchResultPage> {\n this.assertInitialized();\n return this.service.search(request);\n }\n\n /**\n * Search without application-layer gating. See `ingestDirect` for the\n * rationale.\n */\n async searchDirect(request: SearchRequest): Promise<SearchResultPage> {\n this.assertInitialized();\n return this.service.search(request);\n }\n\n /**\n * Build an injection-ready context package from a scoped request.\n * Provider must implement the `package` extension.\n */\n async package(request: PackageRequest): Promise<ContextPackage> {\n this.assertInitialized();\n return this.service.package(request);\n }\n\n /**\n * Package without application-layer gating.\n */\n async packageDirect(request: PackageRequest): Promise<ContextPackage> {\n this.assertInitialized();\n return this.service.package(request);\n }\n\n /**\n * Fetch a single memory by reference.\n */\n async get(ref: MemoryRef): Promise<Memory | null> {\n this.assertInitialized();\n return this.service.get(ref);\n }\n\n /**\n * Delete a single memory by reference.\n */\n async delete(ref: MemoryRef): Promise<void> {\n this.assertInitialized();\n return this.service.delete(ref);\n }\n\n /**\n * List memories within a scope.\n */\n async list(request: ListRequest): Promise<ListResultPage> {\n this.assertInitialized();\n return this.service.list(request);\n }\n\n /**\n * Report the capability surface of the default (or named) provider.\n *\n * @throws if the named provider is unknown or not initialized.\n */\n capabilities(providerName?: string): Capabilities {\n this.assertInitialized();\n return this.service.getProvider(providerName).capabilities();\n }\n\n /**\n * Resolve a named extension on the default (or named) provider.\n * Returns `undefined` when the provider does not advertise the\n * extension.\n *\n * @throws if the named provider is unknown or not initialized.\n *\n * @example\n * ```ts\n * const pkg = memory.getExtension<Packager>('package');\n * ```\n */\n getExtension<T>(extensionName: string, providerName?: string): T | undefined {\n this.assertInitialized();\n const provider = this.service.getProvider(providerName);\n return provider.getExtension?.<T>(extensionName);\n }\n\n /**\n * Aggregate status of all configured providers. Never throws:\n * uninitialized providers report `initialized: false` and\n * `capabilities: null`.\n */\n getProviderStatus(): ProviderStatus[] {\n const configured = this.service.getConfiguredProviders();\n const available = new Set(this.service.getAvailableProviders());\n return configured.map((name) => {\n if (!available.has(name)) {\n return { name, initialized: false, capabilities: null };\n }\n return {\n name,\n initialized: true,\n capabilities: this.service.getProvider(name).capabilities(),\n };\n });\n }\n\n /**\n * Access the full AtomicMemory namespace handle (lifecycle, audit,\n * lessons, config, agents). Returns `undefined` when the client is\n * not yet initialized, the `atomicmemory` provider was not included\n * in the `providers` config, or that provider does not advertise the\n * namespace handle. This getter intentionally never throws — callers\n * can guard with a truthy check and let the handle's own methods\n * raise if used incorrectly.\n */\n get atomicmemory(): AtomicMemoryHandle | undefined {\n if (!this.initialized) return undefined;\n if (!this.service.getConfiguredProviders().includes('atomicmemory')) {\n return undefined;\n }\n const provider = this.service.getProvider('atomicmemory');\n return provider.getExtension?.<AtomicMemoryHandle>('atomicmemory.base');\n }\n\n /**\n * Low-level escape hatch for callers that need the concrete provider.\n */\n getProvider(name?: string): MemoryProvider {\n this.assertInitialized();\n return this.service.getProvider(name);\n }\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'MemoryClient is not initialized. Call `await client.initialize()` first.'\n );\n }\n }\n}\n\nfunction pickFirstProviderKey(providers: Record<string, unknown>): string | undefined {\n for (const [key, value] of Object.entries(providers)) {\n if (value !== undefined && key !== 'default') return key;\n }\n return undefined;\n}\n"]}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

'use strict';
// src/memory/capability-profiles.ts
function capabilityGaps(caps, profile) {
const gaps = [];
for (const mode of profile.ingestModes) {
if (!caps.ingestModes.includes(mode)) {
gaps.push({
kind: "ingestMode",
requirement: mode,
detail: `ingestModes must include '${mode}'`
});
}
}
for (const extension of profile.extensions) {
if (caps.extensions[extension] !== true) {
gaps.push({
kind: "extension",
requirement: extension,
detail: `extensions.${extension} must be true`
});
}
}
return gaps;
}
function satisfiesProfile(caps, profile) {
return capabilityGaps(caps, profile).length === 0;
}
exports.capabilityGaps = capabilityGaps;
exports.satisfiesProfile = satisfiesProfile;
//# sourceMappingURL=chunk-R56Z5WG5.cjs.map
//# sourceMappingURL=chunk-R56Z5WG5.cjs.map
{"version":3,"sources":["../src/memory/capability-profiles.ts"],"names":[],"mappings":";;;AAgDO,SAAS,cAAA,CAAe,MAAoB,OAAA,EAA6C;AAC9F,EAAA,MAAM,OAAwB,EAAC;AAE/B,EAAA,KAAA,MAAW,IAAA,IAAQ,QAAQ,WAAA,EAAa;AACtC,IAAA,IAAI,CAAC,IAAA,CAAK,WAAA,CAAY,QAAA,CAAS,IAAI,CAAA,EAAG;AACpC,MAAA,IAAA,CAAK,IAAA,CAAK;AAAA,QACR,IAAA,EAAM,YAAA;AAAA,QACN,WAAA,EAAa,IAAA;AAAA,QACb,MAAA,EAAQ,6BAA6B,IAAI,CAAA,CAAA;AAAA,OAC1C,CAAA;AAAA,IACH;AAAA,EACF;AAEA,EAAA,KAAA,MAAW,SAAA,IAAa,QAAQ,UAAA,EAAY;AAC1C,IAAA,IAAI,IAAA,CAAK,UAAA,CAAW,SAAS,CAAA,KAAM,IAAA,EAAM;AACvC,MAAA,IAAA,CAAK,IAAA,CAAK;AAAA,QACR,IAAA,EAAM,WAAA;AAAA,QACN,WAAA,EAAa,SAAA;AAAA,QACb,MAAA,EAAQ,cAAc,SAAS,CAAA,aAAA;AAAA,OAChC,CAAA;AAAA,IACH;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT;AAGO,SAAS,gBAAA,CAAiB,MAAoB,OAAA,EAAqC;AACxF,EAAA,OAAO,cAAA,CAAe,IAAA,EAAM,OAAO,CAAA,CAAE,MAAA,KAAW,CAAA;AAClD","file":"chunk-R56Z5WG5.cjs","sourcesContent":["/**\n * @file Capability profiles\n *\n * A capability profile is the minimum {@link Capabilities} a\n * {@link MemoryProvider} must satisfy for a given consumer's needs (for\n * example, an audited ingest→search→replay path that requires deterministic\n * verbatim storage and version pinning). It is expressed as a typed, partial\n * requirement set so a caller can gate a provider at wiring time with an\n * actionable diff instead of an opaque boolean.\n *\n * The SDK ships the generic mechanism; each consumer defines its own profile\n * constant against this type. Pure runtime code — no I/O, no provider\n * construction.\n */\n\nimport type { Capabilities, IngestInput } from './types';\n\n/** A minimum capability requirement set a provider must satisfy. */\nexport interface CapabilityProfile {\n /** Ingest modes the provider must support (e.g. `'text'`, `'verbatim'`). */\n ingestModes: ReadonlyArray<IngestInput['mode']>;\n /**\n * Extension flags the provider must expose (`extensions.<flag> === true`).\n * `search` is not listed here — it is a core method every `MemoryProvider`\n * implements, so it is implied rather than gated.\n */\n extensions: ReadonlyArray<keyof Capabilities['extensions']>;\n}\n\n/**\n * A single unmet capability requirement, for actionable provider-rejection\n * errors.\n */\nexport interface CapabilityGap {\n /** Which requirement category is unmet. */\n kind: 'ingestMode' | 'extension';\n /** The specific ingest mode or extension flag that is missing. */\n requirement: string;\n /** Human-readable reason the requirement is unmet. */\n detail: string;\n}\n\n/**\n * Return every requirement in `profile` that `caps` fails to satisfy. An empty\n * array means the provider satisfies the profile. Use this to build actionable\n * errors (\"provider X is missing verbatim ingest, missing versioning\n * extension\") instead of an opaque boolean rejection.\n */\nexport function capabilityGaps(caps: Capabilities, profile: CapabilityProfile): CapabilityGap[] {\n const gaps: CapabilityGap[] = [];\n\n for (const mode of profile.ingestModes) {\n if (!caps.ingestModes.includes(mode)) {\n gaps.push({\n kind: 'ingestMode',\n requirement: mode,\n detail: `ingestModes must include '${mode}'`,\n });\n }\n }\n\n for (const extension of profile.extensions) {\n if (caps.extensions[extension] !== true) {\n gaps.push({\n kind: 'extension',\n requirement: extension,\n detail: `extensions.${extension} must be true`,\n });\n }\n }\n\n return gaps;\n}\n\n/** Whether `caps` satisfies every requirement in `profile`. */\nexport function satisfiesProfile(caps: Capabilities, profile: CapabilityProfile): boolean {\n return capabilityGaps(caps, profile).length === 0;\n}\n"]}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

import { HindsightProvider, Mem0Provider, AtomicMemoryProvider, noopMemoryPipeline, UnsupportedOperationError } from './chunk-T7PRWXW6.js';
// src/memory/providers/registry.ts
var defaultRegistry = {
atomicmemory: (config) => ({
provider: new AtomicMemoryProvider(config)
}),
mem0: (config) => ({
provider: new Mem0Provider(config)
}),
hindsight: (config) => ({
provider: new HindsightProvider(config)
})
};
// src/memory/memory-service.ts
var MemoryService = class {
constructor(config) {
this.config = config;
this.defaultProviderName = config.defaultProvider;
}
config;
providers = /* @__PURE__ */ new Map();
pipelines = /* @__PURE__ */ new Map();
defaultProviderName;
async initialize(registry = defaultRegistry) {
const stagedProviders = /* @__PURE__ */ new Map();
const stagedPipelines = /* @__PURE__ */ new Map();
try {
for (const [name, providerConfig] of Object.entries(
this.config.providerConfigs
)) {
const factory = registry[name];
if (!factory) continue;
const registration = await factory(providerConfig);
stagedProviders.set(name, registration.provider);
stagedPipelines.set(
name,
registration.pipeline ?? noopMemoryPipeline
);
if (registration.provider.initialize) {
await registration.provider.initialize();
}
}
} catch (cause) {
await Promise.allSettled(
[...stagedProviders.values()].map((p) => p.close?.())
);
throw cause;
}
for (const [name, provider] of stagedProviders) this.providers.set(name, provider);
for (const [name, pipeline] of stagedPipelines) this.pipelines.set(name, pipeline);
}
getProvider(name) {
const providerName = name ?? this.defaultProviderName;
const provider = this.providers.get(providerName);
if (!provider) {
throw new Error(
`Provider "${providerName}" is not registered`
);
}
return provider;
}
getAvailableProviders() {
return Array.from(this.providers.keys());
}
/**
* Provider names declared in the SDK configuration, regardless of whether
* they have been initialized yet. Useful for UI and getter paths that
* need to advertise capabilities before `initialize()` has run.
*/
getConfiguredProviders() {
return Object.keys(this.config.providerConfigs);
}
// -----------------------------------------------------------------------
// Core operations
// -----------------------------------------------------------------------
async ingest(input, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
if (pipeline.preprocessIngest) {
const inputs = await pipeline.preprocessIngest(input);
const results = [];
for (const i of inputs) {
const result2 = await provider.ingest(i);
if (pipeline.postprocessIngest) {
await pipeline.postprocessIngest(result2, i);
}
results.push(result2);
}
return mergeIngestResults(results);
}
const result = await provider.ingest(input);
if (pipeline.postprocessIngest) {
await pipeline.postprocessIngest(result, input);
}
return result;
}
async search(request, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const processedRequest = pipeline.preprocessSearch ? await pipeline.preprocessSearch(request) : request;
const page = await provider.search(processedRequest);
return pipeline.postprocessSearch ? await pipeline.postprocessSearch(page, processedRequest) : page;
}
async get(ref, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const processedRef = pipeline.preprocessGet ? await pipeline.preprocessGet(ref) : ref;
const memory = await provider.get(processedRef);
return pipeline.postprocessGet ? await pipeline.postprocessGet(memory, processedRef) : memory;
}
async delete(ref, providerName) {
const provider = this.getProvider(providerName);
await provider.delete(ref);
}
async list(request, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const page = await provider.list(request);
return pipeline.postprocessList ? await pipeline.postprocessList(page, request) : page;
}
async package(request, providerName) {
const provider = this.getProvider(providerName);
const packager = provider.getExtension?.("package");
if (!packager) {
throw new UnsupportedOperationError(
provider.name,
"package"
);
}
return packager.package(request);
}
// -----------------------------------------------------------------------
// Internals
// -----------------------------------------------------------------------
getPipeline(name) {
const providerName = name ?? this.defaultProviderName;
return this.pipelines.get(providerName) ?? noopMemoryPipeline;
}
};
function mergeIngestResults(results) {
return {
created: results.flatMap((r) => r.created),
updated: results.flatMap((r) => r.updated),
unchanged: results.flatMap((r) => r.unchanged)
};
}
// src/client/memory-client.ts
var MemoryClient = class {
service;
initialized = false;
initPromise;
constructor(config) {
const providerConfigs = { ...config.providers };
const defaultProvider = config.defaultProvider ?? pickFirstProviderKey(providerConfigs);
if (!defaultProvider) {
throw new Error(
'MemoryClient requires at least one provider config. Pass e.g. { providers: { atomicmemory: { apiUrl: "..." } } }.'
);
}
this.service = new MemoryService({
defaultProvider,
providerConfigs
});
}
/**
* Initialize all configured providers. Must be called before any memory
* operation. Idempotent and concurrency-safe: concurrent and subsequent
* calls share a single initialization run. The `registry` argument of the
* first call wins; later calls share that run and their argument is ignored.
* A REJECTED initialization is sticky — retrying on the same instance
* re-throws the original error (partial provider state from a failed run is
* never reused); resolve the cause (e.g. install a missing optional peer)
* and construct a new client.
*/
async initialize(registry = defaultRegistry) {
this.initPromise ??= this.service.initialize(registry).then(() => {
this.initialized = true;
});
return this.initPromise;
}
/**
* Write memory(ies). Input supports `text`, `messages`, or `memory` modes.
*/
async ingest(input) {
this.assertInitialized();
return this.service.ingest(input);
}
/**
* Ingest without any application-layer gating. Equivalent to `ingest()`
* on the core client; application wrappers override the gated variant
* while delegating this path straight through.
*/
async ingestDirect(input) {
this.assertInitialized();
return this.service.ingest(input);
}
/**
* Search for memories matching the request.
*/
async search(request) {
this.assertInitialized();
return this.service.search(request);
}
/**
* Search without application-layer gating. See `ingestDirect` for the
* rationale.
*/
async searchDirect(request) {
this.assertInitialized();
return this.service.search(request);
}
/**
* Build an injection-ready context package from a scoped request.
* Provider must implement the `package` extension.
*/
async package(request) {
this.assertInitialized();
return this.service.package(request);
}
/**
* Package without application-layer gating.
*/
async packageDirect(request) {
this.assertInitialized();
return this.service.package(request);
}
/**
* Fetch a single memory by reference.
*/
async get(ref) {
this.assertInitialized();
return this.service.get(ref);
}
/**
* Delete a single memory by reference.
*/
async delete(ref) {
this.assertInitialized();
return this.service.delete(ref);
}
/**
* List memories within a scope.
*/
async list(request) {
this.assertInitialized();
return this.service.list(request);
}
/**
* Report the capability surface of the default (or named) provider.
*
* @throws if the named provider is unknown or not initialized.
*/
capabilities(providerName) {
this.assertInitialized();
return this.service.getProvider(providerName).capabilities();
}
/**
* Resolve a named extension on the default (or named) provider.
* Returns `undefined` when the provider does not advertise the
* extension.
*
* @throws if the named provider is unknown or not initialized.
*
* @example
* ```ts
* const pkg = memory.getExtension<Packager>('package');
* ```
*/
getExtension(extensionName, providerName) {
this.assertInitialized();
const provider = this.service.getProvider(providerName);
return provider.getExtension?.(extensionName);
}
/**
* Aggregate status of all configured providers. Never throws:
* uninitialized providers report `initialized: false` and
* `capabilities: null`.
*/
getProviderStatus() {
const configured = this.service.getConfiguredProviders();
const available = new Set(this.service.getAvailableProviders());
return configured.map((name) => {
if (!available.has(name)) {
return { name, initialized: false, capabilities: null };
}
return {
name,
initialized: true,
capabilities: this.service.getProvider(name).capabilities()
};
});
}
/**
* Access the full AtomicMemory namespace handle (lifecycle, audit,
* lessons, config, agents). Returns `undefined` when the client is
* not yet initialized, the `atomicmemory` provider was not included
* in the `providers` config, or that provider does not advertise the
* namespace handle. This getter intentionally never throws — callers
* can guard with a truthy check and let the handle's own methods
* raise if used incorrectly.
*/
get atomicmemory() {
if (!this.initialized) return void 0;
if (!this.service.getConfiguredProviders().includes("atomicmemory")) {
return void 0;
}
const provider = this.service.getProvider("atomicmemory");
return provider.getExtension?.("atomicmemory.base");
}
/**
* Low-level escape hatch for callers that need the concrete provider.
*/
getProvider(name) {
this.assertInitialized();
return this.service.getProvider(name);
}
assertInitialized() {
if (!this.initialized) {
throw new Error(
"MemoryClient is not initialized. Call `await client.initialize()` first."
);
}
}
};
function pickFirstProviderKey(providers) {
for (const [key, value] of Object.entries(providers)) {
if (value !== void 0 && key !== "default") return key;
}
return void 0;
}
export { MemoryClient };
//# sourceMappingURL=chunk-V5K4WVX5.js.map
//# sourceMappingURL=chunk-V5K4WVX5.js.map
{"version":3,"sources":["../src/memory/providers/registry.ts","../src/memory/memory-service.ts","../src/client/memory-client.ts"],"names":["result"],"mappings":";;;AAoBO,IAAM,eAAA,GAAoC;AAAA,EAC/C,YAAA,EAAc,CAAC,MAAA,MAAoE;AAAA,IACjF,QAAA,EAAU,IAAI,oBAAA,CAAqB,MAAM;AAAA,GAC3C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,MAAA,MAA4D;AAAA,IACjE,QAAA,EAAU,IAAI,YAAA,CAAa,MAAM;AAAA,GACnC,CAAA;AAAA,EACA,SAAA,EAAW,CAAC,MAAA,MAAiE;AAAA,IAC3E,QAAA,EAAU,IAAI,iBAAA,CAAkB,MAAM;AAAA,GACxC;AACF,CAAA;;;ACIO,IAAM,gBAAN,MAAoB;AAAA,EAKzB,YAA6B,MAAA,EAA6B;AAA7B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAC3B,IAAA,IAAA,CAAK,sBAAsB,MAAA,CAAO,eAAA;AAAA,EACpC;AAAA,EAF6B,MAAA;AAAA,EAJrB,SAAA,uBAAgB,GAAA,EAA4B;AAAA,EAC5C,SAAA,uBAAgB,GAAA,EAAsC;AAAA,EACtD,mBAAA;AAAA,EAMR,MAAM,UAAA,CACJ,QAAA,GAA6B,eAAA,EACd;AAIf,IAAA,MAAM,eAAA,uBAAsB,GAAA,EAA4B;AACxD,IAAA,MAAM,eAAA,uBAAsB,GAAA,EAAsC;AAClE,IAAA,IAAI;AACF,MAAA,KAAA,MAAW,CAAC,IAAA,EAAM,cAAc,CAAA,IAAK,MAAA,CAAO,OAAA;AAAA,QAC1C,KAAK,MAAA,CAAO;AAAA,OACd,EAAG;AACD,QAAA,MAAM,OAAA,GAAU,SAAS,IAAI,CAAA;AAC7B,QAAA,IAAI,CAAC,OAAA,EAAS;AACd,QAAA,MAAM,YAAA,GAA2C,MAAM,OAAA,CAAQ,cAAc,CA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A;AAAA,EAKA,YAAY,IAAA,EAA+B;AACzC,IAAA,IAAA,CAAK,iBAAA,EAAkB;AACvB,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,WAAA,CAAY,IAAI,CAAA;AAAA,EACtC;AAAA,EAEQ,iBAAA,GAA0B;AAChC,IAAA,IAAI,CAAC,KAAK,WAAA,EAAa;AACrB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,qBAAqB,SAAA,EAAwD;AACpF,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,SAAS,CAAA,EAAG;AACpD,IAAA,IAAI,KAAA,KAAU,MAAA,IAAa,GAAA,KAAQ,SAAA,EAAW,OAAO,GAAA;AAAA,EACvD;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-V5K4WVX5.js","sourcesContent":["/**\n * @file Memory Provider Registry\n *\n * Maps provider names to factory functions that create\n * MemoryProviderRegistration instances from configuration.\n */\n\nimport type { MemoryProviderRegistration } from '../registration';\nimport type { AtomicMemoryProviderConfig } from '../atomicmemory-provider/types';\nimport { AtomicMemoryProvider } from '../atomicmemory-provider/atomicmemory-provider';\nimport type { Mem0ProviderConfig } from '../mem0-provider/types';\nimport { Mem0Provider } from '../mem0-provider/mem0-provider';\nimport type { HindsightProviderConfig } from '../hindsight-provider/types';\nimport { HindsightProvider } from '../hindsight-provider/hindsight-provider';\n\nexport type ProviderRegistry = Record<\n string,\n (config: any) => MemoryProviderRegistration | Promise<MemoryProviderRegistration>\n>;\n\nexport const defaultRegistry: ProviderRegistry = {\n atomicmemory: (config: AtomicMemoryProviderConfig): MemoryProviderRegistration => ({\n provider: new AtomicMemoryProvider(config),\n }),\n mem0: (config: Mem0ProviderConfig): MemoryProviderRegistration => ({\n provider: new Mem0Provider(config),\n }),\n hindsight: (config: HindsightProviderConfig): MemoryProviderRegistration => ({\n provider: new HindsightProvider(config),\n }),\n};\n","/**\n * @file Memory Service\n *\n * Replaces UnifiedContextService. Routes operations to the correct\n * provider and applies optional processing pipelines.\n */\n\nimport type { MemoryProvider, Packager } from './provider';\nimport type { MemoryProcessingPipeline } from './pipeline';\nimport { noopMemoryPipeline } from './pipeline';\nimport type { MemoryProviderRegistration } from './registration';\nimport { UnsupportedOperationError } from './errors';\nimport type {\n IngestInput,\n IngestResult,\n SearchRequest,\n SearchResultPage,\n MemoryRef,\n Memory,\n ListRequest,\n ListResultPage,\n PackageRequest,\n ContextPackage,\n} from './types';\nimport {\n defaultRegistry,\n type ProviderRegistry,\n} from './providers/registry';\n\nexport interface MemoryServiceConfig {\n defaultProvider: string;\n providerConfigs: Record<string, unknown>;\n}\n\nexport class MemoryService {\n private providers = new Map<string, MemoryProvider>();\n private pipelines = new Map<string, MemoryProcessingPipeline>();\n private defaultProviderName: string;\n\n constructor(private readonly config: MemoryServiceConfig) {\n this.defaultProviderName = config.defaultProvider;\n }\n\n async initialize(\n registry: ProviderRegistry = defaultRegistry\n ): Promise<void> {\n // Stage registrations locally and commit only on full success, so a\n // mid-loop failure can never leave partially registered providers\n // observable via getProviderStatus()/getAvailableProviders().\n const stagedProviders = new Map<string, MemoryProvider>();\n const stagedPipelines = new Map<string, MemoryProcessingPipeline>();\n try {\n for (const [name, providerConfig] of Object.entries(\n this.config.providerConfigs\n )) {\n const factory = registry[name];\n if (!factory) continue;\n const registration: MemoryProviderRegistration = await factory(providerConfig);\n stagedProviders.set(name, registration.provider);\n stagedPipelines.set(\n name,\n registration.pipeline ?? noopMemoryPipeline\n );\n if (registration.provider.initialize) {\n await registration.provider.initialize();\n }\n }\n } catch (cause) {\n // Best-effort teardown of providers that already initialized during\n // staging, so a failed init doesn't leak connections. The original\n // error still propagates.\n await Promise.allSettled(\n [...stagedProviders.values()].map((p) => p.close?.()),\n );\n throw cause;\n }\n for (const [name, provider] of stagedProviders) this.providers.set(name, provider);\n for (const [name, pipeline] of stagedPipelines) this.pipelines.set(name, pipeline);\n }\n\n getProvider(name?: string): MemoryProvider {\n const providerName = name ?? this.defaultProviderName;\n const provider = this.providers.get(providerName);\n if (!provider) {\n throw new Error(\n `Provider \"${providerName}\" is not registered`\n );\n }\n return provider;\n }\n\n getAvailableProviders(): string[] {\n return Array.from(this.providers.keys());\n }\n\n /**\n * Provider names declared in the SDK configuration, regardless of whether\n * they have been initialized yet. Useful for UI and getter paths that\n * need to advertise capabilities before `initialize()` has run.\n */\n getConfiguredProviders(): string[] {\n return Object.keys(this.config.providerConfigs);\n }\n\n // -----------------------------------------------------------------------\n // Core operations\n // -----------------------------------------------------------------------\n\n async ingest(\n input: IngestInput,\n providerName?: string\n ): Promise<IngestResult> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n if (pipeline.preprocessIngest) {\n const inputs = await pipeline.preprocessIngest(input);\n const results: IngestResult[] = [];\n for (const i of inputs) {\n const result = await provider.ingest(i);\n if (pipeline.postprocessIngest) {\n await pipeline.postprocessIngest(result, i);\n }\n results.push(result);\n }\n return mergeIngestResults(results);\n }\n\n const result = await provider.ingest(input);\n if (pipeline.postprocessIngest) {\n await pipeline.postprocessIngest(result, input);\n }\n return result;\n }\n\n async search(\n request: SearchRequest,\n providerName?: string\n ): Promise<SearchResultPage> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const processedRequest = pipeline.preprocessSearch\n ? await pipeline.preprocessSearch(request)\n : request;\n\n const page = await provider.search(processedRequest);\n\n return pipeline.postprocessSearch\n ? await pipeline.postprocessSearch(page, processedRequest)\n : page;\n }\n\n async get(\n ref: MemoryRef,\n providerName?: string\n ): Promise<Memory | null> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const processedRef = pipeline.preprocessGet\n ? await pipeline.preprocessGet(ref)\n : ref;\n\n const memory = await provider.get(processedRef);\n\n return pipeline.postprocessGet\n ? await pipeline.postprocessGet(memory, processedRef)\n : memory;\n }\n\n async delete(\n ref: MemoryRef,\n providerName?: string\n ): Promise<void> {\n const provider = this.getProvider(providerName);\n await provider.delete(ref);\n }\n\n async list(\n request: ListRequest,\n providerName?: string\n ): Promise<ListResultPage> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const page = await provider.list(request);\n\n return pipeline.postprocessList\n ? await pipeline.postprocessList(page, request)\n : page;\n }\n\n async package(\n request: PackageRequest,\n providerName?: string\n ): Promise<ContextPackage> {\n const provider = this.getProvider(providerName);\n const packager = provider.getExtension?.<Packager>('package');\n if (!packager) {\n throw new UnsupportedOperationError(\n provider.name,\n 'package'\n );\n }\n return packager.package(request);\n }\n\n // -----------------------------------------------------------------------\n // Internals\n // -----------------------------------------------------------------------\n\n private getPipeline(\n name?: string\n ): MemoryProcessingPipeline {\n const providerName = name ?? this.defaultProviderName;\n return (\n this.pipelines.get(providerName) ?? noopMemoryPipeline\n );\n }\n}\n\nfunction mergeIngestResults(\n results: IngestResult[]\n): IngestResult {\n return {\n created: results.flatMap((r) => r.created),\n updated: results.flatMap((r) => r.updated),\n unchanged: results.flatMap((r) => r.unchanged),\n };\n}\n","/**\n * @file MemoryClient — primary public API for the memory-layer SDK\n *\n * Pure memory operations: ingest, search, package, list, get, delete,\n * capability inspection, and provider namespace handles. No policy\n * gating, no platform/targetDomain parameters — applications that need\n * those layer them on top of this client.\n */\n\nimport { MemoryService } from '../memory/memory-service';\nimport type { MemoryProvider } from '../memory/provider';\nimport type { AtomicMemoryProviderConfig } from '../memory/atomicmemory-provider/types';\nimport type { AtomicMemoryHandle } from '../memory/atomicmemory-provider/handle';\nimport type { Mem0ProviderConfig } from '../memory/mem0-provider/types';\nimport type { HindsightProviderConfig } from '../memory/hindsight-provider/types';\nimport type {\n IngestInput,\n IngestResult,\n SearchRequest,\n SearchResultPage,\n MemoryRef,\n Memory,\n ListRequest,\n ListResultPage,\n PackageRequest,\n ContextPackage,\n Capabilities,\n} from '../memory/types';\nimport {\n defaultRegistry,\n type ProviderRegistry,\n} from '../memory/providers/registry';\n\n/**\n * Provider configuration map. Each key names a provider; the value is\n * that provider's configuration object.\n */\nexport interface MemoryProviderConfigs {\n atomicmemory?: AtomicMemoryProviderConfig;\n mem0?: Mem0ProviderConfig;\n hindsight?: HindsightProviderConfig;\n [providerName: string]: unknown;\n}\n\n/**\n * MemoryClient configuration.\n */\nexport interface MemoryClientConfig {\n /** Provider configurations keyed by provider name. */\n providers: MemoryProviderConfigs;\n /** Name of the default provider. If omitted, the first configured provider wins. */\n defaultProvider?: string;\n}\n\n/**\n * Status summary for each configured provider.\n */\nexport interface ProviderStatus {\n name: string;\n initialized: boolean;\n capabilities: Capabilities | null;\n}\n\n/**\n * MemoryClient — pure memory-layer API.\n *\n * @example\n * ```ts\n * const memory = new MemoryClient({\n * providers: { atomicmemory: { apiUrl: 'http://localhost:17350' } },\n * });\n * await memory.initialize();\n * await memory.ingest({ mode: 'text', content: 'hi', scope: { user: 'u1' } });\n * const results = await memory.search({ query: 'hi', scope: { user: 'u1' } });\n * ```\n */\nexport class MemoryClient {\n private readonly service: MemoryService;\n private initialized = false;\n private initPromise?: Promise<void>;\n\n constructor(config: MemoryClientConfig) {\n const providerConfigs: Record<string, unknown> = { ...config.providers };\n const defaultProvider =\n config.defaultProvider ?? pickFirstProviderKey(providerConfigs);\n\n if (!defaultProvider) {\n throw new Error(\n 'MemoryClient requires at least one provider config. ' +\n 'Pass e.g. { providers: { atomicmemory: { apiUrl: \"...\" } } }.'\n );\n }\n\n this.service = new MemoryService({\n defaultProvider,\n providerConfigs,\n });\n }\n\n /**\n * Initialize all configured providers. Must be called before any memory\n * operation. Idempotent and concurrency-safe: concurrent and subsequent\n * calls share a single initialization run. The `registry` argument of the\n * first call wins; later calls share that run and their argument is ignored.\n * A REJECTED initialization is sticky — retrying on the same instance\n * re-throws the original error (partial provider state from a failed run is\n * never reused); resolve the cause (e.g. install a missing optional peer)\n * and construct a new client.\n */\n async initialize(registry: ProviderRegistry = defaultRegistry): Promise<void> {\n this.initPromise ??= this.service.initialize(registry).then(() => {\n this.initialized = true;\n });\n return this.initPromise;\n }\n\n /**\n * Write memory(ies). Input supports `text`, `messages`, or `memory` modes.\n */\n async ingest(input: IngestInput): Promise<IngestResult> {\n this.assertInitialized();\n return this.service.ingest(input);\n }\n\n /**\n * Ingest without any application-layer gating. Equivalent to `ingest()`\n * on the core client; application wrappers override the gated variant\n * while delegating this path straight through.\n */\n async ingestDirect(input: IngestInput): Promise<IngestResult> {\n this.assertInitialized();\n return this.service.ingest(input);\n }\n\n /**\n * Search for memories matching the request.\n */\n async search(request: SearchRequest): Promise<SearchResultPage> {\n this.assertInitialized();\n return this.service.search(request);\n }\n\n /**\n * Search without application-layer gating. See `ingestDirect` for the\n * rationale.\n */\n async searchDirect(request: SearchRequest): Promise<SearchResultPage> {\n this.assertInitialized();\n return this.service.search(request);\n }\n\n /**\n * Build an injection-ready context package from a scoped request.\n * Provider must implement the `package` extension.\n */\n async package(request: PackageRequest): Promise<ContextPackage> {\n this.assertInitialized();\n return this.service.package(request);\n }\n\n /**\n * Package without application-layer gating.\n */\n async packageDirect(request: PackageRequest): Promise<ContextPackage> {\n this.assertInitialized();\n return this.service.package(request);\n }\n\n /**\n * Fetch a single memory by reference.\n */\n async get(ref: MemoryRef): Promise<Memory | null> {\n this.assertInitialized();\n return this.service.get(ref);\n }\n\n /**\n * Delete a single memory by reference.\n */\n async delete(ref: MemoryRef): Promise<void> {\n this.assertInitialized();\n return this.service.delete(ref);\n }\n\n /**\n * List memories within a scope.\n */\n async list(request: ListRequest): Promise<ListResultPage> {\n this.assertInitialized();\n return this.service.list(request);\n }\n\n /**\n * Report the capability surface of the default (or named) provider.\n *\n * @throws if the named provider is unknown or not initialized.\n */\n capabilities(providerName?: string): Capabilities {\n this.assertInitialized();\n return this.service.getProvider(providerName).capabilities();\n }\n\n /**\n * Resolve a named extension on the default (or named) provider.\n * Returns `undefined` when the provider does not advertise the\n * extension.\n *\n * @throws if the named provider is unknown or not initialized.\n *\n * @example\n * ```ts\n * const pkg = memory.getExtension<Packager>('package');\n * ```\n */\n getExtension<T>(extensionName: string, providerName?: string): T | undefined {\n this.assertInitialized();\n const provider = this.service.getProvider(providerName);\n return provider.getExtension?.<T>(extensionName);\n }\n\n /**\n * Aggregate status of all configured providers. Never throws:\n * uninitialized providers report `initialized: false` and\n * `capabilities: null`.\n */\n getProviderStatus(): ProviderStatus[] {\n const configured = this.service.getConfiguredProviders();\n const available = new Set(this.service.getAvailableProviders());\n return configured.map((name) => {\n if (!available.has(name)) {\n return { name, initialized: false, capabilities: null };\n }\n return {\n name,\n initialized: true,\n capabilities: this.service.getProvider(name).capabilities(),\n };\n });\n }\n\n /**\n * Access the full AtomicMemory namespace handle (lifecycle, audit,\n * lessons, config, agents). Returns `undefined` when the client is\n * not yet initialized, the `atomicmemory` provider was not included\n * in the `providers` config, or that provider does not advertise the\n * namespace handle. This getter intentionally never throws — callers\n * can guard with a truthy check and let the handle's own methods\n * raise if used incorrectly.\n */\n get atomicmemory(): AtomicMemoryHandle | undefined {\n if (!this.initialized) return undefined;\n if (!this.service.getConfiguredProviders().includes('atomicmemory')) {\n return undefined;\n }\n const provider = this.service.getProvider('atomicmemory');\n return provider.getExtension?.<AtomicMemoryHandle>('atomicmemory.base');\n }\n\n /**\n * Low-level escape hatch for callers that need the concrete provider.\n */\n getProvider(name?: string): MemoryProvider {\n this.assertInitialized();\n return this.service.getProvider(name);\n }\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'MemoryClient is not initialized. Call `await client.initialize()` first.'\n );\n }\n }\n}\n\nfunction pickFirstProviderKey(providers: Record<string, unknown>): string | undefined {\n for (const [key, value] of Object.entries(providers)) {\n if (value !== undefined && key !== 'default') return key;\n }\n return undefined;\n}\n"]}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

+22
-22
'use strict';
var chunkBEZ6NCCC_cjs = require('./chunk-BEZ6NCCC.cjs');
var chunkGHOB6O5U_cjs = require('./chunk-GHOB6O5U.cjs');
var chunkKIUVJBBH_cjs = require('./chunk-KIUVJBBH.cjs');
var chunkNULA3B6E_cjs = require('./chunk-NULA3B6E.cjs');

@@ -10,81 +10,81 @@

enumerable: true,
get: function () { return chunkBEZ6NCCC_cjs.MemoryClient; }
get: function () { return chunkKIUVJBBH_cjs.MemoryClient; }
});
Object.defineProperty(exports, "ATOMICMEMORY_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.ATOMICMEMORY_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.ATOMICMEMORY_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "ATOMICMEMORY_EXTENSION_NAMES", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.ATOMICMEMORY_EXTENSION_NAMES; }
get: function () { return chunkNULA3B6E_cjs.ATOMICMEMORY_EXTENSION_NAMES; }
});
Object.defineProperty(exports, "AtomicMemoryProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.AtomicMemoryProvider; }
get: function () { return chunkNULA3B6E_cjs.AtomicMemoryProvider; }
});
Object.defineProperty(exports, "BaseMemoryProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.BaseMemoryProvider; }
get: function () { return chunkNULA3B6E_cjs.BaseMemoryProvider; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_API_VERSION", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_API_VERSION; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_API_VERSION; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_MAX_TOKENS", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_MAX_TOKENS; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_MAX_TOKENS; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_PROJECT_ID", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_PROJECT_ID; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_PROJECT_ID; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "HINDSIGHT_SCOPE_TAGS_MATCH", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_SCOPE_TAGS_MATCH; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_SCOPE_TAGS_MATCH; }
});
Object.defineProperty(exports, "HindsightProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HindsightProvider; }
get: function () { return chunkNULA3B6E_cjs.HindsightProvider; }
});
Object.defineProperty(exports, "InvalidScopeError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.InvalidScopeError; }
get: function () { return chunkNULA3B6E_cjs.InvalidScopeError; }
});
Object.defineProperty(exports, "MEM0_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MEM0_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.MEM0_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "Mem0ContextProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.Mem0ContextProvider; }
get: function () { return chunkNULA3B6E_cjs.Mem0ContextProvider; }
});
Object.defineProperty(exports, "Mem0Provider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.Mem0Provider; }
get: function () { return chunkNULA3B6E_cjs.Mem0Provider; }
});
Object.defineProperty(exports, "MemoryProviderError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MemoryProviderError; }
get: function () { return chunkNULA3B6E_cjs.MemoryProviderError; }
});
Object.defineProperty(exports, "MemoryTransportError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MemoryTransportError; }
get: function () { return chunkNULA3B6E_cjs.MemoryTransportError; }
});
Object.defineProperty(exports, "RateLimitError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.RateLimitError; }
get: function () { return chunkNULA3B6E_cjs.RateLimitError; }
});
Object.defineProperty(exports, "UnsupportedOperationError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.UnsupportedOperationError; }
get: function () { return chunkNULA3B6E_cjs.UnsupportedOperationError; }
});
Object.defineProperty(exports, "noopMemoryPipeline", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.noopMemoryPipeline; }
get: function () { return chunkNULA3B6E_cjs.noopMemoryPipeline; }
});
//# sourceMappingURL=browser.cjs.map
//# sourceMappingURL=browser.cjs.map

@@ -1,3 +0,3 @@

import { MemoryProviderRegistration, AtomicMemoryProviderConfig, Mem0ProviderConfig, HindsightProviderConfig, IngestInput, IngestResult, SearchRequest, SearchResultPage, PackageRequest, ContextPackage, MemoryRef, Memory, ListRequest, ListResultPage, Capabilities, AtomicMemoryHandle, MemoryProvider } from './memory.cjs';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AddContextResult, AgentConflict, AgentScope, AtomicMemoryAgents, AtomicMemoryAudit, AtomicMemoryConfig, AtomicMemoryExtensionName, AtomicMemoryHealthStatus, AtomicMemoryIngestInput, AtomicMemoryIngestResult, AtomicMemoryLessons, AtomicMemoryLifecycle, AtomicMemoryListOptions, AtomicMemoryListResultPage, AtomicMemoryMemory, AtomicMemoryProvider, AtomicMemorySearchRequest, AtomicMemorySearchResult, AtomicMemorySearchResultPage, AuditTrailEntry, AuditTrailResult, AutoResolveConflictsResult, BaseMemoryProvider, BatchOps, CapCheckResult, CapRecommendation, CapStatus, ConfigUpdateResult, ConfigUpdates, ConflictResolution, ConflictStatus, ConflictsListResult, ConsolidationExecutionResult, ConsolidationResult, ConsolidationScanResult, ContextMetadata, ContextRecord, ContextSearchOptions, ContextSearchResult, DecayResult, DocumentMetadata, EmbeddingProviderName, FieldFilter, FilterExpr, Forgetter, GetTrustResult, GraphEdge, GraphNode, GraphResult, GraphSearch, GraphSearchRequest, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, Health, HealthConfig, HealthStatus, HindsightOperation, HindsightOperationsHandle, HindsightOperationsPage, HindsightProvider, HindsightRecallBudget, HindsightRetainHandle, HindsightRetainItem, HindsightRetainRequest, HindsightRetainResponse, HindsightTagsMatch, IngestBase, Insight, InvalidScopeError, LLMProviderName, Lesson, LessonSeverity, LessonStats, LessonType, LessonsListResult, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0ContextProviderConfig, Mem0Provider, MemoryKind, MemoryProcessingPipeline, MemoryProviderEntry, MemoryProviderError, MemoryScope, MemoryTransportError, MemoryVersion, Message, MessageIngest, MutationRecord, MutationSummary, MutationType, Packager, Profile, Profiler, Provenance, RateLimitError, RecentMutationsResult, ReconcileStatus, ReconciliationResult, Reflector, ResetSourceResult, ResolveConflictResult, Scope, SearchResult, SetTrustResult, StatsResult, TemporalSearch, TextIngest, UnsupportedOperationError, Updater, VerbatimIngest, Versioner, noopMemoryPipeline } from './memory.cjs';
import { aM as MemoryProviderRegistration, s as AtomicMemoryProviderConfig, aF as Mem0ProviderConfig, ah as HindsightProviderConfig, ap as IngestInput, aq as IngestResult, b9 as SearchRequest, bb as SearchResultPage, aX as PackageRequest, Q as ContextPackage, aN as MemoryRef, aG as Memory, az as ListRequest, aA as ListResultPage, F as Capabilities, i as AtomicMemoryHandle, aJ as MemoryProvider } from './hindsight-provider-CbfXnvx7.cjs';
export { A as ATOMICMEMORY_DEFAULT_TIMEOUT, a as ATOMICMEMORY_EXTENSION_NAMES, b as AddContextResult, c as AgentConflict, d as AgentScope, e as AtomicMemoryAgents, f as AtomicMemoryAudit, g as AtomicMemoryConfig, h as AtomicMemoryExtensionName, j as AtomicMemoryHealthStatus, k as AtomicMemoryIngestInput, l as AtomicMemoryIngestResult, m as AtomicMemoryLessons, n as AtomicMemoryLifecycle, o as AtomicMemoryListOptions, p as AtomicMemoryListResultPage, q as AtomicMemoryMemory, r as AtomicMemoryProvider, t as AtomicMemorySearchRequest, u as AtomicMemorySearchResult, v as AtomicMemorySearchResultPage, w as AuditTrailEntry, x as AuditTrailResult, y as AutoResolveConflictsResult, B as BaseMemoryProvider, z as BatchOps, C as CapCheckResult, D as CapRecommendation, E as CapStatus, G as ConfigUpdateResult, H as ConfigUpdates, I as ConflictResolution, J as ConflictStatus, K as ConflictsListResult, L as ConsolidationExecutionResult, M as ConsolidationResult, N as ConsolidationScanResult, O as ContentClass, P as ContextMetadata, R as ContextRecord, S as ContextSearchOptions, T as ContextSearchResult, V as DecayResult, W as DocumentMetadata, X as EmbeddingProviderName, Y as FieldFilter, Z as FilterExpr, _ as Forgetter, $ as GetTrustResult, a0 as GraphEdge, a1 as GraphNode, a2 as GraphResult, a3 as GraphSearch, a4 as GraphSearchRequest, a5 as HINDSIGHT_DEFAULT_API_VERSION, a6 as HINDSIGHT_DEFAULT_MAX_TOKENS, a7 as HINDSIGHT_DEFAULT_PROJECT_ID, a8 as HINDSIGHT_DEFAULT_TIMEOUT, a9 as HINDSIGHT_SCOPE_TAGS_MATCH, aa as Health, ab as HealthConfig, ac as HealthStatus, ad as HindsightOperation, ae as HindsightOperationsHandle, af as HindsightOperationsPage, ag as HindsightProvider, ai as HindsightRecallBudget, aj as HindsightRetainHandle, ak as HindsightRetainItem, al as HindsightRetainRequest, am as HindsightRetainResponse, an as HindsightTagsMatch, ao as IngestBase, ar as Insight, as as InvalidScopeError, at as LLMProviderName, au as Lesson, av as LessonSeverity, aw as LessonStats, ax as LessonType, ay as LessonsListResult, aB as MEM0_DEFAULT_TIMEOUT, aC as Mem0ContextProvider, aD as Mem0ContextProviderConfig, aE as Mem0Provider, aH as MemoryKind, aI as MemoryProcessingPipeline, aK as MemoryProviderEntry, aL as MemoryProviderError, aO as MemoryScope, aP as MemoryTransportError, aQ as MemoryVersion, aR as Message, aS as MessageIngest, aU as MutationRecord, aV as MutationSummary, aW as MutationType, aY as Packager, aZ as Profile, a_ as Profiler, a$ as Provenance, b0 as RateLimitError, b1 as RecentMutationsResult, b2 as ReconcileStatus, b3 as ReconciliationResult, b4 as Reflector, b5 as ResetSourceResult, b6 as ResolveConflictResult, b7 as RetrievalReceipt, b8 as Scope, ba as SearchResult, bc as SetTrustResult, bd as StatsResult, be as TemporalSearch, bf as TextIngest, bg as UnsupportedOperationError, bh as Updater, bi as VerbatimIngest, bj as Versioner, bm as noopMemoryPipeline } from './hindsight-provider-CbfXnvx7.cjs';

@@ -11,3 +11,3 @@ /**

type ProviderRegistry = Record<string, (config: any) => MemoryProviderRegistration>;
type ProviderRegistry = Record<string, (config: any) => MemoryProviderRegistration | Promise<MemoryProviderRegistration>>;

@@ -66,6 +66,13 @@ /**

private initialized;
private initPromise?;
constructor(config: MemoryClientConfig);
/**
* Initialize all configured providers. Must be called before any
* memory operation. Idempotent.
* Initialize all configured providers. Must be called before any memory
* operation. Idempotent and concurrency-safe: concurrent and subsequent
* calls share a single initialization run. The `registry` argument of the
* first call wins; later calls share that run and their argument is ignored.
* A REJECTED initialization is sticky — retrying on the same instance
* re-throws the original error (partial provider state from a failed run is
* never reused); resolve the cause (e.g. install a missing optional peer)
* and construct a new client.
*/

@@ -72,0 +79,0 @@ initialize(registry?: ProviderRegistry): Promise<void>;

@@ -1,3 +0,3 @@

import { MemoryProviderRegistration, AtomicMemoryProviderConfig, Mem0ProviderConfig, HindsightProviderConfig, IngestInput, IngestResult, SearchRequest, SearchResultPage, PackageRequest, ContextPackage, MemoryRef, Memory, ListRequest, ListResultPage, Capabilities, AtomicMemoryHandle, MemoryProvider } from './memory.js';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AddContextResult, AgentConflict, AgentScope, AtomicMemoryAgents, AtomicMemoryAudit, AtomicMemoryConfig, AtomicMemoryExtensionName, AtomicMemoryHealthStatus, AtomicMemoryIngestInput, AtomicMemoryIngestResult, AtomicMemoryLessons, AtomicMemoryLifecycle, AtomicMemoryListOptions, AtomicMemoryListResultPage, AtomicMemoryMemory, AtomicMemoryProvider, AtomicMemorySearchRequest, AtomicMemorySearchResult, AtomicMemorySearchResultPage, AuditTrailEntry, AuditTrailResult, AutoResolveConflictsResult, BaseMemoryProvider, BatchOps, CapCheckResult, CapRecommendation, CapStatus, ConfigUpdateResult, ConfigUpdates, ConflictResolution, ConflictStatus, ConflictsListResult, ConsolidationExecutionResult, ConsolidationResult, ConsolidationScanResult, ContextMetadata, ContextRecord, ContextSearchOptions, ContextSearchResult, DecayResult, DocumentMetadata, EmbeddingProviderName, FieldFilter, FilterExpr, Forgetter, GetTrustResult, GraphEdge, GraphNode, GraphResult, GraphSearch, GraphSearchRequest, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, Health, HealthConfig, HealthStatus, HindsightOperation, HindsightOperationsHandle, HindsightOperationsPage, HindsightProvider, HindsightRecallBudget, HindsightRetainHandle, HindsightRetainItem, HindsightRetainRequest, HindsightRetainResponse, HindsightTagsMatch, IngestBase, Insight, InvalidScopeError, LLMProviderName, Lesson, LessonSeverity, LessonStats, LessonType, LessonsListResult, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0ContextProviderConfig, Mem0Provider, MemoryKind, MemoryProcessingPipeline, MemoryProviderEntry, MemoryProviderError, MemoryScope, MemoryTransportError, MemoryVersion, Message, MessageIngest, MutationRecord, MutationSummary, MutationType, Packager, Profile, Profiler, Provenance, RateLimitError, RecentMutationsResult, ReconcileStatus, ReconciliationResult, Reflector, ResetSourceResult, ResolveConflictResult, Scope, SearchResult, SetTrustResult, StatsResult, TemporalSearch, TextIngest, UnsupportedOperationError, Updater, VerbatimIngest, Versioner, noopMemoryPipeline } from './memory.js';
import { aM as MemoryProviderRegistration, s as AtomicMemoryProviderConfig, aF as Mem0ProviderConfig, ah as HindsightProviderConfig, ap as IngestInput, aq as IngestResult, b9 as SearchRequest, bb as SearchResultPage, aX as PackageRequest, Q as ContextPackage, aN as MemoryRef, aG as Memory, az as ListRequest, aA as ListResultPage, F as Capabilities, i as AtomicMemoryHandle, aJ as MemoryProvider } from './hindsight-provider-CbfXnvx7.js';
export { A as ATOMICMEMORY_DEFAULT_TIMEOUT, a as ATOMICMEMORY_EXTENSION_NAMES, b as AddContextResult, c as AgentConflict, d as AgentScope, e as AtomicMemoryAgents, f as AtomicMemoryAudit, g as AtomicMemoryConfig, h as AtomicMemoryExtensionName, j as AtomicMemoryHealthStatus, k as AtomicMemoryIngestInput, l as AtomicMemoryIngestResult, m as AtomicMemoryLessons, n as AtomicMemoryLifecycle, o as AtomicMemoryListOptions, p as AtomicMemoryListResultPage, q as AtomicMemoryMemory, r as AtomicMemoryProvider, t as AtomicMemorySearchRequest, u as AtomicMemorySearchResult, v as AtomicMemorySearchResultPage, w as AuditTrailEntry, x as AuditTrailResult, y as AutoResolveConflictsResult, B as BaseMemoryProvider, z as BatchOps, C as CapCheckResult, D as CapRecommendation, E as CapStatus, G as ConfigUpdateResult, H as ConfigUpdates, I as ConflictResolution, J as ConflictStatus, K as ConflictsListResult, L as ConsolidationExecutionResult, M as ConsolidationResult, N as ConsolidationScanResult, O as ContentClass, P as ContextMetadata, R as ContextRecord, S as ContextSearchOptions, T as ContextSearchResult, V as DecayResult, W as DocumentMetadata, X as EmbeddingProviderName, Y as FieldFilter, Z as FilterExpr, _ as Forgetter, $ as GetTrustResult, a0 as GraphEdge, a1 as GraphNode, a2 as GraphResult, a3 as GraphSearch, a4 as GraphSearchRequest, a5 as HINDSIGHT_DEFAULT_API_VERSION, a6 as HINDSIGHT_DEFAULT_MAX_TOKENS, a7 as HINDSIGHT_DEFAULT_PROJECT_ID, a8 as HINDSIGHT_DEFAULT_TIMEOUT, a9 as HINDSIGHT_SCOPE_TAGS_MATCH, aa as Health, ab as HealthConfig, ac as HealthStatus, ad as HindsightOperation, ae as HindsightOperationsHandle, af as HindsightOperationsPage, ag as HindsightProvider, ai as HindsightRecallBudget, aj as HindsightRetainHandle, ak as HindsightRetainItem, al as HindsightRetainRequest, am as HindsightRetainResponse, an as HindsightTagsMatch, ao as IngestBase, ar as Insight, as as InvalidScopeError, at as LLMProviderName, au as Lesson, av as LessonSeverity, aw as LessonStats, ax as LessonType, ay as LessonsListResult, aB as MEM0_DEFAULT_TIMEOUT, aC as Mem0ContextProvider, aD as Mem0ContextProviderConfig, aE as Mem0Provider, aH as MemoryKind, aI as MemoryProcessingPipeline, aK as MemoryProviderEntry, aL as MemoryProviderError, aO as MemoryScope, aP as MemoryTransportError, aQ as MemoryVersion, aR as Message, aS as MessageIngest, aU as MutationRecord, aV as MutationSummary, aW as MutationType, aY as Packager, aZ as Profile, a_ as Profiler, a$ as Provenance, b0 as RateLimitError, b1 as RecentMutationsResult, b2 as ReconcileStatus, b3 as ReconciliationResult, b4 as Reflector, b5 as ResetSourceResult, b6 as ResolveConflictResult, b7 as RetrievalReceipt, b8 as Scope, ba as SearchResult, bc as SetTrustResult, bd as StatsResult, be as TemporalSearch, bf as TextIngest, bg as UnsupportedOperationError, bh as Updater, bi as VerbatimIngest, bj as Versioner, bm as noopMemoryPipeline } from './hindsight-provider-CbfXnvx7.js';

@@ -11,3 +11,3 @@ /**

type ProviderRegistry = Record<string, (config: any) => MemoryProviderRegistration>;
type ProviderRegistry = Record<string, (config: any) => MemoryProviderRegistration | Promise<MemoryProviderRegistration>>;

@@ -66,6 +66,13 @@ /**

private initialized;
private initPromise?;
constructor(config: MemoryClientConfig);
/**
* Initialize all configured providers. Must be called before any
* memory operation. Idempotent.
* Initialize all configured providers. Must be called before any memory
* operation. Idempotent and concurrency-safe: concurrent and subsequent
* calls share a single initialization run. The `registry` argument of the
* first call wins; later calls share that run and their argument is ignored.
* A REJECTED initialization is sticky — retrying on the same instance
* re-throws the original error (partial provider state from a failed run is
* never reused); resolve the cause (e.g. install a missing optional peer)
* and construct a new client.
*/

@@ -72,0 +79,0 @@ initialize(registry?: ProviderRegistry): Promise<void>;

@@ -1,4 +0,4 @@

export { MemoryClient } from './chunk-265G225P.js';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AtomicMemoryProvider, BaseMemoryProvider, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, HindsightProvider, InvalidScopeError, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0Provider, MemoryProviderError, MemoryTransportError, RateLimitError, UnsupportedOperationError, noopMemoryPipeline } from './chunk-YBN5Y627.js';
export { MemoryClient } from './chunk-V5K4WVX5.js';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AtomicMemoryProvider, BaseMemoryProvider, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, HindsightProvider, InvalidScopeError, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0Provider, MemoryProviderError, MemoryTransportError, RateLimitError, UnsupportedOperationError, noopMemoryPipeline } from './chunk-T7PRWXW6.js';
//# sourceMappingURL=browser.js.map
//# sourceMappingURL=browser.js.map
'use strict';
var chunkBEZ6NCCC_cjs = require('./chunk-BEZ6NCCC.cjs');
var chunkGHOB6O5U_cjs = require('./chunk-GHOB6O5U.cjs');
var chunkR56Z5WG5_cjs = require('./chunk-R56Z5WG5.cjs');
var chunkKIUVJBBH_cjs = require('./chunk-KIUVJBBH.cjs');
var chunkNULA3B6E_cjs = require('./chunk-NULA3B6E.cjs');
var chunkH52DPNS2_cjs = require('./chunk-H52DPNS2.cjs');

@@ -17,2 +18,233 @@ var chunkDIZ6Y5IO_cjs = require('./chunk-DIZ6Y5IO.cjs');

// src/entities/client.ts
var EntitiesClient = class {
apiUrl;
apiKey;
fetchImpl;
constructor(config) {
if (!config.apiUrl) throw new Error("EntitiesClient: apiUrl is required");
if (!config.apiKey) throw new Error("EntitiesClient: apiKey is required");
this.apiUrl = config.apiUrl.replace(/\/+$/, "");
this.apiKey = config.apiKey;
this.fetchImpl = config.fetch ?? fetch;
}
/** Get the synthesized profile for an entity. */
async profile(entityId, entityType = "user") {
const res = await this.request("GET", `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/profile`);
return mapProfile(await res.json());
}
/** List all entities with memory counts (paginated). */
async list(opts = {}) {
const qs = buildEntityListQuery(opts);
const res = await this.request("GET", `/v1/entities${qs}`);
return mapList(await res.json());
}
/** Get entity detail — attributes, relations, and recent cards. */
async get(entityId, entityType = "user") {
const res = await this.request("GET", `/v1/entities/${entityType}/${encodeURIComponent(entityId)}`);
return mapDetail(await res.json());
}
/** Cascade-delete all data for an entity. */
async delete(entityId, entityType = "user") {
const res = await this.request("DELETE", `/v1/entities/${entityType}/${encodeURIComponent(entityId)}`);
return mapDeleteResult(await res.json());
}
/** Get structured attribute triples for an entity. */
async attributes(entityId, opts = {}, entityType = "user") {
const qs = buildAttributesQuery(opts);
const res = await this.request("GET", `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/attributes${qs}`);
const body = await res.json();
return (body.attributes ?? []).map(mapAttribute);
}
/** Get the mutation history of a single memory record. */
async memoryHistory(entityId, memoryId, entityType = "user") {
const res = await this.request(
"GET",
`/v1/entities/${entityType}/${encodeURIComponent(entityId)}/memories/${encodeURIComponent(memoryId)}/history`
);
return mapHistory(await res.json());
}
/** Update per-entity extraction guidance and pipeline config. */
async patchSettings(entityId, input, entityType = "user") {
const body = {};
if (input.extractionPrompt !== void 0) body.extraction_prompt = input.extractionPrompt;
if (input.memoryKinds !== void 0) body.memory_kinds = input.memoryKinds;
if (input.decayEnabled !== void 0) body.decay_enabled = input.decayEnabled;
const res = await this.request(
"PATCH",
`/v1/entities/${entityType}/${encodeURIComponent(entityId)}/settings`,
{ headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }
);
return mapSettings(await res.json());
}
/** Merge a source entity into a target entity. */
async merge(source, target) {
const body = {
source: { entity_type: source.entityType ?? "user", entity_id: source.entityId },
target: { entity_type: target.entityType ?? "user", entity_id: target.entityId }
};
const res = await this.request("POST", "/v1/entities/merge", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
return mapMergeResult(await res.json());
}
async request(method, path, init = {}) {
const url = `${this.apiUrl}${path}`;
let res;
try {
res = await this.fetchImpl(url, {
method,
headers: { Authorization: `Bearer ${this.apiKey}`, ...init.headers ?? {} },
body: init.body
});
} catch (cause) {
throw new Error(
`EntitiesClient: network error calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`
);
}
if (res.ok) return res;
const text = await res.text().catch(() => "");
throw new Error(`EntitiesClient: ${method} ${path} failed with ${res.status}: ${text}`);
}
};
function buildEntityListQuery(opts) {
const p = new URLSearchParams();
if (opts.entityType) p.set("entity_type", opts.entityType);
if (opts.page !== void 0) p.set("page", String(opts.page));
if (opts.pageSize !== void 0) p.set("page_size", String(opts.pageSize));
return p.toString() ? `?${p.toString()}` : "";
}
function buildAttributesQuery(opts) {
const p = new URLSearchParams();
if (opts.attribute) p.set("attribute", opts.attribute);
if (opts.entity) p.set("entity", opts.entity);
if (opts.limit !== void 0) p.set("limit", String(opts.limit));
return p.toString() ? `?${p.toString()}` : "";
}
function mapAttribute(r) {
const a = r;
return {
entity: a.entity,
attribute: a.attribute,
value: a.value,
type: a.type,
sourceMemoryId: a.source_memory_id ?? null,
observedAt: a.observed_at
};
}
function mapRelation(r) {
const row = r;
return {
targetEntityId: row.target_entity_id,
relationType: row.relation_type,
confidence: row.confidence,
validTo: row.valid_to ?? null
};
}
function mapCard(c) {
const card = c;
return {
entityName: card.entity_name,
cardText: card.card_text,
version: card.version,
updatedAt: card.updated_at
};
}
function mapProfileBody(raw) {
if (!raw) return null;
return {
summary: raw.summary,
preferences: raw.preferences ?? [],
instructions: raw.instructions ?? [],
openCommitments: raw.open_commitments ?? []
};
}
function mapProfile(r) {
return {
entityType: r.entity_type,
entityId: r.entity_id,
profile: mapProfileBody(r.profile),
attributes: (r.attributes ?? []).map(mapAttribute),
memoryCount: r.memory_count,
lastActive: r.last_active ?? null,
updatedAt: r.updated_at ?? null
};
}
function mapList(r) {
return {
entities: (r.entities ?? []).map((e) => {
const entity = e;
return {
entityType: entity.entity_type,
entityId: entity.entity_id,
memoryCount: entity.memory_count,
lastActive: entity.last_active ?? null
};
}),
total: r.total,
page: r.page,
pageSize: r.page_size
};
}
function mapDetail(r) {
return {
entityType: r.entity_type,
entityId: r.entity_id,
memoryCount: r.memory_count,
attributes: (r.attributes ?? []).map(mapAttribute),
relations: (r.relations ?? []).map(mapRelation),
recentCards: (r.recent_cards ?? []).map(mapCard),
updatedAt: r.updated_at ?? null
};
}
function mapDeleteResult(r) {
const d = r.deleted;
return {
deleted: {
memories: d.memories,
entityAttributes: d.entity_attributes,
profile: d.profile,
entities: d.entities,
entityEdges: d.entity_edges,
entityCards: d.entity_cards
}
};
}
function mapHistory(r) {
return {
memoryId: r.memory_id,
history: (r.history ?? []).map((h) => {
const entry = h;
return {
versionId: entry.version_id,
event: entry.event,
content: entry.content,
timestamp: entry.timestamp,
supersededBy: entry.superseded_by ?? null
};
})
};
}
function mapSettings(r) {
return {
entityId: r.entity_id,
extractionPrompt: r.extraction_prompt ?? null,
memoryKinds: r.memory_kinds ?? null,
decayEnabled: r.decay_enabled,
updatedAt: r.updated_at
};
}
function mapMergeResult(r) {
const m = r.merged;
return {
merged: {
memoriesMoved: m.memories_moved,
attributesMoved: m.attributes_moved,
cardsMoved: m.cards_moved
},
targetEntityId: r.target_entity_id
};
}
// src/client/atomic-memory-client.ts

@@ -22,2 +254,3 @@ var AtomicMemoryClient = class {

storage;
entities;
constructor(config) {

@@ -33,3 +266,3 @@ if (!config.apiUrl) {

}
this.memory = new chunkBEZ6NCCC_cjs.MemoryClient(
this.memory = new chunkKIUVJBBH_cjs.MemoryClient(
config.memory ?? {

@@ -47,2 +280,7 @@ providers: {

});
this.entities = new EntitiesClient({
apiUrl: config.apiUrl,
apiKey: config.apiKey,
fetch: config.fetch
});
}

@@ -55,81 +293,89 @@ };

Object.defineProperty(exports, "capabilityGaps", {
enumerable: true,
get: function () { return chunkR56Z5WG5_cjs.capabilityGaps; }
});
Object.defineProperty(exports, "satisfiesProfile", {
enumerable: true,
get: function () { return chunkR56Z5WG5_cjs.satisfiesProfile; }
});
Object.defineProperty(exports, "MemoryClient", {
enumerable: true,
get: function () { return chunkBEZ6NCCC_cjs.MemoryClient; }
get: function () { return chunkKIUVJBBH_cjs.MemoryClient; }
});
Object.defineProperty(exports, "ATOMICMEMORY_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.ATOMICMEMORY_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.ATOMICMEMORY_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "ATOMICMEMORY_EXTENSION_NAMES", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.ATOMICMEMORY_EXTENSION_NAMES; }
get: function () { return chunkNULA3B6E_cjs.ATOMICMEMORY_EXTENSION_NAMES; }
});
Object.defineProperty(exports, "AtomicMemoryProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.AtomicMemoryProvider; }
get: function () { return chunkNULA3B6E_cjs.AtomicMemoryProvider; }
});
Object.defineProperty(exports, "BaseMemoryProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.BaseMemoryProvider; }
get: function () { return chunkNULA3B6E_cjs.BaseMemoryProvider; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_API_VERSION", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_API_VERSION; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_API_VERSION; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_MAX_TOKENS", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_MAX_TOKENS; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_MAX_TOKENS; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_PROJECT_ID", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_PROJECT_ID; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_PROJECT_ID; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "HINDSIGHT_SCOPE_TAGS_MATCH", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_SCOPE_TAGS_MATCH; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_SCOPE_TAGS_MATCH; }
});
Object.defineProperty(exports, "HindsightProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HindsightProvider; }
get: function () { return chunkNULA3B6E_cjs.HindsightProvider; }
});
Object.defineProperty(exports, "InvalidScopeError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.InvalidScopeError; }
get: function () { return chunkNULA3B6E_cjs.InvalidScopeError; }
});
Object.defineProperty(exports, "MEM0_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MEM0_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.MEM0_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "Mem0ContextProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.Mem0ContextProvider; }
get: function () { return chunkNULA3B6E_cjs.Mem0ContextProvider; }
});
Object.defineProperty(exports, "Mem0Provider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.Mem0Provider; }
get: function () { return chunkNULA3B6E_cjs.Mem0Provider; }
});
Object.defineProperty(exports, "MemoryProviderError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MemoryProviderError; }
get: function () { return chunkNULA3B6E_cjs.MemoryProviderError; }
});
Object.defineProperty(exports, "MemoryTransportError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MemoryTransportError; }
get: function () { return chunkNULA3B6E_cjs.MemoryTransportError; }
});
Object.defineProperty(exports, "RateLimitError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.RateLimitError; }
get: function () { return chunkNULA3B6E_cjs.RateLimitError; }
});
Object.defineProperty(exports, "UnsupportedOperationError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.UnsupportedOperationError; }
get: function () { return chunkNULA3B6E_cjs.UnsupportedOperationError; }
});
Object.defineProperty(exports, "noopMemoryPipeline", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.noopMemoryPipeline; }
get: function () { return chunkNULA3B6E_cjs.noopMemoryPipeline; }
});

@@ -430,4 +676,5 @@ Object.defineProperty(exports, "DEFAULT_VALIDATION_CONFIG", {

exports.AtomicMemoryClient = AtomicMemoryClient;
exports.EntitiesClient = EntitiesClient;
exports.SDK_VERSION = SDK_VERSION;
//# sourceMappingURL=index.cjs.map
//# sourceMappingURL=index.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/client/atomic-memory-client.ts","../src/index.ts"],"names":["MemoryClient","ConcreteStorageClient"],"mappings":";;;;;;;;;;;;;;;;;AA4DO,IAAM,qBAAN,MAAyB;AAAA,EACrB,MAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,MAAA,EAAkC;AAC5C,IAAA,IAAI,CAAC,OAAO,MAAA,EAAQ;AAClB,MAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,IAC1D;AACA,IAAA,IAAI,CAAC,OAAO,MAAA,EAAQ;AAClB,MAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,IAC1D;AACA,IAAA,IAAI,CAAC,OAAO,MAAA,EAAQ;AAClB,MAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,IAC1D;AAOA,IAAA,IAAA,CAAK,SAAS,IAAIA,8BAAA;AAAA,MAChB,OAAO,MAAA,IAAU;AAAA,QACf,SAAA,EAAW;AAAA,UACT,cAAc,EAAE,MAAA,EAAQ,OAAO,MAAA,EAAQ,MAAA,EAAQ,OAAO,MAAA;AAAO;AAC/D;AACF,KACF;AACA,IAAA,IAAA,CAAK,OAAA,GAAU,IAAIC,uCAAA,CAAsB;AAAA,MACvC,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,OAAO,MAAA,CAAO;AAAA,KACf,CAAA;AAAA,EACH;AACF;;;ACsDO,IAAM,WAAA,GAAc;AACpB,IAAM,WAAA,GAAc","file":"index.cjs","sourcesContent":["/**\n * @file `AtomicMemoryClient` — primary public surface for the SDK.\n *\n * Aggregates `memory` (the memory-layer API) and `storage` (the\n * direct-storage API) under one client so callers see a coherent\n * single entry point:\n *\n * import { AtomicMemoryClient } from '@atomicmemory/sdk';\n * const client = new AtomicMemoryClient({\n * apiUrl: 'http://localhost:17350',\n * apiKey: process.env.ATOMICMEMORY_API_KEY!,\n * userId: 'u1',\n * });\n * await client.memory.initialize();\n * const artifact = await client.storage.put({\n * mode: 'pointer',\n * uri: 'https://example.com/file.pdf',\n * contentType: 'application/pdf',\n * });\n *\n * v1 SDK is server-side only. Browser bundles must proxy through a\n * trusted server, such as an application-owned API boundary.\n *\n * Applications that only need memory operations can still use\n * `MemoryClient` directly. New integrations should prefer\n * `AtomicMemoryClient.memory`.\n */\n\nimport { MemoryClient, type MemoryClientConfig } from './memory-client';\nimport { ConcreteStorageClient } from '../storage/client';\nimport type { StorageClient } from '../storage/interfaces';\n\n/**\n * Constructor config for the aggregator. All three transport fields\n * (`apiUrl`, `apiKey`, `userId`) are REQUIRED — they back both the\n * storage namespace and the default AtomicMemory memory provider.\n * Memory-only consumers should still pass `apiUrl` (it doubles as\n * the default memory provider's `apiUrl`); the `memory` block then\n * narrows the registration further if a non-default provider mix is\n * needed.\n *\n * `userId` is the owner-scope seam the storage routes accept until a\n * real auth seam ships. `fetch` is an optional override; defaults to\n * the Node global.\n */\nexport interface AtomicMemoryClientConfig {\n apiUrl: string;\n apiKey: string;\n userId: string;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n /** Memory-provider registration. Defaults to a single AtomicMemory\n * provider pointing at `apiUrl`. */\n memory?: MemoryClientConfig;\n}\n\n/**\n * Primary public client. Holds a `memory` namespace (`MemoryClient`)\n * and a `storage` namespace (`StorageClient`).\n */\nexport class AtomicMemoryClient {\n readonly memory: MemoryClient;\n readonly storage: StorageClient;\n\n constructor(config: AtomicMemoryClientConfig) {\n if (!config.apiUrl) {\n throw new Error('AtomicMemoryClient: apiUrl is required');\n }\n if (!config.apiKey) {\n throw new Error('AtomicMemoryClient: apiKey is required');\n }\n if (!config.userId) {\n throw new Error('AtomicMemoryClient: userId is required');\n }\n // Default provider registration MUST forward the apiKey so the\n // memory namespace shares the storage namespace's auth contract.\n // The earlier shape dropped it silently — memory requests went\n // out unauthenticated even when the caller supplied `apiKey`,\n // failing with 401 against any core deployment that gates `/v1/*`\n // (every deployment since the auth middleware landed).\n this.memory = new MemoryClient(\n config.memory ?? {\n providers: {\n atomicmemory: { apiUrl: config.apiUrl, apiKey: config.apiKey },\n },\n },\n );\n this.storage = new ConcreteStorageClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n userId: config.userId,\n fetch: config.fetch,\n });\n }\n}\n","/**\n * @file @atomicmemory/sdk public surface\n *\n * Backend-agnostic memory-layer SDK. Pluggable providers, local\n * embeddings, storage adapters, semantic search.\n *\n * @example\n * ```typescript\n * import { MemoryClient } from '@atomicmemory/sdk';\n *\n * const memory = new MemoryClient({\n * providers: { atomicmemory: { apiUrl: 'http://localhost:17350' } },\n * });\n * await memory.initialize();\n * await memory.ingest({ mode: 'text', content: 'hello', scope: { user: 'u1' } });\n * const results = await memory.search({ query: 'hello', scope: { user: 'u1' } });\n * ```\n */\n\n// Primary client — `AtomicMemoryClient` aggregates the memory and\n// storage namespaces. `MemoryClient` remains available for\n// applications that only need memory operations.\nexport {\n AtomicMemoryClient,\n type AtomicMemoryClientConfig,\n} from './client/atomic-memory-client';\n\nexport { MemoryClient } from './client/memory-client';\nexport type {\n MemoryClientConfig,\n MemoryProviderConfigs,\n ProviderStatus,\n} from './client/memory-client';\n\n// Types\nexport * from './types';\n\n// Event system\nexport { EventEmitter, type EventMap } from './core/events';\n\n// Error handling\nexport {\n AtomicMemoryError,\n StorageError,\n EmbeddingError,\n SearchError,\n ConfigurationError,\n NetworkError,\n RetryableOperation,\n withRetry,\n ErrorContext,\n ErrorUtils,\n type RetryPolicy,\n} from './core/error-handling/';\n\n// KV cache used by embeddings and local search. New artifact-storage\n// integrations should use the `./storage` subpath.\nexport { StorageManager } from './kv-cache/storage-manager';\nexport { MemoryStorageAdapter } from './kv-cache/memory-storage';\nexport { IndexedDBStorageAdapter } from './kv-cache/indexeddb-storage';\nexport type { StorageAdapter, StorageStats } from './kv-cache/storage-adapter';\n\n// KV cache validation\nexport {\n StorageValidator,\n validateKey,\n validateValue,\n validateKeyValue,\n assertValidKey,\n assertValidValue,\n assertValidKeyValue,\n DEFAULT_VALIDATION_CONFIG,\n} from './kv-cache/validation';\nexport type { ValidationConfig, ValidationResult } from './kv-cache/validation';\n\n// Storage API for the public `client.storage` namespace.\nexport * from './storage';\n\n// Logging\nexport {\n Logger,\n getLogger,\n configureLogging,\n setLogLevel,\n logger,\n} from './utils/logger';\nexport type {\n LogLevel,\n LogContext,\n LogEntry,\n LoggerConfig,\n} from './utils/logger';\n\n// Debug logging\nexport {\n setDebugHandler,\n setDebugEnabled,\n isDebugEnabled,\n debugLog,\n debugInfo,\n debugWarn,\n debugError,\n} from './utils/debug-logger';\nexport type { DebugLogEntry, DebugLogHandler } from './utils/debug-logger';\n\n// Embedding\nexport { EmbeddingGenerator } from './embedding/embedding-generator';\nexport { TransformersAdapter } from './embedding/transformers-adapter';\nexport { WasmSemanticProcessor } from './embedding/wasm-semantic-processor';\nexport { testWebAssemblySupport } from './embedding/wasm-semantic-processor';\n\n// Search\nexport { SemanticSearch } from './search/semantic-search';\nexport { cosineSimilarity } from './search/similarity-calculator';\nexport type {\n SemanticSearchResult,\n SearchOptions,\n StoredContext,\n} from './search/semantic-search/types';\n\n// Utilities\nexport { PerformanceMonitor } from './utils/performance';\nexport { DebugTools } from './utils/debugging';\nexport * from './utils/validation';\nexport {\n getEnvironment,\n isTestEnvironment,\n isDevelopmentEnvironment,\n isExtensionEnvironment,\n} from './utils/environment';\n\n// Runtime configuration — singleton consumed by application wrappers\n// that need to initialize environment settings at SDK startup.\nexport { RuntimeConfig, runtimeConfig } from './core/runtime-config';\n\n// Memory system — types, provider interface, concrete adapters.\n// `MemoryService` is intentionally not re-exported from root; consumers\n// use `MemoryClient` (above) as the canonical API.\nexport * from './memory/types';\nexport * from './memory/errors';\nexport * from './memory/provider';\nexport * from './memory/pipeline';\nexport * from './memory/registration';\nexport * from './memory/atomicmemory-provider';\nexport * from './memory/mem0-provider';\nexport * from './memory/hindsight-provider';\n\n// Version information\nexport const SDK_VERSION = '1.0.0';\nexport const API_VERSION = '1.0';\n"]}
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etch wrapper over the entity API routes. All methods default\n * `entityType` to `'user'` since that is the primary use case.\n * Server responses use snake_case; this client maps to camelCase.\n *\n * Usage:\n * const client = new AtomicMemoryClient({ apiUrl, apiKey, userId });\n * const profile = await client.entities.profile('alice');\n * const attrs = await client.entities.attributes('alice', { attribute: 'role' });\n */\n\nimport type {\n DeleteEntityResult,\n EntityDetail,\n EntityListResult,\n EntityProfile,\n EntitySettings,\n EntityType,\n GetAttributesOptions,\n ListEntitiesOptions,\n MemoryHistory,\n MergeEntitiesResult,\n PatchEntitySettingsInput,\n} from './types.js';\n\nexport interface EntitiesClientConfig {\n apiUrl: string;\n apiKey: string;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n}\n\nexport class EntitiesClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: EntitiesClientConfig) {\n if (!config.apiUrl) throw new Error('EntitiesClient: apiUrl is required');\n if (!config.apiKey) throw new Error('EntitiesClient: apiKey is required');\n this.apiUrl = config.apiUrl.replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.fetchImpl = config.fetch ?? fetch;\n }\n\n /** Get the synthesized profile for an entity. */\n async profile(entityId: string, entityType: EntityType = 'user'): Promise<EntityProfile> {\n const res = await this.request('GET', `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/profile`);\n return mapProfile(await res.json() as Record<string, unknown>);\n }\n\n /** List all entities with memory counts (paginated). */\n async list(opts: ListEntitiesOptions = {}): Promise<EntityListResult> {\n const qs = buildEntityListQuery(opts);\n const res = await this.request('GET', `/v1/entities${qs}`);\n return mapList(await res.json() as Record<string, unknown>);\n }\n\n /** Get entity detail — attributes, relations, and recent cards. */\n async get(entityId: string, entityType: EntityType = 'user'): Promise<EntityDetail> {\n const res = await this.request('GET', `/v1/entities/${entityType}/${encodeURIComponent(entityId)}`);\n return mapDetail(await res.json() as Record<string, unknown>);\n }\n\n /** Cascade-delete all data for an entity. */\n async delete(entityId: string, entityType: EntityType = 'user'): Promise<DeleteEntityResult> {\n const res = await this.request('DELETE', `/v1/entities/${entityType}/${encodeURIComponent(entityId)}`);\n return mapDeleteResult(await res.json() as Record<string, unknown>);\n }\n\n /** Get structured attribute triples for an entity. */\n async attributes(entityId: string, opts: GetAttributesOptions = {}, entityType: EntityType = 'user') {\n const qs = buildAttributesQuery(opts);\n const res = await this.request('GET', `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/attributes${qs}`);\n const body = await res.json() as { attributes: unknown[] };\n return (body.attributes ?? []).map(mapAttribute);\n }\n\n /** Get the mutation history of a single memory record. */\n async memoryHistory(entityId: string, memoryId: string, entityType: EntityType = 'user'): Promise<MemoryHistory> {\n const res = await this.request(\n 'GET',\n `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/memories/${encodeURIComponent(memoryId)}/history`,\n );\n return mapHistory(await res.json() as Record<string, unknown>);\n }\n\n /** Update per-entity extraction guidance and pipeline config. */\n async patchSettings(entityId: string, input: PatchEntitySettingsInput, entityType: EntityType = 'user'): Promise<EntitySettings> {\n const body: Record<string, unknown> = {};\n if (input.extractionPrompt !== undefined) body.extraction_prompt = input.extractionPrompt;\n if (input.memoryKinds !== undefined) body.memory_kinds = input.memoryKinds;\n if (input.decayEnabled !== undefined) body.decay_enabled = input.decayEnabled;\n const res = await this.request(\n 'PATCH',\n `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/settings`,\n { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n );\n return mapSettings(await res.json() as Record<string, unknown>);\n }\n\n /** Merge a source entity into a target entity. */\n async merge(\n source: { entityId: string; entityType?: EntityType },\n target: { entityId: string; entityType?: EntityType },\n ): Promise<MergeEntitiesResult> {\n const body = {\n source: { entity_type: source.entityType ?? 'user', entity_id: source.entityId },\n target: { entity_type: target.entityType ?? 'user', entity_id: target.entityId },\n };\n const res = await this.request('POST', '/v1/entities/merge', {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n return mapMergeResult(await res.json() as Record<string, unknown>);\n }\n\n private async request(\n method: string,\n path: string,\n init: { headers?: Record<string, string>; body?: BodyInit } = {},\n ): Promise<Response> {\n const url = `${this.apiUrl}${path}`;\n let res: Response;\n try {\n res = await this.fetchImpl(url, {\n method,\n headers: { Authorization: `Bearer ${this.apiKey}`, ...(init.headers ?? {}) },\n body: init.body,\n });\n } catch (cause) {\n throw new Error(\n `EntitiesClient: network error calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n if (res.ok) return res;\n const text = await res.text().catch(() => '');\n throw new Error(`EntitiesClient: ${method} ${path} failed with ${res.status}: ${text}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Query builders\n// ---------------------------------------------------------------------------\n\nfunction buildEntityListQuery(opts: ListEntitiesOptions): string {\n const p = new URLSearchParams();\n if (opts.entityType) p.set('entity_type', opts.entityType);\n if (opts.page !== undefined) p.set('page', String(opts.page));\n if (opts.pageSize !== undefined) p.set('page_size', String(opts.pageSize));\n return p.toString() ? `?${p.toString()}` : '';\n}\n\nfunction buildAttributesQuery(opts: GetAttributesOptions): string {\n const p = new URLSearchParams();\n if (opts.attribute) p.set('attribute', opts.attribute);\n if (opts.entity) p.set('entity', opts.entity);\n if (opts.limit !== undefined) p.set('limit', String(opts.limit));\n return p.toString() ? `?${p.toString()}` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Wire → SDK type mappers (snake_case → camelCase)\n// ---------------------------------------------------------------------------\n\nfunction mapAttribute(r: unknown) {\n const a = r as Record<string, unknown>;\n return {\n entity: a.entity as string,\n attribute: a.attribute as string,\n value: a.value as string,\n type: a.type as string,\n sourceMemoryId: (a.source_memory_id as string | null) ?? null,\n observedAt: a.observed_at as string,\n };\n}\n\nfunction mapRelation(r: unknown) {\n const row = r as Record<string, unknown>;\n return {\n targetEntityId: row.target_entity_id as string,\n relationType: row.relation_type as string,\n confidence: row.confidence as number,\n validTo: (row.valid_to as string | null) ?? null,\n };\n}\n\nfunction mapCard(c: unknown) {\n const card = c as Record<string, unknown>;\n return {\n entityName: card.entity_name as string,\n cardText: card.card_text as string,\n version: card.version as number,\n updatedAt: card.updated_at as string,\n };\n}\n\nfunction mapProfileBody(raw: Record<string, unknown> | null): import('./types.js').EntityProfile['profile'] {\n if (!raw) return null;\n return {\n summary: raw.summary as string,\n preferences: (raw.preferences as string[]) ?? [],\n instructions: (raw.instructions as string[]) ?? [],\n openCommitments: (raw.open_commitments as string[]) ?? [],\n };\n}\n\nfunction mapProfile(r: Record<string, unknown>): import('./types.js').EntityProfile {\n return {\n entityType: r.entity_type as import('./types.js').EntityType,\n entityId: r.entity_id as string,\n profile: mapProfileBody(r.profile as Record<string, unknown> | null),\n attributes: ((r.attributes as unknown[]) ?? []).map(mapAttribute),\n memoryCount: r.memory_count as number,\n lastActive: (r.last_active as string | null) ?? null,\n updatedAt: (r.updated_at as string | null) ?? null,\n };\n}\n\nfunction mapList(r: Record<string, unknown>): import('./types.js').EntityListResult {\n return {\n entities: ((r.entities as unknown[]) ?? []).map((e) => {\n const entity = e as Record<string, unknown>;\n return {\n entityType: entity.entity_type as import('./types.js').EntityType,\n entityId: entity.entity_id as string,\n memoryCount: entity.memory_count as number,\n lastActive: (entity.last_active as string | null) ?? null,\n };\n }),\n total: r.total as number,\n page: r.page as number,\n pageSize: r.page_size as number,\n };\n}\n\nfunction mapDetail(r: Record<string, unknown>): import('./types.js').EntityDetail {\n return {\n entityType: r.entity_type as import('./types.js').EntityType,\n entityId: r.entity_id as string,\n memoryCount: r.memory_count as number,\n attributes: ((r.attributes as unknown[]) ?? []).map(mapAttribute),\n relations: ((r.relations as unknown[]) ?? []).map(mapRelation),\n recentCards: ((r.recent_cards as unknown[]) ?? []).map(mapCard),\n updatedAt: (r.updated_at as string | null) ?? null,\n };\n}\n\nfunction mapDeleteResult(r: Record<string, unknown>): import('./types.js').DeleteEntityResult {\n const d = r.deleted as Record<string, number>;\n return {\n deleted: {\n memories: d.memories,\n entityAttributes: d.entity_attributes,\n profile: d.profile,\n entities: d.entities,\n entityEdges: d.entity_edges,\n entityCards: d.entity_cards,\n },\n };\n}\n\nfunction mapHistory(r: Record<string, unknown>): import('./types.js').MemoryHistory {\n return {\n memoryId: r.memory_id as string,\n history: ((r.history as unknown[]) ?? []).map((h) => {\n const entry = h as Record<string, unknown>;\n return {\n versionId: entry.version_id as string,\n event: entry.event as string,\n content: entry.content as string,\n timestamp: entry.timestamp as string,\n supersededBy: (entry.superseded_by as string | null) ?? null,\n };\n }),\n };\n}\n\nfunction mapSettings(r: Record<string, unknown>): import('./types.js').EntitySettings {\n return {\n entityId: r.entity_id as string,\n extractionPrompt: (r.extraction_prompt as string | null) ?? null,\n memoryKinds: (r.memory_kinds as string[] | null) ?? null,\n decayEnabled: r.decay_enabled as boolean,\n updatedAt: r.updated_at as string,\n };\n}\n\nfunction mapMergeResult(r: Record<string, unknown>): import('./types.js').MergeEntitiesResult {\n const m = r.merged as Record<string, number>;\n return {\n merged: {\n memoriesMoved: m.memories_moved,\n attributesMoved: m.attributes_moved,\n cardsMoved: m.cards_moved,\n },\n targetEntityId: r.target_entity_id as string,\n };\n}\n","/**\n * @file `AtomicMemoryClient` — primary public surface for the SDK.\n *\n * Aggregates `memory` (the memory-layer API) and `storage` (the\n * direct-storage API) under one client so callers see a coherent\n * single entry point:\n *\n * import { AtomicMemoryClient } from '@atomicmemory/sdk';\n * const client = new AtomicMemoryClient({\n * apiUrl: 'http://localhost:17350',\n * apiKey: process.env.ATOMICMEMORY_API_KEY!,\n * userId: 'u1',\n * });\n * await client.memory.initialize();\n * const artifact = await client.storage.put({\n * mode: 'pointer',\n * uri: 'https://example.com/file.pdf',\n * contentType: 'application/pdf',\n * });\n *\n * v1 SDK is server-side only. Browser bundles must proxy through a\n * trusted server, such as an application-owned API boundary.\n *\n * Applications that only need memory operations can still use\n * `MemoryClient` directly. New integrations should prefer\n * `AtomicMemoryClient.memory`.\n */\n\nimport { MemoryClient, type MemoryClientConfig } from './memory-client';\nimport { ConcreteStorageClient } from '../storage/client';\nimport type { StorageClient } from '../storage/interfaces';\nimport { EntitiesClient } from '../entities/client';\n\n/**\n * Constructor config for the aggregator. All three transport fields\n * (`apiUrl`, `apiKey`, `userId`) are REQUIRED — they back both the\n * storage namespace and the default AtomicMemory memory provider.\n * Memory-only consumers should still pass `apiUrl` (it doubles as\n * the default memory provider's `apiUrl`); the `memory` block then\n * narrows the registration further if a non-default provider mix is\n * needed.\n *\n * `userId` is the owner-scope seam the storage routes accept until a\n * real auth seam ships. `fetch` is an optional override; defaults to\n * the Node global.\n */\nexport interface AtomicMemoryClientConfig {\n apiUrl: string;\n apiKey: string;\n userId: string;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n /** Memory-provider registration. Defaults to a single AtomicMemory\n * provider pointing at `apiUrl`. */\n memory?: MemoryClientConfig;\n}\n\n/**\n * Primary public client. Holds a `memory` namespace (`MemoryClient`)\n * and a `storage` namespace (`StorageClient`).\n */\nexport class AtomicMemoryClient {\n readonly memory: MemoryClient;\n readonly storage: StorageClient;\n readonly entities: EntitiesClient;\n\n constructor(config: AtomicMemoryClientConfig) {\n if (!config.apiUrl) {\n throw new Error('AtomicMemoryClient: apiUrl is required');\n }\n if (!config.apiKey) {\n throw new Error('AtomicMemoryClient: apiKey is required');\n }\n if (!config.userId) {\n throw new Error('AtomicMemoryClient: userId is required');\n }\n // Default provider registration MUST forward the apiKey so the\n // memory namespace shares the storage namespace's auth contract.\n // The earlier shape dropped it silently — memory requests went\n // out unauthenticated even when the caller supplied `apiKey`,\n // failing with 401 against any core deployment that gates `/v1/*`\n // (every deployment since the auth middleware landed).\n this.memory = new MemoryClient(\n config.memory ?? {\n providers: {\n atomicmemory: { apiUrl: config.apiUrl, apiKey: config.apiKey },\n },\n },\n );\n this.storage = new ConcreteStorageClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n userId: config.userId,\n fetch: config.fetch,\n });\n this.entities = new EntitiesClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n fetch: config.fetch,\n });\n }\n}\n","/**\n * @file @atomicmemory/sdk public surface\n *\n * Backend-agnostic memory-layer SDK. Pluggable providers, local\n * embeddings, storage adapters, semantic search.\n *\n * @example\n * ```typescript\n * import { MemoryClient } from '@atomicmemory/sdk';\n *\n * const memory = new MemoryClient({\n * providers: { atomicmemory: { apiUrl: 'http://localhost:17350' } },\n * });\n * await memory.initialize();\n * await memory.ingest({ mode: 'text', content: 'hello', scope: { user: 'u1' } });\n * const results = await memory.search({ query: 'hello', scope: { user: 'u1' } });\n * ```\n */\n\n// Primary client — `AtomicMemoryClient` aggregates the memory and\n// storage namespaces. `MemoryClient` remains available for\n// applications that only need memory operations.\nexport {\n AtomicMemoryClient,\n type AtomicMemoryClientConfig,\n} from './client/atomic-memory-client';\n\nexport { MemoryClient } from './client/memory-client';\nexport type {\n MemoryClientConfig,\n MemoryProviderConfigs,\n ProviderStatus,\n} from './client/memory-client';\n\n// Types\nexport * from './types';\n\n// Event system\nexport { EventEmitter, type EventMap } from './core/events';\n\n// Error handling\nexport {\n AtomicMemoryError,\n StorageError,\n EmbeddingError,\n SearchError,\n ConfigurationError,\n NetworkError,\n RetryableOperation,\n withRetry,\n ErrorContext,\n ErrorUtils,\n type RetryPolicy,\n} from './core/error-handling/';\n\n// KV cache used by embeddings and local search. New artifact-storage\n// integrations should use the `./storage` subpath.\nexport { StorageManager } from './kv-cache/storage-manager';\nexport { MemoryStorageAdapter } from './kv-cache/memory-storage';\nexport { IndexedDBStorageAdapter } from './kv-cache/indexeddb-storage';\nexport type { StorageAdapter, StorageStats } from './kv-cache/storage-adapter';\n\n// KV cache validation\nexport {\n StorageValidator,\n validateKey,\n validateValue,\n validateKeyValue,\n assertValidKey,\n assertValidValue,\n assertValidKeyValue,\n DEFAULT_VALIDATION_CONFIG,\n} from './kv-cache/validation';\nexport type { ValidationConfig, ValidationResult } from './kv-cache/validation';\n\n// Storage API for the public `client.storage` namespace.\nexport * from './storage';\n\n// Entity API for the public `client.entities` namespace.\nexport * from './entities';\n\n// Logging\nexport {\n Logger,\n getLogger,\n configureLogging,\n setLogLevel,\n logger,\n} from './utils/logger';\nexport type {\n LogLevel,\n LogContext,\n LogEntry,\n LoggerConfig,\n} from './utils/logger';\n\n// Debug logging\nexport {\n setDebugHandler,\n setDebugEnabled,\n isDebugEnabled,\n debugLog,\n debugInfo,\n debugWarn,\n debugError,\n} from './utils/debug-logger';\nexport type { DebugLogEntry, DebugLogHandler } from './utils/debug-logger';\n\n// Embedding\nexport { EmbeddingGenerator } from './embedding/embedding-generator';\nexport { TransformersAdapter } from './embedding/transformers-adapter';\nexport { WasmSemanticProcessor } from './embedding/wasm-semantic-processor';\nexport { testWebAssemblySupport } from './embedding/wasm-semantic-processor';\n\n// Search\nexport { SemanticSearch } from './search/semantic-search';\nexport { cosineSimilarity } from './search/similarity-calculator';\nexport type {\n SemanticSearchResult,\n SearchOptions,\n StoredContext,\n} from './search/semantic-search/types';\n\n// Utilities\nexport { PerformanceMonitor } from './utils/performance';\nexport { DebugTools } from './utils/debugging';\nexport * from './utils/validation';\nexport {\n getEnvironment,\n isTestEnvironment,\n isDevelopmentEnvironment,\n isExtensionEnvironment,\n} from './utils/environment';\n\n// Runtime configuration — singleton consumed by application wrappers\n// that need to initialize environment settings at SDK startup.\nexport { RuntimeConfig, runtimeConfig } from './core/runtime-config';\n\n// Memory system — types, provider interface, concrete adapters.\n// `MemoryService` is intentionally not re-exported from root; consumers\n// use `MemoryClient` (above) as the canonical API.\nexport * from './memory/types';\nexport * from './memory/errors';\nexport * from './memory/provider';\nexport * from './memory/capability-profiles';\nexport * from './memory/pipeline';\nexport * from './memory/registration';\nexport * from './memory/atomicmemory-provider';\nexport * from './memory/mem0-provider';\nexport * from './memory/hindsight-provider';\n\n// Version information\nexport const SDK_VERSION = '1.0.0';\nexport const API_VERSION = '1.0';\n"]}

@@ -13,5 +13,177 @@ import { MemoryClient, MemoryClientConfig } from './browser.cjs';

export { S as SearchOptions, a as SemanticSearch, b as SemanticSearchResult, c as StoredContext, f as cosineSimilarity } from './similarity-calculator-C03LitnZ.cjs';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AddContextResult, AgentConflict, AgentScope, AtomicMemoryAgents, AtomicMemoryAudit, AtomicMemoryConfig, AtomicMemoryExtensionName, AtomicMemoryHandle, AtomicMemoryHealthStatus, AtomicMemoryIngestInput, AtomicMemoryIngestResult, AtomicMemoryLessons, AtomicMemoryLifecycle, AtomicMemoryListOptions, AtomicMemoryListResultPage, AtomicMemoryMemory, AtomicMemoryProvider, AtomicMemoryProviderConfig, AtomicMemorySearchRequest, AtomicMemorySearchResult, AtomicMemorySearchResultPage, AuditTrailEntry, AuditTrailResult, AutoResolveConflictsResult, BaseMemoryProvider, BatchOps, CapCheckResult, CapRecommendation, CapStatus, Capabilities, ConfigUpdateResult, ConfigUpdates, ConflictResolution, ConflictStatus, ConflictsListResult, ConsolidationExecutionResult, ConsolidationResult, ConsolidationScanResult, ContextMetadata, ContextPackage, ContextRecord, ContextSearchOptions, ContextSearchResult, DecayResult, DocumentMetadata, EmbeddingProviderName, FieldFilter, FilterExpr, Forgetter, GetTrustResult, GraphEdge, GraphNode, GraphResult, GraphSearch, GraphSearchRequest, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, Health, HealthConfig, HealthStatus, HindsightOperation, HindsightOperationsHandle, HindsightOperationsPage, HindsightProvider, HindsightProviderConfig, HindsightRecallBudget, HindsightRetainHandle, HindsightRetainItem, HindsightRetainRequest, HindsightRetainResponse, HindsightTagsMatch, IngestBase, IngestInput, IngestResult, Insight, InvalidScopeError, LLMProviderName, Lesson, LessonSeverity, LessonStats, LessonType, LessonsListResult, ListRequest, ListResultPage, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0ContextProviderConfig, Mem0Provider, Mem0ProviderConfig, Memory, MemoryKind, MemoryProcessingPipeline, MemoryProvider, MemoryProviderEntry, MemoryProviderError, MemoryProviderRegistration, MemoryRef, MemoryScope, MemoryTransportError, MemoryVersion, Message, MessageIngest, MutationRecord, MutationSummary, MutationType, PackageRequest, Packager, Profile, Profiler, Provenance, RateLimitError, RecentMutationsResult, ReconcileStatus, ReconciliationResult, Reflector, ResetSourceResult, ResolveConflictResult, Scope, SearchRequest, SearchResult, SearchResultPage, SetTrustResult, StatsResult, TemporalSearch, TextIngest, UnsupportedOperationError, Updater, VerbatimIngest, Versioner, noopMemoryPipeline } from './memory.cjs';
export { A as ATOMICMEMORY_DEFAULT_TIMEOUT, a as ATOMICMEMORY_EXTENSION_NAMES, b as AddContextResult, c as AgentConflict, d as AgentScope, e as AtomicMemoryAgents, f as AtomicMemoryAudit, g as AtomicMemoryConfig, h as AtomicMemoryExtensionName, i as AtomicMemoryHandle, j as AtomicMemoryHealthStatus, k as AtomicMemoryIngestInput, l as AtomicMemoryIngestResult, m as AtomicMemoryLessons, n as AtomicMemoryLifecycle, o as AtomicMemoryListOptions, p as AtomicMemoryListResultPage, q as AtomicMemoryMemory, r as AtomicMemoryProvider, s as AtomicMemoryProviderConfig, t as AtomicMemorySearchRequest, u as AtomicMemorySearchResult, v as AtomicMemorySearchResultPage, w as AuditTrailEntry, x as AuditTrailResult, y as AutoResolveConflictsResult, B as BaseMemoryProvider, z as BatchOps, C as CapCheckResult, D as CapRecommendation, E as CapStatus, F as Capabilities, G as ConfigUpdateResult, H as ConfigUpdates, I as ConflictResolution, J as ConflictStatus, K as ConflictsListResult, L as ConsolidationExecutionResult, M as ConsolidationResult, N as ConsolidationScanResult, O as ContentClass, P as ContextMetadata, Q as ContextPackage, R as ContextRecord, S as ContextSearchOptions, T as ContextSearchResult, V as DecayResult, W as DocumentMetadata, X as EmbeddingProviderName, Y as FieldFilter, Z as FilterExpr, _ as Forgetter, $ as GetTrustResult, a0 as GraphEdge, a1 as GraphNode, a2 as GraphResult, a3 as GraphSearch, a4 as GraphSearchRequest, a5 as HINDSIGHT_DEFAULT_API_VERSION, a6 as HINDSIGHT_DEFAULT_MAX_TOKENS, a7 as HINDSIGHT_DEFAULT_PROJECT_ID, a8 as HINDSIGHT_DEFAULT_TIMEOUT, a9 as HINDSIGHT_SCOPE_TAGS_MATCH, aa as Health, ab as HealthConfig, ac as HealthStatus, ad as HindsightOperation, ae as HindsightOperationsHandle, af as HindsightOperationsPage, ag as HindsightProvider, ah as HindsightProviderConfig, ai as HindsightRecallBudget, aj as HindsightRetainHandle, ak as HindsightRetainItem, al as HindsightRetainRequest, am as HindsightRetainResponse, an as HindsightTagsMatch, ao as IngestBase, ap as IngestInput, aq as IngestResult, ar as Insight, as as InvalidScopeError, at as LLMProviderName, au as Lesson, av as LessonSeverity, aw as LessonStats, ax as LessonType, ay as LessonsListResult, az as ListRequest, aA as ListResultPage, aB as MEM0_DEFAULT_TIMEOUT, aC as Mem0ContextProvider, aD as Mem0ContextProviderConfig, aE as Mem0Provider, aF as Mem0ProviderConfig, aG as Memory, aH as MemoryKind, aI as MemoryProcessingPipeline, aJ as MemoryProvider, aK as MemoryProviderEntry, aL as MemoryProviderError, aM as MemoryProviderRegistration, aN as MemoryRef, aO as MemoryScope, aP as MemoryTransportError, aQ as MemoryVersion, aR as Message, aS as MessageIngest, aU as MutationRecord, aV as MutationSummary, aW as MutationType, aX as PackageRequest, aY as Packager, aZ as Profile, a_ as Profiler, a$ as Provenance, b0 as RateLimitError, b1 as RecentMutationsResult, b2 as ReconcileStatus, b3 as ReconciliationResult, b4 as Reflector, b5 as ResetSourceResult, b6 as ResolveConflictResult, b7 as RetrievalReceipt, b8 as Scope, b9 as SearchRequest, ba as SearchResult, bb as SearchResultPage, bc as SetTrustResult, bd as StatsResult, be as TemporalSearch, bf as TextIngest, bg as UnsupportedOperationError, bh as Updater, bi as VerbatimIngest, bj as Versioner, bm as noopMemoryPipeline } from './hindsight-provider-CbfXnvx7.cjs';
export { CapabilityGap, CapabilityProfile, capabilityGaps, satisfiesProfile } from './memory.cjs';
/**
* @file Public types for the AtomicMemory Entity API.
*
* All shapes mirror the wire contract from /v1/entities. Fields use
* camelCase here; the client translates from the server's snake_case.
*/
type EntityType = 'user' | 'agent' | 'session';
interface EntityAttribute {
entity: string;
attribute: string;
value: string;
type: string;
sourceMemoryId: string | null;
observedAt: string;
}
interface EntityRelation {
targetEntityId: string;
relationType: string;
confidence: number;
validTo: string | null;
}
interface EntityCard {
entityName: string;
cardText: string;
version: number;
updatedAt: string;
}
interface EntityProfileBlock {
summary: string;
preferences: string[];
instructions: string[];
openCommitments: string[];
}
interface EntityProfile {
entityType: EntityType;
entityId: string;
profile: EntityProfileBlock | null;
attributes: EntityAttribute[];
memoryCount: number;
lastActive: string | null;
updatedAt: string | null;
}
interface EntitySummary {
entityType: EntityType;
entityId: string;
memoryCount: number;
lastActive: string | null;
}
interface EntityListResult {
entities: EntitySummary[];
total: number;
page: number;
pageSize: number;
}
interface EntityDetail {
entityType: EntityType;
entityId: string;
memoryCount: number;
attributes: EntityAttribute[];
relations: EntityRelation[];
recentCards: EntityCard[];
updatedAt: string | null;
}
interface DeleteEntityResult {
deleted: {
memories: number;
entityAttributes: number;
profile: number;
entities: number;
entityEdges: number;
entityCards: number;
};
}
interface MemoryHistoryEntry {
versionId: string;
event: string;
content: string;
timestamp: string;
supersededBy: string | null;
}
interface MemoryHistory {
memoryId: string;
history: MemoryHistoryEntry[];
}
interface EntitySettings {
entityId: string;
extractionPrompt: string | null;
memoryKinds: string[] | null;
decayEnabled: boolean;
updatedAt: string;
}
interface MergeEntitiesResult {
merged: {
memoriesMoved: number;
attributesMoved: number;
cardsMoved: number;
};
targetEntityId: string;
}
interface ListEntitiesOptions {
entityType?: EntityType;
page?: number;
pageSize?: number;
}
interface GetAttributesOptions {
attribute?: string;
entity?: string;
limit?: number;
}
interface PatchEntitySettingsInput {
extractionPrompt?: string;
memoryKinds?: string[];
decayEnabled?: boolean;
}
/**
* @file `EntitiesClient` — SDK surface for /v1/entities.
*
* Thin fetch wrapper over the entity API routes. All methods default
* `entityType` to `'user'` since that is the primary use case.
* Server responses use snake_case; this client maps to camelCase.
*
* Usage:
* const client = new AtomicMemoryClient({ apiUrl, apiKey, userId });
* const profile = await client.entities.profile('alice');
* const attrs = await client.entities.attributes('alice', { attribute: 'role' });
*/
interface EntitiesClientConfig {
apiUrl: string;
apiKey: string;
/** Optional fetch override — defaults to the Node global. */
fetch?: typeof fetch;
}
declare class EntitiesClient {
private readonly apiUrl;
private readonly apiKey;
private readonly fetchImpl;
constructor(config: EntitiesClientConfig);
/** Get the synthesized profile for an entity. */
profile(entityId: string, entityType?: EntityType): Promise<EntityProfile>;
/** List all entities with memory counts (paginated). */
list(opts?: ListEntitiesOptions): Promise<EntityListResult>;
/** Get entity detail — attributes, relations, and recent cards. */
get(entityId: string, entityType?: EntityType): Promise<EntityDetail>;
/** Cascade-delete all data for an entity. */
delete(entityId: string, entityType?: EntityType): Promise<DeleteEntityResult>;
/** Get structured attribute triples for an entity. */
attributes(entityId: string, opts?: GetAttributesOptions, entityType?: EntityType): Promise<{
entity: string;
attribute: string;
value: string;
type: string;
sourceMemoryId: string | null;
observedAt: string;
}[]>;
/** Get the mutation history of a single memory record. */
memoryHistory(entityId: string, memoryId: string, entityType?: EntityType): Promise<MemoryHistory>;
/** Update per-entity extraction guidance and pipeline config. */
patchSettings(entityId: string, input: PatchEntitySettingsInput, entityType?: EntityType): Promise<EntitySettings>;
/** Merge a source entity into a target entity. */
merge(source: {
entityId: string;
entityType?: EntityType;
}, target: {
entityId: string;
entityType?: EntityType;
}): Promise<MergeEntitiesResult>;
private request;
}
/**
* @file `AtomicMemoryClient` — primary public surface for the SDK.

@@ -74,2 +246,3 @@ *

readonly storage: StorageClient;
readonly entities: EntitiesClient;
constructor(config: AtomicMemoryClientConfig);

@@ -286,2 +459,2 @@ }

export { API_VERSION, AtomicMemoryClient, type AtomicMemoryClientConfig, type DebugLogEntry, type DebugLogHandler, MemoryClient, MemoryClientConfig, RuntimeConfig, SDK_VERSION, StorageClient, debugError, debugInfo, debugLog, debugWarn, getEnvironment, isDebugEnabled, isDevelopmentEnvironment, isExtensionEnvironment, isTestEnvironment, runtimeConfig, setDebugEnabled, setDebugHandler };
export { API_VERSION, AtomicMemoryClient, type AtomicMemoryClientConfig, type DebugLogEntry, type DebugLogHandler, type DeleteEntityResult, EntitiesClient, type EntitiesClientConfig, type EntityAttribute, type EntityCard, type EntityDetail, type EntityListResult, type EntityProfile, type EntityProfileBlock, type EntityRelation, type EntitySettings, type EntitySummary, type EntityType, type GetAttributesOptions, type ListEntitiesOptions, MemoryClient, MemoryClientConfig, type MemoryHistory, type MemoryHistoryEntry, type MergeEntitiesResult, type PatchEntitySettingsInput, RuntimeConfig, SDK_VERSION, StorageClient, debugError, debugInfo, debugLog, debugWarn, getEnvironment, isDebugEnabled, isDevelopmentEnvironment, isExtensionEnvironment, isTestEnvironment, runtimeConfig, setDebugEnabled, setDebugHandler };

@@ -13,5 +13,177 @@ import { MemoryClient, MemoryClientConfig } from './browser.js';

export { S as SearchOptions, a as SemanticSearch, b as SemanticSearchResult, c as StoredContext, f as cosineSimilarity } from './similarity-calculator-Cxx4s-Gq.js';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AddContextResult, AgentConflict, AgentScope, AtomicMemoryAgents, AtomicMemoryAudit, AtomicMemoryConfig, AtomicMemoryExtensionName, AtomicMemoryHandle, AtomicMemoryHealthStatus, AtomicMemoryIngestInput, AtomicMemoryIngestResult, AtomicMemoryLessons, AtomicMemoryLifecycle, AtomicMemoryListOptions, AtomicMemoryListResultPage, AtomicMemoryMemory, AtomicMemoryProvider, AtomicMemoryProviderConfig, AtomicMemorySearchRequest, AtomicMemorySearchResult, AtomicMemorySearchResultPage, AuditTrailEntry, AuditTrailResult, AutoResolveConflictsResult, BaseMemoryProvider, BatchOps, CapCheckResult, CapRecommendation, CapStatus, Capabilities, ConfigUpdateResult, ConfigUpdates, ConflictResolution, ConflictStatus, ConflictsListResult, ConsolidationExecutionResult, ConsolidationResult, ConsolidationScanResult, ContextMetadata, ContextPackage, ContextRecord, ContextSearchOptions, ContextSearchResult, DecayResult, DocumentMetadata, EmbeddingProviderName, FieldFilter, FilterExpr, Forgetter, GetTrustResult, GraphEdge, GraphNode, GraphResult, GraphSearch, GraphSearchRequest, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, Health, HealthConfig, HealthStatus, HindsightOperation, HindsightOperationsHandle, HindsightOperationsPage, HindsightProvider, HindsightProviderConfig, HindsightRecallBudget, HindsightRetainHandle, HindsightRetainItem, HindsightRetainRequest, HindsightRetainResponse, HindsightTagsMatch, IngestBase, IngestInput, IngestResult, Insight, InvalidScopeError, LLMProviderName, Lesson, LessonSeverity, LessonStats, LessonType, LessonsListResult, ListRequest, ListResultPage, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0ContextProviderConfig, Mem0Provider, Mem0ProviderConfig, Memory, MemoryKind, MemoryProcessingPipeline, MemoryProvider, MemoryProviderEntry, MemoryProviderError, MemoryProviderRegistration, MemoryRef, MemoryScope, MemoryTransportError, MemoryVersion, Message, MessageIngest, MutationRecord, MutationSummary, MutationType, PackageRequest, Packager, Profile, Profiler, Provenance, RateLimitError, RecentMutationsResult, ReconcileStatus, ReconciliationResult, Reflector, ResetSourceResult, ResolveConflictResult, Scope, SearchRequest, SearchResult, SearchResultPage, SetTrustResult, StatsResult, TemporalSearch, TextIngest, UnsupportedOperationError, Updater, VerbatimIngest, Versioner, noopMemoryPipeline } from './memory.js';
export { A as ATOMICMEMORY_DEFAULT_TIMEOUT, a as ATOMICMEMORY_EXTENSION_NAMES, b as AddContextResult, c as AgentConflict, d as AgentScope, e as AtomicMemoryAgents, f as AtomicMemoryAudit, g as AtomicMemoryConfig, h as AtomicMemoryExtensionName, i as AtomicMemoryHandle, j as AtomicMemoryHealthStatus, k as AtomicMemoryIngestInput, l as AtomicMemoryIngestResult, m as AtomicMemoryLessons, n as AtomicMemoryLifecycle, o as AtomicMemoryListOptions, p as AtomicMemoryListResultPage, q as AtomicMemoryMemory, r as AtomicMemoryProvider, s as AtomicMemoryProviderConfig, t as AtomicMemorySearchRequest, u as AtomicMemorySearchResult, v as AtomicMemorySearchResultPage, w as AuditTrailEntry, x as AuditTrailResult, y as AutoResolveConflictsResult, B as BaseMemoryProvider, z as BatchOps, C as CapCheckResult, D as CapRecommendation, E as CapStatus, F as Capabilities, G as ConfigUpdateResult, H as ConfigUpdates, I as ConflictResolution, J as ConflictStatus, K as ConflictsListResult, L as ConsolidationExecutionResult, M as ConsolidationResult, N as ConsolidationScanResult, O as ContentClass, P as ContextMetadata, Q as ContextPackage, R as ContextRecord, S as ContextSearchOptions, T as ContextSearchResult, V as DecayResult, W as DocumentMetadata, X as EmbeddingProviderName, Y as FieldFilter, Z as FilterExpr, _ as Forgetter, $ as GetTrustResult, a0 as GraphEdge, a1 as GraphNode, a2 as GraphResult, a3 as GraphSearch, a4 as GraphSearchRequest, a5 as HINDSIGHT_DEFAULT_API_VERSION, a6 as HINDSIGHT_DEFAULT_MAX_TOKENS, a7 as HINDSIGHT_DEFAULT_PROJECT_ID, a8 as HINDSIGHT_DEFAULT_TIMEOUT, a9 as HINDSIGHT_SCOPE_TAGS_MATCH, aa as Health, ab as HealthConfig, ac as HealthStatus, ad as HindsightOperation, ae as HindsightOperationsHandle, af as HindsightOperationsPage, ag as HindsightProvider, ah as HindsightProviderConfig, ai as HindsightRecallBudget, aj as HindsightRetainHandle, ak as HindsightRetainItem, al as HindsightRetainRequest, am as HindsightRetainResponse, an as HindsightTagsMatch, ao as IngestBase, ap as IngestInput, aq as IngestResult, ar as Insight, as as InvalidScopeError, at as LLMProviderName, au as Lesson, av as LessonSeverity, aw as LessonStats, ax as LessonType, ay as LessonsListResult, az as ListRequest, aA as ListResultPage, aB as MEM0_DEFAULT_TIMEOUT, aC as Mem0ContextProvider, aD as Mem0ContextProviderConfig, aE as Mem0Provider, aF as Mem0ProviderConfig, aG as Memory, aH as MemoryKind, aI as MemoryProcessingPipeline, aJ as MemoryProvider, aK as MemoryProviderEntry, aL as MemoryProviderError, aM as MemoryProviderRegistration, aN as MemoryRef, aO as MemoryScope, aP as MemoryTransportError, aQ as MemoryVersion, aR as Message, aS as MessageIngest, aU as MutationRecord, aV as MutationSummary, aW as MutationType, aX as PackageRequest, aY as Packager, aZ as Profile, a_ as Profiler, a$ as Provenance, b0 as RateLimitError, b1 as RecentMutationsResult, b2 as ReconcileStatus, b3 as ReconciliationResult, b4 as Reflector, b5 as ResetSourceResult, b6 as ResolveConflictResult, b7 as RetrievalReceipt, b8 as Scope, b9 as SearchRequest, ba as SearchResult, bb as SearchResultPage, bc as SetTrustResult, bd as StatsResult, be as TemporalSearch, bf as TextIngest, bg as UnsupportedOperationError, bh as Updater, bi as VerbatimIngest, bj as Versioner, bm as noopMemoryPipeline } from './hindsight-provider-CbfXnvx7.js';
export { CapabilityGap, CapabilityProfile, capabilityGaps, satisfiesProfile } from './memory.js';
/**
* @file Public types for the AtomicMemory Entity API.
*
* All shapes mirror the wire contract from /v1/entities. Fields use
* camelCase here; the client translates from the server's snake_case.
*/
type EntityType = 'user' | 'agent' | 'session';
interface EntityAttribute {
entity: string;
attribute: string;
value: string;
type: string;
sourceMemoryId: string | null;
observedAt: string;
}
interface EntityRelation {
targetEntityId: string;
relationType: string;
confidence: number;
validTo: string | null;
}
interface EntityCard {
entityName: string;
cardText: string;
version: number;
updatedAt: string;
}
interface EntityProfileBlock {
summary: string;
preferences: string[];
instructions: string[];
openCommitments: string[];
}
interface EntityProfile {
entityType: EntityType;
entityId: string;
profile: EntityProfileBlock | null;
attributes: EntityAttribute[];
memoryCount: number;
lastActive: string | null;
updatedAt: string | null;
}
interface EntitySummary {
entityType: EntityType;
entityId: string;
memoryCount: number;
lastActive: string | null;
}
interface EntityListResult {
entities: EntitySummary[];
total: number;
page: number;
pageSize: number;
}
interface EntityDetail {
entityType: EntityType;
entityId: string;
memoryCount: number;
attributes: EntityAttribute[];
relations: EntityRelation[];
recentCards: EntityCard[];
updatedAt: string | null;
}
interface DeleteEntityResult {
deleted: {
memories: number;
entityAttributes: number;
profile: number;
entities: number;
entityEdges: number;
entityCards: number;
};
}
interface MemoryHistoryEntry {
versionId: string;
event: string;
content: string;
timestamp: string;
supersededBy: string | null;
}
interface MemoryHistory {
memoryId: string;
history: MemoryHistoryEntry[];
}
interface EntitySettings {
entityId: string;
extractionPrompt: string | null;
memoryKinds: string[] | null;
decayEnabled: boolean;
updatedAt: string;
}
interface MergeEntitiesResult {
merged: {
memoriesMoved: number;
attributesMoved: number;
cardsMoved: number;
};
targetEntityId: string;
}
interface ListEntitiesOptions {
entityType?: EntityType;
page?: number;
pageSize?: number;
}
interface GetAttributesOptions {
attribute?: string;
entity?: string;
limit?: number;
}
interface PatchEntitySettingsInput {
extractionPrompt?: string;
memoryKinds?: string[];
decayEnabled?: boolean;
}
/**
* @file `EntitiesClient` — SDK surface for /v1/entities.
*
* Thin fetch wrapper over the entity API routes. All methods default
* `entityType` to `'user'` since that is the primary use case.
* Server responses use snake_case; this client maps to camelCase.
*
* Usage:
* const client = new AtomicMemoryClient({ apiUrl, apiKey, userId });
* const profile = await client.entities.profile('alice');
* const attrs = await client.entities.attributes('alice', { attribute: 'role' });
*/
interface EntitiesClientConfig {
apiUrl: string;
apiKey: string;
/** Optional fetch override — defaults to the Node global. */
fetch?: typeof fetch;
}
declare class EntitiesClient {
private readonly apiUrl;
private readonly apiKey;
private readonly fetchImpl;
constructor(config: EntitiesClientConfig);
/** Get the synthesized profile for an entity. */
profile(entityId: string, entityType?: EntityType): Promise<EntityProfile>;
/** List all entities with memory counts (paginated). */
list(opts?: ListEntitiesOptions): Promise<EntityListResult>;
/** Get entity detail — attributes, relations, and recent cards. */
get(entityId: string, entityType?: EntityType): Promise<EntityDetail>;
/** Cascade-delete all data for an entity. */
delete(entityId: string, entityType?: EntityType): Promise<DeleteEntityResult>;
/** Get structured attribute triples for an entity. */
attributes(entityId: string, opts?: GetAttributesOptions, entityType?: EntityType): Promise<{
entity: string;
attribute: string;
value: string;
type: string;
sourceMemoryId: string | null;
observedAt: string;
}[]>;
/** Get the mutation history of a single memory record. */
memoryHistory(entityId: string, memoryId: string, entityType?: EntityType): Promise<MemoryHistory>;
/** Update per-entity extraction guidance and pipeline config. */
patchSettings(entityId: string, input: PatchEntitySettingsInput, entityType?: EntityType): Promise<EntitySettings>;
/** Merge a source entity into a target entity. */
merge(source: {
entityId: string;
entityType?: EntityType;
}, target: {
entityId: string;
entityType?: EntityType;
}): Promise<MergeEntitiesResult>;
private request;
}
/**
* @file `AtomicMemoryClient` — primary public surface for the SDK.

@@ -74,2 +246,3 @@ *

readonly storage: StorageClient;
readonly entities: EntitiesClient;
constructor(config: AtomicMemoryClientConfig);

@@ -286,2 +459,2 @@ }

export { API_VERSION, AtomicMemoryClient, type AtomicMemoryClientConfig, type DebugLogEntry, type DebugLogHandler, MemoryClient, MemoryClientConfig, RuntimeConfig, SDK_VERSION, StorageClient, debugError, debugInfo, debugLog, debugWarn, getEnvironment, isDebugEnabled, isDevelopmentEnvironment, isExtensionEnvironment, isTestEnvironment, runtimeConfig, setDebugEnabled, setDebugHandler };
export { API_VERSION, AtomicMemoryClient, type AtomicMemoryClientConfig, type DebugLogEntry, type DebugLogHandler, type DeleteEntityResult, EntitiesClient, type EntitiesClientConfig, type EntityAttribute, type EntityCard, type EntityDetail, type EntityListResult, type EntityProfile, type EntityProfileBlock, type EntityRelation, type EntitySettings, type EntitySummary, type EntityType, type GetAttributesOptions, type ListEntitiesOptions, MemoryClient, MemoryClientConfig, type MemoryHistory, type MemoryHistoryEntry, type MergeEntitiesResult, type PatchEntitySettingsInput, RuntimeConfig, SDK_VERSION, StorageClient, debugError, debugInfo, debugLog, debugWarn, getEnvironment, isDebugEnabled, isDevelopmentEnvironment, isExtensionEnvironment, isTestEnvironment, runtimeConfig, setDebugEnabled, setDebugHandler };

@@ -1,4 +0,5 @@

import { MemoryClient } from './chunk-265G225P.js';
export { MemoryClient } from './chunk-265G225P.js';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AtomicMemoryProvider, BaseMemoryProvider, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, HindsightProvider, InvalidScopeError, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0Provider, MemoryProviderError, MemoryTransportError, RateLimitError, UnsupportedOperationError, noopMemoryPipeline } from './chunk-YBN5Y627.js';
export { capabilityGaps, satisfiesProfile } from './chunk-4CP57UR3.js';
import { MemoryClient } from './chunk-V5K4WVX5.js';
export { MemoryClient } from './chunk-V5K4WVX5.js';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AtomicMemoryProvider, BaseMemoryProvider, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, HindsightProvider, InvalidScopeError, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0Provider, MemoryProviderError, MemoryTransportError, RateLimitError, UnsupportedOperationError, noopMemoryPipeline } from './chunk-T7PRWXW6.js';
export { DEFAULT_VALIDATION_CONFIG, IndexedDBStorageAdapter, MemoryStorageAdapter, StorageManager, StorageValidator, assertValidKey, assertValidKeyValue, assertValidValue, validateKey, validateKeyValue, validateValue } from './chunk-4H2WXRAW.js';

@@ -17,2 +18,233 @@ import { ConcreteStorageClient } from './chunk-OFIOAOM3.js';

// src/entities/client.ts
var EntitiesClient = class {
apiUrl;
apiKey;
fetchImpl;
constructor(config) {
if (!config.apiUrl) throw new Error("EntitiesClient: apiUrl is required");
if (!config.apiKey) throw new Error("EntitiesClient: apiKey is required");
this.apiUrl = config.apiUrl.replace(/\/+$/, "");
this.apiKey = config.apiKey;
this.fetchImpl = config.fetch ?? fetch;
}
/** Get the synthesized profile for an entity. */
async profile(entityId, entityType = "user") {
const res = await this.request("GET", `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/profile`);
return mapProfile(await res.json());
}
/** List all entities with memory counts (paginated). */
async list(opts = {}) {
const qs = buildEntityListQuery(opts);
const res = await this.request("GET", `/v1/entities${qs}`);
return mapList(await res.json());
}
/** Get entity detail — attributes, relations, and recent cards. */
async get(entityId, entityType = "user") {
const res = await this.request("GET", `/v1/entities/${entityType}/${encodeURIComponent(entityId)}`);
return mapDetail(await res.json());
}
/** Cascade-delete all data for an entity. */
async delete(entityId, entityType = "user") {
const res = await this.request("DELETE", `/v1/entities/${entityType}/${encodeURIComponent(entityId)}`);
return mapDeleteResult(await res.json());
}
/** Get structured attribute triples for an entity. */
async attributes(entityId, opts = {}, entityType = "user") {
const qs = buildAttributesQuery(opts);
const res = await this.request("GET", `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/attributes${qs}`);
const body = await res.json();
return (body.attributes ?? []).map(mapAttribute);
}
/** Get the mutation history of a single memory record. */
async memoryHistory(entityId, memoryId, entityType = "user") {
const res = await this.request(
"GET",
`/v1/entities/${entityType}/${encodeURIComponent(entityId)}/memories/${encodeURIComponent(memoryId)}/history`
);
return mapHistory(await res.json());
}
/** Update per-entity extraction guidance and pipeline config. */
async patchSettings(entityId, input, entityType = "user") {
const body = {};
if (input.extractionPrompt !== void 0) body.extraction_prompt = input.extractionPrompt;
if (input.memoryKinds !== void 0) body.memory_kinds = input.memoryKinds;
if (input.decayEnabled !== void 0) body.decay_enabled = input.decayEnabled;
const res = await this.request(
"PATCH",
`/v1/entities/${entityType}/${encodeURIComponent(entityId)}/settings`,
{ headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }
);
return mapSettings(await res.json());
}
/** Merge a source entity into a target entity. */
async merge(source, target) {
const body = {
source: { entity_type: source.entityType ?? "user", entity_id: source.entityId },
target: { entity_type: target.entityType ?? "user", entity_id: target.entityId }
};
const res = await this.request("POST", "/v1/entities/merge", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
return mapMergeResult(await res.json());
}
async request(method, path, init = {}) {
const url = `${this.apiUrl}${path}`;
let res;
try {
res = await this.fetchImpl(url, {
method,
headers: { Authorization: `Bearer ${this.apiKey}`, ...init.headers ?? {} },
body: init.body
});
} catch (cause) {
throw new Error(
`EntitiesClient: network error calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`
);
}
if (res.ok) return res;
const text = await res.text().catch(() => "");
throw new Error(`EntitiesClient: ${method} ${path} failed with ${res.status}: ${text}`);
}
};
function buildEntityListQuery(opts) {
const p = new URLSearchParams();
if (opts.entityType) p.set("entity_type", opts.entityType);
if (opts.page !== void 0) p.set("page", String(opts.page));
if (opts.pageSize !== void 0) p.set("page_size", String(opts.pageSize));
return p.toString() ? `?${p.toString()}` : "";
}
function buildAttributesQuery(opts) {
const p = new URLSearchParams();
if (opts.attribute) p.set("attribute", opts.attribute);
if (opts.entity) p.set("entity", opts.entity);
if (opts.limit !== void 0) p.set("limit", String(opts.limit));
return p.toString() ? `?${p.toString()}` : "";
}
function mapAttribute(r) {
const a = r;
return {
entity: a.entity,
attribute: a.attribute,
value: a.value,
type: a.type,
sourceMemoryId: a.source_memory_id ?? null,
observedAt: a.observed_at
};
}
function mapRelation(r) {
const row = r;
return {
targetEntityId: row.target_entity_id,
relationType: row.relation_type,
confidence: row.confidence,
validTo: row.valid_to ?? null
};
}
function mapCard(c) {
const card = c;
return {
entityName: card.entity_name,
cardText: card.card_text,
version: card.version,
updatedAt: card.updated_at
};
}
function mapProfileBody(raw) {
if (!raw) return null;
return {
summary: raw.summary,
preferences: raw.preferences ?? [],
instructions: raw.instructions ?? [],
openCommitments: raw.open_commitments ?? []
};
}
function mapProfile(r) {
return {
entityType: r.entity_type,
entityId: r.entity_id,
profile: mapProfileBody(r.profile),
attributes: (r.attributes ?? []).map(mapAttribute),
memoryCount: r.memory_count,
lastActive: r.last_active ?? null,
updatedAt: r.updated_at ?? null
};
}
function mapList(r) {
return {
entities: (r.entities ?? []).map((e) => {
const entity = e;
return {
entityType: entity.entity_type,
entityId: entity.entity_id,
memoryCount: entity.memory_count,
lastActive: entity.last_active ?? null
};
}),
total: r.total,
page: r.page,
pageSize: r.page_size
};
}
function mapDetail(r) {
return {
entityType: r.entity_type,
entityId: r.entity_id,
memoryCount: r.memory_count,
attributes: (r.attributes ?? []).map(mapAttribute),
relations: (r.relations ?? []).map(mapRelation),
recentCards: (r.recent_cards ?? []).map(mapCard),
updatedAt: r.updated_at ?? null
};
}
function mapDeleteResult(r) {
const d = r.deleted;
return {
deleted: {
memories: d.memories,
entityAttributes: d.entity_attributes,
profile: d.profile,
entities: d.entities,
entityEdges: d.entity_edges,
entityCards: d.entity_cards
}
};
}
function mapHistory(r) {
return {
memoryId: r.memory_id,
history: (r.history ?? []).map((h) => {
const entry = h;
return {
versionId: entry.version_id,
event: entry.event,
content: entry.content,
timestamp: entry.timestamp,
supersededBy: entry.superseded_by ?? null
};
})
};
}
function mapSettings(r) {
return {
entityId: r.entity_id,
extractionPrompt: r.extraction_prompt ?? null,
memoryKinds: r.memory_kinds ?? null,
decayEnabled: r.decay_enabled,
updatedAt: r.updated_at
};
}
function mapMergeResult(r) {
const m = r.merged;
return {
merged: {
memoriesMoved: m.memories_moved,
attributesMoved: m.attributes_moved,
cardsMoved: m.cards_moved
},
targetEntityId: r.target_entity_id
};
}
// src/client/atomic-memory-client.ts

@@ -22,2 +254,3 @@ var AtomicMemoryClient = class {

storage;
entities;
constructor(config) {

@@ -46,2 +279,7 @@ if (!config.apiUrl) {

});
this.entities = new EntitiesClient({
apiUrl: config.apiUrl,
apiKey: config.apiKey,
fetch: config.fetch
});
}

@@ -54,4 +292,4 @@ };

export { API_VERSION, AtomicMemoryClient, SDK_VERSION };
export { API_VERSION, AtomicMemoryClient, EntitiesClient, SDK_VERSION };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/client/atomic-memory-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA4DO,IAAM,qBAAN,MAAyB;AAAA,EACrB,MAAA;AAAA,EACA,OAAA;AAAA,EAET,YAAY,MAAA,EAAkC;AAC5C,IAAA,IAAI,CAAC,OAAO,MAAA,EAAQ;AAClB,MAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,IAC1D;AACA,IAAA,IAAI,CAAC,OAAO,MAAA,EAAQ;AAClB,MAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,IAC1D;AACA,IAAA,IAAI,CAAC,OAAO,MAAA,EAAQ;AAClB,MAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,IAC1D;AAOA,IAAA,IAAA,CAAK,SAAS,IAAI,YAAA;AAAA,MAChB,OAAO,MAAA,IAAU;AAAA,QACf,SAAA,EAAW;AAAA,UACT,cAAc,EAAE,MAAA,EAAQ,OAAO,MAAA,EAAQ,MAAA,EAAQ,OAAO,MAAA;AAAO;AAC/D;AACF,KACF;AACA,IAAA,IAAA,CAAK,OAAA,GAAU,IAAI,qBAAA,CAAsB;AAAA,MACvC,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,OAAO,MAAA,CAAO;AAAA,KACf,CAAA;AAAA,EACH;AACF;;;ACsDO,IAAM,WAAA,GAAc;AACpB,IAAM,WAAA,GAAc","file":"index.js","sourcesContent":["/**\n * @file `AtomicMemoryClient` — primary public surface for the SDK.\n *\n * Aggregates `memory` (the memory-layer API) and `storage` (the\n * direct-storage API) under one client so callers see a coherent\n * single entry point:\n *\n * import { AtomicMemoryClient } from '@atomicmemory/sdk';\n * const client = new AtomicMemoryClient({\n * apiUrl: 'http://localhost:17350',\n * apiKey: process.env.ATOMICMEMORY_API_KEY!,\n * userId: 'u1',\n * });\n * await client.memory.initialize();\n * const artifact = await client.storage.put({\n * mode: 'pointer',\n * uri: 'https://example.com/file.pdf',\n * contentType: 'application/pdf',\n * });\n *\n * v1 SDK is server-side only. Browser bundles must proxy through a\n * trusted server, such as an application-owned API boundary.\n *\n * Applications that only need memory operations can still use\n * `MemoryClient` directly. New integrations should prefer\n * `AtomicMemoryClient.memory`.\n */\n\nimport { MemoryClient, type MemoryClientConfig } from './memory-client';\nimport { ConcreteStorageClient } from '../storage/client';\nimport type { StorageClient } from '../storage/interfaces';\n\n/**\n * Constructor config for the aggregator. All three transport fields\n * (`apiUrl`, `apiKey`, `userId`) are REQUIRED — they back both the\n * storage namespace and the default AtomicMemory memory provider.\n * Memory-only consumers should still pass `apiUrl` (it doubles as\n * the default memory provider's `apiUrl`); the `memory` block then\n * narrows the registration further if a non-default provider mix is\n * needed.\n *\n * `userId` is the owner-scope seam the storage routes accept until a\n * real auth seam ships. `fetch` is an optional override; defaults to\n * the Node global.\n */\nexport interface AtomicMemoryClientConfig {\n apiUrl: string;\n apiKey: string;\n userId: string;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n /** Memory-provider registration. Defaults to a single AtomicMemory\n * provider pointing at `apiUrl`. */\n memory?: MemoryClientConfig;\n}\n\n/**\n * Primary public client. Holds a `memory` namespace (`MemoryClient`)\n * and a `storage` namespace (`StorageClient`).\n */\nexport class AtomicMemoryClient {\n readonly memory: MemoryClient;\n readonly storage: StorageClient;\n\n constructor(config: AtomicMemoryClientConfig) {\n if (!config.apiUrl) {\n throw new Error('AtomicMemoryClient: apiUrl is required');\n }\n if (!config.apiKey) {\n throw new Error('AtomicMemoryClient: apiKey is required');\n }\n if (!config.userId) {\n throw new Error('AtomicMemoryClient: userId is required');\n }\n // Default provider registration MUST forward the apiKey so the\n // memory namespace shares the storage namespace's auth contract.\n // The earlier shape dropped it silently — memory requests went\n // out unauthenticated even when the caller supplied `apiKey`,\n // failing with 401 against any core deployment that gates `/v1/*`\n // (every deployment since the auth middleware landed).\n this.memory = new MemoryClient(\n config.memory ?? {\n providers: {\n atomicmemory: { apiUrl: config.apiUrl, apiKey: config.apiKey },\n },\n },\n );\n this.storage = new ConcreteStorageClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n userId: config.userId,\n fetch: config.fetch,\n });\n }\n}\n","/**\n * @file @atomicmemory/sdk public surface\n *\n * Backend-agnostic memory-layer SDK. Pluggable providers, local\n * embeddings, storage adapters, semantic search.\n *\n * @example\n * ```typescript\n * import { MemoryClient } from '@atomicmemory/sdk';\n *\n * const memory = new MemoryClient({\n * providers: { atomicmemory: { apiUrl: 'http://localhost:17350' } },\n * });\n * await memory.initialize();\n * await memory.ingest({ mode: 'text', content: 'hello', scope: { user: 'u1' } });\n * const results = await memory.search({ query: 'hello', scope: { user: 'u1' } });\n * ```\n */\n\n// Primary client — `AtomicMemoryClient` aggregates the memory and\n// storage namespaces. `MemoryClient` remains available for\n// applications that only need memory operations.\nexport {\n AtomicMemoryClient,\n type AtomicMemoryClientConfig,\n} from './client/atomic-memory-client';\n\nexport { MemoryClient } from './client/memory-client';\nexport type {\n MemoryClientConfig,\n MemoryProviderConfigs,\n ProviderStatus,\n} from './client/memory-client';\n\n// Types\nexport * from './types';\n\n// Event system\nexport { EventEmitter, type EventMap } from './core/events';\n\n// Error handling\nexport {\n AtomicMemoryError,\n StorageError,\n EmbeddingError,\n SearchError,\n ConfigurationError,\n NetworkError,\n RetryableOperation,\n withRetry,\n ErrorContext,\n ErrorUtils,\n type RetryPolicy,\n} from './core/error-handling/';\n\n// KV cache used by embeddings and local search. New artifact-storage\n// integrations should use the `./storage` subpath.\nexport { StorageManager } from './kv-cache/storage-manager';\nexport { MemoryStorageAdapter } from './kv-cache/memory-storage';\nexport { IndexedDBStorageAdapter } from './kv-cache/indexeddb-storage';\nexport type { StorageAdapter, StorageStats } from './kv-cache/storage-adapter';\n\n// KV cache validation\nexport {\n StorageValidator,\n validateKey,\n validateValue,\n validateKeyValue,\n assertValidKey,\n assertValidValue,\n assertValidKeyValue,\n DEFAULT_VALIDATION_CONFIG,\n} from './kv-cache/validation';\nexport type { ValidationConfig, ValidationResult } from './kv-cache/validation';\n\n// Storage API for the public `client.storage` namespace.\nexport * from './storage';\n\n// Logging\nexport {\n Logger,\n getLogger,\n configureLogging,\n setLogLevel,\n logger,\n} from './utils/logger';\nexport type {\n LogLevel,\n LogContext,\n LogEntry,\n LoggerConfig,\n} from './utils/logger';\n\n// Debug logging\nexport {\n setDebugHandler,\n setDebugEnabled,\n isDebugEnabled,\n debugLog,\n debugInfo,\n debugWarn,\n debugError,\n} from './utils/debug-logger';\nexport type { DebugLogEntry, DebugLogHandler } from './utils/debug-logger';\n\n// Embedding\nexport { EmbeddingGenerator } from './embedding/embedding-generator';\nexport { TransformersAdapter } from './embedding/transformers-adapter';\nexport { WasmSemanticProcessor } from './embedding/wasm-semantic-processor';\nexport { testWebAssemblySupport } from './embedding/wasm-semantic-processor';\n\n// Search\nexport { SemanticSearch } from './search/semantic-search';\nexport { cosineSimilarity } from './search/similarity-calculator';\nexport type {\n SemanticSearchResult,\n SearchOptions,\n StoredContext,\n} from './search/semantic-search/types';\n\n// Utilities\nexport { PerformanceMonitor } from './utils/performance';\nexport { DebugTools } from './utils/debugging';\nexport * from './utils/validation';\nexport {\n getEnvironment,\n isTestEnvironment,\n isDevelopmentEnvironment,\n isExtensionEnvironment,\n} from './utils/environment';\n\n// Runtime configuration — singleton consumed by application wrappers\n// that need to initialize environment settings at SDK startup.\nexport { RuntimeConfig, runtimeConfig } from './core/runtime-config';\n\n// Memory system — types, provider interface, concrete adapters.\n// `MemoryService` is intentionally not re-exported from root; consumers\n// use `MemoryClient` (above) as the canonical API.\nexport * from './memory/types';\nexport * from './memory/errors';\nexport * from './memory/provider';\nexport * from './memory/pipeline';\nexport * from './memory/registration';\nexport * from './memory/atomicmemory-provider';\nexport * from './memory/mem0-provider';\nexport * from './memory/hindsight-provider';\n\n// Version information\nexport const SDK_VERSION = '1.0.0';\nexport const API_VERSION = '1.0';\n"]}
{"version":3,"sources":["../src/entities/client.ts","../src/client/atomic-memory-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAkCO,IAAM,iBAAN,MAAqB;AAAA,EACT,MAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EAEjB,YAAY,MAAA,EAA8B;AACxC,IAAA,IAAI,CAAC,MAAA,CAAO,MAAA,EAAQ,MAAM,IAAI,MAAM,oCAAoC,CAAA;AACxE,IAAA,IAAI,CAAC,MAAA,CAAO,MAAA,EAAQ,MAAM,IAAI,MAAM,oCAAoC,CAAA;AACxE,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA,CAAO,MAAA,CAAO,OAAA,CAAQ,QAAQ,EAAE,CAAA;AAC9C,IAAA,IAAA,CAAK,SAAS,MAAA,CAAO,MAAA;AACrB,IAAA,IAAA,CAAK,SAAA,GAAY,OAAO,KAAA,IAAS,KAAA;AAAA,EACnC;AAAA;AAAA,EAGA,MAAM,OAAA,CAAQ,QAAA,EAAkB,UAAA,GAAyB,MAAA,EAAgC;AACvF,IAAA,MAAM,GAAA,GAAM,MAAM,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,CAAA,aAAA,EAAgB,UAAU,CAAA,CAAA,EAAI,kBAAA,CAAmB,QAAQ,CAAC,CAAA,QAAA,CAAU,CAAA;AAC1G,IAAA,OAAO,UAAA,CAAW,MAAM,GAAA,CAAI,IAAA,EAAiC,CAAA;AAAA,EAC/D;AAAA;AAAA,EAGA,MAAM,IAAA,CAAK,IAAA,GAA4B,EAA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jC,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,OAAO,MAAA,CAAO;AAAA,KACf,CAAA;AAAA,EACH;AACF;;;ACmDO,IAAM,WAAA,GAAc;AACpB,IAAM,WAAA,GAAc","file":"index.js","sourcesContent":["/**\n * @file `EntitiesClient` — SDK surface for /v1/entities.\n *\n * Thin fetch wrapper over the entity API routes. All methods default\n * `entityType` to `'user'` since that is the primary use case.\n * Server responses use snake_case; this client maps to camelCase.\n *\n * Usage:\n * const client = new AtomicMemoryClient({ apiUrl, apiKey, userId });\n * const profile = await client.entities.profile('alice');\n * const attrs = await client.entities.attributes('alice', { attribute: 'role' });\n */\n\nimport type {\n DeleteEntityResult,\n EntityDetail,\n EntityListResult,\n EntityProfile,\n EntitySettings,\n EntityType,\n GetAttributesOptions,\n ListEntitiesOptions,\n MemoryHistory,\n MergeEntitiesResult,\n PatchEntitySettingsInput,\n} from './types.js';\n\nexport interface EntitiesClientConfig {\n apiUrl: string;\n apiKey: string;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n}\n\nexport class EntitiesClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: EntitiesClientConfig) {\n if (!config.apiUrl) throw new Error('EntitiesClient: apiUrl is required');\n if (!config.apiKey) throw new Error('EntitiesClient: apiKey is required');\n this.apiUrl = config.apiUrl.replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.fetchImpl = config.fetch ?? fetch;\n }\n\n /** Get the synthesized profile for an entity. */\n async profile(entityId: string, entityType: EntityType = 'user'): Promise<EntityProfile> {\n const res = await this.request('GET', `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/profile`);\n return mapProfile(await res.json() as Record<string, unknown>);\n }\n\n /** List all entities with memory counts (paginated). */\n async list(opts: ListEntitiesOptions = {}): Promise<EntityListResult> {\n const qs = buildEntityListQuery(opts);\n const res = await this.request('GET', `/v1/entities${qs}`);\n return mapList(await res.json() as Record<string, unknown>);\n }\n\n /** Get entity detail — attributes, relations, and recent cards. */\n async get(entityId: string, entityType: EntityType = 'user'): Promise<EntityDetail> {\n const res = await this.request('GET', `/v1/entities/${entityType}/${encodeURIComponent(entityId)}`);\n return mapDetail(await res.json() as Record<string, unknown>);\n }\n\n /** Cascade-delete all data for an entity. */\n async delete(entityId: string, entityType: EntityType = 'user'): Promise<DeleteEntityResult> {\n const res = await this.request('DELETE', `/v1/entities/${entityType}/${encodeURIComponent(entityId)}`);\n return mapDeleteResult(await res.json() as Record<string, unknown>);\n }\n\n /** Get structured attribute triples for an entity. */\n async attributes(entityId: string, opts: GetAttributesOptions = {}, entityType: EntityType = 'user') {\n const qs = buildAttributesQuery(opts);\n const res = await this.request('GET', `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/attributes${qs}`);\n const body = await res.json() as { attributes: unknown[] };\n return (body.attributes ?? []).map(mapAttribute);\n }\n\n /** Get the mutation history of a single memory record. */\n async memoryHistory(entityId: string, memoryId: string, entityType: EntityType = 'user'): Promise<MemoryHistory> {\n const res = await this.request(\n 'GET',\n `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/memories/${encodeURIComponent(memoryId)}/history`,\n );\n return mapHistory(await res.json() as Record<string, unknown>);\n }\n\n /** Update per-entity extraction guidance and pipeline config. */\n async patchSettings(entityId: string, input: PatchEntitySettingsInput, entityType: EntityType = 'user'): Promise<EntitySettings> {\n const body: Record<string, unknown> = {};\n if (input.extractionPrompt !== undefined) body.extraction_prompt = input.extractionPrompt;\n if (input.memoryKinds !== undefined) body.memory_kinds = input.memoryKinds;\n if (input.decayEnabled !== undefined) body.decay_enabled = input.decayEnabled;\n const res = await this.request(\n 'PATCH',\n `/v1/entities/${entityType}/${encodeURIComponent(entityId)}/settings`,\n { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) },\n );\n return mapSettings(await res.json() as Record<string, unknown>);\n }\n\n /** Merge a source entity into a target entity. */\n async merge(\n source: { entityId: string; entityType?: EntityType },\n target: { entityId: string; entityType?: EntityType },\n ): Promise<MergeEntitiesResult> {\n const body = {\n source: { entity_type: source.entityType ?? 'user', entity_id: source.entityId },\n target: { entity_type: target.entityType ?? 'user', entity_id: target.entityId },\n };\n const res = await this.request('POST', '/v1/entities/merge', {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n return mapMergeResult(await res.json() as Record<string, unknown>);\n }\n\n private async request(\n method: string,\n path: string,\n init: { headers?: Record<string, string>; body?: BodyInit } = {},\n ): Promise<Response> {\n const url = `${this.apiUrl}${path}`;\n let res: Response;\n try {\n res = await this.fetchImpl(url, {\n method,\n headers: { Authorization: `Bearer ${this.apiKey}`, ...(init.headers ?? {}) },\n body: init.body,\n });\n } catch (cause) {\n throw new Error(\n `EntitiesClient: network error calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n }\n if (res.ok) return res;\n const text = await res.text().catch(() => '');\n throw new Error(`EntitiesClient: ${method} ${path} failed with ${res.status}: ${text}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Query builders\n// ---------------------------------------------------------------------------\n\nfunction buildEntityListQuery(opts: ListEntitiesOptions): string {\n const p = new URLSearchParams();\n if (opts.entityType) p.set('entity_type', opts.entityType);\n if (opts.page !== undefined) p.set('page', String(opts.page));\n if (opts.pageSize !== undefined) p.set('page_size', String(opts.pageSize));\n return p.toString() ? `?${p.toString()}` : '';\n}\n\nfunction buildAttributesQuery(opts: GetAttributesOptions): string {\n const p = new URLSearchParams();\n if (opts.attribute) p.set('attribute', opts.attribute);\n if (opts.entity) p.set('entity', opts.entity);\n if (opts.limit !== undefined) p.set('limit', String(opts.limit));\n return p.toString() ? `?${p.toString()}` : '';\n}\n\n// ---------------------------------------------------------------------------\n// Wire → SDK type mappers (snake_case → camelCase)\n// ---------------------------------------------------------------------------\n\nfunction mapAttribute(r: unknown) {\n const a = r as Record<string, unknown>;\n return {\n entity: a.entity as string,\n attribute: a.attribute as string,\n value: a.value as string,\n type: a.type as string,\n sourceMemoryId: (a.source_memory_id as string | null) ?? null,\n observedAt: a.observed_at as string,\n };\n}\n\nfunction mapRelation(r: unknown) {\n const row = r as Record<string, unknown>;\n return {\n targetEntityId: row.target_entity_id as string,\n relationType: row.relation_type as string,\n confidence: row.confidence as number,\n validTo: (row.valid_to as string | null) ?? null,\n };\n}\n\nfunction mapCard(c: unknown) {\n const card = c as Record<string, unknown>;\n return {\n entityName: card.entity_name as string,\n cardText: card.card_text as string,\n version: card.version as number,\n updatedAt: card.updated_at as string,\n };\n}\n\nfunction mapProfileBody(raw: Record<string, unknown> | null): import('./types.js').EntityProfile['profile'] {\n if (!raw) return null;\n return {\n summary: raw.summary as string,\n preferences: (raw.preferences as string[]) ?? [],\n instructions: (raw.instructions as string[]) ?? [],\n openCommitments: (raw.open_commitments as string[]) ?? [],\n };\n}\n\nfunction mapProfile(r: Record<string, unknown>): import('./types.js').EntityProfile {\n return {\n entityType: r.entity_type as import('./types.js').EntityType,\n entityId: r.entity_id as string,\n profile: mapProfileBody(r.profile as Record<string, unknown> | null),\n attributes: ((r.attributes as unknown[]) ?? []).map(mapAttribute),\n memoryCount: r.memory_count as number,\n lastActive: (r.last_active as string | null) ?? null,\n updatedAt: (r.updated_at as string | null) ?? null,\n };\n}\n\nfunction mapList(r: Record<string, unknown>): import('./types.js').EntityListResult {\n return {\n entities: ((r.entities as unknown[]) ?? []).map((e) => {\n const entity = e as Record<string, unknown>;\n return {\n entityType: entity.entity_type as import('./types.js').EntityType,\n entityId: entity.entity_id as string,\n memoryCount: entity.memory_count as number,\n lastActive: (entity.last_active as string | null) ?? null,\n };\n }),\n total: r.total as number,\n page: r.page as number,\n pageSize: r.page_size as number,\n };\n}\n\nfunction mapDetail(r: Record<string, unknown>): import('./types.js').EntityDetail {\n return {\n entityType: r.entity_type as import('./types.js').EntityType,\n entityId: r.entity_id as string,\n memoryCount: r.memory_count as number,\n attributes: ((r.attributes as unknown[]) ?? []).map(mapAttribute),\n relations: ((r.relations as unknown[]) ?? []).map(mapRelation),\n recentCards: ((r.recent_cards as unknown[]) ?? []).map(mapCard),\n updatedAt: (r.updated_at as string | null) ?? null,\n };\n}\n\nfunction mapDeleteResult(r: Record<string, unknown>): import('./types.js').DeleteEntityResult {\n const d = r.deleted as Record<string, number>;\n return {\n deleted: {\n memories: d.memories,\n entityAttributes: d.entity_attributes,\n profile: d.profile,\n entities: d.entities,\n entityEdges: d.entity_edges,\n entityCards: d.entity_cards,\n },\n };\n}\n\nfunction mapHistory(r: Record<string, unknown>): import('./types.js').MemoryHistory {\n return {\n memoryId: r.memory_id as string,\n history: ((r.history as unknown[]) ?? []).map((h) => {\n const entry = h as Record<string, unknown>;\n return {\n versionId: entry.version_id as string,\n event: entry.event as string,\n content: entry.content as string,\n timestamp: entry.timestamp as string,\n supersededBy: (entry.superseded_by as string | null) ?? null,\n };\n }),\n };\n}\n\nfunction mapSettings(r: Record<string, unknown>): import('./types.js').EntitySettings {\n return {\n entityId: r.entity_id as string,\n extractionPrompt: (r.extraction_prompt as string | null) ?? null,\n memoryKinds: (r.memory_kinds as string[] | null) ?? null,\n decayEnabled: r.decay_enabled as boolean,\n updatedAt: r.updated_at as string,\n };\n}\n\nfunction mapMergeResult(r: Record<string, unknown>): import('./types.js').MergeEntitiesResult {\n const m = r.merged as Record<string, number>;\n return {\n merged: {\n memoriesMoved: m.memories_moved,\n attributesMoved: m.attributes_moved,\n cardsMoved: m.cards_moved,\n },\n targetEntityId: r.target_entity_id as string,\n };\n}\n","/**\n * @file `AtomicMemoryClient` — primary public surface for the SDK.\n *\n * Aggregates `memory` (the memory-layer API) and `storage` (the\n * direct-storage API) under one client so callers see a coherent\n * single entry point:\n *\n * import { AtomicMemoryClient } from '@atomicmemory/sdk';\n * const client = new AtomicMemoryClient({\n * apiUrl: 'http://localhost:17350',\n * apiKey: process.env.ATOMICMEMORY_API_KEY!,\n * userId: 'u1',\n * });\n * await client.memory.initialize();\n * const artifact = await client.storage.put({\n * mode: 'pointer',\n * uri: 'https://example.com/file.pdf',\n * contentType: 'application/pdf',\n * });\n *\n * v1 SDK is server-side only. Browser bundles must proxy through a\n * trusted server, such as an application-owned API boundary.\n *\n * Applications that only need memory operations can still use\n * `MemoryClient` directly. New integrations should prefer\n * `AtomicMemoryClient.memory`.\n */\n\nimport { MemoryClient, type MemoryClientConfig } from './memory-client';\nimport { ConcreteStorageClient } from '../storage/client';\nimport type { StorageClient } from '../storage/interfaces';\nimport { EntitiesClient } from '../entities/client';\n\n/**\n * Constructor config for the aggregator. All three transport fields\n * (`apiUrl`, `apiKey`, `userId`) are REQUIRED — they back both the\n * storage namespace and the default AtomicMemory memory provider.\n * Memory-only consumers should still pass `apiUrl` (it doubles as\n * the default memory provider's `apiUrl`); the `memory` block then\n * narrows the registration further if a non-default provider mix is\n * needed.\n *\n * `userId` is the owner-scope seam the storage routes accept until a\n * real auth seam ships. `fetch` is an optional override; defaults to\n * the Node global.\n */\nexport interface AtomicMemoryClientConfig {\n apiUrl: string;\n apiKey: string;\n userId: string;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n /** Memory-provider registration. Defaults to a single AtomicMemory\n * provider pointing at `apiUrl`. */\n memory?: MemoryClientConfig;\n}\n\n/**\n * Primary public client. Holds a `memory` namespace (`MemoryClient`)\n * and a `storage` namespace (`StorageClient`).\n */\nexport class AtomicMemoryClient {\n readonly memory: MemoryClient;\n readonly storage: StorageClient;\n readonly entities: EntitiesClient;\n\n constructor(config: AtomicMemoryClientConfig) {\n if (!config.apiUrl) {\n throw new Error('AtomicMemoryClient: apiUrl is required');\n }\n if (!config.apiKey) {\n throw new Error('AtomicMemoryClient: apiKey is required');\n }\n if (!config.userId) {\n throw new Error('AtomicMemoryClient: userId is required');\n }\n // Default provider registration MUST forward the apiKey so the\n // memory namespace shares the storage namespace's auth contract.\n // The earlier shape dropped it silently — memory requests went\n // out unauthenticated even when the caller supplied `apiKey`,\n // failing with 401 against any core deployment that gates `/v1/*`\n // (every deployment since the auth middleware landed).\n this.memory = new MemoryClient(\n config.memory ?? {\n providers: {\n atomicmemory: { apiUrl: config.apiUrl, apiKey: config.apiKey },\n },\n },\n );\n this.storage = new ConcreteStorageClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n userId: config.userId,\n fetch: config.fetch,\n });\n this.entities = new EntitiesClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n fetch: config.fetch,\n });\n }\n}\n","/**\n * @file @atomicmemory/sdk public surface\n *\n * Backend-agnostic memory-layer SDK. Pluggable providers, local\n * embeddings, storage adapters, semantic search.\n *\n * @example\n * ```typescript\n * import { MemoryClient } from '@atomicmemory/sdk';\n *\n * const memory = new MemoryClient({\n * providers: { atomicmemory: { apiUrl: 'http://localhost:17350' } },\n * });\n * await memory.initialize();\n * await memory.ingest({ mode: 'text', content: 'hello', scope: { user: 'u1' } });\n * const results = await memory.search({ query: 'hello', scope: { user: 'u1' } });\n * ```\n */\n\n// Primary client — `AtomicMemoryClient` aggregates the memory and\n// storage namespaces. `MemoryClient` remains available for\n// applications that only need memory operations.\nexport {\n AtomicMemoryClient,\n type AtomicMemoryClientConfig,\n} from './client/atomic-memory-client';\n\nexport { MemoryClient } from './client/memory-client';\nexport type {\n MemoryClientConfig,\n MemoryProviderConfigs,\n ProviderStatus,\n} from './client/memory-client';\n\n// Types\nexport * from './types';\n\n// Event system\nexport { EventEmitter, type EventMap } from './core/events';\n\n// Error handling\nexport {\n AtomicMemoryError,\n StorageError,\n EmbeddingError,\n SearchError,\n ConfigurationError,\n NetworkError,\n RetryableOperation,\n withRetry,\n ErrorContext,\n ErrorUtils,\n type RetryPolicy,\n} from './core/error-handling/';\n\n// KV cache used by embeddings and local search. New artifact-storage\n// integrations should use the `./storage` subpath.\nexport { StorageManager } from './kv-cache/storage-manager';\nexport { MemoryStorageAdapter } from './kv-cache/memory-storage';\nexport { IndexedDBStorageAdapter } from './kv-cache/indexeddb-storage';\nexport type { StorageAdapter, StorageStats } from './kv-cache/storage-adapter';\n\n// KV cache validation\nexport {\n StorageValidator,\n validateKey,\n validateValue,\n validateKeyValue,\n assertValidKey,\n assertValidValue,\n assertValidKeyValue,\n DEFAULT_VALIDATION_CONFIG,\n} from './kv-cache/validation';\nexport type { ValidationConfig, ValidationResult } from './kv-cache/validation';\n\n// Storage API for the public `client.storage` namespace.\nexport * from './storage';\n\n// Entity API for the public `client.entities` namespace.\nexport * from './entities';\n\n// Logging\nexport {\n Logger,\n getLogger,\n configureLogging,\n setLogLevel,\n logger,\n} from './utils/logger';\nexport type {\n LogLevel,\n LogContext,\n LogEntry,\n LoggerConfig,\n} from './utils/logger';\n\n// Debug logging\nexport {\n setDebugHandler,\n setDebugEnabled,\n isDebugEnabled,\n debugLog,\n debugInfo,\n debugWarn,\n debugError,\n} from './utils/debug-logger';\nexport type { DebugLogEntry, DebugLogHandler } from './utils/debug-logger';\n\n// Embedding\nexport { EmbeddingGenerator } from './embedding/embedding-generator';\nexport { TransformersAdapter } from './embedding/transformers-adapter';\nexport { WasmSemanticProcessor } from './embedding/wasm-semantic-processor';\nexport { testWebAssemblySupport } from './embedding/wasm-semantic-processor';\n\n// Search\nexport { SemanticSearch } from './search/semantic-search';\nexport { cosineSimilarity } from './search/similarity-calculator';\nexport type {\n SemanticSearchResult,\n SearchOptions,\n StoredContext,\n} from './search/semantic-search/types';\n\n// Utilities\nexport { PerformanceMonitor } from './utils/performance';\nexport { DebugTools } from './utils/debugging';\nexport * from './utils/validation';\nexport {\n getEnvironment,\n isTestEnvironment,\n isDevelopmentEnvironment,\n isExtensionEnvironment,\n} from './utils/environment';\n\n// Runtime configuration — singleton consumed by application wrappers\n// that need to initialize environment settings at SDK startup.\nexport { RuntimeConfig, runtimeConfig } from './core/runtime-config';\n\n// Memory system — types, provider interface, concrete adapters.\n// `MemoryService` is intentionally not re-exported from root; consumers\n// use `MemoryClient` (above) as the canonical API.\nexport * from './memory/types';\nexport * from './memory/errors';\nexport * from './memory/provider';\nexport * from './memory/capability-profiles';\nexport * from './memory/pipeline';\nexport * from './memory/registration';\nexport * from './memory/atomicmemory-provider';\nexport * from './memory/mem0-provider';\nexport * from './memory/hindsight-provider';\n\n// Version information\nexport const SDK_VERSION = '1.0.0';\nexport const API_VERSION = '1.0';\n"]}
'use strict';
var chunkGHOB6O5U_cjs = require('./chunk-GHOB6O5U.cjs');
var chunkR56Z5WG5_cjs = require('./chunk-R56Z5WG5.cjs');
var chunkNULA3B6E_cjs = require('./chunk-NULA3B6E.cjs');
Object.defineProperty(exports, "capabilityGaps", {
enumerable: true,
get: function () { return chunkR56Z5WG5_cjs.capabilityGaps; }
});
Object.defineProperty(exports, "satisfiesProfile", {
enumerable: true,
get: function () { return chunkR56Z5WG5_cjs.satisfiesProfile; }
});
Object.defineProperty(exports, "ATOMICMEMORY_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.ATOMICMEMORY_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.ATOMICMEMORY_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "ATOMICMEMORY_EXTENSION_NAMES", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.ATOMICMEMORY_EXTENSION_NAMES; }
get: function () { return chunkNULA3B6E_cjs.ATOMICMEMORY_EXTENSION_NAMES; }
});
Object.defineProperty(exports, "AtomicMemoryProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.AtomicMemoryProvider; }
get: function () { return chunkNULA3B6E_cjs.AtomicMemoryProvider; }
});
Object.defineProperty(exports, "BaseMemoryProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.BaseMemoryProvider; }
get: function () { return chunkNULA3B6E_cjs.BaseMemoryProvider; }
});
Object.defineProperty(exports, "DEFAULT_META_FACT_PATTERNS", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.DEFAULT_META_FACT_PATTERNS; }
get: function () { return chunkNULA3B6E_cjs.DEFAULT_META_FACT_PATTERNS; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_API_VERSION", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_API_VERSION; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_API_VERSION; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_MAX_TOKENS", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_MAX_TOKENS; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_MAX_TOKENS; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_PROJECT_ID", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_PROJECT_ID; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_PROJECT_ID; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "HINDSIGHT_SCOPE_TAGS_MATCH", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HINDSIGHT_SCOPE_TAGS_MATCH; }
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_SCOPE_TAGS_MATCH; }
});
Object.defineProperty(exports, "HindsightProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.HindsightProvider; }
get: function () { return chunkNULA3B6E_cjs.HindsightProvider; }
});
Object.defineProperty(exports, "InvalidScopeError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.InvalidScopeError; }
get: function () { return chunkNULA3B6E_cjs.InvalidScopeError; }
});
Object.defineProperty(exports, "MEM0_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MEM0_DEFAULT_TIMEOUT; }
get: function () { return chunkNULA3B6E_cjs.MEM0_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "Mem0ContextProvider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.Mem0ContextProvider; }
get: function () { return chunkNULA3B6E_cjs.Mem0ContextProvider; }
});
Object.defineProperty(exports, "Mem0Provider", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.Mem0Provider; }
get: function () { return chunkNULA3B6E_cjs.Mem0Provider; }
});
Object.defineProperty(exports, "MemoryProviderError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MemoryProviderError; }
get: function () { return chunkNULA3B6E_cjs.MemoryProviderError; }
});
Object.defineProperty(exports, "MemoryTransportError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.MemoryTransportError; }
get: function () { return chunkNULA3B6E_cjs.MemoryTransportError; }
});
Object.defineProperty(exports, "RateLimitError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.RateLimitError; }
get: function () { return chunkNULA3B6E_cjs.RateLimitError; }
});
Object.defineProperty(exports, "UnsupportedOperationError", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.UnsupportedOperationError; }
get: function () { return chunkNULA3B6E_cjs.UnsupportedOperationError; }
});
Object.defineProperty(exports, "filterMetaFacts", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.filterMetaFacts; }
get: function () { return chunkNULA3B6E_cjs.filterMetaFacts; }
});
Object.defineProperty(exports, "isMetaFact", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.isMetaFact; }
get: function () { return chunkNULA3B6E_cjs.isMetaFact; }
});
Object.defineProperty(exports, "noopMemoryPipeline", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.noopMemoryPipeline; }
get: function () { return chunkNULA3B6E_cjs.noopMemoryPipeline; }
});
Object.defineProperty(exports, "resolveMetaFactPatterns", {
enumerable: true,
get: function () { return chunkGHOB6O5U_cjs.resolveMetaFactPatterns; }
get: function () { return chunkNULA3B6E_cjs.resolveMetaFactPatterns; }
});
//# sourceMappingURL=memory.cjs.map
//# sourceMappingURL=memory.cjs.map

@@ -1,1673 +0,52 @@

/**
* @file V3 Memory Provider Types
*
* Core type definitions for the unified MemoryProvider interface.
* Based on the accepted V3 specification (providers-v3.md).
*
* Pure types — no runtime code.
*/
/**
* Identity and partition context for memory operations.
* Providers declare which fields they require via capabilities().requiredScope.
*/
interface Scope {
user?: string;
agent?: string;
namespace?: string;
thread?: string;
}
/**
* Reference to a specific memory within a scope.
*/
interface MemoryRef {
id: string;
scope: Scope;
}
/**
* A single memory unit. Returned by get, list, and as part of SearchResult.
*/
interface Memory {
id: string;
content: string;
scope: Scope;
kind?: MemoryKind;
createdAt: Date;
updatedAt?: Date;
provenance?: Provenance;
metadata?: Record<string, unknown>;
}
type MemoryKind = 'fact' | 'episode' | 'summary' | 'procedure' | 'document';
interface Provenance {
source?: string;
sourceUrl?: string;
sourceId?: string;
extractor?: string;
}
type IngestInput = TextIngest | MessageIngest | VerbatimIngest;
interface IngestBase {
scope: Scope;
provenance?: Provenance;
metadata?: Record<string, unknown>;
}
/** Raw text: conversation transcript, document, note. */
interface TextIngest extends IngestBase {
mode: 'text';
content: string;
}
/** Structured chat messages. */
interface MessageIngest extends IngestBase {
mode: 'messages';
messages: Message[];
}
/**
* Verbatim storage: bypass LLM extraction and store the content as a
* single memory record. One input = one memory, deterministic. Use for
* user-provided context blobs where the fact-extraction pipeline
* would either over-split the text or, for ambiguous input, produce
* zero facts and leave the user thinking nothing was saved.
*
* Capability-gated: only available when
* `capabilities().ingestModes` includes 'verbatim'.
*/
interface VerbatimIngest extends IngestBase {
mode: 'verbatim';
content: string;
kind?: MemoryKind;
metadata?: Record<string, unknown>;
}
interface Message {
role: 'user' | 'assistant' | 'system' | 'tool';
content: string;
name?: string;
}
interface IngestResult {
created: string[];
updated: string[];
unchanged: string[];
}
interface SearchRequest {
query: string;
scope: Scope;
limit?: number;
threshold?: number;
filter?: FilterExpr;
reranker?: string;
}
interface SearchResult {
memory: Memory;
/**
* Backward-compatible provider score.
* For AtomicMemory this is the composite ranking score (`rankingScore`) and
* is not normalized. New consumers should prefer the explicit fields below.
* Other providers preserve their historical score semantics.
*/
score: number;
/** Semantic/vector similarity when the provider exposes it. Higher is better. */
similarity?: number;
/** Composite ranking/debug score. Not guaranteed to be normalized. */
rankingScore?: number;
/** Normalized injection relevance in [0, 1], suitable for threshold checks. */
relevance?: number;
}
interface SearchResultPage {
results: SearchResult[];
cursor?: string;
}
type FilterExpr = {
and: FilterExpr[];
} | {
or: FilterExpr[];
} | {
not: FilterExpr;
} | FieldFilter;
interface FieldFilter {
field: string;
op: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'contains' | 'exists';
value?: string | number | boolean | Date | Array<string | number>;
}
interface ListRequest {
scope: Scope;
limit?: number;
cursor?: string;
filter?: FilterExpr;
}
interface ListResultPage {
memories: Memory[];
cursor?: string;
}
interface PackageRequest extends SearchRequest {
tokenBudget?: number;
format?: 'flat' | 'tiered' | 'structured';
}
/**
* Injection-ready context for an AI assistant.
* `text` is the formatted string for prompt injection.
* `results` tracks what contributed (for debugging and attribution).
* `budgetConstrained` is true when the requested token budget shaped
* the package — either eligible memories were omitted entirely or
* eligible richer detail (L1/L2 tier, query-term-revealing upgrades)
* was suppressed solely because the budget could not afford it.
* Quota-driven demotion (e.g. fixed-cap policy) is NOT flagged.
* Powers the v5 CLI envelope's `meta.budget_constrained` field.
*/
interface ContextPackage {
text: string;
results: SearchResult[];
tokens: number;
budgetConstrained: boolean;
}
interface Capabilities {
ingestModes: Array<IngestInput['mode']>;
requiredScope: {
default: Array<keyof Scope>;
ingest?: Array<keyof Scope>;
search?: Array<keyof Scope>;
get?: Array<keyof Scope>;
delete?: Array<keyof Scope>;
list?: Array<keyof Scope>;
update?: Array<keyof Scope>;
package?: Array<keyof Scope>;
temporal?: Array<keyof Scope>;
graph?: Array<keyof Scope>;
forget?: Array<keyof Scope>;
profile?: Array<keyof Scope>;
reflect?: Array<keyof Scope>;
versioning?: Array<keyof Scope>;
batch?: Array<keyof Scope>;
};
extensions: {
update: boolean;
package: boolean;
temporal: boolean;
graph: boolean;
forget: boolean;
profile: boolean;
reflect: boolean;
versioning: boolean;
batch: boolean;
health: boolean;
};
customExtensions?: Record<string, {
version?: string;
description?: string;
}>;
supportedRerankers?: string[];
supportedFilterOps?: FieldFilter['op'][];
maxTokenBudget?: number;
}
interface GraphSearchRequest {
query: string;
scope: Scope;
limit?: number;
graphScope?: 'nodes' | 'edges' | 'episodes';
reranker?: string;
}
interface GraphResult {
nodes: GraphNode[];
edges: GraphEdge[];
}
interface GraphNode {
id: string;
label: string;
summary?: string;
score?: number;
}
interface GraphEdge {
id: string;
fact: string;
from: string;
to: string;
validAt?: Date;
invalidAt?: Date;
score?: number;
}
interface Profile {
summary: string;
facts?: string[];
updatedAt?: Date;
}
interface Insight {
content: string;
confidence: number;
supportingMemoryIds: string[];
}
interface MemoryVersion {
id: string;
content: string;
createdAt: Date;
parentId?: string;
event: 'created' | 'updated' | 'superseded' | 'invalidated';
}
interface HealthStatus {
ok: boolean;
latencyMs?: number;
version?: string;
}
import { ap as IngestInput, F as Capabilities } from './hindsight-provider-CbfXnvx7.cjs';
export { A as ATOMICMEMORY_DEFAULT_TIMEOUT, a as ATOMICMEMORY_EXTENSION_NAMES, b as AddContextResult, c as AgentConflict, d as AgentScope, e as AtomicMemoryAgents, f as AtomicMemoryAudit, g as AtomicMemoryConfig, h as AtomicMemoryExtensionName, i as AtomicMemoryHandle, j as AtomicMemoryHealthStatus, k as AtomicMemoryIngestInput, l as AtomicMemoryIngestResult, m as AtomicMemoryLessons, n as AtomicMemoryLifecycle, o as AtomicMemoryListOptions, p as AtomicMemoryListResultPage, q as AtomicMemoryMemory, r as AtomicMemoryProvider, s as AtomicMemoryProviderConfig, t as AtomicMemorySearchRequest, u as AtomicMemorySearchResult, v as AtomicMemorySearchResultPage, w as AuditTrailEntry, x as AuditTrailResult, y as AutoResolveConflictsResult, B as BaseMemoryProvider, z as BatchOps, C as CapCheckResult, D as CapRecommendation, E as CapStatus, G as ConfigUpdateResult, H as ConfigUpdates, I as ConflictResolution, J as ConflictStatus, K as ConflictsListResult, L as ConsolidationExecutionResult, M as ConsolidationResult, N as ConsolidationScanResult, O as ContentClass, P as ContextMetadata, Q as ContextPackage, R as ContextRecord, S as ContextSearchOptions, T as ContextSearchResult, U as DEFAULT_META_FACT_PATTERNS, V as DecayResult, W as DocumentMetadata, X as EmbeddingProviderName, Y as FieldFilter, Z as FilterExpr, _ as Forgetter, $ as GetTrustResult, a0 as GraphEdge, a1 as GraphNode, a2 as GraphResult, a3 as GraphSearch, a4 as GraphSearchRequest, a5 as HINDSIGHT_DEFAULT_API_VERSION, a6 as HINDSIGHT_DEFAULT_MAX_TOKENS, a7 as HINDSIGHT_DEFAULT_PROJECT_ID, a8 as HINDSIGHT_DEFAULT_TIMEOUT, a9 as HINDSIGHT_SCOPE_TAGS_MATCH, aa as Health, ab as HealthConfig, ac as HealthStatus, ad as HindsightOperation, ae as HindsightOperationsHandle, af as HindsightOperationsPage, ag as HindsightProvider, ah as HindsightProviderConfig, ai as HindsightRecallBudget, aj as HindsightRetainHandle, ak as HindsightRetainItem, al as HindsightRetainRequest, am as HindsightRetainResponse, an as HindsightTagsMatch, ao as IngestBase, aq as IngestResult, ar as Insight, as as InvalidScopeError, at as LLMProviderName, au as Lesson, av as LessonSeverity, aw as LessonStats, ax as LessonType, ay as LessonsListResult, az as ListRequest, aA as ListResultPage, aB as MEM0_DEFAULT_TIMEOUT, aC as Mem0ContextProvider, aD as Mem0ContextProviderConfig, aE as Mem0Provider, aF as Mem0ProviderConfig, aG as Memory, aH as MemoryKind, aI as MemoryProcessingPipeline, aJ as MemoryProvider, aK as MemoryProviderEntry, aL as MemoryProviderError, aM as MemoryProviderRegistration, aN as MemoryRef, aO as MemoryScope, aP as MemoryTransportError, aQ as MemoryVersion, aR as Message, aS as MessageIngest, aT as MetaFactFilterConfig, aU as MutationRecord, aV as MutationSummary, aW as MutationType, aX as PackageRequest, aY as Packager, aZ as Profile, a_ as Profiler, a$ as Provenance, b0 as RateLimitError, b1 as RecentMutationsResult, b2 as ReconcileStatus, b3 as ReconciliationResult, b4 as Reflector, b5 as ResetSourceResult, b6 as ResolveConflictResult, b7 as RetrievalReceipt, b8 as Scope, b9 as SearchRequest, ba as SearchResult, bb as SearchResultPage, bc as SetTrustResult, bd as StatsResult, be as TemporalSearch, bf as TextIngest, bg as UnsupportedOperationError, bh as Updater, bi as VerbatimIngest, bj as Versioner, bk as filterMetaFacts, bl as isMetaFact, bm as noopMemoryPipeline, bn as resolveMetaFactPatterns } from './hindsight-provider-CbfXnvx7.cjs';
/**
* @file V3 Memory Provider Interface and Base Class
* @file Capability profiles
*
* Defines the MemoryProvider interface, standard extension interfaces,
* and the BaseMemoryProvider abstract class with runOperation() enforcement.
*/
interface MemoryProvider {
readonly name: string;
initialize?(): Promise<void>;
close?(): Promise<void>;
ingest(input: IngestInput): Promise<IngestResult>;
search(request: SearchRequest): Promise<SearchResultPage>;
get(ref: MemoryRef): Promise<Memory | null>;
delete(ref: MemoryRef): Promise<void>;
list(request: ListRequest): Promise<ListResultPage>;
capabilities(): Capabilities;
getExtension?<T = unknown>(name: string): T | undefined;
}
interface Updater {
update(ref: MemoryRef, content: string): Promise<Memory>;
}
interface Packager {
package(request: PackageRequest): Promise<ContextPackage>;
}
interface TemporalSearch {
searchAsOf(request: SearchRequest & {
asOf: Date;
}): Promise<SearchResultPage>;
}
interface GraphSearch {
searchGraph(request: GraphSearchRequest): Promise<GraphResult>;
}
interface Forgetter {
forget(ref: MemoryRef, reason?: string): Promise<void>;
}
interface Profiler {
profile(scope: Scope, instructions?: string[]): Promise<Profile>;
}
interface Reflector {
reflect(query: string, scope: Scope): Promise<Insight[]>;
}
interface Versioner {
history(ref: MemoryRef): Promise<MemoryVersion[]>;
}
interface BatchOps {
batchIngest(inputs: IngestInput[]): Promise<IngestResult[]>;
batchDelete(refs: MemoryRef[]): Promise<void>;
}
interface Health {
health(): Promise<HealthStatus>;
}
declare abstract class BaseMemoryProvider implements MemoryProvider {
abstract readonly name: string;
/** Override to `false` in constructor to require async init. */
protected initialized: boolean;
protected abstract doIngest(input: IngestInput): Promise<IngestResult>;
protected abstract doSearch(request: SearchRequest): Promise<SearchResultPage>;
protected abstract doGet(ref: MemoryRef): Promise<Memory | null>;
protected abstract doDelete(ref: MemoryRef): Promise<void>;
protected abstract doList(request: ListRequest): Promise<ListResultPage>;
abstract capabilities(): Capabilities;
/**
* Generic enforcement for core AND extension operations.
* Validates readiness and scope, wraps errors.
*/
protected runOperation<T>(operation: string, scope: Scope | undefined, fn: () => Promise<T>): Promise<T>;
ingest(input: IngestInput): Promise<IngestResult>;
search(request: SearchRequest): Promise<SearchResultPage>;
get(ref: MemoryRef): Promise<Memory | null>;
delete(ref: MemoryRef): Promise<void>;
list(request: ListRequest): Promise<ListResultPage>;
/**
* Default extension resolution: checks capabilities().extensions
* and returns `this` for supported standard extensions.
* Subclasses override for custom extensions.
*/
protected resolveExtension(name: string): unknown | undefined;
getExtension<T = unknown>(name: string): T | undefined;
protected assertReady(): void;
protected validateScope(scope: Scope, operation: string): void;
protected wrapError(operation: string, err: unknown): Error;
}
/**
* @file MetaFactFilter
* A capability profile is the minimum {@link Capabilities} a
* {@link MemoryProvider} must satisfy for a given consumer's needs (for
* example, an audited ingest→search→replay path that requires deterministic
* verbatim storage and version pinning). It is expressed as a typed, partial
* requirement set so a caller can gate a provider at wiring time with an
* actionable diff instead of an opaque boolean.
*
* Post-retrieval filter that drops "meta-facts" — extraction artifacts that
* describe the conversation itself rather than recording a durable fact about
* the user.
*
* Empirically motivated by AlignBench v0 (benchmarks/alignbench/RESULTS.md):
* when extraction-style meta-facts ("The user asked for the user's name.",
* "As of <date>, X is a term mentioned in the conversation.") sit in the
* recall pool alongside real user facts, they often outrank the real fact
* for pronoun and temporal queries — at thin cosine margins (~0.05). The
* pre-registered "fix the query side" hypothesis was falsified; the dominant
* fixable lift came from removing meta-facts from the pool.
*
* Long-term, core should not emit these facts at extraction time. This
* SDK-side filter is the safety net so apps consuming the SDK today see
* cleaner recall results without waiting on a core release.
*
* Default patterns target the verbatim shapes observed in partner demos.
* Apps can extend or replace them via
* `MetaFactFilterConfig.patterns`.
*
* This filter is intentionally:
* - pure (no I/O, no LLM calls — deterministic regex application);
* - opt-in (off unless explicitly enabled in provider config);
* - case-insensitive;
* - additive (apps may add patterns without losing the defaults).
* The SDK ships the generic mechanism; each consumer defines its own profile
* constant against this type. Pure runtime code — no I/O, no provider
* construction.
*/
/**
* Built-in patterns observed in real partner demos. Each is a case-insensitive
* regex matched against the memory's content. A match drops the memory from
* the result set.
*
* Patterns capture the three meta-fact families that AlignBench's distractor
* pool was built from:
* 1. "The user asked/requested/said …" — meta-facts about user actions in
* the conversation, not about the user.
* 2. "As of <date>, X is a term mentioned in the conversation." — vacuous
* acknowledgements of vocabulary, not durable facts.
* 3. "A name was mentioned." / "The conversation involves the user." —
* observations about the chat session, not about the user.
*/
declare const DEFAULT_META_FACT_PATTERNS: readonly RegExp[];
interface MetaFactFilterConfig {
/**
* Master switch. When `false` (the default), the filter is a no-op and
* all results pass through.
*
* Apps explicitly opt in by setting `true`. We do not infer this from
* environment variables in the SDK to keep behaviour deterministic across
* Node / browser / Workers runtimes.
*/
enabled: boolean;
/**
* Patterns to match against `memory.content`. When omitted, the built-in
* `DEFAULT_META_FACT_PATTERNS` are used.
*
* When `mode === 'replace'` (the default when `patterns` is set), only the
* provided patterns are applied. Set `mode: 'extend'` to apply the provided
* patterns *and* the built-in defaults.
*/
patterns?: readonly RegExp[];
/**
* How `patterns` interacts with `DEFAULT_META_FACT_PATTERNS`. Defaults to
* `'replace'` (the provided list fully replaces defaults). `'extend'` is
* the union — useful when an app wants to add its own meta-fact shapes
* without losing the SDK's baseline coverage.
*/
mode?: 'replace' | 'extend';
/**
* Optional callback invoked once per dropped result. Useful for telemetry
* or tests. Receives the memory content and the pattern index that matched.
* Exceptions thrown by `onDrop` are swallowed so they cannot break recall.
*/
onDrop?: (content: string, patternIndex: number) => void;
}
/**
* Resolve the effective pattern list for a config.
*
* Pure; safe to call repeatedly. Used in two places — at filter time, and
* in tests that want to introspect the effective rule set without filtering
* a result list.
*/
declare function resolveMetaFactPatterns(config: MetaFactFilterConfig): readonly RegExp[];
/**
* Return `true` when `content` matches any of `patterns`.
*
* Defensive against non-string input (returns `false`) so a malformed result
* doesn't crash the filter pipeline.
*/
declare function isMetaFact(content: unknown, patterns?: readonly RegExp[]): boolean;
/**
* Filter a list of items by removing entries whose `getContent(item)` matches
* any active meta-fact pattern.
*
* Generic over `T` so callers can filter `SearchResult` / `Memory` / raw
* backend shapes with the same primitive. Pure and synchronous.
*/
declare function filterMetaFacts<T>(items: readonly T[], getContent: (item: T) => unknown, config: MetaFactFilterConfig): T[];
/**
* @file AtomicMemory Provider Configuration
*/
interface AtomicMemoryProviderConfig {
/** Base URL of the atomicmemory-core instance, e.g. `http://localhost:17350`. */
apiUrl: string;
/** Optional bearer token forwarded as `Authorization: Bearer <apiKey>`. */
apiKey?: string;
/** Request timeout in milliseconds. Defaults to 30_000. */
timeout?: number;
/** A minimum capability requirement set a provider must satisfy. */
interface CapabilityProfile {
/** Ingest modes the provider must support (e.g. `'text'`, `'verbatim'`). */
ingestModes: ReadonlyArray<IngestInput['mode']>;
/**
* API version segment prepended to every core-facing route path.
*
* Core mounts its routers under `/v1/memories` and `/v1/agents` (see
* atomicmemory-core/src/app/create-app.ts:31-32). The SDK prepends
* `/${apiVersion}` to all route calls so hitting a pre-v1 deployment
* or future versioned deployments only requires a config change, not
* a code change.
*
* Defaults to `'v1'` — the current mount point on core. Pass `''` to
* disable prefixing entirely (useful only against legacy deployments
* that never versioned their mount).
* Extension flags the provider must expose (`extensions.<flag> === true`).
* `search` is not listed here — it is a core method every `MemoryProvider`
* implements, so it is implied rather than gated.
*/
apiVersion?: string;
/**
* Opt-in post-retrieval filter that drops extraction-style meta-facts
* (e.g. "The user asked for the user's name.", "As of <date>, X is a term
* mentioned in the conversation.") before they reach the caller.
*
* Empirically motivated by `benchmarks/alignbench/RESULTS.md`: meta-facts
* are the dominant cause of partner-visible recall failures, outranking
* real user facts at thin cosine margins. Filtering them post-hoc gives
* cleaner search results today while a durable upstream extraction-prompt
* fix rolls out in core.
*
* When omitted, the filter is OFF and behaviour is unchanged. Set
* `{ enabled: true }` to activate with the built-in pattern set, or pass
* additional `patterns` / `mode` per `MetaFactFilterConfig`.
*/
metaFactFilter?: MetaFactFilterConfig;
extensions: ReadonlyArray<keyof Capabilities['extensions']>;
}
/** Default timeout for AtomicMemory provider HTTP requests (ms). */
declare const ATOMICMEMORY_DEFAULT_TIMEOUT = 30000;
/**
* @file AtomicMemory-specific namespaced handle
*
* Registered as `customExtensions['atomicmemory.*']` on AtomicMemoryProvider
* per V3 spec (docs/providers-v3.md:391-402). Typed access via
* `sdk.atomicmemory.*` on an SDK configured with an AtomicMemoryProvider.
*
* The namespace is a route-shaped HTTP binding for atomicmemory-core —
* request types are semantically aligned with core's parseIngestBody /
* parseSearchBody (SDK idiomatic camelCase + JS-native types; wire format
* snake_case mapping happens in the handle implementation).
*
* V3 `Scope` is intentionally NOT embedded in these request types — scope
* is always a separate argument using `MemoryScope` (the AtomicMemory-
* specific discriminated union below) so workspace semantics are honest
* per-method.
* A single unmet capability requirement, for actionable provider-rejection
* errors.
*/
/**
* Agent visibility scope for workspace reads.
*
* Matches core's `parseOptionalAgentScope`
* (atomicmemory-core/src/routes/memories.ts:617-627):
* - `'all'` | `'self'` | `'others'` — the three canonical modes.
* - any other string — treated as a single `agent_id` filter.
* - `string[]` — a specific list of agent IDs to include.
*
* The `(string & {})` branch preserves the three literal hints in IDE
* autocomplete while still permitting arbitrary strings.
*/
type AgentScope = 'all' | 'self' | 'others' | (string & {}) | string[];
/**
* AtomicMemory's canonical read-path contract. Mirrors core's `MemoryScope`
* at `atomicmemory-core/src/services/memory-service-types.ts:142-144`.
*/
type MemoryScope = {
kind: 'user';
userId: string;
thread?: string;
} | {
kind: 'workspace';
userId: string;
workspaceId: string;
agentId: string;
thread?: string;
agentScope?: AgentScope;
};
interface AtomicMemoryIngestInput {
/** Required, flat conversation string per core's parseIngestBody:517. */
conversation: string;
/** Required by core's parseIngestBody:518. */
sourceSite: string;
sourceUrl?: string;
/**
* Workspace write-time visibility label. Only honored when
* `scope.kind === 'workspace'`; runtime validation throws InputError
* if set with user scope.
*/
visibility?: 'agent_only' | 'restricted' | 'workspace';
/** Per-request core runtime override for benchmark and diagnostic runs. */
configOverride?: Record<string, unknown>;
interface CapabilityGap {
/** Which requirement category is unmet. */
kind: 'ingestMode' | 'extension';
/** The specific ingest mode or extension flag that is missing. */
requirement: string;
/** Human-readable reason the requirement is unmet. */
detail: string;
}
interface AtomicMemorySearchRequest {
query: string;
limit?: number;
/** Normalized relevance floor forwarded to core's `threshold` request field. */
threshold?: number;
/** Temporal filter. Honored by `/memories/search` full path; NOT by fast. */
asOf?: Date;
retrievalMode?: 'flat' | 'tiered' | 'abstract-aware';
tokenBudget?: number;
namespaceScope?: string;
sourceSite?: string;
skipRepair?: boolean;
/** Per-request core runtime override for benchmark and diagnostic runs. */
configOverride?: Record<string, unknown>;
}
interface AtomicMemoryListOptions {
limit?: number;
offset?: number;
/** User-scope only; ignored for workspace scope. */
sourceSite?: string;
/** User-scope only; ignored for workspace scope. */
episodeId?: string;
}
/**
* AtomicMemory-specific memory shape. Distinct from V3's flat `Memory` so
* the namespace can preserve the full `MemoryScope` discriminated union
* (including `workspaceId` / `agentId` / `agentScope`) on returned
* memories — V3's `Scope` type has no place for workspace fields, so a
* V3 Memory coming back from a workspace query would silently forget it
* was scoped to a workspace.
* Return every requirement in `profile` that `caps` fails to satisfy. An empty
* array means the provider satisfies the profile. Use this to build actionable
* errors ("provider X is missing verbatim ingest, missing versioning
* extension") instead of an opaque boolean rejection.
*/
interface AtomicMemoryMemory {
id: string;
content: string;
scope: MemoryScope;
createdAt: Date;
updatedAt?: Date;
importance?: number;
sourceSite?: string;
sourceUrl?: string;
episodeId?: string;
/** Workspace write-time visibility label on the stored memory. */
visibility?: 'agent_only' | 'restricted' | 'workspace';
metadata?: Record<string, unknown>;
}
interface AtomicMemorySearchResult {
memory: AtomicMemoryMemory;
/** Backward-compatible alias for `rankingScore` when core emits it. */
score: number;
/** Semantic/vector similarity when emitted by core. */
similarity?: number;
/** Composite ranking/debug score from core's retrieval pipeline. Not normalized. */
rankingScore?: number;
/** Normalized injection relevance in [0, 1]. */
relevance?: number;
/** AtomicMemory's 0–1 importance weighting on the source memory. */
importance?: number;
}
/**
* Response shape for `/memories/search` and `/memories/search/fast`.
* Mirrors core's `formatSearchResponse` (memories.ts:721-767) but with
* SDK-idiomatic camelCase and wrapped memories (raw core response uses
* snake_case and inline memory fields).
*/
interface AtomicMemorySearchResultPage {
count: number;
retrievalMode: string;
scope: MemoryScope;
results: AtomicMemorySearchResult[];
injectionText?: string;
citations?: string[];
tierAssignments?: Array<{
memoryId: string;
tier: string;
estimatedTokens: number;
}>;
expandIds?: string[];
estimatedContextTokens?: number;
lessonCheck?: {
safe: boolean;
warnings: unknown[];
highestSeverity: string;
matchedCount: number;
};
consensus?: {
originalCount: number;
filteredCount: number;
removedCount: number;
removedMemoryIds: string[];
};
observability?: {
retrieval?: unknown;
packaging?: unknown;
assembly?: unknown;
};
}
/**
* Response shape for `/memories/ingest` and `/memories/ingest/quick`.
* Mirrors core's `IngestResult` (memory-service-types.ts:91-101) with
* SDK-idiomatic camelCase.
*
* IDs are split by outcome: `storedMemoryIds` for newly created memories,
* `updatedMemoryIds` for mutated ones. Length of each array matches its
* corresponding `memoriesStored` / `memoriesUpdated` count.
*/
interface AtomicMemoryIngestResult {
episodeId: string;
factsExtracted: number;
memoriesStored: number;
memoriesUpdated: number;
memoriesDeleted: number;
memoriesSkipped: number;
storedMemoryIds: string[];
updatedMemoryIds: string[];
linksCreated: number;
compositesCreated: number;
}
/**
* Response shape for `/memories/list`.
* Core returns `{ memories, count }`; cursor is derived from offset+limit.
*/
interface AtomicMemoryListResultPage {
memories: AtomicMemoryMemory[];
count: number;
cursor?: string;
}
/**
* Scan-only response from `POST /memories/consolidate` when `execute: false`
* (the default). Mirrors core's `ConsolidationResult`
* (consolidation-service.ts).
*/
interface ConsolidationScanResult {
memoriesScanned: number;
clustersFound: number;
memoriesInClusters: number;
/**
* Cluster candidates identified by the scan. The per-cluster shape is
* internal to core's consolidation engine and is intentionally typed as
* `unknown[]` at the SDK boundary — consumers that need to inspect
* cluster internals should pin a core version and read the shape from
* there.
*/
clusters: unknown[];
}
/**
* Execution response from `POST /memories/consolidate` when `execute: true`.
* Mirrors core's `ConsolidationExecutionResult`.
*/
interface ConsolidationExecutionResult {
clustersConsolidated: number;
memoriesArchived: number;
memoriesCreated: number;
consolidatedMemoryIds: string[];
}
/**
* Union returned by `lifecycle.consolidate`. Discriminated by the presence
* of `consolidatedMemoryIds` (execution) vs `clusters` (scan-only).
*/
type ConsolidationResult = ConsolidationScanResult | ConsolidationExecutionResult;
/**
* Response from `POST /memories/decay`. Mirrors core's `DecayResult` plus
* the `archived` field added by the route handler (memories.ts:327/330).
*/
interface DecayResult {
memoriesEvaluated: number;
candidatesForArchival: Array<{
id: string;
retentionScore: number;
[key: string]: unknown;
}>;
retentionThreshold: number;
avgRetentionScore: number;
/**
* Count of memories actually archived. Non-zero only when `dryRun=false`
* and the scan found candidates (memories.ts:325-330).
*/
archived: number;
}
/**
* Mirrors core's `CapStatus` at memory-lifecycle.ts:133.
* `warn` = approaching the cap (usageRatio >= warnRatio, default 0.8).
* `exceeded` = over the cap.
*/
type CapStatus = 'ok' | 'warn' | 'exceeded';
type CapRecommendation = 'none' | 'consolidate' | 'decay' | 'consolidate-and-decay';
/**
* Response from `GET /memories/cap`. Mirrors core's `CapCheckResult`
* (memory-lifecycle.ts).
*/
interface CapCheckResult {
activeMemories: number;
maxMemories: number;
status: CapStatus;
usageRatio: number;
recommendation: CapRecommendation;
}
/**
* Response from `GET /memories/stats`. Core delegates to
* `MemoryStore.getMemoryStats(userId)` which is an open shape; typed as
* an index signature at the SDK boundary.
*/
interface StatsResult {
[key: string]: unknown;
}
/**
* Response from `POST /memories/reset-source`. Route handler wraps
* `resetBySource` with `{ success: true, ... }` (memories.ts:424).
*/
interface ResetSourceResult {
success: true;
deletedMemories: number;
deletedEpisodes: number;
}
/**
* Response from `POST /memories/reconcile`. Mirrors core's
* `ReconciliationResult` (deferred-audn.ts).
*/
interface ReconciliationResult {
processed: number;
resolved: number;
noops: number;
updates: number;
supersedes: number;
deletes: number;
adds: number;
errors: number;
durationMs: number;
}
/**
* Response from `GET /memories/reconcile/status`. Core returns an open
* shape from `getReconciliationStatus`; typed as index signature here.
*/
interface ReconcileStatus {
[key: string]: unknown;
}
/**
* Admin lifecycle operations. Workspace scope is not accepted by any of
* these routes — core parses `user_id` only (memories.ts:304, :322,
* :340, :251, :421, :409).
*
* Exception: core's `POST /memories/reconcile` also accepts an all-users
* batch-job mode (no `user_id` in the body; see memories.ts:397-400).
* The SDK splits that into an explicit `reconcileAll()` method so the
* all-users admin operation can't happen by accident from a missing
* argument.
*/
interface AtomicMemoryLifecycle {
consolidate(userId: string, execute?: boolean): Promise<ConsolidationResult>;
decay(userId: string, dryRun?: boolean): Promise<DecayResult>;
cap(userId: string): Promise<CapCheckResult>;
stats(userId: string): Promise<StatsResult>;
resetSource(userId: string, sourceSite: string): Promise<ResetSourceResult>;
/** Run deferred-AUDN reconciliation for a single user. */
reconcile(userId: string): Promise<ReconciliationResult>;
/**
* Run deferred-AUDN reconciliation across all users (batch-job mode).
* Maps to `POST /memories/reconcile` with no `user_id` in the body,
* which core routes to `reconcileDeferredAll()`
* (memories.ts:397-400). Intentionally exposed as a separate method
* so callers can't trigger the all-users pass by forgetting a
* `userId` argument.
*/
reconcileAll(): Promise<ReconciliationResult>;
reconcileStatus(userId: string): Promise<ReconcileStatus>;
}
/**
* Mirrors core's `MutationType` at
* atomicmemory-core/src/db/repository-types.ts.
*/
type MutationType = 'add' | 'update' | 'supersede' | 'delete' | 'clarify';
/**
* Aggregate mutation statistics. Mirrors core's `MutationSummary`
* (db/repository-types.ts). Emitted verbatim by GET /memories/audit/summary.
*/
interface MutationSummary {
totalVersions: number;
activeVersions: number;
supersededVersions: number;
totalClaims: number;
byMutationType: Record<string, number>;
}
/**
* A single mutation record from `GET /memories/audit/recent`.
*
* The core route returns raw `ClaimVersionRow[]` (snake_case DB rows);
* the SDK normalizes to camelCase so consumers aren't straddling two
* conventions. `createdAt`, `validFrom`, and `validTo` are `Date`
* values (deserialized from the wire ISO strings).
*/
interface MutationRecord {
id: string;
claimId: string;
userId: string;
memoryId: string | null;
content: string;
mutationType: MutationType | null;
mutationReason: string | null;
actorModel: string | null;
contradictionConfidence: number | null;
previousVersionId: string | null;
supersededByVersionId: string | null;
validFrom: Date;
validTo: Date | null;
createdAt: Date;
}
/** Response shape for `GET /memories/audit/recent`. */
interface RecentMutationsResult {
mutations: MutationRecord[];
count: number;
}
/**
* Single-memory audit trail entry. Mirrors core's `AuditTrailEntry`
* (db/repository-types.ts) verbatim — the service already emits
* camelCase for this one (memory-crud.ts getAuditTrail).
*/
interface AuditTrailEntry {
versionId: string;
claimId: string;
content: string;
mutationType: MutationType | null;
mutationReason: string | null;
actorModel: string | null;
contradictionConfidence: number | null;
previousVersionId: string | null;
supersededByVersionId: string | null;
validFrom: Date;
validTo: Date | null;
memoryId: string | null;
}
/** Response shape for `GET /memories/:id/audit`. */
interface AuditTrailResult {
memoryId: string;
trail: AuditTrailEntry[];
versionCount: number;
}
interface AtomicMemoryAudit {
/** `GET /memories/audit/summary` — aggregate mutation statistics for a user. */
summary(userId: string): Promise<MutationSummary>;
/** `GET /memories/audit/recent` — newest-first mutation records for a user. */
recent(userId: string, limit?: number): Promise<RecentMutationsResult>;
/** `GET /memories/:id/audit` — full version trail for a single memory. */
trail(memoryId: string, userId: string): Promise<AuditTrailResult>;
}
/**
* Mirrors core's `LessonType` at
* atomicmemory-core/src/db/repository-lessons.ts:16-22.
*/
type LessonType = 'injection_blocked' | 'false_memory' | 'contradiction_pattern' | 'user_reported' | 'consensus_violation' | 'trust_violation';
/**
* Mirrors core's `LessonSeverity` at
* atomicmemory-core/src/db/repository-lessons.ts:24.
*/
type LessonSeverity = 'low' | 'medium' | 'high' | 'critical';
/**
* A single lesson. Mirrors core's `LessonRow`
* (db/repository-lessons.ts:26-38), normalized to camelCase + Date on
* the SDK boundary.
*/
interface Lesson {
id: string;
userId: string;
lessonType: LessonType;
pattern: string;
embedding: number[];
sourceMemoryIds: string[];
sourceQuery: string | null;
severity: LessonSeverity;
active: boolean;
metadata: Record<string, unknown>;
createdAt: Date;
}
/** Response shape for `GET /memories/lessons`. */
interface LessonsListResult {
lessons: Lesson[];
count: number;
}
/**
* Aggregate lesson statistics from `GET /memories/lessons/stats`.
* Mirrors core's `getLessonStats` return shape (lesson-service.ts).
*/
interface LessonStats {
totalActive: number;
byType: Record<string, number>;
}
interface AtomicMemoryLessons {
/** `GET /memories/lessons` — list all active lessons for a user. */
list(userId: string): Promise<LessonsListResult>;
/** `GET /memories/lessons/stats` — aggregate counts by lesson type. */
stats(userId: string): Promise<LessonStats>;
/**
* `POST /memories/lessons/report` — record a user-reported lesson
* (explicit feedback path).
*/
report(userId: string, pattern: string, sources?: string[], severity?: LessonSeverity): Promise<{
lessonId: string;
}>;
/** `DELETE /memories/lessons/:id` — deactivate a lesson. */
delete(lessonId: string, userId: string): Promise<void>;
}
/**
* Embedding provider names core ships. Mirrors
* `EmbeddingProviderName` at atomicmemory-core/src/config.ts:14.
*/
type EmbeddingProviderName = 'openai' | 'ollama' | 'openai-compatible' | 'transformers';
/**
* LLM provider names core ships. Mirrors `LLMProviderName` at
* atomicmemory-core/src/config.ts:15.
*/
type LLMProviderName = EmbeddingProviderName | 'groq' | 'anthropic' | 'google-genai';
/**
* Runtime configuration snapshot exposed by `/memories/health`'s `config`
* field and `/memories/config`'s `config` response field. Mirrors core's
* `formatHealthConfig` (memories.ts) with SDK-idiomatic camelCase.
*/
interface HealthConfig {
retrievalProfile: string;
embeddingProvider: EmbeddingProviderName;
embeddingModel: string;
llmProvider: LLMProviderName;
llmModel: string;
clarificationConflictThreshold: number;
maxSearchResults: number;
hybridSearchEnabled: boolean;
iterativeRetrievalEnabled: boolean;
entityGraphEnabled: boolean;
crossEncoderEnabled: boolean;
agenticRetrievalEnabled: boolean;
repairLoopEnabled: boolean;
}
/**
* Response shape for `GET /memories/health`. Distinct from V3's
* `HealthStatus` (types.ts) — V3 health is `{ok, latencyMs?, version?}`
* (capability probe); core's route emits `{status, config}` (runtime
* snapshot). Renamed to avoid the collision at SDK export time.
*/
interface AtomicMemoryHealthStatus {
status: 'ok';
config: HealthConfig;
}
/**
* Runtime-mutable threshold fields accepted by `PUT /memories/config`.
* Mirrors the four fields core extracts from the body at memories.ts:
* 284-289.
*
* Every field is optional; omitted fields are left untouched.
* Provider/model selection is intentionally NOT exposed here — core
* 400s startup-only fields (memories.ts:275-283). Callers should
* restart the process with the relevant env vars to change those.
*/
interface ConfigUpdates {
similarityThreshold?: number;
audnCandidateThreshold?: number;
clarificationConflictThreshold?: number;
maxSearchResults?: number;
}
/**
* Success response from `PUT /memories/config`. Mirrors core's
* success-path body at memories.ts:290-294.
*
* Note: core can return 410 (mutation disabled) or 400 (startup-only
* field present) as HTTP errors; those are wrapped into the SDK's
* MemoryProviderError by the shared fetch layer and should be caught
* with try/catch, not inspected on this type.
*/
interface ConfigUpdateResult {
/** Field names that were actually applied (subset of ConfigUpdates keys). */
applied: string[];
/** Full updated runtime config snapshot. */
config: HealthConfig;
/** Human-readable note reminding that provider/model changes require restart. */
note: string;
}
interface AtomicMemoryConfig {
/** `GET /memories/health` — current runtime config snapshot. */
health(): Promise<AtomicMemoryHealthStatus>;
/**
* `PUT /memories/config` — apply runtime-mutable threshold updates.
*
* Requires the server to have been started with
* `CORE_RUNTIME_CONFIG_MUTATION_ENABLED=true`; otherwise core returns
* HTTP 410, which propagates as a thrown MemoryProviderError.
*/
updateConfig(updates: ConfigUpdates): Promise<ConfigUpdateResult>;
}
/**
* Conflict resolution choices accepted by
* `PUT /agents/conflicts/:id/resolve`. Mirrors core's VALID_RESOLUTIONS
* set at atomicmemory-core/src/routes/agents.ts:102.
*/
type ConflictResolution = 'resolved_new' | 'resolved_existing' | 'resolved_both';
/**
* Conflict status values core writes into the `memory_conflicts.status`
* column. `open` is the initial state; the three resolution variants
* come from manual resolution; `auto_resolved` comes from
* `autoResolveExpiredConflicts`. Typed as a string union but kept open
* via `string` to tolerate future status values without breaking the
* SDK.
*/
type ConflictStatus = 'open' | 'resolved_new' | 'resolved_existing' | 'resolved_both' | 'auto_resolved';
/** Response shape for `PUT /agents/trust`. */
interface SetTrustResult {
agentId: string;
trustLevel: number;
}
/**
* Response shape for `GET /agents/trust`.
*
* `trustLevel` is always a number. When no trust record exists for
* the (userId, agentId) pair, core returns `DEFAULT_TRUST_LEVEL` (0.5
* as of today — see `atomicmemory-core/src/db/agent-trust-repository.ts:46,56`)
* rather than `null`. Callers who need to distinguish "unset" from
* "explicitly 0.5" must track the provenance themselves; the wire
* contract does not expose the distinction.
*/
interface GetTrustResult {
agentId: string;
trustLevel: number;
}
/**
* A single agent conflict row. Mirrors core's `MemoryConflict`
* (agent-trust-repository.ts), normalized to camelCase + Date at the
* SDK boundary.
*/
interface AgentConflict {
id: string;
userId: string;
newMemoryId: string | null;
existingMemoryId: string | null;
newAgentId: string | null;
existingAgentId: string | null;
newTrustLevel: number | null;
existingTrustLevel: number | null;
contradictionConfidence: number;
clarificationNote: string | null;
status: ConflictStatus;
resolutionPolicy: string | null;
resolvedAt: Date | null;
createdAt: Date;
autoResolveAfter: Date | null;
}
/** Response shape for `GET /agents/conflicts`. */
interface ConflictsListResult {
conflicts: AgentConflict[];
count: number;
}
/**
* Response shape for `PUT /agents/conflicts/:id/resolve`.
* `status` echoes the resolution you passed in.
*/
interface ResolveConflictResult {
id: string;
status: ConflictResolution;
}
/** Response shape for `POST /agents/conflicts/auto-resolve`. */
interface AutoResolveConflictsResult {
/** Count of conflicts transitioned to `auto_resolved` state. */
resolved: number;
}
interface AtomicMemoryAgents {
/**
* `PUT /agents/trust` — set or update a (userId, agentId) trust
* record. `trustLevel` must be between 0.0 and 1.0 (core validates).
* Optional `displayName` is a human-readable label.
*/
setTrust(userId: string, agentId: string, trustLevel: number, displayName?: string): Promise<SetTrustResult>;
/**
* `GET /agents/trust` — look up a single (userId, agentId) trust
* record. When no record exists, core returns a default trust level
* (currently 0.5) rather than 404. See `GetTrustResult` for the
* unset-vs-0.5 caveat.
*/
getTrust(userId: string, agentId: string): Promise<GetTrustResult>;
/** `GET /agents/conflicts` — list open conflicts for a user. */
conflicts(userId: string): Promise<ConflictsListResult>;
/**
* `PUT /agents/conflicts/:id/resolve` — manually resolve one
* conflict. NB: this route takes `conflictId` (not `userId`) because
* core resolves by conflict id directly (agents.ts:61-72).
*/
resolveConflict(conflictId: string, resolution: ConflictResolution): Promise<ResolveConflictResult>;
/**
* `POST /agents/conflicts/auto-resolve` — trigger the batch
* auto-resolution pass for a user. Transitions any `open` conflicts
* whose `auto_resolve_after` deadline has elapsed into
* `auto_resolved` state. Returns the count transitioned.
*/
autoResolveConflicts(userId: string): Promise<AutoResolveConflictsResult>;
}
/**
* AtomicMemory-specific SDK handle. Access via `sdk.atomicmemory` when an
* AtomicMemoryProvider is registered. `sdk.atomicmemory` is `undefined`
* for SDK configurations that do not include AtomicMemoryProvider.
*/
interface AtomicMemoryHandle {
ingestFull(input: AtomicMemoryIngestInput, scope: MemoryScope): Promise<AtomicMemoryIngestResult>;
ingestQuick(input: AtomicMemoryIngestInput, scope: MemoryScope, options?: {
skipExtraction?: boolean;
}): Promise<AtomicMemoryIngestResult>;
search(request: AtomicMemorySearchRequest, scope: MemoryScope): Promise<AtomicMemorySearchResultPage>;
/**
* Fast search path. Does NOT honor `request.asOf` — core's handler at
* `atomicmemory-core/src/routes/memories.ts:191-206` parses `as_of`
* but drops it. Use `search()` for temporal queries.
*/
searchFast(request: AtomicMemorySearchRequest, scope: MemoryScope): Promise<AtomicMemorySearchResultPage>;
expand(refs: string[], scope: MemoryScope): Promise<AtomicMemoryMemory[]>;
list(scope: MemoryScope, options?: AtomicMemoryListOptions): Promise<AtomicMemoryListResultPage>;
get(id: string, scope: MemoryScope): Promise<AtomicMemoryMemory | null>;
delete(id: string, scope: MemoryScope): Promise<void>;
lifecycle: AtomicMemoryLifecycle;
audit: AtomicMemoryAudit;
lessons: AtomicMemoryLessons;
config: AtomicMemoryConfig;
agents: AtomicMemoryAgents;
}
declare const ATOMICMEMORY_EXTENSION_NAMES: readonly ["atomicmemory.base", "atomicmemory.lifecycle", "atomicmemory.audit", "atomicmemory.lessons", "atomicmemory.config", "atomicmemory.agents"];
type AtomicMemoryExtensionName = (typeof ATOMICMEMORY_EXTENSION_NAMES)[number];
declare function capabilityGaps(caps: Capabilities, profile: CapabilityProfile): CapabilityGap[];
/** Whether `caps` satisfies every requirement in `profile`. */
declare function satisfiesProfile(caps: Capabilities, profile: CapabilityProfile): boolean;
/**
* @file Mem0 Provider Configuration
*
* Configuration types for the Mem0 memory provider, which connects
* to a local or hosted Mem0 instance via its REST API.
*/
interface Mem0ProviderConfig {
/** Mem0 API base URL (e.g. "https://api.mem0.ai" hosted or "http://localhost:8888" OSS) */
apiUrl: string;
/** Request timeout in milliseconds */
timeout?: number;
/** API key for hosted Mem0 instances */
apiKey?: string;
/** Whether to enable LLM inference on ingest (default true) */
defaultInfer?: boolean;
/**
* When true, ingest sends infer=false synchronously for fast return,
* then fires a background re-ingest with infer=true (deferred AUDN).
* Only applies when the effective infer value would be true.
* Default: false (single-call behavior).
*/
deferInference?: boolean;
/**
* Path prefix for memory-identifier endpoints (ingest, get, delete, list).
* - '/v1' (default) for hosted Mem0 (api.mem0.ai): /v1/memories/, /v1/memories/{id}/
* - '' for OSS self-hosted Mem0: /memories/, /memories/{id}/
*
* Note: search uses the v2 endpoint (`/v2/memories/search/` hosted, or
* `/memories/search/` OSS) regardless of this prefix, per mem0 2.0's
* split of search from the v1 family.
*/
pathPrefix?: string;
/**
* Optional organization ID for enterprise-scoped operations (mem0 2.0+).
* Sent as top-level `org_id` on search and ingest bodies when set.
*/
orgId?: string;
/**
* Optional project ID for enterprise-scoped operations (mem0 2.0+).
* Sent as top-level `project_id` on search and ingest bodies when set.
*/
projectId?: string;
}
/** Default timeout for Mem0 provider HTTP requests (ms). */
declare const MEM0_DEFAULT_TIMEOUT = 30000;
/**
* @file Hindsight Provider Configuration and Wire Types
*
* Defines the public configuration surface and provider-specific extension
* handle types for the Hindsight memory backend. The core SDK provider API
* remains backend-agnostic; these types are exported so callers that opt into
* Hindsight-specific operation metadata can do so through named extensions.
*/
type HindsightRecallBudget = 'low' | 'mid' | 'high';
type HindsightTagsMatch = 'any' | 'all' | 'any_strict' | 'all_strict';
interface HindsightProviderConfig {
/** Hindsight API base URL, e.g. `https://api.hindsight.vectorize.io`. */
apiUrl: string;
/** Optional bearer token for Hindsight Cloud or protected self-hosted APIs. */
apiKey?: string;
/** Request timeout in milliseconds. Defaults to 30_000. */
timeout?: number;
/** API version path segment. Defaults to `v1`. */
apiVersion?: string;
/** Hindsight project path segment. Defaults to `default`. */
projectId?: string;
/** Recall search depth fallback. Request-level typed override is deferred. */
defaultBudget?: HindsightRecallBudget;
/** Fallback context token budget for package/recall requests. */
defaultMaxTokens?: number;
}
interface HindsightRetainItem {
content: string;
context?: string;
timestamp?: string;
metadata?: Record<string, unknown>;
tags?: string[];
}
interface HindsightRetainRequest {
items: HindsightRetainItem[];
async?: boolean;
}
interface HindsightRetainResponse {
success?: boolean;
bank_id?: string;
items_count?: number;
async?: boolean;
operation_id?: string;
operation_ids?: string[];
usage?: Record<string, unknown>;
}
interface HindsightOperation {
id: string;
task_type?: string;
items_count?: number;
document_id?: string | null;
created_at?: string;
status?: string;
error_message?: string | null;
retry_count?: number;
next_retry_at?: string;
}
interface HindsightOperationsPage {
bank_id?: string;
operations: HindsightOperation[];
}
interface HindsightRetainHandle {
retain(input: IngestInput): Promise<HindsightRetainResponse>;
}
interface HindsightOperationsHandle {
list(scope: Scope): Promise<HindsightOperationsPage>;
get(scope: Scope, operationId: string): Promise<HindsightOperation | null>;
}
declare const HINDSIGHT_DEFAULT_TIMEOUT = 30000;
declare const HINDSIGHT_DEFAULT_API_VERSION = "v1";
declare const HINDSIGHT_DEFAULT_PROJECT_ID = "default";
/** Hindsight's documented default source-fact token budget for reflect/recall examples. */
declare const HINDSIGHT_DEFAULT_MAX_TOKENS = 4096;
declare const HINDSIGHT_SCOPE_TAGS_MATCH: HindsightTagsMatch;
/**
* @file V3 Memory Processing Pipeline
*
* SDK-level hooks for transforming data before/after provider calls.
* Pipelines are SDK orchestration, not part of the provider standard.
*/
interface MemoryProcessingPipeline {
preprocessIngest?(input: IngestInput): Promise<IngestInput[]>;
postprocessIngest?(result: IngestResult, input: IngestInput): Promise<void>;
preprocessSearch?(request: SearchRequest): Promise<SearchRequest>;
postprocessSearch?(page: SearchResultPage, request: SearchRequest): Promise<SearchResultPage>;
preprocessGet?(ref: MemoryRef): Promise<MemoryRef>;
postprocessGet?(memory: Memory | null, ref: MemoryRef): Promise<Memory | null>;
postprocessList?(page: ListResultPage, request: ListRequest): Promise<ListResultPage>;
}
/** No-op pipeline that passes data through unchanged. */
declare const noopMemoryPipeline: MemoryProcessingPipeline;
/**
* @file V3 Memory Provider Registration
*
* Types for pairing a provider with an optional processing pipeline
* at registration time.
*/
/** A provider paired with its optional pipeline. */
interface MemoryProviderRegistration {
provider: MemoryProvider;
pipeline?: MemoryProcessingPipeline;
}
/** Registry entry template for provider factory functions. */
interface MemoryProviderEntry<Config> {
name: string;
create(config: Config): MemoryProviderRegistration;
}
/**
* @file V3 Memory Provider Errors
*
* Standardized error hierarchy for memory provider operations.
* Every provider adapter must throw these instead of raw errors.
*/
/** Base class for all provider errors. */
declare class MemoryProviderError extends Error {
readonly provider: string;
readonly operation: string;
readonly cause?: Error | undefined;
constructor(message: string, provider: string, operation: string, cause?: Error | undefined);
}
/** Caller invoked an extension the provider does not support. */
declare class UnsupportedOperationError extends MemoryProviderError {
constructor(provider: string, operation: string);
}
/** Required scope fields are missing or invalid. */
declare class InvalidScopeError extends MemoryProviderError {
constructor(provider: string, missing: string[]);
}
/**
* Transport-layer failure reaching the provider — connection refused,
* timeout, DNS failure, abort, etc. Named `MemoryTransportError` to avoid
* colliding with the generic `NetworkError` exported from
* `src/core/error-handling/errors.ts` (different inheritance tree).
*/
declare class MemoryTransportError extends MemoryProviderError {
readonly url: string;
readonly code: string | null;
constructor(provider: string, operation: string, url: string, cause: Error);
}
/** Provider-side rate limit or quota exceeded. */
declare class RateLimitError extends MemoryProviderError {
readonly retryAfterMs?: number;
constructor(provider: string, retryAfterMs?: number);
}
/**
* @file AtomicMemory Provider
*
* HTTP-based MemoryProvider implementation targeting the AtomicMemory
* prototype backend.
*
* Implements core operations + extensions: Packager, TemporalSearch,
* Versioner, Health.
*/
declare class AtomicMemoryProvider extends BaseMemoryProvider implements Packager, TemporalSearch, Versioner, Health {
readonly name = "atomicmemory";
private readonly http;
/**
* Prefix prepended to every core-facing route path, e.g. `/v1`.
* Empty string disables prefixing (legacy deployments only).
*/
private readonly apiPrefix;
/**
* Opt-in post-retrieval meta-fact filter. `undefined` (default) means
* filtering is off. See `MetaFactFilterConfig` and
* `benchmarks/alignbench/RESULTS.md` for motivation.
*/
private readonly metaFactFilter?;
constructor(config: AtomicMemoryProviderConfig);
/**
* Drop meta-fact entries from a SearchResult list when the filter is enabled.
*
* Called once per search-style endpoint (regular search, temporal search,
* package) so meta-facts never reach the caller. No-op when
* `this.metaFactFilter` is `undefined` or `enabled: false` — matches the
* pre-filter behaviour byte-for-byte.
*/
private applyMetaFactFilter;
/** Prepend the configured API-version prefix to a route path. */
private route;
protected doIngest(input: IngestInput): Promise<IngestResult>;
protected doSearch(request: SearchRequest): Promise<SearchResultPage>;
protected doGet(ref: MemoryRef): Promise<Memory | null>;
protected doDelete(ref: MemoryRef): Promise<void>;
protected doList(request: ListRequest): Promise<ListResultPage>;
capabilities(): Capabilities;
/**
* V3 extension discovery hook. Resolves custom extension names under the
* `atomicmemory.*` namespace to typed handles. Each key returns the
* specific handle for that category — `atomicmemory.lifecycle` returns
* an `AtomicMemoryLifecycle` (callable as `.consolidate(...)` directly),
* not the root handle. `atomicmemory.base` returns the root
* `AtomicMemoryHandle` which aggregates base routes + all category
* sub-accessors. Standard V3 extensions (`package`, `temporal`,
* `versioning`, `health`) are still accessed via interface casting on
* this class — the namespace is additive.
*/
getExtension<T = unknown>(name: string): T | undefined;
/**
* Lazily construct a single AtomicMemoryHandle instance bound to this
* provider. The handle exposes AtomicMemory-specific methods through
* named extensions instead of the backend-agnostic provider surface.
*/
private _atomicmemoryHandle?;
private atomicmemoryHandle;
package(request: PackageRequest): Promise<ContextPackage>;
searchAsOf(request: SearchRequest & {
asOf: Date;
}): Promise<SearchResultPage>;
history(ref: MemoryRef): Promise<MemoryVersion[]>;
health(): Promise<HealthStatus>;
}
/**
* @file Mem0 Provider
*
* HTTP-based MemoryProvider implementation targeting a local or hosted
* Mem0 instance (port 8888 OSS; api.mem0.ai hosted).
*
* Implements core V3 operations plus Health. Other V3 extensions
* (package, temporal, versioning, graph, etc.) are not supported by mem0.
*
* mem0 2.0 compatibility:
* - Search uses `POST /v2/memories/search/` with nested `filters` object.
* - Add response envelope is `{id, event, data: {memory}}`; legacy flat
* `{id, memory, event}` is still tolerated.
* - Enterprise scoping (`org_id`, `project_id`) is passed at top level
* when configured.
*
* Known limitation: mem0 2.0 makes `add` async-by-default and returns
* queued event IDs. For consumers that need the final extracted memories,
* polling `/v1/event/{event_id}/` is a future enhancement (tracked as
* post-v1.0 work); the current implementation returns what mem0 emits
* in the immediate response.
*/
declare class Mem0Provider extends BaseMemoryProvider implements Health {
readonly name = "mem0";
private readonly http;
private readonly config;
private readonly prefix;
constructor(config: Mem0ProviderConfig);
/** Build an API path using the configured prefix (used for /memories/ family). */
private path;
/**
* Build the path to the v2 search endpoint. mem0 2.0 split search out of the
* v1 family, so search ignores `pathPrefix` and uses `/v2/memories/search/`
* on hosted, or `/memories/search/` on OSS (when `pathPrefix === ''`).
*/
private searchPath;
protected doIngest(input: IngestInput): Promise<IngestResult>;
/**
* Fire-and-forget: re-ingest with infer=true for AUDN extraction.
* Logs errors but never blocks the caller.
*/
private fireBackgroundInference;
protected doSearch(request: SearchRequest): Promise<SearchResultPage>;
protected doGet(ref: MemoryRef): Promise<Memory | null>;
protected doDelete(ref: MemoryRef): Promise<void>;
protected doList(request: ListRequest): Promise<ListResultPage>;
/**
* Check Mem0 backend connectivity.
*
* Performs a lightweight list request with page_size=1 to verify
* the server is reachable and responding.
*/
health(): Promise<HealthStatus>;
capabilities(): Capabilities;
}
/**
* @file Mem0 Context Provider Types
*
* V2-compatible type definitions used by the webapp's Mem0SdkAdapter.
* These types bridge the gap between the webapp's expected interface
* and the V3 MemoryProvider architecture.
*/
/**
* Metadata attached to a context when adding via addContext().
* Matches the shape expected by mem0-sdk-adapter.server.ts.
*/
interface ContextMetadata {
userId: string;
source?: string;
type?: 'conversation' | 'document' | 'note' | 'preference' | string;
platform?: string;
title?: string;
url?: string;
timestamp?: number;
[key: string]: unknown;
}
/**
* Metadata attached when updating a context via updateContext().
*/
interface DocumentMetadata {
source?: string;
userId?: string;
type?: 'conversation' | 'document' | 'note' | 'preference' | string;
platform?: string;
title?: string;
url?: string;
[key: string]: unknown;
}
/**
* Configuration for the Mem0ContextProvider bridge.
*/
interface Mem0ContextProviderConfig {
/** API key for the Mem0 instance */
apiKey?: string;
/** Mem0 server base URL (e.g. "http://localhost:8888") */
host: string;
/** API style — currently only 'oss' is supported */
apiStyle: 'oss';
/** Default user ID used when no per-request userId is provided */
defaultUserId: string;
/** Request timeout in milliseconds */
timeout?: number;
/** Path prefix for API endpoints (e.g. '/v1' for hosted, '' for OSS). Defaults to '/v1'. */
pathPrefix?: string;
}
/**
* A context record returned by getContext().
*/
interface ContextRecord {
id: string;
content: string;
metadata?: Record<string, unknown>;
createdAt?: string;
updatedAt?: string;
}
/**
* A search result returned by searchContext().
*/
interface ContextSearchResult {
id: string;
contextId: string;
content: string;
/** Raw Mem0 backend score. For local OSS Mem0 this is distance-like, so lower is better. */
score: number;
metadata?: Record<string, unknown>;
}
/**
* Result from addContext(), containing the Mem0 server-assigned ID.
*/
interface AddContextResult {
/** Mem0's internal ID for the created memory. Use this for get/update/delete. */
memoryId: string;
/** The caller-supplied contextId, stored in metadata. */
contextId: string;
content: string;
}
/**
* Options for searchContext().
*/
interface ContextSearchOptions {
userId: string;
maxResults?: number;
/** Minimum similarity [0, 1]. The bridge converts this to a max allowed raw Mem0 distance. */
threshold?: number;
}
/**
* @file Mem0 Context Provider — V2-Compatible Bridge
*
* Wraps the V3 Mem0Provider HTTP layer to expose the high-level
* context-oriented interface that the webapp's Mem0SdkAdapter expects.
*
* This is NOT a V3 MemoryProvider — it is a compatibility bridge
* for consumers that import `Mem0ContextProvider` from the SDK.
*
* Methods map to Mem0 REST endpoints. Path prefix depends on apiStyle:
* - apiStyle 'oss' → /memories, /search (no version prefix)
* - apiStyle 'hosted' → /v1/memories/, /v1/search/
*/
declare class Mem0ContextProvider {
private readonly http;
private readonly config;
private readonly prefix;
private _initialized;
constructor(config: Mem0ContextProviderConfig);
/** Build an API path using the configured prefix. */
private path;
initialize(): Promise<void>;
/**
* Add a context (memory) for a user.
* Uses infer=false for verbatim storage.
*
* Returns the Mem0 server-assigned ID alongside the caller-supplied contextId.
* The memoryId is what get/update/delete operations require.
*/
addContext(contextId: string, content: string, metadata?: ContextMetadata): Promise<AddContextResult>;
/**
* Update an existing memory's content.
*/
updateContext(memoryId: string, content: string, userId: string, metadata?: DocumentMetadata): Promise<void>;
/**
* Search memories for a user.
*/
searchContext(query: string, options: ContextSearchOptions): Promise<ContextSearchResult[]>;
/**
* Get a single memory by ID. Returns null on 404.
*/
getContext(memoryId: string): Promise<ContextRecord | null>;
/**
* Delete a single memory by ID. Returns false on 404.
*/
deleteContext(memoryId: string): Promise<boolean>;
/**
* Delete all memories for a user.
*/
deleteAllContexts(options: {
userId?: string;
}): Promise<boolean>;
/**
* List all memories for a user.
*/
listContexts(options: {
userId?: string;
limit?: number;
}): Promise<ContextRecord[]>;
private assertInitialized;
}
/**
* @file Hindsight Memory Provider
*
* HTTP-backed `MemoryProvider` implementation for Hindsight Cloud or a
* self-hosted Hindsight API. The adapter keeps Hindsight-specific request and
* response shapes inside this provider while exposing the SDK's backend-neutral
* memory contract plus standard package, reflect, and health extensions.
*/
declare class HindsightProvider extends BaseMemoryProvider implements Packager, Reflector, Health {
readonly name = "hindsight";
private readonly http;
private readonly config;
private readonly apiVersion;
private readonly projectId;
private readonly retainHandle;
private readonly operationsHandle;
constructor(config: HindsightProviderConfig);
protected doIngest(input: IngestInput): Promise<IngestResult>;
protected doSearch(request: SearchRequest): Promise<SearchResultPage>;
protected doGet(ref: MemoryRef): Promise<Memory | null>;
protected doDelete(ref: MemoryRef): Promise<void>;
protected doList(request: ListRequest): Promise<ListResultPage>;
capabilities(): Capabilities;
getExtension<T = unknown>(name: string): T | undefined;
package(request: PackageRequest): Promise<ContextPackage>;
reflect(query: string, scope: Scope): Promise<Insight[]>;
health(): Promise<HealthStatus>;
private retain;
private recallRaw;
private mapListPage;
private createRetainHandle;
private createOperationsHandle;
private listOperations;
private getOperation;
private bankPath;
private memoryPath;
private route;
}
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, type AddContextResult, type AgentConflict, type AgentScope, type AtomicMemoryAgents, type AtomicMemoryAudit, type AtomicMemoryConfig, type AtomicMemoryExtensionName, type AtomicMemoryHandle, type AtomicMemoryHealthStatus, type AtomicMemoryIngestInput, type AtomicMemoryIngestResult, type AtomicMemoryLessons, type AtomicMemoryLifecycle, type AtomicMemoryListOptions, type AtomicMemoryListResultPage, type AtomicMemoryMemory, AtomicMemoryProvider, type AtomicMemoryProviderConfig, type AtomicMemorySearchRequest, type AtomicMemorySearchResult, type AtomicMemorySearchResultPage, type AuditTrailEntry, type AuditTrailResult, type AutoResolveConflictsResult, BaseMemoryProvider, type BatchOps, type CapCheckResult, type CapRecommendation, type CapStatus, type Capabilities, type ConfigUpdateResult, type ConfigUpdates, type ConflictResolution, type ConflictStatus, type ConflictsListResult, type ConsolidationExecutionResult, type ConsolidationResult, type ConsolidationScanResult, type ContextMetadata, type ContextPackage, type ContextRecord, type ContextSearchOptions, type ContextSearchResult, DEFAULT_META_FACT_PATTERNS, type DecayResult, type DocumentMetadata, type EmbeddingProviderName, type FieldFilter, type FilterExpr, type Forgetter, type GetTrustResult, type GraphEdge, type GraphNode, type GraphResult, type GraphSearch, type GraphSearchRequest, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, type Health, type HealthConfig, type HealthStatus, type HindsightOperation, type HindsightOperationsHandle, type HindsightOperationsPage, HindsightProvider, type HindsightProviderConfig, type HindsightRecallBudget, type HindsightRetainHandle, type HindsightRetainItem, type HindsightRetainRequest, type HindsightRetainResponse, type HindsightTagsMatch, type IngestBase, type IngestInput, type IngestResult, type Insight, InvalidScopeError, type LLMProviderName, type Lesson, type LessonSeverity, type LessonStats, type LessonType, type LessonsListResult, type ListRequest, type ListResultPage, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, type Mem0ContextProviderConfig, Mem0Provider, type Mem0ProviderConfig, type Memory, type MemoryKind, type MemoryProcessingPipeline, type MemoryProvider, type MemoryProviderEntry, MemoryProviderError, type MemoryProviderRegistration, type MemoryRef, type MemoryScope, MemoryTransportError, type MemoryVersion, type Message, type MessageIngest, type MetaFactFilterConfig, type MutationRecord, type MutationSummary, type MutationType, type PackageRequest, type Packager, type Profile, type Profiler, type Provenance, RateLimitError, type RecentMutationsResult, type ReconcileStatus, type ReconciliationResult, type Reflector, type ResetSourceResult, type ResolveConflictResult, type Scope, type SearchRequest, type SearchResult, type SearchResultPage, type SetTrustResult, type StatsResult, type TemporalSearch, type TextIngest, UnsupportedOperationError, type Updater, type VerbatimIngest, type Versioner, filterMetaFacts, isMetaFact, noopMemoryPipeline, resolveMetaFactPatterns };
export { Capabilities, type CapabilityGap, type CapabilityProfile, IngestInput, capabilityGaps, satisfiesProfile };

@@ -1,1673 +0,52 @@

/**
* @file V3 Memory Provider Types
*
* Core type definitions for the unified MemoryProvider interface.
* Based on the accepted V3 specification (providers-v3.md).
*
* Pure types — no runtime code.
*/
/**
* Identity and partition context for memory operations.
* Providers declare which fields they require via capabilities().requiredScope.
*/
interface Scope {
user?: string;
agent?: string;
namespace?: string;
thread?: string;
}
/**
* Reference to a specific memory within a scope.
*/
interface MemoryRef {
id: string;
scope: Scope;
}
/**
* A single memory unit. Returned by get, list, and as part of SearchResult.
*/
interface Memory {
id: string;
content: string;
scope: Scope;
kind?: MemoryKind;
createdAt: Date;
updatedAt?: Date;
provenance?: Provenance;
metadata?: Record<string, unknown>;
}
type MemoryKind = 'fact' | 'episode' | 'summary' | 'procedure' | 'document';
interface Provenance {
source?: string;
sourceUrl?: string;
sourceId?: string;
extractor?: string;
}
type IngestInput = TextIngest | MessageIngest | VerbatimIngest;
interface IngestBase {
scope: Scope;
provenance?: Provenance;
metadata?: Record<string, unknown>;
}
/** Raw text: conversation transcript, document, note. */
interface TextIngest extends IngestBase {
mode: 'text';
content: string;
}
/** Structured chat messages. */
interface MessageIngest extends IngestBase {
mode: 'messages';
messages: Message[];
}
/**
* Verbatim storage: bypass LLM extraction and store the content as a
* single memory record. One input = one memory, deterministic. Use for
* user-provided context blobs where the fact-extraction pipeline
* would either over-split the text or, for ambiguous input, produce
* zero facts and leave the user thinking nothing was saved.
*
* Capability-gated: only available when
* `capabilities().ingestModes` includes 'verbatim'.
*/
interface VerbatimIngest extends IngestBase {
mode: 'verbatim';
content: string;
kind?: MemoryKind;
metadata?: Record<string, unknown>;
}
interface Message {
role: 'user' | 'assistant' | 'system' | 'tool';
content: string;
name?: string;
}
interface IngestResult {
created: string[];
updated: string[];
unchanged: string[];
}
interface SearchRequest {
query: string;
scope: Scope;
limit?: number;
threshold?: number;
filter?: FilterExpr;
reranker?: string;
}
interface SearchResult {
memory: Memory;
/**
* Backward-compatible provider score.
* For AtomicMemory this is the composite ranking score (`rankingScore`) and
* is not normalized. New consumers should prefer the explicit fields below.
* Other providers preserve their historical score semantics.
*/
score: number;
/** Semantic/vector similarity when the provider exposes it. Higher is better. */
similarity?: number;
/** Composite ranking/debug score. Not guaranteed to be normalized. */
rankingScore?: number;
/** Normalized injection relevance in [0, 1], suitable for threshold checks. */
relevance?: number;
}
interface SearchResultPage {
results: SearchResult[];
cursor?: string;
}
type FilterExpr = {
and: FilterExpr[];
} | {
or: FilterExpr[];
} | {
not: FilterExpr;
} | FieldFilter;
interface FieldFilter {
field: string;
op: 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'in' | 'contains' | 'exists';
value?: string | number | boolean | Date | Array<string | number>;
}
interface ListRequest {
scope: Scope;
limit?: number;
cursor?: string;
filter?: FilterExpr;
}
interface ListResultPage {
memories: Memory[];
cursor?: string;
}
interface PackageRequest extends SearchRequest {
tokenBudget?: number;
format?: 'flat' | 'tiered' | 'structured';
}
/**
* Injection-ready context for an AI assistant.
* `text` is the formatted string for prompt injection.
* `results` tracks what contributed (for debugging and attribution).
* `budgetConstrained` is true when the requested token budget shaped
* the package — either eligible memories were omitted entirely or
* eligible richer detail (L1/L2 tier, query-term-revealing upgrades)
* was suppressed solely because the budget could not afford it.
* Quota-driven demotion (e.g. fixed-cap policy) is NOT flagged.
* Powers the v5 CLI envelope's `meta.budget_constrained` field.
*/
interface ContextPackage {
text: string;
results: SearchResult[];
tokens: number;
budgetConstrained: boolean;
}
interface Capabilities {
ingestModes: Array<IngestInput['mode']>;
requiredScope: {
default: Array<keyof Scope>;
ingest?: Array<keyof Scope>;
search?: Array<keyof Scope>;
get?: Array<keyof Scope>;
delete?: Array<keyof Scope>;
list?: Array<keyof Scope>;
update?: Array<keyof Scope>;
package?: Array<keyof Scope>;
temporal?: Array<keyof Scope>;
graph?: Array<keyof Scope>;
forget?: Array<keyof Scope>;
profile?: Array<keyof Scope>;
reflect?: Array<keyof Scope>;
versioning?: Array<keyof Scope>;
batch?: Array<keyof Scope>;
};
extensions: {
update: boolean;
package: boolean;
temporal: boolean;
graph: boolean;
forget: boolean;
profile: boolean;
reflect: boolean;
versioning: boolean;
batch: boolean;
health: boolean;
};
customExtensions?: Record<string, {
version?: string;
description?: string;
}>;
supportedRerankers?: string[];
supportedFilterOps?: FieldFilter['op'][];
maxTokenBudget?: number;
}
interface GraphSearchRequest {
query: string;
scope: Scope;
limit?: number;
graphScope?: 'nodes' | 'edges' | 'episodes';
reranker?: string;
}
interface GraphResult {
nodes: GraphNode[];
edges: GraphEdge[];
}
interface GraphNode {
id: string;
label: string;
summary?: string;
score?: number;
}
interface GraphEdge {
id: string;
fact: string;
from: string;
to: string;
validAt?: Date;
invalidAt?: Date;
score?: number;
}
interface Profile {
summary: string;
facts?: string[];
updatedAt?: Date;
}
interface Insight {
content: string;
confidence: number;
supportingMemoryIds: string[];
}
interface MemoryVersion {
id: string;
content: string;
createdAt: Date;
parentId?: string;
event: 'created' | 'updated' | 'superseded' | 'invalidated';
}
interface HealthStatus {
ok: boolean;
latencyMs?: number;
version?: string;
}
import { ap as IngestInput, F as Capabilities } from './hindsight-provider-CbfXnvx7.js';
export { A as ATOMICMEMORY_DEFAULT_TIMEOUT, a as ATOMICMEMORY_EXTENSION_NAMES, b as AddContextResult, c as AgentConflict, d as AgentScope, e as AtomicMemoryAgents, f as AtomicMemoryAudit, g as AtomicMemoryConfig, h as AtomicMemoryExtensionName, i as AtomicMemoryHandle, j as AtomicMemoryHealthStatus, k as AtomicMemoryIngestInput, l as AtomicMemoryIngestResult, m as AtomicMemoryLessons, n as AtomicMemoryLifecycle, o as AtomicMemoryListOptions, p as AtomicMemoryListResultPage, q as AtomicMemoryMemory, r as AtomicMemoryProvider, s as AtomicMemoryProviderConfig, t as AtomicMemorySearchRequest, u as AtomicMemorySearchResult, v as AtomicMemorySearchResultPage, w as AuditTrailEntry, x as AuditTrailResult, y as AutoResolveConflictsResult, B as BaseMemoryProvider, z as BatchOps, C as CapCheckResult, D as CapRecommendation, E as CapStatus, G as ConfigUpdateResult, H as ConfigUpdates, I as ConflictResolution, J as ConflictStatus, K as ConflictsListResult, L as ConsolidationExecutionResult, M as ConsolidationResult, N as ConsolidationScanResult, O as ContentClass, P as ContextMetadata, Q as ContextPackage, R as ContextRecord, S as ContextSearchOptions, T as ContextSearchResult, U as DEFAULT_META_FACT_PATTERNS, V as DecayResult, W as DocumentMetadata, X as EmbeddingProviderName, Y as FieldFilter, Z as FilterExpr, _ as Forgetter, $ as GetTrustResult, a0 as GraphEdge, a1 as GraphNode, a2 as GraphResult, a3 as GraphSearch, a4 as GraphSearchRequest, a5 as HINDSIGHT_DEFAULT_API_VERSION, a6 as HINDSIGHT_DEFAULT_MAX_TOKENS, a7 as HINDSIGHT_DEFAULT_PROJECT_ID, a8 as HINDSIGHT_DEFAULT_TIMEOUT, a9 as HINDSIGHT_SCOPE_TAGS_MATCH, aa as Health, ab as HealthConfig, ac as HealthStatus, ad as HindsightOperation, ae as HindsightOperationsHandle, af as HindsightOperationsPage, ag as HindsightProvider, ah as HindsightProviderConfig, ai as HindsightRecallBudget, aj as HindsightRetainHandle, ak as HindsightRetainItem, al as HindsightRetainRequest, am as HindsightRetainResponse, an as HindsightTagsMatch, ao as IngestBase, aq as IngestResult, ar as Insight, as as InvalidScopeError, at as LLMProviderName, au as Lesson, av as LessonSeverity, aw as LessonStats, ax as LessonType, ay as LessonsListResult, az as ListRequest, aA as ListResultPage, aB as MEM0_DEFAULT_TIMEOUT, aC as Mem0ContextProvider, aD as Mem0ContextProviderConfig, aE as Mem0Provider, aF as Mem0ProviderConfig, aG as Memory, aH as MemoryKind, aI as MemoryProcessingPipeline, aJ as MemoryProvider, aK as MemoryProviderEntry, aL as MemoryProviderError, aM as MemoryProviderRegistration, aN as MemoryRef, aO as MemoryScope, aP as MemoryTransportError, aQ as MemoryVersion, aR as Message, aS as MessageIngest, aT as MetaFactFilterConfig, aU as MutationRecord, aV as MutationSummary, aW as MutationType, aX as PackageRequest, aY as Packager, aZ as Profile, a_ as Profiler, a$ as Provenance, b0 as RateLimitError, b1 as RecentMutationsResult, b2 as ReconcileStatus, b3 as ReconciliationResult, b4 as Reflector, b5 as ResetSourceResult, b6 as ResolveConflictResult, b7 as RetrievalReceipt, b8 as Scope, b9 as SearchRequest, ba as SearchResult, bb as SearchResultPage, bc as SetTrustResult, bd as StatsResult, be as TemporalSearch, bf as TextIngest, bg as UnsupportedOperationError, bh as Updater, bi as VerbatimIngest, bj as Versioner, bk as filterMetaFacts, bl as isMetaFact, bm as noopMemoryPipeline, bn as resolveMetaFactPatterns } from './hindsight-provider-CbfXnvx7.js';
/**
* @file V3 Memory Provider Interface and Base Class
* @file Capability profiles
*
* Defines the MemoryProvider interface, standard extension interfaces,
* and the BaseMemoryProvider abstract class with runOperation() enforcement.
*/
interface MemoryProvider {
readonly name: string;
initialize?(): Promise<void>;
close?(): Promise<void>;
ingest(input: IngestInput): Promise<IngestResult>;
search(request: SearchRequest): Promise<SearchResultPage>;
get(ref: MemoryRef): Promise<Memory | null>;
delete(ref: MemoryRef): Promise<void>;
list(request: ListRequest): Promise<ListResultPage>;
capabilities(): Capabilities;
getExtension?<T = unknown>(name: string): T | undefined;
}
interface Updater {
update(ref: MemoryRef, content: string): Promise<Memory>;
}
interface Packager {
package(request: PackageRequest): Promise<ContextPackage>;
}
interface TemporalSearch {
searchAsOf(request: SearchRequest & {
asOf: Date;
}): Promise<SearchResultPage>;
}
interface GraphSearch {
searchGraph(request: GraphSearchRequest): Promise<GraphResult>;
}
interface Forgetter {
forget(ref: MemoryRef, reason?: string): Promise<void>;
}
interface Profiler {
profile(scope: Scope, instructions?: string[]): Promise<Profile>;
}
interface Reflector {
reflect(query: string, scope: Scope): Promise<Insight[]>;
}
interface Versioner {
history(ref: MemoryRef): Promise<MemoryVersion[]>;
}
interface BatchOps {
batchIngest(inputs: IngestInput[]): Promise<IngestResult[]>;
batchDelete(refs: MemoryRef[]): Promise<void>;
}
interface Health {
health(): Promise<HealthStatus>;
}
declare abstract class BaseMemoryProvider implements MemoryProvider {
abstract readonly name: string;
/** Override to `false` in constructor to require async init. */
protected initialized: boolean;
protected abstract doIngest(input: IngestInput): Promise<IngestResult>;
protected abstract doSearch(request: SearchRequest): Promise<SearchResultPage>;
protected abstract doGet(ref: MemoryRef): Promise<Memory | null>;
protected abstract doDelete(ref: MemoryRef): Promise<void>;
protected abstract doList(request: ListRequest): Promise<ListResultPage>;
abstract capabilities(): Capabilities;
/**
* Generic enforcement for core AND extension operations.
* Validates readiness and scope, wraps errors.
*/
protected runOperation<T>(operation: string, scope: Scope | undefined, fn: () => Promise<T>): Promise<T>;
ingest(input: IngestInput): Promise<IngestResult>;
search(request: SearchRequest): Promise<SearchResultPage>;
get(ref: MemoryRef): Promise<Memory | null>;
delete(ref: MemoryRef): Promise<void>;
list(request: ListRequest): Promise<ListResultPage>;
/**
* Default extension resolution: checks capabilities().extensions
* and returns `this` for supported standard extensions.
* Subclasses override for custom extensions.
*/
protected resolveExtension(name: string): unknown | undefined;
getExtension<T = unknown>(name: string): T | undefined;
protected assertReady(): void;
protected validateScope(scope: Scope, operation: string): void;
protected wrapError(operation: string, err: unknown): Error;
}
/**
* @file MetaFactFilter
* A capability profile is the minimum {@link Capabilities} a
* {@link MemoryProvider} must satisfy for a given consumer's needs (for
* example, an audited ingest→search→replay path that requires deterministic
* verbatim storage and version pinning). It is expressed as a typed, partial
* requirement set so a caller can gate a provider at wiring time with an
* actionable diff instead of an opaque boolean.
*
* Post-retrieval filter that drops "meta-facts" — extraction artifacts that
* describe the conversation itself rather than recording a durable fact about
* the user.
*
* Empirically motivated by AlignBench v0 (benchmarks/alignbench/RESULTS.md):
* when extraction-style meta-facts ("The user asked for the user's name.",
* "As of <date>, X is a term mentioned in the conversation.") sit in the
* recall pool alongside real user facts, they often outrank the real fact
* for pronoun and temporal queries — at thin cosine margins (~0.05). The
* pre-registered "fix the query side" hypothesis was falsified; the dominant
* fixable lift came from removing meta-facts from the pool.
*
* Long-term, core should not emit these facts at extraction time. This
* SDK-side filter is the safety net so apps consuming the SDK today see
* cleaner recall results without waiting on a core release.
*
* Default patterns target the verbatim shapes observed in partner demos.
* Apps can extend or replace them via
* `MetaFactFilterConfig.patterns`.
*
* This filter is intentionally:
* - pure (no I/O, no LLM calls — deterministic regex application);
* - opt-in (off unless explicitly enabled in provider config);
* - case-insensitive;
* - additive (apps may add patterns without losing the defaults).
* The SDK ships the generic mechanism; each consumer defines its own profile
* constant against this type. Pure runtime code — no I/O, no provider
* construction.
*/
/**
* Built-in patterns observed in real partner demos. Each is a case-insensitive
* regex matched against the memory's content. A match drops the memory from
* the result set.
*
* Patterns capture the three meta-fact families that AlignBench's distractor
* pool was built from:
* 1. "The user asked/requested/said …" — meta-facts about user actions in
* the conversation, not about the user.
* 2. "As of <date>, X is a term mentioned in the conversation." — vacuous
* acknowledgements of vocabulary, not durable facts.
* 3. "A name was mentioned." / "The conversation involves the user." —
* observations about the chat session, not about the user.
*/
declare const DEFAULT_META_FACT_PATTERNS: readonly RegExp[];
interface MetaFactFilterConfig {
/**
* Master switch. When `false` (the default), the filter is a no-op and
* all results pass through.
*
* Apps explicitly opt in by setting `true`. We do not infer this from
* environment variables in the SDK to keep behaviour deterministic across
* Node / browser / Workers runtimes.
*/
enabled: boolean;
/**
* Patterns to match against `memory.content`. When omitted, the built-in
* `DEFAULT_META_FACT_PATTERNS` are used.
*
* When `mode === 'replace'` (the default when `patterns` is set), only the
* provided patterns are applied. Set `mode: 'extend'` to apply the provided
* patterns *and* the built-in defaults.
*/
patterns?: readonly RegExp[];
/**
* How `patterns` interacts with `DEFAULT_META_FACT_PATTERNS`. Defaults to
* `'replace'` (the provided list fully replaces defaults). `'extend'` is
* the union — useful when an app wants to add its own meta-fact shapes
* without losing the SDK's baseline coverage.
*/
mode?: 'replace' | 'extend';
/**
* Optional callback invoked once per dropped result. Useful for telemetry
* or tests. Receives the memory content and the pattern index that matched.
* Exceptions thrown by `onDrop` are swallowed so they cannot break recall.
*/
onDrop?: (content: string, patternIndex: number) => void;
}
/**
* Resolve the effective pattern list for a config.
*
* Pure; safe to call repeatedly. Used in two places — at filter time, and
* in tests that want to introspect the effective rule set without filtering
* a result list.
*/
declare function resolveMetaFactPatterns(config: MetaFactFilterConfig): readonly RegExp[];
/**
* Return `true` when `content` matches any of `patterns`.
*
* Defensive against non-string input (returns `false`) so a malformed result
* doesn't crash the filter pipeline.
*/
declare function isMetaFact(content: unknown, patterns?: readonly RegExp[]): boolean;
/**
* Filter a list of items by removing entries whose `getContent(item)` matches
* any active meta-fact pattern.
*
* Generic over `T` so callers can filter `SearchResult` / `Memory` / raw
* backend shapes with the same primitive. Pure and synchronous.
*/
declare function filterMetaFacts<T>(items: readonly T[], getContent: (item: T) => unknown, config: MetaFactFilterConfig): T[];
/**
* @file AtomicMemory Provider Configuration
*/
interface AtomicMemoryProviderConfig {
/** Base URL of the atomicmemory-core instance, e.g. `http://localhost:17350`. */
apiUrl: string;
/** Optional bearer token forwarded as `Authorization: Bearer <apiKey>`. */
apiKey?: string;
/** Request timeout in milliseconds. Defaults to 30_000. */
timeout?: number;
/** A minimum capability requirement set a provider must satisfy. */
interface CapabilityProfile {
/** Ingest modes the provider must support (e.g. `'text'`, `'verbatim'`). */
ingestModes: ReadonlyArray<IngestInput['mode']>;
/**
* API version segment prepended to every core-facing route path.
*
* Core mounts its routers under `/v1/memories` and `/v1/agents` (see
* atomicmemory-core/src/app/create-app.ts:31-32). The SDK prepends
* `/${apiVersion}` to all route calls so hitting a pre-v1 deployment
* or future versioned deployments only requires a config change, not
* a code change.
*
* Defaults to `'v1'` — the current mount point on core. Pass `''` to
* disable prefixing entirely (useful only against legacy deployments
* that never versioned their mount).
* Extension flags the provider must expose (`extensions.<flag> === true`).
* `search` is not listed here — it is a core method every `MemoryProvider`
* implements, so it is implied rather than gated.
*/
apiVersion?: string;
/**
* Opt-in post-retrieval filter that drops extraction-style meta-facts
* (e.g. "The user asked for the user's name.", "As of <date>, X is a term
* mentioned in the conversation.") before they reach the caller.
*
* Empirically motivated by `benchmarks/alignbench/RESULTS.md`: meta-facts
* are the dominant cause of partner-visible recall failures, outranking
* real user facts at thin cosine margins. Filtering them post-hoc gives
* cleaner search results today while a durable upstream extraction-prompt
* fix rolls out in core.
*
* When omitted, the filter is OFF and behaviour is unchanged. Set
* `{ enabled: true }` to activate with the built-in pattern set, or pass
* additional `patterns` / `mode` per `MetaFactFilterConfig`.
*/
metaFactFilter?: MetaFactFilterConfig;
extensions: ReadonlyArray<keyof Capabilities['extensions']>;
}
/** Default timeout for AtomicMemory provider HTTP requests (ms). */
declare const ATOMICMEMORY_DEFAULT_TIMEOUT = 30000;
/**
* @file AtomicMemory-specific namespaced handle
*
* Registered as `customExtensions['atomicmemory.*']` on AtomicMemoryProvider
* per V3 spec (docs/providers-v3.md:391-402). Typed access via
* `sdk.atomicmemory.*` on an SDK configured with an AtomicMemoryProvider.
*
* The namespace is a route-shaped HTTP binding for atomicmemory-core —
* request types are semantically aligned with core's parseIngestBody /
* parseSearchBody (SDK idiomatic camelCase + JS-native types; wire format
* snake_case mapping happens in the handle implementation).
*
* V3 `Scope` is intentionally NOT embedded in these request types — scope
* is always a separate argument using `MemoryScope` (the AtomicMemory-
* specific discriminated union below) so workspace semantics are honest
* per-method.
* A single unmet capability requirement, for actionable provider-rejection
* errors.
*/
/**
* Agent visibility scope for workspace reads.
*
* Matches core's `parseOptionalAgentScope`
* (atomicmemory-core/src/routes/memories.ts:617-627):
* - `'all'` | `'self'` | `'others'` — the three canonical modes.
* - any other string — treated as a single `agent_id` filter.
* - `string[]` — a specific list of agent IDs to include.
*
* The `(string & {})` branch preserves the three literal hints in IDE
* autocomplete while still permitting arbitrary strings.
*/
type AgentScope = 'all' | 'self' | 'others' | (string & {}) | string[];
/**
* AtomicMemory's canonical read-path contract. Mirrors core's `MemoryScope`
* at `atomicmemory-core/src/services/memory-service-types.ts:142-144`.
*/
type MemoryScope = {
kind: 'user';
userId: string;
thread?: string;
} | {
kind: 'workspace';
userId: string;
workspaceId: string;
agentId: string;
thread?: string;
agentScope?: AgentScope;
};
interface AtomicMemoryIngestInput {
/** Required, flat conversation string per core's parseIngestBody:517. */
conversation: string;
/** Required by core's parseIngestBody:518. */
sourceSite: string;
sourceUrl?: string;
/**
* Workspace write-time visibility label. Only honored when
* `scope.kind === 'workspace'`; runtime validation throws InputError
* if set with user scope.
*/
visibility?: 'agent_only' | 'restricted' | 'workspace';
/** Per-request core runtime override for benchmark and diagnostic runs. */
configOverride?: Record<string, unknown>;
interface CapabilityGap {
/** Which requirement category is unmet. */
kind: 'ingestMode' | 'extension';
/** The specific ingest mode or extension flag that is missing. */
requirement: string;
/** Human-readable reason the requirement is unmet. */
detail: string;
}
interface AtomicMemorySearchRequest {
query: string;
limit?: number;
/** Normalized relevance floor forwarded to core's `threshold` request field. */
threshold?: number;
/** Temporal filter. Honored by `/memories/search` full path; NOT by fast. */
asOf?: Date;
retrievalMode?: 'flat' | 'tiered' | 'abstract-aware';
tokenBudget?: number;
namespaceScope?: string;
sourceSite?: string;
skipRepair?: boolean;
/** Per-request core runtime override for benchmark and diagnostic runs. */
configOverride?: Record<string, unknown>;
}
interface AtomicMemoryListOptions {
limit?: number;
offset?: number;
/** User-scope only; ignored for workspace scope. */
sourceSite?: string;
/** User-scope only; ignored for workspace scope. */
episodeId?: string;
}
/**
* AtomicMemory-specific memory shape. Distinct from V3's flat `Memory` so
* the namespace can preserve the full `MemoryScope` discriminated union
* (including `workspaceId` / `agentId` / `agentScope`) on returned
* memories — V3's `Scope` type has no place for workspace fields, so a
* V3 Memory coming back from a workspace query would silently forget it
* was scoped to a workspace.
* Return every requirement in `profile` that `caps` fails to satisfy. An empty
* array means the provider satisfies the profile. Use this to build actionable
* errors ("provider X is missing verbatim ingest, missing versioning
* extension") instead of an opaque boolean rejection.
*/
interface AtomicMemoryMemory {
id: string;
content: string;
scope: MemoryScope;
createdAt: Date;
updatedAt?: Date;
importance?: number;
sourceSite?: string;
sourceUrl?: string;
episodeId?: string;
/** Workspace write-time visibility label on the stored memory. */
visibility?: 'agent_only' | 'restricted' | 'workspace';
metadata?: Record<string, unknown>;
}
interface AtomicMemorySearchResult {
memory: AtomicMemoryMemory;
/** Backward-compatible alias for `rankingScore` when core emits it. */
score: number;
/** Semantic/vector similarity when emitted by core. */
similarity?: number;
/** Composite ranking/debug score from core's retrieval pipeline. Not normalized. */
rankingScore?: number;
/** Normalized injection relevance in [0, 1]. */
relevance?: number;
/** AtomicMemory's 0–1 importance weighting on the source memory. */
importance?: number;
}
/**
* Response shape for `/memories/search` and `/memories/search/fast`.
* Mirrors core's `formatSearchResponse` (memories.ts:721-767) but with
* SDK-idiomatic camelCase and wrapped memories (raw core response uses
* snake_case and inline memory fields).
*/
interface AtomicMemorySearchResultPage {
count: number;
retrievalMode: string;
scope: MemoryScope;
results: AtomicMemorySearchResult[];
injectionText?: string;
citations?: string[];
tierAssignments?: Array<{
memoryId: string;
tier: string;
estimatedTokens: number;
}>;
expandIds?: string[];
estimatedContextTokens?: number;
lessonCheck?: {
safe: boolean;
warnings: unknown[];
highestSeverity: string;
matchedCount: number;
};
consensus?: {
originalCount: number;
filteredCount: number;
removedCount: number;
removedMemoryIds: string[];
};
observability?: {
retrieval?: unknown;
packaging?: unknown;
assembly?: unknown;
};
}
/**
* Response shape for `/memories/ingest` and `/memories/ingest/quick`.
* Mirrors core's `IngestResult` (memory-service-types.ts:91-101) with
* SDK-idiomatic camelCase.
*
* IDs are split by outcome: `storedMemoryIds` for newly created memories,
* `updatedMemoryIds` for mutated ones. Length of each array matches its
* corresponding `memoriesStored` / `memoriesUpdated` count.
*/
interface AtomicMemoryIngestResult {
episodeId: string;
factsExtracted: number;
memoriesStored: number;
memoriesUpdated: number;
memoriesDeleted: number;
memoriesSkipped: number;
storedMemoryIds: string[];
updatedMemoryIds: string[];
linksCreated: number;
compositesCreated: number;
}
/**
* Response shape for `/memories/list`.
* Core returns `{ memories, count }`; cursor is derived from offset+limit.
*/
interface AtomicMemoryListResultPage {
memories: AtomicMemoryMemory[];
count: number;
cursor?: string;
}
/**
* Scan-only response from `POST /memories/consolidate` when `execute: false`
* (the default). Mirrors core's `ConsolidationResult`
* (consolidation-service.ts).
*/
interface ConsolidationScanResult {
memoriesScanned: number;
clustersFound: number;
memoriesInClusters: number;
/**
* Cluster candidates identified by the scan. The per-cluster shape is
* internal to core's consolidation engine and is intentionally typed as
* `unknown[]` at the SDK boundary — consumers that need to inspect
* cluster internals should pin a core version and read the shape from
* there.
*/
clusters: unknown[];
}
/**
* Execution response from `POST /memories/consolidate` when `execute: true`.
* Mirrors core's `ConsolidationExecutionResult`.
*/
interface ConsolidationExecutionResult {
clustersConsolidated: number;
memoriesArchived: number;
memoriesCreated: number;
consolidatedMemoryIds: string[];
}
/**
* Union returned by `lifecycle.consolidate`. Discriminated by the presence
* of `consolidatedMemoryIds` (execution) vs `clusters` (scan-only).
*/
type ConsolidationResult = ConsolidationScanResult | ConsolidationExecutionResult;
/**
* Response from `POST /memories/decay`. Mirrors core's `DecayResult` plus
* the `archived` field added by the route handler (memories.ts:327/330).
*/
interface DecayResult {
memoriesEvaluated: number;
candidatesForArchival: Array<{
id: string;
retentionScore: number;
[key: string]: unknown;
}>;
retentionThreshold: number;
avgRetentionScore: number;
/**
* Count of memories actually archived. Non-zero only when `dryRun=false`
* and the scan found candidates (memories.ts:325-330).
*/
archived: number;
}
/**
* Mirrors core's `CapStatus` at memory-lifecycle.ts:133.
* `warn` = approaching the cap (usageRatio >= warnRatio, default 0.8).
* `exceeded` = over the cap.
*/
type CapStatus = 'ok' | 'warn' | 'exceeded';
type CapRecommendation = 'none' | 'consolidate' | 'decay' | 'consolidate-and-decay';
/**
* Response from `GET /memories/cap`. Mirrors core's `CapCheckResult`
* (memory-lifecycle.ts).
*/
interface CapCheckResult {
activeMemories: number;
maxMemories: number;
status: CapStatus;
usageRatio: number;
recommendation: CapRecommendation;
}
/**
* Response from `GET /memories/stats`. Core delegates to
* `MemoryStore.getMemoryStats(userId)` which is an open shape; typed as
* an index signature at the SDK boundary.
*/
interface StatsResult {
[key: string]: unknown;
}
/**
* Response from `POST /memories/reset-source`. Route handler wraps
* `resetBySource` with `{ success: true, ... }` (memories.ts:424).
*/
interface ResetSourceResult {
success: true;
deletedMemories: number;
deletedEpisodes: number;
}
/**
* Response from `POST /memories/reconcile`. Mirrors core's
* `ReconciliationResult` (deferred-audn.ts).
*/
interface ReconciliationResult {
processed: number;
resolved: number;
noops: number;
updates: number;
supersedes: number;
deletes: number;
adds: number;
errors: number;
durationMs: number;
}
/**
* Response from `GET /memories/reconcile/status`. Core returns an open
* shape from `getReconciliationStatus`; typed as index signature here.
*/
interface ReconcileStatus {
[key: string]: unknown;
}
/**
* Admin lifecycle operations. Workspace scope is not accepted by any of
* these routes — core parses `user_id` only (memories.ts:304, :322,
* :340, :251, :421, :409).
*
* Exception: core's `POST /memories/reconcile` also accepts an all-users
* batch-job mode (no `user_id` in the body; see memories.ts:397-400).
* The SDK splits that into an explicit `reconcileAll()` method so the
* all-users admin operation can't happen by accident from a missing
* argument.
*/
interface AtomicMemoryLifecycle {
consolidate(userId: string, execute?: boolean): Promise<ConsolidationResult>;
decay(userId: string, dryRun?: boolean): Promise<DecayResult>;
cap(userId: string): Promise<CapCheckResult>;
stats(userId: string): Promise<StatsResult>;
resetSource(userId: string, sourceSite: string): Promise<ResetSourceResult>;
/** Run deferred-AUDN reconciliation for a single user. */
reconcile(userId: string): Promise<ReconciliationResult>;
/**
* Run deferred-AUDN reconciliation across all users (batch-job mode).
* Maps to `POST /memories/reconcile` with no `user_id` in the body,
* which core routes to `reconcileDeferredAll()`
* (memories.ts:397-400). Intentionally exposed as a separate method
* so callers can't trigger the all-users pass by forgetting a
* `userId` argument.
*/
reconcileAll(): Promise<ReconciliationResult>;
reconcileStatus(userId: string): Promise<ReconcileStatus>;
}
/**
* Mirrors core's `MutationType` at
* atomicmemory-core/src/db/repository-types.ts.
*/
type MutationType = 'add' | 'update' | 'supersede' | 'delete' | 'clarify';
/**
* Aggregate mutation statistics. Mirrors core's `MutationSummary`
* (db/repository-types.ts). Emitted verbatim by GET /memories/audit/summary.
*/
interface MutationSummary {
totalVersions: number;
activeVersions: number;
supersededVersions: number;
totalClaims: number;
byMutationType: Record<string, number>;
}
/**
* A single mutation record from `GET /memories/audit/recent`.
*
* The core route returns raw `ClaimVersionRow[]` (snake_case DB rows);
* the SDK normalizes to camelCase so consumers aren't straddling two
* conventions. `createdAt`, `validFrom`, and `validTo` are `Date`
* values (deserialized from the wire ISO strings).
*/
interface MutationRecord {
id: string;
claimId: string;
userId: string;
memoryId: string | null;
content: string;
mutationType: MutationType | null;
mutationReason: string | null;
actorModel: string | null;
contradictionConfidence: number | null;
previousVersionId: string | null;
supersededByVersionId: string | null;
validFrom: Date;
validTo: Date | null;
createdAt: Date;
}
/** Response shape for `GET /memories/audit/recent`. */
interface RecentMutationsResult {
mutations: MutationRecord[];
count: number;
}
/**
* Single-memory audit trail entry. Mirrors core's `AuditTrailEntry`
* (db/repository-types.ts) verbatim — the service already emits
* camelCase for this one (memory-crud.ts getAuditTrail).
*/
interface AuditTrailEntry {
versionId: string;
claimId: string;
content: string;
mutationType: MutationType | null;
mutationReason: string | null;
actorModel: string | null;
contradictionConfidence: number | null;
previousVersionId: string | null;
supersededByVersionId: string | null;
validFrom: Date;
validTo: Date | null;
memoryId: string | null;
}
/** Response shape for `GET /memories/:id/audit`. */
interface AuditTrailResult {
memoryId: string;
trail: AuditTrailEntry[];
versionCount: number;
}
interface AtomicMemoryAudit {
/** `GET /memories/audit/summary` — aggregate mutation statistics for a user. */
summary(userId: string): Promise<MutationSummary>;
/** `GET /memories/audit/recent` — newest-first mutation records for a user. */
recent(userId: string, limit?: number): Promise<RecentMutationsResult>;
/** `GET /memories/:id/audit` — full version trail for a single memory. */
trail(memoryId: string, userId: string): Promise<AuditTrailResult>;
}
/**
* Mirrors core's `LessonType` at
* atomicmemory-core/src/db/repository-lessons.ts:16-22.
*/
type LessonType = 'injection_blocked' | 'false_memory' | 'contradiction_pattern' | 'user_reported' | 'consensus_violation' | 'trust_violation';
/**
* Mirrors core's `LessonSeverity` at
* atomicmemory-core/src/db/repository-lessons.ts:24.
*/
type LessonSeverity = 'low' | 'medium' | 'high' | 'critical';
/**
* A single lesson. Mirrors core's `LessonRow`
* (db/repository-lessons.ts:26-38), normalized to camelCase + Date on
* the SDK boundary.
*/
interface Lesson {
id: string;
userId: string;
lessonType: LessonType;
pattern: string;
embedding: number[];
sourceMemoryIds: string[];
sourceQuery: string | null;
severity: LessonSeverity;
active: boolean;
metadata: Record<string, unknown>;
createdAt: Date;
}
/** Response shape for `GET /memories/lessons`. */
interface LessonsListResult {
lessons: Lesson[];
count: number;
}
/**
* Aggregate lesson statistics from `GET /memories/lessons/stats`.
* Mirrors core's `getLessonStats` return shape (lesson-service.ts).
*/
interface LessonStats {
totalActive: number;
byType: Record<string, number>;
}
interface AtomicMemoryLessons {
/** `GET /memories/lessons` — list all active lessons for a user. */
list(userId: string): Promise<LessonsListResult>;
/** `GET /memories/lessons/stats` — aggregate counts by lesson type. */
stats(userId: string): Promise<LessonStats>;
/**
* `POST /memories/lessons/report` — record a user-reported lesson
* (explicit feedback path).
*/
report(userId: string, pattern: string, sources?: string[], severity?: LessonSeverity): Promise<{
lessonId: string;
}>;
/** `DELETE /memories/lessons/:id` — deactivate a lesson. */
delete(lessonId: string, userId: string): Promise<void>;
}
/**
* Embedding provider names core ships. Mirrors
* `EmbeddingProviderName` at atomicmemory-core/src/config.ts:14.
*/
type EmbeddingProviderName = 'openai' | 'ollama' | 'openai-compatible' | 'transformers';
/**
* LLM provider names core ships. Mirrors `LLMProviderName` at
* atomicmemory-core/src/config.ts:15.
*/
type LLMProviderName = EmbeddingProviderName | 'groq' | 'anthropic' | 'google-genai';
/**
* Runtime configuration snapshot exposed by `/memories/health`'s `config`
* field and `/memories/config`'s `config` response field. Mirrors core's
* `formatHealthConfig` (memories.ts) with SDK-idiomatic camelCase.
*/
interface HealthConfig {
retrievalProfile: string;
embeddingProvider: EmbeddingProviderName;
embeddingModel: string;
llmProvider: LLMProviderName;
llmModel: string;
clarificationConflictThreshold: number;
maxSearchResults: number;
hybridSearchEnabled: boolean;
iterativeRetrievalEnabled: boolean;
entityGraphEnabled: boolean;
crossEncoderEnabled: boolean;
agenticRetrievalEnabled: boolean;
repairLoopEnabled: boolean;
}
/**
* Response shape for `GET /memories/health`. Distinct from V3's
* `HealthStatus` (types.ts) — V3 health is `{ok, latencyMs?, version?}`
* (capability probe); core's route emits `{status, config}` (runtime
* snapshot). Renamed to avoid the collision at SDK export time.
*/
interface AtomicMemoryHealthStatus {
status: 'ok';
config: HealthConfig;
}
/**
* Runtime-mutable threshold fields accepted by `PUT /memories/config`.
* Mirrors the four fields core extracts from the body at memories.ts:
* 284-289.
*
* Every field is optional; omitted fields are left untouched.
* Provider/model selection is intentionally NOT exposed here — core
* 400s startup-only fields (memories.ts:275-283). Callers should
* restart the process with the relevant env vars to change those.
*/
interface ConfigUpdates {
similarityThreshold?: number;
audnCandidateThreshold?: number;
clarificationConflictThreshold?: number;
maxSearchResults?: number;
}
/**
* Success response from `PUT /memories/config`. Mirrors core's
* success-path body at memories.ts:290-294.
*
* Note: core can return 410 (mutation disabled) or 400 (startup-only
* field present) as HTTP errors; those are wrapped into the SDK's
* MemoryProviderError by the shared fetch layer and should be caught
* with try/catch, not inspected on this type.
*/
interface ConfigUpdateResult {
/** Field names that were actually applied (subset of ConfigUpdates keys). */
applied: string[];
/** Full updated runtime config snapshot. */
config: HealthConfig;
/** Human-readable note reminding that provider/model changes require restart. */
note: string;
}
interface AtomicMemoryConfig {
/** `GET /memories/health` — current runtime config snapshot. */
health(): Promise<AtomicMemoryHealthStatus>;
/**
* `PUT /memories/config` — apply runtime-mutable threshold updates.
*
* Requires the server to have been started with
* `CORE_RUNTIME_CONFIG_MUTATION_ENABLED=true`; otherwise core returns
* HTTP 410, which propagates as a thrown MemoryProviderError.
*/
updateConfig(updates: ConfigUpdates): Promise<ConfigUpdateResult>;
}
/**
* Conflict resolution choices accepted by
* `PUT /agents/conflicts/:id/resolve`. Mirrors core's VALID_RESOLUTIONS
* set at atomicmemory-core/src/routes/agents.ts:102.
*/
type ConflictResolution = 'resolved_new' | 'resolved_existing' | 'resolved_both';
/**
* Conflict status values core writes into the `memory_conflicts.status`
* column. `open` is the initial state; the three resolution variants
* come from manual resolution; `auto_resolved` comes from
* `autoResolveExpiredConflicts`. Typed as a string union but kept open
* via `string` to tolerate future status values without breaking the
* SDK.
*/
type ConflictStatus = 'open' | 'resolved_new' | 'resolved_existing' | 'resolved_both' | 'auto_resolved';
/** Response shape for `PUT /agents/trust`. */
interface SetTrustResult {
agentId: string;
trustLevel: number;
}
/**
* Response shape for `GET /agents/trust`.
*
* `trustLevel` is always a number. When no trust record exists for
* the (userId, agentId) pair, core returns `DEFAULT_TRUST_LEVEL` (0.5
* as of today — see `atomicmemory-core/src/db/agent-trust-repository.ts:46,56`)
* rather than `null`. Callers who need to distinguish "unset" from
* "explicitly 0.5" must track the provenance themselves; the wire
* contract does not expose the distinction.
*/
interface GetTrustResult {
agentId: string;
trustLevel: number;
}
/**
* A single agent conflict row. Mirrors core's `MemoryConflict`
* (agent-trust-repository.ts), normalized to camelCase + Date at the
* SDK boundary.
*/
interface AgentConflict {
id: string;
userId: string;
newMemoryId: string | null;
existingMemoryId: string | null;
newAgentId: string | null;
existingAgentId: string | null;
newTrustLevel: number | null;
existingTrustLevel: number | null;
contradictionConfidence: number;
clarificationNote: string | null;
status: ConflictStatus;
resolutionPolicy: string | null;
resolvedAt: Date | null;
createdAt: Date;
autoResolveAfter: Date | null;
}
/** Response shape for `GET /agents/conflicts`. */
interface ConflictsListResult {
conflicts: AgentConflict[];
count: number;
}
/**
* Response shape for `PUT /agents/conflicts/:id/resolve`.
* `status` echoes the resolution you passed in.
*/
interface ResolveConflictResult {
id: string;
status: ConflictResolution;
}
/** Response shape for `POST /agents/conflicts/auto-resolve`. */
interface AutoResolveConflictsResult {
/** Count of conflicts transitioned to `auto_resolved` state. */
resolved: number;
}
interface AtomicMemoryAgents {
/**
* `PUT /agents/trust` — set or update a (userId, agentId) trust
* record. `trustLevel` must be between 0.0 and 1.0 (core validates).
* Optional `displayName` is a human-readable label.
*/
setTrust(userId: string, agentId: string, trustLevel: number, displayName?: string): Promise<SetTrustResult>;
/**
* `GET /agents/trust` — look up a single (userId, agentId) trust
* record. When no record exists, core returns a default trust level
* (currently 0.5) rather than 404. See `GetTrustResult` for the
* unset-vs-0.5 caveat.
*/
getTrust(userId: string, agentId: string): Promise<GetTrustResult>;
/** `GET /agents/conflicts` — list open conflicts for a user. */
conflicts(userId: string): Promise<ConflictsListResult>;
/**
* `PUT /agents/conflicts/:id/resolve` — manually resolve one
* conflict. NB: this route takes `conflictId` (not `userId`) because
* core resolves by conflict id directly (agents.ts:61-72).
*/
resolveConflict(conflictId: string, resolution: ConflictResolution): Promise<ResolveConflictResult>;
/**
* `POST /agents/conflicts/auto-resolve` — trigger the batch
* auto-resolution pass for a user. Transitions any `open` conflicts
* whose `auto_resolve_after` deadline has elapsed into
* `auto_resolved` state. Returns the count transitioned.
*/
autoResolveConflicts(userId: string): Promise<AutoResolveConflictsResult>;
}
/**
* AtomicMemory-specific SDK handle. Access via `sdk.atomicmemory` when an
* AtomicMemoryProvider is registered. `sdk.atomicmemory` is `undefined`
* for SDK configurations that do not include AtomicMemoryProvider.
*/
interface AtomicMemoryHandle {
ingestFull(input: AtomicMemoryIngestInput, scope: MemoryScope): Promise<AtomicMemoryIngestResult>;
ingestQuick(input: AtomicMemoryIngestInput, scope: MemoryScope, options?: {
skipExtraction?: boolean;
}): Promise<AtomicMemoryIngestResult>;
search(request: AtomicMemorySearchRequest, scope: MemoryScope): Promise<AtomicMemorySearchResultPage>;
/**
* Fast search path. Does NOT honor `request.asOf` — core's handler at
* `atomicmemory-core/src/routes/memories.ts:191-206` parses `as_of`
* but drops it. Use `search()` for temporal queries.
*/
searchFast(request: AtomicMemorySearchRequest, scope: MemoryScope): Promise<AtomicMemorySearchResultPage>;
expand(refs: string[], scope: MemoryScope): Promise<AtomicMemoryMemory[]>;
list(scope: MemoryScope, options?: AtomicMemoryListOptions): Promise<AtomicMemoryListResultPage>;
get(id: string, scope: MemoryScope): Promise<AtomicMemoryMemory | null>;
delete(id: string, scope: MemoryScope): Promise<void>;
lifecycle: AtomicMemoryLifecycle;
audit: AtomicMemoryAudit;
lessons: AtomicMemoryLessons;
config: AtomicMemoryConfig;
agents: AtomicMemoryAgents;
}
declare const ATOMICMEMORY_EXTENSION_NAMES: readonly ["atomicmemory.base", "atomicmemory.lifecycle", "atomicmemory.audit", "atomicmemory.lessons", "atomicmemory.config", "atomicmemory.agents"];
type AtomicMemoryExtensionName = (typeof ATOMICMEMORY_EXTENSION_NAMES)[number];
declare function capabilityGaps(caps: Capabilities, profile: CapabilityProfile): CapabilityGap[];
/** Whether `caps` satisfies every requirement in `profile`. */
declare function satisfiesProfile(caps: Capabilities, profile: CapabilityProfile): boolean;
/**
* @file Mem0 Provider Configuration
*
* Configuration types for the Mem0 memory provider, which connects
* to a local or hosted Mem0 instance via its REST API.
*/
interface Mem0ProviderConfig {
/** Mem0 API base URL (e.g. "https://api.mem0.ai" hosted or "http://localhost:8888" OSS) */
apiUrl: string;
/** Request timeout in milliseconds */
timeout?: number;
/** API key for hosted Mem0 instances */
apiKey?: string;
/** Whether to enable LLM inference on ingest (default true) */
defaultInfer?: boolean;
/**
* When true, ingest sends infer=false synchronously for fast return,
* then fires a background re-ingest with infer=true (deferred AUDN).
* Only applies when the effective infer value would be true.
* Default: false (single-call behavior).
*/
deferInference?: boolean;
/**
* Path prefix for memory-identifier endpoints (ingest, get, delete, list).
* - '/v1' (default) for hosted Mem0 (api.mem0.ai): /v1/memories/, /v1/memories/{id}/
* - '' for OSS self-hosted Mem0: /memories/, /memories/{id}/
*
* Note: search uses the v2 endpoint (`/v2/memories/search/` hosted, or
* `/memories/search/` OSS) regardless of this prefix, per mem0 2.0's
* split of search from the v1 family.
*/
pathPrefix?: string;
/**
* Optional organization ID for enterprise-scoped operations (mem0 2.0+).
* Sent as top-level `org_id` on search and ingest bodies when set.
*/
orgId?: string;
/**
* Optional project ID for enterprise-scoped operations (mem0 2.0+).
* Sent as top-level `project_id` on search and ingest bodies when set.
*/
projectId?: string;
}
/** Default timeout for Mem0 provider HTTP requests (ms). */
declare const MEM0_DEFAULT_TIMEOUT = 30000;
/**
* @file Hindsight Provider Configuration and Wire Types
*
* Defines the public configuration surface and provider-specific extension
* handle types for the Hindsight memory backend. The core SDK provider API
* remains backend-agnostic; these types are exported so callers that opt into
* Hindsight-specific operation metadata can do so through named extensions.
*/
type HindsightRecallBudget = 'low' | 'mid' | 'high';
type HindsightTagsMatch = 'any' | 'all' | 'any_strict' | 'all_strict';
interface HindsightProviderConfig {
/** Hindsight API base URL, e.g. `https://api.hindsight.vectorize.io`. */
apiUrl: string;
/** Optional bearer token for Hindsight Cloud or protected self-hosted APIs. */
apiKey?: string;
/** Request timeout in milliseconds. Defaults to 30_000. */
timeout?: number;
/** API version path segment. Defaults to `v1`. */
apiVersion?: string;
/** Hindsight project path segment. Defaults to `default`. */
projectId?: string;
/** Recall search depth fallback. Request-level typed override is deferred. */
defaultBudget?: HindsightRecallBudget;
/** Fallback context token budget for package/recall requests. */
defaultMaxTokens?: number;
}
interface HindsightRetainItem {
content: string;
context?: string;
timestamp?: string;
metadata?: Record<string, unknown>;
tags?: string[];
}
interface HindsightRetainRequest {
items: HindsightRetainItem[];
async?: boolean;
}
interface HindsightRetainResponse {
success?: boolean;
bank_id?: string;
items_count?: number;
async?: boolean;
operation_id?: string;
operation_ids?: string[];
usage?: Record<string, unknown>;
}
interface HindsightOperation {
id: string;
task_type?: string;
items_count?: number;
document_id?: string | null;
created_at?: string;
status?: string;
error_message?: string | null;
retry_count?: number;
next_retry_at?: string;
}
interface HindsightOperationsPage {
bank_id?: string;
operations: HindsightOperation[];
}
interface HindsightRetainHandle {
retain(input: IngestInput): Promise<HindsightRetainResponse>;
}
interface HindsightOperationsHandle {
list(scope: Scope): Promise<HindsightOperationsPage>;
get(scope: Scope, operationId: string): Promise<HindsightOperation | null>;
}
declare const HINDSIGHT_DEFAULT_TIMEOUT = 30000;
declare const HINDSIGHT_DEFAULT_API_VERSION = "v1";
declare const HINDSIGHT_DEFAULT_PROJECT_ID = "default";
/** Hindsight's documented default source-fact token budget for reflect/recall examples. */
declare const HINDSIGHT_DEFAULT_MAX_TOKENS = 4096;
declare const HINDSIGHT_SCOPE_TAGS_MATCH: HindsightTagsMatch;
/**
* @file V3 Memory Processing Pipeline
*
* SDK-level hooks for transforming data before/after provider calls.
* Pipelines are SDK orchestration, not part of the provider standard.
*/
interface MemoryProcessingPipeline {
preprocessIngest?(input: IngestInput): Promise<IngestInput[]>;
postprocessIngest?(result: IngestResult, input: IngestInput): Promise<void>;
preprocessSearch?(request: SearchRequest): Promise<SearchRequest>;
postprocessSearch?(page: SearchResultPage, request: SearchRequest): Promise<SearchResultPage>;
preprocessGet?(ref: MemoryRef): Promise<MemoryRef>;
postprocessGet?(memory: Memory | null, ref: MemoryRef): Promise<Memory | null>;
postprocessList?(page: ListResultPage, request: ListRequest): Promise<ListResultPage>;
}
/** No-op pipeline that passes data through unchanged. */
declare const noopMemoryPipeline: MemoryProcessingPipeline;
/**
* @file V3 Memory Provider Registration
*
* Types for pairing a provider with an optional processing pipeline
* at registration time.
*/
/** A provider paired with its optional pipeline. */
interface MemoryProviderRegistration {
provider: MemoryProvider;
pipeline?: MemoryProcessingPipeline;
}
/** Registry entry template for provider factory functions. */
interface MemoryProviderEntry<Config> {
name: string;
create(config: Config): MemoryProviderRegistration;
}
/**
* @file V3 Memory Provider Errors
*
* Standardized error hierarchy for memory provider operations.
* Every provider adapter must throw these instead of raw errors.
*/
/** Base class for all provider errors. */
declare class MemoryProviderError extends Error {
readonly provider: string;
readonly operation: string;
readonly cause?: Error | undefined;
constructor(message: string, provider: string, operation: string, cause?: Error | undefined);
}
/** Caller invoked an extension the provider does not support. */
declare class UnsupportedOperationError extends MemoryProviderError {
constructor(provider: string, operation: string);
}
/** Required scope fields are missing or invalid. */
declare class InvalidScopeError extends MemoryProviderError {
constructor(provider: string, missing: string[]);
}
/**
* Transport-layer failure reaching the provider — connection refused,
* timeout, DNS failure, abort, etc. Named `MemoryTransportError` to avoid
* colliding with the generic `NetworkError` exported from
* `src/core/error-handling/errors.ts` (different inheritance tree).
*/
declare class MemoryTransportError extends MemoryProviderError {
readonly url: string;
readonly code: string | null;
constructor(provider: string, operation: string, url: string, cause: Error);
}
/** Provider-side rate limit or quota exceeded. */
declare class RateLimitError extends MemoryProviderError {
readonly retryAfterMs?: number;
constructor(provider: string, retryAfterMs?: number);
}
/**
* @file AtomicMemory Provider
*
* HTTP-based MemoryProvider implementation targeting the AtomicMemory
* prototype backend.
*
* Implements core operations + extensions: Packager, TemporalSearch,
* Versioner, Health.
*/
declare class AtomicMemoryProvider extends BaseMemoryProvider implements Packager, TemporalSearch, Versioner, Health {
readonly name = "atomicmemory";
private readonly http;
/**
* Prefix prepended to every core-facing route path, e.g. `/v1`.
* Empty string disables prefixing (legacy deployments only).
*/
private readonly apiPrefix;
/**
* Opt-in post-retrieval meta-fact filter. `undefined` (default) means
* filtering is off. See `MetaFactFilterConfig` and
* `benchmarks/alignbench/RESULTS.md` for motivation.
*/
private readonly metaFactFilter?;
constructor(config: AtomicMemoryProviderConfig);
/**
* Drop meta-fact entries from a SearchResult list when the filter is enabled.
*
* Called once per search-style endpoint (regular search, temporal search,
* package) so meta-facts never reach the caller. No-op when
* `this.metaFactFilter` is `undefined` or `enabled: false` — matches the
* pre-filter behaviour byte-for-byte.
*/
private applyMetaFactFilter;
/** Prepend the configured API-version prefix to a route path. */
private route;
protected doIngest(input: IngestInput): Promise<IngestResult>;
protected doSearch(request: SearchRequest): Promise<SearchResultPage>;
protected doGet(ref: MemoryRef): Promise<Memory | null>;
protected doDelete(ref: MemoryRef): Promise<void>;
protected doList(request: ListRequest): Promise<ListResultPage>;
capabilities(): Capabilities;
/**
* V3 extension discovery hook. Resolves custom extension names under the
* `atomicmemory.*` namespace to typed handles. Each key returns the
* specific handle for that category — `atomicmemory.lifecycle` returns
* an `AtomicMemoryLifecycle` (callable as `.consolidate(...)` directly),
* not the root handle. `atomicmemory.base` returns the root
* `AtomicMemoryHandle` which aggregates base routes + all category
* sub-accessors. Standard V3 extensions (`package`, `temporal`,
* `versioning`, `health`) are still accessed via interface casting on
* this class — the namespace is additive.
*/
getExtension<T = unknown>(name: string): T | undefined;
/**
* Lazily construct a single AtomicMemoryHandle instance bound to this
* provider. The handle exposes AtomicMemory-specific methods through
* named extensions instead of the backend-agnostic provider surface.
*/
private _atomicmemoryHandle?;
private atomicmemoryHandle;
package(request: PackageRequest): Promise<ContextPackage>;
searchAsOf(request: SearchRequest & {
asOf: Date;
}): Promise<SearchResultPage>;
history(ref: MemoryRef): Promise<MemoryVersion[]>;
health(): Promise<HealthStatus>;
}
/**
* @file Mem0 Provider
*
* HTTP-based MemoryProvider implementation targeting a local or hosted
* Mem0 instance (port 8888 OSS; api.mem0.ai hosted).
*
* Implements core V3 operations plus Health. Other V3 extensions
* (package, temporal, versioning, graph, etc.) are not supported by mem0.
*
* mem0 2.0 compatibility:
* - Search uses `POST /v2/memories/search/` with nested `filters` object.
* - Add response envelope is `{id, event, data: {memory}}`; legacy flat
* `{id, memory, event}` is still tolerated.
* - Enterprise scoping (`org_id`, `project_id`) is passed at top level
* when configured.
*
* Known limitation: mem0 2.0 makes `add` async-by-default and returns
* queued event IDs. For consumers that need the final extracted memories,
* polling `/v1/event/{event_id}/` is a future enhancement (tracked as
* post-v1.0 work); the current implementation returns what mem0 emits
* in the immediate response.
*/
declare class Mem0Provider extends BaseMemoryProvider implements Health {
readonly name = "mem0";
private readonly http;
private readonly config;
private readonly prefix;
constructor(config: Mem0ProviderConfig);
/** Build an API path using the configured prefix (used for /memories/ family). */
private path;
/**
* Build the path to the v2 search endpoint. mem0 2.0 split search out of the
* v1 family, so search ignores `pathPrefix` and uses `/v2/memories/search/`
* on hosted, or `/memories/search/` on OSS (when `pathPrefix === ''`).
*/
private searchPath;
protected doIngest(input: IngestInput): Promise<IngestResult>;
/**
* Fire-and-forget: re-ingest with infer=true for AUDN extraction.
* Logs errors but never blocks the caller.
*/
private fireBackgroundInference;
protected doSearch(request: SearchRequest): Promise<SearchResultPage>;
protected doGet(ref: MemoryRef): Promise<Memory | null>;
protected doDelete(ref: MemoryRef): Promise<void>;
protected doList(request: ListRequest): Promise<ListResultPage>;
/**
* Check Mem0 backend connectivity.
*
* Performs a lightweight list request with page_size=1 to verify
* the server is reachable and responding.
*/
health(): Promise<HealthStatus>;
capabilities(): Capabilities;
}
/**
* @file Mem0 Context Provider Types
*
* V2-compatible type definitions used by the webapp's Mem0SdkAdapter.
* These types bridge the gap between the webapp's expected interface
* and the V3 MemoryProvider architecture.
*/
/**
* Metadata attached to a context when adding via addContext().
* Matches the shape expected by mem0-sdk-adapter.server.ts.
*/
interface ContextMetadata {
userId: string;
source?: string;
type?: 'conversation' | 'document' | 'note' | 'preference' | string;
platform?: string;
title?: string;
url?: string;
timestamp?: number;
[key: string]: unknown;
}
/**
* Metadata attached when updating a context via updateContext().
*/
interface DocumentMetadata {
source?: string;
userId?: string;
type?: 'conversation' | 'document' | 'note' | 'preference' | string;
platform?: string;
title?: string;
url?: string;
[key: string]: unknown;
}
/**
* Configuration for the Mem0ContextProvider bridge.
*/
interface Mem0ContextProviderConfig {
/** API key for the Mem0 instance */
apiKey?: string;
/** Mem0 server base URL (e.g. "http://localhost:8888") */
host: string;
/** API style — currently only 'oss' is supported */
apiStyle: 'oss';
/** Default user ID used when no per-request userId is provided */
defaultUserId: string;
/** Request timeout in milliseconds */
timeout?: number;
/** Path prefix for API endpoints (e.g. '/v1' for hosted, '' for OSS). Defaults to '/v1'. */
pathPrefix?: string;
}
/**
* A context record returned by getContext().
*/
interface ContextRecord {
id: string;
content: string;
metadata?: Record<string, unknown>;
createdAt?: string;
updatedAt?: string;
}
/**
* A search result returned by searchContext().
*/
interface ContextSearchResult {
id: string;
contextId: string;
content: string;
/** Raw Mem0 backend score. For local OSS Mem0 this is distance-like, so lower is better. */
score: number;
metadata?: Record<string, unknown>;
}
/**
* Result from addContext(), containing the Mem0 server-assigned ID.
*/
interface AddContextResult {
/** Mem0's internal ID for the created memory. Use this for get/update/delete. */
memoryId: string;
/** The caller-supplied contextId, stored in metadata. */
contextId: string;
content: string;
}
/**
* Options for searchContext().
*/
interface ContextSearchOptions {
userId: string;
maxResults?: number;
/** Minimum similarity [0, 1]. The bridge converts this to a max allowed raw Mem0 distance. */
threshold?: number;
}
/**
* @file Mem0 Context Provider — V2-Compatible Bridge
*
* Wraps the V3 Mem0Provider HTTP layer to expose the high-level
* context-oriented interface that the webapp's Mem0SdkAdapter expects.
*
* This is NOT a V3 MemoryProvider — it is a compatibility bridge
* for consumers that import `Mem0ContextProvider` from the SDK.
*
* Methods map to Mem0 REST endpoints. Path prefix depends on apiStyle:
* - apiStyle 'oss' → /memories, /search (no version prefix)
* - apiStyle 'hosted' → /v1/memories/, /v1/search/
*/
declare class Mem0ContextProvider {
private readonly http;
private readonly config;
private readonly prefix;
private _initialized;
constructor(config: Mem0ContextProviderConfig);
/** Build an API path using the configured prefix. */
private path;
initialize(): Promise<void>;
/**
* Add a context (memory) for a user.
* Uses infer=false for verbatim storage.
*
* Returns the Mem0 server-assigned ID alongside the caller-supplied contextId.
* The memoryId is what get/update/delete operations require.
*/
addContext(contextId: string, content: string, metadata?: ContextMetadata): Promise<AddContextResult>;
/**
* Update an existing memory's content.
*/
updateContext(memoryId: string, content: string, userId: string, metadata?: DocumentMetadata): Promise<void>;
/**
* Search memories for a user.
*/
searchContext(query: string, options: ContextSearchOptions): Promise<ContextSearchResult[]>;
/**
* Get a single memory by ID. Returns null on 404.
*/
getContext(memoryId: string): Promise<ContextRecord | null>;
/**
* Delete a single memory by ID. Returns false on 404.
*/
deleteContext(memoryId: string): Promise<boolean>;
/**
* Delete all memories for a user.
*/
deleteAllContexts(options: {
userId?: string;
}): Promise<boolean>;
/**
* List all memories for a user.
*/
listContexts(options: {
userId?: string;
limit?: number;
}): Promise<ContextRecord[]>;
private assertInitialized;
}
/**
* @file Hindsight Memory Provider
*
* HTTP-backed `MemoryProvider` implementation for Hindsight Cloud or a
* self-hosted Hindsight API. The adapter keeps Hindsight-specific request and
* response shapes inside this provider while exposing the SDK's backend-neutral
* memory contract plus standard package, reflect, and health extensions.
*/
declare class HindsightProvider extends BaseMemoryProvider implements Packager, Reflector, Health {
readonly name = "hindsight";
private readonly http;
private readonly config;
private readonly apiVersion;
private readonly projectId;
private readonly retainHandle;
private readonly operationsHandle;
constructor(config: HindsightProviderConfig);
protected doIngest(input: IngestInput): Promise<IngestResult>;
protected doSearch(request: SearchRequest): Promise<SearchResultPage>;
protected doGet(ref: MemoryRef): Promise<Memory | null>;
protected doDelete(ref: MemoryRef): Promise<void>;
protected doList(request: ListRequest): Promise<ListResultPage>;
capabilities(): Capabilities;
getExtension<T = unknown>(name: string): T | undefined;
package(request: PackageRequest): Promise<ContextPackage>;
reflect(query: string, scope: Scope): Promise<Insight[]>;
health(): Promise<HealthStatus>;
private retain;
private recallRaw;
private mapListPage;
private createRetainHandle;
private createOperationsHandle;
private listOperations;
private getOperation;
private bankPath;
private memoryPath;
private route;
}
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, type AddContextResult, type AgentConflict, type AgentScope, type AtomicMemoryAgents, type AtomicMemoryAudit, type AtomicMemoryConfig, type AtomicMemoryExtensionName, type AtomicMemoryHandle, type AtomicMemoryHealthStatus, type AtomicMemoryIngestInput, type AtomicMemoryIngestResult, type AtomicMemoryLessons, type AtomicMemoryLifecycle, type AtomicMemoryListOptions, type AtomicMemoryListResultPage, type AtomicMemoryMemory, AtomicMemoryProvider, type AtomicMemoryProviderConfig, type AtomicMemorySearchRequest, type AtomicMemorySearchResult, type AtomicMemorySearchResultPage, type AuditTrailEntry, type AuditTrailResult, type AutoResolveConflictsResult, BaseMemoryProvider, type BatchOps, type CapCheckResult, type CapRecommendation, type CapStatus, type Capabilities, type ConfigUpdateResult, type ConfigUpdates, type ConflictResolution, type ConflictStatus, type ConflictsListResult, type ConsolidationExecutionResult, type ConsolidationResult, type ConsolidationScanResult, type ContextMetadata, type ContextPackage, type ContextRecord, type ContextSearchOptions, type ContextSearchResult, DEFAULT_META_FACT_PATTERNS, type DecayResult, type DocumentMetadata, type EmbeddingProviderName, type FieldFilter, type FilterExpr, type Forgetter, type GetTrustResult, type GraphEdge, type GraphNode, type GraphResult, type GraphSearch, type GraphSearchRequest, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, type Health, type HealthConfig, type HealthStatus, type HindsightOperation, type HindsightOperationsHandle, type HindsightOperationsPage, HindsightProvider, type HindsightProviderConfig, type HindsightRecallBudget, type HindsightRetainHandle, type HindsightRetainItem, type HindsightRetainRequest, type HindsightRetainResponse, type HindsightTagsMatch, type IngestBase, type IngestInput, type IngestResult, type Insight, InvalidScopeError, type LLMProviderName, type Lesson, type LessonSeverity, type LessonStats, type LessonType, type LessonsListResult, type ListRequest, type ListResultPage, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, type Mem0ContextProviderConfig, Mem0Provider, type Mem0ProviderConfig, type Memory, type MemoryKind, type MemoryProcessingPipeline, type MemoryProvider, type MemoryProviderEntry, MemoryProviderError, type MemoryProviderRegistration, type MemoryRef, type MemoryScope, MemoryTransportError, type MemoryVersion, type Message, type MessageIngest, type MetaFactFilterConfig, type MutationRecord, type MutationSummary, type MutationType, type PackageRequest, type Packager, type Profile, type Profiler, type Provenance, RateLimitError, type RecentMutationsResult, type ReconcileStatus, type ReconciliationResult, type Reflector, type ResetSourceResult, type ResolveConflictResult, type Scope, type SearchRequest, type SearchResult, type SearchResultPage, type SetTrustResult, type StatsResult, type TemporalSearch, type TextIngest, UnsupportedOperationError, type Updater, type VerbatimIngest, type Versioner, filterMetaFacts, isMetaFact, noopMemoryPipeline, resolveMetaFactPatterns };
export { Capabilities, type CapabilityGap, type CapabilityProfile, IngestInput, capabilityGaps, satisfiesProfile };

@@ -1,3 +0,4 @@

export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AtomicMemoryProvider, BaseMemoryProvider, DEFAULT_META_FACT_PATTERNS, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, HindsightProvider, InvalidScopeError, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0Provider, MemoryProviderError, MemoryTransportError, RateLimitError, UnsupportedOperationError, filterMetaFacts, isMetaFact, noopMemoryPipeline, resolveMetaFactPatterns } from './chunk-YBN5Y627.js';
export { capabilityGaps, satisfiesProfile } from './chunk-4CP57UR3.js';
export { ATOMICMEMORY_DEFAULT_TIMEOUT, ATOMICMEMORY_EXTENSION_NAMES, AtomicMemoryProvider, BaseMemoryProvider, DEFAULT_META_FACT_PATTERNS, HINDSIGHT_DEFAULT_API_VERSION, HINDSIGHT_DEFAULT_MAX_TOKENS, HINDSIGHT_DEFAULT_PROJECT_ID, HINDSIGHT_DEFAULT_TIMEOUT, HINDSIGHT_SCOPE_TAGS_MATCH, HindsightProvider, InvalidScopeError, MEM0_DEFAULT_TIMEOUT, Mem0ContextProvider, Mem0Provider, MemoryProviderError, MemoryTransportError, RateLimitError, UnsupportedOperationError, filterMetaFacts, isMetaFact, noopMemoryPipeline, resolveMetaFactPatterns } from './chunk-T7PRWXW6.js';
//# sourceMappingURL=memory.js.map
//# sourceMappingURL=memory.js.map
{
"name": "@atomicmemory/sdk",
"version": "1.0.3",
"version": "1.1.0",
"type": "module",

@@ -108,3 +108,4 @@ "engines": {

"fixtures:capture": "tsx scripts/capture-fixtures.ts",
"prepare": "husky"
"prepare": "husky",
"prepublishOnly": "node ../../scripts/guards/guard-npm-publish.mjs"
},

@@ -128,2 +129,4 @@ "keywords": [

"@vitest/coverage-v8": "^4.1.6",
"ajv": "^8.20.0",
"ajv-formats": "^3.0.1",
"husky": "^9.1.7",

@@ -130,0 +133,0 @@ "jsdom": "^27.0.0",

@@ -12,3 +12,3 @@ # @atomicmemory/sdk

AtomicMemory Core currently reaches cost-Pareto SOTA on BEAM-100K, BEAM-1M, and LoCoMo10, with BEAM-10M parity against the strongest published Mem0-new result. The SDK is the typed application surface for building on that memory layer.
AtomicMemory Core currently reaches leading performance/cost on BEAM-100K, BEAM-1M, and LoCoMo10, with BEAM-10M parity against the strongest published Mem0-new result. The SDK is the typed application surface for building on that memory layer.

@@ -15,0 +15,0 @@ ## What this package provides

import { HindsightProvider, Mem0Provider, AtomicMemoryProvider, noopMemoryPipeline, UnsupportedOperationError } from './chunk-YBN5Y627.js';
// src/memory/providers/registry.ts
var defaultRegistry = {
atomicmemory: (config) => ({
provider: new AtomicMemoryProvider(config)
}),
mem0: (config) => ({
provider: new Mem0Provider(config)
}),
hindsight: (config) => ({
provider: new HindsightProvider(config)
})
};
// src/memory/memory-service.ts
var MemoryService = class {
constructor(config) {
this.config = config;
this.defaultProviderName = config.defaultProvider;
}
config;
providers = /* @__PURE__ */ new Map();
pipelines = /* @__PURE__ */ new Map();
defaultProviderName;
async initialize(registry = defaultRegistry) {
for (const [name, providerConfig] of Object.entries(
this.config.providerConfigs
)) {
const factory = registry[name];
if (!factory) continue;
const registration = factory(providerConfig);
this.providers.set(name, registration.provider);
this.pipelines.set(
name,
registration.pipeline ?? noopMemoryPipeline
);
if (registration.provider.initialize) {
await registration.provider.initialize();
}
}
}
getProvider(name) {
const providerName = name ?? this.defaultProviderName;
const provider = this.providers.get(providerName);
if (!provider) {
throw new Error(
`Provider "${providerName}" is not registered`
);
}
return provider;
}
getAvailableProviders() {
return Array.from(this.providers.keys());
}
/**
* Provider names declared in the SDK configuration, regardless of whether
* they have been initialized yet. Useful for UI and getter paths that
* need to advertise capabilities before `initialize()` has run.
*/
getConfiguredProviders() {
return Object.keys(this.config.providerConfigs);
}
// -----------------------------------------------------------------------
// Core operations
// -----------------------------------------------------------------------
async ingest(input, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
if (pipeline.preprocessIngest) {
const inputs = await pipeline.preprocessIngest(input);
const results = [];
for (const i of inputs) {
const result2 = await provider.ingest(i);
if (pipeline.postprocessIngest) {
await pipeline.postprocessIngest(result2, i);
}
results.push(result2);
}
return mergeIngestResults(results);
}
const result = await provider.ingest(input);
if (pipeline.postprocessIngest) {
await pipeline.postprocessIngest(result, input);
}
return result;
}
async search(request, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const processedRequest = pipeline.preprocessSearch ? await pipeline.preprocessSearch(request) : request;
const page = await provider.search(processedRequest);
return pipeline.postprocessSearch ? await pipeline.postprocessSearch(page, processedRequest) : page;
}
async get(ref, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const processedRef = pipeline.preprocessGet ? await pipeline.preprocessGet(ref) : ref;
const memory = await provider.get(processedRef);
return pipeline.postprocessGet ? await pipeline.postprocessGet(memory, processedRef) : memory;
}
async delete(ref, providerName) {
const provider = this.getProvider(providerName);
await provider.delete(ref);
}
async list(request, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const page = await provider.list(request);
return pipeline.postprocessList ? await pipeline.postprocessList(page, request) : page;
}
async package(request, providerName) {
const provider = this.getProvider(providerName);
const packager = provider.getExtension?.("package");
if (!packager) {
throw new UnsupportedOperationError(
provider.name,
"package"
);
}
return packager.package(request);
}
// -----------------------------------------------------------------------
// Internals
// -----------------------------------------------------------------------
getPipeline(name) {
const providerName = name ?? this.defaultProviderName;
return this.pipelines.get(providerName) ?? noopMemoryPipeline;
}
};
function mergeIngestResults(results) {
return {
created: results.flatMap((r) => r.created),
updated: results.flatMap((r) => r.updated),
unchanged: results.flatMap((r) => r.unchanged)
};
}
// src/client/memory-client.ts
var MemoryClient = class {
service;
initialized = false;
constructor(config) {
const providerConfigs = { ...config.providers };
const defaultProvider = config.defaultProvider ?? pickFirstProviderKey(providerConfigs);
if (!defaultProvider) {
throw new Error(
'MemoryClient requires at least one provider config. Pass e.g. { providers: { atomicmemory: { apiUrl: "..." } } }.'
);
}
this.service = new MemoryService({
defaultProvider,
providerConfigs
});
}
/**
* Initialize all configured providers. Must be called before any
* memory operation. Idempotent.
*/
async initialize(registry = defaultRegistry) {
if (this.initialized) return;
await this.service.initialize(registry);
this.initialized = true;
}
/**
* Write memory(ies). Input supports `text`, `messages`, or `memory` modes.
*/
async ingest(input) {
this.assertInitialized();
return this.service.ingest(input);
}
/**
* Ingest without any application-layer gating. Equivalent to `ingest()`
* on the core client; application wrappers override the gated variant
* while delegating this path straight through.
*/
async ingestDirect(input) {
this.assertInitialized();
return this.service.ingest(input);
}
/**
* Search for memories matching the request.
*/
async search(request) {
this.assertInitialized();
return this.service.search(request);
}
/**
* Search without application-layer gating. See `ingestDirect` for the
* rationale.
*/
async searchDirect(request) {
this.assertInitialized();
return this.service.search(request);
}
/**
* Build an injection-ready context package from a scoped request.
* Provider must implement the `package` extension.
*/
async package(request) {
this.assertInitialized();
return this.service.package(request);
}
/**
* Package without application-layer gating.
*/
async packageDirect(request) {
this.assertInitialized();
return this.service.package(request);
}
/**
* Fetch a single memory by reference.
*/
async get(ref) {
this.assertInitialized();
return this.service.get(ref);
}
/**
* Delete a single memory by reference.
*/
async delete(ref) {
this.assertInitialized();
return this.service.delete(ref);
}
/**
* List memories within a scope.
*/
async list(request) {
this.assertInitialized();
return this.service.list(request);
}
/**
* Report the capability surface of the default (or named) provider.
*
* @throws if the named provider is unknown or not initialized.
*/
capabilities(providerName) {
this.assertInitialized();
return this.service.getProvider(providerName).capabilities();
}
/**
* Resolve a named extension on the default (or named) provider.
* Returns `undefined` when the provider does not advertise the
* extension.
*
* @throws if the named provider is unknown or not initialized.
*
* @example
* ```ts
* const pkg = memory.getExtension<Packager>('package');
* ```
*/
getExtension(extensionName, providerName) {
this.assertInitialized();
const provider = this.service.getProvider(providerName);
return provider.getExtension?.(extensionName);
}
/**
* Aggregate status of all configured providers. Never throws:
* uninitialized providers report `initialized: false` and
* `capabilities: null`.
*/
getProviderStatus() {
const configured = this.service.getConfiguredProviders();
const available = new Set(this.service.getAvailableProviders());
return configured.map((name) => {
if (!available.has(name)) {
return { name, initialized: false, capabilities: null };
}
return {
name,
initialized: true,
capabilities: this.service.getProvider(name).capabilities()
};
});
}
/**
* Access the full AtomicMemory namespace handle (lifecycle, audit,
* lessons, config, agents). Returns `undefined` when the client is
* not yet initialized, the `atomicmemory` provider was not included
* in the `providers` config, or that provider does not advertise the
* namespace handle. This getter intentionally never throws — callers
* can guard with a truthy check and let the handle's own methods
* raise if used incorrectly.
*/
get atomicmemory() {
if (!this.initialized) return void 0;
if (!this.service.getConfiguredProviders().includes("atomicmemory")) {
return void 0;
}
const provider = this.service.getProvider("atomicmemory");
return provider.getExtension?.("atomicmemory.base");
}
/**
* Low-level escape hatch for callers that need the concrete provider.
*/
getProvider(name) {
this.assertInitialized();
return this.service.getProvider(name);
}
assertInitialized() {
if (!this.initialized) {
throw new Error(
"MemoryClient is not initialized. Call `await client.initialize()` first."
);
}
}
};
function pickFirstProviderKey(providers) {
for (const [key, value] of Object.entries(providers)) {
if (value !== void 0 && key !== "default") return key;
}
return void 0;
}
export { MemoryClient };
//# sourceMappingURL=chunk-265G225P.js.map
//# sourceMappingURL=chunk-265G225P.js.map
{"version":3,"sources":["../src/memory/providers/registry.ts","../src/memory/memory-service.ts","../src/client/memory-client.ts"],"names":["result"],"mappings":";;;AAoBO,IAAM,eAAA,GAAoC;AAAA,EAC/C,YAAA,EAAc,CAAC,MAAA,MAAoE;AAAA,IACjF,QAAA,EAAU,IAAI,oBAAA,CAAqB,MAAM;AAAA,GAC3C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,MAAA,MAA4D;AAAA,IACjE,QAAA,EAAU,IAAI,YAAA,CAAa,MAAM;AAAA,GACnC,CAAA;AAAA,EACA,SAAA,EAAW,CAAC,MAAA,MAAiE;AAAA,IAC3E,QAAA,EAAU,IAAI,iBAAA,CAAkB,MAAM;AAAA,GACxC;AACF,CAAA;;;ACIO,IAAM,gBAAN,MAAoB;AAAA,EAKzB,YAA6B,MAAA,EAA6B;AAA7B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAC3B,IAAA,IAAA,CAAK,sBAAsB,MAAA,CAAO,eAAA;AAAA,EACpC;AAAA,EAF6B,MAAA;AAAA,EAJrB,SAAA,uBAAgB,GAAA,EAA4B;AAAA,EAC5C,SAAA,uBAAgB,GAAA,EAAsC;AAAA,EACtD,mBAAA;AAAA,EAMR,MAAM,UAAA,CACJ,QAAA,GAA6B,eAAA,EACd;AACf,IAAA,KAAA,MAAW,CAAC,IAAA,EAAM,cAAc,CAAA,IAAK,MAAA,CAAO,OAAA;AAAA,MAC1C,KAAK,MAAA,CAAO;AAAA,KACd,EAAG;AACD,MAAA,MAAM,OAAA,GAAU,SAAS,IAAI,CAAA;AAC7B,MAAA,IAAI,CAAC,OAAA,EAAS;AACd,MAAA,MAAM,YAAA,GAA2C,QAAQ,cAAc,CAAA;AACvE,MAAA,IAAA,CAAK,SAAA,CAAU,GAAA,CAAI,IAAA,EAAM,YAAA,CAAa,QAAQ,CAAA;AAC9C,MAAA,IAAA,CAAK,SAAA,CAAU,GAAA;AAAA,QACb,IAAA;AAAA,QACA,aA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AQ,WAAA,CAAY,IAAI,EAAE,YAAA;AAAa,OAC5D;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,IAAI,YAAA,GAA+C;AACjD,IAAA,IAAI,CAAC,IAAA,CAAK,WAAA,EAAa,OAAO,MAAA;AAC9B,IAAA,IAAI,CAAC,IAAA,CAAK,OAAA,CAAQ,wBAAuB,CAAE,QAAA,CAAS,cAAc,CAAA,EAAG;AACnE,MAAA,OAAO,MAAA;AAAA,IACT;AACA,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,WAAA,CAAY,cAAc,CAAA;AACxD,IAAA,OAAO,QAAA,CAAS,eAAmC,mBAAmB,CAAA;AAAA,EACxE;AAAA;AAAA;AAAA;AAAA,EAKA,YAAY,IAAA,EAA+B;AACzC,IAAA,IAAA,CAAK,iBAAA,EAAkB;AACvB,IAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,WAAA,CAAY,IAAI,CAAA;AAAA,EACtC;AAAA,EAEQ,iBAAA,GAA0B;AAChC,IAAA,IAAI,CAAC,KAAK,WAAA,EAAa;AACrB,MAAA,MAAM,IAAI,KAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,qBAAqB,SAAA,EAAwD;AACpF,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,SAAS,CAAA,EAAG;AACpD,IAAA,IAAI,KAAA,KAAU,MAAA,IAAa,GAAA,KAAQ,SAAA,EAAW,OAAO,GAAA;AAAA,EACvD;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-265G225P.js","sourcesContent":["/**\n * @file Memory Provider Registry\n *\n * Maps provider names to factory functions that create\n * MemoryProviderRegistration instances from configuration.\n */\n\nimport type { MemoryProviderRegistration } from '../registration';\nimport type { AtomicMemoryProviderConfig } from '../atomicmemory-provider/types';\nimport { AtomicMemoryProvider } from '../atomicmemory-provider/atomicmemory-provider';\nimport type { Mem0ProviderConfig } from '../mem0-provider/types';\nimport { Mem0Provider } from '../mem0-provider/mem0-provider';\nimport type { HindsightProviderConfig } from '../hindsight-provider/types';\nimport { HindsightProvider } from '../hindsight-provider/hindsight-provider';\n\nexport type ProviderRegistry = Record<\n string,\n (config: any) => MemoryProviderRegistration\n>;\n\nexport const defaultRegistry: ProviderRegistry = {\n atomicmemory: (config: AtomicMemoryProviderConfig): MemoryProviderRegistration => ({\n provider: new AtomicMemoryProvider(config),\n }),\n mem0: (config: Mem0ProviderConfig): MemoryProviderRegistration => ({\n provider: new Mem0Provider(config),\n }),\n hindsight: (config: HindsightProviderConfig): MemoryProviderRegistration => ({\n provider: new HindsightProvider(config),\n }),\n};\n","/**\n * @file Memory Service\n *\n * Replaces UnifiedContextService. Routes operations to the correct\n * provider and applies optional processing pipelines.\n */\n\nimport type { MemoryProvider, Packager } from './provider';\nimport type { MemoryProcessingPipeline } from './pipeline';\nimport { noopMemoryPipeline } from './pipeline';\nimport type { MemoryProviderRegistration } from './registration';\nimport { UnsupportedOperationError } from './errors';\nimport type {\n IngestInput,\n IngestResult,\n SearchRequest,\n SearchResultPage,\n MemoryRef,\n Memory,\n ListRequest,\n ListResultPage,\n PackageRequest,\n ContextPackage,\n} from './types';\nimport {\n defaultRegistry,\n type ProviderRegistry,\n} from './providers/registry';\n\nexport interface MemoryServiceConfig {\n defaultProvider: string;\n providerConfigs: Record<string, unknown>;\n}\n\nexport class MemoryService {\n private providers = new Map<string, MemoryProvider>();\n private pipelines = new Map<string, MemoryProcessingPipeline>();\n private defaultProviderName: string;\n\n constructor(private readonly config: MemoryServiceConfig) {\n this.defaultProviderName = config.defaultProvider;\n }\n\n async initialize(\n registry: ProviderRegistry = defaultRegistry\n ): Promise<void> {\n for (const [name, providerConfig] of Object.entries(\n this.config.providerConfigs\n )) {\n const factory = registry[name];\n if (!factory) continue;\n const registration: MemoryProviderRegistration = factory(providerConfig);\n this.providers.set(name, registration.provider);\n this.pipelines.set(\n name,\n registration.pipeline ?? noopMemoryPipeline\n );\n\n if (registration.provider.initialize) {\n await registration.provider.initialize();\n }\n }\n }\n\n getProvider(name?: string): MemoryProvider {\n const providerName = name ?? this.defaultProviderName;\n const provider = this.providers.get(providerName);\n if (!provider) {\n throw new Error(\n `Provider \"${providerName}\" is not registered`\n );\n }\n return provider;\n }\n\n getAvailableProviders(): string[] {\n return Array.from(this.providers.keys());\n }\n\n /**\n * Provider names declared in the SDK configuration, regardless of whether\n * they have been initialized yet. Useful for UI and getter paths that\n * need to advertise capabilities before `initialize()` has run.\n */\n getConfiguredProviders(): string[] {\n return Object.keys(this.config.providerConfigs);\n }\n\n // -----------------------------------------------------------------------\n // Core operations\n // -----------------------------------------------------------------------\n\n async ingest(\n input: IngestInput,\n providerName?: string\n ): Promise<IngestResult> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n if (pipeline.preprocessIngest) {\n const inputs = await pipeline.preprocessIngest(input);\n const results: IngestResult[] = [];\n for (const i of inputs) {\n const result = await provider.ingest(i);\n if (pipeline.postprocessIngest) {\n await pipeline.postprocessIngest(result, i);\n }\n results.push(result);\n }\n return mergeIngestResults(results);\n }\n\n const result = await provider.ingest(input);\n if (pipeline.postprocessIngest) {\n await pipeline.postprocessIngest(result, input);\n }\n return result;\n }\n\n async search(\n request: SearchRequest,\n providerName?: string\n ): Promise<SearchResultPage> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const processedRequest = pipeline.preprocessSearch\n ? await pipeline.preprocessSearch(request)\n : request;\n\n const page = await provider.search(processedRequest);\n\n return pipeline.postprocessSearch\n ? await pipeline.postprocessSearch(page, processedRequest)\n : page;\n }\n\n async get(\n ref: MemoryRef,\n providerName?: string\n ): Promise<Memory | null> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const processedRef = pipeline.preprocessGet\n ? await pipeline.preprocessGet(ref)\n : ref;\n\n const memory = await provider.get(processedRef);\n\n return pipeline.postprocessGet\n ? await pipeline.postprocessGet(memory, processedRef)\n : memory;\n }\n\n async delete(\n ref: MemoryRef,\n providerName?: string\n ): Promise<void> {\n const provider = this.getProvider(providerName);\n await provider.delete(ref);\n }\n\n async list(\n request: ListRequest,\n providerName?: string\n ): Promise<ListResultPage> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const page = await provider.list(request);\n\n return pipeline.postprocessList\n ? await pipeline.postprocessList(page, request)\n : page;\n }\n\n async package(\n request: PackageRequest,\n providerName?: string\n ): Promise<ContextPackage> {\n const provider = this.getProvider(providerName);\n const packager = provider.getExtension?.<Packager>('package');\n if (!packager) {\n throw new UnsupportedOperationError(\n provider.name,\n 'package'\n );\n }\n return packager.package(request);\n }\n\n // -----------------------------------------------------------------------\n // Internals\n // -----------------------------------------------------------------------\n\n private getPipeline(\n name?: string\n ): MemoryProcessingPipeline {\n const providerName = name ?? this.defaultProviderName;\n return (\n this.pipelines.get(providerName) ?? noopMemoryPipeline\n );\n }\n}\n\nfunction mergeIngestResults(\n results: IngestResult[]\n): IngestResult {\n return {\n created: results.flatMap((r) => r.created),\n updated: results.flatMap((r) => r.updated),\n unchanged: results.flatMap((r) => r.unchanged),\n };\n}\n","/**\n * @file MemoryClient — primary public API for the memory-layer SDK\n *\n * Pure memory operations: ingest, search, package, list, get, delete,\n * capability inspection, and provider namespace handles. No policy\n * gating, no platform/targetDomain parameters — applications that need\n * those layer them on top of this client.\n */\n\nimport { MemoryService } from '../memory/memory-service';\nimport type { MemoryProvider } from '../memory/provider';\nimport type { AtomicMemoryProviderConfig } from '../memory/atomicmemory-provider/types';\nimport type { AtomicMemoryHandle } from '../memory/atomicmemory-provider/handle';\nimport type { Mem0ProviderConfig } from '../memory/mem0-provider/types';\nimport type { HindsightProviderConfig } from '../memory/hindsight-provider/types';\nimport type {\n IngestInput,\n IngestResult,\n SearchRequest,\n SearchResultPage,\n MemoryRef,\n Memory,\n ListRequest,\n ListResultPage,\n PackageRequest,\n ContextPackage,\n Capabilities,\n} from '../memory/types';\nimport {\n defaultRegistry,\n type ProviderRegistry,\n} from '../memory/providers/registry';\n\n/**\n * Provider configuration map. Each key names a provider; the value is\n * that provider's configuration object.\n */\nexport interface MemoryProviderConfigs {\n atomicmemory?: AtomicMemoryProviderConfig;\n mem0?: Mem0ProviderConfig;\n hindsight?: HindsightProviderConfig;\n [providerName: string]: unknown;\n}\n\n/**\n * MemoryClient configuration.\n */\nexport interface MemoryClientConfig {\n /** Provider configurations keyed by provider name. */\n providers: MemoryProviderConfigs;\n /** Name of the default provider. If omitted, the first configured provider wins. */\n defaultProvider?: string;\n}\n\n/**\n * Status summary for each configured provider.\n */\nexport interface ProviderStatus {\n name: string;\n initialized: boolean;\n capabilities: Capabilities | null;\n}\n\n/**\n * MemoryClient — pure memory-layer API.\n *\n * @example\n * ```ts\n * const memory = new MemoryClient({\n * providers: { atomicmemory: { apiUrl: 'http://localhost:17350' } },\n * });\n * await memory.initialize();\n * await memory.ingest({ mode: 'text', content: 'hi', scope: { user: 'u1' } });\n * const results = await memory.search({ query: 'hi', scope: { user: 'u1' } });\n * ```\n */\nexport class MemoryClient {\n private readonly service: MemoryService;\n private initialized = false;\n\n constructor(config: MemoryClientConfig) {\n const providerConfigs: Record<string, unknown> = { ...config.providers };\n const defaultProvider =\n config.defaultProvider ?? pickFirstProviderKey(providerConfigs);\n\n if (!defaultProvider) {\n throw new Error(\n 'MemoryClient requires at least one provider config. ' +\n 'Pass e.g. { providers: { atomicmemory: { apiUrl: \"...\" } } }.'\n );\n }\n\n this.service = new MemoryService({\n defaultProvider,\n providerConfigs,\n });\n }\n\n /**\n * Initialize all configured providers. Must be called before any\n * memory operation. Idempotent.\n */\n async initialize(registry: ProviderRegistry = defaultRegistry): Promise<void> {\n if (this.initialized) return;\n await this.service.initialize(registry);\n this.initialized = true;\n }\n\n /**\n * Write memory(ies). Input supports `text`, `messages`, or `memory` modes.\n */\n async ingest(input: IngestInput): Promise<IngestResult> {\n this.assertInitialized();\n return this.service.ingest(input);\n }\n\n /**\n * Ingest without any application-layer gating. Equivalent to `ingest()`\n * on the core client; application wrappers override the gated variant\n * while delegating this path straight through.\n */\n async ingestDirect(input: IngestInput): Promise<IngestResult> {\n this.assertInitialized();\n return this.service.ingest(input);\n }\n\n /**\n * Search for memories matching the request.\n */\n async search(request: SearchRequest): Promise<SearchResultPage> {\n this.assertInitialized();\n return this.service.search(request);\n }\n\n /**\n * Search without application-layer gating. See `ingestDirect` for the\n * rationale.\n */\n async searchDirect(request: SearchRequest): Promise<SearchResultPage> {\n this.assertInitialized();\n return this.service.search(request);\n }\n\n /**\n * Build an injection-ready context package from a scoped request.\n * Provider must implement the `package` extension.\n */\n async package(request: PackageRequest): Promise<ContextPackage> {\n this.assertInitialized();\n return this.service.package(request);\n }\n\n /**\n * Package without application-layer gating.\n */\n async packageDirect(request: PackageRequest): Promise<ContextPackage> {\n this.assertInitialized();\n return this.service.package(request);\n }\n\n /**\n * Fetch a single memory by reference.\n */\n async get(ref: MemoryRef): Promise<Memory | null> {\n this.assertInitialized();\n return this.service.get(ref);\n }\n\n /**\n * Delete a single memory by reference.\n */\n async delete(ref: MemoryRef): Promise<void> {\n this.assertInitialized();\n return this.service.delete(ref);\n }\n\n /**\n * List memories within a scope.\n */\n async list(request: ListRequest): Promise<ListResultPage> {\n this.assertInitialized();\n return this.service.list(request);\n }\n\n /**\n * Report the capability surface of the default (or named) provider.\n *\n * @throws if the named provider is unknown or not initialized.\n */\n capabilities(providerName?: string): Capabilities {\n this.assertInitialized();\n return this.service.getProvider(providerName).capabilities();\n }\n\n /**\n * Resolve a named extension on the default (or named) provider.\n * Returns `undefined` when the provider does not advertise the\n * extension.\n *\n * @throws if the named provider is unknown or not initialized.\n *\n * @example\n * ```ts\n * const pkg = memory.getExtension<Packager>('package');\n * ```\n */\n getExtension<T>(extensionName: string, providerName?: string): T | undefined {\n this.assertInitialized();\n const provider = this.service.getProvider(providerName);\n return provider.getExtension?.<T>(extensionName);\n }\n\n /**\n * Aggregate status of all configured providers. Never throws:\n * uninitialized providers report `initialized: false` and\n * `capabilities: null`.\n */\n getProviderStatus(): ProviderStatus[] {\n const configured = this.service.getConfiguredProviders();\n const available = new Set(this.service.getAvailableProviders());\n return configured.map((name) => {\n if (!available.has(name)) {\n return { name, initialized: false, capabilities: null };\n }\n return {\n name,\n initialized: true,\n capabilities: this.service.getProvider(name).capabilities(),\n };\n });\n }\n\n /**\n * Access the full AtomicMemory namespace handle (lifecycle, audit,\n * lessons, config, agents). Returns `undefined` when the client is\n * not yet initialized, the `atomicmemory` provider was not included\n * in the `providers` config, or that provider does not advertise the\n * namespace handle. This getter intentionally never throws — callers\n * can guard with a truthy check and let the handle's own methods\n * raise if used incorrectly.\n */\n get atomicmemory(): AtomicMemoryHandle | undefined {\n if (!this.initialized) return undefined;\n if (!this.service.getConfiguredProviders().includes('atomicmemory')) {\n return undefined;\n }\n const provider = this.service.getProvider('atomicmemory');\n return provider.getExtension?.<AtomicMemoryHandle>('atomicmemory.base');\n }\n\n /**\n * Low-level escape hatch for callers that need the concrete provider.\n */\n getProvider(name?: string): MemoryProvider {\n this.assertInitialized();\n return this.service.getProvider(name);\n }\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'MemoryClient is not initialized. Call `await client.initialize()` first.'\n );\n }\n }\n}\n\nfunction pickFirstProviderKey(providers: Record<string, unknown>): string | undefined {\n for (const [key, value] of Object.entries(providers)) {\n if (value !== undefined && key !== 'default') return key;\n }\n return undefined;\n}\n"]}
'use strict';
var chunkGHOB6O5U_cjs = require('./chunk-GHOB6O5U.cjs');
// src/memory/providers/registry.ts
var defaultRegistry = {
atomicmemory: (config) => ({
provider: new chunkGHOB6O5U_cjs.AtomicMemoryProvider(config)
}),
mem0: (config) => ({
provider: new chunkGHOB6O5U_cjs.Mem0Provider(config)
}),
hindsight: (config) => ({
provider: new chunkGHOB6O5U_cjs.HindsightProvider(config)
})
};
// src/memory/memory-service.ts
var MemoryService = class {
constructor(config) {
this.config = config;
this.defaultProviderName = config.defaultProvider;
}
config;
providers = /* @__PURE__ */ new Map();
pipelines = /* @__PURE__ */ new Map();
defaultProviderName;
async initialize(registry = defaultRegistry) {
for (const [name, providerConfig] of Object.entries(
this.config.providerConfigs
)) {
const factory = registry[name];
if (!factory) continue;
const registration = factory(providerConfig);
this.providers.set(name, registration.provider);
this.pipelines.set(
name,
registration.pipeline ?? chunkGHOB6O5U_cjs.noopMemoryPipeline
);
if (registration.provider.initialize) {
await registration.provider.initialize();
}
}
}
getProvider(name) {
const providerName = name ?? this.defaultProviderName;
const provider = this.providers.get(providerName);
if (!provider) {
throw new Error(
`Provider "${providerName}" is not registered`
);
}
return provider;
}
getAvailableProviders() {
return Array.from(this.providers.keys());
}
/**
* Provider names declared in the SDK configuration, regardless of whether
* they have been initialized yet. Useful for UI and getter paths that
* need to advertise capabilities before `initialize()` has run.
*/
getConfiguredProviders() {
return Object.keys(this.config.providerConfigs);
}
// -----------------------------------------------------------------------
// Core operations
// -----------------------------------------------------------------------
async ingest(input, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
if (pipeline.preprocessIngest) {
const inputs = await pipeline.preprocessIngest(input);
const results = [];
for (const i of inputs) {
const result2 = await provider.ingest(i);
if (pipeline.postprocessIngest) {
await pipeline.postprocessIngest(result2, i);
}
results.push(result2);
}
return mergeIngestResults(results);
}
const result = await provider.ingest(input);
if (pipeline.postprocessIngest) {
await pipeline.postprocessIngest(result, input);
}
return result;
}
async search(request, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const processedRequest = pipeline.preprocessSearch ? await pipeline.preprocessSearch(request) : request;
const page = await provider.search(processedRequest);
return pipeline.postprocessSearch ? await pipeline.postprocessSearch(page, processedRequest) : page;
}
async get(ref, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const processedRef = pipeline.preprocessGet ? await pipeline.preprocessGet(ref) : ref;
const memory = await provider.get(processedRef);
return pipeline.postprocessGet ? await pipeline.postprocessGet(memory, processedRef) : memory;
}
async delete(ref, providerName) {
const provider = this.getProvider(providerName);
await provider.delete(ref);
}
async list(request, providerName) {
const provider = this.getProvider(providerName);
const pipeline = this.getPipeline(providerName);
const page = await provider.list(request);
return pipeline.postprocessList ? await pipeline.postprocessList(page, request) : page;
}
async package(request, providerName) {
const provider = this.getProvider(providerName);
const packager = provider.getExtension?.("package");
if (!packager) {
throw new chunkGHOB6O5U_cjs.UnsupportedOperationError(
provider.name,
"package"
);
}
return packager.package(request);
}
// -----------------------------------------------------------------------
// Internals
// -----------------------------------------------------------------------
getPipeline(name) {
const providerName = name ?? this.defaultProviderName;
return this.pipelines.get(providerName) ?? chunkGHOB6O5U_cjs.noopMemoryPipeline;
}
};
function mergeIngestResults(results) {
return {
created: results.flatMap((r) => r.created),
updated: results.flatMap((r) => r.updated),
unchanged: results.flatMap((r) => r.unchanged)
};
}
// src/client/memory-client.ts
var MemoryClient = class {
service;
initialized = false;
constructor(config) {
const providerConfigs = { ...config.providers };
const defaultProvider = config.defaultProvider ?? pickFirstProviderKey(providerConfigs);
if (!defaultProvider) {
throw new Error(
'MemoryClient requires at least one provider config. Pass e.g. { providers: { atomicmemory: { apiUrl: "..." } } }.'
);
}
this.service = new MemoryService({
defaultProvider,
providerConfigs
});
}
/**
* Initialize all configured providers. Must be called before any
* memory operation. Idempotent.
*/
async initialize(registry = defaultRegistry) {
if (this.initialized) return;
await this.service.initialize(registry);
this.initialized = true;
}
/**
* Write memory(ies). Input supports `text`, `messages`, or `memory` modes.
*/
async ingest(input) {
this.assertInitialized();
return this.service.ingest(input);
}
/**
* Ingest without any application-layer gating. Equivalent to `ingest()`
* on the core client; application wrappers override the gated variant
* while delegating this path straight through.
*/
async ingestDirect(input) {
this.assertInitialized();
return this.service.ingest(input);
}
/**
* Search for memories matching the request.
*/
async search(request) {
this.assertInitialized();
return this.service.search(request);
}
/**
* Search without application-layer gating. See `ingestDirect` for the
* rationale.
*/
async searchDirect(request) {
this.assertInitialized();
return this.service.search(request);
}
/**
* Build an injection-ready context package from a scoped request.
* Provider must implement the `package` extension.
*/
async package(request) {
this.assertInitialized();
return this.service.package(request);
}
/**
* Package without application-layer gating.
*/
async packageDirect(request) {
this.assertInitialized();
return this.service.package(request);
}
/**
* Fetch a single memory by reference.
*/
async get(ref) {
this.assertInitialized();
return this.service.get(ref);
}
/**
* Delete a single memory by reference.
*/
async delete(ref) {
this.assertInitialized();
return this.service.delete(ref);
}
/**
* List memories within a scope.
*/
async list(request) {
this.assertInitialized();
return this.service.list(request);
}
/**
* Report the capability surface of the default (or named) provider.
*
* @throws if the named provider is unknown or not initialized.
*/
capabilities(providerName) {
this.assertInitialized();
return this.service.getProvider(providerName).capabilities();
}
/**
* Resolve a named extension on the default (or named) provider.
* Returns `undefined` when the provider does not advertise the
* extension.
*
* @throws if the named provider is unknown or not initialized.
*
* @example
* ```ts
* const pkg = memory.getExtension<Packager>('package');
* ```
*/
getExtension(extensionName, providerName) {
this.assertInitialized();
const provider = this.service.getProvider(providerName);
return provider.getExtension?.(extensionName);
}
/**
* Aggregate status of all configured providers. Never throws:
* uninitialized providers report `initialized: false` and
* `capabilities: null`.
*/
getProviderStatus() {
const configured = this.service.getConfiguredProviders();
const available = new Set(this.service.getAvailableProviders());
return configured.map((name) => {
if (!available.has(name)) {
return { name, initialized: false, capabilities: null };
}
return {
name,
initialized: true,
capabilities: this.service.getProvider(name).capabilities()
};
});
}
/**
* Access the full AtomicMemory namespace handle (lifecycle, audit,
* lessons, config, agents). Returns `undefined` when the client is
* not yet initialized, the `atomicmemory` provider was not included
* in the `providers` config, or that provider does not advertise the
* namespace handle. This getter intentionally never throws — callers
* can guard with a truthy check and let the handle's own methods
* raise if used incorrectly.
*/
get atomicmemory() {
if (!this.initialized) return void 0;
if (!this.service.getConfiguredProviders().includes("atomicmemory")) {
return void 0;
}
const provider = this.service.getProvider("atomicmemory");
return provider.getExtension?.("atomicmemory.base");
}
/**
* Low-level escape hatch for callers that need the concrete provider.
*/
getProvider(name) {
this.assertInitialized();
return this.service.getProvider(name);
}
assertInitialized() {
if (!this.initialized) {
throw new Error(
"MemoryClient is not initialized. Call `await client.initialize()` first."
);
}
}
};
function pickFirstProviderKey(providers) {
for (const [key, value] of Object.entries(providers)) {
if (value !== void 0 && key !== "default") return key;
}
return void 0;
}
exports.MemoryClient = MemoryClient;
//# sourceMappingURL=chunk-BEZ6NCCC.cjs.map
//# sourceMappingURL=chunk-BEZ6NCCC.cjs.map
{"version":3,"sources":["../src/memory/providers/registry.ts","../src/memory/memory-service.ts","../src/client/memory-client.ts"],"names":["AtomicMemoryProvider","Mem0Provider","HindsightProvider","noopMemoryPipeline","result","UnsupportedOperationError"],"mappings":";;;;;AAoBO,IAAM,eAAA,GAAoC;AAAA,EAC/C,YAAA,EAAc,CAAC,MAAA,MAAoE;AAAA,IACjF,QAAA,EAAU,IAAIA,sCAAA,CAAqB,MAAM;AAAA,GAC3C,CAAA;AAAA,EACA,IAAA,EAAM,CAAC,MAAA,MAA4D;AAAA,IACjE,QAAA,EAAU,IAAIC,8BAAA,CAAa,MAAM;AAAA,GACnC,CAAA;AAAA,EACA,SAAA,EAAW,CAAC,MAAA,MAAiE;AAAA,IAC3E,QAAA,EAAU,IAAIC,mCAAA,CAAkB,MAAM;AAAA,GACxC;AACF,CAAA;;;ACIO,IAAM,gBAAN,MAAoB;AAAA,EAKzB,YAA6B,MAAA,EAA6B;AAA7B,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAC3B,IAAA,IAAA,CAAK,sBAAsB,MAAA,CAAO,eAAA;AAAA,EACpC;AAAA,EAF6B,MAAA;AAAA,EAJrB,SAAA,uBAAgB,GAAA,EAA4B;AAAA,EAC5C,SAAA,uBAAgB,GAAA,EAAsC;AAAA,EACtD,mBAAA;AAAA,EAMR,MAAM,UAAA,CACJ,QAAA,GAA6B,eAAA,EACd;AACf,I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EA,SAAS,qBAAqB,SAAA,EAAwD;AACpF,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,SAAS,CAAA,EAAG;AACpD,IAAA,IAAI,KAAA,KAAU,MAAA,IAAa,GAAA,KAAQ,SAAA,EAAW,OAAO,GAAA;AAAA,EACvD;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-BEZ6NCCC.cjs","sourcesContent":["/**\n * @file Memory Provider Registry\n *\n * Maps provider names to factory functions that create\n * MemoryProviderRegistration instances from configuration.\n */\n\nimport type { MemoryProviderRegistration } from '../registration';\nimport type { AtomicMemoryProviderConfig } from '../atomicmemory-provider/types';\nimport { AtomicMemoryProvider } from '../atomicmemory-provider/atomicmemory-provider';\nimport type { Mem0ProviderConfig } from '../mem0-provider/types';\nimport { Mem0Provider } from '../mem0-provider/mem0-provider';\nimport type { HindsightProviderConfig } from '../hindsight-provider/types';\nimport { HindsightProvider } from '../hindsight-provider/hindsight-provider';\n\nexport type ProviderRegistry = Record<\n string,\n (config: any) => MemoryProviderRegistration\n>;\n\nexport const defaultRegistry: ProviderRegistry = {\n atomicmemory: (config: AtomicMemoryProviderConfig): MemoryProviderRegistration => ({\n provider: new AtomicMemoryProvider(config),\n }),\n mem0: (config: Mem0ProviderConfig): MemoryProviderRegistration => ({\n provider: new Mem0Provider(config),\n }),\n hindsight: (config: HindsightProviderConfig): MemoryProviderRegistration => ({\n provider: new HindsightProvider(config),\n }),\n};\n","/**\n * @file Memory Service\n *\n * Replaces UnifiedContextService. Routes operations to the correct\n * provider and applies optional processing pipelines.\n */\n\nimport type { MemoryProvider, Packager } from './provider';\nimport type { MemoryProcessingPipeline } from './pipeline';\nimport { noopMemoryPipeline } from './pipeline';\nimport type { MemoryProviderRegistration } from './registration';\nimport { UnsupportedOperationError } from './errors';\nimport type {\n IngestInput,\n IngestResult,\n SearchRequest,\n SearchResultPage,\n MemoryRef,\n Memory,\n ListRequest,\n ListResultPage,\n PackageRequest,\n ContextPackage,\n} from './types';\nimport {\n defaultRegistry,\n type ProviderRegistry,\n} from './providers/registry';\n\nexport interface MemoryServiceConfig {\n defaultProvider: string;\n providerConfigs: Record<string, unknown>;\n}\n\nexport class MemoryService {\n private providers = new Map<string, MemoryProvider>();\n private pipelines = new Map<string, MemoryProcessingPipeline>();\n private defaultProviderName: string;\n\n constructor(private readonly config: MemoryServiceConfig) {\n this.defaultProviderName = config.defaultProvider;\n }\n\n async initialize(\n registry: ProviderRegistry = defaultRegistry\n ): Promise<void> {\n for (const [name, providerConfig] of Object.entries(\n this.config.providerConfigs\n )) {\n const factory = registry[name];\n if (!factory) continue;\n const registration: MemoryProviderRegistration = factory(providerConfig);\n this.providers.set(name, registration.provider);\n this.pipelines.set(\n name,\n registration.pipeline ?? noopMemoryPipeline\n );\n\n if (registration.provider.initialize) {\n await registration.provider.initialize();\n }\n }\n }\n\n getProvider(name?: string): MemoryProvider {\n const providerName = name ?? this.defaultProviderName;\n const provider = this.providers.get(providerName);\n if (!provider) {\n throw new Error(\n `Provider \"${providerName}\" is not registered`\n );\n }\n return provider;\n }\n\n getAvailableProviders(): string[] {\n return Array.from(this.providers.keys());\n }\n\n /**\n * Provider names declared in the SDK configuration, regardless of whether\n * they have been initialized yet. Useful for UI and getter paths that\n * need to advertise capabilities before `initialize()` has run.\n */\n getConfiguredProviders(): string[] {\n return Object.keys(this.config.providerConfigs);\n }\n\n // -----------------------------------------------------------------------\n // Core operations\n // -----------------------------------------------------------------------\n\n async ingest(\n input: IngestInput,\n providerName?: string\n ): Promise<IngestResult> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n if (pipeline.preprocessIngest) {\n const inputs = await pipeline.preprocessIngest(input);\n const results: IngestResult[] = [];\n for (const i of inputs) {\n const result = await provider.ingest(i);\n if (pipeline.postprocessIngest) {\n await pipeline.postprocessIngest(result, i);\n }\n results.push(result);\n }\n return mergeIngestResults(results);\n }\n\n const result = await provider.ingest(input);\n if (pipeline.postprocessIngest) {\n await pipeline.postprocessIngest(result, input);\n }\n return result;\n }\n\n async search(\n request: SearchRequest,\n providerName?: string\n ): Promise<SearchResultPage> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const processedRequest = pipeline.preprocessSearch\n ? await pipeline.preprocessSearch(request)\n : request;\n\n const page = await provider.search(processedRequest);\n\n return pipeline.postprocessSearch\n ? await pipeline.postprocessSearch(page, processedRequest)\n : page;\n }\n\n async get(\n ref: MemoryRef,\n providerName?: string\n ): Promise<Memory | null> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const processedRef = pipeline.preprocessGet\n ? await pipeline.preprocessGet(ref)\n : ref;\n\n const memory = await provider.get(processedRef);\n\n return pipeline.postprocessGet\n ? await pipeline.postprocessGet(memory, processedRef)\n : memory;\n }\n\n async delete(\n ref: MemoryRef,\n providerName?: string\n ): Promise<void> {\n const provider = this.getProvider(providerName);\n await provider.delete(ref);\n }\n\n async list(\n request: ListRequest,\n providerName?: string\n ): Promise<ListResultPage> {\n const provider = this.getProvider(providerName);\n const pipeline = this.getPipeline(providerName);\n\n const page = await provider.list(request);\n\n return pipeline.postprocessList\n ? await pipeline.postprocessList(page, request)\n : page;\n }\n\n async package(\n request: PackageRequest,\n providerName?: string\n ): Promise<ContextPackage> {\n const provider = this.getProvider(providerName);\n const packager = provider.getExtension?.<Packager>('package');\n if (!packager) {\n throw new UnsupportedOperationError(\n provider.name,\n 'package'\n );\n }\n return packager.package(request);\n }\n\n // -----------------------------------------------------------------------\n // Internals\n // -----------------------------------------------------------------------\n\n private getPipeline(\n name?: string\n ): MemoryProcessingPipeline {\n const providerName = name ?? this.defaultProviderName;\n return (\n this.pipelines.get(providerName) ?? noopMemoryPipeline\n );\n }\n}\n\nfunction mergeIngestResults(\n results: IngestResult[]\n): IngestResult {\n return {\n created: results.flatMap((r) => r.created),\n updated: results.flatMap((r) => r.updated),\n unchanged: results.flatMap((r) => r.unchanged),\n };\n}\n","/**\n * @file MemoryClient — primary public API for the memory-layer SDK\n *\n * Pure memory operations: ingest, search, package, list, get, delete,\n * capability inspection, and provider namespace handles. No policy\n * gating, no platform/targetDomain parameters — applications that need\n * those layer them on top of this client.\n */\n\nimport { MemoryService } from '../memory/memory-service';\nimport type { MemoryProvider } from '../memory/provider';\nimport type { AtomicMemoryProviderConfig } from '../memory/atomicmemory-provider/types';\nimport type { AtomicMemoryHandle } from '../memory/atomicmemory-provider/handle';\nimport type { Mem0ProviderConfig } from '../memory/mem0-provider/types';\nimport type { HindsightProviderConfig } from '../memory/hindsight-provider/types';\nimport type {\n IngestInput,\n IngestResult,\n SearchRequest,\n SearchResultPage,\n MemoryRef,\n Memory,\n ListRequest,\n ListResultPage,\n PackageRequest,\n ContextPackage,\n Capabilities,\n} from '../memory/types';\nimport {\n defaultRegistry,\n type ProviderRegistry,\n} from '../memory/providers/registry';\n\n/**\n * Provider configuration map. Each key names a provider; the value is\n * that provider's configuration object.\n */\nexport interface MemoryProviderConfigs {\n atomicmemory?: AtomicMemoryProviderConfig;\n mem0?: Mem0ProviderConfig;\n hindsight?: HindsightProviderConfig;\n [providerName: string]: unknown;\n}\n\n/**\n * MemoryClient configuration.\n */\nexport interface MemoryClientConfig {\n /** Provider configurations keyed by provider name. */\n providers: MemoryProviderConfigs;\n /** Name of the default provider. If omitted, the first configured provider wins. */\n defaultProvider?: string;\n}\n\n/**\n * Status summary for each configured provider.\n */\nexport interface ProviderStatus {\n name: string;\n initialized: boolean;\n capabilities: Capabilities | null;\n}\n\n/**\n * MemoryClient — pure memory-layer API.\n *\n * @example\n * ```ts\n * const memory = new MemoryClient({\n * providers: { atomicmemory: { apiUrl: 'http://localhost:17350' } },\n * });\n * await memory.initialize();\n * await memory.ingest({ mode: 'text', content: 'hi', scope: { user: 'u1' } });\n * const results = await memory.search({ query: 'hi', scope: { user: 'u1' } });\n * ```\n */\nexport class MemoryClient {\n private readonly service: MemoryService;\n private initialized = false;\n\n constructor(config: MemoryClientConfig) {\n const providerConfigs: Record<string, unknown> = { ...config.providers };\n const defaultProvider =\n config.defaultProvider ?? pickFirstProviderKey(providerConfigs);\n\n if (!defaultProvider) {\n throw new Error(\n 'MemoryClient requires at least one provider config. ' +\n 'Pass e.g. { providers: { atomicmemory: { apiUrl: \"...\" } } }.'\n );\n }\n\n this.service = new MemoryService({\n defaultProvider,\n providerConfigs,\n });\n }\n\n /**\n * Initialize all configured providers. Must be called before any\n * memory operation. Idempotent.\n */\n async initialize(registry: ProviderRegistry = defaultRegistry): Promise<void> {\n if (this.initialized) return;\n await this.service.initialize(registry);\n this.initialized = true;\n }\n\n /**\n * Write memory(ies). Input supports `text`, `messages`, or `memory` modes.\n */\n async ingest(input: IngestInput): Promise<IngestResult> {\n this.assertInitialized();\n return this.service.ingest(input);\n }\n\n /**\n * Ingest without any application-layer gating. Equivalent to `ingest()`\n * on the core client; application wrappers override the gated variant\n * while delegating this path straight through.\n */\n async ingestDirect(input: IngestInput): Promise<IngestResult> {\n this.assertInitialized();\n return this.service.ingest(input);\n }\n\n /**\n * Search for memories matching the request.\n */\n async search(request: SearchRequest): Promise<SearchResultPage> {\n this.assertInitialized();\n return this.service.search(request);\n }\n\n /**\n * Search without application-layer gating. See `ingestDirect` for the\n * rationale.\n */\n async searchDirect(request: SearchRequest): Promise<SearchResultPage> {\n this.assertInitialized();\n return this.service.search(request);\n }\n\n /**\n * Build an injection-ready context package from a scoped request.\n * Provider must implement the `package` extension.\n */\n async package(request: PackageRequest): Promise<ContextPackage> {\n this.assertInitialized();\n return this.service.package(request);\n }\n\n /**\n * Package without application-layer gating.\n */\n async packageDirect(request: PackageRequest): Promise<ContextPackage> {\n this.assertInitialized();\n return this.service.package(request);\n }\n\n /**\n * Fetch a single memory by reference.\n */\n async get(ref: MemoryRef): Promise<Memory | null> {\n this.assertInitialized();\n return this.service.get(ref);\n }\n\n /**\n * Delete a single memory by reference.\n */\n async delete(ref: MemoryRef): Promise<void> {\n this.assertInitialized();\n return this.service.delete(ref);\n }\n\n /**\n * List memories within a scope.\n */\n async list(request: ListRequest): Promise<ListResultPage> {\n this.assertInitialized();\n return this.service.list(request);\n }\n\n /**\n * Report the capability surface of the default (or named) provider.\n *\n * @throws if the named provider is unknown or not initialized.\n */\n capabilities(providerName?: string): Capabilities {\n this.assertInitialized();\n return this.service.getProvider(providerName).capabilities();\n }\n\n /**\n * Resolve a named extension on the default (or named) provider.\n * Returns `undefined` when the provider does not advertise the\n * extension.\n *\n * @throws if the named provider is unknown or not initialized.\n *\n * @example\n * ```ts\n * const pkg = memory.getExtension<Packager>('package');\n * ```\n */\n getExtension<T>(extensionName: string, providerName?: string): T | undefined {\n this.assertInitialized();\n const provider = this.service.getProvider(providerName);\n return provider.getExtension?.<T>(extensionName);\n }\n\n /**\n * Aggregate status of all configured providers. Never throws:\n * uninitialized providers report `initialized: false` and\n * `capabilities: null`.\n */\n getProviderStatus(): ProviderStatus[] {\n const configured = this.service.getConfiguredProviders();\n const available = new Set(this.service.getAvailableProviders());\n return configured.map((name) => {\n if (!available.has(name)) {\n return { name, initialized: false, capabilities: null };\n }\n return {\n name,\n initialized: true,\n capabilities: this.service.getProvider(name).capabilities(),\n };\n });\n }\n\n /**\n * Access the full AtomicMemory namespace handle (lifecycle, audit,\n * lessons, config, agents). Returns `undefined` when the client is\n * not yet initialized, the `atomicmemory` provider was not included\n * in the `providers` config, or that provider does not advertise the\n * namespace handle. This getter intentionally never throws — callers\n * can guard with a truthy check and let the handle's own methods\n * raise if used incorrectly.\n */\n get atomicmemory(): AtomicMemoryHandle | undefined {\n if (!this.initialized) return undefined;\n if (!this.service.getConfiguredProviders().includes('atomicmemory')) {\n return undefined;\n }\n const provider = this.service.getProvider('atomicmemory');\n return provider.getExtension?.<AtomicMemoryHandle>('atomicmemory.base');\n }\n\n /**\n * Low-level escape hatch for callers that need the concrete provider.\n */\n getProvider(name?: string): MemoryProvider {\n this.assertInitialized();\n return this.service.getProvider(name);\n }\n\n private assertInitialized(): void {\n if (!this.initialized) {\n throw new Error(\n 'MemoryClient is not initialized. Call `await client.initialize()` first.'\n );\n }\n }\n}\n\nfunction pickFirstProviderKey(providers: Record<string, unknown>): string | undefined {\n for (const [key, value] of Object.entries(providers)) {\n if (value !== undefined && key !== 'default') return key;\n }\n return undefined;\n}\n"]}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display