import { type WorkspacePauseTimerRequest, type SessionMcpApprovalPolicy, type TurnInitiatorContext } from "@opengeni/contracts"; import type { Database, SessionActivityDatabase } from "./database.js"; import * as schema from "./schema.js"; export declare const SESSION_ANCESTRY_LIMIT = 10000; export type WorkspaceControlLockMode = "none" | "share" | "update"; export type EffectiveControlState = "active" | "paused"; export type SessionCommandActor = { type: "human" | "operator"; subjectId: string; } | { type: "service"; subjectId: string; subjectLabel?: string; context?: TurnInitiatorContext; } | { type: "agent_attempt"; attemptId: string; sessionId: string; turnId: string; executionGeneration: number; }; export type SessionTurnAttemptOutcome = "completed" | "failed" | "cancelled" | "superseded" | "requires_action" | "waiting_capacity" | "interrupted_recoverable" | "lease_lost_recoverable" | "pre_cutover_closed"; export type EffectiveControlBlocker = { kind: "session" | "workspace"; sessionId?: string; displayName: string; actor: string | null; reason: string | null; changedAt: Date | null; revision: number; }; export type EffectiveControlResumeOption = { scope: "selected" | "session" | "workspace"; targetId?: string; selectedStateAfter: EffectiveControlState; remainingPrimaryBlocker?: EffectiveControlBlocker; impactCopy: string; }; export type EffectiveSessionControl = { state: EffectiveControlState; controlVersion: number; controlEtag: string; directState: EffectiveControlState; primaryBlocker: EffectiveControlBlocker | null; additionalBlockerCount: number; blockers: EffectiveControlBlocker[]; resumeOptions: EffectiveControlResumeOption[]; override: { rootSessionId: string; revision: number; } | null; settlement: { state: "stopping"; attemptCount: number; interruptionPendingCount: number; quiescencePendingCount: number; } | null; backgroundCommandSettlement: { state: "stopping"; commandCount: number; } | null; }; /** * The bounded control projection required by a locked activity-write fence. * Settlement and background-command summaries are read-model concerns and must * not extend the session-event critical section when admission only needs the * effective run state and blocker scope. */ export type SessionWriteAdmissionControl = { state: EffectiveControlState; controlVersion: number; primaryBlockerKind: EffectiveControlBlocker["kind"] | null; }; export declare const SESSION_DISCOVERY_CONTROL_TITLE_MAX_CHARS = 200; export declare const SESSION_DISCOVERY_CONTROL_TARGET_LIMIT = 100; /** * Purpose-built control projection for session discovery. Full blocker evidence, * actors/reasons, resume options, etags, and settlement state remain available * from the ordinary session detail APIs; this shape is intentionally only what * `sessions_list` renders. */ export type SessionDiscoveryControl = { state: EffectiveControlState; primaryBlocker: { kind: "session" | "workspace"; sessionId?: string; displayName: string; displayNameOriginalChars: number; } | null; additionalBlockerCount: number; }; export declare function serializeEffectiveSessionControl(control: EffectiveSessionControl): { state: EffectiveControlState; controlVersion: number; controlEtag: string; directState: EffectiveControlState; additionalBlockerCount: number; override: { rootSessionId: string; revision: number; } | null; settlement: { state: "stopping"; attemptCount: number; interruptionPendingCount: number; quiescencePendingCount: number; } | null; backgroundCommandSettlement: { state: "stopping"; commandCount: number; } | null; primaryBlocker: (Omit & { changedAt: string | null; }) | null; blockers: (Omit & { changedAt: string | null; })[]; resumeOptions: { scope: "selected" | "session" | "workspace"; targetId?: string; selectedStateAfter: EffectiveControlState; impactCopy: string; remainingPrimaryBlocker?: Omit & { changedAt: string | null; }; }[]; }; export type WorkspaceControlRow = { workspaceId: string; accountId: string; revision: number | string; workspaceState: string; workspacePauseRevision: number | string | null; timerId: string | null; timerAction: string | null; timerDueAt: Date | string | null; timerPauseForSeconds: number | null; timerPauseRevision: number | string | null; reason: string | null; changedBy: string | null; changedAt: Date | string | null; }; export type SessionCommandReceiptRow = typeof schema.sessionCommandReceipts.$inferSelect; export declare class SessionControlInvariantError extends Error { readonly code = "SESSION_CONTROL_INVARIANT"; constructor(message: string); } /** * The session is not in its workspace: it never was, or a concurrent deletion * committed while the caller waited on the workspace-control lock. Callers * that only catch the invariant error still see one; an HTTP surface answers * 404 instead of a server error. */ export declare class SessionMissingFromWorkspaceError extends SessionControlInvariantError { readonly sessionId: string; constructor(sessionId: string); } export declare class SessionControlConflictError extends Error { readonly code = "CONTROL_CHANGED"; constructor(message?: string); } export declare class SessionCommandIdempotencyError extends Error { readonly code = "IDEMPOTENCY_KEY_REUSED"; constructor(); } export declare class AgentCommandAuthorityError extends Error { readonly code: "CALLER_STALE" | "CALLER_INTERRUPTED" | "TARGET_NOT_VERTICAL" | "SELF_STEER" | "PERSONAL_MACHINE_OWNER_REQUIRED"; constructor(code: "CALLER_STALE" | "CALLER_INTERRUPTED" | "TARGET_NOT_VERTICAL" | "SELF_STEER" | "PERSONAL_MACHINE_OWNER_REQUIRED", message: string); } export declare function assertAgentCommandAuthorityInTransaction(db: Database, input: { workspaceId: string; actor: Extract; targetSessionId: string; action: "pause" | "resume" | "steer" | "message" | "goal" | "wait" | "model_settings" | "context"; }): Promise; export declare function canonicalSessionCommandHash(value: unknown): string; /** * Default bounded control-prefix wait for request-scoped API mutations (Send, * Steer, queued Steer, Pause/Resume/Cancel, workspace Pause/Resume, realtime * sync). The bound is one budget across every lock step of the admission * (advisory lock, row lock, and the savepoint escalation of a paused branch), * not a per-statement timeout. A request that cannot enter the workspace * control prefix within the budget fails with the typed, retryable * `WorkspaceControlBusyError` before any write instead of holding a pooled * connection and a snapshot for as long as the HTTP client (or ingress) keeps * the socket open. Worker settlement, claims, and event appends never pass a * bound: a legitimate wait there must not become a failed settlement. * The deployment value is `OPENGENI_WORKSPACE_CONTROL_LOCK_TIMEOUT_MS`, parsed * and validated once at boot by `@opengeni/config` * (`settings.workspaceControlLockTimeoutMs`) and handed to this module through * `configureWorkspaceControlRequestLockTimeoutMs` when the API app is built. * This module never reads `process.env` per request. */ export declare const WORKSPACE_CONTROL_REQUEST_LOCK_TIMEOUT_MS = 20000; /** * Install the validated request-scoped budget for this process. The value is * process-global and last-writer-wins: the API calls this exactly once from * its settings at app composition (`createApp`), and every later * `workspaceControlRequestLockTimeoutMs()` read observes that value. Workers * never call it because they never pass a bound. A non-positive or * non-integer value is a programming error here (the config layer already * rejected it at boot). */ export declare function configureWorkspaceControlRequestLockTimeoutMs(lockTimeoutMs: number): void; /** The request-scoped budget in milliseconds currently configured for this process. */ export declare function workspaceControlRequestLockTimeoutMs(): number; export declare class WorkspaceControlBusyError extends Error { readonly workspaceId: string; readonly lockTimeoutMs: number; readonly code = "WORKSPACE_CONTROL_BUSY"; constructor(workspaceId: string, lockTimeoutMs: number); } /** * One wall-clock budget shared by every lock step of one control-prefix * acquisition. Each step sets `lock_timeout` to the remaining budget, so the * total wait never exceeds the requested bound even when the advisory lock, * the row lock, and a savepoint escalation each wait in turn. */ export type WorkspaceControlLockBudget = { readonly totalMs: number; readonly deadlineAt: number; }; export declare function workspaceControlLockBudget(lockTimeoutMs: number): WorkspaceControlLockBudget; export type WorkspaceControlLockOptions = { /** * Bound the whole prefix acquisition in milliseconds. Omit for * worker/lifecycle writers. The previous `lock_timeout` is restored once the * prefix is held. */ lockTimeoutMs?: number; /** Share an already running budget (used by the admission helper). */ budget?: WorkspaceControlLockBudget; }; /** Run one lock-acquiring statement under the remaining budget. */ export declare function boundedLockStep(db: Database, workspaceId: string, budget: WorkspaceControlLockBudget | null, step: () => Promise): Promise; /** * Lock the mandatory workspace inference-control row. * * `share` and `update` first take a transaction-scoped advisory lock on * `hashtextextended('workspace-control:', 0)` in the matching * mode and only then the row lock. The advisory lock is what makes the prefix * fair: PostgreSQL row locks let a new FOR SHARE requester join a share-locked * tuple without queueing behind an already waiting FOR UPDATE, so under * continuous share traffic (claims, settlement, appends across many sessions) * a genuine control mutation can starve indefinitely. Heavyweight locks have a * FIFO wait queue: a shared request conflicts with a waiting exclusive request * and queues behind it, so a mutator waits only for the holders that preceded * it, and sharers keep flowing between mutations. The row lock is retained * unchanged for FK/consistency semantics and for SQL-function writers that * lock the row directly (session-create triggers and capability functions). * * Invariant: a transaction that locks this row through any other path (a * SECURITY DEFINER function, a trigger, raw SQL) must already hold the prefix * through this helper or must never call this helper afterwards for the same * workspace. Requesting the advisory lock after holding the row lock can * deadlock against a mutator that holds the advisory lock and waits for the * row. Every current SQL-function locker either runs in its own transaction or * runs after this helper in the same transaction. */ export declare function lockWorkspaceInferenceControl(db: Database, workspaceId: string, mode: WorkspaceControlLockMode, options?: WorkspaceControlLockOptions): Promise; export type WorkspaceControlAdmissionLock = { control: WorkspaceControlRow; mode: "share" | "update"; }; /** * Lock the workspace control prefix for an admission. Callers that may resume * a paused branch request escalation; inert queue admission stays shared. * * The common case (the target branch is active) holds only `FOR SHARE`. That * still excludes every control mutation (Pause/Resume/Cancel, workspace * control, auto-resume all take `FOR UPDATE`), so the effective state observed * here cannot change for the rest of the transaction, while other Sends, * Steers, claims, and event appends on the workspace proceed concurrently. * * When the branch is paused the admission must advance the workspace control * revision, so it needs `FOR UPDATE`. Upgrading in place would deadlock as soon * as two sharers decide to upgrade together (each waits for the other's share * lock), so the shared prefix is taken inside a savepoint and rolled back * before the exclusive prefix is requested: PostgreSQL releases row locks and * transaction-level advisory locks acquired inside a rolled-back savepoint, so * the exclusive request queues normally behind other holders. * * Callers that already hold the prefix exclusively (for example a realtime * sync that admitted a delegation) simply observe their own stronger lock. */ export declare function lockWorkspaceInferenceControlForAdmission(db: Database, input: { workspaceId: string; sessionId: string; resumePausedBranch: boolean; } & WorkspaceControlLockOptions): Promise; export type SessionEventWriteLockInput = { workspaceId: string; /** * Control-aware writes take this lock first. Callers that already hold the * workspace control row (for example a Pause mutation under FOR UPDATE) say * `already_locked`; ordinary audit/title appends explicitly use `none`. */ controlLock: WorkspaceControlLockMode | "already_locked" | "none"; /** Used only when a staged caller already established the workspace prefix. */ workspaceLock?: "key_share" | "already_locked"; /** * Semantic writers retain FOR NO KEY UPDATE. Cursor-authoritative raw-only * appends need only the FK-compatible identity hold; KEY SHARE is compatible * with semantic NO KEY UPDATE and therefore removes the wide session row as * their serialization mutex without inverting the rolling lock order. */ sessionLock?: "no_key_update" | "key_share"; sessionIds?: string[]; turnIds?: string[]; attemptIds?: string[]; }; export type SessionEventWriteLocks = { control: WorkspaceControlRow | null; workspace: typeof schema.workspaces.$inferSelect | null; sessions: Array; cursors: Array; turns: Array; attempts: Array; }; type SessionEventWriteProjectionInput = SessionEventWriteLockInput & { /** Event-only appenders need identity, ownership and projection fields, not frozen inputs. */ rowProjection?: "full" | "event"; }; declare const eventWorkspaceColumns: { id: import("drizzle-orm/pg-core").PgColumn<{ name: "id"; tableName: "workspaces"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: true; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; accountId: import("drizzle-orm/pg-core").PgColumn<{ name: "account_id"; tableName: "workspaces"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }; declare const eventSessionColumns: { id: import("drizzle-orm/pg-core").PgColumn<{ name: "id"; tableName: "sessions"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: true; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; accountId: import("drizzle-orm/pg-core").PgColumn<{ name: "account_id"; tableName: "sessions"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; workspaceId: import("drizzle-orm/pg-core").PgColumn<{ name: "workspace_id"; tableName: "sessions"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; activeTurnId: import("drizzle-orm/pg-core").PgColumn<{ name: "active_turn_id"; tableName: "sessions"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; lastSequence: import("drizzle-orm/pg-core").PgColumn<{ name: "last_sequence"; tableName: "sessions"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; authorityEpoch: import("drizzle-orm/pg-core").PgColumn<{ name: "authority_epoch"; tableName: "sessions"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; executionAuthorityEpoch: import("drizzle-orm/pg-core").PgColumn<{ name: "execution_authority_epoch"; tableName: "sessions"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; visibility: import("drizzle-orm/pg-core").PgColumn<{ name: "visibility"; tableName: "sessions"; dataType: "string"; columnType: "PgText"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: [string, ...string[]]; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; ownerOrganizationMembershipId: import("drizzle-orm/pg-core").PgColumn<{ name: "owner_organization_membership_id"; tableName: "sessions"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; parentSessionId: import("drizzle-orm/pg-core").PgColumn<{ name: "parent_session_id"; tableName: "sessions"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; directControlState: import("drizzle-orm/pg-core").PgColumn<{ name: "direct_control_state"; tableName: "sessions"; dataType: "string"; columnType: "PgText"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: [string, ...string[]]; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; directPauseRevision: import("drizzle-orm/pg-core").PgColumn<{ name: "direct_pause_revision"; tableName: "sessions"; dataType: "number"; columnType: "PgBigInt53"; data: number; driverParam: string | number; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; subtreeRunOverrideRevision: import("drizzle-orm/pg-core").PgColumn<{ name: "subtree_run_override_revision"; tableName: "sessions"; dataType: "number"; columnType: "PgBigInt53"; data: number; driverParam: string | number; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; controlVersion: import("drizzle-orm/pg-core").PgColumn<{ name: "control_version"; tableName: "sessions"; dataType: "number"; columnType: "PgBigInt53"; data: number; driverParam: string | number; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }; declare const eventTurnColumns: { id: import("drizzle-orm/pg-core").PgColumn<{ name: "id"; tableName: "session_turns"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: true; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; accountId: import("drizzle-orm/pg-core").PgColumn<{ name: "account_id"; tableName: "session_turns"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; workspaceId: import("drizzle-orm/pg-core").PgColumn<{ name: "workspace_id"; tableName: "session_turns"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; sessionId: import("drizzle-orm/pg-core").PgColumn<{ name: "session_id"; tableName: "session_turns"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; executionGeneration: import("drizzle-orm/pg-core").PgColumn<{ name: "execution_generation"; tableName: "session_turns"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; activeAttemptId: import("drizzle-orm/pg-core").PgColumn<{ name: "active_attempt_id"; tableName: "session_turns"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; status: import("drizzle-orm/pg-core").PgColumn<{ name: "status"; tableName: "session_turns"; dataType: "string"; columnType: "PgText"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: [string, ...string[]]; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; metadata: import("drizzle-orm/pg-core").PgColumn<{ name: "metadata"; tableName: "session_turns"; dataType: "json"; columnType: "PgJsonb"; data: Record; driverParam: unknown; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, { $type: Record; }>; createdAt: import("drizzle-orm/pg-core").PgColumn<{ name: "created_at"; tableName: "session_turns"; dataType: "date"; columnType: "PgTimestamp"; data: Date; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; version: import("drizzle-orm/pg-core").PgColumn<{ name: "version"; tableName: "session_turns"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }; declare const eventAttemptColumns: { id: import("drizzle-orm/pg-core").PgColumn<{ name: "id"; tableName: "session_turn_attempts"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: true; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; accountId: import("drizzle-orm/pg-core").PgColumn<{ name: "account_id"; tableName: "session_turn_attempts"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; workspaceId: import("drizzle-orm/pg-core").PgColumn<{ name: "workspace_id"; tableName: "session_turn_attempts"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; sessionId: import("drizzle-orm/pg-core").PgColumn<{ name: "session_id"; tableName: "session_turn_attempts"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; turnId: import("drizzle-orm/pg-core").PgColumn<{ name: "turn_id"; tableName: "session_turn_attempts"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; executionGeneration: import("drizzle-orm/pg-core").PgColumn<{ name: "execution_generation"; tableName: "session_turn_attempts"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; state: import("drizzle-orm/pg-core").PgColumn<{ name: "state"; tableName: "session_turn_attempts"; dataType: "string"; columnType: "PgText"; data: string; driverParam: string; notNull: true; hasDefault: true; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: [string, ...string[]]; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; authorityEpoch: import("drizzle-orm/pg-core").PgColumn<{ name: "authority_epoch"; tableName: "session_turn_attempts"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; authorityVisibility: import("drizzle-orm/pg-core").PgColumn<{ name: "authority_visibility"; tableName: "session_turn_attempts"; dataType: "string"; columnType: "PgText"; data: string; driverParam: string; notNull: true; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: [string, ...string[]]; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; authorityOwnerOrganizationMembershipId: import("drizzle-orm/pg-core").PgColumn<{ name: "authority_owner_organization_membership_id"; tableName: "session_turn_attempts"; dataType: "string"; columnType: "PgUUID"; data: string; driverParam: string; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }; export type SessionEventWriteFenceLocks = { control: WorkspaceControlRow | null; workspace: Pick | null; sessions: Array>; cursors: SessionEventWriteLocks["cursors"]; turns: Array>; attempts: Array>; }; /** * Establish the one canonical lock prefix for every `session_events` writer: * * workspace-control advisory lock + workspace_inference_controls row * (when control-aware; see `lockWorkspaceInferenceControl`) * -> actual workspaces row FOR KEY SHARE * -> session rows FOR NO KEY UPDATE (semantic) or KEY SHARE (raw), UUID ordered * -> session event cursor rows FOR UPDATE, UUID ordered * -> exact turn rows FOR UPDATE, UUID ordered * -> exact attempt rows FOR UPDATE, UUID ordered * * Control-aware writers that do not mutate the control row take it `share`; * only genuine control mutations (Pause/Resume/Cancel, workspace control, * auto-resume, settings narrowing, quiescent tree deletion) take `update`. * Prompt admission declares whether it may resume a paused branch through * `lockWorkspaceInferenceControlForAdmission`. * * `FOR KEY SHARE` is deliberate. Event inserts need the workspace key to remain * stable for their FK, but they do not mutate the workspace. The old generic * `FOR UPDATE` lock serialized unrelated sessions and inverted the activity * path's session -> implicit workspace-FK edge. * * `FOR NO KEY UPDATE` is equally deliberate for semantic session writers. * Cursor-authoritative raw-only writers use `FOR KEY SHARE`: it preserves the * session identity against deletion while remaining compatible with semantic * `FOR NO KEY UPDATE`. Keeping this rolling session-before-cursor order avoids * an inversion with old binaries and quiescent cascade deletion; the compact * cursor row, not the wide session row, is the raw ordering mutex. * * Complex lifecycle transactions may acquire allocator/control locks before * this helper and may discover exact turn IDs only after locking the session. * They use the explicit `already_locked` stages, while retaining the same * monotonic table order. New event writers should prefer one complete call. * * Retained-screenshot and generated-image prepare are not event writers, but * their INSERTs KEY SHARE the turn and attempt through FKs. They take this prefix * first: PostgreSQL fires those FK checks in catalog name/OID order, which can * be attempt-then-turn and otherwise deadlocks against this helper. */ export declare function lockSessionEventWriteRows(db: Database, input: SessionEventWriteLockInput & { rowProjection: "event"; }): Promise; export declare function lockSessionEventWriteRows(db: Database, input: SessionEventWriteLockInput & { rowProjection?: "full"; }): Promise; export declare function lockSessionEventWriteRows(db: Database, input: SessionEventWriteProjectionInput): Promise; export declare function registerSessionTurnAttemptClaim(db: Database, input: { id: string; accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; temporalWorkflowId: string; temporalWorkflowRunId: string; temporalActivityId: string; verifiedControlRevision: number; authorityEpoch: number; authorityVisibility: "user_private" | "workspace_shared"; authorityOwnerOrganizationMembershipId: string | null; personalResourceProtocolVersion: number; mcpApprovalPolicies: Record; connectorActionPolicies: schema.ConnectorActionPolicySnapshotEntry[]; }): Promise; export type SessionAuthoritySnapshot = { authorityEpoch: number; authorityVisibility: "user_private" | "workspace_shared"; authorityOwnerOrganizationMembershipId: string | null; }; /** * Validate the complete accepted-attempt authority tuple. Missing or partial * values are not legacy defaults: current claim writers must provide the * exact locked session authority explicitly. */ export declare function assertSessionAuthoritySnapshot(input: { attemptId?: string; authorityEpoch: unknown; authorityVisibility: unknown; authorityOwnerOrganizationMembershipId: unknown; }): SessionAuthoritySnapshot; export declare function sessionAuthoritySnapshotMatchesSession(snapshot: SessionAuthoritySnapshot, session: Pick & { executionAuthorityEpoch?: number; }): boolean; export declare function sessionAuthoritySnapshotsEqual(left: Pick, right: Pick): boolean; /** * Close the exact first-class owner while the caller still holds the owning * session/turn locks. Every path that clears `session_turns.active_attempt_id` * must call this in the same transaction; otherwise a later claim would either * collide with a zombie live owner or have to weaken the ownership fence. */ export declare function closeSessionTurnAttemptInTransaction(db: Database, input: { id: string; accountId: string; workspaceId: string; sessionId: string; turnId: string; executionGeneration: number; outcome: SessionTurnAttemptOutcome; closedAt?: Date; }): Promise<{ action: "closed" | "already_closed"; }>; export declare function evaluateSessionControls(db: Database, workspaceId: string, sessionIds: string[], options?: { lock?: WorkspaceControlLockMode; /** Reuse a control row already locked before workspace/session/turn rows. */ workspaceControl?: WorkspaceControlRow | undefined; }): Promise>; /** * Evaluate only the control facts needed to admit an already locked session * write. The workspace-control row must be reused when the caller established * the canonical prefix before session/turn/attempt locks. * * Deliberately omit settlementAttemptCounts and * stoppingBackgroundCommandCounts: those recursive summaries do not affect * effective pause state and their results are discarded by the write fence. */ export declare function evaluateSessionWriteAdmissionControl(db: Database, workspaceId: string, sessionId: string, options?: { lock?: WorkspaceControlLockMode; workspaceControl?: WorkspaceControlRow | undefined; /** Same-transaction NO KEY UPDATE row; KEY SHARE is not sufficient. */ lockedSession?: Pick; }): Promise; /** * Return one compact aggregate row per target for `sessions_list`. * * Unlike `evaluateSessionControls`, the database boundary never returns a row * per blocker/ancestor, nor does application code construct blocker or resume * option arrays. The recursive walk carries no growing visited-path array: a * missing ancestor stops below the limit, while a cycle cannot reach a root and * therefore runs into the hard `SESSION_ANCESTRY_LIMIT`. The externally * supplied target set is capped by `SESSION_DISCOVERY_CONTROL_TARGET_LIMIT`. */ export declare function evaluateSessionDiscoveryControls(db: Database, workspaceId: string, sessionIds: string[]): Promise>; export declare function evaluateSessionControl(db: Database, workspaceId: string, sessionId: string, options?: { lock?: WorkspaceControlLockMode; workspaceControl?: WorkspaceControlRow | undefined; }): Promise; export type SessionPromptCommandAction = "prompt.send" | "prompt.steer"; /** * Prompt operation keys are actor-scoped across target sessions and across the * Send/Steer action pair. The advisory lock closes the gap left by the legacy * action/target-specific unique index without changing old receipt identities. */ export declare function reserveSessionPromptCommandReceipt(db: Database, input: { accountId: string; workspaceId: string; actor: SessionCommandActor; action: SessionPromptCommandAction; targetSessionId: string; operationKey: string; canonicalRequestHash: string; boundaryRequestHash: string; }): Promise<{ receipt: SessionCommandReceiptRow; replay: boolean; }>; /** Serialize one actor-scoped prompt operation before replay or reservation. */ export declare function lockSessionPromptCommandOperation(db: Database, input: { workspaceId: string; actor: SessionCommandActor; operationKey: string; }): Promise; /** Return only a fully committed exact prompt receipt with the new boundary fingerprint. */ export declare function getCompletedSessionPromptCommandReceipt(db: Database, input: { workspaceId: string; actor: SessionCommandActor; action: SessionPromptCommandAction; targetSessionId: string; operationKey: string; boundaryRequestHash: string; }): Promise; export declare function reserveSessionCommandReceipt(db: Database, input: { accountId: string; workspaceId: string; actor: SessionCommandActor; action: string; targetSessionId: string | null; targetTurnId: string | null; operationKey: string; canonicalRequestHash: string; identityScope?: "actor" | "target_operation"; initialResult?: Record; }): Promise<{ receipt: SessionCommandReceiptRow; replay: boolean; }>; /** Register one exact post-commit Temporal nudge without encoding eligibility in * the transport. The workflow re-reads canonical Postgres state; coalescing is * revisioned so a lost or stale delivery cannot hide a later mutation. */ export declare function registerSessionWorkflowWakeInTransaction(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; reason: string; controlRequested?: boolean; }): Promise; /** * Internal producers share one outstanding session-level receipt. While a wake * remains undelivered, another update makes that same batch richer instead of * manufacturing another transport revision or sequential model turn. * * Producers outside the workflow should signal after commit in both cases, so * `shouldSignal` is always `true`; the field stays for callers that read it. An * undelivered row is often a delayed wake that nothing signals before its time * (a `wait_for_input` deadline or goal idle backoff); pulling `next_attempt_at` * to now alone leaves the input waiting for the periodic dispatcher. The signal * is only a hint: the workflow re-reads PostgreSQL, one claim consumes the * whole pending batch, and the admission-aware acknowledgement keeps this * revision open until it does. Terminal background-command settlement returns * its committed wakes so each settlement caller signals them after commit; the * dispatcher delivers any a caller could not signal. */ export declare function registerInternalUpdateWakeInTransaction(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; }): Promise<{ wakeRevision: number; shouldSignal: true; }>; export declare function updateSessionCommandReceiptResult(db: Database, receiptId: string, input: { controlRevision?: number | null; queueVersion?: number | null; turnVersion?: number | null; draftRevision?: number | null; result: Record; }): Promise; export type SessionControlMutationResult = { receipt: SessionCommandReceiptRow; control: EffectiveSessionControl; sessionControlEventId: string | null; workspaceControlEventId: string | null; interruptionCount: number; backgroundCommandCount: number; wakeCount: number; cancelledSessionCount: number; cancelledTurnCount: number; affectedSessionEvents: Array<{ sessionId: string; eventIds: string[]; }>; workflowWake: SessionControlWorkflowWake | null; outcome: "changed" | "unchanged" | "replayed"; replay: boolean; }; export type SessionControlWorkflowWake = { accountId: string; workspaceId: string; sessionId: string; temporalWorkflowId: string; wakeRevision: number; }; /** * Whether a chat or anything it started still has work: a turn, a wait for * input, an active goal or a running background command. Archive cancels such * work when its undo window ends. */ export declare function sessionWorkstreamHasActiveWork(db: Database | SessionActivityDatabase, workspaceId: string, sessionId: string): Promise; export declare function mutateSessionControlInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; actor: SessionCommandActor; operationKey: string; action: "pause" | "resume" | "cancel"; reason?: string | null; expectedControlEtag?: string | null; /** Request-scoped callers bound the control prefix wait; lifecycle callers omit it. */ controlLockTimeoutMs?: number; }): Promise; export declare function autoResumeSessionBranchInTransaction(db: SessionActivityDatabase, input: { workspaceId: string; sessionId: string; actor: string; reason: "human_steer" | "service_steer" | "agent_steer"; observedControlEtag?: string | null; /** * The admission prefix the caller already holds. A `share` admission * proves the branch was active under a lock that excludes every control * mutation, so it never needs to resume; only an `update` admission may * advance the workspace revision here. */ admission?: WorkspaceControlAdmissionLock; }): Promise<{ revision: number; control: EffectiveSessionControl; changed: boolean; workspaceControlEventId: string | null; }>; export type WorkspaceControlMutationResult = { receipt: SessionCommandReceiptRow; revision: number; workspaceControlEventId: string | null; workspaceState: EffectiveControlState; interruptionCount: number; backgroundCommandCount: number; wakeCount: number; /** Session events the mutation appended (Pause releasing capacity waits), for live fanout. */ affectedSessionEvents: Array<{ sessionId: string; eventIds: string[]; }>; outcome: "changed" | "unchanged" | "replayed"; replay: boolean; }; export declare function mutateWorkspaceControlInTransaction(db: SessionActivityDatabase, input: { accountId: string; workspaceId: string; actor: SessionCommandActor; operationKey: string; action: "pause" | "resume"; reason?: string | null; /** Internal timer executor retains/replaces its own timer atomically. */ timerExecution?: boolean; expectedRevision?: number | null; /** Request-scoped callers bound the control prefix wait; lifecycle callers omit it. */ controlLockTimeoutMs?: number; }): Promise; export declare class WorkspacePauseTimerInputError extends Error { } /** Called under workspace RLS. The same control fence serializes timers and human actions. */ export declare function setWorkspacePauseTimerInTransaction(db: SessionActivityDatabase, input: WorkspacePauseTimerRequest & { accountId: string; workspaceId: string; subjectId: string; }): Promise<{ workspaceControlEventId: string | null; affectedSessionEvents: WorkspaceControlMutationResult["affectedSessionEvents"]; }>; /** Discovery is a hint. Identity, deadline and pause ownership are rechecked under the fence. */ export declare function fireWorkspacePauseTimerInTransaction(db: SessionActivityDatabase, input: { workspaceId: string; timerId: string; }): Promise | null>; export {};