Preparing your workspace...

assistant-chat.tsx2.5k
utils.ts850
button.tsx720
Quick Actions
codmir
Docs
Discord
Get started
API
  • Introduction
  • Installation
  • Your First Project
  • Your First Agent
  • Overview
    • Cortex Class
    • ThreatDetector
    • SmartRouter
    • AdaptiveScheduler
    • SelfHealer

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

PropertyTypeDescription
authEdgeAuthServiceThe underlying edge auth service
threatThreatDetectorThreat detection instance
routerSmartRouterSmart routing instance
schedulerAdaptiveSchedulerAdaptive scheduling instance
healerSelfHealerSelf-healing instance

Factory Function

function createCortex(config: CortexConfig): Cortex

Convenience 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>
ParameterTypeDescription
tokenstringJWT or opaque token to validate
eventOmit<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 }>
ParameterTypeDescription
userobjectUser identity (id, email, name, image, role)
requestAuthRequestAuth request metadata from @codmir/edge-auth
const { accessToken, refreshToken, cortexSessionId } = await cortex.createSession(
  { id: 'user_1', email: '[email protected]', 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>
ParameterTypeDescription
requestRefreshRequestRefresh 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 | undefined

CortexSession

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>
ParameterTypeDescription
taskMeshTaskThe task to execute (from @codmir/mesh)
sessionIdstring (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 RoutingDecision

CortexTaskResult

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>
ParameterTypeDescription
groupMeshTaskGroupTask group from @codmir/mesh
sessionIdstring (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
ParameterTypeDescription
restartFn(pid: number) => Promise<boolean>Function to restart a process by PID
intervalMsnumber (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(): void

Mesh 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 }>
): void

The 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 | null

Routing Helpers

routeTask()

Routes a task to the optimal model without executing it. Useful for previewing routing decisions.

routeTask(
  task: MeshTask,
  strategy?: RoutingStrategy
): RoutingDecision
ParameterTypeDescription
taskMeshTaskTask to route
strategyRoutingStrategy (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): ThreatAssessment

Observability

on()

Registers an event handler. Returns an unsubscribe function.

on(handler: CortexEventHandler): () => void
const 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(): void

Complete 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: '[email protected]' },
  { 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();
Open in ChatGPTOpen in ClaudeConnect MCP on CursorConnect MCP on WindsurfEdit on GitHub
codmir
Products
Desktop AppMobile AppIDE ExtensionAI AgentsOverseerVoice ModeCortex ProtocolHive MindGame Dev (Godat)PricingDownload
Solutions
AI Code AgentsCode ReviewError TrackingSelf-HealingDeploy TrackingAI Tracking SDKWorkflow AutomationTesting FrameworkTime TrackingVoice Control
Platform
ProjectsTickets & BoardsAgent MarketplaceIntegrationsTemplatesApp HubAdmin PanelAnalytics
Integrations
GitHubSlackDiscordVercelSentryRailwayLinearAll Integrations
Developers
DocumentationAPI ReferenceSDKCLIDeveloper PortalMarketplaceMCP ConnectorsWebhooksExamplesnpm Packages
Resources
BlogChangelogCommunityTutorialsGet StartedSupportStatusFeedback
Company
AboutCareersContact SalesKickstarterReferral Program
Legal
Terms of UsePrivacy PolicyEULATrademarkSecurity
Download on the App StoreGet it on Google Play

Codmir™ 2026. All rights reserved.

Free & open source SDK — Apache 2.0 License