import { type SessionEvent } from "@opengeni/contracts"; import { type SQL } from "drizzle-orm"; import { type Database } from "./database.js"; /** * Idle-session archive (see docs/session-storage-lifecycle.md). * * Lifecycle on the session row: live -> archiving -> archived. `archiving` is * entered under the session's write lock after re-checking eligibility; from * that moment the database refuses new turns, history and machine inputs, so a * message cannot race the archive. The worker exports the session to a bundle, * uploads and verifies it, records the manifest (`archived`), and only then * purges the bulky tables. Turns, attempts, goals and readable timeline events * stay, so readers and durable references are unchanged. */ export declare const SESSION_ARCHIVE_FORMAT: "opengeni.session-archive"; export declare const SESSION_ARCHIVE_FORMAT_VERSION: 1; export declare const SESSION_ARCHIVE_TRANSCRIPT_FORMAT: "opengeni.session-transcript"; /** Purge order respects every foreign key between these tables. */ export declare const SESSION_ARCHIVE_PURGE_TABLES: readonly ["session_realtime_entries", "session_system_updates", "session_history_items", "session_attempt_codemode_calls", "session_attempt_tool_catalogs", "session_attempt_model_context_snapshots", "session_content_blobs", "session_pending_tool_calls", "session_events"]; export type SessionArchivePurgeTable = (typeof SESSION_ARCHIVE_PURGE_TABLES)[number]; /** Event types purged after archiving; every other type stays readable. */ export declare const SESSION_ARCHIVE_PURGED_EVENT_TYPES: readonly ["agent.message.delta", "agent.reasoning.delta", "sandbox.command.output.delta", "terminal.pty.output.delta", "agent.model.request", "system.update.pending", "system.update.delivered", "system.update.settled", "turn.startup.phase.started", "turn.startup.phase.completed", "codex.credential.selected", "turn.event.rejected_late"]; type KeyColumn = { column: string; cast: string; }; export type SessionArchiveExportTable = { table: string; /** Bundle order; unique per session. */ keys: KeyColumn[]; /** * A uuid column with its own unique index (the primary key). The table is * paged by a prefetched, ordered list of these ids instead of a keyset cursor. * Tables without one page by keyset on a single key that leads a unique * (workspace_id, session_id, key) index. */ idColumn?: string; }; /** * Everything the bundle carries, in bundle order, read so that every page is an * index seek and a very long session exports in linear time. * * Export reads run under row-level security, where PostgreSQL only uses * leakproof comparisons as index conditions; numeric and row comparisons are * not leakproof and become a filter after the policy that re-reads every * earlier row. A multi-column cursor also only bounds its first column. So * tables ordered by several keys, or by a numeric key, page by id list (see * readSessionArchiveTablePages), and keyset tables use one integer, uuid, text * or timestamptz key that an index on (workspace_id, session_id, key) seeks. */ export declare const SESSION_ARCHIVE_EXPORT_TABLES: readonly SessionArchiveExportTable[]; export type SessionArchiveScope = { accountId: string; workspaceId: string; sessionId: string; }; export type SessionArchiveObject = { key: string; bytes: number; sha256: string; }; /** * Fresh object keys for one archive write. Every write uses a new archive id, * so a published key is never overwritten; the secret history scrub writes * its rewritten objects under new keys the same way. */ export declare function sessionArchiveObjectKeys(scope: SessionArchiveScope, archiveId: string): { bundle: string; transcript: string; }; export type SessionArchiveManifest = { format: typeof SESSION_ARCHIVE_FORMAT; version: typeof SESSION_ARCHIVE_FORMAT_VERSION; /** Every object this archive owns; deleted with the session. */ objectKeys: string[]; bundle: SessionArchiveObject; transcript: SessionArchiveObject & { events: number; }; /** Bundle digest, duplicated at top level for database invariants. */ sha256: string; rowCounts: Record; createdAt: string; }; export type SessionRetention = { keepLive: boolean; archive: { state: "archiving" | "archived"; archivedAt: string | null; /** Someone asked to restore it; its content is being put back. */ restoring?: true | undefined; } | null; }; export declare function sessionRetentionFromRow(row: { keepLive: boolean; contentArchiveState: string | null; contentArchivedAt: Date | null; contentRestoreRequestedAt?: Date | null; }): SessionRetention; export declare function listSessionArchiveCandidates(db: Database, input: { idleSeconds: number; limit: number; }): Promise; /** * `restoring`: a stored chat whose restore was requested a while ago and is * not done yet (its workflow may have been lost); the pass finishes it. */ export type UnfinishedSessionArchive = SessionArchiveScope & { state: "archiving" | "archived" | "restoring"; }; export declare function listUnfinishedSessionArchives(db: Database, input: { staleSeconds: number; limit: number; }): Promise; /** * Enter `archiving` if the session is still eligible under its write lock. * Returns false (and changes nothing) when it became active or ineligible. */ export declare function beginSessionArchive(db: Database, scope: SessionArchiveScope, input: { idleSeconds: number; objectKeys: string[]; }): Promise; export declare function completeSessionArchive(db: Database, scope: SessionArchiveScope, manifest: SessionArchiveManifest): Promise; /** Abandon an unfinished archive; its planned objects are queued for deletion. */ export declare function abandonSessionArchive(db: Database, scope: SessionArchiveScope): Promise; /** * One keyset page of raw rows as exact JSON text, in bundle order. Rows are * rendered with row_to_json, not to_jsonb: a row whose jsonb columns together * exceed jsonb's 256 MB object limit (for example a huge retained tool output * stored twice) still renders as JSON text, and column order is preserved. */ export declare function readSessionArchiveRows(db: Database, scope: SessionArchiveScope, spec: SessionArchiveExportTable, input: { after: string[] | null; limit: number; }): Promise<{ rows: string[]; last: string[] | null; }>; /** * The export's page queries, run under the workspace's row-level security * context. Exported so tests can check their plans. */ export declare const sessionArchiveExportSql: { /** One keyset page, with each row's key values as text for the next cursor. */ keysetPage(scope: SessionArchiveScope, spec: SessionArchiveExportTable, input: { after: string[] | null; limit: number; }): SQL; /** Every row id of the session's rows, in bundle order. */ idList(scope: SessionArchiveScope, spec: SessionArchiveExportTable): SQL; /** The rows with these ids, in bundle order, found by primary key. */ idPage(scope: SessionArchiveScope, spec: SessionArchiveExportTable, ids: string[]): SQL; }; /** * Every row of one export table, as exact JSON text in bundle order, in pages * of at most `pageRows`. Each page is a bounded, indexed read, so exporting a * session with hundreds of thousands of rows stays linear. Tables marked * with an `idColumn` first read their ordered ids in one pass, then fetch each * page by primary key; the session is frozen while archiving, and a row that * disappears in between fails the export rather than shortening the bundle. */ export declare function readSessionArchiveTablePages(db: Database, scope: SessionArchiveScope, spec: SessionArchiveExportTable, input: { pageRows: number; }): AsyncGenerator; /** * One page of the readable transcript in the public SessionEvent shape: every * event type that stays in the timeline after archiving. */ export declare function readSessionArchiveTranscriptEvents(db: Database, scope: SessionArchiveScope, input: { afterSequence: number; limit: number; }): Promise; /** * The transcript event for one exported `session_events` row (its exact * row_to_json text, as the bundle carries it), or null when the type is purged * and so not part of the transcript. Equal to what * {@link readSessionArchiveTranscriptEvents} returns for the same row, so the * archive writes the transcript from the rows the bundle already read. */ export declare function sessionArchiveTranscriptEvent(row: string): SessionEvent | null; export declare function readSessionArchiveSessionRow(db: Database, scope: SessionArchiveScope): Promise; /** * Purge one bounded batch per call until every table is empty. Returns the * rows deleted in this call; zero means the purge is complete and recorded. * * Tables are purged in order. A call stops at the first table that still had * a full batch and reports it as `nextTable`; passing that back as * `fromTable` resumes there instead of calling every already-empty table * before it again. The purge is only recorded complete after a call that * starts at the first table and finds nothing in any table. */ export declare function purgeArchivedSessionContent(db: Database, scope: SessionArchiveScope, input: { batchSize: number; fromTable?: number; }): Promise<{ deleted: number; complete: boolean; nextTable: number; }>; export type SessionArchiveObjectDeletion = { objectKey: string; workspaceId: string; sessionId: string; }; export declare function claimSessionArchiveObjectDeletions(db: Database, input: { claimTimeoutSeconds: number; limit: number; }): Promise; export declare function completeSessionArchiveObjectDeletion(db: Database, objectKey: string): Promise; export { SessionArchivedError } from "./session-archive-errors.js"; /** * A control-worker proof that the session's execution is closed: its content * is archived (or being archived) or it is an imported read-only copy. The * database refuses every turn, attempt, history and wake write for such a * session, so a control activity that failed against it can never succeed by * retrying. Read in the session's own worker scope; a hidden or missing row is * not read-only (deletion has its own proof), and read errors propagate. */ export declare function isSessionExecutionReadOnly(db: Database, scope: SessionArchiveScope): Promise; export type SetSessionKeepLiveResult = { status: "updated"; retention: SessionRetention; } | { status: "not_found"; } | { status: "archived"; }; /** * Set or clear the per-session keep-live exemption. Callers authorize the * session first (`session.retention.write`); this is the workspace-scoped write. */ export declare function setSessionKeepLive(db: Database, input: { workspaceId: string; sessionId: string; keepLive: boolean; }): Promise; /** * Seconds after Archive during which Undo returns the chat exactly as it was. */ export declare const SESSION_ARCHIVE_UNDO_SECONDS = 10; /** * Seconds after Archive when storing may start: only once Undo is no longer * accepted, so a late Undo never races the store. session_archive_candidates * in migration 1213 uses the same thirteen seconds. */ export declare const SESSION_ARCHIVE_STORE_AFTER_SECONDS: number; /** * Seconds a chat's sandbox is kept after the Archive action, so a chat * restored within a day still has its files. Well past the Undo window * ({@link SESSION_ARCHIVE_STORE_AFTER_SECONDS}), so an Undo never races the * sandbox's end. A chat stored by the idle archiver was already unused for * weeks and waits no longer. */ export declare const ARCHIVED_CHAT_SANDBOX_KEPT_SECONDS: number; /** * Days a person's own message keeps a sub-chat "in use": a sub-chat someone * talks to directly is a chat they rely on (for example a long-running owner * an agent started), not a finished worker. */ export declare const SESSION_ARCHIVE_SUB_CHAT_IN_USE_DAYS = 14; /** Why a sub-chat counts as in use (see {@link SessionArchiveBlocker}). */ export type SessionArchiveActiveReason = "running" | "waiting" | "goal" | "messaged"; /** * What keeps a chat live, so Archive refuses. Keep-live, a repeating * automation, a site sign-in and an import are on purpose and must be * removed first. `active_sub_chat` is a sub-chat still in use (running, * waiting for input, working on an active goal, or messaged by a person in * the last {@link SESSION_ARCHIVE_SUB_CHAT_IN_USE_DAYS} days): Archive would * stop it, so the caller must confirm each one by id. */ export type SessionArchiveBlocker = { kind: "keep_live" | "scheduled_task" | "site_sign_in" | "imported"; sessionId: string; } | { kind: "active_sub_chat"; sessionId: string; title: string | null; reason: SessionArchiveActiveReason; }; export declare class SessionArchiveBlockedError extends Error { readonly blockers: SessionArchiveBlocker[]; readonly code = "session_archive_blocked"; constructor(blockers: SessionArchiveBlocker[]); } /** One plain sentence per kind of blocker, saying what to change. */ export declare function sessionArchiveBlockedMessage(blockers: SessionArchiveBlocker[]): string; export declare class SessionArchiveFinalError extends Error { readonly code = "session_archive_final"; constructor(); } /** * The chat is being moved to long-term storage right now, or the work its * Archive stopped is still settling; restoring waits for that. */ export declare class SessionArchiveBusyError extends Error { readonly code = "session_archive_busy"; constructor(message?: string); } /** A sub-chat is restored with the archived chat that started it. */ export declare class SessionArchiveRestoreRootError extends Error { readonly rootSessionId: string; readonly code = "session_archive_restore_root"; constructor(rootSessionId: string); } export type SessionArchiveRequest = { /** The chat and every sub-chat it started, all archived together. */ sessionIds: string[]; archivedAt: Date; /** Undo returns the chat as it was until this moment. */ undoUntil: Date; /** Storing may start at this moment, once Undo is no longer accepted. */ storeAfter: Date; /** The chat was archived already; nothing changed. */ alreadyArchived: boolean; }; /** * Archive a chat and its sub-chats for everyone: from now on they are listed * as archived, and once the undo window has passed and nothing runs in them, * the archiver moves their content to long-term storage and they become * read-only for good. Refuses with {@link SessionArchiveBlockedError} when * something keeps the chat live on purpose. Callers authorize session control * first; stopping the chat's running work is theirs too. */ export declare function requestSessionArchive(db: Database, scope: SessionArchiveScope & { subjectId: string; /** * Sub-chats in use that the caller saw and chose to archive too. Archive * refuses while any sub-chat in use is not listed here. */ confirmActiveSubChats?: readonly string[]; }, now?: Date): Promise; /** * Undo an Archive within its window: the chat and its sub-chats are live and * listed again, exactly as before. Throws {@link SessionArchiveFinalError} * once the window has passed or storing has begun. Returns false when the * chat was not archived (nothing to undo). */ export declare function undoSessionArchive(db: Database, scope: SessionArchiveScope, now?: Date): Promise; export type SessionUnarchiveResult = { /** * `undone`: within the undo window, exactly as before the Archive. * `restored`: nothing was stored yet, and the chats are live again. * `restoring`: some chats were in long-term storage; their content is put * back by {@link restoreArchivedSessionContent} (the others are live * already). `not_archived`: nothing to do. */ outcome: "not_archived" | "undone" | "restored" | "restoring"; /** The stored chats whose content is being restored. */ restoringSessionIds: string[]; }; /** * Bring an archived chat back, at any time: within the undo window this is * the exact undo; after it, the chat and the sub-chats archived with it are * live again, and those already in long-term storage are queued for their * content to be restored from the stored bundle. Throws * {@link SessionArchiveBusyError} while one of them is being stored, and * {@link SessionArchiveRestoreRootError} for a sub-chat of an archived chat. * Callers authorize session control first and start the restore. */ export declare function unarchiveSession(db: Database, scope: SessionArchiveScope, now?: Date): Promise; /** * Put the chats an Archive stopped back to idle once they are live again * (restored, or the Archive undone after it stopped them), so they take new * messages: each records an `idle` status change. The turn the Archive cut * off stays as it ended, which reads as interrupted. A chat whose stopped * turn is still settling is left for a later call and counted in `settling`. * The pause the Archive left is lifted separately, by a Resume (see * {@link listArchivePausedSessions}). Repeating a call changes nothing. */ export declare function reopenArchiveStoppedSessions(db: Database, scope: SessionArchiveScope): Promise<{ reopened: Array<{ sessionId: string; eventIds: string[]; }>; settling: number; }>; /** * The chats in this chat's tree still paused by an Archive although they are * live and no longer cancelled, topmost first: a Resume of each one (which * also lifts the pause below it) lets them run again. `pauseRevision` names * the pause, so a repeated Resume of the same one is recognised. */ export declare function listArchivePausedSessions(db: Database, scope: SessionArchiveScope): Promise>; /** * The purged tables a restore puts back, in an order that satisfies their * foreign keys (the reverse of the purge order). Purged timeline events * (streamed fragments, request telemetry, startup timings, update * bookkeeping) are not put back: events can only be appended in sequence, * and nothing a chat needs to continue reads them. */ export declare const SESSION_ARCHIVE_RESTORE_TABLES: ("session_attempt_codemode_calls" | "session_attempt_model_context_snapshots" | "session_attempt_tool_catalogs" | "session_content_blobs" | "session_history_items" | "session_pending_tool_calls" | "session_realtime_entries" | "session_system_updates")[]; export type SessionArchiveRestoreTable = (typeof SESSION_ARCHIVE_RESTORE_TABLES)[number]; /** A stored chat waiting to be restored: where its bundle is and what it must hash to. */ export type PendingSessionContentRestore = { bundle: SessionArchiveObject; sha256: string; }; /** The stored bundle of a chat whose restore was requested, or null when there is none to do. */ export declare function readPendingSessionContentRestore(db: Database, scope: SessionArchiveScope): Promise; export type RestoreArchivedSessionContentResult = { status: "restored"; rows: Record; } /** Nothing to restore: not stored, or no restore requested (done already). */ | { status: "not_pending"; } /** The stored manifest changed (a secret scrub swapped it); read it again. */ | { status: "manifest_changed"; }; /** * Put a stored chat's content back from its verified bundle and make it live * again, in one transaction: either every purged row is back and the chat is * live, or nothing changed. `rows(table)` yields the bundle's exact row JSON * for one table; rows still in the database are kept as they are. The chat's * stored objects are queued for deletion once it is live (migration 1261), * and a later Archive stores it again under new keys. */ export declare function restoreArchivedSessionContent(db: Database, scope: SessionArchiveScope, input: { /** The manifest digest the bundle was verified against. */ sha256: string; rows: (table: SessionArchiveRestoreTable) => AsyncIterable; }): Promise; /** * A chat and its sub-chats (at any depth) with their archive state, for the * step after the undo window and for the archive pass. It follows parent * links from the given chat, so it also works for a sub-chat that was * archived on its own (for example under a chat that is stored already). */ export declare function readSessionArchiveTree(db: Database, scope: { workspaceId: string; sessionId: string; }): Promise>; /** * Whether any of these not-yet-stored chats still holds input it would act on * in a later turn: an undelivered update, an unanswered question or an input * wait. An archived chat never runs again, so this input keeps it from being * stored until its work is cancelled, which settles all three. */ export declare function archivedSessionsHavePendingInput(db: Database, scope: { workspaceId: string; sessionIds: string[]; }): Promise;