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

cognix-core-ai

v0.1.0

Published

Production-grade Cognix Core API - Framework agnostic AI orchestration with SOLID principles

Readme

Cognix Core API

Framework-agnostic Cognix Core - Production Grade Implementation

This is the core API of Cognix. It has ZERO dependencies on any UI framework (React, Vue, Svelte, etc.). You can use it with any framework or even Node.js backend applications.

🌟 Key Features

  • Framework Agnostic - No React, Vue, or any framework dependencies
  • SOLID Principles - Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion
  • Clean Architecture - Clear separation of concerns
  • Design Patterns - Builder, Template Method, State Machine, Strategy, Facade
  • Type-Safe - Full TypeScript with strict mode
  • Production Ready - Battle-tested patterns
  • Zero Runtime Dependencies - Pure TypeScript

📦 Installation

npm install @cognix/core
# or
yarn add @cognix/core
# or
pnpm add @cognix/core

🚀 Quick Start

1. Create a Cognix Instance

import { Cognix } from '@cognix/core';
import { 
  ConsoleAuditLogger, 
  MockAIProvider, 
  JsonSchemaValidator 
} from '@cognix/core/implementations';

const cognix = new Cognix({
  auditLogger: new ConsoleAuditLogger(),
  aiProvider: new MockAIProvider(),
  outputValidator: new JsonSchemaValidator(),
});

2. Build an Intent

const purchaseIntent = cognix
  .intent('purchase_product')
  .withParams({ productId: '123', quantity: 1 })
  .requiresAuth()
  .requiresPermission('purchase')
  .constraint('quantity', 'gt', 0)
  .constraint('price', 'lt', 1000)
  .describe('Purchase a product with validation')
  .build();

3. Create a Flow

import type { Flow, ExecutionContext } from '@cognix/core';

const purchaseFlow: Flow = {
  name: 'purchase_flow',
  steps: [
    {
      name: 'validate',
      type: 'understand',
      handler: async (input) => {
        // Validate purchase
        return { validated: true, ...input };
      },
    },
    {
      name: 'execute',
      type: 'execute',
      handler: async (input) => {
        // Process payment
        return { orderId: '12345', ...input };
      },
      retryPolicy: {
        maxAttempts: 3,
        delayMs: 1000,
        backoffMultiplier: 2,
      },
    },
  ],
};

4. Execute the Flow

const context: ExecutionContext = {
  user: {
    id: 'user-123',
    roles: ['customer'],
    permissions: ['purchase'],
    preferences: {},
  },
  session: {
    id: 'session-456',
    startedAt: new Date(),
    expiresAt: new Date(Date.now() + 3600000),
  },
  timestamp: new Date(),
  traceId: 'trace-789',
  metadata: {},
};

const result = await cognix.executeFlow(
  purchaseFlow,
  { productId: '123' },
  context
);

if (result.success) {
  console.log('Purchase successful:', result.output);
} else {
  console.error('Purchase failed:', result.error);
}

🏗️ Architecture

This package follows Clean Architecture with three distinct layers:

┌─────────────────────────────────────┐
│  Core (Domain Logic)                │
│  - Intent System                    │
│  - Flow Executor                    │
│  - Guard System                     │
│  - AI Orchestration                 │
├─────────────────────────────────────┤
│  Implementations (Infrastructure)   │
│  - AuditLogger (Console, InMemory)  │
│  - AIProvider (Mock, OpenAI, etc)   │
│  - RateLimitStorage                 │
│  - OutputValidator                  │
└─────────────────────────────────────┘

NO UI/Framework dependencies at this layer!

📚 Core Concepts

Intents

Represent user goals independent of implementation:

const intent = cognix
  .intent<TParams, TResult>('intent_name')
  .withParams(params)
  .requiresAuth()
  .requiresPermission('permission_name')
  .constraint('field', 'operator', value)
  .rateLimit('10 per hour')
  .describe('Description')
  .build();

Flows

Multi-step processes with state machine:

const flow: Flow = {
  name: 'flow_name',
  steps: [
    {
      name: 'step_name',
      type: 'understand' | 'reason' | 'propose' | 'confirm' | 'execute' | 'monitor' | 'report',
      handler: async (input, context) => {
        // Your logic
        return output;
      },
      guards: [/* optional guards */],
      retryPolicy: {
        maxAttempts: 3,
        delayMs: 1000,
        backoffMultiplier: 2,
      },
    },
  ],
  errorHandler: async (error, context) => {
    return { action: 'retry' | 'skip' | 'fail' | 'rollback' };
  },
};

Guards

Extensible validation with Template Method pattern:

import { BaseGuard } from '@cognix/core';

class CustomGuard extends BaseGuard {
  constructor() {
    super('custom-guard');
  }

  protected async validate(context: ExecutionContext): Promise<boolean> {
    // Your validation logic
    return context.user?.premium === true;
  }

  protected getFailureReason(context: ExecutionContext): string {
    return 'Premium membership required';
  }
}

cognix.registerGuard(new CustomGuard());

AI Providers

Pluggable AI with Strategy pattern:

import type { AIProvider, ExecutionContext, AIResponse } from '@cognix/core';

class MyAIProvider implements AIProvider {
  readonly name = 'my-ai';

  async reason(prompt: string, context: ExecutionContext): Promise<AIResponse> {
    // Call your AI service
    const response = await yourAI.complete(prompt);

    return {
      content: response.text,
      metadata: {
        model: 'your-model',
        tokens: response.tokens,
        latencyMs: response.latency,
      },
    };
  }

  async *stream(prompt: string, context: ExecutionContext) {
    // Streaming implementation
    for await (const chunk of yourAI.stream(prompt)) {
      yield { delta: chunk.text, done: chunk.finished };
    }
  }
}

🔒 Security

Built-in Guards

import { 
  AuthenticationGuard, 
  PermissionGuard, 
  RateLimitGuard 
} from '@cognix/core';
import { InMemoryRateLimitStorage } from '@cognix/core/implementations';

// Authentication
cognix.registerGuard(new AuthenticationGuard());

// Permission
cognix.registerGuard(new PermissionGuard('admin'));

// Rate Limiting
cognix.registerGuard(new RateLimitGuard(
  100, // max requests
  60000, // per minute
  new InMemoryRateLimitStorage()
));

📊 Audit Logging

import { InMemoryAuditLogger } from '@cognix/core/implementations';

const auditLogger = new InMemoryAuditLogger();

// Query logs
const logs = await auditLogger.query({
  startDate: new Date('2024-01-01'),
  type: 'flow_execution',
  userId: 'user-123',
});

🧪 Testing

This package is designed for easy testing with Dependency Injection:

import { Cognix } from '@cognix/core';
import { MockAIProvider, InMemoryAuditLogger } from '@cognix/core/implementations';

// Test configuration
const testCognix = new Cognix({
  auditLogger: new InMemoryAuditLogger(),
  aiProvider: new MockAIProvider(),
  outputValidator: new JsonSchemaValidator(),
});

// Run tests

🎯 Use Cases

Backend Services (Node.js)

import express from 'express';
import { Cognix } from '@cognix/core';

const app = express();
const cognix = new Cognix(config);

app.post('/api/purchase', async (req, res) => {
  const result = await cognix.executeFlow(
    purchaseFlow,
    req.body,
    createContext(req)
  );
  
  res.json(result);
});

CLI Tools

import { Cognix } from '@cognix/core';

const cognix = new Cognix(config);

async function main() {
  const intent = cognix.intent('process-data')
    .withParams({ file: process.argv[2] })
    .build();

  // Execute
}

Serverless Functions

import { Cognix } from '@cognix/core';

const cognix = new Cognix(config);

export async function handler(event, context) {
  const result = await cognix.executeFlow(
    myFlow,
    event.body,
    createContext(event)
  );
  
  return { statusCode: 200, body: JSON.stringify(result) };
}

React/Vue/Svelte

Use framework-specific adapters:

  • @cognix/react - React integration
  • @cognix/vue - Vue integration (coming soon)
  • @cognix/svelte - Svelte integration (coming soon)

📖 API Reference

Core Classes

  • Cognix - Main facade
  • IntentBuilder - Fluent intent builder
  • FlowExecutor - Flow state machine
  • BaseGuard - Guard base class
  • AIOrchestrator - AI coordination

Implementations

  • InMemoryAuditLogger - Development logging
  • ConsoleAuditLogger - Production logging
  • MockAIProvider - Testing provider
  • OpenAIProvider - OpenAI integration
  • AnthropicProvider - Anthropic Claude integration
  • InMemoryRateLimitStorage - In-memory rate limiting
  • JsonSchemaValidator - JSON validation
  • SimpleTextValidator - Text validation

Types

See TypeScript definitions for complete type information.

🛠️ Development

# Install dependencies
npm install

# Build
npm run build

# Watch mode
npm run dev

# Test
npm test

# Lint
npm run lint

# Format
npm run format

📄 License

MIT © Cognix Team

🔗 Related Packages

  • @cognix/react - React integration for Cognix Core
  • @cognix/vue - Vue integration (coming soon)
  • @cognix/svelte - Svelte integration (coming soon)

Framework Agnostic • SOLID Principles • Production Ready 🚀