/**
 * ToolProviderHealthVerifier -- Active per-provider health verification.
 *
 * BUILD_PLAN_V3_FULL_LIFECYCLE.md line 236:
 *   "Tool-provider health verification surfaced on agent detail page
 *    (provider still compliant under active pack)"
 *
 * WHY: ProviderCompliance answers "Does Anthropic offer a BAA?" at config
 * time. This module answers a different question: "Right now, is this
 * specific provider still healthy for this specific agent under its bound
 * packs?" Provider posture changes underneath you. You signed a BAA on
 * Jan 1; the provider revokes their BAA framework on Mar 15; your
 * HIPAA-bound agent keeps calling them. Without active verification, you
 * find out at the next audit.
 *
 * Four-signal composite (all must pass for HEALTHY):
 *   1. Risk score: ProviderCompliance.check() pass (score derived from
 *      compliance posture) must exceed pack threshold (>= 0.85 strict,
 *      >= 0.70 non-strict).
 *   2. Agreements: TenantProviderAgreementRegistry.requireActive() must
 *      not throw (no missing BAA/DPA/SCC/BCR kinds).
 *   3. Pack compliance: provider capabilities satisfy all pack-required
 *      modes (data-residency, encryption-at-rest).
 *   4. Connectivity: operator-supplied probe callback must respond within
 *      5 s. Optional signal -- absent probe skips this check.
 *
 * State machine:
 *   HEALTHY   -- all four signals green.
 *   DEGRADED  -- 1+ signal warning (agreement expiring <= 30 days; score
 *                0.05 below threshold). Agent continues; operator alerted.
 *   UNHEALTHY -- 1+ signal hard-failed. Agent invocations blocked.
 *
 * Gate ordering (PreToolUse chain):
 *   AFTER capability-change detection (PR #31)
 *   AFTER autonomy spectrum (PR #24)
 *   BEFORE tool rate limit (PR #14)
 *
 * Compliance bindings:
 *   HIPAA 45 CFR 164.308(b): BAA requirement per covered entity
 *   HIPAA 45 CFR 164.308(a)(1)(ii)(D): evaluation of technical controls
 *   SOC 2 CC9.2: vendor monitoring
 *   GDPR Art. 28: controller-processor DPA requirement
 *   DORA Art. 28-30: ICT third-party risk continuous assessment
 *
 * @connexum/ai-governance
 */
import { ProviderCompliance } from '../security/provider-compliance';
import { OperatorRoles } from '../security/operator-roles';
/**
 * Operator-supplied probe. Returns void on success; throws on failure.
 * Must complete within 5 000 ms or the verifier treats it as a failure.
 * The probe is ONE of FOUR signals; a green probe with failing agreements
 * still produces UNHEALTHY.
 */
export type ProviderProbeCallback = () => Promise<void>;
export type ProviderHealthStatus = 'HEALTHY' | 'DEGRADED' | 'UNHEALTHY';
export interface RiskScoreSignal {
    ok: boolean;
    /** True when score is above threshold but within warning band (>= threshold - 0.05). */
    warning: boolean;
    score: number;
    threshold: number;
    detail: string;
}
export interface AgreementSignal {
    ok: boolean;
    /** True when any active agreement expires within 30 days. */
    warning: boolean;
    missingKinds: string[];
    expiringKinds: string[];
    detail: string;
}
export interface PackComplianceSignal {
    ok: boolean;
    warning: boolean;
    missingModes: string[];
    detail: string;
}
export interface ConnectivitySignal {
    ok: boolean;
    warning: boolean;
    skipped: boolean;
    latencyMs?: number;
    detail: string;
}
export interface HealthSignals {
    riskScore: RiskScoreSignal;
    agreements: AgreementSignal;
    packCompliance: PackComplianceSignal;
    connectivity: ConnectivitySignal;
}
export interface HealthVerificationResult {
    status: ProviderHealthStatus;
    signals: HealthSignals;
    /** High-resolution epoch nanoseconds at check time. */
    checkedAtNs: bigint;
    orgId: string;
    tenantId: string;
    agentId: string;
    providerId: string;
    packBinding: string[];
}
export type HealthEventType = 'TOOL_PROVIDER_HEALTH_CHANGED' | 'TOOL_PROVIDER_DEGRADED_USAGE';
export type HealthAuditSeverity = 'NOTICE' | 'WARNING' | 'ERROR';
export interface HealthAuditEvent {
    type: HealthEventType;
    severity: HealthAuditSeverity;
    orgId: string;
    tenantId: string;
    agentId: string;
    providerId: string;
    priorStatus: ProviderHealthStatus | null;
    currentStatus: ProviderHealthStatus;
    packBinding: string[];
    signals?: HealthSignals;
    timestamp: string;
    /** SHA-256 of prior event for chain integrity. */
    prevSha?: string;
}
export declare class ToolProviderUnhealthyError extends Error {
    readonly orgId: string;
    readonly tenantId: string;
    readonly agentId: string;
    readonly providerId: string;
    readonly packBinding: string[];
    constructor(opts: {
        orgId: string;
        tenantId: string;
        agentId: string;
        providerId: string;
        packBinding: string[];
        detail: string;
    });
}
export declare class EmptyPackBindingHealthError extends Error {
    constructor(operation: string);
}
export declare class HealthPermissionError extends Error {
    readonly operatorId: string;
    constructor(operatorId: string, action: string, reason: string);
}
export type StatusChangeCallback = (orgId: string, tenantId: string, agentId: string, providerId: string, prior: ProviderHealthStatus | null, current: ProviderHealthStatus) => void;
/**
 * Minimal surface of TenantProviderAgreementRegistry consumed by this module.
 * Using a structural interface avoids a hard circular dependency on
 * tenant-provider-agreements.ts in the gate chain.
 *
 * Production wiring: pass a real TenantProviderAgreementRegistry instance.
 * Test wiring: pass a stub that throws on missing agreements.
 */
export interface AgreementRegistryStub {
    requireActive(tenantId: string, providerId: string, requiredKinds: string[], packBinding?: string[]): void;
    /**
     * Returns agreements expiring within `daysAhead` days for a specific
     * tenantId + providerId pair. Used to produce the DEGRADED warning signal.
     * Return an empty array when no expiring agreements exist.
     */
    listExpiringWithinForProvider(tenantId: string, providerId: string, daysAhead: number): Array<{
        agreementKind: string;
    }>;
}
/**
 * Minimal pack metadata surface. The full CompliancePack interface is not
 * required -- we only need the provider policy required-capabilities list
 * and the optional providerHealthCheckIntervalMs field.
 */
export interface PackHealthMetadata {
    id: string;
    /** Required provider capability strings (e.g. 'BAA', 'ENCRYPTION_AT_REST'). */
    providerPolicy: {
        requiredCapabilities: string[];
    };
    /**
     * How frequently to probe this provider when the agent is active.
     * Strict packs (HIPAA, GDPR, PCI DSS, DORA) set 300_000 (5 min).
     * Non-strict packs default to 3_600_000 (1 hr).
     */
    providerHealthCheckIntervalMs?: number;
}
declare const STRICT_PACK_IDS: Set<string>;
declare const STRICT_SCORE_THRESHOLD = 0.85;
declare const NON_STRICT_SCORE_THRESHOLD = 0.7;
declare const PROBE_TIMEOUT_MS = 5000;
declare const AGREEMENT_EXPIRY_WARNING_DAYS = 30;
declare const DEFAULT_STRICT_INTERVAL_MS = 300000;
declare const DEFAULT_NON_STRICT_INTERVAL_MS = 3600000;
export declare class ToolProviderHealthVerifier {
    private readonly providerCompliance;
    private readonly agreementRegistry;
    private readonly operatorRoles;
    /** In-memory status cache. Key: `${orgId}::${tenantId}::${agentId}::${providerId}` */
    private readonly statusCache;
    /** Operator-supplied probe callbacks. Key: providerId */
    private readonly probes;
    /** Status-change subscribers. */
    private readonly subscribers;
    /** SHA-256 of the last audit event emitted (for chaining). */
    private lastAuditSha;
    /** Active probe schedulers. */
    private readonly schedulers;
    constructor(opts: {
        providerCompliance: ProviderCompliance;
        agreementRegistry: AgreementRegistryStub;
        operatorRoles: OperatorRoles;
    });
    /**
     * Wire an operator-supplied connectivity probe for a provider.
     * Optional: not all providers expose a cheap health endpoint.
     * Probe is ONE of FOUR signals; a green probe with failing agreements
     * still produces UNHEALTHY.
     */
    setProbe(providerId: string, probeCallback: ProviderProbeCallback): void;
    /**
     * Subscribe to status transitions. Callback fires synchronously after each
     * status change. Multiple subscribers are supported.
     */
    subscribeStatusChanges(callback: StatusChangeCallback): void;
    /**
     * Schedule periodic health probes for an agent-provider pair.
     * Requires 'governance.configure' permission (ADMIN role).
     *
     * Default intervalMs:
     *   - Active agent under strict pack: 300_000 (5 min)
     *   - Active agent under non-strict pack: 3_600_000 (1 hr)
     *
     * @throws HealthPermissionError when operator lacks ADMIN role.
     * @throws EmptyPackBindingHealthError when packBinding is empty.
     */
    scheduleProbe(orgId: string, tenantId: string, agentId: string, providerId: string, intervalMs: number, packBinding: string[], operatorId: string): void;
    /**
     * Cancel a scheduled probe. Cleans up the interval timer.
     */
    cancelSchedule(orgId: string, tenantId: string, agentId: string, providerId: string): void;
    /**
     * Return the last computed status without forcing a fresh check.
     * Returns null when no check has been performed yet.
     *
     * Note: this is a read-only accessor. There is no public setter -- status
     * entries are computed-only (PT-PROVIDER-HEALTH-3 defence: cache-poisoning
     * prevention).
     */
    getStatus(orgId: string, tenantId: string, agentId: string, providerId: string): HealthVerificationResult | null;
    /**
     * Run all four signals and return a composite health result.
     * Updates the in-memory cache and emits TOOL_PROVIDER_HEALTH_CHANGED if
     * the status transitions.
     *
     * @throws EmptyPackBindingHealthError when packBinding is empty.
     */
    verifyHealth(orgId: string, tenantId: string, agentId: string, providerId: string, packBinding: string[]): Promise<HealthVerificationResult>;
    /**
     * PreToolUse gate. Call this when an agent attempts to invoke a
     * provider-bound tool.
     *
     * Behaviour:
     *   - If cached status is fresh (< intervalMs old), uses cache.
     *   - If cache is stale (>= intervalMs), forces a re-check
     *     (PT-PROVIDER-HEALTH-1 stale-status attack mitigation).
     *   - UNHEALTHY: throws ToolProviderUnhealthyError (fail-closed).
     *   - DEGRADED: emits TOOL_PROVIDER_DEGRADED_USAGE WARNING, allows.
     *   - HEALTHY: passes silently.
     *
     * @throws ToolProviderUnhealthyError when provider is UNHEALTHY.
     * @throws EmptyPackBindingHealthError when packBinding is empty.
     */
    enforceGate(orgId: string, tenantId: string, agentId: string, providerId: string, packBinding: string[], intervalMs?: number): Promise<void>;
    private evaluateRiskScore;
    private evaluateAgreements;
    private evaluatePackCompliance;
    private evaluateConnectivity;
    private deriveStatus;
    private emitAuditEvent;
    private cacheKey;
    private transitionSeverity;
    private defaultIntervalMs;
    /**
     * Derive required capability strings for a set of packs.
     * HIPAA requires BAA; GDPR requires GDPR-DPA; PCI-DSS requires SOC2-TYPE2.
     */
    private requiredCapabilitiesForPacks;
    /**
     * Derive required agreement kinds from packs.
     * HIPAA: BAA | GDPR: DPA | DORA: DPA | PCI-DSS: DPA
     */
    private requiredAgreementKinds;
    /**
     * Derive required provider operational modes from packs.
     * E.g. HIPAA requires encryption-at-rest.
     */
    private packRequiredModes;
    private buildUnhealthyDetail;
}
/**
 * Returns the default probe interval for a given pack strictness level.
 * Pack authors use this in their CompliancePack definition.
 */
export declare function defaultProviderHealthCheckIntervalMs(isStrict: boolean): number;
export { STRICT_PACK_IDS, STRICT_SCORE_THRESHOLD, NON_STRICT_SCORE_THRESHOLD, PROBE_TIMEOUT_MS, AGREEMENT_EXPIRY_WARNING_DAYS, DEFAULT_STRICT_INTERVAL_MS, DEFAULT_NON_STRICT_INTERVAL_MS, };
//# sourceMappingURL=tool-provider-health.d.ts.map