npm.io
1.2.0 • Published 3 months ago

@x12i/execution-memory-manager

Licence
MIT
Version
1.2.0
Deps
0
Size
68 kB
Vulns
0
Weekly
0

@x12i/execution-memory-manager

A TypeScript package for managing execution history memory objects with support for clipping, filtering, and markdown formatting.

Installation

npm install @x12i/execution-memory-manager

Features

  • Add memories to history objects with optional clipping
  • Retrieve memories by role, position (first/last), or clip label
  • Get all memories including those in clips and objects
  • Type guard function to check if objects are memory-like
  • Export memories as formatted markdown
  • Full TypeScript support with type definitions
  • Works with RunHistory, JobHistory, and TaskHistory objects

Types

The package manages three types of history objects:

  • RunHistory - Job execution history for database storage
  • JobHistory - Task execution history within a job
  • TaskHistory - Skill execution history within a task

All extend the base HistoryObject interface.

API Reference

Core Functions
addMemory(history, memory, clipLabel?)

Adds a memory to a history object. Optionally clips it with a label.

import { addMemory, RunHistory, MemoryObject } from '@x12i/execution-memory-manager';

const history: RunHistory = {
  context: "Data Processing Job",
  objective: "Process customer data",
  memories: [],
  clips: [],
  jobObjects: [],
  _metadata: { /* ... */ }
};

const memory: MemoryObject = {
  context: "Data validation",
  objective: "Validate customer records",
  role: "validator",
  memory: {
    validatedRecords: 150,
    errors: ["Invalid email format", "Missing phone number"]
  }
};

// Add without clipping
addMemory(history, memory);

// Add with clipping
addMemory(history, memory, "validation-errors");
getLastMemories(history, role?, limit?)

Gets the last N memories, optionally filtered by role.

import { getLastMemories } from '@x12i/execution-memory-manager';

// Get last memory of any role
const lastMemory = getLastMemories(history);

// Get last 3 memories of 'validator' role
const lastValidators = getLastMemories(history, 'validator', 3);

// Get last 5 memories of any role
const lastFive = getLastMemories(history, null, 5);
getFirstMemories(history, role?, limit?)

Gets the first N memories, optionally filtered by role.

import { getFirstMemories } from '@x12i/execution-memory-manager';

// Get first memory of any role
const firstMemory = getFirstMemories(history);

// Get first 2 memories of 'processor' role
const firstProcessors = getFirstMemories(history, 'processor', 2);
getMemories(history, role?)

Gets all memories, optionally filtered by role.

import { getMemories } from '@x12i/execution-memory-manager';

// Get all memories
const allMemories = getMemories(history);

// Get all memories with 'analyzer' role
const analyzers = getMemories(history, 'analyzer');
getClippedMemories(history, clipLabel)

Gets memories that were clipped with a specific label.

import { getClippedMemories } from '@x12i/execution-memory-manager';

// Get all memories clipped with 'validation-errors'
const errorMemories = getClippedMemories(history, 'validation-errors');
isMemoryObject(obj)

Type guard function to check if an object is a MemoryObject.

import { isMemoryObject } from '@x12i/execution-memory-manager';

const obj = { context: "...", objective: "...", role: "...", memory: {...} };
if (isMemoryObject(obj)) {
  // obj is now typed as MemoryObject
  console.log(obj.role);
}
getAllMemories(history, options?)

Gets all memories from a history object, including those stored in clips and objects. This is the most comprehensive memory retrieval function.

import { getAllMemories } from '@x12i/execution-memory-manager';

// Get all memories including clipped ones and objects
const allMemories = getAllMemories(history, {
  includeClips: true,
  includeObjects: true
});

// Get all memories filtered by role
const allValidators = getAllMemories(history, {
  role: 'validator',
  includeClips: true,
  includeObjects: true
});

// Get only memories from main array (exclude clips and objects)
const mainMemories = getAllMemories(history, {
  includeClips: false,
  includeObjects: false
});

Options:

  • includeClips?: boolean - Include memories from all clips (default: true)
  • includeObjects?: boolean - Include memory-like objects from jobObjects/taskObjects (default: true)
  • role?: string | null - Optional role filter (default: null = all roles)
  • sortBy?: 'chronological' | 'priority' - Sort order (default: 'chronological')

Note: This function automatically detects memory-like objects in jobObjects and taskObjects arrays using the isMemoryObject() type guard.

When to use getAllMemories() vs getMemories():

  • Use getMemories() when you only need memories from the main memories array
  • Use getAllMemories() when you need a comprehensive view including:
    • Memories from the main array
    • Memories referenced by clips
    • Memory-like objects stored in jobObjects or taskObjects
Markdown Functions

Each core function has a markdown version that returns formatted markdown instead of JSON objects.

getLastMemoriesMD(history, role?, limit?)
import { getLastMemoriesMD } from '@x12i/execution-memory-manager';

const markdown = getLastMemoriesMD(history, 'validator', 2);
console.log(markdown);

Output:

# Data Processing Job

## Process customer data

---

### validatedRecords

150

### errors

- Invalid email format
- Missing phone number
getFirstMemoriesMD(history, role?, limit?)

Same as getLastMemoriesMD but returns first N memories.

getMemoriesMD(history, role?)

Returns all memories as markdown.

getClippedMemoriesMD(history, clipLabel)

Returns clipped memories as markdown.

getAllMemoriesMD(history, options?)

Markdown version of getAllMemories(). Returns all memories (including from clips and objects) as formatted markdown.

import { getAllMemoriesMD } from '@x12i/execution-memory-manager';

// Get all memories as markdown
const markdown = getAllMemoriesMD(history, {
  includeClips: true,
  includeObjects: true,
  role: 'validator'
});

Complete Example

import {
  addMemory,
  getLastMemories,
  getClippedMemories,
  getAllMemories,
  getAllMemoriesMD,
  getMemoriesMD,
  RunHistory,
  MemoryObject
} from '@x12i/execution-memory-manager';

// Create a history object
const history: RunHistory = {
  context: "Customer Analytics Pipeline",
  objective: "Analyze customer behavior and generate insights",
  memories: [],
  clips: [],
  jobObjects: [
    {
      name: "customer_data",
      type: "dataset",
      id: "ds_001",
      role: "input-object"
    }
  ],
  _metadata: {
    jobId: "job_123",
    agentId: "agent_456",
    totalCost: 0.05,
    totalTokens: 1500,
    totalDurationMs: 3000,
    startTime: new Date(),
    endTime: new Date()
  }
};

// Add memories with different roles
addMemory(history, {
  context: "Data Loading",
  objective: "Load customer dataset",
  role: "loader",
  memory: {
    recordsLoaded: 10000,
    source: "database",
    loadTime: "2.5s"
  }
});

addMemory(history, {
  context: "Data Validation",
  objective: "Validate data quality",
  role: "validator",
  memory: {
    totalRecords: 10000,
    validRecords: 9850,
    invalidRecords: 150,
    validationRules: ["email_format", "phone_format", "date_range"]
  }
}, "quality-check");

addMemory(history, {
  context: "Analysis",
  objective: "Analyze customer segments",
  role: "analyzer",
  memory: {
    segments: ["high-value", "at-risk", "new-customers"],
    insights: {
      highValue: { count: 500, avgRevenue: 5000 },
      atRisk: { count: 200, churnProbability: 0.7 }
    }
  }
});

// Retrieve memories using different methods
const lastTwo = getLastMemories(history, null, 2);
const validators = getClippedMemories(history, 'quality-check');

// Get ALL memories including those in clips and objects
const allMemories = getAllMemories(history, {
  includeClips: true,
  includeObjects: true
});

// Export as markdown
const markdown = getMemoriesMD(history);
const allMemoriesMarkdown = getAllMemoriesMD(history, {
  includeClips: true,
  includeObjects: true
});
console.log(markdown);

Usage Guide

Choosing the Right Function
  • getMemories() - Simple retrieval from main memories array
  • getAllMemories() - Comprehensive retrieval including clips and objects
  • getLastMemories() / getFirstMemories() - Position-based retrieval with limits
  • getClippedMemories() - Retrieve memories by clip label
  • isMemoryObject() - Type guard for runtime type checking
Memory Detection in Objects

The getAllMemories() function can automatically detect memory-like objects in jobObjects and taskObjects arrays. An object is considered memory-like if it has:

  • context: string
  • objective: string
  • role: string
  • memory: Record<string, any>

Use isMemoryObject() to check if an object matches this structure.

Markdown Format

The markdown output follows this structure:

  1. Title: The history's context
  2. Subtitle: The history's objective
  3. Memory sections: Each memory's data with keys as headers
  4. Roles and clips are included in the markdown output (context, objective, role are shown)
  5. Nested objects and arrays are properly formatted

TypeScript Support

Full TypeScript definitions are included. The package exports all types:

import type {
  MemoryObject,
  ClipObject,
  HistoryObject,
  EntityIdentity,
  RunHistory,
  JobHistory,
  TaskHistory,
  AnyHistoryObject,
  GetAllMemoriesOptions
} from '@x12i/execution-memory-manager';

License

MIT

Author

x12i

Keywords