import type { SessionBackgroundCommand, SessionBackgroundCommandActivity, SessionBackgroundCommandReconciliation, } from "@opengeni/contracts"; import { SessionCommandFailure, CONNECTED_COMMAND_CHILD_CLEANUP_NOTICE } from "@opengeni/contracts"; import { isDeepStrictEqual } from "node:util"; import { and, asc, desc, eq, getTableColumns, gte, inArray, sql, type SQL } from "drizzle-orm"; import type { Database, SessionActivityDatabase } from "./database"; import { withRlsContext, withSessionActivityRlsContext } from "./database"; import * as schema from "./schema"; import { lockSessionEventWriteRows } from "./session-control"; import { fromPostgresLosslessJson, fromPostgresLosslessText } from "./lossless-json"; import { commandOutputClientEventIdPrefix } from "./session-command-output"; export type ConnectedMachineBackgroundCommandProof = { outcome: "exited" | "lost"; exitCode: number | null; reason: string; failure?: SessionCommandFailure; backgroundChildrenStopped?: boolean; observedAt: Date; }; export const SESSION_BACKGROUND_COMMAND_REASON_MAX_BYTES = 512; /** Existing reconciler policy, shared by initial push collection failures. */ export function connectedCommandReconciliationRetryMs(attempts: number, periodMs = 30_000): number { return Math.min( 5 * 60_000, Math.max(periodMs, 30_000) * 2 ** Math.min(4, Math.max(0, attempts - 1)), ); } export function boundedSessionBackgroundCommandReason(value: string, label: string): string { const normalized = value.trim(); let bounded = ""; let bytes = 0; for (const character of normalized) { const characterBytes = Buffer.byteLength(character, "utf8"); if (bytes + characterBytes > SESSION_BACKGROUND_COMMAND_REASON_MAX_BYTES) break; bounded += character; bytes += characterBytes; } if (!bounded) throw new Error(`${label} must not be empty`); return bounded; } 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; }; type ConnectedMachineBackgroundCommandClaimRow = { accountId: string; workspaceId: string; sessionId: string; commandId: string; claimId: string; commandState: string; controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; reconcileAttempts: number | string; reconcileProofOutcome: string | null; reconcileProofExitCode: number | string | null; reconcileProofReason: string | null; reconcileProofObservedAt: Date | string | 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; }; function connectedOutputIdentityWhere(input: ConnectedCommandOutputIdentity) { const command = schema.sessionBackgroundCommands; return and( eq(command.id, input.commandId), eq(command.accountId, input.accountId), eq(command.workspaceId, input.workspaceId), eq(command.sessionId, input.sessionId), eq(command.provider, "connected_machine"), eq(command.state, "exited"), eq(command.controlWorkspaceId, input.controlWorkspaceId), eq(command.enrollmentId, input.enrollmentId), eq(command.connectionInstanceId, input.connectionInstanceId), eq(command.opId, input.opId), ); } /** 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 const CONNECTED_COMMAND_CLAIM_TTL_MS = 5 * 60_000; /* * Output custody bookkeeping (consumption receipt, collection claim, release * and retry settlement) changes only the exact exited command row. It appends * no event, reads no session or control state, and never runs on a `running` * row, which is the only state Pause/Stop cancellation touches. So it locks * just that row, like the reconciliation proof and defer writers below, and * does not take the session event-write prefix (workspace-control share, * session NO KEY UPDATE, cursor FOR UPDATE). A transaction that holds one row * lock and requests no other cannot close a deadlock cycle; every prefix * holder that touches the same row locks it FOR UPDATE after its prefix. The * sweep retries this bookkeeping for every unreleased output, so the prefix * made it queue behind, and block, the session's own event appends. */ /** 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 async function recordConnectedCommandOutputConsumption( db: Database, input: ConnectedCommandOutputIdentity & { receipt: ConnectedCommandOutputReceipt; exitCode: number; }, ): Promise { for (const value of [input.receipt.exitSeq, input.receipt.attachGeneration]) { if (!/^[1-9][0-9]{0,19}$/.test(value) || BigInt(value) > 18446744073709551615n) throw new Error("Connected command output receipt has an invalid frontier"); } await withSessionActivityRlsContext(db, input, async (tx) => { const command = schema.sessionBackgroundCommands; const [current] = await tx .select() .from(command) .where(connectedOutputIdentityWhere(input)) .for("update") .limit(1); if (!current || current.exitCode !== input.exitCode || current.outputUnavailableAt !== null) throw new Error("Connected command output receipt disagrees with its exact terminal owner"); if (current.outputExitSeq !== null) { if (current.outputExitSeq !== input.receipt.exitSeq) throw new Error("Connected command output retry changed its durable exit frontier"); return; } await tx .update(command) .set({ outputExitSeq: input.receipt.exitSeq, outputAttachGeneration: input.receipt.attachGeneration, outputConsumedAt: new Date(), reconcileAfter: new Date(), updatedAt: new Date(), }) .where(connectedOutputIdentityWhere(input)); }); } /** A separate terminal-only inventory keeps rolling old workers from receiving * unfamiliar states and never borrows the mutable enrollment's current route. */ export async function claimConnectedCommandOutputReleases( db: Database, input: { claimId: string; limit: number; claimTtlMs: number; dueBefore?: Date }, ): Promise { if ( !Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100 || !Number.isSafeInteger(input.claimTtlMs) || input.claimTtlMs < 0 || input.claimTtlMs > 3_600_000 ) throw new Error("Connected command output claim bounds are invalid"); const rows = await db.execute< ConnectedMachineBackgroundCommandClaimRow & { outputExitSeq: string | null; outputAttachGeneration: string | null; } >(sql` select account_id as "accountId", workspace_id as "workspaceId", session_id as "sessionId", command_id as "commandId", claim_id as "claimId", command_state as "commandState", control_workspace_id as "controlWorkspaceId", enrollment_id as "enrollmentId", connection_instance_id as "connectionInstanceId", op_id as "opId", reconcile_attempts as "reconcileAttempts", output_exit_seq as "outputExitSeq", output_attach_generation as "outputAttachGeneration" from opengeni_private.claim_connected_command_output_releases( ${input.claimId}::uuid, ${input.limit}::integer, ${input.claimTtlMs}::bigint, ${(input.dueBefore ?? new Date()).toISOString()}::timestamptz ) `); return rows.map( ( row: ConnectedMachineBackgroundCommandClaimRow & { outputExitSeq: string | null; outputAttachGeneration: string | null; }, ) => { if (row.commandState !== "exited") throw new Error("Output release claim is not terminal"); return { commandId: row.commandId, accountId: row.accountId, workspaceId: row.workspaceId, sessionId: row.sessionId, claimId: row.claimId, controlWorkspaceId: row.controlWorkspaceId, enrollmentId: row.enrollmentId, connectionInstanceId: row.connectionInstanceId, opId: row.opId, reconcileAttempts: Number(row.reconcileAttempts), receipt: row.outputExitSeq !== null && row.outputAttachGeneration !== null ? { exitSeq: row.outputExitSeq, attachGeneration: row.outputAttachGeneration } : null, }; }, ); } /** 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 async function claimConnectedCommandOutputCollection( db: Database, input: ConnectedCommandOutputIdentity & { claimId: string }, ): Promise { return await withSessionActivityRlsContext(db, input, async (tx) => { const command = schema.sessionBackgroundCommands; const rows = await tx .update(command) .set({ reconcileClaimId: input.claimId, reconcileClaimedAt: new Date(), updatedAt: new Date(), }) .where( and( connectedOutputIdentityWhere(input), sql`${command.outputConsumedAt} is null and ${command.outputExitSeq} is null`, sql`${command.outputReleaseObservedAt} is null and ${command.outputUnavailableAt} is null`, sql`(${command.reconcileClaimId} is null or ${command.reconcileClaimedAt} <= now() - make_interval(secs => ${CONNECTED_COMMAND_CLAIM_TTL_MS / 1000}))`, ), ) .returning({ id: command.id }); return rows.length === 1; }); } /** Give up a collection claim that did not finish: the output stays open for * the runner's next inventory. */ export async function returnConnectedCommandOutputCollection( db: Database, input: ConnectedCommandOutputIdentity & { claimId: string }, ): Promise { await withSessionActivityRlsContext(db, input, async (tx) => { const command = schema.sessionBackgroundCommands; await tx .update(command) .set({ reconcileClaimId: null, reconcileClaimedAt: null, updatedAt: new Date() }) .where(and(connectedOutputIdentityWhere(input), eq(command.reconcileClaimId, input.claimId))); }); } /** 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 async function recordConnectedCommandOutputRelease( db: Database, input: ConnectedCommandOutputIdentity & { exitSeq: string }, ): Promise { return await withSessionActivityRlsContext(db, input, async (tx) => { const command = schema.sessionBackgroundCommands; const rows = await tx .update(command) .set({ outputReleaseObservedAt: new Date(), lastReconcileOutcome: "output_released", reconcileClaimId: null, reconcileClaimedAt: null, updatedAt: new Date(), }) .where( and( connectedOutputIdentityWhere(input), eq(command.outputExitSeq, input.exitSeq), sql`${command.outputConsumedAt} is not null`, sql`${command.outputReleaseObservedAt} is null and ${command.outputUnavailableAt} is null`, ), ) .returning({ id: command.id }); return rows.length === 1; }); } /** 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 async function settleConnectedCommandOutputRetry( db: Database, input: { claim: ConnectedCommandOutputClaim; retryAfterMs: number; uncapturedOutputExpiry?: ConnectedCommandOutputExpiry; }, ): Promise<"retry" | "unavailable" | null> { const expiry = input.uncapturedOutputExpiry; if ( expiry && [expiry.afterRunnerSeenMs, expiry.runnerSeenMarginMs, expiry.abandonAfterMs].some( (value) => !Number.isSafeInteger(value) || value < 0, ) ) throw new Error("Connected command output expiry is invalid"); const outcome = await settleConnectedCommandOutputClaim(db, { claim: input.claim, outcome: "retry", retryAfterMs: input.retryAfterMs, ...(expiry ? { uncapturedOutputExpiry: expiry } : {}), }); return outcome === null ? null : outcome === "unavailable" ? "unavailable" : "retry"; } export async function settleConnectedCommandOutputReleaseClaim( db: Database, input: { claim: ConnectedCommandOutputClaim; outcome: "published" | "not_retained" | "unavailable" | "retry"; retryAfterMs: number; }, ): Promise { return (await settleConnectedCommandOutputClaim(db, input)) !== null; } async function settleConnectedCommandOutputClaim( db: Database, input: { claim: ConnectedCommandOutputClaim; outcome: "published" | "not_retained" | "unavailable" | "retry"; retryAfterMs: number; uncapturedOutputExpiry?: ConnectedCommandOutputExpiry; }, ): Promise<"published" | "not_retained" | "unavailable" | "retry" | null> { if (!Number.isSafeInteger(input.retryAfterMs) || input.retryAfterMs < 0) throw new Error("Connected command output retry delay is invalid"); const released = input.outcome === "not_retained"; return await withSessionActivityRlsContext(db, input.claim, async (tx) => { const command = schema.sessionBackgroundCommands; const retryAt = new Date(Date.now() + input.retryAfterMs); // Evaluated on the row being updated, against the database clock. The // runner's enrollment is read without a lock; one this context cannot // see only leaves the longer abandonment bound. const expiry = input.outcome === "retry" ? input.uncapturedOutputExpiry : undefined; const enrollment = schema.enrollments; const expired = expiry ? sql`(${command.outputConsumedAt} is null and ${command.settledAt} is not null and ( ${command.settledAt} <= now() - make_interval(secs => ${expiry.abandonAfterMs / 1000}) or (${command.settledAt} <= now() - make_interval(secs => ${expiry.afterRunnerSeenMs / 1000}) and exists ( select 1 from ${enrollment} where ${enrollment.workspaceId} = ${command.controlWorkspaceId} and ${enrollment.id} = ${command.enrollmentId} and ${enrollment.lastSeenAt} >= ${command.settledAt} + make_interval(secs => ${expiry.runnerSeenMarginMs / 1000})))))` : null; const rows = await tx .update(command) .set({ ...(released ? { outputReleaseObservedAt: new Date() } : {}), ...(input.outcome === "unavailable" ? { outputUnavailableAt: new Date() } : {}), ...(expired ? { outputUnavailableAt: sql`case when ${expired} then now() end` } : {}), reconcileAfter: expired ? sql`case when ${expired} then now() else ${retryAt.toISOString()}::timestamptz end` : retryAt, reconcileClaimId: null, reconcileClaimedAt: null, lastReconcileOutcome: expired ? sql`case when ${expired} then 'output_unavailable' else 'output_retry' end` : released ? "output_released" : input.outcome === "published" ? "output_ack_published" : input.outcome === "unavailable" ? "output_unavailable" : "output_retry", updatedAt: new Date(), }) .where( and( connectedOutputIdentityWhere(input.claim), eq(command.reconcileClaimId, input.claim.claimId), sql`${command.outputReleaseObservedAt} is null and ${command.outputUnavailableAt} is null`, ...(input.outcome === "unavailable" ? [sql`${command.outputConsumedAt} is null`] : input.outcome !== "retry" ? [sql`${command.outputConsumedAt} is not null`] : []), ), ) .returning({ id: command.id, unavailable: sql`${command.outputUnavailableAt} is not null`, }); if (rows.length !== 1) return null; return input.outcome === "retry" && rows[0]!.unavailable ? "unavailable" : input.outcome; }); } function commandPreview(value: string): string { if (value.length <= 512) return value; let preview = value.slice(0, 511); // Do not split a UTF-16 surrogate pair at the preview boundary. if (/[\uD800-\uDBFF]$/.test(preview)) preview = preview.slice(0, -1); return `${preview}…`; } /** 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 const UNOBSERVABLE_RETAINED_PROCESS_OUTCOMES = [ "process_observation_unavailable", "quarantined_process_observation_unavailable", "provider_binding_missing", "quarantined_provider_binding_missing", "provider_binding_mismatch", "quarantined_provider_binding_mismatch", ] as const; export function unobservableRetainedProcessOutcomeSql(outcome: SQL): SQL { return sql`${outcome} in (${sql.join( UNOBSERVABLE_RETAINED_PROCESS_OUTCOMES.map((value) => sql`${value}`), sql`, `, )})`; } const commandObservationUnavailable = sql` ${schema.sessionBackgroundCommands.state} in ('running','stopping') and ( (${schema.sessionBackgroundCommands.provider} = 'connected_machine' and coalesce(${schema.sessionBackgroundCommands.lastReconcileOutcome} in ('provider_offline', 'provider_error'), false)) or exists ( select 1 from sandbox_retained_processes process where process.id = ${schema.sessionBackgroundCommands.retainedProcessId} and process.account_id = ${schema.sessionBackgroundCommands.accountId} and process.workspace_id = ${schema.sessionBackgroundCommands.workspaceId} and process.session_id = ${schema.sessionBackgroundCommands.sessionId} and process.state = 'active' and ${unobservableRetainedProcessOutcomeSql(sql`process.last_reconcile_outcome`)}))`; const commandReadColumns = { ...getTableColumns(schema.sessionBackgroundCommands), observationUnavailable: commandObservationUnavailable, }; function connectedCommandReconciliation( row: typeof schema.sessionBackgroundCommands.$inferSelect, ): SessionBackgroundCommandReconciliation { const outcome = row.lastReconcileOutcome; const observedAt = row.reconcileProofObservedAt?.toISOString(); return { // Legacy diagnostic text is not a public message or a routing locator. lastOutcome: outcome === null ? null : /^[a-z][a-z0-9_]{0,63}$/.test(outcome) ? outcome : "unknown", attempts: row.reconcileAttempts, dueAt: row.reconcileAfter.toISOString(), claimedAt: row.reconcileClaimedAt?.toISOString() ?? null, terminalProof: observedAt && row.reconcileProofOutcome === "exited" && row.reconcileProofExitCode !== null ? { outcome: "exited", exitCode: row.reconcileProofExitCode, observedAt } : observedAt && row.reconcileProofOutcome === "lost" ? { outcome: "lost", exitCode: null, observedAt } : null, }; } function mapCommand( row: typeof schema.sessionBackgroundCommands.$inferSelect & { observationUnavailable?: boolean }, ): SessionBackgroundCommand { const terminal = row.state === "exited" || row.state === "lost"; const legacyFailureCode = row.provider === "connected_machine" ? /^op_failure_([A-Za-z0-9_-]{1,128})$/.exec(row.settlementReason ?? "")?.[1] : undefined; // Application writes validate exact detail bounds. Older/restored rows may // meet the wider storage envelope without meeting that contract: preserve // failure truth and readable output rather than throwing on every read. const storedFailure = row.runnerFailure ? SessionCommandFailure.safeParse(row.runnerFailure) : null; const failure = !terminal ? undefined : row.runnerFailure ? storedFailure?.success ? storedFailure.data : { code: /^[A-Za-z0-9_-]{1,128}$/.test(row.runnerFailure.code) ? row.runnerFailure.code : "INVALID_RUNNER_FAILURE", detail: { metadata_error: "Stored runner failure details do not match the retained contract.", }, retryable: false as const, } : legacyFailureCode ? { code: legacyFailureCode, retryable: false as const } : undefined; return { id: row.id, workspaceId: row.workspaceId, sessionId: row.sessionId, provider: row.provider, state: row.state, ...(!terminal && row.observationUnavailable ? { observationStatus: "unavailable" as const } : {}), ...(row.provider === "connected_machine" ? { reconciliation: connectedCommandReconciliation(row) } : {}), commandPreview: row.commandPreview, ...(row.commandText !== null ? { commandText: row.commandText } : {}), cancelRequestedAt: row.cancelRequestedAt?.toISOString() ?? null, exitCode: row.exitCode ?? null, settlementReason: row.settlementReason ?? null, ...(failure ? { failure } : {}), ...(row.provider === "connected_machine" && row.backgroundChildrenStopped ? { backgroundChildrenStopped: true as const } : {}), startedAt: row.startedAt.toISOString(), settledAt: row.settledAt?.toISOString() ?? null, completionObservedAt: row.completionObservedAt?.toISOString() ?? null, updatedAt: row.updatedAt.toISOString(), }; } export async function backgroundCommandActivityForSessions( db: Database, input: { accountId: string; workspaceId: string; sessionIds: string[] }, ): Promise> { if (input.sessionIds.length === 0) return new Map(); return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .select({ sessionId: schema.sessionBackgroundCommands.sessionId, count: sql`count(*)::int`, stoppingCount: sql`count(*) filter (where ${schema.sessionBackgroundCommands.state} = 'stopping')::int`, unavailableCount: sql`count(*) filter (where ${commandObservationUnavailable})::int`, }) .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), inArray(schema.sessionBackgroundCommands.sessionId, input.sessionIds), inArray(schema.sessionBackgroundCommands.state, ["running", "stopping"]), ), ) .groupBy(schema.sessionBackgroundCommands.sessionId); return new Map( rows.map((row) => [ row.sessionId, { state: Number(row.stoppingCount) > 0 ? ("stopping" as const) : ("running" as const), count: Number(row.count), ...(Number(row.unavailableCount) > 0 ? { unavailableCount: Number(row.unavailableCount) } : {}), }, ]), ); }, ); } export async function listSessionBackgroundCommands( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; activeOnly?: boolean }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const rows = await scopedDb .select(commandReadColumns) .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), ...(input.activeOnly ? [inArray(schema.sessionBackgroundCommands.state, ["running", "stopping"])] : []), ), ) .orderBy( desc(schema.sessionBackgroundCommands.startedAt), desc(schema.sessionBackgroundCommands.id), ) .limit(1000); return rows.map(mapCommand); }, ); } export type WorkspaceBackgroundCommand = SessionBackgroundCommand & { sessionTitle: string | null; machineName: string | null; }; /** Caller supplies the ordinary session-list audience inside subject RLS. */ export async function listWorkspaceBackgroundCommandsInScope( db: Database, workspaceId: string, filters: SQL[], afterId?: string, ): Promise<{ commands: WorkspaceBackgroundCommand[]; nextCursor: string | null }> { const command = schema.sessionBackgroundCommands; const rows = await db .select({ ...commandReadColumns, sessionTitle: schema.sessions.title, // Resolve the immutable launch target, never the session's current pointer. // A removed or no-longer-visible machine has no name in this projection. machineName: sql`(select machine.name from ${schema.sandboxes} machine where machine.account_id = ${command.accountId} and ( (${command.provider} = 'connected_machine' and machine.workspace_id = ${command.controlWorkspaceId} and machine.enrollment_id = ${command.enrollmentId}) or (${command.provider} = 'managed' and machine.id = ( select process.route_target_id from ${schema.sandboxRetainedProcesses} process where process.id = ${command.retainedProcessId} and process.workspace_id = ${command.workspaceId} and process.session_id = ${command.sessionId}))) order by machine.id limit 1)`, }) .from(command) .innerJoin( schema.sessions, and( eq(schema.sessions.workspaceId, command.workspaceId), eq(schema.sessions.id, command.sessionId), ), ) .where( and( eq(command.workspaceId, workspaceId), inArray(command.state, ["running", "stopping"]), ...(afterId ? [sql`${command.id} > ${afterId}::uuid`] : []), ...filters, ), ) .orderBy(asc(command.id)) .limit(101); const page = rows.slice(0, 100); return { commands: page.map((row) => ({ ...mapCommand(row), sessionTitle: row.sessionTitle, machineName: row.machineName, })), nextCursor: rows.length > 100 ? page.at(-1)!.id : null, }; } /** @internal Caller must already hold the canonical session/control fence. */ export async function insertManagedSessionBackgroundCommandInTransaction( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; retainedProcessId: string; command: string; turnId?: string; attemptId?: string; executionGeneration?: number; }, ): Promise { const [process] = await db .select({ accountId: schema.sandboxRetainedProcesses.accountId, workspaceId: schema.sandboxRetainedProcesses.workspaceId, sessionId: schema.sandboxRetainedProcesses.sessionId, state: schema.sandboxRetainedProcesses.state, ownerActorKind: schema.sandboxRetainedProcesses.ownerActorKind, ownerActorId: schema.sandboxRetainedProcesses.ownerActorId, ownerTurnId: schema.sandboxRetainedProcesses.ownerTurnId, ownerAttemptId: schema.sandboxRetainedProcesses.ownerAttemptId, ownerExecutionGeneration: schema.sandboxRetainedProcesses.ownerExecutionGeneration, }) .from(schema.sandboxRetainedProcesses) .where(eq(schema.sandboxRetainedProcesses.id, input.retainedProcessId)) .for("update") .limit(1); if ( !process || process.accountId !== input.accountId || process.workspaceId !== input.workspaceId || process.sessionId !== input.sessionId || process.state !== "active" ) { throw new Error("Managed background command requires its exact active retained process"); } const [row] = await db .insert(schema.sessionBackgroundCommands) .values({ id: input.commandId, accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, provider: "managed", state: "running", retainedProcessId: input.retainedProcessId, commandPreview: commandPreview(input.command), commandText: input.command, launchTurnId: input.turnId ?? null, launchAttemptId: input.attemptId ?? null, launchExecutionGeneration: input.executionGeneration ?? null, }) .onConflictDoUpdate({ target: schema.sessionBackgroundCommands.retainedProcessId, targetWhere: sql`${schema.sessionBackgroundCommands.retainedProcessId} is not null`, set: { updatedAt: new Date() }, }) .returning(); if (!row) throw new Error("Managed background command adoption returned no row"); const legacyReplayMatches = row.launchTurnId === null && row.launchAttemptId === null && row.launchExecutionGeneration === null && process.ownerActorKind === "turn" && process.ownerActorId === input.attemptId && process.ownerTurnId === input.turnId && process.ownerAttemptId === input.attemptId && process.ownerExecutionGeneration === input.executionGeneration; if ( row.accountId !== input.accountId || row.workspaceId !== input.workspaceId || row.sessionId !== input.sessionId || (!legacyReplayMatches && (row.launchTurnId !== (input.turnId ?? null) || row.launchAttemptId !== (input.attemptId ?? null) || row.launchExecutionGeneration !== (input.executionGeneration ?? null))) || row.provider !== "managed" || row.retainedProcessId !== input.retainedProcessId ) { throw new Error("Managed background command adoption conflicted with another identity"); } return mapCommand(row); } /** Stop requester recorded for an operation abandoned on an unreachable machine. */ export 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 async 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 { const now = new Date(); const [row] = await db .insert(schema.sessionBackgroundCommands) .values({ id: input.commandId, accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, provider: "connected_machine", state: input.abandoned ? "stopping" : "running", ...(input.abandoned ? { cancelRequestedAt: now, cancelRequestedBy: UNREACHABLE_MACHINE_STOP_REQUESTER, reconcileAfter: now, } : {}), controlWorkspaceId: input.controlWorkspaceId, enrollmentId: input.enrollmentId, connectionInstanceId: input.connectionInstanceId, opId: input.opId, commandPreview: commandPreview(input.command), commandText: input.command, launchTurnId: input.turnId ?? null, launchAttemptId: input.attemptId ?? null, launchExecutionGeneration: input.executionGeneration ?? null, }) .onConflictDoUpdate({ target: [ schema.sessionBackgroundCommands.controlWorkspaceId, schema.sessionBackgroundCommands.enrollmentId, schema.sessionBackgroundCommands.connectionInstanceId, schema.sessionBackgroundCommands.opId, ], targetWhere: sql`${schema.sessionBackgroundCommands.provider} = 'connected_machine'`, set: { updatedAt: new Date() }, }) .returning(); if (!row) throw new Error("Connected Machine background command adoption returned no row"); if ( row.accountId !== input.accountId || row.workspaceId !== input.workspaceId || row.sessionId !== input.sessionId || row.launchTurnId !== (input.turnId ?? null) || row.launchAttemptId !== (input.attemptId ?? null) || row.launchExecutionGeneration !== (input.executionGeneration ?? null) || row.provider !== "connected_machine" || row.controlWorkspaceId !== input.controlWorkspaceId || row.enrollmentId !== input.enrollmentId || row.connectionInstanceId !== input.connectionInstanceId || row.opId !== input.opId ) { throw new Error( "Connected Machine background command adoption conflicted with another identity", ); } return mapCommand(row); } /** 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 async function claimConnectedMachineSessionBackgroundCommands( db: Database, input: { claimId: string; limit: number; claimTtlMs: number; dueBefore?: Date }, ): Promise { if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 100) { throw new Error("Connected command reconciliation limit must be between 1 and 100"); } if ( !Number.isSafeInteger(input.claimTtlMs) || input.claimTtlMs < 0 || input.claimTtlMs > 3_600_000 ) { throw new Error("Connected command reconciliation claim TTL is invalid"); } const rows = await db.execute(sql` select account_id as "accountId", workspace_id as "workspaceId", session_id as "sessionId", command_id as "commandId", claim_id as "claimId", command_state as "commandState", control_workspace_id as "controlWorkspaceId", enrollment_id as "enrollmentId", connection_instance_id as "connectionInstanceId", op_id as "opId", reconcile_attempts as "reconcileAttempts", reconcile_proof_outcome as "reconcileProofOutcome", reconcile_proof_exit_code as "reconcileProofExitCode", reconcile_proof_reason as "reconcileProofReason", reconcile_proof_observed_at as "reconcileProofObservedAt" from opengeni_private.claim_connected_machine_background_commands( ${input.claimId}::uuid, ${input.limit}::integer, ${input.claimTtlMs}::bigint, ${(input.dueBefore ?? new Date()).toISOString()}::timestamptz ) `); return rows.map((row: ConnectedMachineBackgroundCommandClaimRow) => { if (row.commandState !== "running" && row.commandState !== "stopping") { throw new Error(`Connected command claim returned invalid state ${row.commandState}`); } const proof = row.reconcileProofOutcome === null ? null : row.reconcileProofOutcome === "exited" || row.reconcileProofOutcome === "lost" ? { outcome: row.reconcileProofOutcome, exitCode: row.reconcileProofExitCode === null ? null : Number(row.reconcileProofExitCode), reason: row.reconcileProofReason!, observedAt: row.reconcileProofObservedAt instanceof Date ? row.reconcileProofObservedAt : new Date(row.reconcileProofObservedAt!), } : (() => { throw new Error( `Connected command claim returned invalid proof ${row.reconcileProofOutcome}`, ); })(); return { commandId: row.commandId, accountId: row.accountId, workspaceId: row.workspaceId, sessionId: row.sessionId, claimId: row.claimId, state: row.commandState, controlWorkspaceId: row.controlWorkspaceId, enrollmentId: row.enrollmentId, connectionInstanceId: row.connectionInstanceId, opId: row.opId, reconcileAttempts: Number(row.reconcileAttempts), proof, }; }); } function connectedClaimIdentityWhere(claim: ConnectedMachineBackgroundCommandClaim) { return and( eq(schema.sessionBackgroundCommands.id, claim.commandId), eq(schema.sessionBackgroundCommands.accountId, claim.accountId), eq(schema.sessionBackgroundCommands.workspaceId, claim.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, claim.sessionId), eq(schema.sessionBackgroundCommands.provider, "connected_machine"), eq(schema.sessionBackgroundCommands.controlWorkspaceId, claim.controlWorkspaceId), eq(schema.sessionBackgroundCommands.enrollmentId, claim.enrollmentId), eq(schema.sessionBackgroundCommands.connectionInstanceId, claim.connectionInstanceId), eq(schema.sessionBackgroundCommands.opId, claim.opId), eq(schema.sessionBackgroundCommands.reconcileClaimId, claim.claimId), inArray(schema.sessionBackgroundCommands.state, ["running", "stopping"]), ); } /** Only the first exit notification bypasses polling backoff. Delivery retries * cannot erase a failed collector's backoff or steal another active claim. */ export async function claimPushedConnectedCommandCompletion( db: Database, input: ConnectedCommandOutputIdentity & { claimTtlMs: number }, ): Promise { if (!Number.isSafeInteger(input.claimTtlMs) || input.claimTtlMs <= 0) throw new Error("Connected command completion claim TTL is invalid"); return withRlsContext(db, input, async (tx) => { const table = schema.sessionBackgroundCommands; const identity = and( eq(table.id, input.commandId), eq(table.accountId, input.accountId), eq(table.workspaceId, input.workspaceId), eq(table.sessionId, input.sessionId), eq(table.provider, "connected_machine"), eq(table.controlWorkspaceId, input.controlWorkspaceId), eq(table.enrollmentId, input.enrollmentId), eq(table.connectionInstanceId, input.connectionInstanceId), eq(table.opId, input.opId), inArray(table.state, ["running", "stopping"]), ); const [row] = await tx.select().from(table).where(identity).for("update").limit(1); if (!row) return null; const now = new Date(); const firstNotification = row.completionNotifiedAt === null; if (firstNotification) await tx .update(table) .set({ reconcileAfter: now, completionNotifiedAt: now }) .where(identity); if ( (!firstNotification && row.reconcileAfter.getTime() > now.getTime()) || row.reconcileProofOutcome !== null || (row.reconcileClaimId !== null && row.reconcileClaimedAt !== null && row.reconcileClaimedAt.getTime() > now.getTime() - input.claimTtlMs) ) return null; const claimId = crypto.randomUUID(); await tx .update(table) .set({ reconcileClaimId: claimId, reconcileClaimedAt: now, reconcileAfter: new Date(now.getTime() + input.claimTtlMs), reconcileAttempts: row.reconcileAttempts + 1, lastReconcileOutcome: "claimed", updatedAt: now, }) .where(identity); return { ...input, claimId, state: row.state as "running" | "stopping", reconcileAttempts: row.reconcileAttempts + 1, proof: null, }; }); } /** 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 async function recordConnectedMachineBackgroundCommandProof( db: Database, input: { claim: ConnectedMachineBackgroundCommandClaim; proof: ConnectedMachineBackgroundCommandProof; }, ): Promise { const failure = input.proof.failure ? SessionCommandFailure.parse(input.proof.failure) : null; const reason = boundedSessionBackgroundCommandReason( input.proof.reason, "Connected command proof reason", ); if (failure && reason !== `op_failure_${failure.code}`) throw new Error("Connected command failure code conflicts with proof reason"); if (input.proof.outcome === "exited" && input.proof.exitCode === null) { throw new Error("Connected command exit proof requires an exit code"); } if (input.proof.outcome === "lost" && input.proof.exitCode !== null) { throw new Error("Connected command loss proof cannot carry an exit code"); } await withRlsContext( db, { accountId: input.claim.accountId, workspaceId: input.claim.workspaceId }, async (scopedDb) => { const [current] = await scopedDb .select() .from(schema.sessionBackgroundCommands) .where(connectedClaimIdentityWhere(input.claim)) .for("update") .limit(1); if (!current) throw new Error("Connected command proof was fenced by newer lifecycle state"); if (current.reconcileProofOutcome !== null) { const observedAt = current.reconcileProofObservedAt?.getTime() ?? null; if ( current.reconcileProofOutcome !== input.proof.outcome || current.reconcileProofExitCode !== input.proof.exitCode || current.reconcileProofReason !== reason || !isDeepStrictEqual(current.runnerFailure, failure) || observedAt !== input.proof.observedAt.getTime() ) { throw new Error("Connected command reconciliation proof conflicts with durable proof"); } return; } const rows = await scopedDb .update(schema.sessionBackgroundCommands) .set({ reconcileProofOutcome: input.proof.outcome, reconcileProofExitCode: input.proof.exitCode, reconcileProofReason: reason, runnerFailure: failure, backgroundChildrenStopped: sql`${schema.sessionBackgroundCommands.backgroundChildrenStopped} OR ${input.proof.backgroundChildrenStopped === true}`, reconcileProofObservedAt: input.proof.observedAt, lastReconcileOutcome: `proof_${input.proof.outcome}`, updatedAt: new Date(), }) .where(connectedClaimIdentityWhere(input.claim)) .returning({ id: schema.sessionBackgroundCommands.id }); if (rows.length !== 1) { throw new Error("Connected command proof lost its exact claim during checkpoint"); } }, ); } export async 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 { if (!Number.isSafeInteger(input.retryAfterMs) || input.retryAfterMs < 0) { throw new Error("Connected command reconciliation retry delay is invalid"); } const outcome = input.outcome.trim().slice(0, 64); if (!outcome) throw new Error("Connected command reconciliation outcome must not be empty"); return await withRlsContext( db, { accountId: input.claim.accountId, workspaceId: input.claim.workspaceId }, async (scopedDb) => { const rows = await scopedDb .update(schema.sessionBackgroundCommands) .set({ reconcileAfter: sql`case when ${outcome} = 'provider_running' and ${schema.sessionBackgroundCommands.completionNotifiedAt} > ${schema.sessionBackgroundCommands.reconcileClaimedAt} then now() else ${new Date(Date.now() + input.retryAfterMs).toISOString()}::timestamptz end`, reconcileClaimId: null, reconcileClaimedAt: null, lastReconcileOutcome: outcome, ...(input.leaveToRunner ? { completionNotifiedAt: null } : {}), updatedAt: new Date(), }) .where(connectedClaimIdentityWhere(input.claim)) .returning({ id: schema.sessionBackgroundCommands.id }); return rows.length === 1; }, ); } /** Settle only from the proof already checkpointed under this exact claim. */ export async function settleClaimedConnectedMachineBackgroundCommandWithMutation( db: Database, input: { claim: ConnectedMachineBackgroundCommandClaim }, mutateTerminal: SessionBackgroundCommandTerminalMutation, ): Promise { return await withSessionActivityRlsContext( db, { accountId: input.claim.accountId, workspaceId: input.claim.workspaceId }, async (tx) => { await mutateTerminal.prepare(tx); const rows = await tx.execute<{ id: string }>(sql` update ${schema.sessionBackgroundCommands} command set state = command.reconcile_proof_outcome, exit_code = case when command.reconcile_proof_outcome = 'exited' then command.reconcile_proof_exit_code else null end, settlement_reason = command.reconcile_proof_reason, settled_at = command.reconcile_proof_observed_at, reconcile_claim_id = null, reconcile_claimed_at = null, last_reconcile_outcome = 'settled_' || command.reconcile_proof_outcome, updated_at = clock_timestamp() where command.id = ${input.claim.commandId} and command.account_id = ${input.claim.accountId} and command.workspace_id = ${input.claim.workspaceId} and command.session_id = ${input.claim.sessionId} and command.provider = 'connected_machine' and command.control_workspace_id = ${input.claim.controlWorkspaceId} and command.enrollment_id = ${input.claim.enrollmentId} and command.connection_instance_id = ${input.claim.connectionInstanceId} and command.op_id = ${input.claim.opId} and command.reconcile_claim_id = ${input.claim.claimId} and command.state in ('running', 'stopping') and command.reconcile_proof_outcome in ('exited', 'lost') and command.reconcile_proof_observed_at is not null returning command.id `); if (rows.length !== 1) return false; const [row] = await tx .select() .from(schema.sessionBackgroundCommands) .where(eq(schema.sessionBackgroundCommands.id, input.claim.commandId)) .limit(1); if (!row) throw new Error("Settled Connected Machine command disappeared"); await mutateTerminal.commit(tx, mapCommand(row)); return true; }, ); } /** 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 async function requestSessionBackgroundCommandCancellation( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string; subjectId: string; }, ): Promise<{ command: SessionBackgroundCommand | null; accepted: boolean; stopTarget?: ConnectedCommandStopTarget; }> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => await scopedDb.transaction(async (tx) => { const [current] = await tx .select() .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.id, input.commandId), ), ) .for("update") .limit(1); if (!current) return { command: null, accepted: false }; if (current.state !== "running") { return { command: mapCommand(current), accepted: false }; } const [updated] = await tx .update(schema.sessionBackgroundCommands) .set({ state: "stopping", cancelRequestedAt: new Date(), cancelRequestedBy: input.subjectId.slice(0, 1024), reconcileAfter: new Date(), reconcileClaimId: null, reconcileClaimedAt: null, updatedAt: new Date(), }) .where(eq(schema.sessionBackgroundCommands.id, current.id)) .returning(); if (current.retainedProcessId) { await tx .update(schema.sandboxRetainedProcesses) .set({ reconcileAfter: new Date(), lastReconcileOutcome: "cancel_requested" }) .where( and( eq(schema.sandboxRetainedProcesses.id, current.retainedProcessId), eq(schema.sandboxRetainedProcesses.state, "active"), sql`${schema.sandboxRetainedProcesses.reconcileClaimId} is null`, ), ); } const stopTarget = updated!.provider === "connected_machine" && updated!.controlWorkspaceId && updated!.enrollmentId && updated!.connectionInstanceId && updated!.opId ? { controlWorkspaceId: updated!.controlWorkspaceId, enrollmentId: updated!.enrollmentId, connectionInstanceId: updated!.connectionInstanceId, opId: updated!.opId, } : undefined; return { command: mapCommand(updated!), accepted: true, ...(stopTarget ? { stopTarget } : {}), }; }), ); } /** * 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 async function requestSessionBackgroundCommandCancellationsInTransaction( db: Database, input: { workspaceId: string; rootSessionIds: string[]; subjectId: string; }, ): Promise { const rootSessionIds = [...new Set(input.rootSessionIds)]; if (rootSessionIds.length === 0) return 0; const rows = await db.execute<{ commandCount: number | string }>(sql` with recursive roots(id) as ( values ${sql.join( rootSessionIds.map((sessionId) => sql`(${sessionId}::uuid)`), sql`, `, )} ), subtree(id, path, cycle) as ( select session.id, array[session.id]::uuid[], false from roots root join ${schema.sessions} session on session.workspace_id = ${input.workspaceId} and session.id = root.id union all select child.id, parent.path || child.id, child.id = any(parent.path) from subtree parent join ${schema.sessions} child on child.workspace_id = ${input.workspaceId} and child.parent_session_id = parent.id where not parent.cycle ), stopped as ( update ${schema.sessionBackgroundCommands} command set state = 'stopping', cancel_requested_at = clock_timestamp(), cancel_requested_by = left(${input.subjectId}, 1024), reconcile_after = clock_timestamp(), reconcile_claim_id = null, reconcile_claimed_at = null, updated_at = clock_timestamp() where command.workspace_id = ${input.workspaceId} and command.session_id in (select id from subtree where not cycle) and command.state = 'running' returning command.retained_process_id ), nudged as ( update ${schema.sandboxRetainedProcesses} process set reconcile_after = clock_timestamp(), reconcile_claim_id = null, reconcile_claimed_at = null, last_reconcile_outcome = 'cancel_requested' where process.id in ( select stopped.retained_process_id from stopped where stopped.retained_process_id is not null ) and process.state = 'active' returning process.id ) select count(*)::integer as "commandCount" from stopped `); return Number(rows[0]?.commandCount ?? 0); } /** Workspace Pause owns every active command in that workspace. */ export async function requestWorkspaceBackgroundCommandCancellationsInTransaction( db: Database, input: { workspaceId: string; subjectId: string }, ): Promise { const rows = await db.execute<{ commandCount: number | string }>(sql` with stopped as ( update ${schema.sessionBackgroundCommands} command set state = 'stopping', cancel_requested_at = clock_timestamp(), cancel_requested_by = left(${input.subjectId}, 1024), reconcile_after = clock_timestamp(), reconcile_claim_id = null, reconcile_claimed_at = null, updated_at = clock_timestamp() where command.workspace_id = ${input.workspaceId} and command.state = 'running' returning command.retained_process_id ), nudged as ( update ${schema.sandboxRetainedProcesses} process set reconcile_after = clock_timestamp(), reconcile_claim_id = null, reconcile_claimed_at = null, last_reconcile_outcome = 'cancel_requested' where process.id in ( select stopped.retained_process_id from stopped where stopped.retained_process_id is not null ) and process.state = 'active' returning process.id ) select count(*)::integer as "commandCount" from stopped `); return Number(rows[0]?.commandCount ?? 0); } export async function settleSessionBackgroundCommandForRetainedProcessInTransaction( tx: SessionActivityDatabase, input: { accountId: string; workspaceId: string; sessionId: string; retainedProcessId: string; outcome: "exited" | "lost"; exitCode: number | null; reason: string; }, mutateTerminal: SessionBackgroundCommandTerminalMutation, ): Promise { const reason = boundedSessionBackgroundCommandReason( input.reason, "Managed command settlement reason", ); await mutateTerminal.prepare(tx); const [updatedRow] = await tx .update(schema.sessionBackgroundCommands) .set({ state: input.outcome, exitCode: input.outcome === "exited" ? input.exitCode : null, settlementReason: reason, settledAt: new Date(), reconcileClaimId: null, reconcileClaimedAt: null, lastReconcileOutcome: `settled_${input.outcome}`, updatedAt: new Date(), }) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.retainedProcessId, input.retainedProcessId), inArray(schema.sessionBackgroundCommands.state, ["running", "stopping"]), ), ) .returning(); let row = updatedRow; if (!row) { const [current] = await tx .select() .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.retainedProcessId, input.retainedProcessId), ), ) .for("update") .limit(1); if (!current) return null; if ( current.state !== input.outcome || current.exitCode !== (input.outcome === "exited" ? input.exitCode : null) ) { throw new Error("Managed background command terminal state conflicts with process proof"); } const [existingEvent] = await tx .select({ id: schema.sessionEvents.id }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.type, "session.command.finished"), sql`${schema.sessionEvents.payload} ->> 'commandId' = ${current.id}`, ), ) .limit(1); if (existingEvent) return mapCommand(current); row = current; } const command = mapCommand(row); await mutateTerminal.commit(tx, command); return command; } export async 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 { const failure = input.failure ? SessionCommandFailure.parse(input.failure) : null; const reason = boundedSessionBackgroundCommandReason( input.reason, "Connected command settlement reason", ); if (failure && reason !== `op_failure_${failure.code}`) throw new Error("Connected command failure code conflicts with settlement reason"); if (input.outcome === "exited" && input.exitCode === null) { throw new Error("Connected command exit settlement requires an exit code"); } if (input.outcome === "lost" && input.exitCode !== null) { throw new Error("Connected command loss settlement cannot carry an exit code"); } return await withSessionActivityRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (tx) => { await mutateTerminal.prepare(tx); const settledAt = new Date(); const [row] = await tx .update(schema.sessionBackgroundCommands) .set({ state: input.outcome, exitCode: input.outcome === "exited" ? input.exitCode : null, settlementReason: reason, runnerFailure: failure, backgroundChildrenStopped: sql`${schema.sessionBackgroundCommands.backgroundChildrenStopped} OR ${input.backgroundChildrenStopped === true}`, settledAt, reconcileClaimId: null, reconcileClaimedAt: null, reconcileProofOutcome: input.outcome, reconcileProofExitCode: input.outcome === "exited" ? input.exitCode : null, reconcileProofReason: reason, reconcileProofObservedAt: settledAt, lastReconcileOutcome: `settled_${input.outcome}`, reconcileAfter: settledAt, updatedAt: new Date(), }) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.id, input.commandId), eq(schema.sessionBackgroundCommands.provider, "connected_machine"), eq(schema.sessionBackgroundCommands.controlWorkspaceId, input.controlWorkspaceId), eq(schema.sessionBackgroundCommands.enrollmentId, input.enrollmentId), eq(schema.sessionBackgroundCommands.connectionInstanceId, input.connectionInstanceId), eq(schema.sessionBackgroundCommands.opId, input.opId), // A fast owner settlement cannot erase or replace metadata already // checkpointed by the reconciler under the exact command identity. sql`(${schema.sessionBackgroundCommands.runnerFailure} is null or ${schema.sessionBackgroundCommands.runnerFailure} = ${failure ? JSON.stringify(failure) : null}::jsonb)`, inArray(schema.sessionBackgroundCommands.state, ["running", "stopping"]), ), ) .returning(); if (!row) return null; const command = mapCommand(row); await mutateTerminal.commit(tx, command); return command; }, ); } export async function getSessionBackgroundCommand( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; commandId: string }, ): Promise { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .select(commandReadColumns) .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.id, input.commandId), ), ) .limit(1); return row ? mapCommand(row) : null; }, ); } 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 async function runningConnectedCommandLocator( db: Database, input: SessionCommandIdentity, ): Promise<{ controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; } | null> { return await withRlsContext( db, { accountId: input.accountId, workspaceId: input.workspaceId }, async (scopedDb) => { const [row] = await scopedDb .select({ controlWorkspaceId: schema.sessionBackgroundCommands.controlWorkspaceId, enrollmentId: schema.sessionBackgroundCommands.enrollmentId, connectionInstanceId: schema.sessionBackgroundCommands.connectionInstanceId, opId: schema.sessionBackgroundCommands.opId, }) .from(schema.sessionBackgroundCommands) .where( and( eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.id, input.commandId), eq(schema.sessionBackgroundCommands.provider, "connected_machine"), eq(schema.sessionBackgroundCommands.state, "running"), ), ) .limit(1); if (!row?.controlWorkspaceId || !row.enrollmentId || !row.connectionInstanceId || !row.opId) return null; return { controlWorkspaceId: row.controlWorkspaceId, enrollmentId: row.enrollmentId, connectionInstanceId: row.connectionInstanceId, opId: row.opId, }; }, ); } /** Internal exact-identity discovery for an authenticated machine event. This * returns only a locator; settlement must revalidate it under the session fence. */ export async function locateConnectedCommandCompletion( db: Database, input: { controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opId: string; }, ): Promise<(SessionCommandIdentity & { terminal: boolean }) | null> { const rows = await db.execute(sql` select account_id as "accountId", workspace_id as "workspaceId", session_id as "sessionId", command_id as "commandId", terminal from opengeni_private.locate_connected_command_completion( ${input.controlWorkspaceId}::uuid, ${input.enrollmentId}::uuid, ${input.connectionInstanceId}::text, ${input.opId}::text )`); return rows[0] ?? null; } /** The most operations one inventory classification reads. */ export const CONNECTED_COMMAND_CLASSIFY_LIMIT = 1_000; /** 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 async function classifyConnectedCommandOps( db: Database, input: { controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string; opIds: readonly string[]; }, ): Promise> { if (input.opIds.length > CONNECTED_COMMAND_CLASSIFY_LIMIT) { throw new Error( `At most ${CONNECTED_COMMAND_CLASSIFY_LIMIT} operations are classified at once`, ); } const classified = new Map(); if (input.opIds.length === 0) return classified; type Row = Omit< ConnectedCommandInventoryRow, "controlWorkspaceId" | "enrollmentId" | "connectionInstanceId" >; const rows = await db.execute(sql` select op_id as "opId", account_id as "accountId", workspace_id as "workspaceId", session_id as "sessionId", command_id as "commandId", state, output_exit_seq as "outputExitSeq", output_consumed as "outputConsumed", output_released as "outputReleased", output_unavailable as "outputUnavailable" from opengeni_private.classify_connected_command_ops( ${input.controlWorkspaceId}::uuid, ${input.enrollmentId}::uuid, ${input.connectionInstanceId}::text, array(select jsonb_array_elements_text(${JSON.stringify(input.opIds)}::jsonb)) )`); for (const row of rows as Row[]) { if (!["running", "stopping", "exited", "lost"].includes(row.state)) throw new Error("Connected command inventory row has an unknown state"); const entry: ConnectedCommandInventoryRow = { ...row, controlWorkspaceId: input.controlWorkspaceId, enrollmentId: input.enrollmentId, connectionInstanceId: input.connectionInstanceId, }; classified.set(row.opId, [...(classified.get(row.opId) ?? []), entry]); } return classified; } /** * 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 async function rearmUnansweredConnectedCommands( db: Database, input: { controlWorkspaceId: string; enrollmentId: string; connectionInstanceId: string }, ): Promise { const rows = await db.execute<{ rearmed: number }>(sql` select opengeni_private.rearm_unanswered_connected_commands( ${input.controlWorkspaceId}::uuid, ${input.enrollmentId}::uuid, ${input.connectionInstanceId}::text ) as rearmed`); return Number((rows as Array<{ rearmed: number }>)[0]?.rearmed ?? 0); } /** 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 async function observeSessionBackgroundCommandCompletion( db: Database, input: SessionCommandIdentity, ): Promise { return await withSessionActivityRlsContext(db, input, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); if (locks.sessions[0]?.accountId !== input.accountId) return null; const identity = and( eq(schema.sessionBackgroundCommands.accountId, input.accountId), eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.id, input.commandId), ); const [command] = await tx .select() .from(schema.sessionBackgroundCommands) .where(identity) .for("update") .limit(1); if (!command) return null; if (command.state !== "exited" && command.state !== "lost") return mapCommand(command); const observedAt = command.completionObservedAt ?? new Date(); await tx .update(schema.sessionBackgroundCommands) .set({ completionObservedAt: observedAt }) .where(identity); await tx .update(schema.sessionSystemUpdates) .set({ state: "superseded" }) .where( and( eq(schema.sessionSystemUpdates.accountId, input.accountId), eq(schema.sessionSystemUpdates.workspaceId, input.workspaceId), eq(schema.sessionSystemUpdates.sessionId, input.sessionId), eq(schema.sessionSystemUpdates.kind, "background_command_result"), eq(schema.sessionSystemUpdates.sourceId, input.commandId), eq(schema.sessionSystemUpdates.dedupeKey, `background-command-result:${input.commandId}`), eq(schema.sessionSystemUpdates.state, "pending"), ), ); return mapCommand({ ...command, completionObservedAt: observedAt }); }); } export const COMMAND_OUTPUT_DEFAULT_BYTES = 16_384; export const COMMAND_OUTPUT_MAX_BYTES = 65_536; export const COMMAND_OUTPUT_PAGE_ROWS = 64; export function parseCommandOutputCursor(cursor: string | undefined, commandId: string) { if (cursor === undefined) return { sequence: 0, offset: 0 }; if (cursor.length > 128) throw new Error("Invalid command output cursor"); const parts = cursor.split(":"); if ( parts.length !== 3 || parts[0] !== commandId || !/^\d+$/.test(parts[1]!) || !/^\d+$/.test(parts[2]!) ) { throw new Error("Invalid command output cursor"); } const sequence = Number(parts[1]); const offset = Number(parts[2]); if (!Number.isSafeInteger(sequence) || !Number.isSafeInteger(offset)) throw new Error("Invalid command output cursor"); return { sequence, offset }; } export type CommandOutputRow = { sequence: number; payload: unknown; payloadCodecVersion: number | null; }; type CommandOutputChunk = { sequence: number; stream: "stdout" | "stderr"; streamFidelity: "separate" | "merged" | "unknown"; chunk: string; }; function commandOutputRowText(row: CommandOutputRow): { text: string; stream: CommandOutputChunk["stream"]; streamFidelity: CommandOutputChunk["streamFidelity"]; gaps: string[]; } { const payload = fromPostgresLosslessJson(row.payload, row.payloadCodecVersion) as Record< string, unknown >; const gaps: string[] = []; if (typeof payload?.chunk !== "string") gaps.push("retained_event_has_no_output_chunk"); if (payload?.commandReadProjectionGap === true) gaps.push("retained_event_exceeds_read_limit"); if (payload?.truncation && typeof payload.truncation === "object") gaps.push("output_truncated_at_retention_boundary"); return { text: typeof payload?.chunk === "string" ? payload.chunk : "", stream: payload?.stream === "stderr" ? "stderr" : "stdout", streamFidelity: payload?.streamFidelity === "merged" ? "merged" : payload?.streamFidelity === "separate" ? "separate" : "unknown", gaps, }; } /** Cursor offsets are UTF-16 positions at code-point boundaries; budgets are UTF-8 bytes. */ export 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; }) { const start = parseCommandOutputCursor(input.cursor, input.commandId); const budget = input.maxOutputBytes ?? COMMAND_OUTPUT_DEFAULT_BYTES; if (!Number.isSafeInteger(budget) || budget < 4 || budget > COMMAND_OUTPUT_MAX_BYTES) throw new Error("maxOutputBytes must be between 4 and 65536"); let remaining = budget; let sequence = start.sequence; let offset = start.offset; const chunks: CommandOutputChunk[] = []; const gaps: string[] = []; if (start.offset > 0 && input.rows[0]?.sequence !== start.sequence) gaps.push("cursor_output_no_longer_retained"); let consumed = 0; for (const row of input.rows.slice(0, input.pageRows ?? COMMAND_OUTPUT_PAGE_ROWS)) { const { text, stream, streamFidelity, gaps: rowGaps } = commandOutputRowText(row); gaps.push(...rowGaps); const begin = row.sequence === start.sequence ? start.offset : 0; if ( begin > 0 && begin < text.length && text.charCodeAt(begin - 1) >= 0xd800 && text.charCodeAt(begin - 1) <= 0xdbff && text.charCodeAt(begin) >= 0xdc00 && text.charCodeAt(begin) <= 0xdfff ) { throw new Error("Invalid command output cursor: offset splits a Unicode code point"); } if (begin > text.length) gaps.push("cursor_output_no_longer_retained"); let end = Math.min(begin, text.length); for (const character of text.slice(end)) { const bytes = Buffer.byteLength(character, "utf8"); if (bytes > remaining) break; remaining -= bytes; end += character.length; } if (end > begin) chunks.push({ sequence: row.sequence, stream, streamFidelity, chunk: text.slice(begin, end), }); if (end < text.length) { sequence = row.sequence; offset = end; break; } sequence = row.sequence + 1; offset = 0; consumed++; } return { chunks, nextCursor: `${input.commandId}:${sequence}:${offset}`, hasMore: consumed < input.rows.length, retention: { source: "retained_session_events" as const, completeness: "unknown" as const, gaps: [...new Set(gaps)], }, }; } /** * 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 function projectCommandOutputTail(input: { commandId: string; from: { sequence: number; offset: number }; maxOutputBytes: number; rows: CommandOutputRow[]; rowLimit?: number | undefined; }) { const rowLimit = Math.max(1, input.rowLimit ?? COMMAND_OUTPUT_PAGE_ROWS); let remaining = Math.max(0, input.maxOutputBytes); const chunks: CommandOutputChunk[] = []; const gaps: string[] = []; let start = { sequence: input.from.sequence, offset: input.from.offset }; let reachedFrom = true; const newest = input.rows[0]; const endCursor = newest ? `${input.commandId}:${newest.sequence + 1}:0` : `${input.commandId}:${input.from.sequence}:${input.from.offset}`; for (const row of input.rows.slice(0, rowLimit)) { if (row.sequence < input.from.sequence) break; const { text, stream, streamFidelity, gaps: rowGaps } = commandOutputRowText(row); gaps.push(...rowGaps); const floor = row.sequence === input.from.sequence ? Math.min(input.from.offset, text.length) : 0; let begin = text.length; while (begin > floor) { // Step back one code point, never splitting a surrogate pair. let step = 1; const low = text.charCodeAt(begin - 1); if (begin - 2 >= floor && low >= 0xdc00 && low <= 0xdfff) { const high = text.charCodeAt(begin - 2); if (high >= 0xd800 && high <= 0xdbff) step = 2; } const bytes = Buffer.byteLength(text.slice(begin - step, begin), "utf8"); if (bytes > remaining) break; remaining -= bytes; begin -= step; } if (begin < text.length) chunks.unshift({ sequence: row.sequence, stream, streamFidelity, chunk: text.slice(begin) }); if (begin > floor) { start = { sequence: row.sequence, offset: begin }; reachedFrom = false; break; } start = { sequence: row.sequence, offset: floor }; } // A fetched row beyond the limit lies between `from` and the oldest used row. const beyond = input.rows[rowLimit]; if (reachedFrom && beyond !== undefined && beyond.sequence >= input.from.sequence) { reachedFrom = false; } return { chunks, start, startCursor: `${input.commandId}:${start.sequence}:${start.offset}`, reachedFrom, endCursor, gaps: [...new Set(gaps)], }; } function commandOutputScanFilter(input: SessionCommandIdentity, fromSequence: number) { // See commandOutputPageQuery for why the client event id prefix bounds the scan. const clientIdFrom = commandOutputClientEventIdPrefix(input.commandId); const clientIdBefore = `${clientIdFrom.slice(0, -1)};`; return and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), sql`${schema.sessionEvents.type} = 'sandbox.command.output.delta'`, sql`${schema.sessionEvents.clientEventId} collate "C" >= ${clientIdFrom}`, sql`${schema.sessionEvents.clientEventId} collate "C" < ${clientIdBefore}`, sql`${schema.sessionEvents.payload} ->> 'commandId' = ${input.commandId}`, gte(schema.sessionEvents.sequence, fromSequence), ); } /** * The newest `rowLimit + 1` output rows of one command, newest first, from a * sequence on; the extra row shows whether older output remains. */ export function commandOutputTailQuery( tx: Database, input: SessionCommandIdentity, fromSequence: number, rowLimit: number = COMMAND_OUTPUT_PAGE_ROWS, ) { return tx .select({ sequence: schema.sessionEvents.sequence, payload: sql`case when octet_length(${schema.sessionEvents.payload}::text) <= 262144 then ${schema.sessionEvents.payload} else jsonb_build_object('commandReadProjectionGap', true) end`, payloadCodecVersion: schema.sessionEvents.payloadCodecVersion, }) .from(schema.sessionEvents) .where(commandOutputScanFilter(input, fromSequence)) .orderBy(desc(schema.sessionEvents.sequence)) .limit(Math.max(1, rowLimit) + 1); } /** * 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 async 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 { if (beforeSequence - afterSequence <= 1) return 0; const clientIdFrom = commandOutputClientEventIdPrefix(input.commandId); const clientIdBefore = `${clientIdFrom.slice(0, -1)};`; const between = and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), sql`${schema.sessionEvents.type} = 'sandbox.command.output.delta'`, sql`${schema.sessionEvents.clientEventId} collate "C" >= ${clientIdFrom}`, sql`${schema.sessionEvents.clientEventId} collate "C" < ${clientIdBefore}`, sql`${schema.sessionEvents.sequence} > ${afterSequence}`, sql`${schema.sessionEvents.sequence} < ${beforeSequence}`, ); if (rowLimit !== undefined) { const bounded = tx .select({ sequence: schema.sessionEvents.sequence }) .from(schema.sessionEvents) .where(between) .limit(Math.max(1, rowLimit)) .as("bounded_output_rows"); const [row] = await tx.select({ rows: sql`count(*)` }).from(bounded); const rows = Number(row?.rows ?? 0); return Number.isSafeInteger(rows) && rows > 0 ? rows : 0; } const [row] = await tx .select({ rows: sql`count(*)` }) .from(schema.sessionEvents) .where(between); const rows = Number(row?.rows ?? 0); return Number.isSafeInteger(rows) && rows > 0 ? rows : 0; } /** One page of a command's retained output rows, from the cursor sequence on. */ export function commandOutputPageQuery( tx: Database, input: SessionCommandIdentity, fromSequence: number, pageRows: number = COMMAND_OUTPUT_PAGE_ROWS, ) { // Bound the scan by the command's client event id prefix in byte order: under // row-level security only leakproof comparisons narrow an index scan, and the // JSON `commandId` key is not one, so filtering on it alone walked every // output chunk of the whole session on each read. ";" is the byte after ":". // The type stays a literal so cached generic plans can still prove the // partial index predicate. const clientIdFrom = commandOutputClientEventIdPrefix(input.commandId); const clientIdBefore = `${clientIdFrom.slice(0, -1)};`; return tx .select({ sequence: schema.sessionEvents.sequence, // Bound legacy payloads in SQL too: LIMIT alone cannot bound one old event. // Oversized historical rows carry explicit loss rather than allocating an // unbounded JSON value in the API process. payload: sql`case when octet_length(${schema.sessionEvents.payload}::text) <= 262144 then ${schema.sessionEvents.payload} else jsonb_build_object('commandReadProjectionGap', true) end`, payloadCodecVersion: schema.sessionEvents.payloadCodecVersion, }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), sql`${schema.sessionEvents.type} = 'sandbox.command.output.delta'`, sql`${schema.sessionEvents.clientEventId} collate "C" >= ${clientIdFrom}`, sql`${schema.sessionEvents.clientEventId} collate "C" < ${clientIdBefore}`, sql`${schema.sessionEvents.payload} ->> 'commandId' = ${input.commandId}`, gte(schema.sessionEvents.sequence, fromSequence), ), ) .orderBy(asc(schema.sessionEvents.sequence)) .limit(pageRows + 1); } /** * The output a read returns from `cursor`. Without `headAndTail` this is one * page from the cursor. With it, output that fits the budget is returned * whole; larger output returns its start (half the budget, at most half the * page rows) as `chunks` and its end as `tail`, with the approximate size of * the omitted middle. Head and tail together never exceed one page of rows. * `nextCursor` then points at the start of the omitted middle, so paging from * it still visits every byte, and `endCursor` follows the newest output. */ async function readCommandOutputWindow( db: Database, input: SessionCommandIdentity & { cursor?: string | undefined; maxOutputBytes?: number | undefined; headAndTail?: boolean | undefined; }, cursor: { sequence: number; offset: number }, ) { return await withRlsContext(db, input, async (tx) => readCommandOutputWindowInTransaction(tx, input, cursor), ); } /** readCommandOutputWindow on a transaction that already holds the RLS scope. * `pageRows` bounds the rows one window reads (head and tail together). */ async 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 }, ) { const pageRows = input.pageRows ?? COMMAND_OUTPUT_PAGE_ROWS; const rows = await commandOutputPageQuery(tx, input, cursor.sequence, pageRows); const page = projectCommandOutputPage({ ...input, rows, pageRows }); if (!input.headAndTail) return page; if (!page.hasMore) return { ...page, endCursor: page.nextCursor }; const budget = input.maxOutputBytes ?? COMMAND_OUTPUT_DEFAULT_BYTES; const head = projectCommandOutputPage({ ...input, rows: rows.slice(0, Math.floor(pageRows / 2)), maxOutputBytes: Math.max(4, Math.floor(budget / 2)), pageRows, }); const headBytes = head.chunks.reduce( (total, chunk) => total + Buffer.byteLength(chunk.chunk, "utf8"), 0, ); const headEnd = parseCommandOutputCursor(head.nextCursor, input.commandId); const tailRowLimit = pageRows - head.chunks.length; const tailRows = await commandOutputTailQuery(tx, input, headEnd.sequence, tailRowLimit); const tail = projectCommandOutputTail({ commandId: input.commandId, from: headEnd, maxOutputBytes: budget - headBytes, rows: tailRows, rowLimit: tailRowLimit, }); const retention = { ...head.retention, gaps: [...new Set([...head.retention.gaps, ...tail.gaps])], }; const merged = () => ({ ...head, chunks: [...head.chunks, ...tail.chunks], nextCursor: tail.endCursor, hasMore: false, retention, endCursor: tail.endCursor, }); // Everything after the head fits: one contiguous window, nothing omitted. if (tail.reachedFrom) return merged(); const textAt = (sequence: number) => { const row = [...rows, ...tailRows].find((candidate) => candidate.sequence === sequence); return row ? commandOutputRowText(row).text : ""; }; let omittedBytes: number; // True only when nothing at all lies between head and tail. let contiguous = false; if (headEnd.sequence === tail.start.sequence) { omittedBytes = Buffer.byteLength( textAt(headEnd.sequence).slice(headEnd.offset, tail.start.offset), "utf8", ); contiguous = omittedBytes === 0; } else { // The rest of the head's last row and the start of the tail's first row // are exact; whole rows in between are estimated from the average size // of the rows this read fetched. const fetched = [...rows, ...tailRows]; const average = fetched.reduce( (total, row) => total + Buffer.byteLength(commandOutputRowText(row).text, "utf8"), 0, ) / Math.max(1, fetched.length); const between = await commandOutputRowsBetween( tx, input, headEnd.sequence, tail.start.sequence, input.omittedRowsCountLimit, ); const boundaryBytes = Buffer.byteLength(textAt(headEnd.sequence).slice(headEnd.offset), "utf8") + Buffer.byteLength(textAt(tail.start.sequence).slice(0, tail.start.offset), "utf8"); // A count stopped at its limit gives no size: the window says "some output". omittedBytes = input.omittedRowsCountLimit !== undefined && between >= input.omittedRowsCountLimit ? 0 : boundaryBytes + Math.round(between * average); contiguous = between === 0 && boundaryBytes === 0; } // Nothing separates head and tail: return them as one window. An estimate // of zero over rows that exist (such as gap rows) still pages them. if (contiguous) return merged(); return { ...head, hasMore: true, retention, omitted: { bytes: omittedBytes, cursor: head.nextCursor }, tail: { chunks: tail.chunks, cursor: tail.startCursor }, endCursor: tail.endCursor, }; } export async 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; }, ) { const cursor = parseCommandOutputCursor(input.cursor, input.commandId); // Validate the budget before any observation mutation. projectCommandOutputPage({ ...input, rows: [] }); const command = await getSessionBackgroundCommand(db, input); if (!command) throw new Error("Background command not found in this session"); const page = await readCommandOutputWindow(db, input, cursor); // Only observe the terminal state actually used by this read. A finish racing // a running read must leave its notification pending. const terminal = command.state === "exited" || command.state === "lost"; // Observation and pending-notice suppression commit together. Once that // receipt exists, retained paging must not take session/event write locks // again: an unrelated writer could otherwise block an already observed read. const observed = terminal && command.completionObservedAt === null ? await observeSessionBackgroundCommandCompletion(db, input) : command; return { commandId: command.id, state: command.state, exitCode: command.exitCode, settlementReason: command.settlementReason, ...(command.failure ? { failure: command.failure } : {}), terminal, completionObservedAt: observed?.completionObservedAt ?? null, ...page, ...(terminal && command.backgroundChildrenStopped ? { notice: CONNECTED_COMMAND_CHILD_CLEANUP_NOTICE } : {}), }; } /** 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 const BACKGROUND_COMMAND_RESULT_OUTPUT_BYTES = 8_192; /** The stored bound (contract: 16 KiB); output plus markers stay well below it. */ const BACKGROUND_COMMAND_RESULT_OUTPUT_MAX_TEXT_BYTES = 12_288; /** Rows that bounded output may read: settlement runs under the session fence. */ const BACKGROUND_COMMAND_RESULT_OUTPUT_ROWS = 16; /** Omitted rows counted for the size estimate, so the read stays bounded for any output. */ const BACKGROUND_COMMAND_RESULT_OMITTED_ROWS_COUNT_LIMIT = 1_000; type CommandOutputWindow = Awaited>; function outputChunksText(chunks: ReadonlyArray<{ chunk: string }>): string { return chunks.map((chunk) => chunk.chunk).join(""); } /** * 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 function commandOutputWindowText(window: CommandOutputWindow): string { let text = outputChunksText(window.chunks); if ("omitted" in window && window.omitted && "tail" in window && window.tail) { if (text !== "" && !text.endsWith("\n")) text += "\n"; const size = window.omitted.bytes > 0 ? `about ${window.omitted.bytes} bytes` : "some output"; text += `[... ${size} omitted; to read them, call command_read with cursor ${window.omitted.cursor} ...]\n`; text += outputChunksText(window.tail.chunks); } else if (window.hasMore) { if (text !== "" && !text.endsWith("\n")) text += "\n"; text += `[... more output follows; to read it, call command_read with cursor ${window.nextCursor} ...]`; } if (window.retention.gaps.length > 0) { if (text !== "" && !text.endsWith("\n")) text += "\n"; text += `[Some output is not retained (${window.retention.gaps.join(", ")}).]`; } return text; } /** * 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 async function backgroundCommandResultOutputInTransaction( tx: SessionActivityDatabase, input: SessionCommandIdentity, ): Promise { try { const text = await tx.transaction(async (savepoint) => commandOutputWindowText( await readCommandOutputWindowInTransaction( savepoint, { ...input, headAndTail: true, maxOutputBytes: BACKGROUND_COMMAND_RESULT_OUTPUT_BYTES, pageRows: BACKGROUND_COMMAND_RESULT_OUTPUT_ROWS, omittedRowsCountLimit: BACKGROUND_COMMAND_RESULT_OMITTED_ROWS_COUNT_LIMIT, }, { sequence: 0, offset: 0 }, ), ), ); return Buffer.byteLength(text, "utf8") <= BACKGROUND_COMMAND_RESULT_OUTPUT_MAX_TEXT_BYTES ? text : null; } catch { return null; } } /** 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; }; const BACKGROUND_COMMAND_RESULT_CLAIM_ROWS = 16; /** Bytes a delivered result's framing (label, command ID, separators) adds to its text. */ const BACKGROUND_COMMAND_RESULT_NOTICE_OVERHEAD_BYTES = 128; /** * 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 async function claimPendingBackgroundCommandResults( db: Database, input: { accountId: string; workspaceId: string; sessionId: string; maxBytes: number }, ): Promise { const updates = schema.sessionSystemUpdates; const pendingResults = and( eq(updates.accountId, input.accountId), eq(updates.workspaceId, input.workspaceId), eq(updates.sessionId, input.sessionId), eq(updates.state, "pending"), eq(updates.kind, "background_command_result"), // Only well-formed results: a malformed row skipped in the loop would // otherwise hold a claim slot (and the session fence) forever. sql`${updates.dedupeKey} = 'background-command-result:' || ${updates.sourceId}`, ); const probe = await withRlsContext(db, input, async (tx) => tx.select({ id: updates.id }).from(updates).where(pendingResults).limit(1), ); if (probe.length === 0) return []; return await withSessionActivityRlsContext(db, input, async (tx) => { const locks = await lockSessionEventWriteRows(tx, { rowProjection: "event", workspaceId: input.workspaceId, controlLock: "share", sessionIds: [input.sessionId], }); if (locks.sessions[0]?.accountId !== input.accountId) return []; const rows = await tx .select() .from(updates) .where(pendingResults) .orderBy(asc(updates.createdAt), asc(updates.id)) .limit(BACKGROUND_COMMAND_RESULT_CLAIM_ROWS) .for("update"); const claimed: ClaimedBackgroundCommandResult[] = []; let bytes = 0; for (const row of rows) { const commandId = row.sourceId; const identity = and( eq(schema.sessionBackgroundCommands.accountId, input.accountId), eq(schema.sessionBackgroundCommands.workspaceId, input.workspaceId), eq(schema.sessionBackgroundCommands.sessionId, input.sessionId), eq(schema.sessionBackgroundCommands.id, commandId), ); const [command] = await tx .select() .from(schema.sessionBackgroundCommands) .where(identity) .for("update") .limit(1); if (!command || (command.state !== "exited" && command.state !== "lost")) continue; const payload = fromPostgresLosslessJson(row.payload, row.payloadCodecVersion) as Record< string, unknown > | null; const summary = fromPostgresLosslessText(row.summary, row.summaryCodecVersion); const output = typeof payload?.output === "string" ? payload.output : null; const notice = typeof payload?.notice === "string" ? payload.notice : null; const size = BACKGROUND_COMMAND_RESULT_NOTICE_OVERHEAD_BYTES + Buffer.byteLength(summary, "utf8") + Buffer.byteLength(output ?? "", "utf8") + Buffer.byteLength(notice ?? "", "utf8"); // One that does not fit stays pending for a result with more room, or // arrives as input; smaller later ones may still go now. if (bytes + size > input.maxBytes) continue; bytes += size; await tx .update(schema.sessionBackgroundCommands) .set({ completionObservedAt: command.completionObservedAt ?? new Date() }) .where(identity); await tx.update(updates).set({ state: "superseded" }).where(eq(updates.id, row.id)); claimed.push({ updateId: row.id, commandId, summary, state: command.state, exitCode: command.exitCode ?? null, output, notice, }); } return claimed; }); }