npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@memrail/ami-sdk

v0.1.1

Published

TypeScript SDK for Memrail AMI (Adaptive Memory Intelligence) API

Readme

AMI SDK - TypeScript Client

TypeScript SDK for Memrail AMI (Adaptive Memory Intelligence) API.

Installation

npm install @memrail/ami-sdk

Quick Start

import { AMIClient, state, tag, event } from '@memrail/ami-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 (ami 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
ami emu-pull ./emus/ -w production -p my-project

# Edit emus/emus.jsonl (one EMU per line, JSON format)

# Preview changes with validation
ami emu-plan ./emus/ --validate

# Apply changes with validation
ami emu-apply ./emus/ --yes --validate

Example 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/ami-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/ami-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/ami-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/ami-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
  • fetch API
  • TextEncoder API

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