npm package: @skytells/cognition
Description: AI-powered observability SDK — capture errors, runtime health metrics, and security threats
Author: Skytells Research
Latest version: 1.0.0

# Skytells Cognition

AI-powered observability SDK for Node.js. Captures errors, monitors runtime health, detects security threats, and streams everything to Skytells for AI analysis.

![Cognition TS SDK](https://plyryjhqtaoivjdgfggu.supabase.co/storage/v1/object/public/assets/cognition-sdk.png)

[![npm](https://img.shields.io/npm/v/@skytells/cognition)](https://www.npmjs.com/package/@skytells/cognition)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)

## What is Cognition SDK?

Cognition SDK is an AI-powered observability layer for Node.js, designed by [Skytells](https://skytells.ai) for modern production systems. It captures errors with full execution context, continuously monitors runtime health, and detects security threats in real time—without adding operational overhead.

All signals are streamed to Skytells, where AI correlates events, identifies anomalies, and explains system behavior—turning raw telemetry into actionable intelligence.

> It is not just monitoring.
> It is a **runtime intelligence** layer that makes your system measurable, explainable, and secure under real-world conditions.

## Get Started

Getting up and running takes less than 5 minutes.

**Step 1 — Create a Skytells account**

Sign up or log in at [console.skytells.ai](https://console.skytells.ai). It's free to get started.

**Step 2 — Create a project**

Go to [console.skytells.ai/projects](https://console.skytells.ai/projects) and click **New Project**. Give it a name (e.g. `my-api`). Your **Project ID** is shown on the project card — you'll need it in the next step.

**Step 3 — Get your API key**

Inside your project, go to **Settings → API Key** and copy your key. Keep it secret — treat it like a password.

**Step 4 — Install the SDK and initialize**

```bash
npm install @skytells/cognition
```

```typescript
import { Cognition } from '@skytells/cognition';

Cognition.init({
  apiKey: process.env.SKYTELLS_API_KEY!,
  projectId: process.env.SKYTELLS_PROJECT_ID!,
});
```

That's it. Cognition immediately starts capturing uncaught errors, monitoring runtime health, and streaming events to your Skytells project.

> **Product page**: [skytells.ai/products/cognition](https://skytells.ai/products/cognition) · **Full docs**: [learn.skytells.ai](https://learn.skytells.ai)

## Features

- **Error Capture** — Automatic `uncaughtException` / `unhandledRejection` handling with rich stack traces and breadcrumbs
- **Runtime Observer** — Event loop lag, memory/CPU usage, GC pressure, handle leak detection
- **Security Scanner** — Detects SQL injection, XSS, path traversal, and command injection in request payloads
- **OpenTelemetry** — Optional OTel trace exporter bridge (peer dependency)
- **Zero Dependencies** — Uses only Node.js built-ins in production
- **Dual Format** — Ships ESM + CJS with full TypeScript declarations

## Installation

```bash
npm install @skytells/cognition
# or
pnpm add @skytells/cognition
# or
yarn add @skytells/cognition
```

## Quick Start

```typescript
import { Cognition } from '@skytells/cognition';

const cognition = Cognition.init({
  apiKey: process.env.SKYTELLS_API_KEY!, // from Settings → API Key
  projectId: process.env.SKYTELLS_PROJECT_ID!, // from console.skytells.ai/projects
});

// Manually capture an error
try {
  riskyOperation();
} catch (err) {
  cognition.captureError(err);
}

// Capture a message
cognition.captureMessage('Deployment complete', 'info');

// Set user context (attached to all subsequent events)
cognition.setUser({ id: 'user-123', username: 'jane_doe' });

// Add tags and extra context
cognition.setTag('service', 'api');
cognition.setExtra('requestId', 'abc-123');

// Graceful shutdown
process.on('SIGTERM', async () => {
  await cognition.close();
  process.exit(0);
});
```

## Configuration

```typescript
Cognition.init({
  // Required — get these from console.skytells.ai
  apiKey: process.env.SKYTELLS_API_KEY!,
  projectId: process.env.SKYTELLS_PROJECT_ID!,

  // Optional
  endpoint: 'https://dsn.skytells.ai', // Default — Skytells hosted endpoint
  environment: 'production', // Environment name
  release: '1.2.3', // App version
  serverName: 'api-01', // Server identifier
  debug: false, // Debug logging

  // Error capture
  captureErrors: true, // Auto-capture uncaught errors

  // Runtime monitoring
  runtime: {
    enabled: true,
    snapshotIntervalMs: 10_000, // How often to collect metrics
    thresholds: {
      heapUsedMb: 512, // Anomaly alert threshold
      eventLoopLagMs: 100, // p99 lag threshold
      eluPercent: 0.8, // Event loop utilization threshold
    },
  },

  // Transport
  transport: {
    batchSize: 50,
    flushIntervalMs: 5_000,
    maxRetries: 3,
    timeoutMs: 10_000,
    maxBufferSize: 1_000,
    compression: true,
  },

  // Security scanning
  captureSecurityThreats: true,

  // OpenTelemetry (requires peer deps)
  tracing: {
    enabled: false,
    sampleRate: 1.0,
  },

  // PII scrubbing / event filtering
  beforeSend: (event) => {
    // Return null to drop the event
    return event;
  },
});
```

## Security Middleware

Scan incoming HTTP requests for injection attacks:

```typescript
import express from 'express';
import { Cognition, createSecurityMiddleware } from '@skytells/cognition';

const app = express();
const cognition = Cognition.init({
  apiKey: process.env.SKYTELLS_API_KEY!,
  projectId: process.env.SKYTELLS_PROJECT_ID!,
});

// Add security scanning middleware
app.use(
  createSecurityMiddleware((event) => {
    cognition.captureEvent(event);
  }),
);
```

Or scan inputs manually:

```typescript
const detected = cognition.scanForThreats(userInput, {
  method: 'POST',
  url: '/api/search',
  ip: '192.168.1.1',
  source: 'body.query',
});
```

## Runtime Snapshots

Get an on-demand runtime snapshot:

```typescript
const snapshot = cognition.getRuntimeSnapshot();
console.log(snapshot);
// {
//   memory: { rss, heapUsed, heapTotal, external, arrayBuffers },
//   cpu: { user, system },
//   eventLoop: { utilization, lagP50, lagP99, lagMax },
//   gc: { majorCount, minorCount, incrementalCount, totalDuration, maxPause },
//   handles: { active, requests },
// }
```

## OpenTelemetry Integration

Install the optional peer dependencies:

```bash
npm install @opentelemetry/api @opentelemetry/sdk-trace-base
```

Then enable tracing:

```typescript
const cognition = Cognition.init({
  apiKey: '...',
  projectId: '...',
  tracing: {
    enabled: true,
    sampleRate: 0.5,
  },
});
```

OTel spans are automatically exported through the Cognition transport.

## Breadcrumbs

Console output is automatically captured as breadcrumbs and attached to error events. Add custom breadcrumbs:

```typescript
cognition.addBreadcrumb('user-action', 'Clicked checkout button', {
  cartItems: 3,
});
```

## Event Filtering

Use `beforeSend` to filter, modify, or drop events before they leave the process:

```typescript
Cognition.init({
  apiKey: '...',
  projectId: '...',
  beforeSend: (event) => {
    // Drop all info-level messages
    if (event.type === 'message' && (event as any).level === 'info') {
      return null;
    }
    // Scrub emails from error messages
    if (event.type === 'error') {
      const e = event as any;
      e.error.message = e.error.message.replace(/[\w.-]+@[\w.-]+/g, '[REDACTED]');
    }
    return event;
  },
});
```

## API Reference

### `Cognition.init(config): Cognition`

Initialize the SDK. Returns the Cognition instance.

### Instance Methods

| Method                                            | Description                                      |
| ------------------------------------------------- | ------------------------------------------------ |
| `captureError(err, opts?)`                        | Capture an error with optional level and context |
| `captureMessage(msg, level?)`                     | Capture a message event                          |
| `captureEvent(event)`                             | Capture an arbitrary event                       |
| `addBreadcrumb(category, message, data?, level?)` | Add a breadcrumb                                 |
| `setUser(user)`                                   | Set user context                                 |
| `setTag(key, value)`                              | Set a tag                                        |
| `setExtra(key, value)`                            | Set extra context                                |
| `scanForThreats(input, context?)`                 | Scan input for security threats                  |
| `getRuntimeSnapshot()`                            | Get current runtime metrics                      |
| `flush()`                                         | Force-flush buffered events                      |
| `close(timeoutMs?)`                               | Gracefully shut down                             |

### Instance Properties

| Property         | Description                    |
| ---------------- | ------------------------------ |
| `isInitialized`  | Whether the SDK is running     |
| `bufferSize`     | Events currently buffered      |
| `droppedCount`   | Events dropped due to overflow |
| `resolvedConfig` | Resolved config with defaults  |

## Requirements

- Node.js >= 18.0.0

## Documentation

Full documentation is available at [learn.skytells.ai](https://learn.skytells.ai) and in the [docs/](docs/) directory.

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and guidelines.

## Security

To report a vulnerability, see [SECURITY.md](SECURITY.md).

## License

Apache-2.0 — see [LICENSE](LICENSE) for details.