npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

saop-sdk

v1.0.2

Published

SAOP - Stateless AI Orchestration Protocol: Secure multi-provider AI SDK & CLI

Readme

SAOP — Stateless AI Orchestration Protocol

Vendor-agnostic enterprise AI orchestration. 50 providers. 6 privacy modules. One CLI.

SAOP is a TypeScript SDK and autonomous CLI agent that sits between your application and the AI provider landscape. It routes requests to the optimal provider, enforces data-privacy transformations before any token leaves your environment, and gives you a full audit trail — all from a single saop command that works like Claude Code.


Contents


What SAOP Does

| Problem | SAOP Solution | |---------|---------------| | Locked into one AI provider | Route across 50 providers with one API call | | PII sent to external APIs in plaintext | SPV module redacts before transmission, remaps on return | | No visibility into cost / latency | QDP scores every provider; full metrics in every response | | Stylometric re-identification risk | LFO obfuscates writing style before sending | | No resilience when providers go down | SHPT circuit breaker + exponential backoff retry | | Compliance requirements (GDPR/HIPAA) | CTPM stores session memory AES-256-GCM encrypted, tagged by compliance framework | | Unknown AI integration opportunities | Codebase scanner + detector maps your repo to 50 providers |


Architecture Overview

┌─────────────────────────────────────────────────────────────────┐
│                     saop CLI / SDK                              │
│                                                                 │
│  User Input ──► SPV ──► LFO ──► QDP ──► DPS ──► SHPT ──► CTPM │
│                  │                │               │             │
│               Redact PII      Route to        Retry +          │
│               + entity map    best provider   circuit break     │
└────────────────────────────────┬────────────────────────────────┘
                                 │
          ┌──────────────────────┼──────────────────────┐
          │                      │                      │
     OpenAI / Anthropic     Cohere / Gemini       + 47 more

Request flow:

1. SPV  — detect & redact PII, create entity map
2. LFO  — apply lexical/syntactic perturbation
3. QDP  — score providers → select optimal
4. DPS  — optionally split prompt across N providers
5. SHPT — invoke with retry + circuit breaker
6. SPV  — remap entities back into output
7. CTPM — store session memory (encrypted)

Installation

Prerequisites

  • Node.js ≥ 18
  • npm ≥ 9

Clone and install

git clone <repo-url> saop-sdk
cd saop-sdk
npm install
npm run build

Global CLI (optional)

npm link
saop --version

As an npm package

npm install saop-sdk

Environment Variables

| Variable | Required | Description | |----------|----------|-------------| | ANTHROPIC_API_KEY | Yes (agent mode) | Powers the Claude reasoning brain in the CLI agent | | OPENAI_API_KEY | Optional | Enables real OpenAI calls (falls back to simulation) | | GROQ_API_KEY | Optional | Enables real Groq calls (falls back to simulation) | | GOOGLE_AI_API_KEY | Optional | Enables real Gemini calls | | SAOP_DEBUG | Optional | Set to 1 to print CTPM audit logs |

Set them in your shell:

export ANTHROPIC_API_KEY=sk-ant-...
export OPENAI_API_KEY=sk-...
export GROQ_API_KEY=gsk_...

Or create a .env file and load it:

# .env
ANTHROPIC_API_KEY=sk-ant-...
OPENAI_API_KEY=sk-...
GROQ_API_KEY=gsk_...
source .env && node bin/saop.js

CLI Agent — Quick Start

SAOP's default mode is an autonomous agentic CLI — Claude drives the interaction and calls SAOP tools automatically, exactly like Claude Code.

node bin/saop.js
# or, after npm link:
saop

On startup the agent:

  1. Detects whether the current directory is a software project
  2. Auto-scans it (language detection, framework detection, pattern analysis)
  3. Injects the codebase summary into Claude's context
  4. Opens the REPL prompt
╔══════════════════════════════════════════════════════════════╗
║  SAOP ─ Stateless AI Orchestration Protocol                  ║
║  6 Core Modules · 50 Providers · Agentic Pipeline            ║
╚══════════════════════════════════════════════════════════════╝
Session: a3f1bc2d  Privacy: HIGH  Providers: 50

  Detected project at /your/project
  Indexed 142 files · TypeScript · React, Express

  >

Example conversations

Scan and discover AI opportunities:

> scan my codebase and tell me what AI integrations make sense

Claude calls scan_codebasefind_integrations automatically and returns a prioritised list.

Run the privacy pipeline:

> protect this text using SPV: "John Smith at [email protected] called about SSN 123-45-6789"

Claude calls spv_protect and shows exactly what was redacted and with what strategy.

Find the cheapest compliant provider:

> which provider should I use for a HIPAA workload under 2000 tokens with max $0.01 cost?

Claude calls qdp_route with the constraints and returns a scored ranking.

Run the full pipeline:

> run the SAOP pipeline on this prompt at MAXIMUM privacy: "Summarize patient records for Dr. Lee"

Claude calls run_pipeline and shows the full provenance — modules applied, provider used, cost, latency.

Demo mode (no API key):

Without ANTHROPIC_API_KEY, the agent falls back to deterministic demo responses for scan, integrations, and provider queries.


CLI Commands Reference

saop / node bin/saop.js

Start the autonomous agent (default):

node bin/saop.js
node bin/saop.js run
saop                    # after npm link

Start the legacy menu-driven CLI:

node bin/saop.js run --legacy

saop analyze [path]

Scan a codebase and save a JSON report without entering the agent.

node bin/saop.js analyze .
node bin/saop.js analyze /path/to/project
node bin/saop.js analyze . --output my-report.json --privacy HIGH

| Flag | Default | Description | |------|---------|-------------| | -o, --output <file> | ./saop-report.json | Output file path | | -p, --privacy <level> | HIGH | Privacy level for analysis |

The JSON report contains:

{
  "timestamp": "2026-04-23T...",
  "analysis": {
    "total_files": 142,
    "primary_languages": ["TypeScript", "JavaScript"],
    "frameworks": ["React", "Express"],
    "patterns": [...],
    "existing_ai_integrations": []
  },
  "opportunities": [
    {
      "priority": "HIGH",
      "provider": "OpenAI",
      "use_case": "Chat completion for user support",
      "saop_modules": ["SPV", "QDP", "SHPT"],
      ...
    }
  ]
}

saop providers

List the full 50-provider catalog:

node bin/saop.js providers
node bin/saop.js providers --category text_llm
node bin/saop.js providers -c vision

Valid categories: text_llm · code · vision · audio · video · search_knowledge · agentic_workflow · optimization · personalization


saop modules

Print the 6 core module descriptions:

node bin/saop.js modules

Slash Commands (inside the agent)

Type these directly at the > prompt:

| Command | Description | |---------|-------------| | /help | Show all commands | | /clear | Clear conversation history and cached codebase scan | | /providers | Full provider catalog grouped by category | | /modules | 6 SAOP core modules with descriptions | | /privacy MAXIMUM\|HIGH\|MEDIUM\|LOW | Change session privacy level | | /compliance GDPR,HIPAA,SOC2 | Set active compliance tags | | /scan [path] | Scan a directory and update context | | /status | Session stats — turns, cost, tokens, memory | | /export | Save full session to saop-session-<id>.json | | /exit | Exit the agent |


The 6 Core Modules

SPV — Secure Prompt Virtualization

Detects and redacts PII before any text leaves your environment. Remaps entities back into provider output.

Detects: Email · Phone · SSN · Credit card · IP address · Date · Address · Person names

Redaction strategies by privacy level:

| Level | Strategy | Example | |-------|----------|---------| | LOW / MEDIUM | Placeholder | [EMAIL_1], [PERSON_1] | | HIGH | Pseudonymize | [PSEUDO_a3f1bc] (keyed SHA-256) | | MAXIMUM | Generalize | [CONTACT_INFO] |

import { SPVModule } from 'saop-sdk';

const spv = new SPVModule();
spv.resetCounters();

const result = spv.process(
  'Call John at [email protected] or 555-123-4567',
  'HIGH'
);

console.log(result.anonymized_prompt);
// 'Call [PERSON_1] at [PSEUDO_a3f1bc] or [PSEUDO_9d2e45]'

console.log(result.entities);
// [{ type: 'PERSON', placeholder: '[PERSON_1]', sensitivity: 'HIGH' }, ...]

// Remap provider output back to originals
const restored = spv.remap(providerOutput, result.entity_map);

LFO — Latent Fingerprint Obfuscation

Prevents stylometric re-identification by substituting synonyms and restructuring syntax. Uses a seeded PRNG — same request_id always produces the same obfuscation (safe for retries).

import { LFOModule } from 'saop-sdk';

const lfo = new LFOModule();

const result = lfo.obfuscate(
  'We need to implement this feature quickly to help our users.',
  0.4,           // strength: 0.1 (minimal) → 1.0 (maximum)
  'request-123'  // seed for deterministic output
);

console.log(result.obfuscated);
// 'We require to construct this functionality rapidly to assist our consumers.'
console.log(result.transformations);
// ['lexical_perturbation', 'syntactic_perturbation']

DPS — Distributed Prompt Splitting

Splits a prompt across multiple providers so no single provider sees the full context. Aggregates results back.

Strategies (auto-selected):

| Strategy | When | Aggregation | |----------|------|-------------| | horizontal | Long docs, many providers | Sequential assembly | | vertical | Pipeline tasks | Stage-by-stage | | redundant | Short prompts, need confidence | Majority voting | | hierarchical | Complex multi-step | Plan → execute → synthesize |

import { DPSModule } from 'saop-sdk';

const dps = new DPSModule();

const result = dps.split(
  'Analyze this 10,000-word document and extract key themes...',
  ['openai', 'anthropic', 'cohere'],  // provider IDs
  3                                    // max splits
);

console.log(result.subtasks.length);         // 3
console.log(result.aggregation_strategy);    // 'sequential_assembly'

// After getting subtask results from providers:
const finalOutput = dps.aggregate(subtasksWithResults, result.aggregation_strategy);

QDP — Quantum Decision Pruning

Scores every available provider against a multi-objective function and returns the optimal choice. Uses increasingly sophisticated algorithms as the provider pool grows.

Objective function:

score = 0.35 × (1 − cost) + 0.30 × (1 − latency) + 0.25 × quality + 0.10 × compliance

Algorithms by pool size:

| Pool Size | Algorithm | Description | |-----------|-----------|-------------| | ≤ 3 | Greedy | Single-pass best score | | 4–10 | Simulated Annealing | 100 iterations, T₀=1.0, cooling=0.95 | | 11–20 | Genetic Algorithm | 50 generations, pop=20, mutation=0.1 | | > 20 | QAOA-approximated | Quantum-inspired SA with quantum noise |

import { QDPModule, ProviderRegistry } from 'saop-sdk';

const registry = new ProviderRegistry();
const qdp = new QDPModule();

const result = qdp.optimize(
  registry.list(),   // all 50 providers
  2000,              // estimated tokens
  {
    maxCostUsd: 0.01,
    maxLatencyMs: 2000,
    requiredCompliance: ['HIPAA', 'SOC2'],
  }
);

console.log(result.selected_provider);   // 'anthropic'
console.log(result.optimization_method); // 'genetic'
console.log(result.cost_estimate);       // 0.0045
console.log(result.alternatives);        // ranked list

Tune weights for your use case:

// Cost-optimized profile
qdp.setWeights(0.60, 0.20, 0.15, 0.05);

// Compliance-first profile
qdp.setWeights(0.15, 0.15, 0.20, 0.50);

SHPT — Self-Healing Prompt Tracing

Wraps all provider calls with automatic retry, circuit breaking, and health tracking. Every step is recorded in a cryptographically hashed trace.

Circuit breaker states:

CLOSED ──(5 consecutive failures)──► OPEN
OPEN   ──(30 seconds)──────────────► HALF-OPEN
HALF-OPEN ──(success)──────────────► CLOSED
HALF-OPEN ──(failure)──────────────► OPEN

Retry backoff formula:

delay = min(baseDelay × 2ⁿ × (1 ± 10% jitter), 30,000ms)
import { SHPTModule } from 'saop-sdk';

const shpt = new SHPTModule();

// Wrap any async operation with retry + circuit breaker
const response = await shpt.withRetry(
  () => provider.invoke(prompt, {}),
  'openai',  // provider ID for circuit breaker tracking
  3,         // max attempts
  500        // base delay ms
);

// Update health metrics after call
shpt.updateHealth('openai', latencyMs, success);

// Check provider health
const status = shpt.getHealthStatus('openai');
// 'healthy' | 'degraded' | 'down'

// Validate output
const { valid, issues } = shpt.validateOutput(response.output);

CTPM — Compliance-Tagged Prompt Memory

AES-256-GCM encrypted tiered session memory with a SHA-256 hash chain for tamper evidence. Supports GDPR right-to-erasure, HIPAA data handling, and automatic tier lifecycle management.

Tier lifecycle:

HOT (< 24h, in-memory) ──► WARM (< 30d, in-memory) ──► COLD (> 30d, in-memory)
                                                          │
                                              Auto-purge at retention_days
import { CTPMModule } from 'saop-sdk';

// Provide your own master key for persistence across restarts
const ctpm = new CTPMModule(process.env.CTPM_MASTER_KEY);

// Store encrypted
const entry = ctpm.store(
  'session-abc123',
  JSON.stringify({ user: 'Dr. Lee', context: 'patient record summary' }),
  ['HIPAA', 'SOC2'],
  90  // retain for 90 days
);

console.log(entry.tier);             // 'hot'
console.log(entry.integrity_hash);   // SHA-256 chain hash

// Retrieve decrypted
const memories = ctpm.retrieve('session-abc123', 5);
console.log(memories[0]); // '{"user":"Dr. Lee","context":"..."}'

// GDPR right-to-erasure
const deleted = ctpm.purgeSession('session-abc123');
console.log(`Purged ${deleted} entries`);

// Verify hash chain integrity
const intact = ctpm.verifyIntegrity(entry.id);

// Tier stats
const stats = ctpm.getStats();
// { hot: 3, warm: 0, cold: 0, total: 3 }

50 AI Providers

SAOP registers 50 providers across 9 categories at startup. Three have real adapter implementations; all 50 expose full capability metadata for routing decisions.

| Category | Count | Providers | |----------|-------|-----------| | text_llm | 8 | OpenAI, Anthropic, Google DeepMind, Azure OpenAI, Cohere, Meta AI (Llama), Mistral AI, Groq | | vision | 6 | Google Cloud Vision, Amazon Rekognition, Azure AI Vision, Clarifai, SenseTime, LandingAI | | code | 3 | GitHub Copilot, Codeium, Sourcegraph Cody | | audio | 6 | Amazon Transcribe, AssemblyAI, Deepgram, Speechmatics, ElevenLabs, Retell AI | | video | 3 | Runway, Synthesia, Twelve Labs | | search_knowledge | 7 | Google Vertex AI Search, Azure Cognitive Search, Amazon OpenSearch, Databricks, Snowflake Cortex, Pinecone, Weaviate | | agentic_workflow | 7 | UiPath, Kore.ai, IBM watsonx Orchestrate, Microsoft Power Platform, Google Vertex AI Agents, Relevance AI, CrewAI | | optimization | 7 | NVIDIA cuOpt, AnyLogic, Gurobi, Anaplan, Palantir Foundry, Cosmo Tech, (+ 1) | | personalization | 5 | Amazon Personalize, Dynamic Yield, Algolia Recommend, Nosto, Bloomreach |

Each provider entry includes:

{
  provider_id: 'anthropic',
  name: 'Anthropic',
  category: 'text_llm',
  models: ['claude-opus-4-7', 'claude-sonnet-4-6', 'claude-haiku-4-5'],
  supports_streaming: true,
  supports_function_calling: true,
  max_context_tokens: 200000,
  input_cost_per_1m: 3.0,     // USD
  output_cost_per_1m: 15.0,
  rate_limit_rpm: 50,
  latency_p50_ms: 750,
  latency_p99_ms: 3500,
  geographic_availability: ['US', 'EU', 'APAC'],
  compliance_certifications: ['SOC2', 'HIPAA', 'ISO27001'],
  health_status: 'healthy',
}

Registering a custom provider

import { ProviderRegistry, BaseProviderAdapter } from 'saop-sdk';

class MyProvider extends BaseProviderAdapter {
  capabilities = {
    provider_id: 'my-provider',
    name: 'My Custom LLM',
    category: 'text_llm' as const,
    models: ['my-model-v1'],
    supports_streaming: true,
    supports_function_calling: false,
    max_context_tokens: 32000,
    input_cost_per_1m: 2.0,
    output_cost_per_1m: 8.0,
    rate_limit_rpm: 60,
    latency_p50_ms: 500,
    latency_p99_ms: 2000,
    geographic_availability: ['US'],
    compliance_certifications: ['SOC2'],
    health_status: 'healthy' as const,
  };

  async invoke(prompt: string, params: Record<string, unknown>) {
    // your API call here
    const response = await fetch('https://api.myprovider.com/v1/complete', {
      method: 'POST',
      body: JSON.stringify({ prompt, ...params }),
      headers: { Authorization: `Bearer ${process.env.MY_PROVIDER_KEY}` },
    });
    const data = await response.json();
    return this.buildResponse(data.text, data.input_tokens, data.output_tokens, data.latency_ms);
  }
}

const registry = new ProviderRegistry();
registry.register(new MyProvider());

SDK — Programmatic Usage

Install

npm install saop-sdk

Minimal example

import { SAOPOrchestrator, ProviderRegistry } from 'saop-sdk';

const registry = new ProviderRegistry();
const orchestrator = new SAOPOrchestrator({ privacy_level: 'HIGH' });

// Register all 50 providers
for (const caps of registry.list()) {
  const adapter = registry.get(caps.provider_id);
  if (adapter) orchestrator.registerProvider(adapter);
}

const response = await orchestrator.process({
  version: '1.0',
  request_id: crypto.randomUUID(),
  client_id: 'my-app',
  timestamp: new Date().toISOString(),
  task: { type: 'CHAT', priority: 5 },
  input: {
    prompt: 'Summarize the Q3 financials for patient John Smith (SSN 123-45-6789)',
  },
  policy: {
    privacy_level: 'HIGH',
    compliance_tags: ['HIPAA', 'SOC2'],
    cost_budget_usd: 0.05,
    latency_budget_ms: 5000,
  },
  memory: { encryption: true },
  meta: { session_id: 'session-001' },
});

console.log(response.status);                        // 'SUCCESS'
console.log(response.result.output);                 // remapped output (PII restored)
console.log(response.provenance.workflow_path);      // 'SPV→LFO→QDP→SHPT'
console.log(response.metrics.total_cost_usd);        // 0.0032
console.log(response.audit.privacy_transformations); // [{ type: 'PII_REDACTION', entities_affected: 2 }]

Using modules individually

import { SPVModule, LFOModule, QDPModule, ProviderRegistry } from 'saop-sdk';

// Privacy pipeline
const spv = new SPVModule();
spv.resetCounters();
const spvResult = spv.process(userInput, 'HIGH');

const lfo = new LFOModule();
const lfoResult = lfo.obfuscate(spvResult.anonymized_prompt, 0.4, requestId);

// Provider routing
const registry = new ProviderRegistry();
const qdp = new QDPModule();
const route = qdp.optimize(registry.list(), estimatedTokens, {
  requiredCompliance: ['SOC2'],
  maxCostUsd: 0.02,
});

// Call provider
const adapter = registry.get(route.selected_provider);
const providerResponse = await adapter!.invoke(lfoResult.obfuscated, {});

// Remap PII back
const finalOutput = spv.remap(providerResponse.output, spvResult.entity_map);

Using the CodebaseAgent

import { CodebaseAgent } from 'saop-sdk';

const agent = new CodebaseAgent();
const report = await agent.run('/path/to/project');

console.log(report);  // formatted text report of AI integration opportunities

Codebase Analysis & Integration Discovery

The scanner and detector can be used independently from the CLI:

import { CodebaseScanner, IntegrationDetector } from 'saop-sdk';

const scanner = new CodebaseScanner();
const analysis = await scanner.scan('./my-project');

console.log(analysis.total_files);             // 312
console.log(analysis.primary_languages);       // ['TypeScript', 'Python']
console.log(analysis.frameworks);              // ['React', 'FastAPI']
console.log(analysis.patterns.map(p => p.type));
// ['api_endpoint', 'auth', 'database', 'search']

const detector = new IntegrationDetector();
const opportunities = detector.detect(analysis);

// Sorted: HIGH priority first
opportunities.forEach(opp => {
  console.log(`[${opp.priority}] ${opp.provider} — ${opp.use_case}`);
  console.log(`  Effort: ${opp.implementation_effort}`);
  console.log(`  SAOP modules: ${opp.saop_modules.join(', ')}`);
  console.log(`  Impact: ${opp.estimated_impact}`);
});

Detected patterns: api_endpoint · data_model · auth · database · queue · cache · search · notification · payment · ml_pipeline

Detected frameworks: React · Next.js · Vue · Angular · Express · FastAPI · Django · Spring Boot · NestJS · Prisma · TypeORM · LangChain · OpenAI · Anthropic


Orchestrator Pipeline

SAOPRequest fields

{
  version: '1.0',
  request_id: string,           // UUIDv4 — unique per request
  client_id: string,            // your application identifier
  timestamp: string,            // ISO 8601

  task: {
    type: TaskType,             // CHAT | COMPLETION | SUMMARIZATION | CODE_GENERATION
                                // CODE_ANALYSIS | DATA_ANALYSIS | CLASSIFICATION
                                // EXTRACTION | TRANSLATION | EMBEDDING | CUSTOM
    priority: number,           // 1 (low) to 10 (urgent)
    deadline_ms?: number,       // optional hard deadline
  },

  input: {
    prompt: string,
    context?: string[],         // additional context documents
    parameters?: Record<string, unknown>,
  },

  policy: {
    privacy_level: PrivacyLevel,         // MAXIMUM | HIGH | MEDIUM | LOW
    compliance_tags: ComplianceTag[],    // GDPR | HIPAA | SOC2 | ISO27001 | PCI | CCPA
    cost_budget_usd?: number,
    latency_budget_ms?: number,
    provider_whitelist?: string[],       // only use these provider IDs
    provider_blacklist?: string[],       // exclude these provider IDs
    geographic_restrictions?: string[], // e.g. ['US', 'EU']
  },

  meta: {
    session_id?: string,        // enables CTPM memory for this session
    tenant_id?: string,
    user_id?: string,
  },
}

SAOPResponse fields

{
  status: 'SUCCESS' | 'PARTIAL' | 'FAILURE',

  result: {
    output: string,          // final output with PII remapped
    confidence: number,      // 0–1
  },

  provenance: {
    providers_used: [{
      provider_id: string,
      model_id: string,
      request_tokens: number,
      response_tokens: number,
      latency_ms: number,
      cost_usd: number,
    }],
    transformations_applied: [{ module: string, version: string, parameters: object }],
    workflow_path: string,   // e.g. 'SPV→LFO→QDP→SHPT'
  },

  audit: {
    compliance_tags: ComplianceTag[],
    privacy_transformations: [{ type: string, entities_affected: number, hash: string }],
    audit_trail: string,     // SHA-256 of request + transformations
  },

  metrics: {
    total_latency_ms: number,
    total_cost_usd: number,
    api_calls: number,
    tokens_processed: number,
  },
}

Configuration Reference

import { SAOPOrchestrator } from 'saop-sdk';

const orchestrator = new SAOPOrchestrator({
  privacy_level: 'HIGH',
  compliance_tags: ['SOC2', 'GDPR'],

  enabled_modules: {
    spv: true,    // PII redaction — recommended always on
    lfo: true,    // stylometric obfuscation
    dps: false,   // prompt splitting — enable for MAXIMUM privacy
    qdp: true,    // provider routing
    shpt: true,   // retry + circuit breaker
    ctpm: true,   // encrypted memory
  },

  providers: {
    whitelist: ['anthropic', 'openai'],  // only use these two
    // blacklist: ['meta-ai'],           // or exclude specific ones
    default: 'anthropic',
  },

  cost: {
    max_per_request_usd: 0.50,
    max_monthly_usd: 100,
  },

  performance: {
    max_latency_ms: 10000,
    enable_caching: true,
  },
});

Privacy Levels

| Level | SPV Strategy | LFO Strength | DPS | Best For | |-------|-------------|--------------|-----|----------| | LOW | Placeholder labels | 0.2 | Off | Internal dev/test | | MEDIUM | Placeholder labels | 0.2 | Off | Trusted internal providers | | HIGH | Pseudonymize (SHA-256) | 0.4 | Off | Enterprise SaaS, external APIs | | MAXIMUM | Generalize to type | 0.6 | On | Healthcare, finance, government |


Compliance Support

| Tag | What SAOP Does | |-----|----------------| | GDPR | purgeSession() enables right-to-erasure; PII never sent to providers at HIGH+ | | HIPAA | PHI patterns detected by SPV; Anthropic adapter includes HIPAA certification | | SOC2 | Full audit trail hash in every response; all provider calls traced | | PCI | Credit card patterns redacted by SPV before any API call | | ISO27001 | Asset handling documented in SRS; encryption at rest (CTPM AES-256-GCM) | | CCPA | purgeSession() supports opt-out deletion across all tiers |


Project Structure

saop-sdk/
├── bin/
│   └── saop.js                  CLI entry point (Commander)
├── src/
│   ├── cli/
│   │   ├── agent.ts             Autonomous agentic CLI ← default
│   │   └── index.ts             Legacy menu-driven CLI
│   ├── core/
│   │   ├── types.ts             All TypeScript interfaces
│   │   ├── orchestrator.ts      Pipeline coordinator
│   │   └── modules/
│   │       ├── spv.ts           Secure Prompt Virtualization
│   │       ├── lfo.ts           Latent Fingerprint Obfuscation
│   │       ├── dps.ts           Distributed Prompt Splitting
│   │       ├── qdp.ts           Quantum Decision Pruning
│   │       ├── shpt.ts          Self-Healing Prompt Tracing
│   │       └── ctpm.ts          Compliance-Tagged Prompt Memory
│   ├── providers/
│   │   ├── base.ts              BaseProviderAdapter (extend for custom providers)
│   │   ├── registry.ts          50-provider catalog + makeAdapter factory
│   │   └── adapters/
│   │       ├── openai.ts        Real OpenAI adapter
│   │       ├── anthropic.ts     Real Anthropic adapter
│   │       └── google.ts        Real Google/Gemini adapter
│   ├── agents/
│   │   ├── base-agent.ts        Abstract agent with SAOP tool registration
│   │   └── codebase-agent.ts    Codebase analysis agent
│   ├── utils/
│   │   ├── codebase-scanner.ts  File system + language + pattern scanner
│   │   └── integration-detector.ts  AI opportunity rule engine
│   └── index.ts                 SDK public exports
├── dist/                        Compiled JS + type declarations
├── package.json
├── tsconfig.json
└── README.md

Building from Source

# Install dependencies
npm install

# Type-check only (no output)
npx tsc --noEmit

# Full build → dist/
npm run build

# Development (ts-node, no build required)
npm run dev

TypeScript configuration: ES2020, CommonJS, strict: true, output → dist/.


Troubleshooting

Error: Cannot find module '../dist/cli/agent'

The project hasn't been built yet. Run:

npm run build

No ANTHROPIC_API_KEY found. Running in demo mode.

The agent needs your Anthropic key to use Claude as its reasoning brain:

export ANTHROPIC_API_KEY=sk-ant-...
node bin/saop.js

Provider returns simulated responses

Only OpenAI, Anthropic, and Google have real adapters. All other 47 providers return simulated responses unless you extend BaseProviderAdapter and register your own implementation.

CTPM data lost on restart

CTPM stores data in-memory. To persist across restarts, provide a consistent master key:

// Persist this key securely (e.g. environment variable)
const ctpm = new CTPMModule(process.env.CTPM_MASTER_KEY);

Without a fixed key, a new random key is generated each run and previous data cannot be decrypted.

TypeScript errors after pulling updates

npm install   # pick up any new type packages
npm run build

License

MIT — SpazorLabs LLP


SAOP v1.0.0 — Built by SpazorLabs LLP