import type { SessionEvent } from "@opengeni/contracts"; import { canonicalizePersistedHistoryItem, omitOutputOnlyHistoryItemFields } from "@opengeni/codex"; import { and, asc, eq, inArray, sql } from "drizzle-orm"; import type { Database } from "./database"; import { fromPostgresLosslessJson, LOSSLESS_CONTENT_CODEC_VERSION } from "./lossless-json"; import { withBoundSessionEventPayloads } from "./session-event-write-bounds"; import * as schema from "./schema"; import { cancelUnacceptedVideoGenerationsForToolCallsInTransaction } from "./video-generation"; export const TOOL_RESULT_TYPE_BY_CALL_TYPE: Readonly> = { function_call: "function_call_result", computer_call: "computer_call_result", shell_call: "shell_call_output", apply_patch_call: "apply_patch_call_output", tool_search_call: "tool_search_output", }; export function historyCallId(item: Record): string | null { const providerData = item.providerData && typeof item.providerData === "object" && !Array.isArray(item.providerData) ? (item.providerData as Record) : null; // Native tool-search `id` is the provider item id, not the call correlation // id. Validate direct and provider identities before the item-id fallback. const value = [ item.callId, item.call_id, providerData?.callId, providerData?.call_id, item.id, ].find((candidate): candidate is string => typeof candidate === "string" && candidate.length > 0); return value ?? null; } export function historyItemType(item: Record): string | null { return typeof item.type === "string" ? item.type : null; } /** * Person-facing projection of a call whose command was proven never sent. The * call's model-visible result is written separately into history. */ export const NOT_STARTED_TOOL_CALL_EVENT_TEXT = "The command was not started because the sandbox was not ready. Nothing ran, so it is safe to run again."; /** * Model-visible result for a function call whose command was proven never * dispatched. Unlike an interrupted call, nothing ran, so the model may run it * again without inspecting state first. */ export const NOT_STARTED_TOOL_CALL_RESULT_TEXT = "The command was not started because the sandbox was not ready. Nothing ran, so it is safe to run it again."; /** * Recovery reasons where the turn's workspace machine (an Opengeni-owned box * behind a lease) was being saved, replaced or moved, for example after setup * found it could not start programs and asked for a fresh one. */ const WORKSPACE_MACHINE_TRANSITION_REASONS: ReadonlySet = new Set([ "sandbox_lifecycle_transition", "sandbox_deadline_rotation", "sandbox_lease_superseded", ]); /** Person-facing not-started copy when the workspace machine was changing. */ export const WORKSPACE_MACHINE_NOT_STARTED_TOOL_CALL_EVENT_TEXT = "The command was not started because the workspace machine was not ready. Nothing ran, so it is safe to run again."; /** Model-visible not-started result when the workspace machine was changing. */ export const WORKSPACE_MACHINE_NOT_STARTED_TOOL_CALL_RESULT_TEXT = "The command was not started because the workspace machine was not ready. Nothing ran, so it is safe to run it again."; /** The person-facing and model-visible not-started copy for a recovery reason. */ export function notStartedToolCallTexts(reason: string | undefined): { event: string; result: string; } { return reason !== undefined && WORKSPACE_MACHINE_TRANSITION_REASONS.has(reason) ? { event: WORKSPACE_MACHINE_NOT_STARTED_TOOL_CALL_EVENT_TEXT, result: WORKSPACE_MACHINE_NOT_STARTED_TOOL_CALL_RESULT_TEXT, } : { event: NOT_STARTED_TOOL_CALL_EVENT_TEXT, result: NOT_STARTED_TOOL_CALL_RESULT_TEXT }; } /** Provider-valid result for a function call proven never started. */ export function notStartedToolCallResult(input: { callId: string; callItem: Record; /** The recovery reason, which picks the copy (see notStartedToolCallTexts). */ reason?: string; }): Record { const name = typeof input.callItem.name === "string" ? input.callItem.name : "tool"; return { type: "function_call_result", name, ...(typeof input.callItem.namespace === "string" ? { namespace: input.callItem.namespace } : {}), callId: input.callId, status: "incomplete", output: { type: "text", text: notStartedToolCallTexts(input.reason).result }, }; } /** Provider-valid result for a started call whose durable outcome is unknown. */ export function interruptedToolCallResult(input: { callType: string; callId: string; callItem: Record; reason: string; }): Record | null { const message = `Tool execution was interrupted by ${input.reason} before its result was durably recorded. ` + "The side-effect outcome is unknown; inspect actual state before repeating the call."; if (input.callType === "function_call") { const name = typeof input.callItem.name === "string" ? input.callItem.name : "tool"; return { type: "function_call_result", name, ...(typeof input.callItem.namespace === "string" ? { namespace: input.callItem.namespace } : {}), callId: input.callId, status: "incomplete", output: { type: "text", text: message }, }; } if (input.callType === "shell_call") { return { type: "shell_call_output", callId: input.callId, output: [{ stdout: "", stderr: message, outcome: { type: "exit", exitCode: null } }], }; } if (input.callType === "apply_patch_call") { return { type: "apply_patch_call_output", callId: input.callId, status: "failed", output: message, }; } if (input.callType === "computer_call") return null; if (input.callType === "tool_search_call") { const providerData = input.callItem.providerData && typeof input.callItem.providerData === "object" && !Array.isArray(input.callItem.providerData) ? (input.callItem.providerData as Record) : null; const execution = input.callItem.execution === "client" || input.callItem.execution === "server" ? input.callItem.execution : providerData?.execution === "client" || providerData?.execution === "server" ? providerData.execution : null; const providerIdentity = typeof providerData?.call_id === "string" || typeof providerData?.callId === "string"; const snakeId = typeof input.callItem.call_id === "string"; return { type: "tool_search_output", ...(providerIdentity ? { providerData: { call_id: input.callId, ...(execution ? { execution } : {}), }, } : snakeId ? { call_id: input.callId, ...(execution ? { execution } : {}) } : { callId: input.callId, ...(execution ? { execution } : {}) }), status: "incomplete", tools: [], }; } return null; } export type ClosePendingSessionToolCallsInput = { accountId: string; workspaceId: string; sessionId: string; turnId: string; reason: string; sequence: number; now: Date; turnAssociation?: "current" | null; preserveInterruptionRows?: boolean; /** * Function calls with call-scoped proof that their command was never * dispatched. Without a durable result they settle as not started (replay * safe) instead of outcome unknown. */ notStartedCallIds?: readonly string[]; }; function mapEvent(row: typeof schema.sessionEvents.$inferSelect): SessionEvent { return { id: row.id, workspaceId: row.workspaceId, sessionId: row.sessionId, sequence: row.sequence, type: row.type as SessionEvent["type"], payload: fromPostgresLosslessJson(row.payload, row.payloadCodecVersion), occurredAt: row.occurredAt.toISOString(), clientEventId: row.clientEventId, turnId: row.turnId, turnGeneration: row.turnGeneration, turnAttemptId: row.turnAttemptId, turnAssociation: row.turnAssociation as SessionEvent["turnAssociation"], duplicateOfEventId: row.duplicateOfEventId, duplicateReason: row.duplicateReason, }; } /** Same terminal fence for model and programmatic calls. Started effects remain unknown. */ export async function settleInterruptedCodemodeCallsInTransaction( tx: Database, input: Pick< ClosePendingSessionToolCallsInput, "workspaceId" | "sessionId" | "turnId" | "reason" | "now" >, ): Promise { await tx .update(schema.sessionAttemptCodemodeCalls) .set({ state: sql`case when ${schema.sessionAttemptCodemodeCalls.executionStartedAt} is null then 'cancelled' else 'outcome_unknown' end`, claimId: sql`case when ${schema.sessionAttemptCodemodeCalls.executionStartedAt} is null then null else ${schema.sessionAttemptCodemodeCalls.claimId} end`, claimedAt: sql`case when ${schema.sessionAttemptCodemodeCalls.executionStartedAt} is null then null else ${schema.sessionAttemptCodemodeCalls.claimedAt} end`, claimExpiresAt: sql`case when ${schema.sessionAttemptCodemodeCalls.executionStartedAt} is null then null else ${schema.sessionAttemptCodemodeCalls.claimExpiresAt} end`, errorCode: input.reason, errorMessage: "The owning turn ended. Started effects require reconciliation before retrying.", completedAt: input.now, updatedAt: input.now, }) .where( and( eq(schema.sessionAttemptCodemodeCalls.workspaceId, input.workspaceId), eq(schema.sessionAttemptCodemodeCalls.sessionId, input.sessionId), eq(schema.sessionAttemptCodemodeCalls.turnId, input.turnId), inArray(schema.sessionAttemptCodemodeCalls.state, [ "queued", "running", "waiting_for_approval", ]), ), ); } /** * A completed turn owns no live tool call. Consume every receipt of this turn * whose owning attempt has settled (closed, and either quiesced or never * interrupted), so the receipt cannot outlive its turn and later read as * unresolved work (tenancy quiescence, Retry preview, native-origin recovery). * Paired calls are already model-visible and projected; an unpaired call of a * completed turn (for example a hosted approval request the model moved past) * can never be resumed, because only failed/cancelled/superseded settlement or * an approval resume of a nonterminal turn reads these rows. This deletes * ledger rows only: history and events are untouched. The predicate matches * migration 0673. Runs under the settlement's session/turn locks and * workspace tenancy fence, after the completing attempt has been closed. */ export async function consumeSettledPendingToolCallsForCompletedTurnInTransaction( tx: Database, input: { workspaceId: string; sessionId: string; turnId: string }, ): Promise { const deleted = await tx.execute<{ id: string }>(sql` delete from session_pending_tool_calls pending where pending.workspace_id = ${input.workspaceId} and pending.session_id = ${input.sessionId} and pending.turn_id = ${input.turnId} and not exists ( select 1 from session_turn_attempts owner_attempt where owner_attempt.workspace_id = pending.workspace_id and owner_attempt.id = pending.attempt_id and (owner_attempt.state <> 'closed' or (owner_attempt.quiesced_at is null and exists ( select 1 from session_attempt_interruptions interruption where interruption.attempt_id = owner_attempt.id)))) returning pending.id`); return deleted.length; } /** * Close raw tool calls for a logical turn while its owning session/turn locks * are held. Recoverable transitions preserve interruption rows because those * rows are the exact open-suffix resume authority for a replacement attempt; * ordinary in-flight rows still receive durable outcome-unknown settlement. * Terminal and superseding transitions close every row. Durable results win; * repeated settlement is an exact no-op after the selected ledger rows are * deleted. */ export async function closePendingSessionToolCallsInTransaction( tx: Database, input: ClosePendingSessionToolCallsInput, ): Promise<{ sequence: number; events: SessionEvent[]; closed: number; interrupted: number }> { if (!input.preserveInterruptionRows) await settleInterruptedCodemodeCallsInTransaction(tx, input); const notStartedCallIds = new Set(input.notStartedCallIds ?? []); const pendingRows = await tx .select() .from(schema.sessionPendingToolCalls) .where( and( eq(schema.sessionPendingToolCalls.workspaceId, input.workspaceId), eq(schema.sessionPendingToolCalls.sessionId, input.sessionId), eq(schema.sessionPendingToolCalls.turnId, input.turnId), ), ) .orderBy(asc(schema.sessionPendingToolCalls.createdAt), asc(schema.sessionPendingToolCalls.id)) .for("update"); const pending = pendingRows .filter((row) => !(input.preserveInterruptionRows && row.interruptionKind !== null)) .map((row) => ({ ...row, callItem: fromPostgresLosslessJson(row.callItem, row.callItemCodecVersion), resultItem: row.resultItem === null ? null : fromPostgresLosslessJson(row.resultItem, row.resultItemCodecVersion), eventOutput: row.eventOutput === null ? null : fromPostgresLosslessJson(row.eventOutput, row.eventOutputCodecVersion), })); if (pending.length === 0) return { sequence: input.sequence, events: [], closed: 0, interrupted: 0 }; const history = await tx .select({ position: schema.sessionHistoryItems.position, item: schema.sessionHistoryItems.item, itemCodecVersion: schema.sessionHistoryItems.itemCodecVersion, active: schema.sessionHistoryItems.active, }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), eq(schema.sessionHistoryItems.turnId, input.turnId), ), ) .orderBy(asc(schema.sessionHistoryItems.position)); const decodedHistory = history.map((row) => ({ ...row, item: fromPostgresLosslessJson(row.item, row.itemCodecVersion), })); const [{ maxPosition } = { maxPosition: -1 }] = await tx .select({ maxPosition: sql`coalesce(max(${schema.sessionHistoryItems.position}), -1)` }) .from(schema.sessionHistoryItems) .where( and( eq(schema.sessionHistoryItems.workspaceId, input.workspaceId), eq(schema.sessionHistoryItems.sessionId, input.sessionId), ), ); const existingOutputEvents = await tx .select({ callId: sql`${schema.sessionEvents.payload} ->> 'id'` }) .from(schema.sessionEvents) .where( and( eq(schema.sessionEvents.workspaceId, input.workspaceId), eq(schema.sessionEvents.sessionId, input.sessionId), eq(schema.sessionEvents.turnId, input.turnId), eq(schema.sessionEvents.type, "agent.toolCall.output"), ), ); const projectedCallIds = new Set( existingOutputEvents.flatMap(({ callId }) => (callId ? [callId] : [])), ); let nextPosition = Math.floor(Number(maxPosition)) + 1; let sequence = input.sequence; const historyValues: Array = []; const eventValues: Array = []; const resolutions = pending.map((call) => { const resultType = TOOL_RESULT_TYPE_BY_CALL_TYPE[call.callType]; const existingCall = decodedHistory.find( ({ item }) => historyItemType(item) === call.callType && historyCallId(item) === call.callId, ); const existingResult = resultType ? decodedHistory.find( ({ item, position }) => position > (existingCall?.position ?? Number.MAX_SAFE_INTEGER) && historyItemType(item) === resultType && historyCallId(item) === call.callId, ) : undefined; const activeCall = decodedHistory.find( ({ item, active }) => active && historyItemType(item) === call.callType && historyCallId(item) === call.callId, ); const activeResult = resultType ? decodedHistory.find( ({ item, active, position }) => active && position > (activeCall?.position ?? Number.MAX_SAFE_INTEGER) && historyItemType(item) === resultType && historyCallId(item) === call.callId, ) : undefined; const interrupted = !existingResult && !call.resultItem; const notStarted = interrupted && call.callType === "function_call" && notStartedCallIds.has(call.callId); const interruptedResult = notStarted ? notStartedToolCallResult({ callId: call.callId, callItem: call.callItem, reason: input.reason, }) : interruptedToolCallResult({ callType: call.callType, callId: call.callId, callItem: call.callItem, reason: input.reason, }); return { call, existingCall, existingResult, activeCall, activeResult, completeDurablePair: Boolean(existingCall && existingResult), supersededDurablePair: Boolean( existingCall && existingResult && (!existingCall.active || !existingResult.active), ), rawCallIsValid: historyItemType(call.callItem) === call.callType, result: existingResult?.item ?? call.resultItem ?? interruptedResult, interrupted, notStarted, }; }); for (const resolution of resolutions) { if ( !resolution.completeDurablePair && !resolution.activeCall && resolution.result && resolution.rawCallIsValid ) { historyValues.push({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, position: nextPosition++, item: omitOutputOnlyHistoryItemFields(resolution.call.callItem), itemCodecVersion: LOSSLESS_CONTENT_CODEC_VERSION, active: true, }); } } const orderedResults = [...resolutions].sort( (left, right) => (left.call.resultRecordedAt?.getTime() ?? Number.MAX_SAFE_INTEGER) - (right.call.resultRecordedAt?.getTime() ?? Number.MAX_SAFE_INTEGER), ); for (const resolution of orderedResults) { if ( !resolution.completeDurablePair && !resolution.activeResult && resolution.result && resolution.rawCallIsValid ) { historyValues.push({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, position: nextPosition++, item: canonicalizePersistedHistoryItem( resolution.result, resolution.call.modelToolOutputTruncationTokens ?? undefined, ), itemCodecVersion: LOSSLESS_CONTENT_CODEC_VERSION, active: true, }); } // A pair superseded by compaction was already projected during its live // response. Reactivating or re-emitting it would undo the checkpoint and // duplicate the UI output. An active complete pair is different: it can be // the crash point after model-memory persistence but before event publish, // so it keeps the existing durable recovery projection below. if (resolution.supersededDurablePair || projectedCallIds.has(resolution.call.callId)) continue; eventValues.push({ accountId: input.accountId, workspaceId: input.workspaceId, sessionId: input.sessionId, sequence: ++sequence, type: "agent.toolCall.output", turnId: input.turnId, turnGeneration: resolution.call.executionGeneration, turnAttemptId: resolution.call.attemptId, turnAssociation: input.turnAssociation === undefined ? "current" : input.turnAssociation, payload: { id: resolution.call.callId, output: resolution.notStarted ? { isError: true, content: [{ type: "text", text: notStartedToolCallTexts(input.reason).event }], } : resolution.interrupted ? { isError: true, content: [ { type: "text", text: `Tool execution was interrupted by ${input.reason}; its side-effect outcome is unknown.`, }, ], } : resolution.call.eventOutput !== null ? resolution.call.eventOutput.value : ((resolution.existingResult?.item ?? resolution.call.resultItem)?.output ?? resolution.existingResult?.item ?? resolution.call.resultItem), recovery: { interrupted: resolution.interrupted, outcome: resolution.notStarted ? "not_started" : resolution.interrupted ? "unknown" : "durable_result_found", reason: input.reason, unsupportedCallShape: resolution.interrupted && (!resolution.result || !resolution.rawCallIsValid), }, // The stored output was bounded like the live event; keep its marker. ...(!resolution.notStarted && !resolution.interrupted && resolution.call.eventOutput?.truncation !== undefined ? { truncation: resolution.call.eventOutput.truncation } : {}), }, payloadCodecVersion: LOSSLESS_CONTENT_CODEC_VERSION, occurredAt: input.now, }); } if (historyValues.length > 0) await tx.insert(schema.sessionHistoryItems).values(historyValues); const boundEventValues = withBoundSessionEventPayloads(eventValues); const inserted = eventValues.length > 0 ? await tx.insert(schema.sessionEvents).values(boundEventValues).returning() : []; await cancelUnacceptedVideoGenerationsForToolCallsInTransaction(tx, { workspaceId: input.workspaceId, sessionId: input.sessionId, turnId: input.turnId, toolCallIds: pending.map((call) => call.callId), reason: input.reason, now: input.now, }); await tx.delete(schema.sessionPendingToolCalls).where( and( eq(schema.sessionPendingToolCalls.workspaceId, input.workspaceId), eq(schema.sessionPendingToolCalls.sessionId, input.sessionId), eq(schema.sessionPendingToolCalls.turnId, input.turnId), inArray( schema.sessionPendingToolCalls.id, pending.map((call) => call.id), ), ), ); return { sequence, events: inserted.map(mapEvent), closed: pending.length, interrupted: resolutions.filter((resolution) => resolution.interrupted).length, }; }