{"version":3,"sources":["../src/errors.ts","../src/client.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/validators.ts","../../detectors/src/detectors/financial.ts","../../detectors/src/detectors/injection.ts","../../detectors/src/detectors/jailbreak.ts","../../detectors/src/detectors/malware.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","../src/inspect.ts","../src/verify.ts","../src/verify-surface.ts","../src/middleware.ts","../src/webhooks.ts","../src/integrations/_chat.ts","../src/integrations/chat-guards.ts","../src/realtime.ts"],"names":["SPECS","b","DEFAULT_BASE_URL","DEFAULT_TIMEOUT_MS"],"mappings":";;;AAGO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF;AAGO,IAAM,iBAAA,GAAN,cAAgC,aAAA,CAAc;AAAA,EACnD,WAAA,CAAY,UAAU,qCAAA,EAAuC;AAC3D,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AAAA,EACd;AACF;AAGO,IAAM,oBAAA,GAAN,cAAmC,aAAA,CAAc;AAAA,EACtD,MAAA;AAAA,EACA,WAAA,CAAY,SAAiB,MAAA,EAAiB;AAC5C,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EA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,OAAA,EAAQ;AAAA,EACjB;AAEA,EAAA,OAAO,EAAE,aAAA,EAAe,OAAA,EAAS,KAAA,CAAM,EAAA,EAAG;AAC5C","file":"index.cjs","sourcesContent":["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 type {\n  AxioRankOptions,\n  AxioTrace,\n  CardVerifyResult,\n  ToolCallParams,\n  ToolCallResult,\n  ToolResultParams,\n  VerifyCardParams,\n} from \"./types\";\nimport {\n  AxioRankAuthError,\n  AxioRankCardDeniedError,\n  AxioRankDeniedError,\n  AxioRankError,\n  AxioRankRateLimitError,\n  AxioRankRequestError,\n} from \"./errors\";\n\nconst DEFAULT_BASE_URL = \"https://app.axiorank.com\";\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_APPROVAL_TIMEOUT_MS = 300_000;\nconst TOOL_CALL_PATH = \"/api/gateway/tool-call\";\nconst VERIFY_CARD_PATH = \"/api/gateway/verify-card\";\nconst APPROVALS_PATH = \"/api/gateway/approvals\";\nconst TOKEN_PATH = \"/api/gateway/token\";\n// Refresh a short-lived token this long before it actually expires.\nconst TOKEN_REFRESH_SKEW_MS = 60_000;\n\nconst delay = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));\n\n/**\n * AxioRank SDK client.\n *\n * @example\n * ```ts\n * const axio = new AxioRank({ apiKey: process.env.AXIORANK_KEY! });\n * const { decision } = await axio.toolCall({ tool: \"github.push\", arguments: {} });\n * ```\n */\nexport class AxioRank {\n  private readonly apiKey?: string;\n  private readonly baseUrl: string;\n  private readonly timeoutMs: number;\n  private readonly approvalTimeoutMs: number;\n  private readonly fetchImpl: typeof fetch;\n  private readonly defaultTraceId?: string;\n  private readonly defaultSessionId?: string;\n\n  // Unavailability posture: what to assume when the gateway is unreachable. The\n  // constructor override wins; else the last posture the gateway reported (learned\n  // per verdict); else fail_open. Applied in submitToolCall via `degraded`.\n  private readonly onUnavailableOverride?: \"fail_open\" | \"fail_closed\";\n  private readonly onDegraded?: AxioRankOptions[\"onDegraded\"];\n  private lastKnownBehavior?: \"fail_open\" | \"fail_closed\";\n\n  // Identity: when enabled, exchange the key (or a federated OIDC token) for\n  // short-lived, auto-refreshed gateway tokens instead of sending a static key.\n  private readonly useTokens: boolean;\n  private readonly subjectToken?: string;\n  private readonly subjectTokenProvider?: () => string | Promise<string>;\n  private readonly tokenScopes?: string[];\n  private readonly tokenTtlSeconds?: number;\n  private cachedToken?: { token: string; expMs: number };\n  private inflightToken?: Promise<string | null>;\n\n  constructor(options: AxioRankOptions) {\n    const hasFederation = Boolean(\n      options?.subjectToken || options?.subjectTokenProvider,\n    );\n    if (!options || (!options.apiKey && !hasFederation)) {\n      throw new AxioRankError(\n        \"AxioRank: `apiKey` (or a federated `subjectToken`/`subjectTokenProvider`) is required\",\n      );\n    }\n    this.apiKey = options.apiKey;\n    this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n    this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n    this.approvalTimeoutMs = options.approvalTimeoutMs ?? DEFAULT_APPROVAL_TIMEOUT_MS;\n    this.defaultTraceId = options.traceId;\n    this.defaultSessionId = options.sessionId;\n    this.onUnavailableOverride = options.onUnavailable;\n    this.onDegraded = options.onDegraded;\n\n    this.subjectToken = options.subjectToken;\n    this.subjectTokenProvider = options.subjectTokenProvider;\n    this.tokenScopes = options.tokenScopes;\n    this.tokenTtlSeconds = options.tokenTtlSeconds;\n    // Federation implies token mode; otherwise opt-in (a non-breaking default).\n    this.useTokens = options.useTokens ?? hasFederation;\n\n    const resolvedFetch = options.fetch ?? globalThis.fetch;\n    if (typeof resolvedFetch !== \"function\") {\n      throw new AxioRankError(\n        \"AxioRank: no global `fetch` found - pass `options.fetch` explicitly\",\n      );\n    }\n    this.fetchImpl = resolvedFetch;\n  }\n\n  /**\n   * The bearer credential to send. In token mode, returns a cached short-lived\n   * token (minting / refreshing as needed, with concurrent refreshes coalesced);\n   * otherwise the static api key. If a token exchange fails but a static key is\n   * available, falls back to it so an older gateway (no `/token` endpoint) keeps\n   * working unchanged.\n   */\n  private async authHeader(): Promise<string> {\n    if (!this.useTokens) {\n      // Guaranteed by the constructor: non-token mode always has an api key.\n      return this.apiKey as string;\n    }\n    const cached = this.cachedToken;\n    if (cached && Date.now() < cached.expMs - TOKEN_REFRESH_SKEW_MS) {\n      return cached.token;\n    }\n    if (!this.inflightToken) {\n      this.inflightToken = this.exchangeToken().finally(() => {\n        this.inflightToken = undefined;\n      });\n    }\n    const token = await this.inflightToken;\n    if (token) return token;\n    if (this.apiKey) return this.apiKey; // graceful fallback to the static key\n    throw new AxioRankAuthError();\n  }\n\n  private invalidateToken(): void {\n    this.cachedToken = undefined;\n  }\n\n  /**\n   * Exchange the api key (or a federated OIDC token) for a short-lived token at\n   * `/api/gateway/token`. Returns the token, or null on any failure (so callers\n   * can fall back to the static key).\n   */\n  private async exchangeToken(): Promise<string | null> {\n    const headers: Record<string, string> = { \"content-type\": \"application/json\" };\n    const body: Record<string, unknown> = {};\n    if (this.subjectToken || this.subjectTokenProvider) {\n      const subject = this.subjectToken ?? (await this.subjectTokenProvider!());\n      body.grant_type = \"federated\";\n      body.subject_token = subject;\n    } else if (this.apiKey) {\n      headers.authorization = `Bearer ${this.apiKey}`;\n    } else {\n      return null;\n    }\n    if (this.tokenScopes) body.scopes = this.tokenScopes;\n    if (this.tokenTtlSeconds) body.ttl_seconds = this.tokenTtlSeconds;\n\n    const controller = new AbortController();\n    const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n    try {\n      const res = await this.fetchImpl(`${this.baseUrl}${TOKEN_PATH}`, {\n        method: \"POST\",\n        headers,\n        body: JSON.stringify(body),\n        signal: controller.signal,\n      });\n      if (!res.ok) return null;\n      const parsed = (await res.json()) as { token?: string; expires_in?: number };\n      if (!parsed.token) return null;\n      const ttlMs = (parsed.expires_in ?? 900) * 1000;\n      this.cachedToken = { token: parsed.token, expMs: Date.now() + ttlMs };\n      return parsed.token;\n    } catch {\n      return null;\n    } finally {\n      clearTimeout(timer);\n    }\n  }\n\n  /**\n   * Send a tool call to the gateway and resolve with the policy decision.\n   * Throws {@link AxioRankAuthError} / {@link AxioRankRequestError} on errors,\n   * but resolves normally for an explicit `deny` decision.\n   */\n  async toolCall(params: ToolCallParams): Promise<ToolCallResult> {\n    if (!params || !params.tool) {\n      throw new AxioRankError(\"AxioRank: `tool` is required\");\n    }\n    return this.submitToolCall({\n      tool: params.tool,\n      arguments: params.arguments ?? {},\n      // `undefined` is omitted by JSON.stringify → the wire is unchanged when no\n      // trace is in use. Precedence: explicit param > constructor default.\n      traceId: params.traceId ?? this.defaultTraceId,\n      stepIndex: params.stepIndex,\n      sessionId: params.sessionId ?? this.defaultSessionId,\n      metadata: params.metadata,\n      parentStepIndex: params.parentStepIndex,\n      costUsd: params.costUsd,\n      model: params.model,\n      inputTokens: params.inputTokens,\n      outputTokens: params.outputTokens,\n      durationMs: params.durationMs,\n      intent: params.intent,\n      passport: params.passport,\n      source: params.source,\n    });\n  }\n\n  /**\n   * POST a tool-call payload (request or result phase) and resolve with the\n   * decision, transparently waiting out a `require_approval` hold so callers only\n   * ever see the final `allow` / `deny`. Shared by {@link toolCall} and\n   * {@link inspectResult}.\n   */\n  private async submitToolCall(\n    payload: Record<string, unknown>,\n  ): Promise<ToolCallResult> {\n    const tool = typeof payload.tool === \"string\" ? payload.tool : \"\";\n    let res: Response;\n    try {\n      res = await this.fetchWithRetry(`${this.baseUrl}${TOOL_CALL_PATH}`, {\n        method: \"POST\",\n        headers: { \"content-type\": \"application/json\" },\n        body: JSON.stringify(payload),\n      });\n    } catch (err) {\n      // A timeout or network error means the gateway is UNREACHABLE - fetchWithRetry\n      // throws an AxioRankRequestError with no HTTP status for those. Apply the\n      // configured posture rather than throwing into the caller's tool site. A rate\n      // limit (AxioRankRateLimitError) or any status-bearing error means the gateway\n      // answered, so let it propagate.\n      if (err instanceof AxioRankRequestError && err.status === undefined) {\n        return this.degraded(\n          tool,\n          err.message.includes(\"timed out\") ? \"timeout\" : \"network\",\n        );\n      }\n      throw err;\n    }\n\n    if (res.status === 401) {\n      throw new AxioRankAuthError();\n    }\n\n    // A 5xx means the gateway is up but unhealthy - treat it as unavailable. A 4xx\n    // is a real, definitive answer (bad request / forbidden) and must surface.\n    if (res.status >= 500) {\n      return this.degraded(tool, \"5xx\");\n    }\n\n    let body: unknown = null;\n    try {\n      body = await res.json();\n    } catch {\n      // leave body null; handled below\n    }\n\n    if (!res.ok) {\n      const message =\n        (body as { error?: string } | null)?.error ??\n        `request failed with status ${res.status}`;\n      throw new AxioRankRequestError(`AxioRank: ${message}`, res.status);\n    }\n\n    const result = body as ToolCallResult;\n    // Learn the current unavailability posture from a real verdict, so a later\n    // outage applies the agent/workspace's configured behavior with no side fetch.\n    if (\n      result.unavailabilityBehavior === \"fail_open\" ||\n      result.unavailabilityBehavior === \"fail_closed\"\n    ) {\n      this.lastKnownBehavior = result.unavailabilityBehavior;\n    }\n    const held = body as { decision?: string; approvalId?: string };\n    if (held.decision === \"hold\" && held.approvalId) {\n      return this.waitForApproval(held.approvalId, result);\n    }\n    return result;\n  }\n\n  /**\n   * Resolve a call locally when the gateway is unreachable. Precedence: the\n   * constructor `onUnavailable` override > the last posture the gateway reported >\n   * `fail_open` (the safe, non-blocking default). `fail_closed` yields a `deny` (so\n   * {@link enforce} throws and no ungoverned call proceeds); `fail_open` yields an\n   * `allow`. Marked `degraded` so callers and telemetry can tell it apart from a\n   * real verdict.\n   */\n  private degraded(\n    tool: string,\n    reason: \"timeout\" | \"network\" | \"5xx\",\n  ): ToolCallResult {\n    const behavior =\n      this.onUnavailableOverride ?? this.lastKnownBehavior ?? \"fail_open\";\n    const decision = behavior === \"fail_closed\" ? \"deny\" : \"allow\";\n    try {\n      this.onDegraded?.({ tool, reason, decision });\n    } catch {\n      // A telemetry callback must never break the call path.\n    }\n    return {\n      decision,\n      reason: `AxioRank unavailable (${reason}); ${behavior} applied`,\n      risk: 0,\n      auditLogId: \"\",\n      signals: [],\n      degraded: true,\n    };\n  }\n\n  /**\n   * Inspect a tool's RESULT (phase=\"result\") and resolve with the decision -\n   * the enforce-capable counterpart to {@link reportResult}. Use it to catch\n   * indirect prompt injection (or a leaked secret / PII) in what a tool returned\n   * BEFORE the agent ingests it: a `deny` means block or redact the output.\n   *\n   * Inspection is opt-in per workspace (`inspect_tool_results`); when it's off,\n   * the gateway scores + audits the result but always resolves `allow`\n   * (monitor-first). The framework adapters call this automatically for\n   * untrusted-source tools when you pass `inspectResults: true`.\n   *\n   * @example\n   * ```ts\n   * const page = await fetchUrl(url);\n   * const { decision } = await axio.inspectResult({ tool: \"web.fetch\", resultText: page });\n   * if (decision === \"deny\") page = \"[blocked: untrusted content removed]\";\n   * ```\n   */\n  async inspectResult(params: ToolResultParams): Promise<ToolCallResult> {\n    if (!params || !params.tool) {\n      throw new AxioRankError(\"AxioRank: `tool` is required\");\n    }\n    return this.submitToolCall({\n      tool: params.tool,\n      phase: \"result\",\n      resultText: params.resultText ?? \"\",\n      traceId: params.traceId ?? this.defaultTraceId,\n      stepIndex: params.stepIndex,\n      sessionId: this.defaultSessionId,\n      taintHandle: params.taintHandle,\n    });\n  }\n\n  /**\n   * Poll the approvals endpoint until a held call is resolved (the gateway\n   * long-polls, so this is cheap), resolving to the final allow/deny. After\n   * {@link AxioRankOptions.approvalTimeoutMs} it gives up and returns `deny`.\n   */\n  private async waitForApproval(\n    approvalId: string,\n    held: ToolCallResult,\n  ): Promise<ToolCallResult> {\n    const url = `${this.baseUrl}${APPROVALS_PATH}/${approvalId}`;\n    const deadline = Date.now() + this.approvalTimeoutMs;\n\n    while (Date.now() < deadline) {\n      const controller = new AbortController();\n      // Generous per-poll timeout - longer than the gateway's long-poll window.\n      const timer = setTimeout(() => controller.abort(), 20_000);\n      let status: { decision?: string; reason?: string } | null = null;\n      try {\n        const res = await this.fetchImpl(url, {\n          headers: { authorization: `Bearer ${await this.authHeader()}` },\n          signal: controller.signal,\n        });\n        if (res.status === 401) {\n          // A token may have expired mid-wait - refresh once and keep polling.\n          if (this.useTokens) {\n            this.invalidateToken();\n            await delay(500);\n            continue;\n          }\n          throw new AxioRankAuthError();\n        }\n        status = (await res.json()) as { decision?: string; reason?: string };\n      } catch (err) {\n        if (err instanceof AxioRankAuthError) throw err;\n        // Transient network/timeout while polling - back off and retry.\n        await delay(1_000);\n        continue;\n      } finally {\n        clearTimeout(timer);\n      }\n\n      if (status?.decision && status.decision !== \"hold\") {\n        return {\n          decision: status.decision as ToolCallResult[\"decision\"],\n          reason: status.reason ?? held.reason,\n          risk: held.risk,\n          auditLogId: held.auditLogId,\n          signals: held.signals,\n        };\n      }\n    }\n\n    return {\n      decision: \"deny\",\n      reason: \"AxioRank: approval timed out\",\n      risk: held.risk,\n      auditLogId: held.auditLogId,\n      signals: held.signals,\n    };\n  }\n\n  /**\n   * Like {@link toolCall}, but throws {@link AxioRankDeniedError} when the\n   * decision is `deny` - convenient for guarding a tool call in one line.\n   */\n  async enforce(params: ToolCallParams): Promise<ToolCallResult> {\n    const result = await this.toolCall(params);\n    if (result.decision === \"deny\") {\n      throw new AxioRankDeniedError(result);\n    }\n    return result;\n  }\n\n  /**\n   * Report a tool's RESULT to the gateway for information-flow-control taint\n   * tracking (phase=\"result\"). Best-effort telemetry: never throws and never\n   * blocks your agent. The guard wrappers call this automatically for\n   * untrusted-source tools when the workspace enforces IFC; you rarely call it\n   * directly.\n   */\n  async reportResult(params: ToolResultParams): Promise<void> {\n    if (!params?.tool) return;\n    const controller = new AbortController();\n    const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n    try {\n      await this.fetchImpl(`${this.baseUrl}${TOOL_CALL_PATH}`, {\n        method: \"POST\",\n        headers: {\n          \"content-type\": \"application/json\",\n          authorization: `Bearer ${await this.authHeader()}`,\n        },\n        body: JSON.stringify({\n          tool: params.tool,\n          phase: \"result\",\n          resultText: params.resultText,\n          traceId: params.traceId ?? this.defaultTraceId,\n          stepIndex: params.stepIndex,\n          sessionId: this.defaultSessionId,\n          taintHandle: params.taintHandle,\n        }),\n        signal: controller.signal,\n      });\n    } catch {\n      // Best-effort: a failed result report must never disrupt the agent.\n    } finally {\n      clearTimeout(timer);\n    }\n  }\n\n  /**\n   * Begin a correlated trace (one agent run). Every call made through the\n   * returned handle shares a trace id and gets an auto-incrementing step index,\n   * so the gateway can correlate them into a multi-step kill chain (e.g. read a\n   * secret → exfiltrate it). Pass your own id to join an existing trace.\n   *\n   * Pass `{ intent }` to declare the user task this run serves: the handle sends\n   * it on its first request-phase call, the gateway stores it once per trace\n   * (redacted), and the AI flow judge uses it to release data-flow holds that\n   * clearly serve the task.\n   *\n   * @example\n   * ```ts\n   * const t = axio.trace();                          // generated uuid\n   * await t.enforce({ tool: \"vault.read\" });         // step 0\n   * await t.toolCall({ tool: \"http.post\", ... });    // step 1\n   *\n   * const t2 = axio.trace({ intent: \"Reply to Bob's email about the offsite\" });\n   * ```\n   */\n  trace(\n    traceIdOrOptions?:\n      | string\n      | {\n          id?: string;\n          intent?: string;\n          /** Session grouping this run with its sibling runs (one conversation). */\n          sessionId?: string;\n          /** Metadata tags sent on every call made through this handle (a\n           *  per-call `metadata` wins on key conflicts). */\n          metadata?: Record<string, string | number | boolean>;\n        },\n  ): AxioTrace {\n    const opts =\n      typeof traceIdOrOptions === \"string\" || traceIdOrOptions === undefined\n        ? { id: traceIdOrOptions }\n        : traceIdOrOptions;\n    const traceId = opts.id ?? crypto.randomUUID();\n    const sessionId = opts.sessionId ?? this.defaultSessionId;\n    // ONE counter shared by the root handle and every child(): step indexes\n    // must stay unique across the whole run. `last` remembers the most recent\n    // issued step so child() can default its parent to the spawning call.\n    const counter = { next: 0, last: undefined as number | undefined };\n    // The intent is sent once, on the first request-phase call (the gateway\n    // stores it per trace; first write wins, so re-sends would be wasteful).\n    let pendingIntent = opts.intent;\n    const takeIntent = (explicit?: string): string | undefined => {\n      if (explicit !== undefined) return explicit;\n      const intent = pendingIntent;\n      pendingIntent = undefined;\n      return intent;\n    };\n    const issueStep = (explicit?: number): number => {\n      const idx = explicit ?? counter.next++;\n      counter.last = idx;\n      if (idx >= counter.next) counter.next = idx + 1;\n      return idx;\n    };\n\n    const makeHandle = (base: {\n      parentStepIndex?: number;\n      metadata?: Record<string, string | number | boolean>;\n    }): AxioTrace => {\n      const mergeMetadata = (\n        perCall?: Record<string, string | number | boolean>,\n      ): Record<string, string | number | boolean> | undefined => {\n        if (!base.metadata) return perCall;\n        return perCall ? { ...base.metadata, ...perCall } : base.metadata;\n      };\n      return {\n        id: traceId,\n        toolCall: (p) =>\n          this.toolCall({\n            ...p,\n            traceId,\n            stepIndex: issueStep(p.stepIndex),\n            sessionId: p.sessionId ?? sessionId,\n            metadata: mergeMetadata(p.metadata),\n            parentStepIndex: p.parentStepIndex ?? base.parentStepIndex,\n            intent: takeIntent(p.intent),\n          }),\n        enforce: (p) =>\n          this.enforce({\n            ...p,\n            traceId,\n            stepIndex: issueStep(p.stepIndex),\n            sessionId: p.sessionId ?? sessionId,\n            metadata: mergeMetadata(p.metadata),\n            parentStepIndex: p.parentStepIndex ?? base.parentStepIndex,\n            intent: takeIntent(p.intent),\n          }),\n        reportResult: (p) => this.reportResult({ ...p, traceId: p.traceId ?? traceId }),\n        inspectResult: (p) =>\n          this.inspectResult({ ...p, traceId: p.traceId ?? traceId }),\n        // Correlation headers for AI Gateway model calls. No step index: the\n        // proxy's turns order by created_at, and reading the auto-counter here\n        // would burn step numbers the tool calls need.\n        headers: () => {\n          const h: Record<string, string> = { \"X-AxioRank-Trace-Id\": traceId };\n          if (sessionId) h[\"X-AxioRank-Session-Id\"] = sessionId;\n          if (base.parentStepIndex !== undefined) {\n            h[\"X-AxioRank-Parent-Step-Index\"] = String(base.parentStepIndex);\n          }\n          return h;\n        },\n        // Sub-agent view: same run, same counter; every call nests under the\n        // spawning step (default: the step this handle issued most recently).\n        child: (childOpts) =>\n          makeHandle({\n            parentStepIndex: childOpts?.parentStepIndex ?? counter.last,\n            metadata: childOpts?.metadata\n              ? { ...base.metadata, ...childOpts.metadata }\n              : base.metadata,\n          }),\n      };\n    };\n\n    return makeHandle({ metadata: opts.metadata });\n  }\n\n  /**\n   * Preflight an external MCP server or A2A agent BEFORE your agent trusts it:\n   * AxioRank fetches its card, verifies the signature / auth hygiene, scores the\n   * declared capabilities, and returns `allow | review | deny`. Pass either a\n   * `url` to fetch from or an inline `document` you already hold.\n   *\n   * @example\n   * ```ts\n   * const { decision, risk } = await axio.verifyCard({ url: \"https://mcp.acme.com\" });\n   * ```\n   */\n  async verifyCard(params: VerifyCardParams): Promise<CardVerifyResult> {\n    if (!params || (params.url === undefined && params.document === undefined)) {\n      throw new AxioRankError(\"AxioRank: `url` or `document` is required\");\n    }\n    return this.request<CardVerifyResult>(VERIFY_CARD_PATH, {\n      url: params.url,\n      document: params.document,\n      protocol: params.protocol,\n    });\n  }\n\n  /**\n   * Like {@link verifyCard}, but throws {@link AxioRankCardDeniedError} when the\n   * verdict is `deny` - guard a connection to an untrusted target in one line.\n   */\n  async enforceCard(params: VerifyCardParams): Promise<CardVerifyResult> {\n    const result = await this.verifyCard(params);\n    if (result.decision === \"deny\") {\n      throw new AxioRankCardDeniedError(result);\n    }\n    return result;\n  }\n\n  /**\n   * Fetch with a per-attempt timeout, retrying on 429 with backoff (honoring\n   * Retry-After). Throws {@link AxioRankRateLimitError} once retries are spent.\n   */\n  private async fetchWithRetry(\n    url: string,\n    init: RequestInit,\n  ): Promise<Response> {\n    const maxAttempts = 4;\n    let refreshedOn401 = false;\n    for (let attempt = 1; ; attempt++) {\n      // Attach auth per attempt so a refreshed token is picked up on retry.\n      const headers = {\n        ...(init.headers as Record<string, string> | undefined),\n        authorization: `Bearer ${await this.authHeader()}`,\n      };\n      const controller = new AbortController();\n      const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n      let res: Response;\n      try {\n        res = await this.fetchImpl(url, {\n          ...init,\n          headers,\n          signal: controller.signal,\n        });\n      } catch (err) {\n        if (err instanceof Error && err.name === \"AbortError\") {\n          throw new AxioRankRequestError(\n            `AxioRank: request timed out after ${this.timeoutMs}ms`,\n          );\n        }\n        throw new AxioRankRequestError(\n          `AxioRank: network error - ${(err as Error).message}`,\n        );\n      } finally {\n        clearTimeout(timer);\n      }\n\n      // A short-lived token can expire or rotate mid-flight: refresh once and\n      // retry transparently before surfacing a 401 to the caller.\n      if (res.status === 401 && this.useTokens && !refreshedOn401) {\n        refreshedOn401 = true;\n        this.invalidateToken();\n        continue;\n      }\n\n      if (res.status !== 429) return res;\n\n      const ra = Number(res.headers.get(\"retry-after\"));\n      if (attempt >= maxAttempts) {\n        throw new AxioRankRateLimitError(\n          \"AxioRank: rate limit exceeded - retries exhausted\",\n          Number.isFinite(ra) ? ra : undefined,\n        );\n      }\n      const waitMs =\n        Number.isFinite(ra) && ra > 0\n          ? ra * 1000\n          : Math.min(8_000, 500 * 2 ** (attempt - 1));\n      await delay(waitMs);\n    }\n  }\n\n  /** Shared POST helper: bearer auth, timeout, 429 backoff, uniform errors. */\n  private async request<T>(path: string, body: unknown): Promise<T> {\n    const res = await this.fetchWithRetry(`${this.baseUrl}${path}`, {\n      method: \"POST\",\n      headers: { \"content-type\": \"application/json\" },\n      body: JSON.stringify(body),\n    });\n\n    if (res.status === 401) {\n      throw new AxioRankAuthError();\n    }\n\n    let resBody: unknown = null;\n    try {\n      resBody = await res.json();\n    } catch {\n      // leave null; handled below\n    }\n\n    if (!res.ok) {\n      const message =\n        (resBody as { error?: string } | null)?.error ??\n        `request failed with status ${res.status}`;\n      throw new AxioRankRequestError(`AxioRank: ${message}`, res.status);\n    }\n\n    return resBody as T;\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 {\n  CatalogEntry,\n  DetectorMatch,\n  Severity,\n  SignalCategory,\n} 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   * Cheap literal pre-check: skip the (more expensive) `matchAll` unless one of\n   * these substrings is present in the leaf. For prefix-anchored tokens this\n   * short-circuits almost every spec on a typical leaf, so the scan stays fast\n   * as the detector count grows. Matched case-insensitively.\n   */\n  prefilter?: string | string[];\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  /** See {@link PatternSpec.prefilter}. */\n  prefilter?: 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 * True when the leaf can possibly contain this spec's match: no prefilter means\n * always scan; otherwise at least one prefilter literal must be present. The\n * check is case-insensitive so a prefilter of `\"AKIA\"` still gates a lower-cased\n * decode variant, and `\"bearer\"` gates `Bearer`.\n */\nfunction passesPrefilter(\n  lowerValue: string,\n  prefilter: string | string[] | undefined,\n): boolean {\n  if (!prefilter) return true;\n  const needles = Array.isArray(prefilter) ? prefilter : [prefilter];\n  for (const n of needles) if (lowerValue.includes(n.toLowerCase())) return true;\n  return false;\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 * `category` defaults to `\"secret\"` but is parameterized so a non-secret\n * category that still needs redaction (a crypto seed phrase / private key under\n * `financial`) reuses this exact fingerprint-and-mask path.\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  category: SignalCategory = \"secret\",\n): DetectorMatch[] {\n  const matches: DetectorMatch[] = [];\n  const lower = value.toLowerCase();\n  for (const spec of specs) {\n    if (!passesPrefilter(lower, spec.prefilter)) continue;\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,\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  const lower = value.toLowerCase();\n  for (const spec of specs) {\n    if (!passesPrefilter(lower, spec.prefilter)) continue;\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\n/**\n * Derive the public catalog (id/label/category/severity) for a set of specs.\n * A detector's `catalog` and its `inspect()` output are then guaranteed to agree\n * because both read the same spec array - the manifest can never silently drift\n * from what actually fires (the parity test enforces this for every detector).\n */\nexport function specCatalog(\n  specs: Array<PatternSpec | FindingSpec>,\n  category: SignalCategory,\n): CatalogEntry[] {\n  return specs.map((s) => ({\n    id: s.id,\n    label: s.label,\n    category,\n    severity: s.severity,\n  }));\n}\n","import type { Detector, DetectorMatch } from \"../types\";\nimport { type FindingSpec, scanFindings, specCatalog } 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  catalog: specCatalog(ABUSE_PATTERNS, \"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, specCatalog } 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  catalog: specCatalog(CARD_PATTERNS, \"supply_chain\"),\n  inspect(ctx): DetectorMatch[] {\n    return scanFindings(normalize(ctx.value), \"supply_chain\", CARD_PATTERNS);\n  },\n};\n","import { truncateEvidence } from \"../mask\";\nimport { specCatalog } from \"./util\";\nimport type { Detector, DetectorMatch, Severity } from \"../types\";\n\ninterface DestructiveSpec {\n  id: string;\n  label: string;\n  severity: Severity;\n  regex: RegExp;\n  /**\n   * Only fire when NO `WHERE` clause appears in the ~160 chars after the match\n   * (a whole-table DELETE/UPDATE). Bounded window keeps this linear - no\n   * unbounded look-ahead, no ReDoS.\n   */\n  requireNoWhere?: true;\n}\n\nconst SPECS: DestructiveSpec[] = [\n  // ---- Filesystem ----------------------------------------------------------\n  {\n    id: \"destructive.rm_rf\",\n    label: \"Recursive/forced file delete\",\n    severity: \"high\",\n    regex: /\\brm\\s+-[a-zA-Z]*[rf][a-zA-Z]*\\b/,\n  },\n  {\n    id: \"destructive.chmod_777\",\n    label: \"World-writable permissions\",\n    severity: \"medium\",\n    regex: /\\bchmod\\s+(?:-[a-zA-Z]+\\s+)*(?:777|0777|a\\+rwx)\\b/,\n  },\n  {\n    id: \"destructive.disk_wipe\",\n    label: \"Disk format or overwrite\",\n    severity: \"high\",\n    regex:\n      /\\bmkfs(?:\\.\\w+)?\\b|\\bdd\\s+if=\\/dev\\/(?:zero|u?random)\\b|>\\s*\\/dev\\/[sh]d[a-z]\\b/,\n  },\n  {\n    id: \"destructive.powershell_remove\",\n    label: \"PowerShell recursive force delete\",\n    severity: \"high\",\n    regex: /\\bRemove-Item\\b(?=[\\s\\S]{0,60}-Recurse\\b)(?=[\\s\\S]{0,60}-Force\\b)/i,\n  },\n  // ---- Version control -----------------------------------------------------\n  {\n    id: \"destructive.force_push\",\n    label: \"Git force push\",\n    severity: \"medium\",\n    regex: /\\bgit\\s+push\\b[\\s\\S]{0,30}?(?:--force\\b|--force-with-lease\\b|\\s-f\\b)/i,\n  },\n  {\n    id: \"destructive.git_history_wipe\",\n    label: \"Git hard reset / clean\",\n    severity: \"medium\",\n    regex: /\\bgit\\s+reset\\s+--hard\\b|\\bgit\\s+clean\\s+-[a-z]*f[a-z]*d?[a-z]*\\b/i,\n  },\n  // ---- SQL -----------------------------------------------------------------\n  {\n    id: \"destructive.sql_drop\",\n    label: \"SQL DROP/TRUNCATE\",\n    severity: \"high\",\n    regex: /\\b(?:drop|truncate)\\s+(?:table|database|schema|index|view)\\b/i,\n  },\n  {\n    id: \"destructive.sql_no_where\",\n    label: \"SQL DELETE/UPDATE without WHERE\",\n    severity: \"high\",\n    regex: /\\b(?:delete\\s+from|update)\\s+[\"'`\\w.]+/i,\n    requireNoWhere: true,\n  },\n  {\n    id: \"destructive.sql_grant\",\n    label: \"SQL GRANT/REVOKE ALL\",\n    severity: \"medium\",\n    regex: /\\b(?:grant|revoke)\\s+all\\b/i,\n  },\n  // ---- Cloud / IaC / orchestration -----------------------------------------\n  {\n    id: \"destructive.resource_delete\",\n    label: \"Resource destruction\",\n    severity: \"high\",\n    regex:\n      /\\b(?:delete|destroy|terminate|remove|teardown)[-_\\s]?(?:bucket|instance|volume|database|cluster|stack|deployment|namespace|table|repo(?:sitory)?)\\b/i,\n  },\n  {\n    id: \"destructive.iac_destroy\",\n    label: \"Infrastructure teardown\",\n    severity: \"high\",\n    regex: /\\bterraform\\s+destroy\\b|\\bterraform\\s+apply\\b[\\s\\S]{0,40}?-auto-approve\\b/i,\n  },\n  {\n    id: \"destructive.k8s_delete\",\n    label: \"Kubernetes/Helm delete\",\n    severity: \"high\",\n    regex: /\\bkubectl\\s+delete\\b|\\bhelm\\s+(?:delete|uninstall)\\b/i,\n  },\n  {\n    id: \"destructive.container_prune\",\n    label: \"Container/volume prune\",\n    severity: \"medium\",\n    regex: /\\bdocker\\s+system\\s+prune\\b|\\bdocker\\s+(?:volume\\s+rm|rmi)\\b[\\s\\S]{0,20}?(?:-f|--force)\\b/i,\n  },\n  {\n    id: \"destructive.cloud_delete\",\n    label: \"Cloud resource delete\",\n    severity: \"high\",\n    regex:\n      /\\baws\\s+s3\\s+rb\\b[\\s\\S]{0,20}?--force\\b|\\baws\\s+s3\\s+rm\\b[\\s\\S]{0,40}?--recursive\\b|\\baws\\s+ec2\\s+terminate-instances\\b|\\bgcloud\\s+\\w+\\s+delete\\b|\\baz\\s+\\w+\\s+delete\\b/i,\n  },\n  {\n    id: \"destructive.datastore_flush\",\n    label: \"Datastore flush\",\n    severity: \"high\",\n    regex: /\\bFLUSH(?:ALL|DB)\\b/i,\n  },\n  // ---- Host control --------------------------------------------------------\n  {\n    id: \"destructive.system_power\",\n    label: \"Host shutdown/reboot\",\n    severity: \"medium\",\n    regex: /(?:^|[;&|\\n]\\s*|\\bsudo\\s+)(?:shutdown|reboot|halt|poweroff|init\\s+0)\\b/i,\n  },\n  {\n    id: \"destructive.firewall_flush\",\n    label: \"Firewall disable/flush\",\n    severity: \"medium\",\n    regex: /\\biptables\\s+-F\\b|\\bufw\\s+disable\\b|\\bnetsh\\s+advfirewall\\s+set\\s+[\\s\\S]{0,30}?\\boff\\b/i,\n  },\n  {\n    id: \"destructive.cron_clear\",\n    label: \"Crontab wipe\",\n    severity: \"medium\",\n    regex: /\\bcrontab\\s+-r\\b/i,\n  },\n  {\n    id: \"destructive.dangerous_flag\",\n    label: \"Dangerous CLI flag\",\n    severity: \"low\",\n    regex: /(?:^|\\s)(?:--all|--recursive|--no-preserve-root|--force)\\b/,\n  },\n];\n\nexport const destructiveDetector: Detector = {\n  id: \"destructive\",\n  category: \"destructive\",\n  catalog: specCatalog(SPECS, \"destructive\"),\n  inspect(ctx): DetectorMatch[] {\n    const v = ctx.value;\n    const out: DetectorMatch[] = [];\n    for (const spec of SPECS) {\n      const re = spec.regex.global\n        ? spec.regex\n        : new RegExp(spec.regex.source, `${spec.regex.flags}g`);\n      for (const m of v.matchAll(re)) {\n        if (spec.requireNoWhere) {\n          const start = m.index ?? 0;\n          if (/\\bwhere\\b/i.test(v.slice(start, start + 160))) continue;\n        }\n        out.push({\n          detector: spec.id,\n          category: \"destructive\",\n          severity: spec.severity,\n          label: spec.label,\n          evidence: truncateEvidence(m[0]),\n        });\n      }\n    }\n    return out;\n  },\n};\n","import { truncateEvidence } from \"../mask\";\nimport { scanFindings, specCatalog, type FindingSpec } from \"./util\";\nimport type { CatalogEntry, Detector, DetectorMatch } from \"../types\";\n\nconst SPECS: FindingSpec[] = [\n  {\n    id: \"egress.select_star\",\n    label: \"Unbounded SELECT *\",\n    severity: \"medium\",\n    regex: /\\bselect\\s+\\*\\s+from\\b/gi,\n  },\n  {\n    id: \"egress.bulk_export\",\n    label: \"Bulk data export\",\n    severity: \"high\",\n    regex:\n      /\\b(?:export|dump|download|scrape)\\s+(?:all|everything|\\*|database|table|users|customers|records)\\b/gi,\n  },\n  {\n    id: \"egress.exfil_host\",\n    label: \"Exfiltration / tunnel host\",\n    severity: \"high\",\n    // Known request-capture, tunnel, and throwaway-paste hosts an exfil payload\n    // routes to. Prefiltered so the alternation only runs when one is present.\n    regex:\n      /\\b(?:webhook\\.site|requestbin\\.(?:com|net)|pipedream\\.net|ngrok\\.(?:io|app|dev)|burpcollaborator\\.net|interact\\.sh|oast\\.(?:fun|site|live|pro|me)|pastebin\\.com\\/raw|hastebin\\.com|transfer\\.sh|0x0\\.st)\\b/gi,\n    prefilter: [\n      \"webhook.site\",\n      \"requestbin\",\n      \"pipedream\",\n      \"ngrok\",\n      \"burpcollaborator\",\n      \"interact.sh\",\n      \"oast.\",\n      \"pastebin.com/raw\",\n      \"hastebin\",\n      \"transfer.sh\",\n      \"0x0.st\",\n    ],\n  },\n  {\n    id: \"egress.base64_in_url\",\n    label: \"Encoded blob in outbound URL\",\n    severity: \"medium\",\n    // A long base64 run inside a URL path/query - the shape of conversation\n    // data smuggled out as an image/beacon URL.\n    regex: /https?:\\/\\/[^\\s\"'<>]{0,200}?[?&/][A-Za-z0-9+/]{80,}={0,2}/gi,\n    prefilter: [\"http\"],\n  },\n  {\n    id: \"egress.data_uri\",\n    label: \"Large embedded data URI\",\n    severity: \"medium\",\n    regex: /data:(?:application|text|image)\\/[^;,]{0,40};base64,[A-Za-z0-9+/]{100,}/gi,\n    prefilter: [\"data:\"],\n  },\n  {\n    id: \"egress.suspicious_tld\",\n    label: \"Outbound to suspicious TLD\",\n    severity: \"low\",\n    regex:\n      /https?:\\/\\/[^\\s/\"'<>]+\\.(?:zip|mov|xyz|top|tk|ml|ga|cf|gq|click|link|country|kim|work|party|gdn|review)\\b/gi,\n    prefilter: [\"http\"],\n  },\n  {\n    id: \"egress.bulk_recipients\",\n    label: \"Bulk recipient list\",\n    severity: \"medium\",\n    regex: /\\b(?:bcc|cc|to)\\s*[:=]\\s*(?:[^\\s,;@]+@[^\\s,;]+[,;]\\s*){10,}/gi,\n  },\n];\n\nconst LARGE_VALUE = 20_000;\n\n/** `inspect` emits the SPECS ids plus the length-based `egress.large_value`. */\nconst EGRESS_CATALOG: CatalogEntry[] = [\n  ...specCatalog(SPECS, \"egress\"),\n  {\n    id: \"egress.large_value\",\n    label: \"Large field value\",\n    category: \"egress\",\n    severity: \"low\",\n  },\n];\n\nexport const egressDetector: Detector = {\n  id: \"egress\",\n  category: \"egress\",\n  catalog: EGRESS_CATALOG,\n  inspect(ctx): DetectorMatch[] {\n    const out = scanFindings(ctx.value, \"egress\", SPECS);\n    if (ctx.value.length >= LARGE_VALUE) {\n      out.push({\n        detector: \"egress.large_value\",\n        category: \"egress\",\n        severity: \"low\",\n        label: \"Large field value\",\n        evidence: `${ctx.value.length.toLocaleString(\"en-US\")} chars`,\n      });\n    }\n    return out;\n  },\n};\n","/**\n * Shared checksum validators. These let high-recall regexes stay tight on\n * precision: the pattern proposes a candidate, the checksum confirms it, so a\n * random 9-digit run isn't flagged as a routing number and a typo'd IBAN isn't\n * flagged as an IBAN. Pure, synchronous, allocation-light - safe on the hot path.\n */\n\n/** Luhn (mod-10) check for credit cards and Luhn-based national ids (e.g. SIN). */\nexport function 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\n/**\n * ISO 7064 mod-97-10 check for IBANs. Move the four leading chars to the end,\n * map letters to numbers (A=10…Z=35), then the big-integer mod 97 must equal 1.\n * Computed digit-by-digit to avoid BigInt.\n */\nexport function ibanValid(raw: string): boolean {\n  const iban = raw.replace(/\\s+/g, \"\").toUpperCase();\n  if (iban.length < 15 || iban.length > 34) return false;\n  if (!/^[A-Z]{2}\\d{2}[A-Z0-9]+$/.test(iban)) return false;\n  const rearranged = iban.slice(4) + iban.slice(0, 4);\n  let remainder = 0;\n  for (const ch of rearranged) {\n    const code = ch.charCodeAt(0);\n    // 0-9 -> \"0\"..\"9\"; A-Z -> \"10\"..\"35\"\n    const chunk =\n      code >= 65 ? String(code - 55) : String.fromCharCode(code);\n    for (const d of chunk) {\n      remainder = (remainder * 10 + (d.charCodeAt(0) - 48)) % 97;\n    }\n  }\n  return remainder === 1;\n}\n\n/**\n * ABA routing-transit checksum: 3·(d1+d4+d7) + 7·(d2+d5+d8) + (d3+d6+d9) ≡ 0\n * (mod 10). Confirms a 9-digit run is a real US routing number, not noise.\n */\nexport function abaValid(digits: string): boolean {\n  if (!/^\\d{9}$/.test(digits)) return false;\n  const w = [3, 7, 1, 3, 7, 1, 3, 7, 1];\n  let sum = 0;\n  for (let i = 0; i < 9; i++) sum += w[i]! * (digits.charCodeAt(i) - 48);\n  return sum % 10 === 0;\n}\n\n/** Verhoeff check digit (India Aadhaar). Dihedral-group checksum over the run. */\nconst VERHOEFF_D = [\n  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n  [1, 2, 3, 4, 0, 6, 7, 8, 9, 5],\n  [2, 3, 4, 0, 1, 7, 8, 9, 5, 6],\n  [3, 4, 0, 1, 2, 8, 9, 5, 6, 7],\n  [4, 0, 1, 2, 3, 9, 5, 6, 7, 8],\n  [5, 9, 8, 7, 6, 0, 4, 3, 2, 1],\n  [6, 5, 9, 8, 7, 1, 0, 4, 3, 2],\n  [7, 6, 5, 9, 8, 2, 1, 0, 4, 3],\n  [8, 7, 6, 5, 9, 3, 2, 1, 0, 4],\n  [9, 8, 7, 6, 5, 4, 3, 2, 1, 0],\n];\nconst VERHOEFF_P = [\n  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],\n  [1, 5, 7, 6, 2, 8, 3, 0, 9, 4],\n  [5, 8, 0, 3, 7, 9, 6, 1, 4, 2],\n  [8, 9, 1, 6, 0, 4, 3, 5, 2, 7],\n  [9, 4, 5, 3, 1, 2, 6, 8, 7, 0],\n  [4, 2, 8, 6, 5, 7, 3, 9, 0, 1],\n  [2, 7, 9, 3, 8, 0, 6, 4, 1, 5],\n  [7, 0, 4, 6, 9, 1, 3, 2, 5, 8],\n];\n\nexport function verhoeffValid(digits: string): boolean {\n  if (!/^\\d+$/.test(digits)) return false;\n  let c = 0;\n  const reversed = digits.split(\"\").reverse();\n  for (let i = 0; i < reversed.length; i++) {\n    c = VERHOEFF_D[c]![VERHOEFF_P[i % 8]![Number(reversed[i])]!]!;\n  }\n  return c === 0;\n}\n","import { cosmeticFingerprint } from \"../mask\";\nimport {\n  scanFindings,\n  scanSecrets,\n  specCatalog,\n  type FindingSpec,\n  type PatternSpec,\n} from \"./util\";\nimport { ibanValid } from \"./validators\";\nimport type { CatalogEntry, Detector, DetectorMatch } from \"../types\";\n\n/**\n * Crypto & financial identifiers. Wallet addresses, IBANs and BICs are FLAGGED\n * like PII (they identify an account, they are not themselves a live secret).\n * Seed phrases and extended/WIF private keys ARE secret-grade: they redact from\n * the stored payload and floor the score (`critical`), exactly like an API key,\n * but under the `financial` category so they route through financial policy.\n */\n\n// Secret-grade: redacted + score-flooring. Runs through the shared secret\n// scanner with the `financial` category so the span is masked in the payload.\nconst SECRET_SPECS: PatternSpec[] = [\n  {\n    id: \"financial.crypto_privkey\",\n    label: \"Crypto private key\",\n    severity: \"critical\",\n    critical: true,\n    // BIP32 extended private key (xprv…) or a WIF key (5…/K…/L…).\n    regex: /\\b(?:xprv[0-9A-Za-z]{100,112}|[5KL][1-9A-HJ-NP-Za-km-z]{50,51})\\b/,\n  },\n];\n\n// Flag-only identifiers.\nconst FINDING_SPECS: FindingSpec[] = [\n  {\n    id: \"financial.btc_address\",\n    label: \"Bitcoin address\",\n    severity: \"medium\",\n    regex: /\\bbc1[ac-hj-np-z02-9]{11,71}\\b|\\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\\b/,\n  },\n  {\n    id: \"financial.eth_address\",\n    label: \"Ethereum address\",\n    severity: \"medium\",\n    regex: /\\b0x[a-fA-F0-9]{40}\\b/,\n    prefilter: \"0x\",\n  },\n  {\n    id: \"financial.swift_bic\",\n    label: \"SWIFT / BIC code\",\n    severity: \"medium\",\n    regex: /\\b(?:swift|bic)(?:\\s+code)?[:\\s]+[A-Z]{6}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\\b/i,\n    prefilter: [\"swift\", \"bic\"],\n  },\n];\n\n// IBAN needs the mod-97 checksum, so it is matched then validated here.\nconst IBAN_RE = /\\b[A-Z]{2}\\d{2}(?:[ ]?[A-Z0-9]){11,30}\\b/g;\n\n// Seed phrase: a 12-24 word lowercase run near a wallet/recovery keyword. The\n// context gate (not a bundled 2048-word list) is what holds precision - an\n// ordinary English sentence of the same shape is not near \"seed\"/\"mnemonic\".\nconst SEED_RUN = /\\b(?:[a-z]{3,8}\\s){11,23}[a-z]{3,8}\\b/g;\nconst SEED_CONTEXT = /(?:seed|mnemonic|recovery|wallet|passphrase|private\\s*key)/i;\nconst SEED_LENGTHS = new Set([12, 15, 18, 21, 24]);\n\nconst FINANCIAL_CATALOG: CatalogEntry[] = [\n  ...specCatalog(SECRET_SPECS, \"financial\"),\n  ...specCatalog(FINDING_SPECS, \"financial\"),\n  { id: \"financial.iban\", label: \"IBAN\", category: \"financial\", severity: \"high\" },\n  {\n    id: \"financial.seed_phrase\",\n    label: \"Crypto seed phrase\",\n    category: \"financial\",\n    severity: \"critical\",\n  },\n];\n\nexport const financialDetector: Detector = {\n  id: \"financial\",\n  category: \"financial\",\n  catalog: FINANCIAL_CATALOG,\n  inspect(ctx): DetectorMatch[] {\n    const v = ctx.value;\n    const fingerprint = ctx.fingerprint ?? cosmeticFingerprint;\n    const out: DetectorMatch[] = [\n      ...scanSecrets(v, SECRET_SPECS, ctx.fingerprint, \"financial\"),\n      ...scanFindings(v, \"financial\", FINDING_SPECS),\n    ];\n\n    for (const m of v.matchAll(IBAN_RE)) {\n      if (!ibanValid(m[0])) continue;\n      out.push({\n        detector: \"financial.iban\",\n        category: \"financial\",\n        severity: \"high\",\n        label: \"IBAN\",\n        evidence: fingerprint(m[0].replace(/\\s+/g, \"\")),\n      });\n    }\n\n    if (SEED_CONTEXT.test(v)) {\n      const re = new RegExp(SEED_RUN.source, \"gd\");\n      for (const m of v.matchAll(re)) {\n        const words = m[0].trim().split(/\\s+/).length;\n        if (!SEED_LENGTHS.has(words)) continue;\n        const idx = m.index ?? 0;\n        // Require the wallet/recovery keyword close to the run, not just anywhere.\n        if (!SEED_CONTEXT.test(v.slice(Math.max(0, idx - 40), idx))) continue;\n        out.push({\n          detector: \"financial.seed_phrase\",\n          category: \"financial\",\n          severity: \"critical\",\n          critical: true,\n          label: \"Crypto seed phrase\",\n          evidence: fingerprint(m[0]),\n          redact: {\n            start: idx,\n            end: idx + m[0].length,\n            mask: \"‹redacted:financial.seed_phrase›\",\n          },\n        });\n      }\n    }\n\n    return out;\n  },\n};\n","import type { Detector } from \"../types\";\nimport { scanFindings, specCatalog, 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.nosql\",\n    label: \"NoSQL operator injection\",\n    severity: \"high\",\n    // Mongo-style query operators smuggled into a JSON value:\n    // {\"$where\": …}, {\"$ne\": null}, {\"$gt\": \"\"}. The quote+colon shape keeps\n    // this off ordinary \"$4.99\" prose.\n    regex:\n      /[\"']\\$(?:where|ne|gt|gte|lt|lte|regex|in|nin|or|and|expr|function)[\"']\\s*:/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.code_exec\",\n    label: \"Code-execution sink\",\n    severity: \"high\",\n    // Dangerous eval/exec sinks: an agent arg carrying `os.system(` or\n    // `child_process.exec(` is trying to run code, not describe it.\n    regex:\n      /\\b(?:eval|exec|system|popen|child_process|os\\.system|subprocess\\.(?:call|run|Popen))\\s*\\(|\\bnew\\s+Function\\s*\\(/gi,\n  },\n  {\n    id: \"injection.template\",\n    label: \"Template (SSTI) injection\",\n    severity: \"medium\",\n    // Server-side template injection probes: `{{7*7}}`, `{{config}}`,\n    // `{{self.__class__}}`, `#{…}`, `<%= … %>`. Requires an arithmetic op or a\n    // known SSTI token inside `{{ }}` so ordinary `{{ user.name }}` is ignored.\n    regex:\n      /\\{\\{[\\s\\S]{0,30}?(?:[-+*/]\\s*\\d|\\b(?:self|config|request|settings|__class__|__globals__|__mro__|cycler|joiner)\\b)[\\s\\S]{0,30}?\\}\\}|#\\{[\\s\\S]{0,40}?\\}|<%[=\\s][\\s\\S]{0,60}?%>/gi,\n  },\n  {\n    id: \"injection.xxe\",\n    label: \"XML external entity\",\n    severity: \"high\",\n    regex: /<!ENTITY\\s+\\S+\\s+SYSTEM\\b|<!DOCTYPE[^>]*\\[[\\s\\S]{0,80}?<!ENTITY\\b/gi,\n  },\n  {\n    id: \"injection.xss\",\n    label: \"Cross-site scripting\",\n    severity: \"medium\",\n    regex:\n      /<script\\b[^>]*>|javascript:\\s*[a-z(]|\\bon(?:error|load|click|mouseover|focus)\\s*=\\s*[\"']?[^\"'\\s>]/gi,\n  },\n  {\n    id: \"injection.crlf\",\n    label: \"CRLF / header injection\",\n    severity: \"medium\",\n    // Percent-encoded or literal CRLF followed by a response header - the\n    // classic HTTP response-splitting vector. Encoded form only, to stay off\n    // legitimate multi-line header dumps.\n    regex:\n      /(?:%0d%0a|%0d|%0a|\\\\r\\\\n)\\s*(?:set-cookie|location|content-length|content-type|refresh)\\s*:/gi,\n  },\n  {\n    id: \"injection.deserialization\",\n    label: \"Unsafe deserialization / prototype pollution\",\n    severity: \"high\",\n    regex:\n      /\"__proto__\"\\s*:|\\bconstructor\\s*\\.\\s*prototype\\b|\\bpickle\\.loads\\b|\\byaml\\.load\\b(?!er)|\\bObjectInputStream\\b|\\brO0AB[A-Za-z0-9+/]/g,\n  },\n  {\n    id: \"injection.ldap\",\n    label: \"LDAP injection\",\n    severity: \"medium\",\n    regex: /\\*\\)\\(|\\)\\(\\||\\(\\&\\(objectclass=\\*|\\(\\|\\(uid=/gi,\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  catalog: specCatalog(SPECS, \"injection\"),\n  inspect: (ctx) => scanFindings(ctx.value, \"injection\", SPECS),\n};\n","import type { Detector } from \"../types\";\nimport { scanFindings, specCatalog, 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    id: \"injection.jailbreak.prompt_leak\",\n    label: \"System-prompt exfiltration\",\n    severity: \"high\",\n    regex:\n      /\\b(?:repeat|print|reveal|show|output|display|reproduce)\\b[\\s\\S]{0,30}?\\b(?:system\\s+prompt|initial\\s+instructions?|the\\s+instructions?\\s+above|everything\\s+above|your\\s+(?:system\\s+)?prompt|the\\s+prompt\\s+above)\\b/gi,\n  },\n  {\n    id: \"injection.jailbreak.emotional_pretext\",\n    label: \"Emotional-pretext jailbreak\",\n    severity: \"medium\",\n    regex:\n      /\\b(?:my\\s+(?:deceased|late|dead)\\s+grandma|pretend\\s+to\\s+be\\s+my\\s+(?:deceased|late|dead))\\b[\\s\\S]{0,60}?\\b(?:used\\s+to|would|tell|read|recite)\\b|\\bif\\s+you\\s+(?:don'?t|do\\s+not)\\s+(?:help|comply)[\\s\\S]{0,40}?\\b(?:die|be\\s+(?:fired|killed)|lose\\s+my\\s+job)\\b/gi,\n  },\n];\n\nexport const jailbreakDetector: Detector = {\n  id: \"jailbreak\",\n  category: \"injection\",\n  catalog: specCatalog(SPECS, \"injection\"),\n  inspect: (ctx) => scanFindings(ctx.value, \"injection\", SPECS),\n};\n","import type { Detector } from \"../types\";\nimport { scanFindings, specCatalog, type FindingSpec } from \"./util\";\n\n/**\n * Malware / dangerous-execution indicators - the commands and payloads an agent\n * would only emit if it were compromised or being driven to compromise a host:\n * reverse shells, encoded PowerShell, download-and-run cradles, credential\n * dumping. Emits the `malware` category, which denies by default (see\n * `decision.ts` / the `deny-malware` seed policy), so an unambiguous indicator\n * is stopped even at a low aggregate score.\n *\n * All patterns use bounded look-ahead windows (no unbounded repetition, no\n * backreferences) so they are linear-time and ReDoS-safe.\n */\nconst SPECS: FindingSpec[] = [\n  {\n    id: \"malware.reverse_shell\",\n    label: \"Reverse shell\",\n    severity: \"critical\",\n    critical: true,\n    regex:\n      /\\/dev\\/tcp\\/\\d{1,3}(?:\\.\\d{1,3}){3}|\\bnc\\s+[\\s\\S]{0,30}?-e\\s+(?:\\/bin\\/)?(?:ba)?sh\\b|\\bsocat\\b[\\s\\S]{0,40}?exec:['\"]?(?:\\/bin\\/)?(?:ba)?sh|\\b(?:python[0-9.]*|perl|ruby)\\b[\\s\\S]{0,12}?-e?c?[\\s\\S]{0,80}?socket[\\s\\S]{0,120}?(?:connect|SOCK_STREAM|TCPSocket)/i,\n  },\n  {\n    id: \"malware.encoded_powershell\",\n    label: \"Encoded PowerShell\",\n    severity: \"critical\",\n    critical: true,\n    regex:\n      /powershell(?:\\.exe)?[\\s\\S]{0,40}?\\s-e(?:nc|ncodedcommand)?\\s+[A-Za-z0-9+/]{20,}|\\bFromBase64String\\b|\\bIEX\\s*\\(\\s*(?:New-Object|iwr|Invoke-WebRequest|\\$)/i,\n    prefilter: [\"powershell\", \"frombase64string\", \"iex\"],\n  },\n  {\n    id: \"malware.remote_exec_pipe\",\n    label: \"Download-and-run pipe\",\n    severity: \"critical\",\n    critical: true,\n    regex:\n      /\\b(?:curl|wget)\\b[\\s\\S]{0,120}?\\|\\s*(?:sudo\\s+)?(?:ba)?sh\\b|\\b(?:curl|wget)\\b[\\s\\S]{0,120}?\\|\\s*python[0-9.]*\\b|\\biwr\\b[\\s\\S]{0,80}?\\|\\s*iex\\b/i,\n    prefilter: [\"curl\", \"wget\", \"iwr\"],\n  },\n  {\n    id: \"malware.download_cradle\",\n    label: \"Download cradle\",\n    severity: \"high\",\n    regex:\n      /\\bcertutil\\b[\\s\\S]{0,40}?-urlcache|\\bbitsadmin\\b[\\s\\S]{0,40}?\\/transfer|\\bInvoke-WebRequest\\b[\\s\\S]{0,80}?-OutFile[\\s\\S]{0,80}?(?:Start-Process|IEX|\\.exe)/i,\n    prefilter: [\"certutil\", \"bitsadmin\", \"invoke-webrequest\"],\n  },\n  {\n    id: \"malware.pe_header\",\n    label: \"Embedded PE executable\",\n    severity: \"high\",\n    // base64 of the DOS \"MZ\" header (TVqQ / TVpQ), or the raw hex signature.\n    regex: /\\bTV[qp]Q[A-Za-z0-9+/]{24,}|\\b4d5a9000[0-9a-f]{8}/,\n    prefilter: [\"tvqq\", \"tvpq\", \"4d5a9000\"],\n  },\n  {\n    id: \"malware.credential_dumping\",\n    label: \"Credential dumping\",\n    severity: \"critical\",\n    critical: true,\n    regex:\n      /\\bsekurlsa\\b|\\bmimikatz\\b|\\bprocdump\\b[\\s\\S]{0,20}?lsass|\\blsass\\.exe\\b[\\s\\S]{0,20}?(?:dump|comsvcs)|\\breg\\s+save\\s+hklm\\\\sam\\b/i,\n    prefilter: [\"sekurlsa\", \"mimikatz\", \"procdump\", \"lsass\", \"hklm\\\\sam\"],\n  },\n  {\n    id: \"malware.disable_defense\",\n    label: \"Security-control tampering\",\n    severity: \"high\",\n    regex:\n      /Set-MpPreference\\b[\\s\\S]{0,40}?-Disable(?:RealtimeMonitoring|IOAVProtection|BehaviorMonitoring)|\\bsetenforce\\s+0\\b|\\bsystemctl\\s+(?:stop|disable)\\s+(?:falcon|crowdstrike|auditd|osquery)/i,\n    prefilter: [\"set-mppreference\", \"setenforce\", \"systemctl\"],\n  },\n  {\n    id: \"malware.persistence\",\n    label: \"Persistence mechanism\",\n    severity: \"high\",\n    regex:\n      /\\bschtasks\\b[\\s\\S]{0,20}?\\/create|\\breg\\s+add\\b[\\s\\S]{0,80}?\\\\CurrentVersion\\\\Run\\b|\\bNew-Service\\b|>>?\\s*\\/etc\\/(?:rc\\.local|cron\\.d)/i,\n    prefilter: [\"schtasks\", \"currentversion\\\\run\", \"new-service\", \"rc.local\", \"cron.d\"],\n  },\n  {\n    id: \"malware.base64_eval\",\n    label: \"Obfuscated eval of encoded payload\",\n    severity: \"high\",\n    regex:\n      /\\beval\\s*\\(\\s*(?:atob|base64_decode|Buffer\\.from)\\s*\\(|\\bexec\\s*\\(\\s*__import__\\s*\\(\\s*['\"]base64/i,\n    prefilter: [\"eval(\", \"exec(\"],\n  },\n  {\n    id: \"malware.obfuscated_shell\",\n    label: \"Obfuscated shell decode-and-run\",\n    severity: \"medium\",\n    regex:\n      /\\$\\{IFS\\}|\\bbase64\\s+-d\\b[\\s\\S]{0,20}?\\|\\s*(?:ba)?sh\\b|\\bxxd\\s+-r\\b[\\s\\S]{0,20}?\\|\\s*(?:ba)?sh\\b/i,\n    prefilter: [\"${ifs}\", \"base64 -d\", \"xxd -r\"],\n  },\n  {\n    id: \"malware.fork_bomb\",\n    label: \"Fork bomb\",\n    severity: \"high\",\n    regex: /:\\(\\)\\s*\\{\\s*:\\s*\\|\\s*:\\s*&\\s*\\}\\s*;\\s*:/,\n    prefilter: [\":(){\", \":|:&\"],\n  },\n];\n\nexport const malwareDetector: Detector = {\n  id: \"malware\",\n  category: \"malware\",\n  catalog: specCatalog(SPECS, \"malware\"),\n  inspect: (ctx) => scanFindings(ctx.value, \"malware\", SPECS),\n};\n","import type { CatalogEntry, Detector, DetectorContext, DetectorMatch } from \"../types\";\nimport { scanFindings, specCatalog, 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\n/** `inspect` emits the SPECS ids plus `injection.hidden_unicode` (below). */\nconst OUTPUT_CATALOG: CatalogEntry[] = [\n  ...specCatalog(SPECS, \"injection\"),\n  {\n    id: \"injection.hidden_unicode\",\n    label: \"Hidden unicode smuggling\",\n    category: \"injection\",\n    severity: \"high\",\n  },\n];\n\nexport const outputInjectionDetector: Detector = {\n  id: \"injection.output\",\n  category: \"injection\",\n  catalog: OUTPUT_CATALOG,\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 { specCatalog } from \"./util\";\nimport { abaValid, luhnValid, verhoeffValid } from \"./validators\";\nimport type { Detector, DetectorMatch, RedactSpan, Severity } from \"../types\";\n\ninterface PiiSpec {\n  id: string;\n  label: string;\n  severity: Severity;\n  regex: RegExp;\n  critical?: true;\n  /** Capture group holding the sensitive value (default 0 = whole match). */\n  group?: number;\n  /** How much context maskMiddle keeps in the evidence (0 = fully masked). */\n  maskKeep?: number;\n  /** Confirm a candidate (digits-only) before emitting - a checksum gate. */\n  validate?: (digits: string) => boolean;\n}\n\nconst SPECS: PiiSpec[] = [\n  {\n    id: \"pii.email\",\n    label: \"Email address\",\n    severity: \"medium\",\n    regex: /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/,\n    maskKeep: 2,\n  },\n  {\n    // US SSN with the standard invalid-range guards (no 000/666/9xx area, etc.).\n    id: \"pii.ssn\",\n    label: \"US Social Security Number\",\n    severity: \"high\",\n    regex: /\\b(?!000|666|9\\d\\d)\\d{3}-(?!00)\\d{2}-(?!0000)\\d{4}\\b/,\n    maskKeep: 0,\n  },\n  {\n    id: \"pii.itin\",\n    label: \"US Individual Taxpayer ID\",\n    severity: \"high\",\n    regex: /\\b9\\d{2}-[7-8]\\d-\\d{4}\\b/,\n    maskKeep: 0,\n  },\n  {\n    id: \"pii.ein\",\n    label: \"US Employer ID Number\",\n    severity: \"medium\",\n    regex: /\\b(?:ein|employer\\s+id(?:entification)?(?:\\s+(?:number|no\\.?))?)\\b[\\s\\S]{0,20}?(\\d{2}-\\d{7})\\b/i,\n    group: 1,\n    maskKeep: 0,\n  },\n  {\n    id: \"pii.phone\",\n    label: \"Phone number\",\n    severity: \"low\",\n    regex: /\\b(?:\\+?1[-.\\s]?)?\\(?\\d{3}\\)?[-.\\s]\\d{3}[-.\\s]\\d{4}\\b/,\n    maskKeep: 2,\n  },\n  {\n    // 13–19 digits with optional space/dash separators; Luhn-validated.\n    id: \"pii.credit_card\",\n    label: \"Credit card number\",\n    severity: \"high\",\n    critical: true,\n    regex: /\\b(?:\\d[ -]?){13,19}\\b/,\n    maskKeep: 0,\n    validate: (d) => d.length >= 13 && d.length <= 19 && luhnValid(d),\n  },\n  {\n    id: \"pii.us_routing\",\n    label: \"US bank routing number\",\n    severity: \"medium\",\n    regex: /\\b(?:routing|aba|rtn)\\b[\\s\\S]{0,20}?\\b(\\d{9})\\b/i,\n    group: 1,\n    maskKeep: 0,\n    validate: (d) => abaValid(d),\n  },\n  {\n    id: \"pii.uk_nino\",\n    label: \"UK National Insurance number\",\n    severity: \"medium\",\n    regex: /\\b[ABCEGHJKLMNOPRSTWXYZ][ABCEGHJKLMNPRSTWXYZ]\\s?\\d{2}\\s?\\d{2}\\s?\\d{2}\\s?[A-D]\\b/i,\n    maskKeep: 0,\n  },\n  {\n    id: \"pii.ca_sin\",\n    label: \"Canada Social Insurance Number\",\n    severity: \"medium\",\n    regex: /\\b(?:sin|social\\s+insurance)\\b[\\s\\S]{0,20}?\\b(\\d{3}[-\\s]?\\d{3}[-\\s]?\\d{3})\\b/i,\n    group: 1,\n    maskKeep: 0,\n    validate: (d) => d.length === 9 && luhnValid(d),\n  },\n  {\n    id: \"pii.aadhaar\",\n    label: \"India Aadhaar number\",\n    severity: \"high\",\n    regex: /\\b[2-9]\\d{3}\\s?\\d{4}\\s?\\d{4}\\b/,\n    maskKeep: 0,\n    validate: (d) => d.length === 12 && verhoeffValid(d),\n  },\n  {\n    id: \"pii.passport\",\n    label: \"Passport number\",\n    severity: \"medium\",\n    regex: /\\bpassport\\b(?:\\s+(?:number|no\\.?|#))?[\\s:]{0,4}([A-Z0-9]{6,9})\\b/i,\n    group: 1,\n    maskKeep: 1,\n  },\n  {\n    id: \"pii.ipv4\",\n    label: \"IPv4 address\",\n    severity: \"low\",\n    regex: /\\b(?:(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1?\\d?\\d)\\b/,\n    maskKeep: 0,\n  },\n  {\n    id: \"pii.ipv6\",\n    label: \"IPv6 address\",\n    severity: \"low\",\n    regex: /\\b(?:[0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\\b/,\n    maskKeep: 0,\n  },\n  {\n    id: \"pii.mac_address\",\n    label: \"MAC address\",\n    severity: \"low\",\n    regex: /\\b(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\\b/,\n    maskKeep: 0,\n  },\n];\n\n/**\n * A redaction span for a matched PII value, only when the caller opted in. Uses\n * a fixed, length-free mask so identical PII always redacts to an identical\n * string (no length or plaintext leakage).\n */\nfunction piiRedact(\n  enabled: boolean | undefined,\n  id: string,\n  start: number,\n  end: number,\n): RedactSpan | undefined {\n  if (!enabled) return undefined;\n  return { start, end, mask: `‹redacted:${id}›` };\n}\n\nexport const piiDetector: Detector = {\n  id: \"pii\",\n  category: \"pii\",\n  catalog: specCatalog(SPECS, \"pii\"),\n  inspect(ctx): DetectorMatch[] {\n    const v = ctx.value;\n    const out: DetectorMatch[] = [];\n    for (const spec of SPECS) {\n      const re = new RegExp(spec.regex.source, `${spec.regex.flags}gd`);\n      for (const m of v.matchAll(re)) {\n        const group = spec.group ?? 0;\n        const value = m[group];\n        const span = m.indices?.[group];\n        if (!value || !span) continue;\n        if (spec.validate && !spec.validate(value.replace(/[^0-9]/g, \"\"))) {\n          continue;\n        }\n        out.push({\n          detector: spec.id,\n          category: \"pii\",\n          severity: spec.severity,\n          label: spec.label,\n          ...(spec.critical ? { critical: true as const } : {}),\n          evidence: maskMiddle(value, spec.maskKeep ?? 2),\n          redact: piiRedact(ctx.redactPii, spec.id, span[0], span[1]),\n        });\n      }\n    }\n    return out;\n  },\n};\n","import type { Detector } from \"../types\";\nimport { scanSecrets, specCatalog, 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, context-gated\n * hex blobs) score lower. The matched span is redacted from the stored payload.\n *\n * Nearly every pattern is prefix-anchored to a vendor-specific literal (`glpat-`,\n * `xox`, `shp…`), so the `prefilter` short-circuit skips the regex entirely on a\n * leaf that can't contain it - the scan stays fast even as this list grows. The\n * few shape-only tokens (Twilio, Cloudflare, Datadog, Okta) require a nearby\n * provider keyword, exactly like `secret.aws_secret_key`, to hold precision.\n */\nconst SECRET_PATTERNS: PatternSpec[] = [\n  // ---- Cloud providers -----------------------------------------------------\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    prefilter: [\"AKIA\", \"ASIA\", \"AGPA\", \"AIDA\", \"AROA\"],\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    prefilter: \"aws\",\n  },\n  {\n    id: \"secret.azure_storage_key\",\n    label: \"Azure storage account key\",\n    severity: \"critical\",\n    critical: true,\n    regex: /AccountKey=([A-Za-z0-9+/]{86}==)/,\n    group: 1,\n    prefilter: \"accountkey=\",\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    prefilter: \"aiza\",\n  },\n  {\n    id: \"secret.google_oauth_token\",\n    label: \"Google OAuth access token\",\n    severity: \"high\",\n    regex: /\\bya29\\.[0-9A-Za-z_-]{30,}\\b/,\n    prefilter: \"ya29.\",\n  },\n  {\n    id: \"secret.cloudflare_token\",\n    label: \"Cloudflare API token\",\n    severity: \"high\",\n    regex: /cloudflare.{0,40}?[\"'=:\\s]([0-9A-Za-z_-]{37,40})\\b/i,\n    group: 1,\n    prefilter: \"cloudflare\",\n  },\n  {\n    id: \"secret.digitalocean_token\",\n    label: \"DigitalOcean token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bdo[oprt]_v1_[0-9a-f]{64}\\b/,\n    prefilter: \"_v1_\",\n  },\n  // ---- Source control ------------------------------------------------------\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    prefilter: [\"ghp_\", \"gho_\", \"ghs_\", \"ghr_\", \"ghu_\"],\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    prefilter: \"github_pat_\",\n  },\n  {\n    id: \"secret.gitlab_pat\",\n    label: \"GitLab personal access token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bglpat-[0-9A-Za-z_-]{20,}\\b/,\n    prefilter: \"glpat-\",\n  },\n  // ---- Package registries --------------------------------------------------\n  {\n    id: \"secret.npm_token\",\n    label: \"npm access token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bnpm_[0-9A-Za-z]{36}\\b/,\n    prefilter: \"npm_\",\n  },\n  {\n    id: \"secret.pypi_token\",\n    label: \"PyPI upload token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bpypi-AgEIcHlwaS[0-9A-Za-z_-]{50,}\\b/,\n    prefilter: \"pypi-\",\n  },\n  // ---- LLM / AI providers --------------------------------------------------\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    prefilter: \"sk-\",\n  },\n  {\n    id: \"secret.huggingface_token\",\n    label: \"Hugging Face token\",\n    severity: \"high\",\n    regex: /\\bhf_[0-9A-Za-z]{34,}\\b/,\n    prefilter: \"hf_\",\n  },\n  // ---- Messaging / comms ---------------------------------------------------\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    prefilter: \"xox\",\n  },\n  {\n    id: \"secret.slack_webhook\",\n    label: \"Slack incoming webhook\",\n    severity: \"high\",\n    regex:\n      /\\bhooks\\.slack\\.com\\/services\\/T[0-9A-Z]{8,}\\/B[0-9A-Z]{8,}\\/[0-9A-Za-z]{24}\\b/,\n    prefilter: \"hooks.slack.com\",\n  },\n  {\n    id: \"secret.sendgrid_key\",\n    label: \"SendGrid API key\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bSG\\.[0-9A-Za-z_-]{22}\\.[0-9A-Za-z_-]{43}\\b/,\n    prefilter: \"sg.\",\n  },\n  {\n    id: \"secret.mailgun_key\",\n    label: \"Mailgun API key\",\n    severity: \"high\",\n    regex: /\\bkey-[0-9a-f]{32}\\b/,\n    prefilter: \"key-\",\n  },\n  {\n    id: \"secret.twilio_token\",\n    label: \"Twilio auth token\",\n    severity: \"high\",\n    regex: /twilio.{0,40}?(?:auth|token|secret).{0,12}?[\"'=:\\s]([0-9a-f]{32})\\b/i,\n    group: 1,\n    prefilter: \"twilio\",\n  },\n  {\n    id: \"secret.telegram_bot_token\",\n    label: \"Telegram bot token\",\n    severity: \"high\",\n    regex: /\\b\\d{8,10}:AA[0-9A-Za-z_-]{33}\\b/,\n    prefilter: \":aa\",\n  },\n  {\n    id: \"secret.discord_bot_token\",\n    label: \"Discord bot token\",\n    severity: \"high\",\n    regex: /discord.{0,40}?(?:bot\\s*)?token.{0,12}?[\"'=:\\s]([MNO][A-Za-z0-9._-]{50,})/i,\n    group: 1,\n    prefilter: \"discord\",\n  },\n  // ---- Payments ------------------------------------------------------------\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    prefilter: [\"sk_live_\", \"rk_live_\"],\n  },\n  {\n    id: \"secret.stripe_webhook_secret\",\n    label: \"Stripe webhook signing secret\",\n    severity: \"high\",\n    regex: /\\bwhsec_[0-9A-Za-z]{32,}\\b/,\n    prefilter: \"whsec_\",\n  },\n  {\n    id: \"secret.square_token\",\n    label: \"Square access token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\b(?:sq0atp-|sq0csp-|EAAA)[0-9A-Za-z_-]{22,}\\b/,\n    prefilter: [\"sq0atp-\", \"sq0csp-\", \"eaaa\"],\n  },\n  {\n    id: \"secret.shopify_token\",\n    label: \"Shopify access token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bshp(?:at|ca|pa|ss)_[0-9a-fA-F]{32}\\b/,\n    prefilter: \"shp\",\n  },\n  // ---- Infra / secrets management ------------------------------------------\n  {\n    id: \"secret.hashicorp_vault\",\n    label: \"HashiCorp Vault token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bhv[sb]\\.[0-9A-Za-z_-]{24,}\\b/,\n    prefilter: [\"hvs.\", \"hvb.\"],\n  },\n  {\n    id: \"secret.terraform_cloud\",\n    label: \"Terraform Cloud token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\b[0-9A-Za-z]{14}\\.atlasv1\\.[0-9A-Za-z_-]{60,}\\b/,\n    prefilter: \"atlasv1.\",\n  },\n  {\n    id: \"secret.doppler_token\",\n    label: \"Doppler token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bdp\\.(?:pt|st|ct|sa|scim|audit)\\.[0-9A-Za-z]{40,}\\b/,\n    prefilter: \"dp.\",\n  },\n  // ---- Databases -----------------------------------------------------------\n  {\n    id: \"secret.db_connection_string\",\n    label: \"Database URL with password\",\n    severity: \"high\",\n    regex:\n      /\\b(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|rediss|amqps?):\\/\\/[^\\s:@/]+:([^\\s:@/]{3,})@[^\\s/]+/i,\n    group: 1,\n    prefilter: [\"postgres\", \"mysql\", \"mongodb\", \"redis\", \"amqp\"],\n  },\n  {\n    id: \"secret.supabase_key\",\n    label: \"Supabase service key\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bsbp_[0-9a-f]{40}\\b/,\n    prefilter: \"sbp_\",\n  },\n  {\n    id: \"secret.planetscale_token\",\n    label: \"PlanetScale token\",\n    severity: \"critical\",\n    critical: true,\n    regex: /\\bpscale_(?:pw|tkn)_[0-9A-Za-z._-]{32,}\\b/,\n    prefilter: \"pscale_\",\n  },\n  {\n    id: \"secret.databricks_token\",\n    label: \"Databricks token\",\n    severity: \"high\",\n    regex: /\\bdapi[0-9a-f]{32}\\b/,\n    prefilter: \"dapi\",\n  },\n  // ---- Observability / SaaS ------------------------------------------------\n  {\n    id: \"secret.datadog_key\",\n    label: \"Datadog API key\",\n    severity: \"high\",\n    regex: /datadog.{0,40}?(?:api|app).{0,8}?key.{0,8}?[\"'=:\\s]([0-9a-f]{32,40})\\b/i,\n    group: 1,\n    prefilter: \"datadog\",\n  },\n  {\n    id: \"secret.newrelic_key\",\n    label: \"New Relic API key\",\n    severity: \"high\",\n    regex: /\\bNRAK-[0-9A-Z]{27}\\b/,\n    prefilter: \"nrak-\",\n  },\n  {\n    id: \"secret.sentry_token\",\n    label: \"Sentry auth token\",\n    severity: \"high\",\n    regex: /\\bsntrys_[0-9A-Za-z_-]{60,}\\b/,\n    prefilter: \"sntrys_\",\n  },\n  {\n    id: \"secret.grafana_token\",\n    label: \"Grafana service-account token\",\n    severity: \"high\",\n    regex: /\\bglsa_[0-9A-Za-z]{32}_[0-9a-f]{8}\\b/,\n    prefilter: \"glsa_\",\n  },\n  {\n    id: \"secret.postman_key\",\n    label: \"Postman API key\",\n    severity: \"high\",\n    regex: /\\bPMAK-[0-9a-f]{24}-[0-9a-f]{34}\\b/,\n    prefilter: \"pmak-\",\n  },\n  {\n    id: \"secret.okta_token\",\n    label: \"Okta API token\",\n    severity: \"high\",\n    regex: /okta.{0,40}?[\"'=:\\s](00[0-9A-Za-z_-]{40})\\b/i,\n    group: 1,\n    prefilter: \"okta\",\n  },\n  // ---- Product / design SaaS -----------------------------------------------\n  {\n    id: \"secret.linear_key\",\n    label: \"Linear API key\",\n    severity: \"high\",\n    regex: /\\blin_api_[0-9A-Za-z]{40,}\\b/,\n    prefilter: \"lin_api_\",\n  },\n  {\n    id: \"secret.notion_token\",\n    label: \"Notion integration token\",\n    severity: \"high\",\n    regex: /\\b(?:secret_[0-9A-Za-z]{43}|ntn_[0-9A-Za-z]{40,})\\b/,\n    prefilter: [\"secret_\", \"ntn_\"],\n  },\n  {\n    id: \"secret.figma_token\",\n    label: \"Figma access token\",\n    severity: \"high\",\n    regex: /\\bfigd_[0-9A-Za-z_-]{40,}\\b/,\n    prefilter: \"figd_\",\n  },\n  {\n    id: \"secret.dropbox_token\",\n    label: \"Dropbox access token\",\n    severity: \"high\",\n    regex: /\\bsl\\.[0-9A-Za-z_-]{130,}\\b/,\n    prefilter: \"sl.\",\n  },\n  // ---- Generic shapes (lowest confidence) ----------------------------------\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    prefilter: \"-----begin\",\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    prefilter: \"eyj\",\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    prefilter: \"bearer\",\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    prefilter: [\"password\", \"passwd\", \"pwd\", \"secret\", \"key\", \"token\"],\n  },\n];\n\nexport const secretsDetector: Detector = {\n  id: \"secrets\",\n  category: \"secret\",\n  catalog: specCatalog(SECRET_PATTERNS, \"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 { CatalogEntry, Detector } from \"../types\";\nimport { abuseDetector } from \"./abuse\";\nimport { cardCapabilityDetector } from \"./card\";\nimport { destructiveDetector } from \"./destructive\";\nimport { egressDetector } from \"./egress\";\nimport { financialDetector } from \"./financial\";\nimport { injectionDetector } from \"./injection\";\nimport { jailbreakDetector } from \"./jailbreak\";\nimport { malwareDetector } from \"./malware\";\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  malwareDetector,\n  financialDetector,\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\n/**\n * The single source of truth for \"how many detectors do we run\". Assembled from\n * each detector's own `catalog`, so the count the product advertises is DERIVED\n * from the engine and can never drift from what actually fires. The parity test\n * asserts every emitted id appears here (and vice versa).\n */\nexport const DETECTOR_MANIFEST: CatalogEntry[] = DETECTORS.flatMap((d) => d.catalog);\n\n/** Always-on outbound detector count (what the marketing catalog advertises). */\nexport const DETECTOR_COUNT = DETECTOR_MANIFEST.length;\n\n/** Manifest for the inbound path (shared detectors + `rate_abuse`). */\nexport const INBOUND_DETECTOR_MANIFEST: CatalogEntry[] = INBOUND_DETECTORS.flatMap(\n  (d) => d.catalog,\n);\n\n/** Manifest for the card-preflight path (shared detectors + `supply_chain`). */\nexport const CARD_DETECTOR_MANIFEST: CatalogEntry[] = CARD_DETECTORS.flatMap(\n  (d) => d.catalog,\n);\n\n/** Distinct detector ids across every scan path (outbound + inbound + card). */\nexport const ALL_DETECTOR_IDS: string[] = [\n  ...new Set(\n    [...INBOUND_DETECTOR_MANIFEST, ...CARD_DETECTOR_MANIFEST].map((e) => e.id),\n  ),\n];\n\n/** Total distinct detectors across every path. */\nexport const ALL_DETECTOR_COUNT = ALL_DETECTOR_IDS.length;\n\nexport {\n  abuseDetector,\n  cardCapabilityDetector,\n  destructiveDetector,\n  egressDetector,\n  financialDetector,\n  injectionDetector,\n  jailbreakDetector,\n  malwareDetector,\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  malware: 1,\n  bot_spoof: 2,\n  supply_chain: 3,\n  destructive: 4,\n  injection: 5,\n  rate_abuse: 6,\n  financial: 7,\n  pii: 8,\n  egress: 9,\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, any destructive operation, any malware / dangerous-execution\n * indicator, and when the risk score reaches 75. Between the review band\n * (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 (signals.some((s) => s.category === \"malware\")) {\n    return {\n      decision: \"deny\",\n      reason: \"A malware / dangerous-execution indicator was detected.\",\n      rule: \"deny-malware\",\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 {\n  AxioRankAuthError,\n  AxioRankError,\n  AxioRankRequestError,\n} from \"./errors\";\nimport type { AxioGuardOptions, VerifyRequestResult } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://app.axiorank.com\";\nconst DEFAULT_TIMEOUT_MS = 800;\nconst DEFAULT_BODY_SAMPLE_BYTES = 16 * 1024;\nconst VERIFY_PATH = \"/api/gateway/verify-request\";\n\n// Never forward the end-user's own credentials to AxioRank.\nconst STRIP_HEADERS = new Set([\n  \"cookie\",\n  \"set-cookie\",\n  \"authorization\",\n  \"proxy-authorization\",\n]);\n\n/**\n * Verify an inbound request against AxioRank: collect the request metadata\n * (method, path, the Web Bot Auth signature headers, a bounded body sample),\n * POST it to the verify endpoint, and resolve with the verdict.\n *\n * Framework-agnostic - takes a standard `Request`, so it works in Next.js\n * middleware, Hono, Express (via a Request shim), or Workers. Throws only on a\n * misconfigured site key (401); any transport failure resolves to a synthetic\n * `onError` verdict so a verification outage never breaks the caller's site.\n */\nexport async function verifyRequest(\n  req: Request,\n  options: AxioGuardOptions,\n): Promise<VerifyRequestResult> {\n  const meta = await collectRequestMeta(\n    req,\n    options?.bodySampleBytes ?? DEFAULT_BODY_SAMPLE_BYTES,\n  );\n\n  return requestVerdict(meta, options);\n}\n\n/**\n * POST a verify-request body to the gateway and resolve with the verdict. Shared\n * by {@link verifyRequest} (website/HTTP surfaces) and {@link verifySurface}\n * (agent-native surfaces). Throws only on a 401 (misconfigured site key); any\n * transport failure resolves to a synthetic `onError` verdict (fail-open).\n */\nexport async function requestVerdict(\n  body: unknown,\n  options: AxioGuardOptions,\n): Promise<VerifyRequestResult> {\n  if (!options || !options.apiKey) {\n    throw new AxioRankError(\"AxioRank: `apiKey` is required\");\n  }\n  const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n  const fetchImpl = options.fetch ?? globalThis.fetch;\n  if (typeof fetchImpl !== \"function\") {\n    throw new AxioRankError(\n      \"AxioRank: no global `fetch` found - pass `options.fetch` explicitly\",\n    );\n  }\n\n  const controller = new AbortController();\n  const timer = setTimeout(() => controller.abort(), timeoutMs);\n  let res: Response;\n  try {\n    res = await fetchImpl(`${baseUrl}${VERIFY_PATH}`, {\n      method: \"POST\",\n      headers: {\n        \"content-type\": \"application/json\",\n        authorization: `Bearer ${options.apiKey}`,\n      },\n      body: JSON.stringify(body),\n      signal: controller.signal,\n    });\n  } catch (err) {\n    const reason =\n      err instanceof Error && err.name === \"AbortError\" ? \"timeout\" : \"network\";\n    return failOpen(options, reason);\n  } finally {\n    clearTimeout(timer);\n  }\n\n  // A bad site key is a configuration error the developer should see.\n  if (res.status === 401) throw new AxioRankAuthError();\n\n  let resBody: unknown = null;\n  try {\n    resBody = await res.json();\n  } catch {\n    // handled below\n  }\n\n  // Any other non-2xx is an operational failure, not a verdict → fail-open.\n  if (!res.ok) return failOpen(options, `status-${res.status}`);\n\n  return resBody as VerifyRequestResult;\n}\n\n/** Synthetic verdict used when AxioRank can't be reached (fail-open by default). */\nfunction failOpen(\n  options: AxioGuardOptions,\n  reason: string,\n): VerifyRequestResult {\n  const decision = options.onError ?? \"allow\";\n  return {\n    decision,\n    reason: `axiorank-unavailable (${reason})`,\n    risk: 0,\n    verification: {\n      status: \"unknown\",\n      method: null,\n      agentSlug: null,\n      agentLabel: null,\n      confidence: 0,\n    },\n    enforced: decision !== \"allow\",\n    requestId: \"\",\n  };\n}\n\nasync function collectRequestMeta(req: Request, bodySampleBytes: number) {\n  const url = new URL(req.url);\n\n  const headers: Record<string, string> = {};\n  req.headers.forEach((value, key) => {\n    const k = key.toLowerCase();\n    if (!STRIP_HEADERS.has(k)) headers[k] = value;\n  });\n\n  const authority =\n    req.headers.get(\"x-forwarded-host\") ??\n    req.headers.get(\"host\") ??\n    url.host;\n  const xff = req.headers.get(\"x-forwarded-for\");\n  const clientIp =\n    (xff ? xff.split(\",\")[0]?.trim() : null) ||\n    req.headers.get(\"x-real-ip\") ||\n    null;\n\n  let bodySample: string | null = null;\n  if (req.body && req.method !== \"GET\" && req.method !== \"HEAD\") {\n    try {\n      const buf = await req.clone().arrayBuffer();\n      const slice =\n        buf.byteLength > bodySampleBytes ? buf.slice(0, bodySampleBytes) : buf;\n      bodySample = new TextDecoder(\"utf-8\", { fatal: false }).decode(slice);\n    } catch {\n      // a non-buffer/streaming body we can't sample - skip it\n    }\n  }\n\n  return {\n    method: req.method.toUpperCase(),\n    authority: authority.toLowerCase(),\n    path: url.pathname,\n    query: url.search.replace(/^\\?/, \"\"),\n    userAgent: req.headers.get(\"user-agent\"),\n    clientIp,\n    signatureInput: req.headers.get(\"signature-input\"),\n    signature: req.headers.get(\"signature\"),\n    signatureAgent: req.headers.get(\"signature-agent\"),\n    headers,\n    bodySample,\n  };\n}\n\n// Re-export so consumers can narrow on the error in a catch.\nexport { AxioRankAuthError, AxioRankRequestError };\n","import { requestVerdict } from \"./verify\";\nimport type {\n  AxioGuardOptions,\n  VerifyRequestResult,\n  VerifySurfaceParams,\n} from \"./types\";\n\n/**\n * Verify the agent reaching into a NON-website surface you operate - an MCP\n * server, an A2A agent, an HTTP API, or a webhook - where there is no standard\n * `Request` to hand to {@link verifyRequest}. You supply the caller's identity\n * material directly (a signed card for mcp/a2a, an OAuth token or mTLS/SPIFFE id\n * for http_api), AxioRank verifies it, and the result carries the verdict plus a\n * per-kind `challenge` instruction to enforce a non-allow decision.\n *\n * Throws only on a misconfigured site key (401); any transport failure resolves\n * to a synthetic `onError` verdict so a verification outage never breaks you.\n *\n * @example MCP server you expose\n * const result = await verifySurface(\n *   { surfaceKind: \"mcp_server\", operation: \"tools/call\", agentCard: incomingCard },\n *   { apiKey: process.env.AXIORANK_SITE_KEY! },\n * );\n * if (result.decision !== \"allow\") throw rpcError(result.challenge);\n */\nexport async function verifySurface(\n  params: VerifySurfaceParams,\n  options: AxioGuardOptions,\n): Promise<VerifyRequestResult> {\n  const body: Record<string, unknown> = {\n    surfaceKind: params.surfaceKind,\n    headers: params.headers ?? {},\n  };\n  // Only forward the fields that are set, so the server schema's per-kind\n  // refinement sees exactly what the caller provided.\n  if (params.operation !== undefined) body.operation = params.operation;\n  if (params.agentCard !== undefined) body.agentCard = params.agentCard;\n  if (params.agentCardUrl !== undefined) body.agentCardUrl = params.agentCardUrl;\n  if (params.authToken !== undefined) body.authToken = params.authToken;\n  if (params.method !== undefined) body.method = params.method;\n  if (params.authority !== undefined) body.authority = params.authority;\n  if (params.path !== undefined) body.path = params.path;\n  if (params.clientIp !== undefined) body.clientIp = params.clientIp;\n  if (params.userAgent !== undefined) body.userAgent = params.userAgent;\n  if (params.bodySample !== undefined) body.bodySample = params.bodySample;\n  if (params.governancePassport !== undefined) body.governancePassport = params.governancePassport;\n\n  return requestVerdict(body, options);\n}\n","import type { AxioGuardOptions, VerifyRequestResult } from \"./types\";\nimport { verifyRequest } from \"./verify\";\n\n/**\n * Drop-in guard for a site's edge/middleware. Returns a `Response` to short\n * the request (403 block / 401 or custom challenge) or `undefined` to let it\n * continue - exactly the contract a Next.js middleware expects, with no\n * `next/server` dependency (a standard `Request`/`Response` works everywhere).\n *\n * @example\n * ```ts\n * // middleware.ts\n * import { axioGuard } from \"@axiorank/sdk\";\n * export const middleware = axioGuard({\n *   apiKey: process.env.AXIORANK_SITE_KEY!,\n *   onChallenge: (req) =>\n *     Response.redirect(new URL(\"/verify-human\", req.url), 302),\n * });\n * export const config = { matcher: [\"/api/:path*\", \"/admin/:path*\"] };\n * ```\n */\nexport function axioGuard(options: AxioGuardOptions) {\n  return async function middleware(req: Request): Promise<Response | undefined> {\n    let result: VerifyRequestResult;\n    try {\n      result = await verifyRequest(req, options);\n    } catch {\n      // Misconfiguration (e.g. bad site key) - fail-open rather than 500 the site.\n      return undefined;\n    }\n\n    if (options.enforce === false) return undefined; // monitor / log-only\n\n    if (result.decision === \"block\") {\n      return json({ error: \"blocked\", reason: result.reason }, 403);\n    }\n    if (result.decision === \"challenge\") {\n      const custom = options.onChallenge?.(req, result);\n      if (custom) return custom;\n      return json({ error: \"verification_required\", reason: result.reason }, 401);\n    }\n    return undefined; // allow → continue down the stack\n  };\n}\n\nfunction json(body: unknown, status: number): Response {\n  return new Response(JSON.stringify(body), {\n    status,\n    headers: { \"content-type\": \"application/json\" },\n  });\n}\n","import { AxioRankWebhookSignatureError } from \"./errors\";\n\n/**\n * Verify + parse AxioRank webhook deliveries (Stripe-style). Framework-agnostic and runtime-\n * portable: uses Web Crypto (`crypto.subtle`), so it works in Node 18+, edge, Workers, and Deno.\n * Pass the EXACT raw request body string you received - re-serializing it will break the HMAC.\n *\n * Signature scheme (kept in lockstep with the server's lib/webhooks/sign.ts):\n *   header `Axiorank-Signature: t=<unix>,v1=<hex>`, where v1 = HMAC_SHA256(secret, `${t}.${body}`).\n */\n\nconst DEFAULT_TOLERANCE_SEC = 300;\n\nexport interface WebhookEvent {\n  /** Stable idempotency id - dedupe on this. */\n  id: string;\n  /** Public event type, e.g. \"tool_call.evaluated\". */\n  type: string;\n  data: Record<string, unknown>;\n  /** Present on a replayed delivery - the original event id. */\n  replayOf?: string;\n}\n\nexport interface VerifyWebhookOptions {\n  /** Max clock skew (seconds) before a delivery is rejected as a replay. Default 300. */\n  toleranceSec?: number;\n  /** Injectable clock (unix seconds) for testing. */\n  nowSec?: number;\n}\n\nfunction parseSignatureHeader(header: string): { t: number; v1: string } | null {\n  let t: number | null = null;\n  let v1: string | null = null;\n  for (const part of header.split(\",\")) {\n    const i = part.indexOf(\"=\");\n    if (i < 0) continue;\n    const k = part.slice(0, i).trim();\n    const v = part.slice(i + 1).trim();\n    if (k === \"t\") t = Number(v);\n    else if (k === \"v1\") v1 = v;\n  }\n  if (t === null || !Number.isFinite(t) || !v1) return null;\n  return { t, v1 };\n}\n\nfunction toHex(buf: ArrayBuffer): string {\n  let out = \"\";\n  for (const b of new Uint8Array(buf)) out += b.toString(16).padStart(2, \"0\");\n  return out;\n}\n\nasync function hmacHex(secret: string, message: string): Promise<string> {\n  const enc = new TextEncoder();\n  const key = await crypto.subtle.importKey(\n    \"raw\",\n    enc.encode(secret),\n    { name: \"HMAC\", hash: \"SHA-256\" },\n    false,\n    [\"sign\"],\n  );\n  const sig = await crypto.subtle.sign(\"HMAC\", key, enc.encode(message));\n  return toHex(sig);\n}\n\n/** Constant-time compare of two hex strings. */\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n  if (a.length !== b.length || a.length === 0) return false;\n  let diff = 0;\n  for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);\n  return diff === 0;\n}\n\n/**\n * Verify the `Axiorank-Signature` header against the raw body. Returns false on a missing,\n * malformed, stale, or mismatched signature - never throws.\n */\nexport async function verifyWebhookSignature(\n  rawBody: string,\n  signatureHeader: string | null | undefined,\n  secret: string,\n  options: VerifyWebhookOptions = {},\n): Promise<boolean> {\n  if (!signatureHeader) return false;\n  const parsed = parseSignatureHeader(signatureHeader);\n  if (!parsed) return false;\n  const tolerance = options.toleranceSec ?? DEFAULT_TOLERANCE_SEC;\n  const now = options.nowSec ?? Math.floor(Date.now() / 1000);\n  if (Math.abs(now - parsed.t) > tolerance) return false;\n  const expected = await hmacHex(secret, `${parsed.t}.${rawBody}`);\n  return timingSafeEqualHex(parsed.v1, expected);\n}\n\n/**\n * Verify the signature and parse the body in one call. Throws\n * {@link AxioRankWebhookSignatureError} on a bad/stale/missing signature or non-JSON body;\n * otherwise returns the typed event. Dedupe on `event.id` (delivery is at-least-once).\n */\nexport async function constructEvent(\n  rawBody: string,\n  signatureHeader: string | null | undefined,\n  secret: string,\n  options: VerifyWebhookOptions = {},\n): Promise<WebhookEvent> {\n  const ok = await verifyWebhookSignature(rawBody, signatureHeader, secret, options);\n  if (!ok) throw new AxioRankWebhookSignatureError();\n  try {\n    return JSON.parse(rawBody) as WebhookEvent;\n  } catch {\n    throw new AxioRankWebhookSignatureError(\"AxioRank webhook body is not valid JSON\");\n  }\n}\n","/**\n * Shared core for the chat/completion guardrails. Every model-I/O wrapper funnels\n * through {@link guardCompletionFlow}: score the PROMPT before the model runs,\n * score the COMPLETION after, and block on a deny. Detection is local and\n * in-process (the same engine the gateway runs), so there is no network hop and\n * no key, exactly like {@link inspectPrompt} / {@link inspectCompletion}.\n */\nimport { AxioRankGuardError } from \"../errors\";\nimport { type InspectResult, inspectCompletion, inspectPrompt } from \"../inspect\";\n\nexport interface ChatGuardOptions {\n  /**\n   * On a denied prompt or completion: `\"throw\"` (default) raises\n   * {@link AxioRankGuardError}; `\"return\"` lets the call proceed and surfaces the\n   * verdict via {@link ChatGuardOptions.onDecision} instead of throwing, so the\n   * caller decides what to do.\n   * @default \"throw\"\n   */\n  onDeny?: \"throw\" | \"return\";\n  /** Observe every verdict (prompt and completion). Errors here are swallowed. */\n  onDecision?: (phase: \"prompt\" | \"completion\", result: InspectResult) => void;\n  /** Skip scoring the prompt (guard the output only). @default false */\n  skipPrompt?: boolean;\n  /** Skip scoring the completion (guard the input only). @default false */\n  skipCompletion?: boolean;\n}\n\nfunction handle(\n  phase: \"prompt\" | \"completion\",\n  result: InspectResult,\n  opts: ChatGuardOptions,\n): void {\n  if (opts.onDecision) {\n    try {\n      opts.onDecision(phase, result);\n    } catch {\n      // An observer must never change the outcome.\n    }\n  }\n  if (result.decision === \"deny\" && opts.onDeny !== \"return\") {\n    throw new AxioRankGuardError(phase, result.reason, result.risk);\n  }\n}\n\n/**\n * Guard a model call: inspect `promptText`, run `call`, inspect the completion\n * text pulled out with `extractCompletion`. Returns the model's own result\n * untouched on allow. Throws {@link AxioRankGuardError} on a blocked prompt or\n * completion unless `onDeny` is `\"return\"`.\n */\nexport async function guardCompletionFlow<R>(\n  promptText: string,\n  call: () => Promise<R>,\n  extractCompletion: (result: R) => string,\n  opts: ChatGuardOptions = {},\n): Promise<R> {\n  if (!opts.skipPrompt) {\n    handle(\"prompt\", inspectPrompt(promptText), opts);\n  }\n  const result = await call();\n  if (!opts.skipCompletion) {\n    handle(\"completion\", inspectCompletion(extractCompletion(result)), opts);\n  }\n  return result;\n}\n","/**\n * Drop-in model-I/O guardrails for the OpenAI and Anthropic chat APIs. Each wraps\n * the client's `create` so the PROMPT is scored before the model runs and the\n * COMPLETION is scored after, blocking prompt injection, jailbreaks, and a secret\n * or PII leaking in or out. Detection is local and in-process (no key, no\n * network), the same engine the hosted gateway runs.\n *\n * The clients are typed structurally, so these add no dependency on the openai or\n * @anthropic-ai/sdk packages.\n *\n * @example OpenAI\n * ```ts\n * import OpenAI from \"openai\";\n * import { guardOpenAIChat } from \"@axiorank/sdk\";\n *\n * const openai = new OpenAI();\n * const chat = guardOpenAIChat(openai.chat.completions, { onDeny: \"throw\" });\n * const res = await chat.create({ model: \"gpt-4.1\", messages });\n * ```\n *\n * @example Anthropic\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { guardAnthropicMessages } from \"@axiorank/sdk\";\n *\n * const anthropic = new Anthropic();\n * const messages = guardAnthropicMessages(anthropic.messages);\n * const msg = await messages.create({ model: \"claude-opus-4-8\", max_tokens: 1024, messages: msgs });\n * ```\n */\nimport { type ChatGuardOptions, guardCompletionFlow } from \"./_chat\";\n\nexport type { ChatGuardOptions } from \"./_chat\";\n\nfunction asText(content: unknown): string {\n  if (typeof content === \"string\") return content;\n  if (Array.isArray(content)) {\n    return content\n      .map((part) =>\n        part && typeof part === \"object\" && \"text\" in part\n          ? String((part as { text?: unknown }).text ?? \"\")\n          : typeof part === \"string\"\n            ? part\n            : \"\",\n      )\n      .join(\"\\n\");\n  }\n  return \"\";\n}\n\n// ── OpenAI chat.completions ────────────────────────────────────────────────\ninterface OpenAIMessage {\n  role: string;\n  content: unknown;\n}\n\nfunction openAIPromptText(messages: OpenAIMessage[]): string {\n  return messages.map((m) => asText(m.content)).join(\"\\n\");\n}\n\nfunction openAICompletionText(res: unknown): string {\n  const choices = (res as { choices?: Array<{ message?: { content?: unknown } }> })?.choices;\n  if (!Array.isArray(choices)) return \"\";\n  return choices.map((c) => asText(c?.message?.content)).join(\"\\n\");\n}\n\n/** Wrap `openai.chat.completions` so every create() is guarded on both sides. */\nexport function guardOpenAIChat<B extends { messages: OpenAIMessage[] }, R>(\n  completions: { create: (body: B) => Promise<R> },\n  opts: ChatGuardOptions = {},\n): { create: (body: B) => Promise<R> } {\n  return {\n    create: (body) =>\n      guardCompletionFlow(\n        openAIPromptText(body.messages),\n        () => completions.create(body),\n        openAICompletionText,\n        opts,\n      ),\n  };\n}\n\n// ── Anthropic messages ──────────────────────────────────────────────────────\ninterface AnthropicMessage {\n  role: string;\n  content: unknown;\n}\n\nfunction anthropicPromptText(messages: AnthropicMessage[]): string {\n  return messages.map((m) => asText(m.content)).join(\"\\n\");\n}\n\nfunction anthropicCompletionText(res: unknown): string {\n  return asText((res as { content?: unknown })?.content);\n}\n\n/** Wrap `anthropic.messages` so every create() is guarded on both sides. */\nexport function guardAnthropicMessages<B extends { messages: AnthropicMessage[] }, R>(\n  messages: { create: (body: B) => Promise<R> },\n  opts: ChatGuardOptions = {},\n): { create: (body: B) => Promise<R> } {\n  return {\n    create: (body) =>\n      guardCompletionFlow(\n        anthropicPromptText(body.messages),\n        () => messages.create(body),\n        anthropicCompletionText,\n        opts,\n      ),\n  };\n}\n","import type { AxioRank } from \"./client\";\nimport type { Decision, ToolCallResult, ToolCallSignal } from \"./types\";\n\n/**\n * Govern an OpenAI Realtime (voice-agent) session with AxioRank.\n *\n * A realtime session streams JSON events over a WebSocket (or WebRTC data\n * channel). Two of those events are security-relevant, and this guard maps each\n * to the SAME policy/risk/audit engine that governs ordinary tool calls:\n *\n * - `response.function_call_arguments.done` — the model asked to run a function\n *   tool. This is governed BEFORE your app executes it (preventive): on a deny,\n *   the guard hands you the client events to send back so the model gets a\n *   blocked result instead of the action running.\n * - `response.output_audio_transcript.done` / `response.output_text.done` — what\n *   the model just said. This is inspected for leaked secrets/PII (detective:\n *   in a live voice session the audio has already streamed, so a hit is audited\n *   and alerted, not un-said).\n *\n * The whole session is correlated into one AxioRank run, so multi-step \"kill\n * chains\" across a conversation are still caught. Transport-agnostic: you own\n * the socket and simply feed each server event to {@link RealtimeGuard.onServerEvent}.\n *\n * @example\n * ```ts\n * const axio = new AxioRank({ apiKey: process.env.AXIORANK_KEY! });\n * const guard = createRealtimeGuard(axio, { sessionId });\n * ws.on(\"message\", async (raw) => {\n *   const event = JSON.parse(raw.toString());\n *   const verdict = await guard.onServerEvent(event);\n *   for (const ev of verdict.send) ws.send(JSON.stringify(ev)); // deny injection\n *   if (verdict.kind === \"function_call\" && verdict.decision === \"allow\") {\n *     // ...run the tool and return your own function_call_output...\n *   }\n * });\n * ```\n */\nexport interface RealtimeGuardOptions {\n  /** Group this voice session with its siblings on the Agent Runs page. */\n  sessionId?: string;\n  /** Join an existing AxioRank run instead of starting a fresh one. */\n  traceId?: string;\n  /** Metadata tags merged onto every governed call (e.g. your end-user id). */\n  metadata?: Record<string, string | number | boolean>;\n  /**\n   * Inspect the model's output transcript for secret/PII leakage. Detective\n   * only (the audio has already streamed), so a hit is audited/alerted.\n   * @default true\n   */\n  inspectOutput?: boolean;\n  /** Tool name recorded for output-DLP inspection. @default \"realtime.output\" */\n  outputTool?: string;\n  /** Called when output DLP flags a leak in what the agent said. Best-effort. */\n  onOutputLeak?: (info: {\n    reason: string;\n    risk: number;\n    signals?: ToolCallSignal[];\n  }) => void;\n}\n\n/** Which kind of event the guard just handled. */\nexport type RealtimeGuardKind = \"function_call\" | \"output\" | \"ignored\";\n\n/** The guard's decision about one Realtime server event. */\nexport interface RealtimeGuardResult {\n  kind: RealtimeGuardKind;\n  /** `allow` = proceed; `deny` = the call was blocked (or a leak was found). */\n  decision: Decision;\n  reason?: string;\n  /** Risk score AxioRank assigned, when a verdict was fetched. */\n  risk?: number;\n  /** The governed function call, when `kind === \"function_call\"`. */\n  call?: { callId: string; name: string; arguments: Record<string, unknown> };\n  /**\n   * Client events to send back over the Realtime socket. On a denied function\n   * call this is a `function_call_output` carrying the block plus a\n   * `response.create` so the model continues gracefully. Empty otherwise.\n   */\n  send: Array<Record<string, unknown>>;\n  /** The raw governance result, when a verdict was fetched. */\n  result?: ToolCallResult;\n}\n\nexport interface RealtimeGuard {\n  /** Feed each server event you receive from the Realtime socket. */\n  onServerEvent(event: unknown): Promise<RealtimeGuardResult>;\n  /** The AxioRank run id correlating this voice session. */\n  readonly traceId: string;\n}\n\n/** A fresh \"not a governed event\" result (fresh so its `send` array is never shared). */\nconst ignored = (): RealtimeGuardResult => ({\n  kind: \"ignored\",\n  decision: \"allow\",\n  send: [],\n});\n\n/** Parse the function-call arguments (a JSON string on the wire) into an object. */\nfunction parseArgs(raw: unknown): Record<string, unknown> {\n  if (raw && typeof raw === \"object\") return raw as Record<string, unknown>;\n  if (typeof raw !== \"string\" || raw.length === 0) return {};\n  try {\n    const v = JSON.parse(raw) as unknown;\n    return v && typeof v === \"object\" ? (v as Record<string, unknown>) : { value: v };\n  } catch {\n    return { _raw: raw };\n  }\n}\n\n/** The events to send back so a denied function call returns a block, not a run. */\nfunction denialEvents(callId: string, reason: string): Array<Record<string, unknown>> {\n  return [\n    {\n      type: \"conversation.item.create\",\n      item: {\n        type: \"function_call_output\",\n        call_id: callId,\n        output: JSON.stringify({ error: \"blocked_by_axiorank\", reason }),\n      },\n    },\n    { type: \"response.create\" },\n  ];\n}\n\n/**\n * Create a guard for one Realtime session. Pass an {@link AxioRank} client; the\n * guard opens a correlated run and governs each relevant server event you feed\n * it. Reuses your client's outage posture (`fail_open`/`fail_closed`), so a\n * gateway outage never silently halts a live call unless you configured it to.\n */\nexport function createRealtimeGuard(\n  client: AxioRank,\n  options: RealtimeGuardOptions = {},\n): RealtimeGuard {\n  const trace = client.trace({\n    id: options.traceId,\n    sessionId: options.sessionId,\n    metadata: { surface: \"realtime\", ...options.metadata },\n  });\n  const inspectOutput = options.inspectOutput ?? true;\n  const outputTool = options.outputTool ?? \"realtime.output\";\n  // The function name isn't always on the arguments.done event, so remember it\n  // from the function_call item when it's created, keyed by call_id.\n  const names = new Map<string, string>();\n\n  async function onServerEvent(event: unknown): Promise<RealtimeGuardResult> {\n    const ev = event as { type?: unknown };\n    const type = typeof ev?.type === \"string\" ? ev.type : \"\";\n\n    // Learn function-call names from the item as it's added to the conversation.\n    if (type === \"response.output_item.added\" || type === \"conversation.item.created\") {\n      const item = (event as { item?: { type?: string; call_id?: string; name?: string } })\n        .item;\n      if (item?.type === \"function_call\" && item.call_id && item.name) {\n        names.set(item.call_id, item.name);\n      }\n      return ignored();\n    }\n\n    // Preventive: govern a function/tool call before your app runs it.\n    if (type === \"response.function_call_arguments.done\") {\n      const e = event as { call_id?: string; name?: string; arguments?: unknown };\n      const callId = e.call_id ?? \"\";\n      const name = e.name ?? names.get(callId) ?? \"unknown\";\n      const args = parseArgs(e.arguments);\n      const call = { callId, name, arguments: args };\n      const result = await trace.toolCall({ tool: name, arguments: args });\n      if (result.decision === \"deny\") {\n        return {\n          kind: \"function_call\",\n          decision: \"deny\",\n          reason: result.reason,\n          risk: result.risk,\n          call,\n          result,\n          send: denialEvents(callId, result.reason),\n        };\n      }\n      return {\n        kind: \"function_call\",\n        decision: \"allow\",\n        reason: result.reason,\n        risk: result.risk,\n        call,\n        result,\n        send: [],\n      };\n    }\n\n    // Detective: inspect what the model SAID for secret/PII leakage.\n    if (\n      inspectOutput &&\n      (type === \"response.output_audio_transcript.done\" ||\n        type === \"response.output_text.done\")\n    ) {\n      const e = event as { transcript?: unknown; text?: unknown };\n      const text =\n        typeof e.transcript === \"string\"\n          ? e.transcript\n          : typeof e.text === \"string\"\n            ? e.text\n            : \"\";\n      if (!text) return ignored();\n      const result = await trace.inspectResult({ tool: outputTool, resultText: text });\n      if (result.decision === \"deny\") {\n        try {\n          options.onOutputLeak?.({\n            reason: result.reason,\n            risk: result.risk,\n            signals: result.signals,\n          });\n        } catch {\n          // A telemetry callback must never break the session.\n        }\n      }\n      return {\n        kind: \"output\",\n        decision: result.decision,\n        reason: result.reason,\n        risk: result.risk,\n        result,\n        send: [],\n      };\n    }\n\n    return ignored();\n  }\n\n  return { onServerEvent, traceId: trace.id };\n}\n"]}