import { EventCondition, InboundEventSummary, type BillingOrigin, type EventActor, type EventDelivery, type EventDeliveryStatus, type EventSourceKind, type EventSourceStatus, type EventSourceVisibility, type EventStatusReasonCode, type InboundEvent, type ParsedEventTriggerInput, type ScheduledTaskEvents, type ScheduledTaskRunEventOccurrence, type WebhookEventAdapter, WebhookFormat } from "@opengeni/contracts"; import { type Database } from "./database.js"; /** * Why a source or trigger is not active: the English sentence people and * agents read, a code (`EVENT_STATUS_REASON_CODES`) clients word in their own * language, and what the app or server said, when it said something. */ export type EventStatusReason = { text: string; code: EventStatusReasonCode; detail?: string | null; }; /** The Temporal workflow id, and so the run producer key, of an occurrence's run. */ export declare function eventOccurrenceProducerKey(occurrenceId: string): string; export type EventSourceRecord = { id: string; accountId: string; workspaceId: string; kind: EventSourceKind; adapter: WebhookEventAdapter | null; /** How a custom webhook reads its app's deliveries; null for every other source. */ format: WebhookFormat | null; name: string; ownerSubjectId: string | null; visibility: EventSourceVisibility; status: EventSourceStatus; statusReason: string | null; statusReasonCode: string | null; statusReasonDetail: string | null; secretEncrypted: string | null; /** * 'api' once an API caller set or received the webhook signing secret, or * named the URL a workspace MCP source listens to: every delivery verified * with it, or arriving on its subscriptions, is API use. Never turned back. */ secretBillingOrigin: "api" | null; externalKey: string | null; mcpServerId: string | null; /** A workspace MCP source's server URL, signed in by the credential provider. */ mcpServerUrl: string | null; connectionId: string | null; /** The webhook URL's route id; null for sources without a URL. */ routeId: string | null; lastDeliveryAt: Date | null; createdBySubjectId: string; createdAt: Date; updatedAt: Date; }; /** Whether a person (or, with null, a workspace-level caller) may see and use a source. */ export declare function eventSourceVisibleTo(source: Pick, subjectId: string | null): boolean; export type CreateEventSourceInput = { accountId: string; workspaceId: string; createdBySubjectId: string; kind: EventSourceKind; name: string; ownerSubjectId: string | null; visibility: EventSourceVisibility; adapter?: WebhookEventAdapter | null; format?: WebhookFormat | null; secretEncrypted?: string | null; /** 'api' when an API caller sets or receives the secret at creation. */ secretBillingOrigin?: "api" | null; /** Defaults to active; a pasted webhook waiting for its secret starts blocked. */ status?: EventSourceStatus; statusReason?: EventStatusReason | null; externalKey?: string | null; mcpServerId?: string | null; mcpServerUrl?: string | null; connectionId?: string | null; /** A GitHub source's routes are keyed with this (see githubInstallationRouteKey). */ routeSecret?: Uint8Array | null; }; /** * Create a source. Webhook sources are always new and get a routed URL. App, * MCP and "This workspace" sources are one per installation, mailbox, * connection or person: creating one that exists returns it unchanged * (`created: false`), except that a GitHub source's routes are recomputed * either way, which repairs lost ones. */ export declare function createEventSource(db: Database, input: CreateEventSourceInput): Promise<{ source: EventSourceRecord; created: boolean; }>; /** * Sources whose events Opengeni reads from the app's change history instead * of receiving them: each has a feed (migration 0935) the feed pump reads. * "This workspace" reads Opengeni's own recording events the same way. */ export declare function eventSourceKindHasFeed(kind: EventSourceKind): boolean; /** Have the feed pump read these sources' feeds now. */ export declare function wakeEventSourceFeeds(scoped: Database, workspaceId: string, sourceIds: readonly string[]): Promise; /** * The route key of one GitHub App installation's deliveries. * event_ingress_routes has no tenant RLS (intake finds the workspace through * it), so it never holds a provider identity: the key is an HMAC-SHA-256 of * the installation under the deployment's route secret. Equality lookups work * the same; the table alone tells nobody which installation a workspace uses. */ export declare function githubInstallationRouteKey(routeSecret: Uint8Array, installationId: number): string; /** * A workspace's GitHub source receives the deliveries of every GitHub App * installation bound to the workspace. Its routes are recomputed from the * bindings whenever a binding or the source changes, inside the writer's * workspace scope. Intake still checks each delivery's repository against the * workspace's current binding, so a route is only ever a candidate. Without a * route secret (a deployment with no encryption key) nothing can be routed, * so the source keeps no routes. */ export declare function syncGitHubEventRoutes(scoped: Database, workspaceId: string, routeSecret: Uint8Array | null): Promise; /** Sources a person can see: shared ones, workspace app sources and their own. */ export declare function listEventSources(db: Database, workspaceId: string, viewerSubjectId: string | null): Promise; /** One source, including its encrypted secret. Callers check visibility. */ export declare function getEventSource(db: Database, workspaceId: string, sourceId: string): Promise; /** A workspace's app source for one app identity (a Slack team), if it has one. */ export declare function findAppEventSource(db: Database, workspaceId: string, kind: "slack", externalKey: string): Promise; export declare function updateEventSource(db: Database, workspaceId: string, sourceId: string, patch: { name?: string; visibility?: EventSourceVisibility; status?: EventSourceStatus; statusReason?: EventStatusReason | null; secretEncrypted?: string; /** * 'api' with a secret an API caller sets or receives, written with the * secret in one statement. There is no way to clear it. */ secretBillingOrigin?: "api"; format?: WebhookFormat; }): Promise; /** * Delete a source and its history. A source automations still use is kept: * the result names them so the caller can say which to change first. */ export declare function deleteEventSource(db: Database, workspaceId: string, sourceId: string): Promise<{ kind: "deleted"; } | { kind: "missing"; } | { kind: "in_use"; taskIds: string[]; }>; /** Credential-free lookup of a webhook URL's route; the source row still authenticates. */ export declare function resolveEventIngressRoute(db: Database, routeId: string): Promise<{ accountId: string; workspaceId: string; sourceId: string; kind: EventSourceKind; } | null>; /** Every workspace GitHub source one GitHub App installation delivers to. */ export declare function listGitHubEventRoutes(db: Database, routeSecret: Uint8Array, installationId: number): Promise>; /** One normalized event, bounded to its columns. */ export type StoredEventInput = { externalId: string | null; streamKey: string; type: string; occurredAt: Date; subject: string | null; summary: string; url: string | null; actor: EventActor; data: Record; dataTruncated: boolean; gapBefore: boolean; /** * The chain depth of the automation run that caused the event, or 0 when * none did (every event from another app). Migration 1105. */ chainDepth?: number; }; /** The parts of a stored trigger a matcher reads. */ export type EventTriggerMatchInput = { eventTypes: readonly string[]; conditions: readonly EventCondition[]; includeOwnEvents: boolean; }; /** Decides whether an event fires a trigger; supplied by the caller (core matching). */ export type EventTriggerMatcher = (event: Pick, trigger: EventTriggerMatchInput) => boolean; export type RecordEventDeliveryInput = { accountId: string; workspaceId: string; sourceId: string; /** The MCP subscription stream the delivery arrived on; empty for other sources. */ streamKey?: string; status: EventDeliveryStatus; reason: string | null; /** The sender's delivery identity, or a digest of the body. */ dedupeKey: string; /** The verified raw body, kept for replay; null for rejected deliveries. */ body: Uint8Array | null; bodyBytes: number; bodySha256: string; headers: Record; events: StoredEventInput[]; replayOfDeliveryId?: string | null; match: EventTriggerMatcher; /** How long the dispatcher waits for more events before starting a run. */ settleMs?: number; /** * Who is behind this delivery: the caller of a test event or a replay, or * for a webhook, whoever holds its signing secret (see * `EventSourceRecord.secretBillingOrigin`). API marks the automations it * fires API use in this delivery's own transaction, before any of their * runs can start, so those runs never pay from plan credit. */ billingOrigin?: BillingOrigin; }; export type RecordEventDeliveryResult = { delivery: EventDelivery; /** The sender delivered this same delivery before; nothing new was stored. */ duplicate: boolean; /** Events stored now; events the source already delivered are skipped. */ eventIds: string[]; /** Automations that queued at least one of the events. */ matchedTaskIds: string[]; }; export declare const EVENT_DISPATCH_SETTLE_MS = 3000; /** * Store one delivery and its events, and queue matching events in their * automations' inboxes, all in one transaction. A repeated delivery (same * dedupe key) only counts the repeat. Events the source already delivered * (same external id on the same stream) are skipped. */ export declare function recordEventDelivery(db: Database, input: RecordEventDeliveryInput): Promise; /** * `recordEventDelivery` inside a caller's workspace-scoped transaction, so a * caller can commit its own state (an MCP subscription's cursor) atomically * with the delivery. */ export declare function recordEventDeliveryInTransaction(tx: Database, input: RecordEventDeliveryInput): Promise; /** A stored delivery with what a replay needs. */ export type EventDeliveryForReplay = { delivery: EventDelivery; body: Uint8Array | null; headers: Record; /** The MCP subscription stream it arrived on; empty for other sources. */ streamKey: string; }; export declare function getEventDeliveryForReplay(db: Database, workspaceId: string, sourceId: string, deliveryId: string): Promise; type Cursor = { at: Date; id: string; }; export declare function encodeEventCursor(at: Date, id: string): string; export declare function decodeEventCursor(cursor: string | null | undefined): Cursor | null; export declare function listEventDeliveries(db: Database, workspaceId: string, sourceId: string, options: { limit: number; cursor?: string | null; }): Promise<{ deliveries: EventDelivery[]; nextCursor: string | null; }>; /** Recent events of the given sources, newest first. */ export declare function listInboundEvents(db: Database, workspaceId: string, options: { sourceIds: string[]; limit: number; cursor?: string | null; }): Promise<{ events: InboundEvent[]; nextCursor: string | null; }>; /** The event types a source delivered recently, most frequent first. */ export declare function listRecentEventTypes(db: Database, workspaceId: string, sourceId: string, limit?: number): Promise>; /** Events by id, in the order asked; ids that expired or never existed are absent. */ export declare function getInboundEvents(db: Database, workspaceId: string, eventIds: string[]): Promise; /** The event triggers and event run policy of automations that have them. */ export declare function getScheduledTaskEvents(db: Database, workspaceId: string, taskIds: string[]): Promise>; /** * Replace an automation's event triggers and set its event run policy. A * trigger keeps its id while its position stays, so runs keep pointing at it. * No triggers removes the policy too; the automation is a plain schedule * again. `once` re-arms whenever it is set. MCP triggers carry the stream key * of their subscription, which is created here when missing. */ export declare function setScheduledTaskEvents(db: Database, input: { accountId: string; workspaceId: string; taskId: string; triggers: Array; maxRunsPerHour?: number | undefined; once?: boolean | undefined; }): Promise; /** * Create the MCP subscriptions an automation's triggers want and wake every * subscription and source feed it uses or used, so the pumps start, keep or * end each one now instead of at its next poll or refresh. The pumps decide * from the committed triggers and automation whether a subscription or feed * is still wanted, so this may run before a status change in the same * transaction. */ export declare function syncEventSubscriptions(tx: Database, workspaceId: string, taskId: string, previous?: ReadonlyArray<{ sourceId: string; streamKey: string; }>): Promise; /** A resumed automation starts over: `once` can fire again and the guard forgets the past episode. */ export declare function rearmScheduledTaskEvents(db: Database, workspaceId: string, taskId: string): Promise; /** * Have the pumps look at an automation's MCP streams and source feeds now, * after it was paused, resumed or deleted, so a stream nothing wants is ended * at once and a feed starts reading as soon as an automation listens again. */ export declare function wakeScheduledTaskEventSubscriptions(db: Database, workspaceId: string, taskId: string): Promise; /** An automation whose trigger changed state because its source or stream did. */ export type EventTriggerNotice = { taskId: string; taskName: string; /** The chat the owner opens from the notice; null when the automation never ran. */ sessionId: string | null; }; /** * Block (or unblock) every trigger listening on one stream of a source (the * empty stream key is every trigger of a source without streams), with a * plain-language reason. Returns the automations whose triggers changed state * now, so the owner is told once per episode. */ export declare function setEventStreamTriggerStatus(db: Database, workspaceId: string, stream: { sourceId: string; streamKey: string; }, status: "active" | "blocked", reason: EventStatusReason | null): Promise; /** Identity-only inventory of automations whose inbox is due; every read after it is workspace-scoped. */ export declare function listDueEventTriggerTasks(db: Database, limit?: number): Promise>; /** At most this many events are carried into one run; the rest are counted. */ export declare const EVENT_OCCURRENCE_CARRIED_EVENTS_MAX = 50; export type EventOccurrenceToStart = { id: string; accountId: string; workspaceId: string; taskId: string; startAttempts: number; }; export type EventThrottleNotice = { taskId: string; taskName: string; /** The chat the owner opens from the notice. */ sessionId: string; maxRunsPerHour: number; resumesAt: Date; }; export type EventTriggerDispatch = { /** Occurrences whose run should be started now (new, or earlier starts that failed). */ start: EventOccurrenceToStart[]; /** The storm guard engaged for this automation; tell its owner once. */ throttleNotice: EventThrottleNotice | null; /** The chain limit left events out; tell the owner once each time it engages. */ chainLimitNotice: EventChainLimitNotice | null; }; /** Default deepest chain of automations waking each other; see the design doc. */ export declare const EVENT_AUTOMATION_MAX_CHAIN_DEPTH = 3; /** Events left out of a run because it would have been deeper than the chain limit. */ export type EventChainLimitNotice = { taskId: string; taskName: string; /** The chat the owner opens from the notice. */ sessionId: string; maxChainDepth: number; limitedEvents: number; }; /** The producer key of the skipped run that records one engagement of the chain limit. */ export declare function eventChainLimitProducerKey(firstInboxId: string): string; /** * One dispatcher step for one automation, under its settings lock. Pending * inbox events become one occurrence unless the storm guard holds them back, * the automation is not runnable (they are skipped), or a once-automation has * already run (it completes instead). Events that would make the run deeper * than `maxChainDepth` are left out and skipped, with a skipped run receipt * (reason `chain_limit`). Occurrences whose start failed earlier are returned * again. A concurrent dispatcher holding the lock makes this a no-op. */ export declare function claimEventTriggerDispatch(db: Database, workspaceId: string, taskId: string, maxChainDepth?: number): Promise; export declare function markEventOccurrenceStarted(db: Database, workspaceId: string, occurrenceId: string): Promise; /** A failed start is retried by the dispatcher with a growing delay, up to ten minutes. */ export declare function recordEventOccurrenceStartFailure(db: Database, workspaceId: string, occurrenceId: string, error: string): Promise; /** The occurrence an event run carries, with full event data while the events are kept. */ export type EventOccurrenceForRun = { id: string; taskId: string; triggerIds: string[]; eventCount: number; gapBefore: boolean; summaries: InboundEventSummary[]; events: InboundEvent[]; }; export declare function getEventOccurrenceForRun(db: Database, workspaceId: string, occurrenceId: string): Promise; /** The occurrence id an event run's producer key names. */ export declare function eventOccurrenceIdFromProducerKey(producerKey: string | null | undefined): string | null; /** The occurrence an event run was started for, found through the run's producer key. */ export declare function getEventOccurrenceForScheduledTaskRun(db: Database, workspaceId: string, runId: string): Promise; /** The events each event run carried, keyed by run id. */ export declare function getScheduledTaskRunEventOccurrences(db: Database, workspaceId: string, runIds: string[]): Promise>; /** One event run's automation and the events it carried; null for any other run. */ export declare function getEventRunOccurrence(db: Database, workspaceId: string, runId: string): Promise<{ taskId: string; occurrence: ScheduledTaskRunEventOccurrence; } | null>; /** Retention: one bounded pass; returns how many rows changed so callers can repeat. */ export declare function pruneEventIntake(db: Database, input: { bodyRetentionSeconds: number; eventRetentionSeconds: number; limit?: number; }): Promise; export {};