The unified orchestrator — auth, routing, scheduling, and self-healing in one class.
Cortex
The Cortex class is the unified orchestrator that combines authentication, threat detection, smart routing, adaptive scheduling, self-healing, and distributed mesh execution into a single entry point.
import { Cortex, createCortex } from '@codmir/cortex';Constructor
new Cortex(config: CortexConfig)CortexConfig
interface CortexConfig {
auth: {
jwtSecret: string;
jwtIssuer?: string; // default: 'codmir-cortex'
accessTokenTtl?: number; // seconds, default: 900
refreshTokenTtl?: number; // seconds, default: 30 * 86400
};
models: ModelProfile[];
threat: Partial<ThreatDetectorConfig>;
router: Partial<SmartRouterConfig>;
scheduler: Partial<AdaptiveSchedulerConfig>;
healer: Partial<SelfHealerConfig>;
mesh: {
maxProcesses?: number; // default: 64
maxMemoryMb?: number; // default: 131072
coordinatorEndpoint?: string;
};
}Instance Properties
| Property | Type | Description |
|---|---|---|
auth | EdgeAuthService | The underlying edge auth service |
threat | ThreatDetector | Threat detection instance |
router | SmartRouter | Smart routing instance |
scheduler | AdaptiveScheduler | Adaptive scheduling instance |
healer | SelfHealer | Self-healing instance |
Factory Function
function createCortex(config: CortexConfig): CortexConvenience wrapper that returns new Cortex(config).
Session Management
authenticate()
Validates a token, runs threat assessment, and creates a Cortex session if the token is valid and the threat level allows it.
async authenticate(
token: string,
event: Omit<AuthEvent, 'success' | 'timestamp'>
): Promise<CortexSession | null>| Parameter | Type | Description |
|---|---|---|
token | string | JWT or opaque token to validate |
event | Omit<AuthEvent, 'success' | 'timestamp'> | Auth event metadata (userId, ip, deviceId, etc.) |
Returns CortexSession on success, null if the token is invalid or the session is blocked by threat detection.
const session = await cortex.authenticate(bearerToken, {
userId: 'user_abc',
ip: req.headers['x-forwarded-for'],
deviceId: 'device_xyz',
userAgent: req.headers['user-agent'],
});
if (!session) {
return res.status(401).json({ error: 'Unauthorized' });
}createSession()
Creates a new authenticated session for a user, returning a token pair and a Cortex session ID.
async createSession(
user: {
id: string;
email: string;
name?: string;
image?: string;
role?: string;
},
request: AuthRequest
): Promise<TokenPair & { cortexSessionId: string }>| Parameter | Type | Description |
|---|---|---|
user | object | User identity (id, email, name, image, role) |
request | AuthRequest | Auth request metadata from @codmir/edge-auth |
const { accessToken, refreshToken, cortexSessionId } = await cortex.createSession(
{ id: 'user_1', email: 'dev@example.com', name: 'Dev' },
{ ip: '10.0.0.1', userAgent: 'Mozilla/5.0' }
);refresh()
Refreshes an expired access token using a refresh token.
async refresh(request: RefreshRequest): Promise<TokenPair | null>| Parameter | Type | Description |
|---|---|---|
request | RefreshRequest | Refresh request from @codmir/edge-auth |
Returns a new TokenPair or null on failure.
const tokens = await cortex.refresh({ refreshToken, ip: '10.0.0.1' });logout()
Invalidates a token.
async logout(token: string): Promise<void>getSession()
Retrieves a stored Cortex session by its ID.
getSession(cortexSessionId: string): CortexSession | undefinedCortexSession
interface CortexSession {
id: string;
userId: string;
authResult: EdgeAuthResult;
session: EdgeSession;
threatAssessment: ThreatAssessment;
createdAt: number;
}Task Execution
executeTask()
Routes a task to the optimal AI model, executes it (via mesh if initialized), feeds results back to the intelligence layer, and returns a full result with routing decision and cost.
async executeTask(
task: MeshTask,
sessionId?: string
): Promise<CortexTaskResult>| Parameter | Type | Description |
|---|---|---|
task | MeshTask | The task to execute (from @codmir/mesh) |
sessionId | string (optional) | Cortex session ID for auth gating |
Throws if the sessionId is invalid or the session is blocked by threat detection.
const result = await cortex.executeTask(
{ id: 'task_1', type: 'code-gen', input: { prompt: 'Build a REST API' } },
session.id
);
console.log(result.model); // 'claude-sonnet'
console.log(result.durationMs); // 2340
console.log(result.costUsd); // 0.0042
console.log(result.routingDecision); // full RoutingDecisionCortexTaskResult
interface CortexTaskResult {
taskId: string;
output: unknown;
model: string;
durationMs: number;
tokensUsed: number;
costUsd: number;
routingDecision: RoutingDecision;
healingEvents: HealingEvent[];
}executeGroup()
Executes a group of tasks via the mesh coordinator. Each task is routed to the optimal model before execution.
async executeGroup(
group: MeshTaskGroup,
sessionId?: string
): Promise<MeshExecutionResult | null>| Parameter | Type | Description |
|---|---|---|
group | MeshTaskGroup | Task group from @codmir/mesh |
sessionId | string (optional) | Cortex session ID for auth gating |
Throws if the mesh coordinator is not initialized (call initMesh() first).
Healing
startHealing()
Starts periodic health checks. When a process status changes, the healer takes action (restart, alert) and emits heal events.
startHealing(restartFn: RestartFn, intervalMs?: number): void| Parameter | Type | Description |
|---|---|---|
restartFn | (pid: number) => Promise<boolean> | Function to restart a process by PID |
intervalMs | number (optional) | Check interval in ms (defaults to config.healer.checkIntervalMs or 10000) |
cortex.startHealing(async (pid) => {
console.log(`Restarting process ${pid}`);
await restartWorker(pid);
return true;
}, 5000);stopHealing()
Stops the periodic healing check loop.
stopHealing(): voidMesh Management
initMesh()
Initializes the distributed mesh coordinator with a worker invocation function.
initMesh(
invokeWorker: (
endpoint: string,
task: MeshTask,
pid: number,
correlationId: string
) => Promise<{ output: unknown; tokensUsed: number }>
): voidThe invokeWorker callback is called for each task execution. Cortex automatically registers processes with the healer and feeds results back to the router and scheduler.
cortex.initMesh(async (endpoint, task, pid, correlationId) => {
const response = await fetch(endpoint, {
method: 'POST',
body: JSON.stringify({ task, pid, correlationId }),
});
return response.json();
});getMeshStatus()
Returns the current mesh coordinator status, or null if the mesh is not initialized.
getMeshStatus(): MeshStatus | nullRouting Helpers
routeTask()
Routes a task to the optimal model without executing it. Useful for previewing routing decisions.
routeTask(
task: MeshTask,
strategy?: RoutingStrategy
): RoutingDecision| Parameter | Type | Description |
|---|---|---|
task | MeshTask | Task to route |
strategy | RoutingStrategy (optional) | Override the default routing strategy |
const decision = cortex.routeTask(
{ id: 'task_1', type: 'code-review' },
'quality'
);
console.log(decision.model.id); // 'claude-opus'
console.log(decision.reason); // 'claude-opus (anthropic) — highest quality, tier=premium'assessThreat()
Runs threat assessment on an auth event without creating a session.
assessThreat(event: AuthEvent): ThreatAssessmentObservability
on()
Registers an event handler. Returns an unsubscribe function.
on(handler: CortexEventHandler): () => voidconst unsubscribe = cortex.on((event) => {
if (event.type === 'threat') {
alertOps(event.payload);
}
});
// Later
unsubscribe();CortexEvent
interface CortexEvent {
type: 'auth' | 'route' | 'schedule' | 'heal' | 'task_complete' | 'task_fail' | 'threat';
payload: unknown;
timestamp: number;
}
type CortexEventHandler = (event: CortexEvent) => void;getIntelligenceReport()
Returns a snapshot of all intelligence subsystems.
getIntelligenceReport(): {
threat: { trackedUsers: number; trackedIps: number; trackedLocations: number };
router: Array<{ id: string; provider: string; healthy: boolean; circuitOpen: boolean; failures: number }>;
scheduler: {
concurrency: number;
failureRate: number;
stats: ExecutionStats[];
};
healer: {
processes: ProcessHealth[];
recentEvents: HealingEvent[];
};
sessions: number;
}const report = cortex.getIntelligenceReport();
console.log(`Active sessions: ${report.sessions}`);
console.log(`Tracked threats: ${report.threat.trackedUsers} users`);
console.log(`Current concurrency: ${report.scheduler.concurrency}`);Lifecycle
destroy()
Stops healing, clears all sessions, removes listeners, and flushes all intelligence subsystem state.
destroy(): voidComplete Example
import { Cortex } from '@codmir/cortex';
import type { ModelProfile } from '@codmir/cortex';
const models: ModelProfile[] = [
{
id: 'claude-sonnet',
provider: 'anthropic',
tier: 'standard',
costPer1kInput: 0.003,
costPer1kOutput: 0.015,
avgLatencyMs: 1200,
qualityScore: 90,
capabilities: ['code', 'reasoning'],
maxTokens: 200_000,
healthy: true,
circuitOpen: false,
},
{
id: 'gpt-4o-mini',
provider: 'openai',
tier: 'fast',
costPer1kInput: 0.00015,
costPer1kOutput: 0.0006,
avgLatencyMs: 400,
qualityScore: 70,
capabilities: ['code', 'chat'],
maxTokens: 128_000,
healthy: true,
circuitOpen: false,
},
];
const cortex = new Cortex({
auth: { jwtSecret: process.env.JWT_SECRET! },
models,
threat: { maxFailedAttempts: 5, velocityThreshold: 10 },
router: { defaultStrategy: 'balanced' },
scheduler: { maxConcurrency: 16 },
healer: { maxConsecutiveFailures: 3, maxRestartAttempts: 5 },
mesh: { maxProcesses: 32 },
});
// Observe all events
cortex.on((event) => {
console.log(`[cortex:${event.type}]`, JSON.stringify(event.payload));
});
// Start self-healing
cortex.startHealing(async (pid) => {
console.log(`Restarting worker ${pid}`);
return true;
});
// Create a session
const { accessToken, cortexSessionId } = await cortex.createSession(
{ id: 'user_1', email: 'dev@codmir.com' },
{ ip: '10.0.0.1', userAgent: 'Codmir-Desktop/1.0' }
);
// Execute a task with session validation
const result = await cortex.executeTask(
{ id: 'review_1', type: 'code-review', input: { diff: '...' } },
cortexSessionId
);
console.log(`Routed to ${result.model}, cost: $${result.costUsd.toFixed(4)}`);
// Inspect intelligence state
const report = cortex.getIntelligenceReport();
console.log(report);
// Teardown
cortex.destroy();