import type { SessionBackgroundCommand, SessionBackgroundCommandActivity } from "@opengeni/contracts"; import { SessionCommandFailure } from "@opengeni/contracts"; import { type SQL } from "drizzle-orm"; import type { Database, SessionActivityDatabase } from "./database.js"; export type ConnectedMachineBackgroundCommandProof = { outcome: "exited" | "lost"; exitCode: number | null; reason: string; failure?: SessionCommandFailure; backgroundChildrenStopped?: boolean; observedAt: Date; }; export declare const SESSION_BACKGROUND_COMMAND_REASON_MAX_BYTES = 512; /** Existing reconciler policy, shared by initial push collection failures. */ export declare function connectedCommandReconciliationRetryMs(attempts: number, periodMs?: number): number; export declare function boundedSessionBackgroundCommandReason(value: string, label: string): string; export type SessionBackgroundCommandTerminalMutation = { prepare: (tx: SessionActivityDatabase) => Promise; commit: (tx: SessionActivityDatabase, command: SessionBackgroundCommand) => Promise; }; export type ConnectedMachineBackgroundCommandClaim = { commandId: string; accountId: string; workspaceId: string; sessionId: string; claimId: string; state: "running" | "stopping"; controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; reconcileAttempts: number; proof: ConnectedMachineBackgroundCommandProof | null; }; export type ConnectedCommandOutputReceipt = { exitSeq: string; attachGeneration: string; }; type ConnectedCommandOutputIdentity = SessionCommandIdentity & { controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; }; export type ConnectedCommandOutputClaim = ConnectedCommandOutputIdentity & { claimId: string; reconcileAttempts: number; receipt: ConnectedCommandOutputReceipt | null; }; /** How long a claim on a command's reconciliation lasts before another owner * may take it over: the reconciler's, and the collection claim of an * inventory answer that stores a command's output. */ export declare const CONNECTED_COMMAND_CLAIM_TTL_MS: number; /** Record full output custody only after the caller's verified, awaited capture. * Terminal observation is insufficient. The persisted receipt is the retry * obligation even when the capturing worker disappears before publishing ACK. */ export declare function recordConnectedCommandOutputConsumption(db: Database, input: ConnectedCommandOutputIdentity & { receipt: ConnectedCommandOutputReceipt; exitCode: number; }): Promise; /** A separate terminal-only inventory keeps rolling old workers from receiving * unfamiliar states and never borrows the mutable enrollment's current route. */ export declare function claimConnectedCommandOutputReleases(db: Database, input: { claimId: string; limit: number; claimTtlMs: number; dueBefore?: Date; }): Promise; /** Claim an exited command's output that was never stored, so exactly one * owner collects it: the answer to its runner's operation inventory, which * collects it while the runner is talking. Only an open, unconsumed output * nobody holds (or whose claim expired) is taken. Returns whether this caller * now holds it. */ export declare function claimConnectedCommandOutputCollection(db: Database, input: ConnectedCommandOutputIdentity & { claimId: string; }): Promise; /** Give up a collection claim that did not finish: the output stays open for * the runner's next inventory. */ export declare function returnConnectedCommandOutputCollection(db: Database, input: ConnectedCommandOutputIdentity & { claimId: string; }): Promise; /** Record a release of exactly the stored exit frontier: one the runner * confirmed in its answer (`OpRelease`), or one its operation inventory * answer told it to make. It settles the release obligation, whoever holds * its claim, and drops that claim. Returns whether this call recorded it; * false when it was already recorded, or the row is not that exact consumed * output. */ export declare function recordConnectedCommandOutputRelease(db: Database, input: ConnectedCommandOutputIdentity & { exitSeq: string; }): Promise; /** When output that was never captured stops being retried: see * `settleConnectedCommandOutputRetry`. */ export type ConnectedCommandOutputExpiry = { afterRunnerSeenMs: number; runnerSeenMarginMs: number; abandonAfterMs: number; }; /** Publish success is only a retry milestone. Stop retrying only after an exact * native absence observation, or record pre-capture loss explicitly as missing * output. Neither outcome is a model-completion acknowledgement. * * A retry may carry an `uncapturedOutputExpiry`. Output that was never * captured is then recorded unavailable, in the same update, instead of being * retried again when either: * - its command settled exited at least `afterRunnerSeenMs` ago, and its * runner's enrollment was seen alive at least `runnerSeenMarginMs` after * that. A live runner reports the completed operations it still retains, * and that report collects them, so this one is no longer retained; or * - its command settled exited at least `abandonAfterMs` ago, whether or not * the runner was seen since. * Such an obligation can no longer be met and would otherwise be swept * forever. Returns the recorded outcome, or null when this claim no longer * owns the row. */ export declare function settleConnectedCommandOutputRetry(db: Database, input: { claim: ConnectedCommandOutputClaim; retryAfterMs: number; uncapturedOutputExpiry?: ConnectedCommandOutputExpiry; }): Promise<"retry" | "unavailable" | null>; export declare function settleConnectedCommandOutputReleaseClaim(db: Database, input: { claim: ConnectedCommandOutputClaim; outcome: "published" | "not_retained" | "unavailable" | "retry"; retryAfterMs: number; }): Promise; /** Reconciliation outcomes under which the retained process cannot currently be * observed. This is a read projection and a probe-backoff hint only; it is never * containment policy or exit proof. */ export declare const UNOBSERVABLE_RETAINED_PROCESS_OUTCOMES: readonly ["process_observation_unavailable", "quarantined_process_observation_unavailable", "provider_binding_missing", "quarantined_provider_binding_missing", "provider_binding_mismatch", "quarantined_provider_binding_mismatch"]; export declare function unobservableRetainedProcessOutcomeSql(outcome: SQL): SQL; export declare function backgroundCommandActivityForSessions(db: Database, input: { accountId: string; workspaceId: string; sessionIds: string[]; }): Promise>; export declare function listSessionBackgroundCommands(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; activeOnly?: boolean; }): Promise; export type WorkspaceBackgroundCommand = SessionBackgroundCommand & { sessionTitle: string | null; machineName: string | null; }; /** Caller supplies the ordinary session-list audience inside subject RLS. */ export declare function listWorkspaceBackgroundCommandsInScope(db: Database, workspaceId: string, filters: SQL[], afterId?: string): Promise<{ commands: WorkspaceBackgroundCommand[]; nextCursor: string | null; }>; /** @internal Caller must already hold the canonical session/control fence. */ export declare function insertManagedSessionBackgroundCommandInTransaction(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; retainedProcessId: string; command: string; turnId?: string; attemptId?: string; executionGeneration?: number; }): Promise; /** Stop requester recorded for an operation abandoned on an unreachable machine. */ export declare const UNREACHABLE_MACHINE_STOP_REQUESTER = "system:connected-machine-unreachable"; /** @internal Caller must already hold the canonical exact-attempt fence, or for * an abandoned operation, proof that the exact attempt launched it. */ export declare function insertConnectedMachineSessionBackgroundCommandInTransaction(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; command: string; turnId?: string; attemptId?: string; executionGeneration?: number; /** The turn already reported this operation as failed because its machine * stopped answering. The row starts with a stop request, so the reconciler * stops it when the machine returns; its settlement adds no model input. */ abandoned?: boolean; }): Promise; /** Claim exact Connected Machine locators globally for provider reconciliation. * The SECURITY DEFINER SQL function owns the bounded SKIP LOCKED inventory; * claim expiry is coordination recovery only and never implies command loss. */ export declare function claimConnectedMachineSessionBackgroundCommands(db: Database, input: { claimId: string; limit: number; claimTtlMs: number; dueBefore?: Date; }): Promise; /** Only the first exit notification bypasses polling backoff. Delivery retries * cannot erase a failed collector's backoff or steal another active claim. */ export declare function claimPushedConnectedCommandCompletion(db: Database, input: ConnectedCommandOutputIdentity & { claimTtlMs: number; }): Promise; /** Checkpoint one exact terminal provider observation before lifecycle settlement. * A retry may reuse an identical proof; a divergent proof is a hard identity fault. */ export declare function recordConnectedMachineBackgroundCommandProof(db: Database, input: { claim: ConnectedMachineBackgroundCommandClaim; proof: ConnectedMachineBackgroundCommandProof; }): Promise; export declare function deferConnectedMachineBackgroundCommandReconciliation(db: Database, input: { claim: ConnectedMachineBackgroundCommandClaim; outcome: string; retryAfterMs: number; /** Its runner reports its own operation inventory and did not answer a * recovery request: forget the completion notice that made it due, so the * running command (outcome provider_unanswered, on any enrollment kind) is * claimed again only once the runner reports it again (or it is stopped, * proven or retired). */ leaveToRunner?: boolean; }): Promise; /** Settle only from the proof already checkpointed under this exact claim. */ export declare function settleClaimedConnectedMachineBackgroundCommandWithMutation(db: Database, input: { claim: ConnectedMachineBackgroundCommandClaim; }, mutateTerminal: SessionBackgroundCommandTerminalMutation): Promise; /** The frozen physical locator of an adopted command on a machine runner (a * Connected Machine or a compute sandbox). Cancellation goes only here. */ export type ConnectedCommandStopTarget = { controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; }; /** * Move one running command to `stopping`. The reconciler owns delivery and * settlement; `stopTarget` lets the caller deliver the cancellation at once, * best effort, so a stop does not wait for the next reconciliation pass. */ export declare function requestSessionBackgroundCommandCancellation(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; subjectId: string; }): Promise<{ command: SessionBackgroundCommand | null; accepted: boolean; stopTarget?: ConnectedCommandStopTarget; }>; /** * Transfer every active command in one or more session subtrees to the * provider-neutral stopping state inside the caller's existing control * transaction. The workspace-control mutation already excludes concurrent * session-tree changes, so the recursive walk and state transition are one * atomic Pause/Cancel effect. Steer deliberately never calls this seam. */ export declare function requestSessionBackgroundCommandCancellationsInTransaction(db: Database, input: { workspaceId: string; rootSessionIds: string[]; subjectId: string; }): Promise; /** Workspace Pause owns every active command in that workspace. */ export declare function requestWorkspaceBackgroundCommandCancellationsInTransaction(db: Database, input: { workspaceId: string; subjectId: string; }): Promise; export declare function settleSessionBackgroundCommandForRetainedProcessInTransaction(tx: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; retainedProcessId: string; outcome: "exited" | "lost"; exitCode: number | null; reason: string; }, mutateTerminal: SessionBackgroundCommandTerminalMutation): Promise; export declare function settleConnectedMachineSessionBackgroundCommandWithMutation(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; outcome: "exited" | "lost"; exitCode: number | null; reason: string; failure?: SessionCommandFailure | undefined; backgroundChildrenStopped?: boolean | undefined; }, mutateTerminal: SessionBackgroundCommandTerminalMutation): Promise; export declare function getSessionBackgroundCommand(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; }): Promise; export type SessionCommandIdentity = { accountId: string; workspaceId: string; sessionId: string; commandId: string; }; /** The immutable machine locator of one of this session's RUNNING connected * commands, copied at adoption: what any attempt of the session reads its * output from, whichever machine the session uses now. Null for any other * command. */ export declare function runningConnectedCommandLocator(db: Database, input: SessionCommandIdentity): Promise<{ controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; } | null>; /** Internal exact-identity discovery for an authenticated machine event. This * returns only a locator; settlement must revalidate it under the session fence. */ export declare function locateConnectedCommandCompletion(db: Database, input: { controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; }): Promise<(SessionCommandIdentity & { terminal: boolean; }) | null>; /** The most operations one inventory classification reads. */ export declare const CONNECTED_COMMAND_CLASSIFY_LIMIT = 1000; /** A command row of an operation a runner reports, with its output custody. */ export type ConnectedCommandInventoryRow = ConnectedCommandOutputIdentity & { state: "running" | "stopping" | "exited" | "lost"; outputExitSeq: string | null; /** Opengeni stored all of its output (`output_consumed_at`). */ outputConsumed: boolean; outputReleased: boolean; outputUnavailable: boolean; }; /** * For the operations a runner process reports it still runs or retains, the * command rows of that exact enrollment and connection instance, with their * state and output custody. Operations without a row (foreground work, or * commands deleted with their chat) are absent. Read-only. */ export declare function classifyConnectedCommandOps(db: Database, input: { controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opIds: readonly string[]; }): Promise>; /** * Make the running commands one exact runner process did not answer for * (left to it as `provider_unanswered`) due again, while it reports its * inventory. A runner reports only operations it knows, so one whose start * never reached it would otherwise stay running forever. The next reconciler * pass asks the runner, which is talking now: an unknown operation answers * lost and settles. Returns how many commands were made due. */ export declare function rearmUnansweredConnectedCommands(db: Database, input: { controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; }): Promise; /** Observe terminal state, not output consumption. Native terminal-result adapters * call this after settlement. Session-first ordering serializes settlement and * inbox claiming; already delivered history is never rewritten. */ export declare function observeSessionBackgroundCommandCompletion(db: Database, input: SessionCommandIdentity): Promise; export declare const COMMAND_OUTPUT_DEFAULT_BYTES = 16384; export declare const COMMAND_OUTPUT_MAX_BYTES = 65536; export declare const COMMAND_OUTPUT_PAGE_ROWS = 64; export declare function parseCommandOutputCursor(cursor: string | undefined, commandId: string): { sequence: number; offset: number; }; export type CommandOutputRow = { sequence: number; payload: unknown; payloadCodecVersion: number | null; }; type CommandOutputChunk = { sequence: number; stream: "stdout" | "stderr"; streamFidelity: "separate" | "merged" | "unknown"; chunk: string; }; /** Cursor offsets are UTF-16 positions at code-point boundaries; budgets are UTF-8 bytes. */ export declare function projectCommandOutputPage(input: { commandId: string; cursor?: string | undefined; maxOutputBytes?: number | undefined; rows: CommandOutputRow[]; /** Rows one page may use; defaults to COMMAND_OUTPUT_PAGE_ROWS. */ pageRows?: number | undefined; }): { chunks: CommandOutputChunk[]; nextCursor: string; hasMore: boolean; retention: { source: "retained_session_events"; completeness: "unknown"; gaps: string[]; }; }; /** * The last `maxOutputBytes` UTF-8 bytes of a command's retained output that * start at or after `from`, from at most `rowLimit` rows. `rows` are the newest * rows first, as commandOutputTailQuery returns them with one extra row, so a * row beyond the limit proves that older output remains. `start` is the cursor * of the first returned character; `endCursor` follows the newest row. */ export declare function projectCommandOutputTail(input: { commandId: string; from: { sequence: number; offset: number; }; maxOutputBytes: number; rows: CommandOutputRow[]; rowLimit?: number | undefined; }): { chunks: CommandOutputChunk[]; start: { sequence: number; offset: number; }; startCursor: string; reachedFrom: boolean; endCursor: string; gaps: string[]; }; /** * The newest `rowLimit + 1` output rows of one command, newest first, from a * sequence on; the extra row shows whether older output remains. */ export declare function commandOutputTailQuery(tx: Database, input: SessionCommandIdentity, fromSequence: number, rowLimit?: number): Omit; payload: SQL; payloadCodecVersion: import("drizzle-orm/pg-core").PgColumn<{ name: "payload_codec_version"; tableName: "session_events"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }, "partial", Record<"session_events", "not-null">, false, "limit" | "orderBy" | "where", { sequence: number; payload: unknown; payloadCodecVersion: number | null; }[], { sequence: import("drizzle-orm/pg-core").PgColumn<{ name: "sequence"; tableName: "session_events"; 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; }, {}, {}>; payload: import("drizzle-orm").DrizzleTypeError<"You cannot reference this field without assigning it an alias first - use `.as()`">; payloadCodecVersion: import("drizzle-orm/pg-core").PgColumn<{ name: "payload_codec_version"; tableName: "session_events"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }>, "limit" | "orderBy" | "where">; /** * How many output rows of one command lie strictly between two sequences. It * reads only the event index range, never a payload, so its cost does not grow * with the size of the output. */ export declare function commandOutputRowsBetween(tx: Database, input: SessionCommandIdentity, afterSequence: number, beforeSequence: number, /** Count at most this many rows (the result is then a lower bound). */ rowLimit?: number): Promise; /** One page of a command's retained output rows, from the cursor sequence on. */ export declare function commandOutputPageQuery(tx: Database, input: SessionCommandIdentity, fromSequence: number, pageRows?: number): Omit; payload: SQL; payloadCodecVersion: import("drizzle-orm/pg-core").PgColumn<{ name: "payload_codec_version"; tableName: "session_events"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }, "partial", Record<"session_events", "not-null">, false, "limit" | "orderBy" | "where", { sequence: number; payload: unknown; payloadCodecVersion: number | null; }[], { sequence: import("drizzle-orm/pg-core").PgColumn<{ name: "sequence"; tableName: "session_events"; 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; }, {}, {}>; payload: import("drizzle-orm").DrizzleTypeError<"You cannot reference this field without assigning it an alias first - use `.as()`">; payloadCodecVersion: import("drizzle-orm/pg-core").PgColumn<{ name: "payload_codec_version"; tableName: "session_events"; dataType: "number"; columnType: "PgInteger"; data: number; driverParam: string | number; notNull: false; hasDefault: false; isPrimaryKey: false; isAutoincrement: false; hasRuntimeDefault: false; enumValues: undefined; baseColumn: never; identity: undefined; generated: undefined; }, {}, {}>; }>, "limit" | "orderBy" | "where">; /** readCommandOutputWindow on a transaction that already holds the RLS scope. * `pageRows` bounds the rows one window reads (head and tail together). */ declare function readCommandOutputWindowInTransaction(tx: Database, input: SessionCommandIdentity & { cursor?: string | undefined; maxOutputBytes?: number | undefined; headAndTail?: boolean | undefined; pageRows?: number | undefined; /** Count at most this many omitted rows; beyond it the size is not estimated. */ omittedRowsCountLimit?: number | undefined; }, cursor: { sequence: number; offset: number; }): Promise<{ chunks: CommandOutputChunk[]; nextCursor: string; hasMore: boolean; retention: { source: "retained_session_events"; completeness: "unknown"; gaps: string[]; }; } | { chunks: CommandOutputChunk[]; nextCursor: string; hasMore: boolean; retention: { source: "retained_session_events"; completeness: "unknown"; gaps: string[]; }; endCursor: string; } | { chunks: CommandOutputChunk[]; nextCursor: string; hasMore: boolean; retention: { source: "retained_session_events"; completeness: "unknown"; gaps: string[]; }; omitted: { bytes: number; cursor: string; }; tail: { chunks: CommandOutputChunk[]; cursor: string; }; endCursor: string; }>; export declare function readSessionBackgroundCommandOutput(db: Database, input: SessionCommandIdentity & { cursor?: string | undefined; maxOutputBytes?: number | undefined; /** Return the start and end of output larger than the budget (see readCommandOutputWindow). */ headAndTail?: boolean | undefined; }): Promise<{ chunks: CommandOutputChunk[]; nextCursor: string; hasMore: boolean; retention: { source: "retained_session_events"; completeness: "unknown"; gaps: string[]; }; commandId: string; state: "exited" | "lost" | "running" | "stopping"; exitCode: number | null; settlementReason: string | null; failure?: { code: string; detail?: Record | undefined; retryable: false; }; terminal: boolean; completionObservedAt: string | null; notice?: string; } | { chunks: CommandOutputChunk[]; nextCursor: string; hasMore: boolean; retention: { source: "retained_session_events"; completeness: "unknown"; gaps: string[]; }; endCursor: string; commandId: string; state: "exited" | "lost" | "running" | "stopping"; exitCode: number | null; settlementReason: string | null; failure?: { code: string; detail?: Record | undefined; retryable: false; }; terminal: boolean; completionObservedAt: string | null; notice?: string; } | { chunks: CommandOutputChunk[]; nextCursor: string; hasMore: boolean; retention: { source: "retained_session_events"; completeness: "unknown"; gaps: string[]; }; omitted: { bytes: number; cursor: string; }; tail: { chunks: CommandOutputChunk[]; cursor: string; }; endCursor: string; commandId: string; state: "exited" | "lost" | "running" | "stopping"; exitCode: number | null; settlementReason: string | null; failure?: { code: string; detail?: Record | undefined; retryable: false; }; terminal: boolean; completionObservedAt: string | null; notice?: string; }>; /** Output a background command result carries, so a turn woken by it, or a * later turn it is delivered to, has the result without another read. */ export declare const BACKGROUND_COMMAND_RESULT_OUTPUT_BYTES = 8192; type CommandOutputWindow = Awaited>; /** * One terminal command's output window as plain text, in the words of the * model's `command_read` copy: the start, a marker naming the omitted middle * and the cursor that reads it, then the end. Empty when nothing was retained. */ export declare function commandOutputWindowText(window: CommandOutputWindow): string; /** * The bounded start and end of a settling command's retained output, read in * the settlement transaction. A failed read rolls back only its savepoint and * returns null, so output can never block the settlement itself. */ export declare function backgroundCommandResultOutputInTransaction(tx: SessionActivityDatabase, input: SessionCommandIdentity): Promise; /** A pending background command result taken for delivery inside a running turn. */ export type ClaimedBackgroundCommandResult = { updateId: string; commandId: string; summary: string; state: "exited" | "lost"; exitCode: number | null; /** Bounded output text, or null when the result predates output in results. */ output: string | null; notice: string | null; }; /** * Take this session's pending background command results for delivery with * the tool result the model receives next. Each taken command is observed and * its pending result superseded in one transaction, exactly as a terminal * `command_read` observes it, so the same result is never delivered again by * the inbox. Results are taken oldest first, each one whose text (with its * framing) still fits `maxBytes`. A cheap unlocked probe skips the session * fence when nothing is pending. */ export declare function claimPendingBackgroundCommandResults(db: Database, input: { accountId: string; workspaceId: string; sessionId: string; maxBytes: number; }): Promise; export {};