@memrail/sdk
v0.3.0
Published
TypeScript SDK for Memrail AMI (Adaptive Memory Intelligence) API
Downloads
106
Maintainers
Readme
AMI SDK - TypeScript Client
TypeScript SDK for Memrail AMI (Adaptive Memory Intelligence) API.
Installation
npm install @memrail/sdkQuick Start
import { AMIClient, state, tag, event } from '@memrail/sdk';
// Environment-driven config
const client = new AMIClient(); // Reads AMI_API_KEY, AMI_WORKSPACE, AMI_PROJECT from env
// Build context atoms
const ctx = [
state('user.id', 'U-123'),
tag('segment', 'new'),
event('user.completed.onboarding_step', {
ts: new Date(),
subject_anchor: ['user', 'U-123'],
}),
];
// Invoke AMI decision engine
const resp = await client.decide({ context: ctx });
// Handle selected actions
for (const sel of resp.selected) {
if (sel.action) {
await handleAction(sel.action);
await client.ack({
activationId: sel.activation_id!,
status: 'acknowledged',
});
}
}Features
- ✅ Type-safe atom builders (state, tag, event)
- ✅ Decide with idempotency, dry-run, top-k
- ✅ Event ingestion (single, batch)
- ✅ EMU management via IaC workflow (
memrail emu-plan/apply) - ✅ ACK activations & retrieve traces
- ✅ Production-ready: retries, timeouts, error taxonomy
- ✅ Built with TypeScript for full type safety
- ✅ Works in Node.js and modern browsers
Configuration
The SDK supports multiple configuration methods:
Environment Variables
export AMI_API_KEY="ami_..."
export AMI_ORG="acme-corp"
export AMI_TEAM="client-team"
export AMI_WORKSPACE="production"
export AMI_PROJECT="api-backend"Explicit Configuration
const client = new AMIClient({
apiKey: 'ami_...',
org: 'acme-corp',
team: 'client-team',
workspace: 'production',
project: 'api-backend',
baseUrl: 'https://api.memrail.com', // optional
timeoutMs: 10000, // optional, default 10s
maxRetries: 3, // optional, default 3
});Core API Methods
Decide
Deterministic EMU selection based on context atoms.
const response = await client.decide({
context: [
state('user.id', 'U-123'),
state('user.tier', 'premium'),
tag('intent', 'upgrade'),
],
options: { top_k: 3, dry_run: false },
trace: true,
idempotencyKey: 'unique-request-id', // optional
});
console.log(`Invocation: ${response.invocation_id}`);
for (const item of response.selected) {
console.log(`EMU: ${item.emu_key}, Score: ${item.score}`);
}Event Ingestion
Single Event
const result = await client.emitEvent({
event: event('user.login.success', {
ts: new Date(),
subject_anchor: ['user', 'U-123'],
attributes: { ip: '192.168.1.1' },
}),
});
console.log(`Accepted: ${result.accepted}`);Batch Events
const events = [
event('user.login.success', { ts: new Date() }),
event('user.viewed.dashboard', { ts: new Date() }),
event('user.clicked.button', { ts: new Date() }),
];
const result = await client.emitEvents({ events });
console.log(`Accepted: ${result.accepted} events`);EMU Management (IaC Workflow)
EMUs are managed via the CLI using an Infrastructure-as-Code workflow. Do not use SDK methods for production EMU registration.
# Pull current EMUs from the API
memrail emu-pull ./emus/ -w production -p my-project
# Edit emus/emus.jsonl (one EMU per line, JSON format)
# Preview changes with validation
memrail emu-plan ./emus/ --validate
# Apply changes with validation
memrail emu-apply ./emus/ --yes --validateExample emus.jsonl entry:
{"emu_key":"welcome_premium_users","trigger":"state.user.tier == \"premium\"","action":{"type":"tool_call","tool":{"tool_id":"mailer","version":"1.0.0"},"intent":"SEND_WELCOME","args":{"template":"premium_welcome"}},"policy":{"mode":"auto","priority":7,"cooldown":{"seconds":86400,"gate":"ack"}},"expected_utility":0.9,"confidence":0.95,"state":"shadow"}Commit both emus.jsonl and .emu.lock.jsonl to version control.
Acknowledgment
await client.ack({
activationId: 'act_01H2X3Y4Z5A6B7C8D9E0F1G2H4',
status: 'acknowledged',
code: 'SUCCESS',
message: 'Email sent successfully',
});Trace Retrieval
const trace = await client.getTrace({
traceId: 'trc_01H2X3Y4Z5A6B7C8',
});
console.log(`Candidates: ${trace.candidates.length}`);
console.log(`Selected: ${trace.selected.length}`);Advanced Features
StateObject Builder
For cleaner ergonomics when working with multiple related state atoms:
import { StateObject } from '@memrail/sdk';
const user = new StateObject('user', {
id: 'U-123',
name: 'John Doe',
tier: 'premium',
is_active: true,
});
const atoms = user.toAtoms();
// Returns: [
// state("user.id", "U-123"),
// state("user.name", "John Doe"),
// state("user.tier", "premium"),
// state("user.is_active", true)
// ]Custom Retry Policies
import { HTTPTransport, RetryPolicy } from '@memrail/sdk';
// Access low-level transport for custom retry behavior
// (most users won't need this - the client handles retries automatically)Error Handling
import {
AMIBadRequest,
AMIUnauthorized,
AMINotFound,
AMIRateLimited,
} from '@memrail/sdk';
try {
const response = await client.decide({ context: [...] });
} catch (error) {
if (error instanceof AMIUnauthorized) {
console.error('Invalid API key');
} else if (error instanceof AMINotFound) {
console.error('Resource not found');
} else if (error instanceof AMIRateLimited) {
console.error(`Rate limited. Retry after: ${error.retryAfter}s`);
} else if (error instanceof AMIBadRequest) {
console.error('Bad request:', error.message);
}
}Workspace & Project Management
// List workspaces
const workspaces = await client.listWorkspaces({ limit: 10 });
// Create workspace
const workspace = await client.createWorkspace({
slug: 'production',
name: 'Production Environment',
});
// List projects
const projects = await client.listProjects('production', { limit: 10 });
// Create project
const project = await client.createProject('production', {
slug: 'api-backend',
name: 'API Backend',
});TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import type {
DecideResponse,
SelectedItem,
EventAtom,
StateAtom,
} from '@memrail/sdk';
// Full IDE autocomplete and type checking
const response: DecideResponse = await client.decide({ context: [...] });
const selected: SelectedItem[] = response.selected;Browser Support
The SDK works in modern browsers that support:
- ES2020
fetchAPITextEncoderAPI
For older browsers, you may need polyfills.
License
Proprietary
Support
For issues and questions:
- GitHub: https://github.com/cadenzai/ami-sdk-ts
- Docs: https://docs.memrail.com
