@opengeni/worker-bundle 0.20.1 → 0.22.0-canary.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/activities/agent-turn/admission.d.ts +52 -0
- package/dist/activities/agent-turn/agent-build.d.ts +89 -0
- package/dist/activities/agent-turn/claim.d.ts +67 -0
- package/dist/activities/agent-turn/codex-capacity.d.ts +40 -0
- package/dist/activities/agent-turn/codex.d.ts +32 -0
- package/dist/activities/agent-turn/compaction-prep.d.ts +88 -0
- package/dist/activities/agent-turn/credential-leases.d.ts +56 -0
- package/dist/activities/agent-turn/errors.d.ts +253 -0
- package/dist/activities/agent-turn/failure-settlement.d.ts +33 -0
- package/dist/activities/agent-turn/file-resources.d.ts +37 -0
- package/dist/activities/agent-turn/finalization.d.ts +42 -0
- package/dist/activities/agent-turn/github-repository-bindings.d.ts +105 -0
- package/dist/activities/agent-turn/governance-model.d.ts +66 -0
- package/dist/activities/agent-turn/history-sink.d.ts +52 -0
- package/dist/activities/agent-turn/history.d.ts +63 -0
- package/dist/activities/agent-turn/media-artifacts.d.ts +145 -0
- package/dist/activities/agent-turn/model-usage.d.ts +218 -0
- package/dist/activities/agent-turn/quiescence.d.ts +135 -0
- package/dist/activities/agent-turn/run-credentials.d.ts +84 -0
- package/dist/activities/agent-turn/run.d.ts +3 -0
- package/dist/activities/agent-turn/sandbox-establish.d.ts +93 -0
- package/dist/activities/agent-turn/sandbox-provision.d.ts +89 -0
- package/dist/activities/agent-turn/sandbox-route.d.ts +151 -0
- package/dist/activities/agent-turn/sandbox-runtime.d.ts +44 -0
- package/dist/activities/agent-turn/stream-attempt.d.ts +107 -0
- package/dist/activities/agent-turn/tool-environment.d.ts +142 -0
- package/dist/activities/agent-turn/tool-policy.d.ts +127 -0
- package/dist/activities/agent-turn/tool-result-spill.d.ts +59 -0
- package/dist/activities/agent-turn/turn-context.d.ts +144 -0
- package/dist/activities/agent-turn/xai-capacity.d.ts +2 -0
- package/dist/activities/agent-turn.d.ts +12 -954
- package/dist/activities/automations.d.ts +16 -0
- package/dist/activities/common.d.ts +1 -1
- package/dist/activities/connector-attachments.d.ts +13 -0
- package/dist/activities/documents.d.ts +1 -0
- package/dist/activities/environment.d.ts +26 -15
- package/dist/activities/generated-images.d.ts +1 -1
- package/dist/activities/git-credential-renewal.d.ts +3 -1
- package/dist/activities/goals.d.ts +4 -1
- package/dist/activities/google-drive-provider.d.ts +29 -0
- package/dist/activities/google-drive-publication.d.ts +66 -0
- package/dist/activities/image-generation-references.d.ts +2 -0
- package/dist/activities/incident-telemetry-authority.d.ts +52 -0
- package/dist/activities/incident-telemetry-preflight.d.ts +71 -0
- package/dist/activities/knowledge-source-sync-driver.d.ts +21 -0
- package/dist/activities/knowledge-source-sync.d.ts +33 -1
- package/dist/activities/mcp-credentials.d.ts +9 -3
- package/dist/activities/open-suffix-resume.d.ts +77 -0
- package/dist/activities/packs.d.ts +3 -11
- package/dist/activities/parent-wake.d.ts +19 -0
- package/dist/activities/retained-screenshot-reaper.d.ts +1 -1
- package/dist/activities/retained-screenshots.d.ts +1 -1
- package/dist/activities/rig-verification.d.ts +1 -1
- package/dist/activities/run-input.d.ts +16 -7
- package/dist/activities/sandbox-images.d.ts +1 -14
- package/dist/activities/sandbox-lease.d.ts +21 -3
- package/dist/activities/scheduled-tasks.d.ts +47 -0
- package/dist/activities/types.d.ts +23 -2
- package/dist/activities/video-media-validation.d.ts +1 -1
- package/dist/activities/video-output-retention.d.ts +1 -2
- package/dist/activities/xai-auth.d.ts +3 -0
- package/dist/{activities-control-SMKF2OBE.js → activities-control-DKG22ONJ.js} +2946 -549
- package/dist/activities-control-DKG22ONJ.js.map +1 -0
- package/dist/activities-control.d.ts +6 -2
- package/dist/activities-turn-4IMC3MAA.js +21326 -0
- package/dist/activities-turn-4IMC3MAA.js.map +1 -0
- package/dist/activities.d.ts +7 -3
- package/dist/artifact-materializer-entry.js +41 -22
- package/dist/artifact-materializer-entry.js.map +1 -1
- package/dist/{chunk-N5TJIFCE.js → chunk-CE7TPKBS.js} +468 -1
- package/dist/chunk-CE7TPKBS.js.map +1 -0
- package/dist/chunk-CNYGVRKF.js +4698 -0
- package/dist/chunk-CNYGVRKF.js.map +1 -0
- package/dist/connection-provider-use.d.ts +18 -0
- package/dist/editable-artifact-materializer.d.ts +4 -3
- package/dist/github-rest-mcp.d.ts +26 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.js +58 -14
- package/dist/index.js.map +1 -1
- package/dist/knowledge-source-sync-activity-policy.d.ts +2 -0
- package/dist/model-context-contributions.d.ts +8 -4
- package/dist/observability-metrics.d.ts +63 -4
- package/dist/opensandbox-kubernetes-inventory.d.ts +21 -0
- package/dist/personal-github-git-credentials.d.ts +9 -0
- package/dist/pr-review-credentials.d.ts +6 -0
- package/dist/sandbox-archive-storage.d.ts +45 -0
- package/dist/sandbox-resume.d.ts +65 -6
- package/dist/sandbox-routing.d.ts +38 -2
- package/dist/scheduled-alert-occurrence.d.ts +33 -0
- package/dist/workflow-bundle.js +87 -28
- package/dist/workflows/activities.d.ts +1 -0
- package/dist/workflows/automations.d.ts +6 -0
- package/dist/workflows/document-index.d.ts +1 -0
- package/dist/workflows.d.ts +1 -0
- package/package.json +17 -17
- package/src/activities/agent-turn/admission.ts +292 -0
- package/src/activities/agent-turn/agent-build.ts +802 -0
- package/src/activities/agent-turn/claim.ts +590 -0
- package/src/activities/agent-turn/codex-capacity.ts +720 -0
- package/src/activities/agent-turn/codex.ts +94 -0
- package/src/activities/agent-turn/compaction-prep.ts +722 -0
- package/src/activities/agent-turn/credential-leases.ts +240 -0
- package/src/activities/agent-turn/errors.ts +1068 -0
- package/src/activities/agent-turn/failure-settlement.ts +1436 -0
- package/src/activities/agent-turn/file-resources.ts +227 -0
- package/src/activities/agent-turn/finalization.ts +754 -0
- package/src/activities/agent-turn/github-repository-bindings.ts +300 -0
- package/src/activities/agent-turn/governance-model.ts +465 -0
- package/src/activities/agent-turn/history-sink.ts +139 -0
- package/src/activities/agent-turn/history.ts +200 -0
- package/src/activities/agent-turn/media-artifacts.ts +359 -0
- package/src/activities/agent-turn/model-usage.ts +823 -0
- package/src/activities/agent-turn/quiescence.ts +353 -0
- package/src/activities/agent-turn/run-credentials.ts +761 -0
- package/src/activities/agent-turn/run.ts +1530 -0
- package/src/activities/agent-turn/sandbox-establish.ts +1207 -0
- package/src/activities/agent-turn/sandbox-provision.ts +569 -0
- package/src/activities/agent-turn/sandbox-route.ts +358 -0
- package/src/activities/agent-turn/sandbox-runtime.ts +731 -0
- package/src/activities/agent-turn/stream-attempt.ts +1670 -0
- package/src/activities/agent-turn/tool-environment.ts +729 -0
- package/src/activities/agent-turn/tool-policy.ts +216 -0
- package/src/activities/agent-turn/tool-result-spill.ts +265 -0
- package/src/activities/agent-turn/turn-context.ts +281 -0
- package/src/activities/agent-turn/xai-capacity.ts +229 -0
- package/src/activities/agent-turn.ts +12 -12575
- package/src/activities/api-integrations.ts +3 -0
- package/src/activities/automations.ts +214 -0
- package/src/activities/codemode-dispatcher.ts +12 -1
- package/src/activities/common.ts +1 -5
- package/src/activities/connector-attachments.ts +168 -0
- package/src/activities/context-compaction.ts +18 -0
- package/src/activities/documents.ts +6 -4
- package/src/activities/environment.ts +151 -55
- package/src/activities/generated-images.ts +26 -11
- package/src/activities/git-credential-renewal.ts +13 -3
- package/src/activities/goals.ts +85 -19
- package/src/activities/google-drive-provider.ts +178 -0
- package/src/activities/google-drive-publication.ts +938 -0
- package/src/activities/image-generation-references.ts +11 -2
- package/src/activities/incident-telemetry-authority.ts +327 -0
- package/src/activities/incident-telemetry-preflight.ts +317 -0
- package/src/activities/knowledge-source-sync-driver.ts +23 -0
- package/src/activities/knowledge-source-sync.ts +556 -40
- package/src/activities/mcp-credentials.ts +191 -17
- package/src/activities/open-suffix-resume.ts +422 -0
- package/src/activities/packs.ts +12 -60
- package/src/activities/parent-wake.ts +64 -14
- package/src/activities/retained-screenshot-reaper.ts +6 -3
- package/src/activities/retained-screenshots.ts +15 -47
- package/src/activities/rig-verification.ts +1 -1
- package/src/activities/run-input.ts +128 -136
- package/src/activities/sandbox-images.ts +7 -166
- package/src/activities/sandbox-lease.ts +406 -15
- package/src/activities/scheduled-tasks.ts +2103 -411
- package/src/activities/session-state.ts +10 -2
- package/src/activities/types.ts +32 -2
- package/src/activities/video-media-validation.ts +3 -3
- package/src/activities/video-output-retention.ts +2 -57
- package/src/activities/xai-auth.ts +8 -0
- package/src/activities-control.ts +2 -0
- package/src/activities.ts +3 -0
- package/src/activity-services.ts +13 -4
- package/src/connection-provider-use.ts +36 -0
- package/src/editable-artifact-materializer-subprocess.ts +25 -14
- package/src/editable-artifact-materializer.ts +29 -18
- package/src/github-rest-mcp.ts +713 -0
- package/src/http.ts +16 -6
- package/src/index.ts +40 -5
- package/src/knowledge-source-sync-activity-policy.ts +2 -0
- package/src/model-context-contributions.ts +33 -10
- package/src/observability-metrics.ts +357 -0
- package/src/opensandbox-kubernetes-inventory.ts +292 -0
- package/src/personal-github-git-credentials.ts +331 -0
- package/src/pr-review-credentials.ts +163 -0
- package/src/sandbox-archive-storage.ts +159 -0
- package/src/sandbox-resume.ts +449 -63
- package/src/sandbox-routing.ts +314 -16
- package/src/scheduled-alert-occurrence.ts +176 -0
- package/src/workflows/activities.ts +18 -2
- package/src/workflows/automations.ts +11 -0
- package/src/workflows/session.ts +13 -3
- package/src/workflows.ts +1 -0
- package/dist/activities-control-SMKF2OBE.js.map +0 -1
- package/dist/activities-turn-IDS3WEHA.js +0 -16532
- package/dist/activities-turn-IDS3WEHA.js.map +0 -1
- package/dist/chunk-N5TJIFCE.js.map +0 -1
- package/dist/chunk-P6Z2SLAA.js +0 -3092
- package/dist/chunk-P6Z2SLAA.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/activities-turn.ts","../src/activities/agent-turn.ts","../src/activities/mcp-credentials.ts","../src/activities/api-integrations.ts","../src/activities/capabilities.ts","../src/activities/codex-fleet-shadow.ts","../src/activities/turn-attempt-fenced.ts","../src/activities/codemode-dispatcher.ts","../src/activities/codex-auth.ts","../src/activities/xai-auth.ts","../src/activities/xai-image-generation.ts","../src/activities/image-generation-operation.ts","../src/activities/generated-images.ts","../src/activities/retained-screenshots.ts","../src/activities/context-compaction.ts","../src/activities/run-input.ts","../src/activities/video-generation-admission.ts","../src/activities/video-reference-staging.ts","../src/activities/video-media-validation.ts","../src/activities/video-generation-credential.ts","../src/activities/environment.ts","../src/activities/git-credential-renewal.ts","../src/activities/expiring-material-renewal.ts","../src/activities/run-credential-renewal.ts","../src/activities/codemode-token-renewal.ts","../src/activities/run-credentials.ts","../src/activities/types.ts","../src/op-journal.ts","../src/model-context-contributions.ts","../src/activities/recording.ts","../src/activities/gateway-image-generation.ts","../src/activities/codex-image-generation.ts","../src/activities/image-generation-references.ts","../src/activities/workspace-capture.ts","../src/model-checkpoint-memory-collector.ts","../src/activities/video-generation-reconciliation.ts","../src/activities/gateway-video-generation.ts","../src/activities/video-output-retention.ts","../src/activities/xai-video-generation.ts"],"sourcesContent":["import { createProductionAgentRuntime, summarizeForCompaction } from \"@opengeni/runtime\";\nimport { createSharedActivityServices } from \"./activity-services\";\nimport { createRunAgentTurnActivity } from \"./activities/agent-turn\";\nimport { createVideoGenerationActivities } from \"./activities/video-generation-reconciliation\";\nimport type { ActivityDependencies, TurnActivityServices } from \"./activities/types\";\nimport { runtimeMetricsHooksForObservability } from \"./observability-metrics\";\n\nfunction createTurnActivityServices(\n dependencies: ActivityDependencies,\n): () => Promise<TurnActivityServices> {\n const shared = createSharedActivityServices(dependencies);\n let servicesPromise: Promise<TurnActivityServices> | null = null;\n return async () => {\n servicesPromise ??= (async () => {\n const services = await shared();\n return {\n ...services,\n runtime:\n dependencies.runtime ??\n createProductionAgentRuntime({\n metrics: runtimeMetricsHooksForObservability(services.observability),\n }),\n summarizeContextForCompaction:\n dependencies.summarizeContextForCompaction ?? summarizeForCompaction,\n };\n })();\n return await servicesPromise;\n };\n}\n\nexport function createTurnActivities(dependencies: ActivityDependencies = {}) {\n return createTurnActivitiesFromServices(createTurnActivityServices(dependencies));\n}\n\nexport function createTurnActivitiesFromServices(services: () => Promise<TurnActivityServices>) {\n return {\n runAgentTurn: createRunAgentTurnActivity(services),\n ...createVideoGenerationActivities(services),\n };\n}\n","import {\n advanceWorkspaceGeneration,\n verifyWorkspaceMutationSettlement,\n applySessionTurnSettlement,\n requestSessionTurnRecovery,\n claimSessionWorkForAttempt,\n applyCreditDebitUpToBalance,\n getBillingBalance,\n getRigName,\n getRigVersion,\n getSandbox,\n readActiveSandbox,\n setActiveSandbox,\n requireFile,\n getSessionEvent,\n getSessionRootId,\n getSessionGoal,\n getHumanInputResumeForEvent,\n getInteractionInterventionResumeForEvent,\n getSessionHumanInputRequest,\n installOrReadTurnExecutionPolicyForAttempt,\n persistAttemptToolCatalog,\n workspaceCodexSubscriptionActive,\n acquireXaiCredentialLease,\n selectXaiCredentialForUse,\n materializeXaiCredentialForRun,\n resolveXaiProviderAccountAuthoritySnapshotForAcceptance,\n heartbeatXaiCredentialLeaseUntil,\n releaseXaiCredentialLease,\n getXaiSessionAccountPin,\n setXaiSessionAccountPin,\n recordXaiSessionLastAccount,\n updateXaiQuotaMetadata,\n XAI_CREDENTIAL_LEASE_TTL_MS,\n acquireCodexCredentialLease,\n armCodexCapacityWait,\n armXaiCapacityWait,\n reconcileXaiCapacityWait,\n heartbeatCodexCredentialLeaseUntil,\n releaseCodexCredentialLease,\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n getCodexRotationSettings,\n getWorkspaceModelPolicy,\n getWorkspaceGrant,\n getWorkspace,\n listCodexAccountStatuses,\n fetchCodexUsageForAccount,\n getSessionCodexState,\n recordSessionActiveCodexCredential,\n setSessionCodexPinInTransaction,\n recordCodexAccountUsageWithWakeTargets,\n quarantineCodexCredentialForLease,\n setActiveCodexCredential,\n resolveWorkspaceMemoryBlock,\n setCodexCredentialExhaustedWithWakeTargets,\n withSessionCodexCapacityMutation,\n countConsecutiveReactiveRotations,\n requireSession,\n recordUsageEvent,\n recordModelCallFact,\n registerPendingSessionToolCall,\n recordPendingSessionToolCallResult,\n clearDurablePendingSessionToolCalls,\n appendSessionHistoryItems,\n isSessionCompactionRequested,\n getActiveSessionHistoryItemsPaged,\n countSessionHistoryItems,\n nextSessionHistoryPosition,\n settleCodexCredentialLeaseLoss,\n settleCodexCredentialFailover,\n upsertSandboxSessionEnvelope,\n setSessionLastInputTokensForTurnAttempt,\n sumUsageQuantity,\n heartbeatLeaseHolder,\n readLease,\n accrueWarmSeconds,\n getMaterializedSandboxFileResources,\n markSandboxFileResourcesMaterialized,\n getGeneratedVideoArtifact,\n listSessionSystemUpdatesForTurn,\n getWorkspaceVideoGenerationPolicy,\n loadWorkspaceVercelAiGatewayCredentialLease,\n areGitHubRepositoriesAllowedForWorkspace,\n SandboxLeaseRecoveryBlockedError,\n SandboxLeaseSupersededError,\n SandboxLeaseTransitionError,\n SandboxImageConflictError,\n ActiveSessionHistoryLimitExceededError,\n ApprovalRunStateLimitExceededError,\n isRetryableDatabaseTransportFailure,\n isSessionEventPersistenceError,\n getEnrollment,\n abandonRecordingForTurnAttempt,\n commitSessionAttemptQuiescence,\n getOrCreateCompanyProfileSnapshot,\n getOrCreatePreferenceRegistrySnapshot,\n getOrCreateWorkspaceInstructionPolicySnapshot,\n PreferenceRegistryInitiatorError,\n beginConnectorActionExecution,\n completeConnectorActionExecution,\n prepareConnectorActionApproval,\n withCodexAppsRequestAuthorization,\n type AppendEventInput,\n type ActiveSandboxPointer,\n type SandboxRecord,\n type CodexCredentialLeaseResult,\n type CodexCredentialLeaseSelectionContext,\n type ApplySessionTurnSettlementInput,\n type ApiIntegrationRuntime,\n type SessionAttemptQuiescenceCommit,\n type SessionTurnRecordingSettlement,\n} from \"@opengeni/db\";\nimport { appendAndPublishTurnEventsFenced, publishDurableSessionEvents } from \"@opengeni/events\";\nimport { sandboxLeaseTelemetryKey, sandboxOperationMetricObserver } from \"@opengeni/observability\";\nimport {\n sandboxStateEntryFromRunState,\n maxTurnsExceededRunState,\n modelResponseServiceTierFromSdkEvent,\n modelTerminalResponseFromSdkEvent,\n normalizeModelCallUsage,\n normalizeSdkEvent,\n normalizeProtocolJsonValue,\n compactMcpResultCustomDataRunState,\n releaseMcpResultCustomDataFromSdkEvent,\n projectHistoryForProvider,\n restoreGenericDispatchHistoryItems,\n sanitizeHistoryItemsForModel,\n projectModelInputForCapabilities,\n appendPersistentSessionSettings,\n appendSessionGoal,\n appendSessionInstructions,\n appendWorkspaceGovernance,\n appendWorkspaceMemory,\n composeAgentInstructions,\n hasActiveWorkspaceInstructionPolicy,\n renderWorkspaceGovernanceContext,\n requestRemoteCompactionV2,\n serializedToolsForRemoteCompaction,\n REMOTE_COMPACTION_V2_BETA_FEATURE,\n REMOTE_COMPACTION_V2_IMPLEMENTATION,\n CompactionProviderResponseError,\n EmptyCompactionSummaryError,\n ensureModalRegistryImage,\n findCompactionNeededError,\n materializeSandboxFileDownloads,\n materializeRunCredentials,\n clearRunCredentials,\n clearRunCredentialsForAttempt,\n withRunCredentialsSession,\n refreshGitCredentialBindingTokenFiles,\n refreshCodemodeTokenFile,\n codemodeTokenFileFromEnvironment,\n sandboxFileDownloadFailureNote,\n SUMMARY_BUFFER_TOKENS,\n isMcpRequestTimeoutError,\n isMcpTransportConnectivityError,\n runOwnedSandboxSetup,\n RoutingMutationOutcomeUnknownError,\n WorkspaceArchiveIntegrityError,\n sdkBackendIdForSandboxBackend,\n swapTargetEstablishability,\n type SandboxFileDownload,\n type SandboxFileDownloadFailure,\n type OpenGeniRuntime,\n type ComputerToolMode,\n type RetainableSessionImageOutputHook,\n type ModelResponseUsage,\n type ModelCallUsageInput,\n type ModelCallUsageNormalization,\n type BuildAgentOptions,\n type ConnectorActionPolicyHooks,\n type TurnToolCancellationFence,\n type BackendUnresolvableCode,\n type EstablishedSandboxSession,\n type GitCredentialTokenWriterSession,\n type LazyToolTransport,\n type NormalizedRunCredentialMaterial,\n type RunCredentialCommandSession,\n type CodemodeTokenWriterSession,\n createFirstPartyInteractionAttemptToolDefinitions,\n deleteRecordingArtifacts,\n stopRecording as stopRecordingOnBox,\n} from \"@opengeni/runtime\";\nimport { connectionTokenResolverForTurn } from \"./mcp-credentials\";\nimport { buildApiIntegrationServersForTurn } from \"./api-integrations\";\nimport {\n allowedFirstPartyMcpToolsForSession,\n assertTurnExecutionPolicyMatchesConfigV1,\n calculateGatewayReportedCostBreakdown,\n calculateModelUsageCostBreakdown,\n configuredModelPricingSchedules,\n configuredStaticUsageLimits,\n responseSatisfiesLatencyMode,\n sandboxLifecycleTransitionWaitMs,\n sandboxWarmRateMicrosPerSecond,\n serviceTierForLatencyMode,\n environmentsEncryptionKeyBytes,\n settingsWithResolvedModelContext,\n resolveTurnExecutionPolicyV1,\n OPENGENI_GATEWAY_MODELS,\n OPENGENI_GATEWAY_PROVIDER_ID,\n WORKSPACE_GATEWAY_PROVIDER_ID,\n codemodeWorkspaceUrl,\n isDirectOpenAiApiBaseUrl,\n resolveModelProvider,\n type ModelUsageInput,\n type ModelProviderApi,\n type RegistryProviderKind,\n type Settings,\n} from \"@opengeni/config\";\nimport { ApplicationFailure, CancelledFailure } from \"@temporalio/activity\";\nimport {\n settingsWithCodexCredential,\n settingsWithEnabledCapabilityMcpServers,\n settingsWithSessionMcpServersForRun,\n settingsWithWorkspaceGatewayCredential,\n withXaiSubscriptionProvider,\n} from \"./capabilities\";\nimport {\n CODEX_USAGE_EXHAUSTED_PCT,\n authoritativeCodexCapacityResetAt,\n chooseRotationActive,\n classifyCodexPin,\n computeIdleDelayMs,\n computeReactiveRotationResume,\n shardCredentialForSession,\n earliestCodexReset,\n isCodexCredentialEligible,\n selectCodexCredentialLeaseForTurn,\n type CodexRotationStrategy,\n type RotationDecision,\n} from \"./codex-rotation\";\nimport {\n codexFleetShadowDecisionMetricLabelsV1,\n codexFleetShadowErrorMetricLabelsV1,\n publishCodexFleetShadowDecisionV1,\n} from \"./codex-fleet-shadow\";\nimport type { CodexAccountStatus } from \"@opengeni/db\";\nimport { CodemodeAttemptDispatcher } from \"./codemode-dispatcher\";\nimport { buildCodexTokenResolver } from \"./codex-auth\";\nimport {\n refreshCodexUsageAndRepairCapacityWaiters,\n signalCodexCapacityWakeTargets,\n signalPendingCodexCapacityWakeTargets,\n} from \"./codex-capacity\";\nimport {\n buildModelResolver,\n CODEX_CLIENT_VERSION,\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_PROVIDER_ID,\n CodexReloginRequired,\n classifyCodexEncryptedArtifactRejection,\n classifyCodexResponseTimeoutError,\n classifyCodexUsageLimitError,\n codexRequestStorage,\n isCodexTransportError,\n opaqueProviderArtifactFingerprint,\n withCodexRequestOverrides,\n selectCodexCredentialId,\n type CodexRequestContext,\n type CodexUsageHeaderSnapshot,\n} from \"@opengeni/codex\";\nimport { mergeResourceRefs } from \"./common\";\nimport {\n fetchXaiSubscriptionQuota,\n isXaiSubscriptionTransportError,\n XaiSubscriptionReloginRequired,\n xaiSubscriptionRequestStorage,\n type XaiSubscriptionRequestContext,\n} from \"@opengeni/xai-subscription\";\nimport { buildXaiTurnRequestAuthorization } from \"./xai-auth\";\nimport { executeXaiSubscriptionImageGeneration } from \"./xai-image-generation\";\nimport {\n assertSessionAllowsProductModel,\n defaultSessionMcpServerIds,\n directPersonalConnectionSubjectId,\n rigProviderImageContentHash,\n resolveCodexAppsCredentialIdForRun,\n withFrozenPersonalConnectionDelegations,\n resolveSessionToolPolicy,\n videoGenerationCapabilitiesForPolicy,\n} from \"@opengeni/core\";\nimport { maybeCompactContext, settleFailedContextCompactionLandmark } from \"./context-compaction\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\nimport {\n admitVideoGenerationRequest,\n managedVideoGenerationCredentialLease,\n xaiVideoGenerationCredentialLease,\n type VideoGenerationCredentialLease,\n} from \"./video-generation-admission\";\nimport { VideoReferenceInputError } from \"./video-reference-staging\";\nimport {\n assertGitCredentialRenewalTransportUnchanged,\n gitCredentialAuthorityForTurn,\n gitHubTokenMintSelections,\n loadWorkspaceEnvironmentForRunWithCredentials,\n mintSandboxCodemodeToken,\n mintRunGitCredentials,\n mintRunGitCredentialBinding,\n sandboxEnvironmentForRun,\n type GitHubTokenMintAuthorization,\n type MintedRunGitCredentials,\n} from \"./environment\";\nimport {\n startGitCredentialRenewalLoop,\n type GitCredentialRenewalController,\n} from \"./git-credential-renewal\";\nimport {\n RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n startRunCredentialRenewalLoop,\n type RunCredentialRenewalController,\n} from \"./run-credential-renewal\";\nimport {\n CODEMODE_TOKEN_EXPIRY_LEAD_MS,\n startCodemodeTokenRenewalLoop,\n type CodemodeTokenRenewalController,\n} from \"./codemode-token-renewal\";\nimport {\n bindRunCredentialResolver,\n runCredentialAuthNeededPayloads,\n runCredentialModelNote,\n} from \"./run-credentials\";\nimport { withFirstPartyTools } from \"./goals\";\nimport {\n mergeRigDefaultVariableSetEnvironment,\n rigProviderImageSourceImage,\n resolveWorkspacePackRuntime,\n resolveWorkspaceInstalledSkillRuntime,\n settingsWithPackSandboxImage,\n settingsWithRigImage,\n settingsWithRigProviderImage,\n} from \"./packs\";\nimport { deliverFailedChildTurnToParent } from \"./parent-wake\";\nimport {\n createModelHistoryAttachmentProjector,\n turnInput,\n type ModelAttachmentInputPolicy,\n} from \"./run-input\";\nimport {\n createRuntimeBatcher,\n currentActivityContext,\n nextStreamEvent,\n startActivityHeartbeat,\n} from \"./streaming\";\nimport type {\n TurnActivityServices as ActivityServices,\n EscapedMcpTimeoutRecoveryDetail,\n PreClaimFailureDetail,\n RunAgentTurnInput,\n RunAgentTurnResult,\n SessionAttemptQuiescenceProof,\n} from \"./types\";\nimport {\n ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE,\n ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE,\n PRE_CLAIM_FAILURE_MESSAGE,\n PRE_CLAIM_FAILURE_TYPE,\n} from \"./types\";\nimport {\n resumeBoxForTurn,\n sandboxLeaseHolderIdForAttempt,\n maybePersistWarmWorkspaceSnapshot,\n waitForWarmSnapshot,\n SandboxWarmingTimeoutError,\n type ResumedTurnSandbox,\n type TurnSandboxLeaseHolderId,\n} from \"../sandbox-resume\";\nimport {\n wrapTurnBoxWithRouting,\n wrapLazyTurnBoxWithRouting,\n establishSelfhostedTurnSession,\n routingEnabled,\n lazyProvisionEnabled,\n} from \"../sandbox-routing\";\nimport { makeTurnOpJournal, type TurnHeartbeatDetails } from \"../op-journal\";\nimport {\n makeMachineOpObserver,\n modelCallAccountContext,\n recordBatchFlush,\n recordContextCompaction,\n recordCreditMicros,\n recordModelCacheTokens,\n recordModelInputTokens,\n recordModelRequestPhase,\n recordCompanyBrainContributions,\n recordSessionEventAppendLatency,\n recordSessionEventPublishLatency,\n recordTurnSandboxEstablishPolicy,\n recordTurnStartupPhase,\n recordTurnWorkerPreparationTotal,\n runtimeMetricsHooksForObservability,\n StreamTimingMetrics,\n turnLifecycleMetricsFor,\n type TurnOutcome,\n type TurnSandboxEstablishReason,\n} from \"../observability-metrics\";\nimport { buildCompanyBrainContributionReceipt } from \"../model-context-contributions\";\nimport {\n beginRecording,\n discardUnpublishedRecording,\n prepareRecordingForSettlement,\n type ActiveRecording,\n} from \"./recording\";\nimport {\n collectRetainedScreenshotReceipts,\n collectRetainedScreenshotRunStateReceipts,\n compactRetainedScreenshotHistory,\n compactRetainedScreenshotRunState,\n materializeRetainedScreenshotHistory,\n materializeRetainedScreenshotRunState,\n sdkEventContainsInlineImage,\n retainComputerScreenshot,\n toolOutputContainsInlineImage,\n typedScreenshotFromSdkEvent,\n typedScreenshotFromToolOutput,\n unavailableRetainedSessionImage,\n} from \"./retained-screenshots\";\nimport {\n assertGeneratedImageHistoryRetained,\n collectGeneratedImageReceipts,\n collectGeneratedImageArtifactReceipts,\n collectGeneratedImageRunStateArtifactReceipts,\n compactGeneratedImageHistory,\n compactGeneratedImageRunState,\n compactGeneratedImageSdkEvent,\n generatedImageFromSdkEvent,\n generatedImagesFromHistory,\n isCompletedGeneratedImageSdkEvent,\n projectGeneratedImageHistoryForModel,\n projectGeneratedImageRunStateForModel,\n retainGeneratedImage,\n type GeneratedImageReceipt,\n type GeneratedImageOutput,\n} from \"./generated-images\";\nimport { executeGatewayImageGeneration } from \"./gateway-image-generation\";\nimport { executeCodexImageGeneration } from \"./codex-image-generation\";\nimport { imageProviderBindingHash } from \"./image-generation-operation\";\nimport { resolveImageGenerationReferences } from \"./image-generation-references\";\nimport { captureWorkspaceRevision, openFreshWorkspaceCaptureSession } from \"./workspace-capture\";\nimport { SandboxChannelAService, type ChannelASession } from \"@opengeni/runtime/sandbox\";\nimport { createObjectStorage, type ObjectStorage } from \"@opengeni/storage\";\nimport {\n desktopCapableBackend,\n sandboxRunAs,\n WorkspaceModelPolicyBlockedError,\n} from \"@opengeni/runtime\";\nimport {\n CAPABILITY_DESCRIPTORS,\n evaluateWorkspaceModelPolicy,\n readTurnExecutionPolicyV1,\n resolveWorkspaceAgentHumanInputEnabled,\n resolveWorkspaceMemoryPromptMode,\n resourceMountPath,\n VideoGenerationRejectedResult,\n type LatencyMode,\n type ResourceRef,\n type RetainedArtifactMetadata,\n type MediaGenerationResult,\n type SessionEvent,\n type SessionEventType,\n type SessionStatus,\n type SessionTurn,\n type ToolAuthNeededPayload,\n type TurnExecutionPolicyV1,\n type XaiProviderAccountAuthoritySnapshotV1,\n} from \"@opengeni/contracts\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { createModelCheckpointMemoryCollector } from \"../model-checkpoint-memory-collector\";\n\n// Retryable provider connectivity/5xx failures start quickly and back off to\n// this ceiling. Explicit rate limits retain the minute-granular fallback.\nexport const PROVIDER_BACKPRESSURE_DELAY_MS = 60_000;\nconst PROVIDER_CONNECTIVITY_BACKOFF_MS = [2_000, 5_000, 15_000, 30_000, 60_000] as const;\n\nexport class WorkspaceHumanInputDisabledError extends Error {\n constructor(kind: \"resume\" | \"interruption\") {\n super(`Workspace policy rejects structured human-input ${kind}`);\n this.name = \"WorkspaceHumanInputDisabledError\";\n }\n}\n\nexport function assertWorkspaceHumanInputAllowed(\n enabled: boolean,\n kind: \"resume\" | \"interruption\",\n attempted: boolean,\n): void {\n if (!enabled && attempted) throw new WorkspaceHumanInputDisabledError(kind);\n}\n\n/** Broad personal lookup is allowed only for a direct human/API command. */\nexport function credentialSubjectIdForTurnInitiator(\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): string | undefined {\n return directPersonalConnectionSubjectId(turn);\n}\n\n/**\n * Direct authenticated-human work is the persisted human source with subject\n * authority and no inherited agent or legacy provenance. Use this complete\n * immutable turn authority instead of inferring causality from a\n * `user.message` event shape or the root initiator alone.\n */\nexport function isDirectHumanTurnInitiation(\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): boolean {\n if ((turn.source !== \"user\" && turn.source !== \"api\") || turn.initiator.kind !== \"subject\") {\n return false;\n }\n return ![\"via\", \"viaTruncated\", \"provenanceError\", \"backfill\"].some((key) =>\n Object.prototype.hasOwnProperty.call(turn.initiatorContext, key),\n );\n}\n\n/**\n * A disconnected personal Slack server is prepared best-effort before the model\n * runs. Its initialize/tools-list credential miss is setup state, not evidence\n * that an unrelated turn wants Slack. Keep concrete tool-call failures\n * actionable, but gate setup-time Slack prompts to a human message that names\n * Slack explicitly. Other providers retain the existing generic behavior.\n */\nexport function shouldPublishToolAuthNeededForTurn(\n payload: Pick<ToolAuthNeededPayload, \"providerDomain\" | \"toolName\">,\n trigger: Pick<SessionEvent, \"type\" | \"payload\">,\n turn: Pick<SessionTurn, \"source\" | \"initiator\" | \"initiatorContext\">,\n): boolean {\n if (typeof payload.toolName === \"string\" && payload.toolName.trim().length > 0) {\n return true;\n }\n const providerDomain = payload.providerDomain.trim().toLowerCase();\n const isSlack = providerDomain === \"slack.com\" || providerDomain.endsWith(\".slack.com\");\n if (!isSlack) {\n return true;\n }\n if (!isDirectHumanTurnInitiation(turn) || trigger.type !== \"user.message\") {\n return false;\n }\n const text = (trigger.payload as { text?: unknown }).text;\n return typeof text === \"string\" && /\\bslack\\b/i.test(text);\n}\n\nexport function turnExecutionPolicyBillingIdentity(policy: TurnExecutionPolicyV1): {\n externallyBilled: boolean;\n codexSubscription: boolean;\n xaiSubscription: boolean;\n} {\n return {\n externallyBilled: policy.billing.metering === \"external\",\n codexSubscription:\n policy.providerId === \"codex-subscription\" &&\n policy.credentialSource.kind === \"connected_subscription\" &&\n policy.credentialSource.provider === \"codex\",\n xaiSubscription:\n policy.providerId === \"supergrok-subscription\" &&\n policy.credentialSource.kind === \"connected_subscription\" &&\n policy.credentialSource.provider === \"xai\",\n };\n}\n\nexport function legacyTurnExecutionPolicyInput(\n turn: Pick<SessionTurn, \"source\" | \"model\" | \"reasoningEffort\" | \"latencyMode\">,\n): Parameters<typeof resolveTurnExecutionPolicyV1>[1] {\n const explicit = turn.source === \"user\" || turn.source === \"api\";\n return {\n modelId: turn.model,\n requestedModelId: explicit ? turn.model : null,\n modelSource: explicit ? \"explicit\" : \"continuation\",\n reasoningEffort: turn.reasoningEffort,\n reasoningSource: explicit ? \"explicit\" : \"continuation\",\n latencyMode: turn.latencyMode,\n latencyModeSource: explicit ? \"explicit\" : \"continuation\",\n };\n}\n\n/** A retryable provider fault recovers the accepted turn itself. Goal state is\n * irrelevant: autonomous continuation and infrastructure recovery are separate\n * concerns. */\nexport function providerRecoveryResult(input: {\n failureCode: string | undefined;\n attemptNumber: number;\n retryAfterMs?: number | null;\n}): {\n status: \"recovering\";\n continueDelayMs: number;\n} {\n const providerDelay =\n input.retryAfterMs !== null &&\n input.retryAfterMs !== undefined &&\n Number.isFinite(input.retryAfterMs) &&\n input.retryAfterMs > 0\n ? Math.ceil(input.retryAfterMs)\n : null;\n const continueDelayMs =\n input.failureCode === \"provider_rate_limited\"\n ? (providerDelay ?? PROVIDER_BACKPRESSURE_DELAY_MS)\n : input.failureCode === \"provider_unavailable\" ||\n input.failureCode === \"upstream_connectivity_unavailable\" ||\n input.failureCode === \"mcp_transport_unavailable\"\n ? Math.max(\n providerDelay ?? 0,\n PROVIDER_CONNECTIVITY_BACKOFF_MS[\n Math.min(\n Math.max(Math.trunc(input.attemptNumber) - 1, 0),\n PROVIDER_CONNECTIVITY_BACKOFF_MS.length - 1,\n )\n ]!,\n )\n : PROVIDER_BACKPRESSURE_DELAY_MS;\n return {\n status: \"recovering\",\n continueDelayMs,\n };\n}\n\nexport function providerRecoveryCountFromMetadata(metadata: Record<string, unknown>): number {\n const value = metadata.providerRecoveryCount;\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : 0;\n}\n\nfunction headerValue(headers: unknown, name: string): string | null {\n if (!headers || typeof headers !== \"object\") return null;\n const getter = (headers as { get?: unknown }).get;\n if (typeof getter === \"function\") {\n const value = getter.call(headers, name);\n return typeof value === \"string\" ? value : null;\n }\n const target = name.toLowerCase();\n const entry = Object.entries(headers as Record<string, unknown>).find(\n ([key, value]) => key.toLowerCase() === target && typeof value === \"string\",\n );\n return typeof entry?.[1] === \"string\" ? entry[1] : null;\n}\n\n/** Read a provider Retry-After hint without retaining response headers/body. */\nexport function providerRetryAfterMs(error: unknown, nowMs = Date.now()): number | null {\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const directSeconds = Number(\n value.retry_after_seconds ?? body?.retry_after_seconds ?? value.retryAfterSeconds,\n );\n const header =\n headerValue(value.headers, \"retry-after\") ??\n headerValue(value.responseHeaders, \"retry-after\") ??\n headerValue(body?.headers, \"retry-after\");\n const headerSeconds = header === null ? Number.NaN : Number(header);\n const headerDate =\n header !== null && !Number.isFinite(headerSeconds) ? Date.parse(header) : Number.NaN;\n const seconds = Number.isFinite(directSeconds)\n ? directSeconds\n : Number.isFinite(headerSeconds)\n ? headerSeconds\n : Number.isFinite(headerDate)\n ? Math.max(0, (headerDate - nowMs) / 1_000)\n : Number.NaN;\n if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1_000);\n current = value.cause;\n }\n return null;\n}\n\n/**\n * Tell the model when durable MCP policy references are unavailable for this\n * exact turn. The policy projection already bounds and validates these ids;\n * this notice prevents a graceful runtime drop from becoming a silent source-\n * of-truth substitution or a false claim that the disconnected system was read.\n */\nexport function unavailableMcpTurnInstructions(input: {\n droppedIds: readonly string[];\n droppedCount: number;\n}): string | undefined {\n if (input.droppedCount <= 0) {\n return undefined;\n }\n const omittedCount = Math.max(0, input.droppedCount - input.droppedIds.length);\n const listed = input.droppedIds.map((id) => `\"${id}\"`).join(\", \");\n const inventory = listed\n ? `${listed}${omittedCount > 0 ? `, plus ${omittedCount} additional unavailable server(s)` : \"\"}`\n : `${input.droppedCount} unavailable server(s)`;\n return `MCP capability availability for this turn: the following session-selected server(s) are disconnected or no longer registered and were skipped: ${inventory}. Do not claim to have read or updated those systems. If the task depends on one as a source of truth, explain the limitation and ask the user to reconnect it or select another authoritative source; continue with unaffected work only when safe.`;\n}\n\n/**\n * Preserve one precise recovery obligation across Temporal's activity boundary.\n * This is intentionally narrower than the ordinary retryable-provider path:\n * only a recovered turn (generation > 1) whose MCP timeout happened before a\n * model request may ask the workflow's DB-only control activity to finish the\n * same-turn checkpoint. The original transport/recovery errors are excluded\n * from details so raw MCP response data can never enter workflow history.\n */\nexport function escapedMcpTimeoutRecoveryFailure(input: {\n failureCode: string | undefined;\n modelRequestStarted: boolean;\n detail: EscapedMcpTimeoutRecoveryDetail;\n}): ApplicationFailure | null {\n if (\n input.failureCode !== \"mcp_transport_timeout\" ||\n input.modelRequestStarted ||\n !Number.isSafeInteger(input.detail.executionGeneration) ||\n input.detail.executionGeneration <= 1\n ) {\n return null;\n }\n return ApplicationFailure.create({\n message: ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE,\n type: ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE,\n nonRetryable: true,\n details: [input.detail],\n });\n}\n\n/**\n * Convert the atomic claim transaction's failure into a small, stable\n * Temporal wire contract. The original error remains in activity diagnostics,\n * but SQL text, parameters, and arbitrary invariant messages never enter\n * workflow history. Contention and operational database unavailability are\n * safe to re-read after backoff because the claim transaction contains no\n * model/tool effects; permanent database and state failures require terminal\n * settlement.\n */\nexport function preClaimAdmissionFailure(error: unknown): ApplicationFailure {\n const persistenceFailure = isSessionEventPersistenceError(error) ? error : null;\n const sqlState = persistenceFailure?.details.sqlState ?? null;\n const rawTransportFailure = sqlState === null && isRetryableDatabaseTransportFailure(error);\n // The database transaction itself retries only the two contention failures\n // proven safe for immediate replay. Once the activity has failed, the\n // workflow may also retry operational outages after a durable re-read and\n // bounded delay. Unknown driver/database failures stay recoverable because\n // they commonly represent a lost connection; known constraint, auth, and\n // application SQLSTATEs are permanent and must not create an infinite loop.\n const retryable = Boolean(\n rawTransportFailure ||\n (persistenceFailure &&\n (sqlState === null ||\n sqlState.startsWith(\"08\") ||\n sqlState.startsWith(\"40\") ||\n sqlState.startsWith(\"53\") ||\n sqlState === \"55P03\" ||\n sqlState === \"57014\" ||\n sqlState === \"57P01\" ||\n sqlState === \"57P02\" ||\n sqlState === \"57P03\" ||\n sqlState.startsWith(\"58\"))),\n );\n const detail: PreClaimFailureDetail = {\n disposition: retryable ? \"retryable\" : \"permanent\",\n code:\n persistenceFailure?.details.code ?? (rawTransportFailure ? \"db_failure\" : \"claim_invariant\"),\n };\n return ApplicationFailure.create({\n message: PRE_CLAIM_FAILURE_MESSAGE,\n type: PRE_CLAIM_FAILURE_TYPE,\n nonRetryable: true,\n details: [detail],\n });\n}\n\n/**\n * Resolve which Codex account a turn runs on (multi-account P1): session-pin >\n * workspace-active. No rotation in P1. The selected id must still be in the\n * connected set — a disconnected pin was FK-nulled, so a stale id can't appear,\n * but we guard anyway. Returns null when there is no usable account (the turn\n * then fails with the existing relogin error path).\n */\nexport function selectCodexCredentialForTurn(args: {\n sessionPinnedCredentialId: string | null;\n activeCredentialId: string | null;\n connectedIds: Set<string>;\n}): string | null {\n return selectCodexCredentialId(args);\n}\n\nexport function filterUnmaterializedSandboxFileDownloads(\n downloads: SandboxFileDownload[],\n materializedFileIds: Set<string>,\n): SandboxFileDownload[] {\n if (downloads.length === 0 || materializedFileIds.size === 0) {\n return downloads;\n }\n return downloads.filter((download) => !materializedFileIds.has(download.fileId));\n}\n\nexport function sandboxFileMaterializationOutcome(\n failures: readonly SandboxFileDownloadFailure[],\n): \"completed\" | \"failed\" {\n return failures.length === 0 ? \"completed\" : \"failed\";\n}\n\n/** Fixed-length one-way tenant correlation for metrics/alerts; never a raw id. */\nexport function codexWorkspaceMetricKey(workspaceId: string): string {\n return createHash(\"sha256\").update(workspaceId).digest(\"hex\").slice(0, 12);\n}\n\n/** Stable public request identity across partial resumes and activity retries. */\nexport function stableHumanInputRequestId(\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n const hex = createHash(\"sha256\")\n .update(\"opengeni-human-input-v1\\0\")\n .update(sessionId)\n .update(\"\\0\")\n .update(turnId)\n .update(\"\\0\")\n .update(toolCallId)\n .digest(\"hex\")\n .slice(0, 32)\n .split(\"\");\n hex[12] = \"5\";\n hex[16] = [\"8\", \"9\", \"a\", \"b\"][Number.parseInt(hex[16] ?? \"0\", 16) % 4] ?? \"8\";\n const value = hex.join(\"\");\n return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;\n}\n\nexport function stableInteractionInterventionId(\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n return stableInteractionInterventionUuid(\n \"opengeni-interaction-intervention-v1\",\n sessionId,\n turnId,\n toolCallId,\n );\n}\n\nexport function stableInteractionInterventionOperationId(\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n return stableInteractionInterventionUuid(\n \"opengeni-interaction-intervention-operation-v1\",\n sessionId,\n turnId,\n toolCallId,\n );\n}\n\nfunction stableInteractionInterventionUuid(\n namespace: string,\n sessionId: string,\n turnId: string,\n toolCallId: string,\n): string {\n const hex = createHash(\"sha256\")\n .update(namespace)\n .update(\"\\0\")\n .update(sessionId)\n .update(\"\\0\")\n .update(turnId)\n .update(\"\\0\")\n .update(toolCallId)\n .digest(\"hex\")\n .slice(0, 32)\n .split(\"\");\n hex[12] = \"5\";\n hex[16] = [\"8\", \"9\", \"a\", \"b\"][Number.parseInt(hex[16] ?? \"0\", 16) % 4] ?? \"8\";\n const value = hex.join(\"\");\n return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;\n}\n\n/**\n * True when this activity attempt was cancelled because its hosting worker is\n * shutting down gracefully (SIGTERM during a deploy), as opposed to a\n * workflow-requested Pause/Steer cancellation or a server-side timeout.\n */\nexport function isWorkerShutdownCancellation(error: unknown): boolean {\n return error instanceof CancelledFailure && error.message === \"WORKER_SHUTDOWN\";\n}\n\n/**\n * Review captures and protective snapshots are cache/persistence housekeeping,\n * never part of cancellation correctness. A control-fenced or Temporal-cancelled\n * attempt must release its physical activity promptly so Steer/Pause can advance.\n */\nexport function shouldRunTurnEndWorkspacePersistence(input: {\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\";\n cancellationRequested: boolean;\n}): boolean {\n return input.activityStatus !== \"cancelled\" && !input.cancellationRequested;\n}\n\n/**\n * Temporal cancellation is delivery/transport state, never proof that the\n * dying activity crossed its mandatory sandbox-tool fence. If that fence\n * fails, surface the fence failure instead of retaining a misleading typed\n * cancellation; replacement admission remains closed because no durable\n * quiescence receipt was written.\n */\nexport function assertPhysicalToolQuiescenceForCancellation(input: {\n acknowledgeQuiescence: boolean;\n physicalToolQuiescenceConfirmed: boolean;\n failure: unknown;\n}): void {\n if (!input.acknowledgeQuiescence || input.physicalToolQuiescenceConfirmed) return;\n if (input.failure instanceof Error) throw input.failure;\n throw new Error(\"Physical sandbox-tool quiescence could not be confirmed\", {\n cause: input.failure,\n });\n}\n\n/** A physically drained attempt must leave one durable recovery producer. The\n * direct Postgres receipt is preferred; after its bounded retries exhaust, an\n * exact Temporal proof signal is sufficient because the workflow persists it\n * through an independently retrying DB-only control activity. */\nexport function assertSessionAttemptQuiescenceRecoveryDurable(input: {\n acknowledgeQuiescence: boolean;\n physicalToolQuiescenceConfirmed: boolean;\n receiptOrProofDurable: boolean;\n failure: unknown;\n}): void {\n if (\n !input.acknowledgeQuiescence ||\n !input.physicalToolQuiescenceConfirmed ||\n input.receiptOrProofDurable\n ) {\n return;\n }\n if (input.failure instanceof Error) throw input.failure;\n throw new Error(\"Physical quiescence had no durable receipt or recovery proof\", {\n cause: input.failure,\n });\n}\n\nconst QUIESCENCE_PROOF_SIGNAL_INITIAL_RETRY_MS = 250;\nconst QUIESCENCE_PROOF_SIGNAL_MAX_RETRY_MS = 5_000;\n\n/** Persist the authoritative receipt or durably hand the exact physical proof\n * to Temporal. This retries signal delivery, not DB eligibility or workflow\n * state. The proof object never changes between attempts. */\nexport async function persistOrSignalSessionAttemptQuiescence(input: {\n proof: SessionAttemptQuiescenceProof;\n persistReceipt: () => Promise<SessionAttemptQuiescenceCommit>;\n deliverWorkflowWake?: (\n wake: NonNullable<SessionAttemptQuiescenceCommit[\"workflowWake\"]>,\n ) => Promise<unknown>;\n publishEvents: (events: SessionEvent[]) => Promise<unknown>;\n signalProof: ActivityServices[\"signalSessionAttemptQuiesced\"];\n sleep?: (ms: number) => Promise<void>;\n heartbeat?: (attempt: number, delayMs: number) => void;\n onReceiptFailure?: (error: unknown) => void;\n onWakeFailure?: (error: unknown) => void;\n onPublishFailure?: (error: unknown) => void;\n onSignalFailure?: (error: unknown, attempt: number, delayMs: number) => void;\n}): Promise<\"receipt\" | \"signal\"> {\n let receipt: SessionAttemptQuiescenceCommit;\n try {\n receipt = await input.persistReceipt();\n } catch (receiptError) {\n input.onReceiptFailure?.(receiptError);\n if (!input.signalProof) {\n throw new Error(\"Session-attempt quiescence proof signaler is unavailable\", {\n cause: receiptError,\n });\n }\n const delay = input.sleep ?? sleep;\n let retryMs = QUIESCENCE_PROOF_SIGNAL_INITIAL_RETRY_MS;\n let attempt = 1;\n for (;;) {\n try {\n await input.signalProof(input.proof);\n return \"signal\";\n } catch (signalError) {\n input.onSignalFailure?.(signalError, attempt, retryMs);\n try {\n input.heartbeat?.(attempt, retryMs);\n } catch {\n // Heartbeat telemetry is not proof delivery and cannot replace or\n // interrupt the exact signal retry loop.\n }\n await delay(retryMs);\n retryMs = Math.min(retryMs * 2, QUIESCENCE_PROOF_SIGNAL_MAX_RETRY_MS);\n attempt += 1;\n }\n }\n }\n\n if (receipt.workflowWake && input.deliverWorkflowWake) {\n try {\n await input.deliverWorkflowWake(receipt.workflowWake);\n } catch (wakeError) {\n // The exact revision is already durable. Immediate delivery is latency\n // optimization only; the outbox dispatcher remains the repair path.\n input.onWakeFailure?.(wakeError);\n }\n }\n try {\n await input.publishEvents(receipt.events);\n } catch (publishError) {\n // Postgres already committed quiesced_at, the queue event, and the wake.\n // NATS is live fanout only; never misclassify its failure as receipt loss.\n input.onPublishFailure?.(publishError);\n }\n return \"receipt\";\n}\n\n/**\n * Cross the non-detachable physical boundary for one dying attempt. Temporal's\n * cancellation signal is intentionally absent: cancellation is transport, not\n * proof that sandbox tools and attempt-owned credential writers have drained.\n * A replacement may be admitted only after this function resolves and the\n * caller durably persists or signals the exact quiescence receipt.\n */\nexport async function drainAttemptOwnedSandboxWriters(input: {\n toolCancellationFence: Pick<TurnToolCancellationFence, \"cancel\" | \"waitForQuiescence\"> | null;\n cancellationReason?: unknown;\n gitCredentialRenewals: readonly Pick<GitCredentialRenewalController, \"stop\">[];\n codemodeTokenRenewal: Pick<CodemodeTokenRenewalController, \"stop\"> | null;\n runCredentialRenewal: Pick<RunCredentialRenewalController, \"stop\"> | null;\n}): Promise<void> {\n if (input.toolCancellationFence) {\n input.toolCancellationFence.cancel(\n input.cancellationReason ?? new Error(\"TURN_ATTEMPT_FENCED\"),\n );\n await input.toolCancellationFence.waitForQuiescence();\n }\n await Promise.all(input.gitCredentialRenewals.map(async (renewal) => await renewal.stop()));\n await input.codemodeTokenRenewal?.stop();\n await input.runCredentialRenewal?.stop();\n}\n\n/** Persist the exact turn's second-stage release only after the caller has\n * crossed the physical writer boundary. This wait is intentionally independent\n * of Temporal cancellation: it is a short idempotent DB transaction that closes\n * the durable archive-capture fence. Bounded retries cover a rollout connection\n * reset without turning ordinary finalizer housekeeping into lifecycle state. */\nexport async function releaseTurnSandboxAfterWriterDrain(\n sandbox: Pick<ResumedTurnSandbox, \"release\">,\n options: {\n maxAttempts?: number;\n retryDelayMs?: number;\n wait?: (delayMs: number) => Promise<void>;\n } = {},\n): Promise<void> {\n const maxAttempts = Math.max(1, options.maxAttempts ?? 3);\n const retryDelayMs = Math.max(0, options.retryDelayMs ?? 50);\n const wait = options.wait ?? sleep;\n let lastError: unknown;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n try {\n await sandbox.release({ workspaceWritersQuiesced: true });\n return;\n } catch (error) {\n lastError = error;\n if (attempt < maxAttempts) {\n await wait(retryDelayMs * attempt);\n }\n }\n }\n throw lastError;\n}\n\n/**\n * Await a finalizer operation only while this Temporal activity still owns its\n * execution window. Once Pause/Steer cancellation arrives, the operation keeps\n * its own rejection handler and may finish its idempotent, attempt-scoped\n * cleanup in the background, but it cannot pin activity terminalization or\n * delay the separately receipt-gated replacement dispatch.\n */\nexport async function waitForTurnFinalizerStep<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n): Promise<T | undefined> {\n if (!signal) return await operation;\n if (signal.aborted) {\n void operation.catch(() => undefined);\n return undefined;\n }\n\n let resolveCancellation: (() => void) | undefined;\n const cancelled = new Promise<undefined>((resolve) => {\n resolveCancellation = () => resolve(undefined);\n });\n const cancel = (): void => {\n void operation.catch(() => undefined);\n resolveCancellation?.();\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n return await Promise.race([operation, cancelled]);\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\n/**\n * Flush provider-facing stream state while the attempt still owns its activity\n * window. On Pause/Steer, both promises are detached with rejection handlers:\n * neither a runtime batcher nor an uncooperative provider completion promise\n * may pin the activity behind cancellation after durable writes are fenced.\n */\nexport async function waitForTurnStreamCleanup(\n batcherFlush: Promise<unknown>,\n providerCompleted: Promise<unknown>,\n signal: AbortSignal | undefined,\n): Promise<void> {\n await waitForTurnFinalizerStep(batcherFlush, signal);\n await waitForTurnFinalizerStep(providerCompleted, signal);\n}\n\n/**\n * Terminal settlement closes the active attempt before turn finalization. The\n * ordinary workspace admission therefore correctly returns `attempt_fenced`\n * for the final attempt-qualified credential deletion. Retry only that exact\n * settled-attempt case directly; every other fence/status and the direct\n * deletion itself remain fail-closed.\n */\nexport async function clearAttemptCredentialsWithSettledFence(input: {\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\";\n runWorkspaceFencedClear: () => Promise<void>;\n clearExactAttempt: () => Promise<void>;\n onSettledAttemptFence: () => void;\n}): Promise<void> {\n try {\n await input.runWorkspaceFencedClear();\n } catch (error) {\n const settledAttemptFence =\n error instanceof Error &&\n error.name === \"SandboxWorkspaceMutationFencedError\" &&\n (error as Error & { code?: unknown }).code === \"attempt_fenced\" &&\n (input.activityStatus === \"idle\" || input.activityStatus === \"failed\");\n if (!settledAttemptFence) throw error;\n input.onSettledAttemptFence();\n await input.clearExactAttempt();\n }\n}\n\nfunction turnFinalizerCancellationSignal(\n temporalSignal: AbortSignal | undefined,\n activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\",\n): AbortSignal | undefined {\n if (activityStatus !== \"cancelled\" || temporalSignal?.aborted) return temporalSignal;\n const fenced = new AbortController();\n fenced.abort(new Error(\"TURN_ATTEMPT_FENCED\"));\n return fenced.signal;\n}\n\nfunction compactionFailureReason(reason: string): string {\n return reason.startsWith(\"compaction summarization failed:\")\n ? reason\n : `compaction summarization failed: ${reason}`;\n}\n\nexport type MandatoryHistoryPersistenceStage = \"history_append\" | \"sandbox_envelope\";\n\n/**\n * Preserve the exact storage failure for the permission-controlled turn event\n * while attaching only a stable, non-secret operation token to public worker\n * diagnostics. Mandatory history failures remain terminal and never inherit a\n * provider-retry classification from coincidental source text or status.\n */\nexport class MandatoryHistoryPersistenceError extends Error {\n readonly name = \"MandatoryHistoryPersistenceError\";\n readonly cause: unknown;\n\n constructor(\n readonly stage: MandatoryHistoryPersistenceStage,\n cause: unknown,\n ) {\n super(cause instanceof Error ? cause.message : String(cause));\n this.cause = cause;\n }\n}\n\nexport async function runMandatoryHistoryPersistenceStep<T>(\n stage: MandatoryHistoryPersistenceStage,\n operation: () => Promise<T>,\n): Promise<T> {\n try {\n return await operation();\n } catch (cause) {\n throw new MandatoryHistoryPersistenceError(stage, cause);\n }\n}\n\nexport type SafeErrorDiagnostic = {\n errorClass: \"WorkerOperationError\";\n errorCode: \"worker_operation_failed\";\n status?: number;\n origin: \"worker\";\n historyPersistenceStage?: MandatoryHistoryPersistenceStage;\n};\n\n/**\n * Produce the only exception shape allowed in worker logs. It deliberately\n * excludes the arbitrary source message, stack, cause, response/request\n * bodies, and enumerable properties. Exact failure content belongs in the\n * permission-controlled session event, not stdout or telemetry.\n */\nexport function safeErrorDiagnostic(error: unknown): SafeErrorDiagnostic {\n const diagnostic: SafeErrorDiagnostic = {\n errorClass: \"WorkerOperationError\",\n errorCode: \"worker_operation_failed\",\n origin: \"worker\",\n };\n try {\n let statusSource = error;\n if (error instanceof MandatoryHistoryPersistenceError) {\n diagnostic.historyPersistenceStage = error.stage;\n statusSource = error.cause;\n }\n if (statusSource && typeof statusSource === \"object\") {\n const status = Number(\n (statusSource as { status?: unknown; statusCode?: unknown }).status ??\n (statusSource as { statusCode?: unknown }).statusCode,\n );\n if (Number.isInteger(status) && status >= 100 && status <= 599) {\n diagnostic.status = status;\n }\n }\n } catch {\n // Public diagnostics are best-effort and must never replace the exact\n // internal worker failure.\n }\n return diagnostic;\n}\n\nfunction safeErrorForTelemetry(error: unknown): Error {\n const diagnostic = safeErrorDiagnostic(error);\n const safe = new Error(\"worker operation failed\") as Error & {\n code?: string;\n status?: number;\n origin?: string;\n };\n safe.name = \"WorkerOperationError\";\n safe.code = diagnostic.errorCode;\n if (diagnostic.status !== undefined) safe.status = diagnostic.status;\n safe.origin = diagnostic.origin;\n return safe;\n}\n\nfunction compactionFailureReasonFromError(error: unknown): string {\n if (\n error instanceof CompactionProviderResponseError ||\n error instanceof EmptyCompactionSummaryError\n ) {\n return compactionFailureReason(error.message);\n }\n const errorName = error instanceof Error && error.name ? error.name : \"unknown error\";\n return compactionFailureReason(`unexpected ${errorName}`);\n}\n\nfunction isCompactionSummaryFailure(error: unknown): boolean {\n return (\n error instanceof CompactionProviderResponseError || error instanceof EmptyCompactionSummaryError\n );\n}\n\nexport function shouldRecoverCompactionProviderFailure(error: unknown): boolean {\n if (!(error instanceof CompactionProviderResponseError)) return false;\n if (isCodexTransportError(error) && classifyCodexUsageLimitError(error)) return true;\n return agentRunFailurePayload(error).retryable === true;\n}\n\nexport function classifyContextWindowOverflowError(\n error: unknown,\n): { message: string; code?: string; detail?: string } | null {\n const fields = collectErrorStrings(error);\n const matched = fields.find(\n (value) =>\n /context[_\\s-]*length[_\\s-]*exceeded/i.test(value) ||\n /exceeds?\\s+(?:the\\s+)?context\\s+window/i.test(value) ||\n /maximum\\s+context\\s+length/i.test(value) ||\n /context\\s+window[^.]*exceed/i.test(value),\n );\n if (!matched) {\n return null;\n }\n const message = error instanceof Error ? error.message : String(error);\n const code = fields.find((value) => /context[_\\s-]*length[_\\s-]*exceeded/i.test(value));\n return {\n message,\n ...(code ? { code } : {}),\n ...(matched && matched !== message ? { detail: matched } : {}),\n };\n}\n\n/**\n * Recognize an MCP transport/request timeout that escaped the SDK's per-tool\n * `mcpConfig.errorFunction` boundary. A thrown tool invocation is normally\n * converted to an `{isError:true}` tool output; however, connect/tools-list or\n * next-loop transport work can reject the stream iterator after a prior tool\n * output was already published. That is transient external backpressure, not a\n * terminal session error. Match MCP-qualified timeout text only: an unrelated\n * sandbox/model timeout and MCP's application-defined Authentication required signal must\n * retain their existing semantics.\n */\nexport function classifyMcpTransportTimeoutError(\n error: unknown,\n): { message: string; detail?: string } | null {\n const fields = collectErrorStrings(error);\n const matchedText = fields.find(\n (value) =>\n /\\bmcp\\b/i.test(value) &&\n /(?:request\\s+timed\\s+out|request\\s+timeout|\\btimed\\s+out\\b|\\btimeout\\b|ETIMEDOUT)/i.test(\n value,\n ) &&\n !/authentication\\s+required/i.test(value),\n );\n const sanitizedSdkTimeout = isMcpRequestTimeoutError(error);\n if (!matchedText && !sanitizedSdkTimeout) {\n return null;\n }\n const message = error instanceof Error ? error.message : String(error);\n const matched = matchedText ?? fields.find((value) => /\\bmcp\\b/i.test(value));\n return {\n message,\n ...(matched && matched !== message ? { detail: matched } : {}),\n };\n}\n\nfunction collectErrorStrings(value: unknown, seen = new WeakSet<object>()): string[] {\n if (typeof value === \"string\") {\n return [value];\n }\n if (!value || typeof value !== \"object\") {\n return [];\n }\n if (seen.has(value)) {\n return [];\n }\n seen.add(value);\n const out: string[] = [];\n const record = value as Record<string, unknown>;\n for (const key of [\"message\", \"code\", \"type\", \"name\", \"param\"]) {\n const field = record[key];\n if (typeof field === \"string\" && field.length > 0) {\n out.push(field);\n }\n }\n for (const key of [\"error\", \"cause\", \"response\", \"data\"]) {\n out.push(...collectErrorStrings(record[key], seen));\n }\n return out;\n}\n\n/**\n * Compute the conversation-truth rows a reconcile pass should append, given the\n * SDK's current `state.history` and the count already persisted.\n *\n * `state.history` is a computed getter that runs the SDK's orphan-tool-call\n * pruning on every access, so it is non-monotonic: a `function_call` with no\n * settling result yet is transiently absent and a later access yields a\n * different, possibly shorter/reordered list. The old code sliced this list by\n * a blind length watermark and appended at fixed positions with\n * onConflictDoNothing, which could freeze a position with one shape and later\n * persist a `function_call_result` whose `function_call` had been pruned away in\n * an earlier slice — the orphaned tool output that 400s the Responses API and\n * bricks the session on every replay.\n *\n * Defending: structurally repair the full current history into an API-valid sequence (the\n * same pure rules the read path uses), then append only the new tail beyond the\n * watermark. A trailing dangling call is dropped here and re-evaluated next\n * pass once its result lands, so a call and its result are written together at\n * consecutive positions and a result is never persisted without its call. The\n * watermark advances to the repaired length — never past anything unwritten —\n * so a non-monotonic history can never desync it. When previously-persisted\n * rows already exceed the repaired length (e.g. legacy orphans written before\n * this fix), nothing new is appended and the watermark holds steady.\n */\n/**\n * Stable+unique usage source key for one model call, used to build the per-call\n * idempotency key (`usage:model.tokens:${turnId}:${sourceKey}`). The turnId is\n * shared across a new attempt of the SAME turn (recovery, approval\n * rerun, activity retry), so the sourceKey alone must distinguish calls.\n *\n * - A provider responseId is globally stable+unique, so reuse it verbatim: a\n * true activity retry that re-emits the same responseId correctly DEDUPES\n * (one charge), while two distinct calls get distinct ids.\n * - Without a responseId the old synthesized key was only POSITIONAL (\"response-1\",\n * \"aggregate\"), which collides across a re-dispatch — dispatch B's first\n * call reuses dispatch A's \"response-1\" key and its charge is silently\n * dropped (undercharge). Qualifying the synthesized key with the\n * per-execution dispatch id (the Temporal activityId, unique per scheduled\n * execution) makes re-dispatched calls distinct while still deduping a\n * same-execution retry.\n */\nexport function modelUsageSourceKey(input: {\n responseId?: string | null | undefined;\n dispatchId: string | null;\n positionalKey: string;\n}): string {\n if (input.responseId) {\n return input.responseId;\n }\n return input.dispatchId ? `${input.dispatchId}:${input.positionalKey}` : input.positionalKey;\n}\n\nexport function providerContextTokens(\n usage:\n | {\n inputTokens?: number;\n outputTokens?: number;\n totalTokens?: number;\n }\n | null\n | undefined,\n): number | null {\n const total = normalizeModelCallUsage(usage).totalTokens;\n return total !== null && total > 0 ? total : null;\n}\n\n/**\n * A provider call has already consumed tokens by the time its usage frame is\n * available. Losing the Codex credential lease at the renewal checkpoint must\n * stop the result from becoming authoritative, but it must not erase accounting\n * truth for the call that already happened. Meter first, then surface the lost\n * lease, then write attempt-owned token/context signals. A replaced attempt can\n * reject those signals without erasing the provider usage already incurred.\n */\nexport async function recordCompletedModelCallBeforeOwnershipFences(input: {\n renewLease: () => Promise<void>;\n recordUsage: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n recordAttemptSignals?: () => Promise<void>;\n}): Promise<void> {\n await input.renewLease();\n await input.recordUsage();\n if (input.leaseLost()) {\n throw new Error(input.leaseLostMessage);\n }\n await input.recordAttemptSignals?.();\n}\n\ntype TurnEventPublisher = (\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>,\n immediate?: boolean,\n) => Promise<{ events: SessionEvent[]; accepted: boolean }>;\n\nexport type ModelResponseEventState = {\n responseCount: number;\n contextSignal: { revision: number; totalTokens: number } | null;\n claimedSourceKeys: Set<string>;\n};\n\nexport type CompactionModelUsageEventState = {\n usageCount: number;\n claimedSourceKeys: Set<string>;\n};\n\nexport function createModelResponseEventState(\n claimedSourceKeys: Set<string> = new Set<string>(),\n): ModelResponseEventState {\n return {\n responseCount: 0,\n contextSignal: null,\n claimedSourceKeys,\n };\n}\n\nexport function createCompactionModelUsageEventState(\n claimedSourceKeys: Set<string> = new Set<string>(),\n): CompactionModelUsageEventState {\n return { usageCount: 0, claimedSourceKeys };\n}\n\nexport function modelResponseContextSignal(\n state: ModelResponseEventState,\n): { revision: number; totalTokens: number } | null {\n return state.contextSignal;\n}\n\nexport function assertModelResponseLatencyMode(input: {\n event: Parameters<typeof modelResponseServiceTierFromSdkEvent>[0];\n requested: LatencyMode;\n model: string;\n /** When set to Codex ChatGPT auth, response `service_tier` is not an honor signal. */\n providerId?: string;\n}): void {\n if (input.requested === \"standard\") {\n return;\n }\n // ChatGPT-auth Codex (subscription): Fast maps to request `service_tier=priority`\n // (see openai/codex ServiceTier::Fast.request_value). The backend may still return\n // `response.service_tier=default`; OpenAI maintainers document that this does not\n // mean Fast was ignored. Native CLI also does not fail closed on that field.\n if (input.providerId === CODEX_PROVIDER_ID) {\n return;\n }\n const serviceTierEvent = modelResponseServiceTierFromSdkEvent(input.event);\n if (\n !serviceTierEvent ||\n (serviceTierEvent.source === \"normalized\" && serviceTierEvent.serviceTier === null)\n ) {\n return;\n }\n if (!responseSatisfiesLatencyMode(input.requested, serviceTierEvent.serviceTier)) {\n throw new Error(\n `Provider did not honor ${input.requested} latency mode for ${input.model}: response service_tier=${serviceTierEvent.serviceTier ?? \"missing\"}`,\n );\n }\n}\n\n/**\n * Process one SDK terminal-response event through the production authority path.\n *\n * The pinned Responses SDK mirrors one provider terminal response as both a\n * normalized `response_done` and a raw `model/response.completed` event. Claim\n * the stable response/source key before lease renewal or any side effect, and\n * use that one positional ordinal for both response identity and same-run\n * context binding. A response without usage still clears attempt-owned token\n * state. When usage exists, the durable `agent.model.usage` source-key fence\n * remains the cross-restart authority: a replay may retry the idempotent billing\n * write, but it cannot advance metrics, context, or attempt-owned signals.\n */\nexport async function processModelResponseTerminalEvent(input: {\n event: Parameters<typeof modelTerminalResponseFromSdkEvent>[0];\n state: ModelResponseEventState;\n dispatchId: string | null;\n settings: Settings;\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n latencyMode?: LatencyMode;\n metricProvider: string;\n externallyBilled: boolean;\n servingCredentialId: string | null;\n priorSessionCredentialId: string | null;\n emittedSourceKeys: Set<string>;\n renewLease: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n setLastInputTokens: (tokens: number | null) => Promise<void>;\n}): Promise<\n | { status: \"not_response\" }\n | { status: \"duplicate\"; sourceKey: string }\n | {\n status: \"processed\";\n sourceKey: string;\n authoritative: boolean;\n usageReported: boolean;\n }\n> {\n const terminal = modelTerminalResponseFromSdkEvent(input.event);\n if (!terminal) {\n return { status: \"not_response\" };\n }\n\n const responseOrdinal = input.state.responseCount + 1;\n const sourceKey = modelUsageSourceKey({\n responseId: terminal.responseId,\n dispatchId: input.dispatchId,\n positionalKey: `response-${responseOrdinal}`,\n });\n if (input.state.claimedSourceKeys.has(sourceKey)) {\n return { status: \"duplicate\", sourceKey };\n }\n input.state.claimedSourceKeys.add(sourceKey);\n input.state.responseCount = responseOrdinal;\n\n const responseUsage = terminal.usage;\n\n const normalizedUsage = normalizeModelCallUsage(responseUsage?.usage);\n const accountContext = modelCallAccountContext({\n servingCredentialId: input.servingCredentialId,\n priorSessionCredentialId: input.priorSessionCredentialId,\n isFirstCallOfTurn: responseOrdinal === 1,\n });\n // A terminal response without usage still authoritatively replaces the\n // attempt-owned context signal. There is simply no billing event to claim.\n let authoritative = responseUsage === null;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: input.renewLease,\n leaseLost: input.leaseLost,\n leaseLostMessage: input.leaseLostMessage,\n recordUsage: async () => {\n if (!responseUsage) return;\n const billing = await recordModelUsageAndDebitCredits(input.settings, input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n model: input.model,\n externallyBilled: input.externallyBilled,\n usage: responseUsage.usage,\n normalizedUsage,\n gatewayManaged: input.provider === OPENGENI_GATEWAY_PROVIDER_ID,\n gatewayBilling: responseUsage.gatewayBilling,\n sourceKey,\n ...(input.latencyMode ? { latencyMode: input.latencyMode } : {}),\n observability: input.observability,\n });\n authoritative = await emitModelCallUsage({\n observability: input.observability,\n publish: input.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey,\n usage: responseUsage,\n normalizedUsage,\n servingAccountHash: accountContext.servingAccountHash,\n accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,\n emittedSourceKeys: input.emittedSourceKeys,\n });\n if (authoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db: input.db,\n observability: input.observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billing,\n });\n }\n const observedInput = normalizedUsage.telemetry.inputTokens;\n if (authoritative && observedInput !== null && observedInput > 0) {\n recordModelInputTokens(input.observability, input.metricProvider, observedInput);\n }\n },\n recordAttemptSignals: async () => {\n if (!authoritative) return;\n const observedTotal = normalizedUsage.totalTokens;\n input.state.contextSignal =\n observedTotal !== null && observedTotal > 0\n ? { revision: responseOrdinal, totalTokens: observedTotal }\n : null;\n const observedInput = normalizedUsage.telemetry.inputTokens;\n await input.setLastInputTokens(\n observedInput !== null && observedInput > 0 ? observedInput : null,\n );\n },\n });\n return {\n status: \"processed\",\n sourceKey,\n authoritative,\n usageReported: responseUsage !== null,\n };\n}\n\n/**\n * Apply the same source-key authority ordering to the compaction summarizer's\n * usage callback. The summarizer can retry or mirror a terminal response just\n * like the main stream, so claim before lease renewal, billing, durable usage,\n * logging, or cache metrics. Durable source-key idempotency remains the\n * cross-process authority after a worker restart.\n */\nexport async function processCompactionModelUsageEvent(input: {\n usage: ModelResponseUsage;\n state: CompactionModelUsageEventState;\n dispatchId: string | null;\n settings: Settings;\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n externallyBilled: boolean;\n servingCredentialId: string | null;\n priorSessionCredentialId: string | null;\n emittedSourceKeys: Set<string>;\n renewLease: () => Promise<void>;\n leaseLost: () => boolean;\n leaseLostMessage: string;\n}): Promise<\n | { status: \"duplicate\"; sourceKey: string }\n | { status: \"processed\"; sourceKey: string; authoritative: boolean }\n> {\n const usageOrdinal = input.state.usageCount + 1;\n const sourceKey = modelUsageSourceKey({\n responseId: input.usage.responseId,\n dispatchId: input.dispatchId,\n positionalKey: `compaction-${usageOrdinal}`,\n });\n if (input.state.claimedSourceKeys.has(sourceKey)) {\n return { status: \"duplicate\", sourceKey };\n }\n input.state.claimedSourceKeys.add(sourceKey);\n input.state.usageCount = usageOrdinal;\n\n const accountContext = modelCallAccountContext({\n servingCredentialId: input.servingCredentialId,\n priorSessionCredentialId: input.priorSessionCredentialId,\n isFirstCallOfTurn: usageOrdinal === 1,\n });\n const normalizedUsage = normalizeModelCallUsage(input.usage.usage);\n let authoritative = false;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: input.renewLease,\n leaseLost: input.leaseLost,\n leaseLostMessage: input.leaseLostMessage,\n recordUsage: async () => {\n const billing = await recordModelUsageAndDebitCredits(input.settings, input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n model: input.model,\n externallyBilled: input.externallyBilled,\n usage: input.usage.usage,\n normalizedUsage,\n gatewayManaged: input.provider === OPENGENI_GATEWAY_PROVIDER_ID,\n gatewayBilling: input.usage.gatewayBilling,\n sourceKey,\n observability: input.observability,\n });\n authoritative = await emitModelCallUsage({\n observability: input.observability,\n publish: input.publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey,\n usage: input.usage,\n normalizedUsage,\n servingAccountHash: accountContext.servingAccountHash,\n accountChangedFromPrevCall: accountContext.accountChangedFromPrevCall,\n emittedSourceKeys: input.emittedSourceKeys,\n });\n if (authoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db: input.db,\n observability: input.observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billing,\n });\n }\n },\n });\n return { status: \"processed\", sourceKey, authoritative };\n}\n\nexport async function emitModelCallUsage(input: {\n observability: ActivityServices[\"observability\"];\n publish: TurnEventPublisher | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n sourceKey: string;\n usage: ModelResponseUsage | { usage?: unknown | null } | null;\n normalizedUsage?: ModelCallUsageNormalization;\n // Prompt-cache research dimensions (log-only; NEVER on a metric label or a\n // durable event). The opaque serving-account tag and whether it changed since\n // the session's previous call — the account-switch hypothesis for cache misses.\n servingAccountHash?: string;\n accountChangedFromPrevCall?: boolean;\n emittedSourceKeys?: Set<string>;\n}): Promise<boolean> {\n const usage =\n input.usage && typeof input.usage === \"object\" && \"usage\" in input.usage\n ? (input.usage as { usage?: unknown }).usage\n : null;\n if (!usage || typeof usage !== \"object\") {\n return false;\n }\n if (input.emittedSourceKeys?.has(input.sourceKey)) return false;\n const normalizedUsage =\n input.normalizedUsage ?? normalizeModelCallUsage(usage as ModelCallUsageInput);\n const telemetry = normalizedUsage.telemetry;\n const appended = await input.publish?.(\n [\n {\n type: \"agent.model.usage\",\n payload: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n sourceKey: input.sourceKey,\n ...telemetry,\n },\n },\n ],\n true,\n );\n input.emittedSourceKeys?.add(input.sourceKey);\n const authoritative = appended?.events.some(\n (event) =>\n event.type === \"agent.model.usage\" &&\n event.turnAssociation === \"current\" &&\n event.payload !== null &&\n typeof event.payload === \"object\" &&\n (event.payload as Record<string, unknown>).sourceKey === input.sourceKey,\n );\n if (!authoritative) return false;\n try {\n input.observability.info(\"model call usage\", {\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n inputTokens: telemetry.inputTokens,\n outputTokens: telemetry.outputTokens,\n cachedTokens: telemetry.cachedTokens,\n cacheWriteTokens: telemetry.cacheWriteTokens,\n reasoningTokens: telemetry.reasoningTokens,\n ...(input.servingAccountHash !== undefined\n ? { servingAccountHash: input.servingAccountHash }\n : {}),\n ...(input.accountChangedFromPrevCall !== undefined\n ? { accountChangedFromPrevCall: input.accountChangedFromPrevCall }\n : {}),\n });\n if (normalizedUsage.rejectedFields.length > 0) {\n input.observability.warn(\"model call usage fields rejected\", {\n provider: input.provider,\n providerApi: input.providerApi,\n model: input.model,\n rejectedFields: normalizedUsage.rejectedFields.join(\",\"),\n });\n }\n } catch {\n // Durable event + billing already committed; logging is best-effort only.\n }\n try {\n applyCodexCacheTelemetry(input.observability, input.provider, normalizedUsage);\n } catch {\n // Durable event + billing already committed; metrics are best-effort only.\n }\n return true;\n}\n\n/**\n * Apply one authoritative, normalized model-call usage frame to the shared\n * prompt-cache metrics. The durable source-key fence in `emitModelCallUsage`\n * owns idempotency; this helper must never receive raw provider values.\n */\nexport function applyCodexCacheTelemetry(\n observability: ActivityServices[\"observability\"],\n provider: string,\n normalizedUsage: ModelCallUsageNormalization,\n): void {\n recordModelCacheTokens(observability, provider, {\n cachedTokens: normalizedUsage.telemetry.cachedTokens,\n cacheWriteTokens: normalizedUsage.telemetry.cacheWriteTokens,\n promptTokens: normalizedUsage.telemetry.inputTokens,\n });\n}\n\nexport function historyRowsToAppend(\n rawHistory: Array<Record<string, unknown>>,\n // How many items of the CURRENT in-memory history are already persisted (the\n // slice index into `sanitized`). This is the in-memory history length, NOT the\n // total persisted-row count: after a compaction the in-memory history is the\n // short [summary, ...tail, ...new] list, far shorter than the total rows in\n // the table (which still hold the superseded prefix).\n persistedHistoryCount: number,\n // Next free WHOLE-NUMBER absolute position to write at. Decoupled from the\n // slice index because compaction inserts a fractional summary position, so the\n // total-row count no longer equals max(position)+1. Defaults to\n // persistedHistoryCount to preserve the pre-compaction behaviour (contiguous\n // positions from 0) when callers do not pass an explicit next position.\n nextPosition: number = persistedHistoryCount,\n toolOutputTruncationTokens?: number,\n): {\n rows: Array<{ position: number; item: Record<string, unknown> }>;\n nextWatermark: number;\n nextPosition: number;\n} {\n const modelReady = sanitizeHistoryItemsForModel(rawHistory, toolOutputTruncationTokens);\n if (modelReady.length <= persistedHistoryCount) {\n return { rows: [], nextWatermark: persistedHistoryCount, nextPosition };\n }\n // Canonical model-facing inputs (including machine-input batches) are\n // persisted before inference and therefore live inside the prefix represented\n // by persistedHistoryCount. System messages synthesized only for this\n // attempt—recovery diagnostics, credential notices, attachment materialization\n // notes—must not accidentally become conversation memory during reconciliation.\n // Advance the in-memory watermark past them, but only allocate durable\n // positions to actual model/tool output.\n const rows: Array<{ position: number; item: Record<string, unknown> }> = [];\n for (const [offset, item] of modelReady.slice(persistedHistoryCount).entries()) {\n if (item.type === \"message\" && item.role === \"system\") {\n continue;\n }\n rows.push({\n position: nextPosition + rows.length,\n item: normalizeProtocolJsonValue(\n item as Record<string, unknown>,\n `$[${persistedHistoryCount + offset}]`,\n ),\n });\n }\n return {\n rows,\n nextWatermark: modelReady.length,\n nextPosition: nextPosition + rows.length,\n };\n}\n\n/** Select only opaque rows that participated in the provider's rejected wire request. */\nexport function selectRejectedProviderArtifactHistoryIds(\n activeHistory: ReadonlyArray<{\n id: string;\n item: Record<string, unknown>;\n providerArtifactInvalidatedAt: Date | null;\n }>,\n candidates: {\n knownHistoryItemIds: readonly string[];\n historyItemIds: readonly string[];\n },\n wireFingerprints: readonly string[],\n): string[] {\n const remainingWireArtifacts = new Map<string, number>();\n for (const fingerprint of wireFingerprints) {\n remainingWireArtifacts.set(fingerprint, (remainingWireArtifacts.get(fingerprint) ?? 0) + 1);\n }\n const knownHistoryItemIds = new Set(candidates.knownHistoryItemIds);\n const initialCandidateIds = new Set(candidates.historyItemIds);\n const selected: string[] = [];\n for (const row of activeHistory) {\n if (row.providerArtifactInvalidatedAt !== null) continue;\n // A row present before this attempt is eligible only when the exact\n // model-facing projection retained it. Rows appended during this run are\n // eligible after durable reconciliation.\n if (knownHistoryItemIds.has(row.id) && !initialCandidateIds.has(row.id)) continue;\n const fingerprint = opaqueProviderArtifactFingerprint(row.item);\n if (!fingerprint) continue;\n const remaining = remainingWireArtifacts.get(fingerprint) ?? 0;\n if (remaining === 0) continue;\n selected.push(row.id);\n remainingWireArtifacts.set(fingerprint, remaining - 1);\n }\n return selected;\n}\n\n/** Literal final per-call boundary for replayed and current-turn model input. */\nexport function isModelOrToolProgressHistoryItem(item: Record<string, unknown>): boolean {\n if (item.type === \"message\") {\n return item.role === \"assistant\";\n }\n if (item.type === \"reasoning\" || item.type === \"compaction\") {\n return true;\n }\n if (typeof item.type === \"string\") {\n return item.type !== \"message\";\n }\n return false;\n}\n\n/**\n * Resolve the EFFECTIVE/active compute backend a turn should gate\n * filesystem-touching agent lifecycle hooks on (today: the repository clone).\n *\n * WHY (Case B — clone-onto-real-disk hazard): a session keeps its CLOUD HOME\n * backend (`settings.sandboxBackend`, e.g. \"modal\") but its ACTIVE sandbox may\n * have been swapped to a connected machine (`active_sandbox_id` → a selfhosted\n * lease). `runtime.buildAgent`'s repository-clone hook keys off the backend it is\n * told; if the worker passes nothing it defaults to the HOME backend and the hook\n * would `git clone` a private GitHub-App repo onto the user's REAL disk — a\n * bring-your-own machine owns its own filesystem and must NEVER be cloned onto. So\n * we look at where the agent ACTUALLY runs, not where the session was created.\n *\n * Returns \"selfhosted\" ONLY when the selfhosted feature is on AND the session has\n * a non-null active pointer whose sandbox `kind` is \"selfhosted\". Otherwise\n * returns undefined so buildAgent falls back to the home backend — byte-for-byte\n * unchanged cloud behavior.\n *\n * Total + best-effort by contract: it NEVER throws (a lookup failure is logged and\n * falls back to the home default), so wiring it at turn start can't fail the turn.\n * The DB I/O is injected (the real call site passes readActiveSandbox + getSandbox,\n * the same helpers wrapTurnBoxWithRouting reuses) so the gate/decision/safety\n * contract is unit-testable without a live database.\n */\nexport async function resolveActiveSandboxBackend(\n routingOn: boolean,\n loadPointer: () => Promise<{ activeSandboxId: string | null } | null>,\n loadSandboxKind: (sandboxId: string) => Promise<string | null>,\n): Promise<Settings[\"sandboxBackend\"] | undefined> {\n // The active pointer + swap tools only exist when selfhosted routing is on; with\n // the flag off there is nothing to resolve and we keep the home-backend default.\n if (!routingOn) {\n return undefined;\n }\n try {\n const pointer = await loadPointer();\n // A null pointer (no swap) means \"use the session's own cloud group box\" — the\n // home backend already governs that path, so leave the override unset.\n if (!pointer?.activeSandboxId) {\n return undefined;\n }\n const kind = await loadSandboxKind(pointer.activeSandboxId);\n return kind === \"selfhosted\" ? \"selfhosted\" : undefined;\n } catch (error) {\n console.error(\n \"active sandbox backend resolution failed (turn proceeds on home backend)\",\n safeErrorDiagnostic(error),\n );\n return undefined;\n }\n}\n\n/**\n * Managed-sandbox ownership exists only when this turn actually uses the\n * managed home. A Connected Machine is fenced by its active-route epoch and\n * must remain independent from cloud recovery state for the same session.\n */\nexport function managedSandboxOwnershipForTurn(\n machinePrimary: boolean,\n attemptId: string,\n sandboxGroupId: string,\n): { holderId: TurnSandboxLeaseHolderId; sandboxGroupId: string } | null {\n if (machinePrimary) return null;\n return {\n holderId: sandboxLeaseHolderIdForAttempt(attemptId),\n sandboxGroupId,\n };\n}\n\n/** A sandboxless home still establishes an explicitly attached Connected Machine. */\nexport function shouldEstablishSandboxForTurn(\n sandboxOwnershipEnabled: boolean,\n homeBackend: Settings[\"sandboxBackend\"],\n machinePrimary: boolean,\n): boolean {\n return sandboxOwnershipEnabled && (homeBackend !== \"none\" || machinePrimary);\n}\n\nexport function sandboxEstablishPolicyDecision(input: {\n lazyEnabled: boolean;\n machinePrimary: boolean;\n sandboxBackend: Settings[\"sandboxBackend\"];\n hasInitialRunCredentialMaterial: boolean;\n generatedVideoFileCount: number;\n hasSignedFileResources: boolean;\n}): { policy: \"eager\" | \"on-demand\"; reason: TurnSandboxEstablishReason } {\n if (!input.lazyEnabled) return { policy: \"eager\", reason: \"lazy_disabled\" };\n if (input.machinePrimary) return { policy: \"eager\", reason: \"machine_primary\" };\n if (input.sandboxBackend === \"none\") return { policy: \"eager\", reason: \"backend_none\" };\n if (input.hasInitialRunCredentialMaterial) {\n return { policy: \"eager\", reason: \"initial_run_credentials\" };\n }\n if (input.generatedVideoFileCount > 0) {\n return { policy: \"eager\", reason: \"generated_video_files\" };\n }\n // Signed file downloads must finish before the first model boundary so any\n // integrity/download failure is present in the prepared input. Deferring the\n // box until the first tool call would make that first request advertise a\n // path whose materialization outcome is not known yet.\n if (input.hasSignedFileResources) {\n return { policy: \"eager\", reason: \"signed_file_resources\" };\n }\n return { policy: \"on-demand\", reason: \"eligible\" };\n}\n\n/**\n * Classify a persisted active-sandbox pointer for TURN-START RECONCILE (issue #341\n * invariant B). Returns the typed reason to RESET the pointer to the session HOME,\n * or null to leave it in place. STRUCTURAL unestablishability only:\n * - no record → the pointed-at sandbox row is gone (`stale_pointer`);\n * - an unestablishable kind (a non-group Modal sibling, or an unknown backend) per\n * the SHARED `swapTargetEstablishability` predicate (`unsupported_backend_context`);\n * - a selfhosted sandbox with no enrollment id to address (`offline_enrollment`).\n * A selfhosted sandbox WITH an enrollment is deliberately left in place even when it\n * is momentarily offline: the machine may recover mid-turn and its ops surface\n * agent_offline lazily, so the user's explicit machine target is never abandoned for\n * a transient control-plane blip (that is #339's concern, not this one).\n */\nexport function pointerReconcileReason(\n record: { kind: string; enrollmentId: string | null } | null,\n): BackendUnresolvableCode | null {\n if (!record) {\n return \"stale_pointer\";\n }\n const establishable = swapTargetEstablishability({\n kind: record.kind,\n isSessionGroup: false,\n });\n if (!establishable.ok) {\n return establishable.code;\n }\n if (record.kind === \"selfhosted\" && !record.enrollmentId) {\n return \"offline_enrollment\";\n }\n return null;\n}\n\n/** The active pointer + its sandbox row, loaded once at turn start and threaded\n * through the reconcile so the establish branch reads the SAME (possibly reset)\n * values with no second query. */\nexport type LoadedActivePointer = {\n pointer: ActiveSandboxPointer | null;\n record: SandboxRecord | null;\n};\n\n/**\n * TURN-START RECONCILE (issue #341 invariant B / Shapes 1+2). If the persisted pointer's\n * target is STRUCTURALLY unestablishable ({@link pointerReconcileReason}) reset the pointer\n * to the session HOME (null) under the epoch fence, emit a VISIBLE `session.route.reconciled`\n * event, and return the reconciled pointer/record so the rest of the turn runs on home. NEVER\n * a silent downgrade. Bounded to ONE attempt: a lost CAS means a concurrent user swap won a\n * higher epoch, so re-read + honor it rather than clobber a newer, user-directed pointer. The\n * event publish is best-effort — a publish failure never fails the turn.\n *\n * FAIL-OPEN on a lookup failure (issue #341 review): the sandbox row is fetched HERE via the\n * caller's NON-swallowing `loadRecord`, so a null decision means the row is genuinely absent,\n * never a suppressed transient DB error. If `loadRecord` THROWS, reconciliation is skipped\n * entirely this turn — the pointer is left UNTOUCHED (record null → the turn runs\n * machinePrimary:false on the group box exactly as before reconcile existed), no CAS, no\n * event — and the next turn retries. A TRANSIENT LOOKUP FAILURE MUST NEVER MUTATE THE POINTER.\n */\nexport async function reconcileActiveSandboxPointer(\n db: ActivityServices[\"db\"],\n ids: { accountId: string; workspaceId: string; sessionId: string },\n pointer: ActiveSandboxPointer | null,\n loadRecord: (sandboxId: string) => Promise<SandboxRecord | null>,\n publish?: (events: Array<{ type: SessionEventType; payload: unknown }>) => Promise<void> | void,\n): Promise<LoadedActivePointer> {\n if (!pointer?.activeSandboxId) {\n return { pointer, record: null };\n }\n // Re-fetch the row WITHOUT error swallowing. A throw here (a transient DB blip) is NOT\n // \"row absent\": fail open — skip reconciliation, leave the pointer untouched.\n let record: SandboxRecord | null;\n try {\n record = await loadRecord(pointer.activeSandboxId);\n } catch {\n return { pointer, record: null };\n }\n const reason = pointerReconcileReason(record);\n if (!reason) {\n return { pointer, record };\n }\n const fromEpoch = pointer.activeEpoch;\n const reset = await setActiveSandbox(db, {\n accountId: ids.accountId,\n workspaceId: ids.workspaceId,\n sessionId: ids.sessionId,\n targetSandboxId: null,\n expectedEpoch: fromEpoch,\n }).catch(\n () => ({ swapped: false, pointer: null }) as Awaited<ReturnType<typeof setActiveSandbox>>,\n );\n if (reset.swapped && reset.pointer) {\n await Promise.resolve(\n publish?.([\n {\n type: \"session.route.reconciled\",\n payload: { reason, fromEpoch, toEpoch: reset.pointer.activeEpoch },\n },\n ]),\n ).catch(() => undefined);\n return { pointer: reset.pointer, record: null };\n }\n // The fence was lost: a concurrent higher-epoch swap won. Honor the newer pointer; its\n // record is re-fetched fail-open too (a transient failure leaves record null, never a\n // mutation — we already did not win the CAS).\n const reread = await readActiveSandbox(db, ids.workspaceId, ids.sessionId).catch(() => null);\n if (!reread) {\n return { pointer, record: null };\n }\n let rereadRecord: SandboxRecord | null = null;\n if (reread.activeSandboxId) {\n try {\n rereadRecord = await loadRecord(reread.activeSandboxId);\n } catch {\n rereadRecord = null;\n }\n }\n return { pointer: reread, record: rereadRecord };\n}\n\n/**\n * Warm the Modal private-registry image for the image ref this turn actually\n * resolved, not only the deployment-global OPENGENI_MODAL_IMAGE_REF warmed at\n * worker boot. A provider-native modalImageId bypasses registry import and is\n * resolved by ModalImageSelector.fromId during create. Otherwise packs can\n * override `modalImageRef` per workspace/turn, so a private pack image must be\n * resolved before sandbox creation or Modal falls back to the unauthenticated\n * `fromTag` path.\n */\nexport async function ensureTurnModalRegistryImage(\n runSettings: Settings,\n sandboxCreationBackend: Settings[\"sandboxBackend\"] | undefined,\n ensureRegistryImage: (settings: Settings) => Promise<void> = ensureModalRegistryImage,\n): Promise<void> {\n if (sandboxCreationBackend !== \"modal\") {\n return;\n }\n if (runSettings.modalImageId) {\n return;\n }\n if (!runSettings.modalImageRegistrySecret || !runSettings.modalImageRef) {\n return;\n }\n await ensureRegistryImage(runSettings);\n}\n\nconst SANDBOX_ARTIFACT_RUNTIME_MANIFEST = \"/opt/opengeni/artifact-runtime/installation.json\";\nconst SANDBOX_ARTIFACT_TOOL_ENTRY = \"/opt/opengeni/artifact-runtime/skill-facade-entry.mjs\";\n\nexport type SandboxArtifactRuntimeAdmission = Readonly<{\n available: boolean;\n environment: Readonly<Record<string, string>>;\n}>;\n\n/**\n * Admit the optional native standalone-file runtime only for the deployment's\n * exact base sandbox image contract. A pack/rig image override is an\n * independent filesystem and therefore fails closed even when the deployment\n * base image is capable. Collaborative artifact skills are admitted separately\n * from the frozen canonical tool catalog.\n *\n * This keeps lazy provisioning intact: CI/release proves the image closure,\n * while a before-agent-start doctor verifies the actual box before any model\n * call. No speculative sandbox is created merely to populate the skill index.\n */\nexport function sandboxArtifactRuntimeAdmission(\n deploymentSettings: Settings,\n runSettings: Settings,\n backend: Settings[\"sandboxBackend\"] | undefined,\n options: Readonly<{ production?: boolean }> = {},\n): SandboxArtifactRuntimeAdmission {\n if (!deploymentSettings.sandboxArtifactRuntimeEnabled) {\n return { available: false, environment: {} };\n }\n const production = options.production ?? process.env.NODE_ENV === \"production\";\n if (backend === \"docker\") {\n const image = deploymentSettings.dockerImage;\n const localDevelopmentImage = /^opengeni-sandbox:local-[0-9a-f]{12}$/u.test(image);\n if (\n runSettings.dockerImage !== image ||\n (!/@sha256:[0-9a-f]{64}$/u.test(image) && (production || !localDevelopmentImage))\n ) {\n return { available: false, environment: {} };\n }\n } else if (backend === \"modal\") {\n if (\n !deploymentSettings.modalImageRef ||\n !/@sha256:[0-9a-f]{64}$/u.test(deploymentSettings.modalImageRef) ||\n runSettings.modalImageRef !== deploymentSettings.modalImageRef ||\n runSettings.modalImageId !== deploymentSettings.modalImageId\n ) {\n return { available: false, environment: {} };\n }\n } else {\n return { available: false, environment: {} };\n }\n return {\n available: true,\n environment: {\n OPENGENI_ARTIFACT_RUNTIME_MANIFEST: SANDBOX_ARTIFACT_RUNTIME_MANIFEST,\n OPENGENI_ARTIFACT_TOOL_ENTRY: SANDBOX_ARTIFACT_TOOL_ENTRY,\n },\n };\n}\n\n/**\n * Decide whether the first actual computer action may start a proof recording.\n *\n * On-turn recording runs ffmpeg/x11grab INSIDE the box and reads the .mp4 back\n * out of the box's /tmp — plumbing that exists only for OpenGeni-operated cloud\n * boxes (the Modal desktop backend). A turn whose EFFECTIVE backend is a connected\n * machine (\"selfhosted\") runs on the user's REAL computer, which has none of that\n * capture plumbing (and the platform must never shell ffmpeg onto a user's machine\n * — the same reason the runtime skips its setup hooks for selfhosted). Left ungated\n * it films nothing, finds no /tmp file, and emits recording.started followed by\n * recording.failed{box-death} on EVERY machine-primary turn — misleading timeline\n * noise + wasted work. So gate it off, exactly like a recording-disabled deployment:\n * skip silently, emit nothing (no new event shape).\n *\n * `effectiveBackend` is the resolved ACTIVE backend for the turn\n * (resolveActiveSandboxBackend) — NOT the session's home backend. A modal-home\n * session actively swapped onto a machine resolves to \"selfhosted\" here and\n * correctly skips; a machine-home turn that degraded back to its cloud group box\n * (swap-away / flag-off) resolves to undefined and records as before.\n *\n * EDGE — mid-turn swap: this is evaluated once when computer-use first runs. A swap\n * after recording starts is deliberately ignored; the partial recording already has\n * defined failure semantics, so there is no stop/restart machinery.\n */\nexport function shouldStartOnTurnRecording(params: {\n recordingEnabled: boolean;\n desktopEnabled: boolean;\n establishedBackendId: string;\n effectiveBackend: Settings[\"sandboxBackend\"] | undefined;\n}): boolean {\n return (\n params.recordingEnabled &&\n params.desktopEnabled &&\n desktopCapableBackend(params.establishedBackendId) &&\n params.effectiveBackend !== \"selfhosted\"\n );\n}\n\n/**\n * Decide the EXPLICIT computer-use tool transport for THIS turn.\n *\n * The runtime's SDK-mirrored capability would otherwise pick hosted-vs-function\n * tools by string-sniffing the bound model instance's constructor name for\n * \"ChatCompletions\" (supportsStructuredToolOutputTransport). That is fragile: a\n * wrapped / proxied / minified model instance defeats the sniff and a\n * chat-completions provider would silently get the HOSTED `computer_use_preview`\n * tool it 400s on every turn. So the mode is decided HERE — the worker's model\n * resolution is the ONE place a provider's true wire identity is authoritative —\n * and threaded to the runtime as an explicit flag (buildAgent → computerToolMode):\n * • codex-subscription → \"function-image\": the ChatGPT/Codex backend rejects\n * hosted tool types but SEES structured `input_image` tool results.\n * • a \"chat\" (OpenAIChatCompletionsModel wire) provider → \"disabled\": it cannot\n * receive a screenshot through a proven visual transport, so computer use fails\n * closed instead of serializing the image as text.\n * • Vercel Gateway providers → \"disabled\": their curated models support ordinary\n * function tools and vision input, not OpenAI's hosted computer tool.\n * • everything else — built-in Azure/OpenAI responses, registry \"responses\"\n * providers, AND the LEGACY global-client fallback (resolveTurnModel returned\n * null) — → \"hosted\": real Responses hosted-tool support.\n *\n * Pure + exported so the mapping is unit-testable without a live turn.\n */\nexport function computerToolModeForTurn(\n resolvedModel: {\n provider: { kind: RegistryProviderKind; api: ModelProviderApi };\n configured: { capabilities: { inputModalities: string[] } };\n } | null,\n): ComputerToolMode {\n if (!resolvedModel) {\n return \"hosted\"; // legacy built-in Responses client — real hosted support\n }\n if (!modelSupportsImageInputForTurn(resolvedModel)) {\n return \"disabled\";\n }\n if (resolvedModel.provider.kind === \"codex-subscription\") {\n return \"function-image\";\n }\n if (\n resolvedModel.provider.kind === \"vercel-gateway-managed\" ||\n resolvedModel.provider.kind === \"vercel-gateway-workspace\"\n ) {\n return \"disabled\";\n }\n if (resolvedModel.provider.api === \"chat\") {\n return \"disabled\";\n }\n return \"hosted\";\n}\n\n/** Gateway models do not advertise OpenAI's hosted apply_patch/view_image tool types. */\nexport function structuredToolTransportForTurn(\n resolvedModel: { provider: { kind: RegistryProviderKind } } | null,\n): boolean {\n if (!resolvedModel) return true;\n return ![\n \"codex-subscription\",\n \"xai-subscription\",\n \"vercel-gateway-managed\",\n \"vercel-gateway-workspace\",\n ].includes(resolvedModel.provider.kind);\n}\n\n/**\n * Progressive tool disclosure is universal for supported OpenGeni turns; only\n * its contained transport differs. Codex keeps its native path, built-in direct\n * OpenAI/Azure Responses use native client tool search, and every other ordinary\n * function-calling provider uses OpenGeni's stable search/invoke dispatcher.\n */\nexport function lazyToolTransportForTurn(\n resolvedModel: {\n provider: {\n id: string;\n kind: RegistryProviderKind;\n api: ModelProviderApi;\n builtin: boolean;\n baseUrl?: string | undefined;\n };\n } | null,\n): LazyToolTransport {\n if (!resolvedModel) return \"openai_native\";\n const provider = resolvedModel.provider;\n if (provider.kind === \"codex-subscription\") return \"codex_native\";\n const isDirectBuiltinResponses =\n provider.builtin &&\n provider.api === \"responses\" &&\n (provider.id === \"azure\" || (provider.id === \"openai\" && provider.baseUrl === undefined));\n if (isDirectBuiltinResponses) {\n return \"openai_native\";\n }\n return \"generic_dispatch\";\n}\n\n/**\n * Native web search is a runtime capability, not part of the session's MCP\n * allow-list. Attach it whenever the resolved provider advertises runnable\n * support. The null model is the legacy built-in Responses path, whose\n * deployment flag is its provider capability gate. There is deliberately no\n * cross-provider or sandbox/curl fallback.\n */\nexport function hostedWebSearchForTurn(\n resolvedModel: { configured: { hostedWebSearch: boolean } } | null,\n deploymentWebSearchEnabled: boolean,\n): boolean {\n return resolvedModel?.configured.hostedWebSearch ?? deploymentWebSearchEnabled;\n}\n\n/**\n * Image generation is an optional connected-account capability. A delegated\n * subscription may still authorize the text model without carrying the local\n * credential identity required for paid image operations; that must narrow the\n * tool catalog, not reject an otherwise valid turn.\n */\nexport function connectedSubscriptionImageGenerationAuthority<T>(\n credentialContext: T | null | undefined,\n credentialId: string | null | undefined,\n): { credentialContext: T; credentialId: string } | null {\n if (credentialContext == null || typeof credentialId !== \"string\" || credentialId.length === 0)\n return null;\n return { credentialContext, credentialId };\n}\n\n/** Direct OpenAI hosted image IDs are reusable only by the exact API credential. */\nexport function openAiHostedImageProviderBindingForTurn(\n settings: Pick<Settings, \"openaiProvider\" | \"openaiApiKey\" | \"openaiBaseUrl\">,\n resolvedModel: {\n provider: {\n id: string;\n kind: RegistryProviderKind;\n builtin: boolean;\n baseUrl?: string | undefined;\n };\n configured: {\n capabilities: {\n hostedTools: { imageGeneration: { runnable: boolean } };\n };\n };\n } | null,\n): { providerId: string; providerBindingHash: string } | null {\n if (!resolvedModel?.configured.capabilities.hostedTools.imageGeneration.runnable) return null;\n const providerId = resolvedModel.provider.id;\n const isDirectOpenAi =\n resolvedModel.provider.builtin &&\n resolvedModel.provider.id === \"openai\" &&\n isDirectOpenAiApiBaseUrl(resolvedModel.provider.baseUrl) &&\n settings.openaiProvider === \"openai\" &&\n isDirectOpenAiApiBaseUrl(settings.openaiBaseUrl);\n const bindingIdentity = isDirectOpenAi ? settings.openaiApiKey : null;\n if (!bindingIdentity) return null;\n return {\n providerId,\n providerBindingHash: imageProviderBindingHash(providerId, bindingIdentity),\n };\n}\n\n/** Exact model-catalog modality gate; null preserves the legacy built-in path. */\nexport function modelSupportsImageInputForTurn(\n resolvedModel: {\n configured: { capabilities?: { inputModalities: string[] } };\n } | null,\n): boolean {\n return (\n resolvedModel === null ||\n resolvedModel.configured.capabilities?.inputModalities.includes(\"image\") !== false\n );\n}\n\nconst LEGACY_INPUT_FILE_MEDIA_TYPES = [\n \"application/json\",\n \"application/pdf\",\n \"application/x-yaml\",\n \"application/yaml\",\n \"text/*\",\n] as const;\n\n/** Image and file input are independent catalogue capabilities. */\nexport function modelAttachmentInputPolicyForTurn(\n resolvedModel: {\n provider: { api: ModelProviderApi };\n configured: {\n capabilities?: {\n inputModalities: string[];\n inputFileMediaTypes?: string[];\n };\n };\n } | null,\n): ModelAttachmentInputPolicy {\n const typedTransport = resolvedModel === null || resolvedModel.provider.api === \"responses\";\n return {\n supportsImageInput: typedTransport && modelSupportsImageInputForTurn(resolvedModel),\n inputFileMediaTypes: typedTransport\n ? (resolvedModel?.configured.capabilities?.inputFileMediaTypes ??\n LEGACY_INPUT_FILE_MEDIA_TYPES)\n : [],\n };\n}\n\nexport type TurnSandboxProvisioner<T> = {\n get(): Promise<T>;\n hasStarted(): boolean;\n waitForSettled(timeoutMs: number): Promise<T | null>;\n};\n\nexport class TurnOperationCancelledError extends Error {\n readonly name = \"TurnOperationCancelledError\";\n\n constructor(readonly reason: unknown) {\n super(\"Turn operation was cancelled with its owning turn\", {\n ...(reason instanceof Error ? { cause: reason } : {}),\n });\n }\n}\n\nexport class SandboxDeadlineRotationError extends Error {\n readonly name = \"SandboxDeadlineRotationError\";\n\n constructor(\n readonly sandboxGroupId: string,\n readonly leaseEpoch: number,\n ) {\n super(\n `Sandbox ${sandboxGroupId} reached its provider rotation boundary at lease epoch ${leaseEpoch}`,\n );\n }\n}\n\n/**\n * Normalize a preparation/provisioning cancellation race back to the Temporal\n * cancellation that owns the activity. Several provider APIs expose no portable\n * abort primitive, so the worker stops awaiting them and disposes any late\n * resource. The wrapper error must never fall through as an ordinary turn\n * failure: doing so would omit the quiescence receipt and strand a committed\n * Steer/Pause behind `control-pending`.\n */\nexport function turnOperationCancellationFailure(error: unknown): CancelledFailure | null {\n if (error instanceof CancelledFailure) return error;\n if (!(error instanceof TurnOperationCancelledError)) return null;\n return error.reason instanceof CancelledFailure\n ? error.reason\n : new CancelledFailure(\"TURN_SANDBOX_PROVISION_CANCELLED\", [], error);\n}\n\nfunction throwIfTurnOperationCancelled(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n}\n\nexport async function waitForTurnOperation<T>(\n operation: Promise<T>,\n signal: AbortSignal | undefined,\n disposeLateResult: ((result: T) => Promise<void> | void) | undefined,\n): Promise<T> {\n if (!signal) return await operation;\n\n let rejectCancellation: ((error: TurnOperationCancelledError) => void) | undefined;\n const cancelled = new Promise<never>((_resolve, reject) => {\n rejectCancellation = reject;\n });\n const cancel = (): void => {\n rejectCancellation?.(new TurnOperationCancelledError(signal.reason));\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n if (signal.aborted) cancel();\n\n try {\n const result = await Promise.race([operation, cancelled]);\n // Cancellation owns an exact turn boundary even when the provider result\n // and AbortSignal settle in the same microtask checkpoint. Never let a\n // just-resolved lease escape after the control was already committed.\n if (signal.aborted) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n return result;\n } catch (error) {\n if (signal.aborted) {\n // The provider establish call has no universal cancellation seam. It may\n // finish after the Temporal activity has correctly stopped; dispose its\n // late lease instead of letting a cancelled turn resurrect a holder/box.\n void operation\n .then(async (result) => await disposeLateResult?.(result))\n .catch(() => undefined);\n // A provider failure may settle in the same checkpoint as the committed\n // control. The control is authoritative; retain its cancellation shape\n // so the activity publishes quiescence instead of looking like an\n // unrelated turn failure.\n if (!(error instanceof TurnOperationCancelledError)) {\n throw new TurnOperationCancelledError(signal.reason);\n }\n }\n throw error;\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport function isLazySandboxProvisionRetryable(error: unknown): boolean {\n if (\n error instanceof SandboxImageConflictError ||\n error instanceof SandboxLeaseRecoveryBlockedError\n ) {\n return false;\n }\n if (error instanceof WorkspaceArchiveIntegrityError) {\n return error.retryable;\n }\n if (\n error instanceof SandboxLeaseSupersededError ||\n error instanceof SandboxLeaseTransitionError\n ) {\n return true;\n }\n if (error instanceof SandboxWarmingTimeoutError) {\n return false;\n }\n // Provider/transport text is not durable evidence that creation never\n // happened. Retrying an ambiguous unknown here can create a second box; only\n // typed, ownership-fenced lifecycle outcomes above are safe to replay.\n return false;\n}\n\n/** Short workflow-visible anti-churn pacing after a lifecycle transition. The\n * next acquire waits on the exact durable claim itself, so this is deliberately\n * not a guessed snapshot-plus-schedules completion time. */\nexport function sandboxDeadlineRotationRecoveryDelayMs(\n settings: Pick<Settings, \"sandboxLeaseReaperPeriodMs\">,\n): number {\n // The next attempt waits on the durable lifecycle claim itself. This delay is\n // only anti-churn pacing, not an estimate of snapshot + future schedules.\n return Math.min(5_000, settings.sandboxLeaseReaperPeriodMs);\n}\n\nexport function createTurnSandboxProvisioner<T>(\n establish: () => Promise<T>,\n options: {\n maxRetries?: number;\n backoffMs?: number;\n signal?: AbortSignal;\n onStarted?: () => Promise<void> | void;\n onCompleted?: (result: T) => Promise<void> | void;\n onFailed?: (error: unknown) => Promise<void> | void;\n disposeResult?: (result: T) => Promise<void> | void;\n } = {},\n): TurnSandboxProvisioner<T> {\n const maxRetries = options.maxRetries ?? 2;\n const backoffMs = options.backoffMs ?? 250;\n let memo: Promise<T> | null = null;\n\n const run = async (): Promise<T> => {\n let attempt = 0;\n while (true) {\n try {\n throwIfTurnOperationCancelled(options.signal);\n const operation = establish();\n return await waitForTurnOperation(operation, options.signal, options.disposeResult);\n } catch (error) {\n if (\n error instanceof TurnOperationCancelledError ||\n attempt >= maxRetries ||\n !isLazySandboxProvisionRetryable(error)\n ) {\n throw error;\n }\n attempt += 1;\n await sleep(backoffMs * attempt);\n }\n }\n };\n\n return {\n get(): Promise<T> {\n if (!memo) {\n memo = (async () => {\n throwIfTurnOperationCancelled(options.signal);\n await options.onStarted?.();\n throwIfTurnOperationCancelled(options.signal);\n let result: T | undefined;\n let hasResult = false;\n try {\n result = await run();\n hasResult = true;\n throwIfTurnOperationCancelled(options.signal);\n await options.onCompleted?.(result);\n return result;\n } catch (error) {\n if (hasResult) {\n await options.disposeResult?.(result as T);\n }\n if (!(error instanceof TurnOperationCancelledError)) {\n await options.onFailed?.(error);\n }\n throw error;\n }\n })().catch((error) => {\n // A terminal lease/archive/configuration result cannot change within\n // this frozen turn. Keep its rejected promise memoized so later model\n // tool calls observe the same typed result without re-entering\n // provisioning, emitting another failure event, or creating another\n // provider attempt. Only a retryable failure releases the single-flight\n // for a later operation to re-read the lease/provider state.\n if (isLazySandboxProvisionRetryable(error)) {\n memo = null;\n }\n throw error;\n });\n }\n return memo;\n },\n hasStarted(): boolean {\n return memo !== null;\n },\n async waitForSettled(timeoutMs: number): Promise<T | null> {\n if (!memo) {\n return null;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n memo.catch(() => null),\n new Promise<null>((resolve) => {\n timer = setTimeout(() => resolve(null), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n },\n };\n}\n\n/**\n * Decide whether THIS turn may send OpenAI's `prompt_cache_key` request field.\n *\n * Accepted transports:\n * - legacy/built-in OpenAI or Azure Responses fallback (resolvedModel null);\n * - resolved built-in OpenAI/Azure providers;\n * - ChatGPT/Codex subscription backend (its strict allowlist permits the field).\n *\n * Registry API-key providers are intentionally excluded. Fireworks' prompt-cache\n * docs prescribe `user` or `x-session-affinity`, not `prompt_cache_key`; Z.AI/GLM\n * documents automatic context caching plus `user_id`. Sending OpenAI-only fields\n * to unknown OpenAI-compatible providers risks unsupported-parameter 400s.\n */\nexport function acceptsPromptCacheKeyForTurn(\n resolvedModel: {\n provider: { kind: RegistryProviderKind; builtin?: boolean };\n } | null,\n): boolean {\n if (!resolvedModel) {\n return true;\n }\n return (\n resolvedModel.provider.builtin === true || resolvedModel.provider.kind === \"codex-subscription\"\n );\n}\n\n/**\n * SELF-HEAL helper for the all-capped rotation idle (invariant 4: BOUNDED, no thrash).\n * The turn hot path never refreshes Codex usage — only the usage API route does — so a\n * window that has actually reset still reads OVER-threshold from the stale cache, which\n * would idle-loop forever. Before idling, refresh LIVE usage for every connected account\n * the cache marks exhausted (bounded to the account count), which re-writes the\n * cache columns, then return the re-read rows so the ranker can pick up a genuinely-reset\n * window THIS turn. A refresh/read failure is swallowed (fall back to the pre-refresh rows\n * + the bounded idle). Cooling (429'd) accounts are NOT refreshed: their exhaustedUntil\n * cooldown is authoritative, and refreshing them would burn a provider call for nothing.\n */\nasync function refreshCappedCodexUsageRows(\n db: ActivityServices[\"db\"],\n settings: Settings,\n workspaceId: string,\n accounts: Array<\n Pick<\n CodexAccountStatus,\n \"id\" | \"status\" | \"primaryUsedPercent\" | \"secondaryUsedPercent\" | \"exhaustedUntil\"\n >\n >,\n capacitySignals: {\n signalCodexCapacityWorkflow?: ActivityServices[\"signalCodexCapacityWorkflow\"] | undefined;\n wakeSessionWorkflow: ActivityServices[\"wakeSessionWorkflow\"];\n },\n): Promise<\n Array<\n Pick<\n CodexAccountStatus,\n \"id\" | \"status\" | \"primaryUsedPercent\" | \"secondaryUsedPercent\" | \"exhaustedUntil\"\n >\n >\n> {\n const stale = accounts.filter(\n (a) =>\n a.status === \"active\" &&\n ((a.primaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT ||\n (a.secondaryUsedPercent ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT),\n );\n if (stale.length === 0) {\n return accounts;\n }\n await refreshCodexUsageAndRepairCapacityWaiters(\n stale.map((account) => () => fetchCodexUsageForAccount(db, settings, workspaceId, account.id)),\n () => signalPendingCodexCapacityWakeTargets({ db, ...capacitySignals }, workspaceId),\n );\n return listCodexAccountStatuses(db, workspaceId).catch(() => accounts);\n}\n\n/**\n * True once the lifetime last confirmed by Postgres is no longer trustworthy.\n * A missing or malformed deadline fails closed for a holder that claims to be\n * leased; callers check this before accepting an in-flight heartbeat promise.\n */\nexport function codexCredentialLeaseDeadlineExpired(\n confirmedUntilMs: number | null,\n nowMs: number = performance.now(),\n): boolean {\n return (\n confirmedUntilMs === null || !Number.isFinite(confirmedUntilMs) || confirmedUntilMs <= nowMs\n );\n}\n\ntype OpStreamFinalizer = {\n finalizeOpStreamOps(): Promise<void>;\n};\n\n/** Release retained Connected Machine output only after the turn is durable. */\nexport async function finalizeDurableTurnOpStreams(\n sessions: readonly unknown[],\n fallback: OpStreamFinalizer | null,\n): Promise<void> {\n const candidates = new Set<OpStreamFinalizer>();\n for (const session of sessions) {\n const candidate = session as Partial<OpStreamFinalizer> | null;\n if (typeof candidate?.finalizeOpStreamOps === \"function\") {\n candidates.add(candidate as OpStreamFinalizer);\n }\n }\n if (candidates.size === 0 && fallback) {\n candidates.add(fallback);\n }\n for (const candidate of candidates) {\n try {\n await candidate.finalizeOpStreamOps();\n } catch {\n // The runner's retention TTL owns the fallback.\n }\n }\n}\n\nexport function createRunAgentTurnActivity(services: () => Promise<ActivityServices>) {\n const modelCheckpointMemoryCollector = createModelCheckpointMemoryCollector();\n // Keep a distinct cooldown for terminal collection. A collection at the\n // final model checkpoint happens while the activity still owns its complete\n // turn graph and must not suppress collection after that graph is released.\n const turnCompletionMemoryCollector = createModelCheckpointMemoryCollector();\n return async function runAgentTurn(input: RunAgentTurnInput): Promise<RunAgentTurnResult> {\n const {\n settings,\n db,\n bus,\n runtime,\n summarizeContextForCompaction,\n objectStorage,\n observability,\n wakeSessionWorkflow,\n signalSessionAttemptQuiesced,\n signalCodexCapacityWorkflow,\n entitlements,\n connectionCredentials,\n startVideoGenerationWorkflow,\n } = await services();\n const activityContext = currentActivityContext();\n const cancellationSignal = activityContext?.cancellationSignal;\n // Temporal cancellation is not the only way an activity loses ownership:\n // a database attempt fence or workflow abandonment can finalize the logical\n // turn while the SDK cancellation signal remains open. Bind sandbox\n // provisioning to both lifetimes so an uninterruptible, late provider\n // promise cannot resurrect a holder after this activity has finalized.\n const sandboxResumeController = new AbortController();\n const sandboxResumeSignal = cancellationSignal\n ? AbortSignal.any([cancellationSignal, sandboxResumeController.signal])\n : sandboxResumeController.signal;\n const sandboxRotationController = new AbortController();\n const runtimeCancellationSignal = cancellationSignal\n ? AbortSignal.any([cancellationSignal, sandboxRotationController.signal])\n : sandboxRotationController.signal;\n let cancellationRequestedAt: number | null = cancellationSignal?.aborted\n ? performance.now()\n : null;\n const noteCancellationRequested = (): void => {\n cancellationRequestedAt ??= performance.now();\n };\n cancellationSignal?.addEventListener(\"abort\", noteCancellationRequested, {\n once: true,\n });\n const dispatchId = activityContext?.info.activityId ?? randomUUID();\n const activityStarted = performance.now();\n const activitySpan = observability.startSpan(\"worker.run_agent_segment\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.workflow_id\": input.workflowId,\n \"opengeni.trigger_kind\": input.trigger.kind,\n });\n let activityStatus: RunAgentTurnResult[\"status\"] | \"unknown\" = \"unknown\";\n let turnMetricOutcome: TurnOutcome | null = null;\n let activityError: unknown;\n let acknowledgeQuiescence = false;\n const acknowledgeLostAttemptOwnership = (): void => {\n // A stale terminal/recovery settlement can lose either to a benign\n // successor or to Pause/Steer closing this exact attempt. Only the\n // receipt transaction can distinguish those cases after the hard tool\n // fence: allowUninterrupted makes the benign case an event-free no-op.\n acknowledgeQuiescence = true;\n noteCancellationRequested();\n };\n const acknowledgeRecoveryQuiescence = (): void => {\n // requestSessionTurnRecovery closed this exact attempt and durably\n // recorded the replacement cause. The activity still owns the physical\n // tool/credential boundary until finally drains it and publishes the\n // exact quiescence receipt; a workflow result alone is never that proof.\n acknowledgeQuiescence = true;\n noteCancellationRequested();\n };\n let turnId: string | undefined;\n let triggerEventId: string | undefined;\n const claimedResult = (\n result: Omit<\n Extract<RunAgentTurnResult, { status: Exclude<RunAgentTurnResult[\"status\"], \"unclaimed\"> }>,\n \"turnId\" | \"attemptId\"\n >,\n ): RunAgentTurnResult => {\n if (!turnId) throw new Error(\"Claimed activity result produced before turn admission\");\n return {\n ...result,\n turnId,\n attemptId: input.attemptId,\n } as RunAgentTurnResult;\n };\n // The Connected Machine op observer for this turn: meters every op AND buffers\n // the eventable ones (infra failures + healed recoveries) as machine.op.* session\n // events, drained (awaited) at turn end in the finally below. ONE instance shared\n // by the machine-primary establish + both routing wraps.\n const machineOpObserver = makeMachineOpObserver(\n runtimeMetricsHooksForObservability(observability),\n );\n const sandboxOperationObserver = sandboxOperationMetricObserver(observability);\n let isCodexTurn = false;\n let isXaiTurn = false;\n let isExternallyBilledTurn = false;\n let executionGeneration = 0;\n let providerRecoveryCount = 0;\n let modelRequestStarted = false;\n // Still required by credential-loss/capacity settlements, whose own\n // recovery transactions fence against worker-death redispatches.\n let redispatchesAtDispatch = 0;\n const setLastInputTokensFenced = async (lastInputTokens: number | null): Promise<void> => {\n if (!turnId || executionGeneration <= 0) {\n throw new Error(\"Turn attempt was not initialized before token accounting\");\n }\n if (\n !(await setSessionLastInputTokensForTurnAttempt(db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n expectedExecutionGeneration: executionGeneration,\n expectedAttemptId: input.attemptId,\n lastInputTokens,\n }))\n ) {\n throw new TurnAttemptFencedError(\"turn attempt was fenced while recording input tokens\");\n }\n };\n let heartbeatTimer: ReturnType<typeof startActivityHeartbeat> | undefined;\n // credential allocator: one workspace-local idempotent credential holder per running\n // Codex turn. The DB row is the cross-replica fairness primitive; this timer\n // only extends its short TTL. A killed worker stops heartbeating and the\n // holder self-expires. Other workspaces never see or share this holder.\n let codexLeaseHeld = false;\n let codexLeaseLost = false;\n let codexLeaseHolderId: string | null = null;\n let codexLeaseGeneration: number | null = null;\n // Monotonic worker deadline, not a comparison between the Postgres and\n // worker wall clocks. It is advanced only after a database renewal confirms,\n // from the request START + TTL; slow queries therefore shorten (never extend)\n // the conservative ownership window.\n let codexLeaseConfirmedUntilMs: number | null = null;\n let codexLeaseHeartbeatInFlight = false;\n let codexLeaseHeartbeatTimer: ReturnType<typeof setInterval> | undefined;\n const codexWorkspaceKey = codexWorkspaceMetricKey(input.workspaceId);\n const markCodexLeaseLost = (reason: \"deadline\" | \"not_found\"): void => {\n if (codexLeaseLost) return;\n codexLeaseLost = true;\n observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: { workspace_key: codexWorkspaceKey, outcome: \"lost\", reason },\n });\n observability.warn(\"Codex credential lease was lost during an active turn\", {\n workspaceId: input.workspaceId,\n turnId,\n reason,\n });\n };\n const renewCodexLease = async (reason: \"timer\" | \"runtime_event\" | \"model_usage\") => {\n if (\n !turnId ||\n !codexLeaseHeld ||\n !codexLeaseHolderId ||\n codexLeaseGeneration === null ||\n codexLeaseLost\n )\n return;\n // Check the last expiry the database actually returned BEFORE the\n // single-flight guard. A hung heartbeat must not make later model/runtime\n // checkpoints trust a lease whose last proven lifetime already elapsed.\n if (codexCredentialLeaseDeadlineExpired(codexLeaseConfirmedUntilMs)) {\n markCodexLeaseLost(\"deadline\");\n return;\n }\n if (codexLeaseHeartbeatInFlight) return;\n codexLeaseHeartbeatInFlight = true;\n const renewalStartedAtMs = performance.now();\n try {\n const renewedUntil = await heartbeatCodexCredentialLeaseUntil(\n db,\n input.accountId,\n input.workspaceId,\n turnId,\n codexLeaseHolderId,\n codexLeaseGeneration,\n CODEX_CREDENTIAL_LEASE_TTL_MS,\n );\n if (!renewedUntil) {\n markCodexLeaseLost(\"not_found\");\n } else {\n codexLeaseConfirmedUntilMs = renewalStartedAtMs + CODEX_CREDENTIAL_LEASE_TTL_MS;\n observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: \"completed\",\n reason,\n },\n });\n }\n } catch (error) {\n // A transient DB failure does not immediately abandon a still-live row,\n // but it also cannot extend the last database-confirmed deadline.\n if (codexCredentialLeaseDeadlineExpired(codexLeaseConfirmedUntilMs)) {\n markCodexLeaseLost(\"deadline\");\n return;\n }\n observability.warn(\"Codex credential lease heartbeat failed\", {\n workspaceId: input.workspaceId,\n turnId,\n reason,\n ...safeErrorDiagnostic(error),\n });\n observability.incrementCounter({\n name: \"opengeni_codex_lease_renewals_total\",\n help: \"Codex lease renewal checkpoints by outcome and reason.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: \"error\",\n reason,\n },\n });\n } finally {\n codexLeaseHeartbeatInFlight = false;\n }\n };\n const startCodexLeaseHeartbeat = (): void => {\n if (!turnId || codexLeaseHeartbeatTimer) return;\n codexLeaseHeartbeatTimer = setInterval(() => {\n void renewCodexLease(\"timer\");\n }, 60_000);\n codexLeaseHeartbeatTimer.unref?.();\n };\n let xaiLeaseHeld = false;\n let xaiLeaseLost = false;\n let xaiLeaseSubjectId: string | null = null;\n let xaiLeaseHolderId: string | null = null;\n let xaiLeaseGeneration: number | null = null;\n let xaiLeaseConfirmedUntilMs: number | null = null;\n let xaiLeaseHeartbeatInFlight = false;\n let xaiLeaseHeartbeatTimer: ReturnType<typeof setInterval> | undefined;\n const markXaiLeaseLost = (reason: \"deadline\" | \"not_found\"): void => {\n if (xaiLeaseLost) return;\n xaiLeaseLost = true;\n observability.warn(\"xAI credential lease was lost during an active turn\", {\n workspaceId: input.workspaceId,\n turnId,\n reason,\n });\n };\n const renewXaiLease = async (): Promise<void> => {\n if (\n !turnId ||\n !xaiLeaseHeld ||\n !xaiLeaseSubjectId ||\n !xaiLeaseHolderId ||\n xaiLeaseGeneration === null ||\n xaiLeaseLost\n ) {\n return;\n }\n if (codexCredentialLeaseDeadlineExpired(xaiLeaseConfirmedUntilMs)) {\n markXaiLeaseLost(\"deadline\");\n return;\n }\n if (xaiLeaseHeartbeatInFlight) return;\n xaiLeaseHeartbeatInFlight = true;\n const renewalStartedAtMs = performance.now();\n try {\n const renewedUntil = await heartbeatXaiCredentialLeaseUntil(db, {\n workspaceId: input.workspaceId,\n subjectId: xaiLeaseSubjectId,\n turnId,\n holderId: xaiLeaseHolderId,\n generation: xaiLeaseGeneration,\n leaseTtlMs: XAI_CREDENTIAL_LEASE_TTL_MS,\n });\n if (!renewedUntil) {\n markXaiLeaseLost(\"not_found\");\n } else {\n xaiLeaseConfirmedUntilMs = renewalStartedAtMs + XAI_CREDENTIAL_LEASE_TTL_MS;\n }\n } catch (error) {\n if (codexCredentialLeaseDeadlineExpired(xaiLeaseConfirmedUntilMs)) {\n markXaiLeaseLost(\"deadline\");\n return;\n }\n observability.warn(\"xAI credential lease heartbeat failed\", {\n workspaceId: input.workspaceId,\n turnId,\n ...safeErrorDiagnostic(error),\n });\n } finally {\n xaiLeaseHeartbeatInFlight = false;\n }\n };\n const startXaiLeaseHeartbeat = (): void => {\n if (!turnId || xaiLeaseHeartbeatTimer) return;\n xaiLeaseHeartbeatTimer = setInterval(() => {\n void renewXaiLease();\n }, 60_000);\n xaiLeaseHeartbeatTimer.unref?.();\n };\n const renewServingCredentialLease = async (\n reason: \"timer\" | \"runtime_event\" | \"model_usage\",\n ): Promise<void> => {\n await renewCodexLease(reason);\n await renewXaiLease();\n };\n const servingCredentialLeaseLost = (): boolean => codexLeaseLost || xaiLeaseLost;\n // P1.2 ownership inversion: when sandboxOwnershipEnabled, the turn resolves\n // the one box by id from the group lease and injects it NON-OWNED into the\n // run. null when the flag is off (byte-for-byte the legacy build-and-discard\n // path) OR when the backend is \"none\". Released + dropped in `finally`.\n let resolvedSandbox: ResumedTurnSandbox | null = null;\n let attemptWritersDrained = false;\n const lateSandboxesAwaitingWriterDrain = new Set<ResumedTurnSandbox>();\n const releaseLateSandbox = async (sandbox: ResumedTurnSandbox): Promise<void> => {\n lateSandboxesAwaitingWriterDrain.add(sandbox);\n // Drop the holder/timer immediately, but keep its null-outcome admissions\n // fenced until the shared attempt writer drain completes. The staged\n // release serializes a later proof-bearing call behind this one.\n await sandbox.release().catch(() => undefined);\n if (!attemptWritersDrained) return;\n try {\n await releaseTurnSandboxAfterWriterDrain(sandbox);\n lateSandboxesAwaitingWriterDrain.delete(sandbox);\n } catch (error) {\n console.error(\n \"late sandbox quiesced release failed (turn outcome unaffected)\",\n safeErrorDiagnostic(error),\n );\n }\n };\n const requireResolvedSandboxForMutation = (message: string): ResumedTurnSandbox => {\n if (!resolvedSandbox) throw new Error(message);\n return resolvedSandbox;\n };\n // The machine-primary SelfhostedSession (the UNWRAPPED backend, not the\n // routing proxy). Kept as a fallback finalizer; the routing proxy normally\n // aggregates it together with every machine reached after a mid-turn swap.\n let machinePrimarySession: import(\"@opengeni/runtime\").SelfhostedSession | null = null;\n let lazyOwnedSandbox: EstablishedSandboxSession | null = null;\n let turnSandboxProvisioner: TurnSandboxProvisioner<ResumedTurnSandbox> | null = null;\n // The UN-PROXIED established box session, captured BEFORE wrapTurnBoxWithRouting.\n // Platform setup (beforeAgentStart hooks + file materialization) execs against\n // THIS handle so a mid-turn sandbox_swap can never re-route those execs onto a\n // connected machine (the user's real computer).\n let setupBoxSession: unknown = null;\n const finalizeTurnOpStreamOps = async (): Promise<void> => {\n await finalizeDurableTurnOpStreams(\n [lazyOwnedSandbox?.session, resolvedSandbox?.established.session],\n machinePrimarySession,\n );\n };\n // A same-target API repair can replace the home provider while this turn is\n // alive. Keep setup/snapshot persistence on the rebound raw session while\n // preserving the SDK-owned routing proxy for eager turns. Lazy turns hold the\n // proxy separately, so their worker-side handle may replace its raw session.\n const onHomeSandboxRebound = (rebound: {\n established: EstablishedSandboxSession;\n leaseEpoch: number;\n }): void => {\n const current = resolvedSandbox;\n const previousSession = current?.established.session;\n const preserveRoutingProxy = current !== null && previousSession !== setupBoxSession;\n setupBoxSession = rebound.established.session;\n if (!current) return;\n current.leaseEpoch = rebound.leaseEpoch;\n current.established = preserveRoutingProxy\n ? {\n ...current.established,\n client: rebound.established.client,\n // Keep the stable SDK-facing proxy; only its resolver changes the\n // underlying backend. The worker's setupBoxSession above is raw.\n session: previousSession,\n sessionState: rebound.established.sessionState,\n instanceId: rebound.established.instanceId,\n backendId: rebound.established.backendId,\n ...(rebound.established.origin ? { origin: rebound.established.origin } : {}),\n ...(rebound.established.restoredArchive\n ? { restoredArchive: rebound.established.restoredArchive }\n : {}),\n }\n : rebound.established;\n };\n // The globally unique durable turn-attempt holder id + the group id,\n // captured so the lease heartbeat can refresh the lease TTL epoch-fenced\n // (a superseded owner self-evicts) and finally can release.\n let sandboxHolderId: TurnSandboxLeaseHolderId | null = null;\n let sandboxGroupId: string | null = null;\n const runWorkspaceMutationForSandbox = async <T>(\n sandbox: ResumedTurnSandbox,\n operation: string,\n mutation: () => Promise<T>,\n ): Promise<T> => {\n // Connected machines are the user's own persistence and never dirty the\n // cloud home archive. Every persistable raw-session write batch is fenced\n // against the exact current lease/provider before the provider sees it.\n if (sandbox.established.backendId === \"selfhosted\") return await mutation();\n if (!sandboxGroupId || !sandboxHolderId || !turnId || executionGeneration <= 0) {\n throw new Error(\"Workspace mutation attempted before exact turn sandbox admission\");\n }\n const identity = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n executionGeneration,\n attemptId: input.attemptId,\n holderId: sandboxHolderId,\n sandboxGroupId,\n expectedEpoch: sandbox.leaseEpoch,\n expectedInstanceId: sandbox.established.instanceId,\n operation,\n captureWaitMs: sandboxLifecycleTransitionWaitMs(settings),\n ...(cancellationSignal ? { waitSignal: cancellationSignal } : {}),\n };\n const admission = await advanceWorkspaceGeneration(db, identity);\n let result: T;\n try {\n result = await mutation();\n } catch (providerError) {\n try {\n await verifyWorkspaceMutationSettlement(db, {\n ...identity,\n admission,\n outcome: \"rejected\",\n });\n } catch (settlementError) {\n throw new RoutingMutationOutcomeUnknownError(\n operation,\n `Platform workspace mutation \"${operation}\" rejected at the provider but lost its durable physical settlement; its outcome is unknown and it was not replayed`,\n { cause: settlementError },\n );\n }\n throw providerError;\n }\n try {\n await verifyWorkspaceMutationSettlement(db, {\n ...identity,\n admission,\n outcome: \"resolved\",\n });\n } catch (settlementError) {\n throw new RoutingMutationOutcomeUnknownError(\n operation,\n `Platform workspace mutation \"${operation}\" returned from the provider but lost its durable settlement fence; its outcome is unknown and it was not replayed`,\n { cause: settlementError },\n );\n }\n return result;\n };\n // Lease-TTL refresh timer (parallels the activity heartbeat): while the turn\n // runs it refreshes expires_at epoch-fenced so a legit multi-day turn is\n // never TTL-reaped. Cleared in finally. Only set when the flag resolved a box.\n let leaseHeartbeatTimer: ReturnType<typeof setInterval> | undefined;\n const stopLeaseHeartbeat = (): void => {\n if (!leaseHeartbeatTimer) return;\n clearInterval(leaseHeartbeatTimer);\n leaseHeartbeatTimer = undefined;\n };\n let rotationInFlight: Promise<void> | null = null;\n // credential-renewal policy: the worker, not the model, owns renewal of run-scoped Git\n // credentials for a multi-day turn. The controller is attached only after\n // the initial seed reached a real cloud box and is drained before capture.\n let gitCredentialRenewals: GitCredentialRenewalController[] = [];\n let gitCredentialRenewalClosed = false;\n // Generic host-owned run material has its own attempt-scoped renewal and\n // write handle. It is always drained and wiped before workspace capture.\n let runCredentialRenewal: RunCredentialRenewalController | null = null;\n let runCredentialRenewalClosed = false;\n let runCredentialSession: RunCredentialCommandSession | null = null;\n // The delegated Codemode bearer has a one-hour TTL. Renewal is attempt-\n // owned and attaches only after the initial token file reached a real\n // sandbox session; finalization drains an in-flight replacement.\n let codemodeTokenRenewal: CodemodeTokenRenewalController | null = null;\n let codemodeTokenRenewalClosed = false;\n // MID-SESSION snapshot single-flight guard: the heartbeat tick fires every\n // 10s but a Modal filesystem snapshot can take longer — never overlap two\n // captures on one box. The in-flight capture's promise is held so the\n // turn-end persist can await it (its capture predates the turn's final\n // writes; landing after the fresher turn-end capture started would make\n // the atomic DB throttle discard the fresher one). Interval throttling\n // itself lives in maybePersistWarmWorkspaceSnapshot / persistWarmSnapshot.\n let snapshotInFlight: Promise<void> | null = null;\n // Turn-end capture needs the lease heartbeat to keep its holder alive, but\n // must prevent that same timer from starting another periodic snapshot\n // while it reads. This gate separates those two responsibilities.\n let turnEndCaptureInProgress = false;\n // Computer-use-only recording. Ordinary shell/filesystem turns leave this\n // null; the first actual computer action starts it after :0 is ready.\n let activeRecording: ActiveRecording | null = null;\n let computerUseRecordingStart: Promise<void> | null = null;\n // P4.3 recording gate: flips true in `onComputerUseReady`, the runtime's\n // execution-time callback for the first real computer action. It must flip\n // BEFORE awaiting recording startup: the SDK tool-call stream item can arrive\n // before ffmpeg has finished starting. A plain text turn (\"hey\"/\"continue\")\n // never invokes the callback, so settlement performs no storage PUT.\n let didComputerUse = false;\n const abandonActiveRecording = async (\n reason: string,\n disposition: \"failed\" | \"discard\" = \"failed\",\n ): Promise<void> => {\n const recording = activeRecording as ActiveRecording | null;\n if (!recording) return;\n activeRecording = null;\n if (resolvedSandbox) {\n await stopRecordingOnBox(resolvedSandbox.established.session, recording.proc).catch(\n () => undefined,\n );\n }\n if (!turnId || executionGeneration <= 0) return;\n await abandonRecordingForTurnAttempt(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n executionGeneration,\n attemptId: input.attemptId,\n recordingId: recording.recordingId,\n disposition,\n reason,\n }).catch(() => undefined);\n };\n let batcher: ReturnType<typeof createRuntimeBatcher> | null = null;\n const flushRuntimeBatcher = async () => {\n const current = batcher as ReturnType<typeof createRuntimeBatcher> | null;\n await current?.flush().catch(() => undefined);\n };\n let preparedTools: Awaited<ReturnType<OpenGeniRuntime[\"prepareTools\"]>> | null = null;\n let codemodeDispatcher: CodemodeAttemptDispatcher | null = null;\n const toolCancellationFenceRef: {\n current: TurnToolCancellationFence | null;\n } = {\n current: null,\n };\n let publish: TurnEventPublisher | null = null;\n let settle:\n | ((input: {\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>;\n turnStatus:\n | \"queued\"\n | \"running\"\n | \"completed\"\n | \"failed\"\n | \"cancelled\"\n | \"requires_action\";\n sessionStatus: SessionStatus;\n activeTurnId: string | null;\n consumeRequestedCompactionFailure?: boolean;\n runState?: ApplySessionTurnSettlementInput[\"runState\"];\n }) => Promise<boolean>)\n | null = null;\n let turnStartedPublished = false;\n let stream: Awaited<ReturnType<OpenGeniRuntime[\"runStream\"]>> | undefined;\n // Reconciliation is declared before provider routing so every turn-end path\n // can share one closure. It cannot run until `stream` exists, by which time\n // this value has been rebound to the turn's resolved model policy.\n let modelRunSettings: Settings = settings;\n const publishSandboxLifecycleEvents = async (sandbox: ResumedTurnSandbox): Promise<void> => {\n const established = sandbox.established;\n if (publish && established.origin && established.origin !== \"resumed\") {\n const lifecycleEvents: Array<{\n type: \"sandbox.box.lost\" | \"sandbox.box.created\";\n payload: unknown;\n }> = [];\n if (established.lostInstanceId) {\n lifecycleEvents.push({\n type: \"sandbox.box.lost\",\n payload: { sandboxId: established.lostInstanceId },\n });\n }\n lifecycleEvents.push({\n type: \"sandbox.box.created\",\n payload: {\n sandboxId: established.instanceId,\n hydrated: established.origin === \"restored\" ? \"archive\" : \"none\",\n },\n });\n await publish(lifecycleEvents).catch(() => undefined);\n }\n };\n const publishSandboxLost = async (lostSandbox: { instanceId: string }): Promise<void> => {\n if (!publish) return;\n await publish([\n {\n type: \"sandbox.box.lost\",\n payload: { sandboxId: lostSandbox.instanceId },\n },\n ]).catch((publishError) => {\n // The lease transition is already authoritative. A fenced/failed audit\n // append must not prevent the same logical turn from recovering.\n console.error(\"sandbox box lost event publish failed\", safeErrorDiagnostic(publishError));\n });\n };\n const startLeaseHeartbeat = (\n sandbox: ResumedTurnSandbox,\n warmBackend: Settings[\"sandboxBackend\"] | undefined,\n ): void => {\n if (!sandboxHolderId || !sandboxGroupId) {\n return;\n }\n // Refresh the lease TTL on the activity-heartbeat cadence (10s, well\n // inside the 90s lease TTL). EPOCH-FENCED: a superseded owner's refresh\n // is rejected (returns false) and we stop refreshing — the box rides the\n // provider idle-timeout and the next dispatch re-establishes it. Best-\n // effort: a transient DB error must never fail the turn.\n const heartbeatEpoch = sandbox.leaseEpoch;\n const heartbeatHolderId = sandboxHolderId;\n const heartbeatGroupId = sandboxGroupId;\n // P2.1 warm-meter (tick A): while a turn runs, the heartbeat is also the\n // warm-seconds tick. GROUP+epoch+tick keyed (one box = one stream, shared\n // box metered once); epoch-fenced (a stale tick no-ops). Warm-cost is\n // metered when a per-backend rate is configured. Best-effort: a metering\n // failure must never fail the turn.\n //\n // Keyed off the EFFECTIVE backend (Stage D): a machine-primary turn has NO\n // Modal box, so it must accrue ZERO cloud warm-seconds — `selfhosted` has no\n // configured warm rate (0). Keying off turn.sandboxBackend (modal) would bill\n // cloud seconds for a box that does not exist (a real money bug). Non-machine\n // turns fall back to groupBoxBackend (the REAL box that ran): for a machine-\n // home turn that degraded to the cloud group box (swap-away / flag-off), that\n // is the deployment default (modal), so the fallback box is warm-metered at\n // the cloud rate instead of selfhosted's rate-0 (which would under-bill).\n const warmRate = sandboxWarmRateMicrosPerSecond(\n settings,\n warmBackend ?? (sandbox.established.backendId as Settings[\"sandboxBackend\"]),\n );\n leaseHeartbeatTimer = setInterval(() => {\n void heartbeatLeaseHolder(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: heartbeatGroupId,\n kind: \"turn\",\n holderId: heartbeatHolderId,\n leaseTtlMs: settings.sandboxLeaseTtlMs,\n expectedEpoch: heartbeatEpoch,\n })\n .then(async (alive) => {\n if (alive || rotationInFlight || sandboxRotationController.signal.aborted) return;\n const rotatingLease = await readLease(db, input.workspaceId, heartbeatGroupId).catch(\n () => null,\n );\n if (\n !rotatingLease ||\n rotatingLease.leaseEpoch !== heartbeatEpoch ||\n rotatingLease.instanceId !== sandbox.established.instanceId ||\n rotatingLease.rotationRequestedAt === null\n ) {\n // The holder was reaped, the exact attempt closed, the epoch was\n // superseded, or the lease began draining. Do not leave a dead\n // interval issuing DB writes and snapshot probes forever.\n stopLeaseHeartbeat();\n return;\n }\n rotationInFlight = (async () => {\n // Rotation admission already fenced all new workspace mutations.\n // Wait for an earlier periodic capture, then produce the exact\n // generation-complete checkpoint that licenses aborting this run.\n if (snapshotInFlight) {\n await waitForWarmSnapshot(\n snapshotInFlight,\n settings.sandboxSnapshotTimeoutMs,\n cancellationSignal,\n );\n }\n const snapshotSession = setupBoxSession;\n const snapshotTurnId = turnId;\n if (snapshotSession && snapshotTurnId) {\n await maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: snapshotTurnId,\n attemptId: input.attemptId,\n sandboxGroupId: heartbeatGroupId,\n },\n snapshotSession,\n heartbeatEpoch,\n cancellationSignal,\n true,\n );\n }\n const checkpointed = await readLease(db, input.workspaceId, heartbeatGroupId);\n if (\n checkpointed?.leaseEpoch === heartbeatEpoch &&\n checkpointed.rotationRequestedAt !== null &&\n checkpointed.archiveComplete &&\n !cancellationSignal?.aborted\n ) {\n sandboxRotationController.abort(\n new SandboxDeadlineRotationError(heartbeatGroupId, heartbeatEpoch),\n );\n }\n })()\n .catch((error) => {\n observability.warn(\"sandbox deadline rotation checkpoint failed; retrying\", {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n sandboxGroupId: heartbeatGroupId,\n leaseEpoch: heartbeatEpoch,\n ...safeErrorDiagnostic(error),\n });\n })\n .finally(() => {\n rotationInFlight = null;\n });\n await rotationInFlight;\n })\n .catch(() => undefined);\n void accrueWarmSeconds(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: heartbeatGroupId,\n expectedEpoch: heartbeatEpoch,\n warmRateMicrosPerSecond: warmRate,\n subjectId: input.sessionId,\n })\n .then((result) => recordCreditMicros(observability, \"usage\", result.costMicros))\n .catch(() => undefined);\n // MID-SESSION snapshot (sandbox-file-persistence): while the turn holds\n // the box, fold a fresh /workspace snapshot onto the lease every\n // sandboxSnapshotIntervalMs, so a box death the reaper never sees\n // (Modal hard timeout mid-busy, OOM, infra) costs at most one interval\n // of work — a legit multi-day turn is otherwise completely unprotected\n // (the reaper only drain-persists IDLE leases). Uses the UN-proxied box\n // session (setupBoxSession): the routing veneer could swap mid-op and a\n // selfhosted target has no persistWorkspace anyway. Best-effort +\n // single-flight; throttling lives in the helper.\n const snapshotSession = setupBoxSession;\n const snapshotTurnId = turnId;\n if (snapshotSession && snapshotTurnId && !snapshotInFlight && !turnEndCaptureInProgress) {\n snapshotInFlight = maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: snapshotTurnId,\n attemptId: input.attemptId,\n sandboxGroupId: heartbeatGroupId,\n },\n snapshotSession,\n heartbeatEpoch,\n activityContext?.cancellationSignal,\n )\n .then(async (persisted) => {\n if (persisted && publish) {\n await publish([\n {\n type: \"sandbox.box.snapshot\",\n payload: { trigger: \"heartbeat\" },\n },\n ]);\n }\n })\n .catch(() => undefined)\n .finally(() => {\n snapshotInFlight = null;\n });\n }\n }, 10_000);\n if (\"unref\" in leaseHeartbeatTimer && typeof leaseHeartbeatTimer.unref === \"function\") {\n leaseHeartbeatTimer.unref();\n }\n };\n const maybeStartOnTurnRecording = async (\n sandbox: ResumedTurnSandbox,\n effectiveBackend: Settings[\"sandboxBackend\"] | undefined,\n ): Promise<void> => {\n if (activeRecording) {\n return;\n }\n if (computerUseRecordingStart) {\n await computerUseRecordingStart;\n return;\n }\n // Called only by the runtime's first-computer-action hook. Plain sandbox\n // operations never start ffmpeg and never boot a display merely to record\n // an unused desktop. Recording failure never fails the computer action.\n if (\n shouldStartOnTurnRecording({\n recordingEnabled: settings.recordingEnabled,\n desktopEnabled: settings.sandboxDesktopEnabled,\n establishedBackendId: sandbox.established.backendId,\n // EFFECTIVE (active) backend, not the session home: a machine-primary turn\n // resolves to \"selfhosted\" and skips; a swap back to the cloud group box\n // resolves to undefined and records as before.\n effectiveBackend,\n })\n ) {\n computerUseRecordingStart = (async () => {\n let begun: Awaited<ReturnType<typeof beginRecording>> | null = null;\n try {\n begun = await beginRecording({\n settings,\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turnId!,\n recordingId: randomUUID(),\n mode: \"on-turn\",\n session: sandbox.established.session,\n runAs: sandboxRunAs(settings),\n reason: null,\n });\n if (!publish) {\n throw new Error(\"recording started before the turn event publisher was ready\");\n }\n await publish([{ type: \"recording.started\", payload: begun.started }]);\n activeRecording = begun.active;\n } catch (recordingError) {\n activeRecording = null;\n if (begun) {\n await discardUnpublishedRecording({\n db,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n active: begun.active,\n session: sandbox.established.session,\n });\n }\n console.error(\n \"computer-use recording start failed (action outcome unaffected)\",\n safeErrorDiagnostic(recordingError),\n );\n }\n })();\n await computerUseRecordingStart;\n }\n };\n // Dual-write of conversation truth (issue #35): completed items are\n // reconciled into session_history_items after every model response and at\n // every turn-end path (idempotent on position), and the sandbox recovery\n // envelope is upserted alongside. Best-effort by design: persistence\n // problems must never fail the run.\n //\n // Orphaned-tool-output guard: `stream.state.history` is NOT a plain\n // append-only array — it is a computed getter\n // (`getTurnInput(originalInput, generatedItems)`) that runs the SDK's\n // `dropOrphanToolCalls` on every access, so a `function_call` with no\n // settling result yet is transiently ABSENT from history and a later\n // reconcile sees a DIFFERENT, shorter/reordered list. A blind length\n // watermark with onConflictDoNothing-on-position then freezes the first\n // shape of a position and can persist a `function_call_result` at a tail\n // position while its `function_call` was pruned away in an earlier slice\n // and never written — the orphan that bricks the session. We defend against\n // it at the stream boundary with the turn-scoped pending-tool ledger. A\n // partial parallel batch records raw results but does not call this\n // reconciler. Once every registered call has a result, the SDK history is\n // stable and this scalar append watermark is valid again. The sanitizer\n // remains the final call/result pairing guard for every other reconcile.\n let persistedHistoryCount = 0;\n const retainedScreenshotReceiptsByCallId = new Map<string, RetainedArtifactMetadata>();\n // Set from the resolved provider wire before any model history is prepared.\n // Text-only/chat wires keep compact receipts and must never allocate image\n // bytes merely for the following request-local projection to remove them.\n let modelCanReceiveRetainedSessionImages = true;\n const generatedImageReceiptsByProviderItemId = new Map<string, GeneratedImageReceipt>();\n const generatedImageReceiptsByArtifactId = new Map<string, GeneratedImageReceipt>();\n const videoGenerationAcceptancesByCallId = new Map<\n string,\n { operationId: string; requestDigest: string }\n >();\n const requiredGeneratedVideoFiles: Array<{\n operationId: string;\n artifactId: string;\n fileId: string;\n objectKey: string;\n sizeBytes: number;\n sha256: string;\n filename: string;\n }> = [];\n let generatedImageMaterializationCache: {\n instanceId: string;\n fileIds: Set<string>;\n } | null = null;\n // Legacy ownership mode lets the Agents SDK create the sandbox inside\n // run(). Keep that exact session once the runtime exposes it so an image\n // generated later in the same model/tool loop can be copied immediately.\n let sdkOwnedSandboxSession: CodemodeTokenWriterSession | null = null;\n const prepareGeneratedImageDownload = async (receipt: GeneratedImageReceipt) => {\n if (!objectStorage) {\n throw new Error(\"Generated image sandbox materialization requires object storage\");\n }\n const file = await requireFile(db, input.workspaceId, receipt.artifact.artifactId);\n const downloadStorage = objectStorageForSandboxDownloads(modelRunSettings, objectStorage);\n const signed = await downloadStorage.createGetUrl({\n key: file.objectKey,\n });\n return {\n file,\n download: {\n fileId: file.id,\n mountPath: \"generated-images\",\n filename: file.safeFilename,\n url: signed.url,\n expiresAt: signed.expiresAt,\n sizeBytes: file.sizeBytes,\n ...(file.sha256 ? { sha256: file.sha256 } : {}),\n } satisfies SandboxFileDownload,\n };\n };\n const writeGeneratedImageDownload = async (\n sessionForDownload: CodemodeTokenWriterSession,\n download: SandboxFileDownload,\n ): Promise<void> => {\n const runAs = sandboxRunAs(modelRunSettings);\n const materialized = await materializeSandboxFileDownloads(sessionForDownload, [download], {\n onRuntimeEvent: async (event) => {\n await publish?.([{ type: event.type, payload: event.payload }], true);\n },\n ...(runAs ? { runAs } : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n });\n if (materialized.failures.length > 0) {\n throw new Error(materialized.failures[0]!.reason);\n }\n };\n const warnGeneratedImageMaterializationDeferred = (error: unknown): void => {\n // Generation and permanent retention are already durable. Never turn a\n // transient sandbox copy failure into a replay of paid provider work;\n // an unmaterialized resource is retried on the next real sandbox.\n observability.warn(\"Generated image sandbox materialization deferred\", {\n errorClass: error instanceof Error ? error.name : \"UnknownError\",\n errorCode: \"generated_image_materialization_deferred\",\n origin: \"worker\",\n });\n };\n const materializeGeneratedImageInSandbox = async (\n receipt: GeneratedImageReceipt,\n sandbox: ResumedTurnSandbox,\n sessionForDownload: unknown,\n ): Promise<boolean> => {\n try {\n const { file, download } = await prepareGeneratedImageDownload(receipt);\n const cacheable = sandbox.established.backendId !== \"selfhosted\";\n if (generatedImageMaterializationCache?.instanceId !== sandbox.established.instanceId) {\n const fileIds =\n cacheable && sandboxGroupId\n ? await getMaterializedSandboxFileResources(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId,\n expectedEpoch: sandbox.leaseEpoch,\n instanceId: sandbox.established.instanceId,\n })\n : new Set<string>();\n generatedImageMaterializationCache = {\n instanceId: sandbox.established.instanceId,\n fileIds,\n };\n }\n if (generatedImageMaterializationCache.fileIds.has(file.id)) return true;\n await runWorkspaceMutationForSandbox(\n sandbox,\n \"generatedImageMaterialization\",\n async () =>\n await writeGeneratedImageDownload(\n sessionForDownload as CodemodeTokenWriterSession,\n download,\n ),\n );\n generatedImageMaterializationCache.fileIds.add(file.id);\n if (cacheable && sandboxGroupId) {\n await markSandboxFileResourcesMaterialized(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId,\n expectedEpoch: sandbox.leaseEpoch,\n instanceId: sandbox.established.instanceId,\n fileIds: [file.id],\n });\n }\n return true;\n } catch (error) {\n warnGeneratedImageMaterializationDeferred(error);\n return false;\n }\n };\n const materializeGeneratedImageInOwnedSdkSession = async (\n receipt: GeneratedImageReceipt,\n sessionForDownload: unknown,\n ): Promise<boolean> => {\n try {\n const { download } = await prepareGeneratedImageDownload(receipt);\n await writeGeneratedImageDownload(\n sessionForDownload as CodemodeTokenWriterSession,\n download,\n );\n return true;\n } catch (error) {\n warnGeneratedImageMaterializationDeferred(error);\n return false;\n }\n };\n const materializeGeneratedImage = async (receipt: GeneratedImageReceipt): Promise<boolean> => {\n if (modelRunSettings.sandboxBackend === \"none\") return false;\n // Never allocate a cloud sandbox merely because durable history contains\n // an image. If this turn later needs one, its ready hook copies every\n // known receipt before releasing the first operation.\n if (resolvedSandbox && setupBoxSession) {\n return await materializeGeneratedImageInSandbox(receipt, resolvedSandbox, setupBoxSession);\n }\n if (sdkOwnedSandboxSession) {\n return await materializeGeneratedImageInOwnedSdkSession(receipt, sdkOwnedSandboxSession);\n }\n return false;\n };\n let nativeImageGenerationRetention: {\n providerId: string;\n providerBindingHash: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n } | null = null;\n const retainNativeGeneratedImage = async (\n output: GeneratedImageOutput,\n ): Promise<GeneratedImageReceipt> => {\n if (output.providerItemId) {\n const existing = generatedImageReceiptsByProviderItemId.get(output.providerItemId);\n if (existing) return existing;\n }\n const context = nativeImageGenerationRetention;\n if (!context || !output.providerItemId) {\n throw new Error(\"Native generated image arrived without provider retention identity\");\n }\n const retained = await retainGeneratedImage({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: context.sessionId,\n turnId: context.turnId,\n attemptId: context.attemptId,\n sourceStrategy: \"native_hosted\",\n providerId: context.providerId,\n providerBindingHash: context.providerBindingHash,\n output,\n });\n generatedImageReceiptsByProviderItemId.set(output.providerItemId, retained.receipt);\n generatedImageReceiptsByArtifactId.set(\n retained.receipt.artifact.artifactId,\n retained.receipt,\n );\n await materializeGeneratedImage(retained.receipt);\n return retained.receipt;\n };\n const retainNativeGeneratedImagesFromHistory = async (\n history: Array<Record<string, unknown>>,\n ): Promise<void> => {\n collectGeneratedImageReceipts(history, generatedImageReceiptsByProviderItemId);\n collectGeneratedImageArtifactReceipts(history, generatedImageReceiptsByArtifactId);\n for (const output of generatedImagesFromHistory(\n history,\n generatedImageReceiptsByProviderItemId,\n )) {\n if (\n !output.providerItemId ||\n generatedImageReceiptsByProviderItemId.has(output.providerItemId)\n ) {\n continue;\n }\n await retainNativeGeneratedImage(output);\n }\n assertGeneratedImageHistoryRetained(history, generatedImageReceiptsByProviderItemId);\n };\n const compactMediaRunState = (serialized: string): string =>\n compactGeneratedImageRunState(\n compactRetainedScreenshotRunState(serialized, retainedScreenshotReceiptsByCallId),\n generatedImageReceiptsByProviderItemId,\n );\n const compactApprovalRunState = (serialized: string): string =>\n compactMcpResultCustomDataRunState(compactMediaRunState(serialized));\n // Explicit image-producing tools cross the durable session-media boundary.\n // Incidental frames returned by click/scroll actions remain unretained; an\n // intentional computer_screenshot or view_image result must never be lost\n // when the event/history sanitizer removes its inline bytes.\n const retainedSessionImageCallIds = new Set<string>();\n const retainSessionImageAtToolBoundary: RetainableSessionImageOutputHook = async ({\n toolCallId,\n output,\n }) => {\n const activeTurnId = turnId;\n if (!activeTurnId) {\n throw new Error(\"Session image tool completed before turn initialization\");\n }\n const typedScreenshot = typedScreenshotFromToolOutput({\n callId: toolCallId,\n output,\n });\n retainedSessionImageCallIds.add(toolCallId);\n if (!typedScreenshot) {\n if (toolOutputContainsInlineImage(output)) {\n retainedScreenshotReceiptsByCallId.set(\n toolCallId,\n unavailableRetainedSessionImage({\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n toolCallId,\n toolOutputId: toolCallId,\n reason: \"unsupported\",\n }),\n );\n }\n return;\n }\n retainedScreenshotReceiptsByCallId.set(\n toolCallId,\n unavailableRetainedSessionImage({\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n toolCallId,\n toolOutputId: toolCallId,\n reason: \"pending\",\n }),\n );\n retainedScreenshotReceiptsByCallId.set(\n toolCallId,\n await retainComputerScreenshot({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n output: typedScreenshot,\n }),\n );\n };\n const materializeScreenshotHistory = async (history: Array<Record<string, unknown>>) => {\n collectRetainedScreenshotReceipts(history, retainedScreenshotReceiptsByCallId);\n if (!modelCanReceiveRetainedSessionImages) return history;\n return await materializeRetainedScreenshotHistory({\n db,\n objectStorage,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n history,\n });\n };\n const materializeScreenshotRunState = async (serialized: string) => {\n collectRetainedScreenshotRunStateReceipts(serialized, retainedScreenshotReceiptsByCallId);\n collectGeneratedImageRunStateArtifactReceipts(serialized, generatedImageReceiptsByArtifactId);\n const withScreenshots = modelCanReceiveRetainedSessionImages\n ? await materializeRetainedScreenshotRunState({\n db,\n objectStorage,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n serialized,\n })\n : serialized;\n return projectGeneratedImageRunStateForModel(\n compactGeneratedImageRunState(withScreenshots, generatedImageReceiptsByProviderItemId),\n );\n };\n let providerArtifactCandidates: Awaited<\n ReturnType<typeof turnInput>\n >[\"providerArtifactCandidates\"] = {\n knownHistoryItemIds: [],\n historyItemIds: [],\n };\n // Next free WHOLE-NUMBER absolute position to append at. Tracked separately\n // from persistedHistoryCount (the in-memory slice index) because a compaction\n // inserts a fractional summary position, so total rows no longer equal\n // max(position)+1 and the slice index can no longer double as the position.\n let nextHistoryPosition = 0;\n const reconcileConversationTruth = async (\n options: { skipInputOnlyRows?: boolean; requireDurable?: boolean } = {},\n ) => {\n if (!stream || !turnId) {\n return;\n }\n const durableTurnId = turnId;\n try {\n const rawHistory = (stream.state as { history?: unknown[] }).history;\n if (Array.isArray(rawHistory)) {\n const typedHistory = rawHistory as Array<Record<string, unknown>>;\n await retainNativeGeneratedImagesFromHistory(typedHistory);\n const durableHistory = compactGeneratedImageHistory(\n compactRetainedScreenshotHistory(typedHistory, retainedScreenshotReceiptsByCallId),\n generatedImageReceiptsByProviderItemId,\n );\n const { rows, nextWatermark, nextPosition } = historyRowsToAppend(\n durableHistory,\n persistedHistoryCount,\n nextHistoryPosition,\n modelRunSettings.modelToolOutputTruncationTokens,\n );\n const hasModelOrToolProgress = rows.some((row) =>\n isModelOrToolProgressHistoryItem(row.item),\n );\n const shouldAppendRows =\n rows.length > 0 && (!options.skipInputOnlyRows || hasModelOrToolProgress);\n if (shouldAppendRows) {\n await runMandatoryHistoryPersistenceStep(\"history_append\", async () => {\n const appended = await appendSessionHistoryItems(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: durableTurnId,\n expectedExecutionGeneration: executionGeneration,\n expectedAttemptId: input.attemptId,\n modelToolOutputTruncationTokens: modelRunSettings.modelToolOutputTruncationTokens,\n items: rows,\n });\n if (!appended) {\n throw new TurnAttemptFencedError(\n \"turn execution generation was fenced while saving conversation history\",\n );\n }\n });\n }\n if (shouldAppendRows || !options.skipInputOnlyRows) {\n persistedHistoryCount = nextWatermark;\n nextHistoryPosition = nextPosition;\n }\n }\n const envelope = sandboxStateEntryFromRunState(stream.state);\n if (envelope) {\n await runMandatoryHistoryPersistenceStep(\"sandbox_envelope\", () =>\n upsertSandboxSessionEnvelope(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n envelope,\n }),\n );\n }\n } catch (persistError) {\n console.error(\n \"session history dual-write failed (run unaffected)\",\n safeErrorDiagnostic(persistError),\n );\n if (options.requireDurable) throw persistError;\n }\n };\n const publishedRunCredentialNotices = new Set<string>();\n\n let variableSetId = \"\";\n // Rig telemetry (M3): set once the session loads; empty string for a rig-less\n // turn (mirrors variableSetId). Read by the activity span's finally block.\n let rigId = \"\";\n let rigVersionId = \"\";\n // The Codex account this turn runs on (pin > workspace active), resolved once\n // a codex-billed turn is confirmed and threaded into the token resolver below.\n let effectiveCodexCredentialId: string | null = null;\n let effectiveXaiCredentialId: string | null = null;\n let xaiRotationEnabled = false;\n let xaiAuthoritySnapshot: XaiProviderAccountAuthoritySnapshotV1 | null = null;\n let xaiRequestContext: XaiSubscriptionRequestContext | null = null;\n let xaiCredentialQuarantined = false;\n // The session's Codex credential BEFORE this turn resolved its own — captured\n // before recordSessionActiveCodexCredential overwrites the durable pointer, so\n // a per-call usage log can report whether the serving account CHANGED since the\n // session's previous call (the prompt-cache account-switch hypothesis).\n let priorSessionCodexCredentialId: string | null = null;\n // The latest usage-header snapshot scraped for free\n // off this turn's `/codex/responses` responses (a turn issues many model calls;\n // latest wins). Flushed ONCE into the P2 usage cache for the serving account in\n // the `finally` — cheaper than a /wham/usage poll AND it self-heals P3 rotation\n // (the proactive + 429 rankers read these exact columns). null ⇒ nothing scraped.\n // Hoisted to activity scope so the finally flush (below) sees it. The sink is\n // wired into codexContext.onUsageHeaders inside the try.\n let latestCodexUsage: CodexUsageHeaderSnapshot | null = null;\n let lastCodexRequestOpaqueArtifacts: readonly string[] = [];\n // Hoisted for same-turn recovery: an approval-decision rerun must\n // re-enter through the approval resume path (its frozen mid-flight state\n // only exists in the RunState blob), never through a swapped trigger.\n let triggerType: string | null = null;\n try {\n const claim = await claimSessionWorkForAttempt(db, input.workspaceId, {\n sessionId: input.sessionId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n attemptId: input.attemptId,\n dispatchId,\n trigger: input.trigger,\n });\n if (claim.action === \"unclaimed\") {\n activityStatus = \"unclaimed\";\n return { status: \"unclaimed\", reason: claim.reason };\n }\n const turn = claim.turn;\n turnId = turn.id;\n // Establish durable attempt ownership before any later read can fail.\n // Therefore every failure with no turnId came from the one atomic claim\n // transaction and can be classified without conflating ordinary runtime\n // or transport failures with admission failures.\n const session = await requireSession(db, input.workspaceId, input.sessionId);\n executionGeneration = turn.executionGeneration;\n providerRecoveryCount = providerRecoveryCountFromMetadata(turn.metadata);\n let installedApiIntegrations: readonly ApiIntegrationRuntime[] = [];\n const credentialSubjectId = credentialSubjectIdForTurnInitiator(turn);\n const mcpSettings = await settingsWithEnabledCapabilityMcpServers(\n db,\n input.workspaceId,\n settings,\n {\n ...(credentialSubjectId\n ? { subjectId: credentialSubjectId }\n : {\n personalConnectionDelegations: turn.personalConnectionDelegations,\n }),\n onResolvedApiIntegrations: (integrations) => {\n installedApiIntegrations = integrations;\n },\n },\n );\n // Read the active-credential flag once for the runtime capability overlay.\n // Accepted billing/provider identity comes from the turn policy below,\n // never from this mutable health snapshot.\n const codexSubscriptionActive = await workspaceCodexSubscriptionActive(\n db,\n mcpSettings,\n input.workspaceId,\n );\n const codexSettings = await settingsWithCodexCredential(\n db,\n input.workspaceId,\n mcpSettings,\n codexSubscriptionActive,\n );\n const xaiSettings = codexSettings.supergrokSubscriptionEnabled\n ? withXaiSubscriptionProvider(codexSettings)\n : codexSettings;\n const capabilitySettings = await settingsWithWorkspaceGatewayCredential(\n db,\n input.workspaceId,\n xaiSettings,\n );\n const codexAppsCredentialId = capabilitySettings.codexConnectedAppsEnabled\n ? await resolveCodexAppsCredentialIdForRun(db, input.workspaceId)\n : null;\n runtime.configure(capabilitySettings);\n const claimedPolicy = readTurnExecutionPolicyV1(turn.metadata);\n const policyForAbsent =\n claimedPolicy.kind === \"valid\"\n ? claimedPolicy.policy\n : resolveTurnExecutionPolicyV1(capabilitySettings, legacyTurnExecutionPolicyInput(turn));\n const installedPolicy = await installOrReadTurnExecutionPolicyForAttempt(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n executionGeneration,\n attemptId: input.attemptId,\n policyForAbsent,\n });\n if (!installedPolicy.accepted) {\n throw new TurnAttemptFencedError(\n `turn execution policy was fenced: ${installedPolicy.reason}`,\n );\n }\n const verifiedExecutionPolicy = assertTurnExecutionPolicyMatchesConfigV1(\n capabilitySettings,\n installedPolicy.policy,\n {\n modelId: turn.model,\n reasoningEffort: turn.reasoningEffort,\n latencyMode: turn.latencyMode,\n },\n );\n const turnExecutionPolicy = verifiedExecutionPolicy.policy;\n assertSessionAllowsProductModel(session, turnExecutionPolicy.productModelId);\n const billingIdentity = turnExecutionPolicyBillingIdentity(turnExecutionPolicy);\n isExternallyBilledTurn = billingIdentity.externallyBilled;\n isCodexTurn = billingIdentity.codexSubscription;\n isXaiTurn = billingIdentity.xaiSubscription;\n triggerEventId = turn.triggerEventId;\n const trigger = await getSessionEvent(db, input.workspaceId, triggerEventId);\n if (!trigger) {\n throw new Error(`Trigger event not found: ${triggerEventId}`);\n }\n const humanInputResume = await getHumanInputResumeForEvent(\n db,\n input.workspaceId,\n input.sessionId,\n trigger,\n );\n const interactionInterventionResume = await getInteractionInterventionResumeForEvent(\n db,\n input.workspaceId,\n input.sessionId,\n trigger,\n );\n triggerType = trigger.type;\n redispatchesAtDispatch = Number(\n (turn.metadata as { workerDeathRedispatches?: number } | null)?.workerDeathRedispatches ??\n 0,\n );\n turnLifecycleMetricsFor(observability).start(turnId);\n // §7.5 P3 — pass the accepted billing attribution (externally funded turns\n // bypass OpenGeni credit/token gates)\n // AND the optional host `entitlements` port (when bound, its admitRun replaces\n // the local credit read). Unset port → today's local-ledger path.\n await waitForTurnOperation(\n ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isExternallyBilledTurn,\n entitlements,\n ),\n cancellationSignal,\n undefined,\n );\n // Setup (variableSet load, MCP connects, sandbox restore) does not\n // stream and so never observes cancellation on its own; these explicit\n // checks let a graceful shutdown checkpoint the turn before the worker is\n // force-killed instead of riding the setup to a heartbeat timeout.\n const throwIfWorkerShuttingDown = () => {\n const reason = activityContext?.cancellationSignal.reason;\n if (isWorkerShutdownCancellation(reason)) {\n throw reason;\n }\n };\n const throwIfTurnCancelled = () => throwIfTurnOperationCancelled(cancellationSignal);\n // ONE shared details object for every heartbeat this activity sends (each\n // site spreads it + its own phase), so cross-site fields — the op-stream\n // settled roster in particular — survive last-write-wins instead of being\n // clobbered by whichever site heartbeated most recently.\n const heartbeatDetails: TurnHeartbeatDetails = {\n phase: \"running\",\n sessionId: input.sessionId,\n turnId,\n opAcks: {},\n };\n const opJournal = makeTurnOpJournal(activityContext, heartbeatDetails);\n heartbeatTimer = startActivityHeartbeat(activityContext, heartbeatDetails);\n let producerSeq = 0;\n // One producer per activity execution, not per turn: a turn can run\n // again on the same workflow (recovery, approval rerun), and\n // each execution restarts producerSeq at 1 — a shared producer id would\n // trip the per-producer uniqueness constraint on the event log. The\n // Temporal activity id is unique per scheduled execution.\n const producerId = `${input.workflowId}:${turnId}${activityContext ? `:${activityContext.info.activityId}` : \"\"}`;\n // Unique per scheduled activity execution (Temporal activityId). Folded\n // into positional usage source keys so a re-dispatch of this turn does\n // not collide its model-call charges with the prior dispatch's. A genuine\n // activity retry reuses the same activityId, so its re-emitted calls keep\n // deduping (no double charge).\n // Local/tests have no Temporal activity id; still generate an execution-\n // unique holder so a second dispatch of the same durable turn fences this\n // one exactly like production.\n codexLeaseHolderId = dispatchId;\n const modelUsageDispatchId = activityContext?.info.activityId ?? dispatchId;\n const claimedModelUsageSourceKeys = new Set<string>();\n const emittedModelUsageSourceKeys = new Set<string>();\n publish = async (\n events: Array<Omit<AppendEventInput, \"producerId\" | \"producerSeq\" | \"turnId\">>,\n immediate = false,\n ) => {\n const inputs = events.map((event) => ({\n ...event,\n payload: event.payload,\n turnId: turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\n const appended = await appendAndPublishTurnEventsFenced(\n db,\n bus,\n input.workspaceId,\n input.sessionId,\n turnId!,\n executionGeneration,\n input.attemptId,\n inputs,\n {\n onAppend: ({ durationSeconds }) =>\n recordSessionEventAppendLatency(observability, {\n durationSeconds,\n }),\n onPublish: ({ durationSeconds }) =>\n recordSessionEventPublishLatency(observability, {\n durationSeconds,\n }),\n },\n );\n if (inputs.length > 0 && !appended.accepted) {\n throw new TurnAttemptFencedError(\"turn execution generation was fenced\");\n }\n if (inputs.length > 0) {\n turnLifecycleMetricsFor(observability).progress(turnId!);\n }\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"events_published\",\n producerSeq,\n });\n if (immediate) {\n await new Promise<void>((resolve) => setTimeout(resolve, 0));\n }\n return appended;\n };\n settle = async (inputSettlement) => {\n const attemptClosing = [\"completed\", \"failed\", \"cancelled\", \"requires_action\"].includes(\n inputSettlement.turnStatus,\n );\n const recordingForSettlement =\n attemptClosing && activeRecording && resolvedSandbox\n ? (activeRecording as ActiveRecording)\n : null;\n const preparedRecording = recordingForSettlement\n ? await prepareRecordingForSettlement({\n settings,\n objectStorage,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n active: recordingForSettlement,\n session: resolvedSandbox!.established.session,\n didComputerUse,\n })\n : null;\n let recordingMutation: SessionTurnRecordingSettlement | undefined;\n if (preparedRecording) {\n const mutation = preparedRecording.mutation;\n recordingMutation =\n mutation.action === \"discard\"\n ? mutation\n : {\n ...mutation,\n producerId,\n producerSeq: ++producerSeq,\n };\n }\n const compactionRequestFailure = inputSettlement.consumeRequestedCompactionFailure\n ? {\n reason: \"summarization_failed\" as const,\n producerId,\n producerSeq: ++producerSeq,\n }\n : undefined;\n const inputs = inputSettlement.events.map((event) => ({\n ...event,\n payload: event.payload,\n turnId: turnId!,\n producerId,\n producerSeq: ++producerSeq,\n }));\n const runState = inputSettlement.runState\n ? {\n ...inputSettlement.runState,\n serializedRunState: compactMediaRunState(inputSettlement.runState.serializedRunState),\n }\n : undefined;\n const result = await applySessionTurnSettlement(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: turnId!,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n turnStatus: inputSettlement.turnStatus,\n sessionStatus: inputSettlement.sessionStatus,\n activeTurnId: inputSettlement.activeTurnId,\n events: inputs,\n ...(runState ? { runState } : {}),\n ...(recordingMutation ? { recording: recordingMutation } : {}),\n ...(compactionRequestFailure ? { compactionRequestFailure } : {}),\n });\n if (result.action === \"stale\") {\n // The terminal write can lose to a control transaction before the\n // workflow delivers Temporal cancellation. That control may settle\n // the already-closed attempt as rejected_stale, so returning without\n // this flag would strand its replacement behind quiesced_at forever.\n // Enter the same hard tool-fence/receipt path as an explicit\n // TurnAttemptFencedError. If ownership was lost for an unrelated\n // reason, allowUninterrupted makes the receipt transaction a no-op.\n acknowledgeLostAttemptOwnership();\n if (recordingForSettlement) {\n await abandonActiveRecording(\n \"recording settlement lost attempt ownership\",\n preparedRecording?.mutation.action === \"discard\" ? \"discard\" : \"failed\",\n );\n }\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return false;\n }\n turnLifecycleMetricsFor(observability).progress(turnId!);\n if (recordingForSettlement && preparedRecording) {\n if (result.recordingMutationApplied) {\n activeRecording = null;\n if (preparedRecording.deleteArtifactsAfterCommit) {\n await deleteRecordingArtifacts(\n resolvedSandbox!.established.session,\n recordingForSettlement.proc,\n );\n }\n } else {\n await abandonActiveRecording(\"recording row was unavailable during turn settlement\");\n }\n }\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, result.events);\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"events_published\",\n producerSeq,\n });\n return true;\n };\n activityContext?.heartbeat({\n ...heartbeatDetails,\n phase: \"turn_started\",\n });\n\n // A shutdown that landed during claim/billing setup stops before the turn\n // visibly starts: nothing ran yet, so the same inference starts cleanly\n // on a healthy worker.\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n recordTurnStartupPhase(observability, {\n phase: \"claim_and_policy\",\n provider: turnExecutionPolicy.providerId,\n backend: turn.sandboxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - activityStarted) / 1_000,\n });\n const turnStartSettlementStartedAt = performance.now();\n if (\n !(await settle({\n events: [\n { type: \"session.status.changed\", payload: { status: \"running\" } },\n {\n type: \"turn.started\",\n payload: { triggerEventId },\n },\n ],\n turnStatus: \"running\",\n sessionStatus: \"running\",\n activeTurnId: turnId,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n recordTurnStartupPhase(observability, {\n phase: \"turn_start_settlement\",\n provider: turnExecutionPolicy.providerId,\n backend: turn.sandboxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - turnStartSettlementStartedAt) / 1_000,\n count: 2,\n });\n turnStartedPublished = true;\n const workerPreparationStartedAt = performance.now();\n\n // Multi-account (P1): resolve the effective Codex account for this turn\n // (session-pin > workspace active) and stamp it on the session so the\n // in-session \"Running on:\" indicator reflects reality. Emit a switch event\n // when it changed from the prior run's account so the pill flips live.\n // Gated on the codex-billed predicate — non-codex turns never touch this.\n if (isCodexTurn) {\n const credentialSelectionStartedAt = performance.now();\n let credentialSelectionOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n const sessionCodex = await getSessionCodexState(db, input.workspaceId, input.sessionId);\n const sessionPin = sessionCodex?.pinnedCredentialId ?? null;\n const sessionPinSource = sessionCodex?.pinSource ?? null;\n const selectForTurn = (context: CodexCredentialLeaseSelectionContext) =>\n selectCodexCredentialLeaseForTurn({\n context,\n leasingEnabled: settings.codexCredentialLeasingEnabled,\n sessionId: input.sessionId,\n sessionPinnedCredentialId: sessionPin,\n sessionPinSource,\n sessionLastCredentialId: sessionCodex?.lastCredentialId ?? null,\n now: new Date(),\n });\n\n // Rollout/rollback path is intentionally table-inert. With the flag off,\n // old and new workers both use legacy pin > active-pointer selection and\n // neither reads nor writes the additive lease/cursor schema.\n let leased: CodexCredentialLeaseResult<RotationDecision>;\n let leaseAcquisitionStartedAtMs: number | null = null;\n if (settings.codexCredentialLeasingEnabled) {\n leaseAcquisitionStartedAtMs = performance.now();\n leased = await acquireCodexCredentialLease(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n turnId,\n holderId: codexLeaseHolderId,\n advanceActivePointer: sessionPin === null,\n },\n selectForTurn,\n );\n } else {\n const [rotation, accounts] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId),\n listCodexAccountStatuses(db, input.workspaceId),\n ]);\n const leaseAccounts = accounts.map((account) => ({\n ...account,\n activeLeaseCount: 0,\n selectionCount: 0,\n lastSelectedAt: null,\n }));\n const activeCredentialId = rotation?.activeCredentialId ?? null;\n const selected = selectForTurn({\n accounts: leaseAccounts,\n activeCredentialId,\n rotationEnabled: rotation?.rotationEnabled ?? false,\n leaseRotationEnabled: false,\n rotationStrategy: rotation?.rotationStrategy ?? \"most_remaining\",\n existingCredentialId: null,\n policyScope: null,\n unavailableDiagnostics: [],\n });\n leased = {\n ...selected,\n accounts: leaseAccounts,\n activeCredentialId,\n rotationEnabled: rotation?.rotationEnabled ?? false,\n rotationStrategy: rotation?.rotationStrategy ?? \"most_remaining\",\n reused: false,\n holderId: null,\n generation: null,\n leasedUntil: null,\n unavailableDiagnostics: [],\n advanceActivePointer: selected.advanceActivePointer !== false,\n };\n }\n if (leased.decision.kind === \"allCapped\") {\n // Bounded self-heal of stale usage cache, then ONE new atomic selection.\n await refreshCappedCodexUsageRows(db, settings, input.workspaceId, leased.accounts, {\n signalCodexCapacityWorkflow,\n wakeSessionWorkflow,\n });\n if (settings.codexCredentialLeasingEnabled) {\n leaseAcquisitionStartedAtMs = performance.now();\n leased = await acquireCodexCredentialLease(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n turnId,\n holderId: codexLeaseHolderId,\n advanceActivePointer: sessionPin === null,\n },\n selectForTurn,\n );\n } else {\n const [rotation, accounts] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId),\n listCodexAccountStatuses(db, input.workspaceId),\n ]);\n const leaseAccounts = accounts.map((account) => ({\n ...account,\n activeLeaseCount: 0,\n selectionCount: 0,\n lastSelectedAt: null,\n }));\n const selected = selectForTurn({\n accounts: leaseAccounts,\n activeCredentialId: rotation?.activeCredentialId ?? null,\n rotationEnabled: rotation?.rotationEnabled ?? false,\n leaseRotationEnabled: false,\n rotationStrategy: rotation?.rotationStrategy ?? \"most_remaining\",\n existingCredentialId: null,\n policyScope: null,\n unavailableDiagnostics: [],\n });\n leased = {\n ...selected,\n accounts: leaseAccounts,\n activeCredentialId: rotation?.activeCredentialId ?? null,\n rotationEnabled: rotation?.rotationEnabled ?? false,\n rotationStrategy: rotation?.rotationStrategy ?? \"most_remaining\",\n reused: false,\n holderId: null,\n generation: null,\n leasedUntil: null,\n unavailableDiagnostics: [],\n advanceActivePointer: selected.advanceActivePointer !== false,\n };\n }\n }\n const rotationDecision = leased.decision;\n const selectedPinDisposition = classifyCodexPin({\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n strategy: leased.rotationStrategy as CodexRotationStrategy,\n rotationEnabled: leased.rotationEnabled,\n });\n // pin policy pin persistence follows the atomic credential allocator selection. The selector\n // already ran exact-turn reuse before policy filtering and vetoed pointer\n // movement for manual/policy homes; this write only records the NEXT turn's\n // policy home (or clears a policy pin whose strategy is no longer active).\n if (\n selectedPinDisposition === \"sharded\" &&\n leased.credentialId !== null &&\n (sessionPinSource !== \"policy\" || sessionPin !== leased.credentialId)\n ) {\n const pinMutation = await withSessionCodexCapacityMutation(\n db,\n {\n workspaceId: input.workspaceId,\n reason: \"codex_policy_pin_changed\",\n },\n async (tx) => {\n const changed = await setSessionCodexPinInTransaction(\n tx,\n input.workspaceId,\n input.sessionId,\n leased.credentialId,\n \"policy\",\n {\n expected: {\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n },\n },\n );\n return { result: changed, changed };\n },\n );\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n pinMutation.wakeTargets,\n );\n } else if (selectedPinDisposition === \"clearStale\") {\n const pinMutation = await withSessionCodexCapacityMutation(\n db,\n {\n workspaceId: input.workspaceId,\n reason: \"codex_stale_policy_pin_cleared\",\n },\n async (tx) => {\n const changed = await setSessionCodexPinInTransaction(\n tx,\n input.workspaceId,\n input.sessionId,\n null,\n \"policy\",\n {\n expected: {\n pinnedCredentialId: sessionPin,\n pinSource: sessionPinSource,\n },\n },\n );\n return { result: changed, changed };\n },\n );\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n pinMutation.wakeTargets,\n );\n }\n if (\n !settings.codexCredentialLeasingEnabled &&\n leased.advanceActivePointer &&\n sessionPin === null &&\n rotationDecision.kind === \"active\" &&\n rotationDecision.moved\n ) {\n await setActiveCodexCredential(db, input.workspaceId, rotationDecision.credentialId);\n }\n effectiveCodexCredentialId = leased.credentialId;\n codexLeaseGeneration = leased.generation;\n codexLeaseConfirmedUntilMs =\n leased.leasedUntil && leaseAcquisitionStartedAtMs !== null\n ? leaseAcquisitionStartedAtMs + CODEX_CREDENTIAL_LEASE_TTL_MS\n : null;\n codexLeaseHeld =\n effectiveCodexCredentialId !== null &&\n leased.holderId !== null &&\n leased.generation !== null &&\n codexLeaseConfirmedUntilMs !== null;\n if (codexLeaseHeld) startCodexLeaseHeartbeat();\n\n const actualOutcome = effectiveCodexCredentialId\n ? \"selected\"\n : rotationDecision.kind === \"allCapped\"\n ? \"waiting\"\n : \"none\";\n const actualReason = effectiveCodexCredentialId\n ? leased.reused\n ? \"lease_reused\"\n : sessionPin === effectiveCodexCredentialId\n ? \"pin\"\n : rotationDecision.kind === \"active\" && rotationDecision.moved\n ? \"rotation\"\n : \"active\"\n : rotationDecision.kind === \"allCapped\"\n ? \"all_capped\"\n : \"none\";\n const fencedInFlight = leased.reused;\n const shadowResult = await publishCodexFleetShadowDecisionV1({\n enabled: settings.codexFleetPolicyShadowEnabled,\n decision: {\n accounts: leased.accounts,\n actualCredentialId: effectiveCodexCredentialId,\n actualOutcome,\n actualReason,\n affinityCredentialId: fencedInFlight\n ? effectiveCodexCredentialId\n : (sessionPin ?? sessionCodex?.lastCredentialId ?? null),\n fencedInFlight,\n nearExhaustionPct: settings.codexRotationNearExhaustionPct,\n now: new Date(),\n aliasSeed: randomUUID(),\n },\n publish,\n });\n if (shadowResult.outcome === \"published\") {\n const shadowPayload = shadowResult.payload;\n observability.incrementCounter({\n name: \"opengeni_codex_fleet_shadow_decisions_total\",\n help: \"Shadow decisions by bounded actual/shadow outcome and comparison.\",\n labels: codexFleetShadowDecisionMetricLabelsV1(shadowPayload),\n });\n observability.info(\"Codex adaptive fleet shadow decision\", {\n workspaceId: input.workspaceId,\n policyVersion: shadowPayload.replay.policyVersion,\n inputFingerprint: shadowPayload.replay.inputFingerprint,\n decisionFingerprint: shadowPayload.replay.decisionFingerprint,\n actualOutcome: shadowPayload.actual.outcome,\n shadowOutcome: shadowPayload.replay.decision.outcome,\n comparison: shadowPayload.comparison,\n candidateCount: shadowPayload.replay.input.candidates.length,\n truncatedCandidateCount: shadowPayload.replay.truncatedCandidateCount,\n payloadBytes: shadowResult.payloadBytes,\n });\n } else if (shadowResult.outcome === \"failed\") {\n // Shadow observability is explicitly non-authoritative. A malformed\n // snapshot or event-write fault must never change the authoritative lease,\n // capacity wait, failover, or the account serving this fenced turn.\n observability.incrementCounter({\n name: \"opengeni_codex_fleet_shadow_errors_total\",\n help: \"Shadow decision build/publication failures.\",\n labels: codexFleetShadowErrorMetricLabelsV1(shadowResult),\n });\n observability.warn(\"Codex adaptive fleet shadow decision failed open\", {\n stage: shadowResult.stage,\n reason: shadowResult.reason,\n errorClass: \"CodexFleetShadowOperationError\",\n errorCode: \"codex_fleet_shadow_failed\",\n origin: \"worker\",\n payloadBytes: shadowResult.payloadBytes,\n });\n }\n\n const eligibleCount = leased.accounts.filter((account) =>\n isCodexCredentialEligible(account, new Date()),\n ).length;\n const poolDepth = eligibleCount === 0 ? \"zero\" : eligibleCount === 1 ? \"one\" : \"many\";\n observability.incrementCounter({\n name: \"opengeni_codex_pool_observations_total\",\n help: \"Observed eligible Codex pool depth buckets at turn selection.\",\n labels: { workspace_key: codexWorkspaceKey, depth: poolDepth },\n });\n if (eligibleCount <= 1) {\n observability.incrementCounter({\n name: \"opengeni_codex_pool_low_total\",\n help: \"Alert signal emitted when the eligible Codex pool is zero or one.\",\n labels: { workspace_key: codexWorkspaceKey, depth: poolDepth },\n });\n observability.warn(\"Codex eligible credential pool is low\", {\n workspaceId: input.workspaceId,\n eligibleCount,\n connectedCount: leased.accounts.length,\n depth: poolDepth,\n });\n }\n\n if (\n effectiveCodexCredentialId === null &&\n leased.accounts.length > 0 &&\n leased.accounts.every((account) => !account.allocatorEnabled) &&\n turnId\n ) {\n if (turn.source === \"compaction\") {\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: \"codex_allocator_disabled\",\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"cancelled\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\", deferredUntilWake: true });\n }\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(\n () => null,\n );\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const armed = await armCodexCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt: null,\n resetKind: \"bounded_refresh\",\n failurePayload: {\n error: \"All connected Codex subscriptions are disabled for new allocations.\",\n code: \"codex_allocator_disabled\",\n detail: \"waiting for a credential to be re-enabled, reconnected, or added\",\n },\n });\n if (armed.action === \"waiting\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n armed.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"waiting_capacity\";\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n nextCheckAt: armed.waiter.nextCheckAt.toISOString(),\n wakeRevision: armed.waiter.wakeRevision,\n },\n });\n }\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: \"All connected Codex subscriptions are disabled for new allocations.\",\n code: \"codex_allocator_disabled\",\n retryable: false,\n recovery: \"user_message\",\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n\n if (rotationDecision.kind === \"allCapped\" && turnId) {\n if (turn.source === \"compaction\") {\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: \"codex_capacity_unavailable\",\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"cancelled\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\", deferredUntilWake: true });\n }\n // Every eligible account is capped/cooling (and a usage refresh did NOT\n // surface a reset): idle the turn AT THE BOUNDARY (no wasted model/sandbox\n // build) until the EARLIEST reset across all accounts — the multi-account\n // generalization of #143's single-account idle-until-reset. No saveRunState:\n // no model ran, nothing to freeze.\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(\n () => null,\n );\n const goalActive = Boolean(goal && goal.status === \"active\");\n // BOUNDED + POSITIVE: clamp to [MIN_IDLE_MS, max] so a null/elapsed/unknown\n // reset can never yield a 0 (which session.ts would treat as \"continue now\",\n // re-entering this path in a tight CPU/DB-hammering loop).\n const resumeMs = computeIdleDelayMs(\n rotationDecision.earliestResetAt,\n new Date(),\n CODEX_USAGE_LIMIT_MAX_RESUME_MS,\n );\n const failurePayload = codexUsageLimitFailurePayload(\n { resetsInSeconds: Math.ceil(resumeMs / 1000) },\n \"all connected Codex subscriptions are rate-limited\",\n { allAccounts: true },\n );\n const authoritativeResetAt = authoritativeCodexCapacityResetAt(\n leased.accounts,\n new Date(),\n );\n const armed = await armCodexCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: goalActive && goal ? goal.id : null,\n goalVersion: goalActive && goal ? goal.version : null,\n earliestResetAt: authoritativeResetAt,\n resetKind: authoritativeResetAt ? \"authoritative\" : \"bounded_refresh\",\n failurePayload,\n });\n if (armed.action === \"waiting\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n armed.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"waiting_capacity\";\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n nextCheckAt: armed.waiter.nextCheckAt.toISOString(),\n wakeRevision: armed.waiter.wakeRevision,\n },\n });\n }\n if (\n !(await settle!({\n events: [\n // `rotated:true` (Finding 2): the proactive all-capped wait is the SAME\n // rotation-wait state as the reactive all-capped path, so it must freeze\n // autoContinuations identically (evaluateGoalContinuation reads this marker)\n // — a goal waiting out a long reset must not burn its continuation budget on\n // the proactive path while the reactive path spares it.\n {\n type: \"turn.failed\",\n payload: {\n ...failurePayload,\n recovery: goalActive ? \"goal_continuation\" : \"user_message\",\n rotated: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n // idleUntilReset marks this a MANDATORY hold: session.ts must wait the full\n // resumeMs even if a future change made it 0 — never a tight re-dispatch.\n return claimedResult(\n goalActive\n ? {\n status: \"idle\",\n continueDelayMs: resumeMs,\n idleUntilReset: true,\n }\n : { status: \"idle\" },\n );\n }\n if (effectiveCodexCredentialId) {\n const priorAccountId = sessionCodex?.lastCredentialId ?? null;\n await recordSessionActiveCodexCredential(\n db,\n input.workspaceId,\n input.sessionId,\n effectiveCodexCredentialId,\n );\n if (priorAccountId !== effectiveCodexCredentialId) {\n const rotated = rotationDecision.kind === \"active\" && rotationDecision.moved;\n await publish([\n {\n type: \"codex.account.switched\",\n payload: {\n fromAccountId: priorAccountId,\n toAccountId: effectiveCodexCredentialId,\n reason: rotated ? \"rotation\" : \"manual\",\n },\n },\n ]);\n }\n\n const selectionReason = leased.reused\n ? \"lease_reused\"\n : sessionPin === effectiveCodexCredentialId\n ? \"pin\"\n : rotationDecision.kind === \"active\" && rotationDecision.moved\n ? \"rotation\"\n : \"active\";\n observability.incrementCounter({\n name: \"opengeni_codex_credential_selections_total\",\n help: \"Codex credential selections by strategy and reason.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n strategy: leased.rotationStrategy,\n reason: selectionReason,\n },\n });\n await publish([\n {\n type: \"codex.credential.selected\",\n payload: {\n credentialId: effectiveCodexCredentialId,\n strategy: leased.rotationStrategy,\n reason: selectionReason,\n eligibleCount,\n connectedCount: leased.accounts.length,\n reused: leased.reused,\n },\n },\n ]);\n }\n } catch (error) {\n credentialSelectionOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"credential_selection\",\n provider: \"codex-subscription\",\n backend: turn.sandboxBackend,\n outcome: credentialSelectionOutcome,\n durationSeconds: (performance.now() - credentialSelectionStartedAt) / 1_000,\n });\n }\n }\n\n if (isXaiTurn) {\n const authoritySnapshot = turn.xaiProviderAccountAuthoritySnapshot;\n xaiAuthoritySnapshot = authoritySnapshot;\n const subjectId =\n authoritySnapshot.scope === \"user\"\n ? turn.initiatingHumanSubjectId\n : \"worker:xai-workspace\";\n if (!subjectId) {\n throw new Error(\"User-scoped SuperGrok work has no frozen initiating human\");\n }\n const sessionPin = await getXaiSessionAccountPin(db, {\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n });\n const leaseStartedAtMs = performance.now();\n const leased = await acquireXaiCredentialLease(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n holderId: dispatchId,\n authoritySnapshot,\n pinnedCredentialId: sessionPin?.pinnedCredentialId ?? null,\n pinSource:\n sessionPin?.pinSource === \"manual\" || sessionPin?.pinSource === \"policy\"\n ? sessionPin.pinSource\n : null,\n });\n effectiveXaiCredentialId = leased.credentialId;\n xaiRotationEnabled = leased.rotationEnabled;\n xaiLeaseSubjectId = subjectId;\n xaiLeaseHolderId = leased.holderId;\n xaiLeaseGeneration = leased.generation;\n xaiLeaseConfirmedUntilMs = leased.leasedUntil\n ? leaseStartedAtMs + XAI_CREDENTIAL_LEASE_TTL_MS\n : null;\n xaiLeaseHeld =\n effectiveXaiCredentialId !== null &&\n leased.holderId !== null &&\n leased.generation !== null &&\n xaiLeaseConfirmedUntilMs !== null;\n if (!effectiveXaiCredentialId) {\n const connected = leased.accounts.length;\n const allocatorEnabled = leased.accounts.filter(\n (account) => account.allocatorEnabled,\n ).length;\n if (connected === 0) {\n throw Object.assign(\n new Error(\"No SuperGrok subscription account is connected for this authority scope\"),\n { code: \"xai_not_connected\" },\n );\n }\n if (turn.source === \"compaction\") {\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.cancelled\",\n payload: {\n maintenance: \"context_compaction\",\n reason: \"xai_capacity_unavailable\",\n requestPreserved: true,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"cancelled\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"cancelled\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\", deferredUntilWake: true });\n }\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(\n () => null,\n );\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const now = new Date();\n const futureResets = leased.accounts\n .map((account) => account.exhaustedUntil)\n .filter((date): date is Date => date !== null && date > now);\n const earliestResetAt = futureResets.length\n ? new Date(Math.min(...futureResets.map((date) => date.getTime())))\n : null;\n const error =\n allocatorEnabled === 0\n ? \"All connected SuperGrok subscription accounts are disabled for allocation\"\n : \"All connected SuperGrok subscription accounts are temporarily unavailable\";\n const armed = await armXaiCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n authoritySnapshot,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt,\n failurePayload: {\n error,\n code: allocatorEnabled === 0 ? \"xai_allocator_disabled\" : \"xai_capacity_unavailable\",\n detail: \"waiting for an eligible account, reconnect, pin change, or quota reset\",\n },\n });\n if (armed.action === \"waiting\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n armed.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"waiting_capacity\";\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n provider: \"xai\",\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n nextCheckAt: armed.waiter.nextCheckAt.toISOString(),\n wakeRevision: armed.waiter.wakeRevision,\n },\n });\n }\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error,\n code: \"xai_capacity_wait_stale\",\n retryable: false,\n recovery: \"user_message\",\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n if (xaiLeaseHeld) startXaiLeaseHeartbeat();\n if (\n leased.rotationEnabled &&\n sessionPin?.pinSource !== \"manual\" &&\n (sessionPin?.pinnedCredentialId !== effectiveXaiCredentialId ||\n sessionPin?.pinSource !== \"policy\")\n ) {\n await setXaiSessionAccountPin(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n credentialId: effectiveXaiCredentialId,\n pinSource: \"policy\",\n expectedVersion: sessionPin?.version ?? null,\n }).catch((error: unknown) => {\n if (error instanceof Error && error.message === \"xAI session pin changed\") return;\n throw error;\n });\n } else if (!leased.rotationEnabled && sessionPin?.pinSource === \"policy\") {\n await setXaiSessionAccountPin(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n credentialId: null,\n pinSource: null,\n expectedVersion: sessionPin.version,\n }).catch((error: unknown) => {\n if (error instanceof Error && error.message === \"xAI session pin changed\") return;\n throw error;\n });\n }\n await recordXaiSessionLastAccount(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n credentialId: effectiveXaiCredentialId,\n });\n }\n\n const runtimePreparationStartedAt = performance.now();\n\n // Pack-scoped runtime: enabled packs may declare the sandbox image this\n // workspace's sessions run in and skills for the sandbox skill index.\n // Resolved after turn.started so a composition conflict (two enabled\n // packs declaring images) fails the turn with its plain error instead\n // of failing the activity opaquely.\n const [packRuntime, installedSkillRuntime] = await Promise.all([\n resolveWorkspacePackRuntime(db, input.workspaceId),\n resolveWorkspaceInstalledSkillRuntime(db, input.workspaceId),\n ]);\n // RIG BINDING (M3): load the session's FROZEN rig version (resolved+frozen\n // at create). Everything rig-derived below (image precedence, env default\n // sets, setup hook, credential hooks, doctrine, lease/telemetry stamps) is\n // gated on this being non-null, so a rig-less session takes a zero-cost\n // branch that is byte-for-byte today's turn. Both ids are frozen together;\n // a defensive null (e.g. a since-deleted rig FK-nulled the columns) simply\n // runs the turn rig-less.\n const rigVersion =\n session.rigId && session.rigVersionId\n ? await getRigVersion(db, input.workspaceId, session.rigId, session.rigVersionId)\n : null;\n // Rig display name for the doctrine block + setup events/errors (only on a\n // rig-bound turn; null-safe fallback keeps the turn alive if the rig row is\n // gone). Loaded once here alongside the version.\n const rigName =\n rigVersion && session.rigId\n ? ((await getRigName(db, input.workspaceId, session.rigId)) ?? \"rig\")\n : null;\n // Telemetry: stamp the frozen rig binding (empty for a rig-less turn).\n rigId = session.rigId ?? \"\";\n rigVersionId = session.rigVersionId ?? \"\";\n // Workspace tier of the agent-persona resolution (session > workspace >\n // deployment default). null means the workspace has no override, so the\n // runtime falls back to runSettings.agentInstructionsTemplate (the\n // deployment default, byte-identical to the historical preamble).\n const governanceClaims = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n };\n const [workspace, companyProfileSnapshot, instructionPolicySnapshot, preferenceSnapshot] =\n await Promise.all([\n getWorkspace(db, input.workspaceId),\n getOrCreateCompanyProfileSnapshot(db, governanceClaims),\n getOrCreateWorkspaceInstructionPolicySnapshot(db, governanceClaims),\n getOrCreatePreferenceRegistrySnapshot(db, governanceClaims).catch((error) => {\n if (error instanceof PreferenceRegistryInitiatorError) return null;\n throw error;\n }),\n ]);\n if (!workspace) throw new Error(`Workspace not found: ${input.workspaceId}`);\n const workspaceAgentInstructions = workspace.agentInstructions;\n const agentHumanInputEnabled = resolveWorkspaceAgentHumanInputEnabled(workspace.settings);\n const memoryPromptMode = resolveWorkspaceMemoryPromptMode(workspace.settings);\n assertWorkspaceHumanInputAllowed(agentHumanInputEnabled, \"resume\", humanInputResume !== null);\n const companyProfileIncluded =\n memoryPromptMode === \"legacy_standing\" || session.nestedAgentDepth === 0;\n const workspaceGovernance = renderWorkspaceGovernanceContext(\n {\n companyProfile: companyProfileSnapshot,\n instructionPolicy: instructionPolicySnapshot,\n preferences: preferenceSnapshot,\n },\n {\n includeCompanyProfile: companyProfileIncluded,\n },\n );\n const structuredWorkspacePolicyActive =\n hasActiveWorkspaceInstructionPolicy(instructionPolicySnapshot);\n const workspaceMemory = await resolveWorkspaceMemoryBlock(db, input.workspaceId);\n const logicalSandboxSettings = settingsWithRigImage(\n settingsWithPackSandboxImage(\n capabilitySettings,\n packRuntime.sandboxImage,\n packRuntime.sandboxProviderImages,\n ),\n rigVersion?.image ?? null,\n );\n const providerImageSettings = await settingsWithRigProviderImage(\n logicalSandboxSettings,\n rigVersion,\n turn.sandboxBackend,\n );\n const baseRunSettings = {\n // IMAGE PRECEDENCE: rig > pre-V2 Pack compatibility > deployment.\n // resolveWorkspacePackRuntime returns no image for V2 Pack rows, so\n // settingsWithRigImage runs outermost over only the intentionally\n // retained legacy fallback. A matching verified provider-native ID is\n // then applied only to fresh creation without changing the logical\n // lease image.\n ...providerImageSettings,\n openaiModel: turn.model,\n openaiReasoningEffort: turn.reasoningEffort,\n sandboxBackend: turn.sandboxBackend,\n };\n const runSettings = await settingsWithSessionMcpServersForRun(\n db,\n input.workspaceId,\n input.sessionId,\n input.attemptId,\n baseRunSettings,\n );\n\n // Multi-provider per-turn routing → the provider gating (compaction mode,\n // hosted web search, encrypted reasoning, context window) the agent and\n // compaction summarizer must use; null falls back to the legacy global\n // client. Resolve against `capabilitySettings` (whose openaiModel is the\n // deployment default), NOT `runSettings`: runSettings.openaiModel is the\n // turn's model, so for a turn ON a registry model the built-in provider\n // would otherwise claim that id (configuredModels builds the built-in's\n // models from openaiModel) and shadow the registry entry — resolving the\n // turn to the built-in (Azure) gating while the global model router routes\n // the name to its registry provider. That mismatch attaches web_search to\n // a chat-only Fireworks model. Resolving against the default-model settings\n // keeps gating consistent with the router. Cost accounting covers registry\n // models via configuredModelPricing.\n const resolvedModel = runtime.resolveTurnModel(\n capabilitySettings,\n turnExecutionPolicy.productModelId,\n );\n const providerApi = resolvedModel?.provider.api ?? \"responses\";\n const nativeImageProviderBinding =\n providerApi === \"responses\"\n ? openAiHostedImageProviderBindingForTurn(capabilitySettings, resolvedModel)\n : null;\n const lazyToolTransport = lazyToolTransportForTurn(resolvedModel);\n const modelInputPolicy = modelAttachmentInputPolicyForTurn(resolvedModel);\n // Use the proven wire capability, not the catalogue modality alone. Chat\n // providers may advertise vision, but OpenGeni intentionally has no typed\n // image transport for that wire yet; exposing view_image there would turn\n // pixels into a multi-megabyte text/base64 function result.\n const supportsImageInput = modelInputPolicy.supportsImageInput;\n modelCanReceiveRetainedSessionImages = supportsImageInput;\n const attachmentProjector = createModelHistoryAttachmentProjector(\n db,\n input.workspaceId,\n modelInputPolicy,\n objectStorage ? (file) => objectStorage.getFileBytes(file) : undefined,\n );\n const modelHistoryProjector = async (items: Array<Record<string, unknown>>) =>\n projectModelInputForCapabilities(await attachmentProjector(items), modelInputPolicy);\n const generatedImageHistoryProjector = async (\n items: Array<Record<string, unknown>>,\n ): Promise<Array<Record<string, unknown>>> => {\n collectGeneratedImageReceipts(items, generatedImageReceiptsByProviderItemId);\n collectGeneratedImageArtifactReceipts(items, generatedImageReceiptsByArtifactId);\n return projectGeneratedImageHistoryForModel(items);\n };\n const compactionModelHistoryProjector = async (items: Array<Record<string, unknown>>) =>\n await modelHistoryProjector(\n projectHistoryForProvider(\n await generatedImageHistoryProjector(restoreGenericDispatchHistoryItems(items)),\n providerApi,\n ),\n );\n // Bind the provider/model catalog's context policy to every model-facing\n // path for this turn. In particular, Codex subscription turns must not\n // inherit the deployment's OpenAI/Azure mode or 1.05M context defaults:\n // raw window, effective ceiling, and auto-compact limit are distinct live\n // catalog values and must reach pre-turn compaction, history guards, and\n // every model call together.\n modelRunSettings = resolvedModel\n ? settingsWithResolvedModelContext(runSettings, resolvedModel.configured)\n : runSettings;\n // WORKSPACE MODEL POLICY — the authoritative hard gate. Runs immediately\n // after resolution and BEFORE any model call (the compaction summarizer\n // and the main run both come later in this scope), so a blocked\n // provider/model can never be reached through ANY stamp path: explicit\n // turn model, inherited session default, goal-continuation inheritance,\n // or the legacy null-resolution fallback. The frozen execution policy is\n // the attribution source even if an injected test runtime returns no\n // concrete resolved model. Fail-loud, never a silent remap.\n {\n const workspaceModelPolicy = await getWorkspaceModelPolicy(db, input.workspaceId);\n if (workspaceModelPolicy) {\n const verdict = evaluateWorkspaceModelPolicy(workspaceModelPolicy, {\n providerId: turnExecutionPolicy.providerId,\n modelId: turnExecutionPolicy.productModelId,\n });\n if (!verdict.allowed) {\n throw new WorkspaceModelPolicyBlockedError(\n turnExecutionPolicy.productModelId,\n turnExecutionPolicy.providerId,\n verdict.reason,\n );\n }\n }\n }\n // A recovered asynchronous video completion is model-visible only after\n // its durable File is present at the exact sandbox path carried by the\n // receipt. Resolve and verify the claimed update before sandbox policy is\n // chosen so this turn cannot remain lazy and expose an absent path.\n for (const update of await listSessionSystemUpdatesForTurn(\n db,\n input.workspaceId,\n input.sessionId,\n turn.id,\n )) {\n const payload = update.payload as MediaGenerationResult;\n if (payload.type !== \"media_generation_result\" || payload.status !== \"ready\") continue;\n const retained = await getGeneratedVideoArtifact(\n db,\n input.workspaceId,\n payload.receipt.artifact.artifactId,\n );\n if (\n !retained ||\n retained.artifact.deletedAt ||\n retained.file.status !== \"ready\" ||\n retained.file.contentType !== \"video/mp4\" ||\n retained.file.sizeBytes !== payload.receipt.artifact.originalBytes ||\n retained.file.sha256 !== payload.receipt.artifact.sha256 ||\n retained.artifact.sandboxFilename !== `generated-video-${retained.artifact.id}.mp4`\n ) {\n throw new Error(\"Generated video completion does not match its retained File\");\n }\n requiredGeneratedVideoFiles.push({\n operationId: payload.operationId,\n artifactId: retained.artifact.id,\n fileId: retained.file.id,\n objectKey: retained.file.objectKey,\n sizeBytes: retained.file.sizeBytes,\n sha256: retained.file.sha256,\n filename: retained.artifact.sandboxFilename,\n });\n }\n // A codex-subscription turn resolves the bearer for THIS turn's effective\n // codex account (effectiveCodexCredentialId; pin > workspace-active) at\n // model-call time — multi-account P1 means a workspace can hold N accounts,\n // so the bearer is per-account, not per-workspace. codexSubscriptionFetch\n // (on the provider's OpenAI client) reads this AsyncLocalStorage context.\n // Build it once and wrap BOTH the compaction summarizer (a separate model\n // call on the same codex client) and the main run; otherwise the summarizer\n // would hit the codex backend unauthenticated.\n let codexModelRequestSequence = 0;\n let firstModelRequestPreparationStartedAt: number | null = null;\n let firstModelRequestPreparationRecorded = false;\n let firstModelRequestAuditRecorded = false;\n let firstModelRequestCheckpointAt: number | null = null;\n const firstModelRequestCheckpoints = new Set<string>();\n const codexContext: CodexRequestContext | null =\n resolvedModel?.provider.kind === \"codex-subscription\"\n ? ((): CodexRequestContext => {\n // The empty-string fallback yields no row → null credential → the\n // existing CodexReloginRequired path (a codex turn with no usable\n // account fails closed, exactly as before multi-account).\n const resolver = buildCodexTokenResolver(\n db,\n runSettings,\n input.workspaceId,\n effectiveCodexCredentialId ?? \"\",\n );\n return {\n clientVersion: CODEX_CLIENT_VERSION,\n // Backend sticky cache-routing key — the SAME id as the body's\n // prompt_cache_key (set from input.sessionId for codex turns),\n // so routing and cache key agree. Without this header on the\n // wire, byte-identical resends hit the prompt cache ~50%\n // (per-request shard lottery = prod's measured 48.6% on sol);\n // with it, resends pin to the warm shard (Codex CLI parity).\n sessionId: input.sessionId,\n getToken: () => resolver.getToken(),\n refresh: () => resolver.refresh(),\n resolveModel: buildModelResolver(\n CODEX_FALLBACK_MODEL_SLUGS,\n CODEX_FALLBACK_MODEL_SLUGS[0],\n ),\n onUsageHeaders: (snapshot) => {\n latestCodexUsage = snapshot;\n }, // latest wins; flushed once in finally\n onRequestPreparationDiagnostic: (phase) => {\n if (\n firstModelRequestCheckpointAt === null ||\n firstModelRequestCheckpoints.has(phase)\n ) {\n return;\n }\n const now = performance.now();\n const metricPhase =\n phase === \"transport_entry\"\n ? \"model_sdk_serialization\"\n : phase === \"credential_ready\"\n ? \"model_credential_resolution\"\n : \"model_wire_normalization\";\n firstModelRequestCheckpoints.add(phase);\n recordTurnStartupPhase(observability, {\n phase: metricPhase,\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (now - firstModelRequestCheckpointAt) / 1_000,\n count: turnTools.length,\n });\n firstModelRequestCheckpointAt = now;\n },\n onRequestOpaqueArtifacts: ({ fingerprints }) => {\n lastCodexRequestOpaqueArtifacts = fingerprints;\n },\n onModelRequestDiagnostic: (event) => {\n if (\n event.phase === \"started\" &&\n firstModelRequestPreparationStartedAt !== null &&\n !firstModelRequestPreparationRecorded\n ) {\n firstModelRequestPreparationRecorded = true;\n recordTurnStartupPhase(observability, {\n phase: \"model_request_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds:\n (performance.now() - firstModelRequestPreparationStartedAt) / 1_000,\n count: turnTools.length,\n });\n }\n const phase =\n event.phase === \"headers\"\n ? \"headers\"\n : event.phase === \"first_byte\"\n ? \"first_byte\"\n : event.phase === \"completed\" ||\n event.phase === \"failed\" ||\n event.phase === \"timed_out\"\n ? \"terminal\"\n : null;\n if (!phase) return;\n recordModelRequestPhase(observability, {\n provider: \"codex-subscription\",\n phase,\n ...(event.phase === \"completed\"\n ? { outcome: \"completed\" as const }\n : event.phase === \"failed\"\n ? { outcome: \"failed\" as const }\n : event.phase === \"timed_out\"\n ? { outcome: \"timed_out\" as const }\n : {}),\n durationSeconds: event.durationMs / 1000,\n });\n },\n nextRequestId: () => `${dispatchId}:${++codexModelRequestSequence}`,\n onModelRequestEvent: async (event) => {\n if (!publish || !turnId) {\n throw new Error(\"Codex model request started before the turn event producer\");\n }\n const shouldRecordStartedAudit =\n event.phase === \"started\" && !firstModelRequestAuditRecorded;\n if (shouldRecordStartedAudit) {\n firstModelRequestAuditRecorded = true;\n }\n const auditStartedAt = shouldRecordStartedAudit ? performance.now() : null;\n let auditOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n await publish([\n {\n type: \"agent.model.request\",\n payload: {\n ...event,\n provider: \"codex-subscription\",\n turnId,\n attemptId: input.attemptId,\n dispatchId,\n executionGeneration,\n },\n },\n ]);\n } catch (error) {\n auditOutcome = \"failed\";\n throw error;\n } finally {\n if (auditStartedAt !== null) {\n recordTurnStartupPhase(observability, {\n phase: \"model_request_audit\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: auditOutcome,\n durationSeconds: (performance.now() - auditStartedAt) / 1_000,\n count: turnTools.length,\n });\n }\n }\n },\n };\n })()\n : null;\n if (resolvedModel?.provider.kind === \"xai-subscription\") {\n if (!effectiveXaiCredentialId || !xaiLeaseSubjectId) {\n throw new Error(\"SuperGrok subscription execution has no leased credential\");\n }\n let xaiModelRequestSequence = 0;\n const authorization = await buildXaiTurnRequestAuthorization({\n db,\n settings: runSettings,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: xaiLeaseSubjectId,\n sessionId: input.sessionId,\n turnId: turn.id,\n credentialId: effectiveXaiCredentialId,\n authoritySnapshot: turn.xaiProviderAccountAuthoritySnapshot,\n hostedSearch: {\n webSearch: runSettings.webSearchEnabled,\n xSearch: runSettings.webSearchEnabled,\n },\n nextRequestId: () => `${dispatchId}:xai:${++xaiModelRequestSequence}`,\n });\n xaiRequestContext = authorization.context;\n }\n const withCodex = <T>(fn: () => Promise<T>): Promise<T> =>\n codexContext ? codexRequestStorage.run(codexContext, fn) : fn();\n const withProviderRequestContext = <T>(fn: () => Promise<T>): Promise<T> =>\n xaiRequestContext\n ? xaiSubscriptionRequestStorage.run(xaiRequestContext, fn)\n : withCodex(fn);\n const withCodexRemoteCompaction = <T>(fn: () => Promise<T>): Promise<T> =>\n withCodex(() =>\n withCodexRequestOverrides(\n {\n betaFeatures: [REMOTE_COMPACTION_V2_BETA_FEATURE],\n turnMetadata: {\n request_kind: \"compaction\",\n compaction: {\n implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,\n strategy: \"memento\",\n },\n },\n },\n fn,\n ),\n );\n const promptCacheKey = acceptsPromptCacheKeyForTurn(resolvedModel)\n ? input.sessionId\n : undefined;\n const compactionUsageState = createCompactionModelUsageEventState(\n claimedModelUsageSourceKeys,\n );\n const recordCompactionUsage = async (usage: ModelResponseUsage) => {\n await processCompactionModelUsageEvent({\n usage,\n state: compactionUsageState,\n dispatchId: modelUsageDispatchId,\n settings,\n db,\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: resolvedModel?.configured.id ?? turn.model,\n externallyBilled: isExternallyBilledTurn,\n turnAttemptId: input.attemptId,\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n renewLease: () => renewServingCredentialLease(\"model_usage\"),\n leaseLost: servingCredentialLeaseLost,\n leaseLostMessage: \"Provider credential lease expired during context compaction\",\n });\n };\n const compactionSummarizerFor = (systemInstructions?: string) =>\n resolvedModel\n ? (s: Settings, m: Array<Record<string, unknown>>) =>\n withProviderRequestContext(() =>\n summarizeContextForCompaction(s, m, {\n client: resolvedModel.client,\n provider: resolvedModel.provider,\n api: resolvedModel.provider.api,\n model: turnExecutionPolicy.upstreamModelId,\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n onUsage: recordCompactionUsage,\n ...(systemInstructions ? { systemInstructions } : {}),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n }),\n )\n : (s: Settings, m: Array<Record<string, unknown>>) =>\n summarizeContextForCompaction(s, m, {\n model: turnExecutionPolicy.upstreamModelId,\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n onUsage: recordCompactionUsage,\n ...(systemInstructions ? { systemInstructions } : {}),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n });\n // Prompt-cache prefix for remote_v2 MUST match ordinary turns:\n // tools → instructions → history. Filled after buildAgent for every\n // compact path (including operator /compact, which now builds the agent\n // first so it does not send empty tools/instructions).\n let remoteCompactionTools: Awaited<ReturnType<typeof serializedToolsForRemoteCompaction>> =\n [];\n let remoteCompactionInstructions = \"\";\n let remoteCompactionToolsReady = false;\n let remoteCompactionAgent: Parameters<typeof serializedToolsForRemoteCompaction>[0] | null =\n null;\n const remoteCompactionRequester =\n resolvedModel && isCodexTurn\n ? (s: Settings, m: Array<Record<string, unknown>>) =>\n withCodexRemoteCompaction(async () => {\n // Lazily serialize tools here so EmptyCompactionSummaryError is\n // thrown inside the compaction try/settlement handlers, not as a\n // raw activity failure before maybeCompactContext runs.\n if (!remoteCompactionInstructions.trim()) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_instructions\",\n reason: \"agent_missing_system_instructions\",\n });\n }\n if (!remoteCompactionToolsReady) {\n if (!remoteCompactionAgent) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_tools\",\n reason: \"agent_missing_for_tools\",\n });\n }\n try {\n remoteCompactionTools =\n await serializedToolsForRemoteCompaction(remoteCompactionAgent);\n } catch (error) {\n // Tool schemas sit before instructions in the cache prefix.\n // Failing open to [] would reintroduce a massive pre-compact\n // cache bust — fail closed so we never send a tools mismatch\n // on purpose.\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_tools\",\n reason: \"serialize_tools_failed\",\n error: String(error),\n });\n }\n remoteCompactionToolsReady = true;\n }\n return requestRemoteCompactionV2(s, m, {\n client: resolvedModel.client,\n provider: resolvedModel.provider,\n model: turnExecutionPolicy.upstreamModelId,\n systemInstructions: remoteCompactionInstructions,\n onUsage: recordCompactionUsage,\n tools: remoteCompactionTools,\n ...(promptCacheKey ? { promptCacheKey } : {}),\n });\n })\n : undefined;\n const publishCompactionLiveEvents = async (events: SessionEvent[]) => {\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events);\n };\n const publishCompactionOutcomeEvents = async (events: SessionEvent[]) => {\n // `compaction.started` was already fanout via publishCompactionLiveEvents.\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n events.filter((event) => event.type !== \"session.context.compaction.started\"),\n );\n };\n const compactionModeOptions = {\n codexCompactionMode: session.codexCompactionMode,\n isCodexSubscriptionTurn: isCodexTurn,\n publishLiveEvents: publishCompactionLiveEvents,\n ...(remoteCompactionRequester\n ? { requestRemoteCompactionV2: remoteCompactionRequester }\n : {}),\n } as const;\n\n // Operator /compact:\n // - portable (incl. Codex portable): early maintenance path — no\n // prepareTools/sandbox; summarizer only needs composed instructions.\n // - remote_v2: fall through to prepareTools/buildAgent so the compact\n // request reuses the ordinary tools→instructions cache prefix, then\n // settle without inference. (Requester is also wired for Codex portable\n // turns but unused there — gate on the frozen session mode.)\n const compactionOnlyTurn = turn.source === \"compaction\";\n const remoteV2CompactionNeedsAgentPrefix =\n Boolean(remoteCompactionRequester) && session.codexCompactionMode === \"remote_v2\";\n if (compactionOnlyTurn && !remoteV2CompactionNeedsAgentPrefix) {\n const persistentSessionSettings = {\n titleIsSet: Boolean(session.title?.trim()),\n };\n const compactionInstructions = appendWorkspaceMemory(\n appendPersistentSessionSettings(\n appendSessionGoal(\n appendSessionInstructions(\n appendWorkspaceGovernance(\n composeAgentInstructions(\n structuredWorkspacePolicyActive\n ? modelRunSettings.agentInstructionsTemplate\n : (workspaceAgentInstructions ?? modelRunSettings.agentInstructionsTemplate),\n undefined,\n rigVersion && rigName\n ? { name: rigName, version: rigVersion.version }\n : undefined,\n ),\n workspaceGovernance ?? undefined,\n ),\n session.instructions ?? undefined,\n ),\n turn.goalSnapshot,\n ),\n persistentSessionSettings,\n ),\n workspaceMemory ?? undefined,\n );\n const requested = await isSessionCompactionRequested(\n db,\n input.workspaceId,\n input.sessionId,\n );\n let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;\n if (requested) {\n try {\n outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n compactionSummarizerFor(compactionInstructions),\n {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n materializeHistory: materializeScreenshotHistory,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n } catch (error) {\n // Codex retries retryable checkpoint-provider failures rather than\n // treating them as a semantic compaction result. Keep the operator\n // request pending and let the ordinary same-turn provider/capacity\n // recovery path re-dispatch this exact maintenance execution.\n if (shouldRecoverCompactionProviderFailure(error)) throw error;\n if (error instanceof TurnAttemptFencedError) throw error;\n // `compaction.started` may already be live — settle skipped before\n // failing the turn so the timeline cannot stick on Compacting…\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: true,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(error)) throw error;\n const errorMessage = String(compactionFailureReasonFromError(error));\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(landmark.requestConsumed ? {} : { consumeRequestedCompactionFailure: true }),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = error;\n return claimedResult({ status: \"idle\" });\n }\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, \"operator\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n }\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n maintenance: \"context_compaction\",\n result: outcome?.compacted ? \"compacted\" : (outcome?.reason ?? \"already_applied\"),\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n\n const turnResources = mergeResourceRefs(session.resources, turn.resources);\n // Attach the first-party MCP server to EVERY turn, regardless of how/when\n // the session was created (API, scheduled task, or a pre-existing session\n // whose stored tools predate this). The server registration is then\n // narrowed by the session's exact firstPartyMcpTools selection and\n // authorization. Idempotent: mergeToolRefs dedupes if already present.\n // Resolve the durable policy at the turn boundary. Workspace-default\n // sessions follow the current configured MCP set,\n // while explicit, inherited-fixed, and legacy sessions remain narrowed\n // to their stored materialized allow-list.\n const resolvedToolPolicy = resolveSessionToolPolicy({\n toolPolicy: session.toolPolicy,\n sessionTools: session.tools,\n availableMcpServerIds: runSettings.mcpServers.map((server) => server.id),\n defaultMcpServerIds: defaultSessionMcpServerIds(capabilitySettings.mcpServers),\n });\n const mcpAvailabilityInstructions = unavailableMcpTurnInstructions({\n droppedIds: resolvedToolPolicy.effectivePolicy.droppedIds,\n droppedCount: resolvedToolPolicy.effectivePolicy.counts.dropped,\n });\n const effectivePolicyTools = resolvedToolPolicy.toolRefs;\n const turnTools = withFirstPartyTools(runSettings, effectivePolicyTools);\n // §7.6 connection-credential provider — load (and decrypt) the variable set via the host\n // `sandboxSecrets` provider when bound; unset → today's local decrypt.\n const connectionScope = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n };\n const workspaceVariableSet = await waitForTurnOperation(\n loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n session.variableSetId,\n connectionCredentials?.sandboxSecrets,\n ),\n cancellationSignal,\n undefined,\n );\n variableSetId = workspaceVariableSet?.id ?? \"\";\n // RIG DEFAULT VARIABLE SETS (M3): decrypt the frozen rig version's default\n // variable sets and layer them BELOW the session's own set — the session's\n // values WIN on any key collision. Loaded through the SAME host-secrets\n // provider path as the session set (embedded-topology parity). Precedence\n // WITHIN the rig defaults is listed order (a later set overrides an earlier\n // one), then the session set overrides all. STABLE-ENV INVARIANT: the rig\n // VERSION is frozen per session, so the SET of default variable sets is\n // fixed for the session's life — the merged manifest env is therefore stable\n // across the session's turns (the same guarantee the session's own variable\n // set already relies on), keeping validateNoEnvironmentDelta empty.\n const rigDefaultEnvironmentValues: Record<string, string> = {};\n for (const rigDefaultVariableSetId of rigVersion?.defaultVariableSetIds ?? []) {\n const rigDefaultSet = await waitForTurnOperation(\n loadWorkspaceEnvironmentForRunWithCredentials(\n db,\n runSettings,\n connectionScope,\n rigDefaultVariableSetId,\n connectionCredentials?.sandboxSecrets,\n ),\n cancellationSignal,\n undefined,\n );\n Object.assign(rigDefaultEnvironmentValues, rigDefaultSet?.values ?? {});\n }\n // Session set wins collisions with the rig defaults (explicit precedence).\n const sandboxWorkspaceEnvironmentValues = mergeRigDefaultVariableSetEnvironment(\n rigDefaultEnvironmentValues,\n workspaceVariableSet?.values ?? {},\n );\n // EFFECTIVE compute backend, resolved ONCE at turn start (Case B + Stage D\n // D1-lite) and reused for EVERY downstream decision: the env mint (skip\n // inert platform git tokens for a machine turn), the establish path (no phantom Modal\n // home box for a machine-primary turn), buildAgent (skip the repository clone\n // hook so a private repo is never `git clone`d onto the user's real disk), and\n // the warm-rate (a machine accrues ZERO cloud warm-seconds). The active pointer\n // + its sandbox row are loaded ONCE here (best-effort, never throwing) and the\n // SAME values feed resolveActiveSandboxBackend (the tested gate) AND the\n // machine-primary establish branch (enrollmentId/epoch/workingDir) below — no\n // double read, no read-skew between the gate decision and the establish. With\n // routing OFF this is byte-for-byte the legacy path: no reads, undefined backend.\n const routingOn = routingEnabled(settings);\n let activeSandboxPointer = routingOn\n ? await readActiveSandbox(db, input.workspaceId, input.sessionId).catch(() => null)\n : null;\n // TURN-START RECONCILE (issue #341 invariant B / Shapes 1+2): a persisted\n // pointer whose target is STRUCTURALLY unestablishable at turn start would strand\n // EVERY op of this turn — reset it to the session HOME under the epoch fence +\n // emit a visible event, honoring a concurrent higher-epoch swap. The sandbox row\n // is loaded HERE, inside reconcile, via a NON-swallowing lookup: a null decision\n // then means the row is genuinely absent, never a suppressed transient DB error\n // (which would wrongly clear a healthy user-chosen pointer). On a lookup throw the\n // reconcile fails open — pointer untouched, record null (machinePrimary:false),\n // no event — and the establish branch below reads the returned values.\n let activeSandboxRecord: SandboxRecord | null = null;\n if (routingOn) {\n const reconciled = await reconcileActiveSandboxPointer(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n },\n activeSandboxPointer,\n (sandboxId) => getSandbox(db, input.workspaceId, sandboxId),\n publish\n ? async (events) => {\n await publish!(events);\n }\n : undefined,\n );\n activeSandboxPointer = reconciled.pointer;\n activeSandboxRecord = reconciled.record;\n }\n const activeSandboxBackend = await resolveActiveSandboxBackend(\n routingOn,\n async () => activeSandboxPointer,\n async () => activeSandboxRecord?.kind ?? null,\n );\n // A machine-primary turn = the effective backend is selfhosted AND we have the\n // machine's enrollment (agent id) + a non-null pointer to bind it. Anything\n // missing (should not happen — the DB enforces selfhosted⇒enrollmentId) falls\n // back to the cloud establish path (a correct, if phantom, box) rather than\n // crashing the turn.\n const machinePrimary =\n activeSandboxBackend === \"selfhosted\" &&\n Boolean(activeSandboxPointer?.activeSandboxId) &&\n Boolean(activeSandboxRecord?.enrollmentId);\n // `none` describes the durable home, not an explicit per-turn route. Give\n // the runtime the effective backend so it builds a SandboxAgent for the\n // attached Connected Machine without mutating the session or turn record.\n if (machinePrimary && modelRunSettings.sandboxBackend === \"none\") {\n modelRunSettings = {\n ...modelRunSettings,\n sandboxBackend: \"selfhosted\",\n };\n }\n // The backend that can actually create a sandbox for this turn. In the\n // common path this is runSettings.sandboxBackend. A selfhosted home turn\n // that is NOT machine-primary falls back to the deployment cloud backend\n // so swap-away / flag-off degrade to a real group box.\n const groupBoxBackend: Settings[\"sandboxBackend\"] =\n runSettings.sandboxBackend === \"selfhosted\" && !machinePrimary\n ? settings.sandboxBackend\n : runSettings.sandboxBackend;\n const sandboxCreationBackend: Settings[\"sandboxBackend\"] =\n settings.sandboxOwnershipEnabled && runSettings.sandboxBackend !== \"none\"\n ? groupBoxBackend\n : runSettings.sandboxBackend;\n const effectiveRunCredentialBackend = activeSandboxBackend ?? groupBoxBackend;\n const runCredentialResolver =\n effectiveRunCredentialBackend === \"none\"\n ? null\n : await waitForTurnOperation(\n bindRunCredentialResolver({\n db,\n connectionCredentials: connectionCredentials ?? null,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n session,\n turn,\n attemptId: input.attemptId,\n effectiveSandboxBackend: effectiveRunCredentialBackend,\n variableSet: workspaceVariableSet\n ? {\n id: workspaceVariableSet.id,\n name: workspaceVariableSet.name,\n }\n : null,\n }),\n cancellationSignal,\n undefined,\n );\n const initialRunCredentialMaterial = runCredentialResolver\n ? await waitForTurnOperation(\n runCredentialResolver.resolve({\n purpose: \"provision\",\n forceRefresh: false,\n }),\n cancellationSignal,\n undefined,\n )\n : null;\n if (initialRunCredentialMaterial) {\n for (const payload of runCredentialAuthNeededPayloads(initialRunCredentialMaterial)) {\n publishedRunCredentialNotices.add(JSON.stringify(payload));\n await publish!([{ type: \"credential.auth_needed\", payload }], true);\n }\n }\n const runCredentialsNote = initialRunCredentialMaterial\n ? runCredentialModelNote(initialRunCredentialMaterial)\n : undefined;\n throwIfTurnOperationCancelled(cancellationSignal);\n await waitForTurnOperation(\n ensureTurnModalRegistryImage(runSettings, sandboxCreationBackend),\n cancellationSignal,\n undefined,\n );\n const establishDecision = sandboxEstablishPolicyDecision({\n lazyEnabled: lazyProvisionEnabled(settings),\n machinePrimary,\n sandboxBackend: runSettings.sandboxBackend,\n // Resolved run credentials must be written to one exact leased sandbox\n // before agent execution. A warm active pointer can bypass the lazy\n // provisioner entirely, which previously skipped materialization.\n hasInitialRunCredentialMaterial: initialRunCredentialMaterial !== null,\n generatedVideoFileCount: requiredGeneratedVideoFiles.length,\n hasSignedFileResources:\n requiresSignedFileResourceDownloads(\n runSettings,\n activeSandboxBackend ?? groupBoxBackend,\n ) && turnResources.some((resource) => resource.kind === \"file\"),\n });\n const establishPolicy = establishDecision.policy;\n recordTurnSandboxEstablishPolicy(observability, {\n policy: establishDecision.policy,\n reason: establishDecision.reason,\n backend: machinePrimary ? \"selfhosted\" : groupBoxBackend,\n });\n // Computed exactly ONCE per turn and reused for BOTH the box manifest\n // (resumeBoxForTurn -> establishSandboxSessionFromEnvelope, below) AND the\n // agent (runtime.buildAgent, below). sandboxEnvironmentForRun mints a FRESH\n // run-scoped git provider tokens on every call, so a second call would\n // yield DIFFERENT token values and re-introduce the manifest-env delta the\n // SDK's provided-session guard throws on — the box and the agent MUST share\n // this same object. A machine-primary turn skips the (inert) token mint entirely\n // (the machine uses its own git creds); the SAME base env still feeds the box +\n // the agent, so env-parity holds.\n // TOKEN-BROKER (B1): sandboxEnvironmentForRun now returns the STABLE manifest\n // env (no rotating GH_TOKEN/GITHUB_TOKEN/GIT_CONFIG_* extraheader) PLUS the\n // run-scoped git tokens minted ONCE per turn as provider seeds, with `gitToken`\n // retained as the GitHub alias. The env feeds BOTH the box manifest AND the\n // agent (env-parity, as before); tokens are threaded OFF-MANIFEST as\n // clone-seeds to buildAgent (below) so the box never carries rotating values\n // on its manifest. When a platform token IS minted, the host `gitCredentials`\n // provider may supply it; unset still self-mints GitHub from settings.\n // gitToken/gitTokens are undefined on the selfhosted skip path (the machine\n // uses its own git creds).\n if (activeSandboxBackend !== \"selfhosted\") {\n await assertGitHubResourcesRemainAuthorized(db, input.workspaceId, turnResources);\n }\n const authorizeGitHubTokenMint: GitHubTokenMintAuthorization = async (selection) => {\n await assertGitHubTokenMintSelectionAuthorized(\n db,\n input.workspaceId,\n selection.installationId,\n selection.repositoryIds,\n );\n };\n // Git and MCP credentials share one lineage snapshot for this turn. A\n // host that supplies both ports must never see two independently resolved\n // roots for the same execution merely because the call sites are far apart.\n const needsHostCredentialRoot = Boolean(\n connectionCredentials?.gitCredentials || connectionCredentials?.mcpCredentials,\n );\n const hostCredentialRootSessionId = needsHostCredentialRoot\n ? await getSessionRootId(db, input.workspaceId, input.sessionId)\n : null;\n if (needsHostCredentialRoot && !hostCredentialRootSessionId) {\n throw new Error(`cannot resolve host credentials for missing session ${input.sessionId}`);\n }\n const gitCredentialAuthority =\n connectionCredentials?.gitCredentials && hostCredentialRootSessionId\n ? gitCredentialAuthorityForTurn({\n sessionId: input.sessionId,\n rootSessionId: hostCredentialRootSessionId,\n attemptId: input.attemptId,\n turn,\n })\n : undefined;\n const codemodeAuthority = {\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration: turn.executionGeneration,\n };\n const sandboxArtifactRuntime = sandboxArtifactRuntimeAdmission(\n settings,\n runSettings,\n activeSandboxBackend ?? groupBoxBackend,\n );\n const {\n environment: baseSandboxEnvironment,\n gitToken: sandboxGitToken,\n gitTokens: sandboxGitTokens,\n gitTokenExpiresAt: sandboxGitTokenExpiresAt,\n gitCredentialBindings: sandboxGitCredentialBindings,\n codemodeToken: sandboxCodemodeToken,\n codemodeTokenExpiresAt: sandboxCodemodeTokenExpiresAt,\n } = await waitForTurnOperation(\n sandboxEnvironmentForRun(\n runSettings,\n turnResources,\n // Rig default sets merged BELOW the session set (session wins); rig-less\n // turns pass exactly workspaceVariableSet?.values (byte-for-byte today).\n sandboxWorkspaceEnvironmentValues,\n {\n skipGitHubToken: activeSandboxBackend === \"selfhosted\",\n codemodeDelivery:\n activeSandboxBackend === \"selfhosted\" ? \"transient_exec\" : \"managed_file\",\n deferGitHubToken:\n activeSandboxBackend !== \"selfhosted\" && establishPolicy === \"on-demand\",\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n authorizeGitHubTokenMint,\n codemodeAuthority,\n },\n ),\n cancellationSignal,\n undefined,\n );\n // Reserved, image-owned paths win over workspace/session variables. The\n // exact same merged object feeds both box manifest and agent declaration,\n // preserving the no-environment-delta invariant.\n const sandboxEnvironment = sandboxArtifactRuntime.available\n ? { ...baseSandboxEnvironment, ...sandboxArtifactRuntime.environment }\n : baseSandboxEnvironment;\n\n // One mutable in-memory bearer cell serves every Connected Machine route\n // in this attempt. SelfhostedSession snapshots it into each exact exec\n // request; it never enters the manifest, argv, filesystem, RunState, or\n // serialized session state. Managed renewal updates the same cell so a\n // later mid-turn swap sees the fresh bearer too.\n const codemodeTokenState = sandboxCodemodeToken ? { token: sandboxCodemodeToken } : undefined;\n const transientCodemodeEnvironment = codemodeTokenState\n ? (): Readonly<Record<string, string>> => ({\n OPENGENI_CODEMODE_URL: codemodeWorkspaceUrl(runSettings, input.workspaceId),\n OPENGENI_CODEMODE_TOKEN: codemodeTokenState.token,\n ...(runSettings.ogtoolPackageSpec\n ? { OPENGENI_OGTOOL_PACKAGE_SPEC: runSettings.ogtoolPackageSpec }\n : {}),\n })\n : undefined;\n\n const sandboxCodemodeTokenFile = sandboxCodemodeToken\n ? codemodeTokenFileFromEnvironment(sandboxEnvironment, input.sessionId)\n : undefined;\n\n const initialGitCredentials: MintedRunGitCredentials | undefined =\n sandboxGitCredentialBindings\n ? {\n bindings: sandboxGitCredentialBindings,\n gitTokens: sandboxGitTokens ?? {},\n expiresAt: sandboxGitTokenExpiresAt ?? {},\n }\n : undefined;\n const attachGitCredentialRenewal = async (\n tokenSession: GitCredentialTokenWriterSession,\n initial: MintedRunGitCredentials | undefined,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!initial || initial.bindings.length === 0) return;\n const previous = gitCredentialRenewals;\n gitCredentialRenewals = [];\n await Promise.all(previous.map(async (controller) => await controller.stop()));\n if (gitCredentialRenewalClosed) return;\n\n const controllers = initial.bindings.map((initialBinding) => {\n let pendingBinding: typeof initialBinding | undefined;\n return startGitCredentialRenewalLoop({\n expectedProviders: [initialBinding.provider],\n initialExpiresAt: initialBinding.expiresAt\n ? { [initialBinding.provider]: initialBinding.expiresAt }\n : {},\n mint: async () => {\n const binding = await mintRunGitCredentialBinding(\n runSettings,\n turnResources,\n initialBinding.provider,\n initialBinding.credentialBindingId,\n {\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n authorizeGitHubTokenMint,\n },\n );\n if (binding) {\n assertGitCredentialRenewalTransportUnchanged(initialBinding, binding);\n }\n pendingBinding = binding;\n return binding\n ? {\n bindings: [binding],\n gitTokens: { [binding.provider]: binding.token },\n expiresAt: binding.expiresAt ? { [binding.provider]: binding.expiresAt } : {},\n }\n : undefined;\n },\n write: async () => {\n if (!pendingBinding) {\n throw new Error(\"credential renewal produced no binding token\");\n }\n const runAs = sandboxRunAs(runSettings);\n const targetSandbox = resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Git credential renewal has no exact sandbox lease target\");\n }\n await runWorkspaceMutationForSandbox(\n targetSandbox,\n \"gitCredentialRenewal\",\n async () =>\n await refreshGitCredentialBindingTokenFiles(tokenSession, [pendingBinding!], {\n ...(runAs ? { runAs } : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n },\n onSuccess: ({ providers: renewedProviders }) => {\n for (const provider of renewedProviders) {\n observability.incrementCounter({\n name: \"opengeni_git_credential_renewals_total\",\n help: \"Host-managed Git credential renewal attempts by provider and outcome.\",\n labels: { provider, outcome: \"completed\" },\n });\n }\n },\n onFailure: ({ providers: failedProviders, retryDelayMs, errorClass }) => {\n for (const provider of failedProviders) {\n observability.incrementCounter({\n name: \"opengeni_git_credential_renewals_total\",\n help: \"Host-managed Git credential renewal attempts by provider and outcome.\",\n labels: { provider, outcome: \"error\" },\n });\n }\n observability.warn(\"Sandbox Git credential renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId,\n providers: failedProviders.join(\",\"),\n errorClass,\n retryDelayMs,\n });\n },\n });\n });\n if (gitCredentialRenewalClosed) {\n await Promise.all(controllers.map(async (controller) => await controller.stop()));\n return;\n }\n gitCredentialRenewals = controllers;\n };\n\n const attachCodemodeTokenRenewal = async (\n tokenSession?: CodemodeTokenWriterSession,\n initialExpiresAt = sandboxCodemodeTokenExpiresAt,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!codemodeTokenState || !initialExpiresAt) return;\n const previous = codemodeTokenRenewal;\n codemodeTokenRenewal = null;\n await previous?.stop();\n if (codemodeTokenRenewalClosed) return;\n\n const mint = async () => {\n const material = await mintSandboxCodemodeToken(\n runSettings,\n connectionScope,\n codemodeAuthority,\n );\n return material;\n };\n const write = async (material: NonNullable<Awaited<ReturnType<typeof mint>>>) => {\n if (tokenSession) {\n const runAs = sandboxRunAs(runSettings);\n const targetSandbox = resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Codemode token renewal has no exact sandbox lease target\");\n }\n await runWorkspaceMutationForSandbox(\n targetSandbox,\n \"codemodeTokenRenewal\",\n async () =>\n await refreshCodemodeTokenFile(tokenSession, material.token, {\n ...(runAs ? { runAs } : {}),\n ...(sandboxCodemodeTokenFile\n ? {\n tokenFile: sandboxCodemodeTokenFile,\n legacyTokenFile: sandboxEnvironment.OPENGENI_CODEMODE_TOKEN_FILE!,\n }\n : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n }\n codemodeTokenState.token = material.token;\n };\n let renewalExpiresAt = initialExpiresAt;\n if (renewalExpiresAt.getTime() <= Date.now() + CODEMODE_TOKEN_EXPIRY_LEAD_MS) {\n const fresh = await mint();\n if (!fresh) {\n throw new Error(\"Codemode token mint became unavailable during sandbox setup\");\n }\n await write(fresh);\n renewalExpiresAt = fresh.expiresAt;\n }\n const controller = startCodemodeTokenRenewalLoop({\n initialExpiresAt: renewalExpiresAt,\n mint,\n write,\n onSuccess: () => {\n observability.incrementCounter({\n name: \"opengeni_codemode_token_renewals_total\",\n help: \"Sandbox Codemode token renewal attempts by outcome.\",\n labels: { outcome: \"completed\" },\n });\n },\n onFailure: ({ retryDelayMs, errorClass }) => {\n observability.incrementCounter({\n name: \"opengeni_codemode_token_renewals_total\",\n help: \"Sandbox Codemode token renewal attempts by outcome.\",\n labels: { outcome: \"error\" },\n });\n observability.warn(\"Sandbox Codemode token renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId,\n errorClass,\n retryDelayMs,\n });\n },\n });\n if (codemodeTokenRenewalClosed) {\n await controller.stop();\n return;\n }\n codemodeTokenRenewal = controller;\n };\n\n // A Connected Machine needs renewal, but renewal is purely worker-local:\n // starting this loop performs no control-plane or machine operation.\n if (activeSandboxBackend === \"selfhosted\") {\n await attachCodemodeTokenRenewal();\n }\n\n const attachRunCredentialRenewal = async (\n credentialSession: RunCredentialCommandSession,\n initialSandbox?: ResumedTurnSandbox,\n ): Promise<void> => {\n if (!runCredentialResolver) return;\n const previous = runCredentialRenewal;\n runCredentialRenewal = null;\n await previous?.stop();\n if (runCredentialRenewalClosed) return;\n runCredentialSession = credentialSession;\n\n const requireTargetSandbox = (): ResumedTurnSandbox => {\n const targetSandbox = resolvedSandbox ?? initialSandbox;\n if (!targetSandbox) {\n throw new Error(\"Run credential mutation has no exact sandbox lease target\");\n }\n return targetSandbox;\n };\n\n if (!initialRunCredentialMaterial) {\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialClear\",\n async () =>\n await clearRunCredentials(\n credentialSession,\n input.sessionId,\n toolCancellationFenceRef.current\n ? toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n )\n : undefined,\n ),\n );\n return;\n }\n\n const write = async (\n material: NormalizedRunCredentialMaterial | null,\n pruneOtherAttempts = false,\n ): Promise<void> => {\n if (!material) {\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialAttemptClear\",\n async () =>\n await clearRunCredentialsForAttempt(credentialSession, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration,\n }),\n );\n return;\n }\n\n await runWorkspaceMutationForSandbox(\n requireTargetSandbox(),\n \"runCredentialMaterialization\",\n async () =>\n await materializeRunCredentials(credentialSession, material, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration,\n ...(pruneOtherAttempts ? { pruneOtherAttempts: true } : {}),\n ...(!pruneOtherAttempts ? { pruneSupersededGenerations: true } : {}),\n ...(material.authNeeded.length > 0 &&\n Object.keys(material.environment).length === 0 &&\n material.files.length === 0\n ? { prunePreviousGenerations: true }\n : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n }),\n );\n for (const payload of runCredentialAuthNeededPayloads(material)) {\n const key = JSON.stringify(payload);\n if (publishedRunCredentialNotices.has(key)) continue;\n publishedRunCredentialNotices.add(key);\n await publish!([{ type: \"credential.auth_needed\", payload }], true);\n }\n };\n\n const initialExpiryMs = initialRunCredentialMaterial.expiresAt?.getTime() ?? null;\n const seed =\n initialExpiryMs !== null && initialExpiryMs <= Date.now() + RUN_CREDENTIAL_EXPIRY_LEAD_MS\n ? await runCredentialResolver.resolve({\n purpose: \"provision\",\n forceRefresh: true,\n })\n : initialRunCredentialMaterial;\n await write(seed, true);\n if (runCredentialRenewalClosed) return;\n const controller = startRunCredentialRenewalLoop({\n initialExpiresAt: seed?.expiresAt ?? null,\n resolve: async () =>\n await runCredentialResolver.resolve({\n purpose: \"renewal\",\n forceRefresh: true,\n }),\n write: async (material) => await write(material),\n onSuccess: ({ authNeeded }) => {\n observability.incrementCounter({\n name: \"opengeni_run_credential_renewals_total\",\n help: \"Host-managed run credential renewal attempts by outcome.\",\n labels: { outcome: authNeeded ? \"auth_needed\" : \"completed\" },\n });\n },\n onFailure: ({ retryDelayMs, errorClass }) => {\n observability.incrementCounter({\n name: \"opengeni_run_credential_renewals_total\",\n help: \"Host-managed run credential renewal attempts by outcome.\",\n labels: { outcome: \"error\" },\n });\n observability.warn(\"Host run credential renewal failed; retry scheduled\", {\n sessionId: input.sessionId,\n turnId,\n errorClass,\n retryDelayMs,\n });\n },\n });\n if (runCredentialRenewalClosed) {\n await controller.stop();\n return;\n }\n runCredentialRenewal = controller;\n };\n\n // P1.2 ownership inversion (gated, default OFF). With the flag off this\n // block is skipped entirely: resolvedSandbox stays null and runStream\n // takes the legacy per-run build-and-discard path — byte-for-byte today.\n // With it on, acquire the group lease (holder = the durable attempt id),\n // resume the one box by id, and inject it NON-OWNED into the run. The box\n // backend is \"none\" -> never resolve (no box to touch).\n //\n // Established AFTER sandboxEnvironment is computed (not before) so the box's\n // manifest is created with the SAME variableSet the agent declares — the SDK\n // applies the agent's manifest to this provided session and throws on ANY\n // variableSet delta (validateNoEnvironmentDelta). Passing sandboxEnvironment\n // here makes current==target so the delta is empty.\n recordTurnStartupPhase(observability, {\n phase: \"runtime_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - runtimePreparationStartedAt) / 1_000,\n });\n if (\n shouldEstablishSandboxForTurn(\n settings.sandboxOwnershipEnabled,\n turn.sandboxBackend,\n machinePrimary,\n )\n ) {\n const sandboxEstablishStartedAt = performance.now();\n let sandboxEstablishOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n const managedOwnership = managedSandboxOwnershipForTurn(\n machinePrimary,\n input.attemptId,\n session.sandboxGroupId,\n );\n sandboxHolderId = managedOwnership?.holderId ?? null;\n sandboxGroupId = managedOwnership?.sandboxGroupId ?? null;\n // STAGE D honest-label guard: a machine-home session carries\n // turn.sandboxBackend \"selfhosted\", but a turn is only machine-PRIMARY\n // when a live machine pointer resolves (activeSandboxBackend==='selfhosted'\n // + enrollmentId). When it is NOT primary — the agent swapped back to the\n // group box (sandbox_swap 'session'/'default'/groupId clears the pointer) or\n // selfhosted routing is flag-OFF (the pointer is ignored) — the else-branch\n // must resume a REAL cloud group box, not a \"selfhosted\" one: the registry\n // SelfhostedSandboxClient has no bound agentId and throws. Fall the group-box\n // backend back to the deployment default cloud backend so swap-away / flag-off\n // degrade to a genuine cloud box exactly like today (home=modal did).\n if (machinePrimary) {\n // STAGE D D1-lite: the active sandbox is a connected machine, so DO NOT\n // establish OR lease the managed home box. The active-sandbox pointer is\n // the machine route's own epoch fence; the managed-home lease separately\n // owns cloud recovery, snapshots, billing, and reaping. Mixing those two\n // ownership domains lets an unrelated degraded cloud archive block a\n // healthy explicitly selected machine.\n // Whether the machine's latest Hello advertised the op-stream engine\n // (refreshed on every connect). Read only when the server flag is on —\n // one indexed lookup, and the flag off keeps this path byte-identical.\n const machineOpStream =\n settings.agentOpStreamEnabled === true\n ? (await getEnrollment(db, input.workspaceId, activeSandboxRecord!.enrollmentId!))\n ?.opStream === true\n : false;\n const established = await establishSelfhostedTurnSession(\n {\n db,\n settings,\n bus,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n opJournal,\n },\n {\n workspaceId: input.workspaceId,\n agentId: activeSandboxRecord!.enrollmentId!,\n opStream: machineOpStream,\n epoch: activeSandboxPointer!.activeEpoch,\n environment: sandboxEnvironment,\n ...(transientCodemodeEnvironment\n ? { transientExecEnvironment: transientCodemodeEnvironment }\n : {}),\n workingDir: activeSandboxPointer!.workingDir,\n },\n );\n // The machine-primary establish narrows `session` to SelfhostedSession\n // (buildSelfhostedBackendSession); EstablishedSandboxSession widens it.\n machinePrimarySession =\n established.session as import(\"@opengeni/runtime\").SelfhostedSession;\n setupBoxSession = established.session;\n resolvedSandbox = {\n // Wrap in the SAME routing proxy so a mid-turn swap (to another machine\n // or back to the group box) still re-routes per op. PIN this established\n // SelfhostedSession for the machine pointer so the turn-start manifest\n // write (via the proxy's `state` getter) and the per-op reads hit ONE\n // instance — no two-instance manifest divergence.\n established: wrapTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n opJournal,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxRebound,\n ...(runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}),\n },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n ...(transientCodemodeEnvironment\n ? { transientExecEnvironment: transientCodemodeEnvironment }\n : {}),\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n pinnedSelfhosted: {\n sandboxId: activeSandboxPointer!.activeSandboxId!,\n epoch: activeSandboxPointer!.activeEpoch,\n },\n // HOME semantics for a mid-turn clear-to-null: only a genuine\n // machine-HOME session (its home IS this machine, session.sandboxBackend\n // === \"selfhosted\") resolves null back to the pinned machine. A Modal-HOME\n // session merely PINNED to a machine this turn never established its group\n // box, so defaultIsHome:false makes a clear-to-null fail typed\n // (`home_unavailable_this_turn`) rather than silently serving the machine;\n // the detach takes effect next turn. (Lazy home-box establishment on such a\n // clear is a deferred follow-up; issue #341.)\n defaultIsHome: session.sandboxBackend === \"selfhosted\",\n },\n established,\n ),\n // For a machine route this is the active-pointer epoch, not a cloud\n // lease epoch. Cloud-only heartbeat/snapshot/capture paths require\n // sandboxGroupId and remain disabled for this branch.\n leaseEpoch: activeSandboxPointer!.activeEpoch,\n release: async () => undefined,\n };\n } else if (establishPolicy === \"on-demand\") {\n // Lazy sandbox provisioning: holder/group ids are fixed at turn start,\n // but the lease acquire + box establish + setup move behind the routing\n // proxy's first default-pointer op. A chat-only turn never calls it, so\n // no lease row, no provider box, no warm-meter interval.\n } else {\n resolvedSandbox = await waitForTurnOperation(\n resumeBoxForTurn(\n {\n db,\n settings: runSettings,\n logicalFallbackSettings: logicalSandboxSettings,\n cancellationSignal: sandboxResumeSignal,\n sandboxMetrics: runtimeMetricsHooksForObservability(observability),\n onSandboxLost: publishSandboxLost,\n },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n sessionId: input.sessionId,\n // groupBoxBackend, not turn.sandboxBackend: a machine-home turn that\n // is not machine-primary resumes a real cloud group box (the\n // deployment default), never a \"selfhosted\" box (which would throw\n // for lack of a bound agentId).\n backend: groupBoxBackend,\n os: session.sandboxOs,\n environment: sandboxEnvironment,\n // IMAGE IS SHARED STATE (B3, Modal warm-box path only): the container image\n // this run resolves. The lease stamps it + conflicts on a live shared box\n // running a DIFFERENT image (solo → durable rotation; N-holders →\n // SandboxImageConflictError surfaced as an actionable turn error). Prefer\n // the explicit Modal image ref, else the docker image. The selfhosted branch\n // (establishSelfhostedTurnSession) NEVER passes\n // an image — B3 lives only on this Modal else-branch.\n ...((runSettings.modalImageRef ?? runSettings.dockerImage)\n ? {\n image: runSettings.modalImageRef ?? runSettings.dockerImage,\n }\n : {}),\n // RIG IS SHARED STATE (M3): stamp the frozen rig version so the lease\n // conflicts on a live shared box set up under a different rig (solo\n // durable rotation / N-holders SandboxRigConflictError). Omitted for a\n // rig-less turn -> never stamped or enforced (shares exactly as today).\n ...(rigVersion ? { rigVersionId: rigVersion.id } : {}),\n },\n \"turn\",\n managedOwnership!.holderId,\n ),\n sandboxResumeSignal,\n releaseLateSandbox,\n );\n setupBoxSession = resolvedSandbox.established.session;\n // Durable box-lifecycle events (sandbox-file-persistence observability):\n // record every box transition in session_events so the NEXT box loss is\n // attributable from the DB alone — worker logs rotate within hours, which\n // left both 2026-07-06 incidents without a durable trace. Best-effort.\n await publishSandboxLifecycleEvents(resolvedSandbox);\n // M7 hot-swap: when the selfhosted feature is on, wrap the established\n // group box in the STABLE routing proxy before it is injected NON-OWNED\n // into the run. The SDK binds to this ONE object once and calls its\n // methods per tool call; the proxy re-reads (active_sandbox_id,\n // active_epoch) per op and dispatches to the currently-active backend, so\n // a sandbox_swap mid-turn lands the NEXT tool call on the new box. With\n // the flag off the established group box is injected unchanged (today's\n // path). The lease still owns the group box lifecycle — the proxy is a\n // routing veneer, not an owner.\n resolvedSandbox = {\n ...resolvedSandbox,\n established: wrapTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n opJournal,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxLost: publishSandboxLost,\n onHomeSandboxRebound,\n ...(runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}),\n },\n // Thread the SAME declared environment the group box was created with\n // (resumeBoxForTurn, above) so a selfhosted swap target's manifest\n // carries it too — the SDK's per-turn manifest-env delta stays empty\n // (no \"cannot change manifest environment variables\" throw).\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n ...(transientCodemodeEnvironment\n ? { transientExecEnvironment: transientCodemodeEnvironment }\n : {}),\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n homeLease: {\n accountId: input.accountId,\n sandboxGroupId: session.sandboxGroupId,\n leaseEpoch: resolvedSandbox.leaseEpoch,\n instanceId: resolvedSandbox.established.instanceId,\n backend: groupBoxBackend,\n },\n },\n resolvedSandbox.established,\n ),\n };\n }\n if (resolvedSandbox) {\n startLeaseHeartbeat(resolvedSandbox, activeSandboxBackend ?? groupBoxBackend);\n }\n } catch (error) {\n sandboxEstablishOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"sandbox_establish\",\n provider: turnExecutionPolicy.providerId,\n backend: machinePrimary ? \"selfhosted\" : groupBoxBackend,\n outcome: sandboxEstablishOutcome,\n durationSeconds: (performance.now() - sandboxEstablishStartedAt) / 1_000,\n });\n }\n }\n\n const ordinaryFileResourceDownloads = await (async () => {\n const fileResolutionStartedAt = performance.now();\n let fileResolutionOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n return await waitForTurnOperation(\n sandboxFileDownloadsForRun(\n runSettings,\n db,\n objectStorage,\n input.workspaceId,\n turnResources,\n activeSandboxBackend ?? groupBoxBackend,\n ),\n cancellationSignal,\n undefined,\n );\n } catch (error) {\n fileResolutionOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"file_resolution\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: fileResolutionOutcome,\n durationSeconds: (performance.now() - fileResolutionStartedAt) / 1_000,\n count: turnResources.length,\n });\n }\n })();\n if (requiredGeneratedVideoFiles.length > 0 && !objectStorage) {\n throw new Error(\"Generated video materialization requires object storage\");\n }\n const generatedVideoDownloads: SandboxFileDownload[] = [];\n if (objectStorage && requiredGeneratedVideoFiles.length > 0) {\n const downloadStorage = objectStorageForSandboxDownloads(modelRunSettings, objectStorage);\n for (const file of requiredGeneratedVideoFiles) {\n const signed = await downloadStorage.createGetUrl({\n key: file.objectKey,\n });\n generatedVideoDownloads.push({\n fileId: file.fileId,\n mountPath: \"generated-videos\",\n filename: file.filename,\n url: signed.url,\n expiresAt: signed.expiresAt,\n sizeBytes: file.sizeBytes,\n sha256: file.sha256,\n });\n }\n }\n const fileResourceDownloads = [\n ...new Map(\n [...ordinaryFileResourceDownloads, ...generatedVideoDownloads].map((download) => [\n download.fileId,\n download,\n ]),\n ).values(),\n ];\n const toolContextPreparationStartedAt = performance.now();\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const mcpCredentialRootSessionId =\n connectionCredentials?.mcpCredentials && hostCredentialRootSessionId\n ? hostCredentialRootSessionId\n : input.sessionId;\n // Connection credentials and the optional Apps credential are resolved\n // independently. Inference auth is never an Apps fallback.\n const rawResolveCredential = connectionTokenResolverForTurn({\n db,\n settings: runSettings,\n connectionCredentials: connectionCredentials ?? null,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n rootSessionId: mcpCredentialRootSessionId,\n attemptId: input.attemptId,\n turn,\n });\n const personalConnectionDelegations = turn.personalConnectionDelegations;\n const delegatedMembershipChecks = new Map<string, Promise<boolean>>();\n const delegatedOwnerHasMembership = async (subjectId: string): Promise<boolean> => {\n const existing = delegatedMembershipChecks.get(subjectId);\n if (existing) return await existing;\n const check = getWorkspaceGrant(db, subjectId, input.workspaceId).then(Boolean);\n delegatedMembershipChecks.set(subjectId, check);\n return await check;\n };\n const resolveFrozenCredential = withFrozenPersonalConnectionDelegations({\n resolveCredential: rawResolveCredential,\n settings: runSettings,\n personalConnectionDelegations,\n ownerHasWorkspaceMembership: delegatedOwnerHasMembership,\n });\n const resolveCredential: typeof rawResolveCredential = async (request) => {\n const result = await resolveFrozenCredential(request);\n if (result.status === \"ok\") {\n }\n return result;\n };\n const publishToolAuthNeeded = async (payload: ToolAuthNeededPayload): Promise<void> => {\n if (!shouldPublishToolAuthNeededForTurn(payload, trigger, turn)) {\n return;\n }\n await publish!([{ type: \"tool.auth_needed\", payload }], true);\n };\n const selectedApiIntegrationServerIds = new Set(turnTools.map((tool) => tool.id));\n const localMcpServers = buildApiIntegrationServersForTurn({\n settings: runSettings,\n integrations: installedApiIntegrations.filter((integration) =>\n selectedApiIntegrationServerIds.has(integration.serverId),\n ),\n authority: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n rootSessionId: session.rootSessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n ...(credentialSubjectId ? { initiatingSubjectId: credentialSubjectId } : {}),\n },\n resolveCredential,\n onAuthNeeded: publishToolAuthNeeded,\n });\n const codexAppsAuth = codexAppsCredentialId\n ? (() => {\n const resolver = buildCodexTokenResolver(\n db,\n runSettings,\n input.workspaceId,\n codexAppsCredentialId,\n );\n return {\n clientVersion: CODEX_CLIENT_VERSION,\n withAuthorization: async <T>(\n use: (token: {\n accessToken: string;\n chatgptAccountId: string | null;\n }) => Promise<T>,\n ): Promise<T> => {\n const snapshot = await resolver.getToken();\n\n return await withCodexAppsRequestAuthorization(\n db,\n {\n workspaceId: input.workspaceId,\n credentialId: codexAppsCredentialId,\n },\n async () => await use(snapshot),\n );\n },\n };\n })()\n : undefined;\n const selectedFirstPartyMcpTools = allowedFirstPartyMcpToolsForSession(\n runSettings,\n session.firstPartyMcpTools,\n );\n recordTurnStartupPhase(observability, {\n phase: \"tool_context_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - toolContextPreparationStartedAt) / 1_000,\n count: turnTools.length,\n });\n const toolPreparationStartedAt = performance.now();\n let toolPreparationOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n preparedTools = await waitForTurnOperation(\n runtime.prepareTools(runSettings, turnTools, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n // Sign the calling turn into the first-party token so tools classify\n // the caller by its own identity (sacred-pause guard), not the racy\n // live active pointer.\n ...(turnId ? { turnId } : {}),\n attemptId: input.attemptId,\n executionGeneration,\n subjectId: \"worker:first-party-mcp\",\n subjectLabel: \"OpenGeni worker\",\n ...(credentialSubjectId ? { credentialSubjectId } : {}),\n ...(codexAppsAuth ? { codexAppsAuth } : {}),\n resolveCredential,\n onAuthNeeded: publishToolAuthNeeded,\n localMcpServers,\n onPreparationPhase: (measurement) => {\n recordTurnStartupPhase(observability, {\n phase: `tool_${measurement.phase}`,\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: measurement.outcome,\n durationSeconds: measurement.durationSeconds,\n count: turnTools.length,\n });\n },\n onAttemptToolCatalog: async (catalog) => {\n await persistAttemptToolCatalog(db, catalog);\n },\n // Manager-style sessions carry a creation-validated permission set\n // for their first-party MCP token; null keeps the fixed default.\n ...(session.firstPartyMcpPermissions?.length\n ? { firstPartyPermissions: session.firstPartyMcpPermissions }\n : {}),\n firstPartyTools: selectedFirstPartyMcpTools,\n nestedAgentDepth: session.nestedAgentDepth,\n effectiveMaxNestedAgentDepth: session.effectiveMaxNestedAgentDepth,\n attemptToolDefinitions: createFirstPartyInteractionAttemptToolDefinitions({\n settings: runSettings,\n scope: {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n executionGeneration,\n },\n ...(session.firstPartyMcpPermissions?.length\n ? { permissions: session.firstPartyMcpPermissions }\n : {}),\n selectedTools: selectedFirstPartyMcpTools,\n subjectId: \"worker:first-party-mcp\",\n subjectLabel: \"OpenGeni worker\",\n ...(interactionInterventionResume\n ? { interventionResume: interactionInterventionResume }\n : {}),\n }),\n }),\n cancellationSignal,\n async (latePreparedTools) => await latePreparedTools.close().catch(() => undefined),\n );\n } catch (error) {\n toolPreparationOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"tool_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: toolPreparationOutcome,\n durationSeconds: (performance.now() - toolPreparationStartedAt) / 1_000,\n count: turnTools.length,\n });\n }\n const postToolPreparationStartedAt = performance.now();\n if (turnId && preparedTools.attemptToolEnvironment) {\n codemodeDispatcher = new CodemodeAttemptDispatcher(\n db,\n bus,\n preparedTools.attemptToolEnvironment,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n executionGeneration,\n },\n cancellationSignal,\n );\n codemodeDispatcher.start();\n }\n // Genesis turn = the first user turn (no assistant history reconciled\n // yet). Durable Postgres state (countSessionHistoryItems includes\n // superseded rows after compaction), NOT a workflow counter (turnsThisRun\n // resets on continueAsNew). Drives the one-shot title hint appended to the\n // agent's instructions; later attempts and goal continuations never match.\n const isGenesisTurn =\n triggerType === \"user.message\" &&\n (await countSessionHistoryItems(db, input.workspaceId, input.sessionId)) === 0;\n // Clone-onto-real-disk hazard (Case B). A session keeps its CLOUD HOME\n // backend (runSettings.sandboxBackend, e.g. \"modal\") but its ACTIVE sandbox\n // may have been swapped to a connected machine (active_sandbox_id → a\n // selfhosted lease). buildAgent's repository-clone lifecycle hook keys off\n // the EFFECTIVE backend; if we let it default to the home backend it would\n // `git clone` a private GitHub-App repo onto the user's REAL disk. So pass\n // \"selfhosted\" through when the active sandbox is a connected machine;\n // otherwise leave it undefined so buildAgent defaults to the home backend\n // (byte-for-byte unchanged cloud behavior). `activeSandboxBackend` was\n // resolved ONCE at turn start (above) via resolveActiveSandboxBackend (the\n // tested gate) and is reused here — resolving once is correct because the\n // clone hook runs at beforeAgentStart, so a mid-turn swap can't affect it.\n // buildAgent's option key is `workspaceEnvironment` (internal runtime\n // symbol; the product concept is a variable set). Built as a TYPED const —\n // a direct literal assignment to Pick<BuildAgentOptions,...> IS excess-\n // property-checked, so a wrong key fails tsc. A bare conditional spread\n // inside the options literal is NOT checked, which is exactly how the M1\n // key regression (workspaceVariableSet vs workspaceEnvironment) slipped\n // through and silently dropped the variable-set instructions block.\n const workspaceEnvironmentOption: Pick<BuildAgentOptions, \"workspaceEnvironment\"> =\n workspaceVariableSet\n ? {\n workspaceEnvironment: {\n name: workspaceVariableSet.name,\n description: workspaceVariableSet.description,\n variableNames: Object.keys(workspaceVariableSet.values),\n },\n }\n : {};\n const hostedWebSearch = hostedWebSearchForTurn(resolvedModel, runSettings.webSearchEnabled);\n const resolveImageReferences = async (\n references: Parameters<typeof resolveImageGenerationReferences>[0][\"references\"],\n ) =>\n await resolveImageGenerationReferences({\n db,\n objectStorage: objectStorage!,\n workspaceId: input.workspaceId,\n references,\n readSandboxFile: async (path, maxBytes) => {\n const imageReferenceSession = (setupBoxSession ??\n sdkOwnedSandboxSession) as ChannelASession | null;\n if (!imageReferenceSession) {\n throw new Error(\"Sandbox image reference is unavailable\");\n }\n const relativePath = path.slice(\"/workspace/\".length);\n const referenceRunAs = sandboxRunAs(modelRunSettings);\n const channel = new SandboxChannelAService({\n session: imageReferenceSession,\n workspaceRoot: \"/workspace\",\n leaseEpoch: resolvedSandbox?.leaseEpoch ?? 0,\n ...(referenceRunAs ? { runAs: referenceRunAs } : {}),\n });\n const read = await channel.fsRead({\n path: relativePath,\n encoding: \"base64\",\n maxBytes,\n });\n if (read.truncated) throw new Error(\"Sandbox image reference exceeds the byte limit\");\n return Uint8Array.from(Buffer.from(read.content, \"base64\"));\n },\n });\n const imageGenerationOption: Pick<BuildAgentOptions, \"imageGeneration\"> = (() => {\n // Never expose a paid image operation unless its permanent artifact can\n // be committed. Failing after provider execution would leave an\n // unrecoverable outcome-unknown operation with no user-visible image.\n if (!objectStorage) return {};\n if (nativeImageProviderBinding) {\n nativeImageGenerationRetention = {\n ...nativeImageProviderBinding,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n };\n return { imageGeneration: { kind: \"native_hosted\" } };\n }\n\n if (resolvedModel?.provider.kind === \"codex-subscription\") {\n const imageAuthority = connectedSubscriptionImageGenerationAuthority(\n codexContext,\n effectiveCodexCredentialId,\n );\n if (!imageAuthority) return {};\n return {\n imageGeneration: {\n kind: \"provider_adapter\",\n execute: async ({ prompt, references }, { toolCallId }) => {\n const resolvedReferences = await resolveImageReferences(references);\n const receipt = await executeCodexImageGeneration({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n toolCallId,\n prompt,\n references: resolvedReferences,\n credentialId: imageAuthority.credentialId,\n codexContext: imageAuthority.credentialContext,\n ...(runtimeCancellationSignal ? { abortSignal: runtimeCancellationSignal } : {}),\n });\n generatedImageReceiptsByArtifactId.set(receipt.artifact.artifactId, receipt);\n await materializeGeneratedImage(receipt);\n return receipt;\n },\n },\n };\n }\n\n if (resolvedModel?.provider.kind === \"xai-subscription\") {\n const imageAuthority = connectedSubscriptionImageGenerationAuthority(\n xaiRequestContext,\n effectiveXaiCredentialId,\n );\n if (!imageAuthority) return {};\n return {\n imageGeneration: {\n kind: \"provider_adapter\",\n execute: async ({ prompt, references }, { toolCallId }) => {\n const resolvedReferences = await resolveImageReferences(references);\n const receipt = await executeXaiSubscriptionImageGeneration({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n toolCallId,\n prompt,\n references: resolvedReferences,\n credentialId: imageAuthority.credentialId,\n xaiContext: imageAuthority.credentialContext,\n ...(runtimeCancellationSignal ? { abortSignal: runtimeCancellationSignal } : {}),\n });\n generatedImageReceiptsByArtifactId.set(receipt.artifact.artifactId, receipt);\n await materializeGeneratedImage(receipt);\n return receipt;\n },\n },\n };\n }\n\n const gatewayResolution = resolveModelProvider(\n capabilitySettings,\n WORKSPACE_GATEWAY_PROVIDER_ID,\n );\n const gateway = gatewayResolution?.provider;\n if (gateway?.kind !== \"vercel-gateway-workspace\" || !gateway.apiKey) return {};\n const gatewayApiKey = gateway.apiKey;\n return {\n imageGeneration: {\n kind: \"provider_adapter\",\n execute: async ({ prompt, references }, { toolCallId }) => {\n const resolvedReferences = await resolveImageReferences(references);\n const receipt = await executeGatewayImageGeneration({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n apiKey: gatewayApiKey,\n modelId: capabilitySettings.imageGenerationModel,\n prompt,\n references: resolvedReferences,\n toolCallId,\n ...(runtimeCancellationSignal ? { abortSignal: runtimeCancellationSignal } : {}),\n });\n generatedImageReceiptsByArtifactId.set(receipt.artifact.artifactId, receipt);\n await materializeGeneratedImage(receipt);\n return receipt;\n },\n },\n };\n })();\n const videoGenerationPolicy = await getWorkspaceVideoGenerationPolicy(db, input.workspaceId);\n const videoGenerationEnabled =\n videoGenerationPolicy.defaultModelId !== null &&\n videoGenerationPolicy.enabledModelIds.length > 0;\n let videoGenerationCredential: VideoGenerationCredentialLease | null = null;\n if (objectStorage && videoGenerationEnabled) {\n if (videoGenerationPolicy.fundingSource === \"opengeni_credits\") {\n videoGenerationCredential = managedVideoGenerationCredentialLease(modelRunSettings);\n } else if (videoGenerationPolicy.fundingSource === \"workspace_gateway\") {\n const workspaceCredential = await loadWorkspaceVercelAiGatewayCredentialLease(\n db,\n modelRunSettings,\n input.workspaceId,\n );\n if (workspaceCredential) {\n videoGenerationCredential = {\n fundingSource: \"workspace_gateway\",\n ...workspaceCredential,\n };\n }\n } else if (videoGenerationPolicy.fundingSource === \"supergrok_subscription\") {\n const encryptionKey = environmentsEncryptionKeyBytes(modelRunSettings);\n const subjectId = xaiLeaseSubjectId ?? turn.initiatingHumanSubjectId;\n if (encryptionKey && subjectId) {\n const authoritySnapshot =\n xaiAuthoritySnapshot ??\n (await resolveXaiProviderAccountAuthoritySnapshotForAcceptance(db, {\n workspaceId: input.workspaceId,\n subjectId,\n }));\n const pin = await getXaiSessionAccountPin(db, {\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n });\n const selected = effectiveXaiCredentialId\n ? {\n credentialId: effectiveXaiCredentialId,\n rotationEnabled: xaiRotationEnabled,\n }\n : await selectXaiCredentialForUse(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n authoritySnapshot,\n shardKey: input.sessionId,\n pinnedCredentialId: pin?.pinnedCredentialId ?? null,\n pinSource:\n pin?.pinSource === \"manual\" || pin?.pinSource === \"policy\"\n ? pin.pinSource\n : null,\n });\n if (selected.credentialId) {\n if (\n selected.rotationEnabled &&\n pin?.pinSource !== \"manual\" &&\n pin?.pinnedCredentialId !== selected.credentialId\n ) {\n await setXaiSessionAccountPin(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId,\n sessionId: input.sessionId,\n authoritySnapshot,\n credentialId: selected.credentialId,\n pinSource: \"policy\",\n expectedVersion: pin?.version ?? null,\n }).catch((error: unknown) => {\n if (error instanceof Error && error.message === \"xAI session pin changed\") return;\n throw error;\n });\n }\n const credential = await materializeXaiCredentialForRun(db, {\n workspaceId: input.workspaceId,\n subjectId,\n credentialId: selected.credentialId,\n authoritySnapshot,\n encryptionKey,\n });\n videoGenerationCredential = xaiVideoGenerationCredentialLease({\n settings: modelRunSettings,\n credential,\n subjectId,\n authoritySnapshot,\n });\n }\n }\n }\n }\n const videoGenerationOption: Pick<BuildAgentOptions, \"videoGeneration\"> = (() => {\n if (\n !objectStorage ||\n modelRunSettings.sandboxBackend === \"none\" ||\n !videoGenerationCredential ||\n !videoGenerationEnabled\n ) {\n return {};\n }\n // Parse the frozen capability snapshot before advertising either tool.\n // Invalid or unsupported workspace policy therefore fails closed before\n // it can perturb the model's tool list.\n const capabilities = videoGenerationCapabilitiesForPolicy({\n policy: videoGenerationPolicy,\n credentialVersion: videoGenerationCredential.version,\n });\n return {\n videoGeneration: {\n capabilities: async () => capabilities,\n execute: async (toolInput, { toolCallId }) => {\n const sessionForReference =\n resolvedSandbox?.established.session ?? sdkOwnedSandboxSession;\n const fence = toolCancellationFenceRef.current;\n const runAs = sandboxRunAs(modelRunSettings);\n let accepted: Awaited<ReturnType<typeof admitVideoGenerationRequest>>;\n try {\n accepted = await admitVideoGenerationRequest({\n db,\n storage: objectStorage,\n settings: modelRunSettings,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n attemptId: input.attemptId,\n toolCallId,\n toolInput,\n policy: videoGenerationPolicy,\n credential: videoGenerationCredential,\n ...(sessionForReference && fence\n ? {\n runCommand: async (command) =>\n await fence.runSandboxCommandStructured(\n sessionForReference as import(\"@opengeni/runtime\").TurnSandboxCommandSession,\n {\n ...command,\n ...(runAs ? { runAs } : {}),\n },\n ),\n }\n : {}),\n ...(runtimeCancellationSignal ? { signal: runtimeCancellationSignal } : {}),\n });\n } catch (error) {\n if (error instanceof VideoReferenceInputError) {\n return VideoGenerationRejectedResult.parse({\n schemaVersion: 1,\n status: \"rejected\",\n code: error.code,\n message: error.message,\n operationCreated: false,\n });\n }\n throw error;\n }\n videoGenerationAcceptancesByCallId.set(toolCallId, {\n operationId: accepted.operationId,\n requestDigest: accepted.requestDigest,\n });\n return accepted.receipt;\n },\n },\n };\n })();\n const serviceTier = serviceTierForLatencyMode(\n turnExecutionPolicy.providerId,\n turnExecutionPolicy.latencyMode,\n );\n const connectorActionIdentity = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n executionGeneration,\n initiator: {\n kind: turn.initiator.kind,\n subjectId: turn.initiator.subjectId,\n },\n } as const;\n const connectorActionPolicy: ConnectorActionPolicyHooks = {\n prepare: async (call) =>\n await prepareConnectorActionApproval(db, connectorActionIdentity, call),\n begin: async (call) =>\n await beginConnectorActionExecution(db, connectorActionIdentity, call),\n complete: async ({ requestId, outcome }) =>\n await completeConnectorActionExecution(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n requestId,\n attemptId: input.attemptId,\n outcome,\n }),\n };\n const runtimeSkillActivations = [\n ...installedSkillRuntime.activations,\n ...packRuntime.skillActivations,\n ...session.skills.map((skill) => ({\n source: \"session\" as const,\n id: `session:${session.id}:${skill.name}`,\n artifact: {\n name: skill.name,\n description: skill.description ?? null,\n files: skill.files.map((file) => ({\n path: file.path,\n content: file.content,\n })),\n },\n reason: \"attached to session\",\n })),\n ];\n recordTurnStartupPhase(observability, {\n phase: \"post_tool_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - postToolPreparationStartedAt) / 1_000,\n });\n const agent = (() => {\n const agentConstructionStartedAt = performance.now();\n let agentConstructionOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n return runtime.buildAgent(modelRunSettings, turnResources, {\n reasoningEffort: turn.reasoningEffort,\n latencyMode: turnExecutionPolicy.latencyMode,\n ...(serviceTier ? { serviceTier } : {}),\n ...(humanInputResume ? { humanInputResponse: humanInputResume } : {}),\n humanInputEnabled: agentHumanInputEnabled,\n genesisTitleHint: isGenesisTurn,\n persistentSessionSettings: {\n titleIsSet: Boolean(session.title?.trim()),\n },\n sandboxEnvironment,\n ...(preparedTools.attemptToolCatalog\n ? { attemptToolCatalog: preparedTools.attemptToolCatalog }\n : {}),\n ...(sandboxArtifactRuntime.available ? { artifactRuntimeAvailable: true } : {}),\n ...(cancellationSignal ? { turnCancellationSignal: cancellationSignal } : {}),\n onToolCancellationFence: (fence) => {\n toolCancellationFenceRef.current = fence;\n },\n // TOKEN-BROKER (B1): forward the per-turn git token OFF-MANIFEST as the clone\n // seed. ONLY when the effective backend is NOT selfhosted (the connected\n // machine uses its own git creds — mirrors the skipGitHubToken gate above)\n // AND the mint actually produced a token (repo resources present). The runtime\n // seeds it to the box's token file before the repository-clone runs; it never\n // touches the box/agent manifest env.\n ...(activeSandboxBackend !== \"selfhosted\" && sandboxGitTokens\n ? { gitTokenSeeds: sandboxGitTokens }\n : {}),\n ...(activeSandboxBackend !== \"selfhosted\" && sandboxGitCredentialBindings\n ? { gitCredentialBindings: sandboxGitCredentialBindings }\n : {}),\n ...(activeSandboxBackend !== \"selfhosted\" && !sandboxGitTokens && sandboxGitToken\n ? { gitTokenSeed: sandboxGitToken }\n : {}),\n ...(sandboxCodemodeToken ? { codemodeAvailable: true } : {}),\n // Managed boxes receive the bearer through their protected per-session\n // token file. Connected Machines use transient per-exec delivery above,\n // so they must not run the file-seeding lifecycle hook.\n ...(activeSandboxBackend !== \"selfhosted\" && sandboxCodemodeToken\n ? {\n codemodeTokenSeed: sandboxCodemodeToken,\n codemodeTokenSessionId: input.sessionId,\n }\n : {}),\n ...(activeSandboxBackend ? { activeSandboxBackend } : {}),\n fileResourceDownloads,\n mcpServers: preparedTools.mcpServers,\n resolvedMcpConnectionIds: preparedTools.resolvedMcpConnectionIds,\n connectorActionPolicy,\n // LIVE by-reference connector namespaces (fills during this turn's\n // codex_apps tools/list): the codex tool_search description reads it per\n // model call so the model sees the account's real connected sources.\n codexConnectorNamespaces: preparedTools.codexConnectorNamespaces,\n // Resolved-model routing + gating (legacy defaults when null). The model\n // is passed as the model *string* (agent.model = runSettings.openaiModel),\n // NOT a Model instance: an instance only survives the in-process\n // (\"none\") run, whereas the SandboxAgent/Modal path drops it and\n // re-resolves the model *name* through the global MultiProviderModelProvider\n // configureOpenAI installed — so registry models (Fireworks GLM) route to\n // their own client instead of 404ing against the built-in Azure/OpenAI\n // client. The gating still comes from the resolved provider: server-side\n // store/compaction follow the provider's compaction mode (registry\n // providers resolve to \"client\"); encrypted reasoning is only\n // round-tripped on the Responses wire API; hosted web search is attached\n // whenever the provider declares it runnable and is independent of the\n // session's MCP allow-list; the effective context window drives the\n // compaction threshold.\n hostedWebSearch,\n ...imageGenerationOption,\n ...videoGenerationOption,\n lazyToolTransport,\n supportsImageInput,\n inputFileMediaTypes: modelInputPolicy.inputFileMediaTypes,\n ...(resolvedModel\n ? {\n encryptedReasoning:\n resolvedModel.provider.api === \"responses\" &&\n runSettings.openaiReasoningEncryptedContent,\n contextWindowTokens:\n resolvedModel.configured.contextWindowTokens ?? runSettings.contextWindowTokens,\n // The ChatGPT/Codex backend rejects the SDK's HOSTED apply_patch\n // tool. Gateway Responses routes likewise expose ordinary function\n // tools, not OpenAI-hosted sandbox tools. Tell buildAgent to use\n // function apply_patch and wrap successful view_image results as\n // typed input_image content. Chat wires have no proven typed image\n // result transport and therefore receive no view_image tool.\n structuredToolTransport: structuredToolTransportForTurn(resolvedModel),\n // EXPLICIT computer-use tool transport, derived from the resolved provider's\n // authoritative wire identity (codex → function-image, chat → disabled,\n // responses → hosted) so the runtime never string-sniffs the model instance's\n // constructor name. See {@link computerToolModeForTurn}.\n computerToolMode: computerToolModeForTurn(resolvedModel),\n ...(promptCacheKey ? { promptCacheKey } : {}),\n }\n : // LEGACY global-client fallback (resolveTurnModel returned null → the model\n // is not in the registry, served by the built-in OpenAI/Azure Responses\n // client). That backend has real hosted support, so pin computerToolMode to\n // \"hosted\" EXPLICITLY rather than leaving the runtime to sniff the instance.\n {\n computerToolMode: computerToolModeForTurn(null),\n promptCacheKey: input.sessionId,\n }),\n // Lazy computer-use seam: runtime first brings up :0 only after the model\n // selects a computer tool, then this hook begins the optional proof\n // recording. Shell/filesystem turns never invoke either operation.\n onComputerUseReady: async () => {\n if (!resolvedSandbox) {\n throw new Error(\"Computer-use display became ready without a resolved sandbox\");\n }\n // This callback is the authoritative execution boundary. Record the\n // action before async ffmpeg startup so transport-event ordering cannot\n // make settlement misclassify a real computer turn as unused.\n didComputerUse = true;\n await maybeStartOnTurnRecording(resolvedSandbox, activeSandboxBackend);\n },\n onRetainableSessionImageOutput: retainSessionImageAtToolBoundary,\n ...(runtimeSkillActivations.length > 0\n ? { skillActivations: runtimeSkillActivations }\n : {}),\n ...(!structuredWorkspacePolicyActive && workspaceAgentInstructions\n ? { instructionsTemplate: workspaceAgentInstructions }\n : {}),\n ...(workspaceGovernance ? { workspaceGovernance } : {}),\n ...(workspaceMemory ? { workspaceMemory } : {}),\n goalSnapshot: turn.goalSnapshot,\n // Per-session persona tier (session > workspace > deployment default).\n // Composed system-level AFTER the workspace persona so it refines it for\n // this one session; absent ⇒ byte-identical to today's composition.\n ...(session.instructions ? { sessionInstructions: session.instructions } : {}),\n // Exact host context captured when this turn was accepted. It is\n // system-level and disappears with the turn rather than entering chat.\n ...(turn.turnInstructions || mcpAvailabilityInstructions\n ? {\n turnInstructions: [turn.turnInstructions, mcpAvailabilityInstructions]\n .filter((value): value is string => Boolean(value))\n .join(\" \"),\n }\n : {}),\n ...workspaceEnvironmentOption,\n // RIG RUNTIME (M3): the doctrine block, the setup-script hook (only when\n // the frozen version carries a non-empty script), and the rig credential\n // hooks. All absent for a rig-less turn (byte-for-byte today).\n ...(rigVersion && rigName\n ? {\n rig: { name: rigName, version: rigVersion.version },\n ...(rigVersion.setupScript && rigVersion.setupScript.trim().length > 0\n ? {\n rigSetup: {\n rigId: session.rigId!,\n versionId: rigVersion.id,\n rigName,\n script: rigVersion.setupScript,\n timeoutMs: runSettings.rigSetupTimeoutMs,\n contentHash: rigProviderImageContentHash({\n backend: turn.sandboxBackend,\n sourceImage: rigProviderImageSourceImage(\n logicalSandboxSettings,\n turn.sandboxBackend,\n ),\n definition: rigVersion,\n }),\n },\n }\n : {}),\n ...(rigVersion.credentialHooks.length > 0\n ? { rigCredentialHookIds: rigVersion.credentialHooks }\n : {}),\n }\n : {}),\n });\n } catch (error) {\n agentConstructionOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"agent_construction\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: agentConstructionOutcome,\n durationSeconds: (performance.now() - agentConstructionStartedAt) / 1_000,\n });\n }\n })();\n const postAgentPreparationStartedAt = performance.now();\n if (modelRunSettings.sandboxBackend !== \"none\" && toolCancellationFenceRef.current === null) {\n throw new Error(\n \"Sandbox agent construction did not install the mandatory turn tool cancellation fence\",\n );\n }\n if (establishPolicy === \"on-demand\" && sandboxHolderId && sandboxGroupId) {\n const lazyHolderId = sandboxHolderId;\n const lazyGroupId = sandboxGroupId;\n const agentDefaultManifest = (agent as { defaultManifest?: unknown }).defaultManifest;\n if (!agentDefaultManifest) {\n throw new Error(\"Lazy sandbox provisioning requires a SandboxAgent defaultManifest\");\n }\n const lazyClient = {\n backendId: sdkBackendIdForSandboxBackend(groupBoxBackend),\n } as EstablishedSandboxSession[\"client\"];\n turnSandboxProvisioner = createTurnSandboxProvisioner<ResumedTurnSandbox>(\n async () => {\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const lazyGitCredentials =\n activeSandboxBackend === \"selfhosted\"\n ? undefined\n : await mintRunGitCredentials(runSettings, turnResources, {\n scope: connectionScope,\n ...(gitCredentialAuthority ? { authority: gitCredentialAuthority } : {}),\n gitCredentials: connectionCredentials?.gitCredentials,\n authorizeGitHubTokenMint,\n });\n const lazyGitTokens = lazyGitCredentials?.gitTokens;\n const lazyCodemodeToken = sandboxCodemodeToken\n ? await mintSandboxCodemodeToken(runSettings, connectionScope, codemodeAuthority)\n : undefined;\n const provisioned = await resumeBoxForTurn(\n {\n db,\n settings: runSettings,\n logicalFallbackSettings: logicalSandboxSettings,\n cancellationSignal: sandboxResumeSignal,\n sandboxMetrics: runtimeMetricsHooksForObservability(observability),\n onSandboxLost: publishSandboxLost,\n },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: lazyGroupId,\n sessionId: input.sessionId,\n backend: groupBoxBackend,\n os: session.sandboxOs,\n environment: sandboxEnvironment,\n ...((runSettings.modalImageRef ?? runSettings.dockerImage)\n ? {\n image: runSettings.modalImageRef ?? runSettings.dockerImage,\n }\n : {}),\n // The lazy acquire must enforce the same frozen rig authority\n // as the eager acquire; otherwise a warm box for another rig\n // can bypass the shared-state conflict/rotation fence.\n ...(rigVersion ? { rigVersionId: rigVersion.id } : {}),\n },\n \"turn\",\n lazyHolderId,\n );\n await publishSandboxLifecycleEvents(provisioned);\n await attachRunCredentialRenewal(\n provisioned.established.session as RunCredentialCommandSession,\n provisioned,\n );\n const provisionedSetupSession = initialRunCredentialMaterial\n ? withRunCredentialsSession(\n provisioned.established.session as object,\n input.sessionId,\n )\n : provisioned.established.session;\n await runWorkspaceMutationForSandbox(\n provisioned,\n \"lazyOwnedSandboxSetup\",\n async () =>\n await runOwnedSandboxSetup(\n agent,\n provisioned.established.session as never,\n provisionedSetupSession as never,\n {\n settings: runSettings,\n environment: sandboxEnvironment,\n onRuntimeEvent: async (event) => {\n await publish?.([{ type: event.type, payload: event.payload }], true);\n },\n ...(lazyGitTokens ? { gitTokenSeedsOverride: lazyGitTokens } : {}),\n ...(lazyGitCredentials?.bindings\n ? {\n gitCredentialBindingsOverride: lazyGitCredentials.bindings,\n }\n : {}),\n ...(lazyCodemodeToken\n ? {\n codemodeTokenSeedOverride: lazyCodemodeToken.token,\n }\n : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n },\n ),\n );\n await attachCodemodeTokenRenewal(\n provisioned.established.session as CodemodeTokenWriterSession,\n lazyCodemodeToken?.expiresAt,\n provisioned,\n );\n await attachGitCredentialRenewal(\n provisioned.established.session as GitCredentialTokenWriterSession,\n lazyGitCredentials,\n provisioned,\n );\n // Return the REAL established box (NOT a copy whose session is the routing\n // proxy). resolveActiveBackend dispatches ops to `provisioned.established.session`;\n // if that were the proxy itself, proxy.exec -> dispatch -> resolve ->\n // provisioner.get() -> proxy.exec -> ... loops forever (an async infinite\n // recursion that HANGS the turn — caught live on staging 2026-07-08). The SDK\n // already holds the proxy directly (injected as lazyOwnedSandbox.session), so it\n // gets per-op routing; the worker-side handle (resolvedSandbox: release,\n // heartbeat, computer-use recording) wants the real box, unproxied.\n return provisioned;\n },\n {\n signal: sandboxResumeSignal,\n onStarted: async () => {\n await publish?.(\n [\n {\n type: \"sandbox.operation.started\",\n payload: { name: \"sandbox.provision\" },\n },\n ],\n true,\n );\n },\n onCompleted: async (provisioned) => {\n await publish?.(\n [\n {\n type: \"sandbox.operation.completed\",\n payload: {\n name: \"sandbox.provision\",\n ...(provisioned.established.origin\n ? { origin: provisioned.established.origin }\n : {}),\n },\n },\n ],\n true,\n );\n throwIfTurnOperationCancelled(sandboxResumeSignal);\n startLeaseHeartbeat(provisioned, activeSandboxBackend ?? groupBoxBackend);\n setupBoxSession = provisioned.established.session;\n resolvedSandbox = provisioned;\n // `get()` does not release the first routed sandbox operation\n // until this hook returns. Materialize durable generated images\n // here so that operation can use their advertised paths without\n // racing a best-effort background copy.\n for (const receipt of generatedImageReceiptsByArtifactId.values()) {\n await materializeGeneratedImageInSandbox(\n receipt,\n provisioned,\n provisioned.established.session,\n );\n }\n },\n onFailed: async (error) => {\n await publish?.(\n [\n {\n type: \"sandbox.operation.failed\",\n payload: {\n name: \"sandbox.provision\",\n error: error instanceof Error ? error.message : String(error),\n },\n },\n ],\n true,\n );\n },\n disposeResult: async (provisioned) => {\n await releaseLateSandbox(provisioned);\n },\n },\n );\n lazyOwnedSandbox = wrapLazyTurnBoxWithRouting(\n {\n db,\n settings,\n bus,\n opJournal,\n onOp: machineOpObserver.observer,\n onSandboxOperation: sandboxOperationObserver,\n onHomeSandboxLost: publishSandboxLost,\n onHomeSandboxRebound,\n ...(runtimeCancellationSignal ? { waitSignal: runtimeCancellationSignal } : {}),\n },\n {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n environment: sandboxEnvironment,\n ...(transientCodemodeEnvironment\n ? { transientExecEnvironment: transientCodemodeEnvironment }\n : {}),\n workspaceMutationFence: {\n accountId: input.accountId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n },\n {\n client: lazyClient,\n backendId: sdkBackendIdForSandboxBackend(groupBoxBackend),\n agentDefaultManifest,\n provisioner: turnSandboxProvisioner,\n homeLeaseIdentity: {\n accountId: input.accountId,\n sandboxGroupId: session.sandboxGroupId,\n backend: groupBoxBackend,\n },\n },\n );\n }\n let companyBrainContributionReceiptRecorded = false;\n const recordCompanyBrainContributionReceiptOnce = (): void => {\n if (companyBrainContributionReceiptRecorded) return;\n companyBrainContributionReceiptRecorded = true;\n try {\n const companyBrainContributionReceipt = buildCompanyBrainContributionReceipt({\n attemptId: input.attemptId,\n turnId: turn.id,\n nestedAgentDepth: session.nestedAgentDepth,\n memoryPromptMode,\n instructionPolicy: instructionPolicySnapshot,\n workspaceAgentInstructions,\n preferences: preferenceSnapshot,\n companyProfile: companyProfileSnapshot,\n companyProfileIncluded,\n workspaceMemory,\n skillActivations: runtimeSkillActivations,\n });\n recordCompanyBrainContributions(observability, companyBrainContributionReceipt);\n observability.info(\"model context contribution receipt\", {\n attemptId: companyBrainContributionReceipt.attemptId,\n turnId: companyBrainContributionReceipt.turnId,\n sessionRole: companyBrainContributionReceipt.sessionRole,\n memoryPromptMode: companyBrainContributionReceipt.memoryPromptMode,\n instructionPolicySnapshotId:\n companyBrainContributionReceipt.instructionPolicySnapshotId,\n preferenceSnapshotId: companyBrainContributionReceipt.preferenceSnapshotId,\n companyProfileSnapshotId: companyBrainContributionReceipt.companyProfileSnapshotId,\n contributions: JSON.stringify(companyBrainContributionReceipt.contributions),\n });\n } catch {\n // Observability must never change model execution semantics.\n }\n };\n const agentInstructions = typeof agent.instructions === \"string\" ? agent.instructions : \"\";\n const compactSummarizer = compactionSummarizerFor(\n agentInstructions.trim() ? agentInstructions : undefined,\n );\n if (remoteCompactionRequester) {\n // Exact byte match with the ordinary turn prefix (CLI base_instructions).\n // Tools serialize lazily inside the requester so setup failures settle as\n // compaction failures rather than raw activity crashes.\n remoteCompactionInstructions = agentInstructions;\n remoteCompactionAgent = agent;\n }\n\n if (compactionOnlyTurn) {\n const requested = await isSessionCompactionRequested(\n db,\n input.workspaceId,\n input.sessionId,\n );\n let outcome: Awaited<ReturnType<typeof maybeCompactContext>> | null = null;\n if (requested) {\n try {\n outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n compactSummarizer,\n {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n } catch (error) {\n // Codex retries retryable checkpoint-provider failures rather than\n // treating them as a semantic compaction result. Keep the operator\n // request pending and let the ordinary same-turn provider/capacity\n // recovery path re-dispatch this exact maintenance execution.\n if (shouldRecoverCompactionProviderFailure(error)) throw error;\n if (error instanceof TurnAttemptFencedError) throw error;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turn.id,\n executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: true,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(error)) throw error;\n const errorMessage = String(compactionFailureReasonFromError(error));\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(landmark.requestConsumed ? {} : { consumeRequestedCompactionFailure: true }),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = error;\n return claimedResult({ status: \"idle\" });\n }\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, \"operator\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n }\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n maintenance: \"context_compaction\",\n result: outcome?.compacted ? \"compacted\" : (outcome?.reason ?? \"already_applied\"),\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n\n // Pre-turn durable context compaction. When the single Codex-parity\n // threshold is crossed, this summarizes active history and rebuilds active\n // history as [user messages..., summary] BEFORE the model input is read.\n // Summarizer context overflows drop one oldest summarizer-input item and\n // retry, exactly like Codex. Other failures end this turn honestly.\n // Run before every fresh inference. Approval resumes replay their frozen\n // RunState verbatim and recovering attempts already compacted, if needed,\n // before the first attempt's model boundary.\n if (triggerType === \"user.message\" || triggerType === \"system.update.delivered\") {\n let forced = false;\n try {\n // Operator /compact (the slash command) sets a durable request flag;\n // observe it without consuming it so a failed/stale attempt cannot\n // lose the request. The replacement transaction clears it on success.\n forced = await isSessionCompactionRequested(db, input.workspaceId, input.sessionId);\n const outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turnId!,\n executionGeneration,\n attemptId: input.attemptId,\n },\n session.lastInputTokens,\n // Provider-aware summarizer: when the turn's model resolved to a\n // registry provider, summarize on THAT provider's client + wire API\n // (a chat provider can't summarize through OpenAI/Azure). Null\n // resolution uses the built-in Responses summarizer with the same\n // session prompt-cache key as the main model calls.\n compactSummarizer,\n forced\n ? {\n force: true,\n clearRequestedCompaction: true,\n trigger: \"operator\",\n materializeHistory: materializeScreenshotHistory,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n }\n : {\n trigger: \"auto\",\n materializeHistory: materializeScreenshotHistory,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n const compactionTrigger = forced ? \"operator\" : undefined;\n recordContextCompaction(observability, compactionTrigger ?? \"auto\");\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n } catch (compactError) {\n if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;\n if (compactError instanceof TurnAttemptFencedError) throw compactError;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: turnId!,\n executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: forced,\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n if (!isCompactionSummaryFailure(compactError)) throw compactError;\n const errorMessage = String(compactionFailureReasonFromError(compactError));\n observability.error(\"context compaction failed\", {\n sessionId: input.sessionId,\n turnId,\n ...safeErrorDiagnostic(compactError),\n });\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(forced && !landmark.requestConsumed\n ? { consumeRequestedCompactionFailure: true }\n : {}),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = compactError;\n return claimedResult({ status: \"idle\" });\n }\n }\n recordTurnStartupPhase(observability, {\n phase: \"post_agent_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - postAgentPreparationStartedAt) / 1_000,\n });\n let fileMaterializationFailures: SandboxFileDownloadFailure[] = [];\n let fileDownloadsMaterializedForRun = false;\n if (resolvedSandbox && setupBoxSession && fileResourceDownloads.length > 0) {\n const fileMaterializationStartedAt = performance.now();\n let fileMaterializationOutcome: \"completed\" | \"failed\" = \"completed\";\n const cacheMaterialization = resolvedSandbox.established.backendId !== \"selfhosted\";\n let fileMaterializationCache: \"hit\" | \"miss\" | \"disabled\" = cacheMaterialization\n ? \"miss\"\n : \"disabled\";\n try {\n const boxInstanceId = resolvedSandbox.established.instanceId;\n // Managed boxes are immutable platform state, so their durable lease can\n // memoize successful downloads. A connected machine is user-owned: files\n // can be changed or removed between turns, so verify/materialize every\n // attached file each turn instead of trusting the managed-box cache.\n const alreadyMaterialized = cacheMaterialization\n ? await getMaterializedSandboxFileResources(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n expectedEpoch: resolvedSandbox.leaseEpoch,\n instanceId: boxInstanceId,\n })\n : new Set<string>();\n const downloadsToMaterialize = filterUnmaterializedSandboxFileDownloads(\n fileResourceDownloads,\n alreadyMaterialized,\n );\n if (cacheMaterialization && downloadsToMaterialize.length === 0) {\n fileMaterializationCache = \"hit\";\n }\n const runAs = sandboxRunAs(runSettings);\n if (downloadsToMaterialize.length > 0) {\n const materialized = await runWorkspaceMutationForSandbox(\n resolvedSandbox,\n \"fileMaterialization\",\n async () =>\n await materializeSandboxFileDownloads(\n setupBoxSession as CodemodeTokenWriterSession,\n downloadsToMaterialize,\n {\n onRuntimeEvent: async (event) => {\n await publish!([{ type: event.type, payload: event.payload }], true);\n },\n ...(runAs ? { runAs } : {}),\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n },\n ),\n );\n fileMaterializationFailures = materialized.failures;\n fileMaterializationOutcome = sandboxFileMaterializationOutcome(materialized.failures);\n const failedFileIds = new Set(materialized.failures.map((failure) => failure.fileId));\n const succeededFileIds = downloadsToMaterialize\n .map((download) => download.fileId)\n .filter((fileId) => !failedFileIds.has(fileId));\n if (cacheMaterialization && succeededFileIds.length > 0) {\n await markSandboxFileResourcesMaterialized(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sandboxGroupId: session.sandboxGroupId,\n expectedEpoch: resolvedSandbox.leaseEpoch,\n instanceId: boxInstanceId,\n fileIds: succeededFileIds,\n });\n }\n }\n fileDownloadsMaterializedForRun = true;\n } catch (error) {\n fileMaterializationOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"file_materialization\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: fileMaterializationOutcome,\n durationSeconds: (performance.now() - fileMaterializationStartedAt) / 1_000,\n count: fileResourceDownloads.length,\n cache: fileMaterializationCache,\n });\n }\n } else {\n recordTurnStartupPhase(observability, {\n phase: \"file_materialization\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: 0,\n count: 0,\n });\n }\n const requiredVideoFileIds = new Set(requiredGeneratedVideoFiles.map((file) => file.fileId));\n const failedRequiredVideo = fileMaterializationFailures.find((failure) =>\n requiredVideoFileIds.has(failure.fileId),\n );\n if (failedRequiredVideo) {\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: turn.id,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"generated_video_materialization_failed\",\n detail: {\n retryable: true,\n operationIds: requiredGeneratedVideoFiles.map((file) => file.operationId),\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n if (recovery.action !== \"recovering\") {\n throw new Error(\"Generated video materialization could not enter recovery\");\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\", continueDelayMs: 1_000 });\n }\n const unavailableSandboxFilesNote = sandboxFileDownloadFailureNote(\n fileMaterializationFailures,\n );\n // Build one attempt from canonical history. The provider adapter creates\n // only the temporary wire view required by this turn's selected API;\n // subscription identity never edits or filters durable history.\n const activeTurnId = turnId;\n if (!activeTurnId) {\n throw new Error(\"Turn id was not initialized\");\n }\n let runInput: Awaited<ReturnType<typeof turnInput>>[\"input\"] | null = null;\n const prepareRunAttemptInput = async () => {\n const historyPreparationStartedAt = performance.now();\n let historyPreparationOutcome: \"completed\" | \"failed\" = \"completed\";\n let preparedHistoryCount: number | null = null;\n try {\n const prepared = await turnInput(db, runtime, agent, trigger, {\n turnId: activeTurnId,\n recovering: turn.executionGeneration > 1,\n ...(unavailableSandboxFilesNote ? { unavailableSandboxFilesNote } : {}),\n ...(runCredentialsNote ? { runCredentialsNote } : {}),\n providerApi,\n projectCanonicalHistory: generatedImageHistoryProjector,\n materializeModelHistory: materializeScreenshotHistory,\n materializeSerializedRunState: materializeScreenshotRunState,\n projectModelHistory: modelHistoryProjector,\n onPreparationPhase: (measurement) => {\n recordTurnStartupPhase(observability, {\n phase: `history_${measurement.phase}`,\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: measurement.outcome,\n durationSeconds: measurement.durationSeconds,\n });\n },\n });\n const generatedImageMaterializationStartedAt = performance.now();\n let generatedImageMaterializationOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n for (const receipt of generatedImageReceiptsByArtifactId.values()) {\n await materializeGeneratedImage(receipt);\n }\n } catch (error) {\n generatedImageMaterializationOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"history_generated_image_materialization\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: generatedImageMaterializationOutcome,\n durationSeconds: (performance.now() - generatedImageMaterializationStartedAt) / 1_000,\n count: generatedImageReceiptsByArtifactId.size,\n });\n }\n runInput = prepared.input;\n providerArtifactCandidates = prepared.providerArtifactCandidates;\n // Slice index = the length of the model-facing (active) history this turn\n // is seeded from; new items beyond it (the trigger message + this turn's\n // generated items) are the ones to persist. After a compaction this is the\n // short [summary, ...tail] active set, NOT the total row count. The\n // absolute write position is tracked separately (next whole number past\n // the max existing position) because the fractional summary row means\n // total rows no longer equal max(position)+1. Pre-compaction both reduce to\n // the old total-count value, so the common path is unchanged.\n //\n // CRITICAL: seed from the structurally repaired active-row length, not the raw active\n // count. `prepareRunInput` builds `state.history` from\n // `sanitizeHistoryItemsForModel(activeRows)`, so when sanitization drops K\n // rows (a legacy orphan/dangling pair), the in-memory history this turn\n // starts from is K shorter than the raw row count. The reconcile slices the\n // repaired `state.history` off `persistedHistoryCount`; seeding it from\n // the raw count (K too high) skips K genuinely-new items, and a\n // `function_call` left in that skipped region can later have its\n // `function_call_result` persisted alone — the orphan that 400s on replay\n // and bricks the session (issue-61). The repaired seed is already\n // orphan-free, so it is a stable prefix of the re-sanitized history and the\n // slice begins exactly at the first genuinely-new item.\n // prepareInput already sanitized the exact durable prefix represented\n // by state.history. Carry its count forward instead of loading and\n // retaining the full active transcript a second time beside runInput.\n persistedHistoryCount = prepared.persistedHistoryCount;\n preparedHistoryCount = prepared.persistedHistoryCount;\n const historyPositionStartedAt = performance.now();\n let historyPositionOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n nextHistoryPosition = await nextSessionHistoryPosition(\n db,\n input.workspaceId,\n input.sessionId,\n );\n } catch (error) {\n historyPositionOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"history_position_load\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: historyPositionOutcome,\n durationSeconds: (performance.now() - historyPositionStartedAt) / 1_000,\n });\n }\n } catch (error) {\n historyPreparationOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"history_preparation\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: historyPreparationOutcome,\n durationSeconds: (performance.now() - historyPreparationStartedAt) / 1_000,\n count: preparedHistoryCount,\n });\n }\n };\n\n const forceContextCompaction = async (\n triggerLabel: \"overflow\" | \"proactive\" | \"operator\",\n recoverySignalTokens: number | null,\n ) => {\n const outcome = await waitForTurnOperation(\n maybeCompactContext(\n db,\n modelRunSettings,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration,\n attemptId: input.attemptId,\n },\n // Never reuse the persisted prior-turn signal for recovery. Proactive\n // guards provide their exact current provider-based signal; provider\n // overflows do not, so their diagnostic signal stays unknown/zero.\n // Forced recovery proves progress separately by comparing the\n // replacement with the current active-history estimate.\n recoverySignalTokens,\n compactSummarizer,\n {\n force: true,\n ...(triggerLabel === \"operator\" ? { clearRequestedCompaction: true } : {}),\n trigger: triggerLabel,\n materializeHistory: materializeScreenshotHistory,\n projectModelInput: compactionModelHistoryProjector,\n ...compactionModeOptions,\n },\n ),\n cancellationSignal,\n undefined,\n );\n if (outcome.events.length > 0) {\n if (outcome.compacted) {\n recordContextCompaction(observability, triggerLabel);\n }\n await publishCompactionOutcomeEvents(outcome.events);\n }\n return outcome;\n };\n\n // Keep response identity across every stream attempt in this\n // activity. Context compaction retries the same logical dispatch by\n // calling runStreamAttempt again; resetting this state there would reuse\n // the first no-response-ID fallback key and suppress a real model call.\n const modelResponseState = createModelResponseEventState(claimedModelUsageSourceKeys);\n let workerPreparationTotalRecorded = false;\n const runStreamAttempt = async (): Promise<RunAgentTurnResult> => {\n if (!runInput) {\n throw new Error(\"Run input was not prepared\");\n }\n stream = undefined;\n batcher = null;\n // The SDK emits every processed call item for one model response before\n // it emits any result for that response. Keep that response-local batch\n // in memory so an orphan from an older response cannot pin later stable\n // calls. Durable recovery remains call/result based and needs no batch\n // schema or compatibility state.\n let currentToolBatchCallIds = new Set<string>();\n let currentToolBatchCompletedCallIds = new Set<string>();\n let streamSawPerResponseUsage = false;\n // Actual input tokens of the most recent model response this turn; the\n // pre-read trigger for the NEXT turn. Persisted at every turn-end path.\n throwIfWorkerShuttingDown();\n throwIfTurnCancelled();\n const ownedEstablished = resolvedSandbox?.established ?? lazyOwnedSandbox;\n const runStreamOnce = async (): ReturnType<OpenGeniRuntime[\"runStream\"]> => {\n // Eager owned sessions must settle the exact platform-setup provider\n // promise before the long model stream starts; otherwise one admission\n // would remain in flight for the entire turn and suppress every\n // heartbeat capture. Lazy setup already runs under the same wrapper in\n // its first-operation provisioner above.\n if (resolvedSandbox && !lazyOwnedSandbox && ownedEstablished) {\n const ownedSandboxSetupStartedAt = performance.now();\n let ownedSandboxSetupOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n const eagerSetupSession = setupBoxSession ?? ownedEstablished.session;\n // `deferredSetup: true` below tells the runtime that the worker owns\n // platform setup, so the runtime intentionally skips its credential\n // session callback. Materialize host-managed run credentials here\n // before any setup command (including provider login hooks), then\n // decorate setup commands so they source the active generation.\n await attachRunCredentialRenewal(\n eagerSetupSession as RunCredentialCommandSession,\n resolvedSandbox,\n );\n const eagerCredentialSetupSession = initialRunCredentialMaterial\n ? withRunCredentialsSession(eagerSetupSession as object, input.sessionId)\n : eagerSetupSession;\n await runWorkspaceMutationForSandbox(\n resolvedSandbox,\n \"eagerOwnedSandboxSetup\",\n async () =>\n await runOwnedSandboxSetup(\n agent,\n ownedEstablished.session as never,\n eagerCredentialSetupSession as never,\n {\n settings: runSettings,\n environment: sandboxEnvironment,\n preparedInput: runInput!,\n ...(fileDownloadsMaterializedForRun\n ? { fileDownloadsMaterialized: true }\n : {}),\n onRuntimeEvent: async (event) => {\n await renewServingCredentialLease(\"runtime_event\");\n if (servingCredentialLeaseLost()) {\n throw new Error(\"Provider credential lease expired during sandbox setup\");\n }\n await publish!([{ type: event.type, payload: event.payload }], true);\n },\n ...(toolCancellationFenceRef.current\n ? {\n commandRunner: toolCancellationFenceRef.current.runSandboxCommand.bind(\n toolCancellationFenceRef.current,\n ),\n }\n : {}),\n },\n ),\n );\n await attachGitCredentialRenewal(\n eagerSetupSession as GitCredentialTokenWriterSession,\n initialGitCredentials,\n );\n } catch (error) {\n ownedSandboxSetupOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"owned_sandbox_setup\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: ownedSandboxSetupOutcome,\n durationSeconds: (performance.now() - ownedSandboxSetupStartedAt) / 1_000,\n count: fileResourceDownloads.length,\n });\n }\n }\n // Conservative request boundary: once control enters runStream, the\n // provider may have accepted work even if no response/event follows.\n // Escaped MCP setup timeouts are automatically recoverable only\n // before this line.\n recordCompanyBrainContributionReceiptOnce();\n const providerDispatchStartedAt = performance.now();\n let providerDispatchOutcome: \"completed\" | \"failed\" = \"completed\";\n try {\n // This histogram describes worker preparation until the first entry\n // into the runtime. Lazy SDK request preparation and the durable\n // model-request audit happen after this boundary and have their own\n // phase metrics. Context-compaction recovery re-enters\n // runStreamAttempt; recording again would fold the prior request and\n // compaction into a bogus second startup sample.\n if (!workerPreparationTotalRecorded) {\n workerPreparationTotalRecorded = true;\n recordTurnWorkerPreparationTotal(observability, {\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - workerPreparationStartedAt) / 1_000,\n });\n }\n modelRequestStarted = true;\n return await runtime.runStream(agent, runInput!, modelRunSettings, {\n signal: runtimeCancellationSignal,\n sandboxEnvironment,\n onRuntimeEvent: async (event) => {\n await renewServingCredentialLease(\"runtime_event\");\n if (servingCredentialLeaseLost()) {\n throw new Error(\"Provider credential lease expired during the active turn\");\n }\n await publish!([{ type: event.type, payload: event.payload }], true);\n },\n // P1.2: inject the resumed box NON-OWNED (the SDK never reaps it — the\n // keystone). Absent when the flag is off -> legacy build-and-discard.\n ...(ownedEstablished\n ? {\n ownedSandbox: {\n client: ownedEstablished.client,\n session: ownedEstablished.session,\n ...(resolvedSandbox?.established.sessionState\n ? {\n sessionState: resolvedSandbox.established.sessionState,\n }\n : {}),\n // Pin platform setup (hooks + file materialization) to the un-proxied\n // established box — never through the routing proxy, which would\n // re-route those execs onto a machine swapped in mid-turn.\n ...(setupBoxSession ? { setupSession: setupBoxSession } : {}),\n ...(fileDownloadsMaterializedForRun\n ? { fileDownloadsMaterialized: true }\n : {}),\n // Both owned paths execute setup outside runStream: eager just\n // above under its exact admission, lazy in the provisioner.\n deferredSetup: true,\n },\n }\n : {}),\n ...(activeSandboxBackend !== \"selfhosted\" &&\n sandboxCodemodeToken &&\n sandboxCodemodeTokenExpiresAt &&\n !lazyOwnedSandbox\n ? {\n onCodemodeTokenSessionReady: async (\n tokenSession: CodemodeTokenWriterSession,\n ) => {\n const renewalSession =\n (setupBoxSession as CodemodeTokenWriterSession | null) ?? tokenSession;\n await attachCodemodeTokenRenewal(renewalSession);\n },\n }\n : {}),\n ...(runCredentialResolver\n ? {\n runCredentialSessionId: input.sessionId,\n ...(!lazyOwnedSandbox\n ? {\n onRunCredentialSessionReady: async (\n credentialSession: RunCredentialCommandSession,\n ) => {\n const pinnedCredentialSession = setupBoxSession\n ? (setupBoxSession as RunCredentialCommandSession)\n : credentialSession;\n await attachRunCredentialRenewal(pinnedCredentialSession);\n },\n }\n : {}),\n }\n : {}),\n ...(modelRunSettings.sandboxBackend !== \"none\"\n ? {\n onSandboxSessionReady: async (sandboxSession: CodemodeTokenWriterSession) => {\n sdkOwnedSandboxSession = sandboxSession;\n for (const receipt of generatedImageReceiptsByArtifactId.values()) {\n await materializeGeneratedImageInOwnedSdkSession(receipt, sandboxSession);\n }\n },\n }\n : {}),\n contextCompactionSignal: () => modelResponseContextSignal(modelResponseState),\n contextCompactionRequested: () =>\n isSessionCompactionRequested(db, input.workspaceId, input.sessionId),\n onModelPreparationPhase: (measurement) => {\n recordTurnStartupPhase(observability, {\n phase: `model_prepare_${measurement.phase}`,\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: measurement.outcome,\n durationSeconds: measurement.durationSeconds,\n ...(measurement.count === undefined ? {} : { count: measurement.count }),\n });\n },\n ...(toolCancellationFenceRef.current\n ? {\n turnToolCancellationFence: toolCancellationFenceRef.current,\n }\n : {}),\n });\n } catch (error) {\n providerDispatchOutcome = \"failed\";\n throw error;\n } finally {\n recordTurnStartupPhase(observability, {\n phase: \"provider_dispatch\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: providerDispatchOutcome,\n durationSeconds: (performance.now() - providerDispatchStartedAt) / 1_000,\n });\n }\n };\n if (codexLeaseLost) {\n throw new Error(\"Codex credential lease expired before the model run\");\n }\n if (xaiLeaseLost) {\n throw new Error(\"xAI credential lease expired before the model run\");\n }\n stream = await withProviderRequestContext(runStreamOnce);\n // Bounded provider label for the streaming SLIs — the resolved registry\n // provider id (or the built-in OpenAI/Azure provider), never a raw\n // user-supplied model string.\n const streamProvider = resolvedModel?.provider.id ?? settings.openaiProvider ?? \"openai\";\n const streamTiming = new StreamTimingMetrics(observability, {\n provider: streamProvider,\n });\n batcher = createRuntimeBatcher(\n async (events) => {\n await publish!(events);\n },\n {\n onFlush: ({ events, durationSeconds }) =>\n recordBatchFlush(observability, { events, durationSeconds }),\n },\n );\n\n const streamBootstrapStartedAt = performance.now();\n let streamBootstrapRecorded = false;\n const recordStreamBootstrap = (): void => {\n if (streamBootstrapRecorded) return;\n streamBootstrapRecorded = true;\n recordTurnStartupPhase(observability, {\n phase: \"stream_bootstrap\",\n provider: turnExecutionPolicy.providerId,\n backend: activeSandboxBackend ?? groupBoxBackend,\n outcome: \"completed\",\n durationSeconds: (performance.now() - streamBootstrapStartedAt) / 1_000,\n count: turnTools.length,\n });\n };\n if (!firstModelRequestPreparationRecorded) {\n firstModelRequestPreparationStartedAt = performance.now();\n firstModelRequestCheckpointAt = firstModelRequestPreparationStartedAt;\n }\n const iterator = stream.toStream()[Symbol.asyncIterator]();\n let streamDone = false;\n try {\n while (true) {\n const next = await nextStreamEvent(iterator, activityContext);\n recordStreamBootstrap();\n if (next.done) {\n streamDone = true;\n break;\n }\n let stableToolCallIdsToClear: string[] | null = null;\n let completedCurrentToolBatch = false;\n let retainedScreenshotMetadata: RetainedArtifactMetadata | null = null;\n let normalizedSdkEvents: ReturnType<typeof normalizeSdkEvent> | null = null;\n const generatedImage = generatedImageFromSdkEvent(next.value);\n if (isCompletedGeneratedImageSdkEvent(next.value) && !generatedImage) {\n throw new Error(\n \"Completed native image item could not cross the retained-artifact boundary\",\n );\n }\n const generatedImageReceipt = generatedImage\n ? await retainNativeGeneratedImage(generatedImage)\n : null;\n const responseResult = await processModelResponseTerminalEvent({\n event: next.value,\n state: modelResponseState,\n dispatchId: modelUsageDispatchId,\n settings,\n db,\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n provider: resolvedModel?.provider.id ?? settings.openaiProvider,\n providerApi: resolvedModel?.provider.api ?? \"responses\",\n model: turn.model,\n latencyMode: turnExecutionPolicy.latencyMode,\n metricProvider: streamProvider,\n externallyBilled: isExternallyBilledTurn,\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n renewLease: () => renewServingCredentialLease(\"model_usage\"),\n leaseLost: servingCredentialLeaseLost,\n leaseLostMessage: \"Provider credential lease expired during the active turn\",\n setLastInputTokens: setLastInputTokensFenced,\n });\n assertModelResponseLatencyMode({\n event: next.value,\n requested: turnExecutionPolicy.latencyMode,\n model: turn.model,\n ...(resolvedModel?.provider.id ? { providerId: resolvedModel.provider.id } : {}),\n });\n if (responseResult.status === \"processed\") {\n const rawStreamHistory = (stream.state as { history?: unknown[] }).history;\n if (Array.isArray(rawStreamHistory)) {\n // The completed image item is normally retained from its own\n // run-item event above. Scan once at the terminal response as\n // a compatibility backstop before reconciliation can persist\n // provider bytes. Never rescan history for every token delta.\n await retainNativeGeneratedImagesFromHistory(\n rawStreamHistory as Array<Record<string, unknown>>,\n );\n }\n streamSawPerResponseUsage ||= responseResult.usageReported;\n currentToolBatchCallIds = new Set<string>();\n currentToolBatchCompletedCallIds = new Set<string>();\n await reconcileConversationTruth();\n turnLifecycleMetricsFor(observability).progress(turnId!);\n modelCheckpointMemoryCollector.schedule(observability);\n try {\n await ensureRunAllowed(\n settings,\n db,\n input.accountId,\n input.workspaceId,\n isExternallyBilledTurn,\n entitlements,\n );\n } catch (limitError) {\n // Capture the run state at the boundary so the budget valve in\n // the outer catch can end this segment gracefully with full\n // conversation context preserved for the post-top-up resume.\n let serializedRunState: string | null = null;\n try {\n serializedRunState = compactMediaRunState(String(stream.state.toString()));\n } catch {\n serializedRunState = null;\n }\n throw new BudgetExhaustedError(\n limitError instanceof Error ? limitError.message : String(limitError),\n serializedRunState,\n );\n }\n }\n const durableSdkEvent = generatedImageReceipt\n ? compactGeneratedImageSdkEvent(next.value, generatedImageReceipt)\n : next.value;\n const pendingToolCall = pendingToolCallFromSdkEvent(durableSdkEvent);\n if (pendingToolCall) {\n const registered = await registerPendingSessionToolCall(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration,\n attemptId: input.attemptId,\n modelToolOutputTruncationTokens: modelRunSettings.modelToolOutputTruncationTokens,\n callId: pendingToolCall.callId,\n callType: pendingToolCall.callType,\n callItem: pendingToolCall.callItem as Record<string, unknown>,\n });\n if (!registered.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording an in-flight tool call\",\n );\n }\n currentToolBatchCallIds.add(pendingToolCall.callId);\n if (toolCallProducesRetainableSessionImage(pendingToolCall.callName)) {\n retainedSessionImageCallIds.add(pendingToolCall.callId);\n }\n }\n const completedToolCall = completedToolCallFromSdkEvent(durableSdkEvent);\n if (completedToolCall) {\n retainedScreenshotMetadata =\n retainedScreenshotReceiptsByCallId.get(completedToolCall.callId) ?? null;\n const typedScreenshot = retainedScreenshotMetadata\n ? null\n : typedScreenshotFromSdkEvent(durableSdkEvent);\n if (\n !retainedScreenshotMetadata &&\n retainedSessionImageCallIds.has(completedToolCall.callId) &&\n sdkEventContainsInlineImage(durableSdkEvent) &&\n !typedScreenshot\n ) {\n retainedScreenshotMetadata = unavailableRetainedSessionImage({\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n toolCallId: completedToolCall.callId,\n toolOutputId: completedToolCall.callId,\n reason: \"unsupported\",\n });\n retainedScreenshotReceiptsByCallId.set(\n completedToolCall.callId,\n retainedScreenshotMetadata,\n );\n }\n if (\n !retainedScreenshotMetadata &&\n typedScreenshot &&\n typedScreenshot.callId === completedToolCall.callId &&\n retainedSessionImageCallIds.has(completedToolCall.callId)\n ) {\n // Install a compact deterministic fallback before database or\n // object-storage I/O. Unexpected retention failure can then\n // reconcile/serialize without leaking inline bytes.\n retainedScreenshotMetadata = unavailableRetainedSessionImage({\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n toolCallId: typedScreenshot.callId,\n toolOutputId: typedScreenshot.toolOutputId,\n reason: \"pending\",\n });\n retainedScreenshotReceiptsByCallId.set(\n completedToolCall.callId,\n retainedScreenshotMetadata,\n );\n retainedScreenshotMetadata = await retainComputerScreenshot({\n db,\n objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n attemptId: input.attemptId,\n output: typedScreenshot,\n });\n retainedScreenshotReceiptsByCallId.set(\n completedToolCall.callId,\n retainedScreenshotMetadata,\n );\n }\n normalizedSdkEvents = normalizeSdkEvent(\n durableSdkEvent as typeof next.value,\n retainedScreenshotMetadata\n ? {\n toolOutputOverride: retainedScreenshotMetadata,\n retainedOutputEvidence: retainedScreenshotMetadata.available\n ? retainedScreenshotMetadata\n : {\n available: false,\n reason: retainedScreenshotMetadata.reason,\n },\n }\n : {},\n );\n const normalizedToolOutput = normalizedSdkEvents.find(\n (event) =>\n event.type === \"agent.toolCall.output\" &&\n (event.payload as { id?: unknown }).id === completedToolCall.callId,\n )?.payload as { output?: unknown } | undefined;\n if (!normalizedToolOutput || !Object.hasOwn(normalizedToolOutput, \"output\")) {\n throw new Error(\n `Completed SDK tool call ${completedToolCall.callId} produced no durable output projection`,\n );\n }\n const durableResultItem = retainedScreenshotMetadata\n ? (compactRetainedScreenshotHistory(\n [completedToolCall.resultItem],\n retainedScreenshotReceiptsByCallId,\n )[0] ?? completedToolCall.resultItem)\n : completedToolCall.resultItem;\n // Keep every parallel result in the attempt ledger until the full\n // call batch has settled. The SDK's computed history is\n // non-monotonic while parallel calls complete (a later call may\n // appear before an earlier persisted pair), so reconciling a\n // partial batch through a scalar watermark can create an orphan.\n const recorded = await recordPendingSessionToolCallResult(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration,\n attemptId: input.attemptId,\n callId: completedToolCall.callId,\n modelToolOutputTruncationTokens: modelRunSettings.modelToolOutputTruncationTokens,\n resultItem: durableResultItem as Record<string, unknown>,\n eventOutput: normalizedToolOutput.output,\n ...(videoGenerationAcceptancesByCallId.has(completedToolCall.callId)\n ? {\n videoGenerationAcceptance: videoGenerationAcceptancesByCallId.get(\n completedToolCall.callId,\n )!,\n }\n : {}),\n });\n if (!recorded.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while recording a tool-call result\",\n );\n }\n const videoAcceptance = videoGenerationAcceptancesByCallId.get(\n completedToolCall.callId,\n );\n if (videoAcceptance && startVideoGenerationWorkflow) {\n try {\n await startVideoGenerationWorkflow({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: videoAcceptance.operationId,\n });\n } catch (error) {\n // The accepted operation is durable. The recovery sweep starts\n // the same deterministic workflow ID if this nudge fails.\n observability.warn(\"Video generation workflow start deferred\", {\n operationId: videoAcceptance.operationId,\n errorClass: error instanceof Error ? error.name : \"UnknownError\",\n });\n }\n }\n const belongsToCurrentBatch = currentToolBatchCallIds.has(completedToolCall.callId);\n if (belongsToCurrentBatch) {\n currentToolBatchCompletedCallIds.add(completedToolCall.callId);\n }\n const currentBatchIsStable =\n belongsToCurrentBatch &&\n currentToolBatchCallIds.size > 0 &&\n currentToolBatchCompletedCallIds.size === currentToolBatchCallIds.size;\n const standaloneStableResult =\n !belongsToCurrentBatch && currentToolBatchCallIds.size === 0;\n if (currentBatchIsStable || standaloneStableResult) {\n // Persist the SDK's now-stable complete call/result batch. Keep\n // the receipts until the normalized tool-output event below is\n // durably flushed: recovery then covers every crash boundary\n // without either losing or duplicating the UI projection.\n await reconcileConversationTruth({ requireDurable: true });\n stableToolCallIdsToClear = currentBatchIsStable\n ? [...currentToolBatchCallIds]\n : [completedToolCall.callId];\n completedCurrentToolBatch = currentBatchIsStable;\n }\n }\n const normalized =\n normalizedSdkEvents ??\n normalizeSdkEvent(\n durableSdkEvent as typeof next.value,\n retainedScreenshotMetadata\n ? {\n toolOutputOverride: retainedScreenshotMetadata,\n retainedOutputEvidence: retainedScreenshotMetadata.available\n ? retainedScreenshotMetadata\n : {\n available: false,\n reason: retainedScreenshotMetadata.reason,\n },\n }\n : {},\n );\n for (const event of normalized) {\n streamTiming.onEvent(event.type);\n await batcher.push(event);\n }\n // Structural tool-output events await their durable append before\n // push returns. The complete result is now retained in the event\n // row and pending-call recovery receipt, so release only our\n // duplicate live SDK marker before a long turn accumulates it.\n releaseMcpResultCustomDataFromSdkEvent(durableSdkEvent);\n if (stableToolCallIdsToClear) {\n const cleared = await clearDurablePendingSessionToolCalls(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n executionGeneration,\n attemptId: input.attemptId,\n callIds: stableToolCallIdsToClear,\n });\n if (!cleared.accepted) {\n throw new TurnAttemptFencedError(\n \"turn attempt ended while finalizing tool-call results\",\n );\n }\n if (completedCurrentToolBatch) {\n currentToolBatchCallIds = new Set<string>();\n currentToolBatchCompletedCallIds = new Set<string>();\n }\n for (const callId of stableToolCallIdsToClear) {\n retainedSessionImageCallIds.delete(callId);\n }\n }\n }\n } finally {\n if (!streamDone) {\n // ReadableStream cancellation synchronously trips the Agents SDK's\n // abort controller, but its returned promise may wait for an\n // uncooperative provider producer. Once this attempt is fenced,\n // awaiting that provider-side cleanup pins the Temporal activity\n // (and therefore Pause) even though every late write is already\n // rejected. Start cancellation and detach only its cleanup wait;\n // the SDK abort signal stops the producer and the durable attempt\n // fence remains the authority for every callback that arrives late.\n void iterator.return?.().catch(() => undefined);\n }\n }\n await waitForTurnStreamCleanup(\n batcher.flush(),\n stream.completed.catch(() => undefined),\n cancellationSignal,\n );\n if (!streamSawPerResponseUsage) {\n const aggregateUsage = stream.state.usage;\n const normalizedAggregateUsage = normalizeModelCallUsage(aggregateUsage);\n const aggregateInput = normalizedAggregateUsage.telemetry.inputTokens;\n const aggregateSourceKey = modelUsageSourceKey({\n responseId: null,\n dispatchId: modelUsageDispatchId,\n positionalKey: \"aggregate\",\n });\n if (!claimedModelUsageSourceKeys.has(aggregateSourceKey)) {\n claimedModelUsageSourceKeys.add(aggregateSourceKey);\n // The aggregate frame is only a billing fallback when no terminal\n // response exposed usage. It is not final-request context authority.\n const aggregateAccountCtx = modelCallAccountContext({\n servingCredentialId: effectiveCodexCredentialId,\n priorSessionCredentialId: priorSessionCodexCredentialId,\n isFirstCallOfTurn: true,\n });\n let aggregateAuthoritative = false;\n await recordCompletedModelCallBeforeOwnershipFences({\n renewLease: () => renewServingCredentialLease(\"model_usage\"),\n leaseLost: servingCredentialLeaseLost,\n leaseLostMessage: \"Provider credential lease expired during the active turn\",\n recordUsage: async () => {\n const billing = await recordModelUsageAndDebitCredits(settings, db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n model: turn.model,\n externallyBilled: isExternallyBilledTurn,\n usage: aggregateUsage,\n normalizedUsage: normalizedAggregateUsage,\n sourceKey: aggregateSourceKey,\n latencyMode: turnExecutionPolicy.latencyMode,\n observability,\n });\n const aggregateProvider = resolvedModel?.provider.id ?? settings.openaiProvider;\n const aggregateProviderApi = resolvedModel?.provider.api ?? \"responses\";\n aggregateAuthoritative = await emitModelCallUsage({\n observability,\n publish,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n provider: aggregateProvider,\n providerApi: aggregateProviderApi,\n model: turn.model,\n sourceKey: aggregateSourceKey,\n usage: { usage: aggregateUsage },\n normalizedUsage: normalizedAggregateUsage,\n servingAccountHash: aggregateAccountCtx.servingAccountHash,\n accountChangedFromPrevCall: aggregateAccountCtx.accountChangedFromPrevCall,\n emittedSourceKeys: emittedModelUsageSourceKeys,\n });\n if (aggregateAuthoritative && billing) {\n await recordAuthoritativeModelCallFact({\n db,\n observability,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n sourceKey: aggregateSourceKey,\n provider: aggregateProvider,\n providerApi: aggregateProviderApi,\n model: turn.model,\n billing,\n });\n }\n if (aggregateAuthoritative && aggregateInput !== null && aggregateInput > 0) {\n recordModelInputTokens(observability, streamProvider, aggregateInput);\n }\n },\n recordAttemptSignals: async () => {\n if (!aggregateAuthoritative) return;\n // Stream aggregates can cover multiple requests and therefore\n // cannot identify the final request that compaction must bind.\n // They remain billing/telemetry fallback data only.\n modelResponseState.contextSignal = null;\n await setLastInputTokensFenced(null);\n },\n });\n }\n }\n if (stream.interruptions.length > 0) {\n await reconcileConversationTruth();\n const approvals = runtime.serializeApprovals(stream.interruptions);\n const humanInputInterruptions =\n runtime.serializeHumanInputRequests?.(stream.interruptions) ?? [];\n const interactionInterventionInterruptions =\n runtime.serializeInteractionInterventionRequests?.(stream.interruptions) ?? [];\n const latestWorkspace = await getWorkspace(db, input.workspaceId);\n if (!latestWorkspace) throw new Error(`Workspace not found: ${input.workspaceId}`);\n assertWorkspaceHumanInputAllowed(\n resolveWorkspaceAgentHumanInputEnabled(latestWorkspace.settings),\n \"interruption\",\n humanInputInterruptions.length > 0,\n );\n const humanInputRequests = await Promise.all(\n humanInputInterruptions.map(async (interruption) => {\n const id = stableHumanInputRequestId(\n input.sessionId,\n activeTurnId,\n interruption.toolCallId,\n );\n const existing = await getSessionHumanInputRequest(\n db,\n input.workspaceId,\n input.sessionId,\n id,\n );\n if (existing && existing.status !== \"pending\") {\n throw new Error(`Settled human-input request ${id} reappeared as an interruption`);\n }\n const expiresAt = existing?.expiresAt\n ? new Date(existing.expiresAt)\n : interruption.input.expiresInSeconds\n ? new Date(Date.now() + interruption.input.expiresInSeconds * 1000)\n : null;\n return {\n id,\n toolCallId: interruption.toolCallId,\n questions: interruption.input.questions,\n allowSkip: interruption.input.allowSkip,\n expiresAt,\n isNew: existing === null,\n };\n }),\n );\n const requestEvents = humanInputRequests\n .filter((request) => request.isNew)\n .map((request) => ({\n type: \"session.humanInput.requested\" as const,\n payload: {\n request: {\n id: request.id,\n questions: request.questions,\n allowSkip: request.allowSkip,\n expiresAt: request.expiresAt?.toISOString() ?? null,\n },\n },\n }));\n const interactionInterventionRequests = interactionInterventionInterruptions.map(\n (interruption) => ({\n id: stableInteractionInterventionId(\n input.sessionId,\n activeTurnId,\n interruption.toolCallId,\n ),\n operationId: stableInteractionInterventionOperationId(\n input.sessionId,\n activeTurnId,\n interruption.toolCallId,\n ),\n toolCallId: interruption.toolCallId,\n input: interruption.input,\n }),\n );\n const pendingApprovals = [\n ...approvals,\n ...interactionInterventionInterruptions.map((interruption) => interruption.approval),\n ];\n if (\n !(await settle!({\n events: [\n ...requestEvents,\n ...(approvals.length > 0\n ? [\n {\n type: \"session.requiresAction\" as const,\n payload: { approvals },\n },\n ]\n : []),\n {\n type: \"session.status.changed\",\n payload: { status: \"requires_action\" },\n },\n ],\n turnStatus: \"requires_action\",\n sessionStatus: \"requires_action\",\n activeTurnId,\n runState: {\n serializedRunState: compactApprovalRunState(stream.state.toString()),\n pendingApprovals,\n humanInputRequests: humanInputRequests.map(\n ({ isNew: _isNew, ...request }) => request,\n ),\n interactionInterventionRequests,\n },\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n // The interruption and its preceding tool results are now durable.\n await finalizeTurnOpStreamOps();\n activityStatus = \"requires_action\";\n return claimedResult({ status: \"requires_action\" });\n }\n\n const finalOutput = String(stream.finalOutput ?? \"\");\n await reconcileConversationTruth({ requireDurable: true });\n // Op-stream durability fence: the tool outputs are now durably in the\n // history store (a redispatch would NOT re-execute them), so this\n // turn's settled ops may advance their acked frontier — journal persist\n // then wire final ack (licensing the runner to GC its retained\n // frames). Best-effort: a miss leaves the runner's retention TTL to\n // reap, never fails a completed turn.\n await finalizeTurnOpStreamOps();\n if (\n !(await settle!({\n events: [\n {\n type: \"agent.message.completed\",\n payload: { text: finalOutput },\n },\n { type: \"turn.completed\", payload: { output: finalOutput } },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: activeTurnId,\n sessionId: input.sessionId,\n turnId: activeTurnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${activeTurnId}`,\n });\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n };\n\n await prepareRunAttemptInput();\n let retriedAfterCompaction = false;\n while (true) {\n try {\n const result = await runStreamAttempt();\n if (retriedAfterCompaction) {\n observability.info(\"context compaction recovery succeeded after in-activity retry\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n });\n }\n return result;\n } catch (attemptError) {\n const overflow = classifyContextWindowOverflowError(attemptError);\n const compactionNeeded = findCompactionNeededError(attemptError);\n const recoveryKind = compactionNeeded\n ? compactionNeeded.trigger === \"operator\"\n ? \"operator\"\n : \"proactive\"\n : overflow\n ? \"overflow\"\n : null;\n if (!recoveryKind || !publish || !turnStartedPublished) {\n throw attemptError;\n }\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ skipInputOnlyRows: true });\n observability.warn(\"context compaction recovery attempted\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n ...safeErrorDiagnostic(attemptError),\n signalTokens: compactionNeeded?.signalTokens,\n thresholdTokens: compactionNeeded?.thresholdTokens,\n });\n let compacted = false;\n let compactionHandled = false;\n let compactionFailureMessage: string | null = null;\n let compactionRequestCleared = false;\n try {\n const outcome = await forceContextCompaction(\n recoveryKind,\n compactionNeeded?.signalTokens ?? null,\n );\n compacted = outcome.compacted;\n if (outcome.compacted) {\n compactionHandled = true;\n } else {\n compactionHandled = recoveryKind === \"operator\" && outcome.requestConsumed;\n if (!compactionHandled) {\n compactionFailureMessage = compactionFailureReason(outcome.reason);\n }\n }\n } catch (compactError) {\n // Transient checkpoint-provider failures recover this same accepted\n // turn through the normal provider/capacity path. They are not an\n // empty summary and must not create a new goal continuation.\n if (shouldRecoverCompactionProviderFailure(compactError)) throw compactError;\n if (compactError instanceof TurnAttemptFencedError) throw compactError;\n const landmark = await settleFailedContextCompactionLandmark(\n db,\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: activeTurnId!,\n executionGeneration,\n attemptId: input.attemptId,\n },\n {\n clearRequestedCompaction: recoveryKind === \"operator\",\n publishLiveEvents: publishCompactionLiveEvents,\n },\n );\n compactionRequestCleared = landmark.requestConsumed;\n if (!isCompactionSummaryFailure(compactError)) throw compactError;\n compactionFailureMessage = String(compactionFailureReasonFromError(compactError));\n observability.warn(\"context compaction recovery compaction failed\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n ...safeErrorDiagnostic(compactError),\n });\n }\n if (!compactionHandled) {\n const errorMessage =\n compactionFailureMessage ??\n \"compaction summarization failed: compaction produced no replacement history\";\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.failed\",\n payload: {\n error: errorMessage,\n code: \"context_compaction_failed\",\n retryable: false,\n recovery: \"user_message\",\n compacted: false,\n },\n },\n {\n type: \"session.status.changed\",\n payload: { status: \"idle\" },\n },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n ...(recoveryKind === \"operator\" && !compactionRequestCleared\n ? { consumeRequestedCompactionFailure: true }\n : {}),\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = attemptError;\n // The failed turn settlement already defers ordinary internal\n // updates and makes the delivered goal-continuation receipt\n // terminal. End this workflow run as well: returning plain idle\n // would immediately synthesize another goal continuation against\n // the unchanged active history and repeat the same failed\n // compaction. A new human/API prompt, Steer, or explicitly requested\n // Compact remains a durable explicit wake and may retry; ordinary\n // machine updates stay pending for that actionable wake.\n return claimedResult({ status: \"idle\", deferredUntilWake: true });\n }\n // Codex parity: compaction remains inside the same logical turn and\n // the same activity. Rebuild the model-visible history from the\n // durable replacement and continue the sampling loop; do not create\n // a recovery event, a queue row, a fake user message, or a sandbox.\n retriedAfterCompaction = true;\n observability.info(\"context compaction recovery retrying turn after compaction\", {\n sessionId: input.sessionId,\n turnId: activeTurnId,\n reason: recoveryKind,\n compacted,\n });\n await prepareRunAttemptInput();\n }\n }\n } catch (error) {\n // Graceful worker shutdown (deploy / rollout restart): checkpoint the\n // same current inference for a new fenced attempt instead of failing the\n // session. Conversation truth is already persisted per model response;\n // the final reconcile bounds loss to the one in-flight model step.\n //\n // The branch deliberately does NOT require turn.started to have been\n // published: a shutdown landing during setup (claim/billing, before the\n // turn visibly started) must also recover, not fail the session. In that\n // early case nothing ran, so the new attempt uses the original trigger.\n // The turn id falls\n // back to the workflow-claimed turn when the local lookup had not\n // finished yet.\n const recoveryTurnId = turnId;\n // A true epoch supersession and a provider lifecycle transition are both\n // recoverable control-plane states, never session failures. The latter is\n // paced briefly; the next acquire waits on the durable claim and resumes\n // immediately when it clears.\n if (\n (error instanceof SandboxLeaseSupersededError ||\n error instanceof SandboxLeaseTransitionError) &&\n recoveryTurnId\n ) {\n try {\n const fencedLease = await readLease(db, input.workspaceId, error.sandboxGroupId).catch(\n () => null,\n );\n const lifecycleTransition = error instanceof SandboxLeaseTransitionError;\n const rotationPending =\n fencedLease?.rotationRequestedAt != null ||\n (lifecycleTransition && error.reason === \"rotation_in_progress\");\n const transitionPending = lifecycleTransition || rotationPending;\n const deadlineRotationPending =\n rotationPending && fencedLease?.rotationReason === \"provider_deadline\";\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: deadlineRotationPending\n ? \"sandbox_deadline_rotation\"\n : lifecycleTransition\n ? \"sandbox_lifecycle_transition\"\n : \"sandbox_lease_superseded\",\n ...(transitionPending\n ? {\n detail: {\n sandboxGroupId: error.sandboxGroupId,\n leaseEpoch: error.leaseEpoch,\n ...(rotationPending\n ? {\n rotationReason: fencedLease?.rotationReason ?? \"operator\",\n }\n : {}),\n ...(lifecycleTransition ? { transitionReason: error.reason } : {}),\n },\n }\n : {}),\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({\n status: \"recovering\",\n ...(transitionPending\n ? {\n continueDelayMs: sandboxDeadlineRotationRecoveryDelayMs(settings),\n }\n : {}),\n });\n } catch (recoveryError) {\n console.error(\"sandbox lifecycle recovery failed\", safeErrorDiagnostic(recoveryError));\n throw recoveryError;\n }\n }\n if (\n sandboxRotationController.signal.aborted &&\n sandboxRotationController.signal.reason instanceof SandboxDeadlineRotationError &&\n !cancellationSignal?.aborted &&\n recoveryTurnId\n ) {\n try {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n const rotation = sandboxRotationController.signal.reason;\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"sandbox_deadline_rotation\",\n detail: {\n sandboxGroupId: rotation.sandboxGroupId,\n leaseEpoch: rotation.leaseEpoch,\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({\n status: \"recovering\",\n continueDelayMs: sandboxDeadlineRotationRecoveryDelayMs(settings),\n });\n } catch (recoveryError) {\n console.error(\n \"sandbox deadline rotation recovery failed\",\n safeErrorDiagnostic(recoveryError),\n );\n throw recoveryError;\n }\n }\n const cancellationFailure = turnOperationCancellationFailure(error);\n if (\n cancellationFailure &&\n isWorkerShutdownCancellation(cancellationFailure) &&\n recoveryTurnId\n ) {\n try {\n await flushRuntimeBatcher();\n await reconcileConversationTruth();\n // An approval-decision rerun always replays its original trigger:\n // the decision is applied through the approval resume path reading\n // the frozen RunState blob (the only representation of a turn\n // paused mid-flight), so swapping the trigger for a resume notice\n // could drop the user's decision. Re-applying an already-consumed\n // approval re-enters at most the single approved step. Every\n // approval-gated MCP action crosses the durable execution admission\n // fence before its provider invocation, so a consumed step resumes\n // as already-executed or outcome-unknown rather than calling MCP again.\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId: recoveryTurnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"worker_shutdown\",\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n } catch (recoveryError) {\n // The database transition is atomic. If it could not commit, surface\n // the failure so Temporal can retry on a healthy worker; never mutate\n // the turn through a second cancellation path.\n console.error(\n \"worker-shutdown recovery checkpoint failed\",\n safeErrorDiagnostic(recoveryError),\n );\n throw recoveryError;\n }\n }\n if (error instanceof TurnAttemptFencedError) {\n activityStatus = \"cancelled\";\n activityError = error;\n acknowledgeQuiescence = true;\n noteCancellationRequested();\n await waitForTurnFinalizerStep(\n flushRuntimeBatcher(),\n turnFinalizerCancellationSignal(cancellationSignal, activityStatus),\n );\n // Ownership already moved to a newer attempt or an authoritative\n // control transaction. Surface the exact transport cancellation rather\n // than a normal result. Temporal terminalization remains diagnostic\n // only; replacement admission waits for the activity-owned durable\n // quiescence receipt written from the hard tool fence below.\n turnMetricOutcome = \"cancelled\";\n throw new CancelledFailure(\"TURN_ATTEMPT_FENCED\", [], error);\n }\n if (cancellationFailure) {\n activityStatus = \"cancelled\";\n activityError = error;\n acknowledgeQuiescence = true;\n noteCancellationRequested();\n await waitForTurnFinalizerStep(\n flushRuntimeBatcher(),\n turnFinalizerCancellationSignal(cancellationSignal, activityStatus),\n );\n // The workflow owns cancellation settlement: Pause/Steer controls use\n // settleSessionControl, and heartbeat timeouts use worker-death\n // recovery. A dying activity must never append a\n // competing cancellation or mutate the turn/session on its own.\n turnMetricOutcome = \"cancelled\";\n throw cancellationFailure;\n }\n // The SDK's per-segment turn cap is a pacing valve, not a failure: end\n // the turn gracefully and idle the session so an active goal continues\n // via a synthesized continuation turn (or a user message resumes work).\n // The run state captured at the cap keeps full conversation context for\n // that resumption.\n const maxTurns = maxTurnsExceededRunState(error);\n if (maxTurns && publish && turnId && turnStartedPublished) {\n await flushRuntimeBatcher();\n // The SDK attaches the run state at the throw site; persisting it lets\n // the continuation resume with this segment's full context. If capture\n // ever fails, the continuation falls back to the previous snapshot --\n // degraded context, flagged on the event, but still strictly better\n // than a terminal failed session: the sandbox filesystem state\n // persists independently and the agent re-derives from it.\n await reconcileConversationTruth();\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: { output: \"\", segmentLimit: \"max_turns\" },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: turnId,\n sessionId: input.sessionId,\n turnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${turnId}`,\n });\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n const settleLostCodexAttempt = async (\n lostTurnId: string,\n holderId: string,\n generation: number,\n historyCheckpointDurable = false,\n ): Promise<RunAgentTurnResult> => {\n let checkpointDurable = historyCheckpointDurable;\n try {\n if (!historyCheckpointDurable) {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n }\n checkpointDurable = true;\n } catch {\n observability.warn(\"Codex lease-loss checkpoint failed; refusing automatic turn replay\", {\n errorClass: \"CodexCheckpointOperationError\",\n errorCode: \"codex_lease_loss_checkpoint_failed\",\n origin: \"worker\",\n });\n }\n\n const settlement = await settleCodexCredentialLeaseLoss(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: lostTurnId,\n attemptId: input.attemptId,\n holderId,\n generation,\n expectedRedispatches: redispatchesAtDispatch,\n checkpointDurable,\n recoveryPayload: {\n triggerEventId: triggerEventId!,\n reason: \"codex_lease_lost\",\n credentialId: effectiveCodexCredentialId,\n },\n failedPayload: {\n error:\n \"The Codex credential lease was lost and the latest conversation checkpoint could not be persisted. Automatic replay was refused.\",\n code: \"codex_lease_checkpoint_failed\",\n retryable: false,\n },\n });\n codexLeaseHeld = false;\n observability.incrementCounter({\n name: \"opengeni_codex_lease_loss_settlements_total\",\n help: \"Fenced Codex lease-loss settlements by outcome.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: settlement.action,\n },\n });\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n settlement.events,\n );\n activityError = error;\n if (settlement.action === \"failed\") {\n activityStatus = \"failed\";\n turnMetricOutcome = \"failed\";\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n lostTurnId,\n );\n return claimedResult({ status: \"failed\" });\n }\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n };\n\n // A missing/expired/superseded lease is an execution-ownership failure,\n // not a provider failure. Settle it before credential quarantine or the\n // generic terminal path: the DB transaction marks a still-current turn\n // recoverable, but a successor attempt or worker recovery makes this activity\n // stale and unable to clobber the shared turn/session.\n if (\n codexLeaseLost &&\n settings.codexCredentialLeasingEnabled &&\n isCodexTurn &&\n publish &&\n turnId &&\n turnStartedPublished &&\n codexLeaseHolderId &&\n codexLeaseGeneration !== null\n ) {\n return await settleLostCodexAttempt(turnId, codexLeaseHolderId, codexLeaseGeneration);\n }\n if (xaiLeaseLost && isXaiTurn && publish && turnId && turnStartedPublished) {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"xai_lease_lost\",\n detail: { provider: \"supergrok-subscription\" },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n // Definitive Codex credential/account refusals are the only provider\n // errors that may walk the pool. This is an explicit checkpoint + SAME\n // turn recovery, never an SDK/Temporal blind retry. A network break,\n // malformed/partial 200 stream, invalid content, prompt 4xx, or provider\n // 5xx does not classify here and therefore cannot consume another\n // subscription or duplicate a side effect.\n const codexCredentialFailure =\n settings.codexCredentialLeasingEnabled && isCodexTurn && effectiveCodexCredentialId\n ? classifyCodexCredentialFailure(error)\n : null;\n if (\n codexCredentialFailure &&\n effectiveCodexCredentialId &&\n publish &&\n turnId &&\n turnStartedPublished\n ) {\n observability.incrementCounter({\n name: \"opengeni_codex_credential_failures_total\",\n help: \"Definitive Codex credential failures classified for safe failover.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n kind: codexCredentialFailure.kind,\n outcome: \"classified\",\n },\n });\n const failoverStartedAt = performance.now();\n let checkpointDurable = false;\n try {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n checkpointDurable = true;\n } catch {\n observability.incrementCounter({\n name: \"opengeni_codex_failover_checkpoints_total\",\n help: \"Durable Codex failover checkpoint attempts by outcome.\",\n labels: { workspace_key: codexWorkspaceKey, outcome: \"failed\" },\n });\n observability.warn(\"Codex failover checkpoint failed; refusing automatic replay\", {\n errorClass: \"CodexCheckpointOperationError\",\n errorCode: \"codex_failover_checkpoint_failed\",\n origin: \"worker\",\n });\n }\n\n if (checkpointDurable) {\n observability.incrementCounter({\n name: \"opengeni_codex_failover_checkpoints_total\",\n help: \"Durable Codex failover checkpoint attempts by outcome.\",\n labels: { workspace_key: codexWorkspaceKey, outcome: \"completed\" },\n });\n const now = new Date();\n const before = await listCodexAccountStatuses(db, input.workspaceId).catch(() => []);\n const servingCached = before.find((account) => account.id === effectiveCodexCredentialId);\n const usageSnapshot = latestCodexUsage as CodexUsageHeaderSnapshot | null;\n const serving = servingCached\n ? {\n ...servingCached,\n ...(usageSnapshot\n ? {\n primaryUsedPercent: usageSnapshot.primaryUsedPercent,\n primaryResetAt: usageSnapshot.primaryResetAt,\n secondaryUsedPercent: usageSnapshot.secondaryUsedPercent,\n secondaryResetAt: usageSnapshot.secondaryResetAt,\n }\n : {}),\n }\n : null;\n const cooldownUntil = codexCredentialCooldownUntil(codexCredentialFailure, serving, now);\n const statePersisted =\n codexLeaseHolderId && codexLeaseGeneration !== null\n ? await quarantineCodexCredentialForLease(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n turnId,\n credentialId: effectiveCodexCredentialId,\n holderId: codexLeaseHolderId,\n generation: codexLeaseGeneration,\n quarantine:\n codexCredentialFailure.kind === \"auth\"\n ? {\n kind: \"status\",\n status: \"needs_relogin\",\n lastError: \"model request remained unauthorized after refresh\",\n }\n : codexCredentialFailure.kind === \"forbidden\"\n ? {\n kind: \"status\",\n status: \"error\",\n lastError: \"model request was forbidden for this credential\",\n }\n : { kind: \"cooldown\", until: cooldownUntil! },\n })\n : false;\n if (!statePersisted && codexLeaseHolderId && codexLeaseGeneration !== null) {\n codexLeaseLost = true;\n return await settleLostCodexAttempt(\n turnId,\n codexLeaseHolderId,\n codexLeaseGeneration,\n true,\n );\n }\n const [rotation, accounts] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId).catch(() => null),\n listCodexAccountStatuses(db, input.workspaceId).catch(() => []),\n ]);\n const decision = rotation\n ? chooseRotationActive({\n rotationStrategy: rotation.rotationStrategy as CodexRotationStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: effectiveCodexCredentialId,\n accounts,\n now: new Date(),\n })\n : ({ kind: \"none\" } as const);\n const candidateAvailable =\n statePersisted &&\n Boolean(rotation?.rotationEnabled && rotation?.leaseRotationEnabled) &&\n decision.kind === \"active\" &&\n decision.credentialId !== effectiveCodexCredentialId;\n\n if (candidateAvailable && codexLeaseHolderId && codexLeaseGeneration !== null) {\n const settlement = await settleCodexCredentialFailover(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n holderId: codexLeaseHolderId,\n generation: codexLeaseGeneration,\n expectedRedispatches: redispatchesAtDispatch,\n maxFailovers: Math.max(1, accounts.length),\n recoveryPayload: {\n triggerEventId: triggerEventId!,\n reason: \"codex_credential_failover\",\n credentialId: effectiveCodexCredentialId,\n failureKind: codexCredentialFailure.kind,\n ...(cooldownUntil ? { cooldownUntil: cooldownUntil.toISOString() } : {}),\n },\n });\n observability.incrementCounter({\n name: \"opengeni_codex_failover_settlements_total\",\n help: \"Atomic Codex failover settlements by outcome.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n outcome: settlement.action,\n },\n });\n if (settlement.action === \"recovering\") {\n codexLeaseHeld = false;\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n settlement.events,\n );\n observability.observeHistogram({\n name: \"opengeni_codex_failover_recovery_seconds\",\n help: \"Time from credential refusal to durable same-turn recovery.\",\n labels: {\n workspace_key: codexWorkspaceKey,\n kind: codexCredentialFailure.kind,\n },\n value: Math.max(0, (performance.now() - failoverStartedAt) / 1000),\n });\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n if (settlement.action === \"stale\") {\n // One transaction proves both exact-holder recovery (including a\n // just-expired or reaped lease row) and successor/control-gate\n // rejection. Cross the hard tool fence so a control-gate loss can\n // write its quiescence receipt; a successor-only loss is a no-op.\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"recovering\" });\n }\n }\n }\n }\n const xaiCredentialFailure =\n isXaiTurn && effectiveXaiCredentialId ? classifyXaiCredentialFailure(error) : null;\n if (\n xaiCredentialFailure &&\n effectiveXaiCredentialId &&\n xaiAuthoritySnapshot &&\n xaiLeaseSubjectId &&\n xaiLeaseHolderId &&\n xaiLeaseGeneration !== null &&\n publish &&\n turnId &&\n turnStartedPublished\n ) {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(() => null);\n const activeGoal = goal?.status === \"active\" ? goal : null;\n const now = new Date();\n const cooldownUntil =\n xaiCredentialFailure.kind === \"rate_limit\"\n ? new Date(now.getTime() + Math.max(1, xaiCredentialFailure.cooldownMs ?? 60_000))\n : null;\n const failurePayload = {\n error:\n xaiCredentialFailure.kind === \"auth\"\n ? \"The serving SuperGrok account requires reconnection\"\n : xaiCredentialFailure.kind === \"forbidden\"\n ? \"The serving SuperGrok account is not authorized for this request\"\n : \"The serving SuperGrok account is temporarily rate limited\",\n code:\n xaiCredentialFailure.kind === \"auth\"\n ? \"xai_relogin_required\"\n : xaiCredentialFailure.kind === \"forbidden\"\n ? \"xai_account_forbidden\"\n : \"xai_account_rate_limited\",\n detail: \"the same accepted turn is waiting for another eligible account\",\n };\n const armed = await armXaiCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: xaiLeaseSubjectId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n authoritySnapshot: xaiAuthoritySnapshot,\n goalId: activeGoal?.id ?? null,\n goalVersion: activeGoal?.version ?? null,\n earliestResetAt: cooldownUntil,\n failurePayload,\n leaseFence: {\n holderId: xaiLeaseHolderId,\n generation: xaiLeaseGeneration,\n },\n credentialQuarantine:\n xaiCredentialFailure.kind === \"auth\"\n ? {\n kind: \"status\",\n status: \"needs_relogin\",\n lastError: \"model request remained unauthorized after refresh\",\n }\n : xaiCredentialFailure.kind === \"forbidden\"\n ? {\n kind: \"status\",\n status: \"error\",\n lastError: \"model request was forbidden for this credential\",\n }\n : { kind: \"cooldown\", until: cooldownUntil! },\n now,\n });\n if (armed.action === \"waiting\") {\n xaiLeaseHeld = false;\n xaiCredentialQuarantined = true;\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, armed.events);\n const evaluated = await reconcileXaiCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n now,\n });\n if (evaluated.events.length > 0) {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n evaluated.events,\n );\n }\n activityError = error;\n if (evaluated.action === \"resumed\") {\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({ status: \"recovering\" });\n }\n if (evaluated.action === \"waiting\") {\n activityStatus = \"waiting_capacity\";\n turnMetricOutcome = \"recovering\";\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n provider: \"xai\",\n waiterId: evaluated.waiter.id,\n generation: evaluated.waiter.generation,\n nextCheckAt: evaluated.waiter.nextCheckAt.toISOString(),\n wakeRevision: evaluated.waiter.wakeRevision,\n },\n });\n }\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: \"xai_credential_recheck\",\n detail: failurePayload,\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, recovery.events);\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n activityError = error;\n return claimedResult({ status: \"recovering\" });\n }\n // A ChatGPT/Codex usage cap (429 usage_limit_reached) is account state,\n // NOT an agent failure: surface the precise, actionable message (so the\n // user sees the reset window) but idle the session — never go terminal,\n // which would reject the user's next message after the cap lifts. The\n // payload is retryable:false so the generic provider-backpressure auto-retry\n // does not loop. For an active goal we hold the continuation for the reported\n // reset window (capped) so it resumes itself when access returns, instead of\n // hammering the capped backend.\n const usageLimit = isCodexTransportError(error) ? classifyCodexUsageLimitError(error) : null;\n if (usageLimit && publish && turnId && turnStartedPublished) {\n const goal = await getSessionGoal(db, input.workspaceId, input.sessionId).catch(() => null);\n const goalActive = Boolean(goal && goal.status === \"active\");\n await flushRuntimeBatcher();\n await reconcileConversationTruth();\n // --- P3 reactive rotation (gated; re-fetch fresh state on this already-failed,\n // already-idling path). Mark THIS account cooling until its reset, then CONSULT the\n // engine over fresh accounts to decide continueDelayMs: a fast 0-delay re-dispatch\n // when another account is available, or idle-until-earliest when all are capped. The\n // catch deliberately does NOT move the active pointer — the re-dispatched turn's\n // proactive seam (turn-start) is the single authoritative pointer-move + strip site.\n let rotated = false;\n let rotationResumeMs: number | null = null; // 0 ⇒ a candidate is available; re-dispatch now\n let rotationResumeIdleUntilReset = false; // circuit-breaker fall (Finding 1b) ⇒ MANDATORY hold\n let allCappedResetAt: Date | null = null; // set ⇒ every account capped; idle until this\n let capacityAuthoritativeResetAt: Date | null = null;\n if (effectiveCodexCredentialId) {\n const [rotation, sessionCodex] = await Promise.all([\n getCodexRotationSettings(db, input.workspaceId).catch(() => null),\n getSessionCodexState(db, input.workspaceId, input.sessionId).catch(() => null),\n ]);\n const reactiveStrategy = (rotation?.rotationStrategy ??\n \"most_remaining\") as CodexRotationStrategy;\n const reactiveDisposition = classifyCodexPin({\n pinnedCredentialId: sessionCodex?.pinnedCredentialId ?? null,\n pinSource: sessionCodex?.pinSource ?? null,\n strategy: reactiveStrategy,\n rotationEnabled: Boolean(rotation?.rotationEnabled),\n });\n const reactiveSharded = reactiveDisposition === \"sharded\";\n const rotating =\n Boolean(rotation?.rotationEnabled || rotation?.leaseRotationEnabled) &&\n reactiveDisposition !== \"manual\";\n if (rotating && rotation) {\n const accounts = await listCodexAccountStatuses(db, input.workspaceId).catch(() => []);\n const serving = accounts.find((a) => a.id === effectiveCodexCredentialId) ?? null;\n // Both provider allowance windows bind. Use the same canonical\n // quarantine calculation as the fenced failover path so a short\n // five-hour reset can never overwrite a later weekly reset.\n const until = codexCredentialCooldownUntil(\n { kind: \"quota\", cooldownSeconds: usageLimit.resetsInSeconds },\n serving,\n new Date(),\n )!;\n // Finding 1a: INSPECT the cooldown-write result. A swallowed best-effort\n // write whose failure went unnoticed is exactly what lets the next proactive\n // rank re-pick this just-capped account (stale-low cached usedPercent, not\n // cooling) — so capture whether it PERSISTED and feed it into the resume floor.\n const cooldownMutation = await setCodexCredentialExhaustedWithWakeTargets(\n db,\n input.workspaceId,\n effectiveCodexCredentialId,\n until,\n ).catch(() => null);\n const cooldownPersisted = cooldownMutation?.result ?? false;\n if (cooldownMutation) {\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n cooldownMutation.wakeTargets,\n );\n }\n // Re-rank over the fresh accounts; the in-memory list predates the cooldown\n // write, so stamp the just-cooled account so the engine excludes it now. The\n // serving account is thus walked AT MOST ONCE per turn (invariant 4: bounded).\n const fresh = accounts.map((a) =>\n a.id === effectiveCodexCredentialId ? { ...a, exhaustedUntil: until } : a,\n );\n if (reactiveSharded) {\n // AM-5: RE-SHARD over the healthy survivors (the just-capped serving account is\n // marked cooling in `fresh` → excluded) so sessions sharing a capped account\n // spread across the pool rather than re-concentrating on one first-eligible\n // failover. AM-3: DURABLY REWRITE the session's POLICY pin to the new home —\n // selectCodexCredentialForTurn returns a cooling pinned account with NO\n // exhaustion check, so a pointer-only move would leave the re-dispatched turn on\n // the capped pin. Like the classic path we do NOT touch the workspace active\n // pointer; the session pin is the sharded home.\n const newHome = shardCredentialForSession({\n sessionId: input.sessionId,\n accounts: fresh,\n now: new Date(),\n });\n if (newHome) {\n rotated = true;\n const pinMutation = await withSessionCodexCapacityMutation(\n db,\n {\n workspaceId: input.workspaceId,\n reason: \"codex_policy_pin_resharded\",\n },\n async (tx) => {\n const changed = await setSessionCodexPinInTransaction(\n tx,\n input.workspaceId,\n input.sessionId,\n newHome,\n \"policy\",\n {\n expected: {\n pinnedCredentialId: sessionCodex?.pinnedCredentialId ?? null,\n pinSource: sessionCodex?.pinSource ?? null,\n },\n },\n );\n return { result: changed, changed };\n },\n ).catch(() => null);\n if (pinMutation) {\n await signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n pinMutation.wakeTargets,\n );\n }\n const priorConsecutiveRotations = await countConsecutiveReactiveRotations(\n db,\n input.workspaceId,\n input.sessionId,\n ).catch(() => 0);\n const resume = computeReactiveRotationResume({\n cooldownPersisted,\n priorConsecutiveRotations,\n connectedAccountCount: accounts.length,\n });\n rotationResumeMs = resume.continueDelayMs;\n rotationResumeIdleUntilReset = resume.idleUntilReset;\n } else {\n // Every account capped/cooling → idle until the earliest reset across all.\n rotated = true;\n allCappedResetAt = earliestCodexReset(fresh, new Date());\n capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, new Date());\n }\n } else {\n const decision = chooseRotationActive({\n rotationStrategy: reactiveStrategy,\n activeCredentialId: rotation.activeCredentialId,\n priorCredentialId: effectiveCodexCredentialId,\n accounts: fresh,\n now: new Date(),\n });\n if (decision.kind === \"active\") {\n rotated = true;\n // Finding 1: a live candidate normally re-dispatches NOW (0). Two second-order\n // faults would turn that 0 into a hot loop, so bound it. Count the consecutive\n // reactive failovers since the last successful turn (this one is not yet\n // published) and combine with the cooldown-persistence result.\n const priorConsecutiveRotations = await countConsecutiveReactiveRotations(\n db,\n input.workspaceId,\n input.sessionId,\n ).catch(() => 0);\n const resume = computeReactiveRotationResume({\n cooldownPersisted,\n priorConsecutiveRotations,\n connectedAccountCount: accounts.length,\n });\n rotationResumeMs = resume.continueDelayMs; // 0 (happy path), a slow-retry floor, or the circuit-breaker idle\n rotationResumeIdleUntilReset = resume.idleUntilReset; // true only on the circuit-breaker fall (MANDATORY hold)\n } else if (decision.kind === \"allCapped\") {\n rotated = true;\n allCappedResetAt = decision.earliestResetAt;\n capacityAuthoritativeResetAt = authoritativeCodexCapacityResetAt(fresh, new Date());\n }\n // kind:\"none\" → fall through to today's single-account idle.\n }\n }\n }\n\n const failurePayload = allCappedResetAt\n ? codexUsageLimitFailurePayload(\n {\n resetsInSeconds: Math.ceil(\n Math.max(0, allCappedResetAt.getTime() - Date.now()) / 1000,\n ),\n },\n error instanceof Error ? error.message : String(error),\n { allAccounts: true },\n )\n : codexUsageLimitFailurePayload(\n usageLimit,\n error instanceof Error ? error.message : String(error),\n );\n // A live alternate is still handled by the existing immediate,\n // same-policy continuation path. When no alternate exists (all capped,\n // or a single non-rotating account), persist the native capacity wait\n // instead of an in-memory delay/user-message recovery.\n if (rotationResumeMs === null) {\n const providerResetAt =\n capacityAuthoritativeResetAt ??\n (usageLimit.resetsInSeconds !== null &&\n Number.isFinite(usageLimit.resetsInSeconds) &&\n usageLimit.resetsInSeconds > 0\n ? new Date(Date.now() + Math.ceil(usageLimit.resetsInSeconds) * 1000)\n : null);\n const armed = await armCodexCapacityWait(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n goalId: goalActive && goal ? goal.id : null,\n goalVersion: goalActive && goal ? goal.version : null,\n earliestResetAt: providerResetAt,\n resetKind: providerResetAt ? \"authoritative\" : \"bounded_refresh\",\n failurePayload,\n ...(codexLeaseHolderId && codexLeaseGeneration !== null\n ? {\n leaseFence: {\n holderId: codexLeaseHolderId,\n generation: codexLeaseGeneration,\n },\n expectedRedispatches: redispatchesAtDispatch,\n }\n : {}),\n });\n if (armed.action === \"waiting\") {\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n armed.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"waiting_capacity\";\n activityError = error;\n return claimedResult({\n status: \"waiting_capacity\",\n capacityWait: {\n waiterId: armed.waiter.id,\n generation: armed.waiter.generation,\n nextCheckAt: armed.waiter.nextCheckAt.toISOString(),\n wakeRevision: armed.waiter.wakeRevision,\n },\n });\n }\n }\n if (\n !(await settle!({\n events: [\n // `rotated:true` ONLY on the reactive rotation path tells evaluateGoalContinuation to\n // freeze autoContinuations (a rotation walk must not burn the goal's continuation budget).\n {\n type: \"turn.failed\",\n payload: {\n ...failurePayload,\n recovery: goalActive ? \"goal_continuation\" : \"user_message\",\n ...(rotated ? { rotated: true } : {}),\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n activityStatus = \"idle\";\n activityError = error;\n if (goalActive) {\n // Rotation: a candidate is available → continue NOW (0). All-capped → idle until the\n // earliest reset across all accounts (capped at 1h). Else the unchanged single-account idle.\n if (rotationResumeMs !== null) {\n // A candidate IS available. Normally the just-failed account is now cooling so\n // the ranker cannot re-pick it → 0 (re-dispatch NOW, the legitimate skip-the-hold\n // case). Finding 1 bounds the two exceptions: a persistence fault yields a positive\n // slow-retry floor, and once consecutive failovers exceed the account count + margin\n // the circuit breaker returns a fixed MANDATORY idle (idleUntilReset) — never a 0-delay\n // hot loop against a capped backend + DB.\n return claimedResult({\n status: \"idle\",\n continueDelayMs: rotationResumeMs,\n ...(rotationResumeIdleUntilReset ? { idleUntilReset: true } : {}),\n });\n }\n // All-capped: clamp to [MIN_IDLE_MS, max] — a POSITIVE, BOUNDED hold (never 0,\n // so session.ts can never tight-loop). The post-idle continuation re-dispatch\n // hits the proactive seam, which refreshes usage and self-heals.\n const resumeMs = allCappedResetAt\n ? computeIdleDelayMs(allCappedResetAt, new Date(), CODEX_USAGE_LIMIT_MAX_RESUME_MS)\n : usageLimit.resetsInSeconds !== null &&\n Number.isFinite(usageLimit.resetsInSeconds) &&\n usageLimit.resetsInSeconds > 0\n ? Math.min(\n Math.ceil(usageLimit.resetsInSeconds) * 1000,\n CODEX_USAGE_LIMIT_MAX_RESUME_MS,\n )\n : CODEX_USAGE_LIMIT_MAX_RESUME_MS;\n return claimedResult({\n status: \"idle\",\n continueDelayMs: resumeMs,\n ...(allCappedResetAt ? { idleUntilReset: true } : {}),\n });\n }\n return claimedResult({ status: \"idle\" });\n }\n // Budget/limit exhaustion between model calls is account state, not an\n // agent failure: idle the session for goal-bearing and goal-less runs\n // alike (a failed session would reject the user's next message after a\n // top-up). An active goal pauses visibly with reason \"limits\" at the\n // next continuation evaluation, without consuming continuation budget.\n if (error instanceof BudgetExhaustedError && publish && turnId && turnStartedPublished) {\n await flushRuntimeBatcher();\n await reconcileConversationTruth();\n if (\n !(await settle!({\n events: [\n {\n type: \"turn.completed\",\n payload: {\n output: \"\",\n segmentLimit: \"budget_exhausted\",\n detail: error.message,\n },\n },\n { type: \"session.status.changed\", payload: { status: \"idle\" } },\n ],\n turnStatus: \"completed\",\n sessionStatus: \"idle\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"completed\";\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"agent_run.completed\",\n quantity: 1,\n unit: \"run\",\n sourceResourceType: \"session_turn\",\n sourceResourceId: turnId,\n sessionId: input.sessionId,\n turnId,\n turnAttemptId: input.attemptId,\n idempotencyKey: `usage:agent_run.completed:${turnId}`,\n });\n activityStatus = \"idle\";\n return claimedResult({ status: \"idle\" });\n }\n // The Codex backend can reject an opaque reasoning artifact that it\n // minted on the immediately preceding successful request, even when the\n // credential-row UUID is unchanged. HTTP 400 + the exact provider\n // semantic proves this request never entered inference. Atomically mark\n // the active opaque artifacts rejected and recover the SAME logical turn\n // from durable history; messages, tool calls/results, readable reasoning,\n // and the original audit rows remain intact. Opaque remote compaction has\n // no portable plaintext representation. If no artifact can be invalidated,\n // fall through to the terminal path rather than resend an equivalent\n // request forever.\n const encryptedArtifactRejection =\n isCodexTurn && effectiveCodexCredentialId\n ? classifyCodexEncryptedArtifactRejection(error)\n : null;\n if (\n encryptedArtifactRejection &&\n effectiveCodexCredentialId &&\n publish &&\n turnId &&\n turnStartedPublished\n ) {\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n const activeHistory = await getActiveSessionHistoryItemsPaged(\n db,\n input.workspaceId,\n input.sessionId,\n );\n const rejectedHistoryItemIds = selectRejectedProviderArtifactHistoryIds(\n activeHistory,\n providerArtifactCandidates,\n lastCodexRequestOpaqueArtifacts,\n );\n const rejectedRunStateId =\n providerArtifactCandidates.runStateId && lastCodexRequestOpaqueArtifacts.length > 0\n ? providerArtifactCandidates.runStateId\n : undefined;\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: encryptedArtifactRejection.kind,\n detail: {\n code: encryptedArtifactRejection.kind,\n retryable: true,\n },\n providerArtifactInvalidation: {\n historyItemIds: rejectedHistoryItemIds,\n ...(rejectedRunStateId ? { runStateId: rejectedRunStateId } : {}),\n reason: encryptedArtifactRejection.kind,\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n if (recovery.action === \"recovering\") {\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"recovering\";\n activityError = error;\n return claimedResult({ status: \"recovering\" });\n }\n }\n // A retryable provider/MCP failure is transient external backpressure,\n // not a session or goal failure. The in-client retry budget is already\n // exhausted by the time the error reaches here. Checkpoint conversation\n // truth, recover this SAME accepted turn, then let the workflow re-claim\n // it after a pacing delay. This is independent of goal state and never\n // relies on a synthetic continuation prompt.\n const failure = agentRunFailurePayload(error, {\n isCodexTurn,\n }) as ReturnType<typeof agentRunFailurePayload>;\n if (isSessionEventPersistenceError(error)) {\n // Preserve the exact source message in the internal runtime diagnostic;\n // SQLSTATE/catalog facts remain separate classification attributes.\n observability.error(\"session event persistence failed\", {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n code: error.details.code,\n sqlState: error.details.sqlState ?? \"unknown\",\n stage: error.details.stage,\n eventTypes: error.details.eventTypes.join(\",\"),\n correlationId: error.details.correlationId,\n attempts: error.details.attempts,\n retryOutcome: error.details.retryOutcome,\n dbSeverity: error.details.database.severity,\n dbSchema: error.details.database.schema,\n dbTable: error.details.database.table,\n dbColumn: error.details.database.column,\n dbDataType: error.details.database.dataType,\n dbConstraint: error.details.database.constraint,\n dbRoutine: error.details.database.routine,\n error: error.message,\n });\n }\n if (failure.retryable && publish && turnId && turnStartedPublished) {\n try {\n const nextProviderRecoveryCount = providerRecoveryCount + 1;\n const recoveryResult = providerRecoveryResult({\n failureCode: failure.code,\n attemptNumber: nextProviderRecoveryCount,\n retryAfterMs: providerRetryAfterMs(error),\n });\n await flushRuntimeBatcher();\n await reconcileConversationTruth({ requireDurable: true });\n const recovery = await requestSessionTurnRecovery(db, input.workspaceId, {\n sessionId: input.sessionId,\n turnId,\n triggerEventId: triggerEventId!,\n attemptId: input.attemptId,\n reason: failure.code ?? \"provider_unavailable\",\n providerRecoveryCount: nextProviderRecoveryCount,\n detail: {\n ...failure,\n continueDelayMs: recoveryResult.continueDelayMs,\n providerRecoveryCount: nextProviderRecoveryCount,\n },\n });\n if (recovery.action === \"stale\") {\n acknowledgeLostAttemptOwnership();\n activityStatus = \"cancelled\";\n turnMetricOutcome = \"cancelled\";\n return claimedResult({ status: \"cancelled\" });\n }\n acknowledgeRecoveryQuiescence();\n await publishDurableSessionEvents(\n bus,\n input.workspaceId,\n input.sessionId,\n recovery.events,\n );\n turnMetricOutcome = \"recovering\";\n activityStatus = \"recovering\";\n activityError = error;\n return claimedResult(recoveryResult);\n } catch (recoveryError) {\n const escaped = escapedMcpTimeoutRecoveryFailure({\n failureCode: failure.code,\n modelRequestStarted,\n detail: {\n turnId,\n triggerEventId: triggerEventId!,\n executionGeneration,\n },\n });\n if (escaped) {\n activityStatus = \"recovering\";\n turnMetricOutcome = \"recovering\";\n activityError = error;\n throw escaped;\n }\n throw recoveryError;\n }\n }\n activityStatus = \"failed\";\n activityError = error;\n if (!turnId) {\n throw preClaimAdmissionFailure(error);\n }\n if (!publish || !turnStartedPublished) {\n throw error;\n }\n // A partial/malformed stream may have emitted assistant/tool items (and\n // external side effects) before its terminal error. Persist every item the\n // SDK state observed before marking the turn failed so a later user revive\n // never replays work from an incomplete history. This does not retry or\n // rotate the ambiguous request.\n await flushRuntimeBatcher();\n await reconcileConversationTruth();\n if (\n !(await settle!({\n events: [\n { type: \"turn.failed\", payload: failure },\n { type: \"session.status.changed\", payload: { status: \"failed\" } },\n ],\n turnStatus: \"failed\",\n sessionStatus: \"failed\",\n activeTurnId: null,\n }))\n ) {\n return claimedResult({ status: \"cancelled\" });\n }\n turnMetricOutcome = \"failed\";\n // The common failure path ends here: runAgentTurn marks the session\n // failed and returns \"failed\", and the session workflow then exits\n // WITHOUT calling failSession/markSessionIdle. Wake a spawned worker's\n // parent here too, so a manager learns of a worker that died inside its\n // turn (not just one failed by the workflow's failSession path). Turn\n // settlement already owns the durable outbox payload; this call only\n // delivers that exact turn-scoped row.\n await deliverFailedChildTurnToParent(\n { db, bus, settings, observability, wakeSessionWorkflow },\n input.workspaceId,\n input.sessionId,\n turnId,\n );\n return claimedResult({ status: \"failed\" });\n } finally {\n // This is the logical ownership boundary. Abort before any fallible\n // housekeeping so a still-pending provider establish releases its private\n // holder/timer even when Temporal itself never delivered cancellation.\n if (resolvedSandbox === null && !sandboxResumeController.signal.aborted) {\n sandboxResumeController.abort(\n cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n );\n }\n const finalizationStarted = performance.now();\n let finalizationError: unknown;\n let physicalToolQuiescenceConfirmed = !acknowledgeQuiescence;\n let quiescenceReceiptOrProofDurable = !acknowledgeQuiescence;\n const finalizerSignal = turnFinalizerCancellationSignal(cancellationSignal, activityStatus);\n try {\n const toolCancellationFence = toolCancellationFenceRef.current;\n // Every renewal controller is an attempt-owned sandbox writer. Capture\n // and close all of them before the tool/run-writer drain and before the\n // quiescence receipt; none may start another admitted write afterward.\n gitCredentialRenewalClosed = true;\n const gitRenewalsToStop = gitCredentialRenewals;\n gitCredentialRenewals = [];\n codemodeTokenRenewalClosed = true;\n const codemodeRenewalToStop = codemodeTokenRenewal as CodemodeTokenRenewalController | null;\n codemodeTokenRenewal = null;\n runCredentialRenewalClosed = true;\n const runRenewalToStop = runCredentialRenewal as RunCredentialRenewalController | null;\n runCredentialRenewal = null;\n\n // Attempt-qualified credential deletion is also a real workspace write.\n // Perform it under the same admission fence before publishing physical\n // quiescence; a failure deliberately keeps the receipt closed.\n const credentialSessionToClear = runCredentialSession;\n runCredentialSession = null;\n if (credentialSessionToClear) {\n const clearAttemptCredentials = async (): Promise<void> =>\n await clearRunCredentialsForAttempt(credentialSessionToClear, {\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n executionGeneration,\n });\n await clearAttemptCredentialsWithSettledFence({\n activityStatus,\n runWorkspaceFencedClear: async () =>\n await runWorkspaceMutationForSandbox(\n requireResolvedSandboxForMutation(\n \"Run credential cleanup has no exact sandbox lease target\",\n ),\n \"runCredentialAttemptClear\",\n clearAttemptCredentials,\n ),\n clearExactAttempt: clearAttemptCredentials,\n onSettledAttemptFence: () => {\n // Terminal settlement closes the active attempt before this finally\n // runs, so the ordinary workspace admission correctly rejects it.\n // The attempt-qualified delete is nevertheless successor-safe: it\n // removes only this attempt/generation and clears the pointer only\n // when it still names that exact generation. Finish that cleanup\n // directly so a successful turn can continue into workspace capture,\n // tool teardown, and lease release.\n observability.info(\"retrying exact run credential cleanup after turn settlement\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": turnId ?? \"\",\n \"opengeni.attempt_id\": input.attemptId,\n });\n },\n });\n }\n await drainAttemptOwnedSandboxWriters({\n // Normal turn completion owns the same process boundary as\n // Pause/Steer: yielded provider shells must be terminated, polled,\n // and durably settled before workspace capture. Only receipt\n // publication remains conditional on acknowledgeQuiescence.\n toolCancellationFence,\n cancellationReason: cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n gitCredentialRenewals: gitRenewalsToStop,\n codemodeTokenRenewal: codemodeRenewalToStop,\n runCredentialRenewal: runRenewalToStop,\n });\n attemptWritersDrained = true;\n if (acknowledgeQuiescence) {\n // A cancellation before sandbox-backed capabilities exist still has\n // no tool controller to drain. Sandbox agent construction fails closed\n // when a backend exists but no controller was installed. Renewal\n // writers, when present, were drained above in either case.\n physicalToolQuiescenceConfirmed = true;\n }\n if (acknowledgeQuiescence && physicalToolQuiescenceConfirmed) {\n // This receipt is part of the hard cancellation boundary, not\n // housekeeping. Persist it immediately after the sandbox/tool fence\n // and before lease, cache, recording, or provider cleanup. Its\n // transaction also enqueues the exact workflow wake that will admit\n // the replacement; Temporal activity terminalization does neither.\n const proof: SessionAttemptQuiescenceProof = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n workflowId: input.workflowId,\n workflowRunId: input.workflowRunId,\n activityId: dispatchId,\n };\n const recoveryMode = await persistOrSignalSessionAttemptQuiescence({\n proof,\n persistReceipt: async () =>\n await commitSessionAttemptQuiescence(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n temporalWorkflowId: input.workflowId,\n temporalWorkflowRunId: input.workflowRunId,\n temporalActivityId: dispatchId,\n allowUninterrupted: true,\n }),\n ...(wakeSessionWorkflow\n ? {\n deliverWorkflowWake: async (\n wake: NonNullable<SessionAttemptQuiescenceCommit[\"workflowWake\"]>,\n ) =>\n await wakeSessionWorkflow({\n accountId: wake.accountId,\n workspaceId: wake.workspaceId,\n sessionId: wake.sessionId,\n workflowId: wake.temporalWorkflowId,\n wakeRevision: wake.wakeRevision,\n interruptionRequested: wake.interruptionRequested,\n }),\n }\n : {}),\n publishEvents: async (events) => {\n await waitForTurnFinalizerStep(\n publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events),\n finalizerSignal,\n );\n },\n signalProof: signalSessionAttemptQuiesced,\n heartbeat: (attempt, retryMs) => {\n activityContext?.heartbeat({\n phase: \"quiescence-proof-delivery\",\n sessionId: input.sessionId,\n attemptId: input.attemptId,\n deliveryAttempt: attempt,\n retryMs,\n at: new Date().toISOString(),\n });\n },\n onReceiptFailure: (error) => {\n console.error(\n \"agent turn quiescence receipt exhausted; signalling proof\",\n safeErrorDiagnostic(error),\n );\n },\n onWakeFailure: (error) => {\n console.error(\n \"agent turn quiescence immediate workflow wake failed; outbox repair retained\",\n safeErrorDiagnostic(error),\n );\n },\n onPublishFailure: (error) => {\n console.error(\n \"agent turn quiescence event fanout failed\",\n safeErrorDiagnostic(error),\n );\n },\n onSignalFailure: (error, attempt, retryMs) => {\n console.error(\"agent turn quiescence proof signal failed; retrying\", {\n error: safeErrorDiagnostic(error),\n attempt,\n retryMs,\n });\n },\n });\n quiescenceReceiptOrProofDurable = true;\n if (recoveryMode === \"signal\") {\n observability.info(\"agent turn quiescence proof handed to workflow recovery\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.attempt_id\": input.attemptId,\n \"opengeni.workflow_run_id\": input.workflowRunId,\n \"opengeni.activity_id\": dispatchId,\n });\n }\n }\n // Drain the buffered Connected Machine op events (infra failures + healed\n // recoveries) to durable session events — awaited, best-effort, never blocking\n // the turn. Sync observer → buffer → single awaited append here (no unawaited\n // DB write inside the activity). Scoped to this turn; skipped if no turnId\n // (the op ran under a turn, so on the normal path turnId is set).\n const machineOpEvents = machineOpObserver.drainEvents();\n if (machineOpEvents.length > 0 && turnId && executionGeneration > 0) {\n await waitForTurnFinalizerStep(\n appendAndPublishTurnEventsFenced(\n db,\n bus,\n input.workspaceId,\n input.sessionId,\n turnId,\n executionGeneration,\n input.attemptId,\n machineOpEvents.map((event) => ({\n ...event,\n turnId: turnId ?? null,\n })),\n ).catch(() => undefined),\n finalizerSignal,\n );\n }\n // Multi-account P4: flush the serving account's free per-turn caches ONCE,\n // best-effort (same discipline as today's usage write). Both writers skip\n // version/updatedAt, so neither can race the token-refresh CAS.\n if (effectiveCodexCredentialId) {\n // Part A: the latest scraped usage-header snapshot → the P2 usage cache. A\n // full both-windows snapshot (parseCodexUsageHeaders gates on both), so this\n // is byte-identical to the /wham/usage write — no partial-window clobber.\n if (latestCodexUsage) {\n const usageMutation = await waitForTurnFinalizerStep(\n recordCodexAccountUsageWithWakeTargets(\n db,\n input.workspaceId,\n effectiveCodexCredentialId,\n latestCodexUsage,\n ).catch(() => null),\n finalizerSignal,\n );\n if (usageMutation) {\n await waitForTurnFinalizerStep(\n signalCodexCapacityWakeTargets(\n { signalCodexCapacityWorkflow, wakeSessionWorkflow },\n usageMutation.wakeTargets,\n ),\n finalizerSignal,\n );\n }\n }\n }\n if (codexLeaseHeartbeatTimer) {\n clearInterval(codexLeaseHeartbeatTimer);\n codexLeaseHeartbeatTimer = undefined;\n }\n if (codexLeaseHeld && turnId && codexLeaseHolderId && codexLeaseGeneration !== null) {\n await waitForTurnFinalizerStep(\n releaseCodexCredentialLease(\n db,\n input.accountId,\n input.workspaceId,\n turnId,\n codexLeaseHolderId,\n codexLeaseGeneration,\n ).catch(() => undefined),\n finalizerSignal,\n );\n codexLeaseHeld = false;\n }\n if (\n effectiveXaiCredentialId &&\n xaiLeaseSubjectId &&\n xaiRequestContext &&\n !xaiCredentialQuarantined\n ) {\n const quota = await waitForTurnFinalizerStep(\n fetchXaiSubscriptionQuota({ context: xaiRequestContext }).catch(() => null),\n finalizerSignal,\n );\n if (quota) {\n await waitForTurnFinalizerStep(\n updateXaiQuotaMetadata(db, {\n workspaceId: input.workspaceId,\n subjectId: xaiLeaseSubjectId,\n credentialId: effectiveXaiCredentialId,\n quotaUsedPercent: quota.usedPercent,\n quotaResetAt: quota.period?.end ?? null,\n quotaCheckedAt: quota.checkedAt,\n exhaustedUntil:\n quota.usedPercent !== null && quota.usedPercent >= 100\n ? (quota.period?.end ?? null)\n : null,\n }).catch(() => undefined),\n finalizerSignal,\n );\n }\n }\n if (xaiLeaseHeartbeatTimer) {\n clearInterval(xaiLeaseHeartbeatTimer);\n xaiLeaseHeartbeatTimer = undefined;\n }\n if (\n xaiLeaseHeld &&\n turnId &&\n xaiLeaseSubjectId &&\n xaiLeaseHolderId &&\n xaiLeaseGeneration !== null\n ) {\n await waitForTurnFinalizerStep(\n releaseXaiCredentialLease(db, {\n workspaceId: input.workspaceId,\n subjectId: xaiLeaseSubjectId,\n turnId,\n holderId: xaiLeaseHolderId,\n generation: xaiLeaseGeneration,\n }).catch(() => undefined),\n finalizerSignal,\n );\n xaiLeaseHeld = false;\n }\n // Workbench v2 turn-end workspace capture — runs FIRST in\n // the turn-end finally, while the box is MAXIMALLY ALIVE. The agent's last\n // tool ran before this finally, so /workspace is already final; capture is\n // FS-equivalent to the already-settled recording preparation and the warm\n // snapshot (neither mutates workspace files). Running it here — BEFORE\n // preparedTools.close() (which tears down tools / computer-use / the display\n // stack and is what starts the Modal box exiting a few seconds later) —\n // gives capture the full live-box margin instead of racing the teardown\n // tail, which was dropping 100% of captures on real Modal desktop boxes\n // (\"request cancelled due to container exiting\", 0 rows). External module:\n // self-capped at 120s, best-effort (never throws past its boundary),\n // epoch-fenced, and it NEVER closes the box. The emitted\n // workspace.revision.captured event is ANNOUNCE-ONLY (metadata, never\n // content).\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture preflight ownership=${settings.sandboxOwnershipEnabled} enabled=${settings.workspaceCaptureEnabled} resolved=${Boolean(resolvedSandbox)} session=${Boolean(setupBoxSession)} group=${Boolean(sandboxGroupId)} storage=${Boolean(objectStorage)}`,\n );\n }\n const runTurnEndPersistence = shouldRunTurnEndWorkspacePersistence({\n activityStatus,\n cancellationRequested: finalizerSignal?.aborted === true,\n });\n if (\n runTurnEndPersistence &&\n turnId &&\n resolvedSandbox &&\n setupBoxSession &&\n sandboxGroupId\n ) {\n // Block new periodic snapshots, then drain any one already in flight.\n // Keep the lease heartbeat itself running: capture may legitimately\n // exceed the 90s holder TTL, and the reaper must remain unable to drain\n // the exact box while this holder still reads it.\n turnEndCaptureInProgress = true;\n if (snapshotInFlight) {\n await waitForWarmSnapshot(\n snapshotInFlight,\n settings.sandboxSnapshotTimeoutMs,\n finalizerSignal,\n );\n }\n const captureEstablished = resolvedSandbox.established;\n await captureWorkspaceRevision({\n db,\n objectStorage,\n settings,\n publish: async (events) => {\n await publishDurableSessionEvents(bus, input.workspaceId, input.sessionId, events);\n },\n session: setupBoxSession as ChannelASession,\n openReadSession: async () =>\n await openFreshWorkspaceCaptureSession({\n backendId: captureEstablished.backendId,\n client: captureEstablished.client,\n session: setupBoxSession as ChannelASession,\n expectedInstanceId: captureEstablished.instanceId,\n }),\n leaseEpoch: resolvedSandbox.leaseEpoch,\n sandboxGroupId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId,\n attemptId: input.attemptId,\n observability,\n ...(finalizerSignal ? { signal: finalizerSignal } : {}),\n });\n }\n if (codemodeDispatcher) {\n await waitForTurnFinalizerStep(\n codemodeDispatcher.close().catch(() => undefined),\n finalizerSignal,\n );\n codemodeDispatcher = null;\n }\n if (preparedTools) {\n await waitForTurnFinalizerStep(\n preparedTools.close().catch(() => undefined),\n finalizerSignal,\n );\n }\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n }\n if (turnSandboxProvisioner?.hasStarted()) {\n await waitForTurnFinalizerStep(\n turnSandboxProvisioner.waitForSettled(30_000),\n finalizerSignal,\n );\n }\n // P1.2: stop the lease-TTL refresh, release the turn holder (idempotent\n // delete-my-row; refcount-- and warm->draining if it hit 0 with no turns),\n // and DROP the in-memory handle. Release NEVER stops the box — the reaper\n // (P1.3) issues the provider stop() past the drain grace at refcount 0; the\n // box rides the provider idle-timeout in the meantime. Best-effort: a\n // release failure must never mask the turn's real outcome.\n if (leaseHeartbeatTimer) {\n stopLeaseHeartbeat();\n }\n if (rotationInFlight) {\n await waitForTurnFinalizerStep(rotationInFlight, finalizerSignal).catch(() => undefined);\n }\n // A recording normally closes inside the attempt-fenced turn settlement.\n // Reaching finally with one still active means settlement threw, never ran,\n // or lost ownership. Stop ffmpeg and mark only this exact attempt-owned row\n // failed; publish no event and leave the artifact recoverable on the box.\n await waitForTurnFinalizerStep(\n abandonActiveRecording(\n \"activity ended without recording settlement\",\n didComputerUse ? \"failed\" : \"discard\",\n ),\n finalizerSignal,\n );\n if (resolvedSandbox) {\n // TURN-END mid-session snapshot (sandbox-file-persistence): fold the\n // turn's finished /workspace onto the lease before releasing the holder,\n // so the work this turn just produced survives any unclean box death in\n // the idle window ahead. Throttled by the same interval as the heartbeat\n // tick (a short turn right after a snapshot skips — bounded-loss contract\n // is the interval, not per-turn). Best-effort and time-capped by the\n // helper's own failure discipline; never delays release on failure.\n const settledTurnId = turnId;\n if (runTurnEndPersistence && setupBoxSession && sandboxGroupId && settledTurnId) {\n // Single-flight vs the heartbeat capture: the timer is already cleared\n // above, but a capture it launched may still be in flight — and that\n // capture predates the turn's final writes. Wait for it, but only up\n // to the snapshot timeout: release must never depend on an unbounded\n // provider capture.\n if (snapshotInFlight) {\n await waitForWarmSnapshot(\n snapshotInFlight,\n settings.sandboxSnapshotTimeoutMs,\n finalizerSignal,\n );\n }\n const persisted = await maybePersistWarmWorkspaceSnapshot(\n { db, settings },\n {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: settledTurnId,\n attemptId: input.attemptId,\n sandboxGroupId,\n },\n setupBoxSession,\n resolvedSandbox.leaseEpoch,\n finalizerSignal,\n );\n if (persisted && publish) {\n await publish([\n {\n type: \"sandbox.box.snapshot\",\n payload: { trigger: \"turn-end\" },\n },\n ]).catch(() => undefined);\n }\n // NB workspace capture no longer runs here — it moved to\n // the TOP of this finally (before preparedTools.close) so it completes\n // while the box is still solidly alive, instead of racing the turn-end\n // teardown that was killing 100% of captures on real Modal desktop boxes.\n }\n }\n } catch (error) {\n finalizationError ??= error;\n console.error(\n \"agent turn finalization failed (turn outcome unaffected)\",\n safeErrorDiagnostic(error),\n );\n } finally {\n // The writer drain is the only authority that licenses settling an\n // abandoned turn admission. Keep this second-stage release outside all\n // later housekeeping so an event/cache/capture/recording failure cannot\n // strand a null-outcome admission forever. Do not race it against\n // Temporal cancellation: the eager listener may already have dropped\n // the holder, and this idempotent proof-bearing pass still must run.\n stopLeaseHeartbeat();\n const sandboxReleaseTargets = new Set(lateSandboxesAwaitingWriterDrain);\n lateSandboxesAwaitingWriterDrain.clear();\n if (resolvedSandbox) {\n sandboxReleaseTargets.add(resolvedSandbox);\n resolvedSandbox = null;\n }\n if (attemptWritersDrained) {\n for (const sandboxToRelease of sandboxReleaseTargets) {\n try {\n await releaseTurnSandboxAfterWriterDrain(sandboxToRelease);\n } catch (releaseError) {\n finalizationError ??= releaseError;\n console.error(\n \"sandbox lease quiesced release failed (turn outcome unaffected)\",\n safeErrorDiagnostic(releaseError),\n );\n }\n }\n } else {\n // No proof exists. Ensure every late result still receives the eager\n // leak-prevention release while preserving its admissions as a\n // fail-closed archive-capture fence.\n for (const sandboxToRelease of sandboxReleaseTargets) {\n await sandboxToRelease.release().catch(() => undefined);\n }\n }\n // Close provisioning after consuming the currently known targets. A\n // provider result that races in later is routed through releaseLateSandbox;\n // targets already released above synchronously removed their listener.\n if (!sandboxResumeController.signal.aborted) {\n sandboxResumeController.abort(\n cancellationSignal?.reason ?? new Error(\"TURN_ATTEMPT_FINALIZED\"),\n );\n }\n cancellationSignal?.removeEventListener(\"abort\", noteCancellationRequested);\n const completedAt = performance.now();\n const durationSeconds = (completedAt - activityStarted) / 1000;\n const finalizationDurationSeconds = (completedAt - finalizationStarted) / 1000;\n observability.observeHistogram({\n name: \"opengeni_turn_finalization_duration_seconds\",\n help: \"Agent turn finalization duration, including workspace housekeeping and lease release.\",\n labels: {\n cancellation_requested: String(cancellationRequestedAt !== null),\n },\n value: finalizationDurationSeconds,\n });\n if (cancellationRequestedAt !== null) {\n const physicalCancellationDurationSeconds =\n (completedAt - cancellationRequestedAt) / 1000;\n observability.observeHistogram({\n name: \"opengeni_turn_physical_cancellation_duration_seconds\",\n help: \"Time from Temporal cancellation delivery until the activity physically stops.\",\n value: physicalCancellationDurationSeconds,\n });\n observability.info(\"agent turn physical cancellation completed\", {\n durationMs: Math.round(physicalCancellationDurationSeconds * 1000),\n ...(sandboxGroupId\n ? {\n sandboxLeaseKey: sandboxLeaseTelemetryKey(input.workspaceId, sandboxGroupId),\n }\n : {}),\n });\n }\n observability.recordWorkerActivity({\n activity: \"runAgentTurn\",\n status: finalizationError ? \"cleanup_failed\" : activityStatus,\n durationSeconds,\n });\n if (turnId && activityStatus !== \"unknown\") {\n turnLifecycleMetricsFor(observability).finish(turnId, turnMetricOutcome, durationSeconds);\n }\n activitySpan.end({\n attributes: {\n \"opengeni.turn_id\": turnId ?? \"\",\n \"opengeni.status\": activityStatus,\n \"opengeni.variable_set_id\": variableSetId,\n \"opengeni.rig_id\": rigId,\n \"opengeni.rig_version_id\": rigVersionId,\n \"opengeni.codex_credential_id\": effectiveCodexCredentialId ?? \"\",\n \"opengeni.duration_ms\": Math.round(durationSeconds * 1000),\n \"opengeni.finalization_duration_ms\": Math.round(finalizationDurationSeconds * 1000),\n },\n error:\n finalizationError || activityError\n ? safeErrorForTelemetry(finalizationError ?? activityError)\n : undefined,\n });\n // This timer runs only after the activity promise and its full turn\n // stack unwind. Checkpoint collection alone cannot reclaim objects that\n // remain strongly reachable until this terminal boundary.\n turnCompletionMemoryCollector.schedule(observability);\n assertPhysicalToolQuiescenceForCancellation({\n acknowledgeQuiescence,\n physicalToolQuiescenceConfirmed,\n failure: finalizationError,\n });\n assertSessionAttemptQuiescenceRecoveryDurable({\n acknowledgeQuiescence,\n physicalToolQuiescenceConfirmed,\n receiptOrProofDurable: quiescenceReceiptOrProofDurable,\n failure: finalizationError,\n });\n }\n }\n };\n}\n\nasync function assertGitHubResourcesRemainAuthorized(\n db: Parameters<typeof areGitHubRepositoriesAllowedForWorkspace>[0],\n workspaceId: string,\n resources: import(\"@opengeni/contracts\").ResourceRef[],\n): Promise<void> {\n // Must check exactly what sandboxEnvironmentForRun would mint a token for,\n // so the selection is derived from the same extraction as the mint path.\n for (const selection of gitHubTokenMintSelections(resources)) {\n await assertGitHubTokenMintSelectionAuthorized(\n db,\n workspaceId,\n selection.installationId,\n selection.repositoryIds,\n );\n }\n}\n\nasync function assertGitHubTokenMintSelectionAuthorized(\n db: Parameters<typeof areGitHubRepositoriesAllowedForWorkspace>[0],\n workspaceId: string,\n installationId: number,\n repositoryIds: number[],\n): Promise<void> {\n if (\n !(await areGitHubRepositoriesAllowedForWorkspace(\n db,\n workspaceId,\n installationId,\n repositoryIds,\n ))\n ) {\n throw new Error(\n \"This workspace no longer authorizes one or more GitHub repositories attached to the session\",\n );\n }\n}\n\n/**\n * True when the error is transient upstream backpressure — a model-provider 5xx,\n * a \"server had a bad minute\" body, or a dropped/again-able network connection —\n * rather than a request the session got wrong. These are safe to recover as a new\n * fenced attempt of the SAME turn after PROVIDER_BACKPRESSURE_DELAY_MS. Durable\n * tool results are preserved and ambiguous in-flight effects are closed before\n * the new attempt, independent of whether the session has an active goal.\n *\n * This is the classification gap that hard-failed a fleet of prod sessions during a\n * provider degradation window: their errors (\"Our servers are currently overloaded\",\n * the generic 500 \"An error occurred while processing your request\", \"Connection\n * error\") carried no retryable marker and fell through to a terminal session.failed.\n *\n * HTTP status is authoritative when present — EVERY 5xx is a server-side failure that\n * is safe to retry, while 4xx (validation, auth, 404) is a request fault that must\n * still hard-fail. The code/message matches are the fallback for network faults and\n * SDK-rethrown bare Errors that carry no status. A ChatGPT/Codex usage cap (a 429\n * that will NOT clear on retry) is classified and returned BEFORE this in\n * agentRunFailurePayload, so it never reaches here.\n */\nconst STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE =\n \"unable to connect. is the computer able to access the url?\";\n\nfunction isExactStatuslessUpstreamConnectivityMessage(message: string): boolean {\n return message.trim().toLowerCase() === STATUSLESS_UPSTREAM_CONNECTIVITY_MESSAGE;\n}\n\nexport function isTransientProviderError(error: unknown): boolean {\n const status =\n typeof error === \"object\" && error !== null\n ? Number(\n (error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode,\n )\n : undefined;\n // A real HTTP status is AUTHORITATIVE: a 5xx is transient, and ANY other status\n // (4xx validation/auth/404, plus the 429 the earlier branches already handled) is\n // a request fault that must NOT auto-retry — even if its body happens to read like\n // \"connection error\" or \"overloaded\". The code/message heuristics below apply ONLY\n // when no status survived: a network fault or an SDK-rethrown bare Error.\n if (status !== undefined && Number.isFinite(status)) {\n return status >= 500 && status < 600;\n }\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n if (code && /^(?:ECONNRESET|ETIMEDOUT|EAI_AGAIN|ECONNREFUSED|EPIPE)$/i.test(code)) {\n return true;\n }\n const message = error instanceof Error ? error.message : String(error);\n if (isExactStatuslessUpstreamConnectivityMessage(message)) {\n return true;\n }\n return /overloaded|an error occurred while processing your request|connection error|service unavailable|bad gateway|gateway timeout/i.test(\n message,\n );\n}\n\nexport type XaiCredentialFailure = {\n kind: \"auth\" | \"forbidden\" | \"rate_limit\";\n cooldownMs: number | null;\n};\n\n/**\n * Only definitive SuperGrok account refusals may move the same logical turn to\n * another credential. The marked transport response proves inference was\n * rejected before a stream began; refresh relogin is equally definitive.\n */\nexport function classifyXaiCredentialFailure(error: unknown): XaiCredentialFailure | null {\n let relogin: unknown = error;\n for (let depth = 0; depth < 6 && relogin && typeof relogin === \"object\"; depth += 1) {\n if (relogin instanceof XaiSubscriptionReloginRequired) {\n return { kind: \"auth\", cooldownMs: null };\n }\n relogin = (relogin as Record<string, unknown>).cause;\n }\n if (!isXaiSubscriptionTransportError(error)) return null;\n let current: unknown = error;\n for (let depth = 0; depth < 6 && current && typeof current === \"object\"; depth += 1) {\n const value = current as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const status = Number(value.status ?? value.statusCode ?? body?.status ?? body?.statusCode);\n const code = String(value.code ?? body?.code ?? \"\").toLowerCase();\n if (status === 401 || code === \"unauthorized\" || code === \"invalid_token\") {\n return { kind: \"auth\", cooldownMs: null };\n }\n if (status === 403) {\n return { kind: \"forbidden\", cooldownMs: null };\n }\n if (status === 429 || code === \"rate_limit_exceeded\" || code === \"too_many_requests\") {\n return {\n kind: \"rate_limit\",\n cooldownMs: providerRetryAfterMs(error) ?? PROVIDER_BACKPRESSURE_DELAY_MS,\n };\n }\n current = value.cause;\n }\n return null;\n}\n\nexport function agentRunFailurePayload(\n error: unknown,\n options: { isCodexTurn?: boolean } = {},\n): {\n error: string;\n code?: string;\n retryable?: boolean;\n detail?: string;\n timeoutClass?: string;\n responseObserved?: boolean;\n requestId?: string;\n correlationId?: string;\n stage?: string;\n sqlState?: string | null;\n attempts?: number;\n retryOutcome?: string;\n database?: Record<string, string>;\n historyPersistenceStage?: MandatoryHistoryPersistenceStage;\n} {\n if (error instanceof MandatoryHistoryPersistenceError) {\n const underlying = isSessionEventPersistenceError(error.cause)\n ? agentRunFailurePayload(error.cause, options)\n : {\n error: error.cause instanceof Error ? error.cause.message : String(error.cause),\n };\n return {\n ...underlying,\n historyPersistenceStage: error.stage,\n };\n }\n const message = error instanceof Error ? error.message : String(error);\n const status =\n typeof error === \"object\" && error !== null\n ? Number(\n (error as { status?: unknown; statusCode?: unknown }).status ??\n (error as { statusCode?: unknown }).statusCode,\n )\n : undefined;\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? String((error as { code?: unknown }).code)\n : undefined;\n if (error instanceof ActiveSessionHistoryLimitExceededError) {\n return {\n error:\n \"The session's active conversation history exceeds the worker's safe materialization envelope. Clear the session context before retrying; an oversized history cannot be compacted safely in a serving worker.\",\n code: error.code,\n retryable: false,\n detail: error.message,\n };\n }\n if (error instanceof ApprovalRunStateLimitExceededError) {\n return {\n error:\n \"The saved approval state exceeds the worker's safe materialization envelope. Clear the pending approval context before retrying.\",\n code: error.code,\n retryable: false,\n detail: error.message,\n };\n }\n // An accepted Codex stream with no terminal response is malformed/partial,\n // not provider backpressure. Replaying the same accepted turn could repeat\n // model or tool effects, so this marked transport failure must outrank the\n // generic 5xx retry classifier (CodexStreamingTerminalError uses status 502).\n if (isCodexTransportError(error) && code === \"invalid_sse_terminal\") {\n return {\n error: \"The Codex response stream ended without a terminal response\",\n code: \"invalid_sse_terminal\",\n retryable: false,\n };\n }\n if (isSessionEventPersistenceError(error)) {\n const { details } = error;\n return {\n error: error.message,\n code: details.code,\n detail:\n details.retryOutcome === \"exhausted\"\n ? `The idempotent persistence transaction failed after ${details.attempts} attempts.`\n : \"The database rejected the idempotent persistence transaction.\",\n correlationId: details.correlationId,\n stage: details.stage,\n sqlState: details.sqlState,\n attempts: details.attempts,\n retryOutcome: details.retryOutcome,\n ...(Object.keys(details.database).length > 0 ? { database: details.database } : {}),\n };\n }\n // A ChatGPT/Codex usage cap is a HARD limit, not transient backpressure: it\n // must NOT be reported as a generic, retryable rate-limit (which would loop a\n // goal against a capped backend). Surface a precise, actionable message with\n // the humanized reset window and code, non-retryable. Checked BEFORE the\n // generic 429 branch below (a usage cap is also a 429).\n // This terminal payload classifier may receive a plain SDK-shaped error in\n // tests or after wrapper metadata was stripped. An explicit\n // `usage_limit_reached` shape must still outrank generic 429 retryability.\n // Credential quarantine/failover remains separately provenance-gated by\n // `isCodexTransportError`; this branch only chooses the truthful user payload.\n const usageLimit = classifyCodexUsageLimitError(error);\n if (usageLimit) {\n return codexUsageLimitFailurePayload(usageLimit, message);\n }\n const codexTimeout = classifyCodexResponseTimeoutError(error, {\n allowLegacyRequestTimeout: options.isCodexTurn === true,\n });\n if (codexTimeout) {\n return {\n error: codexTimeout.responseObserved\n ? \"The Codex response timed out after streaming began. Observed output was checkpointed; automatic replay is disabled because the upstream operation may still be active.\"\n : \"The Codex response timed out before any response was observed. Upstream acceptance is unknown, so automatic replay is disabled.\",\n code: \"codex_response_timeout\",\n retryable: false,\n timeoutClass: codexTimeout.timeoutClass,\n responseObserved: codexTimeout.responseObserved,\n ...(codexTimeout.requestId ? { requestId: codexTimeout.requestId } : {}),\n ...(codexTimeout.message ? { detail: codexTimeout.message } : {}),\n };\n }\n const mcpTimeout = classifyMcpTransportTimeoutError(error);\n if (mcpTimeout) {\n return {\n error:\n \"An MCP server request timed out. Any completed tool output was checkpointed; the session can continue safely.\",\n code: \"mcp_transport_timeout\",\n retryable: true,\n ...(mcpTimeout.detail || mcpTimeout.message\n ? { detail: mcpTimeout.detail ?? mcpTimeout.message }\n : {}),\n };\n }\n if (isMcpTransportConnectivityError(error)) {\n return {\n error:\n \"A required MCP server was temporarily unreachable. The same turn will retry after a short delay.\",\n code: \"mcp_transport_unavailable\",\n retryable: true,\n detail: message,\n };\n }\n if (\n status === 429 ||\n code === \"rate_limit_exceeded\" ||\n /(?:too many requests|rate.?limit|\\b429\\b)/i.test(message)\n ) {\n return {\n error: \"Model provider rate limit hit. Try again in a minute or lower the reasoning effort.\",\n code: \"provider_rate_limited\",\n retryable: true,\n ...(message && message !== \"Too Many Requests\" ? { detail: message } : {}),\n };\n }\n // Transient upstream backpressure (5xx / overloaded / dropped connection): keep\n // the provider's own message (it is already user-meaningful) but mark it\n // retryable so a goal-bearing session idles and auto-continues instead of going\n // terminal on a provider's bad minute. See isTransientProviderError.\n if (isTransientProviderError(error)) {\n if (isExactStatuslessUpstreamConnectivityMessage(message)) {\n return {\n error:\n \"OpenGeni could not reach an upstream service. The same turn will retry after a short delay.\",\n code: \"upstream_connectivity_unavailable\",\n retryable: true,\n };\n }\n return { error: message, code: \"provider_unavailable\", retryable: true };\n }\n return { error: message };\n}\n\nexport type CodexCredentialFailure = {\n kind: \"auth\" | \"forbidden\" | \"rate_limit\" | \"quota\";\n cooldownSeconds: number | null;\n};\n\nexport const CODEX_ALLOWANCE_FALLBACK_MS = 5 * 60 * 60_000;\n\n/**\n * Resolve a deterministic quarantine end. Generic request throttling honors\n * provider retry-after (or one minute); allowance/quota refusal waits for the\n * LAST of provider reset and every still-binding cached window (five-hour and\n * weekly both bind), falling back to one complete five-hour window when no reset\n * metadata exists.\n */\nexport function codexCredentialCooldownUntil(\n failure: CodexCredentialFailure,\n account: Pick<\n CodexAccountStatus,\n \"primaryUsedPercent\" | \"primaryResetAt\" | \"secondaryUsedPercent\" | \"secondaryResetAt\"\n > | null,\n now: Date,\n): Date | null {\n if (failure.kind === \"auth\" || failure.kind === \"forbidden\") {\n return null;\n }\n const providerReset =\n failure.cooldownSeconds !== null &&\n Number.isFinite(failure.cooldownSeconds) &&\n failure.cooldownSeconds > 0\n ? new Date(now.getTime() + Math.ceil(failure.cooldownSeconds) * 1000)\n : null;\n if (failure.kind === \"rate_limit\") {\n return providerReset ?? new Date(now.getTime() + PROVIDER_BACKPRESSURE_DELAY_MS);\n }\n const blockingResets = account\n ? [\n { used: account.primaryUsedPercent, reset: account.primaryResetAt },\n { used: account.secondaryUsedPercent, reset: account.secondaryResetAt },\n ]\n .filter(\n (window): window is { used: number; reset: Date } =>\n (window.used ?? 0) >= CODEX_USAGE_EXHAUSTED_PCT &&\n window.reset instanceof Date &&\n window.reset.getTime() > now.getTime(),\n )\n .map((window) => window.reset)\n : [];\n const quotaResets = providerReset ? [...blockingResets, providerReset] : blockingResets;\n if (quotaResets.length === 0) {\n return new Date(now.getTime() + CODEX_ALLOWANCE_FALLBACK_MS);\n }\n return quotaResets.reduce((latest, reset) =>\n reset.getTime() > latest.getTime() ? reset : latest,\n );\n}\n\n/**\n * Only definitive credential/account refusals are safe rotation signals.\n * Ambiguous network failures, malformed/partial streams, invalid model content,\n * prompt 4xx, and provider 5xx may already have consumed tokens or persisted\n * progress and therefore MUST NOT walk the credential pool automatically.\n */\nexport function classifyCodexCredentialFailure(error: unknown): CodexCredentialFailure | null {\n // A permanent OAuth refresh failure is definitive and the shared resolver has\n // already fenced/stamped the exact credential version. The OpenAI client can\n // wrap a rejection from its custom fetch in APIConnectionError, so recognize\n // the typed exception through the same bounded cause chain used below.\n let refreshError: unknown = error;\n for (let depth = 0; depth < 6 && refreshError && typeof refreshError === \"object\"; depth += 1) {\n if (refreshError instanceof CodexReloginRequired) {\n return { kind: \"auth\", cooldownSeconds: null };\n }\n refreshError = (refreshError as Record<string, unknown>).cause;\n }\n // The activity catch also receives sandbox, MCP, storage, and tool failures.\n // Their HTTP status codes are not Codex account state and must never walk the\n // subscription pool or replay a tool on another credential.\n if (!isCodexTransportError(error)) {\n return null;\n }\n const usageLimit = classifyCodexUsageLimitError(error);\n if (usageLimit) {\n return { kind: \"quota\", cooldownSeconds: usageLimit.resetsInSeconds };\n }\n let cur: unknown = error;\n for (let depth = 0; depth < 6 && cur && typeof cur === \"object\"; depth++) {\n const value = cur as Record<string, unknown>;\n const body =\n value.error && typeof value.error === \"object\"\n ? (value.error as Record<string, unknown>)\n : null;\n const status = Number(value.status ?? value.statusCode ?? body?.status ?? body?.statusCode);\n const code = String(value.code ?? body?.code ?? \"\").toLowerCase();\n const directRetryAfter = Number(\n value.retry_after_seconds ?? body?.retry_after_seconds ?? value.retryAfterSeconds,\n );\n const retryAfterHeader =\n headerValue(value.headers, \"retry-after\") ??\n headerValue(value.responseHeaders, \"retry-after\") ??\n headerValue(body?.headers, \"retry-after\");\n const retryAfterNumber = retryAfterHeader === null ? Number.NaN : Number(retryAfterHeader);\n const retryAfterDate =\n retryAfterHeader !== null && !Number.isFinite(retryAfterNumber)\n ? Date.parse(retryAfterHeader)\n : Number.NaN;\n const retryAfter = Number.isFinite(directRetryAfter)\n ? directRetryAfter\n : Number.isFinite(retryAfterNumber)\n ? retryAfterNumber\n : Number.isFinite(retryAfterDate)\n ? Math.max(0, (retryAfterDate - Date.now()) / 1000)\n : Number.NaN;\n const cooldownSeconds =\n Number.isFinite(retryAfter) && retryAfter > 0 ? Math.ceil(retryAfter) : null;\n // Provider quota codes are more specific than their HTTP transport status.\n // A permanent allowance refusal commonly arrives as HTTP 429; classify it\n // before generic backpressure so it receives the binding-window cooldown.\n if (\n code === \"insufficient_quota\" ||\n code === \"quota_exceeded\" ||\n code === \"billing_hard_limit_reached\"\n ) {\n return { kind: \"quota\", cooldownSeconds };\n }\n if (status === 401 || code === \"unauthorized\" || code === \"invalid_api_key\") {\n return { kind: \"auth\", cooldownSeconds };\n }\n if (status === 403) {\n return { kind: \"forbidden\", cooldownSeconds };\n }\n if (status === 429 || code === \"rate_limit_exceeded\" || code === \"too_many_requests\") {\n return { kind: \"rate_limit\", cooldownSeconds };\n }\n cur = value.cause;\n }\n return null;\n}\n\n/** Humanize a seconds duration into a short \"2h 5m\" / \"9m\" / \"in under a minute\" string. */\nexport function humanizeResetWindow(resetsInSeconds: number | null): string {\n if (resetsInSeconds === null || !Number.isFinite(resetsInSeconds) || resetsInSeconds <= 0) {\n return \"shortly\";\n }\n const total = Math.ceil(resetsInSeconds);\n if (total < 60) {\n return \"in under a minute\";\n }\n const hours = Math.floor(total / 3600);\n const minutes = Math.round((total % 3600) / 60);\n if (hours > 0) {\n return minutes > 0 ? `in about ${hours}h ${minutes}m` : `in about ${hours}h`;\n }\n return `in about ${minutes}m`;\n}\n\n/**\n * Build the turn.failed payload for a ChatGPT/Codex usage cap: a precise,\n * actionable message naming the reset window, the stable `codex_usage_limit_reached`\n * code, and retryable:false (an auto-retry would just re-hit the cap).\n */\nexport function codexUsageLimitFailurePayload(\n info: { resetsInSeconds: number | null },\n detail: string,\n opts?: { allAccounts?: boolean },\n): { error: string; code: string; retryable: boolean; detail?: string } {\n // P3: when EVERY connected subscription is rate-limited the message names the\n // earliest reset across accounts; the single-account message is unchanged.\n const error = opts?.allAccounts\n ? `All connected ChatGPT/Codex subscriptions are rate-limited. Access returns ${humanizeResetWindow(info.resetsInSeconds)}. ` +\n `You can switch this session to a different model in the meantime, or wait for a subscription to reset.`\n : `Your ChatGPT/Codex subscription usage limit has been reached. Access resets ${humanizeResetWindow(info.resetsInSeconds)}. ` +\n `You can switch this session to a different model in the meantime, or wait for the limit to reset.`;\n return {\n error,\n code: \"codex_usage_limit_reached\",\n retryable: false,\n ...(detail ? { detail } : {}),\n };\n}\n\n// A usage cap that won't reset for a long time should not pin a Temporal timer\n// open indefinitely for a goal-bearing session; cap the continuation hold so the\n// goal re-evaluates at most this far out (it will re-pause if still capped).\nconst CODEX_USAGE_LIMIT_MAX_RESUME_MS = 60 * 60_000; // 1h\n\nexport function pendingToolCallFromSdkEvent(event: unknown): {\n callId: string;\n callType: string;\n callName: string | null;\n callItem: Record<string, unknown>;\n} | null {\n if (!event || typeof event !== \"object\") return null;\n if ((event as { type?: unknown }).type !== \"run_item_stream_event\") return null;\n const item = (event as { item?: { type?: unknown; rawItem?: unknown } }).item;\n if (\n !item ||\n (item.type !== \"tool_call_item\" && item.type !== \"tool_search_call_item\") ||\n !item.rawItem ||\n typeof item.rawItem !== \"object\" ||\n Array.isArray(item.rawItem)\n ) {\n return null;\n }\n const raw = item.rawItem as Record<string, unknown>;\n // The hosted image call is a complete provider fact carried by one item; it\n // never receives a separate function result and therefore must not enter the\n // pending function-call ledger.\n if (raw.type === \"hosted_tool_call\" && raw.name === \"image_generation_call\") return null;\n const callId = raw.callId ?? raw.call_id ?? raw.id;\n const callType = raw.type;\n if (typeof callId !== \"string\" || callId.length === 0 || typeof callType !== \"string\") {\n return null;\n }\n const callItem = normalizeProtocolJsonValue(raw, '$[\"item\"][\"rawItem\"]');\n return {\n callId,\n callType,\n callName: typeof raw.name === \"string\" ? raw.name : null,\n callItem,\n };\n}\n\n/** Tools whose intentional visual result must survive inline-media sanitization. */\nexport function toolCallProducesRetainableSessionImage(name: string | null): boolean {\n return name === \"computer_screenshot\" || name === \"view_image\";\n}\n\nexport function completedToolCallFromSdkEvent(event: unknown): {\n callId: string;\n resultItem: Record<string, unknown>;\n} | null {\n if (!event || typeof event !== \"object\") return null;\n if ((event as { type?: unknown }).type !== \"run_item_stream_event\") return null;\n const item = (event as { item?: { type?: unknown; rawItem?: unknown; id?: unknown } }).item;\n if (!item || (item.type !== \"tool_call_output_item\" && item.type !== \"tool_search_output_item\")) {\n return null;\n }\n const raw =\n item.rawItem && typeof item.rawItem === \"object\" && !Array.isArray(item.rawItem)\n ? (item.rawItem as Record<string, unknown>)\n : {};\n const callId = raw.callId ?? raw.call_id ?? item.id;\n if (typeof callId !== \"string\" || callId.length === 0) return null;\n return {\n callId,\n resultItem: normalizeProtocolJsonValue(raw, '$[\"item\"][\"rawItem\"]'),\n };\n}\n\n/**\n * Budget/limit exhaustion detected between model calls. This is account\n * state, not an agent failure: the segment ends gracefully (session idles,\n * run state preserved) so a top-up or limit reset lets the same session\n * continue — a failed session would reject the user's next message. An\n * active goal pauses visibly (reason \"limits\") at the next continuation\n * evaluation without consuming continuation budget.\n */\nclass BudgetExhaustedError extends Error {\n constructor(\n message: string,\n readonly serializedRunState: string | null,\n ) {\n super(message);\n this.name = \"BudgetExhaustedError\";\n }\n}\n\n// Exported for unit testing the external-billing bypass (codex-billing.test.ts); not\n// part of the activity surface. Takes the accepted policy's billing attribution and\n// the optional §7.5 P3 host `entitlements` port (when bound, its `admitRun` REPLACES\n// the local credit read for an OpenGeni-metered turn; unset → local ledger).\nexport async function ensureRunAllowed(\n settings: Settings,\n db: ActivityServices[\"db\"],\n accountId: string,\n workspaceId: string,\n isExternallyBilledTurn: boolean,\n entitlements?: ActivityServices[\"entitlements\"],\n): Promise<void> {\n // Externally billed turns are paid outside OpenGeni: skip the credit-balance\n // gate and monthly token cap. The agent-run COUNT cap below is a\n // volume/fairness quota (not a credit/cost gate) and is intentionally kept.\n //\n // §7.5 P3 — host-entitlements DELEGATION (the worker half of the same seam the\n // API edge exposes). For a non-codex turn, when the host binds `entitlements`, its\n // `admitRun` decision REPLACES the local credit-balance read below: a host that owns\n // its ledger/meter is the funding authority. A deny throws the SAME Error the local\n // read throws, so the mid-stream budget-valve at :727 wraps it in a\n // `BudgetExhaustedError` and pauses identically — the valve never learns whether the\n // deny came from the local ledger or the host meter.\n //\n // This is an admission READ only; it records NO usage (metering stays the sole,\n // idempotency-keyed writer at recordModelUsageAndDebitCredits), so a PULL host meter\n // is consulted without ever double-charging.\n if (\n !isExternallyBilledTurn &&\n entitlements &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const decision = await entitlements.admitRun({\n accountId,\n workspaceId,\n action: \"agent_run:create\",\n quantity: 1,\n });\n if (!decision.allowed) {\n throw new Error(decision.reason || \"insufficient OpenGeni credits\");\n }\n } else if (\n !isExternallyBilledTurn &&\n (settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\")\n ) {\n const balance = await getBillingBalance(db, accountId);\n if (balance.balanceMicros <= 0) {\n throw new Error(\"insufficient OpenGeni credits\");\n }\n }\n if (settings.usageLimitsMode === \"static\" || settings.usageLimitsMode === \"managed\") {\n const limits = configuredStaticUsageLimits(settings);\n if (limits.maxMonthlyAgentRunsPerWorkspace) {\n const used = await sumUsageQuantity(db, {\n workspaceId,\n eventType: \"agent_run.created\",\n since: startOfUtcMonth(),\n });\n // Agent turns are admitted and recorded before this worker activity starts.\n // Equality means this accepted turn is exactly at the cap; greater-than is\n // the race/backstop case where another admission already exceeded the cap.\n if (used > limits.maxMonthlyAgentRunsPerWorkspace) {\n throw new Error(\n `monthly agent run limit reached (${limits.maxMonthlyAgentRunsPerWorkspace})`,\n );\n }\n }\n if (!isExternallyBilledTurn && limits.maxMonthlyTokensPerWorkspace) {\n const used = await sumUsageQuantity(db, {\n workspaceId,\n eventType: \"model.tokens\",\n since: startOfUtcMonth(),\n });\n if (used >= limits.maxMonthlyTokensPerWorkspace) {\n throw new Error(`monthly token limit reached (${limits.maxMonthlyTokensPerWorkspace})`);\n }\n }\n }\n}\n\nexport type ModelUsageBillingRecord = {\n billingPath: \"opengeni_credits\" | \"external\";\n /** Same quantity written to usage_events.model.cost when present; else 0. */\n pricedCostMicros: number;\n /** Hypothetical provider-rate USD micros; never an OpenGeni charge. */\n estimatedProviderCostMicros: number | null;\n pricingSource: \"configured_list_price\" | \"gateway_reported\" | null;\n normalizedUsage: ModelCallUsageNormalization;\n upstreamProvider?: string;\n};\n\n// Exported for unit testing the external-billing bypass; not part of the activity surface.\nexport async function recordModelUsageAndDebitCredits(\n settings: Settings,\n db: ActivityServices[\"db\"],\n input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n model: string;\n externallyBilled: boolean;\n gatewayManaged?: boolean;\n gatewayBilling?: ModelResponseUsage[\"gatewayBilling\"];\n usage?: ModelUsageInput | ModelCallUsageInput | null;\n normalizedUsage?: ModelCallUsageNormalization;\n sourceKey: string;\n latencyMode?: LatencyMode;\n observability?: ActivityServices[\"observability\"];\n },\n): Promise<ModelUsageBillingRecord | null> {\n if (!input.usage) {\n return null;\n }\n const normalizedUsage = input.normalizedUsage ?? normalizeModelCallUsage(input.usage);\n const sanitizedUsage = sanitizedModelUsageInput(normalizedUsage);\n const inputTokens = sanitizedUsage.inputTokens ?? 0;\n const outputTokens = sanitizedUsage.outputTokens ?? 0;\n const totalTokens = sanitizedUsage.totalTokens ?? 0;\n const gatewayBilling = input.gatewayManaged ? input.gatewayBilling : undefined;\n if (gatewayBilling) {\n const gatewayModel = Object.values(OPENGENI_GATEWAY_MODELS).find(\n (candidate) => candidate.productId === input.model,\n );\n if (\n !gatewayModel ||\n !(gatewayModel.providers as readonly string[]).includes(gatewayBilling.finalProvider)\n ) {\n throw new Error(\n `AI Gateway reported unapproved provider ${gatewayBilling.finalProvider} for ${input.model}`,\n );\n }\n }\n const pricingSchedules = configuredModelPricingSchedules(settings);\n const configuredPricingModel = pricingSchedules[input.model]\n ? input.model\n : input.model.startsWith(\"codex/\") && pricingSchedules[input.model.slice(\"codex/\".length)]\n ? input.model.slice(\"codex/\".length)\n : null;\n const pricingBreakdown = gatewayBilling\n ? calculateGatewayReportedCostBreakdown(\n settings,\n input.model,\n gatewayBilling.inferenceCostUsd,\n { inputTokens },\n )\n : configuredPricingModel\n ? calculateModelUsageCostBreakdown(settings, configuredPricingModel, sanitizedUsage, {\n latencyMode: input.latencyMode ?? \"standard\",\n })\n : null;\n const hasCompleteCoreTokenTelemetry =\n normalizedUsage.telemetry.inputTokens !== null &&\n normalizedUsage.telemetry.outputTokens !== null;\n const estimatedProviderCostMicros = gatewayBilling\n ? (pricingBreakdown?.providerCostMicros ?? null)\n : hasCompleteCoreTokenTelemetry\n ? (pricingBreakdown?.providerCostMicros ?? null)\n : null;\n const pricingSource = gatewayBilling\n ? (\"gateway_reported\" as const)\n : estimatedProviderCostMicros !== null\n ? (\"configured_list_price\" as const)\n : null;\n // An externally billed turn is paid outside OpenGeni, so it\n // consumes ZERO OpenGeni credits and must never feed an OpenGeni cap. A\n // codex/<slug> model has no entry in configuredModelPricing, so the normal path\n // below would throw \"Missing model pricing\". We:\n // - do NOT emit the cap-feeding `model.tokens` event (ensureRunAllowed and\n // the API tokens:consume cap sum `model.tokens` with NO cost dimension, so\n // any row would count against maxMonthlyTokensPerWorkspace);\n // - record a `model.cost = 0` audit marker (harmless to the monthly cost cap);\n // - optionally calculate a non-charging provider estimate for Insights when\n // core token telemetry is complete, but never debit credits.\n if (input.externallyBilled) {\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.cost\",\n quantity: 0,\n unit: \"usd_micros\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`,\n });\n return {\n billingPath: \"external\",\n pricedCostMicros: 0,\n estimatedProviderCostMicros,\n pricingSource,\n normalizedUsage,\n };\n }\n if (totalTokens > 0) {\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.tokens\",\n quantity: totalTokens,\n unit: \"tokens\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.tokens:${input.turnId}:${input.sourceKey}`,\n });\n }\n const shouldDebit = settings.billingMode === \"stripe\" || settings.usageLimitsMode === \"managed\";\n if (!shouldDebit || (totalTokens === 0 && !gatewayBilling)) {\n return {\n billingPath: \"opengeni_credits\",\n pricedCostMicros: 0,\n estimatedProviderCostMicros,\n pricingSource,\n normalizedUsage,\n ...(gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}),\n };\n }\n if (!pricingBreakdown) {\n throw new Error(`Missing model pricing for ${input.model}`);\n }\n const costMicros = pricingBreakdown.creditCostMicros;\n await recordUsageEvent(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n eventType: \"model.cost\",\n quantity: costMicros,\n unit: \"usd_micros\",\n sourceResourceType: \"model_response\",\n sourceResourceId: `${input.turnId}:${input.sourceKey}`,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n idempotencyKey: `usage:model.cost:${input.turnId}:${input.sourceKey}`,\n });\n if (costMicros > 0) {\n const result = await applyCreditDebitUpToBalance(db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n type: \"model_usage_debit\",\n requestedAmountMicros: costMicros,\n sourceType: \"model_response\",\n sourceId: `${input.turnId}:${input.sourceKey}`,\n idempotencyKey: `credit:model_usage_debit:${input.turnId}:${input.sourceKey}`,\n metadata: {\n model: input.model,\n sessionId: input.sessionId,\n turnId: input.turnId,\n sourceKey: input.sourceKey,\n latencyMode: input.latencyMode ?? \"standard\",\n inputTokens,\n outputTokens,\n totalTokens,\n // Additive: the prompt-cache slice of this call's input tokens, so the\n // per-call debit record carries cache efficiency alongside the token\n // counts. 0 when the provider did not report cached tokens.\n cachedTokens: normalizedUsage.telemetry.cachedTokens ?? 0,\n ...(gatewayBilling ? { gatewayProvider: gatewayBilling.finalProvider } : {}),\n },\n });\n recordCreditMicros(input.observability, \"usage\", result.debitedMicros);\n }\n return {\n billingPath: \"opengeni_credits\",\n pricedCostMicros: costMicros,\n estimatedProviderCostMicros,\n pricingSource,\n normalizedUsage,\n ...(gatewayBilling ? { upstreamProvider: gatewayBilling.finalProvider } : {}),\n };\n}\n\n/** Soft-fail Insights fact write — never throws into the billing/emit path. */\nexport async function recordAuthoritativeModelCallFact(input: {\n db: ActivityServices[\"db\"];\n observability: ActivityServices[\"observability\"];\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n turnAttemptId: string;\n sourceKey: string;\n provider: string;\n providerApi: ModelProviderApi;\n model: string;\n billing: ModelUsageBillingRecord;\n}): Promise<void> {\n try {\n const telemetry = input.billing.normalizedUsage.telemetry;\n await recordModelCallFact(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n turnAttemptId: input.turnAttemptId,\n sourceKey: input.sourceKey,\n provider: input.billing.upstreamProvider ?? input.provider,\n providerApi: input.providerApi,\n model: input.model,\n billingPath: input.billing.billingPath,\n pricedCostMicros: input.billing.pricedCostMicros,\n estimatedProviderCostMicros: input.billing.estimatedProviderCostMicros,\n pricingSource: input.billing.pricingSource,\n inputTokens: telemetry.inputTokens,\n outputTokens: telemetry.outputTokens,\n cachedTokens: telemetry.cachedTokens,\n cacheWriteTokens: telemetry.cacheWriteTokens,\n reasoningTokens: telemetry.reasoningTokens,\n totalTokens: input.billing.normalizedUsage.totalTokens,\n });\n } catch (error) {\n input.observability.warn(\"model call fact persist failed\", {\n ...safeErrorDiagnostic(error),\n });\n }\n}\n\nfunction sanitizedModelUsageInput(normalized: ModelCallUsageNormalization): ModelUsageInput {\n return {\n ...(normalized.telemetry.inputTokens !== null\n ? { inputTokens: normalized.telemetry.inputTokens }\n : {}),\n ...(normalized.telemetry.outputTokens !== null\n ? { outputTokens: normalized.telemetry.outputTokens }\n : {}),\n ...(normalized.totalTokens !== null ? { totalTokens: normalized.totalTokens } : {}),\n ...(normalized.telemetry.cachedTokens !== null\n ? {\n inputTokensDetails: {\n cached_tokens: normalized.telemetry.cachedTokens,\n },\n }\n : {}),\n ...(normalized.requestUsageEntries\n ? { requestUsageEntries: normalized.requestUsageEntries }\n : {}),\n };\n}\n\nfunction startOfUtcMonth(): Date {\n const now = new Date();\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));\n}\n\nasync function sandboxFileDownloadsForRun(\n settings: Settings,\n db: ActivityServices[\"db\"],\n objectStorage: ObjectStorage | null,\n workspaceId: string,\n resources: ResourceRef[],\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): Promise<SandboxFileDownload[]> {\n if (!requiresSignedFileResourceDownloads(settings, activeSandboxBackend)) {\n return [];\n }\n const fileResources = resources.filter(\n (resource): resource is Extract<ResourceRef, { kind: \"file\" }> => resource.kind === \"file\",\n );\n if (fileResources.length === 0) {\n return [];\n }\n if (!objectStorage) {\n throw new Error(\n `${settings.objectStorageBackend} file resources require configured object storage`,\n );\n }\n const downloadStorage = objectStorageForSandboxDownloads(settings, objectStorage);\n const downloads: SandboxFileDownload[] = [];\n for (const resource of fileResources) {\n const file = await requireFile(db, workspaceId, resource.fileId);\n const url = await downloadStorage.createGetUrl({ key: file.objectKey });\n downloads.push({\n fileId: file.id,\n mountPath: resourceMountPath(resource),\n filename: file.safeFilename,\n url: url.url,\n expiresAt: url.expiresAt,\n sizeBytes: file.sizeBytes,\n ...(file.sha256 ? { sha256: file.sha256 } : {}),\n });\n }\n return downloads;\n}\n\nexport function requiresSignedFileResourceDownloads(\n settings: Settings,\n activeSandboxBackend: Settings[\"sandboxBackend\"] = settings.sandboxBackend,\n): boolean {\n if (activeSandboxBackend === \"none\") {\n return false;\n }\n // A selfhosted machine (bring-your-own-compute) can NEVER mount ANY object store\n // — it is a remote user machine reached only over NATS, so file resources are\n // ALWAYS delivered by exec-curling a pre-signed URL onto it. Without this a\n // machine-home turn (sandbox_backend \"selfhosted\") would silently drop file\n // resources on an azure-blob / s3-compatible store (nativeBucketMount=false),\n // a regression from the pre-honest-label path where the same turn ran home=modal\n // and modal's descriptor forced signed downloads.\n if (activeSandboxBackend === \"selfhosted\") {\n return true;\n }\n // A nativeBucketMount backend (modal) cannot mount Azure Blob entries, so it\n // needs pre-signed downloads for that store. Keying on the descriptor (not the\n // \"modal\" literal) keeps this correct as bucket-mount backends are added.\n const nativeBucketMount = CAPABILITY_DESCRIPTORS[activeSandboxBackend].nativeBucketMount;\n return (\n (activeSandboxBackend === \"docker\" && settings.objectStorageBackend === \"s3-compatible\") ||\n settings.objectStorageBackend === \"aws-s3\" ||\n settings.objectStorageBackend === \"gcs\" ||\n (nativeBucketMount && settings.objectStorageBackend === \"azure-blob\")\n );\n}\n\nfunction objectStorageForSandboxDownloads(\n settings: Settings,\n objectStorage: ObjectStorage,\n): ObjectStorage {\n if (settings.objectStorageBackend !== \"s3-compatible\" || !settings.objectStorageSandboxEndpoint) {\n return objectStorage;\n }\n return (\n createObjectStorage({\n ...settings,\n objectStorageEndpoint: settings.objectStorageSandboxEndpoint,\n }) ?? objectStorage\n );\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type { ConnectionCredentialsPort, SessionTurn } from \"@opengeni/contracts\";\nimport {\n buildConnectionTokenResolver,\n buildHostConnectionTokenResolver,\n type Database,\n type ResolveConnectionCredentialInput,\n type ResolveConnectionCredentialResult,\n} from \"@opengeni/db\";\n\nexport function connectionTokenResolverForTurn(input: {\n db: Database;\n settings: Settings;\n connectionCredentials?: ConnectionCredentialsPort | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n rootSessionId: string;\n attemptId: string;\n turn: SessionTurn;\n}): (request: ResolveConnectionCredentialInput) => Promise<ResolveConnectionCredentialResult> {\n const hostResolver = input.connectionCredentials?.mcpCredentials;\n if (!hostResolver) {\n return buildConnectionTokenResolver(input.db, input.settings);\n }\n return buildHostConnectionTokenResolver(hostResolver, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n rootSessionId: input.rootSessionId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n surface: \"model\",\n allowOfficialGmailRestDestination: input.settings.gmailRestAdapterEnabled,\n });\n}\n","import {\n createGraphqlMcpServer,\n createOpenApiMcpServer,\n createPinnedIntegrationTransport,\n type IntegrationCredentialResolver,\n type IntegrationInvocationAuthority,\n} from \"@opengeni/capabilities\";\nimport type { Settings } from \"@opengeni/config\";\nimport type { ToolAuthNeededPayload } from \"@opengeni/contracts\";\nimport type {\n ApiIntegrationRuntime,\n ResolveConnectionCredentialInput,\n ResolveConnectionCredentialResult,\n} from \"@opengeni/db\";\nimport type { LocalMcpServerRegistration } from \"@opengeni/runtime\";\nimport type { FetchLike } from \"@opengeni/network\";\n\nexport type BuildApiIntegrationServersInput = {\n settings: Settings;\n integrations: readonly ApiIntegrationRuntime[];\n authority: Omit<IntegrationInvocationAuthority, \"connectionRef\">;\n resolveCredential: (\n input: ResolveConnectionCredentialInput,\n ) => Promise<ResolveConnectionCredentialResult>;\n onAuthNeeded?: (payload: ToolAuthNeededPayload) => Promise<void> | void;\n fetchImpl?: FetchLike;\n};\n\n/**\n * Compile active persisted API facets into ordinary in-process MCP servers for\n * one exact attempt. Connection resolution remains request-time, destination-\n * bound, personal-delegation-fenced, and refreshable through the same worker\n * resolver used by remote MCP servers.\n */\nexport function buildApiIntegrationServersForTurn(\n input: BuildApiIntegrationServersInput,\n): LocalMcpServerRegistration[] {\n const transport = createPinnedIntegrationTransport({\n network: input.settings,\n ...(input.fetchImpl ? { fetchImpl: input.fetchImpl } : {}),\n });\n return input.integrations.map((integration) => {\n const authority: IntegrationInvocationAuthority = {\n ...input.authority,\n ...(integration.connectionRef?.connectionId\n ? { connectionRef: integration.connectionRef.connectionId }\n : {}),\n };\n const credentialResolver = integration.connectionRef\n ? integrationCredentialResolver(input, integration)\n : undefined;\n const server =\n integration.revision.protocol === \"openapi\"\n ? createOpenApiMcpServer({\n revision: integration.revision,\n transport,\n authority,\n ...(credentialResolver ? { credentialResolver } : {}),\n })\n : createGraphqlMcpServer({\n revision: integration.revision,\n endpoint: integration.baseUrl,\n transport,\n authority,\n ...(credentialResolver ? { credentialResolver } : {}),\n });\n return {\n id: integration.serverId,\n server,\n ...(integration.connectionRef?.connectionId\n ? { resolvedConnectionId: integration.connectionRef.connectionId }\n : {}),\n };\n });\n}\n\nfunction integrationCredentialResolver(\n input: BuildApiIntegrationServersInput,\n integration: ApiIntegrationRuntime,\n): IntegrationCredentialResolver {\n const connectionRef = integration.connectionRef;\n if (!connectionRef) throw new Error(\"Integration credential resolver requires a connection\");\n return {\n resolve: async (request) => {\n const result = await input.resolveCredential({\n workspaceId: input.authority.workspaceId,\n serverId: integration.serverId,\n toolName: request.operationKey,\n connectionRef,\n destinationUrl: request.destinationUrl,\n credentialTarget: \"http_api\",\n forceRefresh: request.forceRefresh === true,\n });\n if (result.status === \"auth_needed\") {\n await publishAuthNeeded(input, integration.serverId, request.operationKey, result);\n return null;\n }\n const destination = new URL(request.destinationUrl);\n return {\n audience: { origin: destination.origin, pathPrefix: \"/\" },\n placements:\n result.placements ??\n Object.entries(result.headers).map(([name, value]) => ({\n carrier: \"header\" as const,\n name,\n value,\n })),\n ...(result.expiresAt ? { expiresAt: result.expiresAt.toISOString() } : {}),\n ...(connectionRef.scopes ? { scope: [...connectionRef.scopes] } : {}),\n };\n },\n };\n}\n\nasync function publishAuthNeeded(\n input: BuildApiIntegrationServersInput,\n serverId: string,\n toolName: string,\n result: Extract<ResolveConnectionCredentialResult, { status: \"auth_needed\" }>,\n): Promise<void> {\n try {\n await input.onAuthNeeded?.({\n serverId,\n toolName,\n providerDomain: result.providerDomain,\n ...(result.provider ? { provider: result.provider } : {}),\n reason: result.reason,\n ...(result.connectionId ? { connectionId: result.connectionId } : {}),\n ...(result.scopes ? { scopes: result.scopes } : {}),\n ...(result.resource ? { resource: result.resource } : {}),\n ...(result.selectedResources ? { selectedResources: result.selectedResources } : {}),\n ...(result.authorizationUrl ? { authorizationUrl: result.authorizationUrl } : {}),\n });\n } catch {\n // Authentication notices are advisory UI/audit signals. The local tool\n // still returns the fixed connection-required result when publication fails.\n }\n}\n","import {\n environmentsEncryptionKeyBytes,\n type Settings,\n withCodexCatalogProvider,\n withWorkspaceGatewayCatalogProvider,\n withWorkspaceGatewayCredential,\n withXaiSubscriptionCatalogProvider,\n} from \"@opengeni/config\";\nimport { settingsWithEnabledCapabilityMcpServers } from \"@opengeni/core\";\nimport {\n listSessionMcpServerMetadata,\n listSessionMcpServersForRun,\n workspaceCodexSubscriptionActive,\n loadWorkspaceVercelAiGatewayApiKey,\n type Database,\n type SessionMcpServerForRun,\n} from \"@opengeni/db\";\n\nexport { settingsWithEnabledCapabilityMcpServers };\n\nexport async function settingsWithSessionMcpServersForRun(\n db: Database,\n workspaceId: string,\n sessionId: string,\n attemptId: string,\n settings: Settings,\n options?: {\n onResolvedServers?: (servers: readonly SessionMcpServerForRun[]) => void;\n },\n): Promise<Settings> {\n const encryptionKey = environmentsEncryptionKeyBytes(settings);\n if (!encryptionKey) {\n const metadata = await listSessionMcpServerMetadata(db, workspaceId, sessionId);\n if (metadata.length === 0) {\n return settings;\n }\n if (metadata.some((server) => server.headerNames.length > 0)) {\n throw new Error(\n \"session MCP server credentials require OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\",\n );\n }\n }\n const servers = await listSessionMcpServersForRun(\n db,\n workspaceId,\n sessionId,\n attemptId,\n encryptionKey ?? null,\n );\n // Keep credential provenance coupled to the exact decrypted rows that are\n // overlaid into settings. A session projection read earlier in the turn can\n // be stale after a concurrent mcpCredentialUpdates renewal.\n options?.onResolvedServers?.(servers);\n return settingsWithSessionMcpServers(settings, servers);\n}\n\nexport function settingsWithSessionMcpServers(\n settings: Settings,\n servers: SessionMcpServerForRun[],\n): Settings {\n if (servers.length === 0) {\n return settings;\n }\n const sessionIds = new Set(servers.map((server) => server.id));\n return {\n ...settings,\n mcpServers: [\n ...settings.mcpServers.filter((server) => !sessionIds.has(server.id)),\n ...servers.map((server) => ({\n id: server.id,\n ...(server.name ? { name: server.name } : {}),\n url: server.url,\n ...(server.allowedTools ? { allowedTools: server.allowedTools } : {}),\n ...(server.timeoutMs ? { timeoutMs: server.timeoutMs } : {}),\n cacheToolsList: server.cacheToolsList ?? false,\n ...(server.requireApproval !== undefined\n ? { requireApproval: server.requireApproval }\n : {}),\n ...(server.connectionRef ? { connectionRef: server.connectionRef } : {}),\n headers: server.headers,\n })),\n ],\n };\n}\n\n/**\n * When the workspace has an active Codex subscription connected and the feature\n * is enabled, inject a synthetic \"codex-subscription\" registry provider so a\n * `codex/<slug>` model id routes through the ChatGPT backend. No secrets touch\n * this overlay (metadata-only read); the per-request bearer is resolved later via\n * codexRequestStorage. Idempotent and a no-op when not applicable.\n */\nexport async function settingsWithCodexCredential(\n db: Database,\n workspaceId: string,\n settings: Settings,\n activeOverride?: boolean,\n): Promise<Settings> {\n // Same active-credential predicate the billing bypass uses, so provider\n // injection and billing can never disagree on what an \"active codex\" turn is.\n // The caller may pass `activeOverride` (a single, shared read; P2-b) so routing\n // and billing decide from the exact same observation, immune to a concurrent\n // disconnect/reconnect landing between two independent reads.\n const active =\n activeOverride ?? (await workspaceCodexSubscriptionActive(db, settings, workspaceId));\n if (!active) {\n return settings; // disabled / not connected / needs_relogin / error -> leave settings unchanged\n }\n const withProvider = withCodexProvider(settings);\n return withProvider;\n}\n\n/** Pure: append the synthetic codex-subscription provider, idempotently. */\nexport function withCodexProvider(settings: Settings): Settings {\n return withCodexCatalogProvider(settings);\n}\n\n/**\n * Pure: append the synthetic SuperGrok/xAI subscription provider,\n * idempotently. The overlay is catalogue metadata only; the exact account,\n * authority snapshot, and bearer remain frozen later at turn admission.\n */\nexport function withXaiSubscriptionProvider(settings: Settings): Settings {\n return withXaiSubscriptionCatalogProvider(settings);\n}\n\nexport async function settingsWithWorkspaceGatewayCredential(\n db: Database,\n workspaceId: string,\n settings: Settings,\n): Promise<Settings> {\n const catalogSettings = withWorkspaceGatewayCatalogProvider(settings);\n const apiKey = await loadWorkspaceVercelAiGatewayApiKey(db, settings, workspaceId);\n return apiKey ? withWorkspaceGatewayCredential(catalogSettings, apiKey) : catalogSettings;\n}\n","import {\n DEFAULT_CODEX_FLEET_POLICY_V1,\n compareCodexFleetCanonicalStringsV1,\n createCodexFleetReplayRecordV1,\n type CodexFleetCandidateStatus,\n type CodexFleetDecisionInputV1,\n type CodexFleetReplayRecordV1,\n} from \"@opengeni/contracts\";\nimport type { CodexLeaseAccountStatus } from \"@opengeni/db\";\nimport { CancelledFailure } from \"@temporalio/activity\";\nimport { createHmac } from \"node:crypto\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\n\nexport const CODEX_FLEET_SHADOW_MAX_PAYLOAD_BYTES = 34 * 1_024;\n\nexport type CodexFleetActualDecisionV1 = {\n outcome: \"selected\" | \"waiting\" | \"none\";\n candidateKey: string | null;\n reason: \"lease_reused\" | \"pin\" | \"rotation\" | \"active\" | \"all_capped\" | \"none\";\n};\n\nexport type CodexFleetShadowComparisonV1 =\n | \"match\"\n | \"different_candidate\"\n | \"different_outcome\"\n | \"not_comparable_truncated\";\n\nexport type CodexFleetShadowPayloadV1 = {\n schemaVersion: 1;\n mode: \"shadow\";\n actual: CodexFleetActualDecisionV1;\n comparison: CodexFleetShadowComparisonV1;\n replay: CodexFleetReplayRecordV1;\n};\n\nexport type CodexFleetShadowBuildInputV1 = {\n accounts: readonly CodexLeaseAccountStatus[];\n actualCredentialId: string | null;\n actualOutcome: CodexFleetActualDecisionV1[\"outcome\"];\n actualReason: CodexFleetActualDecisionV1[\"reason\"];\n affinityCredentialId: string | null;\n fencedInFlight: boolean;\n nearExhaustionPct: number;\n now: Date;\n /** Per-event entropy used only to unlink account aliases; never persisted. */\n aliasSeed: string;\n};\n\nexport type CodexFleetShadowPublicationResultV1 =\n | { outcome: \"disabled\" }\n | {\n outcome: \"published\";\n payload: CodexFleetShadowPayloadV1;\n payloadBytes: number;\n }\n | {\n outcome: \"failed\";\n stage: \"build\" | \"serialize\" | \"publish\";\n reason: \"payload_too_large\" | \"unexpected\";\n errorName: string;\n payloadBytes: number | null;\n };\n\nexport const CODEX_FLEET_SHADOW_DECISION_MAX_METRIC_SERIES = 3 * 3 * 4 * 4 * 2;\nexport const CODEX_FLEET_SHADOW_ERROR_MAX_METRIC_SERIES = 3 * 2;\n\n/** Fixed low-cardinality labels; workspace/account/tenant identity is structurally absent. */\nexport function codexFleetShadowDecisionMetricLabelsV1(payload: CodexFleetShadowPayloadV1) {\n return {\n actual_outcome: payload.actual.outcome,\n shadow_outcome: payload.replay.decision.outcome,\n comparison: payload.comparison,\n confidence: payload.replay.decision.confidence,\n truncated: payload.replay.truncatedCandidateCount > 0 ? \"true\" : \"false\",\n } as const;\n}\n\nexport function codexFleetShadowErrorMetricLabelsV1(\n result: Extract<CodexFleetShadowPublicationResultV1, { outcome: \"failed\" }>,\n) {\n return { stage: result.stage, reason: result.reason } as const;\n}\n\n/**\n * Default-off, bounded, fail-open runtime seam for the shadow record.\n *\n * The typed result intentionally carries no error message: provider, database,\n * or transport errors can include private metadata. Callers may count/log only\n * the bounded stage, reason, name, and size fields returned here. A failure can\n * never replace or clear the credential already selected by the allocator.\n */\nexport async function publishCodexFleetShadowDecisionV1(input: {\n enabled: boolean;\n decision: CodexFleetShadowBuildInputV1;\n publish: (\n events: Array<{\n type: \"codex.fleet.decision\";\n payload: CodexFleetShadowPayloadV1;\n }>,\n ) => Promise<unknown>;\n}): Promise<CodexFleetShadowPublicationResultV1> {\n if (!input.enabled) return { outcome: \"disabled\" };\n\n let stage: \"build\" | \"serialize\" | \"publish\" = \"build\";\n let payloadBytes: number | null = null;\n try {\n const payload = buildCodexFleetShadowPayloadV1(input.decision);\n stage = \"serialize\";\n payloadBytes = new TextEncoder().encode(JSON.stringify(payload)).byteLength;\n if (payloadBytes > CODEX_FLEET_SHADOW_MAX_PAYLOAD_BYTES) {\n return {\n outcome: \"failed\",\n stage,\n reason: \"payload_too_large\",\n errorName: \"CodexFleetShadowPayloadTooLargeError\",\n payloadBytes,\n };\n }\n stage = \"publish\";\n await input.publish([{ type: \"codex.fleet.decision\", payload }]);\n return { outcome: \"published\", payload, payloadBytes };\n } catch (error) {\n // These are authoritative activity lifecycle signals, not shadow failures.\n // Swallowing either would allow a superseded attempt to continue mutating.\n if (error instanceof TurnAttemptFencedError || error instanceof CancelledFailure) throw error;\n return {\n outcome: \"failed\",\n stage,\n reason: \"unexpected\",\n errorName: safeErrorName(error),\n payloadBytes,\n };\n }\n}\n\nexport function buildCodexFleetShadowPayloadV1(\n input: CodexFleetShadowBuildInputV1,\n): CodexFleetShadowPayloadV1 {\n // Randomized keyed ordering makes c00/c01 unlinkable across events while the\n // supplied event seed keeps this one replay/payload build deterministic.\n const eventAccounts = [...input.accounts].sort(\n (left, right) =>\n compareCodexFleetCanonicalStringsV1(\n aliasSortKey(input.aliasSeed, left.id),\n aliasSortKey(input.aliasSeed, right.id),\n ) || compareCodexFleetCanonicalStringsV1(left.id, right.id),\n );\n const aliases = new Map(\n eventAccounts.map((account, index) => [account.id, candidateAlias(index)] as const),\n );\n const actualCandidateKey = input.actualCredentialId\n ? (aliases.get(input.actualCredentialId) ?? null)\n : null;\n const currentCandidateKey = input.affinityCredentialId\n ? (aliases.get(input.affinityCredentialId) ?? null)\n : null;\n const decisionInput: CodexFleetDecisionInputV1 = {\n observedAtMs: input.now.getTime(),\n request: {\n placement: input.fencedInFlight ? \"fenced_in_flight\" : \"new\",\n priority: \"standard\",\n currentCandidateKey: input.fencedInFlight ? actualCandidateKey : currentCandidateKey,\n waitAgeMs: 0,\n overlayKey: null,\n overlayMode: \"none\",\n },\n admission: {\n // The shadow policy does not invent hard capacity from account count. A later typed\n // admission snapshot supplies dynamic capacity; shadow v1 records unknown.\n dynamicCapacityUnits: null,\n inUseUnits: input.accounts.reduce((sum, account) => sum + account.activeLeaseCount, 0),\n queuedManagerCount: 0,\n emergencyFuseActive: false,\n },\n candidates: eventAccounts.map((account, index) => ({\n key: candidateAlias(index),\n status: normalizeStatus(account.status),\n allocatorEnabled: account.allocatorEnabled,\n cooldownRemainingMs: remainingMs(account.exhaustedUntil, input.now),\n activeLeaseCount: account.activeLeaseCount,\n quota: {\n primary: {\n usedPercent: account.primaryUsedPercent,\n resetRemainingMs: remainingMs(account.primaryResetAt, input.now),\n },\n secondary: {\n usedPercent: account.secondaryUsedPercent,\n resetRemainingMs: remainingMs(account.secondaryResetAt, input.now),\n },\n checkedAgeMs: ageMs(account.usageCheckedAt, input.now),\n confidence: quotaConfidence(account),\n },\n // Current production cache evidence is aggregate metric + opaque log data,\n // not allocator state. Preserve that gap as unknown instead of fabricating 0.\n cache: {\n hitRatio: null,\n sampledTokens: null,\n checkedAgeMs: null,\n confidence: \"unknown\",\n state: \"unknown\",\n thresholdObservedForMs: null,\n },\n // The shadow policy has no typed workspace-local burn feed at this boundary yet.\n observedBurn: {\n primaryPercentPerHour: null,\n secondaryPercentPerHour: null,\n confidence: \"unknown\",\n },\n // Provider accounting has not supplied a typed burn observation yet.\n // Unknown inference is explicit and contributes no fabricated tenant truth.\n inferredUnexplainedBurn: {\n primaryPercentPerHour: null,\n secondaryPercentPerHour: null,\n confidence: \"unknown\",\n },\n overlayKeys: [],\n })),\n };\n const replay = createCodexFleetReplayRecordV1(decisionInput, {\n ...DEFAULT_CODEX_FLEET_POLICY_V1,\n placementUsageCeilingPercent: input.nearExhaustionPct,\n });\n const actual: CodexFleetActualDecisionV1 = {\n outcome: input.actualOutcome,\n candidateKey: actualCandidateKey,\n reason: input.actualReason,\n };\n return {\n schemaVersion: 1,\n mode: \"shadow\",\n actual,\n comparison: compareDecision(actual, replay),\n replay,\n };\n}\n\nfunction compareDecision(\n actual: CodexFleetActualDecisionV1,\n replay: CodexFleetReplayRecordV1,\n): CodexFleetShadowComparisonV1 {\n if (\n replay.truncatedCandidateCount > 0 &&\n actual.candidateKey !== null &&\n !replay.input.candidates.some((candidate) => candidate.key === actual.candidateKey)\n ) {\n return \"not_comparable_truncated\";\n }\n const shadowOutcome = replay.decision.outcome === \"selected\" ? \"selected\" : \"none\";\n const actualComparableOutcome = actual.outcome === \"selected\" ? \"selected\" : \"none\";\n if (shadowOutcome !== actualComparableOutcome) return \"different_outcome\";\n if (shadowOutcome === \"selected\") {\n return replay.decision.selectedCandidateKey === actual.candidateKey\n ? \"match\"\n : \"different_candidate\";\n }\n return \"match\";\n}\n\nfunction normalizeStatus(status: string): CodexFleetCandidateStatus {\n if (status === \"active\" || status === \"needs_relogin\" || status === \"error\") return status;\n return \"unknown\";\n}\n\nfunction candidateAlias(index: number): string {\n return `c${index.toString(36).padStart(2, \"0\")}`;\n}\n\nfunction aliasSortKey(seed: string, credentialId: string): string {\n return createHmac(\"sha256\", seed).update(credentialId).digest(\"hex\");\n}\n\nfunction quotaConfidence(account: CodexLeaseAccountStatus): \"unknown\" | \"low\" | \"medium\" | \"high\" {\n if (!account.usageCheckedAt) return \"unknown\";\n const windows = [\n [account.primaryUsedPercent, account.primaryResetAt],\n [account.secondaryUsedPercent, account.secondaryResetAt],\n ] as const;\n const complete = windows.filter(([used, reset]) => used !== null && reset !== null).length;\n const partial = windows.some(([used, reset]) => (used === null) !== (reset === null));\n if (complete === 0) return \"unknown\";\n if (partial) return \"low\";\n return complete === windows.length ? \"high\" : \"medium\";\n}\n\nfunction remainingMs(value: Date | null, now: Date): number | null {\n return value ? Math.max(0, value.getTime() - now.getTime()) : null;\n}\n\nfunction ageMs(value: Date | null, now: Date): number | null {\n return value ? Math.max(0, now.getTime() - value.getTime()) : null;\n}\n\nfunction safeErrorName(error: unknown): string {\n if (!(error instanceof Error)) return \"UnknownError\";\n return /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(error.name) ? error.name : \"Error\";\n}\n","/**\n * The activity lost ownership of its exact turn generation/attempt.\n *\n * This is an ordinary stale-writer outcome, not a Temporal cancellation. The\n * current owner or control transaction already holds authoritative state, so\n * the losing activity must stop locally without asking the workflow to settle\n * or fail the turn again.\n */\nexport class TurnAttemptFencedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"TurnAttemptFencedError\";\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport {\n AttemptToolApprovalRequiredError,\n AttemptToolCatalogStaleError,\n AttemptToolNotFoundError,\n codemodeDispatchSubject,\n decodeCodemodeDispatchRequest,\n encodeCodemodeDispatchAck,\n type AttemptToolEnvironment,\n} from \"@opengeni/codemode\";\nimport {\n CODEMODE_CLAIM_HEARTBEAT_MS,\n CODEMODE_MAX_CONCURRENT_CALLS_PER_ATTEMPT,\n type CodemodeOperation,\n} from \"@opengeni/contracts\";\nimport {\n cancelQueuedCodemodeOperationsForAttempt,\n claimCodemodeOperation,\n failCodemodeOperation,\n markCodemodeOperationExecutionStarted,\n renewCodemodeOperationClaim,\n settleCodemodeOperationWithOutput,\n type Database,\n} from \"@opengeni/db\";\nimport {\n appendAndPublishTurnEventsFenced,\n publishDurableSessionEvents,\n type EventBus,\n} from \"@opengeni/events\";\n\nexport type CodemodeDispatcherScope = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n};\n\n/**\n * Owns the only Codemode execution edge for one exact attempt. NATS carries a\n * wake-up only; the durable row is claimed before any side effect and the call\n * is executed by the same AttemptToolEnvironment already bound to model MCP.\n */\nexport class CodemodeAttemptDispatcher {\n private readonly stopController = new AbortController();\n private readonly inFlight = new Map<string, Promise<void>>();\n private pendingClaims = 0;\n private unsubscribe: (() => void) | null = null;\n private closing = false;\n\n constructor(\n private readonly db: Database,\n private readonly bus: EventBus,\n private readonly environment: AttemptToolEnvironment,\n private readonly scope: CodemodeDispatcherScope,\n private readonly turnSignal?: AbortSignal,\n private readonly maxConcurrentCalls = CODEMODE_MAX_CONCURRENT_CALLS_PER_ATTEMPT,\n ) {\n if (\n environment.catalog.accountId !== scope.accountId ||\n environment.catalog.workspaceId !== scope.workspaceId ||\n environment.catalog.sessionId !== scope.sessionId ||\n environment.catalog.turnId !== scope.turnId ||\n environment.catalog.attemptId !== scope.attemptId ||\n environment.catalog.executionGeneration !== scope.executionGeneration\n ) {\n throw new Error(\"Codemode dispatcher scope does not match its tool environment\");\n }\n if (!Number.isSafeInteger(maxConcurrentCalls) || maxConcurrentCalls < 1) {\n throw new Error(\"Codemode dispatcher concurrency must be a positive safe integer\");\n }\n }\n\n start(): void {\n if (this.unsubscribe || this.closing)\n throw new Error(\"Codemode dispatcher cannot be restarted\");\n this.unsubscribe = this.bus.subscribeRequests(\n codemodeDispatchSubject(this.scope.workspaceId, this.scope.attemptId),\n async (payload) => {\n const request = decodeCodemodeDispatchRequest(payload);\n if (request.catalogDigest !== this.environment.catalog.digest || this.closing) {\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: \"rejected\",\n });\n }\n if (\n !this.inFlight.has(request.operationId) &&\n this.inFlight.size + this.pendingClaims >= this.maxConcurrentCalls\n ) {\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: \"unavailable\",\n });\n }\n this.pendingClaims += 1;\n try {\n const claim = await claimCodemodeOperation(this.db, {\n ...this.scope,\n catalogDigest: request.catalogDigest,\n operationId: request.operationId,\n claimId: randomUUID(),\n });\n if (claim.status === \"claimed\") {\n const execution = this.execute(claim.operation, claim.claimId).finally(() => {\n this.inFlight.delete(request.operationId);\n });\n this.inFlight.set(request.operationId, execution);\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: \"accepted\",\n });\n }\n return encodeCodemodeDispatchAck({\n version: 1,\n operationId: request.operationId,\n status: claim.status,\n });\n } finally {\n this.pendingClaims -= 1;\n }\n },\n );\n }\n\n async close(reason = \"Execution attempt ended\"): Promise<void> {\n if (this.closing) {\n await Promise.allSettled([...this.inFlight.values()]);\n return;\n }\n this.closing = true;\n this.unsubscribe?.();\n this.unsubscribe = null;\n this.stopController.abort(reason);\n await cancelQueuedCodemodeOperationsForAttempt(this.db, {\n accountId: this.scope.accountId,\n workspaceId: this.scope.workspaceId,\n attemptId: this.scope.attemptId,\n reason,\n });\n await Promise.allSettled([...this.inFlight.values()]);\n }\n\n private async execute(operation: CodemodeOperation, claimId: string): Promise<void> {\n const entry = this.environment.catalog.entries.find(\n (candidate) =>\n candidate.identity.serverId === operation.identity.serverId &&\n candidate.identity.toolName === operation.identity.toolName,\n );\n if (!entry) {\n await this.failBeforeExecution(\n operation.operationId,\n claimId,\n \"tool_not_found\",\n \"Tool left the active catalog\",\n );\n return;\n }\n const signal = combinedSignal(this.stopController.signal, this.turnSignal);\n if (signal.aborted) {\n await this.failBeforeExecution(\n operation.operationId,\n claimId,\n \"attempt_cancelled\",\n \"Execution attempt ended before the Codemode call started\",\n );\n return;\n }\n const created = await appendAndPublishTurnEventsFenced(\n this.db,\n this.bus,\n this.scope.workspaceId,\n this.scope.sessionId,\n this.scope.turnId,\n this.scope.executionGeneration,\n this.scope.attemptId,\n [\n {\n type: \"agent.toolCall.created\",\n turnId: this.scope.turnId,\n turnGeneration: this.scope.executionGeneration,\n turnAttemptId: this.scope.attemptId,\n producerId: operation.caller.subjectId,\n payload: {\n id: operation.operationId,\n name: entry.modelName,\n arguments: operation.arguments,\n origin: \"codemode\",\n subjectId: operation.caller.subjectId,\n raw: {\n type: \"codemode_call\",\n serverId: operation.identity.serverId,\n toolName: operation.identity.toolName,\n catalogDigest: operation.catalogDigest,\n },\n },\n },\n ],\n ).catch(() => ({ accepted: false }));\n if (!created.accepted) {\n await this.failBeforeExecution(\n operation.operationId,\n claimId,\n \"attempt_fence_closed\",\n \"Execution attempt ended before the Codemode call started\",\n );\n return;\n }\n if (signal.aborted) {\n await this.settleWithOutput(operation, claimId, {\n state: \"failed\",\n errorCode: \"attempt_cancelled\",\n errorMessage: \"Execution attempt ended before the Codemode call started\",\n });\n return;\n }\n\n const claimAuthority = {\n accountId: this.scope.accountId,\n workspaceId: this.scope.workspaceId,\n attemptId: this.scope.attemptId,\n operationId: operation.operationId,\n claimId,\n };\n const crossedExecutionBoundary = await markCodemodeOperationExecutionStarted(\n this.db,\n claimAuthority,\n );\n if (!crossedExecutionBoundary) return;\n const heartbeat = setInterval(() => {\n void renewCodemodeOperationClaim(this.db, claimAuthority).catch(() => undefined);\n }, CODEMODE_CLAIM_HEARTBEAT_MS);\n heartbeat.unref?.();\n try {\n const result = await this.environment.call(\n {\n operationId: operation.operationId,\n catalogDigest: operation.catalogDigest,\n identity: operation.identity,\n arguments: operation.arguments,\n caller: operation.caller,\n },\n { signal },\n );\n await this.settleWithOutput(operation, claimId, { state: \"completed\", result });\n } catch (error) {\n const knownPreExecution =\n error instanceof AttemptToolApprovalRequiredError ||\n error instanceof AttemptToolCatalogStaleError ||\n error instanceof AttemptToolNotFoundError;\n await this.settleWithOutput(operation, claimId, {\n state: knownPreExecution ? \"failed\" : \"outcome_unknown\",\n errorCode: errorCode(error, signal),\n errorMessage: !knownPreExecution\n ? \"Tool execution ended without a durable result. Its side-effect outcome is unknown; inspect actual state before retrying.\"\n : safeErrorMessage(error),\n });\n } finally {\n clearInterval(heartbeat);\n }\n }\n\n private async settleWithOutput(\n operation: CodemodeOperation,\n claimId: string,\n settlement:\n | { state: \"completed\"; result: NonNullable<CodemodeOperation[\"result\"]> }\n | {\n state: \"failed\" | \"outcome_unknown\";\n errorCode: string;\n errorMessage: string;\n },\n ): Promise<void> {\n const result = await settleCodemodeOperationWithOutput(this.db, {\n ...this.scope,\n operationId: operation.operationId,\n claimId,\n producerId: operation.caller.subjectId,\n settlement,\n });\n if (!result.committed || result.events.length === 0) return;\n await publishDurableSessionEvents(\n this.bus,\n this.scope.workspaceId,\n this.scope.sessionId,\n result.events,\n );\n }\n\n private async failBeforeExecution(\n operationId: string,\n claimId: string,\n failureCode: string,\n failureMessage: string,\n ): Promise<void> {\n await failCodemodeOperation(this.db, {\n accountId: this.scope.accountId,\n workspaceId: this.scope.workspaceId,\n attemptId: this.scope.attemptId,\n operationId,\n claimId,\n state: \"failed\",\n errorCode: failureCode,\n errorMessage: failureMessage,\n });\n }\n}\n\nfunction combinedSignal(primary: AbortSignal, secondary?: AbortSignal): AbortSignal {\n return secondary ? AbortSignal.any([primary, secondary]) : primary;\n}\n\nfunction errorCode(error: unknown, signal: AbortSignal): string {\n if (signal.aborted) return \"attempt_cancelled_during_execution\";\n if (typeof error === \"object\" && error !== null && \"code\" in error) {\n const code = (error as { code?: unknown }).code;\n if (typeof code === \"string\" && /^[a-z0-9_]{1,128}$/u.test(code)) return code;\n }\n return \"tool_outcome_unknown\";\n}\n\nfunction safeErrorMessage(error: unknown): string {\n if (\n error instanceof AttemptToolApprovalRequiredError ||\n error instanceof AttemptToolCatalogStaleError ||\n error instanceof AttemptToolNotFoundError\n ) {\n return error.message;\n }\n return \"Codemode call failed before tool execution\";\n}\n","// db-backed Codex token lifecycle for a turn: proactive refresh, single-flight\n// per credential instance, and permanent-failure status surfacing.\n//\n// The implementation now lives in @opengeni/db (packages/db/src/codex-token-resolver.ts)\n// so the API process can drive the SAME refreshing resolver for the P2 /wham/usage\n// quota-bar reads without duplicating the refresh-CAS / single-flight / RLS logic.\n// This module re-exports it for back-compat, keeping the agent-turn.ts call site\n// (buildCodexTokenResolver) unchanged.\nexport { buildCodexTokenResolver, type CodexAuthDeps } from \"@opengeni/db\";\n","import { environmentsEncryptionKeyBytes, type Settings } from \"@opengeni/config\";\nimport {\n materializeXaiCredentialForRun,\n refreshXaiSubscriptionCredentialSerialized,\n type Database,\n} from \"@opengeni/db\";\nimport type { XaiProviderAccountAuthoritySnapshotV1 } from \"@opengeni/contracts\";\nimport {\n refreshXaiToken,\n XAI_CLIENT_VERSION,\n XAI_SUBSCRIPTION_MODEL_ID_PREFIX,\n XaiSubscriptionReloginRequired,\n xaiAccessTokenExpiry,\n type XaiFetch,\n type XaiSubscriptionRequestContext,\n type XaiSubscriptionTokenSnapshot,\n} from \"@opengeni/xai-subscription\";\n\nexport type XaiTurnRequestAuthorization = {\n context: XaiSubscriptionRequestContext;\n credentialId: string;\n};\n\nexport async function buildXaiTurnRequestAuthorization(input: {\n db: Database;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n subjectId: string;\n sessionId: string;\n turnId: string;\n credentialId: string;\n authoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;\n fetch?: XaiFetch;\n hostedSearch?: XaiSubscriptionRequestContext[\"hostedSearch\"];\n onFinalContextUsage?: XaiSubscriptionRequestContext[\"onFinalContextUsage\"];\n nextRequestId?: XaiSubscriptionRequestContext[\"nextRequestId\"];\n}): Promise<XaiTurnRequestAuthorization> {\n const encryptionKey = environmentsEncryptionKeyBytes(input.settings);\n if (!encryptionKey) {\n throw new Error(\"SuperGrok subscriptions require OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n let credential = await materializeXaiCredentialForRun(input.db, {\n workspaceId: input.workspaceId,\n subjectId: input.subjectId,\n credentialId: input.credentialId,\n authoritySnapshot: input.authoritySnapshot,\n encryptionKey,\n });\n\n const tokenSnapshot = (): XaiSubscriptionTokenSnapshot => {\n const accessToken = credential.secret.accessToken;\n const userId = credential.providerAccountId;\n if (!accessToken || !userId) {\n throw new XaiSubscriptionReloginRequired(\n \"The SuperGrok connection is missing a verified token identity. Reconnect the account.\",\n );\n }\n return { accessToken, userId };\n };\n\n const refresh = async (): Promise<XaiSubscriptionTokenSnapshot> => {\n const observedAccessToken = credential.secret.accessToken;\n const observedRefreshToken = credential.secret.refreshToken;\n if (!observedRefreshToken) {\n throw new XaiSubscriptionReloginRequired(\n \"The SuperGrok connection cannot be refreshed. Reconnect the account.\",\n );\n }\n const result = await refreshXaiSubscriptionCredentialSerialized(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n subjectId: input.subjectId,\n credentialId: input.credentialId,\n authoritySnapshot: input.authoritySnapshot,\n encryptionKey,\n observedAccessToken,\n observedRefreshToken,\n refresh: async (current) => {\n const refreshToken = current.secret.refreshToken;\n if (!refreshToken) {\n throw new XaiSubscriptionReloginRequired(\n \"The SuperGrok connection cannot be refreshed. Reconnect the account.\",\n );\n }\n const tokens = await refreshXaiToken(refreshToken, {\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n return {\n secret: {\n version: 1,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n },\n expiresAt:\n xaiAccessTokenExpiry(tokens.accessToken) ??\n new Date(Date.now() + tokens.expiresInSeconds * 1_000),\n };\n },\n });\n credential = result.credential;\n return tokenSnapshot();\n };\n\n return {\n credentialId: input.credentialId,\n context: {\n clientVersion: XAI_CLIENT_VERSION,\n sessionId: input.sessionId,\n turnId: input.turnId,\n getToken: async () => tokenSnapshot(),\n refresh,\n resolveModel: (model) =>\n model.startsWith(XAI_SUBSCRIPTION_MODEL_ID_PREFIX)\n ? model.slice(XAI_SUBSCRIPTION_MODEL_ID_PREFIX.length)\n : model,\n ...(input.hostedSearch ? { hostedSearch: input.hostedSearch } : {}),\n ...(input.onFinalContextUsage ? { onFinalContextUsage: input.onFinalContextUsage } : {}),\n ...(input.nextRequestId ? { nextRequestId: input.nextRequestId } : {}),\n },\n };\n}\n","import {\n generateXaiSubscriptionImage,\n XAI_IMAGE_MODEL,\n XAI_SUBSCRIPTION_PROVIDER_ID,\n type XaiSubscriptionRequestContext,\n} from \"@opengeni/xai-subscription\";\nimport type { Database } from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { GeneratedImageReceipt } from \"./generated-images\";\nimport {\n executeImageGenerationOperation,\n imageProviderBindingHash,\n} from \"./image-generation-operation\";\nimport type { ResolvedImageGenerationReference } from \"./image-generation-references\";\n\nexport type XaiImageGenerationPorts = {\n execute: typeof executeImageGenerationOperation;\n generate: typeof generateXaiSubscriptionImage;\n};\n\nconst xaiImageGenerationPorts: XaiImageGenerationPorts = {\n execute: executeImageGenerationOperation,\n generate: generateXaiSubscriptionImage,\n};\n\n/** Execute xAI's standalone subscription image path under the durable paid-operation fence. */\nexport async function executeXaiSubscriptionImageGeneration(\n input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n prompt: string;\n references?: readonly ResolvedImageGenerationReference[];\n credentialId: string;\n xaiContext: Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\">;\n abortSignal?: AbortSignal;\n },\n ports: XaiImageGenerationPorts = xaiImageGenerationPorts,\n): Promise<GeneratedImageReceipt> {\n const providerBindingHash = imageProviderBindingHash(\n XAI_SUBSCRIPTION_PROVIDER_ID,\n input.credentialId,\n );\n return await ports.execute({\n db: input.db,\n objectStorage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n toolCallId: input.toolCallId,\n prompt: input.prompt,\n providerId: XAI_SUBSCRIPTION_PROVIDER_ID,\n providerBindingHash,\n modelId: XAI_IMAGE_MODEL,\n generate: async () => {\n const generated = await ports.generate({\n prompt: input.prompt,\n sessionId: input.sessionId,\n ...(input.references?.length\n ? {\n references: input.references.map((reference) => ({\n mediaType: reference.mediaType,\n bytes: reference.bytes,\n })),\n }\n : {}),\n getToken: input.xaiContext.getToken,\n refresh: input.xaiContext.refresh,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n return {\n toolCallId: input.toolCallId,\n providerItemId: null,\n bytes: generated.bytes,\n declaredMediaType: generated.declaredMediaType,\n };\n },\n });\n}\n","import {\n beginImageGenerationOperation,\n completeImageGenerationOperation,\n getGeneratedImageArtifact,\n markImageGenerationOperationOutcomeUnknown,\n markImageGenerationOperationRetentionFailed,\n prepareImageGenerationOperation,\n type Database,\n type ImageGenerationOperationStatus,\n} from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { createHash } from \"node:crypto\";\nimport {\n generatedImageIdentity,\n recoverGeneratedImageArtifact,\n retainGeneratedImage,\n retainedGeneratedImageFromArtifact,\n verifyReadyGeneratedImageArtifact,\n type GeneratedImageOutput,\n type GeneratedImageReceipt,\n} from \"./generated-images\";\n\nexport class ImageGenerationOutcomeUnknownError extends Error {\n constructor(readonly operationId: string) {\n super(\n \"The image provider request may have completed, but no durable result was recovered. It was not retried to avoid duplicate work or charges.\",\n );\n this.name = \"ImageGenerationOutcomeUnknownError\";\n }\n}\n\nexport class ImageGenerationRetentionFailedError extends Error {\n constructor(\n readonly operationId: string,\n cause?: unknown,\n ) {\n super(\n \"The image was generated, but OpenGeni could not save it. The paid provider request was not repeated.\",\n cause === undefined ? undefined : { cause },\n );\n this.name = \"ImageGenerationRetentionFailedError\";\n }\n}\n\nexport type ImageGenerationOperationPorts = {\n prepare: typeof prepareImageGenerationOperation;\n begin: typeof beginImageGenerationOperation;\n retain: typeof retainGeneratedImage;\n complete: typeof completeImageGenerationOperation;\n markOutcomeUnknown: typeof markImageGenerationOperationOutcomeUnknown;\n markRetentionFailed: typeof markImageGenerationOperationRetentionFailed;\n recover: typeof recoverCompletedImage;\n};\n\nconst imageGenerationOperationPorts: ImageGenerationOperationPorts = {\n prepare: prepareImageGenerationOperation,\n begin: beginImageGenerationOperation,\n retain: retainGeneratedImage,\n complete: completeImageGenerationOperation,\n markOutcomeUnknown: markImageGenerationOperationOutcomeUnknown,\n markRetentionFailed: markImageGenerationOperationRetentionFailed,\n recover: recoverCompletedImage,\n};\n\n/**\n * Durable admission fence shared by every client-executed image provider.\n * Provider execution is permitted at most once after the prepared ->\n * provider_started transition. A crash at that boundary may conservatively\n * leave the outcome unknown; a retry may recover a ready artifact, but never\n * blindly replays the paid operation.\n */\nexport type ExecuteImageGenerationOperationInput = {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n providerId: string;\n providerBindingHash: string;\n modelId: string;\n prompt: string;\n referenceDigests?: readonly Readonly<{ mediaType: string; sha256: string }>[];\n generate: () => Promise<GeneratedImageOutput>;\n};\n\nexport async function executeImageGenerationOperation(\n input: ExecuteImageGenerationOperationInput,\n ports: ImageGenerationOperationPorts = imageGenerationOperationPorts,\n): Promise<GeneratedImageReceipt> {\n const identity = imageGenerationOperationIdentity({\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n modelId: input.modelId,\n prompt: input.prompt,\n ...(input.referenceDigests ? { referenceDigests: input.referenceDigests } : {}),\n toolCallId: input.toolCallId,\n });\n const prepared = await ports.prepare(input.db, {\n id: identity.operationId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n operationKey: identity.operationKey,\n toolCallId: input.toolCallId,\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n modelId: input.modelId,\n requestDigest: identity.requestDigest,\n expectedArtifactId: identity.artifactId,\n });\n\n if (prepared.operation.status !== \"prepared\") {\n const recovered = await ports.recover(input, {\n artifactId: identity.artifactId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n if (recovered) return recovered;\n throw unrecoveredOperationError(prepared.operation.status, identity.operationId);\n }\n\n const begun = await ports.begin(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n if (!begun.started || begun.operation.status !== \"provider_started\") {\n const recovered = await ports.recover(input, {\n artifactId: identity.artifactId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n if (recovered) return recovered;\n throw unrecoveredOperationError(begun.operation.status, identity.operationId);\n }\n\n let output: GeneratedImageOutput;\n try {\n output = await input.generate();\n } catch (error) {\n await ports\n .markOutcomeUnknown(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n error: error instanceof Error ? error.message : String(error),\n })\n .catch(() => undefined);\n throw error;\n }\n\n try {\n if (output.toolCallId !== input.toolCallId || output.providerItemId !== null) {\n throw new Error(\"Client image provider returned a mismatched operation identity\");\n }\n const retained = await ports.retain({\n db: input.db,\n objectStorage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n sourceStrategy: \"provider_adapter\",\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n output,\n });\n await ports.complete(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n return retained.receipt;\n } catch (error) {\n await ports\n .markRetentionFailed(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n error: error instanceof Error ? error.message : String(error),\n })\n .catch(() => undefined);\n throw new ImageGenerationRetentionFailedError(identity.operationId, error);\n }\n}\n\nfunction unrecoveredOperationError(\n status: ImageGenerationOperationStatus,\n operationId: string,\n): Error {\n return status === \"retention_failed\"\n ? new ImageGenerationRetentionFailedError(operationId)\n : new ImageGenerationOutcomeUnknownError(operationId);\n}\n\nexport function imageProviderBindingHash(providerId: string, credentialIdentity: string): string {\n if (!providerId.trim() || !credentialIdentity.trim()) {\n throw new Error(\"Image provider binding identity is empty\");\n }\n return digest(\"opengeni:image-provider-binding:v1\\0\", providerId, credentialIdentity);\n}\n\n/** Stable across worker/Temporal attempt retries; the attempt id is provenance, not identity. */\nexport function imageGenerationOperationIdentity(input: {\n workspaceId: string;\n sessionId: string;\n turnId: string;\n toolCallId: string;\n providerId: string;\n providerBindingHash: string;\n modelId: string;\n prompt: string;\n referenceDigests?: readonly Readonly<{ mediaType: string; sha256: string }>[];\n}): {\n operationId: string;\n operationKey: string;\n requestDigest: string;\n artifactId: string;\n} {\n const referenceDigests = input.referenceDigests ?? [];\n const requestDigest =\n referenceDigests.length === 0\n ? digest(\"opengeni:image-generation-request:v1\\0\", input.modelId, input.prompt)\n : digest(\n \"opengeni:image-generation-request:v2\\0\",\n input.modelId,\n input.prompt,\n ...referenceDigests.flatMap((reference) => [reference.mediaType, reference.sha256]),\n );\n const operationKey = digest(\n \"opengeni:image-generation-operation:v2\\0\",\n input.workspaceId,\n input.sessionId,\n input.turnId,\n input.toolCallId,\n );\n const artifact = generatedImageIdentity({\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n sourceStrategy: \"provider_adapter\",\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n providerItemId: null,\n toolCallId: input.toolCallId,\n });\n return {\n operationId: uuidFromDigest(operationKey),\n operationKey,\n requestDigest,\n artifactId: artifact.artifactId,\n };\n}\n\nasync function recoverCompletedImage(\n input: Pick<\n Parameters<typeof executeImageGenerationOperation>[0],\n | \"db\"\n | \"objectStorage\"\n | \"accountId\"\n | \"workspaceId\"\n | \"sessionId\"\n | \"turnId\"\n | \"toolCallId\"\n | \"providerId\"\n | \"providerBindingHash\"\n >,\n identity: { artifactId: string; operationId: string; operationKey: string },\n): Promise<GeneratedImageReceipt | null> {\n const artifact = await getGeneratedImageArtifact(\n input.db,\n input.workspaceId,\n identity.artifactId,\n );\n if (!artifact) return null;\n if (\n artifact.sourceStrategy !== \"provider_adapter\" ||\n artifact.sessionId !== input.sessionId ||\n artifact.turnId !== input.turnId ||\n artifact.toolCallId !== input.toolCallId ||\n artifact.providerId !== input.providerId ||\n artifact.providerBindingHash !== input.providerBindingHash ||\n artifact.providerItemId !== null\n ) {\n throw new Error(\"Recovered generated image does not match its provider operation\");\n }\n if (!input.objectStorage) {\n throw new Error(\"Recovered generated image requires configured object storage\");\n }\n const recovered = await recoverGeneratedImageArtifact({\n db: input.db,\n storage: input.objectStorage,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifact,\n });\n if (!recovered) return null;\n await verifyReadyGeneratedImageArtifact(input.objectStorage, recovered);\n await completeImageGenerationOperation(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: identity.operationId,\n operationKey: identity.operationKey,\n });\n return retainedGeneratedImageFromArtifact(recovered).receipt;\n}\n\nfunction digest(prefix: string, ...values: string[]): string {\n const hash = createHash(\"sha256\").update(prefix);\n for (const value of values) hash.update(value).update(\"\\0\");\n return hash.digest(\"hex\");\n}\n\nfunction uuidFromDigest(digestValue: string): string {\n const bytes = Uint8Array.from(Buffer.from(digestValue.slice(0, 32), \"hex\"));\n bytes[6] = (bytes[6]! & 0x0f) | 0x80;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n","import {\n COMPUTER_SCREENSHOT_MAX_DIMENSION,\n COMPUTER_SCREENSHOT_MAX_PIXELS,\n GENERATED_IMAGE_MAX_BYTES,\n GeneratedImageReceiptSchema,\n retainedGeneratedImageReferenceFromFile,\n type GeneratedImageReceipt,\n} from \"@opengeni/contracts\";\nimport {\n completeFileUpload,\n prepareGeneratedImageArtifact,\n recordGeneratedImageArtifactError,\n settleGeneratedImageArtifactReady,\n type Database,\n type GeneratedImageArtifact,\n type GeneratedImageSourceStrategy,\n} from \"@opengeni/db\";\nimport type { ObjectHead, ObjectStorage } from \"@opengeni/storage\";\nimport { createHash } from \"node:crypto\";\nimport { ScreenshotValidationError, validateRetainableSessionImage } from \"./retained-screenshots\";\n\nconst GENERATED_IMAGE_MARKER = \"generated_image\";\nconst UPLOAD_INTENT_TTL_MS = 60 * 60_000;\n\nexport type GeneratedImageMediaType = \"image/png\" | \"image/jpeg\" | \"image/webp\";\n\nexport type ValidatedGeneratedImage = {\n bytes: Uint8Array;\n mediaType: GeneratedImageMediaType;\n extension: \"png\" | \"jpg\" | \"webp\";\n sizeBytes: number;\n sha256: string;\n width: number;\n height: number;\n};\n\nexport type GeneratedImageOutput = {\n toolCallId: string;\n providerItemId: string | null;\n bytes: Uint8Array;\n declaredMediaType?: string;\n};\n\nexport type { GeneratedImageReceipt };\n\nexport type RetainedGeneratedImage = {\n receipt: GeneratedImageReceipt;\n artifact: GeneratedImageArtifact;\n};\n\nexport class GeneratedImageValidationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GeneratedImageValidationError\";\n }\n}\n\n/** Extract the completed Responses hosted-tool payload before JSON serialization. */\nexport function generatedImageFromSdkEvent(event: unknown): GeneratedImageOutput | null {\n if (!event || typeof event !== \"object\") return null;\n const streamEvent = event as {\n type?: unknown;\n item?: { type?: unknown; rawItem?: unknown; id?: unknown };\n };\n if (streamEvent.type !== \"run_item_stream_event\") return null;\n const item = streamEvent.item;\n if (!item || item.type !== \"tool_call_item\") return null;\n if (!item.rawItem || typeof item.rawItem !== \"object\" || Array.isArray(item.rawItem)) return null;\n const raw = item.rawItem as Record<string, unknown>;\n if (\n raw.type !== \"hosted_tool_call\" ||\n raw.name !== \"image_generation_call\" ||\n raw.status !== \"completed\"\n ) {\n return null;\n }\n const providerData =\n raw.providerData && typeof raw.providerData === \"object\" && !Array.isArray(raw.providerData)\n ? (raw.providerData as Record<string, unknown>)\n : null;\n const encoded =\n typeof raw.output === \"string\"\n ? raw.output\n : typeof providerData?.result === \"string\"\n ? providerData.result\n : null;\n if (!encoded) return null;\n const providerItemId = raw.id ?? providerData?.id ?? item.id;\n const toolCallId = providerItemId;\n if (typeof toolCallId !== \"string\" || toolCallId.length === 0) return null;\n return {\n toolCallId,\n providerItemId: typeof providerItemId === \"string\" ? providerItemId : null,\n bytes: decodeGeneratedImageBase64(encoded),\n };\n}\n\n/** Classify the native terminal item independently from its current payload shape. */\nexport function isCompletedGeneratedImageSdkEvent(event: unknown): boolean {\n if (!isRecord(event) || event.type !== \"run_item_stream_event\") return false;\n const item = event.item;\n if (!isRecord(item) || item.type !== \"tool_call_item\" || !isRecord(item.rawItem)) return false;\n return (\n item.rawItem.type === \"hosted_tool_call\" &&\n item.rawItem.name === \"image_generation_call\" &&\n item.rawItem.status === \"completed\"\n );\n}\n\nexport function generatedImagesFromHistory(\n history: ReadonlyArray<Record<string, unknown>>,\n retainedProviderItems?: Pick<ReadonlyMap<string, unknown>, \"has\">,\n): GeneratedImageOutput[] {\n const outputs: GeneratedImageOutput[] = [];\n for (const item of history) {\n if (\n item.type !== \"hosted_tool_call\" ||\n item.name !== \"image_generation_call\" ||\n item.status !== \"completed\" ||\n typeof item.id !== \"string\" ||\n (typeof item.output !== \"string\" &&\n !(\n item.providerData &&\n typeof item.providerData === \"object\" &&\n !Array.isArray(item.providerData) &&\n typeof (item.providerData as Record<string, unknown>).result === \"string\"\n ))\n ) {\n continue;\n }\n if (retainedProviderItems?.has(item.id)) continue;\n if (generatedImageReceiptFromUnknown(item.output)) continue;\n outputs.push({\n toolCallId: item.id,\n providerItemId: item.id,\n bytes: decodeGeneratedImageBase64(\n typeof item.output === \"string\"\n ? item.output\n : ((item.providerData as Record<string, unknown>).result as string),\n ),\n });\n }\n return outputs;\n}\n\n/** Refuse to serialize a completed native item unless its bytes have a receipt. */\nexport function assertGeneratedImageHistoryRetained(\n history: ReadonlyArray<Record<string, unknown>>,\n receiptsByProviderItemId: Pick<ReadonlyMap<string, unknown>, \"has\">,\n): void {\n for (const item of history) {\n if (\n item.type !== \"hosted_tool_call\" ||\n item.name !== \"image_generation_call\" ||\n item.status !== \"completed\"\n ) {\n continue;\n }\n if (\n typeof item.id !== \"string\" ||\n (!receiptsByProviderItemId.has(item.id) && !generatedImageReceiptFromUnknown(item.output))\n ) {\n throw new Error(\"Completed native image history has no retained-artifact receipt\");\n }\n }\n}\n\nexport function decodeGeneratedImageBase64(value: string): Uint8Array {\n if (value.length === 0 || value.length % 4 !== 0) {\n throw new GeneratedImageValidationError(\"generated image base64 has invalid length\");\n }\n const padding = value.endsWith(\"==\") ? 2 : value.endsWith(\"=\") ? 1 : 0;\n const decodedBytes = (value.length / 4) * 3 - padding;\n if (decodedBytes <= 0 || decodedBytes > GENERATED_IMAGE_MAX_BYTES) {\n throw new GeneratedImageValidationError(\"generated image exceeds the byte limit\");\n }\n if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {\n throw new GeneratedImageValidationError(\"generated image base64 is malformed\");\n }\n const lastSextet = base64Sextet(value.charCodeAt(value.length - padding - 1));\n if (\n (padding === 2 && (lastSextet & 0x0f) !== 0) ||\n (padding === 1 && (lastSextet & 0x03) !== 0)\n ) {\n throw new GeneratedImageValidationError(\"generated image base64 is non-canonical\");\n }\n const bytes = Buffer.from(value, \"base64\");\n if (bytes.byteLength !== decodedBytes) {\n throw new GeneratedImageValidationError(\"generated image base64 is non-canonical\");\n }\n return bytes;\n}\n\n/** Validate signatures and dimensions; never trust provider-declared MIME metadata. */\nexport function validateGeneratedImage(input: {\n bytes: Uint8Array;\n declaredMediaType?: string;\n}): ValidatedGeneratedImage {\n try {\n return validateRetainableSessionImage(\n {\n bytes: input.bytes,\n ...(input.declaredMediaType ? { declaredMediaType: input.declaredMediaType } : {}),\n },\n {\n maxBytes: GENERATED_IMAGE_MAX_BYTES,\n maxDimension: COMPUTER_SCREENSHOT_MAX_DIMENSION,\n maxPixels: COMPUTER_SCREENSHOT_MAX_PIXELS,\n },\n );\n } catch (error) {\n if (error instanceof ScreenshotValidationError) {\n throw new GeneratedImageValidationError(error.message);\n }\n throw error;\n }\n}\n\ntype GeneratedImageIdentityInput = {\n workspaceId: string;\n sessionId: string;\n turnId: string;\n providerId: string;\n providerBindingHash: string;\n toolCallId: string;\n} & (\n | { sourceStrategy: \"native_hosted\"; providerItemId: string }\n | { sourceStrategy: \"provider_adapter\"; providerItemId: null }\n);\n\nexport function generatedImageIdentity(input: GeneratedImageIdentityInput): {\n artifactId: string;\n uploadId: string;\n settlementKey: string;\n} {\n const hash = createHash(\"sha256\")\n .update(\"opengeni:generated-image:v2\\0\")\n .update(input.workspaceId)\n .update(\"\\0\")\n .update(input.sourceStrategy)\n .update(\"\\0\")\n .update(input.providerId)\n .update(\"\\0\")\n .update(input.providerBindingHash)\n .update(\"\\0\");\n if (input.sourceStrategy === \"native_hosted\") {\n hash.update(input.providerItemId);\n } else {\n hash\n .update(input.sessionId)\n .update(\"\\0\")\n .update(input.turnId)\n .update(\"\\0\")\n .update(input.toolCallId);\n }\n const settlementKey = hash.digest(\"hex\");\n return {\n settlementKey,\n artifactId: uuidFromDigest(settlementKey, 0),\n uploadId: uuidFromDigest(settlementKey, 16),\n };\n}\n\nexport async function retainGeneratedImage(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n sourceStrategy: GeneratedImageSourceStrategy;\n providerId: string;\n providerBindingHash: string;\n output: GeneratedImageOutput;\n now?: Date;\n}): Promise<RetainedGeneratedImage> {\n if (!input.objectStorage) {\n throw new Error(\"Generated image retention requires configured object storage\");\n }\n const image = validateGeneratedImage(input.output);\n const identityInput = {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n toolCallId: input.output.toolCallId,\n };\n let identity: ReturnType<typeof generatedImageIdentity>;\n if (input.sourceStrategy === \"native_hosted\") {\n if (!input.output.providerItemId) {\n throw new Error(\"Native generated image has no provider item identity\");\n }\n identity = generatedImageIdentity({\n ...identityInput,\n sourceStrategy: \"native_hosted\",\n providerItemId: input.output.providerItemId,\n });\n } else {\n if (input.output.providerItemId !== null) {\n throw new Error(\"Adapter-generated image cannot carry a native provider item identity\");\n }\n identity = generatedImageIdentity({\n ...identityInput,\n sourceStrategy: \"provider_adapter\",\n providerItemId: null,\n });\n }\n const filename = `generated-image-${identity.artifactId}.${image.extension}`;\n const sandboxPath = `/workspace/generated-images/${filename}`;\n const objectKey = `workspaces/${input.workspaceId}/files/${identity.artifactId}/generated/${filename}`;\n const prepared = await prepareGeneratedImageArtifact(input.db, {\n artifactId: identity.artifactId,\n uploadId: identity.uploadId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n settlementKey: identity.settlementKey,\n toolCallId: input.output.toolCallId,\n sourceStrategy: input.sourceStrategy,\n providerId: input.providerId,\n providerBindingHash: input.providerBindingHash,\n providerItemId: input.output.providerItemId,\n mediaType: image.mediaType,\n sizeBytes: image.sizeBytes,\n sha256: image.sha256,\n width: image.width,\n height: image.height,\n sandboxPath,\n filename,\n safeFilename: filename,\n bucket: input.objectStorage.bucket,\n objectKey,\n uploadExpiresAt: new Date((input.now ?? new Date()).getTime() + UPLOAD_INTENT_TTL_MS),\n });\n\n if (prepared.artifact.status === \"ready\") {\n await verifyReadyGeneratedImage(input.objectStorage, prepared.artifact, image);\n return retainedGeneratedImageFromArtifact(prepared.artifact);\n }\n\n try {\n // A crash may leave the file complete while the correlation row is pending.\n // Verify and settle that state without rewriting the object.\n if (\n prepared.artifact.file.status !== \"ready\" ||\n prepared.artifact.uploadStatus !== \"completed\"\n ) {\n if (!(await input.objectStorage.fileExists(prepared.artifact.file))) {\n await input.objectStorage.putObject({\n key: objectKey,\n contentType: image.mediaType,\n body: image.bytes,\n sha256: image.sha256,\n });\n }\n assertStoredGeneratedImageHead(\n await input.objectStorage.headFile(prepared.artifact.file),\n image,\n );\n await completeFileUpload(input.db, input.workspaceId, identity.uploadId);\n } else {\n await verifyReadyGeneratedImage(input.objectStorage, prepared.artifact, image);\n }\n const settled = await settleGeneratedImageArtifactReady(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n });\n return retainedGeneratedImageFromArtifact(settled);\n } catch (error) {\n await recordGeneratedImageArtifactError(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n error: error instanceof Error ? error.message : String(error),\n }).catch(() => undefined);\n throw error;\n }\n}\n\n/** Replace provider bytes before they can enter event/history serialization. */\nexport function compactGeneratedImageHistory(\n history: Array<Record<string, unknown>>,\n receiptsByProviderItemId: ReadonlyMap<string, GeneratedImageReceipt>,\n): Array<Record<string, unknown>> {\n if (receiptsByProviderItemId.size === 0) return history;\n return history.map((item) => {\n if (item.type !== \"hosted_tool_call\" || item.name !== \"image_generation_call\") return item;\n const id = typeof item.id === \"string\" ? item.id : null;\n const receipt = id ? receiptsByProviderItemId.get(id) : undefined;\n if (!receipt) return item;\n const existingReceipt = generatedImageReceiptFromUnknown(item.output);\n const providerDataContainsBytes =\n isRecord(item.providerData) && typeof item.providerData.result === \"string\";\n if (\n existingReceipt?.artifact.artifactId === receipt.artifact.artifactId &&\n !providerDataContainsBytes\n ) {\n return item;\n }\n return {\n ...item,\n output: receipt,\n ...(item.providerData ? { providerData: withoutNativeImageResult(item.providerData) } : {}),\n };\n });\n}\n\nexport function compactGeneratedImageSdkEvent(\n event: unknown,\n receipt: GeneratedImageReceipt,\n): unknown {\n if (!event || typeof event !== \"object\") return event;\n const streamEvent = event as Record<string, unknown>;\n const item = streamEvent.item;\n if (!item || typeof item !== \"object\" || Array.isArray(item)) return event;\n const itemRecord = item as Record<string, unknown>;\n const raw = itemRecord.rawItem;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return event;\n const rawRecord = raw as Record<string, unknown>;\n if (rawRecord.type !== \"hosted_tool_call\" || rawRecord.name !== \"image_generation_call\") {\n return event;\n }\n return {\n ...streamEvent,\n item: {\n ...itemRecord,\n rawItem: {\n ...rawRecord,\n output: receipt,\n ...(rawRecord.providerData\n ? { providerData: withoutNativeImageResult(rawRecord.providerData) }\n : {}),\n },\n },\n };\n}\n\nexport function collectGeneratedImageReceipts(\n history: ReadonlyArray<Record<string, unknown>>,\n target: Map<string, GeneratedImageReceipt> = new Map(),\n): Map<string, GeneratedImageReceipt> {\n for (const item of history) {\n if (item.type !== \"hosted_tool_call\" || item.name !== \"image_generation_call\") continue;\n if (typeof item.id !== \"string\") continue;\n const receipt = generatedImageReceiptFromUnknown(item.output);\n if (receipt) target.set(item.id, receipt);\n }\n return target;\n}\n\nexport function collectGeneratedImageArtifactReceipts(\n history: ReadonlyArray<Record<string, unknown>>,\n target: Map<string, GeneratedImageReceipt> = new Map(),\n): Map<string, GeneratedImageReceipt> {\n for (const item of history) {\n const candidates = Array.isArray(item.output) ? item.output : [item.output];\n for (const candidate of candidates) {\n const receipt = generatedImageReceiptFromUnknown(candidate);\n if (receipt) target.set(receipt.artifact.artifactId, receipt);\n }\n }\n return target;\n}\n\n/**\n * Project native image calls to one provider-neutral, cache-stable model fact.\n * The canonical hosted-tool item remains available to the UI, but its provider\n * id and compact receipt are never replayed as a counterfeit native result.\n */\nexport function projectGeneratedImageHistoryForModel(\n history: Array<Record<string, unknown>>,\n): Array<Record<string, unknown>> {\n let changed = false;\n const projected: Array<Record<string, unknown>> = [];\n for (const item of history) {\n if (item.type !== \"hosted_tool_call\" || item.name !== \"image_generation_call\") {\n projected.push(item);\n continue;\n }\n const receipt = generatedImageReceiptFromUnknown(item.output);\n if (!receipt) {\n projected.push(item);\n continue;\n }\n changed = true;\n projected.push(generatedImageModelMessage(receipt, \"history\"));\n }\n return changed ? projected : history;\n}\n\n/**\n * Build the attempt-local RunState view consumed by the Agents SDK on resume.\n *\n * OpenAI serializes a hosted image call from `providerData.result`, not from\n * the SDK item's generic `output`. Our durable state deliberately replaces\n * those bytes with a compact receipt, so replaying the hosted item would send\n * a counterfeit `result: null`. Convert it to the same provider-neutral fact\n * used for ordinary history instead. Durable state is never modified.\n */\nexport function projectGeneratedImageRunStateForModel(serialized: string): string {\n const parsed = parseRunState(serialized);\n if (!parsed) return serialized;\n let changed = false;\n\n visitRunStateProtocolItems(parsed, (items) => {\n const projected = projectGeneratedImageRunStateItemsForModel(items);\n if (projected !== items) {\n items.splice(0, items.length, ...projected);\n changed = true;\n }\n });\n visitRunStateItemWrappers(parsed, (wrappers) => {\n for (let index = 0; index < wrappers.length; index += 1) {\n const projected = projectGeneratedImageRunItemWrapper(wrappers[index]!);\n if (projected !== wrappers[index]) {\n wrappers[index] = projected;\n changed = true;\n }\n }\n });\n\n return changed ? JSON.stringify(parsed) : serialized;\n}\n\nfunction projectGeneratedImageRunStateItemsForModel(\n items: Array<Record<string, unknown>>,\n): Array<Record<string, unknown>> {\n let changed = false;\n const projected = items.map((item) => {\n const receipt = generatedImageReceiptFromHostedItem(item);\n if (!receipt) return item;\n changed = true;\n return generatedImageModelMessage(receipt, \"run_state\");\n });\n return changed ? projected : items;\n}\n\nexport function compactGeneratedImageRunState(\n serialized: string,\n receiptsByProviderItemId: ReadonlyMap<string, GeneratedImageReceipt>,\n): string {\n if (receiptsByProviderItemId.size === 0) return serialized;\n let parsed: Record<string, unknown>;\n try {\n const value: unknown = JSON.parse(serialized);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return serialized;\n parsed = value as Record<string, unknown>;\n } catch {\n return serialized;\n }\n let changed = false;\n visitRunStateProtocolItems(parsed, (items) => {\n const compacted = compactGeneratedImageRunStateItems(items, receiptsByProviderItemId);\n if (compacted.some((item, index) => item !== items[index])) {\n items.splice(0, items.length, ...compacted);\n changed = true;\n }\n });\n visitRunStateItemWrappers(parsed, (wrappers) => {\n for (const wrapper of wrappers) {\n if (!isRecord(wrapper) || !isRecord(wrapper.rawItem)) continue;\n const compacted = compactGeneratedImageRunStateItems(\n [wrapper.rawItem],\n receiptsByProviderItemId,\n )[0];\n if (compacted && compacted !== wrapper.rawItem) {\n wrapper.rawItem = compacted;\n changed = true;\n }\n }\n });\n return changed ? JSON.stringify(parsed) : serialized;\n}\n\nfunction compactGeneratedImageRunStateItems(\n items: Array<Record<string, unknown>>,\n receiptsByProviderItemId: ReadonlyMap<string, GeneratedImageReceipt>,\n): Array<Record<string, unknown>> {\n const compacted = compactGeneratedImageHistory(items, receiptsByProviderItemId);\n let serializedReceipt = false;\n const serialized = compacted.map((item) => {\n const receipt = generatedImageReceiptFromUnknown(item.output);\n if (!receipt || typeof item.output === \"string\") return item;\n serializedReceipt = true;\n return { ...item, output: JSON.stringify(receipt) };\n });\n return serializedReceipt ? serialized : compacted;\n}\n\nexport function collectGeneratedImageRunStateArtifactReceipts(\n serialized: string,\n target: Map<string, GeneratedImageReceipt> = new Map(),\n): Map<string, GeneratedImageReceipt> {\n try {\n const value: unknown = JSON.parse(serialized);\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return target;\n visitRunStateProtocolItems(value as Record<string, unknown>, (items) => {\n collectGeneratedImageArtifactReceipts(items, target);\n });\n visitRunStateItemWrappers(value as Record<string, unknown>, (wrappers) => {\n for (const wrapper of wrappers) {\n if (isRecord(wrapper) && isRecord(wrapper.rawItem)) {\n collectGeneratedImageArtifactReceipts([wrapper.rawItem], target);\n }\n }\n });\n } catch {\n // A provider-owned or legacy state format is opaque to this collector.\n }\n return target;\n}\n\nexport function generatedImageReceiptFromUnknown(value: unknown): GeneratedImageReceipt | null {\n if (typeof value === \"string\" && value.length <= 4_096) {\n try {\n return generatedImageReceiptFromUnknown(JSON.parse(value));\n } catch {\n return null;\n }\n }\n // Function-tool results are durably normalized to the Agents SDK's typed\n // text envelope. Unwrap that canonical transport shape before validating the\n // closed receipt; otherwise a later turn sees the path in model history but\n // cannot discover the artifact that must be copied into its sandbox.\n if (\n isRecord(value) &&\n value.type === \"text\" &&\n typeof value.text === \"string\" &&\n value.text.length <= 4_096\n ) {\n return generatedImageReceiptFromUnknown(value.text);\n }\n const parsed = GeneratedImageReceiptSchema.safeParse(value);\n return parsed.success ? parsed.data : null;\n}\n\nfunction visitRunStateProtocolItems(\n root: Record<string, unknown>,\n visitor: (items: Array<Record<string, unknown>>) => void,\n): void {\n if (Array.isArray(root.originalInput)) {\n visitor(root.originalInput as Array<Record<string, unknown>>);\n }\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n if (!response || typeof response !== \"object\" || Array.isArray(response)) continue;\n const output = (response as Record<string, unknown>).output;\n if (Array.isArray(output)) visitor(output as Array<Record<string, unknown>>);\n }\n }\n if (root.lastModelResponse && typeof root.lastModelResponse === \"object\") {\n const output = (root.lastModelResponse as Record<string, unknown>).output;\n if (Array.isArray(output)) visitor(output as Array<Record<string, unknown>>);\n }\n}\n\nfunction visitRunStateItemWrappers(\n root: Record<string, unknown>,\n visitor: (items: Array<Record<string, unknown>>) => void,\n): void {\n if (Array.isArray(root.generatedItems)) {\n visitor(root.generatedItems as Array<Record<string, unknown>>);\n }\n const processed = root.lastProcessedResponse;\n if (isRecord(processed) && Array.isArray(processed.newItems)) {\n visitor(processed.newItems as Array<Record<string, unknown>>);\n }\n}\n\nfunction projectGeneratedImageRunItemWrapper(\n value: Record<string, unknown>,\n): Record<string, unknown> {\n if (value.type !== \"tool_call_item\" || !isRecord(value.rawItem) || !isRecord(value.agent)) {\n return value;\n }\n const receipt = generatedImageReceiptFromHostedItem(value.rawItem);\n if (!receipt) return value;\n return {\n type: \"message_output_item\",\n rawItem: generatedImageModelMessage(receipt, \"run_state\"),\n agent: value.agent,\n };\n}\n\nfunction generatedImageReceiptFromHostedItem(\n item: Record<string, unknown>,\n): GeneratedImageReceipt | null {\n if (item.type !== \"hosted_tool_call\" || item.name !== \"image_generation_call\") {\n return null;\n }\n return generatedImageReceiptFromUnknown(item.output);\n}\n\nfunction generatedImageModelFact(receipt: GeneratedImageReceipt): string {\n return [\n \"Generated image artifact:\",\n `Artifact ID: ${receipt.artifact.artifactId}`,\n `Sandbox path: ${receipt.sandboxPath}`,\n `Format: ${receipt.artifact.contentType}`,\n `Dimensions: ${receipt.artifact.dimensions?.width ?? \"?\"}x${receipt.artifact.dimensions?.height ?? \"?\"}`,\n ].join(\"\\n\");\n}\n\nfunction generatedImageModelMessage(\n receipt: GeneratedImageReceipt,\n shape: \"history\" | \"run_state\",\n): Record<string, unknown> {\n const text = generatedImageModelFact(receipt);\n return shape === \"history\"\n ? { type: \"message\", role: \"assistant\", content: text }\n : {\n type: \"message\",\n role: \"assistant\",\n status: \"completed\",\n content: [{ type: \"output_text\", text }],\n };\n}\n\nfunction parseRunState(serialized: string): Record<string, unknown> | null {\n try {\n const parsed: unknown = JSON.parse(serialized);\n return isRecord(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value && typeof value === \"object\" && !Array.isArray(value));\n}\n\nexport function retainedGeneratedImageFromArtifact(\n artifact: GeneratedImageArtifact,\n): RetainedGeneratedImage {\n const reference = retainedGeneratedImageReferenceFromFile({\n ...artifact.file,\n width: artifact.width,\n height: artifact.height,\n });\n if (!reference)\n throw new Error(`Ready generated image receipt is invalid: ${artifact.artifactId}`);\n return {\n artifact,\n receipt: {\n type: GENERATED_IMAGE_MARKER,\n artifact: reference,\n sandboxPath: artifact.sandboxPath,\n },\n };\n}\n\n/** Verify a recovered ready correlation against the immutable object metadata. */\nexport async function verifyReadyGeneratedImageArtifact(\n storage: ObjectStorage,\n artifact: GeneratedImageArtifact,\n): Promise<void> {\n if (artifact.status !== \"ready\" || artifact.file.status !== \"ready\") {\n throw new Error(\"Generated image artifact is not durably ready\");\n }\n assertStoredGeneratedImageHead(await storage.headFile(artifact.file), {\n sizeBytes: artifact.sizeBytes,\n mediaType: artifact.mediaType as GeneratedImageMediaType,\n sha256: artifact.sha256,\n });\n}\n\n/**\n * Finish a crash-interrupted upload from immutable DB/object metadata without\n * provider replay. A missing object is not proof that generation failed: the\n * paid outcome remains unknown and the caller may check again later.\n */\nexport async function recoverGeneratedImageArtifact(input: {\n db: Database;\n storage: ObjectStorage;\n accountId: string;\n workspaceId: string;\n artifact: GeneratedImageArtifact;\n}): Promise<GeneratedImageArtifact | null> {\n const { artifact } = input;\n if (artifact.status === \"ready\") {\n await verifyReadyGeneratedImageArtifact(input.storage, artifact);\n return artifact;\n }\n if (artifact.status !== \"pending\") return null;\n if (!(await input.storage.fileExists(artifact.file))) return null;\n assertStoredGeneratedImageHead(await input.storage.headFile(artifact.file), {\n sizeBytes: artifact.sizeBytes,\n mediaType: artifact.mediaType as GeneratedImageMediaType,\n sha256: artifact.sha256,\n });\n if (artifact.file.status !== \"ready\" || artifact.uploadStatus !== \"completed\") {\n if (!artifact.uploadId) return null;\n await completeFileUpload(input.db, input.workspaceId, artifact.uploadId);\n }\n return await settleGeneratedImageArtifactReady(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: artifact.artifactId,\n settlementKey: artifact.settlementKey,\n });\n}\n\nasync function verifyReadyGeneratedImage(\n storage: ObjectStorage,\n artifact: GeneratedImageArtifact,\n expected: ValidatedGeneratedImage,\n): Promise<void> {\n assertStoredGeneratedImageHead(await storage.headFile(artifact.file), expected);\n if (\n artifact.sizeBytes !== expected.sizeBytes ||\n artifact.sha256 !== expected.sha256 ||\n artifact.mediaType !== expected.mediaType ||\n artifact.width !== expected.width ||\n artifact.height !== expected.height\n ) {\n throw new Error(\"ready generated image metadata does not match provider bytes\");\n }\n}\n\nfunction assertStoredGeneratedImageHead(\n head: ObjectHead,\n expected: Pick<ValidatedGeneratedImage, \"sizeBytes\" | \"mediaType\" | \"sha256\">,\n): void {\n if (head.ContentLength !== expected.sizeBytes)\n throw new Error(\"generated image object size mismatch\");\n if (head.ContentType !== expected.mediaType)\n throw new Error(\"generated image object MIME mismatch\");\n if (head.Metadata?.sha256 !== expected.sha256) {\n throw new Error(\"generated image object SHA-256 metadata mismatch\");\n }\n}\n\nfunction uuidFromDigest(digest: string, startByte: number): string {\n const source = Buffer.from(digest, \"hex\");\n const bytes = Uint8Array.from(source.subarray(startByte, startByte + 16));\n bytes[6] = (bytes[6]! & 0x0f) | 0x80;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction base64Sextet(code: number): number {\n if (code >= 0x41 && code <= 0x5a) return code - 0x41;\n if (code >= 0x61 && code <= 0x7a) return code - 0x61 + 26;\n if (code >= 0x30 && code <= 0x39) return code - 0x30 + 52;\n return code === 0x2b ? 62 : 63;\n}\n\nfunction withoutNativeImageResult(value: unknown): unknown {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return value;\n const { result: _result, ...rest } = value as Record<string, unknown>;\n return rest;\n}\n","import {\n COMPUTER_SCREENSHOT_MAX_BYTES,\n COMPUTER_SCREENSHOT_MAX_DIMENSION,\n COMPUTER_SCREENSHOT_MAX_PIXELS,\n COMPUTER_SCREENSHOT_RETENTION_MS,\n COMPUTER_SCREENSHOT_WORKSPACE_QUOTA_BYTES,\n RetainedArtifactMetadataSchema,\n retainedScreenshotReferenceFromFile,\n type RetainedArtifactMetadata,\n type RetainedArtifactReference,\n type RetainedOutputUnavailableReason,\n} from \"@opengeni/contracts\";\nimport {\n RetainedScreenshotQuotaExceededError,\n getRetainedScreenshotArtifact,\n prepareRetainedScreenshotArtifact,\n recordRetainedScreenshotArtifactError,\n settleRetainedScreenshotArtifactReady,\n type Database,\n type RetainedScreenshotArtifact,\n} from \"@opengeni/db\";\nimport type { ObjectHead, ObjectStorage } from \"@opengeni/storage\";\nimport { createHash } from \"node:crypto\";\n\nconst PNG_SIGNATURE = Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a);\nconst PNG_ALLOWED_CRITICAL_CHUNKS = new Set([\"IHDR\", \"PLTE\", \"IDAT\", \"IEND\"]);\nconst PNG_MAX_CHUNKS = 16_384;\nconst RETAINED_IMAGE_MARKER = \"retained_artifact\";\n\nexport type TypedScreenshotToolOutput = {\n callId: string;\n toolOutputId: string;\n bytes: Uint8Array;\n mediaType: string;\n};\n\nexport type ValidatedScreenshot = {\n bytes: Uint8Array;\n mediaType: \"image/png\";\n sizeBytes: number;\n sha256: string;\n width: number;\n height: number;\n};\n\nexport type RetainableSessionImageMediaType = \"image/png\" | \"image/jpeg\" | \"image/webp\";\n\nexport type ValidatedSessionImage = {\n bytes: Uint8Array;\n mediaType: RetainableSessionImageMediaType;\n extension: \"png\" | \"jpg\" | \"webp\";\n sizeBytes: number;\n sha256: string;\n width: number;\n height: number;\n};\n\nexport class ScreenshotValidationError extends Error {\n constructor(\n readonly reason: \"invalid_content\" | \"oversized\" | \"unsupported\",\n message: string,\n ) {\n super(message);\n this.name = \"ScreenshotValidationError\";\n }\n}\n\nexport class RetainedScreenshotUnavailableError extends Error {\n constructor(\n readonly artifactId: string,\n readonly reason: RetainedOutputUnavailableReason,\n ) {\n super(`Retained screenshot ${artifactId} is unavailable: ${reason}`);\n this.name = \"RetainedScreenshotUnavailableError\";\n }\n}\n\n/** Read an intentional image directly at the tool execution boundary. */\nexport function typedScreenshotFromToolOutput(input: {\n callId: string;\n output: unknown;\n}): TypedScreenshotToolOutput | null {\n const image = imageBytesFromSdkToolOutput(input.output);\n if (!image) return null;\n return {\n callId: input.callId,\n toolOutputId: input.callId,\n bytes: image.bytes,\n mediaType: image.mediaType,\n };\n}\n\n/** Read the SDK's trusted typed image before event/history serialization. */\nexport function typedScreenshotFromSdkEvent(event: unknown): TypedScreenshotToolOutput | null {\n if (!event || typeof event !== \"object\") return null;\n const streamEvent = event as {\n type?: unknown;\n item?: {\n id?: unknown;\n type?: unknown;\n rawItem?: unknown;\n output?: unknown;\n };\n };\n if (streamEvent.type !== \"run_item_stream_event\") return null;\n const item = streamEvent.item;\n if (!item || item.type !== \"tool_call_output_item\") return null;\n const image = imageBytesFromSdkToolOutput(item.output);\n if (!image) return null;\n const raw =\n item.rawItem && typeof item.rawItem === \"object\" && !Array.isArray(item.rawItem)\n ? (item.rawItem as Record<string, unknown>)\n : {};\n // Live Agents SDK results can carry the call identity only on the run-item\n // wrapper; reconciled history later copies it into `rawItem`. Use the same\n // fallback as the canonical completed-call extractor so both paths agree.\n const callId = raw.callId ?? raw.call_id ?? item.id;\n if (typeof callId !== \"string\" || callId.length === 0) return null;\n const toolOutputId = raw.id ?? item.id ?? callId;\n if (typeof toolOutputId !== \"string\" || toolOutputId.length === 0) return null;\n return {\n callId,\n toolOutputId,\n bytes: image.bytes,\n mediaType: image.mediaType,\n };\n}\n\n/** Does this SDK result still contain inline bytes that persistence must replace? */\nexport function sdkEventContainsInlineImage(event: unknown): boolean {\n if (!event || typeof event !== \"object\") return false;\n const streamEvent = event as {\n type?: unknown;\n item?: { type?: unknown; output?: unknown };\n };\n return (\n streamEvent.type === \"run_item_stream_event\" &&\n streamEvent.item?.type === \"tool_call_output_item\" &&\n toolOutputContainsInlineImage(streamEvent.item.output)\n );\n}\n\nfunction imageBytesFromSdkToolOutput(\n output: unknown,\n): { bytes: Uint8Array; mediaType: string } | null {\n if (typeof output === \"string\") return decodeInlineImageDataUrl(output);\n if (Array.isArray(output)) {\n for (const entry of output) {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) continue;\n const record = entry as Record<string, unknown>;\n if (record.type !== \"input_image\") continue;\n const decoded = imageBytesFromSdkImageSource(\n record.image ?? record.image_url ?? record.imageUrl,\n );\n if (decoded) return decoded;\n }\n return null;\n }\n if (!output || typeof output !== \"object\") return null;\n const outputRecord = output as Record<string, unknown>;\n if (\n outputRecord.type !== \"image\" ||\n !outputRecord.image ||\n typeof outputRecord.image !== \"object\" ||\n Array.isArray(outputRecord.image)\n ) {\n return null;\n }\n return imageBytesFromSdkImageSource(outputRecord.image);\n}\n\nfunction imageBytesFromSdkImageSource(\n source: unknown,\n): { bytes: Uint8Array; mediaType: string } | null {\n const direct = decodeInlineImageDataUrl(source);\n if (direct) return direct;\n if (!source || typeof source !== \"object\" || Array.isArray(source)) return null;\n const image = source as Record<string, unknown>;\n const fromUrl = decodeInlineImageDataUrl(image.url);\n if (fromUrl) return fromUrl;\n return image.data instanceof Uint8Array && typeof image.mediaType === \"string\"\n ? { bytes: image.data, mediaType: image.mediaType }\n : null;\n}\n\nfunction sdkImageSourceContainsInlineImage(source: unknown): boolean {\n if (typeof source === \"string\") return source.startsWith(\"data:image/\");\n if (!source || typeof source !== \"object\" || Array.isArray(source)) return false;\n const image = source as Record<string, unknown>;\n return (\n (typeof image.url === \"string\" && image.url.startsWith(\"data:image/\")) ||\n (image.data instanceof Uint8Array && typeof image.mediaType === \"string\")\n );\n}\n\nexport function toolOutputContainsInlineImage(output: unknown): boolean {\n if (typeof output === \"string\") return output.startsWith(\"data:image/\");\n if (Array.isArray(output)) {\n return output.some((entry) => {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return false;\n const record = entry as Record<string, unknown>;\n return (\n record.type === \"input_image\" &&\n sdkImageSourceContainsInlineImage(record.image ?? record.image_url ?? record.imageUrl)\n );\n });\n }\n if (!output || typeof output !== \"object\") return false;\n const record = output as Record<string, unknown>;\n return record.type === \"image\" && sdkImageSourceContainsInlineImage(record.image);\n}\n\nfunction decodeInlineImageDataUrl(value: unknown): { bytes: Uint8Array; mediaType: string } | null {\n if (typeof value !== \"string\") return null;\n const match = /^data:(image\\/(?:png|jpeg|webp));base64,/u.exec(value);\n if (!match?.[1]) return null;\n const mediaType = match[1] as RetainableSessionImageMediaType;\n const encoded = value.slice(match[0].length);\n const maxEncodedLength = Math.ceil(COMPUTER_SCREENSHOT_MAX_BYTES / 3) * 4;\n if (\n encoded.length === 0 ||\n encoded.length > maxEncodedLength ||\n encoded.length % 4 !== 0 ||\n !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)\n ) {\n return null;\n }\n const padding = encoded.endsWith(\"==\") ? 2 : encoded.endsWith(\"=\") ? 1 : 0;\n const decodedLength = (encoded.length / 4) * 3 - padding;\n if (decodedLength <= 0 || decodedLength > COMPUTER_SCREENSHOT_MAX_BYTES) {\n return null;\n }\n const lastSextet = base64Sextet(encoded.charCodeAt(encoded.length - padding - 1));\n if (\n (padding === 2 && (lastSextet & 0x0f) !== 0) ||\n (padding === 1 && (lastSextet & 0x03) !== 0)\n ) {\n return null;\n }\n const decoded = Buffer.from(encoded, \"base64\");\n if (decoded.byteLength !== decodedLength) return null;\n const bytes = new Uint8Array(decoded.buffer, decoded.byteOffset, decoded.byteLength);\n return { bytes, mediaType };\n}\n\n/** Validate the complete canonical PNG and derive exact integrity metadata. */\nexport function validateComputerScreenshot(\n input: { bytes: Uint8Array; mediaType: string },\n limits: {\n maxBytes?: number;\n maxDimension?: number;\n maxPixels?: number;\n } = {},\n): ValidatedScreenshot {\n const maxBytes = limits.maxBytes ?? COMPUTER_SCREENSHOT_MAX_BYTES;\n const maxDimension = limits.maxDimension ?? COMPUTER_SCREENSHOT_MAX_DIMENSION;\n const maxPixels = limits.maxPixels ?? COMPUTER_SCREENSHOT_MAX_PIXELS;\n if (input.mediaType !== \"image/png\") {\n throw new ScreenshotValidationError(\n \"unsupported\",\n \"computer screenshot MIME must be image/png\",\n );\n }\n if (input.bytes.byteLength === 0) {\n throw new ScreenshotValidationError(\"invalid_content\", \"computer screenshot is empty\");\n }\n if (input.bytes.byteLength > maxBytes) {\n throw new ScreenshotValidationError(\n \"oversized\",\n `computer screenshot exceeds ${maxBytes} bytes`,\n );\n }\n if (input.bytes.byteLength < PNG_SIGNATURE.byteLength + 25) {\n throw new ScreenshotValidationError(\"invalid_content\", \"computer screenshot PNG is truncated\");\n }\n for (let index = 0; index < PNG_SIGNATURE.byteLength; index += 1) {\n if (input.bytes[index] !== PNG_SIGNATURE[index]) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG signature is invalid\",\n );\n }\n }\n\n let offset = PNG_SIGNATURE.byteLength;\n let chunks = 0;\n let width = 0;\n let height = 0;\n let sawIhdr = false;\n let sawIdat = false;\n let endedIdat = false;\n let sawIend = false;\n while (offset < input.bytes.byteLength) {\n chunks += 1;\n if (chunks > PNG_MAX_CHUNKS || offset + 12 > input.bytes.byteLength) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG chunk table is invalid\",\n );\n }\n const length = readUint32(input.bytes, offset);\n const typeOffset = offset + 4;\n const dataOffset = typeOffset + 4;\n const dataEnd = dataOffset + length;\n const crcOffset = dataEnd;\n const nextOffset = crcOffset + 4;\n if (!Number.isSafeInteger(nextOffset) || nextOffset > input.bytes.byteLength) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG chunk is truncated\",\n );\n }\n const type = asciiChunkType(input.bytes, typeOffset);\n const expectedCrc = readUint32(input.bytes, crcOffset);\n const actualCrc = crc32(input.bytes.subarray(typeOffset, dataEnd));\n if (expectedCrc !== actualCrc) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n `computer screenshot PNG ${type} CRC is invalid`,\n );\n }\n if (chunks === 1 && type !== \"IHDR\") {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG must begin with IHDR\",\n );\n }\n if (isCriticalChunk(type) && !PNG_ALLOWED_CRITICAL_CHUNKS.has(type)) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n `computer screenshot PNG has unsupported critical chunk ${type}`,\n );\n }\n\n if (type === \"IHDR\") {\n if (sawIhdr || length !== 13) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG IHDR is invalid\",\n );\n }\n sawIhdr = true;\n width = readUint32(input.bytes, dataOffset);\n height = readUint32(input.bytes, dataOffset + 4);\n const bitDepth = input.bytes[dataOffset + 8];\n const colorType = input.bytes[dataOffset + 9];\n const compression = input.bytes[dataOffset + 10];\n const filter = input.bytes[dataOffset + 11];\n const interlace = input.bytes[dataOffset + 12];\n if (\n !validPngColorMode(bitDepth, colorType) ||\n compression !== 0 ||\n filter !== 0 ||\n (interlace !== 0 && interlace !== 1)\n ) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG IHDR fields are invalid\",\n );\n }\n if (\n width <= 0 ||\n height <= 0 ||\n width > maxDimension ||\n height > maxDimension ||\n width * height > maxPixels\n ) {\n throw new ScreenshotValidationError(\n \"oversized\",\n \"computer screenshot dimensions exceed policy\",\n );\n }\n } else if (type === \"IDAT\") {\n if (!sawIhdr || sawIend || endedIdat || length === 0) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG IDAT ordering is invalid\",\n );\n }\n sawIdat = true;\n } else if (sawIdat && type !== \"IEND\") {\n endedIdat = true;\n }\n\n if (type === \"IEND\") {\n if (!sawIhdr || !sawIdat || sawIend || length !== 0) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG IEND is invalid\",\n );\n }\n sawIend = true;\n if (nextOffset !== input.bytes.byteLength) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG has trailing/polyglot bytes\",\n );\n }\n }\n offset = nextOffset;\n }\n if (!sawIhdr || !sawIdat || !sawIend || offset !== input.bytes.byteLength) {\n throw new ScreenshotValidationError(\"invalid_content\", \"computer screenshot PNG is incomplete\");\n }\n return {\n bytes: input.bytes,\n mediaType: \"image/png\",\n sizeBytes: input.bytes.byteLength,\n sha256: createHash(\"sha256\").update(input.bytes).digest(\"hex\"),\n width,\n height,\n };\n}\n\n/** Validate a durable view_image/computer image from bytes, never from its claimed MIME alone. */\nexport function validateRetainableSessionImage(\n input: { bytes: Uint8Array; declaredMediaType?: string },\n limits: {\n maxBytes?: number;\n maxDimension?: number;\n maxPixels?: number;\n } = {},\n): ValidatedSessionImage {\n const maxBytes = limits.maxBytes ?? COMPUTER_SCREENSHOT_MAX_BYTES;\n const maxDimension = limits.maxDimension ?? COMPUTER_SCREENSHOT_MAX_DIMENSION;\n const maxPixels = limits.maxPixels ?? COMPUTER_SCREENSHOT_MAX_PIXELS;\n if (input.bytes.byteLength === 0) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session image is empty\");\n }\n if (input.bytes.byteLength > maxBytes) {\n throw new ScreenshotValidationError(\"oversized\", `session image exceeds ${maxBytes} bytes`);\n }\n\n let identity: Pick<ValidatedSessionImage, \"mediaType\" | \"extension\" | \"width\" | \"height\">;\n if (isPng(input.bytes)) {\n const png = validateComputerScreenshot(\n { bytes: input.bytes, mediaType: \"image/png\" },\n { maxBytes, maxDimension, maxPixels },\n );\n identity = {\n mediaType: \"image/png\",\n extension: \"png\",\n width: png.width,\n height: png.height,\n };\n } else if (isJpeg(input.bytes)) {\n identity = {\n mediaType: \"image/jpeg\",\n extension: \"jpg\",\n ...jpegDimensions(input.bytes),\n };\n } else if (isWebp(input.bytes)) {\n identity = {\n mediaType: \"image/webp\",\n extension: \"webp\",\n ...webpDimensions(input.bytes),\n };\n } else {\n throw new ScreenshotValidationError(\"unsupported\", \"session image format is unsupported\");\n }\n assertImageDimensions(identity.width, identity.height, {\n maxDimension,\n maxPixels,\n });\n if (\n input.declaredMediaType &&\n canonicalMediaType(input.declaredMediaType) !== identity.mediaType\n ) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session image MIME does not match its bytes\",\n );\n }\n return {\n bytes: input.bytes,\n ...identity,\n sizeBytes: input.bytes.byteLength,\n sha256: createHash(\"sha256\").update(input.bytes).digest(\"hex\"),\n };\n}\n\nexport function retainedScreenshotIdentity(input: {\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n toolOutputId: string;\n}): { artifactId: string; settlementKey: string } {\n const settlementKey = createHash(\"sha256\")\n .update(\"opengeni:computer-screenshot:v1\\0\")\n .update(input.sessionId)\n .update(\"\\0\")\n .update(input.turnId)\n .update(\"\\0\")\n .update(input.attemptId)\n .update(\"\\0\")\n .update(input.toolCallId)\n .update(\"\\0\")\n .update(input.toolOutputId)\n .digest(\"hex\");\n const uuidBytes = Uint8Array.from(Buffer.from(settlementKey.slice(0, 32), \"hex\"));\n uuidBytes[6] = (uuidBytes[6]! & 0x0f) | 0x80;\n uuidBytes[8] = (uuidBytes[8]! & 0x3f) | 0x80;\n const hex = Buffer.from(uuidBytes).toString(\"hex\");\n return {\n artifactId: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`,\n settlementKey,\n };\n}\n\n/** Deterministic fail-closed receipt installed before retention can perform I/O. */\nexport function unavailableRetainedSessionImage(input: {\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n toolOutputId: string;\n reason: RetainedOutputUnavailableReason;\n}): RetainedArtifactMetadata {\n const identity = retainedScreenshotIdentity(input);\n return unavailable(identity.artifactId, input.reason);\n}\n\nexport async function retainComputerScreenshot(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n output: TypedScreenshotToolOutput;\n now?: Date;\n retentionMs?: number;\n workspaceQuotaBytes?: number;\n}): Promise<RetainedArtifactMetadata> {\n const identity = retainedScreenshotIdentity({\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n toolCallId: input.output.callId,\n toolOutputId: input.output.toolOutputId,\n });\n let screenshot: ValidatedSessionImage;\n try {\n screenshot = validateRetainableSessionImage({\n bytes: input.output.bytes,\n declaredMediaType: input.output.mediaType,\n });\n } catch (error) {\n if (error instanceof ScreenshotValidationError) {\n return unavailable(identity.artifactId, error.reason);\n }\n throw error;\n }\n if (!input.objectStorage) return unavailable(identity.artifactId, \"missing_storage\");\n\n const now = input.now ?? new Date();\n const retentionExpiresAt = new Date(\n now.getTime() + (input.retentionMs ?? COMPUTER_SCREENSHOT_RETENTION_MS),\n );\n const objectKey = `workspaces/${input.workspaceId}/files/${identity.artifactId}/retained/session-image.${screenshot.extension}`;\n let prepared: RetainedScreenshotArtifact;\n try {\n prepared = (\n await prepareRetainedScreenshotArtifact(input.db, {\n artifactId: identity.artifactId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n settlementKey: identity.settlementKey,\n toolCallId: input.output.callId,\n toolOutputId: input.output.toolOutputId,\n mediaType: screenshot.mediaType,\n sizeBytes: screenshot.sizeBytes,\n sha256: screenshot.sha256,\n width: screenshot.width,\n height: screenshot.height,\n retentionExpiresAt,\n bucket: input.objectStorage.bucket,\n objectKey,\n workspaceQuotaBytes: input.workspaceQuotaBytes ?? COMPUTER_SCREENSHOT_WORKSPACE_QUOTA_BYTES,\n })\n ).artifact;\n } catch (error) {\n if (error instanceof RetainedScreenshotQuotaExceededError) {\n return unavailable(identity.artifactId, \"quota_exceeded\");\n }\n throw error;\n }\n\n if (prepared.status === \"ready\") {\n return (await verifyReadyArtifact(input.objectStorage, prepared))\n ? reference(prepared)\n : unavailable(identity.artifactId, \"missing_storage\");\n }\n if (prepared.status !== \"pending\" && prepared.status !== \"reconciling\") {\n return unavailable(identity.artifactId, unavailableReasonForStatus(prepared.status));\n }\n\n try {\n await input.objectStorage.putObject({\n key: objectKey,\n contentType: screenshot.mediaType,\n body: screenshot.bytes,\n sha256: screenshot.sha256,\n });\n const head = await input.objectStorage.headFile(prepared.file);\n assertStoredScreenshotHead(head, screenshot);\n } catch (error) {\n await recordRetainedScreenshotArtifactError(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n error: error instanceof Error ? error.message : String(error),\n }).catch(() => undefined);\n return unavailable(identity.artifactId, \"storage_write_failed\");\n }\n\n try {\n const settled = await settleRetainedScreenshotArtifactReady(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n });\n return reference(settled);\n } catch (error) {\n // PUT completed. If a concurrent cascade removed the deterministic intent,\n // compensate the now-unreferenced key. Otherwise leave the pending row for\n // exact retry/background reconciliation instead of deleting live truth.\n const stillReferenced = await getRetainedScreenshotArtifact(\n input.db,\n input.workspaceId,\n input.sessionId,\n identity.artifactId,\n ).catch(() => undefined);\n if (stillReferenced?.status === \"ready\") {\n return (await verifyReadyArtifact(input.objectStorage, stillReferenced))\n ? reference(stillReferenced)\n : unavailable(identity.artifactId, \"missing_storage\");\n }\n if (\n stillReferenced === null ||\n stillReferenced?.status === \"cleanup_queued\" ||\n stillReferenced?.status === \"cleanup_pending\" ||\n stillReferenced?.status === \"failed\" ||\n stillReferenced?.status === \"expired\" ||\n stillReferenced?.status === \"deleted\"\n ) {\n await input.objectStorage.deleteObject(objectKey).catch(() => undefined);\n } else if (stillReferenced) {\n await recordRetainedScreenshotArtifactError(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n artifactId: identity.artifactId,\n settlementKey: identity.settlementKey,\n error: error instanceof Error ? error.message : String(error),\n }).catch(() => undefined);\n }\n return unavailable(identity.artifactId, \"pending\");\n }\n}\n\n/** Replace only new screenshot bytes with a compact receipt before first persistence. */\nexport function compactRetainedScreenshotHistory(\n history: Array<Record<string, unknown>>,\n receiptsByCallId: ReadonlyMap<string, RetainedArtifactMetadata>,\n): Array<Record<string, unknown>> {\n if (receiptsByCallId.size === 0) return history;\n return history.map((item) => {\n const callId = historyCallId(item);\n const receipt = callId ? receiptsByCallId.get(callId) : undefined;\n if (!receipt) return item;\n if (typeof item.output === \"string\" && item.output.startsWith(\"data:image/\")) {\n return {\n ...item,\n output: { type: RETAINED_IMAGE_MARKER, artifact: receipt },\n };\n }\n if (!Array.isArray(item.output)) return item;\n let changed = false;\n const output = item.output.map((entry) => {\n if (!isInlineImageContent(entry)) return entry;\n changed = true;\n return {\n ...(entry as Record<string, unknown>),\n image: { type: RETAINED_IMAGE_MARKER, artifact: receipt },\n };\n });\n return changed ? { ...item, output } : item;\n });\n}\n\n/** Collect durable screenshot receipts before their provider-only expansion. */\nexport function collectRetainedScreenshotReceipts(\n history: ReadonlyArray<Record<string, unknown>>,\n target: Map<string, RetainedArtifactMetadata> = new Map(),\n): Map<string, RetainedArtifactMetadata> {\n for (const item of history) {\n const callId = historyCallId(item);\n if (!callId) continue;\n const direct = retainedReceiptFromDirectOutput(item.output);\n if (direct) {\n target.set(callId, direct);\n continue;\n }\n if (!Array.isArray(item.output)) continue;\n for (const entry of item.output) {\n const receipt = retainedReceiptFromImageContent(entry);\n if (receipt) {\n target.set(callId, receipt);\n break;\n }\n }\n }\n return target;\n}\n\n/**\n * Compact every protocol-item copy inside an SDK RunState before persistence.\n * The traversal intentionally mirrors the repository's existing serialized\n * RunState sanitizers. A parse failure or no-op returns the original string.\n */\nexport function compactRetainedScreenshotRunState(\n serialized: string,\n receiptsByCallId: ReadonlyMap<string, RetainedArtifactMetadata>,\n): string {\n if (receiptsByCallId.size === 0) return serialized;\n const parsed = parseSerializedRunState(serialized);\n if (!parsed) return serialized;\n let changed = false;\n visitSerializedRunStateItemArrays(parsed, (items) => {\n const compacted = compactRetainedScreenshotHistory(items, receiptsByCallId);\n if (compacted !== items && compacted.some((item, index) => item !== items[index])) {\n items.splice(0, items.length, ...compacted);\n changed = true;\n }\n });\n return changed ? JSON.stringify(parsed) : serialized;\n}\n\nexport function collectRetainedScreenshotRunStateReceipts(\n serialized: string,\n target: Map<string, RetainedArtifactMetadata> = new Map(),\n): Map<string, RetainedArtifactMetadata> {\n const parsed = parseSerializedRunState(serialized);\n if (!parsed) return target;\n visitSerializedRunStateItemArrays(parsed, (items) => {\n collectRetainedScreenshotReceipts(items, target);\n });\n return target;\n}\n\n/**\n * Materialize canonical receipts to the exact SDK input_image data URL shape.\n * Missing/deleted/expired/corrupt bytes fail closed; no item is omitted,\n * reordered, rewritten in storage, or converted to text.\n */\nexport async function materializeRetainedScreenshotHistory(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n workspaceId: string;\n sessionId: string;\n history: Array<Record<string, unknown>>;\n now?: Date;\n}): Promise<Array<Record<string, unknown>>> {\n return await materializeRetainedScreenshotHistoryWithCache(input, new Map());\n}\n\n/** Expand durable markers in an SDK RunState immediately before resume. */\nexport async function materializeRetainedScreenshotRunState(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n workspaceId: string;\n sessionId: string;\n serialized: string;\n now?: Date;\n}): Promise<string> {\n const parsed = parseSerializedRunState(input.serialized);\n if (!parsed) return input.serialized;\n const cache = new Map<string, string>();\n let changed = false;\n await visitSerializedRunStateItemArraysAsync(parsed, async (items) => {\n const materialized = await materializeRetainedScreenshotHistoryWithCache(\n { ...input, history: items },\n cache,\n );\n if (materialized.some((item, index) => item !== items[index])) {\n items.splice(0, items.length, ...materialized);\n changed = true;\n }\n });\n return changed ? JSON.stringify(parsed) : input.serialized;\n}\n\nasync function materializeRetainedScreenshotHistoryWithCache(\n input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n workspaceId: string;\n sessionId: string;\n history: Array<Record<string, unknown>>;\n now?: Date;\n },\n cache: Map<string, string>,\n): Promise<Array<Record<string, unknown>>> {\n const now = input.now ?? new Date();\n const dataUrlForReceipt = async (receipt: RetainedArtifactMetadata): Promise<string> => {\n if (!receipt.available) {\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, receipt.reason);\n }\n let dataUrl = cache.get(receipt.artifactId);\n if (!dataUrl) {\n if (!input.objectStorage) {\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"missing_storage\");\n }\n const artifact = await getRetainedScreenshotArtifact(\n input.db,\n input.workspaceId,\n input.sessionId,\n receipt.artifactId,\n );\n if (!artifact) throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"deleted\");\n if (artifact.status !== \"ready\") {\n throw new RetainedScreenshotUnavailableError(\n receipt.artifactId,\n unavailableReasonForStatus(artifact.status),\n );\n }\n if (artifact.retentionExpiresAt.getTime() <= now.getTime()) {\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"expired\");\n }\n const bytes = await input.objectStorage.getFileBytes(artifact.file).catch(() => null);\n if (!bytes)\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"missing_storage\");\n const validated = validateRetainableSessionImage({\n bytes,\n declaredMediaType: artifact.mediaType,\n });\n if (\n validated.sizeBytes !== artifact.sizeBytes ||\n validated.sha256 !== artifact.sha256 ||\n validated.width !== artifact.width ||\n validated.height !== artifact.height ||\n receipt.sha256 !== artifact.sha256 ||\n receipt.originalBytes !== artifact.sizeBytes\n ) {\n throw new RetainedScreenshotUnavailableError(receipt.artifactId, \"invalid_content\");\n }\n dataUrl = `data:${validated.mediaType};base64,${Buffer.from(validated.bytes).toString(\"base64\")}`;\n cache.set(receipt.artifactId, dataUrl);\n }\n return dataUrl;\n };\n const materializeEntry = async (entry: unknown): Promise<unknown> => {\n const receipt = retainedReceiptFromImageContent(entry);\n if (!receipt) return entry;\n const dataUrl = await dataUrlForReceipt(receipt);\n return { ...(entry as Record<string, unknown>), image: dataUrl };\n };\n\n const materialized: Array<Record<string, unknown>> = [];\n for (const item of input.history) {\n const directReceipt = retainedReceiptFromDirectOutput(item.output);\n if (directReceipt) {\n materialized.push({\n ...item,\n output: await dataUrlForReceipt(directReceipt),\n });\n continue;\n }\n if (!Array.isArray(item.output)) {\n materialized.push(item);\n continue;\n }\n let changed = false;\n const output: unknown[] = [];\n for (const entry of item.output) {\n const next = await materializeEntry(entry);\n changed ||= next !== entry;\n output.push(next);\n }\n materialized.push(changed ? { ...item, output } : item);\n }\n return materialized;\n}\n\nfunction parseSerializedRunState(serialized: string): Record<string, unknown> | null {\n try {\n const parsed: unknown = JSON.parse(serialized);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : null;\n } catch {\n return null;\n }\n}\n\nfunction visitSerializedRunStateItemArrays(\n root: Record<string, unknown>,\n visitor: (items: Array<Record<string, unknown>>) => void,\n): void {\n const originalInput = root.originalInput;\n if (Array.isArray(originalInput)) {\n visitor(originalInput as Array<Record<string, unknown>>);\n }\n if (Array.isArray(root.generatedItems)) {\n for (const wrapper of root.generatedItems) {\n if (!wrapper || typeof wrapper !== \"object\" || Array.isArray(wrapper)) continue;\n const record = wrapper as Record<string, unknown>;\n const rawItem = record.rawItem;\n if (!rawItem || typeof rawItem !== \"object\" || Array.isArray(rawItem)) continue;\n const items = [rawItem as Record<string, unknown>];\n visitor(items);\n if (items[0] !== rawItem) record.rawItem = items[0];\n }\n }\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n if (!response || typeof response !== \"object\" || Array.isArray(response)) continue;\n const output = (response as Record<string, unknown>).output;\n if (Array.isArray(output)) visitor(output as Array<Record<string, unknown>>);\n }\n }\n const lastModelResponse = root.lastModelResponse;\n if (\n lastModelResponse &&\n typeof lastModelResponse === \"object\" &&\n !Array.isArray(lastModelResponse)\n ) {\n const output = (lastModelResponse as Record<string, unknown>).output;\n if (Array.isArray(output)) visitor(output as Array<Record<string, unknown>>);\n }\n}\n\nasync function visitSerializedRunStateItemArraysAsync(\n root: Record<string, unknown>,\n visitor: (items: Array<Record<string, unknown>>) => Promise<void>,\n): Promise<void> {\n const originalInput = root.originalInput;\n if (Array.isArray(originalInput)) {\n await visitor(originalInput as Array<Record<string, unknown>>);\n }\n if (Array.isArray(root.generatedItems)) {\n for (const wrapper of root.generatedItems) {\n if (!wrapper || typeof wrapper !== \"object\" || Array.isArray(wrapper)) continue;\n const record = wrapper as Record<string, unknown>;\n const rawItem = record.rawItem;\n if (!rawItem || typeof rawItem !== \"object\" || Array.isArray(rawItem)) continue;\n const items = [rawItem as Record<string, unknown>];\n await visitor(items);\n if (items[0] !== rawItem) record.rawItem = items[0];\n }\n }\n if (Array.isArray(root.modelResponses)) {\n for (const response of root.modelResponses) {\n if (!response || typeof response !== \"object\" || Array.isArray(response)) continue;\n const output = (response as Record<string, unknown>).output;\n if (Array.isArray(output)) await visitor(output as Array<Record<string, unknown>>);\n }\n }\n const lastModelResponse = root.lastModelResponse;\n if (\n lastModelResponse &&\n typeof lastModelResponse === \"object\" &&\n !Array.isArray(lastModelResponse)\n ) {\n const output = (lastModelResponse as Record<string, unknown>).output;\n if (Array.isArray(output)) await visitor(output as Array<Record<string, unknown>>);\n }\n}\n\nfunction reference(artifact: RetainedScreenshotArtifact): RetainedArtifactReference {\n if (!artifact.sessionId) {\n throw new Error(`Ready retained screenshot is detached: ${artifact.artifactId}`);\n }\n const value = retainedScreenshotReferenceFromFile({\n ...artifact.file,\n sessionId: artifact.sessionId,\n width: artifact.width,\n height: artifact.height,\n expiresAt: artifact.retentionExpiresAt.toISOString(),\n });\n if (!value)\n throw new Error(`Ready retained screenshot receipt is invalid: ${artifact.artifactId}`);\n return value;\n}\n\nfunction unavailable(\n artifactId: string,\n reason: RetainedOutputUnavailableReason,\n): RetainedArtifactMetadata {\n return RetainedArtifactMetadataSchema.parse({\n available: false,\n artifactId,\n reason,\n });\n}\n\nfunction unavailableReasonForStatus(\n status: RetainedScreenshotArtifact[\"status\"],\n): RetainedOutputUnavailableReason {\n switch (status) {\n case \"pending\":\n case \"reconciling\":\n return \"pending\";\n case \"cleanup_queued\":\n case \"cleanup_pending\":\n return \"failed\";\n case \"failed\":\n case \"expired\":\n case \"deleted\":\n return status;\n case \"ready\":\n return \"missing_storage\";\n }\n}\n\nasync function verifyReadyArtifact(\n storage: ObjectStorage,\n artifact: RetainedScreenshotArtifact,\n): Promise<boolean> {\n try {\n assertStoredScreenshotHead(await storage.headFile(artifact.file), {\n sizeBytes: artifact.sizeBytes,\n mediaType: artifact.mediaType as RetainableSessionImageMediaType,\n sha256: artifact.sha256,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction assertStoredScreenshotHead(\n head: ObjectHead,\n expected: Pick<ValidatedSessionImage, \"sizeBytes\" | \"mediaType\" | \"sha256\">,\n): void {\n if (head.ContentLength !== expected.sizeBytes) {\n throw new Error(\"retained screenshot object size mismatch\");\n }\n if (head.ContentType !== expected.mediaType) {\n throw new Error(\"retained screenshot object MIME mismatch\");\n }\n if (head.Metadata?.sha256 !== expected.sha256) {\n throw new Error(\"retained screenshot object SHA-256 metadata mismatch\");\n }\n}\n\nfunction retainedReceiptFromImageContent(entry: unknown): RetainedArtifactMetadata | null {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return null;\n const image = (entry as Record<string, unknown>).image;\n if (!image || typeof image !== \"object\" || Array.isArray(image)) return null;\n const marker = image as Record<string, unknown>;\n if (marker.type !== RETAINED_IMAGE_MARKER) return null;\n return retainedReceipt(marker.artifact);\n}\n\nfunction retainedReceiptFromDirectOutput(output: unknown): RetainedArtifactMetadata | null {\n if (!output || typeof output !== \"object\" || Array.isArray(output)) return null;\n const marker = output as Record<string, unknown>;\n if (marker.type !== RETAINED_IMAGE_MARKER) return null;\n return retainedReceipt(marker.artifact);\n}\n\nfunction retainedReceipt(value: unknown): RetainedArtifactMetadata | null {\n const parsed = RetainedArtifactMetadataSchema.safeParse(value);\n if (!parsed.success) return null;\n return parsed.data.available && parsed.data.kind !== \"computer_screenshot\" ? null : parsed.data;\n}\n\nfunction isInlineImageContent(entry: unknown): boolean {\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) return false;\n const record = entry as Record<string, unknown>;\n return (\n record.type === \"input_image\" &&\n typeof record.image === \"string\" &&\n record.image.startsWith(\"data:image/\")\n );\n}\n\nfunction historyCallId(item: Record<string, unknown>): string | null {\n const value = item.callId ?? item.call_id;\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\nfunction canonicalMediaType(value: string): string {\n return value.split(\";\", 1)[0]!.trim().toLowerCase();\n}\n\nfunction isPng(bytes: Uint8Array): boolean {\n return (\n bytes.byteLength >= PNG_SIGNATURE.byteLength &&\n PNG_SIGNATURE.every((byte, index) => bytes[index] === byte)\n );\n}\n\nfunction isJpeg(bytes: Uint8Array): boolean {\n return bytes.byteLength >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8;\n}\n\nfunction jpegDimensions(bytes: Uint8Array): { width: number; height: number } {\n if (bytes[bytes.length - 2] !== 0xff || bytes[bytes.length - 1] !== 0xd9) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session JPEG is truncated or has trailing bytes\",\n );\n }\n let offset = 2;\n while (offset + 4 <= bytes.length) {\n if (bytes[offset] !== 0xff) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session JPEG marker table is invalid\",\n );\n }\n while (bytes[offset] === 0xff) offset += 1;\n const marker = bytes[offset++];\n if (marker === undefined || marker === 0xd9 || marker === 0xda) break;\n if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;\n if (offset + 2 > bytes.length) break;\n const length = readUint16Be(bytes, offset);\n if (length < 2 || offset + length > bytes.length) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session JPEG segment is invalid\");\n }\n if (JPEG_SOF_MARKERS.has(marker)) {\n if (length < 7) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session JPEG frame is invalid\");\n }\n return {\n height: readUint16Be(bytes, offset + 3),\n width: readUint16Be(bytes, offset + 5),\n };\n }\n offset += length;\n }\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session JPEG has no supported frame header\",\n );\n}\n\nconst JPEG_SOF_MARKERS = new Set([\n 0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,\n]);\n\nfunction isWebp(bytes: Uint8Array): boolean {\n return bytes.byteLength >= 20 && ascii(bytes, 0, 4) === \"RIFF\" && ascii(bytes, 8, 4) === \"WEBP\";\n}\n\nfunction webpDimensions(bytes: Uint8Array): { width: number; height: number } {\n if (readUint32Le(bytes, 4) + 8 !== bytes.byteLength) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP RIFF length is invalid\");\n }\n let offset = 12;\n while (offset + 8 <= bytes.length) {\n const type = ascii(bytes, offset, 4);\n const length = readUint32Le(bytes, offset + 4);\n const data = offset + 8;\n const next = data + length + (length & 1);\n if (next > bytes.length) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP chunk is truncated\");\n }\n if (type === \"VP8X\") {\n if (length < 10) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP VP8X is invalid\");\n }\n return {\n width: 1 + readUint24Le(bytes, data + 4),\n height: 1 + readUint24Le(bytes, data + 7),\n };\n }\n if (type === \"VP8 \") {\n if (\n length < 10 ||\n bytes[data + 3] !== 0x9d ||\n bytes[data + 4] !== 0x01 ||\n bytes[data + 5] !== 0x2a\n ) {\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP VP8 frame is invalid\");\n }\n return {\n width: readUint16Le(bytes, data + 6) & 0x3fff,\n height: readUint16Le(bytes, data + 8) & 0x3fff,\n };\n }\n if (type === \"VP8L\") {\n if (length < 5 || bytes[data] !== 0x2f) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"session WebP VP8L frame is invalid\",\n );\n }\n const bits = readUint32Le(bytes, data + 1);\n return {\n width: 1 + (bits & 0x3fff),\n height: 1 + ((bits >>> 14) & 0x3fff),\n };\n }\n offset = next;\n }\n throw new ScreenshotValidationError(\"invalid_content\", \"session WebP has no image frame\");\n}\n\nfunction assertImageDimensions(\n width: number,\n height: number,\n limits: { maxDimension: number; maxPixels: number },\n): void {\n if (\n !Number.isSafeInteger(width) ||\n !Number.isSafeInteger(height) ||\n width <= 0 ||\n height <= 0 ||\n width > limits.maxDimension ||\n height > limits.maxDimension ||\n width * height > limits.maxPixels\n ) {\n throw new ScreenshotValidationError(\"oversized\", \"session image dimensions exceed policy\");\n }\n}\n\nfunction readUint16Be(bytes: Uint8Array, offset: number): number {\n return (bytes[offset]! << 8) | bytes[offset + 1]!;\n}\n\nfunction readUint16Le(bytes: Uint8Array, offset: number): number {\n return bytes[offset]! | (bytes[offset + 1]! << 8);\n}\n\nfunction readUint24Le(bytes: Uint8Array, offset: number): number {\n return bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16);\n}\n\nfunction readUint32Le(bytes: Uint8Array, offset: number): number {\n return (\n (bytes[offset]! |\n (bytes[offset + 1]! << 8) |\n (bytes[offset + 2]! << 16) |\n (bytes[offset + 3]! << 24)) >>>\n 0\n );\n}\n\nfunction ascii(bytes: Uint8Array, offset: number, length: number): string {\n return String.fromCharCode(...bytes.subarray(offset, offset + length));\n}\n\nfunction base64Sextet(code: number): number {\n if (code >= 0x41 && code <= 0x5a) return code - 0x41;\n if (code >= 0x61 && code <= 0x7a) return code - 0x61 + 26;\n if (code >= 0x30 && code <= 0x39) return code - 0x30 + 52;\n return code === 0x2b ? 62 : 63;\n}\n\nfunction readUint32(bytes: Uint8Array, offset: number): number {\n return (\n ((bytes[offset]! << 24) |\n (bytes[offset + 1]! << 16) |\n (bytes[offset + 2]! << 8) |\n bytes[offset + 3]!) >>>\n 0\n );\n}\n\nfunction asciiChunkType(bytes: Uint8Array, offset: number): string {\n const chars = [bytes[offset], bytes[offset + 1], bytes[offset + 2], bytes[offset + 3]];\n if (\n chars.some(\n (value) => value === undefined || value < 65 || (value > 90 && value < 97) || value > 122,\n )\n ) {\n throw new ScreenshotValidationError(\n \"invalid_content\",\n \"computer screenshot PNG chunk type is invalid\",\n );\n }\n return String.fromCharCode(...(chars as number[]));\n}\n\nfunction isCriticalChunk(type: string): boolean {\n return type.charCodeAt(0) >= 65 && type.charCodeAt(0) <= 90;\n}\n\nfunction validPngColorMode(bitDepth: number | undefined, colorType: number | undefined): boolean {\n if (bitDepth === undefined || colorType === undefined) return false;\n switch (colorType) {\n case 0:\n return [1, 2, 4, 8, 16].includes(bitDepth);\n case 2:\n case 4:\n case 6:\n return bitDepth === 8 || bitDepth === 16;\n case 3:\n return [1, 2, 4, 8].includes(bitDepth);\n default:\n return false;\n }\n}\n\nconst CRC32_TABLE = Uint32Array.from({ length: 256 }, (_, value) => {\n let current = value;\n for (let bit = 0; bit < 8; bit += 1) {\n current = (current & 1) !== 0 ? 0xedb88320 ^ (current >>> 1) : current >>> 1;\n }\n return current >>> 0;\n});\n\nfunction crc32(bytes: Uint8Array): number {\n let crc = 0xffffffff;\n for (const byte of bytes) crc = CRC32_TABLE[(crc ^ byte) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n","import {\n applyContextCompaction,\n getActiveSessionHistoryItemsPaged,\n recordSkippedContextCompaction,\n recordStartedContextCompaction,\n type Database,\n} from \"@opengeni/db\";\nimport {\n EmptyCompactionSummaryError,\n REMOTE_COMPACTION_V2_IMPLEMENTATION,\n SUMMARY_BUFFER_TOKENS,\n buildCompactionReplacementHistory,\n buildRemoteV2ReplacementHistory,\n compactionReplacementFingerprint,\n decideCompaction,\n estimateTokens,\n latestCompactionReplacementFingerprint,\n prepareCompactionPromptInput,\n projectRemoteCompactionOverflowRetryInput,\n sanitizeHistoryItemsForModel,\n summarizeForCompaction,\n type CompactionItem,\n} from \"@opengeni/runtime\";\nimport { contextInputBudgetTokens, type Settings } from \"@opengeni/config\";\nimport type { SessionEvent } from \"@opengeni/contracts\";\nimport { projectRejectedProviderArtifacts } from \"./run-input\";\nimport { TurnAttemptFencedError } from \"./turn-attempt-fenced\";\n\nexport type MaybeCompactResult =\n | {\n compacted: false;\n reason: string;\n events: SessionEvent[];\n requestConsumed: boolean;\n }\n | {\n compacted: true;\n supersededFrom: number;\n summaryPosition: number;\n signalTokens: number;\n thresholdTokens: number;\n estimatedTokensBefore: number;\n estimatedTokensAfter: number;\n replacementFingerprint: string;\n events: SessionEvent[];\n };\n\n/**\n * Durable context compaction.\n *\n * Portable path: Codex CLI local plaintext checkpoint for every provider and\n * for Codex sessions frozen on `portable`.\n *\n * Remote v2 path: when the session is frozen on `remote_v2` and the turn is\n * Codex, call Codex `/codex/responses` with `compaction_trigger` and persist the\n * opaque compaction item. Fail closed — never silently fall back to portable.\n */\nexport type CompactionSummarizer = (settings: Settings, input: CompactionItem[]) => Promise<string>;\n\n/** Returns the opaque Codex remote compaction v2 item. */\nexport type RemoteCompactionV2Requester = (\n settings: Settings,\n input: CompactionItem[],\n) => Promise<CompactionItem>;\n\nexport async function maybeCompactContext(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n lastInputTokens: number | null,\n // Injectable for tests; defaults to the real provider-aware model call.\n summarize: CompactionSummarizer = (s, m) =>\n summarizeForCompaction(s, m, {\n maxOutputTokens: SUMMARY_BUFFER_TOKENS,\n }),\n // Operator-forced (the /compact command): bypass the budget trigger and\n // compact now if there is anything to summarize. Structural guards still hold.\n options: {\n force?: boolean;\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n /** Frozen session mode; remote_v2 selects the Codex opaque path. */\n codexCompactionMode?: \"remote_v2\" | \"portable\";\n /** True when this turn's resolved provider is codex-subscription. */\n isCodexSubscriptionTurn?: boolean;\n /** Injected remote requester; required for the remote_v2 branch. */\n requestRemoteCompactionV2?: RemoteCompactionV2Requester;\n /**\n * Live fanout for the attempt-fenced `compaction.started` event so the\n * timeline can show progress before the provider call returns. Must never\n * append again — the event is already durable.\n */\n publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;\n /** Materialize retained screenshot receipts only in the attempt-local model view. */\n materializeHistory?: (items: CompactionItem[]) => Promise<CompactionItem[]>;\n /** Turn-scoped attachment/modality view; canonical persisted rows stay untouched. */\n projectModelInput?: (items: CompactionItem[]) => Promise<CompactionItem[]>;\n } = {},\n): Promise<MaybeCompactResult> {\n if (options.codexCompactionMode === \"remote_v2\" && options.isCodexSubscriptionTurn !== true) {\n // Fail closed: a V2-locked session must never silently take the portable path\n // (mixed history shapes). Admission should have blocked this already.\n throw new Error(\n \"session is locked to Codex remote compaction v2 but this turn is not a Codex subscription turn\",\n );\n }\n const useRemoteV2 = options.codexCompactionMode === \"remote_v2\";\n\n // Preserve the complete ordered transcript while bounding each Postgres\n // driver result frame beside the decoded history already held by this turn.\n const active = await getActiveSessionHistoryItemsPaged(db, scope.workspaceId, scope.sessionId);\n if (active.length === 0) {\n let requestConsumed = false;\n if (options.clearRequestedCompaction) {\n const skipped = await recordSkippedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n reason: \"no_history\",\n });\n if (!skipped.recorded) {\n throw new TurnAttemptFencedError(\n \"turn attempt was fenced while consuming an empty context compaction request\",\n );\n }\n requestConsumed = true;\n return {\n compacted: false,\n reason: \"no_history\",\n events: skipped.events,\n requestConsumed,\n };\n }\n return {\n compacted: false,\n reason: \"no_history\",\n events: [],\n requestConsumed,\n };\n }\n\n const canonicalItems = projectRejectedProviderArtifacts(active) as CompactionItem[];\n const projectForWire = async (input: CompactionItem[]): Promise<CompactionItem[]> => {\n const materialized = options.materializeHistory\n ? await options.materializeHistory(input)\n : input;\n return sanitizeHistoryItemsForModel(\n options.projectModelInput ? await options.projectModelInput(materialized) : materialized,\n settings.modelToolOutputTruncationTokens,\n ) as CompactionItem[];\n };\n const items = await projectForWire(canonicalItems);\n const decision = decideCompaction({\n items,\n lastInputTokens,\n contextWindowTokens: settings.contextWindowTokens,\n contextReservedOutputTokens: settings.contextReservedOutputTokens,\n contextAutoCompactThresholdTokens: settings.contextAutoCompactThresholdTokens,\n contextCompactionThresholdRatio: settings.contextCompactionThresholdRatio,\n ...(options.force ? { force: true } : {}),\n });\n if (!decision.shouldCompact) {\n return {\n compacted: false,\n reason: decision.reason,\n events: [],\n requestConsumed: false,\n };\n }\n\n const trigger = options.trigger ?? \"auto\";\n const estimatedTokensBefore = estimateTokens(items);\n const started = await recordStartedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n trigger,\n estimatedTokensBefore,\n ...(useRemoteV2 ? { implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION } : {}),\n });\n if (!started.recorded) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced while recording context compaction start: ${started.reason}`,\n );\n }\n await options.publishLiveEvents?.(started.events);\n\n if (useRemoteV2) {\n const outcome = await compactContextRemoteV2(\n db,\n settings,\n scope,\n canonicalItems,\n items,\n decision,\n options,\n projectForWire,\n );\n return prependCompactionEvents(started.events, outcome);\n }\n\n const outcome = await compactContextPortable(\n db,\n settings,\n scope,\n canonicalItems,\n items,\n decision,\n summarize,\n options,\n projectForWire,\n );\n return prependCompactionEvents(started.events, outcome);\n}\n\n/**\n * After `compaction.started`, record a visible skip so the timeline cannot\n * stick on \"Compacting…\". Used when the provider/summarizer throws a terminal\n * (non-retryable) failure — including auto/overflow paths that never set\n * `compactRequested`.\n */\nexport async function settleFailedContextCompactionLandmark(\n db: Database,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n options: {\n clearRequestedCompaction?: boolean;\n publishLiveEvents?: (events: SessionEvent[]) => Promise<void>;\n } = {},\n): Promise<Extract<MaybeCompactResult, { compacted: false }>> {\n const settled = await settleSkippedAfterStart(db, scope, options, \"summarization_failed\");\n await options.publishLiveEvents?.(settled.events);\n return settled;\n}\n\nfunction prependCompactionEvents(\n prefix: SessionEvent[],\n outcome: MaybeCompactResult,\n): MaybeCompactResult {\n if (prefix.length === 0) return outcome;\n return { ...outcome, events: [...prefix, ...outcome.events] };\n}\n\nasync function settleSkippedAfterStart(\n db: Database,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n options: {\n clearRequestedCompaction?: boolean;\n },\n reason:\n | \"no_history\"\n | \"replacement_not_smaller\"\n | \"replacement_unchanged\"\n | \"summarization_failed\",\n): Promise<Extract<MaybeCompactResult, { compacted: false }>> {\n const clearRequestedCompaction = options.clearRequestedCompaction === true;\n const skipped = await recordSkippedContextCompaction(db, {\n ...scope,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n reason,\n // After `compaction.started`, always settle the landmark. Do not require\n // an operator `/compact` flag — auto/overflow never set one.\n requirePendingRequest: false,\n clearRequestedCompaction,\n });\n if (!skipped.recorded) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced while recording a context compaction skip (${reason}): ${skipped.reason}`,\n );\n }\n return {\n compacted: false,\n reason,\n events: skipped.events,\n requestConsumed: clearRequestedCompaction,\n };\n}\n\nasync function compactContextRemoteV2(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n canonicalItems: CompactionItem[],\n items: CompactionItem[],\n decision: { signalTokens: number; thresholdTokens: number },\n options: {\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n requestRemoteCompactionV2?: RemoteCompactionV2Requester;\n },\n projectForWire: (items: CompactionItem[]) => Promise<CompactionItem[]>,\n): Promise<MaybeCompactResult> {\n if (!options.requestRemoteCompactionV2) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_requester\",\n reason: \"missing_requester\",\n });\n }\n const estimatedTokensBefore = estimateTokens(items);\n // Codex remote_v2: on a valid compaction item, install and recompute usage.\n // No local \"must shrink / must differ\" gate — that is portable-only.\n // Fail closed on provider/extract failure — no portable fallback.\n let providerCalls = 1;\n let rewrittenToolOutputs = 0;\n let compactionItem: CompactionItem;\n try {\n compactionItem = await options.requestRemoteCompactionV2(settings, items);\n } catch (error) {\n if (!isExactContextLengthExceeded(error)) throw error;\n const retry = projectRemoteCompactionOverflowRetryInput(items);\n if (retry.rewrittenToolOutputs === 0) throw error;\n providerCalls = 2;\n rewrittenToolOutputs = retry.rewrittenToolOutputs;\n compactionItem = await options.requestRemoteCompactionV2(settings, retry.input);\n }\n const replacementHistory = buildRemoteV2ReplacementHistory(canonicalItems, compactionItem);\n const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));\n const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);\n const tailItem = replacementHistory.at(-1);\n if (!tailItem) {\n throw new EmptyCompactionSummaryError({\n stage: \"remote_v2_replacement\",\n reason: \"no_replacement_history\",\n });\n }\n const applied = await applyContextCompaction(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: scope.sessionId,\n turnId: scope.turnId,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n replacementItems: replacementHistory.slice(0, -1),\n summaryItem: tailItem as Record<string, unknown>,\n ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),\n eventPayload: {\n trigger: options.trigger ?? \"auto\",\n implementation: REMOTE_COMPACTION_V2_IMPLEMENTATION,\n estimatedTokensBefore,\n estimatedTokensAfter,\n compactionInputToolOutputsRewritten: rewrittenToolOutputs,\n compactionInputProviderCalls: providerCalls,\n },\n });\n if (!applied.applied) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced during remote context compaction: ${applied.reason}`,\n );\n }\n return {\n compacted: true,\n supersededFrom: applied.supersededFrom,\n summaryPosition: applied.summaryPosition,\n signalTokens: decision.signalTokens,\n thresholdTokens: decision.thresholdTokens,\n estimatedTokensBefore,\n estimatedTokensAfter,\n replacementFingerprint,\n events: applied.events,\n };\n}\n\nasync function compactContextPortable(\n db: Database,\n settings: Settings,\n scope: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n executionGeneration: number;\n attemptId: string;\n },\n canonicalItems: CompactionItem[],\n items: CompactionItem[],\n decision: { signalTokens: number; thresholdTokens: number },\n summarize: CompactionSummarizer,\n options: {\n clearRequestedCompaction?: boolean;\n trigger?: \"auto\" | \"operator\" | \"proactive\" | \"overflow\";\n },\n projectForWire: (items: CompactionItem[]) => Promise<CompactionItem[]>,\n): Promise<MaybeCompactResult> {\n const estimatedTokensBefore = estimateTokens(items);\n const summarized = await summarizeWithCodexOverflowTrimming(summarize, settings, items);\n const summaryBody = summarized.summaryBody;\n const replacementHistory = buildCompactionReplacementHistory(canonicalItems, summaryBody);\n const estimatedTokensAfter = estimateTokens(await projectForWire(replacementHistory));\n const replacementFingerprint = compactionReplacementFingerprint(replacementHistory);\n const previousReplacementFingerprint = latestCompactionReplacementFingerprint(canonicalItems);\n const summaryItem = replacementHistory.at(-1);\n if (!summaryItem) {\n // Started already fanout; settle visibly so the landmark cannot stick on\n // \"Compacting…\". This is not an operator-request clear path.\n return await settleSkippedAfterStart(db, scope, options, \"summarization_failed\");\n }\n if (previousReplacementFingerprint === replacementFingerprint) {\n return await settleSkippedAfterStart(db, scope, options, \"replacement_unchanged\");\n }\n if (estimatedTokensAfter >= estimatedTokensBefore) {\n return await settleSkippedAfterStart(db, scope, options, \"replacement_not_smaller\");\n }\n const applied = await applyContextCompaction(db, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n sessionId: scope.sessionId,\n turnId: scope.turnId,\n expectedExecutionGeneration: scope.executionGeneration,\n expectedAttemptId: scope.attemptId,\n replacementItems: replacementHistory.slice(0, -1),\n summaryItem: summaryItem as Record<string, unknown>,\n ...(options.clearRequestedCompaction ? { clearRequestedCompaction: true } : {}),\n eventPayload: {\n trigger: options.trigger ?? \"auto\",\n estimatedTokensBefore,\n estimatedTokensAfter,\n compactionInputEstimatedTokens: summarized.preparation.estimatedInputTokens,\n compactionInputToolOutputsRewritten: summarized.preparation.rewrittenToolOutputs,\n compactionInputHistoryItemsDropped: summarized.preparation.droppedHistoryItems,\n compactionInputProviderCalls: summarized.providerCalls,\n },\n });\n if (!applied.applied) {\n throw new TurnAttemptFencedError(\n `turn attempt was fenced during context compaction: ${applied.reason}`,\n );\n }\n\n return {\n compacted: true,\n supersededFrom: applied.supersededFrom,\n summaryPosition: applied.summaryPosition,\n signalTokens: decision.signalTokens,\n thresholdTokens: decision.thresholdTokens,\n estimatedTokensBefore,\n estimatedTokensAfter,\n replacementFingerprint,\n events: applied.events,\n };\n}\n\nasync function summarizeWithCodexOverflowTrimming(\n summarize: CompactionSummarizer,\n settings: Settings,\n activeHistory: CompactionItem[],\n): Promise<{\n summaryBody: string;\n preparation: ReturnType<typeof prepareCompactionPromptInput>;\n providerCalls: number;\n}> {\n // Codex's estimator is intentionally coarse. Keep the explicit checkpoint\n // request below both the effective input window and the raw window minus the\n // requested summary, then leave 15% estimator headroom. This changes only the\n // temporary summarizer input; durable active history remains untouched until\n // applyContextCompaction succeeds under the attempt fence.\n const summaryAwareBudget = Math.max(0, settings.contextWindowTokens - SUMMARY_BUFFER_TOKENS);\n const configuredInputBudget = contextInputBudgetTokens(settings);\n const structuralBudget = Math.min(\n configuredInputBudget > 0 ? configuredInputBudget : summaryAwareBudget,\n summaryAwareBudget,\n );\n const initialBudget = Math.floor(structuralBudget * 0.85);\n let preparation = prepareCompactionPromptInput(activeHistory, initialBudget);\n try {\n return {\n summaryBody: await summarize(settings, preparation.input),\n preparation,\n providerCalls: 1,\n };\n } catch (error) {\n if (!isContextWindowExceeded(error)) throw error;\n // The provider is more authoritative than the byte/4 estimate. Refit once\n // to 70% of both the configured target and the actual prepared estimate;\n // then fail terminally with prior history intact. Never issue one failing\n // request per oldest item. The production incident proved that the\n // provider can count slightly more than twice the byte/4 estimate, so a\n // half-size retry is the smallest honest bound for that observed skew.\n const retryBudget = Math.floor(\n Math.min(initialBudget * 0.5, preparation.estimatedInputTokens * 0.5),\n );\n preparation = prepareCompactionPromptInput(activeHistory, retryBudget);\n return {\n summaryBody: await summarize(settings, preparation.input),\n preparation,\n providerCalls: 2,\n };\n }\n}\n\nexport function isContextWindowExceeded(error: unknown, seen = new WeakSet<object>()): boolean {\n if (!error || typeof error !== \"object\") return false;\n if (seen.has(error)) return false;\n seen.add(error);\n const record = error as Record<string, unknown>;\n const code = typeof record.code === \"string\" ? record.code.toLowerCase() : \"\";\n const message =\n typeof record.message === \"string\"\n ? record.message.toLowerCase()\n : error instanceof Error\n ? error.message.toLowerCase()\n : \"\";\n const direct =\n code === \"context_length_exceeded\" ||\n code === \"context_window_exceeded\" ||\n message.includes(\"context window\") ||\n message.includes(\"maximum context length\") ||\n message.includes(\"too many tokens\");\n return (\n direct ||\n isContextWindowExceeded(record.cause, seen) ||\n isContextWindowExceeded(record.error, seen) ||\n isContextWindowExceeded(record.diagnostics, seen)\n );\n}\n\nexport function isExactContextLengthExceeded(\n error: unknown,\n seen = new WeakSet<object>(),\n): boolean {\n if (!error || typeof error !== \"object\") return false;\n if (seen.has(error)) return false;\n seen.add(error);\n const record = error as Record<string, unknown>;\n if (record.code === \"context_length_exceeded\") {\n return true;\n }\n return (\n isExactContextLengthExceeded(record.cause, seen) ||\n isExactContextLengthExceeded(record.error, seen) ||\n isExactContextLengthExceeded(record.diagnostics, seen)\n );\n}\n","import {\n MODEL_ATTACHMENT_REFS_FIELD,\n FileResourceRef,\n resourceMountPath,\n type FileAsset,\n type ResourceRef,\n} from \"@opengeni/contracts\";\nimport { createHash } from \"node:crypto\";\nimport {\n getActiveSessionHistoryItemsPaged,\n getFiles,\n getLatestRunState,\n getHumanInputResumeForEvent,\n getSandboxSessionEnvelope,\n getSessionEvent,\n listSessionSystemUpdatesForTurn,\n requireFile,\n type Database,\n} from \"@opengeni/db\";\nimport {\n projectHistoryForProvider,\n projectRejectedProviderArtifactsFromSerializedRunState,\n projectRejectedReasoningArtifact,\n hasOpaqueProviderArtifact,\n type HistoryProviderApi,\n type OpenGeniRuntime,\n} from \"@opengeni/runtime\";\n\n/** Project only artifacts explicitly rejected by the provider out of its next view. */\nexport function projectRejectedProviderArtifacts(\n rows: ReadonlyArray<{\n item: Record<string, unknown>;\n providerArtifactInvalidatedAt?: Date | null;\n }>,\n): Array<Record<string, unknown>> {\n const out: Array<Record<string, unknown>> = [];\n for (const row of rows) {\n if (!row.providerArtifactInvalidatedAt) {\n out.push(row.item);\n continue;\n }\n const type = typeof row.item.type === \"string\" ? row.item.type : undefined;\n if (type === \"reasoning\") {\n out.push(projectRejectedReasoningArtifact(row.item));\n continue;\n }\n if (type === \"compaction\") {\n continue;\n }\n out.push(row.item);\n }\n return out;\n}\n\n/** Build the attempt-local RunState view after an explicit provider rejection. */\nexport function resumeRunState(state: {\n serializedRunState: string;\n providerArtifactInvalidatedAt?: Date | null;\n}): string {\n if (!state.providerArtifactInvalidatedAt) {\n return state.serializedRunState;\n }\n return projectRejectedProviderArtifactsFromSerializedRunState(state.serializedRunState);\n}\n\n/** Prepared input and its exact durable-history prefix length for reconciliation. */\nexport type PreparedTurnInput = {\n input: Awaited<ReturnType<OpenGeniRuntime[\"prepareInput\"]>>;\n persistedHistoryCount: number;\n providerArtifactCandidates: {\n knownHistoryItemIds: string[];\n historyItemIds: string[];\n runStateId?: string;\n };\n};\n\nexport type TurnInputOptions = {\n turnId: string;\n recovering?: boolean;\n unavailableSandboxFilesNote?: string;\n runCredentialsNote?: string;\n providerApi: HistoryProviderApi;\n projectCanonicalHistory?: ModelHistoryAttachmentProjector;\n materializeModelHistory?: ModelHistoryAttachmentProjector;\n materializeSerializedRunState?: (serialized: string) => Promise<string>;\n projectModelHistory?: ModelHistoryAttachmentProjector;\n loadActiveHistory?: typeof getActiveSessionHistoryItemsPaged;\n /** Bounded critical-path timings; telemetry failures never affect preparation. */\n onPreparationPhase?: (measurement: HistoryPreparationPhaseMeasurement) => void;\n};\n\nexport type HistoryPreparationPhase =\n | \"system_update_load\"\n | \"current_attachment_resolution\"\n | \"durable_history_load\"\n | \"sandbox_envelope_load\"\n | \"canonical_projection\"\n | \"provider_projection\"\n | \"attachment_ref_projection\"\n | \"screenshot_materialization\"\n | \"model_attachment_projection\"\n | \"runtime_input_assembly\"\n | \"artifact_candidate_scan\";\n\nexport type HistoryPreparationPhaseMeasurement = {\n phase: HistoryPreparationPhase;\n outcome: \"completed\" | \"failed\";\n durationSeconds: number;\n};\n\nasync function measureHistoryPreparationPhase<T>(\n options: Pick<TurnInputOptions, \"onPreparationPhase\">,\n phase: HistoryPreparationPhase,\n operation: () => T | Promise<T>,\n): Promise<T> {\n const startedAt = performance.now();\n let outcome: HistoryPreparationPhaseMeasurement[\"outcome\"] = \"completed\";\n try {\n return await operation();\n } catch (error) {\n outcome = \"failed\";\n throw error;\n } finally {\n try {\n options.onPreparationPhase?.({\n phase,\n outcome,\n durationSeconds: (performance.now() - startedAt) / 1_000,\n });\n } catch {\n // Diagnostics must not change durable history or provider input.\n }\n }\n}\n\nexport const MAX_INLINE_MODEL_ATTACHMENT_BYTES = 20 * 1024 * 1024;\n\nexport type ModelAttachmentContent = {\n kind: \"image\" | \"file\";\n fileId: string;\n filename: string;\n contentType: string;\n dataUrl: string;\n};\n\nexport type ModelHistoryAttachmentProjector = (\n items: Array<Record<string, unknown>>,\n) => Promise<Array<Record<string, unknown>>>;\n\nexport type ModelAttachmentInputPolicy = {\n supportsImageInput: boolean;\n inputFileMediaTypes: readonly string[];\n};\n\nconst MODEL_IMAGE_CONTENT_TYPES = new Set([\"image/gif\", \"image/jpeg\", \"image/png\", \"image/webp\"]);\n\nconst MODEL_FILE_CONTENT_TYPES = new Set([\n \"application/json\",\n \"application/pdf\",\n \"application/x-yaml\",\n \"application/yaml\",\n]);\n\n// Generic XML has equivalent application/* and text/* registrations. Keep both\n// aliases on the sandbox-path fallback until a provider parser boundary is\n// explicitly supported and verified; MIME spelling must not bypass the fence.\nconst BLOCKED_TEXT_CONTENT_TYPES = new Set([\n \"text/css\",\n \"text/html\",\n \"text/javascript\",\n \"text/xml\",\n]);\n\nfunction safeErrorType(error: unknown): string {\n if (!(error instanceof Error)) return typeof error;\n const name = error.name.trim();\n return /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/.test(name) ? name : \"Error\";\n}\n\nfunction modelAttachmentDescriptor(\n contentType: string,\n): Pick<ModelAttachmentContent, \"kind\" | \"contentType\"> | null {\n const normalized = contentType.toLowerCase().split(\";\", 1)[0]?.trim() ?? \"\";\n if (MODEL_IMAGE_CONTENT_TYPES.has(normalized)) {\n return { kind: \"image\", contentType: normalized };\n }\n if (\n MODEL_FILE_CONTENT_TYPES.has(normalized) ||\n (normalized.startsWith(\"text/\") && !BLOCKED_TEXT_CONTENT_TYPES.has(normalized))\n ) {\n return { kind: \"file\", contentType: normalized };\n }\n return null;\n}\n\nexport async function modelAttachmentContentForFiles(\n files: FileAsset[],\n readFileBytes: (file: FileAsset) => Promise<Uint8Array>,\n): Promise<ModelAttachmentContent[]> {\n const selected: Array<{\n file: FileAsset;\n descriptor: Pick<ModelAttachmentContent, \"kind\" | \"contentType\">;\n checksum: string;\n }> = [];\n let remainingBytes = MAX_INLINE_MODEL_ATTACHMENT_BYTES;\n for (const file of files) {\n const descriptor = modelAttachmentDescriptor(file.contentType);\n const checksum = file.sha256?.trim().toLowerCase() ?? \"\";\n if (\n file.status !== \"ready\" ||\n !descriptor ||\n file.sizeBytes > remainingBytes ||\n !/^[a-f0-9]{64}$/.test(checksum)\n ) {\n continue;\n }\n selected.push({ file, descriptor, checksum });\n remainingBytes -= file.sizeBytes;\n }\n\n const attachments = new Array<ModelAttachmentContent | undefined>(selected.length);\n let cursor = 0;\n const worker = async () => {\n while (cursor < selected.length) {\n const index = cursor++;\n const { file, descriptor, checksum } = selected[index]!;\n try {\n const bytes = await readFileBytes(file);\n if (bytes.byteLength !== file.sizeBytes) {\n console.error(\"model attachment bytes did not match finalized metadata\", {\n fileId: file.id,\n expectedSizeBytes: file.sizeBytes,\n actualSizeBytes: bytes.byteLength,\n });\n continue;\n }\n if (createHash(\"sha256\").update(bytes).digest(\"hex\") !== checksum) {\n console.error(\"model attachment checksum did not match finalized metadata\", {\n fileId: file.id,\n });\n continue;\n }\n attachments[index] = {\n kind: descriptor.kind,\n fileId: file.id,\n filename: file.safeFilename,\n contentType: descriptor.contentType,\n dataUrl: `data:${descriptor.contentType};base64,${Buffer.from(bytes).toString(\"base64\")}`,\n };\n } catch (error) {\n // The sandbox-path projection remains available for every file. A direct\n // provider-content read is an additive fast path and must not turn a\n // transient storage read into loss of the accepted prompt.\n console.error(\"model attachment content read failed; retaining sandbox path fallback\", {\n fileId: file.id,\n errorType: safeErrorType(error),\n });\n }\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(8, selected.length) }, async () => await worker()),\n );\n return attachments.filter(\n (attachment): attachment is ModelAttachmentContent => attachment !== undefined,\n );\n}\n\nfunction modelAcceptsFileMediaType(\n policy: ModelAttachmentInputPolicy,\n contentType: string,\n): boolean {\n const normalized = contentType.toLowerCase().split(\";\", 1)[0]?.trim() ?? \"\";\n return policy.inputFileMediaTypes.some(\n (accepted) =>\n accepted === normalized ||\n (accepted.endsWith(\"/*\") && normalized.startsWith(accepted.slice(0, -1))),\n );\n}\n\nfunction attachmentRefsFromItem(item: Record<string, unknown>): FileResourceRef[] {\n const raw = item[MODEL_ATTACHMENT_REFS_FIELD];\n if (!Array.isArray(raw)) return [];\n const refs: FileResourceRef[] = [];\n for (const candidate of raw) {\n const parsed = FileResourceRef.safeParse(candidate);\n if (parsed.success) refs.push(parsed.data);\n }\n return refs;\n}\n\nfunction attachmentUnavailableText(ref: FileResourceRef, file: FileAsset | undefined): string {\n const filename = file?.safeFilename ?? ref.fileId;\n const mediaType = file?.contentType ?? \"unknown type\";\n const path = file ? sandboxFilePath(ref, file) : `/workspace/${resourceMountPath(ref)}`;\n return (\n `[Attachment not included directly because the selected model does not accept this input ` +\n `or it exceeded the safe inline limit: ${filename} (${mediaType}). ` +\n `It remains available to tools in the sandbox at ${path}.]`\n );\n}\n\n/**\n * Build one turn-scoped durable-attachment projector. Metadata is batch-loaded\n * and file bytes are memoized, so compaction/retry can reuse the same work and\n * the SDK's repeated tool loop never touches storage or rescans old history.\n */\nexport function createModelHistoryAttachmentProjector(\n db: Database,\n workspaceId: string,\n policy: ModelAttachmentInputPolicy,\n readFileBytes?: (file: FileAsset) => Promise<Uint8Array>,\n): ModelHistoryAttachmentProjector {\n const fileById = new Map<string, FileAsset>();\n const missingFileIds = new Set<string>();\n const contentById = new Map<string, ModelAttachmentContent>();\n const attemptedContentIds = new Set<string>();\n\n return async (items) => {\n const refsByIndex = new Map<number, FileResourceRef[]>();\n const orderedFileIds: string[] = [];\n const seenFileIds = new Set<string>();\n for (let index = 0; index < items.length; index += 1) {\n const refs = attachmentRefsFromItem(items[index]!);\n if (refs.length === 0) continue;\n refsByIndex.set(index, refs);\n for (const ref of refs) {\n if (seenFileIds.has(ref.fileId)) continue;\n seenFileIds.add(ref.fileId);\n orderedFileIds.push(ref.fileId);\n }\n }\n if (refsByIndex.size === 0) return items;\n\n const unknownIds = orderedFileIds.filter((id) => !fileById.has(id) && !missingFileIds.has(id));\n if (unknownIds.length > 0) {\n const files = await getFiles(db, workspaceId, unknownIds);\n for (const file of files) fileById.set(file.id, file);\n for (const id of unknownIds) {\n if (!fileById.has(id)) missingFileIds.add(id);\n }\n }\n\n if (readFileBytes) {\n // Prefer the newest attachments if the aggregate request safety limit is\n // reached; an old image becomes a marker instead of hiding the new prompt.\n const readable = [...orderedFileIds]\n .reverse()\n .map((id) => fileById.get(id))\n .filter((file): file is FileAsset => {\n if (!file || attemptedContentIds.has(file.id)) return false;\n const descriptor = modelAttachmentDescriptor(file.contentType);\n return Boolean(\n descriptor &&\n ((descriptor.kind === \"image\" && policy.supportsImageInput) ||\n (descriptor.kind === \"file\" && modelAcceptsFileMediaType(policy, file.contentType))),\n );\n });\n for (const file of readable) attemptedContentIds.add(file.id);\n const content = await modelAttachmentContentForFiles(readable, readFileBytes);\n for (const attachment of content) contentById.set(attachment.fileId, attachment);\n }\n\n const projected = [...items];\n for (const [index, refs] of refsByIndex) {\n const original = items[index]!;\n const existingContent = Array.isArray(original.content)\n ? [...original.content]\n : [{ type: \"input_text\", text: String(original.content ?? \"\") }];\n const attachmentParts = refs.map((ref) => {\n const attachment = contentById.get(ref.fileId);\n if (!attachment) {\n return {\n type: \"input_text\",\n text: attachmentUnavailableText(ref, fileById.get(ref.fileId)),\n };\n }\n return attachment.kind === \"image\"\n ? { type: \"input_image\", image: attachment.dataUrl }\n : {\n type: \"input_file\",\n file: attachment.dataUrl,\n filename: attachment.filename,\n };\n });\n const clone: Record<string, unknown> = {\n ...original,\n content: [...existingContent, ...attachmentParts],\n };\n delete clone[MODEL_ATTACHMENT_REFS_FIELD];\n projected[index] = clone;\n }\n return projected;\n };\n}\n\n/** Add current trigger refs only when older/local history predates durable stamping. */\nexport function withCurrentUserAttachmentRefs(\n historyItems: Array<Record<string, unknown>>,\n refs: FileResourceRef[],\n): Array<Record<string, unknown>> {\n if (refs.length === 0) return historyItems;\n for (let index = historyItems.length - 1; index >= 0; index -= 1) {\n const item = historyItems[index]!;\n if (item.type !== \"message\" || item.role !== \"user\") continue;\n const existing = attachmentRefsFromItem(item);\n const existingIds = new Set(existing.map((ref) => ref.fileId));\n const additions = refs.filter((ref) => !existingIds.has(ref.fileId));\n if (additions.length === 0) return historyItems;\n const projected = [...historyItems];\n projected[index] = { ...item, [MODEL_ATTACHMENT_REFS_FIELD]: [...existing, ...additions] };\n return projected;\n }\n return historyItems;\n}\n\nexport async function turnInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: Awaited<ReturnType<typeof getSessionEvent>>,\n options: TurnInputOptions,\n): Promise<PreparedTurnInput> {\n if (!trigger) {\n throw new Error(\"Missing trigger event\");\n }\n const updates = await measureHistoryPreparationPhase(\n options,\n \"system_update_load\",\n async () =>\n await listSessionSystemUpdatesForTurn(\n db,\n trigger.workspaceId,\n trigger.sessionId,\n options.turnId,\n ),\n );\n if (updates.length > 0) {\n const historyItemIds = new Set(\n updates.map((update) => update.deliveredHistoryItemId).filter(Boolean),\n );\n if (historyItemIds.size !== 1 || updates.some((update) => !update.deliveredHistoryItemId)) {\n throw new Error(\"Delivered internal updates have no single durable model-memory batch\");\n }\n }\n const internalContext = joinInternalContext(\n options.recovering\n ? [\n \"[OpenGeni inference recovery]\",\n \"Continue the same inference from durable conversation and sandbox state. A previous execution stopped before it could finish. Do not repeat completed side effects; inspect actual state when uncertain.\",\n ].join(\"\\n\")\n : undefined,\n options.unavailableSandboxFilesNote,\n options.runCredentialsNote,\n );\n if (trigger.type === \"user.message\") {\n const payload = trigger.payload as {\n text?: unknown;\n annotations?: unknown;\n resources?: unknown;\n };\n const hasAnnotations = Array.isArray(payload.annotations) && payload.annotations.length > 0;\n if (typeof payload.text !== \"string\" || (payload.text.trim().length === 0 && !hasAnnotations)) {\n throw new Error(\"user.message payload is missing text and annotations\");\n }\n const resources = Array.isArray(payload.resources) ? (payload.resources as ResourceRef[]) : [];\n const fileAttachments = await measureHistoryPreparationPhase(\n options,\n \"current_attachment_resolution\",\n async () => await resolveUserMessageFileAttachments(db, trigger.workspaceId, resources),\n );\n const attachmentContext = userMessageAttachmentsContext(fileAttachments);\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n joinInternalContext(internalContext, attachmentContext),\n fileAttachments.map((attachment) => attachment.resource),\n options.providerApi,\n options.projectCanonicalHistory,\n options.materializeModelHistory,\n options.projectModelHistory,\n options.loadActiveHistory,\n options,\n );\n }\n if (trigger.type === \"system.update.delivered\") {\n if (updates.length === 0) {\n throw new Error(\"Internal update inference has no delivered updates\");\n }\n return await messageInput(\n db,\n runtime,\n agent,\n trigger,\n undefined,\n internalContext,\n [],\n options.providerApi,\n options.projectCanonicalHistory,\n options.materializeModelHistory,\n options.projectModelHistory,\n options.loadActiveHistory,\n options,\n );\n }\n if (trigger.type === \"user.approvalDecision\") {\n const payload = trigger.payload as {\n approvalId?: unknown;\n decision?: unknown;\n message?: unknown;\n };\n // Approvals are the one path that legitimately requires the RunState blob:\n // a turn frozen mid-flight cannot be represented as plain history items.\n const state = await getLatestRunState(db, trigger.workspaceId, trigger.sessionId);\n if (!state) {\n throw new Error(\"No saved run state is available for approval decision\");\n }\n const serializedRunState = resumeRunState(state);\n const prepared = await runtime.prepareInput(agent, {\n kind: \"approval\",\n serializedRunState: options.materializeSerializedRunState\n ? await options.materializeSerializedRunState(serializedRunState)\n : serializedRunState,\n approvalId: String(payload.approvalId ?? \"\"),\n decision: payload.decision === \"approve\" ? \"approve\" : \"reject\",\n ...(typeof payload.message === \"string\" ? { message: payload.message } : {}),\n });\n return {\n input: prepared,\n persistedHistoryCount: prepared.persistedHistoryCount,\n providerArtifactCandidates: {\n knownHistoryItemIds: [],\n historyItemIds: [],\n runStateId: state.id,\n },\n };\n }\n if (trigger.type === \"user.humanInputResponse\") {\n const [state, resume] = await Promise.all([\n getLatestRunState(db, trigger.workspaceId, trigger.sessionId),\n getHumanInputResumeForEvent(db, trigger.workspaceId, trigger.sessionId, trigger),\n ]);\n if (!state) {\n throw new Error(\"No saved run state is available for human-input response\");\n }\n if (!resume) {\n throw new Error(\"Human-input response does not resolve to a durable request\");\n }\n const serializedRunState = resumeRunState(state);\n const prepared = await runtime.prepareInput(agent, {\n kind: \"human_input\",\n serializedRunState: options.materializeSerializedRunState\n ? await options.materializeSerializedRunState(serializedRunState)\n : serializedRunState,\n toolCallId: resume.toolCallId,\n });\n return {\n input: prepared,\n persistedHistoryCount: prepared.persistedHistoryCount,\n providerArtifactCandidates: {\n knownHistoryItemIds: [],\n historyItemIds: [],\n runStateId: state.id,\n },\n };\n }\n throw new Error(`Unsupported trigger event type: ${trigger.type}`);\n}\n\nfunction joinInternalContext(...parts: Array<string | undefined>): string | undefined {\n const content = parts.map((part) => part?.trim()).filter((part): part is string => Boolean(part));\n return content.length > 0 ? content.join(\"\\n\\n\") : undefined;\n}\n\n/** Build one inference from canonical history plus attempt-local operational context. */\nasync function messageInput(\n db: Database,\n runtime: OpenGeniRuntime,\n agent: any,\n trigger: NonNullable<Awaited<ReturnType<typeof getSessionEvent>>>,\n text: string | undefined,\n internalContext: string | undefined,\n currentAttachmentRefs: FileResourceRef[] = [],\n providerApi: HistoryProviderApi = \"responses\",\n projectCanonicalHistory?: ModelHistoryAttachmentProjector,\n materializeModelHistory?: ModelHistoryAttachmentProjector,\n projectModelHistory?: ModelHistoryAttachmentProjector,\n loadActiveHistory: typeof getActiveSessionHistoryItemsPaged = getActiveSessionHistoryItemsPaged,\n preparationOptions: Pick<TurnInputOptions, \"onPreparationPhase\"> = {},\n): Promise<PreparedTurnInput> {\n const [stored, envelope] = await Promise.all([\n measureHistoryPreparationPhase(preparationOptions, \"durable_history_load\", async () =>\n loadActiveHistory(db, trigger.workspaceId, trigger.sessionId),\n ),\n measureHistoryPreparationPhase(preparationOptions, \"sandbox_envelope_load\", async () =>\n getSandboxSessionEnvelope(db, trigger.workspaceId, trigger.sessionId),\n ),\n ]);\n const canonicalView = await measureHistoryPreparationPhase(\n preparationOptions,\n \"canonical_projection\",\n async () => {\n const active = projectRejectedProviderArtifacts(stored);\n return projectCanonicalHistory ? await projectCanonicalHistory(active) : active;\n },\n );\n const providerView = await measureHistoryPreparationPhase(\n preparationOptions,\n \"provider_projection\",\n () => projectHistoryForProvider(canonicalView, providerApi),\n );\n const referencedHistory = await measureHistoryPreparationPhase(\n preparationOptions,\n \"attachment_ref_projection\",\n () => withCurrentUserAttachmentRefs(providerView, currentAttachmentRefs),\n );\n const materializedHistory = await measureHistoryPreparationPhase(\n preparationOptions,\n \"screenshot_materialization\",\n async () =>\n materializeModelHistory\n ? await materializeModelHistory(referencedHistory)\n : referencedHistory,\n );\n const historyItems = await measureHistoryPreparationPhase(\n preparationOptions,\n \"model_attachment_projection\",\n async () =>\n projectModelHistory ? await projectModelHistory(materializedHistory) : materializedHistory,\n );\n const prepared = await measureHistoryPreparationPhase(\n preparationOptions,\n \"runtime_input_assembly\",\n async () =>\n await runtime.prepareInput(agent, {\n kind: \"message\",\n ...(text ? { text } : {}),\n ...(internalContext ? { internalContext } : {}),\n historyItems: historyItems as any,\n sandboxEnvelope: envelope,\n ...(projectModelHistory ? { modelInputAlreadyProjected: true } : {}),\n }),\n );\n const providerArtifactCandidates = await measureHistoryPreparationPhase(\n preparationOptions,\n \"artifact_candidate_scan\",\n () => {\n const preparedItems = Array.isArray(prepared.input)\n ? new Set(prepared.input)\n : new Set<unknown>();\n return {\n knownHistoryItemIds: stored.map((row) => row.id),\n historyItemIds: stored\n .filter(\n (row) =>\n row.providerArtifactInvalidatedAt === null &&\n hasOpaqueProviderArtifact(row.item) &&\n preparedItems.has(row.item),\n )\n .map((row) => row.id),\n };\n },\n );\n return {\n input: prepared,\n persistedHistoryCount: prepared.persistedHistoryCount,\n providerArtifactCandidates,\n };\n}\n\nexport async function userMessageTextWithAttachments(\n db: Database,\n workspaceId: string,\n text: string,\n resources: ResourceRef[],\n): Promise<string> {\n const fileAttachments = await resolveUserMessageFileAttachments(db, workspaceId, resources);\n const attachmentContext = userMessageAttachmentsContext(fileAttachments);\n return attachmentContext ? [text, \"\", attachmentContext].join(\"\\n\") : text;\n}\n\ntype UserMessageFileAttachment = {\n resource: Extract<ResourceRef, { kind: \"file\" }>;\n file: FileAsset;\n};\n\nasync function resolveUserMessageFileAttachments(\n db: Database,\n workspaceId: string,\n resources: ResourceRef[],\n): Promise<UserMessageFileAttachment[]> {\n const attachments: UserMessageFileAttachment[] = [];\n for (const resource of resources) {\n if (resource.kind !== \"file\") continue;\n const file = await requireFile(db, workspaceId, resource.fileId);\n attachments.push({ resource, file });\n }\n return attachments;\n}\n\nfunction userMessageAttachmentsContext(\n attachments: UserMessageFileAttachment[],\n): string | undefined {\n const attachedFiles = attachments.map(\n ({ resource, file }) =>\n `- ${file.filename} (${file.contentType}, ${file.sizeBytes} bytes): ${sandboxFilePath(resource, file)}`,\n );\n if (attachedFiles.length === 0) {\n return undefined;\n }\n return [\"Attached files are available in the sandbox:\", ...attachedFiles].join(\"\\n\");\n}\n\nfunction sandboxFilePath(\n resource: Extract<ResourceRef, { kind: \"file\" }>,\n file: FileAsset,\n): string {\n return `/workspace/${resourceMountPath(resource)}/${file.safeFilename}`;\n}\n","import {\n VideoGenerationAcceptedReceipt,\n type GenerateVideoToolInput,\n type VideoGenerationCapabilities,\n type VideoGenerationPolicy,\n type XaiProviderAccountAuthoritySnapshotV1,\n} from \"@opengeni/contracts\";\nimport {\n normalizeVideoGenerationRequest,\n videoGenerationAdmissionKey,\n videoGenerationProviderIdempotencyKey,\n videoGenerationRequestDigest,\n} from \"@opengeni/core\";\nimport { videoGenerationCapabilitiesForPolicy } from \"@opengeni/core\";\nimport {\n admitVideoGenerationOperation,\n encryptEnvironmentValue,\n getVideoGenerationOperation,\n markVideoGenerationPrepared,\n type Database,\n type VideoGenerationReference,\n type XaiCredentialForRun,\n} from \"@opengeni/db\";\nimport {\n calculateVideoGenerationCreditCostMicros,\n environmentsEncryptionKeyBytes,\n type Settings,\n} from \"@opengeni/config\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n inspectSandboxVideoReferences,\n uploadAndVerifyVideoReferences,\n videoReferenceStagingKey,\n type SandboxCommandRunner,\n} from \"./video-reference-staging\";\nimport {\n encryptVideoGenerationApiKey,\n encryptVideoGenerationXaiCredential,\n} from \"./video-generation-credential\";\n\nexport type VideoGenerationCredentialLease = Readonly<{\n fundingSource: \"opengeni_credits\" | \"workspace_gateway\" | \"supergrok_subscription\";\n connectionId: string | null;\n version: number;\n credentialEncrypted: string;\n}>;\n\nexport type AcceptedVideoGeneration = Readonly<{\n receipt: ReturnType<typeof VideoGenerationAcceptedReceipt.parse>;\n operationId: string;\n requestDigest: string;\n}>;\n\nexport function videoCapabilitiesForTurn(input: {\n policy: VideoGenerationPolicy;\n credential: VideoGenerationCredentialLease;\n}): VideoGenerationCapabilities {\n if (input.policy.fundingSource !== input.credential.fundingSource) {\n throw new Error(\"Video generation funding changed before capability resolution\");\n }\n return videoGenerationCapabilitiesForPolicy({\n policy: input.policy,\n credentialVersion: input.credential.version,\n });\n}\n\nexport function managedVideoGenerationCredentialLease(\n settings: Settings,\n): VideoGenerationCredentialLease | null {\n if (!settings.vercelAiGatewayApiKey) return null;\n const encryptionKey = environmentsEncryptionKeyBytes(settings);\n if (!encryptionKey) {\n throw new Error(\"Managed video generation requires OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n return Object.freeze({\n fundingSource: \"opengeni_credits\",\n connectionId: null,\n version: 1,\n credentialEncrypted: encryptVideoGenerationApiKey(\n encryptionKey,\n settings.vercelAiGatewayApiKey,\n ),\n });\n}\n\nexport function xaiVideoGenerationCredentialLease(input: {\n settings: Settings;\n credential: XaiCredentialForRun;\n subjectId: string;\n authoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;\n}): VideoGenerationCredentialLease {\n const encryptionKey = environmentsEncryptionKeyBytes(input.settings);\n if (!encryptionKey) {\n throw new Error(\"SuperGrok video generation requires OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n const { accessToken, refreshToken } = input.credential.secret;\n const userId = input.credential.providerAccountId;\n if (!accessToken || !refreshToken || !userId) {\n throw new Error(\"The selected SuperGrok account cannot fund video generation\");\n }\n return Object.freeze({\n fundingSource: \"supergrok_subscription\",\n connectionId: null,\n version: input.credential.version,\n credentialEncrypted: encryptVideoGenerationXaiCredential(encryptionKey, {\n accessToken,\n refreshToken,\n userId,\n credentialId: input.credential.id,\n subjectId: input.subjectId,\n authoritySnapshot: input.authoritySnapshot,\n }),\n });\n}\n\nexport async function admitVideoGenerationRequest(input: {\n db: Database;\n storage: ObjectStorage;\n settings: Settings;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n toolInput: GenerateVideoToolInput;\n policy: VideoGenerationPolicy;\n credential: VideoGenerationCredentialLease;\n runCommand?: SandboxCommandRunner;\n signal?: AbortSignal;\n}): Promise<AcceptedVideoGeneration> {\n const capabilities = videoCapabilitiesForTurn({\n policy: input.policy,\n credential: input.credential,\n });\n const selectedModelId = input.toolInput.modelId ?? capabilities.defaultModelId;\n const model = capabilities.models.find((candidate) => candidate.modelId === selectedModelId);\n if (!model) throw new Error(\"The requested video model is not enabled for this workspace\");\n\n const sourceMode = input.toolInput.source?.mode ?? \"text\";\n if (sourceMode !== \"text\" && !input.runCommand) {\n throw new Error(\"Video references require an active sandbox\");\n }\n const inspected = input.runCommand\n ? await inspectSandboxVideoReferences({\n request: input.toolInput,\n runCommand: input.runCommand,\n })\n : [];\n const canonical = normalizeVideoGenerationRequest({\n toolInput: input.toolInput,\n model,\n sealedReferences: inspected.map((reference) => ({\n role: reference.role,\n contentSha256: reference.sha256,\n contentType: reference.contentType,\n byteSize: reference.sizeBytes,\n })),\n });\n const requestDigest = videoGenerationRequestDigest(canonical);\n const shouldDebitManagedCredits =\n input.credential.fundingSource === \"opengeni_credits\" &&\n (input.settings.billingMode === \"stripe\" || input.settings.usageLimitsMode === \"managed\");\n const pricedCostMicros = shouldDebitManagedCredits\n ? calculateVideoGenerationCreditCostMicros(input.settings, canonical)\n : 0;\n const admissionKey = videoGenerationAdmissionKey(input);\n const candidateOperationId = randomUUID();\n const expectedArtifactId = randomUUID();\n const expectedFileId = randomUUID();\n const providerIdempotencyKey = videoGenerationProviderIdempotencyKey({\n operationId: candidateOperationId,\n requestDigest,\n });\n const encryptionKey = environmentsEncryptionKeyBytes(input.settings);\n if (!encryptionKey) {\n throw new Error(\"Video generation requires OPENGENI_ENVIRONMENTS_ENCRYPTION_KEY\");\n }\n const now = Date.now();\n const recoveryDeadlineAt = new Date(now + input.settings.videoGenerationRecoveryDeadlineMs);\n const stagingKeys = inspected.map((reference) =>\n videoReferenceStagingKey({\n workspaceId: input.workspaceId,\n operationId: candidateOperationId,\n ordinal: reference.ordinal,\n sha256: reference.sha256,\n }),\n );\n const admitted = await admitVideoGenerationOperation(input.db, {\n id: candidateOperationId,\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n toolCallId: input.toolCallId,\n admissionKey,\n requestDigest,\n promptDigest: createHash(\"sha256\").update(canonical.prompt).digest(\"hex\"),\n requestEncrypted: encryptEnvironmentValue(encryptionKey, JSON.stringify(canonical)),\n modelId: canonical.modelId,\n sourceMode: canonical.sourceMode,\n capabilityRevision: capabilities.capabilityRevision,\n policyRevision: input.policy.revision,\n fundingSource: input.credential.fundingSource,\n pricedCostMicros,\n connectionId: input.credential.connectionId,\n credentialVersion: input.credential.version,\n credentialEncrypted: input.credential.credentialEncrypted,\n providerIdempotencyKey,\n expectedArtifactId,\n expectedFileId,\n workspaceQuotaBytes: input.settings.videoGenerationWorkspaceQuotaBytes,\n maxConcurrentPerWorkspace: input.settings.videoGenerationMaxConcurrentPerWorkspace,\n recoveryDeadlineAt,\n references: inspected.map((reference, index) => ({\n ordinal: reference.ordinal,\n role: reference.role,\n contentType: reference.contentType,\n sizeBytes: reference.sizeBytes,\n sha256: reference.sha256,\n stagingObjectKey: stagingKeys[index]!,\n grantExpiresAt: null,\n cleanupAfter: recoveryDeadlineAt,\n })),\n });\n const operation = await getVideoGenerationOperation(\n input.db,\n input.workspaceId,\n admitted.operation.id,\n );\n if (!operation) throw new Error(\"Admitted video generation operation disappeared\");\n if (operation.status === \"preparing\") {\n assertStoredReferencePlan(operation.references, inspected);\n if (inspected.length > 0) {\n if (!input.runCommand) throw new Error(\"Prepared video references lost their sandbox\");\n await uploadAndVerifyVideoReferences({\n storage: input.storage,\n references: inspected,\n stagingKeys: operation.references.map((reference) => {\n if (!reference.stagingObjectKey) {\n throw new Error(\"Video reference staging key is missing\");\n }\n return reference.stagingObjectKey;\n }),\n runCommand: input.runCommand,\n tempRoot: input.settings.videoGenerationTempDirectory,\n ffprobePath: input.settings.videoGenerationFfprobePath,\n uploadTtlSeconds: input.settings.videoGenerationReferenceUrlTtlSeconds,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n }\n await markVideoGenerationPrepared(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest,\n });\n } else if (\n ![\n \"prepared\",\n \"accepted\",\n \"submission_uncertain\",\n \"provider_started\",\n \"retaining\",\n \"completed\",\n ].includes(operation.status)\n ) {\n throw new Error(\"The existing video generation request cannot be resumed\");\n }\n return {\n receipt: VideoGenerationAcceptedReceipt.parse({\n schemaVersion: 1,\n status: \"accepted\",\n operationId: operation.id,\n }),\n operationId: operation.id,\n requestDigest,\n };\n}\n\nfunction assertStoredReferencePlan(\n stored: VideoGenerationReference[],\n inspected: Awaited<ReturnType<typeof inspectSandboxVideoReferences>>,\n): void {\n if (\n stored.length !== inspected.length ||\n stored.some((reference, index) => {\n const source = inspected[index];\n return (\n !source ||\n reference.ordinal !== source.ordinal ||\n reference.role !== source.role ||\n reference.contentType !== source.contentType ||\n reference.sizeBytes !== source.sizeBytes ||\n reference.sha256 !== source.sha256\n );\n })\n ) {\n throw new Error(\"Video reference bytes changed across tool-call recovery\");\n }\n}\n","import {\n GENERATED_VIDEO_MAX_BYTES,\n type GenerateVideoToolInput,\n type VideoGenerationRejectedCode,\n} from \"@opengeni/contracts\";\nimport type { SealedVideoReference, SealedVideoReferenceRole } from \"@opengeni/core\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport {\n copyVersionedObjectToVerifiedTemp,\n validateImageReference,\n validateVideoReference,\n} from \"./video-media-validation\";\n\nconst MAX_IMAGE_REFERENCE_BYTES = 30 * 1024 * 1024;\nconst MAX_VIDEO_REFERENCE_BYTES = 200 * 1024 * 1024;\nconst UPLOAD_TIMEOUT_SECONDS = 15 * 60;\n\nexport type SandboxCommandRunner = (input: {\n cmd: string;\n workdir: string;\n maxOutputTokens: number;\n}) => Promise<{ stdout: string; stderr: string; exitCode: number }>;\n\nexport type InspectedSandboxVideoReference = Readonly<{\n ordinal: number;\n role: SealedVideoReferenceRole;\n path: string;\n contentType: string;\n sizeBytes: number;\n sha256: string;\n}>;\n\nexport type VideoReferenceInputErrorCode = VideoGenerationRejectedCode;\n\n/** A deterministic, pre-admission tool-input error. No video operation exists yet. */\nexport class VideoReferenceInputError extends Error {\n readonly code: VideoReferenceInputErrorCode;\n\n constructor(code: VideoReferenceInputErrorCode, message: string) {\n super(message);\n this.name = \"VideoReferenceInputError\";\n this.code = code;\n }\n}\n\nexport function videoReferencePaths(\n request: GenerateVideoToolInput,\n): Array<{ role: SealedVideoReferenceRole; path: string }> {\n const source = request.source;\n if (!source || source.mode === \"text\") return [];\n if (source.mode === \"first_frame\") return [{ role: \"first_frame\", path: source.imagePath }];\n if (source.mode === \"first_and_last_frames\") {\n return [\n { role: \"first_frame\", path: source.firstFramePath },\n { role: \"last_frame\", path: source.lastFramePath },\n ];\n }\n if (source.mode === \"image_reference\") {\n return [{ role: \"image_reference\", path: source.imagePath }];\n }\n return [{ role: \"video_reference\", path: source.videoPath }];\n}\n\nexport async function inspectSandboxVideoReferences(input: {\n request: GenerateVideoToolInput;\n runCommand: SandboxCommandRunner;\n}): Promise<InspectedSandboxVideoReference[]> {\n const paths = videoReferencePaths(input.request);\n const inspected: InspectedSandboxVideoReference[] = [];\n for (const [ordinal, reference] of paths.entries()) {\n const result = await input.runCommand({\n cmd: inspectCommand(reference.path),\n workdir: \"/workspace\",\n maxOutputTokens: 4_096,\n });\n if (result.exitCode !== 0) {\n throw new VideoReferenceInputError(\n \"reference_not_stable\",\n \"The video reference must be an existing regular file at the exact /workspace path returned by the preceding tool.\",\n );\n }\n const [sizeText, sha256, prefixBase64] = result.stdout.trim().split(\"\\t\");\n const sizeBytes = Number(sizeText);\n if (\n !Number.isSafeInteger(sizeBytes) ||\n sizeBytes <= 0 ||\n !/^[0-9a-f]{64}$/u.test(sha256 ?? \"\")\n ) {\n throw new VideoReferenceInputError(\n \"reference_not_stable\",\n \"The video reference changed or could not be read safely. Use the exact current /workspace path and try again.\",\n );\n }\n const prefix = Buffer.from(prefixBase64 ?? \"\", \"base64\");\n const contentType = sniffContentType(prefix);\n const maxBytes =\n reference.role === \"video_reference\" ? MAX_VIDEO_REFERENCE_BYTES : MAX_IMAGE_REFERENCE_BYTES;\n if (sizeBytes > maxBytes) {\n throw new VideoReferenceInputError(\n \"reference_too_large\",\n \"The video reference exceeds the supported size for this source mode.\",\n );\n }\n if (\n (reference.role === \"video_reference\" && contentType !== \"video/mp4\") ||\n (reference.role !== \"video_reference\" && !contentType.startsWith(\"image/\"))\n ) {\n throw new VideoReferenceInputError(\n \"reference_media_type_mismatch\",\n \"The video reference media type does not match the selected source mode.\",\n );\n }\n inspected.push({\n ordinal,\n role: reference.role,\n path: reference.path,\n contentType,\n sizeBytes,\n sha256: sha256!,\n });\n }\n return inspected;\n}\n\nexport async function uploadAndVerifyVideoReferences(input: {\n storage: ObjectStorage;\n references: readonly InspectedSandboxVideoReference[];\n stagingKeys: readonly string[];\n runCommand: SandboxCommandRunner;\n tempRoot: string;\n ffprobePath: string;\n uploadTtlSeconds: number;\n signal?: AbortSignal;\n}): Promise<SealedVideoReference[]> {\n if (input.references.length !== input.stagingKeys.length) {\n throw new Error(\"Video reference staging identities do not match\");\n }\n const sealed: SealedVideoReference[] = [];\n for (const [index, reference] of input.references.entries()) {\n throwIfAborted(input.signal);\n const key = input.stagingKeys[index]!;\n const existing = input.storage.headObject ? await input.storage.headObject(key) : null;\n if (!existing) {\n const upload = await input.storage.createPutUrl({\n key,\n contentType: reference.contentType,\n sha256: reference.sha256,\n expiresInSeconds: Math.min(input.uploadTtlSeconds, UPLOAD_TIMEOUT_SECONDS),\n });\n const result = await input.runCommand({\n cmd: uploadCommand(reference, upload),\n workdir: \"/workspace\",\n maxOutputTokens: 4_096,\n });\n if (result.exitCode !== 0) throw new Error(\"Video reference staging upload failed\");\n }\n const verified = await copyVersionedObjectToVerifiedTemp({\n storage: input.storage,\n key,\n expectedSizeBytes: reference.sizeBytes,\n expectedSha256: reference.sha256,\n expectedContentType: reference.contentType,\n maxBytes:\n reference.role === \"video_reference\"\n ? MAX_VIDEO_REFERENCE_BYTES\n : MAX_IMAGE_REFERENCE_BYTES,\n tempRoot: input.tempRoot,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n try {\n if (reference.role === \"video_reference\") {\n await validateVideoReference({\n path: verified.path,\n ffprobePath: input.ffprobePath,\n });\n } else {\n const image = await validateImageReference(verified.path);\n if (image.contentType !== reference.contentType) {\n throw new Error(\"Video image reference MIME type changed during validation\");\n }\n }\n } finally {\n await verified.cleanup();\n }\n sealed.push({\n role: reference.role,\n contentSha256: reference.sha256,\n contentType: reference.contentType,\n byteSize: reference.sizeBytes,\n });\n }\n return sealed;\n}\n\nexport function videoReferenceStagingKey(input: {\n workspaceId: string;\n operationId: string;\n ordinal: number;\n sha256: string;\n}): string {\n if (!/^[0-9a-f]{64}$/u.test(input.sha256)) throw new Error(\"Video reference digest is invalid\");\n return `video-generation/staging/${input.workspaceId}/${input.operationId}/${input.ordinal}/${input.sha256}`;\n}\n\nfunction inspectCommand(path: string): string {\n return [\n \"set -euo pipefail\",\n ...stableWorkspaceFilePrelude(path, { nonCanonical: 43, invalidFile: 45 }),\n 'sha=$(video_reference_sha256 \"$fd\")',\n 'exec 3<&-; exec 3<\"$resolved\"',\n 'fd=/proc/$$/fd/3; [ -e \"$fd\" ] || fd=/dev/fd/3',\n 'reopened=$(video_reference_stat_identity \"$fd\")',\n '[ \"$before\" = \"$reopened\" ] || exit 46',\n '[ \"$(video_reference_stat_content_identity \"$resolved\")\" = \"$(video_reference_stat_content_identity \"$fd\")\" ] || exit 46',\n '[ \"$(realpath -- \"$requested\")\" = \"$expected\" ] || exit 46',\n 'prefix=$(dd if=\"$fd\" bs=32 count=1 2>/dev/null | base64 | tr -d \"\\\\r\\\\n\")',\n 'after=$(video_reference_stat_identity \"$fd\")',\n '[ \"$before\" = \"$after\" ] || exit 46',\n 'printf \"%s\\\\t%s\\\\t%s\\\\n\" \"$size\" \"$sha\" \"$prefix\"',\n ].join(\"\\n\");\n}\n\nfunction uploadCommand(\n reference: InspectedSandboxVideoReference,\n upload: Awaited<ReturnType<ObjectStorage[\"createPutUrl\"]>>,\n): string {\n const headers = Object.entries(upload.requiredHeaders)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([name, value]) => `--header ${shellQuote(`${name}: ${value}`)}`)\n .join(\" \");\n return [\n \"set -euo pipefail\",\n ...stableWorkspaceFilePrelude(reference.path, {\n nonCanonical: 51,\n invalidFile: 52,\n }),\n `[ \"$size\" = ${shellQuote(String(reference.sizeBytes))} ] || exit 53`,\n 'sha=$(video_reference_sha256 \"$fd\")',\n `[ \"$sha\" = ${shellQuote(reference.sha256)} ] || exit 54`,\n 'exec 3<&-; exec 3<\"$resolved\"',\n 'fd=/proc/$$/fd/3; [ -e \"$fd\" ] || fd=/dev/fd/3',\n 'reopened=$(video_reference_stat_identity \"$fd\")',\n '[ \"$before\" = \"$reopened\" ] || exit 55',\n '[ \"$(video_reference_stat_content_identity \"$resolved\")\" = \"$(video_reference_stat_content_identity \"$fd\")\" ] || exit 55',\n '[ \"$(realpath -- \"$requested\")\" = \"$expected\" ] || exit 55',\n `curl --silent --show-error --fail --connect-timeout 20 --max-time ${UPLOAD_TIMEOUT_SECONDS} --request PUT ${headers} --upload-file \"$fd\" --output /dev/null ${shellQuote(upload.url)}`,\n 'after=$(video_reference_stat_identity \"$fd\")',\n '[ \"$before\" = \"$after\" ] || exit 56',\n ].join(\"\\n\");\n}\n\nfunction stableWorkspaceFilePrelude(\n path: string,\n exitCodes: { nonCanonical: number; invalidFile: number },\n): string[] {\n const requested = workspaceRelativeReferencePath(path);\n return [\n `requested=${shellQuote(requested)}`,\n \"root=$(pwd -P)\",\n 'expected=\"$root/${requested#./}\"',\n 'resolved=$(realpath -- \"$requested\")',\n `[ \"$resolved\" = \"$expected\" ] || exit ${exitCodes.nonCanonical}`,\n `[ -f \"$resolved\" ] || exit ${exitCodes.invalidFile}`,\n 'exec 3<\"$resolved\"',\n 'fd=/proc/$$/fd/3; [ -e \"$fd\" ] || fd=/dev/fd/3',\n `[ -f \"$fd\" ] || exit ${exitCodes.invalidFile}`,\n \"video_reference_platform=$(uname -s)\",\n 'if [ \"$video_reference_platform\" = Darwin ]; then',\n ' video_reference_stat_identity() { stat -f \"%d:%i:%z:%m\" \"$1\"; }',\n ' video_reference_stat_content_identity() { stat -f \"%i:%z:%m\" \"$1\"; }',\n ' video_reference_stat_size() { stat -f \"%z\" \"$1\"; }',\n \"else\",\n ' video_reference_stat_identity() { stat -Lc \"%d:%i:%s:%Y\" -- \"$1\"; }',\n ' video_reference_stat_content_identity() { stat -Lc \"%d:%i:%s:%Y\" -- \"$1\"; }',\n ' video_reference_stat_size() { stat -Lc \"%s\" -- \"$1\"; }',\n \"fi\",\n \"video_reference_sha256() {\",\n \" if command -v sha256sum >/dev/null 2>&1; then\",\n \" sha256sum \\\"$1\\\" | awk '{print $1}'\",\n \" else\",\n \" shasum -a 256 \\\"$1\\\" | awk '{print $1}'\",\n \" fi\",\n \"}\",\n 'if [ \"$video_reference_platform\" != Darwin ]; then',\n ' fd_path=$(realpath -- \"$fd\")',\n ` [ \"$fd_path\" = \"$expected\" ] || exit ${exitCodes.invalidFile}`,\n \"fi\",\n `[ \"$(video_reference_stat_content_identity \"$resolved\")\" = \"$(video_reference_stat_content_identity \"$fd\")\" ] || exit ${exitCodes.invalidFile}`,\n `[ \"$(realpath -- \"$requested\")\" = \"$expected\" ] || exit ${exitCodes.invalidFile}`,\n 'before=$(video_reference_stat_identity \"$fd\")',\n 'size=$(video_reference_stat_size \"$fd\")',\n ];\n}\n\nfunction workspaceRelativeReferencePath(path: string): string {\n if (!path.startsWith(\"/workspace/\") || /[\\0\\r\\n]/u.test(path)) {\n throw new VideoReferenceInputError(\n \"invalid_reference_path\",\n \"Video references must use an exact file path under /workspace.\",\n );\n }\n const segments = path.slice(\"/workspace/\".length).split(\"/\");\n if (segments.some((segment) => segment.length === 0 || segment === \".\" || segment === \"..\")) {\n throw new VideoReferenceInputError(\n \"invalid_reference_path\",\n \"Video references must use a canonical file path under /workspace.\",\n );\n }\n return `./${segments.join(\"/\")}`;\n}\n\nfunction sniffContentType(prefix: Uint8Array): string {\n if (\n prefix.byteLength >= 8 &&\n Buffer.from(prefix.subarray(0, 8)).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))\n ) {\n return \"image/png\";\n }\n if (prefix.byteLength >= 3 && prefix[0] === 0xff && prefix[1] === 0xd8 && prefix[2] === 0xff) {\n return \"image/jpeg\";\n }\n if (\n prefix.byteLength >= 12 &&\n Buffer.from(prefix.subarray(0, 4)).toString(\"ascii\") === \"RIFF\" &&\n Buffer.from(prefix.subarray(8, 12)).toString(\"ascii\") === \"WEBP\"\n ) {\n return \"image/webp\";\n }\n if (prefix.byteLength >= 12 && Buffer.from(prefix.subarray(4, 8)).toString(\"ascii\") === \"ftyp\") {\n return \"video/mp4\";\n }\n throw new VideoReferenceInputError(\n \"unsupported_reference_media\",\n \"The video reference is not a supported PNG, JPEG, WebP, or MP4 file.\",\n );\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Video reference staging was cancelled\");\n}\n\nexport const VIDEO_REFERENCE_LIMITS = Object.freeze({\n imageBytes: MAX_IMAGE_REFERENCE_BYTES,\n videoBytes: MAX_VIDEO_REFERENCE_BYTES,\n outputBytes: GENERATED_VIDEO_MAX_BYTES,\n});\n","import type { GeneratedVideoFacts } from \"@opengeni/contracts\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { open, mkdir, rm, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { spawn } from \"node:child_process\";\nimport sharp from \"sharp\";\n\nconst RANGE_BYTES = 1024 * 1024;\nconst PROBE_STDOUT_MAX_BYTES = 64 * 1024;\nconst PROBE_STDERR_MAX_BYTES = 16 * 1024;\nconst PROBE_TIMEOUT_MS = 20_000;\n\nexport type VerifiedTempFile = Readonly<{\n directory: string;\n path: string;\n sizeBytes: number;\n sha256: string;\n contentType: string;\n cleanup: () => Promise<void>;\n}>;\n\nexport async function copyVersionedObjectToVerifiedTemp(input: {\n storage: ObjectStorage;\n key: string;\n expectedSizeBytes: number;\n expectedSha256: string;\n expectedContentType: string;\n maxBytes: number;\n tempRoot: string;\n signal?: AbortSignal;\n}): Promise<VerifiedTempFile> {\n if (!input.storage.headObject || !input.storage.getObjectRange) {\n throw new Error(\"Object storage lacks versioned range reads\");\n }\n assertSha256(input.expectedSha256);\n if (\n !Number.isSafeInteger(input.expectedSizeBytes) ||\n input.expectedSizeBytes <= 0 ||\n input.expectedSizeBytes > input.maxBytes\n ) {\n throw new Error(\"Media staging size is invalid\");\n }\n throwIfAborted(input.signal);\n const head = await input.storage.headObject(input.key);\n if (\n !head ||\n head.ContentLength !== input.expectedSizeBytes ||\n head.ContentType !== input.expectedContentType ||\n head.Metadata?.sha256 !== input.expectedSha256 ||\n !head.VersionToken\n ) {\n throw new Error(\"Media staging metadata does not match its sealed reference\");\n }\n const versionToken = head.VersionToken;\n await mkdir(input.tempRoot, { recursive: true, mode: 0o700 });\n const directory = join(input.tempRoot, `media-${randomUUID()}`);\n const path = join(directory, \"payload\");\n await mkdir(directory, { recursive: false, mode: 0o700 });\n const handle = await open(path, \"wx\", 0o600);\n const hash = createHash(\"sha256\");\n let offset = 0;\n try {\n while (offset < input.expectedSizeBytes) {\n throwIfAborted(input.signal);\n const endInclusive = Math.min(input.expectedSizeBytes - 1, offset + RANGE_BYTES - 1);\n const range = await input.storage.getObjectRange({\n key: input.key,\n start: offset,\n endInclusive,\n expectedVersionToken: versionToken,\n });\n if (\n !range ||\n range.versionToken !== versionToken ||\n range.bytes.byteLength !== endInclusive - offset + 1\n ) {\n throw new Error(\"Media staging object changed during range read\");\n }\n await writeAll(handle, range.bytes, offset);\n hash.update(range.bytes);\n offset += range.bytes.byteLength;\n }\n await handle.sync();\n } catch (error) {\n await handle.close().catch(() => undefined);\n await rm(directory, { recursive: true, force: true });\n throw error;\n }\n await handle.close();\n const digest = hash.digest(\"hex\");\n if (offset !== input.expectedSizeBytes || digest !== input.expectedSha256) {\n await rm(directory, { recursive: true, force: true });\n throw new Error(\"Media staging bytes do not match their sealed digest\");\n }\n const after = await input.storage.headObject(input.key);\n if (!after || after.VersionToken !== versionToken) {\n await rm(directory, { recursive: true, force: true });\n throw new Error(\"Media staging object changed after verification\");\n }\n return Object.freeze({\n directory,\n path,\n sizeBytes: offset,\n sha256: digest,\n contentType: input.expectedContentType,\n cleanup: async () => await rm(directory, { recursive: true, force: true }),\n });\n}\n\nexport async function validateImageReference(path: string): Promise<{\n contentType: \"image/jpeg\" | \"image/png\" | \"image/webp\";\n width: number;\n height: number;\n}> {\n const metadata = await sharp(path, { failOn: \"error\", limitInputPixels: 67_108_864 }).metadata();\n const contentType =\n metadata.format === \"jpeg\"\n ? \"image/jpeg\"\n : metadata.format === \"png\"\n ? \"image/png\"\n : metadata.format === \"webp\"\n ? \"image/webp\"\n : null;\n if (\n !contentType ||\n !metadata.width ||\n !metadata.height ||\n metadata.width > 8_192 ||\n metadata.height > 8_192\n ) {\n throw new Error(\"Video image reference is not a supported JPEG, PNG, or WebP image\");\n }\n return { contentType, width: metadata.width, height: metadata.height };\n}\n\nexport async function validateGeneratedVideo(input: {\n path: string;\n ffprobePath: string;\n expectedDurationSeconds?: number;\n}): Promise<GeneratedVideoFacts> {\n const facts = await probeBrowserCompatibleMp4(input.path, input.ffprobePath);\n if (\n input.expectedDurationSeconds !== undefined &&\n Math.abs(facts.durationSeconds - input.expectedDurationSeconds) > 3\n ) {\n throw new Error(\"Generated video duration differs from the requested duration\");\n }\n return facts;\n}\n\nexport async function validateVideoReference(input: {\n path: string;\n ffprobePath: string;\n}): Promise<GeneratedVideoFacts> {\n return await probeBrowserCompatibleMp4(input.path, input.ffprobePath);\n}\n\nasync function probeBrowserCompatibleMp4(\n path: string,\n ffprobePath: string,\n): Promise<GeneratedVideoFacts> {\n const file = await stat(path);\n if (!file.isFile() || file.size <= 0) throw new Error(\"Media probe input is not a regular file\");\n const result = await spawnBounded(ffprobePath, [\n \"-v\",\n \"error\",\n \"-protocol_whitelist\",\n \"file,pipe\",\n \"-probesize\",\n \"8388608\",\n \"-analyzeduration\",\n \"5000000\",\n \"-show_entries\",\n \"format=format_name,duration:stream=codec_type,codec_name,width,height,avg_frame_rate:stream_disposition=attached_pic\",\n \"-of\",\n \"json\",\n \"--\",\n path,\n ]);\n let decoded: unknown;\n try {\n decoded = JSON.parse(result.stdout);\n } catch {\n throw new Error(\"Media probe returned malformed metadata\");\n }\n const root = record(decoded);\n const format = record(root?.format);\n const streams = Array.isArray(root?.streams) ? root.streams.map(record).filter(Boolean) : [];\n const video = streams.filter(\n (stream) => stream?.codec_type === \"video\" && !isAttachedPicture(stream),\n );\n const audio = streams.filter((stream) => stream?.codec_type === \"audio\");\n const durationSeconds = finitePositive(format?.duration);\n const width = positiveInteger(video[0]?.width);\n const height = positiveInteger(video[0]?.height);\n const fps = parseFrameRate(video[0]?.avg_frame_rate);\n if (\n !stringValue(format?.format_name)\n ?.split(\",\")\n .some((value) => value === \"mp4\") ||\n video.length !== 1 ||\n audio.length > 1 ||\n video[0]?.codec_name !== \"h264\" ||\n (audio.length === 1 && audio[0]?.codec_name !== \"aac\") ||\n !durationSeconds ||\n durationSeconds > 120 ||\n !width ||\n !height ||\n width > 8_192 ||\n height > 8_192 ||\n !fps ||\n fps > 120\n ) {\n throw new Error(\"Video is not a supported browser-compatible H.264 MP4\");\n }\n return {\n durationSeconds,\n width,\n height,\n fps,\n hasAudio: audio.length === 1,\n videoCodec: \"h264\",\n audioCodec: audio.length === 1 ? \"aac\" : null,\n };\n}\n\nfunction isAttachedPicture(stream: Record<string, unknown>): boolean {\n return Number(record(stream.disposition)?.attached_pic) === 1;\n}\n\nasync function spawnBounded(\n command: string,\n args: string[],\n): Promise<{ stdout: string; stderr: string }> {\n return await new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n env: { PATH: process.env.PATH ?? \"/usr/local/bin:/usr/bin:/bin\", LC_ALL: \"C\" },\n });\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n let stdoutBytes = 0;\n let stderrBytes = 0;\n let settled = false;\n const fail = (error: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.kill(\"SIGKILL\");\n reject(error);\n };\n const timer = setTimeout(() => fail(new Error(\"Media probe timed out\")), PROBE_TIMEOUT_MS);\n child.stdout.on(\"data\", (chunk: Buffer) => {\n stdoutBytes += chunk.byteLength;\n if (stdoutBytes > PROBE_STDOUT_MAX_BYTES) fail(new Error(\"Media probe output is too large\"));\n else stdout.push(Buffer.from(chunk));\n });\n child.stderr.on(\"data\", (chunk: Buffer) => {\n stderrBytes += chunk.byteLength;\n if (stderrBytes > PROBE_STDERR_MAX_BYTES) fail(new Error(\"Media probe error is too large\"));\n else stderr.push(Buffer.from(chunk));\n });\n child.once(\"error\", (error) => fail(error));\n child.once(\"close\", (code) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n const stderrText = Buffer.concat(stderr).toString(\"utf8\").trim();\n if (code !== 0) {\n reject(\n new Error(\n stderrText ? `Media probe failed: ${stderrText.slice(0, 1_000)}` : \"Media probe failed\",\n ),\n );\n } else {\n resolve({ stdout: Buffer.concat(stdout).toString(\"utf8\"), stderr: stderrText });\n }\n });\n });\n}\n\nasync function writeAll(\n handle: Awaited<ReturnType<typeof open>>,\n chunk: Uint8Array,\n offset: number,\n): Promise<void> {\n let written = 0;\n while (written < chunk.byteLength) {\n const result = await handle.write(chunk, written, chunk.byteLength - written, offset + written);\n if (result.bytesWritten <= 0) throw new Error(\"Media temporary file write stalled\");\n written += result.bytesWritten;\n }\n}\n\nfunction parseFrameRate(value: unknown): number | null {\n const text = stringValue(value);\n if (!text) return null;\n const [left, right] = text.split(\"/\");\n const numerator = Number(left);\n const denominator = right === undefined ? 1 : Number(right);\n const fps = numerator / denominator;\n return Number.isFinite(fps) && fps > 0 ? fps : null;\n}\n\nfunction positiveInteger(value: unknown): number | null {\n const parsed = typeof value === \"number\" ? value : Number(value);\n return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction finitePositive(value: unknown): number | null {\n const parsed = typeof value === \"number\" ? value : Number(value);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n}\n\nfunction stringValue(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value : null;\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction assertSha256(value: string): void {\n if (!/^[0-9a-f]{64}$/u.test(value)) throw new Error(\"Media SHA-256 is invalid\");\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Media operation was cancelled\");\n}\n","import { decryptEnvironmentValue, encryptEnvironmentValue } from \"@opengeni/db\";\nimport type { XaiProviderAccountAuthoritySnapshotV1 } from \"@opengeni/contracts\";\n\nexport type VideoGenerationProviderCredential =\n | Readonly<{ kind: \"api-key\"; apiKey: string }>\n | Readonly<{\n kind: \"xai-subscription\";\n accessToken: string;\n refreshToken: string;\n userId: string;\n credentialId: string;\n subjectId: string;\n authoritySnapshot: XaiProviderAccountAuthoritySnapshotV1;\n }>;\n\n/** One frozen, provider-neutral credential envelope for every video funding route. */\nexport function encryptVideoGenerationApiKey(key: Uint8Array, apiKey: string): string {\n if (!apiKey.trim()) throw new Error(\"Video provider credential is empty\");\n return encryptEnvironmentValue(key, JSON.stringify({ kind: \"api-key\", apiKey }));\n}\n\nexport function encryptVideoGenerationXaiCredential(\n key: Uint8Array,\n credential: Omit<\n Extract<VideoGenerationProviderCredential, { kind: \"xai-subscription\" }>,\n \"kind\"\n >,\n): string {\n if (\n !credential.accessToken.trim() ||\n !credential.refreshToken.trim() ||\n !credential.userId.trim() ||\n !credential.credentialId.trim() ||\n !credential.subjectId.trim()\n ) {\n throw new Error(\"SuperGrok video credential is incomplete\");\n }\n return encryptEnvironmentValue(key, JSON.stringify({ kind: \"xai-subscription\", ...credential }));\n}\n\n/**\n * Decrypt without ever attaching parser/decryption errors: JSON parser errors\n * may quote plaintext and must not enter Temporal failure payloads or logs.\n */\nexport function decryptVideoGenerationCredential(\n key: Uint8Array,\n stored: string,\n): VideoGenerationProviderCredential {\n let plaintext: string;\n try {\n plaintext = decryptEnvironmentValue(key, stored);\n } catch {\n throw new Error(\"Video provider credential lease could not be decrypted\");\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(plaintext);\n } catch {\n throw new Error(\"Video provider credential lease is malformed\");\n }\n const row =\n decoded && typeof decoded === \"object\" && !Array.isArray(decoded)\n ? (decoded as Record<string, unknown>)\n : null;\n if (row?.kind === \"api-key\" || (row?.kind === undefined && typeof row?.apiKey === \"string\")) {\n if (typeof row.apiKey !== \"string\" || !row.apiKey.trim()) {\n throw new Error(\"Video provider credential lease is malformed\");\n }\n return Object.freeze({ kind: \"api-key\", apiKey: row.apiKey });\n }\n const authority =\n row?.authoritySnapshot &&\n typeof row.authoritySnapshot === \"object\" &&\n !Array.isArray(row.authoritySnapshot)\n ? (row.authoritySnapshot as Record<string, unknown>)\n : null;\n if (\n row?.kind !== \"xai-subscription\" ||\n typeof row.accessToken !== \"string\" ||\n !row.accessToken.trim() ||\n typeof row.refreshToken !== \"string\" ||\n !row.refreshToken.trim() ||\n typeof row.userId !== \"string\" ||\n !row.userId.trim() ||\n typeof row.credentialId !== \"string\" ||\n !row.credentialId.trim() ||\n typeof row.subjectId !== \"string\" ||\n !row.subjectId.trim() ||\n authority?.version !== 1 ||\n (authority.scope !== \"workspace\" && authority.scope !== \"user\") ||\n (authority.scope === \"user\" && !Number.isSafeInteger(authority.authorityGeneration))\n ) {\n throw new Error(\"Video provider credential lease is malformed\");\n }\n return Object.freeze({\n kind: \"xai-subscription\",\n accessToken: row.accessToken,\n refreshToken: row.refreshToken,\n userId: row.userId,\n credentialId: row.credentialId,\n subjectId: row.subjectId,\n authoritySnapshot: authority as XaiProviderAccountAuthoritySnapshotV1,\n });\n}\n\nexport function decryptVideoGenerationApiKey(key: Uint8Array, stored: string): string {\n const credential = decryptVideoGenerationCredential(key, stored);\n if (credential.kind !== \"api-key\") {\n throw new Error(\"Video provider credential is not an API key\");\n }\n return credential.apiKey;\n}\n","import {\n applyGitAuthPointerEnvironment,\n codemodeWorkspaceUrl,\n resolveFirstPartyDelegationSecret,\n stableSandboxEnvironmentForRun,\n type Settings,\n} from \"@opengeni/config\";\nimport {\n gitCredentialBindingIdForRepository,\n gitCredentialProviderForRepository,\n gitRemoteIdentity,\n signDelegatedAccessToken,\n type ConnectionCredentialsPort,\n type GitCredentialProvider,\n type GitCredentialRepositoryRef,\n type GitCredentialTransport,\n type GitCredentials,\n type ResourceRef,\n type SandboxSecrets,\n type SessionTurn,\n type TurnInitiator,\n type TurnInitiatorContext,\n} from \"@opengeni/contracts\";\nimport {\n loadVariableSetForRun as loadWorkspaceEnvironmentForRunFromDb,\n type Database,\n type VariableSetForRun as WorkspaceEnvironmentForRun,\n} from \"@opengeni/db\";\nimport { createGitHubAppInstallationTokenWithExpiry, githubAppBotIdentity } from \"@opengeni/github\";\n\n// Re-exported from the shared @opengeni/db leaf (moved there so the API-direct\n// attach paths can load the SAME decrypted workspace environment the turn\n// declares — keeping the box-manifest env and agent-manifest env identical).\n// Existing worker import sites (agent-turn) continue importing from here.\nexport {\n loadWorkspaceEnvironmentForRunFromDb as loadWorkspaceEnvironmentForRun,\n type WorkspaceEnvironmentForRun,\n};\n\n// §7.6 connection-credential provider — the run's workspace identity, threaded so the connection-credential\n// provider can be called with the run's tenant context AND so the workspace-scope cross-check\n// cross-check has the run's workspace to assert the provider's echo against.\nexport type ConnectionScope = {\n accountId: string;\n workspaceId: string;\n};\n\nexport type GitTokenSeeds = Partial<Record<GitCredentialProvider, string>>;\nexport type GitTokenExpiries = Partial<Record<GitCredentialProvider, string>>;\nexport type GitCredentialBindingSeed = {\n credentialBindingId: string;\n provider: GitCredentialProvider;\n token: string;\n transport?: GitCredentialTransport;\n expiresAt?: string;\n providerBindingCount?: number;\n};\nexport type MintedRunGitCredentials = {\n bindings: GitCredentialBindingSeed[];\n // Compatibility views exist only when a provider has exactly one binding.\n // A multi-binding provider intentionally has no provider-level alias.\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n};\n\nexport type GitHubTokenMintAuthorization = (selection: {\n installationId: number;\n repositoryIds: number[];\n}) => Promise<void>;\n\nexport const CODEMODE_TOKEN_TTL_SECONDS = 60 * 60;\n\nexport type MintedSandboxCodemodeToken = {\n token: string;\n expiresAt: Date;\n};\n\nexport type SandboxCodemodeAuthority = {\n sessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n};\n\nexport async function mintSandboxCodemodeToken(\n settings: Settings,\n scope: ConnectionScope,\n authority: SandboxCodemodeAuthority,\n nowMs = Date.now(),\n): Promise<MintedSandboxCodemodeToken | undefined> {\n const delegationSecret = resolveFirstPartyDelegationSecret(settings);\n if (!delegationSecret) return undefined;\n const expiresAtSeconds = Math.floor(nowMs / 1000) + CODEMODE_TOKEN_TTL_SECONDS;\n const token = await signDelegatedAccessToken(delegationSecret, {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n subjectId: `sandbox:${authority.attemptId}`,\n subjectLabel: \"sandbox Codemode\",\n permissions: [\"codemode:call\"],\n sessionId: authority.sessionId,\n turnId: authority.turnId,\n attemptId: authority.attemptId,\n executionGeneration: authority.executionGeneration,\n principalKind: \"agent_attempt\",\n exp: expiresAtSeconds,\n });\n return { token, expiresAt: new Date(expiresAtSeconds * 1000) };\n}\n\nexport type GitCredentialAuthority = {\n sessionId: string;\n rootSessionId: string;\n turnId: string;\n attemptId: string;\n executionGeneration: number;\n initiator: TurnInitiator;\n initiatorContext: TurnInitiatorContext;\n};\n\nexport function gitCredentialAuthorityForTurn(input: {\n sessionId: string;\n rootSessionId: string;\n attemptId: string;\n turn: Pick<SessionTurn, \"id\" | \"executionGeneration\" | \"initiator\" | \"initiatorContext\">;\n}): GitCredentialAuthority {\n return {\n sessionId: input.sessionId,\n rootSessionId: input.rootSessionId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n };\n}\n\ntype RunGitCredentialOptions = {\n scope?: ConnectionScope;\n authority?: GitCredentialAuthority;\n gitCredentials?: ConnectionCredentialsPort[\"gitCredentials\"];\n authorizeGitHubTokenMint?: GitHubTokenMintAuthorization;\n};\n\n// §7.6 connection-credential provider — load the run's workspace environment, delegating the DECRYPT to a\n// host `sandboxSecrets` provider when one is bound (the host owns the secret\n// vault + encryption key in embedded/separate topologies) and otherwise running\n// today's local `environmentsEncryptionKeyBytes`-keyed decrypt byte-for-byte.\n//\n// Unattached runs (environmentId === null) short-circuit identically in BOTH\n// modes: zero DB/provider work, returns null. When a provider IS bound it owns\n// the decrypt end-to-end (it reads the host's own store), so the local DB read\n// is skipped — the provider is the sole source of truth for that leg.\nexport async function loadWorkspaceEnvironmentForRunWithCredentials(\n db: Database,\n settings: Settings,\n scope: ConnectionScope,\n environmentId: string | null,\n sandboxSecrets?: ConnectionCredentialsPort[\"sandboxSecrets\"],\n): Promise<WorkspaceEnvironmentForRun | null> {\n if (!sandboxSecrets) {\n // Standalone default: today's local decrypt, unchanged.\n return loadWorkspaceEnvironmentForRunFromDb(db, settings, scope.workspaceId, environmentId);\n }\n if (!environmentId) {\n return null;\n }\n const secrets: SandboxSecrets = await sandboxSecrets({\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n variableSetId: environmentId,\n });\n // workspace-scope cross-check: the provider must echo THIS run's workspace before we apply its\n // decrypted values into the sandbox.\n assertWorkspaceEcho(\"sandboxSecrets\", scope, secrets.workspaceId);\n return {\n id: secrets.id ?? environmentId,\n name: secrets.name ?? environmentId,\n description: secrets.description ?? null,\n values: secrets.values,\n };\n}\n\n// Workspace-scope cross-check. A credential provider echoes the workspace it scoped\n// the credential to; we ASSERT it equals the run's workspace BEFORE the caller\n// injects the credential. A host mapping bug returning tenant B's creds for a\n// tenant-A run hard-throws here instead of landing tenant B's token in tenant\n// A's sandbox. Account/workspace ids only in the message (never the credential).\nfunction assertWorkspaceEcho(\n kind: string,\n scope: ConnectionScope,\n echoedWorkspaceId: string,\n): void {\n if (echoedWorkspaceId !== scope.workspaceId) {\n throw new Error(\n `connection-credential provider (${kind}) scoped to workspace ${echoedWorkspaceId} but the run is workspace ${scope.workspaceId}`,\n );\n }\n}\n\nexport async function sandboxEnvironmentForRun(\n settings: Settings,\n resources: ResourceRef[],\n workspaceEnvironment: Record<string, string> = {},\n // §7.6 connection-credential provider - optional host git-credential provider + the run scope it needs\n // (unset, the standalone default → self-mint from `settings` byte-for-byte).\n // `skipGitHubToken` (Stage D): a connected-machine turn skips the inert platform\n // token mint entirely and returns the stable base env unchanged. `deferGitHubToken`\n // is the lazy CLOUD path: apply stable git-auth pointers now, mint only the token\n // value later. `= {}` default so the non-optional reads below are safe.\n options: RunGitCredentialOptions & {\n skipGitHubToken?: boolean;\n /**\n * Codemode credential delivery for this attempt. Managed sandboxes receive\n * stable URL/file pointers in their manifest and the bearer through the\n * lifecycle file writer. Connected Machines receive no manifest pointers;\n * the worker injects the minted bearer only into exact exec requests.\n */\n codemodeDelivery?: \"managed_file\" | \"transient_exec\" | \"none\";\n deferGitHubToken?: boolean;\n codemodeAuthority?: SandboxCodemodeAuthority;\n } = {},\n): Promise<{\n environment: Record<string, string>;\n gitToken?: string;\n gitTokens?: GitTokenSeeds;\n gitTokenExpiresAt?: GitTokenExpiries;\n gitCredentialBindings?: GitCredentialBindingSeed[];\n codemodeToken?: string;\n codemodeTokenExpiresAt?: Date;\n}> {\n // Precedence: deployment allowlist < git identity < workspace environment\n // < backend-aware HOME (the STABLE base, shared with the API-direct attach\n // paths via stableSandboxEnvironmentForRun) < platform run-scoped git auth\n // (applied below, always last). Reserved name validation at write time prevents\n // workspace values from colliding with the platform-managed entries.\n //\n // TOKEN-BROKER (B1): run-scoped git provider tokens are NO LONGER layered into\n // the box/agent MANIFEST env (no GH_TOKEN/GITHUB_TOKEN/GITLAB_TOKEN/\n // AZURE_DEVOPS_EXT_PAT/GIT_CONFIG_* extraheader). They are minted once per turn\n // and returned separately as provider token seeds; the caller threads them\n // OFF-MANIFEST as clone-seed exec env vars so the clone hook writes stable token\n // files. The manifest carries only stable pointers (GIT_ASKPASS,\n // GIT_TERMINAL_PROMPT, identity, OPENGENI_GIT_CREDENTIALS_DIR, and\n // OPENGENI_GIT_TOKEN_FILE), so token VALUES never ride the manifest and the SDK's\n // per-turn provided-session env delta stays empty even though tokens rotate.\n // GitHub keeps the legacy `gitToken`/OPENGENI_GIT_TOKEN_FILE alias. The worker\n // proactively renews every selected provider behind these stable pointers.\n const stableOptions = options.scope ? { workspaceId: options.scope.workspaceId } : {};\n const environment = stableSandboxEnvironmentForRun(settings, workspaceEnvironment, stableOptions);\n const codemodeDelivery = options.codemodeDelivery ?? \"managed_file\";\n // Connected Machines keep their machine-wide environment untouched. Their\n // URL, package hint, and direct bearer are projected only onto an exact child\n // exec request by SelfhostedSession, never into the manifest or filesystem.\n if (codemodeDelivery !== \"managed_file\") {\n delete environment.OPENGENI_CODEMODE_URL;\n delete environment.OPENGENI_CODEMODE_TOKEN_FILE;\n delete environment.OPENGENI_OGTOOL_PACKAGE_SPEC;\n }\n const codemodeScope = options.scope;\n const codemodeToken =\n codemodeDelivery !== \"none\" && codemodeScope && options.codemodeAuthority\n ? await mintSandboxCodemodeToken(settings, codemodeScope, options.codemodeAuthority)\n : undefined;\n if (codemodeDelivery === \"managed_file\" && codemodeToken && codemodeScope) {\n environment.OPENGENI_CODEMODE_URL ??= codemodeWorkspaceUrl(settings, codemodeScope.workspaceId);\n }\n const selections = gitCredentialSelections(resources);\n // NO-TOKEN SKIP (Stage D, change B): when the turn's EFFECTIVE compute backend is\n // a connected machine (selfhosted), platform git provider tokens are INERT: exec\n // routes over NATS to the user's machine, which uses ITS OWN git credentials, and\n // the box those tokens would auth is never created. So skip the token mint entirely\n // and return the STABLE base env (no gitToken/gitTokens). Env-\n // parity holds: the SAME base object still feeds buildManifest + the SelfhostedSession\n // manifest, so the SDK's per-turn provided-session env delta stays empty\n // (validateNoEnvironmentDelta). The API-direct viewer attach path already drops the\n // token under this exact contract — proof a box runs fine without it.\n if (selections.length === 0 || options.skipGitHubToken) {\n return {\n environment,\n ...(codemodeToken\n ? {\n codemodeToken: codemodeToken.token,\n codemodeTokenExpiresAt: codemodeToken.expiresAt,\n }\n : {}),\n };\n }\n if (options.deferGitHubToken) {\n applyGitAuthPointerEnvironment(\n environment,\n await resolveRunGitIdentityWithSelections(settings, selections, options),\n );\n return {\n environment,\n ...(codemodeToken\n ? {\n codemodeToken: codemodeToken.token,\n codemodeTokenExpiresAt: codemodeToken.expiresAt,\n }\n : {}),\n };\n }\n // Run-scoped sandbox preparation for repository resources. GitHub retains the\n // legacy request shape and standalone self-mint path. Non-GitHub providers are\n // host-brokered only: without a `gitCredentials` port there is no token value\n // to seed, and the runtime wrappers degrade to passthrough.\n const minted = await mintRunGitTokensWithIdentity(settings, selections, options);\n // TOKEN-BROKER (B2): the askpass helper is PROVISIONED AT SETUP (runtime) into a\n // per-box, user-writable path in the SAME dir as the token file, instead of a\n // baked image script at /usr/local/bin/opengeni-git-askpass. The clone-hook seed\n // block writes both the token file AND this askpass script before the fetch, so\n // git auth becomes correct on ANY box image (including pre-existing warm boxes on\n // their next turn's clone hook) — no product image needs to carry the askpass.\n // The pointer layer is the SHARED config helper so every API-direct attach\n // surface (viewer attach, channel-A) declares the IDENTICAL env when it\n // cold-creates the box for a repo-attached session — an attach-warmed box\n // missing these keys kills the next repo turn on the SDK's manifest-env guard.\n applyGitAuthPointerEnvironment(environment, minted.identity);\n return {\n environment,\n ...(minted.gitTokens.github ? { gitToken: minted.gitTokens.github } : {}),\n ...(Object.keys(minted.gitTokens).length > 0 ? { gitTokens: minted.gitTokens } : {}),\n ...(Object.keys(minted.expiresAt).length > 0 ? { gitTokenExpiresAt: minted.expiresAt } : {}),\n ...(minted.bindings.length > 0 ? { gitCredentialBindings: minted.bindings } : {}),\n ...(codemodeToken\n ? {\n codemodeToken: codemodeToken.token,\n codemodeTokenExpiresAt: codemodeToken.expiresAt,\n }\n : {}),\n };\n}\n\nexport async function mintRunGitCredentials(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<MintedRunGitCredentials | undefined> {\n const selections = gitCredentialSelections(resources);\n if (selections.length === 0) {\n return undefined;\n }\n const minted = await mintRunGitTokensWithIdentity(settings, selections, options);\n return minted.bindings.length > 0\n ? { bindings: minted.bindings, gitTokens: minted.gitTokens, expiresAt: minted.expiresAt }\n : undefined;\n}\n\nexport async function mintRunGitCredentialBinding(\n settings: Settings,\n resources: ResourceRef[],\n provider: GitCredentialProvider,\n credentialBindingId: string,\n options: RunGitCredentialOptions = {},\n): Promise<GitCredentialBindingSeed | undefined> {\n const selections = gitCredentialSelections(resources);\n const selection = selections.find(\n (candidate) =>\n candidate.provider === provider && candidate.credentialBindingId === credentialBindingId,\n );\n if (!selection) {\n return undefined;\n }\n const minted = await mintRunGitTokensWithIdentity(settings, [selection], options);\n const binding = minted.bindings[0];\n if (binding) {\n binding.providerBindingCount = selections.filter(\n (candidate) => candidate.provider === selection.provider,\n ).length;\n }\n return binding;\n}\n\nexport async function mintRunGitTokens(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<GitTokenSeeds | undefined> {\n const tokens = (await mintRunGitCredentials(settings, resources, options))?.gitTokens;\n return tokens && Object.keys(tokens).length > 0 ? tokens : undefined;\n}\n\nexport async function mintRunGitToken(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<string | undefined> {\n return (await mintRunGitTokens(settings, resources, options))?.github;\n}\n\nexport async function resolveRunGitIdentity(\n settings: Settings,\n resources: ResourceRef[],\n options: RunGitCredentialOptions = {},\n): Promise<{ name: string; email: string } | null> {\n const selections = gitCredentialSelections(resources);\n if (selections.length === 0) {\n return null;\n }\n return await resolveRunGitIdentityWithSelections(settings, selections, options);\n}\n\nasync function mintRunGitTokensWithIdentity(\n settings: Settings,\n selections: GitCredentialSelection[],\n options: RunGitCredentialOptions,\n): Promise<{\n bindings: GitCredentialBindingSeed[];\n gitTokens: GitTokenSeeds;\n expiresAt: GitTokenExpiries;\n identity: { name: string; email: string } | null;\n}> {\n const bindings: GitCredentialBindingSeed[] = [];\n let identity: { name: string; email: string } | null = null;\n for (const selection of selections) {\n let token: string | null = null;\n let transport: GitCredentialTransport | undefined;\n let tokenExpiresAt: string | undefined;\n if (\n selection.provider === \"github\" &&\n selection.installationId > 0 &&\n selection.repositoryIds.length > 0\n ) {\n // This callback belongs immediately next to the side effect. Turn startup\n // performs its own admission check, but lazy provisioning and proactive\n // renewal can happen much later in an intentionally unbounded run. Recheck\n // the current workspace binding before every host-brokered or built-in\n // GitHub installation-token mint.\n await options.authorizeGitHubTokenMint?.({\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\n }\n if (options?.gitCredentials && options.scope) {\n const request = gitCredentialsRequestForSelection(\n options.scope,\n requireGitCredentialAuthority(options),\n selection,\n \"token\",\n );\n const minted: GitCredentials = await options.gitCredentials(request);\n // workspace-scope cross-check: assert the provider scoped the token to THIS run's workspace\n // before accepting the token for clone seeding.\n assertWorkspaceEcho(\"gitCredentials\", options.scope, minted.workspaceId);\n assertGitCredentialBindingEcho(selection, request, minted);\n if (!minted.token) {\n throw new Error(\n \"connection-credential provider (gitCredentials) did not return a token for a token request\",\n );\n }\n token = minted.token;\n transport = validatedGitCredentialTransport(selection, minted);\n tokenExpiresAt = minted.expiresAt\n ? validatedGitCredentialExpiry(selection.provider, minted.expiresAt)\n : undefined;\n if (minted.identity) {\n identity = minted.identity;\n } else if (selection.provider === \"github\") {\n identity = githubAppBotIdentity(settings);\n }\n } else if (selection.provider === \"github\" && selection.installationId > 0) {\n const minted = await createGitHubAppInstallationTokenWithExpiry(settings, {\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n });\n token = minted.token;\n tokenExpiresAt = minted.expiresAt\n ? validatedGitCredentialExpiry(\"github\", minted.expiresAt)\n : undefined;\n identity = githubAppBotIdentity(settings);\n }\n if (token) {\n bindings.push({\n credentialBindingId: selection.credentialBindingId,\n provider: selection.provider,\n token,\n ...(transport ? { transport } : {}),\n ...(tokenExpiresAt ? { expiresAt: tokenExpiresAt } : {}),\n });\n }\n }\n const gitTokens: GitTokenSeeds = {};\n const expiresAt: GitTokenExpiries = {};\n const counts = new Map<GitCredentialProvider, number>();\n for (const binding of bindings) {\n counts.set(binding.provider, (counts.get(binding.provider) ?? 0) + 1);\n }\n for (const binding of bindings) {\n binding.providerBindingCount = counts.get(binding.provider) ?? 1;\n if (binding.transport?.kind === \"http_broker\") continue;\n if (counts.get(binding.provider) !== 1) continue;\n gitTokens[binding.provider] = binding.token;\n if (binding.expiresAt) expiresAt[binding.provider] = binding.expiresAt;\n }\n return { bindings, gitTokens, expiresAt, identity };\n}\n\nfunction validatedGitCredentialExpiry(provider: GitCredentialProvider, value: string): string {\n const timestamp = Date.parse(value);\n if (!Number.isFinite(timestamp)) {\n throw new Error(`connection-credential provider (${provider}) returned an invalid expiresAt`);\n }\n return new Date(timestamp).toISOString();\n}\n\nconst MAX_GIT_HTTP_BROKER_ROUTES = 256;\nconst MAX_GIT_HTTP_BROKER_URI_LENGTH = 4_096;\n\nfunction validatedGitCredentialTransport(\n selection: GitCredentialSelection,\n minted: GitCredentials,\n): GitCredentialTransport | undefined {\n const transport = minted.transport;\n if (!transport) return undefined;\n\n if (\n typeof transport !== \"object\" ||\n transport.kind !== \"http_broker\" ||\n !Array.isArray(transport.repositories)\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git credential transport`,\n );\n }\n const requestedUris = new Set(selection.repositoryRefs.map((repository) => repository.uri));\n if (\n requestedUris.size === 0 ||\n requestedUris.size > MAX_GIT_HTTP_BROKER_ROUTES ||\n transport.repositories.length !== requestedUris.size\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an incomplete Git HTTP broker route set`,\n );\n }\n\n const echoedUris = new Set<string>();\n const brokerUris = new Set<string>();\n const repositories = transport.repositories.map((route) => {\n if (\n !route ||\n typeof route !== \"object\" ||\n typeof route.repositoryUri !== \"string\" ||\n typeof route.brokerUri !== \"string\"\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker route`,\n );\n }\n if (!requestedUris.has(route.repositoryUri) || echoedUris.has(route.repositoryUri)) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an unexpected Git HTTP broker repository`,\n );\n }\n echoedUris.add(route.repositoryUri);\n if (\n route.brokerUri.length === 0 ||\n route.brokerUri.length > MAX_GIT_HTTP_BROKER_URI_LENGTH ||\n route.brokerUri.trim() !== route.brokerUri\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker URI`,\n );\n }\n let brokerUrl: URL;\n try {\n brokerUrl = new URL(route.brokerUri);\n } catch {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an invalid Git HTTP broker URI`,\n );\n }\n if (\n brokerUrl.protocol !== \"https:\" ||\n brokerUrl.username ||\n brokerUrl.password ||\n brokerUrl.search ||\n brokerUrl.hash ||\n brokerUris.has(brokerUrl.href) ||\n brokerUrl.href === route.repositoryUri\n ) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an unsafe Git HTTP broker URI`,\n );\n }\n brokerUris.add(brokerUrl.href);\n return {\n repositoryUri: route.repositoryUri,\n brokerUri: brokerUrl.href,\n };\n });\n\n if ([...requestedUris].some((uri) => !echoedUris.has(uri))) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned an incomplete Git HTTP broker route set`,\n );\n }\n return { kind: \"http_broker\", repositories };\n}\n\nexport function assertGitCredentialRenewalTransportUnchanged(\n initial: GitCredentialBindingSeed,\n renewed: GitCredentialBindingSeed,\n): void {\n if (!initial.transport && !renewed.transport) return;\n if (\n !initial.transport ||\n !renewed.transport ||\n initial.transport.kind !== renewed.transport.kind\n ) {\n throw new Error(\n `renewed ${initial.provider} credential changed transport for binding ${initial.credentialBindingId}`,\n );\n }\n const routeKey = (route: { repositoryUri: string; brokerUri: string }) =>\n `${route.repositoryUri}\\u0000${route.brokerUri}`;\n const initialRoutes = initial.transport.repositories.map(routeKey).sort();\n const renewedRoutes = renewed.transport.repositories.map(routeKey).sort();\n if (\n initialRoutes.length !== renewedRoutes.length ||\n initialRoutes.some((route, index) => route !== renewedRoutes[index])\n ) {\n throw new Error(\n `renewed ${initial.provider} credential changed Git HTTP broker routes for binding ${initial.credentialBindingId}`,\n );\n }\n}\n\nasync function resolveRunGitIdentityWithSelections(\n settings: Settings,\n selections: GitCredentialSelection[],\n options: RunGitCredentialOptions,\n): Promise<{ name: string; email: string } | null> {\n let identity: { name: string; email: string } | null = null;\n for (const selection of selections) {\n if (options.gitCredentials && options.scope) {\n const request = gitCredentialsRequestForSelection(\n options.scope,\n requireGitCredentialAuthority(options),\n selection,\n \"identity\",\n );\n const resolved: GitCredentials = await options.gitCredentials(request);\n assertWorkspaceEcho(\"gitCredentials\", options.scope, resolved.workspaceId);\n assertGitCredentialBindingEcho(selection, request, resolved);\n if (resolved.identity) {\n identity = resolved.identity;\n } else if (selection.provider === \"github\") {\n identity = githubAppBotIdentity(settings);\n }\n } else if (selection.provider === \"github\" && selection.installationId > 0) {\n identity = githubAppBotIdentity(settings);\n }\n }\n return identity;\n}\n\ntype GitCredentialSelection = {\n provider: GitCredentialProvider;\n credentialBindingId: string;\n explicitCredentialBinding: boolean;\n requireBindingEcho: boolean;\n providerHost?: string;\n installationId: number;\n repositoryIds: number[];\n repositoryRefs: GitCredentialRepositoryRef[];\n};\n\nfunction gitCredentialsRequestForSelection(\n scope: ConnectionScope,\n authority: GitCredentialAuthority,\n selection: GitCredentialSelection,\n purpose?: \"token\" | \"identity\",\n): Parameters<NonNullable<ConnectionCredentialsPort[\"gitCredentials\"]>>[0] {\n const legacy = {\n accountId: scope.accountId,\n workspaceId: scope.workspaceId,\n ...authority,\n ...(purpose ? { purpose } : {}),\n installationId: selection.installationId,\n repositoryIds: selection.repositoryIds,\n };\n const bindingEcho = selection.requireBindingEcho\n ? {\n credentialBindingId: selection.credentialBindingId,\n provider: selection.provider,\n ...(selection.providerHost ? { providerHost: selection.providerHost } : {}),\n }\n : {};\n if (selection.provider === \"github\") {\n return {\n ...legacy,\n ...bindingEcho,\n repositoryRefs: selection.repositoryRefs,\n };\n }\n return {\n ...legacy,\n ...bindingEcho,\n provider: selection.provider,\n repositoryRefs: selection.repositoryRefs,\n };\n}\n\nfunction requireGitCredentialAuthority(options: RunGitCredentialOptions): GitCredentialAuthority {\n if (!options.authority) {\n throw new Error(\"host git credential resolution requires immutable session turn authority\");\n }\n return options.authority;\n}\n\nfunction assertGitCredentialBindingEcho(\n selection: GitCredentialSelection,\n request: Parameters<NonNullable<ConnectionCredentialsPort[\"gitCredentials\"]>>[0],\n minted: GitCredentials,\n): void {\n if (!selection.requireBindingEcho) return;\n if (minted.credentialBindingId !== request.credentialBindingId) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong credential binding`,\n );\n }\n if (minted.provider !== selection.provider) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong provider echo`,\n );\n }\n if (request.providerHost && minted.providerHost !== request.providerHost) {\n throw new Error(\n `connection-credential provider (${selection.provider}) returned the wrong provider host echo`,\n );\n }\n}\n\n/**\n * The GitHub App installation + repository ids a run's git-credential mint\n * would use for these resources, or null when no GitHub token would be minted.\n * Derived from gitCredentialSelections so workspace-authorization rechecks\n * cover exactly the ids that reach createGitHubAppInstallationToken —\n * including legacy string-typed installationId/repositoryId refs, which the\n * mint path coerces via positiveInteger.\n */\nexport function gitHubTokenMintSelections(\n resources: ResourceRef[],\n): Array<{ installationId: number; repositoryIds: number[] }> {\n return gitCredentialSelections(resources)\n .filter(\n (candidate) =>\n candidate.provider === \"github\" &&\n candidate.installationId > 0 &&\n candidate.repositoryIds.length > 0,\n )\n .map(({ installationId, repositoryIds }) => ({ installationId, repositoryIds }));\n}\n\n/** @deprecated Use gitHubTokenMintSelections for multi-installation sessions. */\nexport function gitHubTokenMintSelection(\n resources: ResourceRef[],\n): { installationId: number; repositoryIds: number[] } | null {\n const selections = gitHubTokenMintSelections(resources);\n if (selections.length > 1) {\n throw new Error(\"GitHub resources span multiple credential bindings\");\n }\n return selections[0] ?? null;\n}\n\nfunction gitCredentialSelections(resources: ResourceRef[]): GitCredentialSelection[] {\n const byBinding = new Map<string, GitCredentialSelection>();\n const remoteBindings = new Map<string, string>();\n const bindingProviders = new Map<string, GitCredentialProvider>();\n for (const resource of resources) {\n if (resource.kind !== \"repository\") {\n continue;\n }\n const provider = repositoryCredentialProvider(resource);\n if (!provider) {\n continue;\n }\n const installationId =\n provider === \"github\"\n ? (positiveInteger(resource.githubInstallationId ?? resource.installationId) ?? 0)\n : 0;\n const credentialBindingId = gitCredentialBindingIdForRepository(resource, provider)!;\n const bindingKey = `${provider}\\u0000${credentialBindingId}`;\n const boundProvider = bindingProviders.get(credentialBindingId);\n if (boundProvider && boundProvider !== provider) {\n throw new Error(\n `credential binding ${credentialBindingId} is assigned to multiple Git providers`,\n );\n }\n bindingProviders.set(credentialBindingId, provider);\n const normalizedRemote = gitRemoteIdentity(resource.uri, provider);\n const claimedBinding = remoteBindings.get(normalizedRemote);\n if (claimedBinding && claimedBinding !== bindingKey) {\n throw new Error(\n `repository remote ${resource.uri} is claimed by multiple credential bindings`,\n );\n }\n remoteBindings.set(normalizedRemote, bindingKey);\n const entry = byBinding.get(bindingKey) ?? {\n provider,\n credentialBindingId,\n explicitCredentialBinding: Boolean(resource.credentialBindingId),\n requireBindingEcho: false,\n installationId: 0,\n repositoryIds: [],\n repositoryRefs: [],\n };\n entry.explicitCredentialBinding ||= Boolean(resource.credentialBindingId);\n const ref = gitCredentialRepositoryRef(resource, provider);\n entry.repositoryRefs.push(ref);\n if (provider === \"github\") {\n const repositoryId = positiveInteger(resource.githubRepositoryId ?? resource.repositoryId);\n if (installationId && repositoryId) {\n if (entry.installationId > 0 && entry.installationId !== installationId) {\n throw new Error(\n `GitHub credential binding ${credentialBindingId} spans multiple installations`,\n );\n }\n entry.installationId = installationId;\n entry.repositoryIds.push(repositoryId);\n }\n }\n byBinding.set(bindingKey, entry);\n }\n const selections = [...byBinding.values()];\n const providerCounts = new Map<GitCredentialProvider, number>();\n for (const selection of selections) {\n providerCounts.set(selection.provider, (providerCounts.get(selection.provider) ?? 0) + 1);\n const hosts = new Set(\n selection.repositoryRefs.map((ref) => normalizedGitHost(ref.uri)).filter(Boolean),\n );\n const [providerHost] = hosts;\n if (hosts.size === 1 && providerHost) selection.providerHost = providerHost;\n }\n for (const selection of selections) {\n selection.requireBindingEcho =\n selection.explicitCredentialBinding || (providerCounts.get(selection.provider) ?? 0) > 1;\n }\n return selections;\n}\n\nfunction normalizedGitHost(uri: string): string {\n try {\n return new URL(uri).host.toLowerCase();\n } catch {\n return \"\";\n }\n}\n\nfunction repositoryCredentialProvider(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n): GitCredentialProvider | null {\n return gitCredentialProviderForRepository(resource);\n}\n\nfunction gitCredentialRepositoryRef(\n resource: Extract<ResourceRef, { kind: \"repository\" }>,\n provider: GitCredentialProvider,\n): GitCredentialRepositoryRef {\n return {\n provider,\n ...(resource.credentialBindingId ? { credentialBindingId: resource.credentialBindingId } : {}),\n ...(resource.access ? { access: resource.access } : {}),\n uri: resource.uri,\n ref: resource.ref,\n ...(resource.repositoryId !== undefined\n ? { repositoryId: resource.repositoryId }\n : resource.githubRepositoryId !== undefined\n ? { repositoryId: resource.githubRepositoryId }\n : {}),\n ...(resource.installationId !== undefined\n ? { installationId: resource.installationId }\n : resource.githubInstallationId !== undefined\n ? { installationId: resource.githubInstallationId }\n : {}),\n ...(resource.projectId !== undefined ? { projectId: resource.projectId } : {}),\n ...(resource.connectionId ? { connectionId: resource.connectionId } : {}),\n };\n}\n\nfunction positiveInteger(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isInteger(value) && value > 0) {\n return value;\n }\n if (typeof value === \"string\" && /^\\d+$/.test(value) && Number(value) > 0) {\n return Number(value);\n }\n return null;\n}\n","import type { GitCredentialProvider } from \"@opengeni/contracts\";\nimport type { GitTokenExpiries, GitTokenSeeds, MintedRunGitCredentials } from \"./environment\";\n\nexport const GIT_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const GIT_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const GIT_CREDENTIAL_MIN_REFRESH_MS = 5_000;\nexport const GIT_CREDENTIAL_MAX_RETRY_MS = 5 * 60_000;\n\ntype RenewalTimer = unknown;\n\nexport type GitCredentialRenewalResult = {\n providers: readonly GitCredentialProvider[];\n nextDelayMs: number;\n};\n\nexport type GitCredentialRenewalFailure = {\n providers: readonly GitCredentialProvider[];\n retryDelayMs: number;\n errorClass: \"GitCredentialRenewalOperationError\";\n};\n\nexport type GitCredentialRenewalController = {\n refreshNow(): Promise<void>;\n stop(): Promise<void>;\n};\n\nexport type GitCredentialRenewalOptions = {\n expectedProviders: readonly GitCredentialProvider[];\n initialExpiresAt?: GitTokenExpiries;\n mint: () => Promise<MintedRunGitCredentials | undefined>;\n write: (tokens: GitTokenSeeds) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: GitCredentialRenewalResult) => void;\n onFailure?: (failure: GitCredentialRenewalFailure) => void;\n};\n\n/**\n * Return a conservative refresh delay for a provider set.\n *\n * The fixed cadence caps long/unknown provider TTLs; a known earlier expiry\n * pulls renewal forward. Invalid metadata is treated as unknown rather than\n * allowing a token to live indefinitely.\n */\nexport function nextGitCredentialRenewalDelay(\n expiresAt: GitTokenExpiries | undefined,\n providers: readonly GitCredentialProvider[],\n nowMs = Date.now(),\n): number {\n let delay = GIT_CREDENTIAL_DEFAULT_REFRESH_MS;\n for (const provider of providers) {\n const rawExpiry = expiresAt?.[provider];\n if (!rawExpiry) continue;\n const expiryMs = Date.parse(rawExpiry);\n if (!Number.isFinite(expiryMs)) continue;\n delay = Math.min(\n delay,\n Math.max(GIT_CREDENTIAL_MIN_REFRESH_MS, expiryMs - nowMs - GIT_CREDENTIAL_EXPIRY_LEAD_MS),\n );\n }\n return delay;\n}\n\nexport function startGitCredentialRenewalLoop(\n options: GitCredentialRenewalOptions,\n): GitCredentialRenewalController {\n const providers = [...new Set(options.expectedProviders)];\n const now = options.now ?? Date.now;\n const schedule =\n options.schedule ??\n ((callback: () => void, delayMs: number): ReturnType<typeof setTimeout> => {\n const timer = setTimeout(callback, delayMs);\n timer.unref?.();\n return timer;\n });\n const clearSchedule =\n options.clearSchedule ??\n ((timer: RenewalTimer): void => clearTimeout(timer as ReturnType<typeof setTimeout>));\n\n let stopped = false;\n let timer: RenewalTimer | null = null;\n let inFlight: Promise<void> | null = null;\n let writeInFlight: Promise<void> | null = null;\n let retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;\n\n const clearTimer = (): void => {\n if (timer === null) return;\n clearSchedule(timer);\n timer = null;\n };\n\n const scheduleRefresh = (delayMs: number): void => {\n if (stopped || providers.length === 0) return;\n clearTimer();\n timer = schedule(() => {\n timer = null;\n void refreshNow();\n }, delayMs);\n };\n\n const validateMintedTokens = (\n minted: MintedRunGitCredentials | undefined,\n ): MintedRunGitCredentials => {\n if (!minted) {\n throw new GitCredentialRenewalError(\"credential provider returned no token bundle\");\n }\n for (const provider of providers) {\n if (!minted.gitTokens[provider]) {\n throw new GitCredentialRenewalError(`credential provider omitted ${provider}`);\n }\n }\n return minted;\n };\n\n const performRefresh = async (): Promise<void> => {\n try {\n const minted = validateMintedTokens(await options.mint());\n if (stopped) return;\n const write = options.write(minted.gitTokens);\n writeInFlight = write;\n try {\n await write;\n } finally {\n if (writeInFlight === write) writeInFlight = null;\n }\n if (stopped) return;\n retryDelayMs = GIT_CREDENTIAL_MIN_REFRESH_MS;\n const nextDelayMs = nextGitCredentialRenewalDelay(minted.expiresAt, providers, now());\n try {\n options.onSuccess?.({ providers, nextDelayMs });\n } catch {\n // Observability callbacks never own credential liveness.\n }\n scheduleRefresh(nextDelayMs);\n } catch {\n if (stopped) return;\n const scheduledRetryMs = retryDelayMs;\n retryDelayMs = Math.min(retryDelayMs * 2, GIT_CREDENTIAL_MAX_RETRY_MS);\n try {\n options.onFailure?.({\n providers,\n retryDelayMs: scheduledRetryMs,\n errorClass: \"GitCredentialRenewalOperationError\",\n });\n } catch {\n // Observability callbacks never own credential liveness.\n }\n scheduleRefresh(scheduledRetryMs);\n }\n };\n\n const refreshNow = (): Promise<void> => {\n if (stopped || providers.length === 0) return Promise.resolve();\n if (inFlight) return inFlight;\n clearTimer();\n const operation = performRefresh();\n inFlight = operation;\n void operation.finally(() => {\n if (inFlight === operation) inFlight = null;\n });\n return operation;\n };\n\n scheduleRefresh(nextGitCredentialRenewalDelay(options.initialExpiresAt, providers, now()));\n\n return {\n refreshNow,\n stop: async () => {\n stopped = true;\n clearTimer();\n // A broker mint can be a remote host call with no cancellation seam. It\n // cannot mutate the sandbox, and the stopped check above rejects its late\n // result, so never hold turn settlement hostage to a hung mint. A write\n // does mutate the box and must drain before capture/teardown.\n await writeInFlight?.catch(() => undefined);\n },\n };\n}\n\nclass GitCredentialRenewalError extends Error {\n override readonly name = \"GitCredentialRenewalError\";\n}\n","export type ExpiringMaterialRenewalPolicy = {\n defaultRefreshMs: number;\n expiryLeadMs: number;\n minRefreshMs: number;\n maxRetryMs: number;\n};\n\ntype RenewalTimer = unknown;\n\nexport type ExpiringMaterialRenewalController = {\n refreshNow(): Promise<void>;\n stop(): Promise<void>;\n};\n\nexport type ExpiringMaterialRenewalPublicErrorClass =\n | \"RunCredentialRenewalOperationError\"\n | \"CodemodeTokenRenewalOperationError\";\n\nexport type ExpiringMaterialRenewalOptions<\n T,\n ErrorClass extends ExpiringMaterialRenewalPublicErrorClass,\n> = {\n initialExpiresAt: Date | null;\n resolve: () => Promise<T>;\n write: (material: T) => Promise<void>;\n expiresAt: (material: T) => Date | null;\n publicErrorClass: ErrorClass;\n policy: ExpiringMaterialRenewalPolicy;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: { material: T; nextDelayMs: number }) => void;\n onFailure?: (failure: { retryDelayMs: number; errorClass: ErrorClass }) => void;\n};\n\nexport function nextExpiringMaterialRenewalDelay(\n expiresAt: Date | null,\n policy: ExpiringMaterialRenewalPolicy,\n nowMs = Date.now(),\n): number {\n if (!expiresAt || !Number.isFinite(expiresAt.getTime())) {\n return policy.defaultRefreshMs;\n }\n return Math.min(\n policy.defaultRefreshMs,\n Math.max(policy.minRefreshMs, expiresAt.getTime() - nowMs - policy.expiryLeadMs),\n );\n}\n\n/**\n * Attempt-owned single-flight renewal for expiring sandbox material.\n *\n * A late resolver cannot write after stop. A physical sandbox write that already\n * started is drained so turn settlement cannot race a stale mutation.\n */\nexport function startExpiringMaterialRenewalLoop<\n T,\n ErrorClass extends ExpiringMaterialRenewalPublicErrorClass,\n>(options: ExpiringMaterialRenewalOptions<T, ErrorClass>): ExpiringMaterialRenewalController {\n const now = options.now ?? Date.now;\n const schedule =\n options.schedule ??\n ((callback: () => void, delayMs: number): ReturnType<typeof setTimeout> => {\n const timer = setTimeout(callback, delayMs);\n timer.unref?.();\n return timer;\n });\n const clearSchedule =\n options.clearSchedule ??\n ((timer: RenewalTimer): void => clearTimeout(timer as ReturnType<typeof setTimeout>));\n let stopped = false;\n let timer: RenewalTimer | null = null;\n let inFlight: Promise<void> | null = null;\n let writeInFlight: Promise<void> | null = null;\n let retryDelayMs = options.policy.minRefreshMs;\n\n const clearTimer = (): void => {\n if (timer === null) return;\n clearSchedule(timer);\n timer = null;\n };\n const scheduleRefresh = (delayMs: number): void => {\n if (stopped) return;\n clearTimer();\n timer = schedule(() => {\n timer = null;\n void refreshNow();\n }, delayMs);\n };\n const performRefresh = async (): Promise<void> => {\n try {\n const material = await options.resolve();\n if (stopped) return;\n const write = options.write(material);\n writeInFlight = write;\n try {\n await write;\n } finally {\n if (writeInFlight === write) writeInFlight = null;\n }\n if (stopped) return;\n retryDelayMs = options.policy.minRefreshMs;\n const nextDelayMs = nextExpiringMaterialRenewalDelay(\n options.expiresAt(material),\n options.policy,\n now(),\n );\n try {\n options.onSuccess?.({ material, nextDelayMs });\n } catch {\n // Observability never owns credential liveness.\n }\n scheduleRefresh(nextDelayMs);\n } catch {\n if (stopped) return;\n const scheduledRetryMs = retryDelayMs;\n retryDelayMs = Math.min(retryDelayMs * 2, options.policy.maxRetryMs);\n try {\n options.onFailure?.({\n retryDelayMs: scheduledRetryMs,\n errorClass: options.publicErrorClass,\n });\n } catch {\n // Observability never owns credential liveness.\n }\n scheduleRefresh(scheduledRetryMs);\n }\n };\n const refreshNow = (): Promise<void> => {\n if (stopped) return Promise.resolve();\n if (inFlight) return inFlight;\n clearTimer();\n const operation = performRefresh();\n inFlight = operation;\n void operation.finally(() => {\n if (inFlight === operation) inFlight = null;\n });\n return operation;\n };\n\n scheduleRefresh(\n nextExpiringMaterialRenewalDelay(options.initialExpiresAt, options.policy, now()),\n );\n return {\n refreshNow,\n stop: async () => {\n stopped = true;\n clearTimer();\n await writeInFlight?.catch(() => undefined);\n },\n };\n}\n","import type { NormalizedRunCredentialMaterial } from \"@opengeni/runtime\";\nimport {\n nextExpiringMaterialRenewalDelay,\n startExpiringMaterialRenewalLoop,\n type ExpiringMaterialRenewalController,\n} from \"./expiring-material-renewal\";\n\nexport const RUN_CREDENTIAL_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const RUN_CREDENTIAL_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const RUN_CREDENTIAL_MIN_REFRESH_MS = 5_000;\nexport const RUN_CREDENTIAL_MAX_RETRY_MS = 5 * 60_000;\n\nexport type RunCredentialRenewalController = ExpiringMaterialRenewalController;\n\ntype RenewalTimer = unknown;\n\nexport type RunCredentialRenewalOptions = {\n initialExpiresAt: Date | null;\n resolve: () => Promise<NormalizedRunCredentialMaterial | null>;\n write: (material: NormalizedRunCredentialMaterial | null) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => RenewalTimer;\n clearSchedule?: (timer: RenewalTimer) => void;\n onSuccess?: (result: { nextDelayMs: number; authNeeded: boolean }) => void;\n onFailure?: (failure: {\n retryDelayMs: number;\n errorClass: \"RunCredentialRenewalOperationError\";\n }) => void;\n};\n\nexport function nextRunCredentialRenewalDelay(expiresAt: Date | null, nowMs = Date.now()): number {\n return nextExpiringMaterialRenewalDelay(\n expiresAt,\n {\n defaultRefreshMs: RUN_CREDENTIAL_DEFAULT_REFRESH_MS,\n expiryLeadMs: RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n minRefreshMs: RUN_CREDENTIAL_MIN_REFRESH_MS,\n maxRetryMs: RUN_CREDENTIAL_MAX_RETRY_MS,\n },\n nowMs,\n );\n}\n\n/** Single-flight renewal; late resolves cannot mutate a stopped attempt. */\nexport function startRunCredentialRenewalLoop(\n options: RunCredentialRenewalOptions,\n): RunCredentialRenewalController {\n return startExpiringMaterialRenewalLoop<\n NormalizedRunCredentialMaterial | null,\n \"RunCredentialRenewalOperationError\"\n >({\n initialExpiresAt: options.initialExpiresAt,\n resolve: options.resolve,\n write: options.write,\n expiresAt: (material) => material?.expiresAt ?? null,\n publicErrorClass: \"RunCredentialRenewalOperationError\",\n policy: {\n defaultRefreshMs: RUN_CREDENTIAL_DEFAULT_REFRESH_MS,\n expiryLeadMs: RUN_CREDENTIAL_EXPIRY_LEAD_MS,\n minRefreshMs: RUN_CREDENTIAL_MIN_REFRESH_MS,\n maxRetryMs: RUN_CREDENTIAL_MAX_RETRY_MS,\n },\n ...(options.now ? { now: options.now } : {}),\n ...(options.schedule ? { schedule: options.schedule } : {}),\n ...(options.clearSchedule ? { clearSchedule: options.clearSchedule } : {}),\n ...(options.onSuccess\n ? {\n onSuccess: ({ material, nextDelayMs }) =>\n options.onSuccess?.({\n nextDelayMs,\n authNeeded: (material?.authNeeded.length ?? 0) > 0,\n }),\n }\n : {}),\n ...(options.onFailure ? { onFailure: options.onFailure } : {}),\n });\n}\n","import {\n startExpiringMaterialRenewalLoop,\n type ExpiringMaterialRenewalController,\n} from \"./expiring-material-renewal\";\nimport type { MintedSandboxCodemodeToken } from \"./environment\";\n\nexport const CODEMODE_TOKEN_DEFAULT_REFRESH_MS = 30 * 60_000;\nexport const CODEMODE_TOKEN_EXPIRY_LEAD_MS = 5 * 60_000;\nexport const CODEMODE_TOKEN_MIN_REFRESH_MS = 5_000;\nexport const CODEMODE_TOKEN_MAX_RETRY_MS = 5 * 60_000;\n\nexport type CodemodeTokenRenewalController = ExpiringMaterialRenewalController;\n\nexport type CodemodeTokenRenewalOptions = {\n initialExpiresAt: Date;\n mint: () => Promise<MintedSandboxCodemodeToken | undefined>;\n write: (material: MintedSandboxCodemodeToken) => Promise<void>;\n now?: () => number;\n schedule?: (callback: () => void, delayMs: number) => unknown;\n clearSchedule?: (timer: unknown) => void;\n onSuccess?: (result: { nextDelayMs: number }) => void;\n onFailure?: (failure: {\n retryDelayMs: number;\n errorClass: \"CodemodeTokenRenewalOperationError\";\n }) => void;\n};\n\nclass CodemodeTokenRenewalError extends Error {\n override readonly name = \"CodemodeTokenRenewalError\";\n}\n\nexport function startCodemodeTokenRenewalLoop(\n options: CodemodeTokenRenewalOptions,\n): CodemodeTokenRenewalController {\n return startExpiringMaterialRenewalLoop<\n MintedSandboxCodemodeToken,\n \"CodemodeTokenRenewalOperationError\"\n >({\n initialExpiresAt: options.initialExpiresAt,\n resolve: async () => {\n const minted = await options.mint();\n if (!minted) {\n throw new CodemodeTokenRenewalError(\"Codemode token mint is no longer available\");\n }\n return minted;\n },\n write: options.write,\n expiresAt: (material) => material.expiresAt,\n publicErrorClass: \"CodemodeTokenRenewalOperationError\",\n policy: {\n defaultRefreshMs: CODEMODE_TOKEN_DEFAULT_REFRESH_MS,\n expiryLeadMs: CODEMODE_TOKEN_EXPIRY_LEAD_MS,\n minRefreshMs: CODEMODE_TOKEN_MIN_REFRESH_MS,\n maxRetryMs: CODEMODE_TOKEN_MAX_RETRY_MS,\n },\n ...(options.now ? { now: options.now } : {}),\n ...(options.schedule ? { schedule: options.schedule } : {}),\n ...(options.clearSchedule ? { clearSchedule: options.clearSchedule } : {}),\n ...(options.onSuccess\n ? { onSuccess: ({ nextDelayMs }) => options.onSuccess?.({ nextDelayMs }) }\n : {}),\n ...(options.onFailure ? { onFailure: options.onFailure } : {}),\n });\n}\n","import type {\n ConnectionCredentialsPort,\n CredentialAuthNeededPayload,\n SandboxBackend,\n RunCredentialsRequest,\n Session,\n SessionTurn,\n} from \"@opengeni/contracts\";\nimport { getSessionRootId, type Database } from \"@opengeni/db\";\nimport {\n normalizeRunCredentialsResolution,\n type NormalizedRunCredentialMaterial,\n} from \"@opengeni/runtime\";\n\nexport type RunCredentialResolutionContext = {\n db: Database;\n connectionCredentials?: ConnectionCredentialsPort | null;\n accountId: string;\n workspaceId: string;\n session: Session;\n turn: SessionTurn;\n attemptId: string;\n effectiveSandboxBackend: SandboxBackend;\n variableSet: { id: string; name: string } | null;\n};\n\nexport type BoundRunCredentialResolver = {\n resolve(input: {\n purpose: \"provision\" | \"renewal\";\n forceRefresh: boolean;\n }): Promise<NormalizedRunCredentialMaterial | null>;\n};\n\nexport function buildRunCredentialsRequest(\n input: Omit<RunCredentialResolutionContext, \"db\" | \"connectionCredentials\"> & {\n rootSessionId: string;\n purpose: \"provision\" | \"renewal\";\n forceRefresh: boolean;\n },\n): RunCredentialsRequest {\n return {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.session.id,\n parentSessionId: input.session.parentSessionId,\n rootSessionId: input.rootSessionId,\n sandboxGroupId: input.session.sandboxGroupId,\n turnId: input.turn.id,\n attemptId: input.attemptId,\n executionGeneration: input.turn.executionGeneration,\n initiator: input.turn.initiator,\n initiatorContext: input.turn.initiatorContext,\n effectiveSandboxBackend: input.effectiveSandboxBackend,\n sandboxOs: input.turn.sandboxOs ?? input.session.sandboxOs,\n purpose: input.purpose,\n forceRefresh: input.forceRefresh,\n variableSet: input.variableSet,\n };\n}\n\nexport function runCredentialAuthNeededPayloads(\n material: NormalizedRunCredentialMaterial,\n): CredentialAuthNeededPayload[] {\n return material.authNeeded.map((notice) => ({\n credentialClass: \"run\",\n reason: notice.reason,\n ...(notice.providerDomain ? { providerDomain: notice.providerDomain } : {}),\n ...(notice.connectionId ? { connectionId: notice.connectionId } : {}),\n ...(notice.scopes?.length ? { scopes: notice.scopes } : {}),\n ...(notice.resource ? { resource: notice.resource } : {}),\n ...(notice.authorizationUrl ? { authorizationUrl: notice.authorizationUrl } : {}),\n ...(notice.message ? { message: notice.message } : {}),\n }));\n}\n\nexport function runCredentialModelNote(\n material: NormalizedRunCredentialMaterial,\n): string | undefined {\n if (material.authNeeded.length === 0) return undefined;\n return [\n \"[OpenGeni connected-service status]\",\n \"One or more host-managed credentials need user attention. Continue with available capabilities, but do not claim the affected service is usable until it is reconnected.\",\n JSON.stringify({\n credentials: material.authNeeded.map((notice) => ({\n reason: notice.reason,\n ...(notice.providerDomain ? { providerDomain: notice.providerDomain } : {}),\n ...(notice.resource ? { resource: notice.resource } : {}),\n ...(notice.message ? { message: notice.message } : {}),\n })),\n }),\n ].join(\"\\n\");\n}\n\n/**\n * Freeze the provider-neutral host credential request to this exact admitted\n * turn. The host selects connections and material; the worker never infers a\n * provider from repositories, environment names, or an OpenGeni variable set.\n */\nexport async function bindRunCredentialResolver(\n input: RunCredentialResolutionContext,\n): Promise<BoundRunCredentialResolver | null> {\n const resolver = input.connectionCredentials?.runCredentials;\n if (!resolver) return null;\n const rootSessionId = await getSessionRootId(input.db, input.workspaceId, input.session.id);\n if (!rootSessionId) {\n throw new Error(`cannot resolve run credentials for missing session ${input.session.id}`);\n }\n const scope = {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.session.id,\n };\n return {\n resolve: async ({ purpose, forceRefresh }) => {\n const resolution = await resolver(\n buildRunCredentialsRequest({\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n session: input.session,\n turn: input.turn,\n attemptId: input.attemptId,\n effectiveSandboxBackend: input.effectiveSandboxBackend,\n variableSet: input.variableSet,\n rootSessionId,\n purpose,\n forceRefresh,\n }),\n );\n return normalizeRunCredentialsResolution(resolution, scope);\n },\n };\n}\n","import type { Settings } from \"@opengeni/config\";\nimport type {\n ConnectionCredentialsPort,\n DocumentAuthorityKind,\n EntitlementsPort,\n ScheduledTaskTriggerType,\n TurnInitiator,\n} from \"@opengeni/contracts\";\nimport type { Database } from \"@opengeni/db\";\nimport type { DocumentServices } from \"@opengeni/documents\";\nimport type { EventBus } from \"@opengeni/events\";\nimport type { Observability } from \"@opengeni/observability\";\nimport type { OpenGeniRuntime } from \"@opengeni/runtime\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\n\n// Signal (start-if-needed) a session's Temporal workflow so a queued turn it\n// cannot otherwise observe gets claimed. Used to wake a PARENT session's\n// workflow when a spawned worker completes: the parent may have idled and let\n// its workflow run complete, so a plain signal would not start one — this must\n// signalWithStart. Injected (not built from the worker's NativeConnection)\n// because the worker package owns only the worker runtime, not a client; an\n// missing signaler leaves the committed outbox revision for the global repair\n// sweep; production workers always inject this dependency.\nexport type WakeSessionWorkflowSignal = (input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n wakeRevision: number;\n interruptionRequested?: boolean;\n}) => Promise<void>;\n\nexport type SignalCodexCapacityWorkflow = (input: {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n wakeRevision: number;\n}) => Promise<void>;\n\n/** Start the versioned, per-box sandbox reaper from the history-stable legacy\n * activity. The legacy Schedule workflow must keep its exact historical\n * ScheduleActivity command across mixed-version worker pools. */\nexport type StartSandboxReaperWorkflow = () => Promise<\"started\" | \"already_running\">;\n\n/** Start-or-observe the one durable reconciler for a paid video operation. */\nexport type StartVideoGenerationWorkflow = (input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n}) => Promise<\"started\" | \"already_running\">;\n\n/** Exact activity-owned proof that the hard sandbox/tool fence physically\n * drained. This is delivery evidence only: the workflow still validates the\n * persisted attempt dispatch and commits the authoritative Postgres receipt. */\nexport type SessionAttemptQuiescenceProof = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n workflowRunId: string;\n activityId: string;\n};\n\nexport type SignalSessionAttemptQuiesced = (input: SessionAttemptQuiescenceProof) => Promise<void>;\n\nexport type InspectSessionAttemptActivity = (input: {\n workflowId: string;\n workflowRunId: string;\n activityId: string;\n}) => Promise<\"pending\" | \"settled\">;\n\n/** Services shared by both Temporal worker roles. Keep this graph free of the\n * agent runtime and document parser so each process can load only its role. */\nexport type SharedActivityServices = {\n settings: Settings;\n db: Database;\n bus: EventBus;\n objectStorage: ObjectStorage | null;\n observability: Observability;\n wakeSessionWorkflow: WakeSessionWorkflowSignal | null;\n /** Durable signalWithStart fallback used only after the activity's direct\n * physical-quiescence receipt write exhausts its bounded DB retries. */\n signalSessionAttemptQuiesced: SignalSessionAttemptQuiesced | null;\n /** Server-authoritative Temporal activity lease inspection used only to\n * recover a missing quiescence receipt after the original activity vanished. */\n inspectSessionAttemptActivity: InspectSessionAttemptActivity | null;\n /** Revision-carrying capacity nudge; generic outbox repair is also sufficient. */\n signalCodexCapacityWorkflow?: SignalCodexCapacityWorkflow | null;\n /** Production control workers inject this Temporal client edge. A null edge\n * deliberately retains the composite implementation for embedded/test hosts. */\n startSandboxReaperWorkflow?: StartSandboxReaperWorkflow | null;\n startVideoGenerationWorkflow?: StartVideoGenerationWorkflow | null;\n // §7.5 P3 — host-entitlements port, the WORKER half of the same seam the API\n // edge exposes on `AppDependencies`. When set, `ensureRunAllowed` (turn-entry\n // AND the mid-stream budget valve) delegates the funding decision to\n // `admitRun` instead of reading `getBillingBalance` locally. null/undefined\n // (standalone default) → today's local-ledger read runs unchanged.\n //\n // IDEMPOTENCY: the worker calls `admitRun` ONLY as an admission READ (\"may\n // this run/continue?\"), never to RECORD consumption. Usage is recorded\n // exactly once, by `recordUsageEvent` keyed on a deterministic idempotency\n // key the API already wrote at create-time — so a host PULL meter that also\n // observes that same recorded event is consulted without double-charging:\n // admission and metering are separate operations, and only metering carries\n // the idempotency key.\n entitlements?: EntitlementsPort | null;\n // §7.6 connection-credential provider — host connection-credential provider, the WORKER half of the\n // federated-connection boundary. When set, the run's per-run credential mint\n // delegates to the host instead of self-minting from `settings`:\n // - `gitCredentials` REPLACES `createGitHubAppInstallationToken(settings,…)`\n // in `sandboxEnvironmentForRun` (the GH_TOKEN / git-extraheader source).\n // - `sandboxSecrets` REPLACES the `environmentsEncryptionKeyBytes(settings)`\n // decrypt in `loadWorkspaceEnvironmentForRun`.\n // Each leg is independently optional; an unset leg falls through to today's\n // self-mint for THAT leg. null/undefined (standalone default) → both legs\n // self-mint byte-for-byte as today.\n //\n // workspace-scope cross-check CROSS-CHECK: a provider echoes the `workspaceId` it scoped the\n // credential to; the consuming activity ASSERTS agreement with the run's\n // workspace BEFORE injecting `GH_TOKEN` (or applying decrypted values). A host\n // mapping bug returning tenant B's creds for a tenant-A run is caught here.\n connectionCredentials?: ConnectionCredentialsPort | null;\n};\n\n/** Control workers own short database and maintenance activities. Document\n * parsing is resolved lazily by the indexing activity itself. */\nexport type ControlActivityServices = SharedActivityServices;\n\n/** Turn workers own the model loop and never construct document parsers. */\nexport type TurnActivityServices = SharedActivityServices & {\n runtime: OpenGeniRuntime;\n /** Provider-free test/profiling seam; production injects the real runtime summarizer. */\n summarizeContextForCompaction: typeof import(\"@opengeni/runtime\").summarizeForCompaction;\n};\n\n/** Full test/embedded harness retained as a source-compatible superset. */\nexport type ActivityServices = ControlActivityServices &\n TurnActivityServices & {\n documentServices: DocumentServices;\n };\n\nexport type CodexCapacityWaitRef = {\n /** Absent only for Temporal histories written before provider-tagged waits. */\n provider?: \"codex\" | \"xai\";\n waiterId: string;\n generation: number;\n nextCheckAt: string;\n wakeRevision: number;\n};\n\nexport type XaiCapacityWaitRef = CodexCapacityWaitRef & { provider: \"xai\" };\n\nexport type GetCodexCapacityWaitInput = {\n workspaceId: string;\n sessionId: string;\n};\n\nexport type ReconcileCodexCapacityWaitInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n waiterId: string;\n generation: number;\n cause: \"timer\" | \"signal\" | \"queue\" | \"recovery\";\n /** Absent only for Codex waits and pre-provider-tagged workflow histories. */\n provider?: \"codex\" | \"xai\";\n};\n\nexport type ReconcileCodexCapacityWaitResult =\n | ({ action: \"waiting\" } & CodexCapacityWaitRef)\n | { action: \"resumed\" | \"paused\" | \"superseded\" | \"stale\" };\n\nexport type ActivityDependencies = Partial<ActivityServices>;\nexport type ControlActivityDependencies = Partial<ControlActivityServices>;\nexport type TurnActivityDependencies = Partial<TurnActivityServices>;\n\nexport type RunAgentTurnInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n workflowRunId: string;\n attemptId: string;\n trigger: { kind: \"next\" } | { kind: \"approval\"; triggerEventId: string };\n};\n\nexport type VideoGenerationTerminalStatus =\n | \"completed\"\n | \"provider_failed\"\n | \"cancelled_before_submit\"\n | \"outcome_unknown\"\n | \"retention_failed\";\n\nexport type VideoGenerationReconcileResult =\n | { action: \"waiting\"; delayMs: number }\n | { action: \"terminal\"; status: VideoGenerationTerminalStatus };\n\nexport type SettleSessionInterruptionsInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n /**\n * Replay-only compatibility for session workflow histories created before\n * the receipt-gated cancellation v2 patch. New histories never send this\n * phase; the exact activity writes the authoritative receipt itself.\n */\n phase?: \"logical\" | \"attempt_quiesced\";\n};\n\nexport type PersistSessionAttemptQuiescenceInput = SessionAttemptQuiescenceProof;\n\nexport type ReconcileSessionAttemptQuiescenceInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n workflowId: string;\n};\n\nexport type ReconcileSessionAttemptQuiescenceResult = {\n action: \"quiesced\" | \"pending\" | \"stale\";\n};\n\nexport type FailSessionAttemptInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n /** Added in v2; old Temporal histories derive the session's canonical id. */\n workflowId?: string;\n /** Added in v2; old Temporal histories use the bounded 60-second floor. */\n retryDelayMs?: number;\n /** Added in v3. Upgraded turn workers classify failures from the atomic\n * admission transaction; omission is a rolling-deploy/legacy unknown and\n * deliberately keeps the recoverable wake behavior. */\n preClaimFailureDisposition?: PreClaimFailureDisposition;\n /** The workflow admission trigger is required to re-evaluate the same\n * durable admission branch before terminally settling a permanent failure. */\n trigger?: RunAgentTurnInput[\"trigger\"];\n error?: string;\n};\n\nexport type FailSessionAttemptResult =\n | { action: \"failed\" }\n | { action: \"unclaimed\" }\n | { action: \"terminal\" }\n | { action: \"stale\" };\n\nexport type PreClaimFailureDisposition = \"retryable\" | \"permanent\";\n\nexport type PreClaimFailureDetail = {\n disposition: PreClaimFailureDisposition;\n code: \"db_deadlock\" | \"db_serialization_failure\" | \"db_failure\" | \"claim_invariant\";\n};\n\nexport const PRE_CLAIM_FAILURE_TYPE = \"OpenGeniPreClaimFailure\";\nexport const PRE_CLAIM_FAILURE_MESSAGE = \"Agent turn admission failed before attempt claim.\";\n\nexport type RecoverDispatchInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n timeoutType: \"HEARTBEAT\" | \"SCHEDULE_TO_START\";\n};\n\nexport type RecoverDispatchResult =\n // The same current inference is now recoverable. It never enters the prompt\n // queue; the next claim creates a new attempt for this exact turn.\n | { action: \"unclaimed\" }\n | { action: \"recovering\"; turnId: string; redispatches: number }\n // The turn is no longer running/requires_action: the timed-out attempt was\n // a zombie that actually settled the turn after the server gave up on its\n // heartbeats. Nothing to redo; the workflow just continues its loop.\n | { action: \"stale\" }\n // The per-turn crash-loop guard tripped; the workflow must fail the\n // session for real. `redispatches` is the count already consumed (== the\n // ceiling), so the failed attempt was worker death number redispatches + 1.\n | { action: \"exceeded\"; turnId: string; redispatches: number };\n\nexport const ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_TYPE = \"EscapedMcpTimeoutRecoveryFailure\";\nexport const ESCAPED_MCP_TIMEOUT_RECOVERY_FAILURE_MESSAGE =\n \"MCP request timeout recovery checkpoint failed before model request\";\n\nexport type EscapedMcpTimeoutRecoveryDetail = {\n turnId: string;\n triggerEventId: string;\n executionGeneration: number;\n};\n\nexport type RecoverEscapedMcpTimeoutInput = EscapedMcpTimeoutRecoveryDetail & {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n attemptId: string;\n};\n\nexport type RecoverEscapedMcpTimeoutResult = {\n action: \"recovering\" | \"stale\" | \"ineligible\";\n};\n\nexport type PeekSessionWorkInput = {\n workspaceId: string;\n sessionId: string;\n};\n\nexport type ExpireSessionHumanInputInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n requestId: string;\n};\n\nexport type ExpireSessionHumanInputResult = {\n action: \"expired\" | \"stale\" | \"not_found\";\n};\n\nexport type ExpireSessionInteractionInterventionInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n interventionId: string;\n};\n\nexport type ExpireSessionInteractionInterventionResult = {\n action: \"expired\" | \"stale\" | \"not_found\";\n};\n\nexport type MarkSessionIdleInput = {\n workspaceId: string;\n sessionId: string;\n};\n\nexport type MaybeContinueGoalInput = {\n accountId: string;\n workspaceId: string;\n sessionId: string;\n workflowId: string;\n};\n\nexport type MaybeContinueGoalResult = {\n action: \"none\" | \"queue\" | \"continue\" | \"paused\";\n};\n\nexport type DispatchScheduledTaskRunInput = {\n workspaceId: string;\n taskId: string;\n /** Stable Temporal workflow identity; retries must reuse the same source row. */\n producerKey?: string;\n} & (\n | {\n triggerType: Extract<ScheduledTaskTriggerType, \"scheduled\">;\n agentRunUsageIdempotencyKey?: never;\n initiator?: never;\n }\n | {\n triggerType: Extract<\n ScheduledTaskTriggerType,\n \"manual\" | \"initial\" | \"provider_event\" | \"retry\" | \"repair\"\n >;\n agentRunUsageIdempotencyKey: string;\n /** Exact identity used by the API-side charge for this same trigger. */\n initiator: TurnInitiator;\n }\n);\n\nexport type DispatchScheduledTaskRunResult =\n | { action: \"deleted\" }\n | {\n action: \"blocked\";\n reason:\n | \"insufficient_credits\"\n | \"monthly_model_cost_limit\"\n | \"monthly_agent_run_limit\"\n | \"malformed_manual_trigger\"\n | \"knowledge_source_paused\";\n }\n | {\n action: \"start\" | \"signal\";\n accountId: string;\n workspaceId: string;\n sessionId: string;\n triggerEventId: string;\n workflowId: string;\n workflowWakeRevision: number | null;\n }\n | {\n action: \"knowledge_source_sync\";\n accountId: string;\n workspaceId: string;\n taskId: string;\n scheduledTaskRunId: string;\n sourceId: string;\n overlapPolicy: \"skip\" | \"buffer_one\";\n };\n\nexport type RunKnowledgeSourceSyncBatchInput = {\n accountId: string;\n workspaceId: string;\n taskId: string;\n scheduledTaskRunId: string;\n sourceId: string;\n overlapPolicy: \"skip\" | \"buffer_one\";\n};\n\nexport type RunKnowledgeSourceSyncBatchResult =\n | { action: \"continue\" }\n | {\n action: \"complete\";\n bufferedWake: boolean;\n bufferedScheduledTaskRunId?: string | null;\n }\n | { action: \"skipped\" | \"buffered\" }\n | {\n action: \"failed\";\n bufferedWake: boolean;\n bufferedScheduledTaskRunId?: string | null;\n };\n\ntype DocumentIndexIdentity = {\n accountId: string;\n workspaceId: string;\n documentId: string;\n};\n\ntype CurrentDocumentIndexAuthority = {\n authorityKind: DocumentAuthorityKind;\n authorityWorkspaceId: string | null;\n authoritySubjectId: string | null;\n};\n\ntype HistoricalDocumentIndexAuthority = {\n authorityKind?: never;\n authorityWorkspaceId?: never;\n authoritySubjectId?: never;\n};\n\nexport type IndexDocumentInput = DocumentIndexIdentity &\n (CurrentDocumentIndexAuthority | HistoricalDocumentIndexAuthority);\n\ntype ClaimedRunAgentTurnResult = {\n // \"recovering\": this attempt ended after durably preserving the same current\n // inference for a new attempt. Recovery is not prompt queue work.\n status: \"idle\" | \"requires_action\" | \"failed\" | \"cancelled\" | \"recovering\" | \"waiting_capacity\";\n turnId: string;\n attemptId: string;\n // Provider backpressure pacing: when set on an idle or recovering result, the\n // session workflow holds the loop this long before admitting the next attempt.\n continueDelayMs?: number;\n // Multi-account rotation all-capped idle: every connected Codex subscription is\n // rate-limited/cooling. This is a MANDATORY hold — session.ts must wait\n // continueDelayMs (floored to a minimum) and must NOT treat a 0/elapsed delay as\n // \"continue now\" (invariant 4: NO THRASH). Distinct from a normal continueDelayMs:0\n // which legitimately means \"a rotation candidate is ready, re-dispatch immediately\".\n idleUntilReset?: boolean;\n // Durable native zero-pool wait for this same nonterminal logical turn.\n // Unlike continueDelayMs, this reference is persisted in Postgres and\n // reconstructed after workflow/worker restart. The workflow must not call\n // maybeContinueGoal or manufacture queue/input work while it is active.\n capacityWait?: CodexCapacityWaitRef;\n // This execution reached a durable terminal-for-now boundary (for example,\n // maintenance could not run or same-turn context recovery failed). End this\n // workflow run without synthesizing another goal continuation from unchanged\n // state. A later prompt/control/new-update wake may retry through normal claim\n // ordering.\n deferredUntilWake?: boolean;\n};\n\nexport type RunAgentTurnResult =\n | ClaimedRunAgentTurnResult\n | {\n status: \"unclaimed\";\n reason: \"gate-closed\" | \"no-work\" | \"stale-approval\" | \"control-pending\";\n };\n","// The Temporal adaptation of the op-stream durable-resume journal\n// (`OpStreamJournal`, @opengeni/runtime): the runtime leaf stays\n// Temporal-free; this is where its two seams bind to the activity.\n//\n// * `attachGeneration` — the consumer generation the runner fences zombie\n// consumers by. `Info.attempt` CANNOT serve here: `runAgentTurn` runs with\n// `maximumAttempts: 1`, so worker death is healed by the WORKFLOW\n// redispatching a NEW activity whose attempt is 1 again. The activity's\n// `currentAttemptScheduledTimestampMs` is Temporal-server-assigned and\n// strictly larger for a later dispatch (death detection is bounded below by\n// the 2-minute heartbeat timeout, far above ms resolution), so it is a\n// monotonic generation with zero workflow plumbing. Intra-activity\n// re-attaches (blip/gap heals) reuse it — the runner's equal-generation\n// replay path.\n//\n// * `persistSettled` — the durable-before-wire-ack ordering hook: fold the\n// settled op's frontier into the activity's shared heartbeat details and\n// flush a heartbeat BEFORE the client publishes the final ack. The shared\n// `details` object is the SAME one every other heartbeat site spreads, so a\n// later phase heartbeat re-carries the roster instead of clobbering it.\n\nimport type { Context } from \"@temporalio/activity\";\nimport type { OpStreamJournal } from \"@opengeni/runtime\";\n\n/** The activity's shared heartbeat-details object: every heartbeat call site\n * spreads THIS one object (plus its own phase), so fields like the op-ack\n * roster survive across sites instead of being lost to last-write-wins. */\nexport interface TurnHeartbeatDetails extends Record<string, unknown> {\n /** Settled-op roster: durable op id → its exit seq (the final-ack frontier). */\n opAcks: Record<string, string>;\n}\n\nexport function makeTurnOpJournal(\n context: Context | null,\n details: TurnHeartbeatDetails,\n): OpStreamJournal {\n return {\n attachGeneration: () => String(context?.info.currentAttemptScheduledTimestampMs ?? 1),\n persistSettled: (opId, exitSeq) => {\n details.opAcks[opId] = exitSeq;\n // Flush immediately (heartbeats are also sent on the 10s timer; this one\n // exists so the persist precedes the wire final ack, not just eventually).\n context?.heartbeat({ ...details, phase: \"op_settled\", at: new Date().toISOString() });\n },\n };\n}\n","import type {\n PreferenceRegistrySnapshot,\n ResolvedCompanyProfileSnapshot,\n ResolvedWorkspaceInstructionPolicySnapshot,\n WorkspaceMemoryPromptMode,\n} from \"@opengeni/contracts\";\nimport { composeRuntimeSkills, type RuntimeSkillActivation } from \"@opengeni/runtime\";\n\nexport type CompanyBrainContributionCategory =\n | \"mandatory_rule\"\n | \"skill_guide_descriptor\"\n | \"retrieved_knowledge\"\n | \"task_note\";\n\nexport type CompanyBrainContribution = Readonly<{\n category: CompanyBrainContributionCategory;\n source:\n | \"workspace_instruction_policy\"\n | \"legacy_workspace_instructions\"\n | \"preference_registry_descriptor\"\n | \"company_profile\"\n | \"legacy_memory_v1\"\n | \"runtime_skill_catalog\";\n inclusionReason:\n | \"active_instruction_policy\"\n | \"legacy_instruction_fallback\"\n | \"active_preference_descriptor\"\n | \"active_company_profile_root\"\n | \"legacy_standing_working_set\"\n | \"authorized_skill_descriptor\";\n authorityScope: \"organization\" | \"workspace\" | \"user\" | \"session\";\n utf8Bytes: number;\n estimatedTokens: number;\n}>;\n\nexport type CompanyBrainContributionReceipt = Readonly<{\n attemptId: string;\n turnId: string;\n sessionRole: \"root\" | \"child\";\n memoryPromptMode: WorkspaceMemoryPromptMode;\n instructionPolicySnapshotId: string;\n preferenceSnapshotId: string | null;\n companyProfileSnapshotId: string;\n contributions: readonly CompanyBrainContribution[];\n}>;\n\n/**\n * Build a content-free exact-attempt receipt for the Company Brain material\n * selected before inference. Token counts are deliberately estimates (UTF-8\n * bytes / 4); provider-accounted total input tokens remain the separate source\n * of truth for billing and context pressure.\n */\nexport function buildCompanyBrainContributionReceipt(input: {\n attemptId: string;\n turnId: string;\n nestedAgentDepth: number;\n memoryPromptMode: WorkspaceMemoryPromptMode;\n instructionPolicy: ResolvedWorkspaceInstructionPolicySnapshot;\n workspaceAgentInstructions: string | null;\n preferences: PreferenceRegistrySnapshot | null;\n companyProfile: ResolvedCompanyProfileSnapshot;\n companyProfileIncluded: boolean;\n workspaceMemory: string | null;\n skillActivations: readonly RuntimeSkillActivation[];\n}): CompanyBrainContributionReceipt {\n const contributions: CompanyBrainContribution[] = [];\n for (const entry of input.instructionPolicy.entries) {\n contributions.push(\n contribution({\n category: \"mandatory_rule\",\n source: \"workspace_instruction_policy\",\n inclusionReason: \"active_instruction_policy\",\n authorityScope: \"workspace\",\n text: entry.content,\n }),\n );\n }\n if (input.instructionPolicy.entries.length === 0 && input.workspaceAgentInstructions) {\n contributions.push(\n contribution({\n category: \"mandatory_rule\",\n source: \"legacy_workspace_instructions\",\n inclusionReason: \"legacy_instruction_fallback\",\n authorityScope: \"workspace\",\n text: input.workspaceAgentInstructions,\n }),\n );\n }\n for (const descriptor of input.preferences?.descriptors ?? []) {\n contributions.push(\n contribution({\n category: \"skill_guide_descriptor\",\n source: \"preference_registry_descriptor\",\n inclusionReason: \"active_preference_descriptor\",\n authorityScope: descriptor.scope,\n text: JSON.stringify(descriptor),\n }),\n );\n }\n if (input.companyProfileIncluded && input.companyProfile.profile) {\n contributions.push(\n contribution({\n category: \"retrieved_knowledge\",\n source: \"company_profile\",\n inclusionReason: \"active_company_profile_root\",\n authorityScope: \"organization\",\n text: JSON.stringify(input.companyProfile.profile.profile),\n }),\n );\n }\n if (input.workspaceMemory?.trim()) {\n contributions.push(\n contribution({\n category: \"retrieved_knowledge\",\n source: \"legacy_memory_v1\",\n inclusionReason: \"legacy_standing_working_set\",\n authorityScope: \"workspace\",\n text: input.workspaceMemory,\n }),\n );\n }\n for (const descriptor of composeRuntimeSkills(input.skillActivations).configuredDescriptors) {\n contributions.push(\n contribution({\n category: \"skill_guide_descriptor\",\n source: \"runtime_skill_catalog\",\n inclusionReason: \"authorized_skill_descriptor\",\n authorityScope: descriptor.source === \"session\" ? \"session\" : \"workspace\",\n text: descriptor.description,\n }),\n );\n }\n return Object.freeze({\n attemptId: input.attemptId,\n turnId: input.turnId,\n sessionRole: input.nestedAgentDepth === 0 ? \"root\" : \"child\",\n memoryPromptMode: input.memoryPromptMode,\n instructionPolicySnapshotId: input.instructionPolicy.id,\n preferenceSnapshotId: input.preferences?.id ?? null,\n companyProfileSnapshotId: input.companyProfile.id,\n contributions: Object.freeze(contributions),\n });\n}\n\nfunction contribution(\n input: Omit<CompanyBrainContribution, \"utf8Bytes\" | \"estimatedTokens\"> & {\n text: string;\n },\n): CompanyBrainContribution {\n const utf8Bytes = Buffer.byteLength(input.text, \"utf8\");\n return Object.freeze({\n category: input.category,\n source: input.source,\n inclusionReason: input.inclusionReason,\n authorityScope: input.authorityScope,\n utf8Bytes,\n estimatedTokens: Math.ceil(utf8Bytes / 4),\n });\n}\n","// apps/worker/src/activities/recording.ts — the recording finalize helper (P4.3).\n//\n// The \"agent films itself proving the fix\" finalize loop, run IN the process that\n// already holds the resumed-by-id box (the agent turn's own activity). A scoped\n// upload URL sends bytes box → object storage; the worker never buffers the\n// recording and no bytes enter a Temporal payload.\n//\n// Ordering invariant (F9): the box file is deleted ONLY after the storage PUT\n// confirms and the `available` row commits — so a failed upload leaves the bytes\n// recoverable on the box.\n\nimport type { Settings } from \"@opengeni/config\";\nimport type { Database } from \"@opengeni/db\";\nimport { deleteRecording } from \"@opengeni/db\";\nimport type {\n RecordingCodec,\n RecordingFailedReason,\n RecordingStartedPayload,\n} from \"@opengeni/contracts\";\nimport {\n contentTypeForCodec,\n deleteRecordingArtifacts,\n RecordingError,\n recordingStorageKey,\n startRecording as startRecordingOnBox,\n stopRecording as stopRecordingOnBox,\n uploadRecordingArtifact,\n type RecordingProcess,\n} from \"@opengeni/runtime\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { DOWNLOAD_URL_TTL_SECONDS } from \"@opengeni/storage\";\n\nexport type RecordingMode = \"manual\" | \"on-turn\" | \"on-verify\";\n\nexport type ActiveRecording = {\n recordingId: string;\n turnId: string | null;\n mode: RecordingMode;\n proc: RecordingProcess;\n dimensions: [number, number];\n framerate: number;\n};\n\nexport const RECORDING_SETTLEMENT_PREP_TIMEOUT_MS = 100_000;\nconst RECORDING_SETTLEMENT_UPLOAD_MAX_SECONDS = 45;\n\nexport async function withRecordingPreparationTimeout(\n preparation: Promise<PreparedRecordingSettlement>,\n timeoutResult: PreparedRecordingSettlement,\n timeoutMs = RECORDING_SETTLEMENT_PREP_TIMEOUT_MS,\n): Promise<PreparedRecordingSettlement> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n preparation,\n new Promise<PreparedRecordingSettlement>((resolve) => {\n timer = setTimeout(() => resolve(timeoutResult), timeoutMs);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/**\n * Insert the recording row, launch ffmpeg on the box, and return the live handle.\n * Emits the `recording.started` payload (the caller publishes it on the spine).\n */\nexport async function beginRecording(args: {\n settings: Settings;\n db: Database;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string | null;\n recordingId: string;\n mode: RecordingMode;\n session: unknown;\n runAs?: string | undefined;\n reason?: string | null;\n}): Promise<{ active: ActiveRecording; started: RecordingStartedPayload }> {\n const { settings, db } = args;\n const codec = settings.recordingDefaultCodec as RecordingCodec;\n const dimensions: [number, number] = [\n settings.streamResolutionWidth,\n settings.streamResolutionHeight,\n ];\n const framerate = settings.recordingFramerate;\n await import(\"@opengeni/db\").then(({ insertRecording }) =>\n insertRecording(db, {\n id: args.recordingId,\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n sessionId: args.sessionId,\n turnId: args.turnId,\n mode: args.mode,\n codec,\n width: dimensions[0],\n height: dimensions[1],\n reason: scrubFreeText(args.reason),\n }),\n );\n let proc: RecordingProcess;\n try {\n proc = await startRecordingOnBox(args.session, {\n recordingId: args.recordingId,\n codec,\n framerate,\n maxSeconds: settings.recordingMaxSeconds,\n dimensions,\n ...(args.runAs ? { runAs: args.runAs } : {}),\n });\n } catch (error) {\n await deleteRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: args.recordingId,\n }).catch(() => undefined);\n throw error;\n }\n const active: ActiveRecording = {\n recordingId: args.recordingId,\n turnId: args.turnId,\n mode: args.mode,\n proc,\n dimensions,\n framerate,\n };\n const started: RecordingStartedPayload = {\n recordingId: args.recordingId,\n turnId: args.turnId,\n mode: args.mode,\n codec,\n dimensions,\n framerate,\n startedAt: new Date().toISOString(),\n reason: scrubFreeText(args.reason),\n };\n return { active, started };\n}\n\nexport type PreparedRecordingSettlement =\n | {\n mutation: {\n action: \"available\";\n recordingId: string;\n storageKey: string;\n sizeBytes: number;\n durationSeconds: number;\n };\n deleteArtifactsAfterCommit: true;\n }\n | {\n mutation: {\n action: \"failed\";\n recordingId: string;\n reason: RecordingFailedReason;\n detail: string | null;\n };\n deleteArtifactsAfterCommit: false;\n }\n | {\n mutation: { action: \"discard\"; recordingId: string };\n deleteArtifactsAfterCommit: true;\n };\n\n/**\n * Prepare an on-turn recording for the attempt-closing settlement. This performs\n * only bounded box/storage work; it does not mutate canonical database state and\n * never deletes the box artifact. The caller folds the returned mutation into the\n * exact attempt-fenced turn settlement, then deletes artifacts only after commit.\n * NEVER throws and never prevents turn truth from settling.\n */\nexport async function prepareRecordingForSettlement(args: {\n settings: Settings;\n objectStorage: ObjectStorage | null;\n workspaceId: string;\n sessionId: string;\n active: ActiveRecording;\n session: unknown;\n didComputerUse: boolean;\n}): Promise<PreparedRecordingSettlement> {\n const { settings, objectStorage, active } = args;\n const codec = active.proc.codec;\n const fail = (\n reason: RecordingFailedReason,\n detail: string | null,\n ): PreparedRecordingSettlement => {\n return {\n mutation: {\n action: \"failed\",\n recordingId: active.recordingId,\n reason,\n detail: scrubFreeText(detail),\n },\n deleteArtifactsAfterCommit: false,\n };\n };\n\n const prepare = async (): Promise<PreparedRecordingSettlement> => {\n try {\n await stopRecordingOnBox(args.session, active.proc);\n if (!args.didComputerUse) {\n return {\n mutation: { action: \"discard\", recordingId: active.recordingId },\n deleteArtifactsAfterCommit: true,\n };\n }\n if (!objectStorage) {\n return fail(\"upload-failed\", \"object storage is not configured\");\n }\n const key = recordingStorageKey(args.workspaceId, args.sessionId, active.recordingId, codec);\n const upload = await objectStorage.createPutUrl({\n key,\n contentType: contentTypeForCodec(codec),\n });\n const finalized = await uploadRecordingArtifact(args.session, active.proc, {\n url: upload.url,\n requiredHeaders: upload.requiredHeaders,\n maxBytes: settings.recordingMaxBytes,\n maxSeconds: RECORDING_SETTLEMENT_UPLOAD_MAX_SECONDS,\n });\n return {\n mutation: {\n action: \"available\",\n recordingId: active.recordingId,\n storageKey: key,\n sizeBytes: finalized.sizeBytes,\n durationSeconds: finalized.durationSeconds,\n },\n deleteArtifactsAfterCommit: true,\n };\n } catch (error) {\n const reason: RecordingFailedReason =\n error instanceof RecordingError ? error.reason : \"upload-failed\";\n return fail(reason, error instanceof Error ? error.message : String(error));\n }\n };\n\n return await withRecordingPreparationTimeout(\n prepare(),\n fail(\"upload-failed\", \"recording settlement preparation timed out\"),\n );\n}\n\n/**\n * Compensate a start whose fenced `recording.started` event was rejected. Since\n * no canonical event was admitted, this exact recording id must leave no row,\n * process, or box artifact behind.\n */\nexport async function discardUnpublishedRecording(args: {\n db: Database;\n accountId: string;\n workspaceId: string;\n active: ActiveRecording;\n session: unknown;\n}): Promise<void> {\n const { db, active } = args;\n try {\n await stopRecordingOnBox(args.session, active.proc).catch(() => undefined);\n await deleteRecordingArtifacts(args.session, active.proc).catch(() => undefined);\n } finally {\n await deleteRecording(db, {\n accountId: args.accountId,\n workspaceId: args.workspaceId,\n recordingId: active.recordingId,\n }).catch(() => undefined);\n }\n}\n\nexport { DOWNLOAD_URL_TTL_SECONDS };\n\n// Recording diagnostics are canonical OpenGeni data. Preserve the exact text;\n// transport-specific byte limits must reject or paginate rather than rewrite it.\nfunction scrubFreeText(value: string | null | undefined): string | null {\n if (value === null || value === undefined) return null;\n const exact = String(value);\n return exact.length === 0 ? null : exact;\n}\n","import type { Database } from \"@opengeni/db\";\nimport { readJsonBase64Field, readResponseTextBounded, type FetchLike } from \"@opengeni/network\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { type GeneratedImageOutput, type GeneratedImageReceipt } from \"./generated-images\";\nimport {\n executeImageGenerationOperation,\n imageProviderBindingHash,\n} from \"./image-generation-operation\";\nimport type { ResolvedImageGenerationReference } from \"./image-generation-references\";\n\nconst GATEWAY_IMAGE_PROVIDER_ID = \"vercel-ai-gateway\";\nconst GATEWAY_IMAGE_URL = \"https://ai-gateway.vercel.sh/v3/ai/image-model\";\nconst GATEWAY_PROTOCOL_VERSION = \"0.0.1\";\nconst GATEWAY_IMAGE_SPECIFICATION_VERSION = \"3\";\nconst GATEWAY_IMAGE_RESPONSE_MAX_BYTES = 90 * 1024 * 1024;\nconst GATEWAY_IMAGE_MAX_BYTES = 64 * 1024 * 1024;\nconst GATEWAY_IMAGE_ERROR_MAX_BYTES = 64 * 1024;\n\nexport class GatewayImageApiError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"GatewayImageApiError\";\n }\n}\n\nexport async function executeGatewayImageGeneration(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n apiKey: string;\n modelId: string;\n prompt: string;\n references?: readonly ResolvedImageGenerationReference[];\n toolCallId: string;\n abortSignal?: AbortSignal;\n}): Promise<GeneratedImageReceipt> {\n const providerBindingHash = imageProviderBindingHash(GATEWAY_IMAGE_PROVIDER_ID, input.apiKey);\n return await executeImageGenerationOperation({\n ...input,\n providerId: GATEWAY_IMAGE_PROVIDER_ID,\n providerBindingHash,\n ...(input.references ? { referenceDigests: input.references } : {}),\n generate: async () =>\n await generateGatewayImage({\n apiKey: input.apiKey,\n modelId: input.modelId,\n prompt: input.prompt,\n ...(input.references ? { references: input.references } : {}),\n toolCallId: input.toolCallId,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n }),\n });\n}\n\n/**\n * One explicit Vercel AI Gateway image-protocol adapter. The caller owns durable\n * operation admission; this function never retries an outcome-ambiguous paid\n * request. The response is decoded directly from its JSON stream so neither\n * the complete envelope nor its multi-megabyte base64 string enters memory.\n */\nexport async function generateGatewayImage(input: {\n apiKey: string;\n modelId: string;\n prompt: string;\n references?: readonly ResolvedImageGenerationReference[];\n toolCallId: string;\n abortSignal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<GeneratedImageOutput> {\n if (!input.apiKey.trim()) throw new Error(\"AI Gateway image generation credential is empty\");\n if (!input.modelId.trim()) throw new Error(\"AI Gateway image generation model is empty\");\n const response = await (input.fetch ?? globalThis.fetch)(GATEWAY_IMAGE_URL, {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n Authorization: `Bearer ${input.apiKey}`,\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"ai-gateway-auth-method\": \"api-key\",\n \"ai-gateway-protocol-version\": GATEWAY_PROTOCOL_VERSION,\n \"ai-image-model-specification-version\": GATEWAY_IMAGE_SPECIFICATION_VERSION,\n \"ai-model-id\": input.modelId,\n \"user-agent\": \"opengeni/image-generation\",\n },\n body: JSON.stringify({\n prompt: input.prompt,\n n: 1,\n ...(input.references?.length\n ? {\n files: input.references.map((reference) => ({\n type: \"file\",\n mediaType: reference.mediaType,\n data: Buffer.from(reference.bytes).toString(\"base64\"),\n })),\n }\n : {}),\n }),\n ...(input.abortSignal ? { signal: input.abortSignal } : {}),\n });\n if (!response.ok) {\n const detail = await readResponseTextBounded(\n response,\n GATEWAY_IMAGE_ERROR_MAX_BYTES,\n \"AI Gateway image error\",\n input.abortSignal ? { signal: input.abortSignal } : {},\n ).catch(() => \"\");\n throw new GatewayImageApiError(\n response.status,\n detail\n ? `AI Gateway image generation failed (${response.status}): ${boundedErrorMessage(detail)}`\n : `AI Gateway image generation failed (${response.status})`,\n );\n }\n const bytes = await readJsonBase64Field(response, {\n fieldName: \"images\",\n shape: \"first_array_string\",\n maxResponseBytes: GATEWAY_IMAGE_RESPONSE_MAX_BYTES,\n maxDecodedBytes: GATEWAY_IMAGE_MAX_BYTES,\n label: \"AI Gateway image generation\",\n ...(input.abortSignal ? { signal: input.abortSignal } : {}),\n });\n return {\n toolCallId: input.toolCallId,\n providerItemId: null,\n bytes,\n };\n}\n\nfunction boundedErrorMessage(body: string): string {\n let message = body;\n try {\n const value = JSON.parse(body) as { error?: { message?: unknown }; message?: unknown };\n const candidate = value.error?.message ?? value.message;\n if (typeof candidate === \"string\") message = candidate;\n } catch {\n // Preserve a bounded non-JSON provider diagnostic.\n }\n return message.replace(/\\s+/g, \" \").trim().slice(0, 1_000);\n}\n","import {\n CODEX_PROVIDER_ID,\n generateCodexSubscriptionImage,\n type CodexRequestContext,\n} from \"@opengeni/codex\";\nimport type { Database } from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { GeneratedImageReceipt } from \"./generated-images\";\nimport {\n executeImageGenerationOperation,\n imageProviderBindingHash,\n} from \"./image-generation-operation\";\nimport type { ResolvedImageGenerationReference } from \"./image-generation-references\";\n\nconst CODEX_IMAGE_MODEL = \"gpt-image-2\";\n\n/** Execute the same standalone subscription image path used by Codex clients. */\nexport async function executeCodexImageGeneration(input: {\n db: Database;\n objectStorage: ObjectStorage | null;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n toolCallId: string;\n prompt: string;\n references?: readonly ResolvedImageGenerationReference[];\n credentialId: string;\n codexContext: Pick<CodexRequestContext, \"clientVersion\" | \"getToken\" | \"refresh\">;\n abortSignal?: AbortSignal;\n}): Promise<GeneratedImageReceipt> {\n const providerBindingHash = imageProviderBindingHash(CODEX_PROVIDER_ID, input.credentialId);\n return await executeImageGenerationOperation({\n ...input,\n providerId: CODEX_PROVIDER_ID,\n providerBindingHash,\n modelId: CODEX_IMAGE_MODEL,\n ...(input.references ? { referenceDigests: input.references } : {}),\n generate: async () => {\n const generated = await generateCodexSubscriptionImage({\n prompt: input.prompt,\n ...(input.references ? { references: input.references } : {}),\n turnId: input.turnId,\n context: input.codexContext,\n ...(input.abortSignal ? { abortSignal: input.abortSignal } : {}),\n });\n return {\n toolCallId: input.toolCallId,\n providerItemId: null,\n bytes: generated.bytes,\n declaredMediaType: generated.declaredMediaType,\n };\n },\n });\n}\n","import { type ImageGenerationReference, type FileAsset } from \"@opengeni/contracts\";\nimport { getGeneratedImageArtifact, requireFile, type Database } from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { validateGeneratedImage, type GeneratedImageMediaType } from \"./generated-images\";\n\nexport const IMAGE_GENERATION_REFERENCE_MAX_BYTES = 30 * 1024 * 1024;\nexport const IMAGE_GENERATION_REFERENCES_MAX_TOTAL_BYTES = 64 * 1024 * 1024;\n\nexport type ResolvedImageGenerationReference = Readonly<{\n mediaType: GeneratedImageMediaType;\n bytes: Uint8Array;\n sizeBytes: number;\n sha256: string;\n}>;\n\nexport type SandboxImageReferenceReader = (path: string, maxBytes: number) => Promise<Uint8Array>;\n\n/**\n * Resolve ordered model-facing references without accepting arbitrary URLs.\n * Stored files remain workspace-RLS scoped; sandbox reads stay rooted beneath\n * /workspace. Provider adapters receive only validated immutable bytes.\n */\nexport async function resolveImageGenerationReferences(input: {\n db: Database;\n objectStorage: ObjectStorage;\n workspaceId: string;\n references: readonly ImageGenerationReference[];\n readSandboxFile?: SandboxImageReferenceReader;\n}): Promise<ResolvedImageGenerationReference[]> {\n const resolved: ResolvedImageGenerationReference[] = [];\n let totalBytes = 0;\n\n for (const reference of input.references) {\n const source = await referenceBytes(input, reference);\n if (source.bytes.byteLength > IMAGE_GENERATION_REFERENCE_MAX_BYTES) {\n throw new Error(\"Image reference exceeds the per-image byte limit\");\n }\n totalBytes += source.bytes.byteLength;\n if (totalBytes > IMAGE_GENERATION_REFERENCES_MAX_TOTAL_BYTES) {\n throw new Error(\"Image references exceed the combined byte limit\");\n }\n\n const image = validateGeneratedImage({ bytes: source.bytes });\n if (source.file) assertStoredFileMatches(source.file, image);\n resolved.push({\n mediaType: image.mediaType,\n bytes: source.bytes,\n sizeBytes: image.sizeBytes,\n sha256: image.sha256,\n });\n }\n\n return resolved;\n}\n\nasync function referenceBytes(\n input: {\n db: Database;\n objectStorage: ObjectStorage;\n workspaceId: string;\n readSandboxFile?: SandboxImageReferenceReader;\n },\n reference: ImageGenerationReference,\n): Promise<{ bytes: Uint8Array; file?: FileAsset }> {\n if (reference.kind === \"sandbox_path\") {\n if (!input.readSandboxFile) {\n throw new Error(\"Sandbox image references require an active sandbox\");\n }\n return {\n bytes: await input.readSandboxFile(reference.path, IMAGE_GENERATION_REFERENCE_MAX_BYTES + 1),\n };\n }\n\n const file =\n reference.kind === \"file\"\n ? await requireFile(input.db, input.workspaceId, reference.fileId)\n : await artifactFile(input.db, input.workspaceId, reference.artifactId);\n if (file.status !== \"ready\" || !file.sha256) {\n throw new Error(\"Image reference file is not durably ready\");\n }\n if (file.sizeBytes <= 0 || file.sizeBytes > IMAGE_GENERATION_REFERENCE_MAX_BYTES) {\n throw new Error(\"Image reference file exceeds the supported size\");\n }\n return {\n bytes: await readStoredFile(input.objectStorage, file),\n file,\n };\n}\n\nasync function readStoredFile(objectStorage: ObjectStorage, file: FileAsset): Promise<Uint8Array> {\n const bytes = await objectStorage.getFileRange(file, {\n start: 0,\n end: file.sizeBytes - 1,\n });\n if (!bytes) throw new Error(\"Image reference file bytes are unavailable\");\n return bytes;\n}\n\nasync function artifactFile(\n db: Database,\n workspaceId: string,\n artifactId: string,\n): Promise<FileAsset> {\n const artifact = await getGeneratedImageArtifact(db, workspaceId, artifactId);\n if (!artifact || artifact.status !== \"ready\") {\n throw new Error(`Generated image artifact not found or unavailable: ${artifactId}`);\n }\n return artifact.file;\n}\n\nfunction assertStoredFileMatches(\n file: FileAsset,\n image: Pick<ResolvedImageGenerationReference, \"sizeBytes\" | \"sha256\">,\n): void {\n if (file.sizeBytes !== image.sizeBytes || file.sha256 !== image.sha256) {\n throw new Error(\"Image reference bytes do not match their durable file metadata\");\n }\n}\n","// Workbench v2 — turn-end workspace capture.\n//\n// The universal spine that makes the session workspace paint instantly on cold /\n// offline reads: at TURN END, while the box is still guaranteed live and the\n// turn's lease pins the refcount (the reaper cannot drain), we probe the box's\n// CHANGED files directly off the un-proxied Channel-A session — per-repo git\n// status + diff, after-images of the touched files, and a pruned tree index —\n// serialize a manifest, PUT it + the after-image blobs to object storage, and\n// insert an epoch-fenced `workspace_captures` row. The read path (M2/M3) serves\n// this when the machine is cold/offline; a warm box always wins (capture is a\n// labelled cache, never a replacement).\n//\n// SAFETY INVARIANTS (non-negotiable — see):\n// • This module NEVER calls close()/terminate()/kill() on the session handle.\n// session.close() == terminate() on Modal and would kill the user's box.\n// Only the reaper terminates. We drop references, nothing more.\n// • The whole capture is time-capped (120s) and best-effort: ANY failure logs\n// \"workspace capture failed — turn outcome unaffected\" and returns; nothing\n// throws past captureWorkspaceRevision.\n// • The DB write is fenced on the exact attempt, accepted control requests,\n// and lease epoch — a cancelled attempt or superseded lease writes zero rows\n// (insertWorkspaceCapture).\n// • F9 storage ordering: blobs + manifest are PUT and the row is committed\n// BEFORE any GC delete runs.\n//\n// It is deliberately an EXTERNAL module with a SINGLE call-site line in\n// agent-turn.ts's finally (the accepted design tradeoff — do not grow the turn\n// activity). The emitted `workspace.revision.captured` event is ANNOUNCE-ONLY\n// (metadata, never content) and must never gain a rendered timeline item.\n\nimport { createHash } from \"node:crypto\";\nimport type { Settings } from \"@opengeni/config\";\nimport type { Database } from \"@opengeni/db\";\nimport {\n deleteWorkspaceCaptureRows,\n insertFailedWorkspaceCapture,\n insertWorkspaceCapture,\n latestWorkspaceCapture,\n planWorkspaceCaptureGc,\n} from \"@opengeni/db\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport type { Observability } from \"@opengeni/observability\";\n// The un-agent-loop leaf. Constructing the Channel-A service over the un-proxied\n// setupBoxSession here (NOT the routing veneer) guarantees a mid-turn\n// sandbox_swap can never re-route capture execs onto a user's machine — the same\n// reason the snapshot uses setupBoxSession.\nimport {\n SandboxChannelAService,\n type ChannelASession,\n type RepositoryDiscoveryDegradedReason,\n} from \"@opengeni/runtime/sandbox\";\nimport type {\n FsTreeNode,\n GitFileStatus,\n GitFileStatusCode,\n SessionEvent,\n WorkspaceCaptureFile,\n WorkspaceCaptureDegradedReason,\n WorkspaceCaptureManifest,\n WorkspaceCaptureRepo,\n WorkspaceCaptureStats,\n} from \"@opengeni/contracts\";\n\n// ─── Guards & constants for pathological cases; configurable ─────\n// Production Modal captures of the acceptance workspace normally take ~30s:\n// repository diff framing deliberately trades provider round-trips for bounded\n// output and symlink-safe reads. Sixty seconds gave that healthy path only a 2x\n// margin and repeatedly timed it out under ordinary provider variance. The turn\n// holder keeps the exact lease pinned for this whole window.\nexport const CAPTURE_TIMEOUT_MS = 120_000;\nexport const PER_FILE_CONTENT_GUARD_BYTES = 5 * 1024 * 1024; // after-image; over → tooLarge marker\nexport const PER_FILE_DIFF_GUARD_BYTES = 10 * 1024 * 1024; // per-file diff; over → truncated marker\nexport const WHOLE_CAPTURE_GUARD_BYTES = 200 * 1024 * 1024; // total → skip, fall back to live\nexport const KEEP_LATEST_REVISIONS = 10;\n// Directories listed as collapsed nodes in the tree index but NEVER descended\n// (their contents live on the machine — the Files tab wakes to expand them).\n//\n// Two classes:\n// • BUILD/DEP residue — huge, machine-resident, never review content.\n// • DESKTOP/SYSTEM residue (the Modal desktop-box fix): on a desktop image the\n// workspace root IS $HOME, and XFCE/dbus/etc. CONTINUOUSLY rewrite dotfiles\n// under ~/.config/xfce4, ~/.cache, ~/.dbus, … A tree walk that descends into\n// them (a) wastes the round-trip budget on churn no user is reviewing and\n// (b) races files that VANISH mid-walk. These are never workspace content, so\n// collapse them at the source. Legit hidden entries a user DOES author\n// (.gitignore, .env, .github, .vscode, .devcontainer) are deliberately NOT\n// here — they stay fully visible.\nexport const RESIDUE_DIRS: readonly string[] = [\n // build/dep residue\n \"node_modules\",\n \".git\",\n // Platform credential/helper state. The workspace root can be $HOME, so this\n // directory may sit inside a root repository; it must never enter a revision.\n \".opengeni\",\n \"dist\",\n \"build\",\n \"target\",\n \".venv\",\n \"__pycache__\",\n \".next\",\n // desktop/system residue (never workspace content; churned by the desktop stack)\n \".config\",\n \".cache\",\n \".local\",\n \".dbus\",\n \".gnupg\",\n \".ssh\",\n \".mozilla\",\n \".xfce4\",\n \".pki\",\n \".gvfs\",\n \".dbus-keyrings\",\n \".Xauthority\",\n \".ICEauthority\",\n];\nconst RESIDUE_DIR_SET: ReadonlySet<string> = new Set(RESIDUE_DIRS);\n\n/**\n * True when a workspace-relative FILE path lives INSIDE a residue dir — i.e. a\n * residue dir is one of its ANCESTOR segments (not the leaf), so the file is\n * churn/machine content never worth an after-image. `.config/xfce4/xfconf/…` and\n * `.config/mimeapps.list` → true; a root FILE literally named `.config` (a user\n * config the seed edits) → false (single segment, no residue ancestor); and\n * `.github/x.yml`, `.gitignore` → false (`.github`/`.gitignore` are not residue).\n * Matches the tree-BFS collapse (which collapses residue DIR nodes) so the\n * Changes tab and the tree agree on what is workspace content.\n */\nexport function isUnderResidueDir(wsPath: string): boolean {\n const segments = wsPath.split(\"/\");\n // Check ancestors only (every segment except the leaf): the leaf is the file\n // itself; a residue-named file at the root is still legitimate content.\n for (let i = 0; i < segments.length - 1; i++) {\n const seg = segments[i];\n if (seg && RESIDUE_DIR_SET.has(seg)) return true;\n }\n return false;\n}\n\n/**\n * The box is being torn down under us (Modal reclaim / reaper drain / terminate)\n * — NOT a single file vanishing. Every subsequent op will fail too, so the\n * capture must ABORT (throw) rather than skip-and-continue, so it never commits a\n * bogus empty/partial revision for a dead box. Matched loosely so a provider\n * wording tweak still classifies. (The real fix for this is keeping the box\n * pinned through the capture window — sandbox-resume / agent-turn lease\n * heartbeat; this classifier only guarantees we fail HONESTLY if it still races.)\n */\nexport function isBoxExitingError(error: unknown): boolean {\n const msg = (error instanceof Error ? error.message : String(error ?? \"\")).toLowerCase();\n return (\n msg.includes(\"container exiting\") ||\n msg.includes(\"container is exiting\") ||\n msg.includes(\"container exited\") ||\n msg.includes(\"sandbox has been terminated\") ||\n msg.includes(\"sandbox is not running\") ||\n msg.includes(\"sandbox has terminated\") ||\n msg.includes(\"task has exited\")\n );\n}\n\n/** Marker thrown when the box died mid-capture — aborts cleanly (no partial row). */\nexport class BoxExitingError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BoxExitingError\";\n }\n}\n\n/** Re-throw as a BoxExitingError when the box is gone; otherwise return null so\n * the caller SKIPS this single entry (a vanished/unreadable file) and continues.\n * One churning file must never kill the capture; a dead box must never yield a\n * bogus revision. */\nfunction classifyCaptureEntryError(error: unknown): BoxExitingError | null {\n if (isBoxExitingError(error)) {\n return new BoxExitingError(error instanceof Error ? error.message : String(error));\n }\n return null;\n}\nconst TREE_MAX_ENTRIES = 20_000; // whole-tree node cap (truncate beyond)\nconst TREE_MAX_DEPTH = 600; // pathological nesting cap; still one remote round-trip\n\n// The capture row and announcement are committed together by @opengeni/db. This\n// callback performs only best-effort live fanout of those already-durable events.\nexport type CaptureEventPublisher = (events: SessionEvent[]) => Promise<void>;\n\nexport type CaptureWorkspaceRevisionInput = {\n db: Database;\n objectStorage: ObjectStorage | null;\n settings: Settings;\n publish: CaptureEventPublisher | null;\n /** The un-proxied setupBoxSession (NOT the routing veneer). */\n session: ChannelASession;\n /**\n * Reopen the exact live provider instance as a fresh, non-owning read handle.\n * Modal sessions keep mutable exec-process bookkeeping; reusing the handle\n * that just drove model tools can strand a later capture command behind stale\n * provider state. The lease still owns the box. Capture drops this handle\n * without calling close(), which would terminate Modal's sandbox.\n */\n openReadSession?: () => Promise<ChannelASession>;\n leaseEpoch: number;\n sandboxGroupId: string;\n accountId: string;\n workspaceId: string;\n sessionId: string;\n turnId: string;\n attemptId: string;\n observability: Observability;\n /**\n * The owning turn activity's cancellation signal. Pause/Steer must preempt\n * review-cache housekeeping immediately; correctness still comes from the\n * activity plus the capture's transaction-level attempt/control/lease fences.\n */\n signal?: AbortSignal;\n /** Test-only: override keep-latest-N GC threshold (default 10). */\n keepLatest?: number;\n};\n\ntype CaptureRepositoryReadResult =\n | {\n complete: true;\n status: Awaited<ReturnType<SandboxChannelAService[\"gitStatus\"]>>;\n diff: Awaited<ReturnType<SandboxChannelAService[\"gitDiff\"]>>;\n branchDiff?: Awaited<ReturnType<SandboxChannelAService[\"gitDiff\"]>> | undefined;\n }\n | { complete: false; degradedReason: \"repository_read_unavailable\" };\n\ntype ResumableCaptureClient = {\n resume?: (state: unknown) => Promise<unknown>;\n};\n\ntype StatefulCaptureSession = ChannelASession & {\n state?: unknown;\n};\n\nfunction captureSessionInstanceId(session: unknown): string | null {\n const state =\n session && typeof session === \"object\"\n ? (session as { state?: Record<string, unknown> }).state\n : undefined;\n if (!state || typeof state !== \"object\") return null;\n for (const value of [\n state.sandboxId,\n state.instanceId,\n state.id,\n state.hostId,\n state.containerId,\n state.workspaceRootPath,\n ]) {\n if (typeof value === \"string\" && value.length > 0) return value;\n }\n return null;\n}\n\n/**\n * Reattach a clean SDK handle to the exact already-live Modal sandbox. Modal's\n * resume contract is a pure from-id reattach. Other providers keep the original\n * session because their generic resume contract may restore or replace a dead\n * instance, which capture does not own.\n */\nexport async function openFreshWorkspaceCaptureSession(input: {\n backendId: string;\n client: unknown;\n session: ChannelASession;\n expectedInstanceId: string;\n}): Promise<ChannelASession> {\n if (input.backendId !== \"modal\") {\n return input.session;\n }\n const client = input.client as ResumableCaptureClient;\n const state = (input.session as StatefulCaptureSession).state;\n if (typeof client.resume !== \"function\" || state === undefined) {\n return input.session;\n }\n // The lease—not this temporary reader—owns provider teardown. Preserve the\n // exact state while explicitly removing close/terminate authority from\n // providers (Modal) that encode it in the resumed state.\n const readState =\n state !== null && typeof state === \"object\" ? { ...state, ownsSandbox: false } : state;\n const reopened = await client.resume(readState);\n const actualInstanceId = captureSessionInstanceId(reopened);\n if (input.expectedInstanceId.length > 0 && actualInstanceId !== input.expectedInstanceId) {\n throw new Error(\n `workspace capture reopened provider instance ${actualInstanceId ?? \"unknown\"}, expected ${input.expectedInstanceId}`,\n );\n }\n return reopened as ChannelASession;\n}\n\n/** One discovered repository is all-or-nothing capture authority. A provider\n * transport failure must never be represented as an authoritative empty diff. */\nexport async function readCaptureRepository(\n svc: Pick<SandboxChannelAService, \"gitStatus\" | \"gitDiff\">,\n root: string,\n): Promise<CaptureRepositoryReadResult> {\n let status: Awaited<ReturnType<SandboxChannelAService[\"gitStatus\"]>>;\n try {\n status = await svc.gitStatus({ path: root });\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n if (!status.isRepo) {\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n try {\n const workingRequest = svc.gitDiff({\n path: root,\n staged: false,\n includeUntracked: true,\n fromRef: \"HEAD\",\n pathspec: [],\n contextLines: 3,\n maxBytesPerFile: PER_FILE_DIFF_GUARD_BYTES,\n });\n // Branch capture is additive. A repository without origin/HEAD must not\n // degrade the authoritative working-tree capture.\n const branchRequest = Promise.resolve()\n .then(() =>\n svc.gitDiff({\n path: root,\n staged: false,\n includeUntracked: true,\n fromRef: \"origin/HEAD\",\n pathspec: [],\n contextLines: 3,\n maxBytesPerFile: PER_FILE_DIFF_GUARD_BYTES,\n }),\n )\n .then((value) => value)\n .catch(() => null);\n const [diff, branchDiff] = await Promise.all([workingRequest, branchRequest]);\n return {\n complete: true,\n status,\n diff,\n ...(branchDiff ? { branchDiff } : {}),\n };\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n return { complete: false, degradedReason: \"repository_read_unavailable\" };\n }\n}\n\nlet loggedStorageNullOnce = false;\n\n/**\n * Turn-end entrypoint. Gates on the flag + configured object storage, races the\n * whole capture against a 120s cap, and swallows every failure (\"turn outcome\n * unaffected\"). Returns void — the caller awaits it (it self-caps) and moves on\n * to release() regardless.\n */\nexport async function captureWorkspaceRevision(\n input: CaptureWorkspaceRevisionInput,\n): Promise<void> {\n const { observability } = input;\n const stage = { value: \"preflight\" };\n if (input.signal?.aborted) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"cancelled\" },\n });\n return;\n }\n if (!input.settings.workspaceCaptureEnabled) {\n return; // flag off → capture skipped; reads fall back to live/wake (status quo)\n }\n if (!input.objectStorage) {\n if (!loggedStorageNullOnce) {\n loggedStorageNullOnce = true;\n observability.info(\"workspace capture skipped — object storage not configured\");\n }\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"skipped_no_storage\" },\n });\n return;\n }\n\n const startedAt = Date.now();\n const controller = new AbortController();\n let rejectOwnerCancellation: ((reason?: unknown) => void) | undefined;\n const ownerCancelled = input.signal\n ? new Promise<never>((_resolve, reject) => {\n rejectOwnerCancellation = reject;\n })\n : new Promise<never>(() => undefined);\n const cancelFromOwner = (): void => {\n controller.abort(input.signal?.reason);\n rejectOwnerCancellation?.(\n input.signal?.reason ?? new Error(\"workspace capture cancelled by its owning activity\"),\n );\n };\n input.signal?.addEventListener(\"abort\", cancelFromOwner, { once: true });\n if (input.signal?.aborted) cancelFromOwner();\n observability.incrementGauge({\n name: \"opengeni_workspace_captures_inflight\",\n help: \"Current workspace-capture operations still resident in this worker process.\",\n });\n const capture = runCapture(\n input,\n { ...input, objectStorage: input.objectStorage },\n startedAt,\n controller.signal,\n stage,\n ).finally(() => {\n observability.incrementGauge({\n name: \"opengeni_workspace_captures_inflight\",\n help: \"Current workspace-capture operations still resident in this worker process.\",\n amount: -1,\n });\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n await Promise.race([\n capture,\n ownerCancelled,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new Error(`workspace capture exceeded ${CAPTURE_TIMEOUT_MS}ms`));\n }, CAPTURE_TIMEOUT_MS);\n }),\n ]);\n } catch (error) {\n if (input.signal?.aborted) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"cancelled\" },\n });\n return;\n }\n // The one and only place a capture failure surfaces — as a log line, never\n // an exception past this boundary (the turn already completed).\n observability.warn(\"workspace capture failed — turn outcome unaffected\", {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": input.turnId ?? \"\",\n \"error.message\": error instanceof Error ? error.message : String(error),\n \"workspace_capture.duration_ms\": Date.now() - startedAt,\n \"workspace_capture.stage\": stage.value,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"failed\" },\n });\n } finally {\n if (timer) clearTimeout(timer);\n input.signal?.removeEventListener(\"abort\", cancelFromOwner);\n controller.abort();\n }\n}\n\n// The strongly-typed inner run (objectStorage proven non-null by the caller).\nasync function runCapture(\n input: CaptureWorkspaceRevisionInput,\n ctx: CaptureWorkspaceRevisionInput & { objectStorage: ObjectStorage },\n startedAt: number,\n signal: AbortSignal,\n stage: { value: string },\n): Promise<void> {\n const { observability } = input;\n const storage = ctx.objectStorage;\n const keepN = input.keepLatest ?? KEEP_LATEST_REVISIONS;\n stage.value = \"open_read_session\";\n const readSession = input.openReadSession ? await input.openReadSession() : input.session;\n throwIfCaptureAborted(signal);\n // Reads only — no emitter (we publish the announce ourselves after commit).\n const svc = new SandboxChannelAService({ session: readSession, leaseEpoch: input.leaseEpoch });\n\n // Resolve the previous revision before discovery so even a failed discovery\n // can commit a monotonic, explicit degraded marker. That marker becomes the\n // newest read result and prevents an older successful capture from being\n // mistaken for the current turn's authoritative workspace state.\n stage.value = \"load_previous_capture\";\n const prev = await latestWorkspaceCapture(input.db, input.workspaceId, input.sessionId);\n throwIfCaptureAborted(signal);\n const revision = (prev?.revision ?? -1) + 1;\n\n // ── 1. per-repo status + diff, union the touched set ──────────────────────\n stage.value = \"repository_discovery\";\n const discovery = await svc.detectReposDetailed();\n throwIfCaptureAborted(signal);\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture discovery complete=${discovery.complete} repos=${JSON.stringify(discovery.repos)} degraded=${discovery.degradedReason ?? \"none\"}`,\n );\n }\n if (!discovery.complete) {\n const reason = captureDegradedReason(discovery.degradedReason);\n await persistDegradedCapture(\n input,\n startedAt,\n signal,\n revision,\n reason,\n discovery.repos.length,\n );\n return;\n }\n const repoRoots = discovery.repos;\n const repos: WorkspaceCaptureRepo[] = [];\n // workspace-relative path → touched-file descriptor\n const touched = new Map<string, { status: GitFileStatusCode; deleted: boolean }>();\n let additions = 0;\n let deletions = 0;\n\n for (const root of repoRoots) {\n stage.value = \"repository_read\";\n throwIfCaptureAborted(signal);\n // Repository discovery defines the authoritative set. Once a root is in\n // that set, status/diff failure must degrade the entire revision rather than\n // publish a partial or false-empty change surface. Box death still aborts\n // through the outer best-effort boundary.\n const repository = await readCaptureRepository(svc, root);\n throwIfCaptureAborted(signal);\n if (!repository.complete) {\n await persistDegradedCapture(\n input,\n startedAt,\n signal,\n revision,\n repository.degradedReason,\n repoRoots.length,\n );\n return;\n }\n const { status, diff, branchDiff } = repository;\n // Drop residue churn from the review diff too. On a desktop box the seed's\n // `git add -A` in $HOME commits ~/.config/xfce4/* into HEAD, so `git diff HEAD`\n // lists the continuously-rewritten desktop dotfiles as changed — noise the\n // Changes tab must not show. The status/after-image loop already excludes them\n // (isUnderResidueDir); exclude them here so the diff surface agrees.\n const diffFiles = diff.files.filter((f) => !isUnderResidueDir(joinRepoPath(root, f.path)));\n // Also drop residue-only status entries below; status.files is filtered in the\n // touched loop (isUnderResidueDir), so `status: status.files` would still carry\n // residue rows — filter for a consistent captured status surface.\n const statusFiles = status.files.filter((f) => !isUnderResidueDir(joinRepoPath(root, f.path)));\n repos.push({\n root,\n head: status.head,\n headOid: status.headOid ?? null,\n detached: status.detached,\n upstream: status.upstream,\n ahead: status.ahead,\n behind: status.behind,\n status: statusFiles,\n diff: diffFiles,\n ...(branchDiff\n ? {\n branchDiff: branchDiff.files.filter(\n (f) => !isUnderResidueDir(joinRepoPath(root, f.path)),\n ),\n }\n : {}),\n });\n for (const f of diffFiles) {\n additions += f.additions;\n deletions += f.deletions;\n }\n for (const f of status.files) {\n const wsPath = joinRepoPath(root, f.path);\n // Skip desktop/system residue churn (~/.config/xfce4/…): on a desktop box\n // the workspace root is $HOME, so git reports the continuously-rewritten\n // XFCE/cache dotfiles as untracked. They are never review content — dropping\n // them here keeps the after-image loop off churn AND matches the tree BFS's\n // residue collapse (Changes tab and tree agree on what is workspace content).\n if (isUnderResidueDir(wsPath)) continue;\n touched.set(wsPath, {\n status: statusCodeOf(f),\n deleted: f.worktree === \"deleted\" || f.index === \"deleted\",\n });\n }\n }\n\n // Previous revision (for the empty-turn gate + revision assignment). The gate\n // itself fires AFTER the after-image loop, once the change fingerprint is known\n // (§10.1 / B3): uncommitted changes persist in the box across turns, so a\n // literal \"skip when git status is clean\" gate would re-capture an identical\n // dirty tree on every read-only turn. Instead we skip when the change surface\n // is byte-identical to the previous revision — \"no new revision when nothing\n // changed\" holds even with a persistently dirty tree, and content-addressed\n // blobs already dedupe storage. This preserves the intended empty-turn behavior\n // while correctly handling a persistently dirty tree.\n // ── 3. after-images of touched files (size-gated), content-addressed ───────\n const files: WorkspaceCaptureFile[] = [];\n const blobKeys = new Set<string>();\n let totalBytes = 0;\n let tooLargeCount = 0;\n let binaryCount = 0;\n\n for (const [wsPath, info] of touched) {\n stage.value = \"file_read\";\n throwIfCaptureAborted(signal);\n if (info.deleted) {\n files.push({\n path: wsPath,\n status: \"deleted\",\n hash: null,\n baseHash: null,\n contentRef: null,\n sizeBytes: 0,\n isBinary: false,\n tooLarge: false,\n deleted: true,\n });\n continue;\n }\n // Always request base64 so we get raw bytes uniformly (text or binary) for\n // content-addressing. maxBytes caps the read at the 5MB guard; `truncated`\n // means the file is ≥5MB → we record a tooLarge marker (no content blob).\n //\n // Per-file resilience: a file the box reported as changed can VANISH or turn\n // unreadable between git-status and this read (fs churn, a follow-up mutation,\n // a race). That must NEVER abort the whole capture — skip the one entry and\n // keep the rest. A box-death error is different: it aborts (BoxExitingError),\n // because every remaining read would fail too and we must not commit a partial\n // revision for a dead box.\n let read: Awaited<ReturnType<typeof svc.fsRead>>;\n try {\n read = await svc.fsRead({\n path: wsPath,\n encoding: \"base64\",\n maxBytes: PER_FILE_CONTENT_GUARD_BYTES,\n });\n throwIfCaptureAborted(signal);\n } catch (error) {\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n continue; // vanished/unreadable single file — omit it, capture continues\n }\n if (read.truncated) {\n tooLargeCount += 1;\n files.push({\n path: wsPath,\n status: info.status,\n hash: null,\n baseHash: null,\n contentRef: null,\n sizeBytes: read.sizeBytes,\n isBinary: read.isBinary,\n tooLarge: true,\n deleted: false,\n });\n continue;\n }\n const bytes = Buffer.from(read.content, \"base64\");\n const hash = sha256(bytes);\n const contentRef = blobKey(input.workspaceId, input.sessionId, hash);\n if (read.isBinary) binaryCount += 1;\n if (!blobKeys.has(contentRef)) {\n totalBytes += bytes.byteLength;\n // Whole-capture guard: bail before writing anything (fall back to live).\n if (totalBytes > WHOLE_CAPTURE_GUARD_BYTES) {\n observability.warn(\"workspace capture skipped — whole-capture guard tripped\", {\n \"opengeni.session_id\": input.sessionId,\n \"workspace_capture.total_bytes\": totalBytes,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"guard_tripped\" },\n });\n return;\n }\n }\n blobKeys.add(contentRef);\n files.push({\n // baseHash (git HEAD blob sha) is intentionally null in M1: the wake-on-edit\n // flush guard (M3/C2) compares live content against the after-image `hash`,\n // not the HEAD blob, so baseHash is not load-bearing yet. Populating it would\n // cost an extra per-file round-trip at turn end (latency risk #1). Deferred.\n path: wsPath,\n status: info.status,\n hash,\n baseHash: null,\n contentRef,\n sizeBytes: bytes.byteLength,\n isBinary: read.isBinary,\n tooLarge: false,\n deleted: false,\n });\n }\n\n // ── 4. empty-turn gate (B3) ───────────────────────────────\n // Skip when the change surface is byte-identical to the previous revision.\n // Fires BEFORE the tree BFS + storage PUTs (the expensive parts) so a no-op\n // read-only turn on a persistently dirty tree costs only the (small) status/\n // diff/after-image probes.\n let fingerprint = changeFingerprint(repos, files);\n if (prev && prev.stats.fingerprint === fingerprint) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"skipped_empty\" },\n });\n return;\n }\n\n // ── 5. tree index (one bounded listing; residue dirs pruned at source) ─────\n stage.value = \"tree_index\";\n const tree = await buildTreeIndex(svc, startedAt, signal);\n throwIfCaptureAborted(signal);\n\n // ── 6. PUT blobs + tree + manifest (F9: all writes BEFORE any delete) ──────\n // Key manifest/tree by the turn (one capture per turn) so the key is known\n // before the revision is committed; content blobs are content-addressed.\n const turnKey = input.turnId;\n const treeKey = `workspace-captures/${input.workspaceId}/${input.sessionId}/trees/${turnKey}.json`;\n const manifestKey = `workspace-captures/${input.workspaceId}/${input.sessionId}/manifests/${turnKey}.json`;\n\n // Re-read and upload ONE after-image at a time. The first pass above computes\n // the stable capture fingerprint without retaining every changed file. This\n // second pass takes the actual after-image that will be uploaded, refreshing\n // metadata when a live process changed a file between passes. Peak worker\n // memory is bounded by PER_FILE_CONTENT_GUARD_BYTES instead of\n // WHOLE_CAPTURE_GUARD_BYTES per concurrent turn.\n const uploadedKeys = new Set<string>();\n blobKeys.clear();\n totalBytes = 0;\n let refreshedFiles = 0;\n const omittedFiles = new Set<string>();\n for (const file of files) {\n stage.value = \"content_upload\";\n throwIfCaptureAborted(signal);\n if (file.deleted || file.tooLarge || !file.contentRef || !file.hash) {\n continue;\n }\n let reread: Awaited<ReturnType<typeof svc.fsRead>>;\n try {\n reread = await svc.fsRead({\n path: file.path,\n encoding: \"base64\",\n maxBytes: PER_FILE_CONTENT_GUARD_BYTES,\n });\n throwIfCaptureAborted(signal);\n } catch (error) {\n if (signal.aborted) throw error;\n const boxExiting = classifyCaptureEntryError(error);\n if (boxExiting) throw boxExiting;\n // Match the first pass: a single vanished or unreadable file is omitted,\n // never misreported as deleted and never allowed to fail the full capture.\n omittedFiles.add(file.path);\n refreshedFiles += 1;\n continue;\n }\n if (reread.truncated) {\n file.hash = null;\n file.contentRef = null;\n file.sizeBytes = reread.sizeBytes;\n file.isBinary = reread.isBinary;\n file.tooLarge = true;\n refreshedFiles += 1;\n continue;\n }\n const bytes = Buffer.from(reread.content, \"base64\");\n const hash = sha256(bytes);\n const contentRef = blobKey(input.workspaceId, input.sessionId, hash);\n if (\n hash !== file.hash ||\n bytes.byteLength !== file.sizeBytes ||\n reread.isBinary !== file.isBinary\n ) {\n file.hash = hash;\n file.contentRef = contentRef;\n file.sizeBytes = bytes.byteLength;\n file.isBinary = reread.isBinary;\n refreshedFiles += 1;\n }\n if (!blobKeys.has(contentRef)) {\n totalBytes += bytes.byteLength;\n if (totalBytes > WHOLE_CAPTURE_GUARD_BYTES) {\n observability.warn(\"workspace capture skipped — whole-capture guard tripped\", {\n \"opengeni.session_id\": input.sessionId,\n \"workspace_capture.total_bytes\": totalBytes,\n });\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"guard_tripped\" },\n });\n return;\n }\n }\n blobKeys.add(contentRef);\n if (!uploadedKeys.has(contentRef)) {\n await storage.putObject({\n key: contentRef,\n contentType: \"application/octet-stream\",\n body: bytes,\n });\n throwIfCaptureAborted(signal);\n uploadedKeys.add(contentRef);\n }\n }\n if (omittedFiles.size > 0) {\n for (let index = files.length - 1; index >= 0; index -= 1) {\n const file = files[index];\n if (file && omittedFiles.has(file.path)) files.splice(index, 1);\n }\n }\n if (refreshedFiles > 0) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_files_refreshed_total\",\n amount: refreshedFiles,\n });\n }\n tooLargeCount = files.filter((file) => file.tooLarge).length;\n binaryCount = files.filter((file) => !file.deleted && file.isBinary).length;\n fingerprint = changeFingerprint(repos, files);\n if (prev && prev.stats.fingerprint === fingerprint) {\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"skipped_empty\" },\n });\n return;\n }\n\n // ── 7. serialize the exact uploaded after-images ──────────────────────────\n const capturedAt = new Date();\n const stats: WorkspaceCaptureStats = {\n repoCount: repos.length,\n fileCount: files.length,\n additions,\n deletions,\n totalBytes,\n tooLargeCount,\n binaryCount,\n treeEntryCount: tree.entryCount,\n treeTruncated: tree.truncated,\n durationMs: 0, // filled after tree/content writes, before manifest serialization\n fingerprint,\n };\n const manifest: WorkspaceCaptureManifest = {\n version: 1,\n revision,\n capturedAt: capturedAt.toISOString(),\n turnId: input.turnId,\n leaseEpoch: input.leaseEpoch,\n treeIndex: tree.root,\n treeTruncated: tree.truncated,\n repos,\n files,\n stats,\n };\n const treeBytes = utf8(\n JSON.stringify({\n version: 1,\n root: tree.root,\n truncated: tree.truncated,\n entryCount: tree.entryCount,\n }),\n );\n stage.value = \"tree_upload\";\n await storage.putObject({ key: treeKey, contentType: \"application/json\", body: treeBytes });\n throwIfCaptureAborted(signal);\n stats.durationMs = Date.now() - startedAt;\n const manifestBytes = utf8(JSON.stringify(manifest));\n stage.value = \"manifest_upload\";\n await storage.putObject({\n key: manifestKey,\n contentType: \"application/json\",\n body: manifestBytes,\n });\n throwIfCaptureAborted(signal);\n const sizeBytes = totalBytes + treeBytes.byteLength + manifestBytes.byteLength;\n\n // ── 8. epoch-fenced insert (superseded lease → zero rows) ─────────────────\n stage.value = \"database_commit\";\n const inserted = await insertWorkspaceCapture(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: input.leaseEpoch,\n revision,\n manifestKey,\n treeIndexKey: treeKey,\n blobKeys: [...blobKeys],\n sizeBytes,\n stats,\n capturedAt,\n });\n if (process.env.OPENGENI_TEST_SCENARIO === \"sandbox\") {\n console.log(\n `[sandbox-e2e] capture commit inserted=${Boolean(inserted)} revision=${revision} epoch=${input.leaseEpoch} group=${input.sandboxGroupId}`,\n );\n }\n throwIfCaptureAborted(signal);\n if (!inserted) {\n // Lease superseded/released between capture and commit. Best-effort clean up\n // the turn-keyed blobs we just PUT (content blobs may be shared with a\n // surviving revision — leave them for the next GC); never throw.\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"superseded\" },\n });\n await safeDelete(storage, [manifestKey, treeKey], observability, signal);\n return;\n }\n\n if (input.publish) {\n await input.publish(inserted.events).catch(() => undefined);\n }\n\n // ── 9. inline keep-latest-N GC (best-effort; F9 — after the commit) ────────\n let gcDeleted = 0;\n try {\n throwIfCaptureAborted(signal);\n const plan = await planWorkspaceCaptureGc(input.db, {\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n keepN,\n });\n throwIfCaptureAborted(signal);\n if (plan.evictedRowIds.length > 0) {\n await safeDelete(\n storage,\n [...plan.deleteBlobKeys, ...plan.deletePerRevisionKeys],\n observability,\n signal,\n );\n throwIfCaptureAborted(signal);\n gcDeleted = await deleteWorkspaceCaptureRows(input.db, {\n workspaceId: input.workspaceId,\n rowIds: plan.evictedRowIds,\n });\n throwIfCaptureAborted(signal);\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_gc_deletions_total\",\n amount: gcDeleted,\n });\n }\n } catch (gcError) {\n if (signal.aborted) throw gcError;\n // GC is storage hygiene — a failure never affects the just-committed capture.\n observability.warn(\"workspace capture GC failed — capture unaffected\", {\n \"opengeni.session_id\": input.sessionId,\n \"error.message\": gcError instanceof Error ? gcError.message : String(gcError),\n });\n }\n\n // ── 10. observe completion ────────────────────────────────────────────────\n const durationMs = Date.now() - startedAt;\n observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"ok\" },\n });\n observability.observeHistogram({\n name: \"opengeni_workspace_capture_duration_seconds\",\n value: durationMs / 1000,\n });\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────────\n\nfunction captureDegradedReason(\n reason: RepositoryDiscoveryDegradedReason | null,\n): WorkspaceCaptureDegradedReason {\n switch (reason) {\n case \"command_timed_out\":\n return \"repository_discovery_timed_out\";\n case \"result_limit_exceeded\":\n return \"repository_discovery_result_limit_exceeded\";\n case \"command_failed\":\n default:\n return \"repository_discovery_command_failed\";\n }\n}\n\nasync function persistDegradedCapture(\n input: CaptureWorkspaceRevisionInput,\n startedAt: number,\n signal: AbortSignal,\n revision: number,\n reason: WorkspaceCaptureDegradedReason,\n discoveredRepoCount: number,\n): Promise<void> {\n const capturedAt = new Date();\n const stats = {\n degradedReason: reason,\n discoveredRepoCount,\n durationMs: Date.now() - startedAt,\n };\n const inserted = await insertFailedWorkspaceCapture(input.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n sessionId: input.sessionId,\n turnId: input.turnId,\n attemptId: input.attemptId,\n sandboxGroupId: input.sandboxGroupId,\n expectedEpoch: input.leaseEpoch,\n revision,\n stats,\n capturedAt,\n });\n throwIfCaptureAborted(signal);\n if (!inserted) {\n input.observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: { result: \"superseded\" },\n });\n return;\n }\n const discoveryFailure = reason.startsWith(\"repository_discovery_\");\n input.observability.warn(\n discoveryFailure\n ? \"workspace capture degraded — repository discovery incomplete\"\n : \"workspace capture degraded — repository read incomplete\",\n {\n \"opengeni.session_id\": input.sessionId,\n \"opengeni.turn_id\": input.turnId ?? \"\",\n \"workspace_capture.degraded_reason\": reason,\n \"workspace_capture.discovered_repo_count\": discoveredRepoCount,\n },\n );\n input.observability.incrementCounter({\n name: \"opengeni_workspace_capture_total\",\n labels: {\n result: discoveryFailure ? \"degraded_repository_discovery\" : \"degraded_repository_read\",\n },\n });\n if (input.publish) {\n await input.publish(inserted.events).catch(() => undefined);\n }\n}\n\nfunction throwIfCaptureAborted(signal: AbortSignal): void {\n if (signal.aborted) {\n throw new Error(\"workspace capture cancelled after its deadline\");\n }\n}\n\nfunction statusCodeOf(f: GitFileStatus): GitFileStatusCode {\n return f.worktree ?? f.index ?? \"modified\";\n}\n\n/**\n * sha256 over the CHANGE SURFACE only — per-file (path, status, hash, deleted,\n * tooLarge), exact HEAD identity, the working diff summary, and exact committed\n * branch changes.\n * Deliberately excludes the tree index and file mtimes (which drift without a\n * real change) so two turns that leave the workspace in the same state produce\n * the same fingerprint (the empty-turn gate). Order-independent (sorted).\n */\nexport function changeFingerprint(\n repos: WorkspaceCaptureRepo[],\n files: WorkspaceCaptureFile[],\n): string {\n const fileParts = files\n .map((f) => `${f.path}|${f.status}|${f.hash ?? \"\"}|${f.deleted ? 1 : 0}|${f.tooLarge ? 1 : 0}`)\n .sort();\n const branchDiffPart = (diff: WorkspaceCaptureRepo[\"diff\"][number]): string =>\n JSON.stringify([\n diff.path,\n diff.oldPath,\n diff.status,\n diff.isBinary,\n diff.isImage,\n diff.additions,\n diff.deletions,\n diff.truncated,\n diff.hunks.map((hunk) => [\n hunk.oldStart,\n hunk.oldLines,\n hunk.newStart,\n hunk.newLines,\n hunk.header,\n hunk.lines.map((line) => [line.type, line.oldNo, line.newNo, line.text]),\n ]),\n ]);\n const repoParts = repos\n .map((repo) => {\n const workingDiff = repo.diff\n .map(\n (diff) =>\n `${diff.path}:${diff.status}:${diff.additions}:${diff.deletions}:${diff.truncated ? 1 : 0}`,\n )\n .sort();\n const branchDiff =\n repo.branchDiff === undefined ? null : repo.branchDiff.map(branchDiffPart).sort();\n return JSON.stringify([\n repo.root,\n repo.head,\n repo.headOid ?? null,\n repo.ahead,\n workingDiff,\n branchDiff,\n ]);\n })\n .sort();\n return sha256(utf8(JSON.stringify({ files: fileParts, repos: repoParts })));\n}\n\n/** Join a repo-root-relative path onto its workspace-relative repo root. */\nexport function joinRepoPath(repoRoot: string, repoRelPath: string): string {\n if (!repoRoot || repoRoot === \"\" || repoRoot === \".\") return repoRelPath;\n return `${repoRoot.replace(/\\/+$/, \"\")}/${repoRelPath}`;\n}\n\nfunction sha256(bytes: Uint8Array): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\nfunction utf8(s: string): Uint8Array {\n return new TextEncoder().encode(s);\n}\n\n/** Content-addressed after-image blob key (shared across revisions → GC input). */\nexport function blobKey(workspaceId: string, sessionId: string, sha256Hex: string): string {\n return `workspace-captures/${workspaceId}/${sessionId}/blobs/${sha256Hex}`;\n}\n\nasync function safeDelete(\n storage: ObjectStorage,\n keys: string[],\n observability: Observability,\n signal: AbortSignal,\n): Promise<void> {\n for (const key of keys) {\n throwIfCaptureAborted(signal);\n await storage.deleteObject(key).catch((error) => {\n observability.warn(\"workspace capture blob delete failed (orphan left; capture unaffected)\", {\n \"storage.key\": key,\n \"error.message\": error instanceof Error ? error.message : String(error),\n });\n });\n }\n}\n\n/**\n * Build the workspace tree index in ONE remote filesystem round-trip. Channel-A\n * prunes residue directories inside `find` while still emitting their collapsed\n * node, so node_modules cannot consume the authored-file budget. The former\n * serial per-directory BFS took 55.8 seconds for a 4,522-entry production tree\n * and blocked Steer cancellation. This path is bounded by entry count, nesting\n * depth, the outer capture deadline, and the owning activity's cancellation.\n */\nasync function buildTreeIndex(\n svc: SandboxChannelAService,\n startedAt: number,\n signal: AbortSignal,\n): Promise<{ root: FsTreeNode; entryCount: number; truncated: boolean }> {\n throwIfCaptureAborted(signal);\n if (Date.now() - startedAt > CAPTURE_TIMEOUT_MS - 5_000) {\n throw new Error(\"workspace capture tree index reached its deadline before listing\");\n }\n let listing: Awaited<ReturnType<typeof svc.fsListPruned>>;\n try {\n listing = await svc.fsListPruned(\n {\n path: \"\",\n depth: TREE_MAX_DEPTH,\n maxEntries: TREE_MAX_ENTRIES,\n includeHidden: true,\n },\n RESIDUE_DIRS,\n );\n throwIfCaptureAborted(signal);\n } catch (error) {\n if (isBoxExitingError(error)) {\n throw new BoxExitingError(error instanceof Error ? error.message : String(error));\n }\n throw error;\n }\n\n let entryCount = 0;\n let depthTruncated = false;\n const stack = [...(listing.root.children ?? [])];\n while (stack.length > 0) {\n const node = stack.pop()!;\n entryCount += 1;\n if (node.type !== \"dir\") continue;\n if (RESIDUE_DIR_SET.has(node.name)) {\n node.truncated = true;\n node.children = [];\n continue;\n }\n if (node.path.split(\"/\").length >= TREE_MAX_DEPTH) {\n node.truncated = true;\n depthTruncated = true;\n continue;\n }\n stack.push(...(node.children ?? []));\n }\n return {\n root: listing.root,\n entryCount,\n truncated: listing.truncated || depthTruncated,\n };\n}\n","import type { Observability } from \"@opengeni/observability\";\n\nexport const MODEL_CHECKPOINT_GC_PRESSURE_BYTES = 512 * 1024 * 1024;\nexport const MODEL_CHECKPOINT_GC_COOLDOWN_MS = 30_000;\n\ntype ProcessMemory = Pick<NodeJS.MemoryUsage, \"heapUsed\" | \"external\">;\n\ntype ModelCheckpointMemoryCollectorDependencies = {\n now?: () => number;\n memoryUsage?: () => ProcessMemory;\n gc?: () => void;\n setTimeout?: typeof setTimeout;\n};\n\nexport type ModelCheckpointMemoryCollector = {\n schedule(observability: Observability): void;\n};\n\nexport function modelCheckpointPressureBytes(memory: ProcessMemory): number {\n // `external` includes ArrayBuffer storage in Bun/Node's memoryUsage contract.\n // Heap and external allocations are independent, so max(heap, external)\n // undercounts the actual reclaimable pressure whenever both are large.\n return memory.heapUsed + memory.external;\n}\n\n/**\n * Reclaim request serialization and stream buffers only after one model\n * response has crossed the durable conversation checkpoint. The callback runs\n * on a later task so the completed response's stack can unwind first. Active\n * turns and their exact model context remain strongly reachable and are never\n * shortened, restarted, or rewritten by this process-local collection.\n */\nexport function createModelCheckpointMemoryCollector(\n dependencies: ModelCheckpointMemoryCollectorDependencies = {},\n): ModelCheckpointMemoryCollector {\n const now = dependencies.now ?? Date.now;\n const memoryUsage = dependencies.memoryUsage ?? process.memoryUsage;\n const collectGarbage = dependencies.gc ?? (() => Bun.gc(true));\n const scheduleTask = dependencies.setTimeout ?? setTimeout;\n let scheduled = false;\n let lastCollectionAt = Number.NEGATIVE_INFINITY;\n\n return {\n schedule(observability) {\n if (scheduled) return;\n scheduled = true;\n try {\n const timer = scheduleTask(() => {\n scheduled = false;\n let memory: ProcessMemory;\n try {\n memory = memoryUsage();\n } catch {\n safeIncrementCounter(observability, {\n name: \"opengeni_turn_worker_model_checkpoint_gc_failures_total\",\n help: \"Model-checkpoint garbage collections that could not sample or collect memory.\",\n });\n return;\n }\n\n const pressureBytes = modelCheckpointPressureBytes(memory);\n const observedAt = now();\n if (\n !Number.isFinite(pressureBytes) ||\n pressureBytes < MODEL_CHECKPOINT_GC_PRESSURE_BYTES ||\n observedAt - lastCollectionAt < MODEL_CHECKPOINT_GC_COOLDOWN_MS\n ) {\n return;\n }\n\n lastCollectionAt = observedAt;\n const startedAt = performance.now();\n try {\n collectGarbage();\n safeIncrementCounter(observability, {\n name: \"opengeni_turn_worker_model_checkpoint_gc_total\",\n help: \"Forced garbage collections after durable model-response checkpoints.\",\n });\n safeObserveHistogram(observability, {\n name: \"opengeni_turn_worker_model_checkpoint_gc_duration_seconds\",\n help: \"Forced garbage-collection duration after durable model-response checkpoints.\",\n value: Math.max(0, performance.now() - startedAt) / 1_000,\n });\n } catch {\n safeIncrementCounter(observability, {\n name: \"opengeni_turn_worker_model_checkpoint_gc_failures_total\",\n help: \"Model-checkpoint garbage collections that could not sample or collect memory.\",\n });\n }\n }, 0);\n try {\n timer.unref?.();\n } catch {\n // A timer implementation without a usable unref is still safe.\n }\n } catch {\n scheduled = false;\n }\n },\n };\n}\n\nfunction safeIncrementCounter(\n observability: Observability,\n input: Parameters<Observability[\"incrementCounter\"]>[0],\n): void {\n try {\n observability.incrementCounter(input);\n } catch {\n // Telemetry cannot disable collection at a durable model checkpoint.\n }\n}\n\nfunction safeObserveHistogram(\n observability: Observability,\n input: Parameters<Observability[\"observeHistogram\"]>[0],\n): void {\n try {\n observability.observeHistogram(input);\n } catch {\n // Telemetry cannot disable collection at a durable model checkpoint.\n }\n}\n","import { environmentsEncryptionKeyBytes } from \"@opengeni/config\";\nimport type { MediaGenerationResult } from \"@opengeni/contracts\";\nimport { type CanonicalVideoGenerationRequest, videoGenerationRequestDigest } from \"@opengeni/core\";\nimport {\n addSessionSystemUpdateWithSourceMutation,\n decryptEnvironmentValue,\n encryptEnvironmentValue,\n getVideoGenerationOperation,\n markVideoGenerationProviderStarted,\n markVideoGenerationReferenceCleaned,\n markVideoGenerationRetaining,\n markVideoGenerationSubmissionIntent,\n markVideoGenerationSubmissionUncertain,\n materializeXaiCredentialForRun,\n refreshXaiSubscriptionCredentialSerialized,\n rotateVideoGenerationCredential,\n markVideoGenerationTerminalUpdate,\n markVideoGenerationTerminalUpdateInTransaction,\n mediaGenerationResultForStoredOperation,\n rescheduleVideoGenerationOperation,\n settleVideoGenerationFailure,\n settleVideoGenerationReady,\n type XaiCredentialForRun,\n type VideoGenerationOperationWithReferences,\n} from \"@opengeni/db\";\nimport { publishDurableSessionEvents } from \"@opengeni/events\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport {\n buildGatewayVideoStartBody,\n GatewayVideoApiError,\n getGatewayVideoGenerationStatus,\n startGatewayVideoGenerationWithBody,\n type GatewayVideoReferenceGrant,\n} from \"./gateway-video-generation\";\nimport {\n downloadGeneratedVideoToVerifiedTemp,\n retainVerifiedGeneratedVideo,\n} from \"./video-output-retention\";\nimport {\n decryptVideoGenerationCredential,\n encryptVideoGenerationXaiCredential,\n type VideoGenerationProviderCredential,\n} from \"./video-generation-credential\";\nimport {\n refreshXaiToken,\n XaiSubscriptionError,\n xaiAccessTokenExpiry,\n type XaiSubscriptionRequestContext,\n} from \"@opengeni/xai-subscription\";\nimport {\n buildXaiVideoStartBody,\n getXaiVideoGenerationStatus,\n startXaiVideoGeneration,\n} from \"./xai-video-generation\";\nimport type {\n TurnActivityServices,\n VideoGenerationReconcileResult,\n VideoGenerationTerminalStatus,\n} from \"./types\";\n\nconst RECONCILE_ERROR_MAX = 1_000;\n\nexport function createVideoGenerationActivities(services: () => Promise<TurnActivityServices>) {\n return {\n reconcileVideoGenerationOperation: async (input: {\n accountId: string;\n workspaceId: string;\n operationId: string;\n }): Promise<VideoGenerationReconcileResult> => {\n const service = await services();\n if (!service.objectStorage) {\n throw new Error(\"Video generation reconciliation requires object storage\");\n }\n return await reconcileVideoGenerationOperation(service, input);\n },\n };\n}\n\nexport async function reconcileVideoGenerationOperation(\n service: TurnActivityServices,\n input: { accountId: string; workspaceId: string; operationId: string },\n): Promise<VideoGenerationReconcileResult> {\n const storage = requireStorage(service.objectStorage);\n let operation = await requireOperation(service, input);\n if (isTerminal(operation.status)) {\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: operation.status };\n }\n const key = environmentsEncryptionKeyBytes(service.settings);\n if (!key) throw new Error(\"Video generation recovery encryption key is unavailable\");\n if (!operation.credentialEncrypted) {\n throw new Error(\"Video provider credential lease was erased too early\");\n }\n const providerCredential = decryptVideoGenerationCredential(key, operation.credentialEncrypted);\n const usesSuperGrok = operation.fundingSource === \"supergrok_subscription\";\n if (usesSuperGrok !== (providerCredential.kind === \"xai-subscription\")) {\n throw new Error(\"Video provider credential does not match its funding source\");\n }\n const apiKey = providerCredential.kind === \"api-key\" ? providerCredential.apiKey : null;\n const xaiAuth =\n providerCredential.kind === \"xai-subscription\"\n ? await durableXaiVideoAuth(service, operation, key, providerCredential)\n : null;\n let preparedSubmissionThisRun = false;\n\n if (operation.status === \"accepted\") {\n const canonical = decryptCanonicalRequest(operation, key);\n const grants: GatewayVideoReferenceGrant[] = [];\n const expirations: Date[] = [];\n for (const reference of operation.references) {\n if (!reference.stagingObjectKey) {\n throw new Error(\"Video generation reference staging object is missing\");\n }\n const signed = await storage.createGetUrl({\n key: reference.stagingObjectKey,\n expiresInSeconds: service.settings.videoGenerationReferenceUrlTtlSeconds,\n });\n grants.push({\n role: parseReferenceRole(reference.role),\n url: signed.url,\n mediaType: reference.contentType,\n });\n expirations.push(signed.expiresAt);\n }\n const providerRequestExpiresAt = expirations.length\n ? new Date(Math.min(...expirations.map((value) => value.getTime())))\n : operation.recoveryDeadlineAt;\n const body = usesSuperGrok\n ? buildXaiVideoStartBody(canonical, grants)\n : buildGatewayVideoStartBody(canonical, grants);\n operation = retainReferences(\n operation,\n await markVideoGenerationSubmissionIntent(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n encryptedProviderRequest: encryptEnvironmentValue(key, JSON.stringify(body)),\n providerRequestExpiresAt,\n nextReconcileAt: new Date(),\n }),\n );\n preparedSubmissionThisRun = true;\n }\n\n if (operation.status === \"submission_uncertain\") {\n if (usesSuperGrok && !preparedSubmissionThisRun) {\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: \"outcome_unknown\",\n publicReason:\n \"The video provider did not confirm whether generation started. It was not replayed because xAI provides no start idempotency key.\",\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n const deadline = Math.min(\n operation.recoveryDeadlineAt.getTime(),\n operation.providerRequestExpiresAt?.getTime() ?? 0,\n );\n if (Date.now() >= deadline) {\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: \"outcome_unknown\",\n publicReason:\n \"The video provider did not confirm whether generation started. It was not retried with a new request.\",\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n const body = decryptProviderBody(operation, key);\n try {\n const started = usesSuperGrok\n ? await startXaiVideoGeneration({\n body,\n sessionId: operation.sessionId,\n auth: requireXaiAuth(xaiAuth),\n })\n : await startGatewayVideoGenerationWithBody({\n apiKey: requireApiKey(apiKey),\n modelId: operation.modelId,\n body,\n idempotencyKey: operation.providerIdempotencyKey,\n });\n operation = retainReferences(\n operation,\n await markVideoGenerationProviderStarted(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n providerJobId: started.providerJobId,\n nextReconcileAt: nextPoll(service),\n }),\n );\n return waitResult(service);\n } catch (error) {\n if (isPermanentProviderFailure(error)) {\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: \"provider_failed\",\n publicReason: \"The video provider rejected the generation request.\",\n privateError: privateError(error),\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n await markVideoGenerationSubmissionUncertain(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n nextReconcileAt: nextPoll(service),\n error: privateError(error),\n });\n return waitResult(service);\n }\n }\n\n if (operation.status !== \"provider_started\" && operation.status !== \"retaining\") {\n throw new Error(`Video operation cannot be reconciled from ${operation.status}`);\n }\n if (!operation.providerJobId) throw new Error(\"Video provider job identity is missing\");\n let status;\n try {\n status = usesSuperGrok\n ? await getXaiVideoGenerationStatus({\n providerJobId: operation.providerJobId,\n sessionId: operation.sessionId,\n auth: requireXaiAuth(xaiAuth),\n })\n : await getGatewayVideoGenerationStatus({\n apiKey: requireApiKey(apiKey),\n modelId: operation.modelId,\n providerJobId: operation.providerJobId,\n });\n } catch (error) {\n if (Date.now() < operation.recoveryDeadlineAt.getTime() && !isPermanentProviderFailure(error)) {\n await rescheduleVideoGenerationOperation(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n nextReconcileAt: nextPoll(service),\n error: privateError(error),\n });\n return waitResult(service);\n }\n const failureStatus = operation.status === \"retaining\" ? \"retention_failed\" : \"outcome_unknown\";\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: failureStatus,\n publicReason:\n failureStatus === \"retention_failed\"\n ? \"The generated video could not be retained.\"\n : \"The video provider stopped reporting the accepted generation.\",\n privateError: privateError(error),\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n if (status.status === \"pending\") {\n await rescheduleVideoGenerationOperation(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n nextReconcileAt: nextPoll(service),\n });\n return waitResult(service);\n }\n if (status.status === \"error\") {\n const failureStatus = operation.status === \"retaining\" ? \"retention_failed\" : \"provider_failed\";\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: failureStatus,\n publicReason: status.publicReason,\n }),\n );\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n }\n\n if (operation.status === \"provider_started\") {\n operation = retainReferences(\n operation,\n await markVideoGenerationRetaining(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n }),\n );\n }\n try {\n const canonical = decryptCanonicalRequest(operation, key);\n const downloaded = await downloadGeneratedVideoToVerifiedTemp({\n url: status.outputUrl,\n mediaType: status.mediaType,\n settings: service.settings,\n expectedDurationSeconds: canonical.durationSeconds,\n });\n try {\n const retained = await retainVerifiedGeneratedVideo({\n storage,\n temp: downloaded.temp,\n facts: downloaded.facts,\n });\n const settled = await settleVideoGenerationReady(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n fileId: operation.expectedFileId,\n bucket: retained.bucket,\n objectKey: retained.objectKey,\n sizeBytes: retained.sizeBytes,\n sha256: retained.sha256,\n facts: retained.facts,\n });\n operation = { ...settled.operation, references: operation.references };\n } finally {\n await downloaded.temp.cleanup();\n }\n } catch (error) {\n if (Date.now() < operation.recoveryDeadlineAt.getTime()) {\n await rescheduleVideoGenerationOperation(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n nextReconcileAt: nextPoll(service),\n error: privateError(error),\n });\n return waitResult(service);\n }\n operation = retainReferences(\n operation,\n await settleVideoGenerationFailure(service.db, {\n accountId: input.accountId,\n workspaceId: input.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n status: \"retention_failed\",\n publicReason: \"The generated video could not be retained.\",\n privateError: privateError(error),\n }),\n );\n }\n await deliverTerminalResult(service, operation);\n return { action: \"terminal\", status: terminalStatus(operation.status) };\n}\n\nasync function deliverTerminalResult(\n service: TurnActivityServices,\n operation: VideoGenerationOperationWithReferences,\n): Promise<void> {\n if (\n operation.terminalUpdateState === \"delivered\" ||\n operation.terminalUpdateState === \"suppressed\"\n ) {\n await cleanupTerminalReferences(service, operation);\n return;\n }\n if (!operation.sessionId) {\n await markVideoGenerationTerminalUpdate(service.db, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n operationId: operation.id,\n state: \"suppressed\",\n });\n await cleanupTerminalReferences(service, operation);\n return;\n }\n const payload = await terminalPayload(service, operation);\n const result = await addSessionSystemUpdateWithSourceMutation(\n service.db,\n {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n sessionId: operation.sessionId,\n kind: \"media_generation_result\",\n classification: payload.status === \"ready\" ? \"success\" : \"failure\",\n sourceId: operation.id,\n dedupeKey: `video-generation-terminal:${operation.id}`,\n summary:\n payload.status === \"ready\"\n ? \"The requested video is ready and available in the workspace.\"\n : payload.boundedPublicReason,\n payload,\n lineage: { operationId: operation.id },\n },\n async (tx, _wakeEventId, updateId) => {\n const marked = await markVideoGenerationTerminalUpdateInTransaction(tx, {\n workspaceId: operation.workspaceId,\n operationId: operation.id,\n state: updateId ? \"leased\" : \"suppressed\",\n ...(updateId ? { updateId } : {}),\n });\n if (!marked && operation.terminalUpdateState !== \"leased\") {\n throw new Error(\"Video terminal result lost its disposition fence\");\n }\n },\n );\n if (result.reason === \"session_cancelled\") {\n await cleanupTerminalReferences(service, operation);\n return;\n }\n if (result.added && result.events.length > 0) {\n await publishDurableSessionEvents(\n service.bus,\n operation.workspaceId,\n operation.sessionId,\n result.events,\n );\n }\n if (result.shouldWake && service.wakeSessionWorkflow) {\n if (result.workflowWakeRevision === null) {\n throw new Error(\"Video terminal result wake has no revision\");\n }\n await service.wakeSessionWorkflow({\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n sessionId: operation.sessionId,\n workflowId: result.temporalWorkflowId ?? `session-${operation.sessionId}`,\n wakeRevision: result.workflowWakeRevision,\n });\n }\n await cleanupTerminalReferences(service, operation);\n}\n\nasync function cleanupTerminalReferences(\n service: TurnActivityServices,\n operation: VideoGenerationOperationWithReferences,\n): Promise<void> {\n const storage = requireStorage(service.objectStorage);\n for (const reference of operation.references) {\n if (!reference.stagingObjectKey || reference.cleanedAt) continue;\n // `outcome_unknown` is only terminal after the frozen provider grant and\n // recovery deadline have elapsed. Other terminal outcomes have observed a\n // provider terminal state, so their immutable staging inputs are no longer\n // needed. Delete first, then CAS the row; a crash repeats an idempotent delete.\n if (\n operation.status === \"outcome_unknown\" &&\n Date.now() <\n Math.max(\n operation.recoveryDeadlineAt.getTime(),\n reference.grantExpiresAt?.getTime() ?? 0,\n reference.cleanupAfter?.getTime() ?? 0,\n )\n ) {\n continue;\n }\n const stagingObjectKey = reference.stagingObjectKey;\n await storage.deleteObject(stagingObjectKey);\n const marked = await markVideoGenerationReferenceCleaned(service.db, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n operationId: operation.id,\n ordinal: reference.ordinal,\n stagingObjectKey,\n });\n if (!marked) throw new Error(\"Video reference cleanup lost its durable identity\");\n }\n}\n\nasync function terminalPayload(\n service: TurnActivityServices,\n operation: VideoGenerationOperationWithReferences,\n): Promise<MediaGenerationResult> {\n return await mediaGenerationResultForStoredOperation(service.db, operation);\n}\n\nasync function requireOperation(\n service: TurnActivityServices,\n input: { workspaceId: string; operationId: string },\n): Promise<VideoGenerationOperationWithReferences> {\n const operation = await getVideoGenerationOperation(\n service.db,\n input.workspaceId,\n input.operationId,\n );\n if (!operation) throw new Error(\"Video generation operation was not found\");\n return operation;\n}\n\nfunction decryptCanonicalRequest(\n operation: VideoGenerationOperationWithReferences,\n key: Uint8Array,\n): CanonicalVideoGenerationRequest {\n if (!operation.requestEncrypted) throw new Error(\"Video generation request was erased too early\");\n const parsed = JSON.parse(decryptEnvironmentValue(key, operation.requestEncrypted)) as unknown;\n const request = validateCanonicalRequest(parsed);\n if (videoGenerationRequestDigest(request) !== operation.requestDigest) {\n throw new Error(\"Video generation request digest is inconsistent\");\n }\n return request;\n}\n\nfunction validateCanonicalRequest(value: unknown): CanonicalVideoGenerationRequest {\n const row = record(value);\n const references = Array.isArray(row?.references) ? row.references.map(record) : null;\n if (\n row?.schemaVersion !== 1 ||\n typeof row.modelId !== \"string\" ||\n typeof row.prompt !== \"string\" ||\n ![\n \"text\",\n \"first_frame\",\n \"first_and_last_frames\",\n \"image_reference\",\n \"video_reference\",\n ].includes(String(row.sourceMode)) ||\n !references ||\n !Number.isInteger(row.durationSeconds) ||\n ![\"16:9\", \"4:3\", \"1:1\", \"3:4\", \"9:16\", \"21:9\", \"adaptive\"].includes(String(row.aspectRatio)) ||\n ![\"480p\", \"720p\"].includes(String(row.resolution)) ||\n typeof row.generateAudio !== \"boolean\" ||\n references.some(\n (reference) =>\n !reference ||\n ![\"first_frame\", \"last_frame\", \"image_reference\", \"video_reference\"].includes(\n String(reference.role),\n ) ||\n typeof reference.contentSha256 !== \"string\" ||\n !/^[0-9a-f]{64}$/u.test(reference.contentSha256) ||\n typeof reference.contentType !== \"string\" ||\n !Number.isSafeInteger(reference.byteSize),\n )\n ) {\n throw new Error(\"Encrypted video generation request is malformed\");\n }\n return value as CanonicalVideoGenerationRequest;\n}\n\nfunction decryptProviderBody(\n operation: VideoGenerationOperationWithReferences,\n key: Uint8Array,\n): Record<string, unknown> {\n if (!operation.providerRequestEncrypted) throw new Error(\"Frozen provider request is missing\");\n const body = record(JSON.parse(decryptEnvironmentValue(key, operation.providerRequestEncrypted)));\n if (!body || Buffer.byteLength(JSON.stringify(body)) > 256 * 1024) {\n throw new Error(\"Frozen provider request is malformed\");\n }\n return body;\n}\n\nfunction parseReferenceRole(value: string): GatewayVideoReferenceGrant[\"role\"] {\n if (\n value !== \"first_frame\" &&\n value !== \"last_frame\" &&\n value !== \"image_reference\" &&\n value !== \"video_reference\"\n ) {\n throw new Error(\"Video reference role is invalid\");\n }\n return value;\n}\n\nfunction requireStorage(storage: ObjectStorage | null): ObjectStorage {\n if (!storage) throw new Error(\"Video generation requires object storage\");\n return storage;\n}\n\nfunction nextPoll(service: TurnActivityServices): Date {\n return new Date(Date.now() + service.settings.videoGenerationPollIntervalMs);\n}\n\nfunction waitResult(service: TurnActivityServices): VideoGenerationReconcileResult {\n return {\n action: \"waiting\",\n delayMs: service.settings.videoGenerationPollIntervalMs,\n };\n}\n\nfunction requireApiKey(value: string | null): string {\n if (!value) throw new Error(\"Video provider API key is unavailable\");\n return value;\n}\n\nfunction requireXaiAuth(\n value: Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\"> | null,\n): Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\"> {\n if (!value) throw new Error(\"SuperGrok video authorization is unavailable\");\n return value;\n}\n\n/**\n * A paid video job outlives the connected-account row. Keep its frozen OAuth\n * lease usable after disconnect, and durably replace rotated refresh tokens\n * before exposing them to another provider call. The shared account row is a\n * best-effort mirror only; it is never the operation's recovery authority.\n */\nasync function durableXaiVideoAuth(\n service: TurnActivityServices,\n operation: VideoGenerationOperationWithReferences,\n key: Uint8Array,\n credential: Extract<VideoGenerationProviderCredential, { kind: \"xai-subscription\" }>,\n): Promise<Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\">> {\n let current = credential;\n const frozenEncrypted = operation.credentialEncrypted;\n if (!frozenEncrypted) throw new Error(\"SuperGrok video credential lease is unavailable\");\n let currentEncrypted: string = frozenEncrypted;\n\n let connectedAccount: XaiCredentialForRun | null = null;\n try {\n connectedAccount = await materializeXaiCredentialForRun(service.db, {\n workspaceId: operation.workspaceId,\n subjectId: current.subjectId,\n credentialId: current.credentialId,\n authoritySnapshot: current.authoritySnapshot,\n encryptionKey: key,\n });\n } catch {\n // Disconnect/revocation must not cancel a previously accepted paid job.\n }\n\n return {\n getToken: async () => ({\n accessToken: current.accessToken,\n userId: current.userId,\n }),\n refresh: async () => {\n let next: typeof current | null = null;\n if (connectedAccount) {\n try {\n const result = await refreshXaiSubscriptionCredentialSerialized(service.db, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n subjectId: current.subjectId,\n credentialId: current.credentialId,\n authoritySnapshot: current.authoritySnapshot,\n encryptionKey: key,\n observedAccessToken: current.accessToken,\n observedRefreshToken: current.refreshToken,\n refresh: async (shared) => {\n const refreshToken = shared.secret.refreshToken;\n if (!refreshToken) {\n throw new Error(\"The connected SuperGrok account cannot be refreshed\");\n }\n const tokens = await refreshXaiToken(refreshToken);\n return {\n secret: {\n version: 1,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n },\n expiresAt:\n xaiAccessTokenExpiry(tokens.accessToken) ??\n new Date(Date.now() + tokens.expiresInSeconds * 1_000),\n };\n },\n });\n connectedAccount = result.credential;\n if (\n connectedAccount.secret.accessToken &&\n connectedAccount.secret.refreshToken &&\n connectedAccount.providerAccountId\n ) {\n next = Object.freeze({\n ...current,\n accessToken: connectedAccount.secret.accessToken,\n refreshToken: connectedAccount.secret.refreshToken,\n userId: connectedAccount.providerAccountId,\n });\n }\n } catch {\n // Disconnect/revocation must not cancel a previously accepted paid job.\n connectedAccount = null;\n }\n }\n if (!next) {\n const tokens = await refreshXaiToken(current.refreshToken);\n next = Object.freeze({\n ...current,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n });\n }\n const nextEncrypted = encryptVideoGenerationXaiCredential(key, next);\n await rotateVideoGenerationCredential(service.db, {\n accountId: operation.accountId,\n workspaceId: operation.workspaceId,\n operationId: operation.id,\n requestDigest: operation.requestDigest,\n expectedCredentialEncrypted: currentEncrypted,\n credentialEncrypted: nextEncrypted,\n });\n current = next;\n currentEncrypted = nextEncrypted;\n return { accessToken: current.accessToken, userId: current.userId };\n },\n };\n}\n\nfunction isPermanentProviderFailure(error: unknown): boolean {\n if (error instanceof GatewayVideoApiError) return !error.retryable;\n if (!(error instanceof XaiSubscriptionError)) return false;\n if (error.kind === \"relogin_required\") return true;\n if (error.kind !== \"provider_rejected\") return false;\n return (\n typeof error.status === \"number\" &&\n error.status >= 400 &&\n error.status < 500 &&\n error.status !== 408 &&\n error.status !== 429\n );\n}\n\nfunction privateError(error: unknown): string {\n return (error instanceof Error ? `${error.name}: ${error.message}` : String(error))\n .replace(/https?:\\/\\/\\S+/gu, \"[url omitted]\")\n .slice(0, RECONCILE_ERROR_MAX);\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction isTerminal(status: string): status is VideoGenerationTerminalStatus {\n return [\n \"completed\",\n \"provider_failed\",\n \"cancelled_before_submit\",\n \"outcome_unknown\",\n \"retention_failed\",\n ].includes(status);\n}\n\nfunction terminalStatus(status: string): VideoGenerationTerminalStatus {\n if (!isTerminal(status)) throw new Error(`Video generation status ${status} is not terminal`);\n return status;\n}\n\nfunction retainReferences(\n current: VideoGenerationOperationWithReferences,\n next: Omit<VideoGenerationOperationWithReferences, \"references\">,\n): VideoGenerationOperationWithReferences {\n return { ...next, references: current.references };\n}\n","import type { CanonicalVideoGenerationRequest } from \"@opengeni/core\";\nimport { readResponseTextBounded, type FetchLike } from \"@opengeni/network\";\n\nexport const GATEWAY_VIDEO_PROVIDER_ID = \"vercel-ai-gateway\" as const;\nexport const GATEWAY_VIDEO_START_URL =\n \"https://ai-gateway.vercel.sh/v4/ai/video-model/start\" as const;\nexport const GATEWAY_VIDEO_STATUS_URL =\n \"https://ai-gateway.vercel.sh/v4/ai/video-model/status\" as const;\n\nconst PROTOCOL_VERSION = \"0.0.1\";\nconst VIDEO_SPECIFICATION_VERSION = \"4\";\nconst RESPONSE_MAX_BYTES = 1024 * 1024;\nconst ERROR_MAX_BYTES = 64 * 1024;\n\nexport type GatewayVideoReferenceGrant = Readonly<{\n role: \"first_frame\" | \"last_frame\" | \"image_reference\" | \"video_reference\";\n url: string;\n mediaType: string;\n}>;\n\nexport type GatewayVideoStartResult = Readonly<{ providerJobId: string }>;\nexport type GatewayVideoStatusResult =\n | Readonly<{ status: \"pending\" }>\n | Readonly<{ status: \"completed\"; outputUrl: string; mediaType: string }>\n | Readonly<{ status: \"error\"; publicReason: string }>;\n\nexport class GatewayVideoApiError extends Error {\n constructor(\n readonly status: number | null,\n readonly retryable: boolean,\n message: string,\n ) {\n super(message);\n this.name = \"GatewayVideoApiError\";\n }\n}\n\nexport async function startGatewayVideoGeneration(input: {\n apiKey: string;\n request: CanonicalVideoGenerationRequest;\n idempotencyKey: string;\n referenceGrants: readonly GatewayVideoReferenceGrant[];\n signal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<GatewayVideoStartResult> {\n return await startGatewayVideoGenerationWithBody({\n apiKey: input.apiKey,\n modelId: input.request.modelId,\n body: buildGatewayVideoStartBody(input.request, input.referenceGrants),\n idempotencyKey: input.idempotencyKey,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\n/** Replay entrypoint for the encrypted, byte-stable provider request. */\nexport async function startGatewayVideoGenerationWithBody(input: {\n apiKey: string;\n modelId: string;\n body: Record<string, unknown>;\n idempotencyKey: string;\n signal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<GatewayVideoStartResult> {\n requireSecret(input.apiKey);\n requireIdempotencyKey(input.idempotencyKey);\n const response = await gatewayFetch({\n url: GATEWAY_VIDEO_START_URL,\n apiKey: input.apiKey,\n modelId: input.modelId,\n body: input.body,\n idempotencyKey: input.idempotencyKey,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n const parsed = await readGatewayJson(response, \"AI Gateway video start\", input.signal);\n const operation = record(parsed.operation);\n const providerJobId = stringValue(operation?.gatewayJobId);\n if (!providerJobId || providerJobId.length > 1_024) {\n throw new GatewayVideoApiError(null, true, \"AI Gateway video start response is malformed\");\n }\n return Object.freeze({ providerJobId });\n}\n\nexport async function getGatewayVideoGenerationStatus(input: {\n apiKey: string;\n modelId: string;\n providerJobId: string;\n signal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<GatewayVideoStatusResult> {\n requireSecret(input.apiKey);\n if (!input.providerJobId.trim() || input.providerJobId.length > 1_024) {\n throw new Error(\"AI Gateway video job identity is invalid\");\n }\n const response = await gatewayFetch({\n url: GATEWAY_VIDEO_STATUS_URL,\n apiKey: input.apiKey,\n modelId: input.modelId,\n body: { operation: { gatewayJobId: input.providerJobId } },\n retryNotFound: true,\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n const parsed = await readGatewayJson(response, \"AI Gateway video status\", input.signal);\n const status = stringValue(parsed.status);\n if (status === \"pending\" || status === \"queued\" || status === \"running\") {\n return Object.freeze({ status: \"pending\" });\n }\n if (status === \"error\" || status === \"cancelled\") {\n return Object.freeze({\n status: \"error\",\n publicReason: publicProviderReason(parsed.error, status === \"cancelled\"),\n });\n }\n if (status !== \"completed\" || !Array.isArray(parsed.videos) || parsed.videos.length !== 1) {\n throw new GatewayVideoApiError(null, true, \"AI Gateway video status response is malformed\");\n }\n const video = record(parsed.videos[0]);\n const outputUrl = video?.type === \"url\" ? stringValue(video.url) : null;\n const mediaType = stringValue(video?.mediaType);\n if (!outputUrl || !mediaType || outputUrl.length > 8_192 || mediaType.length > 128) {\n throw new GatewayVideoApiError(null, false, \"AI Gateway returned an unsupported video result\");\n }\n return Object.freeze({ status: \"completed\", outputUrl, mediaType });\n}\n\nexport function buildGatewayVideoStartBody(\n request: CanonicalVideoGenerationRequest,\n referenceGrants: readonly GatewayVideoReferenceGrant[],\n): Record<string, unknown> {\n const expectedRoles = request.references.map((reference) => reference.role);\n if (\n referenceGrants.length !== expectedRoles.length ||\n referenceGrants.some((grant, index) => grant.role !== expectedRoles[index])\n ) {\n throw new Error(\"Video reference grants do not match the sealed request\");\n }\n const files = referenceGrants.map((grant) => ({\n role: grant.role,\n file: {\n type: \"url\" as const,\n url: requireHttps(grant.url),\n mediaType: grant.mediaType,\n },\n }));\n return {\n prompt: request.prompt,\n n: 1,\n aspectRatio: request.aspectRatio,\n resolution: request.resolution,\n duration: request.durationSeconds,\n fps: 24,\n generateAudio: request.generateAudio,\n providerOptions: {},\n ...(request.sourceMode === \"first_frame\" || request.sourceMode === \"first_and_last_frames\"\n ? {\n frameImages: files.map(({ role, file }) => ({\n frameType: role,\n image: file,\n })),\n }\n : request.sourceMode === \"image_reference\" || request.sourceMode === \"video_reference\"\n ? { inputReferences: files.map(({ file }) => file) }\n : {}),\n };\n}\n\nasync function gatewayFetch(input: {\n url: string;\n apiKey: string;\n modelId: string;\n body: Record<string, unknown>;\n idempotencyKey?: string;\n retryNotFound?: boolean;\n signal?: AbortSignal;\n fetch?: FetchLike;\n}): Promise<Response> {\n const timeout = AbortSignal.timeout(60_000);\n const signal = input.signal ? AbortSignal.any([input.signal, timeout]) : timeout;\n let response: Response;\n try {\n response = await (input.fetch ?? globalThis.fetch)(input.url, {\n method: \"POST\",\n redirect: \"error\",\n signal,\n headers: {\n Authorization: `Bearer ${input.apiKey}`,\n accept: \"application/json\",\n \"content-type\": \"application/json\",\n \"ai-gateway-auth-method\": \"api-key\",\n \"ai-gateway-protocol-version\": PROTOCOL_VERSION,\n \"ai-video-model-specification-version\": VIDEO_SPECIFICATION_VERSION,\n \"ai-model-id\": input.modelId,\n \"user-agent\": \"opengeni/video-generation\",\n ...(input.idempotencyKey ? { \"idempotency-key\": input.idempotencyKey } : {}),\n },\n body: JSON.stringify(input.body),\n });\n } catch (error) {\n if (input.signal?.aborted) throw input.signal.reason;\n throw new GatewayVideoApiError(\n null,\n true,\n error instanceof Error ? error.message : \"AI Gateway video request failed\",\n );\n }\n if (response.ok) return response;\n const detail = await readResponseTextBounded(\n response,\n ERROR_MAX_BYTES,\n \"AI Gateway video error\",\n {\n signal,\n },\n ).catch(() => \"\");\n const retryable =\n (input.retryNotFound === true && response.status === 404) ||\n response.status === 408 ||\n response.status === 429 ||\n response.status >= 500;\n throw new GatewayVideoApiError(\n response.status,\n retryable,\n detail\n ? `AI Gateway video request failed (${response.status}): ${boundedError(detail)}`\n : `AI Gateway video request failed (${response.status})`,\n );\n}\n\nasync function readGatewayJson(\n response: Response,\n label: string,\n signal?: AbortSignal,\n): Promise<Record<string, unknown>> {\n const text = await readResponseTextBounded(response, RESPONSE_MAX_BYTES, label, {\n ...(signal ? { signal } : {}),\n });\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n throw new GatewayVideoApiError(null, true, `${label} response is not JSON`);\n }\n const value = record(parsed);\n if (!value) throw new GatewayVideoApiError(null, true, `${label} response is malformed`);\n return value;\n}\n\nfunction requireSecret(value: string): void {\n if (!value.trim()) throw new Error(\"AI Gateway video generation credential is empty\");\n}\n\nfunction requireIdempotencyKey(value: string): void {\n if (!/^ogvid_[0-9a-f]{48}$/u.test(value)) {\n throw new Error(\"AI Gateway video idempotency key is invalid\");\n }\n}\n\nfunction requireHttps(value: string): string {\n const url = new URL(value);\n if (url.protocol !== \"https:\" || url.username || url.password || url.hash) {\n throw new Error(\"Video reference grant must be an HTTPS bearer URL\");\n }\n return url.toString();\n}\n\nfunction record(value: unknown): Record<string, unknown> | null {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\nfunction stringValue(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value : null;\n}\n\nfunction boundedError(value: string): string {\n let message = value;\n try {\n const parsed = record(JSON.parse(value));\n const error = record(parsed?.error);\n message = stringValue(error?.message) ?? stringValue(parsed?.message) ?? value;\n } catch {\n // Preserve the already-bounded non-JSON diagnostic.\n }\n return message.replace(/\\s+/gu, \" \").trim().slice(0, 1_000);\n}\n\nfunction publicProviderReason(error: unknown, cancelled: boolean): string {\n if (cancelled) return \"The video provider cancelled the generation.\";\n const message =\n typeof error === \"string\"\n ? error\n : (stringValue(record(error)?.message) ??\n \"The video provider could not complete the generation.\");\n return message.replace(/\\s+/gu, \" \").trim().slice(0, 1_000);\n}\n","import type { Settings } from \"@opengeni/config\";\nimport { GENERATED_VIDEO_MAX_BYTES, type GeneratedVideoFacts } from \"@opengeni/contracts\";\nimport { pinnedFetch, type FetchLike } from \"@opengeni/network\";\nimport type { ObjectStorage } from \"@opengeni/storage\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { createReadStream } from \"node:fs\";\nimport { mkdir, open, rm } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { validateGeneratedVideo, type VerifiedTempFile } from \"./video-media-validation\";\n\nconst DOWNLOAD_TIMEOUT_MS = 15 * 60_000;\nconst READ_STALL_TIMEOUT_MS = 45_000;\nconst MAX_REDIRECTS = 3;\nconst STORAGE_RANGE_BYTES = 1024 * 1024;\ntype StreamReadResult = Awaited<ReturnType<ReadableStreamDefaultReader<Uint8Array>[\"read\"]>>;\n\nexport type RetainedGeneratedVideo = Readonly<{\n bucket: string;\n objectKey: string;\n sizeBytes: number;\n sha256: string;\n facts: GeneratedVideoFacts;\n}>;\n\n/**\n * Treat the provider's result URL and bytes as hostile. DNS is pinned, every\n * redirect is revalidated, and the body streams to a private temporary file\n * under hard time/size limits before ffprobe sees it.\n */\nexport async function downloadGeneratedVideoToVerifiedTemp(input: {\n url: string;\n mediaType: string;\n settings: Settings;\n expectedDurationSeconds: number;\n fetch?: FetchLike;\n signal?: AbortSignal;\n}): Promise<{ temp: VerifiedTempFile; facts: GeneratedVideoFacts }> {\n if (normalizedMediaType(input.mediaType) !== \"video/mp4\") {\n throw new Error(\"Video provider returned an unsupported media type\");\n }\n const timeoutSignal = AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS);\n const signal = input.signal ? AbortSignal.any([input.signal, timeoutSignal]) : timeoutSignal;\n const response = await fetchFollowingSafeRedirects(input.url, {\n settings: input.settings,\n signal,\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n if (!response.ok || !response.body) {\n await response.body?.cancel().catch(() => undefined);\n throw new Error(\"Video provider output could not be downloaded\");\n }\n if (normalizedMediaType(response.headers.get(\"content-type\")) !== \"video/mp4\") {\n await response.body.cancel().catch(() => undefined);\n throw new Error(\"Video provider output is not an MP4 response\");\n }\n const declaredBytes = parseContentLength(response.headers.get(\"content-length\"));\n if (declaredBytes !== null && declaredBytes > GENERATED_VIDEO_MAX_BYTES) {\n await response.body.cancel().catch(() => undefined);\n throw new Error(\"Generated video exceeds the retained output limit\");\n }\n\n await mkdir(input.settings.videoGenerationTempDirectory, { recursive: true, mode: 0o700 });\n const directory = join(input.settings.videoGenerationTempDirectory, `output-${randomUUID()}`);\n const path = join(directory, \"video.mp4\");\n await mkdir(directory, { recursive: false, mode: 0o700 });\n const handle = await open(path, \"wx\", 0o600);\n const reader = response.body.getReader();\n const digest = createHash(\"sha256\");\n let sizeBytes = 0;\n try {\n for (;;) {\n throwIfAborted(signal);\n const chunk = await readChunkWithStallLimit(reader, signal);\n if (chunk.done) break;\n if (chunk.value.byteLength === 0) continue;\n sizeBytes += chunk.value.byteLength;\n if (sizeBytes > GENERATED_VIDEO_MAX_BYTES) {\n throw new Error(\"Generated video exceeds the retained output limit\");\n }\n await writeAll(handle, chunk.value, sizeBytes - chunk.value.byteLength);\n digest.update(chunk.value);\n }\n await handle.sync();\n } catch (error) {\n await reader.cancel(error).catch(() => undefined);\n await handle.close().catch(() => undefined);\n await rm(directory, { recursive: true, force: true });\n throw error;\n } finally {\n try {\n reader.releaseLock();\n } catch {\n // The aborted transport may retain the lock until cancellation settles.\n }\n }\n await handle.close();\n if (sizeBytes <= 0 || (declaredBytes !== null && sizeBytes !== declaredBytes)) {\n await rm(directory, { recursive: true, force: true });\n throw new Error(\"Generated video response was truncated\");\n }\n const sha256 = digest.digest(\"hex\");\n const temp: VerifiedTempFile = Object.freeze({\n directory,\n path,\n sizeBytes,\n sha256,\n contentType: \"video/mp4\",\n cleanup: async () => await rm(directory, { recursive: true, force: true }),\n });\n try {\n const facts = await validateGeneratedVideo({\n path,\n ffprobePath: input.settings.videoGenerationFfprobePath,\n expectedDurationSeconds: input.expectedDurationSeconds,\n });\n return { temp, facts };\n } catch (error) {\n await temp.cleanup();\n throw error;\n }\n}\n\n/** Stream verified bytes into an immutable content-addressed object and hash\n * the stored generation back through version-fenced Range reads. */\nexport async function retainVerifiedGeneratedVideo(input: {\n storage: ObjectStorage;\n temp: VerifiedTempFile;\n facts: GeneratedVideoFacts;\n signal?: AbortSignal;\n}): Promise<RetainedGeneratedVideo> {\n if (\n !input.storage.putObjectStreamIfAbsent ||\n !input.storage.headObject ||\n !input.storage.getObjectRange\n ) {\n throw new Error(\"Object storage lacks bounded immutable video primitives\");\n }\n const objectKey = `video-generation/objects/sha256/${input.temp.sha256}.mp4`;\n const chunks = fileChunks(input.temp.path, input.signal);\n await input.storage.putObjectStreamIfAbsent({\n key: objectKey,\n contentType: \"video/mp4\",\n chunks,\n byteSize: input.temp.sizeBytes,\n sha256: input.temp.sha256,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n await verifyStoredObject({\n storage: input.storage,\n key: objectKey,\n expectedSizeBytes: input.temp.sizeBytes,\n expectedSha256: input.temp.sha256,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n return Object.freeze({\n bucket: input.storage.bucket,\n objectKey,\n sizeBytes: input.temp.sizeBytes,\n sha256: input.temp.sha256,\n facts: input.facts,\n });\n}\n\nasync function fetchFollowingSafeRedirects(\n rawUrl: string,\n input: { settings: Settings; fetch?: FetchLike; signal: AbortSignal },\n): Promise<Response> {\n let url = requireSafeOutputUrl(rawUrl);\n for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {\n const response = await pinnedFetch(\n url,\n {\n method: \"GET\",\n headers: { accept: \"video/mp4\", \"accept-encoding\": \"identity\" },\n redirect: \"manual\",\n signal: input.signal,\n },\n {\n environment: input.settings.environment,\n // Provider output must never inherit an integration-level private-net override.\n integrationsAllowPrivateNetworkTargets: false,\n },\n {\n label: \"video provider output\",\n requireHttpsOutsideLocalTest: true,\n ...(input.fetch ? { fetchImpl: input.fetch } : {}),\n },\n );\n if (![301, 302, 303, 307, 308].includes(response.status)) return response;\n const location = response.headers.get(\"location\");\n await response.body?.cancel().catch(() => undefined);\n if (!location || redirect === MAX_REDIRECTS) {\n throw new Error(\"Video provider output redirect is invalid\");\n }\n url = requireSafeOutputUrl(new URL(location, url).toString());\n }\n throw new Error(\"Video provider output has too many redirects\");\n}\n\nfunction requireSafeOutputUrl(rawUrl: string): string {\n const url = new URL(rawUrl);\n if (url.protocol !== \"https:\" || url.username || url.password || url.hash) {\n throw new Error(\"Video provider output URL is invalid\");\n }\n return url.toString();\n}\n\nasync function verifyStoredObject(input: {\n storage: ObjectStorage;\n key: string;\n expectedSizeBytes: number;\n expectedSha256: string;\n signal?: AbortSignal;\n}): Promise<void> {\n const head = await input.storage.headObject!(input.key);\n if (\n !head ||\n head.ContentLength !== input.expectedSizeBytes ||\n head.ContentType !== \"video/mp4\" ||\n head.Metadata?.sha256 !== input.expectedSha256 ||\n !head.VersionToken\n ) {\n throw new Error(\"Retained video object metadata is inconsistent\");\n }\n const hash = createHash(\"sha256\");\n let offset = 0;\n while (offset < input.expectedSizeBytes) {\n throwIfAborted(input.signal);\n const endInclusive = Math.min(input.expectedSizeBytes - 1, offset + STORAGE_RANGE_BYTES - 1);\n const range = await input.storage.getObjectRange!({\n key: input.key,\n start: offset,\n endInclusive,\n expectedVersionToken: head.VersionToken,\n });\n if (\n !range ||\n range.versionToken !== head.VersionToken ||\n range.bytes.byteLength !== endInclusive - offset + 1\n ) {\n throw new Error(\"Retained video object changed during verification\");\n }\n hash.update(range.bytes);\n offset += range.bytes.byteLength;\n }\n if (hash.digest(\"hex\") !== input.expectedSha256) {\n throw new Error(\"Retained video object digest is inconsistent\");\n }\n}\n\nasync function* fileChunks(path: string, signal?: AbortSignal): AsyncIterable<Uint8Array> {\n const stream = createReadStream(path, { highWaterMark: STORAGE_RANGE_BYTES });\n try {\n for await (const chunk of stream) {\n throwIfAborted(signal);\n yield chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);\n }\n } finally {\n stream.destroy();\n }\n}\n\nasync function readChunkWithStallLimit(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n signal: AbortSignal,\n): Promise<StreamReadResult> {\n if (signal.aborted) throw signal.reason;\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n reader.read(),\n new Promise<never>((_, reject) => {\n timeout = setTimeout(\n () => reject(new Error(\"Generated video download stalled\")),\n READ_STALL_TIMEOUT_MS,\n );\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nasync function writeAll(\n handle: Awaited<ReturnType<typeof open>>,\n chunk: Uint8Array,\n offset: number,\n): Promise<void> {\n let written = 0;\n while (written < chunk.byteLength) {\n const result = await handle.write(chunk, written, chunk.byteLength - written, offset + written);\n if (result.bytesWritten <= 0) throw new Error(\"Generated video write stalled\");\n written += result.bytesWritten;\n }\n}\n\nfunction normalizedMediaType(value: string | null): string | null {\n const normalized = value?.split(\";\", 1)[0]?.trim().toLowerCase();\n return normalized || null;\n}\n\nfunction parseContentLength(value: string | null): number | null {\n if (value === null) return null;\n if (!/^\\d+$/u.test(value.trim())) throw new Error(\"Generated video length is invalid\");\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new Error(\"Generated video length is invalid\");\n }\n return parsed;\n}\n\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (signal?.aborted) throw signal.reason ?? new Error(\"Video retention was cancelled\");\n}\n","import { GROK_IMAGINE_VIDEO_1_5_MODEL_ID } from \"@opengeni/contracts\";\nimport type { CanonicalVideoGenerationRequest } from \"@opengeni/core\";\nimport {\n getXaiSubscriptionVideoStatus,\n startXaiSubscriptionVideoWithBody,\n XAI_VIDEO_MODEL,\n type XaiFetch,\n type XaiSubscriptionRequestContext,\n type XaiVideoStatus,\n} from \"@opengeni/xai-subscription\";\nimport type { GatewayVideoReferenceGrant } from \"./gateway-video-generation\";\n\nexport function buildXaiVideoStartBody(\n request: CanonicalVideoGenerationRequest,\n referenceGrants: readonly GatewayVideoReferenceGrant[],\n): Record<string, unknown> {\n if (request.modelId !== GROK_IMAGINE_VIDEO_1_5_MODEL_ID) {\n throw new Error(\"The selected video model is not a SuperGrok video model\");\n }\n if (request.sourceMode === \"first_and_last_frames\" || request.sourceMode === \"video_reference\") {\n throw new Error(`Grok Imagine Video does not support ${request.sourceMode}`);\n }\n if (referenceGrants.length !== request.references.length) {\n throw new Error(\"Video reference grants do not match the sealed request\");\n }\n const reference = referenceGrants[0];\n return {\n model: XAI_VIDEO_MODEL,\n prompt: request.prompt,\n duration: request.durationSeconds,\n aspect_ratio: request.aspectRatio,\n resolution: request.resolution,\n ...(request.sourceMode === \"first_frame\" && reference\n ? { image: { url: reference.url } }\n : request.sourceMode === \"image_reference\" && reference\n ? { reference_images: [{ url: reference.url }] }\n : {}),\n };\n}\n\nexport async function startXaiVideoGeneration(input: {\n body: Record<string, unknown>;\n sessionId: string | null;\n auth: Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\">;\n fetch?: XaiFetch;\n}): Promise<{ providerJobId: string }> {\n return await startXaiSubscriptionVideoWithBody({\n body: input.body,\n getToken: input.auth.getToken,\n refresh: input.auth.refresh,\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n\nexport async function getXaiVideoGenerationStatus(input: {\n providerJobId: string;\n sessionId: string | null;\n auth: Pick<XaiSubscriptionRequestContext, \"getToken\" | \"refresh\">;\n fetch?: XaiFetch;\n}): Promise<XaiVideoStatus> {\n return await getXaiSubscriptionVideoStatus({\n providerJobId: input.providerJobId,\n getToken: input.auth.getToken,\n refresh: input.auth.refresh,\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n ...(input.fetch ? { fetch: input.fetch } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,8BAA8B,0BAAAA,+BAA8B;;;ACArE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA,mBAAAC;AAAA,EACA,oBAAAC;AAAA,EACA;AAAA,EACA,+BAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oCAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA,kCAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,qCAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,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B,QAAQ;AAAA,IACjD,GAAG,gCAAgC,QAAQ;AAAA,EAC7C;AACF;","names":["summarizeForCompaction","requireFile","getSessionEvent","getSessionRootId","getHumanInputResumeForEvent","workspaceCodexSubscriptionActive","materializeXaiCredentialForRun","getActiveSessionHistoryItemsPaged","listSessionSystemUpdatesForTurn","appendAndPublishTurnEventsFenced","publishDurableSessionEvents","projectHistoryForProvider","sanitizeHistoryItemsForModel","REMOTE_COMPACTION_V2_IMPLEMENTATION","EmptyCompactionSummaryError","SUMMARY_BUFFER_TOKENS","deleteRecordingArtifacts","stopRecordingOnBox","environmentsEncryptionKeyBytes","codemodeWorkspaceUrl","CancelledFailure","CODEX_PROVIDER_ID","XaiSubscriptionReloginRequired","environmentsEncryptionKeyBytes","createHash","COMPUTER_SCREENSHOT_MAX_DIMENSION","COMPUTER_SCREENSHOT_MAX_PIXELS","createHash","record","base64Sextet","COMPUTER_SCREENSHOT_MAX_DIMENSION","COMPUTER_SCREENSHOT_MAX_PIXELS","createHash","reference","digest","reference","uuidFromDigest","createHash","reference","videoGenerationCapabilitiesForPolicy","getActiveSessionHistoryItemsPaged","createHash","getActiveSessionHistoryItemsPaged","outcome","record","encryptEnvironmentValue","environmentsEncryptionKeyBytes","createHash","randomUUID","createHash","randomUUID","digest","reference","sha256","throwIfAborted","environmentsEncryptionKeyBytes","reference","randomUUID","createHash","encryptEnvironmentValue","positiveInteger","timer","timer","reference","getGeneratedImageArtifact","requireFile","reference","requireFile","getGeneratedImageArtifact","createHash","SandboxChannelAService","resourceMountPath","createHash","randomUUID","createHash","CancelledFailure","EmptyCompactionSummaryError","record","CODEX_PROVIDER_ID","sanitizeHistoryItemsForModel","record","CancelledFailure","randomUUID","stopRecordingOnBox","snapshotSession","snapshotTurnId","requireFile","workspaceCodexSubscriptionActive","getSessionEvent","getHumanInputResumeForEvent","appendAndPublishTurnEventsFenced","deleteRecordingArtifacts","publishDurableSessionEvents","projectHistoryForProvider","listSessionSystemUpdatesForTurn","REMOTE_COMPACTION_V2_IMPLEMENTATION","SUMMARY_BUFFER_TOKENS","EmptyCompactionSummaryError","getSessionRootId","codemodeWorkspaceUrl","SandboxChannelAService","environmentsEncryptionKeyBytes","materializeXaiCredentialForRun","videoGenerationCapabilitiesForPolicy","getActiveSessionHistoryItemsPaged","XaiSubscriptionReloginRequired","resourceMountPath","environmentsEncryptionKeyBytes","videoGenerationRequestDigest","decryptEnvironmentValue","encryptEnvironmentValue","getVideoGenerationOperation","materializeXaiCredentialForRun","refreshXaiSubscriptionCredentialSerialized","publishDurableSessionEvents","readResponseTextBounded","record","stringValue","reference","readResponseTextBounded","GENERATED_VIDEO_MAX_BYTES","createHash","randomUUID","mkdir","open","rm","join","GENERATED_VIDEO_MAX_BYTES","mkdir","join","randomUUID","open","digest","createHash","throwIfAborted","writeAll","rm","sha256","refreshXaiToken","xaiAccessTokenExpiry","reference","environmentsEncryptionKeyBytes","reference","encryptEnvironmentValue","publishDurableSessionEvents","getVideoGenerationOperation","decryptEnvironmentValue","videoGenerationRequestDigest","record","materializeXaiCredentialForRun","refreshXaiSubscriptionCredentialSerialized","refreshXaiToken","xaiAccessTokenExpiry","summarizeForCompaction"]}
|