Policy enforcement, rate limiting, and Overseer bridge for AI operations

AI Governance

The governance layer enforces policies on AI operations -- rate limiting, action approval gates, and event reporting. The OverseerBridge connects the AI client to the Overseer service for centralized governance and monitoring.

Installation

import {
  OverseerBridge,
  createOverseerBridge,
  createOverseerReporter,
} from "@codmir/ai";
import type {
  OverseerConnection,
  OverseerCommand,
  OverseerBridgeConfig,
  GovernanceConfig,
  GovernanceDecision,
  ActionType,
} from "@codmir/ai";

GovernanceConfig

Governance is configured when creating a CodemirAI client. Every complete() and stream() call checks governance before proceeding.

import { createCodemirAI } from "@codmir/ai";

const ai = createCodemirAI({
  governance: {
    enabled: true,
    rateLimitPerMinute: 60,
    autoApprove: ["code_generation", "api_call"],
    requireApproval: ["file_deletion", "database_operation", "command_execution"],
    maxTokensPerRequest: 8192,
    notifyOn: ["task_failed", "rate_limit_reached", "error_occurred"],
  },
});

Configuration Reference

interface GovernanceConfig {
  enabled: boolean;
  requireApproval?: ActionType[];
  autoApprove?: ActionType[];
  maxTokensPerRequest?: number;
  rateLimitPerMinute?: number;
  notifyOn?: GovernanceEvent[];
}
PropertyTypeDescription
enabledbooleanEnable governance checks
requireApprovalActionType[]Actions that require explicit approval
autoApproveActionType[]Actions auto-approved without checks
maxTokensPerRequestnumberMaximum tokens per request
rateLimitPerMinutenumberMax requests per minute
notifyOnGovernanceEvent[]Events that trigger notifications

Action Types

type ActionType =
  | "code_generation"
  | "code_modification"
  | "file_creation"
  | "file_deletion"
  | "command_execution"
  | "api_call"
  | "database_operation";

Governance Events

type GovernanceEvent =
  | "task_started"
  | "task_completed"
  | "task_failed"
  | "approval_required"
  | "rate_limit_reached"
  | "error_occurred";

Rate Limiting

When rateLimitPerMinute is set, the client tracks request counts per minute. If the limit is exceeded, the request is denied and a rate_limit_reached event is emitted.

const ai = createCodemirAI({
  governance: {
    enabled: true,
    rateLimitPerMinute: 30,
  },
});

// After 30 requests in a minute:
try {
  await ai.complete({ messages: [...] });
} catch (error) {
  // "Request denied: Rate limit exceeded"
}

Approval Gates

Actions listed in requireApproval emit an approval_required event. In the current implementation, these are auto-approved with a "Review required" condition logged. In production, this integrates with the Overseer service for human-in-the-loop approval.

Actions listed in autoApprove bypass all checks.

const ai = createCodemirAI({
  governance: {
    enabled: true,
    autoApprove: ["code_generation"],
    requireApproval: ["file_deletion"],
  },
});

// code_generation requests pass immediately
// file_deletion requests emit approval_required event

GovernanceDecision

Every governance check produces a decision:

interface GovernanceDecision {
  action: ActionType;
  approved: boolean;
  reason?: string;
  conditions?: string[];
  decidedBy: "auto" | "overseer" | "human";
  timestamp: Date;
}

OverseerBridge

The OverseerBridge connects the AI client to the Overseer service for centralized governance, event reporting, and command reception.

createOverseerBridge(config?): OverseerBridge

import { createOverseerBridge } from "@codmir/ai";

const bridge = createOverseerBridge({
  overseerUrl: "https://overseer.codmir.com",
  projectId: "proj_abc",
  organizationId: "org_xyz",
  realTimeSync: true,
  eventBufferSize: 10,
});

await bridge.connect();

OverseerBridgeConfig

interface OverseerBridgeConfig {
  overseerUrl?: string;          // defaults to OVERSEER_URL env var
  projectId?: string;
  organizationId?: string;
  realTimeSync?: boolean;        // default: true
  eventBufferSize?: number;      // default: 10
}

Methods

connect(): Promise<void>

Establishes connection to the Overseer service. If overseerUrl is not set, logs a warning and runs in standalone mode.

await bridge.connect();

reportEvent(event): void

Reports an AI event to Overseer. Events are buffered and flushed in batches.

import type { AIEvent } from "@codmir/ai";

bridge.reportEvent({
  type: "request_completed",
  timestamp: new Date(),
  data: { provider: "anthropic", tokens: 1500 },
});

requestApproval(action, context): Promise<GovernanceDecision>

Requests approval from Overseer for a specific action. Returns auto-approved if Overseer is not connected.

const decision = await bridge.requestApproval("file_deletion", {
  path: "/src/legacy/old-module.ts",
  reason: "Deprecated code cleanup",
});

if (decision.approved) {
  await deleteFile(path);
}

getGovernanceConfig(): Promise<GovernanceConfig>

Fetches the current governance configuration from the Overseer service.

const config = await bridge.getGovernanceConfig();
ai.setGovernance(config);

onCommand(handler): () => void

Subscribes to commands from Overseer (pause, resume, cancel, config updates). Returns an unsubscribe function.

const unsub = bridge.onCommand((command) => {
  switch (command.type) {
    case "pause":
      agent.pause();
      break;
    case "resume":
      agent.resume();
      break;
    case "cancel":
      agent.cancelCurrentTask();
      break;
    case "update_config":
      ai.setGovernance(command.data as GovernanceConfig);
      break;
  }
});

disconnect(): Promise<void>

Flushes remaining events and disconnects from the Overseer service.

await bridge.disconnect();

OverseerCommand

interface OverseerCommand {
  type: "pause" | "resume" | "cancel" | "update_config" | "set_context";
  data?: Record<string, unknown>;
}

Event Reporter

createOverseerReporter(bridge): AIEventHandler

Creates an event handler that forwards all AI events to Overseer via the bridge. Use this with CodemirAI.on("*", ...).

import { createCodemirAI, createOverseerBridge, createOverseerReporter } from "@codmir/ai";

const ai = createCodemirAI({ defaultProvider: "anthropic" });
const bridge = createOverseerBridge({ overseerUrl: "https://overseer.codmir.com" });
await bridge.connect();

const reporter = createOverseerReporter(bridge);
ai.on("*", reporter);

This pipes all AI events (request start/complete/fail, streaming, governance decisions, rate limits) to the Overseer service for centralized monitoring and alerting.

Full Integration Example

import { createCodemirAI, createOverseerBridge, createOverseerReporter } from "@codmir/ai";

// 1. Create AI client with governance
const ai = createCodemirAI({
  defaultProvider: "anthropic",
  governance: {
    enabled: true,
    rateLimitPerMinute: 60,
    autoApprove: ["code_generation"],
    requireApproval: ["command_execution"],
  },
});

// 2. Connect to Overseer
const bridge = createOverseerBridge({
  overseerUrl: process.env.OVERSEER_URL,
  projectId: "proj_abc",
});
await bridge.connect();

// 3. Forward all events to Overseer
ai.on("*", createOverseerReporter(bridge));

// 4. Listen for Overseer commands
bridge.onCommand((cmd) => {
  if (cmd.type === "update_config") {
    ai.setGovernance(cmd.data as GovernanceConfig);
  }
});

// 5. Fetch remote governance config on startup
const remoteConfig = await bridge.getGovernanceConfig();
if (remoteConfig.enabled) {
  ai.setGovernance(remoteConfig);
}

// 6. Use AI -- governance is enforced automatically
const response = await ai.chat("Fix the login validation bug");