Skip to main content

@agentlib/core

The core runtime engine for AgentLIB — a type-safe, extensible AI agent framework for Node.js.

Installation

npm install @agentlib/core

Overview

@agentlib/core provides the foundational building blocks for creating AI agents:
  • Agent Creation: Factory functions and decorator-based agent definitions
  • Tool System: Type-safe tool definitions and registry
  • Reasoning Context: Execution context for reasoning engines
  • Memory Utilities: Token estimation and budget management
  • Middleware Pipeline: Extensible middleware system for agent lifecycle hooks
  • Event System: Type-safe event emitter for agent events
  • Terminal Utilities: Console prompting for interactive agents

Key Exports

Agent Factory

import { createAgent } from '@agentlib/core'

const agent = createAgent({
  name: 'my-agent',
  description: 'A helpful AI assistant',
  model: myModelProvider,
  tools: [myTool],
  memory: myMemoryProvider
})

Tool Definition

import { defineTool } from '@agentlib/core'

const weatherTool = defineTool({
  schema: {
    name: 'get_weather',
    description: 'Get current weather for a location',
    parameters: {
      type: 'object',
      properties: {
        location: { type: 'string', description: 'City name' }
      },
      required: ['location']
    }
  },
  execute: async (args, ctx) => {
    const { location } = args
    // Fetch weather data
    return { temp: 72, condition: 'sunny' }
  }
})

Decorators

import { Agent, Tool, Arg } from '@agentlib/core'

@Agent({
  name: 'math-agent',
  description: 'Performs mathematical operations'
})
class MathAgent {
  @Tool({ description: 'Add two numbers' })
  add(
    @Arg('a', 'First number') a: number,
    @Arg('b', 'Second number') b: number
  ) {
    return a + b
  }
}

const agent = createAgent(MathAgent)

Middleware

import { MiddlewarePipeline } from '@agentlib/core'

const loggingMiddleware = {
  name: 'logger',
  scope: 'run:before',
  run: async (mCtx, next) => {
    console.log('Agent starting:', mCtx.ctx.input)
    await next()
  }
}

agent.use(loggingMiddleware)

Memory Utilities

import { 
  estimateTokens, 
  estimateMessagesTokens, 
  trimToTokenBudget 
} from '@agentlib/core'

// Estimate tokens for a single message
const tokens = estimateTokens('Hello, world!')

// Estimate tokens for a message array
const messageTokens = estimateMessagesTokens(messages)

// Trim messages to fit token budget
const trimmed = trimToTokenBudget(messages, 4000)

Event System

import { EventEmitter } from '@agentlib/core'

agent.on('run:start', ({ input, sessionId }) => {
  console.log(`Starting run: ${input}`)
})

agent.on('step:reasoning', (step) => {
  console.log(`Step: ${step.type}`, step)
})

agent.on('run:end', ({ output, state }) => {
  console.log(`Completed: ${output}`)
})

Reasoning Context

import { createReasoningContext } from '@agentlib/core'

const rCtx = createReasoningContext({
  ctx: executionContext,
  model: modelProvider,
  tools: toolRegistry,
  policy: agentPolicy
})

// Used internally by reasoning engines
await rCtx.callTool('my_tool', { arg: 'value' }, 'call-id-123')
rCtx.pushStep({ type: 'thought', content: 'Thinking...', engine: 'react' })

Terminal Utilities

import { loopConsolePrompting } from '@agentlib/core'

// Interactive console loop
await loopConsolePrompting(agent, {
  sessionId: 'console-session',
  greeting: 'Welcome! How can I help?'
})

Core Types

All core types are exported from @agentlib/core:
  • AgentConfig - Agent configuration interface
  • ModelProvider - Model provider interface
  • ModelMessage, ModelRequest, ModelResponse - Message types
  • ToolDefinition, ToolSchema - Tool types
  • MemoryProvider, MemoryEntry - Memory types
  • ReasoningEngine, ReasoningContext, ReasoningStep - Reasoning types
  • Middleware, MiddlewareContext - Middleware types
  • ExecutionContext, ExecutionState - Runtime context types
  • AgentPolicy - Policy configuration
  • RunOptions, RunResult - Execution types

Engine Registry

import { registerEngine, engineRegistry } from '@agentlib/core'

// Register a custom reasoning engine
registerEngine('custom', () => new MyCustomEngine())

// Use by name
agent.reasoning('custom')

Requirements

  • Node.js: >= 18.0.0
  • Peer Dependencies: dotenv (optional)

Dependencies

  • reflect-metadata: For decorator support
  • @agentlib/utils: Shared utilities

Build docs developers (and LLMs) love