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

context-kernel

v0.1.2

Published

Platform-agnostic context kernel for routing, budget management, policy guards, and audit trails.

Readme


context-kernel

The brain between your agent and your models.

Platform-agnostic context routing kernel for agent runtimes. Classifies inputs, routes to the right model, enforces policy gates, extracts memory candidates, and emits audit events — all before a single token gets generated. Drop it into any agent system and stop hardcoding your routing logic.

npm License: MIT Node

Install

npm install context-kernel

Quick Start

Basic routing decision

import { ContextKernel } from "context-kernel";

const kernel = new ContextKernel({
  router: {
    tokenCompressionThreshold: 10000,
    allowPremiumEscalation: true,
    routeMap: {
      textDefault: "local_text",
      multimodal: "local_vision",
      urgent: "premium",
      codeHighContext: "premium",
    },
  },
  policy: { postOnlyMode: false },
});

const decision = await kernel.decide({
  sessionId: "sess-001",
  timestamp: new Date().toISOString(),
  messages: [{ role: "user", content: "Help me refactor this repo" }],
  estimatedTokens: 12000,
});

console.log(decision.route);       // "premium" (code + high tokens)
console.log(decision.compress);    // true (over threshold)
console.log(decision.taskType);    // "code"

Policy enforcement with quiet hours

const kernel = new ContextKernel({
  router: { tokenCompressionThreshold: 8000, allowPremiumEscalation: false },
  policy: {
    postOnlyMode: false,
    quietHours: { startHour: 23, endHour: 7 },
    rules: [
      { id: "safe-actions", kind: "action_allowlist", actions: ["send", "post"] },
      { id: "no-keys", kind: "secret_regex", patterns: ["AKIA[0-9A-Z]{16}"], severity: "high" },
    ],
  },
});

OpenClaw adapter

import { fromOpenClawEnvelope } from "context-kernel/adapters/openclaw";

const kernelInput = fromOpenClawEnvelope({
  sessionKey: "oc-session-42",
  timestamp: new Date().toISOString(),
  messages: [{ role: "user", content: "Summarize this image" }],
  images: [{ name: "screenshot.png" }],
});

const decision = await kernel.decide(kernelInput);
// inputKind: "multimodal" → routes to vision model

HTTP adapter

import { fromHttpEnvelope } from "context-kernel/adapters/http";

const kernelInput = fromHttpEnvelope({
  id: "req-abc",
  at: new Date().toISOString(),
  payload: {
    messages: [{ role: "user", content: "What's the weather?" }],
    estimatedTokens: 500,
  },
});

CLI usage

npx context-kernel --config ./kernel.config.json --input ./input.json

Input Classification

The kernel classifies every input along two axes:

Input kindtext or multimodal (detected from attachments)

Task type — pattern-matched from message content:

| Task Type | Triggers | |-----------|----------| | urgent | "urgent", "asap", "immediately" | | code | "refactor", "typescript", "bug", "test", "build", "npm", "repo", "PR" | | memory | "remember", "recall", "note this" | | admin | "config", "policy", "settings", "permission" | | chat | everything else |

Model Routing

Routes are resolved from your routeMap based on classification:

routeMap: {
  textDefault: "local_text",      // default for text chat
  multimodal: "local_vision",     // any input with image/audio attachments
  urgent: "premium",              // urgent requests escalate
  codeHighContext: "premium",     // code tasks over token threshold
  premiumFallback: "premium",    // fallback when escalation is allowed
}

Premium escalation (allowPremiumEscalation) controls whether urgent and high-context code tasks can jump to premium models. Disable it to keep everything local.

Token Budget & Compression

router: {
  tokenCompressionThreshold: 10000  // trigger compression above this
}

When estimatedTokens exceeds the threshold, the decision returns compress: true with a compressionReason. Your downstream worker handles the actual compression — the kernel just makes the call.

Policy Engine

Three built-in guards run on every request, plus a rule DSL for custom policies:

Built-in guards

  • Post-only mode — restricts actions to post/send when postOnlyMode: true
  • Quiet hours — blocks during configured hours (supports overnight ranges like 23→7)
  • Secret detection — regex scan on message content (defaults: api_key, password, token, secret, AKIA...)

Custom rules

rules: [
  // Only allow specific actions
  { id: "safe-actions", kind: "action_allowlist", actions: ["send", "post", "tool_call"] },

  // Block during overnight hours
  { id: "overnight", kind: "quiet_hours", startHour: 1, endHour: 6, severity: "low" },

  // Catch leaked credentials
  { id: "no-aws", kind: "secret_regex", patterns: ["AKIA[0-9A-Z]{16}"], severity: "high" },
]

Every guard and rule produces a PolicyVerdict with allowed, reason, ruleId, and severity.

Memory Extraction

The kernel scans user messages for memory-worthy content and returns MemoryCandidate[]:

| Strategy | Trigger patterns | Priority | TTL | |----------|-----------------|----------|-----| | preference | "remember", "always", "never", "I prefer" | high | 365 days | | decision | "decided", "we will", "approved" | high | 180 days | | summary | long messages (>220 chars) | medium | 30 days |

Each candidate includes writebackHint with namespace, optional upsert key, and TTL — ready for your memory store.

Hook into extraction:

const kernel = new ContextKernel(config, {
  onMemoryCandidates: (candidates, input) => {
    for (const c of candidates) {
      console.log(`[${c.priority}] ${c.source.strategy}: ${c.summary}`);
    }
  },
});

Audit Events

Every decision emits a lifecycle of events via the onEvent hook:

const kernel = new ContextKernel(config, {
  onEvent: (event) => console.log(JSON.stringify(event)),
});

Events: startedclassifiedguard_blocked? → compressed? → routedcompleted | failed

Each event carries sessionId, timestamp, and a detail object for observability.

Zod Validation

All inputs and configs are validated at runtime with Zod schemas. Import them directly:

import { kernelInputSchema, kernelConfigSchema } from "context-kernel/schemas";

const config = kernelConfigSchema.parse(rawConfig);  // throws on invalid
const input = kernelInputSchema.parse(rawInput);

Configuration Reference

| Option | Type | Default | Description | |--------|------|---------|-------------| | router.tokenCompressionThreshold | number | 10000 | Token count that triggers compression | | router.allowPremiumEscalation | boolean | true | Allow urgent/code tasks to escalate to premium models | | router.modelRegistry | Record<string, {provider?, model}> | — | Named model targets (informational) | | router.routeMap | object | — | Maps task classifications to model keys | | policy.postOnlyMode | boolean | false | Restrict to post/send actions only | | policy.quietHours | {startHour, endHour, timezone?} | — | Global quiet hours window | | policy.blockedSecretPatterns | string[] | common patterns | Regex patterns for secret detection | | policy.rules | PolicyRule[] | [] | Custom policy rules (allowlist, quiet hours, secret regex) |

Links


Built with teeth. 🌑