KAKUNIN

Know Your Agent (KYA): Framework for AI System Governance

In traditional finance, "Know Your Customer" (KYC) is the foundation of regulatory compliance and risk management. For autonomous AI agents operating with real-world authority—executing trades, managing data, controlling infrastructure—we need an equivalent: Know Your Agent (KYA).

KYA is a governance framework that establishes agent identity, profiles normal behavior, detects deviations, and enforces limits. It bridges the gap between cryptographic proof of identity (certificate binding) and operational verification (continuous monitoring).


Core Principles

1. Identity Verification

Every agent must have cryptographically verifiable identity—not API keys that can leak, but X.509 certificates bound to a specific runtime.

// KYA step 1: Bind agent to cryptographic identity
const agent = await kakunin.agents.create({
  name: 'trading_bot_eu_v2',
  metadata: { version: '2.1.0', deployment: 'kubernetes' },
});

const cert = await kakunin.agents.getCertificate(agent.id, {
  validityDays: 365,
  scope: {
    maxTransactionSize: 50000,
    allowedMarkets: ['EUR_USD', 'GBP_EUR'],
    allowedRegions: ['eu-west-1'],
  },
});

2. Behavioral Baseline

Before an agent can operate, establish what "normal" looks like:

// KYA step 2: Record baseline behavior
const baseline = {
  agent_id: agent.id,
  transaction_size_p50: 25000,  // median
  transaction_size_p99: 45000,  // 99th percentile
  transactions_per_hour: 8,
  preferred_markets: ['EUR_USD', 'GBP_EUR'],
  trading_hours: { start: '08:00', end: '17:00', tz: 'UTC' },
};

await kakunin.monitoring.recordBaseline(agent.id, baseline);

3. Anomaly Detection

Continuously monitor agent behavior against baseline. Flag deviations with confidence scores.

MetricBaselineCurrentAnomaly?Confidence
Transaction size€25K (p50)€180K✓ YES0.92
Hourly frequency8/hr42/hr✓ YES0.87
MarketEUR_USD, GBP_EURJPY_KRW✓ YES0.99
Regioneu-west-1us-east-1✓ YES0.95

Action triggered: Risk score = 0.88 → pre-revocation warning issued.

4. Continuous Verification

At each action, verify three things:

  1. Certificate valid? Not expired, not revoked
  2. Signature correct? Signed by agent's private key
  3. Within scope? Transaction respects certificate limits AND baseline
// KYA step 4: Verify at action time
async function verifyAction(action) {
  // 1. Check certificate
  const certValid = await kakunin.certificates.verify(action.certificate);
  if (!certValid) return { allowed: false, reason: 'cert_invalid' };

  // 2. Verify signature
  const sigValid = crypto.verify(
    action.payload,
    action.signature,
    certValid.publicKey
  );
  if (!sigValid) return { allowed: false, reason: 'sig_invalid' };

  // 3. Check scope
  const scope = certValid.scope;
  if (action.size > scope.maxTransactionSize) {
    return { allowed: false, reason: 'exceeds_cert_scope' };
  }

  // 4. Check baseline
  const baseline = await kakunin.monitoring.getBaseline(action.agentId);
  const riskScore = computeAnomalyScore(action, baseline);
  if (riskScore > 0.75) {
    return { allowed: false, reason: 'anomaly_threshold', riskScore };
  }

  return { allowed: true };
}

KYA Implementation Architecture

Typical Deployment: Kubernetes + Sidecar

apiVersion: v1
kind: Pod
metadata:
  name: trading-bot-pod
spec:
  containers:
  # Main agent container
  - name: agent
    image: myrepo/trading-bot:v2.1.0
    env:
    - name: AGENT_ID
      value: trading_bot_eu_v2
    - name: KAKUNIN_API_KEY
      valueFrom:
        secretKeyRef:
          name: kakunin-secrets
          key: api-key
    volumeMounts:
    - name: cert-volume
      mountPath: /var/certs
      readOnly: true

  # KYA enforcement sidecar
  - name: kya-enforcer
    image: kakunin/kya-enforcer:latest
    env:
    - name: AGENT_ID
      value: trading_bot_eu_v2
    - name: BASELINE_REFRESH_INTERVAL
      value: "3600"  # 1 hour
    - name: ANOMALY_CHECK_INTERVAL
      value: "60"    # 60 seconds
    volumeMounts:
    - name: cert-volume
      mountPath: /var/certs
      readOnly: true
    ports:
    - containerPort: 8443
      name: kya-api

  volumes:
  - name: cert-volume
    projected:
      sources:
      - secret:
          name: agent-certificate
          items:
          - key: cert.pem
            path: cert.pem
          - key: key-arn.txt
            path: kms-key-arn.txt

Agent calls KYA enforcer for every significant action:

// In agent code
async function executeTrade(tradeRequest) {
  // Call KYA sidecar to verify + sign
  const verified = await fetch('http://localhost:8443/verify-and-sign', {
    method: 'POST',
    body: JSON.stringify(tradeRequest),
  });

  if (!verified.ok) {
    console.error('KYA rejection:', await verified.text());
    return; // Trade blocked
  }

  const { signature, riskScore } = await verified.json();

  // Submit to exchange with proof
  const response = await fetch('https://api.exchange.com/v1/trades', {
    method: 'POST',
    headers: {
      'X-Agent-Certificate': fs.readFileSync('/var/certs/cert.pem'),
      'X-Agent-Signature': signature,
      'X-Risk-Score': riskScore.toString(),
    },
    body: JSON.stringify(tradeRequest),
  });

  return response.json();
}

Behavioral Profiling: Deep Dive

Establishing Baseline

Baseline should be established over 1–2 weeks of production observation:

// Week 1: Collect behavior samples
const samples = await kakunin.monitoring.getSamples(agent.id, {
  startTime: Date.now() - 7 * 24 * 60 * 60 * 1000,  // 7 days
  metrics: ['transaction_size', 'frequency', 'market', 'counterparty', 'time_of_day'],
});

// Compute percentiles
const baseline = {
  transaction_size: {
    p25: 15000,
    p50: 25000,
    p75: 40000,
    p99: 48000,
  },
  transactions_per_hour: {
    p50: 8,
    p95: 15,  // Allow for busy periods
    p99: 20,  // Strict ceiling
  },
  preferred_markets: ['EUR_USD', 'GBP_EUR'],  // 95%+ of volume
  allowed_time_windows: [
    { day: 'MON-FRI', start: '08:00', end: '17:00', tz: 'UTC' },
    // No weekend trading
  ],
};

await kakunin.monitoring.setBaseline(agent.id, baseline);

Anomaly Scoring

Anomaly score = weighted sum of deviations from baseline.

function computeAnomalyScore(action, baseline) {
  let score = 0;

  // Size anomaly (weight: 0.35)
  const sizePercentile = percentileRank(action.size, baseline.transaction_size);
  if (sizePercentile > 0.98) {
    score += 0.35 * Math.min(1.0, (sizePercentile - 0.98) * 50);
  }

  // Frequency anomaly (weight: 0.25)
  const hourlyFreq = getHourlyTransactionCount(action.agentId);
  if (hourlyFreq > baseline.transactions_per_hour.p99) {
    score += 0.25 * Math.min(1.0, (hourlyFreq / baseline.transactions_per_hour.p99) - 1);
  }

  // Market anomaly (weight: 0.20)
  if (!baseline.preferred_markets.includes(action.market)) {
    score += 0.20;  // 20% boost for trading outside normal markets
  }

  // Time-of-day anomaly (weight: 0.15)
  const currentTime = getCurrentTime();
  if (!isWithinTradingHours(currentTime, baseline)) {
    score += 0.15;  // Trading outside business hours
  }

  // Geographic anomaly (weight: 0.05)
  if (action.region !== baseline.allowedRegions[0]) {
    score += 0.05;
  }

  return Math.min(1.0, score);
}

Regulatory Alignment

EU AI Act (Articles 13, 26, 29)

KYA addresses "appropriate human oversight" requirements:

RequirementKYA Implementation
Operator identity documentedX.509 certificate with Kakunin issuer
Authority limits enforcedScope policy in certificate + runtime enforcement
Capability changes loggedAudit trail of certificate rotations
Behavior monitored continuouslyBaseline + anomaly detection
Automatic halt on anomalyPre-revocation warning → certificate revoke

MiCA (Articles 67–72)

KYA provides the "governance, risk and internal control framework":

ArticleKYA Fulfillment
67 — Governance frameworkBaseline defines authority, anomaly detection = continuous risk assessment
70 — Segregation of dutiesAgent identity ≠ operator identity; certificate issued by Kakunin
71 — Record-keepingAudit log for every action + signature proof
72 — Testing & incident responseBaseline captures behavior over time; anomaly detection triggers testing

Lifecycle: From Deployment to Revocation

Phase 1: Bootstrap (Days 1–3)

Agent deployed with certificate. High anomaly thresholds (0.95+) to avoid false positives.

const agent = await kakunin.agents.create({ name: 'trading_bot_v2' });
const cert = await kakunin.agents.getCertificate(agent.id, {
  bootstrapMode: true,  // Permissive anomaly detection
  anomalyThreshold: 0.95,  // 95% confidence required to flag
  validityDays: 7,  // Short-lived bootstrap cert
});

Phase 2: Profiling (Days 4–14)

Collect 7–10 days of normal operations. Establish baseline.

// Day 7: Review behavior samples
const stats = await kakunin.monitoring.analyzeWeek(agent.id);
console.log('Median trade size:', stats.transaction_size.p50);
console.log('Hourly avg:', stats.transactions_per_hour.p50);

// Day 14: Lock in baseline
await kakunin.monitoring.setBaseline(agent.id, deriveBaseline(stats));

// Rotate to production certificate
const prodCert = await kakunin.agents.getCertificate(agent.id, {
  validityDays: 365,
  anomalyThreshold: 0.75,  // Standard threshold
});

Phase 3: Production (Ongoing)

Continuous monitoring. Anomaly score checked at each action.

Score < 0.3: Normal. Action allowed.
Score 0.3–0.75: Medium risk. Log warning, continue monitoring.
Score > 0.75: High risk. Issue pre-revocation warning; block action if score > 0.85.

if (riskScore > 0.75) {
  await kakunin.notifications.sendPreRevocationWarning(agent.id, {
    score: riskScore,
    reason: 'anomaly_threshold_exceeded',
    action: action,
    grace_period_seconds: 300,  // 5 minutes to investigate
  });

  // Schedule automatic revocation if no human ACK
  if (riskScore > 0.85) {
    await kakunin.monitoring.scheduleAutoRevocation(agent.id, {
      delay_seconds: 300,
      notification_sent: true,
    });
  }
}

Phase 4: Incident & Recovery

If certificate revoked:

// Post-revocation: Launch replacement
const replacementAgent = await kakunin.agents.create({
  name: 'trading_bot_v2_replacement',
  replaces: originalAgent.id,
  inheritBaseline: true,  // Reuse normal behavior profile
});

Monitoring Dashboard Metrics

KYA-enabled platforms expose these metrics to operators:


What's Next?

KYA is the foundation for autonomous agent governance. It makes regulatory compliance demonstrable: you can show regulators baseline data, anomaly detection logic, and complete audit trails proving the agent stayed within bounds.

Ready to implement KYA? See: