Skip to content

About

TypeScript/JavaScript SDK for AI Agent Security - Drop-in security for LangChain, CrewAI, AutoGPT and custom agents

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Latest commit

 

History

93 Commits

Folders and files

TealTiger Logo

TealTiger SDK

The first open-source AI agent security SDK with client-side guardrails 🛡️

npm version npm downloads Tests License: Apache 2.0 TypeScript v1.6.1 Discord

📖 Read the introduction blog post | 📚 Documentation

What's New in v1.6.1

  • tealtiger/reliability, tealtiger/secrets, tealtiger/verify are now importable. All three shipped in the package but were exported from nowhere, so no consumer could reach them. Retry budgets and circuit breakers, secret detection with confidence scoring, and the red-team / golden-test / SARIF evidence tooling.
  • PolicyMode, DecisionAction and ReasonCode are usable as values. They are enums, but were re-exported as types only, so PolicyMode.ENFORCE did not work.
  • Every provider subpath now delivers its client. tealtiger/providers/mistral and tealtiger/providers/cohere resolved but omitted TealMistral and TealCohere. TealMultiProvider is also exported now.
  • Removed five provider subpaths that never worked — providers/{groq,deepseek,together,hf-tgi,xai} were listed in exports but never built, so importing them failed with module-not-found.

Observe Mode (Zero-Config Adoption)

observe() — one line to instrument any LLM client with full visibility and an instant kill switch:

  • observe(client) — Zero-config proxy wrapping for any of 12 supported LLM providers
  • Automatic Cost Tracking — Per-request, per-session, per-agent cost accumulation across all providers
  • Behavioral Baseline — Statistical profiling (P50/P95/P99 latency, token distribution, cost patterns)
  • PII Detection (REPORT_ONLY) — Passive PII scanning without blocking — visibility before enforcement
  • freeze() / unfreeze() — Instant kill switch to halt any agent immediately, zero policy required
  • Structured Audit Trail — Every call logged with correlation IDs, cost, latency, and governance metadata
  • Governance Dashboard — Real-time overview with KPI metrics, defense pipeline, canary alerts, agent matrix
  • Under 5ms overhead — All instrumentation is in-process, deterministic, and offline-capable
npm install tealtiger

🚀 Quick Start

npm install tealtiger
import { TealOpenAI, GuardrailEngine, PIIDetectionGuardrail, PromptInjectionGuardrail } from 'tealtiger';

// Set up guardrails
const engine = new GuardrailEngine();
engine.registerGuardrail(new PIIDetectionGuardrail());
engine.registerGuardrail(new PromptInjectionGuardrail());

// Create guarded client — drop-in replacement for OpenAI
const client = new TealOpenAI({
  apiKey: process.env.OPENAI_API_KEY,
  agentId: 'my-agent',
  guardrailEngine: engine
});

const response = await client.chat.completions.create({
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Hello!' }]
});

console.log(response.choices[0].message.content);
console.log('Guardrails passed:', response.security?.guardrailResult?.passed);

🌐 Supported Providers

Eight guarded provider clients. Four are available from the package root; the rest import from their provider subpath, which also keeps bundles smaller.

Provider Client Import from Models
OpenAI TealOpenAI tealtiger GPT-4, GPT-3.5 Turbo
Anthropic TealAnthropic tealtiger Claude 3, Claude 2
Azure TealAzureOpenAI tealtiger GPT-4, GPT-3.5
Ollama TealOllama tealtiger Local / self-hosted models
Google TealGemini tealtiger/providers/gemini Gemini Pro, Ultra
AWS TealBedrock tealtiger/providers/bedrock Claude, Titan, Jurassic, Command, Llama
Mistral TealMistral tealtiger/providers/mistral Large, Medium, Small, Mixtral
Cohere TealCohere tealtiger/providers/cohere Command, Embed
import { TealOpenAI } from 'tealtiger';
import { TealGemini } from 'tealtiger/providers/gemini';

Multi-Provider Orchestration

import { TealMultiProvider, TealOpenAI, TealAnthropic } from 'tealtiger';

const multiProvider = new TealMultiProvider({
  strategy: 'priority',      // or 'round-robin', 'cost', 'use-case'
  enableFailover: true,
  maxFailoverAttempts: 3
});

multiProvider.registerProvider({
  type: 'openai',
  name: 'openai-primary',
  client: new TealOpenAI({ apiKey: 'key' }),
  priority: 1
});

multiProvider.registerProvider({
  type: 'anthropic',
  name: 'anthropic-backup',
  client: new TealAnthropic({ apiKey: 'key' }),
  priority: 2
});

// Automatic failover if primary fails
const response = await multiProvider.chat({
  messages: [{ role: 'user', content: 'Hello' }]
});

🛡️ Key Features

TealEngine — Policy Evaluation

Deterministic tool-allowlist enforcement. Same input and policy produce the same decision every time, with no model in the decision path.

import { TealEngine, PolicyMode, DecisionAction, ReasonCode } from 'tealtiger';

// Policies are the FIRST positional argument; mode goes in the options object.
const engine = new TealEngine(
  {
    tools: {
      file_delete: { allowed: false },
      search: { allowed: true }
    }
  },
  { mode: { default: PolicyMode.ENFORCE } }   // or MONITOR, REPORT_ONLY
);

// evaluateWithMode returns a Decision. (evaluate() returns the lower-level
// PolicyEvaluationResult, which has no `action` field.)
const decision = engine.evaluateWithMode({
  agentId: 'agent-001',
  action: 'tool.execute',
  tool: 'file_delete'
});

switch (decision.action) {
  case DecisionAction.DENY:
    // reason_codes: [POLICY_VIOLATION, TOOL_NOT_ALLOWED]
    // triggering_clause: 'tools.file_delete.allowed'
    throw new ToolNotAllowedError(decision.reason);
  case DecisionAction.ALLOW:
    await executeTool();
    break;
}

triggering_clause names the single clause that produced the decision. It distinguishes a tool denied by an explicit allowed: false (tools.<tool>.allowed) from one denied because it is absent from the policy (tools.<tool>.absent). Both carry TOOL_NOT_ALLOWED; they are different policy facts.

Decision fields: action (ALLOW, DENY, REDACT, TRANSFORM, REQUIRE_APPROVAL, DEGRADE), reason_codes, triggering_clause, risk_score (0-100), correlation_id, metadata

What this engine does and does not enforce

Stated explicitly, because earlier revisions of this README implied more:

Policy section State
tools Enforced. Specified and verified against the shared conformance corpus — 16/16, run on every build.
codeExecution Partially wired. The language is read from context.metadata.language, which RequestContext does not declare, so an unset language resolves to 'unknown' and denies on allowedLanguages before any blocked-function check runs. Do not rely on it.
content (PII, moderation) Not implemented. The clause returns allow unconditionally. Use TealGuard for PII and injection.
behavioral Compares a supplied cost against a daily limit. No accumulation across requests; rate limits are not enforced.

risk_score has no severity model behind it: it is 0 on any allow and a flat value derived from the count of triggered clauses otherwise. Do not route on its magnitude.

TealGuard — Security Guardrails

Client-side guardrails that run in milliseconds with no server dependency:

import { GuardrailEngine, PIIDetectionGuardrail, PromptInjectionGuardrail, ContentModerationGuardrail } from 'tealtiger';

const engine = new GuardrailEngine({ parallelExecution: true, timeout: 5000 });

engine.registerGuardrail(new PIIDetectionGuardrail({ action: 'redact' }));
engine.registerGuardrail(new PromptInjectionGuardrail({ sensitivity: 'high' }));
engine.registerGuardrail(new ContentModerationGuardrail({ threshold: 0.7 }));

const result = await engine.execute(userInput);
console.log('Passed:', result.passed);
console.log('Risk Score:', result.riskScore);

Detects: PII (emails, phones, SSNs, credit cards), prompt injection, jailbreaks, harmful content, custom patterns.

TealCircuit — Circuit Breaker

Cascading failure prevention with automatic failover:

import { TealCircuit } from 'tealtiger';

const circuit = new TealCircuit({
  failureThreshold: 5,     // consecutive failures before opening
  timeout: 30000,          // ms to wait before attempting to close
  halfOpenRequests: 3      // successes in half-open before closing
});

// Wraps provider calls with circuit breaker protection
const response = await circuit.execute(() =>
  client.chat.completions.create({ model: 'gpt-4', messages })
);

TealAudit — Audit Logging & Redaction

Versioned audit events with security-by-default PII redaction:

import { TealAudit, RedactionLevel, ConsoleOutput } from 'tealtiger';

const audit = new TealAudit({
  outputs: [new ConsoleOutput()],   // or CustomOutput for your own sink
  config: {
    input_redaction: RedactionLevel.HASH,    // SHA-256 hash + size (default)
    output_redaction: RedactionLevel.HASH,
    detect_pii: true,
    debug_mode: false
  }
});

Redaction levels: HASH (default, production-safe), SIZE_ONLY, CATEGORY_ONLY, FULL, NONE (debug only).

Correlation IDs & Traceability

End-to-end request tracking across all components:

import { ContextManager } from 'tealtiger';

const context = ContextManager.createContext({
  tenant_id: 'acme-corp',
  app: 'customer-support',
  env: 'production'
});

// Context propagates through TealEngine, TealAudit, and all providers
const response = await client.chat.create({
  model: 'gpt-4',
  messages: [{ role: 'user', content: 'Hello' }],
  context: context
});

// Query audit logs by correlation_id
const events = audit.query({ correlation_id: context.correlation_id });

Features: Auto-generated UUID v4 correlation IDs, OpenTelemetry-compatible trace IDs, HTTP header propagation, multi-tenant support.

Policy Test Harness

Validate policy behavior before production deployment:

import { PolicyTester } from 'tealtiger';

// PolicyTester holds the policies under test — not an engine.
const tester = new PolicyTester(myPolicies);

// Check a single request against the loaded policies
const result = tester.testRequest({
  toolName: 'file_delete',
  parameters: {},
  context: { agentId: 'support-001' }
});
console.log('Allowed:', result.allowed);

// Or run a suite of requests
const report = tester.runTestSuite(myTestSuite);

// Generate candidate test cases from a policy
const cases = tester.generateTestCases(myPolicies[0]);

Note: the Python SDK's policy-test API differs — it uses PolicyTestRunner(engine) with run_suite(). The two are not interchangeable.

# CLI usage
npx tealtiger test ./policies/*.test.json --coverage --format=junit --output=./results.xml

Cost Tracking & Budget Management

Track costs across 50+ models and enforce spending limits:

import { CostTracker, BudgetManager, InMemoryCostStorage } from 'tealtiger';

const storage = new InMemoryCostStorage();
const tracker = new CostTracker({ enabled: true });
const budgetManager = new BudgetManager(storage);

budgetManager.createBudget({
  name: 'Daily GPT-4 Budget',
  limit: 10.0,
  period: 'daily',
  alertThresholds: [50, 75, 90, 100],
  action: 'block',
  enabled: true
});

// Estimate before request
const estimate = tracker.estimateCost('gpt-4', { inputTokens: 1000, outputTokens: 500 }, 'openai');

// Check budget
const check = await budgetManager.checkBudget('agent-123', estimate);
if (!check.allowed) {
  console.log(`Blocked by: ${check.blockedBy?.name}`);
}

🛡️ OWASP Top 10 for Agentic Applications Coverage

ASI Vulnerability Coverage Components
ASI01 Goal Hijacking & Prompt Injection 🟡 Partial TealGuard
ASI02 Tool Misuse & Unauthorized Actions 🟢 Full TealEngine
ASI03 Identity & Access Control Failures 🟡 Partial TealEngine
ASI04 Supply Chain Vulnerabilities 🔧 Support TealAudit
ASI05 Unsafe Code Execution 🟡 Partial TealEngine
ASI06 Memory & Context Corruption ❌ Not reachable —
ASI07 Inter-Agent Communication Security ❌ Platform N/A
ASI08 Cascading Failures & Resource Exhaustion 🟢 Full TealCircuit
ASI09 Harmful Content Generation 🔧 Support TealGuard
ASI10 Rogue Agent Behavior 🟢 Full TealAudit

Revised 2026-11. This table previously claimed "7 out of 10" with 🟢 Full coverage of ASI03, ASI05 and ASI06. Those were downgraded after the policy engine was measured against the shared conformance corpus. What changed and why:

  • ASI02 remains Full, and is now the only engine row with evidence behind it: tool allowlist is specified, implemented and verified 16/16 against the conformance corpus on every build.
  • ASI01 drops TealEngine. Its content clause returns allow unconditionally, so injection coverage rests entirely on TealGuard.
  • ASI03 → Partial. Identity policy evaluates, but it is unspecified and has no conformance coverage.
  • ASI05 → Partial. The code-execution clause denies on a language precondition before reaching blocked-function detection, because the language is read from context.metadata.language, which RequestContext does not declare.
  • ASI06 → Not reachable. Memory governance is a separate subsystem from the policy engine, so the engine attribution was wrong either way. But TealMemory also cannot be imported: it is absent from the root export and from exports in package.json, and dist/memory/ contains only .d.ts declarations with no emitted JavaScript. It will type-check and fail at runtime. This is the same declaration-only build gap that affected reliability, secrets and verify before 1.6.0, and it is tracked separately from this correction.

Coverage claims for an engine clause are only marked Full where a conformance suite demonstrates it. That is a deliberately higher bar than the one this table previously used.

📖 Complete OWASP ASI Mapping | OWASP Top 10 for Agentic Applications

🎯 Use Cases

  • Customer Support Bots — Protect customer PII
  • Healthcare AI — HIPAA compliance
  • Financial Services — Prevent data leakage
  • E-commerce — Secure payment information
  • Enterprise AI — Policy enforcement and audit trails
  • Education Platforms — Content safety

📚 Documentation

🤝 Contributing

We welcome contributions! Please see our Contributing Guide.

📄 License

Apache 2.0 — see LICENSE

🔗 Links


Made with ❤️ by the TealTiger team

About

TypeScript/JavaScript SDK for AI Agent Security - Drop-in security for LangChain, CrewAI, AutoGPT and custom agents

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages