🚀. 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.1.0
to
1.1.1
+76
dist/chunk-3HWUP4VL.js
import { isIP } from 'net';
// src/utils/validate-api-url.ts
function isLinkLocalIpv4([a, b]) {
return a === 169 && b === 254;
}
function isPrivateIpv4([a, b]) {
return a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 100 && b >= 64 && b <= 127;
}
function isSpecialIpv4([a, b, c, d]) {
const loopback = a === 127;
const unspecified = a === 0;
const broadcast = a === 255 && b === 255 && c === 255 && d === 255;
const reserved = a === 192 && b === 0 && c === 0 || a >= 240;
const multicast = a >= 224 && a <= 239;
return loopback || unspecified || broadcast || reserved || multicast;
}
function classifyIpv4(host) {
const octets = host.split(".").map(Number);
return {
linkLocal: isLinkLocalIpv4(octets),
blockedByDefault: isPrivateIpv4(octets) || isSpecialIpv4(octets)
};
}
function mappedIpv4(host) {
const rest = host.toLowerCase().match(/^::ffff:(.+)$/)?.[1];
if (rest === void 0) return null;
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(rest)) return rest;
const pair = rest.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
if (!pair) return null;
const hi = parseInt(pair[1], 16);
const lo = parseInt(pair[2], 16);
return `${hi >> 8 & 255}.${hi & 255}.${lo >> 8 & 255}.${lo & 255}`;
}
function classifyIpv6(host) {
const mapped = mappedIpv4(host);
if (mapped) return classifyIpv4(mapped);
const lower = host.toLowerCase();
return {
linkLocal: /^fe[89ab]/.test(lower),
// fe80::/10
blockedByDefault: lower === "::1" || lower === "::" || /^f[cd]/.test(lower)
// loopback, unspecified, fc00::/7 ULA
};
}
function validateApiUrl(value, options = {}) {
const stripped = value.trim();
let parsed;
try {
parsed = new URL(stripped);
} catch {
throw new Error("api_url must be an http(s) URL");
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error("api_url must be an http(s) URL");
}
const host = parsed.hostname.replace(/^\[|\]$/g, "");
if (!host) throw new Error("api_url must include a host");
const kind = isIP(host);
if (kind === 0) return stripped;
const ipClass = kind === 4 ? classifyIpv4(host) : classifyIpv6(host);
if (ipClass.linkLocal) {
throw new Error("api_url must not target a link-local or cloud-metadata address");
}
const allowPrivate = options.allowPrivateNetworks ?? true;
if (!allowPrivate && ipClass.blockedByDefault) {
throw new Error(
"api_url must not target a loopback, private, or reserved address; set allowPrivateNetworks=true to permit it"
);
}
return stripped;
}
export { validateApiUrl };
//# sourceMappingURL=chunk-3HWUP4VL.js.map
//# sourceMappingURL=chunk-3HWUP4VL.js.map
{"version":3,"sources":["../src/utils/validate-api-url.ts"],"names":[],"mappings":";;;AA2CA,SAAS,eAAA,CAAgB,CAAC,CAAA,EAAG,CAAC,CAAA,EAAoB;AAChD,EAAA,OAAO,CAAA,KAAM,OAAO,CAAA,KAAM,GAAA;AAC5B;AAGA,SAAS,aAAA,CAAc,CAAC,CAAA,EAAG,CAAC,CAAA,EAAoB;AAC9C,EAAA,OACE,MAAM,EAAA,IACL,CAAA,KAAM,GAAA,IAAO,CAAA,IAAK,MAAM,CAAA,IAAK,EAAA,IAC7B,CAAA,KAAM,GAAA,IAAO,MAAM,GAAA,IACnB,CAAA,KAAM,GAAA,IAAO,CAAA,IAAK,MAAM,CAAA,IAAK,GAAA;AAElC;AAGA,SAAS,cAAc,CAAC,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAC,CAAA,EAAoB;AACpD,EAAA,MAAM,WAAW,CAAA,KAAM,GAAA;AACvB,EAAA,MAAM,cAAc,CAAA,KAAM,CAAA;AAC1B,EAAA,MAAM,YAAY,CAAA,KAAM,GAAA,IAAO,MAAM,GAAA,IAAO,CAAA,KAAM,OAAO,CAAA,KAAM,GAAA;AAC/D,EAAA,MAAM,WAAY,C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AM,YAAA,GAAe,QAAQ,oBAAA,IAAwB,IAAA;AACrD,EAAA,IAAI,CAAC,YAAA,IAAgB,OAAA,CAAQ,gBAAA,EAAkB;AAC7C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACA,EAAA,OAAO,QAAA;AACT","file":"chunk-3HWUP4VL.js","sourcesContent":["/**\n * @file Shared `api_url` SSRF guard for every SDK client/provider config.\n *\n * Port of the python SDK's `atomicmemory/core/url.py` (AGNT-PY-001). An\n * `api_url` must be an http(s) URL with a host. Link-local addresses — the\n * cloud metadata endpoint `169.254.169.254` (`169.254.0.0/16`) and IPv6\n * `fe80::/10` — are ALWAYS rejected. Loopback / private / reserved literals\n * (incl. the `100.64.0.0/10` CGN range) are ALLOWED BY DEFAULT, since the SDK\n * routinely connects to local and self-hosted cores; pass\n * `allowPrivateNetworks: false` to reject those too (posture B).\n *\n * `URL` normalizes the legacy IPv4 encodings the OS resolver still accepts —\n * decimal (`http://2852039166/`), hex, octal, and short forms — to dotted-quad,\n * so they cannot slip through as hostnames. IPv4-mapped IPv6 (`::ffff:a.b.c.d`)\n * is reclassified by its embedded IPv4. Genuine hostnames (incl. the `localhost`\n * default and `metadata.google.internal`) are intentionally NOT DNS-resolved\n * here — config-time resolution is racy and still bypassable via DNS rebinding;\n * deployments that must defend against hostname-based metadata access should pin\n * `api_url` to a vetted host.\n */\nimport { isIP } from 'node:net';\n\nexport interface ValidateApiUrlOptions {\n /**\n * Permit loopback / private / reserved IP literals (self-hosted / local dev).\n * Defaults to `true`: the SDK routinely connects to private/local cores, so\n * the security floor is the always-on link-local / cloud-metadata block. Set\n * `false` to also reject loopback/private/reserved (stricter, e.g. a hosted\n * multi-tenant deployment). Matches the python SDK's posture.\n */\n allowPrivateNetworks?: boolean;\n}\n\ninterface IpClass {\n /** Link-local / cloud-metadata — always rejected regardless of the opt-in. */\n linkLocal: boolean;\n /** Loopback / private / reserved / multicast / unspecified — gated by the opt-in. */\n blockedByDefault: boolean;\n}\n\ntype Octets = [number, number, number, number];\n\n/** 169.254.0.0/16 — AWS/GCP/Azure instance metadata (IMDS); always blocked. */\nfunction isLinkLocalIpv4([a, b]: Octets): boolean {\n return a === 169 && b === 254;\n}\n\n/** RFC 1918 + 100.64.0.0/10 CGN (e.g. Alibaba metadata). */\nfunction isPrivateIpv4([a, b]: Octets): boolean {\n return (\n a === 10 ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 100 && b >= 64 && b <= 127)\n );\n}\n\n/** Loopback, \"this network\", broadcast, reserved, and multicast ranges. */\nfunction isSpecialIpv4([a, b, c, d]: Octets): boolean {\n const loopback = a === 127; // 127.0.0.0/8\n const unspecified = a === 0; // 0.0.0.0/8 \"this network\"\n const broadcast = a === 255 && b === 255 && c === 255 && d === 255;\n const reserved = (a === 192 && b === 0 && c === 0) || a >= 240; // 192.0.0.0/24, 240.0.0.0/4\n const multicast = a >= 224 && a <= 239; // 224.0.0.0/4\n return loopback || unspecified || broadcast || reserved || multicast;\n}\n\nfunction classifyIpv4(host: string): IpClass {\n const octets = host.split('.').map(Number) as Octets;\n return {\n linkLocal: isLinkLocalIpv4(octets),\n blockedByDefault: isPrivateIpv4(octets) || isSpecialIpv4(octets),\n };\n}\n\nfunction mappedIpv4(host: string): string | null {\n const rest = host.toLowerCase().match(/^::ffff:(.+)$/)?.[1];\n if (rest === undefined) return null;\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(rest)) return rest;\n const pair = rest.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n if (!pair) return null;\n const hi = parseInt(pair[1], 16);\n const lo = parseInt(pair[2], 16);\n return `${(hi >> 8) & 255}.${hi & 255}.${(lo >> 8) & 255}.${lo & 255}`;\n}\n\nfunction classifyIpv6(host: string): IpClass {\n const mapped = mappedIpv4(host);\n if (mapped) return classifyIpv4(mapped);\n const lower = host.toLowerCase();\n return {\n linkLocal: /^fe[89ab]/.test(lower), // fe80::/10\n blockedByDefault: lower === '::1' || lower === '::' || /^f[cd]/.test(lower), // loopback, unspecified, fc00::/7 ULA\n };\n}\n\n/**\n * Validate and normalize an `api_url`, guarding against SSRF.\n *\n * @param value - The candidate URL.\n * @param options - `allowPrivateNetworks` permits loopback/private/reserved IP\n * literals; link-local / cloud-metadata addresses are rejected regardless.\n * @returns The whitespace-trimmed URL.\n * @throws Error if the scheme is not http(s), the host is missing, or the host\n * is a disallowed IP literal.\n */\nexport function validateApiUrl(value: string, options: ValidateApiUrlOptions = {}): string {\n const stripped = value.trim();\n let parsed: URL;\n try {\n parsed = new URL(stripped);\n } catch {\n throw new Error('api_url must be an http(s) URL');\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error('api_url must be an http(s) URL');\n }\n const host = parsed.hostname.replace(/^\\[|\\]$/g, '');\n if (!host) throw new Error('api_url must include a host');\n\n const kind = isIP(host);\n if (kind === 0) return stripped; // hostname — intentionally not DNS-resolved\n\n const ipClass = kind === 4 ? classifyIpv4(host) : classifyIpv6(host);\n if (ipClass.linkLocal) {\n throw new Error('api_url must not target a link-local or cloud-metadata address');\n }\n const allowPrivate = options.allowPrivateNetworks ?? true;\n if (!allowPrivate && ipClass.blockedByDefault) {\n throw new Error(\n 'api_url must not target a loopback, private, or reserved address; ' +\n 'set allowPrivateNetworks=true to permit it',\n );\n }\n return stripped;\n}\n"]}
'use strict';
var chunkWSP2HCUV_cjs = require('./chunk-WSP2HCUV.cjs');
// src/memory/providers/registry.ts
var defaultRegistry = {
atomicmemory: (config) => ({
provider: new chunkWSP2HCUV_cjs.AtomicMemoryProvider(config)
}),
mem0: (config) => ({
provider: new chunkWSP2HCUV_cjs.Mem0Provider(config)
}),
hindsight: (config) => ({
provider: new chunkWSP2HCUV_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 ?? chunkWSP2HCUV_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 chunkWSP2HCUV_cjs.UnsupportedOperationError(
provider.name,
"package"
);
}
return packager.package(request);
}
// -----------------------------------------------------------------------
// Internals
// -----------------------------------------------------------------------
getPipeline(name) {
const providerName = name ?? this.defaultProviderName;
return this.pipelines.get(providerName) ?? chunkWSP2HCUV_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-AQHNXVMQ.cjs.map
//# sourceMappingURL=chunk-AQHNXVMQ.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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":["/**\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

import { HindsightProvider, Mem0Provider, AtomicMemoryProvider, noopMemoryPipeline, UnsupportedOperationError } from './chunk-KI5UNWJI.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-KYVD7KQV.js.map
//# sourceMappingURL=chunk-KYVD7KQV.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,CAA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ACT;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-KYVD7KQV.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"]}
import { validateApiUrl } from './chunk-3HWUP4VL.js';
// src/storage/errors.ts
var StorageClientError = class extends Error {
errorCode;
status;
bodyText;
constructor(args) {
super(args.message);
this.name = "StorageClientError";
this.errorCode = args.errorCode;
this.status = args.status;
this.bodyText = args.bodyText;
}
};
var UnsupportedCapabilityError = class extends StorageClientError {
capability;
constructor(args) {
super({
message: args.message,
errorCode: "unsupported_capability",
status: 400,
bodyText: args.bodyText
});
this.name = "UnsupportedCapabilityError";
this.capability = args.capability;
}
};
var ArtifactNotFoundError = class extends StorageClientError {
artifactId;
constructor(args) {
super({
message: `Storage artifact ${args.artifactId} not found`,
errorCode: "artifact_not_found",
status: 404,
bodyText: args.bodyText
});
this.name = "ArtifactNotFoundError";
this.artifactId = args.artifactId;
}
};
var ArtifactInUseError = class extends StorageClientError {
artifactId;
referencedByDocumentCount;
constructor(args) {
super({
message: `Storage artifact ${args.artifactId} is referenced by ${args.referencedByDocumentCount} document(s); pass 'policy: "with_documents"' to cascade`,
errorCode: "artifact_in_use",
status: 409,
bodyText: args.bodyText
});
this.name = "ArtifactInUseError";
this.artifactId = args.artifactId;
this.referencedByDocumentCount = args.referencedByDocumentCount;
}
};
var PointerContentNotManagedError = class extends StorageClientError {
artifactId;
uri;
constructor(args) {
super({
message: `Artifact ${args.artifactId} is pointer-mode; fetch the URI directly (the server does not proxy pointer content)`,
errorCode: "pointer_content_not_managed",
status: 409,
bodyText: args.bodyText
});
this.name = "PointerContentNotManagedError";
this.artifactId = args.artifactId;
this.uri = args.uri;
}
};
var FilecoinDirectStorageNotSupportedError = class extends StorageClientError {
constructor(args) {
super({
message: "Direct Filecoin artifact uploads are not supported in this version. Use document ingestion or pointer mode.",
errorCode: "filecoin_direct_storage_not_yet_supported",
status: 501,
bodyText: args.bodyText
});
this.name = "FilecoinDirectStorageNotSupportedError";
}
};
// src/storage/client.ts
var METADATA_HEADER = "X-AtomicMemory-Metadata";
var ConcreteStorageClient = class {
apiUrl;
apiKey;
userId;
fetchImpl;
constructor(config) {
if (!config.apiUrl) throw new Error("StorageClient: apiUrl is required");
if (!config.apiKey) throw new Error("StorageClient: apiKey is required");
if (!config.userId) throw new Error("StorageClient: userId is required");
this.apiUrl = validateApiUrl(config.apiUrl, {
allowPrivateNetworks: config.allowPrivateNetworks
}).replace(/\/+$/, "");
this.apiKey = config.apiKey;
this.userId = config.userId;
this.fetchImpl = config.fetch ?? fetch;
}
async capabilities() {
const res = await this.request("GET", "/v1/storage/capabilities");
return await res.json();
}
async put(input) {
if (input.mode === "pointer") return this.putPointer(input);
return this.putManaged(input);
}
async get(ref) {
const id = this.requireArtifactId(ref);
const res = await this.request("GET", `/v1/storage/artifacts/${id}`, {}, id);
return mapStoredArtifact(await res.json());
}
async getContent(ref) {
const id = this.requireArtifactId(ref);
return this.request("GET", `/v1/storage/artifacts/${id}/content`, {}, id);
}
async head(ref) {
const id = this.requireArtifactId(ref);
const res = await this.request("HEAD", `/v1/storage/artifacts/${id}`, {}, id);
return mapHeadHeaders(res.headers, id);
}
async delete(ref, options) {
const id = this.requireArtifactId(ref);
const query = options?.policy ? `?policy=${encodeURIComponent(options.policy)}` : "";
const res = await this.request("DELETE", `/v1/storage/artifacts/${id}${query}`, {}, id);
return mapDeleteResult(await res.json());
}
async verify(ref, _options) {
const id = this.requireArtifactId(ref);
const res = await this.request("POST", `/v1/storage/artifacts/${id}/verify`, {}, id);
return mapVerifyResult(await res.json());
}
async putPointer(input) {
const body = {
mode: "pointer",
uri: input.uri,
content_type: input.contentType,
...input.sizeBytes !== void 0 ? { size_bytes: input.sizeBytes } : {},
...input.contentHash !== void 0 ? { content_hash: input.contentHash } : {},
...input.metadata !== void 0 ? { metadata: input.metadata } : {}
};
const res = await this.request("POST", "/v1/storage/artifacts", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
return mapStoredArtifact(await res.json());
}
async putManaged(input) {
const view = coerceManagedBody(input.body);
const params = new URLSearchParams({ mode: "managed" });
if (input.discloseContentHash === true) params.set("disclose_content_hash", "true");
const headers = {
"Content-Type": input.contentType,
"Content-Length": String(view.byteLength)
};
if (input.metadata !== void 0) {
headers[METADATA_HEADER] = encodeMetadataHeader(input.metadata);
}
const res = await this.request(
"POST",
`/v1/storage/artifacts?${params.toString()}`,
// Cast: Node's fetch accepts Uint8Array as BodyInit, but the
// shared lib.dom type predates that. Sending the view directly
// is intentional — see the comment above coerceManagedBody.
{ headers, body: view }
);
return mapStoredArtifact(await res.json());
}
/**
* Send a request to the storage API and map non-2xx responses to
* typed errors. Callers receive the raw `Response` on success and
* read the body themselves so streaming reads (e.g. getContent)
* can stay zero-copy.
*
* Auth contract: owner identity travels on the
* `X-AtomicMemory-User-Id` request header alongside the
* deployment-wide `Authorization: Bearer <apiKey>`. The legacy
* `?user_id=` URL parameter is NEVER serialized — the server's
* auth middleware rejects it with 400 `legacy_user_id_unsupported`.
*
* Transport-level fetch failures (DNS, ECONNREFUSED, AbortError,
* a misconfigured fetch impl that throws synchronously) are
* wrapped as `StorageClientError({errorCode:'network_error',
* status:0})` so callers can branch on a stable error contract
* instead of catching arbitrary `TypeError`s.
*
* `artifactId`, when supplied, threads into the error mapper so
* `ArtifactNotFoundError` / `ArtifactInUseError` /
* `PointerContentNotManagedError` carry the id the caller already
* knows. The capabilities route omits it (no artifact context).
*/
async request(method, path, init = {}, artifactId) {
const url = `${this.apiUrl}${path}`;
let res;
try {
res = await this.fetchImpl(url, {
method,
headers: {
Authorization: `Bearer ${this.apiKey}`,
"X-AtomicMemory-User-Id": this.userId,
...init.headers ?? {}
},
body: init.body
});
} catch (cause) {
throw new StorageClientError({
message: `Network error while calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
errorCode: "network_error",
status: 0,
bodyText: ""
});
}
if (res.ok) return res;
await throwForResponse(res, artifactId);
throw new StorageClientError({
message: `unexpected non-ok response (${res.status})`,
errorCode: "unexpected_response",
status: res.status,
bodyText: ""
});
}
requireArtifactId(ref) {
if (!ref.artifactId) {
throw new StorageClientError({
message: "ArtifactRef.artifactId is required for this operation in v1",
errorCode: "missing_artifact_id",
status: 0,
bodyText: ""
});
}
return ref.artifactId;
}
};
var STORAGE_MODES = ["pointer", "managed"];
var STORAGE_STATUSES = [
"stored",
"pending",
"available",
"unavailable",
"deleting",
"deleted",
"delete_failed",
"failed"
];
var CONTENT_ENCODINGS = ["identity", "aes_gcm"];
function parseSize(value) {
if (value === null) return null;
const n = Number(value);
if (!Number.isFinite(n) || n < 0) return null;
return n;
}
function mapHeadHeaders(headers, fallbackId) {
const modeRaw = headers.get("x-atomicmemory-storage-mode");
const statusRaw = headers.get("x-atomicmemory-storage-status");
if (modeRaw === null || !STORAGE_MODES.includes(modeRaw)) {
throw new StorageClientError({
message: `head(): server returned an unrecognized x-atomicmemory-storage-mode value ('${modeRaw ?? "<missing>"}'). Expected one of: ${STORAGE_MODES.join(", ")}.`,
errorCode: "invalid_head_response",
status: 200,
bodyText: ""
});
}
if (statusRaw === null || !STORAGE_STATUSES.includes(statusRaw)) {
throw new StorageClientError({
message: `head(): server returned an unrecognized x-atomicmemory-storage-status value ('${statusRaw ?? "<missing>"}'). Expected one of: ${STORAGE_STATUSES.join(", ")}.`,
errorCode: "invalid_head_response",
status: 200,
bodyText: ""
});
}
return {
artifactId: headers.get("x-atomicmemory-artifact-id") ?? fallbackId,
provider: headers.get("x-atomicmemory-provider") ?? "",
mode: modeRaw,
status: statusRaw,
sizeBytes: parseSize(headers.get("content-length")),
contentType: headers.get("content-type")
};
}
function coerceManagedBody(body) {
if (Buffer.isBuffer(body)) {
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
}
if (body instanceof Uint8Array) return body;
if (body instanceof ArrayBuffer) return new Uint8Array(body);
if (typeof Blob !== "undefined" && body instanceof Blob) {
throw new StorageClientError({
message: "StorageClient.put: Blob input must be converted to Buffer / Uint8Array / ArrayBuffer before calling put(). Use `new Uint8Array(await blob.arrayBuffer())`.",
errorCode: "unsupported_body_type",
status: 0,
bodyText: ""
});
}
throw new StorageClientError({
message: "StorageClient.put: only Buffer / Uint8Array / ArrayBuffer are accepted in v1. Streaming body uploads land in the Streaming + Resumable Uploads PR.",
errorCode: "streaming_body_not_supported",
status: 0,
bodyText: ""
});
}
function encodeMetadataHeader(metadata) {
return Buffer.from(JSON.stringify(metadata), "utf8").toString("base64");
}
function mapStoredArtifact(raw) {
const artifactId = requireWireString(raw, "artifact_id");
const provider = requireWireString(raw, "provider");
const mode = requireWireEnum(raw, "mode", STORAGE_MODES);
const status = requireWireEnum(raw, "status", STORAGE_STATUSES);
const contentEncoding = requireWireEnum(
raw,
"content_encoding",
CONTENT_ENCODINGS
);
const createdAt = requireWireString(raw, "created_at");
const updatedAt = requireWireString(raw, "updated_at");
const out = {
artifactId,
provider,
mode,
uri: typeof raw.uri === "string" ? raw.uri : null,
status,
sizeBytes: typeof raw.size_bytes === "number" ? raw.size_bytes : null,
contentType: typeof raw.content_type === "string" ? raw.content_type : null,
contentEncoding,
identifiers: raw.identifiers ?? {},
lifecycle: raw.lifecycle ?? {},
metadata: raw.metadata ?? {},
createdAt,
updatedAt
};
if (typeof raw.content_hash === "string") out.contentHash = raw.content_hash;
if (raw.provider_details && typeof raw.provider_details === "object") {
out.providerDetails = raw.provider_details;
}
if (raw.replication && typeof raw.replication === "object") {
out.replication = raw.replication;
}
if (raw.verification && typeof raw.verification === "object") {
out.verification = raw.verification;
}
if (raw.retrieval && typeof raw.retrieval === "object") {
out.retrieval = raw.retrieval;
}
return out;
}
function requireWireString(raw, field) {
const value = raw[field];
if (typeof value !== "string" || value.length === 0) {
throw new StorageClientError({
message: `mapStoredArtifact: server response is missing required \`${field}\` (or it is not a non-empty string). The storage API contract requires it.`,
errorCode: "invalid_storage_response",
status: 200,
bodyText: ""
});
}
return value;
}
function requireWireEnum(raw, field, allowed) {
const value = raw[field];
if (typeof value !== "string" || !allowed.includes(value)) {
throw new StorageClientError({
message: `mapStoredArtifact: server response field \`${field}\` is not in the SDK's closed enum. Got '${String(value ?? "<missing>")}', expected one of: ${allowed.join(", ")}.`,
errorCode: "invalid_storage_response",
status: 200,
bodyText: ""
});
}
return value;
}
function mapDeleteResult(raw) {
const artifactId = requireWireString(raw, "artifact_id");
const status = requireWireEnum(raw, "status", STORAGE_STATUSES);
const out = { artifactId, status };
if (Array.isArray(raw.cascaded_document_ids)) {
out.cascadedDocumentIds = raw.cascaded_document_ids.map(String);
}
return out;
}
function mapVerifyResult(raw) {
const kind = raw.kind;
if (kind === "verified") {
return { kind: "verified", details: raw.details ?? {} };
}
if (kind === "failed") {
return { kind: "failed", reason: String(raw.reason ?? "unknown failure") };
}
return { kind: "unsupported", reason: String(raw.reason ?? "unsupported") };
}
async function throwForResponse(res, artifactId) {
const bodyText = await res.text();
const envelope = parseEnvelope(bodyText);
const code = envelope.error_code;
const message = envelope.error ?? `request failed with status ${res.status}`;
const id = artifactId ?? "";
if (code === "artifact_in_use") {
throw new ArtifactInUseError({
artifactId: id,
referencedByDocumentCount: envelope.referenced_by_document_count ?? 0,
bodyText
});
}
if (code === "pointer_content_not_managed") {
throw new PointerContentNotManagedError({
artifactId: id,
uri: envelope.uri ?? "",
bodyText
});
}
if (code === "filecoin_direct_storage_not_yet_supported") {
throw new FilecoinDirectStorageNotSupportedError({ bodyText });
}
if (code === "artifact_not_found" || res.status === 404) {
throw new ArtifactNotFoundError({ artifactId: id, bodyText });
}
if (code === "unsupported_capability") {
throw new UnsupportedCapabilityError({
capability: "unknown",
message,
bodyText
});
}
throw new StorageClientError({
message,
errorCode: code ?? `http_${res.status}`,
status: res.status,
bodyText
});
}
function parseEnvelope(bodyText) {
if (bodyText.length === 0) return {};
try {
return JSON.parse(bodyText);
} catch {
return {};
}
}
export { ArtifactInUseError, ArtifactNotFoundError, ConcreteStorageClient, FilecoinDirectStorageNotSupportedError, PointerContentNotManagedError, StorageClientError, UnsupportedCapabilityError };
//# sourceMappingURL=chunk-LCCTVUJO.js.map
//# sourceMappingURL=chunk-LCCTVUJO.js.map
{"version":3,"sources":["../src/stor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D,IAAA,MAAM,IAAI,qBAAA,CAAsB,EAAE,UAAA,EAAY,EAAA,EAAI,UAAU,CAAA;AAAA,EAC9D;AACA,EAAA,IAAI,SAAS,wBAAA,EAA0B;AACrC,IAAA,MAAM,IAAI,0BAAA,CAA2B;AAAA,MACnC,UAAA,EAAY,SAAA;AAAA,MACZ,OAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AACA,EAAA,MAAM,IAAI,kBAAA,CAAmB;AAAA,IAC3B,OAAA;AAAA,IACA,SAAA,EAAW,IAAA,IAAQ,CAAA,KAAA,EAAQ,GAAA,CAAI,MAAM,CAAA,CAAA;AAAA,IACrC,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ;AAAA,GACD,CAAA;AACH;AAEA,SAAS,cAAc,QAAA,EAAqC;AAC1D,EAAA,IAAI,QAAA,CAAS,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AACnC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAM,QAAQ,CAAA;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF","file":"chunk-LCCTVUJO.js","sourcesContent":["/**\n * @file Artifact-storage error classes.\n *\n * Instanceof-checkable error classes the SDK throws from\n * `client.storage.*` methods. v1 exports the class shapes only\n * — no message formatting magic.\n *\n * Why classes (not enums): callers can `catch (err)\n * { if (err instanceof ArtifactInUseError) { ... } }` without\n * pattern-matching on `error_code` strings, and bundled stack\n * traces survive code minification.\n */\n\n/**\n * Base class for everything `client.storage.*` throws when the\n * server returns a typed error envelope. `errorCode` mirrors the\n * server's `error_code` field — opaque, snake_case, stable.\n */\nexport class StorageClientError extends Error {\n readonly errorCode: string;\n readonly status: number;\n readonly bodyText: string;\n constructor(args: {\n message: string;\n errorCode: string;\n status: number;\n bodyText: string;\n }) {\n super(args.message);\n this.name = 'StorageClientError';\n this.errorCode = args.errorCode;\n this.status = args.status;\n this.bodyText = args.bodyText;\n }\n}\n\n/**\n * Thrown when a capability the call assumes (range read, bundles,\n * `hash_verify` mode) isn't supported by the active backend.\n */\nexport class UnsupportedCapabilityError extends StorageClientError {\n readonly capability: string;\n constructor(args: {\n capability: string;\n message: string;\n bodyText: string;\n }) {\n super({\n message: args.message,\n errorCode: 'unsupported_capability',\n status: 400,\n bodyText: args.bodyText,\n });\n this.name = 'UnsupportedCapabilityError';\n this.capability = args.capability;\n }\n}\n\n/** Thrown when `get` / `head` / `delete` / `verify` cannot find the artifact. */\nexport class ArtifactNotFoundError extends StorageClientError {\n readonly artifactId: string;\n constructor(args: { artifactId: string; bodyText: string }) {\n super({\n message: `Storage artifact ${args.artifactId} not found`,\n errorCode: 'artifact_not_found',\n status: 404,\n bodyText: args.bodyText,\n });\n this.name = 'ArtifactNotFoundError';\n this.artifactId = args.artifactId;\n }\n}\n\n/**\n * Thrown when a default delete hits a referenced artifact. Server\n * returns 409 with `referenced_by_document_count`; callers can use\n * `?policy=with_documents` to cascade.\n */\nexport class ArtifactInUseError extends StorageClientError {\n readonly artifactId: string;\n readonly referencedByDocumentCount: number;\n constructor(args: {\n artifactId: string;\n referencedByDocumentCount: number;\n bodyText: string;\n }) {\n super({\n message:\n `Storage artifact ${args.artifactId} is referenced by ` +\n `${args.referencedByDocumentCount} document(s); pass ` +\n `'policy: \\\"with_documents\\\"' to cascade`,\n errorCode: 'artifact_in_use',\n status: 409,\n bodyText: args.bodyText,\n });\n this.name = 'ArtifactInUseError';\n this.artifactId = args.artifactId;\n this.referencedByDocumentCount = args.referencedByDocumentCount;\n }\n}\n\n/**\n * Thrown when `getContent` targets a pointer-mode artifact. v1\n * pointers are metadata-only — the server NEVER proxies external\n * bytes. Caller must fetch the URI directly.\n */\nexport class PointerContentNotManagedError extends StorageClientError {\n readonly artifactId: string;\n readonly uri: string;\n constructor(args: { artifactId: string; uri: string; bodyText: string }) {\n super({\n message:\n `Artifact ${args.artifactId} is pointer-mode; fetch the URI ` +\n `directly (the server does not proxy pointer content)`,\n errorCode: 'pointer_content_not_managed',\n status: 409,\n bodyText: args.bodyText,\n });\n this.name = 'PointerContentNotManagedError';\n this.artifactId = args.artifactId;\n this.uri = args.uri;\n }\n}\n\n/**\n * Thrown when a managed put against a Filecoin backend hits the v1\n * carve-out (direct Filecoin uploads require artifact reconciliation,\n * which is not implemented yet). Callers can use document ingestion\n * (`PUT /v1/documents/:id/raw`) or pointer mode against Filecoin.\n */\nexport class FilecoinDirectStorageNotSupportedError extends StorageClientError {\n constructor(args: { bodyText: string }) {\n super({\n message:\n 'Direct Filecoin artifact uploads are not supported in this ' +\n 'version. Use document ingestion or pointer mode.',\n errorCode: 'filecoin_direct_storage_not_yet_supported',\n status: 501,\n bodyText: args.bodyText,\n });\n this.name = 'FilecoinDirectStorageNotSupportedError';\n }\n}\n","/**\n * @file Concrete `StorageClient` implementation.\n *\n * Wraps `fetch` to call the direct storage API\n * (`/v1/storage/artifacts/*`). The SDK is server-side only —\n * `Authorization: Bearer <apiKey>` is sent from a trusted process;\n * browser callers must proxy through a server they control.\n *\n * Managed-mode bodies are restricted to known-length values\n * (`Buffer | Uint8Array | ArrayBuffer`) so the client can compute\n * `Content-Length` before sending — the server requires it. Streams\n * (`ReadableStream`, Node `Readable`) are explicitly rejected with\n * `streaming_body_not_supported`; `Blob` is rejected with\n * `unsupported_body_type` so the silent buffering needed to compute\n * `Content-Length` stays visible at the call site (convert with\n * `new Uint8Array(await blob.arrayBuffer())` first). Streaming +\n * resumable uploads land in a follow-up PR.\n *\n * Wire mapping: core emits snake_case (`artifact_id`,\n * `cascaded_document_ids`); the SDK's public types use camelCase for\n * the top-level handles (`artifactId`, `cascadedDocumentIds`). The\n * client is the single seam that translates.\n */\n\nimport { validateApiUrl } from '../utils/validate-api-url.js';\nimport {\n ArtifactInUseError,\n ArtifactNotFoundError,\n FilecoinDirectStorageNotSupportedError,\n PointerContentNotManagedError,\n StorageClientError,\n UnsupportedCapabilityError,\n} from './errors.js';\nimport type { StorageClient } from './interfaces.js';\nimport type {\n ArtifactBody,\n ArtifactHead,\n ArtifactRef,\n DeleteArtifactOptions,\n DeleteArtifactResult,\n PutArtifactInput,\n PutManagedInput,\n StorageArtifactStatus,\n StorageCapabilities,\n StorageLifecycle,\n StoredArtifact,\n VerificationResult,\n VerifyArtifactOptions,\n} from './types.js';\n\n/** Caller-supplied configuration for the concrete client. */\nexport interface StorageClientConfig {\n apiUrl: string;\n apiKey: string;\n /**\n * Permit `apiUrl` to target loopback / private / reserved IP literals.\n * Defaults to `true`; set `false` to harden against SSRF. Link-local /\n * cloud-metadata addresses are blocked regardless. See `validateApiUrl`.\n */\n allowPrivateNetworks?: boolean;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n /** Owner scope for the caller. Sent as `X-AtomicMemory-User-Id`\n * on every storage request. The legacy `?user_id=` URL parameter\n * is not used — the server rejects it with 400\n * `legacy_user_id_unsupported`. */\n userId: string;\n}\n\nconst METADATA_HEADER = 'X-AtomicMemory-Metadata';\n\n/** Wire-shape JSON envelope the core route layer emits on errors. */\ninterface CoreErrorEnvelope {\n error_code?: string;\n error?: string;\n uri?: string;\n referenced_by_document_count?: number;\n allowed_schemes?: ReadonlyArray<string>;\n}\n\nexport class ConcreteStorageClient implements StorageClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly userId: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: StorageClientConfig) {\n if (!config.apiUrl) throw new Error('StorageClient: apiUrl is required');\n if (!config.apiKey) throw new Error('StorageClient: apiKey is required');\n if (!config.userId) throw new Error('StorageClient: userId is required');\n this.apiUrl = validateApiUrl(config.apiUrl, {\n allowPrivateNetworks: config.allowPrivateNetworks,\n }).replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.userId = config.userId;\n this.fetchImpl = config.fetch ?? fetch;\n }\n\n async capabilities(): Promise<StorageCapabilities> {\n const res = await this.request('GET', '/v1/storage/capabilities');\n return (await res.json()) as StorageCapabilities;\n }\n\n async put(input: PutArtifactInput): Promise<StoredArtifact> {\n if (input.mode === 'pointer') return this.putPointer(input);\n return this.putManaged(input);\n }\n\n async get(ref: ArtifactRef): Promise<StoredArtifact> {\n const id = this.requireArtifactId(ref);\n const res = await this.request('GET', `/v1/storage/artifacts/${id}`, {}, id);\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n async getContent(ref: ArtifactRef): Promise<ArtifactBody> {\n const id = this.requireArtifactId(ref);\n return this.request('GET', `/v1/storage/artifacts/${id}/content`, {}, id);\n }\n\n async head(ref: ArtifactRef): Promise<ArtifactHead> {\n const id = this.requireArtifactId(ref);\n const res = await this.request('HEAD', `/v1/storage/artifacts/${id}`, {}, id);\n return mapHeadHeaders(res.headers, id);\n }\n\n async delete(\n ref: ArtifactRef,\n options?: DeleteArtifactOptions,\n ): Promise<DeleteArtifactResult> {\n const id = this.requireArtifactId(ref);\n const query = options?.policy ? `?policy=${encodeURIComponent(options.policy)}` : '';\n const res = await this.request('DELETE', `/v1/storage/artifacts/${id}${query}`, {}, id);\n return mapDeleteResult((await res.json()) as Record<string, unknown>);\n }\n\n async verify(\n ref: ArtifactRef,\n _options?: VerifyArtifactOptions,\n ): Promise<VerificationResult> {\n // `_options` is reserved for future verification depth choices;\n // the server ignores it in v1, so we do not serialize it on\n // the request.\n const id = this.requireArtifactId(ref);\n const res = await this.request('POST', `/v1/storage/artifacts/${id}/verify`, {}, id);\n return mapVerifyResult((await res.json()) as Record<string, unknown>);\n }\n\n private async putPointer(input: Extract<PutArtifactInput, { mode: 'pointer' }>): Promise<StoredArtifact> {\n const body = {\n mode: 'pointer' as const,\n uri: input.uri,\n content_type: input.contentType,\n ...(input.sizeBytes !== undefined ? { size_bytes: input.sizeBytes } : {}),\n ...(input.contentHash !== undefined ? { content_hash: input.contentHash } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n const res = await this.request('POST', '/v1/storage/artifacts', {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n private async putManaged(input: PutManagedInput): Promise<StoredArtifact> {\n // `view` is a Uint8Array narrowed to exactly the caller's bytes —\n // `Buffer` and Uint8Array sub-views share a backing ArrayBuffer\n // with potentially much larger contents, so we MUST send the view\n // itself (or an exact ArrayBuffer slice). Sending `view.buffer`\n // would leak adjacent bytes and produce a body whose actual size\n // disagrees with `Content-Length`.\n const view = coerceManagedBody(input.body);\n const params = new URLSearchParams({ mode: 'managed' });\n if (input.discloseContentHash === true) params.set('disclose_content_hash', 'true');\n const headers: Record<string, string> = {\n 'Content-Type': input.contentType,\n 'Content-Length': String(view.byteLength),\n };\n if (input.metadata !== undefined) {\n headers[METADATA_HEADER] = encodeMetadataHeader(input.metadata);\n }\n const res = await this.request(\n 'POST',\n `/v1/storage/artifacts?${params.toString()}`,\n // Cast: Node's fetch accepts Uint8Array as BodyInit, but the\n // shared lib.dom type predates that. Sending the view directly\n // is intentional — see the comment above coerceManagedBody.\n { headers, body: view as unknown as BodyInit },\n );\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n /**\n * Send a request to the storage API and map non-2xx responses to\n * typed errors. Callers receive the raw `Response` on success and\n * read the body themselves so streaming reads (e.g. getContent)\n * can stay zero-copy.\n *\n * Auth contract: owner identity travels on the\n * `X-AtomicMemory-User-Id` request header alongside the\n * deployment-wide `Authorization: Bearer <apiKey>`. The legacy\n * `?user_id=` URL parameter is NEVER serialized — the server's\n * auth middleware rejects it with 400 `legacy_user_id_unsupported`.\n *\n * Transport-level fetch failures (DNS, ECONNREFUSED, AbortError,\n * a misconfigured fetch impl that throws synchronously) are\n * wrapped as `StorageClientError({errorCode:'network_error',\n * status:0})` so callers can branch on a stable error contract\n * instead of catching arbitrary `TypeError`s.\n *\n * `artifactId`, when supplied, threads into the error mapper so\n * `ArtifactNotFoundError` / `ArtifactInUseError` /\n * `PointerContentNotManagedError` carry the id the caller already\n * knows. The capabilities route omits it (no artifact context).\n */\n private async request(\n method: string,\n path: string,\n init: { headers?: Record<string, string>; body?: BodyInit } = {},\n artifactId?: string,\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: {\n Authorization: `Bearer ${this.apiKey}`,\n 'X-AtomicMemory-User-Id': this.userId,\n ...(init.headers ?? {}),\n },\n body: init.body,\n });\n } catch (cause) {\n throw new StorageClientError({\n message:\n `Network error while calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,\n errorCode: 'network_error',\n status: 0,\n bodyText: '',\n });\n }\n if (res.ok) return res;\n await throwForResponse(res, artifactId);\n // Unreachable — throwForResponse always throws on non-ok.\n throw new StorageClientError({\n message: `unexpected non-ok response (${res.status})`,\n errorCode: 'unexpected_response',\n status: res.status,\n bodyText: '',\n });\n }\n\n private requireArtifactId(ref: ArtifactRef): string {\n if (!ref.artifactId) {\n throw new StorageClientError({\n message: 'ArtifactRef.artifactId is required for this operation in v1',\n errorCode: 'missing_artifact_id',\n status: 0,\n bodyText: '',\n });\n }\n return ref.artifactId;\n }\n}\n\n/** Closed enums the SDK consumes from HEAD response headers + JSON bodies. */\nconst STORAGE_MODES = ['pointer', 'managed'] as const;\nconst STORAGE_STATUSES: ReadonlyArray<StorageArtifactStatus> = [\n 'stored', 'pending', 'available', 'unavailable',\n 'deleting', 'deleted', 'delete_failed', 'failed',\n];\nconst CONTENT_ENCODINGS = ['identity', 'aes_gcm'] as const;\n\nfunction parseSize(value: string | null): number | null {\n if (value === null) return null;\n const n = Number(value);\n if (!Number.isFinite(n) || n < 0) return null;\n return n;\n}\n\n/**\n * Project HEAD response headers into an `ArtifactHead`. Validates\n * mode + status against the SDK's closed enums; throws a typed\n * `StorageClientError({errorCode:'invalid_head_response'})` if the\n * server sends a value the SDK doesn't model. The previous shape\n * cast arbitrary header strings to the enum types, which silently\n * accepted unknown values and propagated them into user code.\n */\nfunction mapHeadHeaders(headers: Headers, fallbackId: string): ArtifactHead {\n const modeRaw = headers.get('x-atomicmemory-storage-mode');\n const statusRaw = headers.get('x-atomicmemory-storage-status');\n if (modeRaw === null || !(STORAGE_MODES as ReadonlyArray<string>).includes(modeRaw)) {\n throw new StorageClientError({\n message:\n `head(): server returned an unrecognized x-atomicmemory-storage-mode value ` +\n `('${modeRaw ?? '<missing>'}'). Expected one of: ${STORAGE_MODES.join(', ')}.`,\n errorCode: 'invalid_head_response',\n status: 200,\n bodyText: '',\n });\n }\n if (statusRaw === null || !(STORAGE_STATUSES as ReadonlyArray<string>).includes(statusRaw)) {\n throw new StorageClientError({\n message:\n `head(): server returned an unrecognized x-atomicmemory-storage-status value ` +\n `('${statusRaw ?? '<missing>'}'). Expected one of: ${STORAGE_STATUSES.join(', ')}.`,\n errorCode: 'invalid_head_response',\n status: 200,\n bodyText: '',\n });\n }\n return {\n artifactId: headers.get('x-atomicmemory-artifact-id') ?? fallbackId,\n provider: headers.get('x-atomicmemory-provider') ?? '',\n mode: modeRaw as 'pointer' | 'managed',\n status: statusRaw as StorageArtifactStatus,\n sizeBytes: parseSize(headers.get('content-length')),\n contentType: headers.get('content-type'),\n };\n}\n\n/**\n * Narrow a caller-supplied body to a `Uint8Array` view that covers\n * exactly the caller's bytes. Buffer / Uint8Array sub-views keep\n * their `byteOffset` + `byteLength` here so the request layer never\n * sends adjacent bytes from the backing ArrayBuffer.\n *\n * Parameter is `unknown` (not the static `PutManagedInput['body']`\n * type) so the runtime checks guard untyped JS callers too — TS\n * already removed Blob and stream types from the public input, but\n * a JS caller could still hand us a Blob or a stream object.\n */\nfunction coerceManagedBody(body: unknown): Uint8Array {\n if (Buffer.isBuffer(body)) {\n return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n }\n if (body instanceof Uint8Array) return body;\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (typeof Blob !== 'undefined' && body instanceof Blob) {\n // Blob is async-coerce only via arrayBuffer(); reject here and\n // let callers convert deliberately so the client never silently\n // buffers the entire Blob.\n throw new StorageClientError({\n message:\n 'StorageClient.put: Blob input must be converted to Buffer / Uint8Array / ArrayBuffer ' +\n 'before calling put(). Use `new Uint8Array(await blob.arrayBuffer())`.',\n errorCode: 'unsupported_body_type',\n status: 0,\n bodyText: '',\n });\n }\n // Stream / Readable / unknown — explicitly rejected. Streaming\n // body uploads land in the Streaming + Resumable Uploads PR.\n throw new StorageClientError({\n message:\n 'StorageClient.put: only Buffer / Uint8Array / ArrayBuffer are accepted in v1. ' +\n 'Streaming body uploads land in the Streaming + Resumable Uploads PR.',\n errorCode: 'streaming_body_not_supported',\n status: 0,\n bodyText: '',\n });\n}\n\nfunction encodeMetadataHeader(metadata: Record<string, string | number | boolean>): string {\n return Buffer.from(JSON.stringify(metadata), 'utf8').toString('base64');\n}\n\n/**\n * Translate the snake_case wire response into the camelCase SDK\n * shape via an EXPLICIT named-key projection. Wire-only fields\n * (`stored_hash`, `delete_attempt_id`, etc.) the server formatter\n * already redacts; this layer drops anything not in the allowlist\n * even if a future server regression slipped a field through.\n *\n * Closed-set validation. `mode`, `status`, and `content_encoding`\n * are each checked against the enum the SDK actually models — an\n * unrecognized server / proxy / version-skew value throws\n * `StorageClientError({errorCode:'invalid_storage_response'})`\n * rather than silently producing a typed SDK object whose enum\n * fields lie about reality. Same discipline as HEAD header\n * validation.\n *\n * Required-field hardening. The wire contract guarantees\n * `artifact_id`, `provider`, `mode`, `status`, `content_encoding`,\n * `created_at`, `updated_at` on every read. Missing or wrong-type\n * values throw rather than defaulting to empty strings. Wire-only\n * `artifact_id` (no `artifactId` alias) — this is the SDK's snake→\n * camel seam, not a polyfill for callers that pre-translated.\n */\nfunction mapStoredArtifact(raw: Record<string, unknown>): StoredArtifact {\n const artifactId = requireWireString(raw, 'artifact_id');\n const provider = requireWireString(raw, 'provider');\n const mode = requireWireEnum(raw, 'mode', STORAGE_MODES) as 'pointer' | 'managed';\n const status = requireWireEnum(raw, 'status', STORAGE_STATUSES) as StorageArtifactStatus;\n const contentEncoding = requireWireEnum(\n raw, 'content_encoding', CONTENT_ENCODINGS,\n ) as 'identity' | 'aes_gcm';\n const createdAt = requireWireString(raw, 'created_at');\n const updatedAt = requireWireString(raw, 'updated_at');\n const out: StoredArtifact = {\n artifactId,\n provider,\n mode,\n uri: typeof raw.uri === 'string' ? raw.uri : null,\n status,\n sizeBytes: typeof raw.size_bytes === 'number' ? raw.size_bytes : null,\n contentType: typeof raw.content_type === 'string' ? raw.content_type : null,\n contentEncoding,\n identifiers: (raw.identifiers as Record<string, string> | undefined) ?? {},\n lifecycle: (raw.lifecycle as StorageLifecycle | undefined) ?? {},\n metadata:\n (raw.metadata as Record<string, string | number | boolean> | undefined) ?? {},\n createdAt,\n updatedAt,\n };\n if (typeof raw.content_hash === 'string') out.contentHash = raw.content_hash;\n if (raw.provider_details && typeof raw.provider_details === 'object') {\n out.providerDetails = raw.provider_details as Record<string, unknown>;\n }\n if (raw.replication && typeof raw.replication === 'object') {\n out.replication = raw.replication as StoredArtifact['replication'];\n }\n if (raw.verification && typeof raw.verification === 'object') {\n out.verification = raw.verification as StoredArtifact['verification'];\n }\n if (raw.retrieval && typeof raw.retrieval === 'object') {\n out.retrieval = raw.retrieval as StoredArtifact['retrieval'];\n }\n return out;\n}\n\nfunction requireWireString(raw: Record<string, unknown>, field: string): string {\n const value = raw[field];\n if (typeof value !== 'string' || value.length === 0) {\n throw new StorageClientError({\n message:\n `mapStoredArtifact: server response is missing required \\`${field}\\` ` +\n '(or it is not a non-empty string). The storage API contract requires it.',\n errorCode: 'invalid_storage_response',\n status: 200,\n bodyText: '',\n });\n }\n return value;\n}\n\nfunction requireWireEnum<T extends string>(\n raw: Record<string, unknown>,\n field: string,\n allowed: ReadonlyArray<T>,\n): T {\n const value = raw[field];\n if (typeof value !== 'string' || !(allowed as ReadonlyArray<string>).includes(value)) {\n throw new StorageClientError({\n message:\n `mapStoredArtifact: server response field \\`${field}\\` is not in the SDK's ` +\n `closed enum. Got '${String(value ?? '<missing>')}', expected one of: ${allowed.join(', ')}.`,\n errorCode: 'invalid_storage_response',\n status: 200,\n bodyText: '',\n });\n }\n return value as T;\n}\n\n/**\n * Translate the snake_case DELETE response envelope into the\n * camelCase SDK shape. Same discipline as `mapStoredArtifact`:\n *\n * - require non-empty snake_case `artifact_id` (no camelCase\n * alias polyfill — the wire is snake_case);\n * - validate `status` against the closed `StorageArtifactStatus`\n * enum;\n * - throw `StorageClientError({errorCode:'invalid_storage_response'})`\n * on missing / wrong-type / out-of-enum values rather than\n * silently producing a typed SDK object whose fields lie.\n */\nfunction mapDeleteResult(raw: Record<string, unknown>): DeleteArtifactResult {\n const artifactId = requireWireString(raw, 'artifact_id');\n const status = requireWireEnum(raw, 'status', STORAGE_STATUSES) as StorageArtifactStatus;\n const out: DeleteArtifactResult = { artifactId, status };\n if (Array.isArray(raw.cascaded_document_ids)) {\n out.cascadedDocumentIds = raw.cascaded_document_ids.map(String);\n }\n return out;\n}\n\nfunction mapVerifyResult(raw: Record<string, unknown>): VerificationResult {\n const kind = raw.kind;\n if (kind === 'verified') {\n return { kind: 'verified', details: (raw.details ?? {}) as Record<string, unknown> };\n }\n if (kind === 'failed') {\n return { kind: 'failed', reason: String(raw.reason ?? 'unknown failure') };\n }\n return { kind: 'unsupported', reason: String(raw.reason ?? 'unsupported') };\n}\n\nasync function throwForResponse(res: Response, artifactId?: string): Promise<never> {\n const bodyText = await res.text();\n const envelope = parseEnvelope(bodyText);\n const code = envelope.error_code;\n const message = envelope.error ?? `request failed with status ${res.status}`;\n const id = artifactId ?? '';\n if (code === 'artifact_in_use') {\n throw new ArtifactInUseError({\n artifactId: id,\n referencedByDocumentCount: envelope.referenced_by_document_count ?? 0,\n bodyText,\n });\n }\n if (code === 'pointer_content_not_managed') {\n throw new PointerContentNotManagedError({\n artifactId: id,\n uri: envelope.uri ?? '',\n bodyText,\n });\n }\n if (code === 'filecoin_direct_storage_not_yet_supported') {\n throw new FilecoinDirectStorageNotSupportedError({ bodyText });\n }\n if (code === 'artifact_not_found' || res.status === 404) {\n throw new ArtifactNotFoundError({ artifactId: id, bodyText });\n }\n if (code === 'unsupported_capability') {\n throw new UnsupportedCapabilityError({\n capability: 'unknown',\n message,\n bodyText,\n });\n }\n throw new StorageClientError({\n message,\n errorCode: code ?? `http_${res.status}`,\n status: res.status,\n bodyText,\n });\n}\n\nfunction parseEnvelope(bodyText: string): CoreErrorEnvelope {\n if (bodyText.length === 0) return {};\n try {\n return JSON.parse(bodyText) as CoreErrorEnvelope;\n } catch {\n return {};\n }\n}\n"]}
'use strict';
var chunkMIG2OG5Z_cjs = require('./chunk-MIG2OG5Z.cjs');
// src/storage/errors.ts
var StorageClientError = class extends Error {
errorCode;
status;
bodyText;
constructor(args) {
super(args.message);
this.name = "StorageClientError";
this.errorCode = args.errorCode;
this.status = args.status;
this.bodyText = args.bodyText;
}
};
var UnsupportedCapabilityError = class extends StorageClientError {
capability;
constructor(args) {
super({
message: args.message,
errorCode: "unsupported_capability",
status: 400,
bodyText: args.bodyText
});
this.name = "UnsupportedCapabilityError";
this.capability = args.capability;
}
};
var ArtifactNotFoundError = class extends StorageClientError {
artifactId;
constructor(args) {
super({
message: `Storage artifact ${args.artifactId} not found`,
errorCode: "artifact_not_found",
status: 404,
bodyText: args.bodyText
});
this.name = "ArtifactNotFoundError";
this.artifactId = args.artifactId;
}
};
var ArtifactInUseError = class extends StorageClientError {
artifactId;
referencedByDocumentCount;
constructor(args) {
super({
message: `Storage artifact ${args.artifactId} is referenced by ${args.referencedByDocumentCount} document(s); pass 'policy: "with_documents"' to cascade`,
errorCode: "artifact_in_use",
status: 409,
bodyText: args.bodyText
});
this.name = "ArtifactInUseError";
this.artifactId = args.artifactId;
this.referencedByDocumentCount = args.referencedByDocumentCount;
}
};
var PointerContentNotManagedError = class extends StorageClientError {
artifactId;
uri;
constructor(args) {
super({
message: `Artifact ${args.artifactId} is pointer-mode; fetch the URI directly (the server does not proxy pointer content)`,
errorCode: "pointer_content_not_managed",
status: 409,
bodyText: args.bodyText
});
this.name = "PointerContentNotManagedError";
this.artifactId = args.artifactId;
this.uri = args.uri;
}
};
var FilecoinDirectStorageNotSupportedError = class extends StorageClientError {
constructor(args) {
super({
message: "Direct Filecoin artifact uploads are not supported in this version. Use document ingestion or pointer mode.",
errorCode: "filecoin_direct_storage_not_yet_supported",
status: 501,
bodyText: args.bodyText
});
this.name = "FilecoinDirectStorageNotSupportedError";
}
};
// src/storage/client.ts
var METADATA_HEADER = "X-AtomicMemory-Metadata";
var ConcreteStorageClient = class {
apiUrl;
apiKey;
userId;
fetchImpl;
constructor(config) {
if (!config.apiUrl) throw new Error("StorageClient: apiUrl is required");
if (!config.apiKey) throw new Error("StorageClient: apiKey is required");
if (!config.userId) throw new Error("StorageClient: userId is required");
this.apiUrl = chunkMIG2OG5Z_cjs.validateApiUrl(config.apiUrl, {
allowPrivateNetworks: config.allowPrivateNetworks
}).replace(/\/+$/, "");
this.apiKey = config.apiKey;
this.userId = config.userId;
this.fetchImpl = config.fetch ?? fetch;
}
async capabilities() {
const res = await this.request("GET", "/v1/storage/capabilities");
return await res.json();
}
async put(input) {
if (input.mode === "pointer") return this.putPointer(input);
return this.putManaged(input);
}
async get(ref) {
const id = this.requireArtifactId(ref);
const res = await this.request("GET", `/v1/storage/artifacts/${id}`, {}, id);
return mapStoredArtifact(await res.json());
}
async getContent(ref) {
const id = this.requireArtifactId(ref);
return this.request("GET", `/v1/storage/artifacts/${id}/content`, {}, id);
}
async head(ref) {
const id = this.requireArtifactId(ref);
const res = await this.request("HEAD", `/v1/storage/artifacts/${id}`, {}, id);
return mapHeadHeaders(res.headers, id);
}
async delete(ref, options) {
const id = this.requireArtifactId(ref);
const query = options?.policy ? `?policy=${encodeURIComponent(options.policy)}` : "";
const res = await this.request("DELETE", `/v1/storage/artifacts/${id}${query}`, {}, id);
return mapDeleteResult(await res.json());
}
async verify(ref, _options) {
const id = this.requireArtifactId(ref);
const res = await this.request("POST", `/v1/storage/artifacts/${id}/verify`, {}, id);
return mapVerifyResult(await res.json());
}
async putPointer(input) {
const body = {
mode: "pointer",
uri: input.uri,
content_type: input.contentType,
...input.sizeBytes !== void 0 ? { size_bytes: input.sizeBytes } : {},
...input.contentHash !== void 0 ? { content_hash: input.contentHash } : {},
...input.metadata !== void 0 ? { metadata: input.metadata } : {}
};
const res = await this.request("POST", "/v1/storage/artifacts", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
return mapStoredArtifact(await res.json());
}
async putManaged(input) {
const view = coerceManagedBody(input.body);
const params = new URLSearchParams({ mode: "managed" });
if (input.discloseContentHash === true) params.set("disclose_content_hash", "true");
const headers = {
"Content-Type": input.contentType,
"Content-Length": String(view.byteLength)
};
if (input.metadata !== void 0) {
headers[METADATA_HEADER] = encodeMetadataHeader(input.metadata);
}
const res = await this.request(
"POST",
`/v1/storage/artifacts?${params.toString()}`,
// Cast: Node's fetch accepts Uint8Array as BodyInit, but the
// shared lib.dom type predates that. Sending the view directly
// is intentional — see the comment above coerceManagedBody.
{ headers, body: view }
);
return mapStoredArtifact(await res.json());
}
/**
* Send a request to the storage API and map non-2xx responses to
* typed errors. Callers receive the raw `Response` on success and
* read the body themselves so streaming reads (e.g. getContent)
* can stay zero-copy.
*
* Auth contract: owner identity travels on the
* `X-AtomicMemory-User-Id` request header alongside the
* deployment-wide `Authorization: Bearer <apiKey>`. The legacy
* `?user_id=` URL parameter is NEVER serialized — the server's
* auth middleware rejects it with 400 `legacy_user_id_unsupported`.
*
* Transport-level fetch failures (DNS, ECONNREFUSED, AbortError,
* a misconfigured fetch impl that throws synchronously) are
* wrapped as `StorageClientError({errorCode:'network_error',
* status:0})` so callers can branch on a stable error contract
* instead of catching arbitrary `TypeError`s.
*
* `artifactId`, when supplied, threads into the error mapper so
* `ArtifactNotFoundError` / `ArtifactInUseError` /
* `PointerContentNotManagedError` carry the id the caller already
* knows. The capabilities route omits it (no artifact context).
*/
async request(method, path, init = {}, artifactId) {
const url = `${this.apiUrl}${path}`;
let res;
try {
res = await this.fetchImpl(url, {
method,
headers: {
Authorization: `Bearer ${this.apiKey}`,
"X-AtomicMemory-User-Id": this.userId,
...init.headers ?? {}
},
body: init.body
});
} catch (cause) {
throw new StorageClientError({
message: `Network error while calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
errorCode: "network_error",
status: 0,
bodyText: ""
});
}
if (res.ok) return res;
await throwForResponse(res, artifactId);
throw new StorageClientError({
message: `unexpected non-ok response (${res.status})`,
errorCode: "unexpected_response",
status: res.status,
bodyText: ""
});
}
requireArtifactId(ref) {
if (!ref.artifactId) {
throw new StorageClientError({
message: "ArtifactRef.artifactId is required for this operation in v1",
errorCode: "missing_artifact_id",
status: 0,
bodyText: ""
});
}
return ref.artifactId;
}
};
var STORAGE_MODES = ["pointer", "managed"];
var STORAGE_STATUSES = [
"stored",
"pending",
"available",
"unavailable",
"deleting",
"deleted",
"delete_failed",
"failed"
];
var CONTENT_ENCODINGS = ["identity", "aes_gcm"];
function parseSize(value) {
if (value === null) return null;
const n = Number(value);
if (!Number.isFinite(n) || n < 0) return null;
return n;
}
function mapHeadHeaders(headers, fallbackId) {
const modeRaw = headers.get("x-atomicmemory-storage-mode");
const statusRaw = headers.get("x-atomicmemory-storage-status");
if (modeRaw === null || !STORAGE_MODES.includes(modeRaw)) {
throw new StorageClientError({
message: `head(): server returned an unrecognized x-atomicmemory-storage-mode value ('${modeRaw ?? "<missing>"}'). Expected one of: ${STORAGE_MODES.join(", ")}.`,
errorCode: "invalid_head_response",
status: 200,
bodyText: ""
});
}
if (statusRaw === null || !STORAGE_STATUSES.includes(statusRaw)) {
throw new StorageClientError({
message: `head(): server returned an unrecognized x-atomicmemory-storage-status value ('${statusRaw ?? "<missing>"}'). Expected one of: ${STORAGE_STATUSES.join(", ")}.`,
errorCode: "invalid_head_response",
status: 200,
bodyText: ""
});
}
return {
artifactId: headers.get("x-atomicmemory-artifact-id") ?? fallbackId,
provider: headers.get("x-atomicmemory-provider") ?? "",
mode: modeRaw,
status: statusRaw,
sizeBytes: parseSize(headers.get("content-length")),
contentType: headers.get("content-type")
};
}
function coerceManagedBody(body) {
if (Buffer.isBuffer(body)) {
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
}
if (body instanceof Uint8Array) return body;
if (body instanceof ArrayBuffer) return new Uint8Array(body);
if (typeof Blob !== "undefined" && body instanceof Blob) {
throw new StorageClientError({
message: "StorageClient.put: Blob input must be converted to Buffer / Uint8Array / ArrayBuffer before calling put(). Use `new Uint8Array(await blob.arrayBuffer())`.",
errorCode: "unsupported_body_type",
status: 0,
bodyText: ""
});
}
throw new StorageClientError({
message: "StorageClient.put: only Buffer / Uint8Array / ArrayBuffer are accepted in v1. Streaming body uploads land in the Streaming + Resumable Uploads PR.",
errorCode: "streaming_body_not_supported",
status: 0,
bodyText: ""
});
}
function encodeMetadataHeader(metadata) {
return Buffer.from(JSON.stringify(metadata), "utf8").toString("base64");
}
function mapStoredArtifact(raw) {
const artifactId = requireWireString(raw, "artifact_id");
const provider = requireWireString(raw, "provider");
const mode = requireWireEnum(raw, "mode", STORAGE_MODES);
const status = requireWireEnum(raw, "status", STORAGE_STATUSES);
const contentEncoding = requireWireEnum(
raw,
"content_encoding",
CONTENT_ENCODINGS
);
const createdAt = requireWireString(raw, "created_at");
const updatedAt = requireWireString(raw, "updated_at");
const out = {
artifactId,
provider,
mode,
uri: typeof raw.uri === "string" ? raw.uri : null,
status,
sizeBytes: typeof raw.size_bytes === "number" ? raw.size_bytes : null,
contentType: typeof raw.content_type === "string" ? raw.content_type : null,
contentEncoding,
identifiers: raw.identifiers ?? {},
lifecycle: raw.lifecycle ?? {},
metadata: raw.metadata ?? {},
createdAt,
updatedAt
};
if (typeof raw.content_hash === "string") out.contentHash = raw.content_hash;
if (raw.provider_details && typeof raw.provider_details === "object") {
out.providerDetails = raw.provider_details;
}
if (raw.replication && typeof raw.replication === "object") {
out.replication = raw.replication;
}
if (raw.verification && typeof raw.verification === "object") {
out.verification = raw.verification;
}
if (raw.retrieval && typeof raw.retrieval === "object") {
out.retrieval = raw.retrieval;
}
return out;
}
function requireWireString(raw, field) {
const value = raw[field];
if (typeof value !== "string" || value.length === 0) {
throw new StorageClientError({
message: `mapStoredArtifact: server response is missing required \`${field}\` (or it is not a non-empty string). The storage API contract requires it.`,
errorCode: "invalid_storage_response",
status: 200,
bodyText: ""
});
}
return value;
}
function requireWireEnum(raw, field, allowed) {
const value = raw[field];
if (typeof value !== "string" || !allowed.includes(value)) {
throw new StorageClientError({
message: `mapStoredArtifact: server response field \`${field}\` is not in the SDK's closed enum. Got '${String(value ?? "<missing>")}', expected one of: ${allowed.join(", ")}.`,
errorCode: "invalid_storage_response",
status: 200,
bodyText: ""
});
}
return value;
}
function mapDeleteResult(raw) {
const artifactId = requireWireString(raw, "artifact_id");
const status = requireWireEnum(raw, "status", STORAGE_STATUSES);
const out = { artifactId, status };
if (Array.isArray(raw.cascaded_document_ids)) {
out.cascadedDocumentIds = raw.cascaded_document_ids.map(String);
}
return out;
}
function mapVerifyResult(raw) {
const kind = raw.kind;
if (kind === "verified") {
return { kind: "verified", details: raw.details ?? {} };
}
if (kind === "failed") {
return { kind: "failed", reason: String(raw.reason ?? "unknown failure") };
}
return { kind: "unsupported", reason: String(raw.reason ?? "unsupported") };
}
async function throwForResponse(res, artifactId) {
const bodyText = await res.text();
const envelope = parseEnvelope(bodyText);
const code = envelope.error_code;
const message = envelope.error ?? `request failed with status ${res.status}`;
const id = artifactId ?? "";
if (code === "artifact_in_use") {
throw new ArtifactInUseError({
artifactId: id,
referencedByDocumentCount: envelope.referenced_by_document_count ?? 0,
bodyText
});
}
if (code === "pointer_content_not_managed") {
throw new PointerContentNotManagedError({
artifactId: id,
uri: envelope.uri ?? "",
bodyText
});
}
if (code === "filecoin_direct_storage_not_yet_supported") {
throw new FilecoinDirectStorageNotSupportedError({ bodyText });
}
if (code === "artifact_not_found" || res.status === 404) {
throw new ArtifactNotFoundError({ artifactId: id, bodyText });
}
if (code === "unsupported_capability") {
throw new UnsupportedCapabilityError({
capability: "unknown",
message,
bodyText
});
}
throw new StorageClientError({
message,
errorCode: code ?? `http_${res.status}`,
status: res.status,
bodyText
});
}
function parseEnvelope(bodyText) {
if (bodyText.length === 0) return {};
try {
return JSON.parse(bodyText);
} catch {
return {};
}
}
exports.ArtifactInUseError = ArtifactInUseError;
exports.ArtifactNotFoundError = ArtifactNotFoundError;
exports.ConcreteStorageClient = ConcreteStorageClient;
exports.FilecoinDirectStorageNotSupportedError = FilecoinDirectStorageNotSupportedError;
exports.PointerContentNotManagedError = PointerContentNotManagedError;
exports.StorageClientError = StorageClientError;
exports.UnsupportedCapabilityError = UnsupportedCapabilityError;
//# sourceMappingURL=chunk-LPC54QOU.cjs.map
//# sourceMappingURL=chunk-LPC54QOU.cjs.map
{"version":3,"sources":["../src/storage/errors.ts","../src/storage/client.ts"],"names":["validateApiUrl"],"mappings":";;;;;AAkBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EACnC,SAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACT,YAAY,IAAA,EAKT;AACD,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AACZ,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AAAA,EACvB;AACF;AAMO,IAAM,0BAAA,GAAN,cAAyC,kBAAA,CAAmB;AAAA,EACxD,UAAA;AAAA,EACT,YAAY,IAAA,EAIT;AACD,IAAA,KAAA,CAAM;AAAA,MACJ,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,SAAA,EAAW,wBAAA;AAAA,MACX,MAAA,EAAQ,GAAA;AAAA,MACR,UAAU,IAAA,CAAK;AAAA,KAChB,CAAA;AACD,IAAA,IAAA,CAAK,IAAA,GAAO,4BAAA;AACZ,IAAA,IAAA,CAAK,aAAa,IAAA,CA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error classes.\n *\n * Instanceof-checkable error classes the SDK throws from\n * `client.storage.*` methods. v1 exports the class shapes only\n * — no message formatting magic.\n *\n * Why classes (not enums): callers can `catch (err)\n * { if (err instanceof ArtifactInUseError) { ... } }` without\n * pattern-matching on `error_code` strings, and bundled stack\n * traces survive code minification.\n */\n\n/**\n * Base class for everything `client.storage.*` throws when the\n * server returns a typed error envelope. `errorCode` mirrors the\n * server's `error_code` field — opaque, snake_case, stable.\n */\nexport class StorageClientError extends Error {\n readonly errorCode: string;\n readonly status: number;\n readonly bodyText: string;\n constructor(args: {\n message: string;\n errorCode: string;\n status: number;\n bodyText: string;\n }) {\n super(args.message);\n this.name = 'StorageClientError';\n this.errorCode = args.errorCode;\n this.status = args.status;\n this.bodyText = args.bodyText;\n }\n}\n\n/**\n * Thrown when a capability the call assumes (range read, bundles,\n * `hash_verify` mode) isn't supported by the active backend.\n */\nexport class UnsupportedCapabilityError extends StorageClientError {\n readonly capability: string;\n constructor(args: {\n capability: string;\n message: string;\n bodyText: string;\n }) {\n super({\n message: args.message,\n errorCode: 'unsupported_capability',\n status: 400,\n bodyText: args.bodyText,\n });\n this.name = 'UnsupportedCapabilityError';\n this.capability = args.capability;\n }\n}\n\n/** Thrown when `get` / `head` / `delete` / `verify` cannot find the artifact. */\nexport class ArtifactNotFoundError extends StorageClientError {\n readonly artifactId: string;\n constructor(args: { artifactId: string; bodyText: string }) {\n super({\n message: `Storage artifact ${args.artifactId} not found`,\n errorCode: 'artifact_not_found',\n status: 404,\n bodyText: args.bodyText,\n });\n this.name = 'ArtifactNotFoundError';\n this.artifactId = args.artifactId;\n }\n}\n\n/**\n * Thrown when a default delete hits a referenced artifact. Server\n * returns 409 with `referenced_by_document_count`; callers can use\n * `?policy=with_documents` to cascade.\n */\nexport class ArtifactInUseError extends StorageClientError {\n readonly artifactId: string;\n readonly referencedByDocumentCount: number;\n constructor(args: {\n artifactId: string;\n referencedByDocumentCount: number;\n bodyText: string;\n }) {\n super({\n message:\n `Storage artifact ${args.artifactId} is referenced by ` +\n `${args.referencedByDocumentCount} document(s); pass ` +\n `'policy: \\\"with_documents\\\"' to cascade`,\n errorCode: 'artifact_in_use',\n status: 409,\n bodyText: args.bodyText,\n });\n this.name = 'ArtifactInUseError';\n this.artifactId = args.artifactId;\n this.referencedByDocumentCount = args.referencedByDocumentCount;\n }\n}\n\n/**\n * Thrown when `getContent` targets a pointer-mode artifact. v1\n * pointers are metadata-only — the server NEVER proxies external\n * bytes. Caller must fetch the URI directly.\n */\nexport class PointerContentNotManagedError extends StorageClientError {\n readonly artifactId: string;\n readonly uri: string;\n constructor(args: { artifactId: string; uri: string; bodyText: string }) {\n super({\n message:\n `Artifact ${args.artifactId} is pointer-mode; fetch the URI ` +\n `directly (the server does not proxy pointer content)`,\n errorCode: 'pointer_content_not_managed',\n status: 409,\n bodyText: args.bodyText,\n });\n this.name = 'PointerContentNotManagedError';\n this.artifactId = args.artifactId;\n this.uri = args.uri;\n }\n}\n\n/**\n * Thrown when a managed put against a Filecoin backend hits the v1\n * carve-out (direct Filecoin uploads require artifact reconciliation,\n * which is not implemented yet). Callers can use document ingestion\n * (`PUT /v1/documents/:id/raw`) or pointer mode against Filecoin.\n */\nexport class FilecoinDirectStorageNotSupportedError extends StorageClientError {\n constructor(args: { bodyText: string }) {\n super({\n message:\n 'Direct Filecoin artifact uploads are not supported in this ' +\n 'version. Use document ingestion or pointer mode.',\n errorCode: 'filecoin_direct_storage_not_yet_supported',\n status: 501,\n bodyText: args.bodyText,\n });\n this.name = 'FilecoinDirectStorageNotSupportedError';\n }\n}\n","/**\n * @file Concrete `StorageClient` implementation.\n *\n * Wraps `fetch` to call the direct storage API\n * (`/v1/storage/artifacts/*`). The SDK is server-side only —\n * `Authorization: Bearer <apiKey>` is sent from a trusted process;\n * browser callers must proxy through a server they control.\n *\n * Managed-mode bodies are restricted to known-length values\n * (`Buffer | Uint8Array | ArrayBuffer`) so the client can compute\n * `Content-Length` before sending — the server requires it. Streams\n * (`ReadableStream`, Node `Readable`) are explicitly rejected with\n * `streaming_body_not_supported`; `Blob` is rejected with\n * `unsupported_body_type` so the silent buffering needed to compute\n * `Content-Length` stays visible at the call site (convert with\n * `new Uint8Array(await blob.arrayBuffer())` first). Streaming +\n * resumable uploads land in a follow-up PR.\n *\n * Wire mapping: core emits snake_case (`artifact_id`,\n * `cascaded_document_ids`); the SDK's public types use camelCase for\n * the top-level handles (`artifactId`, `cascadedDocumentIds`). The\n * client is the single seam that translates.\n */\n\nimport { validateApiUrl } from '../utils/validate-api-url.js';\nimport {\n ArtifactInUseError,\n ArtifactNotFoundError,\n FilecoinDirectStorageNotSupportedError,\n PointerContentNotManagedError,\n StorageClientError,\n UnsupportedCapabilityError,\n} from './errors.js';\nimport type { StorageClient } from './interfaces.js';\nimport type {\n ArtifactBody,\n ArtifactHead,\n ArtifactRef,\n DeleteArtifactOptions,\n DeleteArtifactResult,\n PutArtifactInput,\n PutManagedInput,\n StorageArtifactStatus,\n StorageCapabilities,\n StorageLifecycle,\n StoredArtifact,\n VerificationResult,\n VerifyArtifactOptions,\n} from './types.js';\n\n/** Caller-supplied configuration for the concrete client. */\nexport interface StorageClientConfig {\n apiUrl: string;\n apiKey: string;\n /**\n * Permit `apiUrl` to target loopback / private / reserved IP literals.\n * Defaults to `true`; set `false` to harden against SSRF. Link-local /\n * cloud-metadata addresses are blocked regardless. See `validateApiUrl`.\n */\n allowPrivateNetworks?: boolean;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n /** Owner scope for the caller. Sent as `X-AtomicMemory-User-Id`\n * on every storage request. The legacy `?user_id=` URL parameter\n * is not used — the server rejects it with 400\n * `legacy_user_id_unsupported`. */\n userId: string;\n}\n\nconst METADATA_HEADER = 'X-AtomicMemory-Metadata';\n\n/** Wire-shape JSON envelope the core route layer emits on errors. */\ninterface CoreErrorEnvelope {\n error_code?: string;\n error?: string;\n uri?: string;\n referenced_by_document_count?: number;\n allowed_schemes?: ReadonlyArray<string>;\n}\n\nexport class ConcreteStorageClient implements StorageClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly userId: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: StorageClientConfig) {\n if (!config.apiUrl) throw new Error('StorageClient: apiUrl is required');\n if (!config.apiKey) throw new Error('StorageClient: apiKey is required');\n if (!config.userId) throw new Error('StorageClient: userId is required');\n this.apiUrl = validateApiUrl(config.apiUrl, {\n allowPrivateNetworks: config.allowPrivateNetworks,\n }).replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.userId = config.userId;\n this.fetchImpl = config.fetch ?? fetch;\n }\n\n async capabilities(): Promise<StorageCapabilities> {\n const res = await this.request('GET', '/v1/storage/capabilities');\n return (await res.json()) as StorageCapabilities;\n }\n\n async put(input: PutArtifactInput): Promise<StoredArtifact> {\n if (input.mode === 'pointer') return this.putPointer(input);\n return this.putManaged(input);\n }\n\n async get(ref: ArtifactRef): Promise<StoredArtifact> {\n const id = this.requireArtifactId(ref);\n const res = await this.request('GET', `/v1/storage/artifacts/${id}`, {}, id);\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n async getContent(ref: ArtifactRef): Promise<ArtifactBody> {\n const id = this.requireArtifactId(ref);\n return this.request('GET', `/v1/storage/artifacts/${id}/content`, {}, id);\n }\n\n async head(ref: ArtifactRef): Promise<ArtifactHead> {\n const id = this.requireArtifactId(ref);\n const res = await this.request('HEAD', `/v1/storage/artifacts/${id}`, {}, id);\n return mapHeadHeaders(res.headers, id);\n }\n\n async delete(\n ref: ArtifactRef,\n options?: DeleteArtifactOptions,\n ): Promise<DeleteArtifactResult> {\n const id = this.requireArtifactId(ref);\n const query = options?.policy ? `?policy=${encodeURIComponent(options.policy)}` : '';\n const res = await this.request('DELETE', `/v1/storage/artifacts/${id}${query}`, {}, id);\n return mapDeleteResult((await res.json()) as Record<string, unknown>);\n }\n\n async verify(\n ref: ArtifactRef,\n _options?: VerifyArtifactOptions,\n ): Promise<VerificationResult> {\n // `_options` is reserved for future verification depth choices;\n // the server ignores it in v1, so we do not serialize it on\n // the request.\n const id = this.requireArtifactId(ref);\n const res = await this.request('POST', `/v1/storage/artifacts/${id}/verify`, {}, id);\n return mapVerifyResult((await res.json()) as Record<string, unknown>);\n }\n\n private async putPointer(input: Extract<PutArtifactInput, { mode: 'pointer' }>): Promise<StoredArtifact> {\n const body = {\n mode: 'pointer' as const,\n uri: input.uri,\n content_type: input.contentType,\n ...(input.sizeBytes !== undefined ? { size_bytes: input.sizeBytes } : {}),\n ...(input.contentHash !== undefined ? { content_hash: input.contentHash } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n const res = await this.request('POST', '/v1/storage/artifacts', {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n private async putManaged(input: PutManagedInput): Promise<StoredArtifact> {\n // `view` is a Uint8Array narrowed to exactly the caller's bytes —\n // `Buffer` and Uint8Array sub-views share a backing ArrayBuffer\n // with potentially much larger contents, so we MUST send the view\n // itself (or an exact ArrayBuffer slice). Sending `view.buffer`\n // would leak adjacent bytes and produce a body whose actual size\n // disagrees with `Content-Length`.\n const view = coerceManagedBody(input.body);\n const params = new URLSearchParams({ mode: 'managed' });\n if (input.discloseContentHash === true) params.set('disclose_content_hash', 'true');\n const headers: Record<string, string> = {\n 'Content-Type': input.contentType,\n 'Content-Length': String(view.byteLength),\n };\n if (input.metadata !== undefined) {\n headers[METADATA_HEADER] = encodeMetadataHeader(input.metadata);\n }\n const res = await this.request(\n 'POST',\n `/v1/storage/artifacts?${params.toString()}`,\n // Cast: Node's fetch accepts Uint8Array as BodyInit, but the\n // shared lib.dom type predates that. Sending the view directly\n // is intentional — see the comment above coerceManagedBody.\n { headers, body: view as unknown as BodyInit },\n );\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n /**\n * Send a request to the storage API and map non-2xx responses to\n * typed errors. Callers receive the raw `Response` on success and\n * read the body themselves so streaming reads (e.g. getContent)\n * can stay zero-copy.\n *\n * Auth contract: owner identity travels on the\n * `X-AtomicMemory-User-Id` request header alongside the\n * deployment-wide `Authorization: Bearer <apiKey>`. The legacy\n * `?user_id=` URL parameter is NEVER serialized — the server's\n * auth middleware rejects it with 400 `legacy_user_id_unsupported`.\n *\n * Transport-level fetch failures (DNS, ECONNREFUSED, AbortError,\n * a misconfigured fetch impl that throws synchronously) are\n * wrapped as `StorageClientError({errorCode:'network_error',\n * status:0})` so callers can branch on a stable error contract\n * instead of catching arbitrary `TypeError`s.\n *\n * `artifactId`, when supplied, threads into the error mapper so\n * `ArtifactNotFoundError` / `ArtifactInUseError` /\n * `PointerContentNotManagedError` carry the id the caller already\n * knows. The capabilities route omits it (no artifact context).\n */\n private async request(\n method: string,\n path: string,\n init: { headers?: Record<string, string>; body?: BodyInit } = {},\n artifactId?: string,\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: {\n Authorization: `Bearer ${this.apiKey}`,\n 'X-AtomicMemory-User-Id': this.userId,\n ...(init.headers ?? {}),\n },\n body: init.body,\n });\n } catch (cause) {\n throw new StorageClientError({\n message:\n `Network error while calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,\n errorCode: 'network_error',\n status: 0,\n bodyText: '',\n });\n }\n if (res.ok) return res;\n await throwForResponse(res, artifactId);\n // Unreachable — throwForResponse always throws on non-ok.\n throw new StorageClientError({\n message: `unexpected non-ok response (${res.status})`,\n errorCode: 'unexpected_response',\n status: res.status,\n bodyText: '',\n });\n }\n\n private requireArtifactId(ref: ArtifactRef): string {\n if (!ref.artifactId) {\n throw new StorageClientError({\n message: 'ArtifactRef.artifactId is required for this operation in v1',\n errorCode: 'missing_artifact_id',\n status: 0,\n bodyText: '',\n });\n }\n return ref.artifactId;\n }\n}\n\n/** Closed enums the SDK consumes from HEAD response headers + JSON bodies. */\nconst STORAGE_MODES = ['pointer', 'managed'] as const;\nconst STORAGE_STATUSES: ReadonlyArray<StorageArtifactStatus> = [\n 'stored', 'pending', 'available', 'unavailable',\n 'deleting', 'deleted', 'delete_failed', 'failed',\n];\nconst CONTENT_ENCODINGS = ['identity', 'aes_gcm'] as const;\n\nfunction parseSize(value: string | null): number | null {\n if (value === null) return null;\n const n = Number(value);\n if (!Number.isFinite(n) || n < 0) return null;\n return n;\n}\n\n/**\n * Project HEAD response headers into an `ArtifactHead`. Validates\n * mode + status against the SDK's closed enums; throws a typed\n * `StorageClientError({errorCode:'invalid_head_response'})` if the\n * server sends a value the SDK doesn't model. The previous shape\n * cast arbitrary header strings to the enum types, which silently\n * accepted unknown values and propagated them into user code.\n */\nfunction mapHeadHeaders(headers: Headers, fallbackId: string): ArtifactHead {\n const modeRaw = headers.get('x-atomicmemory-storage-mode');\n const statusRaw = headers.get('x-atomicmemory-storage-status');\n if (modeRaw === null || !(STORAGE_MODES as ReadonlyArray<string>).includes(modeRaw)) {\n throw new StorageClientError({\n message:\n `head(): server returned an unrecognized x-atomicmemory-storage-mode value ` +\n `('${modeRaw ?? '<missing>'}'). Expected one of: ${STORAGE_MODES.join(', ')}.`,\n errorCode: 'invalid_head_response',\n status: 200,\n bodyText: '',\n });\n }\n if (statusRaw === null || !(STORAGE_STATUSES as ReadonlyArray<string>).includes(statusRaw)) {\n throw new StorageClientError({\n message:\n `head(): server returned an unrecognized x-atomicmemory-storage-status value ` +\n `('${statusRaw ?? '<missing>'}'). Expected one of: ${STORAGE_STATUSES.join(', ')}.`,\n errorCode: 'invalid_head_response',\n status: 200,\n bodyText: '',\n });\n }\n return {\n artifactId: headers.get('x-atomicmemory-artifact-id') ?? fallbackId,\n provider: headers.get('x-atomicmemory-provider') ?? '',\n mode: modeRaw as 'pointer' | 'managed',\n status: statusRaw as StorageArtifactStatus,\n sizeBytes: parseSize(headers.get('content-length')),\n contentType: headers.get('content-type'),\n };\n}\n\n/**\n * Narrow a caller-supplied body to a `Uint8Array` view that covers\n * exactly the caller's bytes. Buffer / Uint8Array sub-views keep\n * their `byteOffset` + `byteLength` here so the request layer never\n * sends adjacent bytes from the backing ArrayBuffer.\n *\n * Parameter is `unknown` (not the static `PutManagedInput['body']`\n * type) so the runtime checks guard untyped JS callers too — TS\n * already removed Blob and stream types from the public input, but\n * a JS caller could still hand us a Blob or a stream object.\n */\nfunction coerceManagedBody(body: unknown): Uint8Array {\n if (Buffer.isBuffer(body)) {\n return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n }\n if (body instanceof Uint8Array) return body;\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (typeof Blob !== 'undefined' && body instanceof Blob) {\n // Blob is async-coerce only via arrayBuffer(); reject here and\n // let callers convert deliberately so the client never silently\n // buffers the entire Blob.\n throw new StorageClientError({\n message:\n 'StorageClient.put: Blob input must be converted to Buffer / Uint8Array / ArrayBuffer ' +\n 'before calling put(). Use `new Uint8Array(await blob.arrayBuffer())`.',\n errorCode: 'unsupported_body_type',\n status: 0,\n bodyText: '',\n });\n }\n // Stream / Readable / unknown — explicitly rejected. Streaming\n // body uploads land in the Streaming + Resumable Uploads PR.\n throw new StorageClientError({\n message:\n 'StorageClient.put: only Buffer / Uint8Array / ArrayBuffer are accepted in v1. ' +\n 'Streaming body uploads land in the Streaming + Resumable Uploads PR.',\n errorCode: 'streaming_body_not_supported',\n status: 0,\n bodyText: '',\n });\n}\n\nfunction encodeMetadataHeader(metadata: Record<string, string | number | boolean>): string {\n return Buffer.from(JSON.stringify(metadata), 'utf8').toString('base64');\n}\n\n/**\n * Translate the snake_case wire response into the camelCase SDK\n * shape via an EXPLICIT named-key projection. Wire-only fields\n * (`stored_hash`, `delete_attempt_id`, etc.) the server formatter\n * already redacts; this layer drops anything not in the allowlist\n * even if a future server regression slipped a field through.\n *\n * Closed-set validation. `mode`, `status`, and `content_encoding`\n * are each checked against the enum the SDK actually models — an\n * unrecognized server / proxy / version-skew value throws\n * `StorageClientError({errorCode:'invalid_storage_response'})`\n * rather than silently producing a typed SDK object whose enum\n * fields lie about reality. Same discipline as HEAD header\n * validation.\n *\n * Required-field hardening. The wire contract guarantees\n * `artifact_id`, `provider`, `mode`, `status`, `content_encoding`,\n * `created_at`, `updated_at` on every read. Missing or wrong-type\n * values throw rather than defaulting to empty strings. Wire-only\n * `artifact_id` (no `artifactId` alias) — this is the SDK's snake→\n * camel seam, not a polyfill for callers that pre-translated.\n */\nfunction mapStoredArtifact(raw: Record<string, unknown>): StoredArtifact {\n const artifactId = requireWireString(raw, 'artifact_id');\n const provider = requireWireString(raw, 'provider');\n const mode = requireWireEnum(raw, 'mode', STORAGE_MODES) as 'pointer' | 'managed';\n const status = requireWireEnum(raw, 'status', STORAGE_STATUSES) as StorageArtifactStatus;\n const contentEncoding = requireWireEnum(\n raw, 'content_encoding', CONTENT_ENCODINGS,\n ) as 'identity' | 'aes_gcm';\n const createdAt = requireWireString(raw, 'created_at');\n const updatedAt = requireWireString(raw, 'updated_at');\n const out: StoredArtifact = {\n artifactId,\n provider,\n mode,\n uri: typeof raw.uri === 'string' ? raw.uri : null,\n status,\n sizeBytes: typeof raw.size_bytes === 'number' ? raw.size_bytes : null,\n contentType: typeof raw.content_type === 'string' ? raw.content_type : null,\n contentEncoding,\n identifiers: (raw.identifiers as Record<string, string> | undefined) ?? {},\n lifecycle: (raw.lifecycle as StorageLifecycle | undefined) ?? {},\n metadata:\n (raw.metadata as Record<string, string | number | boolean> | undefined) ?? {},\n createdAt,\n updatedAt,\n };\n if (typeof raw.content_hash === 'string') out.contentHash = raw.content_hash;\n if (raw.provider_details && typeof raw.provider_details === 'object') {\n out.providerDetails = raw.provider_details as Record<string, unknown>;\n }\n if (raw.replication && typeof raw.replication === 'object') {\n out.replication = raw.replication as StoredArtifact['replication'];\n }\n if (raw.verification && typeof raw.verification === 'object') {\n out.verification = raw.verification as StoredArtifact['verification'];\n }\n if (raw.retrieval && typeof raw.retrieval === 'object') {\n out.retrieval = raw.retrieval as StoredArtifact['retrieval'];\n }\n return out;\n}\n\nfunction requireWireString(raw: Record<string, unknown>, field: string): string {\n const value = raw[field];\n if (typeof value !== 'string' || value.length === 0) {\n throw new StorageClientError({\n message:\n `mapStoredArtifact: server response is missing required \\`${field}\\` ` +\n '(or it is not a non-empty string). The storage API contract requires it.',\n errorCode: 'invalid_storage_response',\n status: 200,\n bodyText: '',\n });\n }\n return value;\n}\n\nfunction requireWireEnum<T extends string>(\n raw: Record<string, unknown>,\n field: string,\n allowed: ReadonlyArray<T>,\n): T {\n const value = raw[field];\n if (typeof value !== 'string' || !(allowed as ReadonlyArray<string>).includes(value)) {\n throw new StorageClientError({\n message:\n `mapStoredArtifact: server response field \\`${field}\\` is not in the SDK's ` +\n `closed enum. Got '${String(value ?? '<missing>')}', expected one of: ${allowed.join(', ')}.`,\n errorCode: 'invalid_storage_response',\n status: 200,\n bodyText: '',\n });\n }\n return value as T;\n}\n\n/**\n * Translate the snake_case DELETE response envelope into the\n * camelCase SDK shape. Same discipline as `mapStoredArtifact`:\n *\n * - require non-empty snake_case `artifact_id` (no camelCase\n * alias polyfill — the wire is snake_case);\n * - validate `status` against the closed `StorageArtifactStatus`\n * enum;\n * - throw `StorageClientError({errorCode:'invalid_storage_response'})`\n * on missing / wrong-type / out-of-enum values rather than\n * silently producing a typed SDK object whose fields lie.\n */\nfunction mapDeleteResult(raw: Record<string, unknown>): DeleteArtifactResult {\n const artifactId = requireWireString(raw, 'artifact_id');\n const status = requireWireEnum(raw, 'status', STORAGE_STATUSES) as StorageArtifactStatus;\n const out: DeleteArtifactResult = { artifactId, status };\n if (Array.isArray(raw.cascaded_document_ids)) {\n out.cascadedDocumentIds = raw.cascaded_document_ids.map(String);\n }\n return out;\n}\n\nfunction mapVerifyResult(raw: Record<string, unknown>): VerificationResult {\n const kind = raw.kind;\n if (kind === 'verified') {\n return { kind: 'verified', details: (raw.details ?? {}) as Record<string, unknown> };\n }\n if (kind === 'failed') {\n return { kind: 'failed', reason: String(raw.reason ?? 'unknown failure') };\n }\n return { kind: 'unsupported', reason: String(raw.reason ?? 'unsupported') };\n}\n\nasync function throwForResponse(res: Response, artifactId?: string): Promise<never> {\n const bodyText = await res.text();\n const envelope = parseEnvelope(bodyText);\n const code = envelope.error_code;\n const message = envelope.error ?? `request failed with status ${res.status}`;\n const id = artifactId ?? '';\n if (code === 'artifact_in_use') {\n throw new ArtifactInUseError({\n artifactId: id,\n referencedByDocumentCount: envelope.referenced_by_document_count ?? 0,\n bodyText,\n });\n }\n if (code === 'pointer_content_not_managed') {\n throw new PointerContentNotManagedError({\n artifactId: id,\n uri: envelope.uri ?? '',\n bodyText,\n });\n }\n if (code === 'filecoin_direct_storage_not_yet_supported') {\n throw new FilecoinDirectStorageNotSupportedError({ bodyText });\n }\n if (code === 'artifact_not_found' || res.status === 404) {\n throw new ArtifactNotFoundError({ artifactId: id, bodyText });\n }\n if (code === 'unsupported_capability') {\n throw new UnsupportedCapabilityError({\n capability: 'unknown',\n message,\n bodyText,\n });\n }\n throw new StorageClientError({\n message,\n errorCode: code ?? `http_${res.status}`,\n status: res.status,\n bodyText,\n });\n}\n\nfunction parseEnvelope(bodyText: string): CoreErrorEnvelope {\n if (bodyText.length === 0) return {};\n try {\n return JSON.parse(bodyText) as CoreErrorEnvelope;\n } catch {\n return {};\n }\n}\n"]}
'use strict';
var net = require('net');
// src/utils/validate-api-url.ts
function isLinkLocalIpv4([a, b]) {
return a === 169 && b === 254;
}
function isPrivateIpv4([a, b]) {
return a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 100 && b >= 64 && b <= 127;
}
function isSpecialIpv4([a, b, c, d]) {
const loopback = a === 127;
const unspecified = a === 0;
const broadcast = a === 255 && b === 255 && c === 255 && d === 255;
const reserved = a === 192 && b === 0 && c === 0 || a >= 240;
const multicast = a >= 224 && a <= 239;
return loopback || unspecified || broadcast || reserved || multicast;
}
function classifyIpv4(host) {
const octets = host.split(".").map(Number);
return {
linkLocal: isLinkLocalIpv4(octets),
blockedByDefault: isPrivateIpv4(octets) || isSpecialIpv4(octets)
};
}
function mappedIpv4(host) {
const rest = host.toLowerCase().match(/^::ffff:(.+)$/)?.[1];
if (rest === void 0) return null;
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(rest)) return rest;
const pair = rest.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
if (!pair) return null;
const hi = parseInt(pair[1], 16);
const lo = parseInt(pair[2], 16);
return `${hi >> 8 & 255}.${hi & 255}.${lo >> 8 & 255}.${lo & 255}`;
}
function classifyIpv6(host) {
const mapped = mappedIpv4(host);
if (mapped) return classifyIpv4(mapped);
const lower = host.toLowerCase();
return {
linkLocal: /^fe[89ab]/.test(lower),
// fe80::/10
blockedByDefault: lower === "::1" || lower === "::" || /^f[cd]/.test(lower)
// loopback, unspecified, fc00::/7 ULA
};
}
function validateApiUrl(value, options = {}) {
const stripped = value.trim();
let parsed;
try {
parsed = new URL(stripped);
} catch {
throw new Error("api_url must be an http(s) URL");
}
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error("api_url must be an http(s) URL");
}
const host = parsed.hostname.replace(/^\[|\]$/g, "");
if (!host) throw new Error("api_url must include a host");
const kind = net.isIP(host);
if (kind === 0) return stripped;
const ipClass = kind === 4 ? classifyIpv4(host) : classifyIpv6(host);
if (ipClass.linkLocal) {
throw new Error("api_url must not target a link-local or cloud-metadata address");
}
const allowPrivate = options.allowPrivateNetworks ?? true;
if (!allowPrivate && ipClass.blockedByDefault) {
throw new Error(
"api_url must not target a loopback, private, or reserved address; set allowPrivateNetworks=true to permit it"
);
}
return stripped;
}
exports.validateApiUrl = validateApiUrl;
//# sourceMappingURL=chunk-MIG2OG5Z.cjs.map
//# sourceMappingURL=chunk-MIG2OG5Z.cjs.map
{"version":3,"sources":["../src/utils/validate-api-url.ts"],"names":["isIP"],"mappings":";;;;;AA2CA,SAAS,eAAA,CAAgB,CAAC,CAAA,EAAG,CAAC,CAAA,EAAoB;AAChD,EAAA,OAAO,CAAA,KAAM,OAAO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ClD;AACA,EAAA,IAAI,MAAA,CAAO,QAAA,KAAa,OAAA,IAAW,MAAA,CAAO,aAAa,QAAA,EAAU;AAC/D,IAAA,MAAM,IAAI,MAAM,gCAAgC,CAAA;AAAA,EAClD;AACA,EAAA,MAAM,IAAA,GAAO,MAAA,CAAO,QAAA,CAAS,OAAA,CAAQ,YAAY,EAAE,CAAA;AACnD,EAAA,IAAI,CAAC,IAAA,EAAM,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAExD,EAAA,MAAM,IAAA,GAAOA,SAAK,IAAI,CAAA;AACtB,EAAA,IAAI,IAAA,KAAS,GAAG,OAAO,QAAA;AAEvB,EAAA,MAAM,UAAU,IAAA,KAAS,CAAA,GAAI,aAAa,IAAI,CAAA,GAAI,aAAa,IAAI,CAAA;AACnE,EAAA,IAAI,QAAQ,SAAA,EAAW;AACrB,IAAA,MAAM,IAAI,MAAM,gEAAgE,CAAA;AAAA,EAClF;AACA,EAAA,MAAM,YAAA,GAAe,QAAQ,oBAAA,IAAwB,IAAA;AACrD,EAAA,IAAI,CAAC,YAAA,IAAgB,OAAA,CAAQ,gBAAA,EAAkB;AAC7C,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAEF;AAAA,EACF;AACA,EAAA,OAAO,QAAA;AACT","file":"chunk-MIG2OG5Z.cjs","sourcesContent":["/**\n * @file Shared `api_url` SSRF guard for every SDK client/provider config.\n *\n * Port of the python SDK's `atomicmemory/core/url.py` (AGNT-PY-001). An\n * `api_url` must be an http(s) URL with a host. Link-local addresses — the\n * cloud metadata endpoint `169.254.169.254` (`169.254.0.0/16`) and IPv6\n * `fe80::/10` — are ALWAYS rejected. Loopback / private / reserved literals\n * (incl. the `100.64.0.0/10` CGN range) are ALLOWED BY DEFAULT, since the SDK\n * routinely connects to local and self-hosted cores; pass\n * `allowPrivateNetworks: false` to reject those too (posture B).\n *\n * `URL` normalizes the legacy IPv4 encodings the OS resolver still accepts —\n * decimal (`http://2852039166/`), hex, octal, and short forms — to dotted-quad,\n * so they cannot slip through as hostnames. IPv4-mapped IPv6 (`::ffff:a.b.c.d`)\n * is reclassified by its embedded IPv4. Genuine hostnames (incl. the `localhost`\n * default and `metadata.google.internal`) are intentionally NOT DNS-resolved\n * here — config-time resolution is racy and still bypassable via DNS rebinding;\n * deployments that must defend against hostname-based metadata access should pin\n * `api_url` to a vetted host.\n */\nimport { isIP } from 'node:net';\n\nexport interface ValidateApiUrlOptions {\n /**\n * Permit loopback / private / reserved IP literals (self-hosted / local dev).\n * Defaults to `true`: the SDK routinely connects to private/local cores, so\n * the security floor is the always-on link-local / cloud-metadata block. Set\n * `false` to also reject loopback/private/reserved (stricter, e.g. a hosted\n * multi-tenant deployment). Matches the python SDK's posture.\n */\n allowPrivateNetworks?: boolean;\n}\n\ninterface IpClass {\n /** Link-local / cloud-metadata — always rejected regardless of the opt-in. */\n linkLocal: boolean;\n /** Loopback / private / reserved / multicast / unspecified — gated by the opt-in. */\n blockedByDefault: boolean;\n}\n\ntype Octets = [number, number, number, number];\n\n/** 169.254.0.0/16 — AWS/GCP/Azure instance metadata (IMDS); always blocked. */\nfunction isLinkLocalIpv4([a, b]: Octets): boolean {\n return a === 169 && b === 254;\n}\n\n/** RFC 1918 + 100.64.0.0/10 CGN (e.g. Alibaba metadata). */\nfunction isPrivateIpv4([a, b]: Octets): boolean {\n return (\n a === 10 ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168) ||\n (a === 100 && b >= 64 && b <= 127)\n );\n}\n\n/** Loopback, \"this network\", broadcast, reserved, and multicast ranges. */\nfunction isSpecialIpv4([a, b, c, d]: Octets): boolean {\n const loopback = a === 127; // 127.0.0.0/8\n const unspecified = a === 0; // 0.0.0.0/8 \"this network\"\n const broadcast = a === 255 && b === 255 && c === 255 && d === 255;\n const reserved = (a === 192 && b === 0 && c === 0) || a >= 240; // 192.0.0.0/24, 240.0.0.0/4\n const multicast = a >= 224 && a <= 239; // 224.0.0.0/4\n return loopback || unspecified || broadcast || reserved || multicast;\n}\n\nfunction classifyIpv4(host: string): IpClass {\n const octets = host.split('.').map(Number) as Octets;\n return {\n linkLocal: isLinkLocalIpv4(octets),\n blockedByDefault: isPrivateIpv4(octets) || isSpecialIpv4(octets),\n };\n}\n\nfunction mappedIpv4(host: string): string | null {\n const rest = host.toLowerCase().match(/^::ffff:(.+)$/)?.[1];\n if (rest === undefined) return null;\n if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(rest)) return rest;\n const pair = rest.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);\n if (!pair) return null;\n const hi = parseInt(pair[1], 16);\n const lo = parseInt(pair[2], 16);\n return `${(hi >> 8) & 255}.${hi & 255}.${(lo >> 8) & 255}.${lo & 255}`;\n}\n\nfunction classifyIpv6(host: string): IpClass {\n const mapped = mappedIpv4(host);\n if (mapped) return classifyIpv4(mapped);\n const lower = host.toLowerCase();\n return {\n linkLocal: /^fe[89ab]/.test(lower), // fe80::/10\n blockedByDefault: lower === '::1' || lower === '::' || /^f[cd]/.test(lower), // loopback, unspecified, fc00::/7 ULA\n };\n}\n\n/**\n * Validate and normalize an `api_url`, guarding against SSRF.\n *\n * @param value - The candidate URL.\n * @param options - `allowPrivateNetworks` permits loopback/private/reserved IP\n * literals; link-local / cloud-metadata addresses are rejected regardless.\n * @returns The whitespace-trimmed URL.\n * @throws Error if the scheme is not http(s), the host is missing, or the host\n * is a disallowed IP literal.\n */\nexport function validateApiUrl(value: string, options: ValidateApiUrlOptions = {}): string {\n const stripped = value.trim();\n let parsed: URL;\n try {\n parsed = new URL(stripped);\n } catch {\n throw new Error('api_url must be an http(s) URL');\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error('api_url must be an http(s) URL');\n }\n const host = parsed.hostname.replace(/^\\[|\\]$/g, '');\n if (!host) throw new Error('api_url must include a host');\n\n const kind = isIP(host);\n if (kind === 0) return stripped; // hostname — intentionally not DNS-resolved\n\n const ipClass = kind === 4 ? classifyIpv4(host) : classifyIpv6(host);\n if (ipClass.linkLocal) {\n throw new Error('api_url must not target a link-local or cloud-metadata address');\n }\n const allowPrivate = options.allowPrivateNetworks ?? true;\n if (!allowPrivate && ipClass.blockedByDefault) {\n throw new Error(\n 'api_url must not target a loopback, private, or reserved address; ' +\n 'set allowPrivateNetworks=true to permit it',\n );\n }\n return stripped;\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

+5
-0

@@ -9,2 +9,7 @@ # Changelog

## [1.1.1] - 2026-06-16
### Security
- Hardened client configuration validation. Upgrade recommended.
## [1.0.1] - 2026-05-14

@@ -11,0 +16,0 @@

+23
-22
'use strict';
var chunkKIUVJBBH_cjs = require('./chunk-KIUVJBBH.cjs');
var chunkNULA3B6E_cjs = require('./chunk-NULA3B6E.cjs');
var chunkAQHNXVMQ_cjs = require('./chunk-AQHNXVMQ.cjs');
var chunkWSP2HCUV_cjs = require('./chunk-WSP2HCUV.cjs');
require('./chunk-MIG2OG5Z.cjs');

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

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

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

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';
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-2_IU9rqm.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-2_IU9rqm.cjs';

@@ -4,0 +4,0 @@ /**

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

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';
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-2_IU9rqm.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-2_IU9rqm.js';

@@ -4,0 +4,0 @@ /**

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

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 { MemoryClient } from './chunk-KYVD7KQV.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-KI5UNWJI.js';
import './chunk-3HWUP4VL.js';
//# sourceMappingURL=browser.js.map
//# sourceMappingURL=browser.js.map
'use strict';
var chunkR56Z5WG5_cjs = require('./chunk-R56Z5WG5.cjs');
var chunkKIUVJBBH_cjs = require('./chunk-KIUVJBBH.cjs');
var chunkNULA3B6E_cjs = require('./chunk-NULA3B6E.cjs');
var chunkAQHNXVMQ_cjs = require('./chunk-AQHNXVMQ.cjs');
var chunkWSP2HCUV_cjs = require('./chunk-WSP2HCUV.cjs');
var chunkH52DPNS2_cjs = require('./chunk-H52DPNS2.cjs');
var chunkDIZ6Y5IO_cjs = require('./chunk-DIZ6Y5IO.cjs');
var chunkLPC54QOU_cjs = require('./chunk-LPC54QOU.cjs');
var chunkMIG2OG5Z_cjs = require('./chunk-MIG2OG5Z.cjs');
var chunkZXO6ES3G_cjs = require('./chunk-ZXO6ES3G.cjs');

@@ -26,3 +27,5 @@ var chunkB2CN7FAS_cjs = require('./chunk-B2CN7FAS.cjs');

if (!config.apiKey) throw new Error("EntitiesClient: apiKey is required");
this.apiUrl = config.apiUrl.replace(/\/+$/, "");
this.apiUrl = chunkMIG2OG5Z_cjs.validateApiUrl(config.apiUrl, {
allowPrivateNetworks: config.allowPrivateNetworks
}).replace(/\/+$/, "");
this.apiKey = config.apiKey;

@@ -265,13 +268,18 @@ this.fetchImpl = config.fetch ?? fetch;

}
this.memory = new chunkKIUVJBBH_cjs.MemoryClient(
this.memory = new chunkAQHNXVMQ_cjs.MemoryClient(
config.memory ?? {
providers: {
atomicmemory: { apiUrl: config.apiUrl, apiKey: config.apiKey }
atomicmemory: {
apiUrl: config.apiUrl,
apiKey: config.apiKey,
allowPrivateNetworks: config.allowPrivateNetworks
}
}
}
);
this.storage = new chunkDIZ6Y5IO_cjs.ConcreteStorageClient({
this.storage = new chunkLPC54QOU_cjs.ConcreteStorageClient({
apiUrl: config.apiUrl,
apiKey: config.apiKey,
userId: config.userId,
allowPrivateNetworks: config.allowPrivateNetworks,
fetch: config.fetch

@@ -282,2 +290,3 @@ });

apiKey: config.apiKey,
allowPrivateNetworks: config.allowPrivateNetworks,
fetch: config.fetch

@@ -302,79 +311,79 @@ });

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

@@ -427,27 +436,27 @@ Object.defineProperty(exports, "DEFAULT_VALIDATION_CONFIG", {

enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.ArtifactInUseError; }
get: function () { return chunkLPC54QOU_cjs.ArtifactInUseError; }
});
Object.defineProperty(exports, "ArtifactNotFoundError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.ArtifactNotFoundError; }
get: function () { return chunkLPC54QOU_cjs.ArtifactNotFoundError; }
});
Object.defineProperty(exports, "ConcreteStorageClient", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.ConcreteStorageClient; }
get: function () { return chunkLPC54QOU_cjs.ConcreteStorageClient; }
});
Object.defineProperty(exports, "FilecoinDirectStorageNotSupportedError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.FilecoinDirectStorageNotSupportedError; }
get: function () { return chunkLPC54QOU_cjs.FilecoinDirectStorageNotSupportedError; }
});
Object.defineProperty(exports, "PointerContentNotManagedError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.PointerContentNotManagedError; }
get: function () { return chunkLPC54QOU_cjs.PointerContentNotManagedError; }
});
Object.defineProperty(exports, "StorageClientError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.StorageClientError; }
get: function () { return chunkLPC54QOU_cjs.StorageClientError; }
});
Object.defineProperty(exports, "UnsupportedCapabilityError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.UnsupportedCapabilityError; }
get: function () { return chunkLPC54QOU_cjs.UnsupportedCapabilityError; }
});

@@ -454,0 +463,0 @@ Object.defineProperty(exports, "EmbeddingGenerator", {

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

{"version":3,"sources":["../src/entities/client.ts","../src/client/atomic-memory-client.ts","../src/index.ts"],"names":["MemoryClient","ConcreteStorageClient"],"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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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;AACD,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,cAAA,CAAe;AAAA,MACjC,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.cjs","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"]}
{"version":3,"sources":["../src/entities/client.ts","../src/client/atomic-memory-client.ts","../src/index.ts"],"names":["validateApiUrl","MemoryClient","ConcreteStorageClient"],"mappings":";;;;;;;;;;;;;;;;;;;AAyCO,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,GAASA,gCAAA,CAAe,MAAA,CAAO,MAAA,EAAQ;AAAA,MAC1C,sBAAsB,MAAA,CAAO;AAAA,KAC9B,CAAA,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O,MAAA,EAAQ;AAClB,MAAA,MAAM,IAAI,MAAM,wCAAwC,CAAA;AAAA,IAC1D;AAOA,IAAA,IAAA,CAAK,SAAS,IAAIC,8BAAA;AAAA,MAChB,OAAO,MAAA,IAAU;AAAA,QACf,SAAA,EAAW;AAAA,UACT,YAAA,EAAc;AAAA,YACZ,QAAQ,MAAA,CAAO,MAAA;AAAA,YACf,QAAQ,MAAA,CAAO,MAAA;AAAA,YACf,sBAAsB,MAAA,CAAO;AAAA;AAC/B;AACF;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,sBAAsB,MAAA,CAAO,oBAAA;AAAA,MAC7B,OAAO,MAAA,CAAO;AAAA,KACf,CAAA;AACD,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,cAAA,CAAe;AAAA,MACjC,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,sBAAsB,MAAA,CAAO,oBAAA;AAAA,MAC7B,OAAO,MAAA,CAAO;AAAA,KACf,CAAA;AAAA,EACH;AACF;;;ACqCO,IAAM,WAAA,GAAc;AACpB,IAAM,WAAA,GAAc","file":"index.cjs","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 { validateApiUrl } from '../utils/validate-api-url.js';\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 /**\n * Permit `apiUrl` to target loopback / private / reserved IP literals.\n * Defaults to `true`; set `false` to harden against SSRF. Link-local /\n * cloud-metadata addresses are blocked regardless. See `validateApiUrl`.\n */\n allowPrivateNetworks?: boolean;\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 = validateApiUrl(config.apiUrl, {\n allowPrivateNetworks: config.allowPrivateNetworks,\n }).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 /**\n * Permit `apiUrl` to target loopback / private / reserved IP literals.\n * Defaults to `true` — the SDK routinely connects to local/self-hosted\n * cores. Set `false` to harden against SSRF; link-local / cloud-metadata\n * addresses are blocked regardless. Forwarded to the default memory\n * provider, storage, and entities sub-clients. See `validateApiUrl`.\n */\n allowPrivateNetworks?: boolean;\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: {\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n allowPrivateNetworks: config.allowPrivateNetworks,\n },\n },\n },\n );\n this.storage = new ConcreteStorageClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n userId: config.userId,\n allowPrivateNetworks: config.allowPrivateNetworks,\n fetch: config.fetch,\n });\n this.entities = new EntitiesClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n allowPrivateNetworks: config.allowPrivateNetworks,\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,3 +13,3 @@ 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 { 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 { 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-2_IU9rqm.cjs';
export { CapabilityGap, CapabilityProfile, capabilityGaps, satisfiesProfile } from './memory.cjs';

@@ -148,2 +148,8 @@

apiKey: string;
/**
* Permit `apiUrl` to target loopback / private / reserved IP literals.
* Defaults to `true`; set `false` to harden against SSRF. Link-local /
* cloud-metadata addresses are blocked regardless. See `validateApiUrl`.
*/
allowPrivateNetworks?: boolean;
/** Optional fetch override — defaults to the Node global. */

@@ -236,2 +242,10 @@ fetch?: typeof fetch;

fetch?: typeof fetch;
/**
* Permit `apiUrl` to target loopback / private / reserved IP literals.
* Defaults to `true` — the SDK routinely connects to local/self-hosted
* cores. Set `false` to harden against SSRF; link-local / cloud-metadata
* addresses are blocked regardless. Forwarded to the default memory
* provider, storage, and entities sub-clients. See `validateApiUrl`.
*/
allowPrivateNetworks?: boolean;
/** Memory-provider registration. Defaults to a single AtomicMemory

@@ -238,0 +252,0 @@ * provider pointing at `apiUrl`. */

@@ -13,3 +13,3 @@ 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 { 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 { 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-2_IU9rqm.js';
export { CapabilityGap, CapabilityProfile, capabilityGaps, satisfiesProfile } from './memory.js';

@@ -148,2 +148,8 @@

apiKey: string;
/**
* Permit `apiUrl` to target loopback / private / reserved IP literals.
* Defaults to `true`; set `false` to harden against SSRF. Link-local /
* cloud-metadata addresses are blocked regardless. See `validateApiUrl`.
*/
allowPrivateNetworks?: boolean;
/** Optional fetch override — defaults to the Node global. */

@@ -236,2 +242,10 @@ fetch?: typeof fetch;

fetch?: typeof fetch;
/**
* Permit `apiUrl` to target loopback / private / reserved IP literals.
* Defaults to `true` — the SDK routinely connects to local/self-hosted
* cores. Set `false` to harden against SSRF; link-local / cloud-metadata
* addresses are blocked regardless. Forwarded to the default memory
* provider, storage, and entities sub-clients. See `validateApiUrl`.
*/
allowPrivateNetworks?: boolean;
/** Memory-provider registration. Defaults to a single AtomicMemory

@@ -238,0 +252,0 @@ * provider pointing at `apiUrl`. */

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';
import { MemoryClient } from './chunk-KYVD7KQV.js';
export { MemoryClient } from './chunk-KYVD7KQV.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-KI5UNWJI.js';
export { DEFAULT_VALIDATION_CONFIG, IndexedDBStorageAdapter, MemoryStorageAdapter, StorageManager, StorageValidator, assertValidKey, assertValidKeyValue, assertValidValue, validateKey, validateKeyValue, validateValue } from './chunk-4H2WXRAW.js';
import { ConcreteStorageClient } from './chunk-OFIOAOM3.js';
export { ArtifactInUseError, ArtifactNotFoundError, ConcreteStorageClient, FilecoinDirectStorageNotSupportedError, PointerContentNotManagedError, StorageClientError, UnsupportedCapabilityError } from './chunk-OFIOAOM3.js';
import { ConcreteStorageClient } from './chunk-LCCTVUJO.js';
export { ArtifactInUseError, ArtifactNotFoundError, ConcreteStorageClient, FilecoinDirectStorageNotSupportedError, PointerContentNotManagedError, StorageClientError, UnsupportedCapabilityError } from './chunk-LCCTVUJO.js';
import { validateApiUrl } from './chunk-3HWUP4VL.js';
export { EmbeddingGenerator, WasmSemanticProcessor, testWebAssemblySupport } from './chunk-CLKTWYFG.js';

@@ -26,3 +27,5 @@ export { TransformersAdapter } from './chunk-X73QW6GA.js';

if (!config.apiKey) throw new Error("EntitiesClient: apiKey is required");
this.apiUrl = config.apiUrl.replace(/\/+$/, "");
this.apiUrl = validateApiUrl(config.apiUrl, {
allowPrivateNetworks: config.allowPrivateNetworks
}).replace(/\/+$/, "");
this.apiKey = config.apiKey;

@@ -268,3 +271,7 @@ this.fetchImpl = config.fetch ?? fetch;

providers: {
atomicmemory: { apiUrl: config.apiUrl, apiKey: config.apiKey }
atomicmemory: {
apiUrl: config.apiUrl,
apiKey: config.apiKey,
allowPrivateNetworks: config.allowPrivateNetworks
}
}

@@ -277,2 +284,3 @@ }

userId: config.userId,
allowPrivateNetworks: config.allowPrivateNetworks,
fetch: config.fetch

@@ -283,2 +291,3 @@ });

apiKey: config.apiKey,
allowPrivateNetworks: config.allowPrivateNetworks,
fetch: config.fetch

@@ -285,0 +294,0 @@ });

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

{"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,M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AI,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;AACD,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,cAAA,CAAe;AAAA,MACjC,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"]}
{"version":3,"sources":["../src/entities/client.ts","../src/client/atomic-memory-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAyCO,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,cAAA,CAAe,MAAA,CAAO,MAAA,EAAQ;AAAA,MAC1C,sBAAsB,MAAA,CAAO;AAAA,KAC9B,CAAA,CAA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AAA,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,YAAA,EAAc;AAAA,YACZ,QAAQ,MAAA,CAAO,MAAA;AAAA,YACf,QAAQ,MAAA,CAAO,MAAA;AAAA,YACf,sBAAsB,MAAA,CAAO;AAAA;AAC/B;AACF;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,sBAAsB,MAAA,CAAO,oBAAA;AAAA,MAC7B,OAAO,MAAA,CAAO;AAAA,KACf,CAAA;AACD,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,cAAA,CAAe;AAAA,MACjC,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,sBAAsB,MAAA,CAAO,oBAAA;AAAA,MAC7B,OAAO,MAAA,CAAO;AAAA,KACf,CAAA;AAAA,EACH;AACF;;;ACqCO,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 { validateApiUrl } from '../utils/validate-api-url.js';\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 /**\n * Permit `apiUrl` to target loopback / private / reserved IP literals.\n * Defaults to `true`; set `false` to harden against SSRF. Link-local /\n * cloud-metadata addresses are blocked regardless. See `validateApiUrl`.\n */\n allowPrivateNetworks?: boolean;\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 = validateApiUrl(config.apiUrl, {\n allowPrivateNetworks: config.allowPrivateNetworks,\n }).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 /**\n * Permit `apiUrl` to target loopback / private / reserved IP literals.\n * Defaults to `true` — the SDK routinely connects to local/self-hosted\n * cores. Set `false` to harden against SSRF; link-local / cloud-metadata\n * addresses are blocked regardless. Forwarded to the default memory\n * provider, storage, and entities sub-clients. See `validateApiUrl`.\n */\n allowPrivateNetworks?: boolean;\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: {\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n allowPrivateNetworks: config.allowPrivateNetworks,\n },\n },\n },\n );\n this.storage = new ConcreteStorageClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n userId: config.userId,\n allowPrivateNetworks: config.allowPrivateNetworks,\n fetch: config.fetch,\n });\n this.entities = new EntitiesClient({\n apiUrl: config.apiUrl,\n apiKey: config.apiKey,\n allowPrivateNetworks: config.allowPrivateNetworks,\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 chunkR56Z5WG5_cjs = require('./chunk-R56Z5WG5.cjs');
var chunkNULA3B6E_cjs = require('./chunk-NULA3B6E.cjs');
var chunkWSP2HCUV_cjs = require('./chunk-WSP2HCUV.cjs');
require('./chunk-MIG2OG5Z.cjs');

@@ -18,93 +19,93 @@

enumerable: true,
get: function () { return chunkNULA3B6E_cjs.ATOMICMEMORY_DEFAULT_TIMEOUT; }
get: function () { return chunkWSP2HCUV_cjs.ATOMICMEMORY_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "ATOMICMEMORY_EXTENSION_NAMES", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.ATOMICMEMORY_EXTENSION_NAMES; }
get: function () { return chunkWSP2HCUV_cjs.ATOMICMEMORY_EXTENSION_NAMES; }
});
Object.defineProperty(exports, "AtomicMemoryProvider", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.AtomicMemoryProvider; }
get: function () { return chunkWSP2HCUV_cjs.AtomicMemoryProvider; }
});
Object.defineProperty(exports, "BaseMemoryProvider", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.BaseMemoryProvider; }
get: function () { return chunkWSP2HCUV_cjs.BaseMemoryProvider; }
});
Object.defineProperty(exports, "DEFAULT_META_FACT_PATTERNS", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.DEFAULT_META_FACT_PATTERNS; }
get: function () { return chunkWSP2HCUV_cjs.DEFAULT_META_FACT_PATTERNS; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_API_VERSION", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_API_VERSION; }
get: function () { return chunkWSP2HCUV_cjs.HINDSIGHT_DEFAULT_API_VERSION; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_MAX_TOKENS", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_MAX_TOKENS; }
get: function () { return chunkWSP2HCUV_cjs.HINDSIGHT_DEFAULT_MAX_TOKENS; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_PROJECT_ID", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_PROJECT_ID; }
get: function () { return chunkWSP2HCUV_cjs.HINDSIGHT_DEFAULT_PROJECT_ID; }
});
Object.defineProperty(exports, "HINDSIGHT_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_DEFAULT_TIMEOUT; }
get: function () { return chunkWSP2HCUV_cjs.HINDSIGHT_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "HINDSIGHT_SCOPE_TAGS_MATCH", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.HINDSIGHT_SCOPE_TAGS_MATCH; }
get: function () { return chunkWSP2HCUV_cjs.HINDSIGHT_SCOPE_TAGS_MATCH; }
});
Object.defineProperty(exports, "HindsightProvider", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.HindsightProvider; }
get: function () { return chunkWSP2HCUV_cjs.HindsightProvider; }
});
Object.defineProperty(exports, "InvalidScopeError", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.InvalidScopeError; }
get: function () { return chunkWSP2HCUV_cjs.InvalidScopeError; }
});
Object.defineProperty(exports, "MEM0_DEFAULT_TIMEOUT", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.MEM0_DEFAULT_TIMEOUT; }
get: function () { return chunkWSP2HCUV_cjs.MEM0_DEFAULT_TIMEOUT; }
});
Object.defineProperty(exports, "Mem0ContextProvider", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.Mem0ContextProvider; }
get: function () { return chunkWSP2HCUV_cjs.Mem0ContextProvider; }
});
Object.defineProperty(exports, "Mem0Provider", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.Mem0Provider; }
get: function () { return chunkWSP2HCUV_cjs.Mem0Provider; }
});
Object.defineProperty(exports, "MemoryProviderError", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.MemoryProviderError; }
get: function () { return chunkWSP2HCUV_cjs.MemoryProviderError; }
});
Object.defineProperty(exports, "MemoryTransportError", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.MemoryTransportError; }
get: function () { return chunkWSP2HCUV_cjs.MemoryTransportError; }
});
Object.defineProperty(exports, "RateLimitError", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.RateLimitError; }
get: function () { return chunkWSP2HCUV_cjs.RateLimitError; }
});
Object.defineProperty(exports, "UnsupportedOperationError", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.UnsupportedOperationError; }
get: function () { return chunkWSP2HCUV_cjs.UnsupportedOperationError; }
});
Object.defineProperty(exports, "filterMetaFacts", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.filterMetaFacts; }
get: function () { return chunkWSP2HCUV_cjs.filterMetaFacts; }
});
Object.defineProperty(exports, "isMetaFact", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.isMetaFact; }
get: function () { return chunkWSP2HCUV_cjs.isMetaFact; }
});
Object.defineProperty(exports, "noopMemoryPipeline", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.noopMemoryPipeline; }
get: function () { return chunkWSP2HCUV_cjs.noopMemoryPipeline; }
});
Object.defineProperty(exports, "resolveMetaFactPatterns", {
enumerable: true,
get: function () { return chunkNULA3B6E_cjs.resolveMetaFactPatterns; }
get: function () { return chunkWSP2HCUV_cjs.resolveMetaFactPatterns; }
});
//# sourceMappingURL=memory.cjs.map
//# sourceMappingURL=memory.cjs.map

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

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';
import { ap as IngestInput, F as Capabilities } from './hindsight-provider-2_IU9rqm.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-2_IU9rqm.cjs';

@@ -4,0 +4,0 @@ /**

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

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';
import { ap as IngestInput, F as Capabilities } from './hindsight-provider-2_IU9rqm.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-2_IU9rqm.js';

@@ -4,0 +4,0 @@ /**

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';
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-KI5UNWJI.js';
import './chunk-3HWUP4VL.js';
//# sourceMappingURL=memory.js.map
//# sourceMappingURL=memory.js.map
'use strict';
var chunkDIZ6Y5IO_cjs = require('./chunk-DIZ6Y5IO.cjs');
var chunkLPC54QOU_cjs = require('./chunk-LPC54QOU.cjs');
require('./chunk-MIG2OG5Z.cjs');

@@ -9,29 +10,29 @@

enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.ArtifactInUseError; }
get: function () { return chunkLPC54QOU_cjs.ArtifactInUseError; }
});
Object.defineProperty(exports, "ArtifactNotFoundError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.ArtifactNotFoundError; }
get: function () { return chunkLPC54QOU_cjs.ArtifactNotFoundError; }
});
Object.defineProperty(exports, "ConcreteStorageClient", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.ConcreteStorageClient; }
get: function () { return chunkLPC54QOU_cjs.ConcreteStorageClient; }
});
Object.defineProperty(exports, "FilecoinDirectStorageNotSupportedError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.FilecoinDirectStorageNotSupportedError; }
get: function () { return chunkLPC54QOU_cjs.FilecoinDirectStorageNotSupportedError; }
});
Object.defineProperty(exports, "PointerContentNotManagedError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.PointerContentNotManagedError; }
get: function () { return chunkLPC54QOU_cjs.PointerContentNotManagedError; }
});
Object.defineProperty(exports, "StorageClientError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.StorageClientError; }
get: function () { return chunkLPC54QOU_cjs.StorageClientError; }
});
Object.defineProperty(exports, "UnsupportedCapabilityError", {
enumerable: true,
get: function () { return chunkDIZ6Y5IO_cjs.UnsupportedCapabilityError; }
get: function () { return chunkLPC54QOU_cjs.UnsupportedCapabilityError; }
});
//# sourceMappingURL=storage.cjs.map
//# sourceMappingURL=storage.cjs.map

@@ -393,2 +393,8 @@ /**

apiKey: string;
/**
* Permit `apiUrl` to target loopback / private / reserved IP literals.
* Defaults to `true`; set `false` to harden against SSRF. Link-local /
* cloud-metadata addresses are blocked regardless. See `validateApiUrl`.
*/
allowPrivateNetworks?: boolean;
/** Optional fetch override — defaults to the Node global. */

@@ -395,0 +401,0 @@ fetch?: typeof fetch;

@@ -393,2 +393,8 @@ /**

apiKey: string;
/**
* Permit `apiUrl` to target loopback / private / reserved IP literals.
* Defaults to `true`; set `false` to harden against SSRF. Link-local /
* cloud-metadata addresses are blocked regardless. See `validateApiUrl`.
*/
allowPrivateNetworks?: boolean;
/** Optional fetch override — defaults to the Node global. */

@@ -395,0 +401,0 @@ fetch?: typeof fetch;

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

export { ArtifactInUseError, ArtifactNotFoundError, ConcreteStorageClient, FilecoinDirectStorageNotSupportedError, PointerContentNotManagedError, StorageClientError, UnsupportedCapabilityError } from './chunk-OFIOAOM3.js';
export { ArtifactInUseError, ArtifactNotFoundError, ConcreteStorageClient, FilecoinDirectStorageNotSupportedError, PointerContentNotManagedError, StorageClientError, UnsupportedCapabilityError } from './chunk-LCCTVUJO.js';
import './chunk-3HWUP4VL.js';
//# sourceMappingURL=storage.js.map
//# sourceMappingURL=storage.js.map
{
"name": "@atomicmemory/sdk",
"version": "1.1.0",
"version": "1.1.1",
"type": "module",

@@ -5,0 +5,0 @@ "engines": {

'use strict';
// src/storage/errors.ts
var StorageClientError = class extends Error {
errorCode;
status;
bodyText;
constructor(args) {
super(args.message);
this.name = "StorageClientError";
this.errorCode = args.errorCode;
this.status = args.status;
this.bodyText = args.bodyText;
}
};
var UnsupportedCapabilityError = class extends StorageClientError {
capability;
constructor(args) {
super({
message: args.message,
errorCode: "unsupported_capability",
status: 400,
bodyText: args.bodyText
});
this.name = "UnsupportedCapabilityError";
this.capability = args.capability;
}
};
var ArtifactNotFoundError = class extends StorageClientError {
artifactId;
constructor(args) {
super({
message: `Storage artifact ${args.artifactId} not found`,
errorCode: "artifact_not_found",
status: 404,
bodyText: args.bodyText
});
this.name = "ArtifactNotFoundError";
this.artifactId = args.artifactId;
}
};
var ArtifactInUseError = class extends StorageClientError {
artifactId;
referencedByDocumentCount;
constructor(args) {
super({
message: `Storage artifact ${args.artifactId} is referenced by ${args.referencedByDocumentCount} document(s); pass 'policy: "with_documents"' to cascade`,
errorCode: "artifact_in_use",
status: 409,
bodyText: args.bodyText
});
this.name = "ArtifactInUseError";
this.artifactId = args.artifactId;
this.referencedByDocumentCount = args.referencedByDocumentCount;
}
};
var PointerContentNotManagedError = class extends StorageClientError {
artifactId;
uri;
constructor(args) {
super({
message: `Artifact ${args.artifactId} is pointer-mode; fetch the URI directly (the server does not proxy pointer content)`,
errorCode: "pointer_content_not_managed",
status: 409,
bodyText: args.bodyText
});
this.name = "PointerContentNotManagedError";
this.artifactId = args.artifactId;
this.uri = args.uri;
}
};
var FilecoinDirectStorageNotSupportedError = class extends StorageClientError {
constructor(args) {
super({
message: "Direct Filecoin artifact uploads are not supported in this version. Use document ingestion or pointer mode.",
errorCode: "filecoin_direct_storage_not_yet_supported",
status: 501,
bodyText: args.bodyText
});
this.name = "FilecoinDirectStorageNotSupportedError";
}
};
// src/storage/client.ts
var METADATA_HEADER = "X-AtomicMemory-Metadata";
var ConcreteStorageClient = class {
apiUrl;
apiKey;
userId;
fetchImpl;
constructor(config) {
if (!config.apiUrl) throw new Error("StorageClient: apiUrl is required");
if (!config.apiKey) throw new Error("StorageClient: apiKey is required");
if (!config.userId) throw new Error("StorageClient: userId is required");
this.apiUrl = config.apiUrl.replace(/\/+$/, "");
this.apiKey = config.apiKey;
this.userId = config.userId;
this.fetchImpl = config.fetch ?? fetch;
}
async capabilities() {
const res = await this.request("GET", "/v1/storage/capabilities");
return await res.json();
}
async put(input) {
if (input.mode === "pointer") return this.putPointer(input);
return this.putManaged(input);
}
async get(ref) {
const id = this.requireArtifactId(ref);
const res = await this.request("GET", `/v1/storage/artifacts/${id}`, {}, id);
return mapStoredArtifact(await res.json());
}
async getContent(ref) {
const id = this.requireArtifactId(ref);
return this.request("GET", `/v1/storage/artifacts/${id}/content`, {}, id);
}
async head(ref) {
const id = this.requireArtifactId(ref);
const res = await this.request("HEAD", `/v1/storage/artifacts/${id}`, {}, id);
return mapHeadHeaders(res.headers, id);
}
async delete(ref, options) {
const id = this.requireArtifactId(ref);
const query = options?.policy ? `?policy=${encodeURIComponent(options.policy)}` : "";
const res = await this.request("DELETE", `/v1/storage/artifacts/${id}${query}`, {}, id);
return mapDeleteResult(await res.json());
}
async verify(ref, _options) {
const id = this.requireArtifactId(ref);
const res = await this.request("POST", `/v1/storage/artifacts/${id}/verify`, {}, id);
return mapVerifyResult(await res.json());
}
async putPointer(input) {
const body = {
mode: "pointer",
uri: input.uri,
content_type: input.contentType,
...input.sizeBytes !== void 0 ? { size_bytes: input.sizeBytes } : {},
...input.contentHash !== void 0 ? { content_hash: input.contentHash } : {},
...input.metadata !== void 0 ? { metadata: input.metadata } : {}
};
const res = await this.request("POST", "/v1/storage/artifacts", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
return mapStoredArtifact(await res.json());
}
async putManaged(input) {
const view = coerceManagedBody(input.body);
const params = new URLSearchParams({ mode: "managed" });
if (input.discloseContentHash === true) params.set("disclose_content_hash", "true");
const headers = {
"Content-Type": input.contentType,
"Content-Length": String(view.byteLength)
};
if (input.metadata !== void 0) {
headers[METADATA_HEADER] = encodeMetadataHeader(input.metadata);
}
const res = await this.request(
"POST",
`/v1/storage/artifacts?${params.toString()}`,
// Cast: Node's fetch accepts Uint8Array as BodyInit, but the
// shared lib.dom type predates that. Sending the view directly
// is intentional — see the comment above coerceManagedBody.
{ headers, body: view }
);
return mapStoredArtifact(await res.json());
}
/**
* Send a request to the storage API and map non-2xx responses to
* typed errors. Callers receive the raw `Response` on success and
* read the body themselves so streaming reads (e.g. getContent)
* can stay zero-copy.
*
* Auth contract: owner identity travels on the
* `X-AtomicMemory-User-Id` request header alongside the
* deployment-wide `Authorization: Bearer <apiKey>`. The legacy
* `?user_id=` URL parameter is NEVER serialized — the server's
* auth middleware rejects it with 400 `legacy_user_id_unsupported`.
*
* Transport-level fetch failures (DNS, ECONNREFUSED, AbortError,
* a misconfigured fetch impl that throws synchronously) are
* wrapped as `StorageClientError({errorCode:'network_error',
* status:0})` so callers can branch on a stable error contract
* instead of catching arbitrary `TypeError`s.
*
* `artifactId`, when supplied, threads into the error mapper so
* `ArtifactNotFoundError` / `ArtifactInUseError` /
* `PointerContentNotManagedError` carry the id the caller already
* knows. The capabilities route omits it (no artifact context).
*/
async request(method, path, init = {}, artifactId) {
const url = `${this.apiUrl}${path}`;
let res;
try {
res = await this.fetchImpl(url, {
method,
headers: {
Authorization: `Bearer ${this.apiKey}`,
"X-AtomicMemory-User-Id": this.userId,
...init.headers ?? {}
},
body: init.body
});
} catch (cause) {
throw new StorageClientError({
message: `Network error while calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
errorCode: "network_error",
status: 0,
bodyText: ""
});
}
if (res.ok) return res;
await throwForResponse(res, artifactId);
throw new StorageClientError({
message: `unexpected non-ok response (${res.status})`,
errorCode: "unexpected_response",
status: res.status,
bodyText: ""
});
}
requireArtifactId(ref) {
if (!ref.artifactId) {
throw new StorageClientError({
message: "ArtifactRef.artifactId is required for this operation in v1",
errorCode: "missing_artifact_id",
status: 0,
bodyText: ""
});
}
return ref.artifactId;
}
};
var STORAGE_MODES = ["pointer", "managed"];
var STORAGE_STATUSES = [
"stored",
"pending",
"available",
"unavailable",
"deleting",
"deleted",
"delete_failed",
"failed"
];
var CONTENT_ENCODINGS = ["identity", "aes_gcm"];
function parseSize(value) {
if (value === null) return null;
const n = Number(value);
if (!Number.isFinite(n) || n < 0) return null;
return n;
}
function mapHeadHeaders(headers, fallbackId) {
const modeRaw = headers.get("x-atomicmemory-storage-mode");
const statusRaw = headers.get("x-atomicmemory-storage-status");
if (modeRaw === null || !STORAGE_MODES.includes(modeRaw)) {
throw new StorageClientError({
message: `head(): server returned an unrecognized x-atomicmemory-storage-mode value ('${modeRaw ?? "<missing>"}'). Expected one of: ${STORAGE_MODES.join(", ")}.`,
errorCode: "invalid_head_response",
status: 200,
bodyText: ""
});
}
if (statusRaw === null || !STORAGE_STATUSES.includes(statusRaw)) {
throw new StorageClientError({
message: `head(): server returned an unrecognized x-atomicmemory-storage-status value ('${statusRaw ?? "<missing>"}'). Expected one of: ${STORAGE_STATUSES.join(", ")}.`,
errorCode: "invalid_head_response",
status: 200,
bodyText: ""
});
}
return {
artifactId: headers.get("x-atomicmemory-artifact-id") ?? fallbackId,
provider: headers.get("x-atomicmemory-provider") ?? "",
mode: modeRaw,
status: statusRaw,
sizeBytes: parseSize(headers.get("content-length")),
contentType: headers.get("content-type")
};
}
function coerceManagedBody(body) {
if (Buffer.isBuffer(body)) {
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
}
if (body instanceof Uint8Array) return body;
if (body instanceof ArrayBuffer) return new Uint8Array(body);
if (typeof Blob !== "undefined" && body instanceof Blob) {
throw new StorageClientError({
message: "StorageClient.put: Blob input must be converted to Buffer / Uint8Array / ArrayBuffer before calling put(). Use `new Uint8Array(await blob.arrayBuffer())`.",
errorCode: "unsupported_body_type",
status: 0,
bodyText: ""
});
}
throw new StorageClientError({
message: "StorageClient.put: only Buffer / Uint8Array / ArrayBuffer are accepted in v1. Streaming body uploads land in the Streaming + Resumable Uploads PR.",
errorCode: "streaming_body_not_supported",
status: 0,
bodyText: ""
});
}
function encodeMetadataHeader(metadata) {
return Buffer.from(JSON.stringify(metadata), "utf8").toString("base64");
}
function mapStoredArtifact(raw) {
const artifactId = requireWireString(raw, "artifact_id");
const provider = requireWireString(raw, "provider");
const mode = requireWireEnum(raw, "mode", STORAGE_MODES);
const status = requireWireEnum(raw, "status", STORAGE_STATUSES);
const contentEncoding = requireWireEnum(
raw,
"content_encoding",
CONTENT_ENCODINGS
);
const createdAt = requireWireString(raw, "created_at");
const updatedAt = requireWireString(raw, "updated_at");
const out = {
artifactId,
provider,
mode,
uri: typeof raw.uri === "string" ? raw.uri : null,
status,
sizeBytes: typeof raw.size_bytes === "number" ? raw.size_bytes : null,
contentType: typeof raw.content_type === "string" ? raw.content_type : null,
contentEncoding,
identifiers: raw.identifiers ?? {},
lifecycle: raw.lifecycle ?? {},
metadata: raw.metadata ?? {},
createdAt,
updatedAt
};
if (typeof raw.content_hash === "string") out.contentHash = raw.content_hash;
if (raw.provider_details && typeof raw.provider_details === "object") {
out.providerDetails = raw.provider_details;
}
if (raw.replication && typeof raw.replication === "object") {
out.replication = raw.replication;
}
if (raw.verification && typeof raw.verification === "object") {
out.verification = raw.verification;
}
if (raw.retrieval && typeof raw.retrieval === "object") {
out.retrieval = raw.retrieval;
}
return out;
}
function requireWireString(raw, field) {
const value = raw[field];
if (typeof value !== "string" || value.length === 0) {
throw new StorageClientError({
message: `mapStoredArtifact: server response is missing required \`${field}\` (or it is not a non-empty string). The storage API contract requires it.`,
errorCode: "invalid_storage_response",
status: 200,
bodyText: ""
});
}
return value;
}
function requireWireEnum(raw, field, allowed) {
const value = raw[field];
if (typeof value !== "string" || !allowed.includes(value)) {
throw new StorageClientError({
message: `mapStoredArtifact: server response field \`${field}\` is not in the SDK's closed enum. Got '${String(value ?? "<missing>")}', expected one of: ${allowed.join(", ")}.`,
errorCode: "invalid_storage_response",
status: 200,
bodyText: ""
});
}
return value;
}
function mapDeleteResult(raw) {
const artifactId = requireWireString(raw, "artifact_id");
const status = requireWireEnum(raw, "status", STORAGE_STATUSES);
const out = { artifactId, status };
if (Array.isArray(raw.cascaded_document_ids)) {
out.cascadedDocumentIds = raw.cascaded_document_ids.map(String);
}
return out;
}
function mapVerifyResult(raw) {
const kind = raw.kind;
if (kind === "verified") {
return { kind: "verified", details: raw.details ?? {} };
}
if (kind === "failed") {
return { kind: "failed", reason: String(raw.reason ?? "unknown failure") };
}
return { kind: "unsupported", reason: String(raw.reason ?? "unsupported") };
}
async function throwForResponse(res, artifactId) {
const bodyText = await res.text();
const envelope = parseEnvelope(bodyText);
const code = envelope.error_code;
const message = envelope.error ?? `request failed with status ${res.status}`;
const id = artifactId ?? "";
if (code === "artifact_in_use") {
throw new ArtifactInUseError({
artifactId: id,
referencedByDocumentCount: envelope.referenced_by_document_count ?? 0,
bodyText
});
}
if (code === "pointer_content_not_managed") {
throw new PointerContentNotManagedError({
artifactId: id,
uri: envelope.uri ?? "",
bodyText
});
}
if (code === "filecoin_direct_storage_not_yet_supported") {
throw new FilecoinDirectStorageNotSupportedError({ bodyText });
}
if (code === "artifact_not_found" || res.status === 404) {
throw new ArtifactNotFoundError({ artifactId: id, bodyText });
}
if (code === "unsupported_capability") {
throw new UnsupportedCapabilityError({
capability: "unknown",
message,
bodyText
});
}
throw new StorageClientError({
message,
errorCode: code ?? `http_${res.status}`,
status: res.status,
bodyText
});
}
function parseEnvelope(bodyText) {
if (bodyText.length === 0) return {};
try {
return JSON.parse(bodyText);
} catch {
return {};
}
}
exports.ArtifactInUseError = ArtifactInUseError;
exports.ArtifactNotFoundError = ArtifactNotFoundError;
exports.ConcreteStorageClient = ConcreteStorageClient;
exports.FilecoinDirectStorageNotSupportedError = FilecoinDirectStorageNotSupportedError;
exports.PointerContentNotManagedError = PointerContentNotManagedError;
exports.StorageClientError = StorageClientError;
exports.UnsupportedCapabilityError = UnsupportedCapabilityError;
//# sourceMappingURL=chunk-DIZ6Y5IO.cjs.map
//# sourceMappingURL=chunk-DIZ6Y5IO.cjs.map
{"version":3,"sources":["../src/storage/errors.ts","../src/storage/client.ts"],"names":[],"mappings":";;;AAkBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EACnC,SAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACT,YAAY,IAAA,EAKT;AACD,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AACZ,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AAAA,EACvB;AACF;AAMO,IAAM,0BAAA,GAAN,cAAyC,kBAAA,CAAmB;AAAA,EACxD,UAAA;AAAA,EACT,YAAY,IAAA,EAIT;AACD,IAAA,KAAA,CAAM;AAAA,MACJ,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,SAAA,EAAW,wBAAA;AAAA,M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EAAC;AAAA,EACV;AACF","file":"chunk-DIZ6Y5IO.cjs","sourcesContent":["/**\n * @file Artifact-storage error classes.\n *\n * Instanceof-checkable error classes the SDK throws from\n * `client.storage.*` methods. v1 exports the class shapes only\n * — no message formatting magic.\n *\n * Why classes (not enums): callers can `catch (err)\n * { if (err instanceof ArtifactInUseError) { ... } }` without\n * pattern-matching on `error_code` strings, and bundled stack\n * traces survive code minification.\n */\n\n/**\n * Base class for everything `client.storage.*` throws when the\n * server returns a typed error envelope. `errorCode` mirrors the\n * server's `error_code` field — opaque, snake_case, stable.\n */\nexport class StorageClientError extends Error {\n readonly errorCode: string;\n readonly status: number;\n readonly bodyText: string;\n constructor(args: {\n message: string;\n errorCode: string;\n status: number;\n bodyText: string;\n }) {\n super(args.message);\n this.name = 'StorageClientError';\n this.errorCode = args.errorCode;\n this.status = args.status;\n this.bodyText = args.bodyText;\n }\n}\n\n/**\n * Thrown when a capability the call assumes (range read, bundles,\n * `hash_verify` mode) isn't supported by the active backend.\n */\nexport class UnsupportedCapabilityError extends StorageClientError {\n readonly capability: string;\n constructor(args: {\n capability: string;\n message: string;\n bodyText: string;\n }) {\n super({\n message: args.message,\n errorCode: 'unsupported_capability',\n status: 400,\n bodyText: args.bodyText,\n });\n this.name = 'UnsupportedCapabilityError';\n this.capability = args.capability;\n }\n}\n\n/** Thrown when `get` / `head` / `delete` / `verify` cannot find the artifact. */\nexport class ArtifactNotFoundError extends StorageClientError {\n readonly artifactId: string;\n constructor(args: { artifactId: string; bodyText: string }) {\n super({\n message: `Storage artifact ${args.artifactId} not found`,\n errorCode: 'artifact_not_found',\n status: 404,\n bodyText: args.bodyText,\n });\n this.name = 'ArtifactNotFoundError';\n this.artifactId = args.artifactId;\n }\n}\n\n/**\n * Thrown when a default delete hits a referenced artifact. Server\n * returns 409 with `referenced_by_document_count`; callers can use\n * `?policy=with_documents` to cascade.\n */\nexport class ArtifactInUseError extends StorageClientError {\n readonly artifactId: string;\n readonly referencedByDocumentCount: number;\n constructor(args: {\n artifactId: string;\n referencedByDocumentCount: number;\n bodyText: string;\n }) {\n super({\n message:\n `Storage artifact ${args.artifactId} is referenced by ` +\n `${args.referencedByDocumentCount} document(s); pass ` +\n `'policy: \\\"with_documents\\\"' to cascade`,\n errorCode: 'artifact_in_use',\n status: 409,\n bodyText: args.bodyText,\n });\n this.name = 'ArtifactInUseError';\n this.artifactId = args.artifactId;\n this.referencedByDocumentCount = args.referencedByDocumentCount;\n }\n}\n\n/**\n * Thrown when `getContent` targets a pointer-mode artifact. v1\n * pointers are metadata-only — the server NEVER proxies external\n * bytes. Caller must fetch the URI directly.\n */\nexport class PointerContentNotManagedError extends StorageClientError {\n readonly artifactId: string;\n readonly uri: string;\n constructor(args: { artifactId: string; uri: string; bodyText: string }) {\n super({\n message:\n `Artifact ${args.artifactId} is pointer-mode; fetch the URI ` +\n `directly (the server does not proxy pointer content)`,\n errorCode: 'pointer_content_not_managed',\n status: 409,\n bodyText: args.bodyText,\n });\n this.name = 'PointerContentNotManagedError';\n this.artifactId = args.artifactId;\n this.uri = args.uri;\n }\n}\n\n/**\n * Thrown when a managed put against a Filecoin backend hits the v1\n * carve-out (direct Filecoin uploads require artifact reconciliation,\n * which is not implemented yet). Callers can use document ingestion\n * (`PUT /v1/documents/:id/raw`) or pointer mode against Filecoin.\n */\nexport class FilecoinDirectStorageNotSupportedError extends StorageClientError {\n constructor(args: { bodyText: string }) {\n super({\n message:\n 'Direct Filecoin artifact uploads are not supported in this ' +\n 'version. Use document ingestion or pointer mode.',\n errorCode: 'filecoin_direct_storage_not_yet_supported',\n status: 501,\n bodyText: args.bodyText,\n });\n this.name = 'FilecoinDirectStorageNotSupportedError';\n }\n}\n","/**\n * @file Concrete `StorageClient` implementation.\n *\n * Wraps `fetch` to call the direct storage API\n * (`/v1/storage/artifacts/*`). The SDK is server-side only —\n * `Authorization: Bearer <apiKey>` is sent from a trusted process;\n * browser callers must proxy through a server they control.\n *\n * Managed-mode bodies are restricted to known-length values\n * (`Buffer | Uint8Array | ArrayBuffer`) so the client can compute\n * `Content-Length` before sending — the server requires it. Streams\n * (`ReadableStream`, Node `Readable`) are explicitly rejected with\n * `streaming_body_not_supported`; `Blob` is rejected with\n * `unsupported_body_type` so the silent buffering needed to compute\n * `Content-Length` stays visible at the call site (convert with\n * `new Uint8Array(await blob.arrayBuffer())` first). Streaming +\n * resumable uploads land in a follow-up PR.\n *\n * Wire mapping: core emits snake_case (`artifact_id`,\n * `cascaded_document_ids`); the SDK's public types use camelCase for\n * the top-level handles (`artifactId`, `cascadedDocumentIds`). The\n * client is the single seam that translates.\n */\n\nimport {\n ArtifactInUseError,\n ArtifactNotFoundError,\n FilecoinDirectStorageNotSupportedError,\n PointerContentNotManagedError,\n StorageClientError,\n UnsupportedCapabilityError,\n} from './errors.js';\nimport type { StorageClient } from './interfaces.js';\nimport type {\n ArtifactBody,\n ArtifactHead,\n ArtifactRef,\n DeleteArtifactOptions,\n DeleteArtifactResult,\n PutArtifactInput,\n PutManagedInput,\n StorageArtifactStatus,\n StorageCapabilities,\n StorageLifecycle,\n StoredArtifact,\n VerificationResult,\n VerifyArtifactOptions,\n} from './types.js';\n\n/** Caller-supplied configuration for the concrete client. */\nexport interface StorageClientConfig {\n apiUrl: string;\n apiKey: string;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n /** Owner scope for the caller. Sent as `X-AtomicMemory-User-Id`\n * on every storage request. The legacy `?user_id=` URL parameter\n * is not used — the server rejects it with 400\n * `legacy_user_id_unsupported`. */\n userId: string;\n}\n\nconst METADATA_HEADER = 'X-AtomicMemory-Metadata';\n\n/** Wire-shape JSON envelope the core route layer emits on errors. */\ninterface CoreErrorEnvelope {\n error_code?: string;\n error?: string;\n uri?: string;\n referenced_by_document_count?: number;\n allowed_schemes?: ReadonlyArray<string>;\n}\n\nexport class ConcreteStorageClient implements StorageClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly userId: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: StorageClientConfig) {\n if (!config.apiUrl) throw new Error('StorageClient: apiUrl is required');\n if (!config.apiKey) throw new Error('StorageClient: apiKey is required');\n if (!config.userId) throw new Error('StorageClient: userId is required');\n this.apiUrl = config.apiUrl.replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.userId = config.userId;\n this.fetchImpl = config.fetch ?? fetch;\n }\n\n async capabilities(): Promise<StorageCapabilities> {\n const res = await this.request('GET', '/v1/storage/capabilities');\n return (await res.json()) as StorageCapabilities;\n }\n\n async put(input: PutArtifactInput): Promise<StoredArtifact> {\n if (input.mode === 'pointer') return this.putPointer(input);\n return this.putManaged(input);\n }\n\n async get(ref: ArtifactRef): Promise<StoredArtifact> {\n const id = this.requireArtifactId(ref);\n const res = await this.request('GET', `/v1/storage/artifacts/${id}`, {}, id);\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n async getContent(ref: ArtifactRef): Promise<ArtifactBody> {\n const id = this.requireArtifactId(ref);\n return this.request('GET', `/v1/storage/artifacts/${id}/content`, {}, id);\n }\n\n async head(ref: ArtifactRef): Promise<ArtifactHead> {\n const id = this.requireArtifactId(ref);\n const res = await this.request('HEAD', `/v1/storage/artifacts/${id}`, {}, id);\n return mapHeadHeaders(res.headers, id);\n }\n\n async delete(\n ref: ArtifactRef,\n options?: DeleteArtifactOptions,\n ): Promise<DeleteArtifactResult> {\n const id = this.requireArtifactId(ref);\n const query = options?.policy ? `?policy=${encodeURIComponent(options.policy)}` : '';\n const res = await this.request('DELETE', `/v1/storage/artifacts/${id}${query}`, {}, id);\n return mapDeleteResult((await res.json()) as Record<string, unknown>);\n }\n\n async verify(\n ref: ArtifactRef,\n _options?: VerifyArtifactOptions,\n ): Promise<VerificationResult> {\n // `_options` is reserved for future verification depth choices;\n // the server ignores it in v1, so we do not serialize it on\n // the request.\n const id = this.requireArtifactId(ref);\n const res = await this.request('POST', `/v1/storage/artifacts/${id}/verify`, {}, id);\n return mapVerifyResult((await res.json()) as Record<string, unknown>);\n }\n\n private async putPointer(input: Extract<PutArtifactInput, { mode: 'pointer' }>): Promise<StoredArtifact> {\n const body = {\n mode: 'pointer' as const,\n uri: input.uri,\n content_type: input.contentType,\n ...(input.sizeBytes !== undefined ? { size_bytes: input.sizeBytes } : {}),\n ...(input.contentHash !== undefined ? { content_hash: input.contentHash } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n const res = await this.request('POST', '/v1/storage/artifacts', {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n private async putManaged(input: PutManagedInput): Promise<StoredArtifact> {\n // `view` is a Uint8Array narrowed to exactly the caller's bytes —\n // `Buffer` and Uint8Array sub-views share a backing ArrayBuffer\n // with potentially much larger contents, so we MUST send the view\n // itself (or an exact ArrayBuffer slice). Sending `view.buffer`\n // would leak adjacent bytes and produce a body whose actual size\n // disagrees with `Content-Length`.\n const view = coerceManagedBody(input.body);\n const params = new URLSearchParams({ mode: 'managed' });\n if (input.discloseContentHash === true) params.set('disclose_content_hash', 'true');\n const headers: Record<string, string> = {\n 'Content-Type': input.contentType,\n 'Content-Length': String(view.byteLength),\n };\n if (input.metadata !== undefined) {\n headers[METADATA_HEADER] = encodeMetadataHeader(input.metadata);\n }\n const res = await this.request(\n 'POST',\n `/v1/storage/artifacts?${params.toString()}`,\n // Cast: Node's fetch accepts Uint8Array as BodyInit, but the\n // shared lib.dom type predates that. Sending the view directly\n // is intentional — see the comment above coerceManagedBody.\n { headers, body: view as unknown as BodyInit },\n );\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n /**\n * Send a request to the storage API and map non-2xx responses to\n * typed errors. Callers receive the raw `Response` on success and\n * read the body themselves so streaming reads (e.g. getContent)\n * can stay zero-copy.\n *\n * Auth contract: owner identity travels on the\n * `X-AtomicMemory-User-Id` request header alongside the\n * deployment-wide `Authorization: Bearer <apiKey>`. The legacy\n * `?user_id=` URL parameter is NEVER serialized — the server's\n * auth middleware rejects it with 400 `legacy_user_id_unsupported`.\n *\n * Transport-level fetch failures (DNS, ECONNREFUSED, AbortError,\n * a misconfigured fetch impl that throws synchronously) are\n * wrapped as `StorageClientError({errorCode:'network_error',\n * status:0})` so callers can branch on a stable error contract\n * instead of catching arbitrary `TypeError`s.\n *\n * `artifactId`, when supplied, threads into the error mapper so\n * `ArtifactNotFoundError` / `ArtifactInUseError` /\n * `PointerContentNotManagedError` carry the id the caller already\n * knows. The capabilities route omits it (no artifact context).\n */\n private async request(\n method: string,\n path: string,\n init: { headers?: Record<string, string>; body?: BodyInit } = {},\n artifactId?: string,\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: {\n Authorization: `Bearer ${this.apiKey}`,\n 'X-AtomicMemory-User-Id': this.userId,\n ...(init.headers ?? {}),\n },\n body: init.body,\n });\n } catch (cause) {\n throw new StorageClientError({\n message:\n `Network error while calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,\n errorCode: 'network_error',\n status: 0,\n bodyText: '',\n });\n }\n if (res.ok) return res;\n await throwForResponse(res, artifactId);\n // Unreachable — throwForResponse always throws on non-ok.\n throw new StorageClientError({\n message: `unexpected non-ok response (${res.status})`,\n errorCode: 'unexpected_response',\n status: res.status,\n bodyText: '',\n });\n }\n\n private requireArtifactId(ref: ArtifactRef): string {\n if (!ref.artifactId) {\n throw new StorageClientError({\n message: 'ArtifactRef.artifactId is required for this operation in v1',\n errorCode: 'missing_artifact_id',\n status: 0,\n bodyText: '',\n });\n }\n return ref.artifactId;\n }\n}\n\n/** Closed enums the SDK consumes from HEAD response headers + JSON bodies. */\nconst STORAGE_MODES = ['pointer', 'managed'] as const;\nconst STORAGE_STATUSES: ReadonlyArray<StorageArtifactStatus> = [\n 'stored', 'pending', 'available', 'unavailable',\n 'deleting', 'deleted', 'delete_failed', 'failed',\n];\nconst CONTENT_ENCODINGS = ['identity', 'aes_gcm'] as const;\n\nfunction parseSize(value: string | null): number | null {\n if (value === null) return null;\n const n = Number(value);\n if (!Number.isFinite(n) || n < 0) return null;\n return n;\n}\n\n/**\n * Project HEAD response headers into an `ArtifactHead`. Validates\n * mode + status against the SDK's closed enums; throws a typed\n * `StorageClientError({errorCode:'invalid_head_response'})` if the\n * server sends a value the SDK doesn't model. The previous shape\n * cast arbitrary header strings to the enum types, which silently\n * accepted unknown values and propagated them into user code.\n */\nfunction mapHeadHeaders(headers: Headers, fallbackId: string): ArtifactHead {\n const modeRaw = headers.get('x-atomicmemory-storage-mode');\n const statusRaw = headers.get('x-atomicmemory-storage-status');\n if (modeRaw === null || !(STORAGE_MODES as ReadonlyArray<string>).includes(modeRaw)) {\n throw new StorageClientError({\n message:\n `head(): server returned an unrecognized x-atomicmemory-storage-mode value ` +\n `('${modeRaw ?? '<missing>'}'). Expected one of: ${STORAGE_MODES.join(', ')}.`,\n errorCode: 'invalid_head_response',\n status: 200,\n bodyText: '',\n });\n }\n if (statusRaw === null || !(STORAGE_STATUSES as ReadonlyArray<string>).includes(statusRaw)) {\n throw new StorageClientError({\n message:\n `head(): server returned an unrecognized x-atomicmemory-storage-status value ` +\n `('${statusRaw ?? '<missing>'}'). Expected one of: ${STORAGE_STATUSES.join(', ')}.`,\n errorCode: 'invalid_head_response',\n status: 200,\n bodyText: '',\n });\n }\n return {\n artifactId: headers.get('x-atomicmemory-artifact-id') ?? fallbackId,\n provider: headers.get('x-atomicmemory-provider') ?? '',\n mode: modeRaw as 'pointer' | 'managed',\n status: statusRaw as StorageArtifactStatus,\n sizeBytes: parseSize(headers.get('content-length')),\n contentType: headers.get('content-type'),\n };\n}\n\n/**\n * Narrow a caller-supplied body to a `Uint8Array` view that covers\n * exactly the caller's bytes. Buffer / Uint8Array sub-views keep\n * their `byteOffset` + `byteLength` here so the request layer never\n * sends adjacent bytes from the backing ArrayBuffer.\n *\n * Parameter is `unknown` (not the static `PutManagedInput['body']`\n * type) so the runtime checks guard untyped JS callers too — TS\n * already removed Blob and stream types from the public input, but\n * a JS caller could still hand us a Blob or a stream object.\n */\nfunction coerceManagedBody(body: unknown): Uint8Array {\n if (Buffer.isBuffer(body)) {\n return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n }\n if (body instanceof Uint8Array) return body;\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (typeof Blob !== 'undefined' && body instanceof Blob) {\n // Blob is async-coerce only via arrayBuffer(); reject here and\n // let callers convert deliberately so the client never silently\n // buffers the entire Blob.\n throw new StorageClientError({\n message:\n 'StorageClient.put: Blob input must be converted to Buffer / Uint8Array / ArrayBuffer ' +\n 'before calling put(). Use `new Uint8Array(await blob.arrayBuffer())`.',\n errorCode: 'unsupported_body_type',\n status: 0,\n bodyText: '',\n });\n }\n // Stream / Readable / unknown — explicitly rejected. Streaming\n // body uploads land in the Streaming + Resumable Uploads PR.\n throw new StorageClientError({\n message:\n 'StorageClient.put: only Buffer / Uint8Array / ArrayBuffer are accepted in v1. ' +\n 'Streaming body uploads land in the Streaming + Resumable Uploads PR.',\n errorCode: 'streaming_body_not_supported',\n status: 0,\n bodyText: '',\n });\n}\n\nfunction encodeMetadataHeader(metadata: Record<string, string | number | boolean>): string {\n return Buffer.from(JSON.stringify(metadata), 'utf8').toString('base64');\n}\n\n/**\n * Translate the snake_case wire response into the camelCase SDK\n * shape via an EXPLICIT named-key projection. Wire-only fields\n * (`stored_hash`, `delete_attempt_id`, etc.) the server formatter\n * already redacts; this layer drops anything not in the allowlist\n * even if a future server regression slipped a field through.\n *\n * Closed-set validation. `mode`, `status`, and `content_encoding`\n * are each checked against the enum the SDK actually models — an\n * unrecognized server / proxy / version-skew value throws\n * `StorageClientError({errorCode:'invalid_storage_response'})`\n * rather than silently producing a typed SDK object whose enum\n * fields lie about reality. Same discipline as HEAD header\n * validation.\n *\n * Required-field hardening. The wire contract guarantees\n * `artifact_id`, `provider`, `mode`, `status`, `content_encoding`,\n * `created_at`, `updated_at` on every read. Missing or wrong-type\n * values throw rather than defaulting to empty strings. Wire-only\n * `artifact_id` (no `artifactId` alias) — this is the SDK's snake→\n * camel seam, not a polyfill for callers that pre-translated.\n */\nfunction mapStoredArtifact(raw: Record<string, unknown>): StoredArtifact {\n const artifactId = requireWireString(raw, 'artifact_id');\n const provider = requireWireString(raw, 'provider');\n const mode = requireWireEnum(raw, 'mode', STORAGE_MODES) as 'pointer' | 'managed';\n const status = requireWireEnum(raw, 'status', STORAGE_STATUSES) as StorageArtifactStatus;\n const contentEncoding = requireWireEnum(\n raw, 'content_encoding', CONTENT_ENCODINGS,\n ) as 'identity' | 'aes_gcm';\n const createdAt = requireWireString(raw, 'created_at');\n const updatedAt = requireWireString(raw, 'updated_at');\n const out: StoredArtifact = {\n artifactId,\n provider,\n mode,\n uri: typeof raw.uri === 'string' ? raw.uri : null,\n status,\n sizeBytes: typeof raw.size_bytes === 'number' ? raw.size_bytes : null,\n contentType: typeof raw.content_type === 'string' ? raw.content_type : null,\n contentEncoding,\n identifiers: (raw.identifiers as Record<string, string> | undefined) ?? {},\n lifecycle: (raw.lifecycle as StorageLifecycle | undefined) ?? {},\n metadata:\n (raw.metadata as Record<string, string | number | boolean> | undefined) ?? {},\n createdAt,\n updatedAt,\n };\n if (typeof raw.content_hash === 'string') out.contentHash = raw.content_hash;\n if (raw.provider_details && typeof raw.provider_details === 'object') {\n out.providerDetails = raw.provider_details as Record<string, unknown>;\n }\n if (raw.replication && typeof raw.replication === 'object') {\n out.replication = raw.replication as StoredArtifact['replication'];\n }\n if (raw.verification && typeof raw.verification === 'object') {\n out.verification = raw.verification as StoredArtifact['verification'];\n }\n if (raw.retrieval && typeof raw.retrieval === 'object') {\n out.retrieval = raw.retrieval as StoredArtifact['retrieval'];\n }\n return out;\n}\n\nfunction requireWireString(raw: Record<string, unknown>, field: string): string {\n const value = raw[field];\n if (typeof value !== 'string' || value.length === 0) {\n throw new StorageClientError({\n message:\n `mapStoredArtifact: server response is missing required \\`${field}\\` ` +\n '(or it is not a non-empty string). The storage API contract requires it.',\n errorCode: 'invalid_storage_response',\n status: 200,\n bodyText: '',\n });\n }\n return value;\n}\n\nfunction requireWireEnum<T extends string>(\n raw: Record<string, unknown>,\n field: string,\n allowed: ReadonlyArray<T>,\n): T {\n const value = raw[field];\n if (typeof value !== 'string' || !(allowed as ReadonlyArray<string>).includes(value)) {\n throw new StorageClientError({\n message:\n `mapStoredArtifact: server response field \\`${field}\\` is not in the SDK's ` +\n `closed enum. Got '${String(value ?? '<missing>')}', expected one of: ${allowed.join(', ')}.`,\n errorCode: 'invalid_storage_response',\n status: 200,\n bodyText: '',\n });\n }\n return value as T;\n}\n\n/**\n * Translate the snake_case DELETE response envelope into the\n * camelCase SDK shape. Same discipline as `mapStoredArtifact`:\n *\n * - require non-empty snake_case `artifact_id` (no camelCase\n * alias polyfill — the wire is snake_case);\n * - validate `status` against the closed `StorageArtifactStatus`\n * enum;\n * - throw `StorageClientError({errorCode:'invalid_storage_response'})`\n * on missing / wrong-type / out-of-enum values rather than\n * silently producing a typed SDK object whose fields lie.\n */\nfunction mapDeleteResult(raw: Record<string, unknown>): DeleteArtifactResult {\n const artifactId = requireWireString(raw, 'artifact_id');\n const status = requireWireEnum(raw, 'status', STORAGE_STATUSES) as StorageArtifactStatus;\n const out: DeleteArtifactResult = { artifactId, status };\n if (Array.isArray(raw.cascaded_document_ids)) {\n out.cascadedDocumentIds = raw.cascaded_document_ids.map(String);\n }\n return out;\n}\n\nfunction mapVerifyResult(raw: Record<string, unknown>): VerificationResult {\n const kind = raw.kind;\n if (kind === 'verified') {\n return { kind: 'verified', details: (raw.details ?? {}) as Record<string, unknown> };\n }\n if (kind === 'failed') {\n return { kind: 'failed', reason: String(raw.reason ?? 'unknown failure') };\n }\n return { kind: 'unsupported', reason: String(raw.reason ?? 'unsupported') };\n}\n\nasync function throwForResponse(res: Response, artifactId?: string): Promise<never> {\n const bodyText = await res.text();\n const envelope = parseEnvelope(bodyText);\n const code = envelope.error_code;\n const message = envelope.error ?? `request failed with status ${res.status}`;\n const id = artifactId ?? '';\n if (code === 'artifact_in_use') {\n throw new ArtifactInUseError({\n artifactId: id,\n referencedByDocumentCount: envelope.referenced_by_document_count ?? 0,\n bodyText,\n });\n }\n if (code === 'pointer_content_not_managed') {\n throw new PointerContentNotManagedError({\n artifactId: id,\n uri: envelope.uri ?? '',\n bodyText,\n });\n }\n if (code === 'filecoin_direct_storage_not_yet_supported') {\n throw new FilecoinDirectStorageNotSupportedError({ bodyText });\n }\n if (code === 'artifact_not_found' || res.status === 404) {\n throw new ArtifactNotFoundError({ artifactId: id, bodyText });\n }\n if (code === 'unsupported_capability') {\n throw new UnsupportedCapabilityError({\n capability: 'unknown',\n message,\n bodyText,\n });\n }\n throw new StorageClientError({\n message,\n errorCode: code ?? `http_${res.status}`,\n status: res.status,\n bodyText,\n });\n}\n\nfunction parseEnvelope(bodyText: string): CoreErrorEnvelope {\n if (bodyText.length === 0) return {};\n try {\n return JSON.parse(bodyText) as CoreErrorEnvelope;\n } catch {\n return {};\n }\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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A;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-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

// src/storage/errors.ts
var StorageClientError = class extends Error {
errorCode;
status;
bodyText;
constructor(args) {
super(args.message);
this.name = "StorageClientError";
this.errorCode = args.errorCode;
this.status = args.status;
this.bodyText = args.bodyText;
}
};
var UnsupportedCapabilityError = class extends StorageClientError {
capability;
constructor(args) {
super({
message: args.message,
errorCode: "unsupported_capability",
status: 400,
bodyText: args.bodyText
});
this.name = "UnsupportedCapabilityError";
this.capability = args.capability;
}
};
var ArtifactNotFoundError = class extends StorageClientError {
artifactId;
constructor(args) {
super({
message: `Storage artifact ${args.artifactId} not found`,
errorCode: "artifact_not_found",
status: 404,
bodyText: args.bodyText
});
this.name = "ArtifactNotFoundError";
this.artifactId = args.artifactId;
}
};
var ArtifactInUseError = class extends StorageClientError {
artifactId;
referencedByDocumentCount;
constructor(args) {
super({
message: `Storage artifact ${args.artifactId} is referenced by ${args.referencedByDocumentCount} document(s); pass 'policy: "with_documents"' to cascade`,
errorCode: "artifact_in_use",
status: 409,
bodyText: args.bodyText
});
this.name = "ArtifactInUseError";
this.artifactId = args.artifactId;
this.referencedByDocumentCount = args.referencedByDocumentCount;
}
};
var PointerContentNotManagedError = class extends StorageClientError {
artifactId;
uri;
constructor(args) {
super({
message: `Artifact ${args.artifactId} is pointer-mode; fetch the URI directly (the server does not proxy pointer content)`,
errorCode: "pointer_content_not_managed",
status: 409,
bodyText: args.bodyText
});
this.name = "PointerContentNotManagedError";
this.artifactId = args.artifactId;
this.uri = args.uri;
}
};
var FilecoinDirectStorageNotSupportedError = class extends StorageClientError {
constructor(args) {
super({
message: "Direct Filecoin artifact uploads are not supported in this version. Use document ingestion or pointer mode.",
errorCode: "filecoin_direct_storage_not_yet_supported",
status: 501,
bodyText: args.bodyText
});
this.name = "FilecoinDirectStorageNotSupportedError";
}
};
// src/storage/client.ts
var METADATA_HEADER = "X-AtomicMemory-Metadata";
var ConcreteStorageClient = class {
apiUrl;
apiKey;
userId;
fetchImpl;
constructor(config) {
if (!config.apiUrl) throw new Error("StorageClient: apiUrl is required");
if (!config.apiKey) throw new Error("StorageClient: apiKey is required");
if (!config.userId) throw new Error("StorageClient: userId is required");
this.apiUrl = config.apiUrl.replace(/\/+$/, "");
this.apiKey = config.apiKey;
this.userId = config.userId;
this.fetchImpl = config.fetch ?? fetch;
}
async capabilities() {
const res = await this.request("GET", "/v1/storage/capabilities");
return await res.json();
}
async put(input) {
if (input.mode === "pointer") return this.putPointer(input);
return this.putManaged(input);
}
async get(ref) {
const id = this.requireArtifactId(ref);
const res = await this.request("GET", `/v1/storage/artifacts/${id}`, {}, id);
return mapStoredArtifact(await res.json());
}
async getContent(ref) {
const id = this.requireArtifactId(ref);
return this.request("GET", `/v1/storage/artifacts/${id}/content`, {}, id);
}
async head(ref) {
const id = this.requireArtifactId(ref);
const res = await this.request("HEAD", `/v1/storage/artifacts/${id}`, {}, id);
return mapHeadHeaders(res.headers, id);
}
async delete(ref, options) {
const id = this.requireArtifactId(ref);
const query = options?.policy ? `?policy=${encodeURIComponent(options.policy)}` : "";
const res = await this.request("DELETE", `/v1/storage/artifacts/${id}${query}`, {}, id);
return mapDeleteResult(await res.json());
}
async verify(ref, _options) {
const id = this.requireArtifactId(ref);
const res = await this.request("POST", `/v1/storage/artifacts/${id}/verify`, {}, id);
return mapVerifyResult(await res.json());
}
async putPointer(input) {
const body = {
mode: "pointer",
uri: input.uri,
content_type: input.contentType,
...input.sizeBytes !== void 0 ? { size_bytes: input.sizeBytes } : {},
...input.contentHash !== void 0 ? { content_hash: input.contentHash } : {},
...input.metadata !== void 0 ? { metadata: input.metadata } : {}
};
const res = await this.request("POST", "/v1/storage/artifacts", {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
return mapStoredArtifact(await res.json());
}
async putManaged(input) {
const view = coerceManagedBody(input.body);
const params = new URLSearchParams({ mode: "managed" });
if (input.discloseContentHash === true) params.set("disclose_content_hash", "true");
const headers = {
"Content-Type": input.contentType,
"Content-Length": String(view.byteLength)
};
if (input.metadata !== void 0) {
headers[METADATA_HEADER] = encodeMetadataHeader(input.metadata);
}
const res = await this.request(
"POST",
`/v1/storage/artifacts?${params.toString()}`,
// Cast: Node's fetch accepts Uint8Array as BodyInit, but the
// shared lib.dom type predates that. Sending the view directly
// is intentional — see the comment above coerceManagedBody.
{ headers, body: view }
);
return mapStoredArtifact(await res.json());
}
/**
* Send a request to the storage API and map non-2xx responses to
* typed errors. Callers receive the raw `Response` on success and
* read the body themselves so streaming reads (e.g. getContent)
* can stay zero-copy.
*
* Auth contract: owner identity travels on the
* `X-AtomicMemory-User-Id` request header alongside the
* deployment-wide `Authorization: Bearer <apiKey>`. The legacy
* `?user_id=` URL parameter is NEVER serialized — the server's
* auth middleware rejects it with 400 `legacy_user_id_unsupported`.
*
* Transport-level fetch failures (DNS, ECONNREFUSED, AbortError,
* a misconfigured fetch impl that throws synchronously) are
* wrapped as `StorageClientError({errorCode:'network_error',
* status:0})` so callers can branch on a stable error contract
* instead of catching arbitrary `TypeError`s.
*
* `artifactId`, when supplied, threads into the error mapper so
* `ArtifactNotFoundError` / `ArtifactInUseError` /
* `PointerContentNotManagedError` carry the id the caller already
* knows. The capabilities route omits it (no artifact context).
*/
async request(method, path, init = {}, artifactId) {
const url = `${this.apiUrl}${path}`;
let res;
try {
res = await this.fetchImpl(url, {
method,
headers: {
Authorization: `Bearer ${this.apiKey}`,
"X-AtomicMemory-User-Id": this.userId,
...init.headers ?? {}
},
body: init.body
});
} catch (cause) {
throw new StorageClientError({
message: `Network error while calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
errorCode: "network_error",
status: 0,
bodyText: ""
});
}
if (res.ok) return res;
await throwForResponse(res, artifactId);
throw new StorageClientError({
message: `unexpected non-ok response (${res.status})`,
errorCode: "unexpected_response",
status: res.status,
bodyText: ""
});
}
requireArtifactId(ref) {
if (!ref.artifactId) {
throw new StorageClientError({
message: "ArtifactRef.artifactId is required for this operation in v1",
errorCode: "missing_artifact_id",
status: 0,
bodyText: ""
});
}
return ref.artifactId;
}
};
var STORAGE_MODES = ["pointer", "managed"];
var STORAGE_STATUSES = [
"stored",
"pending",
"available",
"unavailable",
"deleting",
"deleted",
"delete_failed",
"failed"
];
var CONTENT_ENCODINGS = ["identity", "aes_gcm"];
function parseSize(value) {
if (value === null) return null;
const n = Number(value);
if (!Number.isFinite(n) || n < 0) return null;
return n;
}
function mapHeadHeaders(headers, fallbackId) {
const modeRaw = headers.get("x-atomicmemory-storage-mode");
const statusRaw = headers.get("x-atomicmemory-storage-status");
if (modeRaw === null || !STORAGE_MODES.includes(modeRaw)) {
throw new StorageClientError({
message: `head(): server returned an unrecognized x-atomicmemory-storage-mode value ('${modeRaw ?? "<missing>"}'). Expected one of: ${STORAGE_MODES.join(", ")}.`,
errorCode: "invalid_head_response",
status: 200,
bodyText: ""
});
}
if (statusRaw === null || !STORAGE_STATUSES.includes(statusRaw)) {
throw new StorageClientError({
message: `head(): server returned an unrecognized x-atomicmemory-storage-status value ('${statusRaw ?? "<missing>"}'). Expected one of: ${STORAGE_STATUSES.join(", ")}.`,
errorCode: "invalid_head_response",
status: 200,
bodyText: ""
});
}
return {
artifactId: headers.get("x-atomicmemory-artifact-id") ?? fallbackId,
provider: headers.get("x-atomicmemory-provider") ?? "",
mode: modeRaw,
status: statusRaw,
sizeBytes: parseSize(headers.get("content-length")),
contentType: headers.get("content-type")
};
}
function coerceManagedBody(body) {
if (Buffer.isBuffer(body)) {
return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
}
if (body instanceof Uint8Array) return body;
if (body instanceof ArrayBuffer) return new Uint8Array(body);
if (typeof Blob !== "undefined" && body instanceof Blob) {
throw new StorageClientError({
message: "StorageClient.put: Blob input must be converted to Buffer / Uint8Array / ArrayBuffer before calling put(). Use `new Uint8Array(await blob.arrayBuffer())`.",
errorCode: "unsupported_body_type",
status: 0,
bodyText: ""
});
}
throw new StorageClientError({
message: "StorageClient.put: only Buffer / Uint8Array / ArrayBuffer are accepted in v1. Streaming body uploads land in the Streaming + Resumable Uploads PR.",
errorCode: "streaming_body_not_supported",
status: 0,
bodyText: ""
});
}
function encodeMetadataHeader(metadata) {
return Buffer.from(JSON.stringify(metadata), "utf8").toString("base64");
}
function mapStoredArtifact(raw) {
const artifactId = requireWireString(raw, "artifact_id");
const provider = requireWireString(raw, "provider");
const mode = requireWireEnum(raw, "mode", STORAGE_MODES);
const status = requireWireEnum(raw, "status", STORAGE_STATUSES);
const contentEncoding = requireWireEnum(
raw,
"content_encoding",
CONTENT_ENCODINGS
);
const createdAt = requireWireString(raw, "created_at");
const updatedAt = requireWireString(raw, "updated_at");
const out = {
artifactId,
provider,
mode,
uri: typeof raw.uri === "string" ? raw.uri : null,
status,
sizeBytes: typeof raw.size_bytes === "number" ? raw.size_bytes : null,
contentType: typeof raw.content_type === "string" ? raw.content_type : null,
contentEncoding,
identifiers: raw.identifiers ?? {},
lifecycle: raw.lifecycle ?? {},
metadata: raw.metadata ?? {},
createdAt,
updatedAt
};
if (typeof raw.content_hash === "string") out.contentHash = raw.content_hash;
if (raw.provider_details && typeof raw.provider_details === "object") {
out.providerDetails = raw.provider_details;
}
if (raw.replication && typeof raw.replication === "object") {
out.replication = raw.replication;
}
if (raw.verification && typeof raw.verification === "object") {
out.verification = raw.verification;
}
if (raw.retrieval && typeof raw.retrieval === "object") {
out.retrieval = raw.retrieval;
}
return out;
}
function requireWireString(raw, field) {
const value = raw[field];
if (typeof value !== "string" || value.length === 0) {
throw new StorageClientError({
message: `mapStoredArtifact: server response is missing required \`${field}\` (or it is not a non-empty string). The storage API contract requires it.`,
errorCode: "invalid_storage_response",
status: 200,
bodyText: ""
});
}
return value;
}
function requireWireEnum(raw, field, allowed) {
const value = raw[field];
if (typeof value !== "string" || !allowed.includes(value)) {
throw new StorageClientError({
message: `mapStoredArtifact: server response field \`${field}\` is not in the SDK's closed enum. Got '${String(value ?? "<missing>")}', expected one of: ${allowed.join(", ")}.`,
errorCode: "invalid_storage_response",
status: 200,
bodyText: ""
});
}
return value;
}
function mapDeleteResult(raw) {
const artifactId = requireWireString(raw, "artifact_id");
const status = requireWireEnum(raw, "status", STORAGE_STATUSES);
const out = { artifactId, status };
if (Array.isArray(raw.cascaded_document_ids)) {
out.cascadedDocumentIds = raw.cascaded_document_ids.map(String);
}
return out;
}
function mapVerifyResult(raw) {
const kind = raw.kind;
if (kind === "verified") {
return { kind: "verified", details: raw.details ?? {} };
}
if (kind === "failed") {
return { kind: "failed", reason: String(raw.reason ?? "unknown failure") };
}
return { kind: "unsupported", reason: String(raw.reason ?? "unsupported") };
}
async function throwForResponse(res, artifactId) {
const bodyText = await res.text();
const envelope = parseEnvelope(bodyText);
const code = envelope.error_code;
const message = envelope.error ?? `request failed with status ${res.status}`;
const id = artifactId ?? "";
if (code === "artifact_in_use") {
throw new ArtifactInUseError({
artifactId: id,
referencedByDocumentCount: envelope.referenced_by_document_count ?? 0,
bodyText
});
}
if (code === "pointer_content_not_managed") {
throw new PointerContentNotManagedError({
artifactId: id,
uri: envelope.uri ?? "",
bodyText
});
}
if (code === "filecoin_direct_storage_not_yet_supported") {
throw new FilecoinDirectStorageNotSupportedError({ bodyText });
}
if (code === "artifact_not_found" || res.status === 404) {
throw new ArtifactNotFoundError({ artifactId: id, bodyText });
}
if (code === "unsupported_capability") {
throw new UnsupportedCapabilityError({
capability: "unknown",
message,
bodyText
});
}
throw new StorageClientError({
message,
errorCode: code ?? `http_${res.status}`,
status: res.status,
bodyText
});
}
function parseEnvelope(bodyText) {
if (bodyText.length === 0) return {};
try {
return JSON.parse(bodyText);
} catch {
return {};
}
}
export { ArtifactInUseError, ArtifactNotFoundError, ConcreteStorageClient, FilecoinDirectStorageNotSupportedError, PointerContentNotManagedError, StorageClientError, UnsupportedCapabilityError };
//# sourceMappingURL=chunk-OFIOAOM3.js.map
//# sourceMappingURL=chunk-OFIOAOM3.js.map
{"version":3,"sources":["../src/storage/errors.ts","../src/storage/client.ts"],"names":[],"mappings":";AAkBO,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EACnC,SAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACT,YAAY,IAAA,EAKT;AACD,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AACZ,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AAAA,EACvB;AACF;AAMO,IAAM,0BAAA,GAAN,cAAyC,kBAAA,CAAmB;AAAA,EACxD,UAAA;AAAA,EACT,YAAY,IAAA,EAIT;AACD,IAAA,KAAA,CAAM;AAAA,MACJ,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,SAAA,EAAW,wBAAA;AAAA,MACX,MAAA,EAAQ,GAAA;AAAA,MACR,UAAU,IAAA,CAAK;AAAA,KAChB,CAAA;AACD,IAAA,IAAA,CAAK,IAAA,GAAO,4BAAA;AACZ,IAAA,IAAA,CAAK,aAAa,IAAA,CAAK,UAAA;AAAA,EACzB;AACF;AAGO,IAAM,qBAAA,GAAN,cAAoC,kBAAA,CAAmB;AAAA,EACnD,UAAA;AAAA,EACT,YAAY,IAAA,EAAgD;AAC1D,IAAA,KAAA,CAAM;AAAA,MACJ,OAAA,EAAS,CAAA,iBAAA,EAAoB,IAAA,CAAK,UAAU,CAAA,UAAA,CAAA;AAAA,MAC5C,SAAA,EAAW,oBAAA;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,IAAI,sCAAA,CAAuC,EAAE,QAAA,EAAU,CAAA;AAAA,EAC/D;AACA,EAAA,IAAI,IAAA,KAAS,oBAAA,IAAwB,GAAA,CAAI,MAAA,KAAW,GAAA,EAAK;AACvD,IAAA,MAAM,IAAI,qBAAA,CAAsB,EAAE,UAAA,EAAY,EAAA,EAAI,UAAU,CAAA;AAAA,EAC9D;AACA,EAAA,IAAI,SAAS,wBAAA,EAA0B;AACrC,IAAA,MAAM,IAAI,0BAAA,CAA2B;AAAA,MACnC,UAAA,EAAY,SAAA;AAAA,MACZ,OAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AACA,EAAA,MAAM,IAAI,kBAAA,CAAmB;AAAA,IAC3B,OAAA;AAAA,IACA,SAAA,EAAW,IAAA,IAAQ,CAAA,KAAA,EAAQ,GAAA,CAAI,MAAM,CAAA,CAAA;AAAA,IACrC,QAAQ,GAAA,CAAI,MAAA;AAAA,IACZ;AAAA,GACD,CAAA;AACH;AAEA,SAAS,cAAc,QAAA,EAAqC;AAC1D,EAAA,IAAI,QAAA,CAAS,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AACnC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,MAAM,QAAQ,CAAA;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF","file":"chunk-OFIOAOM3.js","sourcesContent":["/**\n * @file Artifact-storage error classes.\n *\n * Instanceof-checkable error classes the SDK throws from\n * `client.storage.*` methods. v1 exports the class shapes only\n * — no message formatting magic.\n *\n * Why classes (not enums): callers can `catch (err)\n * { if (err instanceof ArtifactInUseError) { ... } }` without\n * pattern-matching on `error_code` strings, and bundled stack\n * traces survive code minification.\n */\n\n/**\n * Base class for everything `client.storage.*` throws when the\n * server returns a typed error envelope. `errorCode` mirrors the\n * server's `error_code` field — opaque, snake_case, stable.\n */\nexport class StorageClientError extends Error {\n readonly errorCode: string;\n readonly status: number;\n readonly bodyText: string;\n constructor(args: {\n message: string;\n errorCode: string;\n status: number;\n bodyText: string;\n }) {\n super(args.message);\n this.name = 'StorageClientError';\n this.errorCode = args.errorCode;\n this.status = args.status;\n this.bodyText = args.bodyText;\n }\n}\n\n/**\n * Thrown when a capability the call assumes (range read, bundles,\n * `hash_verify` mode) isn't supported by the active backend.\n */\nexport class UnsupportedCapabilityError extends StorageClientError {\n readonly capability: string;\n constructor(args: {\n capability: string;\n message: string;\n bodyText: string;\n }) {\n super({\n message: args.message,\n errorCode: 'unsupported_capability',\n status: 400,\n bodyText: args.bodyText,\n });\n this.name = 'UnsupportedCapabilityError';\n this.capability = args.capability;\n }\n}\n\n/** Thrown when `get` / `head` / `delete` / `verify` cannot find the artifact. */\nexport class ArtifactNotFoundError extends StorageClientError {\n readonly artifactId: string;\n constructor(args: { artifactId: string; bodyText: string }) {\n super({\n message: `Storage artifact ${args.artifactId} not found`,\n errorCode: 'artifact_not_found',\n status: 404,\n bodyText: args.bodyText,\n });\n this.name = 'ArtifactNotFoundError';\n this.artifactId = args.artifactId;\n }\n}\n\n/**\n * Thrown when a default delete hits a referenced artifact. Server\n * returns 409 with `referenced_by_document_count`; callers can use\n * `?policy=with_documents` to cascade.\n */\nexport class ArtifactInUseError extends StorageClientError {\n readonly artifactId: string;\n readonly referencedByDocumentCount: number;\n constructor(args: {\n artifactId: string;\n referencedByDocumentCount: number;\n bodyText: string;\n }) {\n super({\n message:\n `Storage artifact ${args.artifactId} is referenced by ` +\n `${args.referencedByDocumentCount} document(s); pass ` +\n `'policy: \\\"with_documents\\\"' to cascade`,\n errorCode: 'artifact_in_use',\n status: 409,\n bodyText: args.bodyText,\n });\n this.name = 'ArtifactInUseError';\n this.artifactId = args.artifactId;\n this.referencedByDocumentCount = args.referencedByDocumentCount;\n }\n}\n\n/**\n * Thrown when `getContent` targets a pointer-mode artifact. v1\n * pointers are metadata-only — the server NEVER proxies external\n * bytes. Caller must fetch the URI directly.\n */\nexport class PointerContentNotManagedError extends StorageClientError {\n readonly artifactId: string;\n readonly uri: string;\n constructor(args: { artifactId: string; uri: string; bodyText: string }) {\n super({\n message:\n `Artifact ${args.artifactId} is pointer-mode; fetch the URI ` +\n `directly (the server does not proxy pointer content)`,\n errorCode: 'pointer_content_not_managed',\n status: 409,\n bodyText: args.bodyText,\n });\n this.name = 'PointerContentNotManagedError';\n this.artifactId = args.artifactId;\n this.uri = args.uri;\n }\n}\n\n/**\n * Thrown when a managed put against a Filecoin backend hits the v1\n * carve-out (direct Filecoin uploads require artifact reconciliation,\n * which is not implemented yet). Callers can use document ingestion\n * (`PUT /v1/documents/:id/raw`) or pointer mode against Filecoin.\n */\nexport class FilecoinDirectStorageNotSupportedError extends StorageClientError {\n constructor(args: { bodyText: string }) {\n super({\n message:\n 'Direct Filecoin artifact uploads are not supported in this ' +\n 'version. Use document ingestion or pointer mode.',\n errorCode: 'filecoin_direct_storage_not_yet_supported',\n status: 501,\n bodyText: args.bodyText,\n });\n this.name = 'FilecoinDirectStorageNotSupportedError';\n }\n}\n","/**\n * @file Concrete `StorageClient` implementation.\n *\n * Wraps `fetch` to call the direct storage API\n * (`/v1/storage/artifacts/*`). The SDK is server-side only —\n * `Authorization: Bearer <apiKey>` is sent from a trusted process;\n * browser callers must proxy through a server they control.\n *\n * Managed-mode bodies are restricted to known-length values\n * (`Buffer | Uint8Array | ArrayBuffer`) so the client can compute\n * `Content-Length` before sending — the server requires it. Streams\n * (`ReadableStream`, Node `Readable`) are explicitly rejected with\n * `streaming_body_not_supported`; `Blob` is rejected with\n * `unsupported_body_type` so the silent buffering needed to compute\n * `Content-Length` stays visible at the call site (convert with\n * `new Uint8Array(await blob.arrayBuffer())` first). Streaming +\n * resumable uploads land in a follow-up PR.\n *\n * Wire mapping: core emits snake_case (`artifact_id`,\n * `cascaded_document_ids`); the SDK's public types use camelCase for\n * the top-level handles (`artifactId`, `cascadedDocumentIds`). The\n * client is the single seam that translates.\n */\n\nimport {\n ArtifactInUseError,\n ArtifactNotFoundError,\n FilecoinDirectStorageNotSupportedError,\n PointerContentNotManagedError,\n StorageClientError,\n UnsupportedCapabilityError,\n} from './errors.js';\nimport type { StorageClient } from './interfaces.js';\nimport type {\n ArtifactBody,\n ArtifactHead,\n ArtifactRef,\n DeleteArtifactOptions,\n DeleteArtifactResult,\n PutArtifactInput,\n PutManagedInput,\n StorageArtifactStatus,\n StorageCapabilities,\n StorageLifecycle,\n StoredArtifact,\n VerificationResult,\n VerifyArtifactOptions,\n} from './types.js';\n\n/** Caller-supplied configuration for the concrete client. */\nexport interface StorageClientConfig {\n apiUrl: string;\n apiKey: string;\n /** Optional fetch override — defaults to the Node global. */\n fetch?: typeof fetch;\n /** Owner scope for the caller. Sent as `X-AtomicMemory-User-Id`\n * on every storage request. The legacy `?user_id=` URL parameter\n * is not used — the server rejects it with 400\n * `legacy_user_id_unsupported`. */\n userId: string;\n}\n\nconst METADATA_HEADER = 'X-AtomicMemory-Metadata';\n\n/** Wire-shape JSON envelope the core route layer emits on errors. */\ninterface CoreErrorEnvelope {\n error_code?: string;\n error?: string;\n uri?: string;\n referenced_by_document_count?: number;\n allowed_schemes?: ReadonlyArray<string>;\n}\n\nexport class ConcreteStorageClient implements StorageClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly userId: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: StorageClientConfig) {\n if (!config.apiUrl) throw new Error('StorageClient: apiUrl is required');\n if (!config.apiKey) throw new Error('StorageClient: apiKey is required');\n if (!config.userId) throw new Error('StorageClient: userId is required');\n this.apiUrl = config.apiUrl.replace(/\\/+$/, '');\n this.apiKey = config.apiKey;\n this.userId = config.userId;\n this.fetchImpl = config.fetch ?? fetch;\n }\n\n async capabilities(): Promise<StorageCapabilities> {\n const res = await this.request('GET', '/v1/storage/capabilities');\n return (await res.json()) as StorageCapabilities;\n }\n\n async put(input: PutArtifactInput): Promise<StoredArtifact> {\n if (input.mode === 'pointer') return this.putPointer(input);\n return this.putManaged(input);\n }\n\n async get(ref: ArtifactRef): Promise<StoredArtifact> {\n const id = this.requireArtifactId(ref);\n const res = await this.request('GET', `/v1/storage/artifacts/${id}`, {}, id);\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n async getContent(ref: ArtifactRef): Promise<ArtifactBody> {\n const id = this.requireArtifactId(ref);\n return this.request('GET', `/v1/storage/artifacts/${id}/content`, {}, id);\n }\n\n async head(ref: ArtifactRef): Promise<ArtifactHead> {\n const id = this.requireArtifactId(ref);\n const res = await this.request('HEAD', `/v1/storage/artifacts/${id}`, {}, id);\n return mapHeadHeaders(res.headers, id);\n }\n\n async delete(\n ref: ArtifactRef,\n options?: DeleteArtifactOptions,\n ): Promise<DeleteArtifactResult> {\n const id = this.requireArtifactId(ref);\n const query = options?.policy ? `?policy=${encodeURIComponent(options.policy)}` : '';\n const res = await this.request('DELETE', `/v1/storage/artifacts/${id}${query}`, {}, id);\n return mapDeleteResult((await res.json()) as Record<string, unknown>);\n }\n\n async verify(\n ref: ArtifactRef,\n _options?: VerifyArtifactOptions,\n ): Promise<VerificationResult> {\n // `_options` is reserved for future verification depth choices;\n // the server ignores it in v1, so we do not serialize it on\n // the request.\n const id = this.requireArtifactId(ref);\n const res = await this.request('POST', `/v1/storage/artifacts/${id}/verify`, {}, id);\n return mapVerifyResult((await res.json()) as Record<string, unknown>);\n }\n\n private async putPointer(input: Extract<PutArtifactInput, { mode: 'pointer' }>): Promise<StoredArtifact> {\n const body = {\n mode: 'pointer' as const,\n uri: input.uri,\n content_type: input.contentType,\n ...(input.sizeBytes !== undefined ? { size_bytes: input.sizeBytes } : {}),\n ...(input.contentHash !== undefined ? { content_hash: input.contentHash } : {}),\n ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),\n };\n const res = await this.request('POST', '/v1/storage/artifacts', {\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(body),\n });\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n private async putManaged(input: PutManagedInput): Promise<StoredArtifact> {\n // `view` is a Uint8Array narrowed to exactly the caller's bytes —\n // `Buffer` and Uint8Array sub-views share a backing ArrayBuffer\n // with potentially much larger contents, so we MUST send the view\n // itself (or an exact ArrayBuffer slice). Sending `view.buffer`\n // would leak adjacent bytes and produce a body whose actual size\n // disagrees with `Content-Length`.\n const view = coerceManagedBody(input.body);\n const params = new URLSearchParams({ mode: 'managed' });\n if (input.discloseContentHash === true) params.set('disclose_content_hash', 'true');\n const headers: Record<string, string> = {\n 'Content-Type': input.contentType,\n 'Content-Length': String(view.byteLength),\n };\n if (input.metadata !== undefined) {\n headers[METADATA_HEADER] = encodeMetadataHeader(input.metadata);\n }\n const res = await this.request(\n 'POST',\n `/v1/storage/artifacts?${params.toString()}`,\n // Cast: Node's fetch accepts Uint8Array as BodyInit, but the\n // shared lib.dom type predates that. Sending the view directly\n // is intentional — see the comment above coerceManagedBody.\n { headers, body: view as unknown as BodyInit },\n );\n return mapStoredArtifact((await res.json()) as Record<string, unknown>);\n }\n\n /**\n * Send a request to the storage API and map non-2xx responses to\n * typed errors. Callers receive the raw `Response` on success and\n * read the body themselves so streaming reads (e.g. getContent)\n * can stay zero-copy.\n *\n * Auth contract: owner identity travels on the\n * `X-AtomicMemory-User-Id` request header alongside the\n * deployment-wide `Authorization: Bearer <apiKey>`. The legacy\n * `?user_id=` URL parameter is NEVER serialized — the server's\n * auth middleware rejects it with 400 `legacy_user_id_unsupported`.\n *\n * Transport-level fetch failures (DNS, ECONNREFUSED, AbortError,\n * a misconfigured fetch impl that throws synchronously) are\n * wrapped as `StorageClientError({errorCode:'network_error',\n * status:0})` so callers can branch on a stable error contract\n * instead of catching arbitrary `TypeError`s.\n *\n * `artifactId`, when supplied, threads into the error mapper so\n * `ArtifactNotFoundError` / `ArtifactInUseError` /\n * `PointerContentNotManagedError` carry the id the caller already\n * knows. The capabilities route omits it (no artifact context).\n */\n private async request(\n method: string,\n path: string,\n init: { headers?: Record<string, string>; body?: BodyInit } = {},\n artifactId?: string,\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: {\n Authorization: `Bearer ${this.apiKey}`,\n 'X-AtomicMemory-User-Id': this.userId,\n ...(init.headers ?? {}),\n },\n body: init.body,\n });\n } catch (cause) {\n throw new StorageClientError({\n message:\n `Network error while calling ${method} ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,\n errorCode: 'network_error',\n status: 0,\n bodyText: '',\n });\n }\n if (res.ok) return res;\n await throwForResponse(res, artifactId);\n // Unreachable — throwForResponse always throws on non-ok.\n throw new StorageClientError({\n message: `unexpected non-ok response (${res.status})`,\n errorCode: 'unexpected_response',\n status: res.status,\n bodyText: '',\n });\n }\n\n private requireArtifactId(ref: ArtifactRef): string {\n if (!ref.artifactId) {\n throw new StorageClientError({\n message: 'ArtifactRef.artifactId is required for this operation in v1',\n errorCode: 'missing_artifact_id',\n status: 0,\n bodyText: '',\n });\n }\n return ref.artifactId;\n }\n}\n\n/** Closed enums the SDK consumes from HEAD response headers + JSON bodies. */\nconst STORAGE_MODES = ['pointer', 'managed'] as const;\nconst STORAGE_STATUSES: ReadonlyArray<StorageArtifactStatus> = [\n 'stored', 'pending', 'available', 'unavailable',\n 'deleting', 'deleted', 'delete_failed', 'failed',\n];\nconst CONTENT_ENCODINGS = ['identity', 'aes_gcm'] as const;\n\nfunction parseSize(value: string | null): number | null {\n if (value === null) return null;\n const n = Number(value);\n if (!Number.isFinite(n) || n < 0) return null;\n return n;\n}\n\n/**\n * Project HEAD response headers into an `ArtifactHead`. Validates\n * mode + status against the SDK's closed enums; throws a typed\n * `StorageClientError({errorCode:'invalid_head_response'})` if the\n * server sends a value the SDK doesn't model. The previous shape\n * cast arbitrary header strings to the enum types, which silently\n * accepted unknown values and propagated them into user code.\n */\nfunction mapHeadHeaders(headers: Headers, fallbackId: string): ArtifactHead {\n const modeRaw = headers.get('x-atomicmemory-storage-mode');\n const statusRaw = headers.get('x-atomicmemory-storage-status');\n if (modeRaw === null || !(STORAGE_MODES as ReadonlyArray<string>).includes(modeRaw)) {\n throw new StorageClientError({\n message:\n `head(): server returned an unrecognized x-atomicmemory-storage-mode value ` +\n `('${modeRaw ?? '<missing>'}'). Expected one of: ${STORAGE_MODES.join(', ')}.`,\n errorCode: 'invalid_head_response',\n status: 200,\n bodyText: '',\n });\n }\n if (statusRaw === null || !(STORAGE_STATUSES as ReadonlyArray<string>).includes(statusRaw)) {\n throw new StorageClientError({\n message:\n `head(): server returned an unrecognized x-atomicmemory-storage-status value ` +\n `('${statusRaw ?? '<missing>'}'). Expected one of: ${STORAGE_STATUSES.join(', ')}.`,\n errorCode: 'invalid_head_response',\n status: 200,\n bodyText: '',\n });\n }\n return {\n artifactId: headers.get('x-atomicmemory-artifact-id') ?? fallbackId,\n provider: headers.get('x-atomicmemory-provider') ?? '',\n mode: modeRaw as 'pointer' | 'managed',\n status: statusRaw as StorageArtifactStatus,\n sizeBytes: parseSize(headers.get('content-length')),\n contentType: headers.get('content-type'),\n };\n}\n\n/**\n * Narrow a caller-supplied body to a `Uint8Array` view that covers\n * exactly the caller's bytes. Buffer / Uint8Array sub-views keep\n * their `byteOffset` + `byteLength` here so the request layer never\n * sends adjacent bytes from the backing ArrayBuffer.\n *\n * Parameter is `unknown` (not the static `PutManagedInput['body']`\n * type) so the runtime checks guard untyped JS callers too — TS\n * already removed Blob and stream types from the public input, but\n * a JS caller could still hand us a Blob or a stream object.\n */\nfunction coerceManagedBody(body: unknown): Uint8Array {\n if (Buffer.isBuffer(body)) {\n return new Uint8Array(body.buffer, body.byteOffset, body.byteLength);\n }\n if (body instanceof Uint8Array) return body;\n if (body instanceof ArrayBuffer) return new Uint8Array(body);\n if (typeof Blob !== 'undefined' && body instanceof Blob) {\n // Blob is async-coerce only via arrayBuffer(); reject here and\n // let callers convert deliberately so the client never silently\n // buffers the entire Blob.\n throw new StorageClientError({\n message:\n 'StorageClient.put: Blob input must be converted to Buffer / Uint8Array / ArrayBuffer ' +\n 'before calling put(). Use `new Uint8Array(await blob.arrayBuffer())`.',\n errorCode: 'unsupported_body_type',\n status: 0,\n bodyText: '',\n });\n }\n // Stream / Readable / unknown — explicitly rejected. Streaming\n // body uploads land in the Streaming + Resumable Uploads PR.\n throw new StorageClientError({\n message:\n 'StorageClient.put: only Buffer / Uint8Array / ArrayBuffer are accepted in v1. ' +\n 'Streaming body uploads land in the Streaming + Resumable Uploads PR.',\n errorCode: 'streaming_body_not_supported',\n status: 0,\n bodyText: '',\n });\n}\n\nfunction encodeMetadataHeader(metadata: Record<string, string | number | boolean>): string {\n return Buffer.from(JSON.stringify(metadata), 'utf8').toString('base64');\n}\n\n/**\n * Translate the snake_case wire response into the camelCase SDK\n * shape via an EXPLICIT named-key projection. Wire-only fields\n * (`stored_hash`, `delete_attempt_id`, etc.) the server formatter\n * already redacts; this layer drops anything not in the allowlist\n * even if a future server regression slipped a field through.\n *\n * Closed-set validation. `mode`, `status`, and `content_encoding`\n * are each checked against the enum the SDK actually models — an\n * unrecognized server / proxy / version-skew value throws\n * `StorageClientError({errorCode:'invalid_storage_response'})`\n * rather than silently producing a typed SDK object whose enum\n * fields lie about reality. Same discipline as HEAD header\n * validation.\n *\n * Required-field hardening. The wire contract guarantees\n * `artifact_id`, `provider`, `mode`, `status`, `content_encoding`,\n * `created_at`, `updated_at` on every read. Missing or wrong-type\n * values throw rather than defaulting to empty strings. Wire-only\n * `artifact_id` (no `artifactId` alias) — this is the SDK's snake→\n * camel seam, not a polyfill for callers that pre-translated.\n */\nfunction mapStoredArtifact(raw: Record<string, unknown>): StoredArtifact {\n const artifactId = requireWireString(raw, 'artifact_id');\n const provider = requireWireString(raw, 'provider');\n const mode = requireWireEnum(raw, 'mode', STORAGE_MODES) as 'pointer' | 'managed';\n const status = requireWireEnum(raw, 'status', STORAGE_STATUSES) as StorageArtifactStatus;\n const contentEncoding = requireWireEnum(\n raw, 'content_encoding', CONTENT_ENCODINGS,\n ) as 'identity' | 'aes_gcm';\n const createdAt = requireWireString(raw, 'created_at');\n const updatedAt = requireWireString(raw, 'updated_at');\n const out: StoredArtifact = {\n artifactId,\n provider,\n mode,\n uri: typeof raw.uri === 'string' ? raw.uri : null,\n status,\n sizeBytes: typeof raw.size_bytes === 'number' ? raw.size_bytes : null,\n contentType: typeof raw.content_type === 'string' ? raw.content_type : null,\n contentEncoding,\n identifiers: (raw.identifiers as Record<string, string> | undefined) ?? {},\n lifecycle: (raw.lifecycle as StorageLifecycle | undefined) ?? {},\n metadata:\n (raw.metadata as Record<string, string | number | boolean> | undefined) ?? {},\n createdAt,\n updatedAt,\n };\n if (typeof raw.content_hash === 'string') out.contentHash = raw.content_hash;\n if (raw.provider_details && typeof raw.provider_details === 'object') {\n out.providerDetails = raw.provider_details as Record<string, unknown>;\n }\n if (raw.replication && typeof raw.replication === 'object') {\n out.replication = raw.replication as StoredArtifact['replication'];\n }\n if (raw.verification && typeof raw.verification === 'object') {\n out.verification = raw.verification as StoredArtifact['verification'];\n }\n if (raw.retrieval && typeof raw.retrieval === 'object') {\n out.retrieval = raw.retrieval as StoredArtifact['retrieval'];\n }\n return out;\n}\n\nfunction requireWireString(raw: Record<string, unknown>, field: string): string {\n const value = raw[field];\n if (typeof value !== 'string' || value.length === 0) {\n throw new StorageClientError({\n message:\n `mapStoredArtifact: server response is missing required \\`${field}\\` ` +\n '(or it is not a non-empty string). The storage API contract requires it.',\n errorCode: 'invalid_storage_response',\n status: 200,\n bodyText: '',\n });\n }\n return value;\n}\n\nfunction requireWireEnum<T extends string>(\n raw: Record<string, unknown>,\n field: string,\n allowed: ReadonlyArray<T>,\n): T {\n const value = raw[field];\n if (typeof value !== 'string' || !(allowed as ReadonlyArray<string>).includes(value)) {\n throw new StorageClientError({\n message:\n `mapStoredArtifact: server response field \\`${field}\\` is not in the SDK's ` +\n `closed enum. Got '${String(value ?? '<missing>')}', expected one of: ${allowed.join(', ')}.`,\n errorCode: 'invalid_storage_response',\n status: 200,\n bodyText: '',\n });\n }\n return value as T;\n}\n\n/**\n * Translate the snake_case DELETE response envelope into the\n * camelCase SDK shape. Same discipline as `mapStoredArtifact`:\n *\n * - require non-empty snake_case `artifact_id` (no camelCase\n * alias polyfill — the wire is snake_case);\n * - validate `status` against the closed `StorageArtifactStatus`\n * enum;\n * - throw `StorageClientError({errorCode:'invalid_storage_response'})`\n * on missing / wrong-type / out-of-enum values rather than\n * silently producing a typed SDK object whose fields lie.\n */\nfunction mapDeleteResult(raw: Record<string, unknown>): DeleteArtifactResult {\n const artifactId = requireWireString(raw, 'artifact_id');\n const status = requireWireEnum(raw, 'status', STORAGE_STATUSES) as StorageArtifactStatus;\n const out: DeleteArtifactResult = { artifactId, status };\n if (Array.isArray(raw.cascaded_document_ids)) {\n out.cascadedDocumentIds = raw.cascaded_document_ids.map(String);\n }\n return out;\n}\n\nfunction mapVerifyResult(raw: Record<string, unknown>): VerificationResult {\n const kind = raw.kind;\n if (kind === 'verified') {\n return { kind: 'verified', details: (raw.details ?? {}) as Record<string, unknown> };\n }\n if (kind === 'failed') {\n return { kind: 'failed', reason: String(raw.reason ?? 'unknown failure') };\n }\n return { kind: 'unsupported', reason: String(raw.reason ?? 'unsupported') };\n}\n\nasync function throwForResponse(res: Response, artifactId?: string): Promise<never> {\n const bodyText = await res.text();\n const envelope = parseEnvelope(bodyText);\n const code = envelope.error_code;\n const message = envelope.error ?? `request failed with status ${res.status}`;\n const id = artifactId ?? '';\n if (code === 'artifact_in_use') {\n throw new ArtifactInUseError({\n artifactId: id,\n referencedByDocumentCount: envelope.referenced_by_document_count ?? 0,\n bodyText,\n });\n }\n if (code === 'pointer_content_not_managed') {\n throw new PointerContentNotManagedError({\n artifactId: id,\n uri: envelope.uri ?? '',\n bodyText,\n });\n }\n if (code === 'filecoin_direct_storage_not_yet_supported') {\n throw new FilecoinDirectStorageNotSupportedError({ bodyText });\n }\n if (code === 'artifact_not_found' || res.status === 404) {\n throw new ArtifactNotFoundError({ artifactId: id, bodyText });\n }\n if (code === 'unsupported_capability') {\n throw new UnsupportedCapabilityError({\n capability: 'unknown',\n message,\n bodyText,\n });\n }\n throw new StorageClientError({\n message,\n errorCode: code ?? `http_${res.status}`,\n status: res.status,\n bodyText,\n });\n}\n\nfunction parseEnvelope(bodyText: string): CoreErrorEnvelope {\n if (bodyText.length === 0) return {};\n try {\n return JSON.parse(bodyText) as CoreErrorEnvelope;\n } catch {\n return {};\n }\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/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AAA,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