context-kernel
v0.1.2
Published
Platform-agnostic context kernel for routing, budget management, policy guards, and audit trails.
Maintainers
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.
Install
npm install context-kernelQuick 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 modelHTTP 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.jsonInput Classification
The kernel classifies every input along two axes:
Input kind — text 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: started → classified → guard_blocked? → compressed? → routed → completed | 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
- GitHub: github.com/darks0l/context-kernel
- Changelog:
CHANGELOG.md - Architecture:
ARCHITECTURE.md - Security:
SECURITY.md - License: MIT
Built with teeth. 🌑
