TypeScript SDK

Learn how to install and configure the TraceMem TypeScript SDK to enable decision tracking and traceability within your AI agents and automation systems.

Overview

The @tracemem/ts-sdk package provides a powerful interface to TraceMem's API, enabling you to:

  • Track decisions made by your AI agents or automation scripts
  • Automatically map actions to standardized intents for consistent decision tracking
  • Add context to decisions with safe, sanitized logs
  • Evaluate policies against your decision context
  • Protect sensitive data with automatic secret redaction and sanitization

This SDK is designed for TypeScript and Node.js environments, making it ideal for backend services, CLI tools, and AI agent implementations.

Prerequisites

Before installing the SDK, ensure you have:

  1. Node.js - Version 18.0.0 or higher
  2. A TraceMem account - Sign up at app.tracemem.com
  3. An Agent API key - Generate one from your TraceMem project settings

Installation

Install the SDK using npm:

bash
npm install @tracemem/ts-sdk

Configuration

Basic Configuration

The SDK requires only an API key to get started. You can pass it directly to the constructor:

typescript
import { TraceMemClient } from '@tracemem/ts-sdk';

const client = new TraceMemClient({
  apiKey: process.env.TRACEMEM_API_KEY!,
});

Advanced Configuration

You can customize the client behavior with additional options:

typescript
const client = new TraceMemClient({
  apiKey: process.env.TRACEMEM_API_KEY!,
  mcpUrl: 'https://mcp.tracemem.com',     // Custom MCP URL
  timeoutMs: 30000,                       // Request timeout in ms (default: 30000)
  sanitize: true,                         // Enable/disable data sanitization (default: true)
  defaultActor: 'my-agent',               // Default actor for decisions
  defaultAutomationMode: 'propose',       // Default mode for decisions
});

Recommended Workflow

The SDK provides a fluent API for managing the decision lifecycle. Here's a typical pattern:

1. Open a Decision

Start by opening a decision envelope. You can use a high-level action (like 'refactor') which automatically maps to a TraceMem intent:

typescript
const decision = await client.open('refactor', {
  automationMode: 'propose',
});

2. Add Context

Document the decision-making process by adding notes and context:

typescript
await decision.note({
  kind: 'info',
  message: 'Starting refactoring work',
  data: { file: 'user.ts' }
});

3. Read Decision Data

Retrieve necessary context from data products:

typescript
const context = await decision.read('pg_customers_v1', 'order_validation', {
  query: { customer_id: '123' }
});

4. Evaluate Policies

Check if your proposed actions comply with defined policies:

typescript
const evaluation = await decision.evaluate('discount_policy', {
  inputs: { discount: 0.15 }
});

5. Request Approval (if needed)

If an evaluation fails or policy dictates, request human approval:

typescript
if (evaluation.requiresApproval) {
  await decision.requestApproval({
    kind: 'policy_override',
    message: 'Requesting exception for discount'
  });
}

6. Write Changes

Record mutations or changes:

typescript
await decision.write('pg_orders_v1', 'create_order', {
  operation: 'insert',
  records: [...]
});

7. Close the Decision

Complete the lifecycle by closing the decision with an outcome:

typescript
await decision.close({
  outcome: 'commit',
  reason: 'Refactoring completed successfully',
});

Auto-Intent Mapping

The client.open() method automatically maps common actions to standardized TraceMem intents, simplifying your code:

ActionIntent
edit_filescode.change.apply
refactorcode.refactor.execute
run_commandops.command.execute
deploydeploy.release.execute
secretssecrets.change.propose
db_changedata.change.apply
reviewcode.review.assist

If you provide an action not in this list, it will be used as-is.

Available Methods

The SDK provides methods organized by the objects they belong to:

Client Methods (client.*)

  • open(action, options) - Open a new decision with automatic intent mapping
  • createDecision(intent, options) - Create a new decision with a specific intent
  • products.list(filter?) - List available data products
  • products.get(name) - Get details for a specific data product

Decision Methods (decision.*)

These methods are available on the decision object returned by open() or createDecision():

  • note(note) - Add a context note to the decision
  • read(product, purpose, options) - Read from a data product
  • evaluate(policy, options) - Evaluate a policy against inputs
  • requestApproval(request) - Request human approval
  • write(product, creation, mutation, options) - Write data/mutations
  • trace() - Retrieve the full trace of the decision
  • receipt() - Get a summary receipt of the decision
  • close(outcome) - Close the decision

Security

Secret Redaction

By default, the SDK automatically sanitizes all data sent to TraceMem. This includes:

  • Redacting Secrets: Keys matching password, key, token, secret, auth, etc., have their values replaced with [redacted].
  • Truncating Data: Large strings (>1000 chars), arrays (>100 items), and deep objects (>10 levels) are truncated to prevent payload bloat.

To disable this (not recommended): set sanitize: false in the client constructor.

Example Workflow

Here is a complete example of a refactoring workflow:

typescript
import { TraceMemClient } from '@tracemem/ts-sdk';

async function runRefactor() {
  const client = new TraceMemClient({ 
    apiKey: process.env.TRACEMEM_API_KEY! 
  });

  // 1. Open decision
  const decision = await client.open('refactor', {
    automationMode: 'propose',
    metadata: { file: 'src/utils.ts' }
  });

  try {
    // 2. Add context
    await decision.note({
      kind: 'info',
      message: 'Analyzing dependency graph'
    });

    // 3. Perform work (simulated)
    // ... analyzing code ...
    
    // 4. Record the outcome
    await decision.close({
      outcome: 'commit',
      reason: 'Extracted helpers to shared module'
    });
    
    console.log(`Decision ${decision.decisionId} completed.`);
    
  } catch (error) {
    // Handle errors (network, validation, etc.)
    console.error('Decision failed:', error);
    
    // Attempt to close as aborted if possible
    await decision.close({ 
      outcome: 'abort', 
      reason: error.message 
    }).catch(console.error);
  }
}

Error Handling

The SDK exports typed error classes for precise error handling:

  • TraceMemError: Base class for all SDK errors
  • TraceMemNetworkError: Connectivity issues
  • TraceMemValidationError: Invalid inputs or parameters
  • TraceMemTimeoutError: Request timeout
typescript
import { TraceMemNetworkError } from '@tracemem/ts-sdk';

try {
  await client.open('refactor');
} catch (err) {
  if (err instanceof TraceMemNetworkError) {
    console.log('Check your internet connection');
  }
}

TraceMem is trace-native infrastructure for AI agents