@axiorank/ai-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/extract.ts","../../detectors/src/walk.ts","../../detectors/src/canonicalize.ts","../../detectors/src/mask.ts","../../detectors/src/detectors/util.ts","../../detectors/src/detectors/abuse.ts","../../detectors/src/detectors/card.ts","../../detectors/src/detectors/destructive.ts","../../detectors/src/detectors/egress.ts","../../detectors/src/detectors/injection.ts","../../detectors/src/detectors/jailbreak.ts","../../detectors/src/detectors/output-injection.ts","../../detectors/src/detectors/pii.ts","../../detectors/src/detectors/secrets.ts","../../detectors/src/detectors/index.ts","../../detectors/src/scoring.ts","../../detectors/src/tool-risk.ts","../../detectors/src/engine.ts","../../detectors/src/decision.ts","../../sdk/src/inspect.ts","../../sdk/src/errors.ts","../src/guard-result.ts","../src/inspect-client.ts","../src/stream.ts","../src/types.ts","../src/middleware.ts"],"names":["SPECS","b"],"mappings":";AAYO,SAAS,kBAAkB,MAAA,EAAuC;AACvE,EAAA,MAAM,MAAgB,EAAC;AACvB,EAAA,KAAA,MAAW,WAAW,MAAA,EAAQ;AAC5B,IAAA,IAAI,OAAO,OAAA,CAAQ,OAAA,KAAY,QAAA,EAAU;AACvC,MAAA,GAAA,CAAI,IAAA,CAAK,QAAQ,OAAO,CAAA;AACxB,MAAA;AAAA,IACF;AACA,IAAA,KAAA,MAAW,IAAA,IAAQ,QAAQ,OAAA,EAAS;AAClC,MAAA,IAAI,KAAK,IAAA,KAAS,MAAA,EAAQ,GAAA,CAAI,IAAA,CAAK,KAAK,IAAI,CAAA;AAAA,IAC9C;AAAA,EACF;AACA,EAAA,OAAO,GAAA,CAAI,KAAK,IAAI,CAAA;AACtB;AAGO,SAAS,sBACd,OAAA,EACQ;AACR,EAAA,OAAO,OAAA,CACJ,OAAA,CAAQ,CAAC,IAAA,KAAU,KAAK,IAAA,KAAS,MAAA,GAAS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n LanguageModelV4Prompt,\n LanguageModelV4ToolCall,\n} from \"@ai-sdk/provider\";\n\n/**\n * Flatten a language-model prompt into inspectable text. Pulls the string body\n * of system messages and the `text` parts of user/assistant messages (files,\n * tool results, and reasoning are skipped). This is what a prompt-injection,\n * jailbreak, or leaked-secret check runs against.\n */\nexport function extractPromptText(prompt: LanguageModelV4Prompt): string {\n const out: string[] = [];\n for (const message of prompt) {\n if (typeof message.content === \"string\") {\n out.push(message.content);\n continue;\n }\n for (const part of message.content) {\n if (part.type === \"text\") out.push(part.text);\n }\n }\n return out.join(\"\\n\");\n}\n\n/** Concatenate the `text` parts of a generated completion. */\nexport function extractCompletionText(\n content: readonly LanguageModelV4Content[],\n): string {\n return content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\");\n}\n\n/** The tool calls the model proposed in a completion. */\nexport function extractToolCalls(\n content: readonly LanguageModelV4Content[],\n): LanguageModelV4ToolCall[] {\n return content.filter(\n (part): part is LanguageModelV4ToolCall => part.type === \"tool-call\",\n );\n}\n\n/**\n * Parse a tool call's stringified-JSON `input` into an arguments object for\n * inspection. Falls back to wrapping the raw string so a non-JSON body is still\n * scanned rather than dropped.\n */\nexport function parseToolInput(input: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(input);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n return { input: parsed };\n } catch {\n return { input };\n }\n}\n","/**\n * Bounded payload traversal. Maps every string leaf of an arbitrary JSON value\n * through a transform (used to mask secrets in place) while rebuilding arrays\n * and objects into a structural copy. Hard budgets keep the hot path safe\n * against adversarial or accidentally huge payloads.\n */\n\nexport const LIMITS = {\n /** Max object/array nesting inspected before passing values through. */\n maxDepth: 8,\n /** Max number of string leaves inspected. */\n maxLeaves: 2000,\n /** Max total bytes of string content inspected. */\n maxTotalBytes: 256 * 1024,\n /** Per-leaf: only the first N chars are scanned by detectors. */\n maxLeafScan: 64 * 1024,\n /** Max signals retained per evaluation (bounds the stored array). */\n maxSignals: 50,\n // Decode-variant budgets (lib/risk/normalize.ts) - per inspectContent call.\n /** Max nested decode layers unwrapped (base64-in-base64 stops here). */\n maxDecodeDepth: 3,\n /** Max bytes a single decoded variant may produce (gzip output cap). */\n maxDecodedBytesPerLeaf: 16 * 1024,\n /** Max total decoded bytes across the whole payload. */\n maxDecodedBytesTotal: 64 * 1024,\n /** Max decode attempts across the whole payload. */\n maxDecodeAttempts: 160,\n /** Max scan variants derived from one leaf. */\n maxVariantsPerLeaf: 6,\n} as const;\n\nexport interface WalkState {\n leaves: number;\n bytes: number;\n /** Set when a budget was hit and inspection was cut short. */\n truncated: boolean;\n}\n\nexport type LeafTransform = (\n path: string,\n value: string,\n state: WalkState,\n) => string;\n\n/**\n * Recursively map every string leaf of `value` through `fn`, rebuilding\n * containers so the result is a structural copy. Once a depth/leaf/byte budget\n * is exhausted, remaining leaves pass through unchanged and `state.truncated`\n * is set. Non-string, non-container values are returned as-is.\n */\nexport function transformStrings(\n value: unknown,\n fn: LeafTransform,\n state: WalkState,\n path = \"\",\n depth = 0,\n): unknown {\n if (typeof value === \"string\") {\n if (state.leaves >= LIMITS.maxLeaves || state.bytes >= LIMITS.maxTotalBytes) {\n state.truncated = true;\n return value;\n }\n state.leaves += 1;\n state.bytes += value.length;\n return fn(path, value, state);\n }\n\n if (Array.isArray(value)) {\n if (depth >= LIMITS.maxDepth) {\n state.truncated = true;\n return value;\n }\n return value.map((item, i) =>\n transformStrings(item, fn, state, `${path}[${i}]`, depth + 1),\n );\n }\n\n if (value !== null && typeof value === \"object\") {\n if (depth >= LIMITS.maxDepth) {\n state.truncated = true;\n return value;\n }\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const childPath = path ? `${path}.${key}` : key;\n out[key] = transformStrings(child, fn, state, childPath, depth + 1);\n }\n return out;\n }\n\n return value;\n}\n","/**\n * Pure (no-IO) unicode normalization for the content-inspection engine.\n *\n * Attackers veil payloads behind homoglyphs and zero-width characters so the\n * detector regexes never see them. `canonicalize` folds those veils back to\n * plain Latin/ASCII. This file is dependency-free and runs in every runtime;\n * the heavier nested-encoding decode (base64 / hex / gzip) lives in the\n * Node-only `./node/decode` because it needs `Buffer` / `node:zlib`.\n */\n\nimport type { NormalizedVariant } from \"./types\";\nimport { LIMITS } from \"./walk\";\n\n/**\n * Invisible characters that split detector keywords without changing what a\n * human (or model) reads: soft hyphen, combining grapheme joiner, zero-width\n * spaces/joiners, bidi controls, word joiner family, BOM.\n */\nconst INVISIBLES =\n /[\\u00AD\\u034F\\u200B-\\u200F\\u202A-\\u202E\\u2060-\\u2064\\u206A-\\u206F\\uFEFF]/g;\n\n/**\n * Conservative homoglyph map: only Cyrillic/Greek letters that render\n * indistinguishably from their Latin counterparts in common fonts. NFKC\n * already folds fullwidth and mathematical alphanumerics; this covers the\n * cross-script cases NFKC deliberately leaves alone.\n */\nconst CONFUSABLES: Record<string, string> = {\n // Cyrillic lowercase\n а: \"a\",\n е: \"e\",\n о: \"o\",\n р: \"p\",\n с: \"c\",\n у: \"y\",\n х: \"x\",\n і: \"i\",\n ј: \"j\",\n ѕ: \"s\",\n ԁ: \"d\",\n // Cyrillic uppercase\n А: \"A\",\n В: \"B\",\n Е: \"E\",\n К: \"K\",\n М: \"M\",\n Н: \"H\",\n О: \"O\",\n Р: \"P\",\n С: \"C\",\n Т: \"T\",\n У: \"Y\",\n Х: \"X\",\n // Greek lowercase\n α: \"a\",\n ι: \"i\",\n ν: \"v\",\n ο: \"o\",\n ρ: \"p\",\n υ: \"u\",\n // Greek uppercase\n Α: \"A\",\n Β: \"B\",\n Ε: \"E\",\n Ζ: \"Z\",\n Η: \"H\",\n Ι: \"I\",\n Κ: \"K\",\n Μ: \"M\",\n Ν: \"N\",\n Ο: \"O\",\n Ρ: \"P\",\n Τ: \"T\",\n Υ: \"Y\",\n Χ: \"X\",\n};\n\nconst CONFUSABLE_RE = new RegExp(`[${Object.keys(CONFUSABLES).join(\"\")}]`, \"g\");\n\n/** NFKC + strip invisibles + fold cross-script homoglyphs to Latin. */\nexport function canonicalize(value: string): string {\n return value\n .normalize(\"NFKC\")\n .replace(INVISIBLES, \"\")\n .replace(CONFUSABLE_RE, (ch) => CONFUSABLES[ch] ?? ch);\n}\n\n/**\n * The universal (crypto/Buffer-free) variant scanner: derives only the unicode\n * canonical form of a leaf, so homoglyph and zero-width veils are still caught\n * everywhere. The server swaps in the Node scanner (`./node/decode`) which adds\n * recursive base64 / hex / gzip decoding. Returns a fresh scanner per call to\n * mirror the per-payload budget semantics of the Node variant.\n */\nexport function makeCanonicalVariantScanner(): (\n value: string,\n) => NormalizedVariant[] {\n return (value: string): NormalizedVariant[] => {\n const text =\n value.length > LIMITS.maxLeafScan\n ? value.slice(0, LIMITS.maxLeafScan)\n : value;\n const canonical = canonicalize(text);\n return canonical !== text ? [{ kind: \"canonical\", value: canonical }] : [];\n };\n}\n","/**\n * Pure, dependency-free redaction helpers shared by every runtime.\n *\n * The server pairs these with a salted SHA-256 {@link fingerprint} from\n * `./node/fingerprint` for audit-grade evidence; the universal build uses\n * {@link cosmeticFingerprint} here so a browser/edge bundle never pulls in\n * `node:crypto`. Both produce the SAME display shape - only the trailing hash\n * differs (irreversible salted digest vs. a fast non-crypto hash).\n */\n\nimport type { RedactSpan } from \"./types\";\n\n/**\n * A fast, non-cryptographic hash (FNV-1a). NOT a security primitive: it exists\n * only so the universal build can render a stable, secret-free evidence string\n * with the same shape as the real fingerprint. Never use it for the audit log.\n */\nfunction fnv1a(value: string): string {\n let h = 0x811c9dc5;\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return (h >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Cosmetic, crypto-free fingerprint. Same display shape as the salted-SHA-256\n * server fingerprint (`redacted · sha256:1a2b3c4d`) so evidence strings look\n * identical across runtimes, but the digest is a non-crypto hash and must never\n * back an audit claim. The engine's universal default; the server injects the\n * real one. Like the server fingerprint, it carries no plaintext characters and\n * no length, so it never narrows the underlying value.\n */\nexport function cosmeticFingerprint(value: string): string {\n return `redacted · sha256:${fnv1a(value)}`;\n}\n\n/** Mask the middle of a value, keeping a little context (for PII evidence). */\nexport function maskMiddle(value: string, keep = 2): string {\n if (value.length <= keep * 2) return \"•\".repeat(value.length);\n // `slice(-0)` is `slice(0)` (the whole string), so guard keep === 0 - else a\n // fully-masked value (SSN, card) would echo its raw tail.\n const head = value.slice(0, keep);\n const tail = keep > 0 ? value.slice(-keep) : \"\";\n const middle = \"•\".repeat(Math.max(3, value.length - keep * 2));\n return `${head}${middle}${tail}`;\n}\n\n/** Collapse whitespace and truncate (for injection/destructive snippets). */\nexport function truncateEvidence(value: string, max = 80): string {\n const oneLine = value.replace(/\\s+/g, \" \").trim();\n return oneLine.length > max ? `${oneLine.slice(0, max)}…` : oneLine;\n}\n\n/**\n * Apply redaction spans to a leaf string, right-to-left so earlier offsets stay\n * valid. Overlapping spans are merged (first mask wins). Returns the masked\n * string; a no-op when there are no spans.\n */\nexport function applyRedactions(value: string, spans: RedactSpan[]): string {\n if (spans.length === 0) return value;\n const sorted = [...spans].sort((a, b) => a.start - b.start);\n\n const merged: RedactSpan[] = [];\n for (const span of sorted) {\n const last = merged[merged.length - 1];\n if (last && span.start <= last.end) {\n last.end = Math.max(last.end, span.end);\n } else {\n merged.push({ ...span });\n }\n }\n\n let out = value;\n for (let i = merged.length - 1; i >= 0; i--) {\n const s = merged[i]!;\n out = out.slice(0, s.start) + s.mask + out.slice(s.end);\n }\n return out;\n}\n","import { cosmeticFingerprint, truncateEvidence } from \"../mask\";\nimport type { DetectorMatch, Severity, SignalCategory } from \"../types\";\n\n/** A secret-style pattern: the matched span (or capture group) IS sensitive. */\nexport interface PatternSpec {\n id: string;\n label: string;\n severity: Severity;\n critical?: true;\n /** `globalize` adds the `g`/`d` flags if missing. */\n regex: RegExp;\n /** Capture group holding the secret (default 0 = whole match). */\n group?: number;\n}\n\n/** A finding-style pattern: the match is evidence; the payload is not mutated. */\nexport interface FindingSpec {\n id: string;\n label: string;\n severity: Severity;\n critical?: true;\n regex: RegExp;\n /** Build evidence from the match (default: collapsed + truncated match). */\n evidence?: (match: string) => string;\n}\n\nfunction withFlags(re: RegExp, required: string): RegExp {\n let flags = re.flags;\n for (const f of required) if (!flags.includes(f)) flags += f;\n return flags === re.flags ? re : new RegExp(re.source, flags);\n}\n\n/**\n * Run secret patterns. The matched (group) span is fingerprinted for evidence\n * and marked for redaction in the stored payload - never echoed in plaintext.\n * Requires the `d` flag for exact group offsets (added automatically).\n *\n * `fingerprint` is injected so the same scanner serves both runtimes: the\n * server passes a salted SHA-256 (irreversible, deterministic across calls);\n * the universal build falls back to {@link cosmeticFingerprint}, a non-crypto\n * hash that produces the same display shape without a `node:crypto` dependency.\n */\nexport function scanSecrets(\n value: string,\n specs: PatternSpec[],\n fingerprint: (value: string) => string = cosmeticFingerprint,\n): DetectorMatch[] {\n const matches: DetectorMatch[] = [];\n for (const spec of specs) {\n const re = withFlags(spec.regex, \"gd\");\n for (const m of value.matchAll(re)) {\n const group = spec.group ?? 0;\n const secret = m[group];\n const span = m.indices?.[group];\n if (!secret || !span) continue;\n matches.push({\n detector: spec.id,\n category: \"secret\",\n severity: spec.severity,\n label: spec.label,\n evidence: fingerprint(secret),\n ...(spec.critical ? { critical: true as const } : {}),\n redact: { start: span[0], end: span[1], mask: `‹redacted:${spec.id}›` },\n });\n }\n }\n return matches;\n}\n\n/** Run finding patterns. No payload mutation; evidence is masked/truncated. */\nexport function scanFindings(\n value: string,\n category: SignalCategory,\n specs: FindingSpec[],\n): DetectorMatch[] {\n const matches: DetectorMatch[] = [];\n for (const spec of specs) {\n const re = withFlags(spec.regex, \"g\");\n for (const m of value.matchAll(re)) {\n const whole = m[0];\n if (!whole) continue;\n matches.push({\n detector: spec.id,\n category,\n severity: spec.severity,\n label: spec.label,\n evidence: (spec.evidence ?? truncateEvidence)(whole),\n ...(spec.critical ? { critical: true as const } : {}),\n });\n }\n }\n return matches;\n}\n","import type { Detector, DetectorMatch } from \"../types\";\nimport { type FindingSpec, scanFindings } from \"./util\";\n\n/**\n * Inbound abuse detector - scraping / enumeration / probe patterns that only\n * make sense for a request ARRIVING at a site (never an outbound tool call), so\n * it is excluded from the global registry and only added to INBOUND_DETECTORS.\n * Emits the `rate_abuse` category. (The companion `bot_spoof` category is an\n * identity verdict, injected by the verify handler - not a content finding.)\n */\nconst ABUSE_PATTERNS: FindingSpec[] = [\n {\n id: \"rate_abuse.path_probe\",\n label: \"Sensitive path probe\",\n severity: \"high\",\n regex:\n /(?:^|\\/)(?:\\.env\\b|\\.git(?:\\/|\\b)|\\.aws(?:\\/|\\b)|\\.ssh(?:\\/|\\b)|id_rsa\\b|wp-login\\.php|wp-admin\\b|xmlrpc\\.php|phpmyadmin\\b|actuator\\/env|server-status\\b)/i,\n },\n {\n id: \"rate_abuse.enumeration\",\n label: \"Deep pagination / enumeration\",\n severity: \"medium\",\n regex: /(?:^|[?&])(?:page|offset|start|p)=\\d{4,}/i,\n },\n {\n id: \"rate_abuse.bulk_limit\",\n label: \"Oversized result window\",\n severity: \"medium\",\n regex: /(?:^|[?&])(?:limit|per_page|page_size|count|size)=(?:[1-9]\\d{3,})/i,\n },\n {\n id: \"rate_abuse.graphql_introspection\",\n label: \"GraphQL introspection\",\n severity: \"medium\",\n regex: /\\b__schema\\b|\\bIntrospectionQuery\\b/,\n },\n {\n id: \"rate_abuse.wildcard_fields\",\n label: \"Wildcard field selection\",\n severity: \"low\",\n regex: /(?:^|[?&])(?:fields|select|include)=\\*/i,\n },\n {\n id: \"rate_abuse.automation_client\",\n label: \"Automation / scraper client\",\n severity: \"low\",\n regex:\n /\\b(?:python-requests|aiohttp|httpx|scrapy|go-http-client|node-fetch|okhttp|libwww-perl|wget|curl\\/[\\d.]+|headlesschrome|phantomjs|puppeteer|playwright)\\b/i,\n },\n];\n\nexport const abuseDetector: Detector = {\n id: \"rate_abuse\",\n category: \"rate_abuse\",\n inspect(ctx): DetectorMatch[] {\n return scanFindings(ctx.value, \"rate_abuse\", ABUSE_PATTERNS);\n },\n};\n","import type { Detector, DetectorMatch } from \"../types\";\nimport { type FindingSpec, scanFindings } from \"./util\";\n\n/**\n * Card capability detector - supply-chain risk in the capabilities an external\n * MCP server / A2A agent DECLARES. Runs only on the card-preflight path\n * (CARD_DETECTORS), emitting the `supply_chain` category.\n *\n * It deliberately targets the gaps the content detectors miss: code-execution,\n * fund-movement, and credential-access capabilities, admin reach, and wildcard\n * scopes. (Outright destructive verbs like `delete_database` are already caught\n * by the shared `destructive` detector, which also runs here.)\n *\n * Capability identifiers come in every casing - `exec_shell`, `runCommand`,\n * `wire-transfer`, `read:*` - and `_`/`:` are word characters, so `\\b` alone\n * misses them. We normalize separators and camelCase to spaces first, then match\n * plain keywords.\n */\nconst CARD_PATTERNS: FindingSpec[] = [\n {\n id: \"supply_chain.code_execution\",\n label: \"Code-execution capability\",\n severity: \"high\",\n regex: /\\b(?:exec|execute|eval|spawn|shell|sudo|run command|os command|terminal)\\b/i,\n },\n {\n id: \"supply_chain.fund_movement\",\n label: \"Payment / fund-movement capability\",\n severity: \"high\",\n regex: /\\b(?:payment|transfer|wire|payout|withdraw|charge|refund|disburse)\\b/i,\n },\n {\n id: \"supply_chain.credential_access\",\n label: \"Credential / secret access capability\",\n severity: \"high\",\n regex: /\\b(?:credential|secret|password|api key|private key|ssh key|access token)\\b/i,\n },\n {\n id: \"supply_chain.admin_reach\",\n label: \"Administrative capability\",\n severity: \"medium\",\n regex: /\\b(?:admin|administrator|superuser|impersonate|grant role)\\b/i,\n },\n {\n id: \"supply_chain.wildcard_scope\",\n label: \"Wildcard scope / permission\",\n severity: \"medium\",\n regex: /\\b(?:read|write|admin|scope|access|permissions?)\\s\\*|(?:^|\\s)\\*(?:\\s|$)/i,\n },\n];\n\n/** Split camelCase and turn `_ - . / :` separators into spaces for matching. */\nfunction normalize(value: string): string {\n return value.replace(/([a-z])([A-Z])/g, \"$1 $2\").replace(/[_\\-./:]+/g, \" \");\n}\n\nexport const cardCapabilityDetector: Detector = {\n id: \"supply_chain.capability\",\n category: \"supply_chain\",\n inspect(ctx): DetectorMatch[] {\n return scanFindings(normalize(ctx.value), \"supply_chain\", CARD_PATTERNS);\n },\n};\n","import { truncateEvidence } from \"../mask\";\nimport type { Detector, DetectorMatch, Severity } from \"../types\";\n\nconst RM_RF = /\\brm\\s+-[a-zA-Z]*[rf][a-zA-Z]*\\b/g;\nconst SQL_DROP = /\\b(?:drop|truncate)\\s+(?:table|database|schema|index|view)\\b/gi;\nconst SQL_MUTATE = /\\b(?:delete\\s+from|update)\\s+[\"'`\\w.]+/gi;\nconst RESOURCE_DELETE =\n /\\b(?:delete|destroy|terminate|remove|teardown)[-_\\s]?(?:bucket|instance|volume|database|cluster|stack|deployment|namespace|table|repo(?:sitory)?)\\b/gi;\nconst FORCE_PUSH = /\\bgit\\s+push\\b[\\s\\S]{0,30}?(?:--force\\b|--force-with-lease\\b|\\s-f\\b)/gi;\nconst DANGEROUS_FLAG = /(?:^|\\s)(?:--all|--recursive|--no-preserve-root|--force)\\b/gi;\n\nfunction mk(\n detector: string,\n label: string,\n severity: Severity,\n match: string,\n): DetectorMatch {\n return {\n detector,\n category: \"destructive\",\n severity,\n label,\n evidence: truncateEvidence(match),\n };\n}\n\nexport const destructiveDetector: Detector = {\n id: \"destructive\",\n category: \"destructive\",\n inspect(ctx): DetectorMatch[] {\n const v = ctx.value;\n const out: DetectorMatch[] = [];\n\n for (const m of v.matchAll(RM_RF)) {\n out.push(mk(\"destructive.rm_rf\", \"Recursive/forced file delete\", \"high\", m[0]));\n }\n for (const m of v.matchAll(SQL_DROP)) {\n out.push(mk(\"destructive.sql_drop\", \"SQL DROP/TRUNCATE\", \"high\", m[0]));\n }\n // DELETE/UPDATE without a WHERE in the next ~160 chars = whole-table mutation.\n // Bounded window keeps this linear (no unbounded look-ahead → no ReDoS).\n for (const m of v.matchAll(SQL_MUTATE)) {\n const start = m.index ?? 0;\n if (!/\\bwhere\\b/i.test(v.slice(start, start + 160))) {\n out.push(\n mk(\"destructive.sql_no_where\", \"SQL DELETE/UPDATE without WHERE\", \"high\", m[0]),\n );\n }\n }\n for (const m of v.matchAll(RESOURCE_DELETE)) {\n out.push(mk(\"destructive.resource_delete\", \"Resource destruction\", \"high\", m[0]));\n }\n for (const m of v.matchAll(FORCE_PUSH)) {\n out.push(mk(\"destructive.force_push\", \"Git force push\", \"medium\", m[0]));\n }\n for (const m of v.matchAll(DANGEROUS_FLAG)) {\n out.push(mk(\"destructive.dangerous_flag\", \"Dangerous CLI flag\", \"low\", m[0]));\n }\n return out;\n },\n};\n","import { truncateEvidence } from \"../mask\";\nimport type { Detector, DetectorMatch } from \"../types\";\n\nconst SELECT_STAR = /\\bselect\\s+\\*\\s+from\\b/gi;\nconst BULK_EXPORT =\n /\\b(?:export|dump|download|scrape)\\s+(?:all|everything|\\*|database|table|users|customers|records)\\b/gi;\nconst LARGE_VALUE = 20_000;\n\nexport const egressDetector: Detector = {\n id: \"egress\",\n category: \"egress\",\n inspect(ctx): DetectorMatch[] {\n const v = ctx.value;\n const out: DetectorMatch[] = [];\n\n for (const m of v.matchAll(SELECT_STAR)) {\n out.push({\n detector: \"egress.select_star\",\n category: \"egress\",\n severity: \"medium\",\n label: \"Unbounded SELECT *\",\n evidence: truncateEvidence(m[0]),\n });\n }\n for (const m of v.matchAll(BULK_EXPORT)) {\n out.push({\n detector: \"egress.bulk_export\",\n category: \"egress\",\n severity: \"high\",\n label: \"Bulk data export\",\n evidence: truncateEvidence(m[0]),\n });\n }\n if (v.length >= LARGE_VALUE) {\n out.push({\n detector: \"egress.large_value\",\n category: \"egress\",\n severity: \"low\",\n label: \"Large field value\",\n evidence: `${v.length.toLocaleString(\"en-US\")} chars`,\n });\n }\n return out;\n },\n};\n","import type { Detector } from \"../types\";\nimport { scanFindings, type FindingSpec } from \"./util\";\n\nconst SPECS: FindingSpec[] = [\n {\n id: \"injection.prompt\",\n label: \"Prompt injection\",\n severity: \"high\",\n regex:\n /\\b(?:ignore|disregard|forget|override)\\b[\\s\\S]{0,40}?\\b(?:previous|prior|above|earlier|all|your)\\b[\\s\\S]{0,20}?\\b(?:instructions?|prompts?|rules?|guidelines?|context|directives?)\\b/gi,\n },\n {\n id: \"injection.system_override\",\n label: \"System-prompt override\",\n severity: \"high\",\n regex:\n /\\b(?:you\\s+are\\s+now|act\\s+as(?:\\s+if)?|pretend\\s+to\\s+be|new\\s+system\\s+prompt|developer\\s+mode|jailbreak)\\b/gi,\n },\n {\n id: \"injection.sql\",\n label: \"SQL injection\",\n severity: \"high\",\n regex:\n /(?:'|%27)\\s*(?:or|and)\\s*(?:'|%27|\\d)|\\bunion\\s+select\\b|\\bor\\s+1\\s*=\\s*1\\b|;\\s*drop\\s+table\\b/gi,\n },\n {\n id: \"injection.shell\",\n label: \"Shell/command injection\",\n severity: \"high\",\n regex:\n /[;&|]\\s*(?:rm|cat|curl|wget|nc|bash|sh|chmod|chown|kill|mkfs|dd|eval)\\b|\\$\\([^)]{0,120}\\)|`[^`]{0,120}`/g,\n },\n {\n id: \"injection.ssrf\",\n label: \"SSRF / internal endpoint\",\n severity: \"high\",\n regex:\n /\\b(?:169\\.254\\.169\\.254|metadata\\.google\\.internal|127\\.0\\.0\\.1|0\\.0\\.0\\.0)\\b|\\bfile:\\/\\/|\\bgopher:\\/\\//gi,\n },\n {\n id: \"injection.path_traversal\",\n label: \"Path traversal\",\n severity: \"medium\",\n regex: /(?:\\.\\.[/\\\\]){2,}|\\/etc\\/(?:passwd|shadow)\\b|c:\\\\windows\\\\system32/gi,\n },\n];\n\nexport const injectionDetector: Detector = {\n id: \"injection\",\n category: \"injection\",\n inspect: (ctx) => scanFindings(ctx.value, \"injection\", SPECS),\n};\n","import type { Detector } from \"../types\";\nimport { scanFindings, type FindingSpec } from \"./util\";\n\n/**\n * Jailbreak patterns: the well-known attempts to talk a model out of its safety\n * training. These complement `injection.system_override` (which already catches\n * \"developer mode\", \"you are now\", \"act as\", \"jailbreak\"). Emitted under the\n * existing `injection` SignalCategory with `injection.jailbreak.*` ids, so they\n * flow through every policy predicate, response rule, alert, and the audit\n * ledger with NO closed-enum migration.\n *\n * Obfuscation (leetspeak, homoglyphs, base64) is handled upstream by the\n * engine's canonicalize + recursive-variant scan, so these regexes only need to\n * match the normalized text.\n */\nconst SPECS: FindingSpec[] = [\n {\n id: \"injection.jailbreak.dan\",\n label: \"DAN-style jailbreak\",\n severity: \"high\",\n regex: /\\bDAN\\b|\\bdo\\s+anything\\s+now\\b|\\bstay\\s+in\\s+character\\b/gi,\n },\n {\n id: \"injection.jailbreak.no_restrictions\",\n label: \"No-restrictions jailbreak\",\n severity: \"high\",\n regex:\n /\\b(?:unrestricted|unfiltered|uncensored|jailbroken|no\\s+longer\\s+bound)\\b|\\b(?:no|without|free\\s+(?:from|of))\\s+(?:restrictions?|rules?|filters?|limitations?|guidelines?|guardrails?|censorship|safety\\s+(?:rules|guidelines))\\b/gi,\n },\n {\n id: \"injection.jailbreak.policy_override\",\n label: \"Safety-policy override\",\n severity: \"high\",\n regex:\n /\\b(?:ignore|bypass|disable|turn\\s+off|switch\\s+off|forget)\\b[\\s\\S]{0,30}?\\b(?:safety|content\\s+(?:policy|filter)|moderation|guardrails?|ethical\\s+guidelines?|restrictions?)\\b/gi,\n },\n {\n id: \"injection.jailbreak.roleplay_escape\",\n label: \"Roleplay-escape jailbreak\",\n severity: \"medium\",\n regex:\n /\\b(?:hypothetically|in\\s+a\\s+(?:fictional|hypothetical)\\s+(?:story|scenario|world)|for\\s+(?:educational|research)\\s+purposes\\s+only)\\b[\\s\\S]{0,60}?\\b(?:no\\s+rules|without\\s+restrictions?|anything|illegal|harmful)\\b/gi,\n },\n {\n id: \"injection.jailbreak.persona\",\n label: \"Adversarial persona\",\n severity: \"high\",\n regex:\n /\\b(?:evil\\s+(?:mode|assistant|confidant|ai)|opposite\\s+day|do\\s+not\\s+(?:follow|obey)\\s+(?:any\\s+)?(?:rules?|policies|guidelines?)|you\\s+have\\s+no\\s+(?:rules?|restrictions?|guidelines?|filters?))\\b/gi,\n },\n];\n\nexport const jailbreakDetector: Detector = {\n id: \"jailbreak\",\n category: \"injection\",\n inspect: (ctx) => scanFindings(ctx.value, \"injection\", SPECS),\n};\n","import type { Detector, DetectorContext, DetectorMatch } from \"../types\";\nimport { scanFindings, type FindingSpec } from \"./util\";\n\n/**\n * Output-phase detectors for indirect prompt injection - the dominant live agent\n * attack. Unlike the request-tuned {@link injectionDetector}, these target the\n * vectors that arrive in a tool's RESULT (a fetched web page, document, email,\n * or API response the agent reads back), not in the call it makes.\n *\n * They emit under the existing `injection` category with new `injection.*` ids,\n * so the findings flow through every policy predicate, response rule, alert, and\n * the audit ledger unchanged - no `SignalCategory` migration.\n *\n * Gated to `phase === \"result\"`: an agent legitimately sending \"ignore previous\n * instructions\" as data (e.g. summarising an article about prompt injection)\n * must not be flagged on the request side. The request detectors still run on\n * results too, so a result that leaks a secret/PII is already caught elsewhere.\n */\nconst SPECS: FindingSpec[] = [\n {\n id: \"injection.tool_output_override\",\n label: \"Instruction override in tool output\",\n severity: \"high\",\n // Three shapes aimed at hijacking the agent from inside untrusted content:\n // classic \"ignore previous instructions\", a re-tasking (\"your new task\n // is…\"), and a secrecy directive (\"do not tell the user…\").\n regex:\n /\\b(?:ignore|disregard|forget|override)\\b[\\s\\S]{0,40}?\\b(?:previous|prior|above|earlier|all|the)\\b[\\s\\S]{0,20}?\\b(?:instructions?|prompts?|rules?|context|messages?|directives?)\\b|\\byour\\s+(?:new\\s+|real\\s+|actual\\s+)?(?:task|instruction|goal|objective|job)\\s+is\\b|\\bdo\\s+not\\s+(?:tell|inform|reveal\\s+to|mention\\s+to|notify)\\s+(?:the\\s+)?(?:user|human|operator)\\b/gi,\n },\n {\n id: \"injection.exfil_markdown\",\n label: \"Data-exfiltration markdown link or image\",\n severity: \"high\",\n // A markdown image/link whose URL carries query data or a template\n // placeholder - the classic \"render this image to leak the conversation\"\n // vector. A plain link with no params is not flagged (too noisy).\n regex:\n /!?\\[[^\\]]*\\]\\(\\s*(?:https?:)?\\/\\/[^)\\s]*(?:\\?[^)\\s]+|\\{\\{[^)\\s]*\\}\\}|\\$\\{[^)\\s]*\\})[^)\\s]*\\)/gi,\n },\n {\n id: \"injection.tool_directive\",\n label: \"Embedded tool-call directive\",\n severity: \"high\",\n // Content instructing the agent to invoke a tool/function, or a fake\n // function-call object smuggled into prose.\n regex:\n /\\b(?:call|invoke|use|run|execute|trigger)\\s+(?:the\\s+)?[`\"']?[\\w.\\-]{2,}[`\"']?\\s+(?:tool|function|command|endpoint|api)\\b|\"(?:tool_name|tool_call|function_call|function)\"\\s*:/gi,\n },\n {\n id: \"injection.role_marker\",\n label: \"Fake role or chat marker in content\",\n severity: \"medium\",\n // Chat-template / role markers embedded in untrusted text to forge a new\n // turn or a system message.\n regex:\n /<\\|im_(?:start|end)\\|>|<\\/?(?:system|assistant)\\b[^>]*>|\\[\\/?INST\\]|\\[\\/?SYS\\]|(?:^|\\n)\\s{0,3}#{1,3}\\s*system\\s*:/gi,\n },\n {\n id: \"injection.encoded_payload\",\n label: \"Suspicious encoded blob\",\n severity: \"medium\",\n // A long contiguous base64 run embedded in otherwise-readable content - a\n // common way to hide instructions from prose-level detectors. Kept long to\n // avoid flagging short ids/hashes; medium severity, monitor-first.\n regex: /[A-Za-z0-9+/]{200,}={0,2}/g,\n },\n];\n\n/**\n * Codepoints used to smuggle instructions invisibly past a human reviewer:\n * zero-width spaces/joiners, the word-joiner, the BOM, bidirectional overrides,\n * and the Unicode Tags block (which can encode hidden ASCII).\n */\nconst HIDDEN_UNICODE =\n /[\\u{200B}-\\u{200D}\\u{2060}\\u{FEFF}\\u{202A}-\\u{202E}\\u{2066}-\\u{2069}\\u{E0000}-\\u{E007F}]/gu;\n\nexport const outputInjectionDetector: Detector = {\n id: \"injection.output\",\n category: \"injection\",\n inspect(ctx: DetectorContext): DetectorMatch[] {\n if (ctx.phase !== \"result\") return [];\n\n const matches = scanFindings(ctx.value, \"injection\", SPECS);\n\n // Hidden-unicode is counted, never echoed - the raw bytes are invisible and\n // would corrupt the evidence string.\n const hidden = ctx.value.match(HIDDEN_UNICODE);\n if (hidden) {\n matches.push({\n detector: \"injection.hidden_unicode\",\n category: \"injection\",\n severity: \"high\",\n label: \"Hidden unicode smuggling\",\n evidence: `${hidden.length} hidden/bidirectional character${\n hidden.length === 1 ? \"\" : \"s\"\n } in output`,\n });\n }\n\n return matches;\n },\n};\n","import { maskMiddle } from \"../mask\";\nimport type { Detector, DetectorMatch, RedactSpan } from \"../types\";\n\n// Fixed, length-free masks so identical PII always redacts to an identical\n// string (no length or plaintext leakage). Only emitted when ctx.redactPii is on.\nconst PII_MASK: Record<string, string> = {\n \"pii.email\": \"‹redacted:pii.email›\",\n \"pii.ssn\": \"‹redacted:pii.ssn›\",\n \"pii.phone\": \"‹redacted:pii.phone›\",\n \"pii.credit_card\": \"‹redacted:pii.card›\",\n};\n\n/** A redaction span for a matched PII run, only when the caller opted in. */\nfunction piiRedact(\n enabled: boolean | undefined,\n detector: string,\n index: number,\n length: number,\n): RedactSpan | undefined {\n if (!enabled) return undefined;\n return { start: index, end: index + length, mask: PII_MASK[detector]! };\n}\n\nconst EMAIL = /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g;\n// US SSN with the standard invalid-range guards (no 000/666/9xx area, etc.).\nconst SSN = /\\b(?!000|666|9\\d\\d)\\d{3}-(?!00)\\d{2}-(?!0000)\\d{4}\\b/g;\nconst PHONE = /\\b(?:\\+?1[-.\\s]?)?\\(?\\d{3}\\)?[-.\\s]\\d{3}[-.\\s]\\d{4}\\b/g;\n// 13–19 digits with optional space/dash separators; Luhn-validated below.\nconst CARD = /\\b(?:\\d[ -]?){13,19}\\b/g;\n\nfunction luhnValid(digits: string): boolean {\n let sum = 0;\n let alt = false;\n for (let i = digits.length - 1; i >= 0; i--) {\n let d = digits.charCodeAt(i) - 48;\n if (d < 0 || d > 9) return false;\n if (alt) {\n d *= 2;\n if (d > 9) d -= 9;\n }\n sum += d;\n alt = !alt;\n }\n return sum % 10 === 0;\n}\n\nexport const piiDetector: Detector = {\n id: \"pii\",\n category: \"pii\",\n inspect(ctx): DetectorMatch[] {\n const v = ctx.value;\n const out: DetectorMatch[] = [];\n\n for (const m of v.matchAll(EMAIL)) {\n out.push({\n detector: \"pii.email\",\n category: \"pii\",\n severity: \"medium\",\n label: \"Email address\",\n evidence: maskMiddle(m[0]),\n redact: piiRedact(ctx.redactPii, \"pii.email\", m.index, m[0].length),\n });\n }\n for (const m of v.matchAll(SSN)) {\n out.push({\n detector: \"pii.ssn\",\n category: \"pii\",\n severity: \"high\",\n label: \"US Social Security Number\",\n evidence: maskMiddle(m[0], 0),\n redact: piiRedact(ctx.redactPii, \"pii.ssn\", m.index, m[0].length),\n });\n }\n for (const m of v.matchAll(PHONE)) {\n out.push({\n detector: \"pii.phone\",\n category: \"pii\",\n severity: \"low\",\n label: \"Phone number\",\n evidence: maskMiddle(m[0]),\n redact: piiRedact(ctx.redactPii, \"pii.phone\", m.index, m[0].length),\n });\n }\n for (const m of v.matchAll(CARD)) {\n const digits = m[0].replace(/[ -]/g, \"\");\n if (digits.length >= 13 && digits.length <= 19 && luhnValid(digits)) {\n out.push({\n detector: \"pii.credit_card\",\n category: \"pii\",\n severity: \"high\",\n critical: true,\n label: \"Credit card number\",\n evidence: maskMiddle(digits, 0),\n redact: piiRedact(ctx.redactPii, \"pii.credit_card\", m.index, m[0].length),\n });\n }\n }\n return out;\n },\n};\n","import type { Detector } from \"../types\";\nimport { scanSecrets, type PatternSpec } from \"./util\";\n\n/**\n * High-precision credential patterns. Live cloud/service keys floor the score\n * (`critical`); lower-confidence shapes (JWT, generic assignments) score lower.\n * The matched span is redacted from the stored payload.\n */\nconst SECRET_PATTERNS: PatternSpec[] = [\n {\n id: \"secret.aws_access_key\",\n label: \"AWS access key id\",\n severity: \"critical\",\n critical: true,\n regex: /\\b(?:AKIA|ASIA|AGPA|AIDA|AROA)[0-9A-Z]{16}\\b/,\n },\n {\n id: \"secret.aws_secret_key\",\n label: \"AWS secret access key\",\n severity: \"critical\",\n critical: true,\n regex: /aws.{0,24}?(?:secret|private).{0,24}?[\"'=:\\s]([A-Za-z0-9/+]{40})\\b/i,\n group: 1,\n },\n {\n id: \"secret.github_token\",\n label: \"GitHub token\",\n severity: \"critical\",\n critical: true,\n regex: /\\bgh[posru]_[A-Za-z0-9]{36,}\\b/,\n },\n {\n id: \"secret.github_pat\",\n label: \"GitHub fine-grained PAT\",\n severity: \"critical\",\n critical: true,\n regex: /\\bgithub_pat_[A-Za-z0-9_]{22,}\\b/,\n },\n {\n id: \"secret.slack_token\",\n label: \"Slack token\",\n severity: \"critical\",\n critical: true,\n regex: /\\bxox[baprs]-[A-Za-z0-9-]{10,}\\b/,\n },\n {\n id: \"secret.google_api_key\",\n label: \"Google API key\",\n severity: \"high\",\n regex: /\\bAIza[0-9A-Za-z_-]{35}\\b/,\n },\n {\n id: \"secret.llm_key\",\n label: \"LLM provider API key\",\n severity: \"critical\",\n critical: true,\n regex: /\\bsk-(?:ant-|proj-|live-)?[A-Za-z0-9_-]{20,}\\b/,\n },\n {\n id: \"secret.stripe_key\",\n label: \"Stripe live key\",\n severity: \"critical\",\n critical: true,\n regex: /\\b[sr]k_live_[A-Za-z0-9]{16,}\\b/,\n },\n {\n id: \"secret.private_key\",\n label: \"Private key (PEM)\",\n severity: \"critical\",\n critical: true,\n regex: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----/,\n },\n {\n id: \"secret.jwt\",\n label: \"JSON Web Token\",\n severity: \"high\",\n regex: /\\beyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{8,}\\b/,\n },\n {\n id: \"secret.bearer\",\n label: \"Bearer token\",\n severity: \"high\",\n regex: /\\bbearer\\s+([A-Za-z0-9._-]{16,})\\b/i,\n group: 1,\n },\n {\n id: \"secret.assignment\",\n label: \"Hardcoded credential\",\n severity: \"medium\",\n regex:\n /(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token)[\"']?\\s*[:=]\\s*[\"']?([^\\s\"']{8,})/i,\n group: 1,\n },\n];\n\nexport const secretsDetector: Detector = {\n id: \"secrets\",\n category: \"secret\",\n // `ctx.fingerprint` is injected by the engine (salted SHA-256 on the server,\n // a cosmetic hash in the universal build); scanSecrets falls back to the\n // cosmetic default when it is unset.\n inspect: (ctx) => scanSecrets(ctx.value, SECRET_PATTERNS, ctx.fingerprint),\n};\n","import type { Detector } from \"../types\";\nimport { abuseDetector } from \"./abuse\";\nimport { cardCapabilityDetector } from \"./card\";\nimport { destructiveDetector } from \"./destructive\";\nimport { egressDetector } from \"./egress\";\nimport { injectionDetector } from \"./injection\";\nimport { jailbreakDetector } from \"./jailbreak\";\nimport { outputInjectionDetector } from \"./output-injection\";\nimport { piiDetector } from \"./pii\";\nimport { secretsDetector } from \"./secrets\";\n\n/**\n * Ordered registry - stable order yields deterministic signal output. The\n * output-injection detector is a no-op on request-phase leaves, so it adds zero\n * signals to argument scoring; it only fires when a leaf is a tool result.\n */\nexport const DETECTORS: Detector[] = [\n secretsDetector,\n piiDetector,\n destructiveDetector,\n injectionDetector,\n jailbreakDetector,\n outputInjectionDetector,\n egressDetector,\n];\n\n/**\n * Inbound scoring runs the shared detectors PLUS the abuse detector (scraping /\n * enumeration / probe patterns). Outbound scoring never sees `rate_abuse`.\n */\nexport const INBOUND_DETECTORS: Detector[] = [...DETECTORS, abuseDetector];\n\n/**\n * Card-preflight scoring runs the shared detectors (a leaked secret or injection\n * string inside a card still matters) PLUS the capability detector that flags\n * supply-chain risk in what an external server declares.\n */\nexport const CARD_DETECTORS: Detector[] = [...DETECTORS, cardCapabilityDetector];\n\nexport {\n abuseDetector,\n cardCapabilityDetector,\n destructiveDetector,\n egressDetector,\n injectionDetector,\n jailbreakDetector,\n outputInjectionDetector,\n piiDetector,\n secretsDetector,\n};\n","import type { RiskSignal, Severity } from \"./types\";\n\n/** Severity → base points. Single source of truth for signal weight. */\nexport const SEVERITY_POINTS: Record<Severity, number> = {\n low: 8,\n medium: 18,\n high: 35,\n critical: 55,\n};\n\n/** Each successive (sorted-desc) signal contributes DECAY^i of its points. */\nexport const DECAY = 0.6;\n\n/** A critical signal floors the final score here, regardless of base tool. */\nexport const CRITICAL_FLOOR = 90;\n\nfunction clamp(n: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, n));\n}\n\n/** Resolve a severity to its point weight. */\nexport function pointsFor(severity: Severity): number {\n return SEVERITY_POINTS[severity];\n}\n\n/**\n * Combine the base tool-name risk with payload signals into a 0–100 integer.\n *\n * contribution = Σ pᵢ · DECAY^i (points sorted desc → most severe counts full)\n * combined = 100·(1 − (1−base/100)·(1−contribution/100)) (probabilistic OR)\n * final = max(combined, CRITICAL_FLOOR) if any critical signal\n *\n * Properties: no signals ⇒ combined === base (exact back-compat); monotonic\n * (adding a signal never lowers the score); diminishing returns (many tiny\n * signals can't trivially saturate); always clamped to [0,100] - the DB has a\n * CHECK (risk_score between 0 and 100) constraint, so overflow would 500 the\n * gateway hot path.\n */\nexport function combine(base: number, signals: RiskSignal[]): number {\n const points = signals.map((s) => s.points).sort((a, b) => b - a);\n const contribution = Math.min(\n points.reduce((acc, p, i) => acc + p * DECAY ** i, 0),\n 100,\n );\n\n const b = clamp(base, 0, 100) / 100;\n let final = 100 * (1 - (1 - b) * (1 - contribution / 100));\n\n if (signals.some((s) => s.critical)) {\n final = Math.max(final, CRITICAL_FLOOR);\n }\n\n return clamp(Math.round(final), 0, 100);\n}\n\n/** One signal's attributed share of a risk score (the decomposition view). */\nexport interface RiskContribution {\n detector: string;\n label: string;\n category: RiskSignal[\"category\"];\n severity: Severity;\n /** Raw severity weight before diminishing returns. */\n points: number;\n /** The signal's actual weighted contribution: points · DECAY^rank. */\n effectivePoints: number;\n /** True for a critical signal (it also floors the score at CRITICAL_FLOOR). */\n critical: boolean;\n}\n\n/** A risk score broken into its base tool prior + per-signal contributions. */\nexport interface RiskDecomposition {\n /** Base tool-name risk prior (0–100). */\n base: number;\n /** Per-signal shares, highest weight first (mirrors combine's sort + DECAY). */\n contributions: RiskContribution[];\n /** Σ effectivePoints, clamped to 100 (the combined signal contribution term). */\n signalContribution: number;\n /** The recombined final score - equals combine(base, signals). */\n score: number;\n /** Whether a critical signal floored the score to CRITICAL_FLOOR. */\n criticalFloored: boolean;\n}\n\n/**\n * Explain a risk score: attribute it to the base tool prior and each signal's\n * diminishing-returns share, exactly reproducing {@link combine}'s arithmetic\n * (points sorted desc, the i-th counting DECAY^i). Pure - drives the log-detail\n * \"why this score?\" breakdown. No I/O, no engine version drift: it reads the\n * `points` already stored on each signal.\n */\nexport function decomposeRisk(\n base: number,\n signals: RiskSignal[],\n): RiskDecomposition {\n const sorted = [...signals].sort((a, b) => b.points - a.points);\n const contributions: RiskContribution[] = sorted.map((s, i) => ({\n detector: s.detector,\n label: s.label,\n category: s.category,\n severity: s.severity,\n points: s.points,\n effectivePoints: s.points * DECAY ** i,\n critical: s.critical === true,\n }));\n const signalContribution = Math.min(\n contributions.reduce((acc, c) => acc + c.effectivePoints, 0),\n 100,\n );\n return {\n base: clamp(base, 0, 100),\n contributions,\n signalContribution,\n score: combine(base, signals),\n criticalFloored: signals.some((s) => s.critical === true),\n };\n}\n","/**\n * Base tool-name risk - assigns a 0–100 prior to a tool *name*. Pure & sync.\n * This is the \"what kind of tool is this\" prior; payload-content signals are\n * layered on top of it in scoring.ts.\n *\n * Lookup order:\n * 1. exact match in RISK_MAP\n * 2. longest-prefix match in RISK_PREFIX_MAP (so an unknown `aws.*` action\n * scores high rather than defaulting to neutral - fail-safe for a firewall)\n * 3. DEFAULT_RISK for fully-unknown tools\n */\n\nexport const RISK_MAP: Record<string, number> = {\n \"github.read\": 10,\n \"github.push\": 40,\n \"gmail.send\": 80,\n \"slack.post\": 50,\n \"aws.delete\": 100,\n \"db.query\": 70,\n // Inbound HTTP methods (the verify path scores requests as `inbound.<method>`).\n // Reads are cheap; writes/deletes warrant a higher prior.\n \"inbound.get\": 10,\n \"inbound.head\": 5,\n \"inbound.options\": 5,\n \"inbound.post\": 35,\n \"inbound.put\": 40,\n \"inbound.patch\": 40,\n \"inbound.delete\": 60,\n};\n\n/** Fallback scores for unknown tools within a known namespace. */\nexport const RISK_PREFIX_MAP: Record<string, number> = {\n \"aws.\": 90,\n \"github.\": 30,\n \"gmail.\": 70,\n \"inbound.\": 25,\n};\n\nexport const DEFAULT_RISK = 50;\n\nexport function calculateRisk(toolName: string): number {\n const tool = toolName.trim().toLowerCase();\n\n const exact = RISK_MAP[tool];\n if (exact !== undefined) return exact;\n\n let best: number | null = null;\n let bestLen = -1;\n for (const [prefix, score] of Object.entries(RISK_PREFIX_MAP)) {\n if (tool.startsWith(prefix) && prefix.length > bestLen) {\n best = score;\n bestLen = prefix.length;\n }\n }\n return best ?? DEFAULT_RISK;\n}\n","import { canonicalize, makeCanonicalVariantScanner } from \"./canonicalize\";\nimport { DETECTORS } from \"./detectors\";\nimport { applyRedactions, cosmeticFingerprint } from \"./mask\";\nimport { combine, pointsFor } from \"./scoring\";\nimport { calculateRisk } from \"./tool-risk\";\nimport type {\n Detector,\n DetectorContext,\n InspectionResult,\n NormalizedVariant,\n RedactSpan,\n RiskSignal,\n SignalCategory,\n} from \"./types\";\nimport { LIMITS, transformStrings, type WalkState } from \"./walk\";\n\nconst TOOL_NAME_LOCATION = \"(tool_name)\";\nconst PAYLOAD_LOCATION = \"(payload)\";\n\n/** Whole-leaf mask used when a secret was found only inside a decoded variant\n * (redaction spans cannot be mapped back through a decode). */\nconst ENCODED_SECRET_MASK = \"‹redacted:obfuscation.encoded_secret›\";\n\n/**\n * Runtime-injected capabilities the engine needs but that differ by platform.\n * The server (`./node`) supplies a salted SHA-256 fingerprint and a recursive\n * base64/hex/gzip variant scanner; the universal default below uses a cosmetic\n * fingerprint and a canonical-only scanner so the engine runs in any runtime\n * with no `node:crypto` / `node:zlib` dependency. Detection of plain secrets,\n * injection, destructive, PII and egress is identical either way; only nested\n * de-obfuscation and the fingerprint digest differ.\n */\nexport interface EngineDeps {\n /** Fingerprint a sensitive value for secret evidence. */\n fingerprint: (value: string) => string;\n /**\n * Build a per-payload variant scanner. Called once per `inspectContent` so a\n * decode budget can be shared across every leaf of one payload.\n */\n makeVariantScanner: () => (value: string) => NormalizedVariant[];\n /**\n * When true, PII detectors emit redaction spans so PII is masked in the\n * stored payload (just like secrets). Default OFF everywhere: PII is flagged,\n * not redacted. The hosted `model.completion` gateway branch is the only\n * caller that turns this on (via {@link ./node}.scoreToolCallRedacted), so a\n * model output is audited with PII masked and can be returned masked under a\n * `redact` policy. Nothing else changes.\n */\n redactPii?: boolean;\n}\n\n/** The crypto/Buffer-free defaults - safe in Node, edge, and the browser. */\nconst UNIVERSAL_DEPS: EngineDeps = {\n fingerprint: cosmeticFingerprint,\n makeVariantScanner: makeCanonicalVariantScanner,\n};\n\n/**\n * Scan the variants of one leaf as synthetic leaves. Returns the variant\n * signals, whether any variant carried a secret (the caller must then mask the\n * WHOLE leaf - spans don't survive a decode), and the variant kinds that\n * produced findings (for the obfuscation marker).\n */\nfunction runVariantDetectors(\n ctx: DetectorContext,\n detectors: Detector[],\n scanVariants: (value: string) => NormalizedVariant[],\n): { signals: RiskSignal[]; secretInVariant: boolean; hitKinds: string[] } {\n const signals: RiskSignal[] = [];\n const hitKinds: string[] = [];\n let secretInVariant = false;\n for (const variant of scanVariants(ctx.value)) {\n const result = runDetectors(\n { ...ctx, path: `${ctx.path} (${variant.kind})`, value: variant.value },\n detectors,\n );\n if (result.signals.length > 0) {\n signals.push(...result.signals);\n hitKinds.push(variant.kind);\n }\n if (result.redactions.length > 0) secretInVariant = true;\n }\n return { signals, secretInVariant, hitKinds };\n}\n\n/** The engine-level marker that content only flagged after de-obfuscation. */\nfunction obfuscationSignal(location: string, hitKinds: string[]): RiskSignal {\n return {\n detector: \"obfuscation.encoded_payload\",\n category: \"injection\",\n severity: \"medium\",\n label: \"Obfuscated content\",\n points: pointsFor(\"medium\"),\n location,\n evidence: `signals surfaced only after ${[...new Set(hitKinds)].join(\", \")}`,\n };\n}\n\n/** Run every detector against one leaf, attaching location + points. */\nfunction runDetectors(\n ctx: DetectorContext,\n detectors: Detector[],\n): {\n signals: RiskSignal[];\n redactions: RedactSpan[];\n} {\n // Only scan the first N chars of a huge leaf; the rest still flows through to\n // the (redacted) payload untouched.\n const scanCtx =\n ctx.value.length > LIMITS.maxLeafScan\n ? { ...ctx, value: ctx.value.slice(0, LIMITS.maxLeafScan) }\n : ctx;\n\n const signals: RiskSignal[] = [];\n const redactions: RedactSpan[] = [];\n for (const detector of detectors) {\n for (const match of detector.inspect(scanCtx)) {\n signals.push({\n detector: match.detector,\n category: match.category,\n severity: match.severity,\n label: match.label,\n points: pointsFor(match.severity),\n location: ctx.path,\n evidence: match.evidence,\n ...(match.critical ? { critical: true } : {}),\n });\n if (match.redact) redactions.push(match.redact);\n }\n }\n return { signals, redactions };\n}\n\nconst CATEGORY_ORDER: Record<SignalCategory, number> = {\n secret: 0,\n bot_spoof: 1,\n supply_chain: 2,\n destructive: 3,\n injection: 4,\n rate_abuse: 5,\n pii: 6,\n egress: 7,\n};\n\n/** Dedupe by (detector, location), sort deterministically, cap at the limit. */\nfunction finalize(signals: RiskSignal[]): RiskSignal[] {\n const seen = new Set<string>();\n const unique: RiskSignal[] = [];\n for (const s of signals) {\n const key = `${s.detector}|${s.location}`;\n if (seen.has(key)) continue;\n seen.add(key);\n unique.push(s);\n }\n unique.sort(\n (a, b) =>\n b.points - a.points ||\n CATEGORY_ORDER[a.category] - CATEGORY_ORDER[b.category] ||\n a.location.localeCompare(b.location),\n );\n return unique.slice(0, LIMITS.maxSignals);\n}\n\n/**\n * Inspect a tool name + arguments payload. Runs every detector against the\n * tool name (as a synthetic leaf) and each string leaf of the arguments,\n * returning the collected signals plus a structural copy of the payload with\n * secret spans masked in place.\n */\nexport function inspectContent(\n toolName: string,\n args: Record<string, unknown>,\n detectors: Detector[] = DETECTORS,\n phase: \"request\" | \"result\" = \"request\",\n deps: EngineDeps = UNIVERSAL_DEPS,\n): InspectionResult {\n // Canonicalize the tool name so a homoglyph-veiled name is judged (and\n // base-risk scored) as what it visually claims to be.\n const normalizedTool = canonicalize(toolName).trim().toLowerCase();\n const collected: RiskSignal[] = [];\n const state: WalkState = { leaves: 0, bytes: 0, truncated: false };\n const scanVariants = deps.makeVariantScanner();\n\n // 1. tool name as a synthetic leaf (never mutates the payload).\n collected.push(\n ...runDetectors(\n {\n toolName: normalizedTool,\n path: TOOL_NAME_LOCATION,\n value: normalizedTool,\n phase,\n fingerprint: deps.fingerprint,\n redactPii: deps.redactPii,\n },\n detectors,\n ).signals,\n );\n\n // 2. each string leaf of the arguments; mask secret spans in the copy.\n // Each leaf is also scanned through its normalization/decode variants so\n // homoglyph, zero-width, and nested-encoding veils don't blind detectors.\n const redactedPayload = transformStrings(\n args,\n (path, value) => {\n const ctx: DetectorContext = {\n toolName: normalizedTool,\n path,\n value,\n phase,\n fingerprint: deps.fingerprint,\n redactPii: deps.redactPii,\n };\n const { signals, redactions } = runDetectors(ctx, detectors);\n collected.push(...signals);\n\n const variants = runVariantDetectors(ctx, detectors, scanVariants);\n if (variants.hitKinds.length > 0) {\n collected.push(...variants.signals);\n collected.push(obfuscationSignal(path, variants.hitKinds));\n }\n if (variants.secretInVariant) return ENCODED_SECRET_MASK;\n return applyRedactions(value, redactions);\n },\n state,\n ) as Record<string, unknown>;\n\n if (state.truncated) {\n collected.push({\n detector: \"egress.oversized_payload\",\n category: \"egress\",\n severity: \"medium\",\n label: \"Oversized payload\",\n points: pointsFor(\"medium\"),\n location: PAYLOAD_LOCATION,\n evidence: \"payload too large to fully inspect\",\n });\n }\n\n return { signals: finalize(collected), redactedPayload };\n}\n\nexport interface ScoredToolCall {\n score: number;\n base: number;\n signals: RiskSignal[];\n redactedPayload: Record<string, unknown>;\n}\n\n/** The hot-path entry: base tool risk + content signals → final scored call. */\nexport function scoreToolCall(\n toolName: string,\n args: Record<string, unknown>,\n detectors: Detector[] = DETECTORS,\n phase: \"request\" | \"result\" = \"request\",\n deps: EngineDeps = UNIVERSAL_DEPS,\n): ScoredToolCall {\n const { signals, redactedPayload } = inspectContent(\n toolName,\n args,\n detectors,\n phase,\n deps,\n );\n const base = calculateRisk(canonicalize(toolName));\n const score = combine(base, signals);\n return { score, base, signals, redactedPayload };\n}\n","/**\n * Default-posture decision mapping.\n *\n * Mirrors the out-of-the-box posture a fresh AxioRank workspace runs with. The\n * seed policy (supabase migration `0005_seed_signal_policies.sql`) denies on any\n * live secret, denies on any destructive operation, and denies when the risk\n * score reaches 75. Between the review band (score 50 to 74) and the deny\n * threshold, content that still trips a detector is advised for human review\n * (`hold`): this is the require-approval tier most workspaces add for medium\n * risk content, and it lets the local read surface the same three states the\n * gateway produces (allow, deny, hold) rather than collapsing review into allow.\n *\n * It is ADVISORY. The hosted gateway evaluates the workspace's real policy\n * (custom rules, approvals/holds, budgets, IFC, the ML flow judge, kill-chain\n * correlation), which can differ. Use this for a fast local \"what would the\n * defaults say\" read, then route the call through the gateway to enforce.\n */\n\nimport type { RiskSignal } from \"./types\";\n\nexport type LocalDecision = \"allow\" | \"deny\" | \"hold\";\n\nexport interface LocalVerdict {\n decision: LocalDecision;\n /** Human-readable explanation for the decision. */\n reason: string;\n /** The default rule that fired, or null when nothing matched (allow). */\n rule: string | null;\n}\n\n/** The default risk tier: deny at or above this score. */\nexport const DEFAULT_DENY_RISK = 75;\n\n/**\n * The review tier: at or above this score (and below the deny threshold), a\n * call that still trips a detector is held for human review. Advisory only.\n */\nexport const DEFAULT_HOLD_RISK = 50;\n\n/**\n * Resolve a scored call against the default seed policy. Pure and synchronous.\n */\nexport function localDecision(\n score: number,\n signals: RiskSignal[],\n): LocalVerdict {\n if (signals.some((s) => s.category === \"secret\")) {\n return {\n decision: \"deny\",\n reason: \"A live secret was detected in the payload.\",\n rule: \"deny-live-secret\",\n };\n }\n if (signals.some((s) => s.category === \"destructive\")) {\n return {\n decision: \"deny\",\n reason: \"A destructive operation was detected.\",\n rule: \"deny-destructive\",\n };\n }\n if (score >= DEFAULT_DENY_RISK) {\n return {\n decision: \"deny\",\n reason: `Risk score ${score} is at or above the ${DEFAULT_DENY_RISK} threshold.`,\n rule: `risk>=${DEFAULT_DENY_RISK}`,\n };\n }\n if (score >= DEFAULT_HOLD_RISK && signals.length > 0) {\n return {\n decision: \"hold\",\n reason: `Risk score ${score} is in the review band (${DEFAULT_HOLD_RISK} to ${DEFAULT_DENY_RISK - 1}). A human should approve this call.`,\n rule: `risk>=${DEFAULT_HOLD_RISK}`,\n };\n }\n return {\n decision: \"allow\",\n reason: \"No default policy rule matched.\",\n rule: null,\n };\n}\n","import {\n type LocalDecision,\n localDecision,\n type RiskSignal,\n scoreToolCall,\n} from \"@axiorank/detectors\";\nimport type { ToolCallSignal } from \"./types\";\n\n/**\n * Result of a LOCAL inspection - the same detectors and risk scoring the hosted\n * gateway runs, evaluated in-process against the default policy. No API key, no\n * network, no signup.\n */\nexport interface InspectResult {\n /**\n * Advisory verdict under the default posture (deny on a live secret, a\n * destructive op, or risk >= 75). The hosted gateway applies YOUR workspace's\n * real policy (custom rules, approvals/holds, budgets, information-flow\n * control, the ML flow judge, kill-chain correlation) and may decide\n * differently - route the call through `new AxioRank(...).enforce()` to enforce.\n */\n decision: LocalDecision;\n /** Risk score (0-100) the engine assigned. */\n risk: number;\n /** Human-readable explanation for the decision. */\n reason: string;\n /** The content-inspection findings that drove the score. */\n signals: ToolCallSignal[];\n /** A structural copy of the input with secret spans masked in place. */\n redactedPayload: Record<string, unknown>;\n}\n\n// The default detectors only emit the five content categories, all of which are\n// in the public `ToolCallSignal` union; narrow the engine's wider category set.\nfunction toPublicSignal(s: RiskSignal): ToolCallSignal {\n return {\n detector: s.detector,\n category: s.category as ToolCallSignal[\"category\"],\n severity: s.severity,\n label: s.label,\n location: s.location,\n evidence: s.evidence,\n };\n}\n\n/**\n * Inspect a tool call locally - in-process, with no API key and no network.\n *\n * Runs the exact AxioRank detectors (leaked secrets, prompt injection,\n * destructive operations, PII, risky egress) and risk scoring the hosted\n * gateway runs, then resolves an advisory `allow` / `deny` under the default\n * policy. Use it to see what AxioRank catches in seconds, then route real\n * traffic through {@link AxioRank.enforce} to enforce centrally with your own\n * policy, an audit trail, approvals, and multi-step kill-chain correlation.\n *\n * Pure and synchronous; safe in Node, edge, and the browser. Plain payloads are\n * scored identically to the gateway; the gateway additionally decodes deeply\n * nested base64/hex/gzip wrappers and writes a salted-SHA-256 audit fingerprint.\n *\n * @example\n * ```ts\n * import { inspect } from \"@axiorank/sdk\";\n *\n * const r = inspect(\"aws.s3.putObject\", {\n * body: \"AKIAIOSFODNN7EXAMPLE\",\n * webhook: \"http://attacker.example/exfil\",\n * });\n * console.log(r.decision, r.risk, r.signals.map((s) => s.detector));\n * // → \"deny\" 96 [\"secret.aws_access_key\", ...]\n * ```\n */\nexport function inspect(\n tool: string,\n args: Record<string, unknown> = {},\n): InspectResult {\n const { score, signals, redactedPayload } = scoreToolCall(tool, args);\n const verdict = localDecision(score, signals);\n return {\n decision: verdict.decision,\n risk: score,\n reason: verdict.reason,\n signals: signals.map(toPublicSignal),\n redactedPayload,\n };\n}\n\n/**\n * Inspect a tool's RESULT (or any freeform text) locally - the result-phase\n * counterpart to {@link inspect}. Catches indirect prompt injection, a leaked\n * secret, or PII in what a tool returned BEFORE your agent ingests it. No API\n * key, no network.\n *\n * @example\n * ```ts\n * const page = await fetchUrl(url);\n * const r = inspectText(\"web.fetch\", page);\n * if (r.decision === \"deny\") {\n * // strip or quarantine untrusted content before the model sees it\n * }\n * ```\n */\nexport function inspectText(tool: string, text: string): InspectResult {\n const { score, signals, redactedPayload } = scoreToolCall(\n tool,\n { text },\n undefined,\n \"result\",\n );\n const verdict = localDecision(score, signals);\n return {\n decision: verdict.decision,\n risk: score,\n reason: verdict.reason,\n signals: signals.map(toPublicSignal),\n redactedPayload,\n };\n}\n\n/**\n * Inspect an LLM PROMPT locally - the model-input guardrail. Catches prompt\n * injection, jailbreak attempts, and a secret or PII leaking INTO the prompt,\n * before you send it to the model. No API key, no network.\n *\n * @example\n * ```ts\n * const r = inspectPrompt(userMessage);\n * if (r.decision === \"deny\") throw new Error(\"blocked prompt: \" + r.reason);\n * ```\n */\nexport function inspectPrompt(text: string): InspectResult {\n const { score, signals, redactedPayload } = scoreToolCall(\"model.prompt\", {\n prompt: text,\n });\n const verdict = localDecision(score, signals);\n return {\n decision: verdict.decision,\n risk: score,\n reason: verdict.reason,\n signals: signals.map(toPublicSignal),\n redactedPayload,\n };\n}\n\n/**\n * Inspect an LLM COMPLETION locally - the model-output guardrail. Catches\n * injected instructions in the output, PII egress, and a leaked secret in what\n * the model returned, before it reaches a user or a downstream tool. No API key,\n * no network.\n *\n * @example\n * ```ts\n * const out = await model.generate(prompt);\n * const r = inspectCompletion(out.text);\n * if (r.decision === \"deny\") out.text = \"[response withheld]\";\n * ```\n */\nexport function inspectCompletion(text: string): InspectResult {\n const { score, signals, redactedPayload } = scoreToolCall(\n \"model.completion\",\n { completion: text },\n undefined,\n \"result\",\n );\n const verdict = localDecision(score, signals);\n return {\n decision: verdict.decision,\n risk: score,\n reason: verdict.reason,\n signals: signals.map(toPublicSignal),\n redactedPayload,\n };\n}\n","import type { CardVerifyResult, ToolCallResult } from \"./types\";\n\n/** Base class for all errors thrown by the SDK. */\nexport class AxioRankError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AxioRankError\";\n }\n}\n\n/** Thrown when the API key is missing, invalid, or revoked (HTTP 401). */\nexport class AxioRankAuthError extends AxioRankError {\n constructor(message = \"Invalid or missing AxioRank API key\") {\n super(message);\n this.name = \"AxioRankAuthError\";\n }\n}\n\n/** Thrown for malformed requests, timeouts, and other non-2xx responses. */\nexport class AxioRankRequestError extends AxioRankError {\n status?: number;\n constructor(message: string, status?: number) {\n super(message);\n this.name = \"AxioRankRequestError\";\n this.status = status;\n }\n}\n\n/** Thrown by {@link AxioRank.enforce} when the gateway denies the call. */\nexport class AxioRankDeniedError extends AxioRankError {\n result: ToolCallResult;\n constructor(result: ToolCallResult) {\n super(`AxioRank denied tool call: ${result.reason}`);\n this.name = \"AxioRankDeniedError\";\n this.result = result;\n }\n}\n\n/** Thrown by the chat guards when a prompt or completion is blocked locally. */\nexport class AxioRankGuardError extends AxioRankError {\n /** Which side of the model call was blocked. */\n phase: \"prompt\" | \"completion\";\n risk: number;\n reason: string;\n constructor(phase: \"prompt\" | \"completion\", reason: string, risk: number) {\n super(`AxioRank blocked the ${phase}: ${reason} (risk ${risk}).`);\n this.name = \"AxioRankGuardError\";\n this.phase = phase;\n this.reason = reason;\n this.risk = risk;\n }\n}\n\n/** Thrown by {@link AxioRank.enforceCard} when the preflight verdict is `deny`. */\nexport class AxioRankCardDeniedError extends AxioRankError {\n result: CardVerifyResult;\n constructor(result: CardVerifyResult) {\n super(`AxioRank denied card preflight: ${result.reason}`);\n this.name = \"AxioRankCardDeniedError\";\n this.result = result;\n }\n}\n\n/** Thrown when the workspace is rate-limited (HTTP 429) after retries are exhausted. */\nexport class AxioRankRateLimitError extends AxioRankError {\n retryAfterSec?: number;\n constructor(message = \"AxioRank rate limit exceeded\", retryAfterSec?: number) {\n super(message);\n this.name = \"AxioRankRateLimitError\";\n this.retryAfterSec = retryAfterSec;\n }\n}\n\n/** Thrown by {@link constructEvent} when a webhook signature is missing, stale, or invalid. */\nexport class AxioRankWebhookSignatureError extends AxioRankError {\n constructor(message = \"AxioRank webhook signature verification failed\") {\n super(message);\n this.name = \"AxioRankWebhookSignatureError\";\n }\n}\n","import { AxioRankDeniedError } from \"@axiorank/sdk\";\nimport type { ToolCallResult } from \"@axiorank/sdk\";\nimport type {\n LanguageModelV4Content,\n LanguageModelV4GenerateResult,\n LanguageModelV4StreamPart,\n LanguageModelV4Usage,\n} from \"@ai-sdk/provider\";\nimport type { Verdict } from \"./types\";\n\n/** Zero-valued usage for a synthesized (never-sent) result. */\nexport const ZERO_USAGE: LanguageModelV4Usage = {\n inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },\n outputTokens: { total: 0, text: 0, reasoning: 0 },\n};\n\n/** Build the `AxioRankDeniedError` thrown when `onDeny: \"throw\"`. */\nexport function deniedError(verdict: Verdict): AxioRankDeniedError {\n const result: ToolCallResult = {\n decision: \"deny\",\n reason: verdict.reason,\n risk: verdict.risk,\n auditLogId: \"\",\n signals: verdict.signals,\n };\n return new AxioRankDeniedError(result);\n}\n\n/** A complete generate result whose only content is the refusal text. */\nexport function blockedGenerateResult(\n refusal: string,\n): LanguageModelV4GenerateResult {\n return {\n content: [{ type: \"text\", text: refusal }],\n finishReason: { unified: \"content-filter\", raw: undefined },\n usage: ZERO_USAGE,\n warnings: [],\n };\n}\n\n/**\n * Replace the model's text with a single redacted block, preserving non-text\n * content (tool calls, sources, files) in order. The hosted gateway returns the\n * full masked completion, so the first text part carries it and later text parts\n * are folded away.\n */\nexport function redactCompletionContent(\n content: readonly LanguageModelV4Content[],\n redactedText: string,\n): LanguageModelV4Content[] {\n const out: LanguageModelV4Content[] = [];\n let replaced = false;\n for (const part of content) {\n if (part.type === \"text\") {\n if (!replaced) {\n out.push({ type: \"text\", text: redactedText });\n replaced = true;\n }\n continue;\n }\n out.push(part);\n }\n if (!replaced) out.push({ type: \"text\", text: redactedText });\n return out;\n}\n\n/** Drop the model's text entirely, leaving only the refusal. */\nexport function blockCompletionContent(\n refusal: string,\n): LanguageModelV4Content[] {\n return [{ type: \"text\", text: refusal }];\n}\n\n/**\n * Remove the denied tool-call parts so the AI SDK never executes them, and\n * append a short note (in `block` mode) so the agent can see why and replan.\n */\nexport function stripToolCalls(\n content: readonly LanguageModelV4Content[],\n blockedIds: ReadonlySet<string>,\n note?: string,\n): LanguageModelV4Content[] {\n const out: LanguageModelV4Content[] = content.filter(\n (part) => !(part.type === \"tool-call\" && blockedIds.has(part.toolCallId)),\n );\n if (note) out.push({ type: \"text\", text: note });\n return out;\n}\n\n/** A minimal stream that emits only the refusal text and a finish part. */\nexport function refusalStream(\n refusal: string,\n): ReadableStream<LanguageModelV4StreamPart> {\n const id = \"axiorank-refusal\";\n return new ReadableStream<LanguageModelV4StreamPart>({\n start(controller) {\n controller.enqueue({ type: \"stream-start\", warnings: [] });\n controller.enqueue({ type: \"text-start\", id });\n controller.enqueue({ type: \"text-delta\", id, delta: refusal });\n controller.enqueue({ type: \"text-end\", id });\n controller.enqueue({\n type: \"finish\",\n usage: ZERO_USAGE,\n finishReason: { unified: \"content-filter\", raw: undefined },\n });\n controller.close();\n },\n });\n}\n","import {\n inspect as localInspect,\n inspectCompletion as localInspectCompletion,\n inspectPrompt as localInspectPrompt,\n} from \"@axiorank/sdk\";\nimport type { InspectResult, ToolCallSignal } from \"@axiorank/sdk\";\nimport type { InspectPhase, ResolvedOptions, Verdict } from \"./types\";\n\n/** Correlation metadata attached to each inspection. */\nexport interface CallMeta {\n model?: string;\n traceId?: string;\n}\n\n/**\n * Inspects the three surfaces of a model call. Two implementations back it: a\n * hosted client that calls the AxioRank gateway, and a local client that runs\n * the bundled detectors in-process.\n */\nexport interface Inspector {\n prompt(text: string, meta: CallMeta): Promise<Verdict>;\n completion(text: string, meta: CallMeta): Promise<Verdict>;\n toolCall(\n tool: string,\n args: Record<string, unknown>,\n meta: CallMeta,\n ): Promise<Verdict>;\n}\n\nexport function createInspector(opts: ResolvedOptions): Inspector {\n return opts.mode === \"hosted\"\n ? createHostedInspector(opts)\n : createLocalInspector();\n}\n\n// ---------------------------------------------------------------------------\n// Local (offline) inspection\n// ---------------------------------------------------------------------------\n\nfunction verdictFromLocal(phase: InspectPhase, r: InspectResult): Verdict {\n // Local inspection has no reviewer, so a `hold` (advisory review band) blocks\n // like a `deny`. There is no server-side redaction policy offline.\n return {\n phase,\n decision: r.decision,\n blocked: r.decision !== \"allow\",\n reason: r.reason,\n risk: r.risk,\n signals: r.signals,\n };\n}\n\nfunction createLocalInspector(): Inspector {\n return {\n async prompt(text) {\n return verdictFromLocal(\"prompt\", localInspectPrompt(text));\n },\n async completion(text) {\n return verdictFromLocal(\"completion\", localInspectCompletion(text));\n },\n async toolCall(tool, args) {\n return verdictFromLocal(\"tool-call\", localInspect(tool, args));\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Hosted (gateway) inspection\n// ---------------------------------------------------------------------------\n\ninterface GatewayResponse {\n decision?: string;\n reason?: string;\n risk?: number;\n signals?: ToolCallSignal[];\n transform?: \"redact\";\n redactedText?: string;\n}\n\nfunction verdictFromHosted(phase: InspectPhase, j: GatewayResponse): Verdict {\n const decision =\n j.decision === \"deny\"\n ? \"deny\"\n : j.decision === \"hold\"\n ? \"hold\"\n : j.transform === \"redact\"\n ? \"redact\"\n : \"allow\";\n return {\n phase,\n decision,\n blocked: decision === \"deny\" || decision === \"hold\",\n reason: j.reason ?? \"\",\n risk: typeof j.risk === \"number\" ? j.risk : 0,\n signals: j.signals ?? [],\n redactedText:\n j.transform === \"redact\" ? (j.redactedText ?? \"\") : undefined,\n };\n}\n\nfunction failVerdict(\n phase: InspectPhase,\n opts: ResolvedOptions,\n reason: string,\n): Verdict {\n // fail-open: pass through so an AxioRank outage never breaks the app.\n // fail-closed: deny, so no model I/O is ever ungoverned.\n const blocked = !opts.failOpen;\n return {\n phase,\n decision: blocked ? \"deny\" : \"allow\",\n blocked,\n reason: `AxioRank ${reason} (${opts.failOpen ? \"fail-open\" : \"fail-closed\"})`,\n risk: 0,\n signals: [],\n };\n}\n\nfunction createHostedInspector(opts: ResolvedOptions): Inspector {\n const url = `${opts.baseUrl}/api/gateway/tool-call`;\n\n const post = async (\n phase: InspectPhase,\n body: Record<string, unknown>,\n ): Promise<Verdict> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs);\n try {\n const res = await opts.fetch(url, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${opts.apiKey}`,\n },\n body: JSON.stringify(body),\n signal: controller.signal,\n });\n if (!res.ok) return failVerdict(phase, opts, `returned ${res.status}`);\n const json = (await res.json()) as GatewayResponse;\n return verdictFromHosted(phase, json);\n } catch {\n return failVerdict(phase, opts, \"was unreachable\");\n } finally {\n clearTimeout(timer);\n }\n };\n\n return {\n prompt(text, meta) {\n const model = meta.model ?? opts.model;\n return post(\"prompt\", {\n tool: model ?? \"model\",\n phase: \"prompt\",\n promptText: text,\n model,\n traceId: meta.traceId,\n source: \"sdk\",\n });\n },\n completion(text, meta) {\n const model = meta.model ?? opts.model;\n return post(\"completion\", {\n tool: model ?? \"model\",\n phase: \"completion\",\n completionText: text,\n model,\n traceId: meta.traceId,\n source: \"sdk\",\n });\n },\n toolCall(tool, args, meta) {\n return post(\"tool-call\", {\n tool,\n arguments: args,\n model: meta.model ?? opts.model,\n traceId: meta.traceId,\n source: \"sdk\",\n });\n },\n };\n}\n","import type {\n LanguageModelV4,\n LanguageModelV4CallOptions,\n LanguageModelV4StreamPart,\n LanguageModelV4StreamResult,\n} from \"@ai-sdk/provider\";\nimport { extractPromptText, parseToolInput } from \"./extract\";\nimport { deniedError, refusalStream } from \"./guard-result\";\nimport type { CallMeta, Inspector } from \"./inspect-client\";\nimport type { ResolvedOptions } from \"./types\";\n\ninterface StreamArgs {\n doStream: () => PromiseLike<LanguageModelV4StreamResult>;\n params: LanguageModelV4CallOptions;\n model: LanguageModelV4;\n}\n\n/**\n * Guard a streaming call: inspect the prompt up front (short-circuiting a denied\n * one), then run the completion + tool-call inspection over the stream per the\n * configured `stream` mode.\n */\nexport async function guardStream(\n args: StreamArgs,\n opts: ResolvedOptions,\n inspector: Inspector,\n): Promise<LanguageModelV4StreamResult> {\n const meta: CallMeta = { model: opts.model ?? args.model.modelId };\n\n if (opts.inspectPrompts) {\n const verdict = await inspector.prompt(\n extractPromptText(args.params.prompt),\n meta,\n );\n opts.onDecision?.(\"prompt\", verdict);\n if (verdict.blocked) {\n if (opts.onDeny === \"throw\") throw deniedError(verdict);\n return { stream: refusalStream(opts.refusal) };\n }\n }\n\n const result = await args.doStream();\n const transform =\n opts.stream === \"passthrough\"\n ? passthroughGuard(opts, inspector, meta)\n : bufferGuard(opts, inspector, meta);\n return { ...result, stream: result.stream.pipeThrough(transform) };\n}\n\nfunction collectText(parts: readonly LanguageModelV4StreamPart[]): string {\n return parts\n .flatMap((part) => (part.type === \"text-delta\" ? [part.delta] : []))\n .join(\"\");\n}\n\n/**\n * Buffer mode: hold every part until the source closes, inspect the assembled\n * text and tool calls, then release. Text is redacted or replaced with the\n * refusal before the client sees it; denied tool calls are dropped. This trades\n * first-token latency for correct redaction (the user's chosen default).\n */\nfunction bufferGuard(\n opts: ResolvedOptions,\n inspector: Inspector,\n meta: CallMeta,\n): TransformStream<LanguageModelV4StreamPart, LanguageModelV4StreamPart> {\n const parts: LanguageModelV4StreamPart[] = [];\n return new TransformStream({\n transform(chunk) {\n parts.push(chunk);\n },\n async flush(controller) {\n let redactedText: string | undefined;\n let blockCompletion = false;\n\n if (opts.inspectCompletions) {\n const text = collectText(parts);\n if (text) {\n const verdict = await inspector.completion(text, meta);\n opts.onDecision?.(\"completion\", verdict);\n if (verdict.blocked) {\n if (opts.onDeny === \"throw\") {\n controller.error(deniedError(verdict));\n return;\n }\n blockCompletion = true;\n } else if (\n verdict.decision === \"redact\" &&\n verdict.redactedText !== undefined\n ) {\n redactedText = verdict.redactedText;\n }\n }\n }\n\n const blockedIds = new Set<string>();\n if (opts.inspectToolCalls) {\n for (const part of parts) {\n if (part.type !== \"tool-call\") continue;\n const verdict = await inspector.toolCall(\n part.toolName,\n parseToolInput(part.input),\n meta,\n );\n opts.onDecision?.(\"tool-call\", verdict);\n if (verdict.blocked) {\n if (opts.onDeny === \"throw\") {\n controller.error(deniedError(verdict));\n return;\n }\n blockedIds.add(part.toolCallId);\n }\n }\n }\n\n emitBuffered(\n controller,\n parts,\n blockCompletion ? opts.refusal : redactedText,\n blockedIds,\n );\n },\n });\n}\n\n/**\n * Re-emit buffered parts, substituting a single text block for the model's text\n * when `finalText` is set (block or redact) and dropping the parts of denied\n * tool calls. Non-text parts (reasoning, sources, finish) pass through in order.\n */\nfunction emitBuffered(\n controller: TransformStreamDefaultController<LanguageModelV4StreamPart>,\n parts: readonly LanguageModelV4StreamPart[],\n finalText: string | undefined,\n blockedIds: ReadonlySet<string>,\n): void {\n let emittedText = false;\n for (const part of parts) {\n if (\n part.type === \"text-start\" ||\n part.type === \"text-delta\" ||\n part.type === \"text-end\"\n ) {\n if (finalText === undefined) {\n controller.enqueue(part);\n continue;\n }\n if (!emittedText) {\n const id = part.id;\n controller.enqueue({ type: \"text-start\", id });\n controller.enqueue({ type: \"text-delta\", id, delta: finalText });\n controller.enqueue({ type: \"text-end\", id });\n emittedText = true;\n }\n continue;\n }\n if (part.type === \"tool-call\" && blockedIds.has(part.toolCallId)) continue;\n if (\n (part.type === \"tool-input-start\" ||\n part.type === \"tool-input-delta\" ||\n part.type === \"tool-input-end\") &&\n blockedIds.has(part.id)\n ) {\n continue;\n }\n controller.enqueue(part);\n }\n}\n\n/**\n * Passthrough mode: forward tokens live and inspect at the end for audit only.\n * It cannot retract already-streamed text, so it never redacts; with\n * `onDeny: \"throw\"` a denied verdict errors the stream at the end.\n */\nfunction passthroughGuard(\n opts: ResolvedOptions,\n inspector: Inspector,\n meta: CallMeta,\n): TransformStream<LanguageModelV4StreamPart, LanguageModelV4StreamPart> {\n let text = \"\";\n const toolCalls: { tool: string; args: Record<string, unknown> }[] = [];\n return new TransformStream({\n transform(chunk, controller) {\n controller.enqueue(chunk);\n if (chunk.type === \"text-delta\") text += chunk.delta;\n else if (chunk.type === \"tool-call\") {\n toolCalls.push({\n tool: chunk.toolName,\n args: parseToolInput(chunk.input),\n });\n }\n },\n async flush(controller) {\n if (opts.inspectCompletions && text) {\n const verdict = await inspector.completion(text, meta);\n opts.onDecision?.(\"completion\", verdict);\n if (verdict.blocked && opts.onDeny === \"throw\") {\n controller.error(deniedError(verdict));\n return;\n }\n }\n if (opts.inspectToolCalls) {\n for (const call of toolCalls) {\n const verdict = await inspector.toolCall(call.tool, call.args, meta);\n opts.onDecision?.(\"tool-call\", verdict);\n if (verdict.blocked && opts.onDeny === \"throw\") {\n controller.error(deniedError(verdict));\n return;\n }\n }\n }\n },\n });\n}\n","import type { ToolCallSignal } from \"@axiorank/sdk\";\n\n/** Which surface of a model call a {@link Verdict} came from. */\nexport type InspectPhase = \"prompt\" | \"completion\" | \"tool-call\";\n\n/**\n * A normalized inspection verdict, shared across hosted and local inspection.\n * `blocked` is the single field the middleware acts on: `true` means deny the\n * surface (refuse or throw). `redact` is a separate, non-blocking outcome that\n * swaps in {@link redactedText}.\n */\nexport interface Verdict {\n /** The surface this verdict is about. */\n phase: InspectPhase;\n /** `deny`/`hold` block; `redact` masks a completion; `allow` passes through. */\n decision: \"allow\" | \"deny\" | \"hold\" | \"redact\";\n /** True when the surface should be denied (`deny` or `hold`). */\n blocked: boolean;\n /** Human-readable explanation for the decision. */\n reason: string;\n /** Risk score (0-100) the engine assigned. */\n risk: number;\n /** Redacted content-inspection findings that drove the score. */\n signals: ToolCallSignal[];\n /**\n * The masked completion to return in place of the model's text. Present only\n * when {@link decision} is `redact` (hosted model-output redaction policy).\n */\n redactedText?: string;\n}\n\n/**\n * Configuration for {@link createAxioRankMiddleware}. Every field is optional;\n * the defaults mirror the Python LiteLLM guardrail (inspect every surface, block\n * gracefully, fail open).\n */\nexport interface AxioRankMiddlewareOptions {\n /** AxioRank API key. Falls back to `AXIORANK_API_KEY`, then `AXIORANK_KEY`. */\n apiKey?: string;\n /** Gateway base URL. Falls back to `AXIORANK_BASE_URL`, then app.axiorank.com. */\n baseUrl?: string;\n /**\n * `hosted` calls the AxioRank gateway (your workspace's real policy, audit\n * trail, and completion redaction). `local` runs the bundled detectors\n * in-process with no key and no network (advisory, block-on-deny only).\n * Defaults to `hosted` when an API key resolves, otherwise `local`.\n */\n mode?: \"hosted\" | \"local\";\n /**\n * `block` (default) refuses gracefully: a denied prompt/completion is replaced\n * with {@link refusal}, a denied tool call is stripped. `throw` raises\n * `AxioRankDeniedError` from `@axiorank/sdk` instead.\n */\n onDeny?: \"block\" | \"throw\";\n /**\n * When the gateway is unreachable or errors, `true` (default) lets the call\n * through so an AxioRank outage never breaks your app; `false` blocks it\n * (zero-trust). Only affects `hosted` mode. Local inspection never fails.\n */\n failOpen?: boolean;\n /** Inspect the outgoing prompt. Default `true`. */\n inspectPrompts?: boolean;\n /** Inspect (and redact) the model completion. Default `true`. */\n inspectCompletions?: boolean;\n /** Inspect the tool calls the model proposes. Default `true`. */\n inspectToolCalls?: boolean;\n /**\n * `buffer` (default) accumulates streamed text, inspects it, then releases it,\n * so a mid-stream secret can be redacted or blocked before the client sees it\n * (adds latency to the first visible token). `passthrough` streams tokens live\n * and inspects at the end for audit only (it cannot retract already-streamed\n * text).\n */\n stream?: \"buffer\" | \"passthrough\";\n /** Text substituted for blocked prompts/completions. Default `[blocked by AxioRank]`. */\n refusal?: string;\n /** Observe every verdict (never changes flow). Useful for logging/metrics. */\n onDecision?: (phase: InspectPhase, verdict: Verdict) => void;\n /** Per-request timeout in ms for hosted inspection. Default `10000`. */\n timeoutMs?: number;\n /** Model label sent to the gateway (spend/routing). Defaults to the call's model id. */\n model?: string;\n /** Custom fetch implementation (defaults to `globalThis.fetch`). */\n fetch?: typeof fetch;\n}\n\n/** Fully-resolved options with defaults applied (internal). */\nexport interface ResolvedOptions {\n mode: \"hosted\" | \"local\";\n apiKey?: string;\n baseUrl: string;\n onDeny: \"block\" | \"throw\";\n failOpen: boolean;\n inspectPrompts: boolean;\n inspectCompletions: boolean;\n inspectToolCalls: boolean;\n stream: \"buffer\" | \"passthrough\";\n refusal: string;\n onDecision?: (phase: InspectPhase, verdict: Verdict) => void;\n timeoutMs: number;\n model?: string;\n fetch: typeof fetch;\n}\n\nexport const DEFAULT_BASE_URL = \"https://app.axiorank.com\";\nexport const DEFAULT_REFUSAL = \"[blocked by AxioRank]\";\n\n/** Apply defaults and env-var fallbacks to raw options. */\nexport function resolveOptions(o: AxioRankMiddlewareOptions = {}): ResolvedOptions {\n const apiKey =\n o.apiKey ?? process.env.AXIORANK_API_KEY ?? process.env.AXIORANK_KEY;\n const baseUrl = (\n o.baseUrl ??\n process.env.AXIORANK_BASE_URL ??\n DEFAULT_BASE_URL\n ).replace(/\\/+$/, \"\");\n // Fall back to local (advisory) inspection when hosted is requested but there\n // is no key to authenticate with, rather than fail-open to a silent no-op.\n const requested = o.mode ?? (apiKey ? \"hosted\" : \"local\");\n const mode = requested === \"hosted\" && !apiKey ? \"local\" : requested;\n\n return {\n mode,\n apiKey,\n baseUrl,\n onDeny: o.onDeny ?? \"block\",\n failOpen: o.failOpen ?? true,\n inspectPrompts: o.inspectPrompts ?? true,\n inspectCompletions: o.inspectCompletions ?? true,\n inspectToolCalls: o.inspectToolCalls ?? true,\n stream: o.stream ?? \"buffer\",\n refusal: o.refusal ?? DEFAULT_REFUSAL,\n onDecision: o.onDecision,\n timeoutMs: o.timeoutMs ?? 10_000,\n model: o.model,\n fetch: o.fetch ?? globalThis.fetch,\n };\n}\n","import type { LanguageModelMiddleware } from \"ai\";\nimport {\n extractCompletionText,\n extractPromptText,\n extractToolCalls,\n parseToolInput,\n} from \"./extract\";\nimport {\n blockCompletionContent,\n blockedGenerateResult,\n deniedError,\n redactCompletionContent,\n stripToolCalls,\n} from \"./guard-result\";\nimport { createInspector, type CallMeta } from \"./inspect-client\";\nimport { guardStream } from \"./stream\";\nimport {\n type AxioRankMiddlewareOptions,\n resolveOptions,\n} from \"./types\";\n\n/**\n * Create an AxioRank guardrail as a Vercel AI SDK `LanguageModelMiddleware`.\n * Wrap any model with `wrapLanguageModel({ model, middleware })` and every\n * `generateText` / `streamText` / `generateObject` through it is governed: the\n * prompt is inspected before it is sent, the completion is inspected and\n * optionally redacted before your app sees it, and the tool calls the model\n * proposes are inspected before the SDK executes them.\n *\n * @example\n * ```ts\n * import { wrapLanguageModel } from \"ai\";\n * import { openai } from \"@ai-sdk/openai\";\n * import { createAxioRankMiddleware } from \"@axiorank/ai-sdk\";\n *\n * const model = wrapLanguageModel({\n * model: openai(\"gpt-4o\"),\n * middleware: createAxioRankMiddleware({ apiKey: process.env.AXIORANK_KEY }),\n * });\n * ```\n */\nexport function createAxioRankMiddleware(\n options: AxioRankMiddlewareOptions = {},\n): LanguageModelMiddleware {\n const opts = resolveOptions(options);\n const inspector = createInspector(opts);\n\n return {\n specificationVersion: \"v4\",\n\n async wrapGenerate({ doGenerate, params, model }) {\n const meta: CallMeta = { model: opts.model ?? model.modelId };\n\n if (opts.inspectPrompts) {\n const verdict = await inspector.prompt(\n extractPromptText(params.prompt),\n meta,\n );\n opts.onDecision?.(\"prompt\", verdict);\n if (verdict.blocked) {\n if (opts.onDeny === \"throw\") throw deniedError(verdict);\n return blockedGenerateResult(opts.refusal);\n }\n }\n\n const result = await doGenerate();\n let content = result.content;\n\n if (opts.inspectCompletions) {\n const text = extractCompletionText(content);\n if (text) {\n const verdict = await inspector.completion(text, meta);\n opts.onDecision?.(\"completion\", verdict);\n if (verdict.blocked) {\n if (opts.onDeny === \"throw\") throw deniedError(verdict);\n content = blockCompletionContent(opts.refusal);\n } else if (\n verdict.decision === \"redact\" &&\n verdict.redactedText !== undefined\n ) {\n content = redactCompletionContent(content, verdict.redactedText);\n }\n }\n }\n\n if (opts.inspectToolCalls) {\n const calls = extractToolCalls(content);\n if (calls.length > 0) {\n const blockedIds = new Set<string>();\n for (const call of calls) {\n const verdict = await inspector.toolCall(\n call.toolName,\n parseToolInput(call.input),\n meta,\n );\n opts.onDecision?.(\"tool-call\", verdict);\n if (verdict.blocked) {\n if (opts.onDeny === \"throw\") throw deniedError(verdict);\n blockedIds.add(call.toolCallId);\n }\n }\n if (blockedIds.size > 0) {\n content = stripToolCalls(\n content,\n blockedIds,\n `${opts.refusal} (${blockedIds.size} tool call(s) removed)`,\n );\n }\n }\n }\n\n return content === result.content ? result : { ...result, content };\n },\n\n async wrapStream({ doStream, params, model }) {\n return guardStream({ doStream, params, model }, opts, inspector);\n },\n };\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@axiorank/ai-sdk",
3
+ "version": "0.1.0",
4
+ "description": "AxioRank guardrail middleware for the Vercel AI SDK. Inspect and redact prompts, completions, and proposed tool calls on every generateText and streamText.",
5
+ "license": "MIT",
6
+ "homepage": "https://axiorank.com",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/frostyhand/AxioRank.git",
10
+ "directory": "packages/ai-sdk"
11
+ },
12
+ "bugs": "https://github.com/frostyhand/AxioRank/issues",
13
+ "author": "AxioRank",
14
+ "type": "module",
15
+ "main": "./dist/index.cjs",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js",
22
+ "require": "./dist/index.cjs"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "sideEffects": false,
32
+ "keywords": [
33
+ "axiorank",
34
+ "ai",
35
+ "vercel-ai-sdk",
36
+ "ai-sdk",
37
+ "middleware",
38
+ "wraplanguagemodel",
39
+ "guardrails",
40
+ "llm",
41
+ "security",
42
+ "gateway",
43
+ "prompt-injection",
44
+ "secrets-detection",
45
+ "pii",
46
+ "redaction",
47
+ "agent-security"
48
+ ],
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "peerDependencies": {
53
+ "ai": "^7.0.0"
54
+ },
55
+ "devDependencies": {
56
+ "@ai-sdk/provider": "^4.0.0",
57
+ "@types/node": "^22.10.0",
58
+ "ai": "^7.0.0",
59
+ "tsup": "^8.3.5",
60
+ "typescript": "^6.0.3",
61
+ "vite": "^8.0.16",
62
+ "vitest": "^4.1.8",
63
+ "@axiorank/sdk": "0.18.0"
64
+ },
65
+ "scripts": {
66
+ "build": "tsup",
67
+ "dev": "tsup --watch",
68
+ "typecheck": "tsc --noEmit",
69
+ "test": "vitest run"
70
+ }
71
+ }