Ledra Memory API
Published @ldgr/memory@0.1.3 supplies encryption, signed service requests, an embedding adapter, local MCP tools, and optional public ledger anchors. It includes receiver profiles, username resolution, original doctor diagnostics and typed errors. Version 0.1.4 is a candidate adding latest-on-restart registration and doctor update checks. Memory operations support ledger ID 0 only.
Ledra Memory is the public product name. Package names, configuration keys, request domains such as ldgr-memory-v1, and existing wire schema identifiers remain unchanged. The published ESM SDK supports Node.js 20.19 or newer and Bun, with built JavaScript and TypeScript declarations at @ldgr/memory and @ldgr/memory/protocol. The bundled ledra-memory executable requires Node.js 20.19 or newer. The shared testnet service is https://memory-testnet.ldgr.ltd. Version 0.1.3 includes the setup helper with username-aware recipients. Candidate 0.1.4 features need publication or the built checkout.
Receiver profiles and usernames
Version 0.1.3 exports MEMORY_TESTNET_PROFILE and resolveMemoryRecipient. The profile defines the testnet ledger, service origin, @testnet-memory username, and pinned Bech32 receiver. It does not define a mainnet Memory deployment.
import { MEMORY_TESTNET_PROFILE, resolveMemoryRecipient } from "@ldgr/memory";
const profile = MEMORY_TESTNET_PROFILE;
const recipient = await resolveMemoryRecipient("@" + profile.recipientUsername, {
ledgerId: profile.ledgerId,
ledgerUrl: profile.ledgerUrl,
expectedAddress: profile.recipientAddress,
});
// Review recipient.username and recipient.address before approving funding.
// Signed transfers still use recipient.address and native asset dng.Username lookups verify the endpoint network, normalized name, unexpired registration, address network, and any expected address. Read-only resolution can target ledger 0 or 1 explicitly; this does not enable mainnet Memory operations. Setup stores the resolved address and checks a configured username again before funding. Unknown, expired, or changed names stop the operation. Names can be transferred and are not proof of identity; automatic redirection is never authorized by a matching label.
MCP initialization and packaged skill
Project-only MCP registration is recommended. Ask the user to choose project-only or user-wide setup when their intent is unclear. Client registration scope controls where the tools are available; each running server still uses one configured owner and Memory space. User-wide registration does not add repository routing or authorize cross-project data access. A global package installation also does not choose the MCP client's registration scope.
Initialization guidance and the packaged skill are available in published version 0.1.1 and later. The setup helper requires version 0.1.2 or a built repository checkout.
The stdio server returns an instructions string in its MCP initialize result. This built-in workflow guidance requires no optional skill. Clients decide whether to honor it; it is not a permission boundary, lifecycle hook, or automatic saving service. It includes the configured project-space label and per-call fee ceiling. The four tools remain memory_remember, memory_recall, memory_get, and memory_balance.
The package ships skills/ledra-memory/SKILL.md and exports the asset at @ldgr/memory/skills/ledra-memory/SKILL.md. Skill-capable clients can use it after manual installation and review; installation or activation grants no saving consent and does not configure MCP, providers, grants, or keys. See the setup guide for paths and consent examples.
Automatic saving is off by default and requires scoped user opt-in in client instructions or session policy. There is no server autoSave configuration field or consent-persistence tool. The service still enforces grants, expiry, and spending budgets.
Create a client
createMemoryClient(options) requires serviceUrl, ledgerId: 0, a canonical testnet owner address, space, an @ldgr/client signer, a 32-byte encryptionKey, and an embed function. An optional fetch implementation can replace transport. The service URL must be an HTTPS origin or loopback HTTP origin without credentials, query, fragment, or a path other than /.
Embedder accepts a text string and returns a promise of { model: string, values: readonly number[] }. createOpenAICompatibleEmbedder({ baseUrl, model, apiKey?, fetch? }) sends selected text to baseUrl + /embeddings. The model is required; there is no default. The endpoint must use HTTPS or loopback HTTP. The configured provider receives text and queries.
The following method examples assume memory is your configured client. Choose only the calls you need; replace funding and delegate placeholders before running owner-only operations. See the setup guide for a complete local file-based example. Fee arguments are canonical nonnegative integer strings of native atomic units. Omitted fee caps default to zero, so ordinarily priced reads and writes need explicit caps. remember defaults metadata to null and its fee object to { maxFeeAtomic: "0" }.
recall(query, limit?, maxFeeAtomic?) defaults to 10 matches and a zero fee cap. get(id, maxFeeAtomic?) defaults its fee cap to zero. list, export, and rebuild accept an optional { cursor?: string, limit?: number } first argument (default {}) and an optional fee-cap string (default zero). prepareRequest and request also default the final fee-cap argument to zero.
// Use your configured client as memory. Run only the operations you need.
const saved = await memory.remember(
"Project facts are reviewed weekly.",
{ kind: "project-convention" },
{ maxFeeAtomic: "42" },
);
const recalled = await memory.recall("When are project facts reviewed?", 10, "21");
const exact = await memory.get(saved.blob.id, "21");
const page = await memory.list({ limit: 50 }, "21");
const balance = await memory.balance();
const plaintext = await memory.decrypt(saved.blob); // Local; no service fee
// Manual OWNER client only. Replace placeholders before running these calls.
const exportedPage = await memory.export({ limit: 50 });
const rebuiltPage = await memory.rebuild({ limit: 50 });
await memory.fund("YOUR_SETTLED_FUNDING_TRANSACTION_HASH");
const delegate = "YOUR_AGENT_TESTNET_ADDRESS";
await memory.grant({
delegate, permissions: ["read", "write"],
expiresAt: Date.now() + 86_400_000, maxSpendAtomic: "1000000",
});
await memory.revoke(delegate); // Deliberately removes the grant just shown
// Low-level access. Persist signed before submitting if recovery matters.
const signed = await memory.prepareRequest("balance", {}, "0");
const result = await memory.submitRequest(signed);
const anotherBalance = await memory.request("balance", {}, "0");remember embeds and locally encrypts text/metadata, returning the envelope as blob plus the service result. recall embeds a query and returns decrypted matches, each with text, metadata, blob, and score. get returns decrypted text/metadata and its blob after checking the requested ID. decrypt(blob) performs local scope, digest, and AES-GCM authentication checks without a service call. List and export return encrypted envelopes.
HTTP endpoints and signed requests
GET /health returns service identity and testnet ledger ID. GET /v1/pricing returns ledgerId, asset: "dng", readFeeAtomic, writeFeeAtomic, paymentRecipient (or null), and paymentsConfigured. Independently verify the payment recipient with the operator before approving a transfer.
All account operations use POST /v1/spaces/:owner/:space with JSON { payload, signature }. The example below shows the shape only: replace address/key/signature placeholders, generate a current timestamp and fresh UUID, and sign the complete canonical payload. It is not a valid pre-signed request.
{
"payload": {
"version": 1,
"domain": "ldgr-memory-v1",
"audience": "https://YOUR_MEMORY_SERVICE",
"ledgerId": 0,
"from": "YOUR_SIGNER_TESTNET_ADDRESS",
"publicKey": "CANONICAL_BASE64URL_PUBLIC_KEY",
"owner": "YOUR_OWNER_TESTNET_ADDRESS",
"space": "my-project",
"operation": "balance",
"timestamp": 1793090000000,
"requestId": "d78f5b58-b64d-4b71-8063-0413f18f882c",
"maxFeeAtomic": "0",
"body": {}
},
"signature": "CANONICAL_BASE64URL_SIGNATURE"
}The signature binds every payload field: version, domain, service origin (audience), ledger, signer address (from), public key, owner, exact space, operation, timestamp, request UUID, fee cap, and body. The URL owner and space must match the payload, and audience must match the receiving origin. No raw signing secret is transmitted.
Sign using the canonical payload implementation in @ldgr/protocol or the SDK; ordinary JSON serialization is not a signing algorithm. Public keys are canonical unpadded base64url encodings of 32-byte Ed25519 keys; signatures are canonical unpadded base64url encodings of 64 bytes. Public key derivation must match from. Owner and signer must be canonical version-0 Bech32 testnet addresses, not legacy hex addresses.
timestamp is an integer Unix time in milliseconds within five minutes of service time. requestId is a lowercase version-4 UUID; consumed IDs are protected against replay. maxFeeAtomic is a decimal integer string with no sign or leading zeroes (except "0"), up to 40 digits. Space labels are 1–64 ASCII letters/digits, underscores, or hyphens, beginning with a letter or digit.
Operations and permissions
| Operation | Body shape | Authority | Result and charging |
|---|---|---|---|
put | { blob } | Owner or write grant | Encrypted envelope; successful new write is billed |
get | { id } | Owner or read grant | One encrypted blob; billed |
list | { cursor?, limit? } | Owner or read grant | Encrypted blobs and optional nextCursor; each page billed |
search | { embedding: { model, vector }, limit? } | Owner or read grant | Matches containing blob and cosine score; billed |
grant | { delegate, permissions, expiresAt, maxSpendAtomic } | Owner only | Create or replace a grant; free |
revoke | { delegate } | Owner only | Remove future grant authority; free |
export | { cursor?, limit? } | Owner only | Encrypted blobs and optional nextCursor; free |
rebuild | { cursor?, limit? } | Owner only | Restored count and optional nextCursor; free |
fund | { transactionHash } | Owner only | Claim verified native payment once; free service operation |
balance | {} | Owner or active grant | Scoped prepaid service credit; free |
Bodies reject unknown fields. permissions is a nonempty distinct subset of ["read", "write"]; expiresAt is an integer future Unix timestamp in milliseconds at most 30 days away. maxSpendAtomic is a cumulative native atomic cap for that grant. Granting an existing delegate replaces the grant and resets its tracked spending; review that new authorization deliberately.
List, export, and rebuild take { cursor?, limit? } and return nextCursor when another page exists. Pass that value into the next request's body.cursor or SDK input object's cursor; it is not a URL query parameter. List/export cursors are memory IDs; rebuild cursors are opaque and must not be interchanged. Default and maximum page size is 50. Search defaults to 10 matches, with a maximum of 20.
Balance is available to an active delegate even with only one of read/write permissions. Grants never convey authority to spend the owner's ledger funds. Only manual owner clients can fund, grant, revoke, export, rebuild, or prepare public anchors.
Encrypted blob format
type MemoryBlob = {
version: 1;
ledgerId: 0;
owner: string;
space: string;
id: string; // Lowercase UUID v4
createdAt: number; // Integer Unix milliseconds
iv: string; // 12 bytes, unpadded base64url
ciphertext: string; // AES-256-GCM ciphertext + authentication tag, base64url
digest: string; // SHA-256 of ciphertext bytes, 64 lowercase hex digits
embedding: {
model: string;
vector: string; // Little-endian float32 bytes, unpadded base64url
};
};The encrypted JSON plaintext contains text and metadata. AES-GCM uses a separate random 32-byte key and a fresh 12-byte IV. Additional authenticated data uses domain ldgr-memory-blob-v1 and binds ledger ID, owner, space, memory ID, creation time, and the full embedding model and vector. Tampering with those fields fails authentication.
The digest hashes ciphertext bytes, not plaintext or the textual base64url representation. A digest checks bytes; AES-GCM provides encryption and authentication. Do not publish plaintext hashes as a substitute: predictable text can be guessed by hashing candidates.
Vectors contain 1–1,024 finite little-endian float32 values and must not be all zero. Encode them with encodeVector. Model labels are 1–128 characters, beginning with a letter, digit, or @, followed by letters, digits, or . _ : / @ -. Every space uses the same model and dimension count. Vectors remain visible to the service.
Billing and payment verification
Successful service responses include asset: "dng", chargedAtomic, balanceAtomic, and scope (owner or delegate). Amounts are decimal integer strings. An owner sees the account's service credit. A delegate also receives grantRemainingAtomic and sees only the smaller of account credit and its remaining grant budget as balanceAtomic.
Illustrative defaults charge 42 atomic units (0.000042 tLEDRA) for a new put, and 21 (0.000021 tLEDRA) for a get, search, or each list page. Owner administration, export, and rebuild are free service operations. Ledra Testnet (tLEDRA) has six decimal places: 1 tLEDRA = 1,000,000 dng. A dng is its smallest indivisible unit. Use configured pricing and integer arithmetic, never floating-point money. Service credit is separate from the ledger balance.
fund accepts a 64-character lowercase hexadecimal transaction hash. The service reads the authoritative testnet transaction and checks its hash, direct-transfer action, owner sender, configured recipient, native wire asset code dng, and positive decimal amount converted to atomic units. One receipt can credit the owner account only once across all spaces, including concurrent claims. A hash string alone is not payment evidence.
Independently operated services need dedicated receiving wallets: receipt deduplication does not span unrelated deployments. There is no automatic wallet debit, refill, refund, or credit-expiry mechanism. Protocol transfer and object-write fees remain separate.
Commit boundaries and retries
A new put first writes an immutable encrypted object. Service credit, grant spending, index entry, and a committed-write receipt then commit together. Success means the service stored and committed the memory; it does not mean a ledger anchor was published. A failed operation does not debit service credit, although a failed put can leave an uncommitted object. Rebuild ignores objects without matching committed receipts.
Service completion is the billing boundary. A read can be charged even if the response is lost after commit or the client later fails to decrypt with a wrong local key. Neither transport ambiguity nor local decryption failure automatically refunds that service charge.
Same memory ID and identical encrypted envelope is put-idempotent and incurs no second write charge. Changed content under that ID conflicts. The request UUID is a separate replay identity: submitting a consumed signed request returns 409 REPLAY. Calling remember again creates a fresh memory ID and ciphertext, so it is not a retry of the original blob.
prepareRequest(operation, body, maxFeeAtomic) returns the signed envelope without sending it. Persist it before calling submitRequest(signed) if crash recovery matters. Exact resubmission can succeed only if that request was not consumed and remains within its clock window. Reconcile ambiguous outcomes rather than automatically creating another paid query. There is no hidden automatic paid-query retry.
Limits and HTTP errors
| Limit | Preview bound |
|---|---|
| Ciphertext | 64 KiB including authentication tag |
| Request body | 128 KiB |
| Indexed memories | 500 per space |
| Embedding | 1–1,024 dimensions; finite and nonzero |
| Search | 1–20 matches |
| List/export/rebuild | 1–50 per page |
| Request clock tolerance | Five minutes, plus replay checks |
| Grant expiry | Future timestamp, at most 30 days away |
Raw HTTP failures return JSON { code, message }. The published 0.1.3 SDK/MCP exposes sanitized errors shaped as {code, message, action, outcome, status?}. Codes are allowlisted; messages and actions are static local guidance without raw service/provider details. Published 0.1.2 retains its generic SDK/MCP errors. Optional status is HTTP status.
Outcomes are not_submitted, rejected, unknown and completed. Never automatically repeat a paid call after an unknown outcome. DECRYPTION_FAILED with completed outcome may mean a service read was charged before local decryption failed; inspect the local key and configuration first. REQUEST_UNCERTAINand INVALID_RESPONSE require outcome reconciliation.
SPACE_CAPACITY means stop writes at 500 memories and discuss a separate approved space. More credit or rebuilding does not expand capacity. A read-only preflight rejects a known-full space before R2 upload; the transactional capacity guard remains. Concurrent writes can both pass preflight and the losing write may still leave an uncommitted R2 object. No quota expansion or garbage collection is added. An identical committed-write retry remains free.
Review prepaid credit for INSUFFICIENT_CREDIT, owner grant budget for GRANT_BUDGET, permissions/expiry/space for FORBIDDEN, pricing and approved cap for FEE_LIMIT, and model/dimensions for EMBEDDING_MISMATCH. Embedding codes EMBEDDING_UNAVAILABLE, EMBEDDING_REJECTEDand EMBEDDING_INVALID require endpoint, credential environment or model checks. Start with published 0.1.3 or newer and doctor --directory ABS_DIRECTORY. Only explicitly approved --probe-embedding sends a provider probe that may incur a charge; default doctor makes no embedding POST. See the setup guidefor independent diagnostics and balance evidence limits.
Candidate 0.1.4 doctor also reports informational checks.updates: currentVersion identifies the executing package, latestVersion is the published npm release, and updateAvailable signals a newer release. Its read-only registry check neither installs nor edits registration; an unavailable registry or a newer release alone does not degrade health. Restart the host MCP server after publication and verify its live initialize version. The latest registration currently resolves 0.1.3 with original doctor; update checks need published 0.1.4 or the built checkout.
| Status | Code | Meaning |
|---|---|---|
| 400 | INVALID_REQUEST, INVALID_PAYMENT | Malformed or mismatched request; payment not found or does not match the required transfer. |
| 401 | INVALID_SIGNATURE, EXPIRED_REQUEST | Signature verification failed or timestamp outside five minutes. |
| 402 | FEE_LIMIT, INSUFFICIENT_CREDIT, GRANT_BUDGET | Per-call cap, service credit, or grant budget cannot cover the operation. |
| 403 | FORBIDDEN, GRANT_CHANGED, ACCOUNT_MISMATCH | No active permission, changed authorization during work, or mismatched account identity. |
| 404 | BLOB_NOT_FOUND, NOT_FOUND | No committed memory for this ID, or unknown HTTP route. |
| 409 | REPLAY, PAYMENT_ALREADY_USED | Signed UUID consumed, or funding transaction already claimed. |
| 409 | EMBEDDING_MISMATCH, SPACE_CAPACITY | Different model/dimensions, or the space's index is full. |
| 409 | BLOB_CONFLICT, STORED_BLOB_CONFLICT | Existing immutable content differs, or stored content does not match identity/committed receipt. |
| 413 | REQUEST_TOO_LARGE | Request exceeds 128 KiB. |
| 503 | PAYMENTS_UNCONFIGURED, INVALID_STORED_BLOB, UNAVAILABLE | Payment setup missing, stored blob exceeds its bound, or service/storage temporarily unavailable. |
Export and index recovery
Use owner-only export across every page to save encrypted envelopes. Keep the content key in a separately protected backup. rebuild reads existing private objects and their vectors, checks committed receipts, and restores index entries in bounded pages. It does not re-embed text, restore deleted objects, recover lost decryption keys, or regenerate grants, service credits, and receipts. Back up authoritative service account state separately.
This preview exposes no memory deletion operation through its API.
Optional owner-approved public anchors
buildMemoryAnchor(blob, { serviceUrl }) produces a small public JSON record with schema: "ldgr-memory-anchor-v1", ledgerId, owner, space, id, ciphertextSha256, r2ObjectKey, and serviceUrl. The wire field r2ObjectKey holds the private object-store locator v1/0/<owner>/<space>/<id>.json; publishing it does not make private ciphertext publicly downloadable.
prepareMemoryAnchor takes an owner signer, testnet ledger API base URL, blob, service origin, optional existing objectId, optional positive integer-string expectedVersion, and optional fetch. It checks the testnet owner, reads the native dng nonce, and signs one existing object_create or object_update. It returns { objectId, path, submission }.
import { prepareMemoryAnchor, submitMemoryAnchor } from "@ldgr/memory";
// ownerSigner, blob, and serviceUrl come from your trusted local owner client.
// Obtain explicit owner approval for this public record and separate ledger fee.
const prepared = await prepareMemoryAnchor({
ownerSigner,
ledgerApiBaseUrl: "https://tst.ldgr.ltd",
serviceUrl,
blob,
// objectId: existingObjectId, expectedVersion: "2", // Optional update
});
// Persist prepared (including its exact signed submission) before sending.
const receipt = await submitMemoryAnchor(prepared, {
ledgerApiBaseUrl: "https://tst.ldgr.ltd",
});
// Preserve the settled receipt.transactionHash for the owner.
// On an ambiguous transport failure, reuse the SAME prepared value.submitMemoryAnchor submits the prepared path and exact signed submission; it does not refresh the nonce or sign a replacement. Preserve the prepared envelope for transport retries and the settled transaction hash as the receipt. Expected-version updates can reject concurrent changes. Preserve canonical signed payloads externally if historical revision verification is needed: current public object rows retain the latest JSON, not every earlier document.
Public anchors reveal owner, space, memory ID, digest, origin, locator, and timing; use opaque identifiers. They supply cryptographic provenance for the published commitment, not proof of factual truth, search completeness, storage availability, or decentralized history. No plaintext, content key, private metadata, or vector is included.