/** * Opengeni Console data: managed workspaces, the organization's session review * level, the Console audit log, end-user labels, and the reviewable session * reads with their metered cost. * * Authorization lives in the API (`requireConsoleAccess` in * apps/api/src/routes/console-roles.ts): only the organization's owners, admins * and members with a Console role reach these reads. * This module enforces what they may see, in SQL, on every read: * * - only workspaces marked in `organization_managed_workspaces`; * - only root sessions that are shared, or private to an end user of the * product (`external_user:` owner). A private ("Only me") chat of an * Opengeni account is never selected, in any workspace; * - nothing at all when the review level is `off`, and no content (title, * messages, comments, events) when it is `metadata`. * * Reads run with no session RLS actor (as the system sees the tenant) under * the ordinary tenancy RLS of each workspace, and never write session data. */ import type { ConsoleAuditAction, ConsoleAuditEvent, ConsoleManagedSource, ConsoleReviewLevel, ConsoleSessionFeedback, ConsoleSessionSummary } from "@opengeni/contracts"; import { type SQL } from "drizzle-orm"; import { type Database } from "./database.js"; /** * The private-visibility predicate every Console session read uses. Site * conversations are excluded: a visitor's Site chat is theirs alone, even when * it is stored as workspace-shared. */ export declare const CONSOLE_REVIEWABLE_SESSION_SQL: (alias: string) => SQL; export declare const CONSOLE_MAX_WORKSPACE_READS = 2000; export type ConsoleManagedWorkspaceMarker = { workspaceId: string; source: ConsoleManagedSource; createdByApiKeyId: string | null; createdAt: string; }; export type ConsoleOrganizationWorkspace = { id: string; name: string; externalSource: string | null; externalId: string | null; createdAt: string; }; /** The organization's shared workspaces (never Personal ones), newest first, without projections. */ export declare function listConsoleOrganizationWorkspaces(db: Database, accountId: string): Promise; export declare function listManagedWorkspaceMarkers(db: Database, accountId: string): Promise>; export declare function isManagedWorkspace(db: Database, accountId: string, workspaceId: string): Promise; /** Mark a workspace an organization API key created. Never fails the caller's request. */ export declare function markWorkspaceManagedByApiKey(db: Database, input: { accountId: string; workspaceId: string; apiKeyId: string | null; }): Promise; /** Console: mark or unmark a shared workspace as managed by the product, with an audit row. */ export declare function setConsoleWorkspaceKind(db: Database, input: { accountId: string; workspaceId: string; kind: "managed" | "team"; actorSubjectId: string; actorLabel: string | null; }): Promise; export type ConsoleReviewSettingsRow = { reviewLevel: ConsoleReviewLevel; updatedAt: string | null; updatedBySubjectId: string | null; }; export declare function getConsoleReviewSettings(db: Database, accountId: string): Promise; export declare function setConsoleReviewLevel(db: Database, input: { accountId: string; reviewLevel: ConsoleReviewLevel; actorSubjectId: string; actorLabel: string | null; }): Promise; type AuditInput = { accountId: string; actorSubjectId: string; actorLabel: string | null; action: ConsoleAuditAction; workspaceId: string | null; sessionId: string | null; detail: Record; }; /** Writes one audit row in the caller's transaction (account context of the organization). */ export declare function insertConsoleAuditEvent(tx: Database, input: ConsoleAuditInput): Promise; export type ConsoleAuditInput = AuditInput; export declare function recordConsoleAuditEvent(db: Database, input: AuditInput): Promise; /** * Records a read unless the same reader already has the same entry for this * session within the last ten minutes (opening a transcript reads its detail, * then pages its events). */ export declare function recordConsoleAuditEventOnce(db: Database, input: AuditInput): Promise; export declare function encodeConsoleCursor(value: Record): string; export declare function decodeConsoleCursor(value: string, keys: readonly K[]): Record | null; export declare class ConsoleCursorError extends Error { } export declare function listConsoleAuditEvents(db: Database, input: { accountId: string; limit: number; cursor?: string; sessionId?: string; }): Promise<{ events: ConsoleAuditEvent[]; nextCursor: string | null; }>; /** * Remember the product's own id for an external user subject so Console can * show it, with the display name and email the product sent (the latest value * wins; an omitted field keeps its stored value). Display only; best effort, * never fails the caller. */ export declare function rememberEndUserLabel(db: Database, input: { accountId: string; subjectId: string; source: string; externalId: string; /** Already normalized (`normalizeEndUserProfile`). */ displayName?: string | undefined; email?: string | undefined; }): Promise; /** Forget what this process stored (tests). */ export declare function resetRememberedEndUserLabels(): void; export type ConsoleEndUserRow = { subjectId: string; externalId: string | null; source: string | null; displayName: string | null; email: string | null; }; /** * The product's id, display name and email of each given end user subject. * Runs in the caller's account context of the organization. */ export declare function readConsoleEndUsers(tx: Database, accountId: string, subjectIds: readonly string[]): Promise>; export type ConsoleWindow = { since: string; until: string; }; /** Spend per workspace (null: not tied to a workspace) in the window. */ export declare function consoleSpendByWorkspace(db: Database, accountId: string, window: ConsoleWindow): Promise>; /** Daily spend split by managed workspaces and the rest, plus the top models. */ export declare function consoleSpendBreakdown(db: Database, accountId: string, window: ConsoleWindow): Promise<{ byDay: { date: string; managed: boolean; spendMicros: number; }[]; byModel: { model: string; spendMicros: number; calls: number; inputTokens: number; outputTokens: number; cachedTokens: number; }[]; }>; /** Spend in the managed workspaces each organization key created. */ export declare function consoleSpendByApiKey(db: Database, accountId: string, window: ConsoleWindow): Promise<{ apiKeyId: string; workspaces: number; spendMicros: number; }[]>; /** Who created each organization key (the subject that created its service account). */ export declare function consoleApiKeyCreators(db: Database, accountId: string): Promise>; export declare function consoleSessionCounts(db: Database, accountId: string, workspaceIds: readonly string[], window: ConsoleWindow, options?: { endUsersFor?: ReadonlySet; }): Promise<{ sessions: Map; lastActivity: Map; endUsers: number; truncated: boolean; }>; export type ConsoleSessionCursor = { updatedUs: string; id: string; }; export declare function decodeConsoleSessionCursor(value: string): ConsoleSessionCursor; /** * Newest-first reviewable root sessions across the given managed workspaces, * with their turns, ratings, metered cost and opening message. `includeContent` * is false for the `metadata` review level: no title, message or content * search. `q` matches the workspace name and the end user's id, name or email * at every level, and the title and opening messages with content. */ export declare function listConsoleSessions(db: Database, input: { accountId: string; workspaces: readonly { id: string; name: string; }[]; limit: number; cursor: ConsoleSessionCursor | null; q: string | null; includeContent: boolean; }): Promise<{ sessions: ConsoleSessionSummary[]; nextCursor: string | null; truncated: boolean; }>; /** * Metered spend of each given root session's tree (the session and its * sub-agents) in one workspace: rows of `{ id, spend }`, omitting sessions * without debits. * * A model call is debited under `credit:model_usage_debit::` * and, for BYOK, `credit:byok_platform_fee::`. The keys are * built in a materialized CTE so the ledger join is a plain column equality: * under row-level security PostgreSQL will not use an index for a join clause * that applies a non-leakproof function such as `||`, and probing the unique * idempotency index once per key replaces a full ledger scan per session. */ export declare function consoleSessionSpendSql(accountId: string, workspaceId: string, sessionIds: readonly string[]): SQL; export type ConsoleSessionDetailRow = { summary: ConsoleSessionSummary; model: string | null; reasoningEffort: string | null; durationMs: number; tokens: { input: number; output: number; cached: number; total: number; }; modelCalls: number; models: string[]; toolCalls: number; feedback: ConsoleSessionFeedback[]; }; /** * One reviewable root session in a managed workspace, or null when it does * not exist, is not a root session, or is an Opengeni account's private chat. */ export declare function getConsoleSession(db: Database, input: { accountId: string; workspace: { id: string; name: string; }; sessionId: string; includeContent: boolean; }): Promise; /** Runs a read of a session Console has already authorized, as the system sees it. */ export declare function withConsoleSessionRead(fn: () => Promise): Promise; export {};