Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

181 KB
Raw Blame
/**
 * Auto-generated from the Django backend OpenAPI schema.
 * To modify these types, update the Django serializers or views, then run:
 *   hogli build:openapi
 * Questions or issues? #team-devex on Slack
 *
 * PostHog API - generated
 * OpenAPI spec version: 1.0.0
 */
/**
 * * `metric` - Metric
 * * `match` - Match
 */
export type VisionAlertKindEnumApi = (typeof VisionAlertKindEnumApi)[keyof typeof VisionAlertKindEnumApi]

export const VisionAlertKindEnumApi = {
    Metric: 'metric',
    Match: 'match',
} as const

export interface VisionAlertSelectionApi {
    /**
     * Monitor verdicts to match, e.g. ['yes'].
     * @maxItems 10
     * @items.maxLength 100
     */
    verdict?: string[]
    /**
     * Classifier tags to match; an observation matches when it carries any of them.
     * @maxItems 20
     * @items.maxLength 200
     */
    tags?: string[]
    /** Minimum scorer score (inclusive). */
    min_score?: number
    /** Maximum scorer score (inclusive). */
    max_score?: number
}

/**
 * * `count` - Count matching observations
 * * `avg_score` - Average score
 */
export type VisionAlertMetricEnumApi = (typeof VisionAlertMetricEnumApi)[keyof typeof VisionAlertMetricEnumApi]

export const VisionAlertMetricEnumApi = {
    Count: 'count',
    AvgScore: 'avg_score',
} as const

/**
 * * `above` - At or above
 * * `below` - At or below
 */
export type VisionAlertDirectionEnumApi = (typeof VisionAlertDirectionEnumApi)[keyof typeof VisionAlertDirectionEnumApi]

export const VisionAlertDirectionEnumApi = {
    Above: 'above',
    Below: 'below',
} as const

/**
 * * `not_firing` - Not firing
 * * `firing` - Firing
 * * `pending_resolve` - Pending resolve
 * * `errored` - Errored
 * * `snoozed` - Snoozed
 * * `broken` - Broken
 */
export type LogsAlertConfigurationStateEnumApi =
    (typeof LogsAlertConfigurationStateEnumApi)[keyof typeof LogsAlertConfigurationStateEnumApi]

export const LogsAlertConfigurationStateEnumApi = {
    NotFiring: 'not_firing',
    Firing: 'firing',
    PendingResolve: 'pending_resolve',
    Errored: 'errored',
    Snoozed: 'snoozed',
    Broken: 'broken',
} as const

export interface AlertScheduleRestrictionWindowApi {
    /** Start time HH:MM (24-hour, project timezone). Inclusive. Each window must span ≥ 30 minutes on the local daily timeline (half-open [start, end)). */
    start: string
    /** End time HH:MM (24-hour). Exclusive (half-open interval). Each window must span ≥ 30 minutes locally. */
    end: string
}

export interface AlertScheduleRestrictionApi {
    /** Blocked local time windows when the alert must not run. Overlapping or identical windows are merged when saved. At most five windows before normalization; empty array clears quiet hours. */
    blocked_windows: AlertScheduleRestrictionWindowApi[]
}

/**
 * * `engineering` - Engineering
 * * `data` - Data
 * * `product` - Product Management
 * * `founder` - Founder
 * * `leadership` - Leadership
 * * `marketing` - Marketing
 * * `sales` - Sales / Success
 * * `student` - Student
 * * `other` - Other
 */
export type RoleAtOrganizationEnumApi = (typeof RoleAtOrganizationEnumApi)[keyof typeof RoleAtOrganizationEnumApi]

export const RoleAtOrganizationEnumApi = {
    Engineering: 'engineering',
    Data: 'data',
    Product: 'product',
    Founder: 'founder',
    Leadership: 'leadership',
    Marketing: 'marketing',
    Sales: 'sales',
    Student: 'student',
    Other: 'other',
} as const

export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]

export const BlankEnumApi = {
    '': '',
} as const

/**
 * @nullable
 */
export type UserBasicApiHedgehogConfig = { [key: string]: unknown } | null

export interface UserBasicApi {
    readonly id: number
    readonly uuid: string
    /**
     * @maxLength 200
     * @nullable
     */
    distinct_id?: string | null
    /** @maxLength 150 */
    first_name?: string
    /** @maxLength 150 */
    last_name?: string
    /** @maxLength 254 */
    email: string
    /** @nullable */
    is_email_verified?: boolean | null
    /** @nullable */
    readonly hedgehog_config: UserBasicApiHedgehogConfig
    role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
}

export interface VisionAlertConfigurationApi {
    /** Unique identifier for this alert. */
    readonly id: string
    /** Scanner whose observations this alert watches. Immutable after creation. */
    scanner_id: string
    /**
     * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
     * @maxLength 255
     */
    name?: string
    /** Whether the alert is active. Disabling a metric alert resets its state to not_firing. */
    enabled?: boolean
    /** 'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.
     *
     * * `metric` - Metric
     * * `match` - Match */
    kind: VisionAlertKindEnumApi
    /** Which observations count. Empty matches every observation of the scanner. */
    selection?: VisionAlertSelectionApi
    /** Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.
     *
     * * `count` - Count matching observations
     * * `avg_score` - Average score */
    metric?: VisionAlertMetricEnumApi
    /** Metric alerts only: whether the alert fires at or above, or at or below, the threshold.
     *
     * * `above` - At or above
     * * `below` - At or below */
    direction?: VisionAlertDirectionEnumApi
    /**
     * Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.
     * @nullable
     */
    threshold?: number | null
    /** Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30]. */
    window_days?: number
    /**
     * Metric alerts only: evaluation cadence in minutes, at least 15.
     * @minimum 15
     */
    check_interval_minutes?: number
    /** Current lifecycle state. Always not_firing for match alerts. Server-managed.
     *
     * * `not_firing` - Not firing
     * * `firing` - Firing
     * * `pending_resolve` - Pending resolve
     * * `errored` - Errored
     * * `snoozed` - Snoozed
     * * `broken` - Broken */
    readonly state: LogsAlertConfigurationStateEnumApi
    /**
     * Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).
     * @minimum 1
     * @maximum 10
     */
    evaluation_periods?: number
    /**
     * Metric alerts only: how many periods must breach to fire (N in N-of-M).
     * @minimum 1
     * @maximum 10
     */
    datapoints_to_alarm?: number
    /**
     * Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.
     * @minimum 0
     */
    cooldown_minutes?: number
    /** Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours. */
    schedule_restriction?: AlertScheduleRestrictionApi | null
    /**
     * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
     * @nullable
     */
    snooze_until?: string | null
    /**
     * When the next evaluation is scheduled. Server-managed.
     * @nullable
     */
    readonly next_check_at: string | null
    /**
     * When the last notification was sent. Server-managed.
     * @nullable
     */
    readonly last_notified_at: string | null
    /**
     * When the alert was last evaluated. Server-managed.
     * @nullable
     */
    readonly last_checked_at: string | null
    /** Consecutive evaluation failures. Resets on success. Server-managed. */
    readonly consecutive_failures: number
    /**
     * When the alert was first enabled. Null means still a draft.
     * @nullable
     */
    readonly first_enabled_at: string | null
    /** When the alert was created. */
    readonly created_at: string
    /** User who created the alert; null once that user is deleted. */
    readonly created_by: UserBasicApi | null
    /**
     * When the alert was last modified.
     * @nullable
     */
    readonly updated_at: string | null
}

export interface PaginatedVisionAlertConfigurationListApi {
    count: number
    /** @nullable */
    next?: string | null
    /** @nullable */
    previous?: string | null
    results: VisionAlertConfigurationApi[]
}

/**
 * * `slack` - slack
 * * `webhook` - webhook
 */
export type VisionAlertDestinationTypeEnumApi =
    (typeof VisionAlertDestinationTypeEnumApi)[keyof typeof VisionAlertDestinationTypeEnumApi]

export const VisionAlertDestinationTypeEnumApi = {
    Slack: 'slack',
    Webhook: 'webhook',
} as const

export interface VisionAlertDestinationConfigApi {
    /** HogFunctions backing the created destination, one per event kind. */
    hog_function_ids: string[]
    /** Notification destination type.
     *
     * * `slack` - slack
     * * `webhook` - webhook */
    type: VisionAlertDestinationTypeEnumApi
    /** Whether every HogFunction in the group is enabled, so the destination notifies on every event kind. */
    enabled: boolean
    /** Integration ID of the Slack workspace, for Slack destinations. */
    slack_workspace_id?: number
    /** Slack channel ID, for Slack destinations. */
    slack_channel_id?: string
    /** Webhook endpoint reduced to scheme and host, because the path, query and userinfo can carry a secret. */
    webhook_url?: string
}

export interface VisionAlertConfigurationDetailApi {
    /** Unique identifier for this alert. */
    readonly id: string
    /** Scanner whose observations this alert watches. Immutable after creation. */
    scanner_id: string
    /**
     * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
     * @maxLength 255
     */
    name?: string
    /** Whether the alert is active. Disabling a metric alert resets its state to not_firing. */
    enabled?: boolean
    /** 'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.
     *
     * * `metric` - Metric
     * * `match` - Match */
    kind: VisionAlertKindEnumApi
    /** Which observations count. Empty matches every observation of the scanner. */
    selection?: VisionAlertSelectionApi
    /** Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.
     *
     * * `count` - Count matching observations
     * * `avg_score` - Average score */
    metric?: VisionAlertMetricEnumApi
    /** Metric alerts only: whether the alert fires at or above, or at or below, the threshold.
     *
     * * `above` - At or above
     * * `below` - At or below */
    direction?: VisionAlertDirectionEnumApi
    /**
     * Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.
     * @nullable
     */
    threshold?: number | null
    /** Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30]. */
    window_days?: number
    /**
     * Metric alerts only: evaluation cadence in minutes, at least 15.
     * @minimum 15
     */
    check_interval_minutes?: number
    /** Current lifecycle state. Always not_firing for match alerts. Server-managed.
     *
     * * `not_firing` - Not firing
     * * `firing` - Firing
     * * `pending_resolve` - Pending resolve
     * * `errored` - Errored
     * * `snoozed` - Snoozed
     * * `broken` - Broken */
    readonly state: LogsAlertConfigurationStateEnumApi
    /**
     * Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).
     * @minimum 1
     * @maximum 10
     */
    evaluation_periods?: number
    /**
     * Metric alerts only: how many periods must breach to fire (N in N-of-M).
     * @minimum 1
     * @maximum 10
     */
    datapoints_to_alarm?: number
    /**
     * Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.
     * @minimum 0
     */
    cooldown_minutes?: number
    /** Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours. */
    schedule_restriction?: AlertScheduleRestrictionApi | null
    /**
     * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
     * @nullable
     */
    snooze_until?: string | null
    /**
     * When the next evaluation is scheduled. Server-managed.
     * @nullable
     */
    readonly next_check_at: string | null
    /**
     * When the last notification was sent. Server-managed.
     * @nullable
     */
    readonly last_notified_at: string | null
    /**
     * When the alert was last evaluated. Server-managed.
     * @nullable
     */
    readonly last_checked_at: string | null
    /** Consecutive evaluation failures. Resets on success. Server-managed. */
    readonly consecutive_failures: number
    /**
     * When the alert was first enabled. Null means still a draft.
     * @nullable
     */
    readonly first_enabled_at: string | null
    /** When the alert was created. */
    readonly created_at: string
    /** User who created the alert; null once that user is deleted. */
    readonly created_by: UserBasicApi | null
    /**
     * When the alert was last modified.
     * @nullable
     */
    readonly updated_at: string | null
    /** This alert's notification destinations, one entry per destination, with credential-bearing URL parts removed. */
    readonly destinations: readonly VisionAlertDestinationConfigApi[]
}

export interface PatchedVisionAlertConfigurationApi {
    /** Unique identifier for this alert. */
    readonly id?: string
    /** Scanner whose observations this alert watches. Immutable after creation. */
    scanner_id?: string
    /**
     * Human-readable name for this alert. Defaults to 'Untitled alert' on create when omitted.
     * @maxLength 255
     */
    name?: string
    /** Whether the alert is active. Disabling a metric alert resets its state to not_firing. */
    enabled?: boolean
    /** 'metric' fires when a metric crosses a threshold over a rolling window; 'match' fires on every observation that matches the selection. Immutable after creation.
     *
     * * `metric` - Metric
     * * `match` - Match */
    kind?: VisionAlertKindEnumApi
    /** Which observations count. Empty matches every observation of the scanner. */
    selection?: VisionAlertSelectionApi
    /** Metric alerts only: what to measure over the window. 'avg_score' requires a scorer scanner.
     *
     * * `count` - Count matching observations
     * * `avg_score` - Average score */
    metric?: VisionAlertMetricEnumApi
    /** Metric alerts only: whether the alert fires at or above, or at or below, the threshold.
     *
     * * `above` - At or above
     * * `below` - At or below */
    direction?: VisionAlertDirectionEnumApi
    /**
     * Metric alerts only: the threshold value. Required for metric alerts, must be omitted for match alerts.
     * @nullable
     */
    threshold?: number | null
    /** Metric alerts only: rolling window in days. Allowed values: [1, 3, 7, 14, 30]. */
    window_days?: number
    /**
     * Metric alerts only: evaluation cadence in minutes, at least 15.
     * @minimum 15
     */
    check_interval_minutes?: number
    /** Current lifecycle state. Always not_firing for match alerts. Server-managed.
     *
     * * `not_firing` - Not firing
     * * `firing` - Firing
     * * `pending_resolve` - Pending resolve
     * * `errored` - Errored
     * * `snoozed` - Snoozed
     * * `broken` - Broken */
    readonly state?: LogsAlertConfigurationStateEnumApi
    /**
     * Metric alerts only: total check periods in the sliding evaluation window (M in N-of-M).
     * @minimum 1
     * @maximum 10
     */
    evaluation_periods?: number
    /**
     * Metric alerts only: how many periods must breach to fire (N in N-of-M).
     * @minimum 1
     * @maximum 10
     */
    datapoints_to_alarm?: number
    /**
     * Metric alerts only: minimum minutes between repeated notifications. 0 means no cooldown.
     * @minimum 0
     */
    cooldown_minutes?: number
    /** Blocked local time windows when the alert must not notify. Times use the project timezone. Null disables quiet hours. */
    schedule_restriction?: AlertScheduleRestrictionApi | null
    /**
     * ISO 8601 timestamp until which the alert is snoozed. Set to null to unsnooze.
     * @nullable
     */
    snooze_until?: string | null
    /**
     * When the next evaluation is scheduled. Server-managed.
     * @nullable
     */
    readonly next_check_at?: string | null
    /**
     * When the last notification was sent. Server-managed.
     * @nullable
     */
    readonly last_notified_at?: string | null
    /**
     * When the alert was last evaluated. Server-managed.
     * @nullable
     */
    readonly last_checked_at?: string | null
    /** Consecutive evaluation failures. Resets on success. Server-managed. */
    readonly consecutive_failures?: number
    /**
     * When the alert was first enabled. Null means still a draft.
     * @nullable
     */
    readonly first_enabled_at?: string | null
    /** When the alert was created. */
    readonly created_at?: string
    /** User who created the alert; null once that user is deleted. */
    readonly created_by?: UserBasicApi | null
    /**
     * When the alert was last modified.
     * @nullable
     */
    readonly updated_at?: string | null
}

export interface VisionAlertCreateDestinationApi {
    /** Notification destination type.
     *
     * * `slack` - slack
     * * `webhook` - webhook */
    type: VisionAlertDestinationTypeEnumApi
    /** Integration ID for the Slack workspace. Required when type=slack. */
    slack_workspace_id?: number
    /** Slack channel ID. Required when type=slack. */
    slack_channel_id?: string
    /** Human-readable channel name for display. */
    slack_channel_name?: string
    /** HTTPS endpoint to post to. Required when type=webhook. */
    webhook_url?: string
}

export interface VisionAlertDestinationResponseApi {
    /** HogFunctions backing the created destination, one per event kind. */
    hog_function_ids: string[]
}

export interface VisionAlertDeleteDestinationApi {
    /**
     * HogFunction IDs to delete as one atomic destination group.
     * @minItems 1
     * @maxItems 5
     */
    hog_function_ids: string[]
}

/**
 * * `check` - Check
 * * `reset` - Reset
 * * `enable` - Enable
 * * `disable` - Disable
 * * `snooze` - Snooze
 * * `unsnooze` - Unsnooze
 * * `threshold_change` - Threshold change
 */
export type VisionAlertEventKindEnumApi = (typeof VisionAlertEventKindEnumApi)[keyof typeof VisionAlertEventKindEnumApi]

export const VisionAlertEventKindEnumApi = {
    Check: 'check',
    Reset: 'reset',
    Enable: 'enable',
    Disable: 'disable',
    Snooze: 'snooze',
    Unsnooze: 'unsnooze',
    ThresholdChange: 'threshold_change',
} as const

export interface VisionAlertEventApi {
    readonly id: string
    readonly created_at: string
    readonly kind: VisionAlertEventKindEnumApi
    readonly state_before: string
    readonly state_after: string
    readonly threshold_breached: boolean
    /** @nullable */
    readonly metric_value: number | null
    /** @nullable */
    readonly error_message: string | null
}

export interface PaginatedVisionAlertEventListApi {
    count: number
    /** @nullable */
    next?: string | null
    /** @nullable */
    previous?: string | null
    results: VisionAlertEventApi[]
}

/**
 * * `emerging` - Emerging
 * * `active` - Active
 * * `fading` - Fading
 * * `dormant` - Dormant
 */
export type ClusterStatusEnumApi = (typeof ClusterStatusEnumApi)[keyof typeof ClusterStatusEnumApi]

export const ClusterStatusEnumApi = {
    Emerging: 'emerging',
    Active: 'active',
    Fading: 'fading',
    Dormant: 'dormant',
} as const

export interface VariantCountApi {
    /** The variant key, or `__unattributed__` for members with none. */
    key: string
    /** The group's members in this variant in the window. */
    observation_count: number
    /** Distinct people among them. */
    people_count: number
}

export interface ClusterApi {
    /** The cluster id. Pass it as `theme` or `group` to `vision-scanners-observations-list` to read members. */
    id: string
    /** The scanner whose observations the cluster groups. */
    scanner_id: string
    /** The scanner's name. */
    scanner_name: string
    /**
     * A short model-written search phrase for a theme. Null for a group, and for a theme too small to be named; `example_summary` stands in.
     * @nullable
     */
    name: string | null
    /** Where the cluster stands, from its members: `emerging` (first member this week), `active`, `fading` (last week under half of the week before) or `dormant` (no member for two weeks).
     *
     * * `emerging` - Emerging
     * * `active` - Active
     * * `fading` - Fading
     * * `dormant` - Dormant */
    status: ClusterStatusEnumApi
    /** Readable observations in the window: issue observations, plus routine ones with `include_routine`. */
    observation_count: number
    /** Distinct people among them; a session without an identified person counts as one. */
    people_count: number
    /** Members in the same-length window just before `date_from`, to compare the trend against. */
    previous_observation_count: number
    /** When the window's oldest member was observed. */
    first_seen: string
    /** When the window's newest member was observed. */
    last_seen: string
    /** Up to 3 of the window's highest-ranked members, best first. */
    example_observation_ids: string[]
    /** One-line summary of the best example; the readable label for a group, which has no name. */
    example_summary: string
    /** The window's members split by experiment variant, largest first. Empty unless `by_variant` is set. Compare each variant's share of the group with its share of the scanner's sessions, since variants are sampled at different rates. */
    variants: VariantCountApi[]
}

export interface ClusterListApi {
    /** Clusters with at least one member in the window. */
    results: ClusterApi[]
    /** Whether another page follows at `offset + limit`. */
    has_more: boolean
}

/**
 * * `configured` - Configured
 * * `inline` - Inline
 */
export type ScannerOriginEnumApi = (typeof ScannerOriginEnumApi)[keyof typeof ScannerOriginEnumApi]

export const ScannerOriginEnumApi = {
    Configured: 'configured',
    Inline: 'inline',
} as const

/**
 * * `pending` - Pending
 * * `running` - Running
 * * `succeeded` - Succeeded
 * * `failed` - Failed
 * * `ineligible` - Ineligible
 */
export type ObservationStatusEnumApi = (typeof ObservationStatusEnumApi)[keyof typeof ObservationStatusEnumApi]

export const ObservationStatusEnumApi = {
    Pending: 'pending',
    Running: 'running',
    Succeeded: 'succeeded',
    Failed: 'failed',
    Ineligible: 'ineligible',
} as const

/**
 * * `monitor` - Monitor
 * * `classifier` - Classifier
 * * `scorer` - Scorer
 * * `summarizer` - Summarizer
 * * `experiment` - Experiment
 */
export type ScannerTypeEnumApi = (typeof ScannerTypeEnumApi)[keyof typeof ScannerTypeEnumApi]

export const ScannerTypeEnumApi = {
    Monitor: 'monitor',
    Classifier: 'classifier',
    Scorer: 'scorer',
    Summarizer: 'summarizer',
    Experiment: 'experiment',
} as const

/**
 * Experiment scanners with balanced sampling: the 0..1 rate each watched variant was sampled at by the tick that dispatched this scan. Null otherwise, so even per-variant counts can be read against the rates that produced them.
 * @nullable
 */
export type ScannerSnapshotApiVariantSamplingRates = { [key: string]: number } | null

/**
 * Mirrors `temporal.types.ScannerSnapshot` for OpenAPI generation.
 */
export interface ScannerSnapshotApi {
    /** Scanner name at run time. */
    name: string
    /** Scanner type (monitor, classifier, scorer, summarizer, experiment) at run time.
     *
     * * `monitor` - Monitor
     * * `classifier` - Classifier
     * * `scorer` - Scorer
     * * `summarizer` - Summarizer
     * * `experiment` - Experiment */
    scanner_type: ScannerTypeEnumApi
    /** The `ReplayScanner.scanner_version` value at the moment the workflow ran. */
    scanner_version: number
    /** Concrete model that ran the observation; historical rows may carry since-retired model ids. */
    model: string
    /** Concrete provider that ran the observation; historical rows may carry since-retired providers. */
    provider: string
    /** Whether the observation was run with Signal emission enabled. */
    emits_signals: boolean
    /** Scanner-type-specific configuration at run time (prompt, tags, scale, etc.). */
    scanner_config: unknown
    /**
     * Experiment scanners with balanced sampling: the 0..1 rate each watched variant was sampled at by the tick that dispatched this scan. Null otherwise, so even per-variant counts can be read against the rates that produced them.
     * @nullable
     */
    variant_sampling_rates?: ScannerSnapshotApiVariantSamplingRates
}

/**
 * Mirrors `temporal.types.ScannerResult` for OpenAPI generation.
 */
export interface ScannerResultApi {
    /** Validated scanner output. Shape depends on `scanner_snapshot.scanner_type`; always carries `confidence` and `scanner_type`. */
    model_output: unknown
    /**
     * Number of PostHog Signals emitted from this observation.
     * @minimum 0
     */
    signals_count: number
    /**
     * Experiment scanners only: the variant the exposure data attributes this session's person to. Null on the other types and on rows scanned before variant attribution shipped.
     * @nullable
     */
    experiment_variant?: string | null
    /**
     * Experiment scanners only: the scanned session's duration in seconds.
     * @nullable
     */
    session_duration_s?: number | null
}

export type PromptValenceEnumApi = (typeof PromptValenceEnumApi)[keyof typeof PromptValenceEnumApi]

export const PromptValenceEnumApi = {
    Good: 'good',
    Bad: 'bad',
    Neutral: 'neutral',
} as const

/**
 * * `schedule` - Schedule
 * * `on_demand` - On demand
 * * `retry` - Retry
 * * `backfill` - Backfill
 */
export type ObservationTriggerEnumApi = (typeof ObservationTriggerEnumApi)[keyof typeof ObservationTriggerEnumApi]

export const ObservationTriggerEnumApi = {
    Schedule: 'schedule',
    OnDemand: 'on_demand',
    Retry: 'retry',
    Backfill: 'backfill',
} as const

/**
 * The team's shared judgement on whether the scanner scored this session correctly.
 */
export interface ReplayObservationLabelApi {
    /** True if the scanner scored this session correctly, false if not. */
    is_correct: boolean
    /**
     * Optional written context on the rating, for thumbs-up and thumbs-down alike: what the scanner got right or wrong, or what it should have concluded.
     * @maxLength 5000
     */
    feedback?: string
}

/**
 * * `thumbnail` - Thumbnail
 * * `chapter` - Chapter
 */
export type ReplayObservationMediaKindEnumApi =
    (typeof ReplayObservationMediaKindEnumApi)[keyof typeof ReplayObservationMediaKindEnumApi]

export const ReplayObservationMediaKindEnumApi = {
    Thumbnail: 'thumbnail',
    Chapter: 'chapter',
} as const

/**
 * One frame illustrating an observation.
 */
export interface ReplayObservationMediaApi {
    /** Id of this media entry. */
    readonly id: string
    /** `thumbnail` for the single frame that illustrates the observation, `chapter` for the frame of one summary chapter.
     *
     * * `thumbnail` - Thumbnail
     * * `chapter` - Chapter */
    readonly kind: ReplayObservationMediaKindEnumApi
    /** Order among media of the same kind. For a `chapter` frame, the index into `model_output.chapters`. */
    readonly position: number
    /** Export asset holding the bytes; fetch it from the export content endpoint. */
    readonly asset_id: number
    /** Where this media starts in the analysis video, in milliseconds. */
    readonly video_start_ms: number
}

export interface ReplayObservationApi {
    readonly id: string
    /** The scanner that produced this observation. */
    readonly scanner_id: string
    /** Where the producing scanner came from. `configured` scanners are saved, named, and have a detail page; `inline` ones are throwaways minted for a one-off scan and are not addressable, so callers must not link to them.
     *
     * * `configured` - Configured
     * * `inline` - Inline */
    readonly scanner_origin: ScannerOriginEnumApi
    /** Session recording id this scanner was applied to. */
    readonly session_id: string
    /** Observation status (pending, running, succeeded, failed, ineligible).
     *
     * * `pending` - Pending
     * * `running` - Running
     * * `succeeded` - Succeeded
     * * `failed` - Failed
     * * `ineligible` - Ineligible */
    readonly status: ObservationStatusEnumApi
    /** Populated on terminal non-success statuses; formatted as `kind:human-readable message`. For `ineligible`, kind is one of no_recording / too_short / too_inactive / too_long / no_events / no_snapshots / too_large / not_exposed / experiment_unresolved. For `failed`, kind is one of provider_transient / provider_rejected / rasterization_failed / validation_failed / infra_transient / internal_error / orphaned / pii_detected. */
    readonly error_reason: string
    /** Temporal workflow id for progress queries and debugging. Empty until the workflow starts. */
    readonly workflow_id: string
    /** Frozen view of the scanner at run time; scanner edits do not retroactively mutate this observation. */
    readonly scanner_snapshot: ScannerSnapshotApi | null
    /** Result data persisted on success; null until the observation succeeds. */
    readonly scanner_result: ScannerResultApi | null
    /**
     * The scanner's prompt condensed into the one question it answers about a session. Null when the prompt has changed since this observation was scanned, since the question then describes a different prompt; read `scanner_snapshot.scanner_config.prompt` instead.
     * @nullable
     */
    readonly prompt_question: string | null
    /** For a monitor or scorer: `good` when a yes or a high score is good news for the team, `bad` when it is a problem, `neutral` when neither. Judged by AI from the prompt. Null for other scanner types, when not judged, or when the prompt has changed since this observation was scanned. */
    readonly prompt_valence: PromptValenceEnumApi | null
    /** Whether this observation came from the schedule, an on-demand request, a retry of a failed or ineligible observation, or a historical backfill.
     *
     * * `schedule` - Schedule
     * * `on_demand` - On demand
     * * `retry` - Retry
     * * `backfill` - Backfill */
    readonly triggered_by: ObservationTriggerEnumApi
    /** User who triggered an on-demand observation; null for scheduled observations. */
    readonly triggered_by_user: UserBasicApi | null
    /**
     * Backfill that dispatched this observation; null for live, on-demand, and retry triggers.
     * @nullable
     */
    readonly backfill_id: string | null
    /**
     * Distinct id of the person in the recorded session (the subject being watched); null if unknown.
     * @nullable
     */
    readonly distinct_id: string | null
    /**
     * Email of the person in the recorded session (the subject being watched, not the user who triggered the observation), captured at scan time. Null when the session had no identified person.
     * @nullable
     */
    readonly recording_subject_email: string | null
    /**
     * Id of the preceding sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the start of the set.
     * @nullable
     */
    readonly previous_observation_id: string | null
    /**
     * Id of the following sibling observation for the same scanner (prev/next nav), honoring any list filters and ordering passed to retrieve; only set on retrieve, null at the end of the set.
     * @nullable
     */
    readonly next_observation_id: string | null
    /** The team's shared label on this observation (correct/incorrect + feedback), or null if unlabeled. */
    readonly label: ReplayObservationLabelApi | null
    /** Whether the calling user has opened this observation. */
    readonly viewed: boolean
    /** Frames illustrating this observation, in order. Empty until the media render finishes. */
    readonly media: readonly ReplayObservationMediaApi[]
    /** One line of plain text saying what the scanner found: its verdict, score, tags or title, then its own words, with markdown flattened and the text truncated. An observation that produced no result carries the reason instead, and one still in flight carries an empty string. Read this in place of `scanner_result` when you scan a list of observations. */
    readonly summary_line: string
    /** @nullable */
    started_at?: string | null
    /** @nullable */
    completed_at?: string | null
    readonly created_at: string
}

export interface PaginatedReplayObservationListApi {
    count: number
    /** @nullable */
    next?: string | null
    /** @nullable */
    previous?: string | null
    results: ReplayObservationApi[]
}

/**
 * The PostHog Task created from an observation.
 */
export interface CreateTaskFromObservationResponseApi {
    /** ID of the PostHog Task holding this observation's finding, created now (201) or by an earlier call (200). */
    task_id: string
}

/**
 * * `not_a_real_problem` - Not a real problem
 * * `already_known` - Already known
 * * `not_my_area` - Not my area
 * * `other` - Other
 */
export type FeedDismissalReasonEnumApi = (typeof FeedDismissalReasonEnumApi)[keyof typeof FeedDismissalReasonEnumApi]

export const FeedDismissalReasonEnumApi = {
    NotARealProblem: 'not_a_real_problem',
    AlreadyKnown: 'already_known',
    NotMyArea: 'not_my_area',
    Other: 'other',
} as const

/**
 * Why the calling user marked an observation not useful in the Highlights feed.
 */
export interface ObservationFeedDismissalApi {
    /** Optional reason the observation was not useful. Omit or send null when the user gave none.
     *
     * * `not_a_real_problem` - Not a real problem
     * * `already_known` - Already known
     * * `not_my_area` - Not my area
     * * `other` - Other */
    reason?: FeedDismissalReasonEnumApi | null
}

/**
 * Async-accepted response for POST /vision/scanners/{id}/observations/{id}/retry/.
 */
export interface RetryResponseApi {
    /** Temporal workflow id for the re-run. The retried observation row is deleted; look up its replacement via GET /vision/scanners/{id}/observations/?session_id=<session_id>. */
    workflow_id: string
}

/**
 * The shape every Replay Vision error response uses, so generated clients read one key.
 */
export interface ReplayVisionErrorApi {
    /** Human-readable explanation of why the request was refused. */
    detail: string
}

/**
 * An inbox report that this observation's emitted signals were grouped into.
 */
export interface ObservationSignalReportApi {
    /** ID of the inbox report, for linking to its inbox page. */
    id: string
    /**
     * Report title, null while the report is still too new to have been summarized.
     * @nullable
     */
    title: string | null
    /** The report's status in the inbox: potential, candidate, in_progress, pending_input, ready, resolved, failed, or suppressed. */
    status: string
    /** When the report was created. */
    created_at: string
}

export interface ObservationSearchResultApi {
    /** The matching observation. */
    observation: ReplayObservationApi
    /** Cosine distance between the search text and the observation's closest embedding. Lower is a closer match. Only comparable to other results in the same response. */
    distance: number
    /** Excerpt of the observation text that best matched the search, truncated. Empty for observations analyzed before excerpts were stored. */
    matched_content: string
}

export interface ObservationSearchResponseApi {
    /** Matching observations, most relevant first. */
    results: ObservationSearchResultApi[]
    /** True when more matches may exist beyond `results`, so the response is a top slice rather than everything that matched. */
    truncated: boolean
    /** True when a relevance model reordered the top results after the embedding match. False when the results are in embedding distance order, for example because the model did not answer in time. */
    reranked: boolean
}

export interface SearchSuggestionsResponseApi {
    /** Up to 4 example searches naming the largest active themes in recent issue observations. Empty until a scanner has a named theme. */
    queries: string[]
}

export interface SearchSuggestionsQueryApi {
    /** Scope to a single scanner's observations. Defaults to every scanner you can read. */
    scanner_id?: string
}

export interface VisionQuotaApi {
    /**
     * Credits the organization may spend per billing period (1 credit = $0.01). 0 is a hard block: no observation can start. Null when billing has synced the product with no spend limit: uncapped.
     * @nullable
     */
    readonly credit_limit: number | null
    /** `credits_settled` plus `credits_reserved`: the organization's total draw on `credit_limit` this period, across every project. */
    readonly credits_used: number
    /** Credits posted to the receipt ledger by succeeded observations and finished prompt-test sessions this period, across every project in the organization. Deleting an observation never refunds these. */
    readonly credits_settled: number
    /** Credits held by in-flight observations across every project in the organization. Released without charge when the work fails, settled into `credits_settled` when it succeeds. */
    readonly credits_reserved: number
    /**
     * `credit_limit - credits_used`, floored at 0. Null when uncapped.
     * @nullable
     */
    readonly remaining: number | null
    /** True when `credits_used >= credit_limit`; further observations are skipped until next period. Always false when uncapped. */
    readonly exhausted: boolean
    /** First moment of the current quota period (UTC). */
    readonly period_start: string
    /** First moment of the next quota period (UTC); the current period's exclusive upper bound. */
    readonly period_end: string
    /** `scanners_monthly_credits` plus `backfills_committed_credits`. Kept as the single headline number; prefer the two components when pro-rating, since only the scanner half is a monthly rate. */
    readonly projected_monthly_credits: number
    /** Credit-weighted sum of enabled scanners' projected observations/month across the organization. A capped scanner contributes at most what its own credit limit has left this period, folded back into a 30-day rate. A monthly rate: only the part falling in the days left of the period lands this period. Scanners without a computed estimate contribute 0. */
    readonly scanners_monthly_credits: number
    /** The part of `scanners_monthly_credits` that lands between now and `period_end`. Use it for rest-of-period forecasts; billing forecasts from the same figure. */
    readonly scanners_period_credits: number
    /** Committed-but-unspent credits of the organization's active backfills. A one-off charge rather than a rate, so it lands in full regardless of how much of the period is left. */
    readonly backfills_committed_credits: number
    /** Credits per period included for free. Already counted inside `credit_limit`; only credits beyond this number are billed. */
    readonly free_monthly_credits: number
}

export interface VisionSpendDayApi {
    /** UTC calendar day. */
    readonly date: string
    /** Credits settled by observations created on this day across every project in the organization; 0 when none. */
    readonly credits: number
}

export interface VisionSpendSeriesApi {
    /** First moment of the current quota period (UTC). */
    readonly period_start: string
    /** First moment of the next quota period (UTC); the current period's exclusive upper bound. */
    readonly period_end: string
    /** One entry per UTC day from `period_start` through today, in order, zero-filled for days without spend. */
    readonly days: readonly VisionSpendDayApi[]
}

/**
 * * `summarize_recording` - Summarize recording
 */
export type BuiltInScanKeyEnumApi = (typeof BuiltInScanKeyEnumApi)[keyof typeof BuiltInScanKeyEnumApi]

export const BuiltInScanKeyEnumApi = {
    SummarizeRecording: 'summarize_recording',
} as const

/**
 * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
 * * `gemini-3-flash-preview` - Gemini 3 Flash
 * * `gemini-3.8-flash` - Gemini 3.8 Flash
 */
export type ScannerModelEnumApi = (typeof ScannerModelEnumApi)[keyof typeof ScannerModelEnumApi]

export const ScannerModelEnumApi = {
    Gemini35FlashLite: 'gemini-3.5-flash-lite',
    Gemini3FlashPreview: 'gemini-3-flash-preview',
    Gemini38Flash: 'gemini-3.8-flash',
} as const

/**
 * A question asked inline, without saving a scanner first.
 */
export interface InlineScanConfigApi {
    /** Run a scan PostHog defines instead of your own prompt. `summarize_recording` is the AI summary the Summarize button in the replay player runs, so its results are shared with that button. Leave out `prompt`, `scanner_type` and `scanner_config` when this is set.
     *
     * * `summarize_recording` - Summarize recording */
    built_in?: BuiltInScanKeyEnumApi
    /**
     * What to look for in these sessions, in plain language. The same instruction a saved scanner carries. Required unless `built_in` is set.
     * @maxLength 20000
     */
    prompt?: string
    /** What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` for a summary in your own words; use `built_in: summarize_recording` for the Summarize button's summary. An inline scan is keyed by its whole config, so asking the same question again reuses its answers.
     *
     * * `monitor` - Monitor
     * * `classifier` - Classifier
     * * `scorer` - Scorer
     * * `summarizer` - Summarizer
     * * `experiment` - Experiment */
    scanner_type?: ScannerTypeEnumApi
    /** Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here. */
    scanner_config?: unknown
    /** Model to scan with. Determines what each observation costs in credits.
     *
     * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
     * * `gemini-3-flash-preview` - Gemini 3 Flash
     * * `gemini-3.8-flash` - Gemini 3.8 Flash */
    model?: ScannerModelEnumApi
}

/**
 * Body of POST /vision/requests/ - the sessions plus a saved scanner or an inline question.
 */
export interface CreateObservationRequestApi {
    /**
     * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole request. Duplicates are dropped.
     * @maxItems 200
     * @items.maxLength 128
     */
    session_ids: string[]
    /** A saved scanner to apply to the sessions. Pass this or `inline`, not both. */
    scanner_id?: string
    /** A question to ask without saving a scanner first. Asking the same question again reuses the answers already given for the same sessions. Pass this or `scanner_id`, not both. */
    inline?: InlineScanConfigApi
    /**
     * Any unique string per logical request, such as a UUID. Sending the same key again returns the first request instead of starting new scans, so a retry after a timeout never charges twice.
     * @maxLength 200
     */
    idempotency_key?: string
    /**
     * Your own id for this request, such as a ticket or job id. Returned unchanged.
     * @maxLength 200
     */
    reference?: string
    /** Hold the scans until every session has been quiet for 35 minutes, so each one is scanned whole. Use it when the sessions may still be recording. A scan of a live session sees only part of it, and its observation can't be replaced later. Sessions still active after 6 hours are scanned as they are. */
    wait_for_session_end?: boolean
}

/**
 * * `running` - Running
 * * `completed` - Completed
 */
export type ObservationRequestStatusEnumApi =
    (typeof ObservationRequestStatusEnumApi)[keyof typeof ObservationRequestStatusEnumApi]

export const ObservationRequestStatusEnumApi = {
    Running: 'running',
    Completed: 'completed',
} as const

/**
 * * `started` - Started
 * * `already_running` - Already running
 * * `already_scanned` - Already scanned
 * * `skipped_limit` - Skipped, in-flight limit reached
 * * `skipped_quota` - Skipped, the org's credit quota for this period was reached
 * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached
 * * `failed` - Failed to start
 */
export type ScanOutcomeEnumApi = (typeof ScanOutcomeEnumApi)[keyof typeof ScanOutcomeEnumApi]

export const ScanOutcomeEnumApi = {
    Started: 'started',
    AlreadyRunning: 'already_running',
    AlreadyScanned: 'already_scanned',
    SkippedLimit: 'skipped_limit',
    SkippedQuota: 'skipped_quota',
    SkippedScannerLimit: 'skipped_scanner_limit',
    Failed: 'failed',
} as const

/**
 * * `pending` - Pending
 * * `running` - Running
 * * `succeeded` - Succeeded
 * * `failed` - Failed
 * * `ineligible` - Ineligible
 * * `skipped` - Skipped
 * * `lost` - Lost
 */
export type RequestSessionStateEnumApi = (typeof RequestSessionStateEnumApi)[keyof typeof RequestSessionStateEnumApi]

export const RequestSessionStateEnumApi = {
    Pending: 'pending',
    Running: 'running',
    Succeeded: 'succeeded',
    Failed: 'failed',
    Ineligible: 'ineligible',
    Skipped: 'skipped',
    Lost: 'lost',
} as const

/**
 * One session of a request: how it started and where it stands now.
 */
export interface ObservationRequestSessionApi {
    /** The session recording this outcome is for. */
    session_id: string
    /** How the session's scan started, with the same values as a bulk scan trigger. Null while the request still waits for the session to end, or before its scan has started.
     *
     * * `started` - Started
     * * `already_running` - Already running
     * * `already_scanned` - Already scanned
     * * `skipped_limit` - Skipped, in-flight limit reached
     * * `skipped_quota` - Skipped, the org's credit quota for this period was reached
     * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached
     * * `failed` - Failed to start */
    scan_outcome: ScanOutcomeEnumApi | null
    /** Where the session stands now. 'pending' and 'running' are still in progress; 'succeeded' has a result; 'failed' and 'ineligible' finished without one; 'skipped' never started because a limit was reached (`scan_outcome` names which); 'lost' started but produced nothing before the scan timed out.
     *
     * * `pending` - Pending
     * * `running` - Running
     * * `succeeded` - Succeeded
     * * `failed` - Failed
     * * `ineligible` - Ineligible
     * * `skipped` - Skipped
     * * `lost` - Lost */
    state: RequestSessionStateEnumApi
    /**
     * The observation for this session, once one exists. Null before that.
     * @nullable
     */
    readonly observation_id: string | null
    /** The scanner's answer for this session. Null until the session succeeds. */
    readonly scanner_result: ScannerResultApi | null
}

/**
 * A scan request and the current state of each of its sessions.
 */
export interface ObservationRequestApi {
    /** Request ID. Poll `GET /vision/requests/{id}/` with it. */
    id: string
    /** 'completed' once every session has settled, whether or not it produced a result.
     *
     * * `running` - Running
     * * `completed` - Completed */
    status: ObservationRequestStatusEnumApi
    /**
     * The scanner the sessions were scanned with. For an inline question this is a hidden scanner, shared by every request that asks the same question. Null when nothing could start.
     * @nullable
     */
    scanner_id: string | null
    /** The `reference` sent with the request. */
    reference: string
    /** When the request was made. */
    created_at: string
    /** One entry per session, in request order. */
    sessions: ObservationRequestSessionApi[]
}

/**
 * * `ai` - AI draft
 * * `template` - Template
 * * `scratch` - From scratch
 */
export type ScannerCreationMethodEnumApi =
    (typeof ScannerCreationMethodEnumApi)[keyof typeof ScannerCreationMethodEnumApi]

export const ScannerCreationMethodEnumApi = {
    Ai: 'ai',
    Template: 'template',
    Scratch: 'scratch',
} as const

/**
 * * `focused` - Focused
 * * `balanced` - Balanced
 * * `comprehensive` - Comprehensive
 */
export type SamplingModeEnumApi = (typeof SamplingModeEnumApi)[keyof typeof SamplingModeEnumApi]

export const SamplingModeEnumApi = {
    Focused: 'focused',
    Balanced: 'balanced',
    Comprehensive: 'comprehensive',
} as const

/**
 * * `google` - Google
 */
export type ScannerProviderEnumApi = (typeof ScannerProviderEnumApi)[keyof typeof ScannerProviderEnumApi]

export const ScannerProviderEnumApi = {
    Google: 'google',
} as const

/**
 * The experiment a scanner watches. Scans derive their person-scoped exposure filter from
 * this blob at query time, so it is the only place an experiment can enter a scanner's
 * targeting — which is what lets the write-side access check and read-side redaction cover it.
 */
export interface ScannerExperimentTargetingApi {
    /**
     * The experiment the scanner watches.
     * @minimum 1
     */
    experiment_id: number
    /**
     * Narrow to sessions of people exposed to this variant. Null means every variant.
     * @maxLength 400
     * @nullable
     */
    variant?: string | null
}

export type UnrunnableReasonEnumApi = (typeof UnrunnableReasonEnumApi)[keyof typeof UnrunnableReasonEnumApi]

export const UnrunnableReasonEnumApi = {
    NoAiConsent: 'no_ai_consent',
    CreatorLostAccess: 'creator_lost_access',
} as const

/**
 * A Replay Vision scanner: its type, targeting query, and AI configuration.
 */
export interface ReplayScannerApi {
    readonly id: string
    /**
     * Human-readable scanner name. Unique within the team.
     * @maxLength 255
     */
    name: string
    /**
     * Free-form description shown in the scanner management UI.
     * @maxLength 1000
     */
    description?: string
    /**
     * Organizational tags for this scanner. Distinct from a classifier's categories in scanner_config. Tags cannot contain commas.
     * @maxItems 32
     * @items.maxLength 255
     */
    tags?: string[]
    /** What the scanner does: monitor, classifier, scorer, or summarizer.
     *
     * * `monitor` - Monitor
     * * `classifier` - Classifier
     * * `scorer` - Scorer
     * * `summarizer` - Summarizer
     * * `experiment` - Experiment */
    scanner_type: ScannerTypeEnumApi
    /**
     * The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.
     * @maxLength 2000
     * @nullable
     */
    goal?: string | null
    /** How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.
     *
     * * `ai` - AI draft
     * * `template` - Template
     * * `scratch` - From scratch */
    creation_method?: ScannerCreationMethodEnumApi | null
    /**
     * The app surface the creator started from, such as `replay_filters`. Reported to product analytics at creation so a scanner can be attributed to its entry point, and not stored on the scanner. Only the app's value is kept: any other caller is reported as its own source, such as `mcp`. Ignored on update.
     * @nullable
     * @pattern ^[a-z0-9_]{1,64}$
     */
    entry_point?: string | null
    /** Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`. */
    take_over_as_creator?: boolean
    /** Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`. */
    scanner_config: unknown
    /** The current prompt condensed by AI into the one question the scanner answers about a session. Falls back to the prompt's first line when no question matches the current prompt. */
    readonly prompt_question: string
    /** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
    query?: unknown
    /**
     * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.
     * @minimum 0
     * @maximum 1
     */
    sampling_rate?: number
    /** Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).
     *
     * * `focused` - Focused
     * * `balanced` - Balanced
     * * `comprehensive` - Comprehensive */
    sampling_mode?: SamplingModeEnumApi
    /**
     * Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped.
     * @minimum 1
     * @maximum 2147483647
     * @nullable
     */
    credit_limit?: number | null
    /** Run only while the organization has free credits left this billing period, so the scanner never adds spend. */
    free_only?: boolean
    /** LLM provider. v1 is Google-only.
     *
     * * `google` - Google */
    provider?: ScannerProviderEnumApi
    /** Concrete model to use for this scanner.
     *
     * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
     * * `gemini-3-flash-preview` - Gemini 3 Flash
     * * `gemini-3.8-flash` - Gemini 3.8 Flash */
    model: ScannerModelEnumApi
    /** When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work. */
    enabled?: boolean
    /** When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals. */
    emits_signals?: boolean
    /** The experiment this scanner's targeting watches, if any. Set null when the experiment targeting is removed. */
    experiment_targeting?: ScannerExperimentTargetingApi | null
    /** Increments on every config-changing save. Observations snapshot this value. */
    readonly scanner_version: number
    /**
     * Latest projected observations/month for this scanner. Null until first computed.
     * @nullable
     */
    readonly estimated_monthly_observations: number | null
    /**
     * When `estimated_monthly_observations` was last computed. Null means the estimate is being recomputed after a config change or has never run, so the stored number may be stale.
     * @nullable
     */
    readonly estimated_at: string | null
    /** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */
    readonly credits_per_observation: number
    /**
     * `estimated_monthly_observations` priced at `credits_per_observation`, capped at `credit_limit` when one is set. Null until the estimate is first computed.
     * @nullable
     */
    readonly estimated_monthly_credits: number | null
    /** Credits billed for this scanner's observations created in the current billing period (1 credit = $0.01), each at the price frozen when it succeeded. Deleted observations still count. */
    readonly credits_this_month: number
    /** Billed observations this scanner created in the current billing period, including deleted ones. */
    readonly observations_this_month: number
    /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. For a `free_only` scanner bound by the organization's free credits, this is the organization's usage, not the scanner's own. */
    readonly credits_used_against_limit: number
    /** True when the organization's free credits bind this `free_only` scanner rather than its own `credit_limit`. `credits_used_against_limit` is then the organization's usage, measured against its free credits. */
    readonly limit_from_free_credits: boolean
    /** Whether this scanner has stopped because of its own credit limit, or, for a `free_only` scanner, because the organization has used its free credits. True when the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set and `free_only` is false. */
    readonly limit_reached: boolean
    /** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */
    readonly sweep_throttle_factor: number
    /**
     * Dashboard created for this scanner with the create_dashboard action. Null when none was created or the user deleted it.
     * @nullable
     */
    readonly dashboard_id: number | null
    /** Whether to offer the user a dashboard for this scanner: true when the scanner has no dashboard and at least 20 succeeded observations to chart. Offer it once and do not repeat the offer if the user declines. */
    readonly dashboard_suggested: boolean
    /** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
    readonly last_swept_at: string
    /**
     * Why the scanner's recording filter cannot run, from the last sweep or estimate that tried it. Cleared when the filter changes or a sweep runs it.
     * @nullable
     */
    readonly filter_error: string | null
    /** Why the scanner can never run, or null when it can. `no_ai_consent`: the organization has not approved AI data processing. `creator_lost_access`: the creator can no longer view recordings, which the sweep reads as them, so turning the scanner on requires `take_over_as_creator`. The sweep turns an enabled scanner off when either applies. */
    readonly unrunnable_reason: UnrunnableReasonEnumApi | null
    readonly created_at: string
    /** User who created the scanner. */
    readonly created_by: UserBasicApi | null
    readonly updated_at: string
    /**
     * The effective access level the user has for this object
     * @nullable
     */
    readonly user_access_level: string | null
}

export interface PaginatedReplayScannerListApi {
    count: number
    /** @nullable */
    next?: string | null
    /** @nullable */
    previous?: string | null
    results: ReplayScannerApi[]
}

/**
 * A Replay Vision scanner: its type, targeting query, and AI configuration.
 */
export interface PatchedReplayScannerApi {
    readonly id?: string
    /**
     * Human-readable scanner name. Unique within the team.
     * @maxLength 255
     */
    name?: string
    /**
     * Free-form description shown in the scanner management UI.
     * @maxLength 1000
     */
    description?: string
    /**
     * Organizational tags for this scanner. Distinct from a classifier's categories in scanner_config. Tags cannot contain commas.
     * @maxItems 32
     * @items.maxLength 255
     */
    tags?: string[]
    /** What the scanner does: monitor, classifier, scorer, or summarizer.
     *
     * * `monitor` - Monitor
     * * `classifier` - Classifier
     * * `scorer` - Scorer
     * * `summarizer` - Summarizer
     * * `experiment` - Experiment */
    scanner_type?: ScannerTypeEnumApi
    /**
     * The goal an AI draft was built from, in the creator's own words, so the scanner keeps what it was meant to find. Set on create only and ignored on update.
     * @maxLength 2000
     * @nullable
     */
    goal?: string | null
    /** How the creator built this scanner: from an AI draft, from a template, or from scratch. Reported to product analytics at creation and not stored on the scanner. Independent of any experiment the creator is in, since a person offered the AI flow can still fill the form by hand. Only the app can answer this, so a request from anywhere else reports the calling surface instead of whatever it sends here. Ignored on update.
     *
     * * `ai` - AI draft
     * * `template` - Template
     * * `scratch` - From scratch */
    creation_method?: ScannerCreationMethodEnumApi | null
    /**
     * The app surface the creator started from, such as `replay_filters`. Reported to product analytics at creation so a scanner can be attributed to its entry point, and not stored on the scanner. Only the app's value is kept: any other caller is reported as its own source, such as `mcp`. Ignored on update.
     * @nullable
     * @pattern ^[a-z0-9_]{1,64}$
     */
    entry_point?: string | null
    /** Set with `enabled: true` to turn on a scanner whose creator can no longer view recordings. The caller becomes the scanner's creator, and scheduled scans then run as the caller. Without it, that request fails with code `scanner_creator_lost_access`. */
    take_over_as_creator?: boolean
    /** Type-specific configuration. All scanner types require `prompt`; monitors add optional `allow_inconclusive`, classifiers add `tags`, scorers add `scale`, summarizers add optional `length`. */
    scanner_config?: unknown
    /** The current prompt condensed by AI into the one question the scanner answers about a session. Falls back to the prompt's first line when no question matches the current prompt. */
    readonly prompt_question?: string
    /** Persisted `RecordingsQuery` shape used to pick candidate sessions. `date_from`/`date_to` are stripped on save — the schedule controls time, not the user. */
    query?: unknown
    /**
     * 0..1 random downsample applied after the query matches. Defaults to 1.0 (no downsampling). Use exactly 0 to pause scanning; non-zero rates below 0.0001 (0.01%) are rejected as below the sampling precision.
     * @minimum 0
     * @maximum 1
     */
    sampling_rate?: number
    /** Quality pre-filter applied before random sampling. focused = top sessions only, balanced = drops the lowest-quality, comprehensive = no filter (default).
     *
     * * `focused` - Focused
     * * `balanced` - Balanced
     * * `comprehensive` - Comprehensive */
    sampling_mode?: SamplingModeEnumApi
    /**
     * Optional cap on this scanner's own credit spend per billing period. Null means no scanner-level cap. When reached, this scanner stops scanning until the period resets. It stays enabled and does not scan the sessions it skipped.
     * @minimum 1
     * @maximum 2147483647
     * @nullable
     */
    credit_limit?: number | null
    /** Run only while the organization has free credits left this billing period, so the scanner never adds spend. */
    free_only?: boolean
    /** LLM provider. v1 is Google-only.
     *
     * * `google` - Google */
    provider?: ScannerProviderEnumApi
    /** Concrete model to use for this scanner.
     *
     * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
     * * `gemini-3-flash-preview` - Gemini 3 Flash
     * * `gemini-3.8-flash` - Gemini 3.8 Flash */
    model?: ScannerModelEnumApi
    /** When false, the reconciler removes the scanner's Temporal schedule. On-demand triggers still work. */
    enabled?: boolean
    /** When true, the prompt is augmented with the Signal side mission and the scanner emits PostHog Signals. */
    emits_signals?: boolean
    /** The experiment this scanner's targeting watches, if any. Set null when the experiment targeting is removed. */
    experiment_targeting?: ScannerExperimentTargetingApi | null
    /** Increments on every config-changing save. Observations snapshot this value. */
    readonly scanner_version?: number
    /**
     * Latest projected observations/month for this scanner. Null until first computed.
     * @nullable
     */
    readonly estimated_monthly_observations?: number | null
    /**
     * When `estimated_monthly_observations` was last computed. Null means the estimate is being recomputed after a config change or has never run, so the stored number may be stale.
     * @nullable
     */
    readonly estimated_at?: string | null
    /** Credits one observation by this scanner costs (1 credit = $0.01), derived from `model`. */
    readonly credits_per_observation?: number
    /**
     * `estimated_monthly_observations` priced at `credits_per_observation`, capped at `credit_limit` when one is set. Null until the estimate is first computed.
     * @nullable
     */
    readonly estimated_monthly_credits?: number | null
    /** Credits billed for this scanner's observations created in the current billing period (1 credit = $0.01), each at the price frozen when it succeeded. Deleted observations still count. */
    readonly credits_this_month?: number
    /** Billed observations this scanner created in the current billing period, including deleted ones. */
    readonly observations_this_month?: number
    /** Credits counted against `credit_limit` for the current billing period: settled receipts plus in-flight observations, priced from their frozen snapshot model. This is what the limit gate measures, so it includes work still in progress. It is not the same as `credits_this_month`, which counts only succeeded observations. For a `free_only` scanner bound by the organization's free credits, this is the organization's usage, not the scanner's own. */
    readonly credits_used_against_limit?: number
    /** True when the organization's free credits bind this `free_only` scanner rather than its own `credit_limit`. `credits_used_against_limit` is then the organization's usage, measured against its free credits. */
    readonly limit_from_free_credits?: boolean
    /** Whether this scanner has stopped because of its own credit limit, or, for a `free_only` scanner, because the organization has used its free credits. True when the budget left cannot cover one more observation, which is the same test the scanner's enforcement gates apply. Always false when no limit is set and `free_only` is false. */
    readonly limit_reached?: boolean
    /** How much the scheduled sweep is slowed to keep this scanner inside its daily ClickHouse read budget. 1 means it checks for new recordings on the normal schedule; N means it checks once every N schedule intervals. Expensive filters raise it. */
    readonly sweep_throttle_factor?: number
    /**
     * Dashboard created for this scanner with the create_dashboard action. Null when none was created or the user deleted it.
     * @nullable
     */
    readonly dashboard_id?: number | null
    /** Whether to offer the user a dashboard for this scanner: true when the scanner has no dashboard and at least 20 succeeded observations to chart. Offer it once and do not repeat the offer if the user declines. */
    readonly dashboard_suggested?: boolean
    /** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */
    readonly last_swept_at?: string
    /**
     * Why the scanner's recording filter cannot run, from the last sweep or estimate that tried it. Cleared when the filter changes or a sweep runs it.
     * @nullable
     */
    readonly filter_error?: string | null
    /** Why the scanner can never run, or null when it can. `no_ai_consent`: the organization has not approved AI data processing. `creator_lost_access`: the creator can no longer view recordings, which the sweep reads as them, so turning the scanner on requires `take_over_as_creator`. The sweep turns an enabled scanner off when either applies. */
    readonly unrunnable_reason?: UnrunnableReasonEnumApi | null
    readonly created_at?: string
    /** User who created the scanner. */
    readonly created_by?: UserBasicApi | null
    readonly updated_at?: string
    /**
     * The effective access level the user has for this object
     * @nullable
     */
    readonly user_access_level?: string | null
}

/**
 * * `yes` - Yes
 * * `no` - No
 * * `inconclusive` - Inconclusive
 */
export type ObservationVerdictEnumApi = (typeof ObservationVerdictEnumApi)[keyof typeof ObservationVerdictEnumApi]

export const ObservationVerdictEnumApi = {
    Yes: 'yes',
    No: 'no',
    Inconclusive: 'inconclusive',
} as const

/**
 * Body of POST /vision/scanners/:id/affected_cohort/. Same qualifiers as the impact GET.
 */
export interface AffectedCohortRequestApi {
    /**
     * Trailing window of observations to count. Defaults to 30 days.
     * @minimum 1
     * @maximum 90
     */
    window_days?: number
    /** Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.
     *
     * * `yes` - Yes
     * * `no` - No
     * * `inconclusive` - Inconclusive */
    verdict?: ObservationVerdictEnumApi | null
    /**
     * Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.
     * @maxLength 100
     * @nullable
     */
    tag?: string | null
    /**
     * Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.
     * @nullable
     */
    min_score?: number | null
    /**
     * Scorer scanners only: count sessions scoring at or below this value.
     * @nullable
     */
    max_score?: number | null
}

/**
 * The static cohort created from the scanner's affected users.
 */
export interface AffectedCohortResponseApi {
    /** ID of the created static cohort; usable anywhere cohorts are (funnels, surveys, experiments). */
    readonly cohort_id: number
    /** Generated cohort name, stamped with the creation date since the snapshot doesn't live-update. */
    readonly name: string
    /** Persons actually in the created cohort. Can be lower than `affected_users`: matched distinct IDs without a person profile are dropped, and merged persons deduplicate. */
    readonly users_in_cohort: number
    /** Trailing window the cohort was drawn from, in days. */
    readonly window_days: number
}

/**
 * Body of POST /vision/scanners/{id}/bulk_observe/.
 */
export interface BulkObserveRequestApi {
    /**
     * Session recording IDs to scan on demand, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch. Already-running sessions are a no-op.
     * @maxItems 200
     * @items.maxLength 128
     */
    session_ids: string[]
}

/**
 * Per-session outcome of a bulk scan trigger.
 */
export interface BulkObserveResultApi {
    /** The session recording this outcome is for. */
    session_id: string
    /** 'started' - a scan workflow was kicked off; 'already_running' - a scan for this session is already in flight (no-op, not recharged); 'already_scanned' - this scanner already has a finished observation for this session, so nothing was started and nothing was charged (read it back, or use the retry action to run it again); 'skipped_limit' - the in-flight cap was reached before this session; 'skipped_quota' - the org's credit quota for this period would be exceeded; 'skipped_scanner_limit' - this scanner's own credit limit would be exceeded; 'failed' - the workflow failed to start.
     *
     * * `started` - Started
     * * `already_running` - Already running
     * * `already_scanned` - Already scanned
     * * `skipped_limit` - Skipped, in-flight limit reached
     * * `skipped_quota` - Skipped, the org's credit quota for this period was reached
     * * `skipped_scanner_limit` - Skipped, scanner's own credit limit reached
     * * `failed` - Failed to start */
    scan_outcome: ScanOutcomeEnumApi
}

/**
 * Result of POST /vision/scanners/{id}/bulk_observe/ — partial success by design.
 */
export interface BulkObserveResponseApi {
    /** How many new scans were started. */
    started: number
    /** Per-session outcomes, in request order (deduplicated). */
    results: BulkObserveResultApi[]
}

export interface ScannerDashboardResponseApi {
    /** Id of the scanner's dashboard. */
    dashboard_id: number
    /** Name of the dashboard. */
    name: string
    /** True when this call created the dashboard. False when the scanner already had one, which is returned instead. */
    created: boolean
}

/**
 * Who this scanner's findings affected in the window; counted from observations, not estimated.
 */
export interface ScannerImpactApi {
    /** Distinct sessions with an affected observation in the window. For monitors only observations with the requested verdict count (yes by default); for other scanner types every succeeded observation counts. */
    readonly affected_sessions: number
    /** Distinct users behind the affected sessions, by distinct ID. May include anonymous device IDs when the recorded sessions were not identified. */
    readonly affected_users: number
    /** Affected sessions whose recording carried no distinct ID at all. */
    readonly sessions_without_user: number
    /** Trailing window the counts cover, in days. */
    readonly window_days: number
}

/**
 * Body of POST /vision/scanners/{id}/observe/.
 */
export interface ObserveRequestApi {
    /**
     * ID of the session recording to apply the scanner to.
     * @maxLength 128
     */
    session_id: string
}

/**
 * 200 from POST /vision/scanners/{id}/observe/ - nothing started, the answer already exists.
 */
export interface ObserveAlreadyScannedApi {
    /** The settled observation this scanner already has for the session. Nothing was started and nothing was charged; read it from /vision/scanners/{id}/observations/, or use the retry action on it to scan the session again. */
    observation_id: string
}

/**
 * Async-accepted response for POST /vision/scanners/{id}/observe/.
 */
export interface ObserveResponseApi {
    /** Temporal workflow id for this scanner application. Look up the resulting ReplayObservation via GET /vision/scanners/{id}/observations/?session_id=<session_id>. */
    workflow_id: string
}

export interface SelfDrivingReportApi {
    /** Signal report ID, for linking to it in the inbox. */
    id: string
    /**
     * Report title. Null until the report is summarized.
     * @nullable
     */
    title: string | null
    /** The report's inbox status. */
    status: string
}

export interface SelfDrivingPullRequestApi {
    /** URL of the implementation pull request. */
    url: string
    /** Whether the pull request has merged. */
    merged: boolean
}

/**
 * Response of GET /vision/scanners/:id/self_driving_stats/.
 */
export interface ScannerSelfDrivingStatsApi {
    /** Signals this scanner has pushed into the Signals inbox, all time. */
    signals_emitted: number
    /** Signal reports that include at least one of this scanner's signals. Reports usually aggregate signals from several sources, so this counts contributions, not sole causes. */
    reports_contributed: number
    /** Implementation PRs opened by self-driving on those reports. */
    prs_opened: number
    /** Of the opened PRs, how many have merged. */
    prs_merged: number
    /** The newest reports counted in `reports_contributed`, at most 20. */
    reports: SelfDrivingReportApi[]
    /** The newest PRs counted in `prs_opened`, at most 20. */
    pull_requests: SelfDrivingPullRequestApi[]
}

/**
 * * `running` - Running
 * * `paused_quota` - Paused (quota)
 * * `completed` - Completed
 * * `cancelled` - Cancelled
 */
export type BackfillStatusEnumApi = (typeof BackfillStatusEnumApi)[keyof typeof BackfillStatusEnumApi]

export const BackfillStatusEnumApi = {
    Running: 'running',
    PausedQuota: 'paused_quota',
    Completed: 'completed',
    Cancelled: 'cancelled',
} as const

export interface ReplayScannerBackfillApi {
    readonly id: string
    readonly status: BackfillStatusEnumApi
    /** Inclusive lower bound of the historical window to scan. */
    readonly window_start: string
    /** Exclusive upper bound of the window; clamped to now at creation. */
    readonly window_end: string
    /** Unobserved candidates enumerated at creation; the ceiling is total_count x credits_per_observation. */
    readonly total_count: number
    readonly dispatched_count: number
    /** Candidates the walk stepped over because this scanner had already tried them. Counted at creation but never dispatched, so progress and remaining spend both have to account for them. */
    readonly skipped_count: number
    /** Per-observation credit price frozen at creation from the snapshot model. */
    readonly credits_per_observation: number
    /** Observations from this backfill that succeeded. */
    readonly succeeded_count: number
    /** Observations from this backfill that failed. */
    readonly failed_count: number
    /** Sessions that turned out ineligible (too short, expired recording, ...). */
    readonly ineligible_count: number
    /** Observations from this backfill still pending or running. */
    readonly in_flight_count: number
    readonly created_by: UserBasicApi | null
    readonly created_at: string
    /**
     * When the backfill reached a terminal status (completed or cancelled).
     * @nullable
     */
    readonly finished_at: string | null
}

export interface PaginatedReplayScannerBackfillListApi {
    count: number
    /** @nullable */
    next?: string | null
    /** @nullable */
    previous?: string | null
    results: ReplayScannerBackfillApi[]
}

export interface BackfillCreateApi {
    /** Inclusive lower bound of the historical window to scan. */
    window_start: string
    /** Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date. */
    window_end: string
    /**
     * The most this backfill may cost, in credits (1 credit = $0.01): pass the `total_credits` from the estimate the person agreed to. The create is rejected if the window now costs more.
     * @minimum 0
     */
    max_total_credits: number
}

export interface BackfillWindowApi {
    /** Inclusive lower bound of the historical window to scan. */
    window_start: string
    /** Exclusive upper bound of the window; clamped server-side to now, and for an experiment scanner to the experiment's end date. */
    window_end: string
}

export interface BackfillEstimateResponseApi {
    /** Upper bound on the sessions the backfill would scan, after sampling and quality filters and excluding sessions this scanner already reported an observation for. */
    total_sessions: number
    /** Cost ceiling in credits (1 credit = $0.01): total_sessions x credits_per_observation. Actual spend lands under it: sessions already tried, expired recordings, and failures are not billed. */
    total_credits: number
    /** Per-observation credit price at the scanner's current model. */
    credits_per_observation: number
    /**
     * Credits left in the org's monthly quota; null when the org is uncapped.
     * @nullable
     */
    credits_remaining: number | null
    /** The window lower bound the estimate covered. */
    window_start: string
    /** The window upper bound after clamping to now and, for an experiment scanner, to the experiment's end date. */
    window_end: string
}

export interface ObservationStatusCountsApi {
    /** Total observations in the filtered set. */
    total: number
    /** Observations with `status=succeeded`. */
    succeeded: number
    /** Observations with `status=failed`. */
    failed: number
    /** Observations with `status=ineligible`. */
    ineligible: number
    /** Observations not yet in a terminal status. */
    in_flight: number
    /**
     * Percentage of (succeeded + failed) observations that succeeded; ineligible rows are excluded. Null when no observations have completed.
     * @nullable
     */
    success_rate: number | null
}

export interface CoverageStatsApi {
    /** Distinct sessions observed within the last `recent_days` days. */
    recent_sessions: number
    /** Distinct sessions observed overall. */
    total_sessions: number
    /** Window size in days used for `recent_sessions`. */
    recent_days: number
}

export interface ObservationLabelDayCountApi {
    /** Day (UTC) the observed sessions were scanned. */
    date: string
    /** Observations scanned this day labeled correct (thumbs up). */
    up: number
    /** Observations scanned this day labeled incorrect (thumbs down). */
    down: number
}

export interface ObservationVersionMarkerApi {
    /** First day (UTC) this prompt version produced observations. */
    date: string
    /** The scanner (prompt) version number. */
    version: number
    /** The prompt text this version ran with, taken from the observation run snapshots. */
    prompt: string
    /** The full type-specific config this version ran with (prompt plus, depending on scanner type, allow_inconclusive, tags, scale, or length), taken from the observation run snapshots. */
    scanner_config: unknown
    /**
     * The scanner type this version ran as.
     * @nullable
     */
    scanner_type: string | null
    /**
     * The model this version ran on.
     * @nullable
     */
    model: string | null
    /**
     * The provider this version ran on.
     * @nullable
     */
    provider: string | null
    /**
     * Whether this version emitted signals.
     * @nullable
     */
    emits_signals: boolean | null
    /** The `RecordingsQuery` recording filters this version ran with. */
    query: unknown
    /**
     * The 0..1 downsample this version ran with.
     * @nullable
     */
    sampling_rate: number | null
    /**
     * The session-coverage pre-filter this version ran with.
     * @nullable
     */
    sampling_mode: string | null
    /** Thumbs-up ratings on this version's observations. */
    up: number
    /** Thumbs-down ratings on this version's observations. */
    down: number
    /** Succeeded (ratable) observations this version produced, rated or not. */
    total: number
}

export interface ObservationLabelStatsApi {
    /** Observations in the filtered set labeled correct (thumbs up). */
    up_total: number
    /** Observations in the filtered set labeled incorrect (thumbs down). */
    down_total: number
    /** Daily label counts over the last `recent_days` days, bucketed by the day the session was scanned so the series tracks scanner quality over time. Days without labels are omitted. */
    by_day: ObservationLabelDayCountApi[]
    /** Daily label counts over the last `recent_days` days, bucketed by the day the rating was last set or changed: the team's rating activity. Days without rating changes are omitted. */
    by_rating_day: ObservationLabelDayCountApi[]
    /** Each scanner version that produced observations (all-time), with its first day, the config it ran with, and rating counts, for chart markers and the config version history. */
    version_markers: ObservationVersionMarkerApi[]
}

export interface MonitorStatsApi {
    /** Succeeded observations whose verdict was `yes`. */
    yes_total: number
    /** Succeeded observations whose verdict was `no`. */
    no_total: number
    /** Succeeded observations whose verdict was `inconclusive`. */
    inconclusive_total: number
}

export interface TagCountApi {
    /** The tag value. */
    tag: string
    /** Number of succeeded observations carrying this tag. */
    count: number
}

export interface ClassifierStatsApi {
    /** Top fixed-vocabulary tags by emission count. */
    fixed_ranked: TagCountApi[]
    /** Top freeform tags by emission count. */
    freeform_ranked: TagCountApi[]
    /** Succeeded observations that emitted at least one tag. */
    total_with_tags: number
}

export interface ScorerSummaryApi {
    /** Minimum observed score. */
    min: number
    /** 25th-percentile score. */
    p25: number
    /** Median score. */
    median: number
    /** Mean score. */
    mean: number
    /** 75th-percentile score. */
    p75: number
    /** Maximum observed score. */
    max: number
    /** Number of scored observations summarized. */
    count: number
}

export interface ScorerHistogramApi {
    /** Bucket labels (one per histogram bar) spanning the scanner's configured scale. */
    labels: string[]
    /** Observation count per bucket; same length as `labels`. */
    counts: number[]
}

export interface ScorerStatsApi {
    /** Score quantile summary; null when no observations have been scored. */
    summary: ScorerSummaryApi | null
    /** Score histogram; null when no observations have been scored. */
    histogram: ScorerHistogramApi | null
}

export interface ObservationStatsApi {
    /** Counts of observations by terminal status. */
    status_counts: ObservationStatusCountsApi
    /** Session-level scanner coverage. */
    coverage: CoverageStatsApi
    /** Team label (thumbs up/down) aggregates over the filtered set. */
    labels: ObservationLabelStatsApi
    /** All distinct tags (fixed + freeform) emitted by succeeded observations in the filtered set. */
    available_tags: string[]
    /** Monitor-type aggregates; null when the scanner is not a monitor. */
    monitor: MonitorStatsApi | null
    /** Classifier-type aggregates; null when the scanner is not a classifier. */
    classifier: ClassifierStatsApi | null
    /** Scorer-type aggregates; null when the scanner is not a scorer. */
    scorer: ScorerStatsApi | null
}

/**
 * * `small` - small
 * * `medium` - medium
 * * `large` - large
 */
export type SizeEnumApi = (typeof SizeEnumApi)[keyof typeof SizeEnumApi]

export const SizeEnumApi = {
    Small: 'small',
    Medium: 'medium',
    Large: 'large',
} as const

/**
 * One chart attached to a report — rendered in the inbox and referenceable from the summary.
 */
export interface ReportChartApi {
    /**
     * Stable slug for this chart within the report (lowercase letters, numbers, underscores, hyphens; must start with a letter or number). Reference it from `summary` as a markdown link with a `chart:` target — `[Daily signups](chart:signups-drop)` — to place the chart at that point in the body. A chart you don't reference still renders, below the summary.
     * @maxLength 100
     */
    chart_id: string
    /**
     * Short heading shown above the chart.
     * @maxLength 200
     */
    title: string
    /** The query node to render. `kind` must be `InsightVizNode` (an ad-hoc product analytics chart), `DataVisualizationNode` (a SQL series — a `HogQLQuery` source plus a `display`), or `SavedInsightNode` (an existing insight by `shortId`). Pin the window to absolute dates where the node supports it, so the reader sees the data you wrote about rather than whatever a relative range resolves to when they open the report. */
    query: unknown
    /**
     * Optional one-line note on what to look at in the chart.
     * @maxLength 500
     * @nullable
     */
    caption?: string | null
    /** How much height the chart gets: `small` for a single number or a short series, `medium` for an ordinary graph, `large` when there are rows or a grid to read (retention, paths, a wide breakdown). Leave it out unless the default looks wrong — the inbox sizes a chart from its query, and two charts referenced from the same paragraph sit side by side.
     *
     * * `small` - small
     * * `medium` - medium
     * * `large` - large */
    size?: SizeEnumApi | null
}

/**
 * One report a scanner's scout filed. Enough to read it in Replay Vision; the inbox owns the
 * full record (status, priority, reviewers, run trail).
 */
export interface ScoutReportApi {
    /** The report's id, as used by the Signals inbox. */
    report_id: string
    /** The scout that filed it, as its skill name. */
    skill_name: string
    /** When the run that filed this report started. Later edits do not move it. */
    filed_at: string
    /** The report's title. Empty when the scout left it unset. */
    title: string
    /** The report body, as markdown. Empty when the scout left it unset. */
    summary: string
    /** Charts the scout attached. The summary places one inline with a `[label](chart:<chart_id>)` link; any it does not place render after the body. */
    charts: ReportChartApi[]
}

/**
 * * `read_only` - Read only
 * * `support_notes` - Support notes
 */
export type ToolPresetEnumApi = (typeof ToolPresetEnumApi)[keyof typeof ToolPresetEnumApi]

export const ToolPresetEnumApi = {
    ReadOnly: 'read_only',
    SupportNotes: 'support_notes',
} as const

export interface SignalScoutSlackDestinationApi {
    /**
     * ID of the Slack integration whose bot posts this scout's findings and reports.
     * @minimum 1
     */
    integration_id: number
    /**
     * Slack channel target in the channel picker's `channel_id|#channel-name` format. Null while choosing a channel; no messages are sent until a channel or user is set.
     * @maxLength 255
     * @nullable
     */
    channel?: string | null
    /**
     * Slack members to send output to as direct messages, each in `member_id|@display-name` format (a bare member ID like `U0123ABC456` also works). Each member gets their own DM from the PostHog app; at most 5. Set either this or `channel`, not both. Useful for personal scouts where a DM beats a channel.
     * @minItems 1
     * @maxItems 5
     * @nullable
     * @items.maxLength 255
     * @items.pattern ^[UW][A-Z0-9]{4,}\s*(\|.*)?$
     */
    users?: string[] | null
    /** When true, post a report as a thread: a short lead in the channel and the rest split into replies at the summary's section labels, which can be Markdown headings or bold labels. Keeps a long summary from being clipped at Slack's section limit. On by default; set it false to post a single message, which can truncate a long summary. It does not change how findings post. */
    thread_reports?: boolean
}

export interface SignalScoutWebhookDestinationApi {
    /** Id of the CDP destination delivering this scout's reports. Set by the product that provisioned it, so it can find that destination again to update or remove it. */
    hog_function_id: string
}

export interface SignalScoutOutputDestinationsApi {
    /** Slack destination for each emitted scout finding or report. Null or omitted disables Slack delivery. */
    slack?: SignalScoutSlackDestinationApi | null
    /** The CDP destination another product provisioned for this scout's reports. Null or omitted means no webhook. Unlike Slack, Signals does not deliver this itself: the reference lives here so the owning product can manage the destination's lifecycle. */
    webhook?: SignalScoutWebhookDestinationApi | null
    /** Whether this scout's reports appear in the shared inbox. Defaults to true. Set false to keep the reports this scout authors out of the inbox and its Slack notifications, for example for a digest scout read in Slack. Reports this scout only edits are not affected. An update that omits this key keeps the stored value. */
    inbox?: boolean
}

/**
 * * `trusted` - Trusted domains only
 * * `full` - Full
 */
export type SignalScoutConfigNetworkAccessEnumApi =
    (typeof SignalScoutConfigNetworkAccessEnumApi)[keyof typeof SignalScoutConfigNetworkAccessEnumApi]

export const SignalScoutConfigNetworkAccessEnumApi = {
    Trusted: 'trusted',
    Full: 'full',
} as const

/**
 * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.
 * @nullable
 */
export type SignalScoutConfigOptionsApiStructuredOutputSchema = { [key: string]: unknown } | null

/**
 * Schedule, enablement, and delivery options accepted while creating a scout.
 */
export interface SignalScoutConfigOptionsApi {
    /**
     * Optional model id this scout's runs are pinned to, e.g. `claude-opus-4-5`. Must be one of the platform's agent models; an invalid id is rejected with the available ones listed. Null keeps the default model, chosen by the platform. Early access: the pin can only be set on projects enrolled in the scout model preview, and only takes effect there. Set null to clear it.
     * @maxLength 200
     * @nullable
     */
    model?: string | null
    /**
     * Free-form labels for grouping the fleet, e.g. `["revenue", "on-call"]`. Normalized to lowercase kebab-case (`On Call` and `on_call` both become `on-call`), deduped, and stored sorted; at most 10 tags, each at most 50 characters once normalized. Pass the full desired set — a write replaces the existing tags rather than merging into them. Filter the config list with the `tags` query parameter.
     * @maxItems 10
     */
    tags?: string[]
    /**
     * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.
     * @nullable
     */
    structured_output_schema?: SignalScoutConfigOptionsApiStructuredOutputSchema
    /**
     * MCP gateway servers (by id) this scout's runs may use, chosen from the connections members shared to the whole team. Selection is per scout: an empty list gives the scout no MCP servers. Applies from the scout's next run.
     * @maxItems 100
     */
    mcp_gateway_server_ids?: string[]
    /**
     * GitHub repositories this scout clones into its sandbox, each in `organization/repo` format. Set them for a scout that reads code, so it can search the tree and run the project's own tests instead of reading files one API call at a time. Empty (the default) leaves the sandbox without a checkout. The scout's GitHub access stays read-only either way, so a repository listed here is never writable from a run. At most 10, each reachable through the project's GitHub connection. Applies from the scout's next run.
     * @maxItems 10
     * @items.maxLength 255
     */
    repositories?: string[]
    /**
     * Write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `canvas:write`, `customer_task:write`, `dashboard:write`, `event_definition:write`, `experiment:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `notebook:write`, `replay_scanner:write`, `ticket:write`, `warehouse_table:write`, `warehouse_view:write`. A new scout starts with `notebook:write` when this field is omitted. Empty means the scout reads the project and writes only its findings and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. `ticket:write` lets the scout update tickets, manage saved views, and add private notes. Scouts cannot send public replies, compose emails, change existing notes, or change customer identity fields. Ticket changes can start workflows that message customers. `event_definition:write` lets the scout change the tags on event definitions and nothing else. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant, and a run that acts as a project member other than the author holds only the default scopes. Applies from the scout's next run.
     * @maxItems 15
     */
    write_scopes?: string[]
    /** Opt-in guard on this scout's lifecycle. Off by default, so anyone with scout write access may pause, resume, switch the scout to dry run, or delete it. On, only the person the scout's runs act as or a project admin may do any of those, or change this flag. Use it on a scout whose output people depend on: `signal_scout:write` is a project-wide scope held by people and by unattended agents alike, and a resume has to pass the project's enabled-scout maximum that a pause does not, so a bulk pause is not undone in one step. The lock never stops an automatic pause, such as the inactivity sweep or the repeated-failure breaker. */
    lifecycle_locked?: boolean
    /**
     * Exact MCP tool names selected for this scout, excluding its built-in run context tools. Null means no tool restriction; an empty list selects no additional tools. Write access is derived from selected write tools. Clearing to null preserves the last write scopes. Send this field or tool_preset, never both. Requires the scouts-tool-access feature flag.
     * @nullable
     */
    allowed_mcp_tools?: string[] | null
    /** Expand this named preset into a saved tool list. Later preset changes do not alter the saved list. Send this field or allowed_mcp_tools, never both. Requires the scouts-tool-access feature flag.
     *
     * * `read_only` - Read only
     * * `support_notes` - Support notes */
    tool_preset?: ToolPresetEnumApi
    /**
     * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. `{interval_minutes}` is the gap between two scheduled runs, so a backstop can follow the schedule: `{since} < {now} - toIntervalMinute(greatest(1440, 2 * {interval_minutes}))` runs at least daily and never more often than every two intervals. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank uses the default pre-check the scout's skill ships, if any. To turn every pre-check off, set `precheck_disabled`.
     * @maxLength 10000
     * @nullable
     */
    precheck_query?: string | null
    /** Whether this scout runs on its schedule. Defaults to true. */
    enabled?: boolean
    /** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. Defaults to true. */
    emit?: boolean
    /**
     * Minutes between runs (30–43200). Defaults to 1440 (every 24 hours).
     * @minimum 30
     * @maximum 43200
     */
    run_interval_minutes?: number
    /** Destinations that receive each finding or report this scout emits. Empty by default. */
    output_destinations?: SignalScoutOutputDestinationsApi
    /** What the scout's sandbox can reach over the network while it runs. Defaults to `trusted`, the platform's trusted-domain allowlist (PostHog, GitHub, common package registries). Set `full` to let this scout reach any site, for skills that read external sources such as documentation or papers.
     *
     * * `trusted` - Trusted domains only
     * * `full` - Full */
    network_access?: SignalScoutConfigNetworkAccessEnumApi
    /** Exempt this scout from the inactivity pause, which otherwise switches off a scout that goes a fortnight without surfacing anything anyone engages with. Set it on watchdog scouts whose value is staying quiet. Defaults to false. */
    auto_pause_exempt?: boolean
    /**
     * Optional five-field cron expression, e.g. '30 9 * * *' (daily at 09:30), '0 9,17 * * *' (twice daily), or '0 9 * * 1-5' (weekday mornings). Evaluated in the project timezone. Takes precedence over `run_interval_minutes`; occurrences must be at least 30 minutes apart.
     * @maxLength 100
     * @nullable
     */
    run_cron_schedule?: string | null
}

/**
 * * `variant-analysis` - Variant analysis
 * * `daily-digest` - Daily digest
 * * `root-cause` - Root cause
 * * `weekly-themes` - Weekly themes
 * * `trend-watch` - Trend watch
 * * `new-issues` - New issue watch
 * * `scratch` - Start from scratch
 */
export type ScoutTemplateKeyEnumApi = (typeof ScoutTemplateKeyEnumApi)[keyof typeof ScoutTemplateKeyEnumApi]

export const ScoutTemplateKeyEnumApi = {
    VariantAnalysis: 'variant-analysis',
    DailyDigest: 'daily-digest',
    RootCause: 'root-cause',
    WeeklyThemes: 'weekly-themes',
    TrendWatch: 'trend-watch',
    NewIssues: 'new-issues',
    Scratch: 'scratch',
} as const

/**
 * A scout to stand up for this scanner. The scanner comes from the URL, never the body: it is
 * what the caller's access is checked against, and what the scout is recorded as belonging to.
 *
 * Inherits the Signals scout definition so a scout created here clears the same name and prompt-size
 * bars as one created through the generic endpoint.
 */
export interface ScannerScoutCreateApi {
    /**
     * Name shown wherever people identify this scout, written however you want it — spaces, capitalization, and acronyms are kept as typed, and two scouts may share one. It does not change the scout's skill name, which stays its identity, so renaming a scout keeps its schedule, run history, notes, memory, and links. At most 200 characters; blank means the scout has no name of its own and is labelled from its skill name instead.
     * @maxLength 200
     */
    display_name?: string
    /**
     * Optional skill name for the scout — its permanent identifier, containing only lowercase letters, numbers, and hyphens. Omit it and one is generated from `display_name` (`My APM scout` becomes `my-apm-scout`), with a numeric suffix when that name is taken. Pass it to pick the identifier yourself, or to keep a client written before display names working unchanged. The `signals-scout-` prefix is optional.
     * @maxLength 64
     */
    name?: string
    /**
     * Short description of the signal or behavior this scout investigates.
     * @maxLength 1024
     */
    description: string
    /** Complete markdown prompt executed on every scout run. Include any project-specific signal names, thresholds, investigation steps, and report criteria here. */
    body: string
    /** Optional schedule, enablement, dry-run posture, and delivery settings. Defaults to an enabled, emitting scout on the daily interval with no external destination. */
    config?: SignalScoutConfigOptionsApi
    /** Make this the experiment scanner's variant analysis scout: its runs record a structured comparison of the variants, which the scanner's variants readout shows. Experiment scanners only. */
    variant_analysis?: boolean
    /** The template the body came from. A body left exactly as the template rendered it keeps following later edits to that template; an edited body stays as written.
     *
     * * `variant-analysis` - Variant analysis
     * * `daily-digest` - Daily digest
     * * `root-cause` - Root cause
     * * `weekly-themes` - Weekly themes
     * * `trend-watch` - Trend watch
     * * `new-issues` - New issue watch
     * * `scratch` - Start from scratch */
    template_key?: ScoutTemplateKeyEnumApi
}

/**
 * * `canonical` - canonical
 * * `custom` - custom
 */
export type ScoutOriginEnumApi = (typeof ScoutOriginEnumApi)[keyof typeof ScoutOriginEnumApi]

export const ScoutOriginEnumApi = {
    Canonical: 'canonical',
    Custom: 'custom',
} as const

export type ScoutRoleEnumApi = (typeof ScoutRoleEnumApi)[keyof typeof ScoutRoleEnumApi]

export const ScoutRoleEnumApi = {
    Specialist: 'specialist',
    Operational: 'operational',
} as const

/**
 * * `announced` - announced
 * * `retired` - retired
 */
export type ScoutDeprecationPhaseEnumApi =
    (typeof ScoutDeprecationPhaseEnumApi)[keyof typeof ScoutDeprecationPhaseEnumApi]

export const ScoutDeprecationPhaseEnumApi = {
    Announced: 'announced',
    Retired: 'retired',
} as const

/**
 * What PostHog has said about retiring this scout, for the chip and the banner to render.
 */
export interface ScoutDeprecationApi {
    /** How far the retirement has got: `announced` while the scout still runs, `retired` once its sunset has passed. A retired scout is paused and does not run again.
     *
     * * `announced` - announced
     * * `retired` - retired */
    phase: ScoutDeprecationPhaseEnumApi
    /** Why PostHog is retiring the scout, written to be shown to a person as-is. */
    reason: string
    /** Skill name of the scout that takes over, or blank when nothing replaces it. */
    superseded_by: string
    /**
     * When the scout stops running. Null means the next fleet reconcile retires it.
     * @nullable
     */
    sunset_at: string | null
}

/**
 * * `active` - Active
 * * `pending_pause` - Pending pause
 * * `paused_by_system` - Paused by system
 * * `paused_by_user` - Paused by user
 */
export type SignalScoutConfigStatusEnumApi =
    (typeof SignalScoutConfigStatusEnumApi)[keyof typeof SignalScoutConfigStatusEnumApi]

export const SignalScoutConfigStatusEnumApi = {
    Active: 'active',
    PendingPause: 'pending_pause',
    PausedBySystem: 'paused_by_system',
    PausedByUser: 'paused_by_user',
} as const

/**
 * * `no_output` - No output
 * * `ignored` - Ignored
 * * `repeated_failures` - Repeated failures
 * * `retired` - Retired
 * * `background_removed` - Background removed
 */
export type SignalScoutConfigPauseReasonEnumApi =
    (typeof SignalScoutConfigPauseReasonEnumApi)[keyof typeof SignalScoutConfigPauseReasonEnumApi]

export const SignalScoutConfigPauseReasonEnumApi = {
    NoOutput: 'no_output',
    Ignored: 'ignored',
    RepeatedFailures: 'repeated_failures',
    Retired: 'retired',
    BackgroundRemoved: 'background_removed',
} as const

/**
 * * `team` - Team
 * * `background` - Background
 */
export type SignalScoutConfigManagedByEnumApi =
    (typeof SignalScoutConfigManagedByEnumApi)[keyof typeof SignalScoutConfigManagedByEnumApi]

export const SignalScoutConfigManagedByEnumApi = {
    Team: 'team',
    Background: 'background',
} as const

export type ScoutPrecheckQuerySourceEnumApi =
    (typeof ScoutPrecheckQuerySourceEnumApi)[keyof typeof ScoutPrecheckQuerySourceEnumApi]

export const ScoutPrecheckQuerySourceEnumApi = {
    Config: 'config',
    SkillDefault: 'skill_default',
    Off: 'off',
} as const

/**
 * * `run` - Run
 * * `skip` - Skip
 * * `error` - Error
 */
export type SignalScoutConfigPrecheckOutcomeEnumApi =
    (typeof SignalScoutConfigPrecheckOutcomeEnumApi)[keyof typeof SignalScoutConfigPrecheckOutcomeEnumApi]

export const SignalScoutConfigPrecheckOutcomeEnumApi = {
    Run: 'run',
    Skip: 'skip',
    Error: 'error',
} as const

/**
 * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.
 * @nullable
 */
export type SignalScoutConfigApiStructuredOutputSchema = { [key: string]: unknown } | null

/**
 * Read shape for a per-(team, skill) scout config.
 *
 * One row per scout skill on the team. The coordinator auto-creates a row
 * when it discovers a scout skill; this serializer lets agents tune the row.
 */
export interface SignalScoutConfigApi {
    readonly id: string
    /** The skill this config controls as a scout. Set at creation, not editable. */
    readonly skill_name: string
    /** Human-readable summary of what this scout investigates, sourced from the scout skill's `description` metadata. Use it for a quick steer on the scout's focus without loading the full skill body. Empty if the skill is not currently present on the team or carries no description. */
    readonly description: string
    /**
     * Name shown in the UI. Does not change the skill name. Leave blank to use the default name.
     * @maxLength 200
     */
    display_name?: string
    /** Where this scout came from: `canonical` for a scout PostHog ships and maintains (seeded from `products/signals/skills/`), or `custom` for one a team hand-authored on this project. Use it to badge built-in vs custom scouts instead of a hardcoded name list. Defaults to `custom` if the skill is not currently present on the team. */
    readonly scout_origin: ScoutOriginEnumApi
    /** What this scout is to the harness: `specialist` for one that watches a product surface, or `operational` for one PostHog ships to watch the self-driving system itself. An operational scout is exempt from the inactivity sweep and from the enabled-scout cap, and is not a scout a project should delete. Always `specialist` for a custom scout. */
    readonly scout_role: ScoutRoleEnumApi
    /** Set when PostHog is retiring this scout, and null otherwise. Carries the phase, the reason to show, what replaces the scout, and when it stops running. Only a canonical scout the project has not edited is ever marked: a project's own copy keeps running and reads as null. */
    readonly deprecation: ScoutDeprecationApi | null
    /** Who answers for this scout, seed-creator first. Ownership is recorded on the scout's skill rather than on this config, so editing the skill or toggling the scout leaves it unchanged. Reports the scout files suggest these people as reviewers. Prefer this over `created_by`-style fields, which only say who last flipped a switch. Empty when nobody owns the scout, when the owners are no longer members with access to the project, or when the caller is a scout sandbox token: owners are member PII, and a scout reads them through the skill API instead. */
    readonly owners: readonly UserBasicApi[]
    /** Whether this scout runs on its schedule. Disabled scouts are skipped by the coordinator. Derived from `status`: true for `active` and `pending_pause`, false for the paused statuses. */
    readonly enabled: boolean
    /** Lifecycle status. `active`: runs on its schedule. `pending_pause`: still running, but flagged by the system to pause soon unless something changes (any config edit clears it). `paused_by_system`: paused automatically, see `pause_reason`; set `enabled=true` to resume. `paused_by_user`: switched off by a person and never resumed automatically.
     *
     * * `active` - Active
     * * `pending_pause` - Pending pause
     * * `paused_by_system` - Paused by system
     * * `paused_by_user` - Paused by user */
    readonly status: SignalScoutConfigStatusEnumApi
    /** Why the system paused (or warned) this scout: `no_output` (it emitted nothing over the evaluation window), `ignored` (no person engaged with its reports — no view, rating, note, dismissal, or resolution), `repeated_failures` (consecutive failed runs), `retired` (PostHog retired the scout), or `background_removed` (the background lane stopped managing the scout). Null unless `status` is `pending_pause` or `paused_by_system`.
     *
     * * `no_output` - No output
     * * `ignored` - Ignored
     * * `repeated_failures` - Repeated failures
     * * `retired` - Retired
     * * `background_removed` - Background removed */
    readonly pause_reason: SignalScoutConfigPauseReasonEnumApi | null
    /** Who controls this scout now. `team`: a person set it up or has changed it. `background`: PostHog runs it in the background and no person has edited it yet. Any edit through this API changes `background` to `team`.
     *
     * * `team` - Team
     * * `background` - Background */
    readonly managed_by: SignalScoutConfigManagedByEnumApi
    /** Whether the scout writes findings to the inbox. False = dry-run: it runs and logs but emits nothing. */
    readonly emit: boolean
    /**
     * Minutes between runs (30–43200). The scout runs once this interval has elapsed since its last run.
     * @minimum 30
     * @maximum 43200
     */
    readonly run_interval_minutes: number
    /**
     * Optional five-field cron expression evaluated in the project timezone, e.g. '30 9 * * *'. Takes precedence over `run_interval_minutes` when set. Null means the rolling interval schedule.
     * @nullable
     */
    readonly run_cron_schedule: string | null
    /** Destinations that receive each finding or report this scout emits. Empty when none is configured. */
    readonly output_destinations: SignalScoutOutputDestinationsApi
    /**
     * Optional JSON Schema (draft 2020-12) describing ONE structured record this scout produces via `scout-record-output` — e.g. a per-report quality judgment (`{"type": "object", "properties": {"verdict": {"enum": ["good", "bad", "unsure"]}, "reason": {"type": "string"}}, "required": ["verdict", "reason"]}`). The root must be `"type": "object"`. Setting a schema turns the structured-output channel on: the run prompt renders the schema and every submitted record is validated against it and recorded in the project as a `$scout_structured_output` event, queryable like any event. The channel also requires emit — a dry-run scout has nowhere to record to. Cardinality is the scout's call (one record per run, one per judged entity, ...). Null = channel off. Setting a schema requires skill-authoring authorization (the `llm_skill:write` scope and skill editor access) since the scout reads it verbatim in its prompt; clearing it needs only the config write. Records validate against the schema in force when the run was dispatched.
     * @nullable
     */
    readonly structured_output_schema: SignalScoutConfigApiStructuredOutputSchema
    /** What the scout's sandbox can reach over the network while it runs. `trusted` (the default) restricts runs to the platform's trusted-domain allowlist (PostHog, GitHub, common package registries). `full` lets the scout reach any site, for skills that read external sources such as documentation or papers.
     *
     * * `trusted` - Trusted domains only
     * * `full` - Full */
    readonly network_access: SignalScoutConfigNetworkAccessEnumApi
    /**
     * Optional model id this scout's runs are pinned to, e.g. `claude-opus-4-5`. Must be one of the platform's agent models; an invalid id is rejected with the available ones listed. Null keeps the default model, chosen by the platform. Early access: the pin can only be set on projects enrolled in the scout model preview, and only takes effect there. Set null to clear it.
     * @nullable
     */
    readonly model: string | null
    /**
     * MCP gateway servers (by id) this scout's runs may use, chosen from the connections members shared to the whole team. Selection is per scout: an empty list gives the scout no MCP servers. Applies from the scout's next run.
     * @maxItems 100
     */
    readonly mcp_gateway_server_ids: readonly string[]
    /**
     * GitHub repositories this scout clones into its sandbox, each in `organization/repo` format. Set them for a scout that reads code, so it can search the tree and run the project's own tests instead of reading files one API call at a time. Empty (the default) leaves the sandbox without a checkout. The scout's GitHub access stays read-only either way, so a repository listed here is never writable from a run. At most 10, each reachable through the project's GitHub connection. Applies from the scout's next run.
     * @maxItems 10
     * @items.maxLength 255
     */
    repositories?: string[]
    /**
     * Write access granted to this one scout, as scope strings. The grantable set is `alert:write`, `annotation:write`, `canvas:write`, `customer_task:write`, `dashboard:write`, `event_definition:write`, `experiment:write`, `hog_flow_proposal:write`, `insight:write`, `llm_skill:write`, `notebook:write`, `replay_scanner:write`, `ticket:write`, `warehouse_table:write`, `warehouse_view:write`. A new scout starts with `notebook:write` when this field is omitted. Empty means the scout reads the project and writes only its findings and its own memory. Each scope is project-wide and object-level, so a scout holding `dashboard:write` can update or delete any dashboard in the project, not only ones it made. `ticket:write` lets the scout update tickets, manage saved views, and add private notes. Scouts cannot send public replies, compose emails, change existing notes, or change customer identity fields. Ticket changes can start workflows that message customers. `event_definition:write` lets the scout change the tags on event definitions and nothing else. Grant only what this scout maintains. Only the person the scout's runs act as (whoever authored it) or a project admin can set it, and a scoped API key must itself carry each scope it grants. A dry run (`emit=false`) never holds the grant, and a run that acts as a project member other than the author holds only the default scopes. Applies from the scout's next run.
     * @maxItems 15
     */
    readonly write_scopes: readonly string[]
    /** Opt-in guard on this scout's lifecycle. Off by default, so anyone with scout write access may pause, resume, switch the scout to dry run, or delete it. On, only the person the scout's runs act as or a project admin may do any of those, or change this flag. Use it on a scout whose output people depend on: `signal_scout:write` is a project-wide scope held by people and by unattended agents alike, and a resume has to pass the project's enabled-scout maximum that a pause does not, so a bulk pause is not undone in one step. The lock never stops an automatic pause, such as the inactivity sweep or the repeated-failure breaker. */
    readonly lifecycle_locked: boolean
    /**
     * Exact MCP tool names selected for this scout, excluding its built-in run context tools. Null means no tool restriction; an empty list selects no additional tools. Write access is derived from selected write tools. Clearing to null preserves the last write scopes. Send this field or tool_preset, never both. Requires the scouts-tool-access feature flag.
     * @nullable
     */
    readonly allowed_mcp_tools: readonly string[] | null
    /**
     * Preset used to select the saved tool list, custom for an explicit list, or null when unrestricted.
     * @nullable
     */
    readonly tool_preset: string | null
    /**
     * Optional HogQL `SELECT` a scheduled run evaluates before it starts. When it returns no rows, or one row with one false value (`false`, `0`, null or empty), the run is skipped: no sandbox, no model call, and no run row. Any other result starts the run, and the scout reads the rows. A query error also starts the run. Use `{since}` (the start of the last run that ran, or when the scout was created) and `{now}` to look only at what is new, e.g. `SELECT count() FROM events WHERE event = '$exception' AND timestamp > {since}`. To run at least once a week however quiet it is, add `OR {since} < {now} - INTERVAL 7 DAY` to the condition. Only scheduled runs evaluate it: a manual or workflow run always starts. `{interval_minutes}` is the gap between two scheduled runs, so a backstop can follow the schedule: `{since} < {now} - toIntervalMinute(greatest(1440, 2 * {interval_minutes}))` runs at least daily and never more often than every two intervals. The query stops after 10 seconds and reads at most 50 rows. Try a query with `scout-config-precheck-test` before you save it. Null or blank uses the default pre-check the scout's skill ships, if any. To turn every pre-check off, set `precheck_disabled`.
     * @nullable
     */
    readonly precheck_query: string | null
    /** True turns off the pre-check, both `precheck_query` and the default the skill ships, so every scheduled run starts. False (the default) uses `precheck_query`, or the skill default when that is null. */
    readonly precheck_disabled: boolean
    /**
     * The pre-check query the next scheduled run uses: `precheck_query`, or the default the scout's skill ships. Null when no pre-check runs.
     * @nullable
     */
    readonly effective_precheck_query: string | null
    /** Where `effective_precheck_query` comes from: `config` (this scout's `precheck_query`), `skill_default` (the default its skill ships), or `off` (no pre-check runs). */
    readonly precheck_query_source: ScoutPrecheckQuerySourceEnumApi
    /**
     * When a scheduled run last evaluated this scout's pre-check. A skipped run writes no run row, so this stays recent while `last_run_at` ages. Null if no pre-check has run.
     * @nullable
     */
    readonly last_precheck_at: string | null
    /** The outcome of the latest scheduled pre-check: `run` (the query found something new), `skip` (nothing new, so the run did not start), or `error` (the query failed and the run started). Null if no pre-check has run.
     *
     * * `run` - Run
     * * `skip` - Skip
     * * `error` - Error */
    readonly last_precheck_outcome: SignalScoutConfigPrecheckOutcomeEnumApi | null
    /**
     * How many rows the latest scheduled pre-check returned, at most 50. Null if no pre-check has run.
     * @nullable
     */
    readonly last_precheck_row_count: number | null
    /**
     * When the coordinator last dispatched this scout. Null if it has never run.
     * @nullable
     */
    readonly last_run_at: string | null
    /** How many of this scout's runs have failed in a row. Back to 0 after a successful run or any config edit. At the failure limit the scout pauses itself (`status` becomes `paused_by_system` with `pause_reason` `repeated_failures`) and retries about once a day; a successful retry resumes it, and so does setting `enabled=true`. */
    readonly consecutive_failure_count: number
    /**
     * When `status` last changed. For `pending_pause` this is when the warning was issued (an `ignored` warning pauses about a week later unless someone engages with the scout's reports — opening one counts; a `no_output` warning only flags the scout); for the paused statuses it is when the scout was paused. Null if the status never changed.
     * @nullable
     */
    readonly status_changed_at: string | null
    /** Who last moved `status`, when a person did it through this API. Null for a system transition such as an automatic pause, for a row whose status never changed, and for a caller that may not read member identities. Pair it with `status` to say who turned a scout off, instead of only when it went off. */
    readonly status_changed_by: UserBasicApi | null
    /** Whether this scout is exempt from the inactivity sweep, meaning both the `ignored` pause and the `no_output` quiet warning. Set it on watchdog scouts whose value is staying quiet. Only ever set explicitly: re-enabling a swept scout instead grants a fresh grace window before the sweep may judge it again. */
    readonly auto_pause_exempt: boolean
    /** Free-form labels for grouping the fleet, e.g. `["revenue", "on-call"]`. Normalized to lowercase kebab-case (`On Call` and `on_call` both become `on-call`), deduped, and stored sorted; at most 10 tags, each at most 50 characters once normalized. Pass the full desired set — a write replaces the existing tags rather than merging into them. Filter the config list with the `tags` query parameter. */
    tags?: string[]
    /**
     * The product that stood this scout up for one of its own objects. Null when a person created it.
     * @nullable
     */
    readonly source_product: string | null
    /**
     * Id of the owning object in `source_product`, e.g. a Replay Vision scanner id.
     * @nullable
     */
    readonly source_id: string | null
    readonly created_at: string
    /** When this config last changed: an edit through this API, or a status change the system made such as an automatic pause. A scheduled run does not bump it — the coordinator stamps `last_run_at` with a direct write — so this reads as when the scout was last tuned rather than when it last ran. */
    readonly updated_at: string
}

/**
 * The scout that now watches this scanner.
 */
export interface ScannerScoutCreateResponseApi {
    /** False when a scout of this name already existed and the supplied config was applied to it. */
    created: boolean
    /** The scout's config, including the source recorded for it. */
    config: SignalScoutConfigApi
}

export interface ScannerScoutTemplateApi {
    /** The template's id.
     *
     * * `variant-analysis` - Variant analysis
     * * `daily-digest` - Daily digest
     * * `root-cause` - Root cause
     * * `weekly-themes` - Weekly themes
     * * `trend-watch` - Trend watch
     * * `new-issues` - New issue watch
     * * `scratch` - Start from scratch */
    key: ScoutTemplateKeyEnumApi
    /** The template's name, as the template picker shows it. */
    title: string
    /** What a scout made from this template does. */
    description: string
    /** The name the create form starts with. */
    default_name: string
    /** The default run schedule, as a cron expression in the project timezone. */
    cron: string
    /** The scout's instructions, rendered for this scanner. */
    body: string
}

export interface VariantsExperimentApi {
    /** The experiment's id. */
    id: number
    /** The experiment's name. */
    name: string
    /** draft, running, paused, exposure_frozen, or stopped. */
    status: string
    /**
     * When the experiment launched.
     * @nullable
     */
    start_date: string | null
    /**
     * When the experiment ended; null while it runs.
     * @nullable
     */
    end_date: string | null
    /**
     * The experiment's recommended running time in days, when one was set.
     * @nullable
     */
    planned_duration_days: number | null
    /**
     * The experiment's day number: 1 on its launch day, frozen once it ends. Null before launch.
     * @nullable
     */
    current_day: number | null
}

export interface VariantsWindowApi {
    /** Succeeded observations of this scanner, attributed to a variant or not. */
    total_observations: number
    /**
     * When the earliest of those observations completed.
     * @nullable
     */
    first_observation_at: string | null
    /**
     * When the latest of those observations completed.
     * @nullable
     */
    last_observation_at: string | null
}

export interface VariantAnalysisLineApi {
    /** A short label for the theme, shared across variants. */
    theme: string
    /** How the theme shows up for this variant. */
    statement: string
    /** How many of this variant's summaries the analysis read show the theme, as the scout counted them. */
    count: number
    /**
     * How many of this variant's summaries the theme was counted over, when that is fewer than the analysis read in total. Null when the theme was counted over every summary the analysis read.
     * @nullable
     */
    read: number | null
    /** Observations of this variant the scout cited for the theme. Ids it can't back are dropped. */
    example_observation_ids: string[]
}

export interface VariantReadoutApi {
    /** The variant key. */
    key: string
    /** Succeeded observations attributed to this variant. */
    observations: number
    /** Distinct people (by distinct id) behind those observations. */
    distinct_people: number
    /**
     * Median scanned session length in seconds; null with no observations.
     * @nullable
     */
    median_session_duration_s: number | null
    /**
     * The 0..1 rate this variant was sampled at when its latest observation was dispatched. Read even counts against it: balanced sampling gives a small variant a higher rate.
     * @nullable
     */
    sampling_rate: number | null
    /**
     * Summaries of this variant the analysis read: the denominator of its digest and difference counts. Null without a current analysis.
     * @nullable
     */
    analysis_observations: number | null
    /**
     * This variant's most notable themes from the variant analysis. Null without a current analysis.
     * @nullable
     */
    digest: VariantAnalysisLineApi[] | null
    /** This variant's most recent observations, newest first. */
    latest_observations: ReplayObservationApi[]
}

/**
 * Summaries the analysis read that show the theme, per variant key, as the scout counted them.
 */
export type VariantAnalysisDifferenceApiCounts = { [key: string]: number }

/**
 * Per variant key, how many summaries the theme was counted over, for a theme counted over fewer summaries than the analysis read in total. Empty when it was counted over all of them.
 */
export type VariantAnalysisDifferenceApiRead = { [key: string]: number }

export interface VariantAnalysisDifferenceApi {
    /** The theme the difference rests on. */
    theme: string
    /** What differs between the variants. */
    statement: string
    /** Summaries the analysis read that show the theme, per variant key, as the scout counted them. */
    counts: VariantAnalysisDifferenceApiCounts
    /** Per variant key, how many summaries the theme was counted over, for a theme counted over fewer summaries than the analysis read in total. Empty when it was counted over all of them. */
    read: VariantAnalysisDifferenceApiRead
}

export interface VariantsAnalysisStateApi {
    /** The variant analysis scout's config id. */
    scout_config_id: string
    /** Whether the scout runs on its schedule. */
    scout_enabled: boolean
    /**
     * When the run behind the newest analysis started; null before its first run.
     * @nullable
     */
    recorded_at: string | null
    /**
     * The scanner version the newest analysis covered.
     * @nullable
     */
    scanner_version: number | null
    /** Whether the newest analysis covers the scanner's current version. When false, digests and differences are null until the scout's next run. */
    current: boolean
}

export interface ExperimentVariantsReadoutApi {
    /** The watched experiment; null if it was deleted. */
    experiment: VariantsExperimentApi | null
    /** The span of observations the counts cover. */
    window: VariantsWindowApi
    /** One entry per watched variant, plus any variant still holding observations. */
    variants: VariantReadoutApi[]
    /**
     * What differs between variants, from the variant analysis. Null without a current analysis.
     * @nullable
     */
    differences: VariantAnalysisDifferenceApi[] | null
    /** Succeeded observations with no attributed variant. */
    unattributed_count: number
    /** The scanner's variant analysis scout and its newest run; null when none is set up. */
    analysis: VariantsAnalysisStateApi | null
}

/**
 * Distinct creators across all scanners on the team — feeds the `Created by` filter dropdown.
 */
export interface ScannerCreatorsResponseApi {
    /** Users who created at least one scanner on this team. Returned regardless of pagination state so the dropdown stays stable across pages. */
    creators: UserBasicApi[]
}

/**
 * Body of POST /vision/scanners/draft/ — the user's goal, stated in their own words.
 */
export interface DraftScannerRequestApi {
    /**
     * What the user wants to accomplish, e.g. 'find out where users get stuck during onboarding'.
     * @maxLength 2000
     */
    goal: string
    /**
     * Credits a month to spend (1 credit = $0.01). The draft picks the `model`, then solves `sampling_mode` and `sampling_rate` so the projected spend lands on this number, and sets `credit_limit` to it as a hard cap. Ask the person for it rather than guessing. Required unless `free_only` is true, and not allowed with it.
     * @minimum 1
     * @maximum 100000000
     */
    monthly_credit_budget?: number
    /** Draft a scanner that runs only on the organization's free monthly credits, so it never adds to the bill and pauses when they run out. The draft is sized to those free credits and comes back with `free_only` true and no `credit_limit`. Use instead of `monthly_credit_budget`. */
    free_only?: boolean
    /**
     * A launched experiment the person picked for the scanner to watch. The draft is then an `experiment` scanner on it.
     * @minimum 1
     * @maximum 2147483647
     */
    experiment_id?: number
    /** A `RecordingsQuery` the person already chose, as the replay list holds it. The draft starts from it and never removes or widens it. When the goal asks for narrower recordings, the draft can AND its own page, event, action or cohort filters onto it. It keeps them only when the combined filter still matches recent recordings, returns them in `query_additions`, and sizes the sampling dials against the combined `query`. `experiment_exposure` becomes the scanner's experiment and variants, which the draft keeps as they are. `date_from`/`date_to` are dropped, because a scanner's schedule owns time. `comment_text`, `hide_viewed_recordings` and in-session exposure are refused, because a scanner cannot apply them. A query with no filters starts from every new recording. Omit to let the draft pick the sessions. */
    query?: unknown
}

/**
 * An AI-drafted scanner configuration, ready to seed the creation wizard. Nothing is persisted.
 */
export interface DraftScannerResponseApi {
    /** Drafted scanner name. */
    name: string
    /** Drafted one-sentence description. */
    description: string
    /** The scanner type the draft picked for the goal.
     *
     * * `monitor` - Monitor
     * * `classifier` - Classifier
     * * `scorer` - Scorer
     * * `summarizer` - Summarizer
     * * `experiment` - Experiment */
    scanner_type: ScannerTypeEnumApi
    /** Type-specific config for the drafted `scanner_type`; always includes `prompt`. */
    scanner_config: unknown
    /** Why the draft picked this scanner type and configuration, addressed to the user. */
    rationale: string
    /** `RecordingsQuery` narrowing which sessions get scanned; null when the draft targets every session. */
    query: unknown
    /** When the request passed a `query`: the filters the draft ANDed onto it, which `query` already includes. Show them to the person as added by AI. Null when nothing was added or no `query` was passed. */
    query_additions: unknown
    /** The quality pre-filter the draft chose for the goal. Null when the costing estimate failed, in which case the wizard keeps its defaults.
     *
     * * `focused` - Focused
     * * `balanced` - Balanced
     * * `comprehensive` - Comprehensive */
    sampling_mode: SamplingModeEnumApi | null
    /**
     * The random sampling rate solved from `monthly_credit_budget`, 0..1. 1.0 when the budget covers every matching recording. Floored at the minimum rate, so a budget below that floor keeps the minimum. Null whenever `sampling_mode` is.
     * @nullable
     */
    sampling_rate: number | null
    /** The observation model the draft chose for the goal, by how much judgment it needs.
     *
     * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
     * * `gemini-3-flash-preview` - Gemini 3 Flash
     * * `gemini-3.8-flash` - Gemini 3.8 Flash */
    model: ScannerModelEnumApi | null
    /**
     * The monthly credit cap, set to `monthly_credit_budget` so a mis-estimate stops the scanner at the credits the user agreed to. Null for a free-only draft.
     * @nullable
     */
    credit_limit: number | null
    /** Whether the draft runs only on the organization's free monthly credits. Pass it on to create. */
    free_only: boolean
    /**
     * Recordings a month the drafted scanner is projected to watch under the solved dials. Its credit cost lands at or under `monthly_credit_budget`, except when the budget is below what the minimum sampling rate can reach, where this is the floor and exceeds the budget. Null whenever `sampling_mode` is.
     * @nullable
     */
    estimated_monthly_observations: number | null
}

export interface EstimateExperimentScopeApi {
    /**
     * The experiment an experiment scanner watches.
     * @minimum 1
     */
    experiment_id: number
    /**
     * The variant keys it watches. Null or omitted means every variant.
     * @minItems 1
     * @nullable
     * @items.maxLength 400
     */
    variants?: string[] | null
}

/**
 * Body of POST /vision/scanners/estimate/ — a proposed, unsaved scanner config.
 */
export interface EstimateRequestApi {
    /** Proposed `RecordingsQuery` for the candidate filter. `date_from`/`date_to` are ignored — the estimate scans a recent window (`window_days` in the response) and scales it to 30 days. Omit to estimate against all recordings. */
    query?: unknown
    /**
     * 0..1 downsample applied to matched sessions. Defaults to 1.0 (no downsampling).
     * @minimum 0
     * @maximum 1
     */
    sampling_rate?: number
    /** Quality pre-filter applied to the matched-session count, mirroring the sweep's candidate query. Defaults to comprehensive (no filter).
     *
     * * `focused` - Focused
     * * `balanced` - Balanced
     * * `comprehensive` - Comprehensive */
    sampling_mode?: SamplingModeEnumApi
    /**
     * The scanner being edited, excluded from `other_enabled_scanners_monthly_credits` so its stored estimate isn't double-counted in the forecast. Omit (or null) when estimating a brand-new scanner.
     * @nullable
     */
    scanner_id?: string | null
    /** Proposed model; determines `credits_per_observation` in the response.
     *
     * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
     * * `gemini-3-flash-preview` - Gemini 3 Flash
     * * `gemini-3.8-flash` - Gemini 3.8 Flash */
    model?: ScannerModelEnumApi
    /** Proposed experiment targeting, merged into the query as its exposure filter the same way a saved scanner derives it. The estimate then runs as the requesting user. */
    experiment_targeting?: ScannerExperimentTargetingApi | null
    /** For an experiment scanner: the `experiment_id` and `variants` it will keep in its config, merged into the query as its exposure filter so the estimate counts only exposed sessions. Not combined with `experiment_targeting`. */
    experiment?: EstimateExperimentScopeApi | null
}

/**
 * Forward-looking volume and credit-cost estimate for a proposed scanner.
 */
export interface EstimateResponseApi {
    /** Distinct sessions matching the query within the scanned window (`window_days`), after the sampling_mode quality filter but before random sampling. */
    matched_sessions_in_window: number
    /** Days of recordings the estimate scanned before scaling to 30. Up to a week (shorter when the query's operand rules out sampling); smaller when the team has fewer days of recordings. */
    window_days: number
    /** Projected monthly observations: quality-filtered matched sessions scaled from `window_days` to 30 days, times sampling_rate. */
    estimated_observations_per_month: number
    /** Credits one observation costs at the proposed `model` (1 credit = $0.01). */
    credits_per_observation: number
    /** `estimated_observations_per_month` priced at `credits_per_observation`. */
    estimated_credits_per_month: number
    /** Credit-weighted projected monthly spend of the org's other enabled scanners (excluding `scanner_id`), from their cached estimates. Read from the same snapshot as this estimate so the forecast can't double-count the edited scanner. */
    other_enabled_scanners_monthly_credits: number
    /** Committed-but-unspent credits of the org's active backfills, the same figure the quota snapshot's projection carries. A one-off charge rather than a monthly rate, so the forecast shows it as its own segment instead of adding it to a per-month total. */
    active_backfill_credits: number
    /** The monthly credit rate the organization's free credits still cover for one more free-only scanner, after the other free-only scanners and backfills. The forecast caps a free-only scanner at this rate, because free-only scanners share one pool. */
    free_only_monthly_credits_left: number
    /** Sampling rate applied to the projection. Echoed from the request. */
    sampling_rate: number
}

/**
 * * `embedding_pick` - Embedding Pick
 * * `unviewed_recent` - Unviewed Recent
 * * `recent` - Recent
 */
export type HighlightFeedReasonEnumApi = (typeof HighlightFeedReasonEnumApi)[keyof typeof HighlightFeedReasonEnumApi]

export const HighlightFeedReasonEnumApi = {
    EmbeddingPick: 'embedding_pick',
    UnviewedRecent: 'unviewed_recent',
    Recent: 'recent',
} as const

/**
 * * `failure` - Failure
 * * `struggle` - Struggle
 * * `revenue` - Revenue
 */
export type HighlightFeedCategoryEnumApi =
    (typeof HighlightFeedCategoryEnumApi)[keyof typeof HighlightFeedCategoryEnumApi]

export const HighlightFeedCategoryEnumApi = {
    Failure: 'failure',
    Struggle: 'struggle',
    Revenue: 'revenue',
} as const

/**
 * Machine-readable reason an observation made the feed; the frontend renders the copy.
 */
export interface HighlightFeedReasonApi {
    /** Why the observation is in the feed: `embedding_pick` (the session reads like a failure, struggle, or revenue moment and ranks in its scanner's top fifth), `unviewed_recent` (new to you), `recent` (nothing special, newest available).
     *
     * * `embedding_pick` - Embedding Pick
     * * `unviewed_recent` - Unviewed Recent
     * * `recent` - Recent */
    kind: HighlightFeedReasonEnumApi
    /** What the session reads like, for `embedding_pick`.
     *
     * * `failure` - Failure
     * * `struggle` - Struggle
     * * `revenue` - Revenue */
    watch_category?: HighlightFeedCategoryEnumApi
    /**
     * Other sessions from the same scanner in the window that describe nearly the same thing, for `embedding_pick`. The feed shows one session per group.
     * @nullable
     */
    similar_count?: number | null
    /**
     * Distinct people across the session's feed group in the window, for `embedding_pick`. A finding that reached more people ranks higher.
     * @nullable
     */
    affected_people?: number | null
}

/**
 * One feed entry: the observation plus why it ranked.
 */
export interface HighlightFeedItemApi {
    /** The observation, in the standard shape. */
    observation: ReplayObservationApi
    /** Why this observation made the feed. */
    reason: HighlightFeedReasonApi
}

/**
 * Response of GET /vision/scanners/highlight_feed/.
 */
export interface HighlightFeedResponseApi {
    /** Succeeded observations in the window worth watching, most interesting first, each carrying the reason it ranked. Every observation that carries a finding is returned; observations that carry none (`unviewed_recent`, `recent`) are returned only to pad a near-empty feed to three items, so a quiet window answers with a handful of rows rather than a full page of newest clips. */
    results: HighlightFeedItemApi[]
    /** Whether a later page holds more ranked items. Request it with `offset` set past this page. */
    has_more: boolean
    /** The time this feed ranks as of. Send it back with later pages. */
    as_of: string
}

/**
 * Body of POST /vision/scanners/highlight_feed_impressions/.
 */
export interface HighlightFeedImpressionsApi {
    /** The client's id for the feed load that showed these cards. One load counts each card once. */
    feed_load_id: string
    /**
     * Observations the calling user saw in the Highlights feed, at most 100. Ids the user cannot read are ignored.
     * @minItems 1
     * @maxItems 100
     */
    observation_ids: string[]
}

/**
 * Body of POST /vision/scanners/inline_scan/ - a prompt or built-in scan plus the sessions to point it at.
 */
export interface InlineScanRequestApi {
    /** Run a scan PostHog defines instead of your own prompt. `summarize_recording` is the AI summary the Summarize button in the replay player runs, so its results are shared with that button. Leave out `prompt`, `scanner_type` and `scanner_config` when this is set.
     *
     * * `summarize_recording` - Summarize recording */
    built_in?: BuiltInScanKeyEnumApi
    /**
     * What to look for in these sessions, in plain language. The same instruction a saved scanner carries. Required unless `built_in` is set.
     * @maxLength 20000
     */
    prompt?: string
    /** What the scan produces. Defaults to monitor, an open-ended observation against the prompt. Use `summarizer` for a summary in your own words; use `built_in: summarize_recording` for the Summarize button's summary. An inline scan is keyed by its whole config, so asking the same question again reuses its answers.
     *
     * * `monitor` - Monitor
     * * `classifier` - Classifier
     * * `scorer` - Scorer
     * * `summarizer` - Summarizer
     * * `experiment` - Experiment */
    scanner_type?: ScannerTypeEnumApi
    /** Type-specific configuration beyond the prompt: `tags` for a classifier, `scale` for a scorer, optional `length` for a summarizer. Omit it for a monitor. `prompt` belongs in the `prompt` field and is rejected here. */
    scanner_config?: unknown
    /** Model to scan with. Determines what each observation costs in credits.
     *
     * * `gemini-3.5-flash-lite` - Gemini 3.5 Flash Lite
     * * `gemini-3-flash-preview` - Gemini 3 Flash
     * * `gemini-3.8-flash` - Gemini 3.8 Flash */
    model?: ScannerModelEnumApi
    /**
     * Session recording IDs to scan, at most 200 per request. Scans start until the in-flight limit or monthly credit quota is reached; the rest are reported as skipped rather than failing the whole batch.
     * @maxItems 200
     * @items.maxLength 128
     */
    session_ids: string[]
}

/**
 * `bulk_observe`'s partial-success shape plus the id to read the results back through.
 */
export interface InlineScanResponseApi {
    /** How many new scans were started. */
    started: number
    /** Per-session outcomes, in request order (deduplicated). */
    results: BulkObserveResultApi[]
    /**
     * Read results from `/vision/scanners/{scan_id}/observations/`. Stable for a given prompt and model, so asking the same question again returns the same id. Null when nothing was started and nothing existed to read, which happens when the quota is already used up.
     * @nullable
     */
    scan_id: string | null
}

/**
 * Per-scanner-type count of enabled vs total scanners.
 */
export interface ScannerTypeStatsApi {
    /** Number of enabled scanners of this type. */
    enabled: number
    /** Number of scanners of this type (enabled + disabled). */
    total: number
}

/**
 * One `ScannerTypeStats` per scanner type — explicit fields give callers a typed shape, not `Record<string, …>`.
 */
export interface ScannerStatsByTypeApi {
    monitor: ScannerTypeStatsApi
    classifier: ScannerTypeStatsApi
    scorer: ScannerTypeStatsApi
    summarizer: ScannerTypeStatsApi
    experiment: ScannerTypeStatsApi
}

/**
 * Team-wide scanner counts independent of any list-filter state.
 */
export interface ScannerStatsResponseApi {
    /** Total scanners on the team. */
    total: number
    /** Number of enabled scanners on the team. */
    enabled: number
    /** Per-scanner-type breakdown (monitor / classifier / scorer / summarizer / experiment). */
    by_type: ScannerStatsByTypeApi
}

export type VisionAlertsListParams = {
    /**
     * Number of results to return per page.
     */
    limit?: number
    /**
     * The initial index from which to return the results.
     */
    offset?: number
    /**
     * Only return alerts on this scanner.
     */
    scanner_id?: string
}

export type VisionAlertsEventsListParams = {
    /**
     * Narrow the history to one event kind.
     */
    kind?: VisionAlertsEventsListKind
    /**
     * Number of results to return per page.
     */
    limit?: number
    /**
     * The initial index from which to return the results.
     */
    offset?: number
}

export type VisionAlertsEventsListKind = (typeof VisionAlertsEventsListKind)[keyof typeof VisionAlertsEventsListKind]

export const VisionAlertsEventsListKind = {
    Check: 'check',
    Disable: 'disable',
    Enable: 'enable',
    Reset: 'reset',
    Snooze: 'snooze',
    ThresholdChange: 'threshold_change',
    Unsnooze: 'unsnooze',
} as const

export type VisionGroupsListParams = {
    /**
     * Split each group's window counts by experiment variant in `variants`. Use it on experiment scanners.
     */
    by_variant?: boolean
    /**
     * Count members from this time: ISO 8601 or relative like `-7d`. Defaults to `-30d`. The window spans at most 90 days with `scanner_id`, and at most 30 days without it.
     * @minLength 1
     */
    date_from?: string
    /**
     * Count members up to this time: ISO 8601, relative, or `now`. Defaults to now.
     * @minLength 1
     */
    date_to?: string
    /**
     * Also count routine observations, so groups describe ordinary behavior and not only issues. Use it for experiment scanners, where the question is how each variant's users behave.
     */
    include_routine?: boolean
    /**
     * Page size.
     * @minimum 1
     * @maximum 100
     */
    limit?: number
    /**
     * Rows to skip, for the next page.
     * @minimum 0
     */
    offset?: number
    /**
     * `people` (distinct people affected), `observations` (member count), `growth` (members gained over the same-length window before `date_from`), or `recent` (newest member first).
     *
     * * `people` - People
     * * `observations` - Observations
     * * `growth` - Growth
     * * `recent` - Recent
     * @minLength 1
     */
    order?: VisionGroupsListOrder
    /**
     * Only this scanner's clusters. Defaults to every scanner you can read.
     */
    scanner_id?: string
    /**
     * Experiment scanners only: count only members attributed to these variant keys (comma-separated). `__unattributed__` matches members with no attributed variant.
     * @minLength 1
     */
    variant?: string
}

export type VisionGroupsListOrder = (typeof VisionGroupsListOrder)[keyof typeof VisionGroupsListOrder]

export const VisionGroupsListOrder = {
    People: 'people',
    Observations: 'observations',
    Growth: 'growth',
    Recent: 'recent',
} as const

export type VisionGroupsRetrieveParams = {
    /**
     * Split each group's window counts by experiment variant in `variants`. Use it on experiment scanners.
     */
    by_variant?: boolean
    /**
     * Count members from this time: ISO 8601 or relative like `-7d`. Defaults to `-30d`. The window spans at most 90 days with `scanner_id`, and at most 30 days without it.
     * @minLength 1
     */
    date_from?: string
    /**
     * Count members up to this time: ISO 8601, relative, or `now`. Defaults to now.
     * @minLength 1
     */
    date_to?: string
    /**
     * Also count routine observations, so groups describe ordinary behavior and not only issues. Use it for experiment scanners, where the question is how each variant's users behave.
     */
    include_routine?: boolean
    /**
     * Only this scanner's clusters. Defaults to every scanner you can read.
     */
    scanner_id?: string
    /**
     * Experiment scanners only: count only members attributed to these variant keys (comma-separated). `__unattributed__` matches members with no attributed variant.
     * @minLength 1
     */
    variant?: string
}

export type VisionObservationsListParams = {
    /**
     * Number of results to return per page.
     */
    limit?: number
    /**
     * The initial index from which to return the results.
     */
    offset?: number
    /**
     * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), result_confidence, scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
     */
    order_by?: string
    /**
     * Session recording id to return observations for.
     */
    session_id: string
}

export type VisionObservationsRetrieveParams = {
    /**
     * Only observations dispatched by this backfill.
     */
    backfill_id?: string
    /**
     * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.
     */
    date_from?: string
    /**
     * Only observations created at or before this time. Accepts ISO 8601, a relative date like `-1d`, or `now` for the current time; omit it to query through the current time. Date-only values include the whole day, interpreted in the project's timezone.
     */
    date_to?: string
    /**
     * Only issue observations in this group of near duplicates, an `id` from the groups list. Pair it with the same `date_from`, `date_to`, `include_routine` and `variant` to list the observations the group counted.
     */
    group?: string
    /**
     * With `group`, also list the group's routine observations, as the groups list does with the same flag.
     */
    include_routine?: boolean
    /**
     * When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.
     */
    labeled?: boolean
    /**
     * Filter scorer observations to those scoring at or below this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    max_score?: number
    /**
     * Filter scorer observations to those scoring at or above this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    min_score?: number
    /**
     * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), result_confidence, scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
     */
    order_by?: string
    /**
     * Filter to observations whose person email contains this value (case-insensitive).
     */
    recording_subject?: string
    /**
     * Filter to observations of one or more session recordings. Accepts a comma-separated list.
     */
    session_id?: string
    /**
     * Filter by observation status. Accepts a comma-separated list.
     */
    status?: string
    /**
     * Filter classifier observations whose fixed or freeform tags include any of the given values (comma-separated). Matches if the tag appears in either `tags` or `tags_freeform`.
     */
    tags?: string
    /**
     * Only issue observations in this search theme, an `id` from the themes list. Pair it with the same `date_from` and `date_to` to list the observations the theme counted.
     */
    theme?: string
    /**
     * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
     */
    triggered_by?: string
    /**
     * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
     */
    variant?: string
    /**
     * Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
     */
    verdict?: string
    /**
     * Only observations the watch feed ranks under any of these kinds (comma-separated: failure, struggle, revenue). Pair it with `watch_group` and the feed's `categories`.
     */
    watch_category?: string
    /**
     * Only observations the highlight feed groups with this observation as near duplicates, including itself. Pair it with the feed's `date_from` to list the sessions a feed card counts.
     */
    watch_group?: string
}

export type VisionObservationsThumbnailRetrieveParams = {
    /**
     * Index into the summary's `model_output.chapters`. Serves that chapter's frame instead of the observation's thumbnail.
     * @minimum 0
     */
    chapter?: number
    /**
     * `large` is up to 1280px wide, for detail views. `small` is up to 480px wide, for lists and grids. A frame rendered before small copies existed serves the large image for both.
     *
     * * `large` - Large
     * * `small` - Small
     * @minLength 1
     */
    size?: VisionObservationsThumbnailRetrieveSize
}

export type VisionObservationsThumbnailRetrieveSize =
    (typeof VisionObservationsThumbnailRetrieveSize)[keyof typeof VisionObservationsThumbnailRetrieveSize]

export const VisionObservationsThumbnailRetrieveSize = {
    Large: 'large',
    Small: 'small',
} as const

export type VisionObservationsSearchRetrieveParams = {
    /**
     * Only observations analyzed at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.
     * @minLength 1
     */
    date_from?: string
    /**
     * Only observations analyzed at or before this time. Accepts ISO 8601, a relative date like `-1d`, or `now` for the current time; omit it to query through the current time. Date-only values include the whole day, interpreted in the project's timezone.
     * @minLength 1
     */
    date_to?: string
    /**
     * Maximum number of results (default 20, at most 50).
     * @minimum 1
     * @maximum 50
     */
    limit?: number
    /**
     * Keep only scorer observations with a score at or below this value.
     */
    max_score?: number
    /**
     * Keep only scorer observations with a score at or above this value.
     */
    min_score?: number
    /**
     * Natural-language description of what to find, e.g. 'users confused by the pricing page'.
     * @minLength 1
     * @maxLength 2000
     */
    q: string
    /**
     * Search a single scanner's observations. Defaults to every scanner you can read.
     */
    scanner_id?: string
    /**
     * Comma-separated classifier tags to keep. Matching is case- and format-insensitive. Unlike `verdict`, tags are not validated against a fixed list, so an unknown tag matches nothing.
     * @minLength 1
     */
    tags?: string
    /**
     * Comma-separated monitor verdicts to keep, e.g. `yes,inconclusive`.
     * @minLength 1
     */
    verdict?: string
}

export type VisionObservationsSearchSuggestionsRetrieveParams = {
    /**
     * Scope to a single scanner's observations. Defaults to every scanner you can read.
     */
    scanner_id?: string
}

export type VisionScannersListParams = {
    /**
     * Filter to scanners created by the given user IDs (comma-separated).
     */
    created_by?: string
    /**
     * Filter to scanners that emit Signals.
     */
    emits_signals?: boolean
    /**
     * Filter by enabled state. Accepts `enabled`, `disabled`, a comma-separated list of both, or the boolean form `true`/`false`. Omit to list every scanner.
     */
    enabled?: string
    /**
     * Filter to scanners whose targeting watches the given experiment.
     */
    experiment_id?: string
    /**
     * Number of results to return per page.
     */
    limit?: number
    /**
     * The initial index from which to return the results.
     */
    offset?: number
    /**
     * Sort scanners by name, created_at, updated_at, scanner_type, enabled, sampling_rate, created_by, credits_this_month. Prefix with `-` for descending.
     */
    order_by?: string
    /**
     * Filter by scanner type (monitor, classifier, scorer, summarizer). Accepts a comma-separated list.
     */
    scanner_type?: string
    /**
     * Case-insensitive substring match across name, description, and the prompt in scanner_config.
     */
    search?: string
    /**
     * Filter to scanners carrying at least one of the given tags (comma-separated).
     */
    tags?: string
}

export type VisionScannersImpactRetrieveParams = {
    /**
     * Scorer scanners only: count sessions scoring at or below this value.
     * @nullable
     */
    max_score?: number | null
    /**
     * Scorer scanners only: count sessions scoring at or above this value. Scorers require `min_score` and/or `max_score`. Not applicable to other scanner types.
     * @nullable
     */
    min_score?: number | null
    /**
     * Classifier scanners only, required for them: count sessions carrying this tag (fixed or freeform). Not applicable to other scanner types.
     * @maxLength 100
     * @nullable
     */
    tag?: string | null
    /**
     * Monitor scanners only: count sessions with this verdict. Defaults to `yes`. Not applicable to other scanner types.
     *
     * * `yes` - Yes
     * * `no` - No
     * * `inconclusive` - Inconclusive
     * @nullable
     */
    verdict?: VisionScannersImpactRetrieveVerdict
    /**
     * Trailing window of observations to count. Defaults to 30 days.
     * @minimum 1
     * @maximum 90
     */
    window_days?: number
}

export type VisionScannersImpactRetrieveVerdict =
    | (typeof VisionScannersImpactRetrieveVerdict)[keyof typeof VisionScannersImpactRetrieveVerdict]
    | null

export const VisionScannersImpactRetrieveVerdict = {
    Yes: 'yes',
    No: 'no',
    Inconclusive: 'inconclusive',
} as const

export type VisionScannersBackfillsListParams = {
    /**
     * Number of results to return per page.
     */
    limit?: number
    /**
     * The initial index from which to return the results.
     */
    offset?: number
}

export type VisionScannersObservationsListParams = {
    /**
     * Only observations dispatched by this backfill.
     */
    backfill_id?: string
    /**
     * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.
     */
    date_from?: string
    /**
     * Only observations created at or before this time. Accepts ISO 8601, a relative date like `-1d`, or `now` for the current time; omit it to query through the current time. Date-only values include the whole day, interpreted in the project's timezone.
     */
    date_to?: string
    /**
     * Only issue observations in this group of near duplicates, an `id` from the groups list. Pair it with the same `date_from`, `date_to`, `include_routine` and `variant` to list the observations the group counted.
     */
    group?: string
    /**
     * With `group`, also list the group's routine observations, as the groups list does with the same flag.
     */
    include_routine?: boolean
    /**
     * When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.
     */
    labeled?: boolean
    /**
     * Number of results to return per page.
     */
    limit?: number
    /**
     * Filter scorer observations to those scoring at or below this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    max_score?: number
    /**
     * Filter scorer observations to those scoring at or above this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    min_score?: number
    /**
     * The initial index from which to return the results.
     */
    offset?: number
    /**
     * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), result_confidence, scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
     */
    order_by?: string
    /**
     * Filter to observations whose person email contains this value (case-insensitive).
     */
    recording_subject?: string
    /**
     * Filter to observations of one or more session recordings. Accepts a comma-separated list.
     */
    session_id?: string
    /**
     * Filter by observation status. Accepts a comma-separated list.
     */
    status?: string
    /**
     * Filter classifier observations whose fixed or freeform tags include any of the given values (comma-separated). Matches if the tag appears in either `tags` or `tags_freeform`.
     */
    tags?: string
    /**
     * Only issue observations in this search theme, an `id` from the themes list. Pair it with the same `date_from` and `date_to` to list the observations the theme counted.
     */
    theme?: string
    /**
     * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
     */
    triggered_by?: string
    /**
     * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
     */
    variant?: string
    /**
     * Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
     */
    verdict?: string
    /**
     * Only observations the watch feed ranks under any of these kinds (comma-separated: failure, struggle, revenue). Pair it with `watch_group` and the feed's `categories`.
     */
    watch_category?: string
    /**
     * Only observations the highlight feed groups with this observation as near duplicates, including itself. Pair it with the feed's `date_from` to list the sessions a feed card counts.
     */
    watch_group?: string
}

export type VisionScannersObservationsRetrieveParams = {
    /**
     * Only observations dispatched by this backfill.
     */
    backfill_id?: string
    /**
     * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.
     */
    date_from?: string
    /**
     * Only observations created at or before this time. Accepts ISO 8601, a relative date like `-1d`, or `now` for the current time; omit it to query through the current time. Date-only values include the whole day, interpreted in the project's timezone.
     */
    date_to?: string
    /**
     * Only issue observations in this group of near duplicates, an `id` from the groups list. Pair it with the same `date_from`, `date_to`, `include_routine` and `variant` to list the observations the group counted.
     */
    group?: string
    /**
     * With `group`, also list the group's routine observations, as the groups list does with the same flag.
     */
    include_routine?: boolean
    /**
     * When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.
     */
    labeled?: boolean
    /**
     * Filter scorer observations to those scoring at or below this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    max_score?: number
    /**
     * Filter scorer observations to those scoring at or above this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    min_score?: number
    /**
     * Sort observations. Plain keys: created_at, started_at, completed_at, status, recording_subject_email. JSONB keys: result_score (scorer), result_verdict (monitor), result_confidence, scanner_version. Prefix with `-` for descending; nullable keys sort nulls last either way.
     */
    order_by?: string
    /**
     * Filter to observations whose person email contains this value (case-insensitive).
     */
    recording_subject?: string
    /**
     * Filter to observations of one or more session recordings. Accepts a comma-separated list.
     */
    session_id?: string
    /**
     * Filter by observation status. Accepts a comma-separated list.
     */
    status?: string
    /**
     * Filter classifier observations whose fixed or freeform tags include any of the given values (comma-separated). Matches if the tag appears in either `tags` or `tags_freeform`.
     */
    tags?: string
    /**
     * Only issue observations in this search theme, an `id` from the themes list. Pair it with the same `date_from` and `date_to` to list the observations the theme counted.
     */
    theme?: string
    /**
     * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
     */
    triggered_by?: string
    /**
     * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
     */
    variant?: string
    /**
     * Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
     */
    verdict?: string
    /**
     * Only observations the watch feed ranks under any of these kinds (comma-separated: failure, struggle, revenue). Pair it with `watch_group` and the feed's `categories`.
     */
    watch_category?: string
    /**
     * Only observations the highlight feed groups with this observation as near duplicates, including itself. Pair it with the feed's `date_from` to list the sessions a feed card counts.
     */
    watch_group?: string
}

export type VisionScannersObservationsSignalReportsListParams = {
    /**
     * Only observations dispatched by this backfill.
     */
    backfill_id?: string
    /**
     * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.
     */
    date_from?: string
    /**
     * Only observations created at or before this time. Accepts ISO 8601, a relative date like `-1d`, or `now` for the current time; omit it to query through the current time. Date-only values include the whole day, interpreted in the project's timezone.
     */
    date_to?: string
    /**
     * Only issue observations in this group of near duplicates, an `id` from the groups list. Pair it with the same `date_from`, `date_to`, `include_routine` and `variant` to list the observations the group counted.
     */
    group?: string
    /**
     * With `group`, also list the group's routine observations, as the groups list does with the same flag.
     */
    include_routine?: boolean
    /**
     * When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.
     */
    labeled?: boolean
    /**
     * Filter scorer observations to those scoring at or below this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    max_score?: number
    /**
     * Filter scorer observations to those scoring at or above this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    min_score?: number
    /**
     * Sort observations by created_at, started_at, completed_at, status, recording_subject_email, result_score, result_verdict, result_confidence, or scanner_version. Prefix with `-` for descending. Keys that can be null (started_at, completed_at, recording_subject_email, result_*, scanner_version) sort nulls last regardless of direction.
     */
    order_by?: string
    /**
     * Filter to observations whose person email contains this value (case-insensitive).
     */
    recording_subject?: string
    /**
     * Filter to observations of one or more session recordings. Accepts a comma-separated list.
     */
    session_id?: string
    /**
     * Filter by observation status. Accepts a comma-separated list.
     */
    status?: string
    /**
     * Filter classifier observations whose fixed or freeform tags include any of the given values (comma-separated). Matches if the tag appears in either `tags` or `tags_freeform`.
     */
    tags?: string
    /**
     * Only issue observations in this search theme, an `id` from the themes list. Pair it with the same `date_from` and `date_to` to list the observations the theme counted.
     */
    theme?: string
    /**
     * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
     */
    triggered_by?: string
    /**
     * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
     */
    variant?: string
    /**
     * Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
     */
    verdict?: string
    /**
     * Only observations the watch feed ranks under any of these kinds (comma-separated: failure, struggle, revenue). Pair it with `watch_group` and the feed's `categories`.
     */
    watch_category?: string
    /**
     * Only observations the highlight feed groups with this observation as near duplicates, including itself. Pair it with the feed's `date_from` to list the sessions a feed card counts.
     */
    watch_group?: string
}

export type VisionScannersObservationsThumbnailRetrieveParams = {
    /**
     * Index into the summary's `model_output.chapters`. Serves that chapter's frame instead of the observation's thumbnail.
     * @minimum 0
     */
    chapter?: number
    /**
     * `large` is up to 1280px wide, for detail views. `small` is up to 480px wide, for lists and grids. A frame rendered before small copies existed serves the large image for both.
     *
     * * `large` - Large
     * * `small` - Small
     * @minLength 1
     */
    size?: VisionScannersObservationsThumbnailRetrieveSize
}

export type VisionScannersObservationsThumbnailRetrieveSize =
    (typeof VisionScannersObservationsThumbnailRetrieveSize)[keyof typeof VisionScannersObservationsThumbnailRetrieveSize]

export const VisionScannersObservationsThumbnailRetrieveSize = {
    Large: 'large',
    Small: 'small',
} as const

export type VisionScannersObservationsStatsRetrieveParams = {
    /**
     * Only observations dispatched by this backfill.
     */
    backfill_id?: string
    /**
     * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone.
     */
    date_from?: string
    /**
     * Only observations created at or before this time. Accepts ISO 8601, a relative date like `-1d`, or `now` for the current time; omit it to query through the current time. Date-only values include the whole day, interpreted in the project's timezone.
     */
    date_to?: string
    /**
     * Only issue observations in this group of near duplicates, an `id` from the groups list. Pair it with the same `date_from`, `date_to`, `include_routine` and `variant` to list the observations the group counted.
     */
    group?: string
    /**
     * With `group`, also list the group's routine observations, as the groups list does with the same flag.
     */
    include_routine?: boolean
    /**
     * When true, return only observations that have a shared label (thumbs up or down); when false, only unlabeled observations.
     */
    labeled?: boolean
    /**
     * Filter scorer observations to those scoring at or below this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    max_score?: number
    /**
     * Filter scorer observations to those scoring at or above this value. Rows with no numeric score (other scanner types, failed or in-flight runs) are excluded.
     */
    min_score?: number
    /**
     * Window size in days for the coverage `recent_sessions` count. Clamped to [1, 365]. Defaults to 14 when omitted.
     */
    recent_days?: number
    /**
     * Filter to observations whose person email contains this value (case-insensitive).
     */
    recording_subject?: string
    /**
     * Filter to observations of one or more session recordings. Accepts a comma-separated list.
     */
    session_id?: string
    /**
     * Filter by observation status. Accepts a comma-separated list.
     */
    status?: string
    /**
     * Filter classifier observations whose fixed or freeform tags include any of the given values (comma-separated). Matches if the tag appears in either `tags` or `tags_freeform`.
     */
    tags?: string
    /**
     * Only issue observations in this search theme, an `id` from the themes list. Pair it with the same `date_from` and `date_to` to list the observations the theme counted.
     */
    theme?: string
    /**
     * Filter by trigger source (schedule, on_demand, retry, or backfill). Accepts a comma-separated list.
     */
    triggered_by?: string
    /**
     * Experiment scanners only: filter to observations attributed to any of the given variant keys (comma-separated). `__unattributed__` matches observations with no attributed variant.
     */
    variant?: string
    /**
     * Filter monitor observations by verdict. Accepts a comma-separated list (e.g. `yes,inconclusive`).
     */
    verdict?: string
    /**
     * Only observations the watch feed ranks under any of these kinds (comma-separated: failure, struggle, revenue). Pair it with `watch_group` and the feed's `categories`.
     */
    watch_category?: string
    /**
     * Only observations the highlight feed groups with this observation as near duplicates, including itself. Pair it with the feed's `date_from` to list the sessions a feed card counts.
     */
    watch_group?: string
}

export type VisionScannersHighlightFeedRetrieveParams = {
    /**
     * The time the first page loaded. Later pages rank as of that time: observations, views, dismissals and impressions after it are ignored, so pages do not shift under a reader who scrolls.
     */
    as_of?: string
    /**
     * Comma-separated kinds of moment to include: `failure` (errors, failed requests, dead ends), `struggle` (repeated attempts, rage clicks, abandoned forms), `revenue` (failed payments, cancellations, usage limits). Defaults to all three. A pick keeps its rank within its scanner, so leaving a kind out drops its sessions without promoting weaker ones.
     * @minLength 1
     */
    categories?: string
    /**
     * Comma-separated user IDs. Restrict the feed to observations from scanners those users created.
     * @minLength 1
     */
    created_by?: string
    /**
     * Only observations created at or after this time. Accepts ISO 8601, a relative date like `-7d`, or `now`; values without an explicit offset are interpreted in the project's timezone. The window between `date_from` and `date_to` may span at most 90 days.
     * @minLength 1
     */
    date_from?: string
    /**
     * Only observations created at or before this time. Same formats as `date_from`; omit it to query through the current time.
     * @minLength 1
     */
    date_to?: string
    /**
     * Ceiling on feed items to return per page, at most 50. A page routinely returns fewer: a window is not padded to this number with clips that carry no finding.
     * @minimum 1
     * @maximum 50
     */
    limit?: number
    /**
     * How many ranked items to skip. Send `as_of` with every page after the first.
     * @minimum 0
     * @maximum 1000
     */
    offset?: number
    /**
     * Comma-separated scanner UUIDs to restrict the feed to. Defaults to every scanner you can read.
     * @minLength 1
     */
    scanner_ids?: string
    /**
     * Restrict the feed to observations from scanners of this type.
     *
     * * `monitor` - Monitor
     * * `classifier` - Classifier
     * * `scorer` - Scorer
     * * `summarizer` - Summarizer
     * * `experiment` - Experiment
     * @minLength 1
     */
    scanner_type?: VisionScannersHighlightFeedRetrieveScannerType
    /**
     * Comma-separated scanner tags to restrict the feed to. A team with many scanners uses these to follow one area without naming every scanner in it.
     * @minLength 1
     */
    tags?: string
}

export type VisionScannersHighlightFeedRetrieveScannerType =
    (typeof VisionScannersHighlightFeedRetrieveScannerType)[keyof typeof VisionScannersHighlightFeedRetrieveScannerType]

export const VisionScannersHighlightFeedRetrieveScannerType = {
    Monitor: 'monitor',
    Classifier: 'classifier',
    Scorer: 'scorer',
    Summarizer: 'summarizer',
    Experiment: 'experiment',
} as const

export type VisionThemesListParams = {
    /**
     * Count members from this time: ISO 8601 or relative like `-7d`. Defaults to `-30d`. The window spans at most 90 days with `scanner_id`, and at most 30 days without it.
     * @minLength 1
     */
    date_from?: string
    /**
     * Count members up to this time: ISO 8601, relative, or `now`. Defaults to now.
     * @minLength 1
     */
    date_to?: string
    /**
     * Page size.
     * @minimum 1
     * @maximum 100
     */
    limit?: number
    /**
     * Rows to skip, for the next page.
     * @minimum 0
     */
    offset?: number
    /**
     * `people` (distinct people affected), `observations` (member count), `growth` (members gained over the same-length window before `date_from`), or `recent` (newest member first).
     *
     * * `people` - People
     * * `observations` - Observations
     * * `growth` - Growth
     * * `recent` - Recent
     * @minLength 1
     */
    order?: VisionThemesListOrder
    /**
     * Only this scanner's clusters. Defaults to every scanner you can read.
     */
    scanner_id?: string
}

export type VisionThemesListOrder = (typeof VisionThemesListOrder)[keyof typeof VisionThemesListOrder]

export const VisionThemesListOrder = {
    People: 'people',
    Observations: 'observations',
    Growth: 'growth',
    Recent: 'recent',
} as const

export type VisionThemesRetrieveParams = {
    /**
     * Count members from this time: ISO 8601 or relative like `-7d`. Defaults to `-30d`. The window spans at most 90 days with `scanner_id`, and at most 30 days without it.
     * @minLength 1
     */
    date_from?: string
    /**
     * Count members up to this time: ISO 8601, relative, or `now`. Defaults to now.
     * @minLength 1
     */
    date_to?: string
    /**
     * Only this scanner's clusters. Defaults to every scanner you can read.
     */
    scanner_id?: string
}