package runtimegrpc

import (
	"context"
	"errors"
	"fmt"
	"io"
	"strings"
	"sync"
	"time"

	catalogsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/catalog/consumerv1"
	analyticsauthoringsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/analyticsauthoringv1"
	applicationresultsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/applicationresultv1"
	approvalnotificationsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/approvalnotificationflowv1"
	approvalsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/approvalv1"
	auditsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/auditlogv1"
	authorizationsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/authorizationv1"
	bulkingestsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/bulkingestv1"
	commandsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/commandv1"
	commonsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/commonv1"
	permissionsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/effectivepermissionsv1"
	externaleffectsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/externaleffectv1"
	federatedloginsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/federatedloginv1"
	filessemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/filesv1"
	flowsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/flowv1"
	identitysemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/identityv1"
	layoutauthoringsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/layoutauthoringv1"
	layoutauthoringv2semantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/layoutauthoringv2"
	listviewsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/listviewv1"
	metadataadminsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/metadataadminreadv1"
	outboundintentsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/outboundintentv1"
	pagelayoutsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/pagelayoutresolutionv1"
	permissionadminsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/permissionadminv1"
	permissionauthoringsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/permissionauthoringv1"
	reportsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/reportv1"
	resourceaccesssemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/resourceaccessv1"
	searchsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/searchv1"
	sessionsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/sessionv1"
	"github.com/pingcap-inc/nexuscrm-contract/wire-go/envelope"
	catalogv1 "github.com/pingcap-inc/nexuscrm-contract/wire-go/gen/catalog/v1"
	runtimev1 "github.com/pingcap-inc/nexuscrm-contract/wire-go/gen/runtime/v1"
	"github.com/pingcap-inc/nexuscrm-contract/wire-go/mapping"
	"google.golang.org/grpc"
	"google.golang.org/grpc/connectivity"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/metadata"
)

// RuntimePlatformClient uses one private target while preserving the two
// non-identity method classes. Search, Flow, Report, Files, connected-mailbox
// authorization, effective permissions, and Approval exchange an end-user
// bearer for a least-privilege delegation.
// Catalog views, Command acceptance, and ApplicationResult reads are
// workload-consumer methods and expose no bearer parameter.
type RuntimePlatformClient struct {
	connection          *grpc.ClientConn
	identity            *IdentityExchangeClient
	identityCoordinator *identityExchangeCoordinator
	sessions            *SessionLifecycleClient
	authorizations      *AuthorizationLifecycleClient
	federatedLogins     *FederatedLoginTransactionClient
	catalog             catalogv1.ConsumerViewServiceClient
	catalogV3           catalogv1.AppMetadataViewV3ServiceClient
	search              runtimev1.RecordSearchServiceClient
	flow                runtimev1.FlowExecutionServiceClient
	report              runtimev1.ReportReadServiceClient
	auditLog            runtimev1.AuditLogReadServiceClient
	listViews           runtimev1.PrivateListViewServiceClient
	metadataAdminReads  runtimev1.MetadataAdminReadServiceClient
	approvalFlowReads   runtimev1.ApprovalNotificationFlowReadServiceClient
	pageLayouts         runtimev1.PageLayoutResolutionServiceClient
	mailboxes           runtimev1.ConnectedMailboxAuthorizationServiceClient
	files               runtimev1.AuthorizedFilesServiceClient
	bulkIngest          runtimev1.BulkIngestServiceClient
	commands            runtimev1.CommandAcceptanceServiceClient
	results             runtimev1.ApplicationResultServiceClient
	externalEffects     runtimev1.ExternalEffectDispatchServiceClient
	outboundIntents     runtimev1.OutboundIntentServiceClient
	outboundNoEffect    runtimev1.OutboundIntentNoEffectServiceClient
	permissions         runtimev1.EffectivePermissionServiceClient
	permissionAdmin     runtimev1.PermissionAdministrationServiceClient
	permissionAuthoring runtimev1.PermissionAuthoringServiceClient
	layoutAuthoring     runtimev1.LayoutAuthoringServiceClient
	layoutAuthoringV2   runtimev1.LayoutAuthoringV2ServiceClient
	navigation          runtimev1.ApplicationNavigationServiceClient
	analyticsAuthoring  runtimev1.AnalyticsAuthoringServiceClient
	resourceAccess      runtimev1.ResourceAccessServiceClient
	approvals           runtimev1.ApprovalServiceClient
	appInstallationID   string
	workloadToken       string
	attemptTimeout      time.Duration
}

type streamLifecycle struct {
	cancel     context.CancelFunc
	cancelOnce sync.Once
}

func (lifecycle *streamLifecycle) Cancel() {
	if lifecycle == nil {
		return
	}
	lifecycle.cancelOnce.Do(func() {
		if lifecycle.cancel != nil {
			lifecycle.cancel()
		}
	})
}

// AppMetadataWatch owns one bounded Catalog watch attempt. Recv validates the
// monotonic, same-scope semantic stream before returning each view. The caller
// owns consumption and must call Cancel when it stops before Recv returns.
type AppMetadataWatch struct {
	streamLifecycle
	mu     sync.Mutex
	stream catalogv1.ConsumerViewService_WatchAppMetadataViewClient
	state  catalogsemantic.AppMetadataWatchState
	closed bool
}

// AppMetadataV2Watch owns one bounded effective-metadata watch attempt.
// It preserves the same cancellation and monotonic scope guarantees as the
// v1 watch while validating the v2 semantic view before consumption.
type AppMetadataV2Watch struct {
	streamLifecycle
	mu     sync.Mutex
	stream catalogv1.ConsumerViewService_WatchAppMetadataViewV2Client
	state  catalogsemantic.AppMetadataV2WatchState
	closed bool
}

// AppMetadataV3Watch owns one bounded complete-metadata watch attempt under
// the V3 capability identity and its larger semantic response ceiling.
type AppMetadataV3Watch struct {
	streamLifecycle
	mu     sync.Mutex
	stream catalogv1.AppMetadataViewV3Service_WatchAppMetadataViewV3Client
	state  catalogsemantic.AppMetadataV3WatchState
	closed bool
}

// IntegrationBindingWatch owns one bounded Integration binding watch attempt.
// It has the same cancellation and monotonicity contract as AppMetadataWatch.
type IntegrationBindingWatch struct {
	streamLifecycle
	mu     sync.Mutex
	stream catalogv1.ConsumerViewService_WatchIntegrationBindingViewClient
	state  catalogsemantic.IntegrationBindingWatchState
	closed bool
}

// RuntimeFileUpload owns a bounded authorized upload stream and its semantic
// state. Send and CloseAndRecv serialize stream use; Cancel is safe to invoke
// concurrently and interrupts an in-flight gRPC operation. Source-body reads
// remain owned by the caller rather than being hidden behind an uncancellable
// io.Reader callback.
type RuntimeFileUpload struct {
	streamLifecycle
	mu     sync.Mutex
	stream runtimev1.AuthorizedFilesService_CreateFileClient
	state  *filessemantic.CreateStreamState
	closed bool
}

// RuntimeFileDownload owns a bounded authorized download stream. Recv validates
// the complete semantic stream, including exact EOF, before reporting io.EOF.
type RuntimeFileDownload struct {
	streamLifecycle
	mu     sync.Mutex
	stream runtimev1.AuthorizedFilesService_OpenFileClient
	state  *filessemantic.OpenStreamState
	closed bool
}

// RuntimeBulkIngestUpload owns one authorized bounded CSV stream. The caller
// drives source reads explicitly, so HTTP cancellation interrupts both the
// gRPC stream and the upstream body without an uncancellable copy goroutine.
type RuntimeBulkIngestUpload struct {
	streamLifecycle
	mu     sync.Mutex
	stream runtimev1.BulkIngestService_UploadBulkIngestDataClient
	state  *bulkingestsemantic.UploadStreamState
	header bulkingestsemantic.UploadHeader
	closed bool
}

func DialPlatformRuntime(ctx context.Context, config RuntimeClientConfig) (*RuntimePlatformClient, error) {
	return dialPlatformRuntime(ctx, config, newIdentityExchangeCoordinator(config))
}

func (group *RuntimeClientGroup) DialPlatformRuntime(ctx context.Context) (*RuntimePlatformClient, error) {
	if group == nil {
		return nil, errors.New("runtime client group: configuration is required")
	}
	return dialPlatformRuntime(ctx, group.config, group.identityCoordinator)
}

func dialPlatformRuntime(ctx context.Context, config RuntimeClientConfig, coordinator *identityExchangeCoordinator) (*RuntimePlatformClient, error) {
	if ctx == nil {
		return nil, errors.New("runtime Platform client: startup context is required")
	}
	if strings.TrimSpace(config.Target) == "" || strings.TrimSpace(config.Target) != config.Target ||
		(config.AppInstallationID != "" && strings.TrimSpace(config.AppInstallationID) != config.AppInstallationID) ||
		strings.TrimSpace(config.WorkloadToken) == "" || strings.TrimSpace(config.WorkloadToken) != config.WorkloadToken ||
		config.AttemptTimeout <= 0 {
		return nil, errors.New("runtime Platform client: canonical target, optional AppInstallation, workload token and attempt timeout are required")
	}
	transport, err := runtimeClientTransportCredentials(config)
	if err != nil {
		return nil, err
	}
	return dialPlatformRuntimeWithCredentialsAndCoordinator(ctx, config, transport, coordinator)
}

func dialPlatformRuntimeWithCredentials(ctx context.Context, config RuntimeClientConfig, transport credentials.TransportCredentials) (*RuntimePlatformClient, error) {
	return dialPlatformRuntimeWithCredentialsAndCoordinator(ctx, config, transport, newIdentityExchangeCoordinator(config))
}

func dialPlatformRuntimeWithCredentialsAndCoordinator(ctx context.Context, config RuntimeClientConfig, transport credentials.TransportCredentials, coordinator *identityExchangeCoordinator) (*RuntimePlatformClient, error) {
	if transport == nil {
		return nil, errors.New("runtime Platform client: transport credentials are required")
	}
	connection, err := runtimeClientConnection(config.Target, transport, coordinator)
	if err != nil {
		return nil, fmt.Errorf("runtime Platform client: create connection: %w", err)
	}
	generatedIdentity := runtimev1.NewIdentityContextServiceClient(connection)
	generatedSessions := runtimev1.NewSessionLifecycleServiceClient(connection)
	generatedAuthorizations := runtimev1.NewAuthorizationLifecycleServiceClient(connection)
	generatedFederatedLogins := runtimev1.NewFederatedLoginTransactionServiceClient(connection)
	client := &RuntimePlatformClient{
		connection: connection, catalog: catalogv1.NewConsumerViewServiceClient(connection),
		catalogV3: catalogv1.NewAppMetadataViewV3ServiceClient(connection),
		search:    runtimev1.NewRecordSearchServiceClient(connection), flow: runtimev1.NewFlowExecutionServiceClient(connection),
		report: runtimev1.NewReportReadServiceClient(connection), listViews: runtimev1.NewPrivateListViewServiceClient(connection),
		metadataAdminReads: runtimev1.NewMetadataAdminReadServiceClient(connection),
		approvalFlowReads:  runtimev1.NewApprovalNotificationFlowReadServiceClient(connection),
		pageLayouts:        runtimev1.NewPageLayoutResolutionServiceClient(connection),
		mailboxes:          runtimev1.NewConnectedMailboxAuthorizationServiceClient(connection),
		auditLog:           runtimev1.NewAuditLogReadServiceClient(connection),
		files:              runtimev1.NewAuthorizedFilesServiceClient(connection),
		bulkIngest:         runtimev1.NewBulkIngestServiceClient(connection),
		commands:           runtimev1.NewCommandAcceptanceServiceClient(connection),
		results:            runtimev1.NewApplicationResultServiceClient(connection),
		externalEffects:    runtimev1.NewExternalEffectDispatchServiceClient(connection),
		outboundIntents:    runtimev1.NewOutboundIntentServiceClient(connection),
		outboundNoEffect:   runtimev1.NewOutboundIntentNoEffectServiceClient(connection),
		permissions:        runtimev1.NewEffectivePermissionServiceClient(connection), appInstallationID: config.AppInstallationID,
		permissionAdmin:     runtimev1.NewPermissionAdministrationServiceClient(connection),
		permissionAuthoring: runtimev1.NewPermissionAuthoringServiceClient(connection),
		layoutAuthoring:     runtimev1.NewLayoutAuthoringServiceClient(connection),
		layoutAuthoringV2:   runtimev1.NewLayoutAuthoringV2ServiceClient(connection),
		navigation:          runtimev1.NewApplicationNavigationServiceClient(connection),
		analyticsAuthoring:  runtimev1.NewAnalyticsAuthoringServiceClient(connection),
		resourceAccess:      runtimev1.NewResourceAccessServiceClient(connection),
		approvals:           runtimev1.NewApprovalServiceClient(connection),
		workloadToken:       config.WorkloadToken, attemptTimeout: config.AttemptTimeout,
		identityCoordinator: coordinator,
	}
	client.identity, err = NewIdentityExchangeClient(func(callCtx context.Context, request *runtimev1.ExchangeRequest, options ...grpc.CallOption) (*runtimev1.ExchangeResponse, error) {
		return generatedIdentity.Exchange(
			withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken),
			request,
			options...,
		)
	})
	if err != nil {
		_ = connection.Close()
		return nil, err
	}
	client.authorizations, err = NewAuthorizationLifecycleClient(
		func(callCtx context.Context, request *runtimev1.BeginAuthorizationRequest, options ...grpc.CallOption) (*runtimev1.BeginAuthorizationResponse, error) {
			return generatedAuthorizations.BeginAuthorization(withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken), request, options...)
		},
		func(callCtx context.Context, request *runtimev1.CompleteAuthorizationRequest, options ...grpc.CallOption) (*runtimev1.CompleteAuthorizationResponse, error) {
			return generatedAuthorizations.CompleteAuthorization(withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken), request, options...)
		},
		func(callCtx context.Context, request *runtimev1.ExchangeAuthorizationTokenRequest, options ...grpc.CallOption) (*runtimev1.ExchangeAuthorizationTokenResponse, error) {
			return generatedAuthorizations.ExchangeAuthorizationToken(withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken), request, options...)
		},
	)
	if err != nil {
		_ = connection.Close()
		return nil, err
	}
	client.federatedLogins, err = NewFederatedLoginTransactionClient(
		func(callCtx context.Context, request *runtimev1.BeginFederatedLoginRequest, options ...grpc.CallOption) (*runtimev1.BeginFederatedLoginResponse, error) {
			return generatedFederatedLogins.BeginFederatedLogin(withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken), request, options...)
		},
		func(callCtx context.Context, request *runtimev1.ConsumeFederatedLoginRequest, options ...grpc.CallOption) (*runtimev1.ConsumeFederatedLoginResponse, error) {
			return generatedFederatedLogins.ConsumeFederatedLogin(withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken), request, options...)
		},
	)
	if err != nil {
		_ = connection.Close()
		return nil, err
	}
	client.sessions, err = NewSessionLifecycleClient(
		func(callCtx context.Context, request *runtimev1.CreateSessionRequest, options ...grpc.CallOption) (*runtimev1.CreateSessionResponse, error) {
			return generatedSessions.CreateSession(
				withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken), request, options...,
			)
		},
		func(callCtx context.Context, request *runtimev1.ReadSessionRequest, options ...grpc.CallOption) (*runtimev1.ReadSessionResponse, error) {
			return generatedSessions.ReadSession(
				withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken), request, options...,
			)
		},
		func(callCtx context.Context, request *runtimev1.RevokeSessionRequest, options ...grpc.CallOption) (*runtimev1.RevokeSessionResponse, error) {
			return generatedSessions.RevokeSession(
				withWorkloadAuthorization(withoutOutgoingRuntimeDelegation(callCtx), client.workloadToken), request, options...,
			)
		},
	)
	if err != nil {
		_ = connection.Close()
		return nil, err
	}
	connection.Connect()
	for {
		state := connection.GetState()
		if state == connectivity.Ready {
			return client, nil
		}
		if state == connectivity.Shutdown {
			_ = connection.Close()
			return nil, errors.New("runtime Platform client: connection shut down during startup")
		}
		if !connection.WaitForStateChange(ctx, state) {
			_ = connection.Close()
			return nil, fmt.Errorf("runtime Platform client: Runtime not ready: %w", ctx.Err())
		}
	}
}

func (c *RuntimePlatformClient) CreateSession(
	ctx context.Context,
	credentials SessionCreateCredentials,
	request sessionsemantic.CreateRequest,
) (sessionsemantic.CreateResponse, SessionIssuedCredentials, error) {
	if c == nil || c.sessions == nil || c.appInstallationID == "" {
		return sessionsemantic.CreateResponse{}, SessionIssuedCredentials{}, sessionUnavailable()
	}
	if request.AppInstallationID != "" && request.AppInstallationID != c.appInstallationID {
		return sessionsemantic.CreateResponse{}, SessionIssuedCredentials{}, &sessionsemantic.Failure{
			Category: sessionsemantic.FailureInvalidRequest, InvalidComponent: sessionsemantic.InvalidComponentAppInstallationID,
		}
	}
	request.AppInstallationID = c.appInstallationID
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return sessionsemantic.CreateResponse{}, SessionIssuedCredentials{}, err
	}
	defer cancel()
	return c.sessions.CreateSession(callCtx, credentials, request)
}

func (c *RuntimePlatformClient) ReadSession(
	ctx context.Context,
	credentials SessionPresentedCredentials,
	request sessionsemantic.ReadRequest,
) (sessionsemantic.ReadResponse, SessionIssuedCredentials, error) {
	if c == nil || c.sessions == nil || c.appInstallationID == "" {
		return sessionsemantic.ReadResponse{}, SessionIssuedCredentials{}, sessionUnavailable()
	}
	if request.AppInstallationID != "" && request.AppInstallationID != c.appInstallationID {
		return sessionsemantic.ReadResponse{}, SessionIssuedCredentials{}, &sessionsemantic.Failure{
			Category: sessionsemantic.FailureInvalidRequest, InvalidComponent: sessionsemantic.InvalidComponentAppInstallationID,
		}
	}
	request.AppInstallationID = c.appInstallationID
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return sessionsemantic.ReadResponse{}, SessionIssuedCredentials{}, err
	}
	defer cancel()
	return c.sessions.ReadSession(callCtx, credentials, request)
}

func (c *RuntimePlatformClient) RevokeSession(
	ctx context.Context,
	credentials SessionPresentedCredentials,
	request sessionsemantic.RevokeRequest,
) error {
	if c == nil || c.sessions == nil || c.appInstallationID == "" {
		return sessionUnavailable()
	}
	if request.AppInstallationID != "" && request.AppInstallationID != c.appInstallationID {
		return &sessionsemantic.Failure{
			Category: sessionsemantic.FailureInvalidRequest, InvalidComponent: sessionsemantic.InvalidComponentAppInstallationID,
		}
	}
	request.AppInstallationID = c.appInstallationID
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return err
	}
	defer cancel()
	return c.sessions.RevokeSession(callCtx, credentials, request)
}

func (c *RuntimePlatformClient) BeginAuthorization(ctx context.Context, request authorizationsemantic.BeginRequest) (authorizationsemantic.BeginResponse, error) {
	if c == nil || c.authorizations == nil || c.appInstallationID == "" {
		return authorizationsemantic.BeginResponse{}, sessionUnavailable()
	}
	if request.AppInstallationID != "" && request.AppInstallationID != c.appInstallationID {
		return authorizationsemantic.BeginResponse{}, &authorizationsemantic.Failure{Category: authorizationsemantic.FailureInvalidRequest,
			InvalidComponent: authorizationsemantic.InvalidComponentAppInstallationID}
	}
	request.AppInstallationID = c.appInstallationID
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return authorizationsemantic.BeginResponse{}, err
	}
	defer cancel()
	return c.authorizations.Begin(callCtx, request)
}

func (c *RuntimePlatformClient) BeginFederatedLogin(ctx context.Context, request federatedloginsemantic.BeginRequest) (federatedloginsemantic.BeginResponse, error) {
	if c == nil || c.federatedLogins == nil || c.appInstallationID == "" {
		return federatedloginsemantic.BeginResponse{}, &federatedloginsemantic.Failure{Category: federatedloginsemantic.FailureUnavailable}
	}
	if request.AppInstallationID != "" && request.AppInstallationID != c.appInstallationID {
		return federatedloginsemantic.BeginResponse{}, &federatedloginsemantic.Failure{
			Category: federatedloginsemantic.FailureInvalidRequest, InvalidComponent: federatedloginsemantic.InvalidComponentAppInstallationID,
		}
	}
	request.AppInstallationID = c.appInstallationID
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return federatedloginsemantic.BeginResponse{}, err
	}
	defer cancel()
	return c.federatedLogins.Begin(callCtx, request)
}

func (c *RuntimePlatformClient) ConsumeFederatedLogin(ctx context.Context, request federatedloginsemantic.ConsumeRequest) error {
	if c == nil || c.federatedLogins == nil || c.appInstallationID == "" {
		return &federatedloginsemantic.Failure{Category: federatedloginsemantic.FailureUnavailable}
	}
	if request.AppInstallationID != "" && request.AppInstallationID != c.appInstallationID {
		return &federatedloginsemantic.Failure{
			Category: federatedloginsemantic.FailureInvalidRequest, InvalidComponent: federatedloginsemantic.InvalidComponentAppInstallationID,
		}
	}
	request.AppInstallationID = c.appInstallationID
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return err
	}
	defer cancel()
	return c.federatedLogins.Consume(callCtx, request)
}

func (c *RuntimePlatformClient) CompleteAuthorization(ctx context.Context, credentials SessionPresentedCredentials, request authorizationsemantic.CompleteRequest) (authorizationsemantic.CompleteResponse, IssuedAuthorizationCredentials, error) {
	if c == nil || c.authorizations == nil || c.appInstallationID == "" {
		return authorizationsemantic.CompleteResponse{}, IssuedAuthorizationCredentials{}, sessionUnavailable()
	}
	if request.AppInstallationID != "" && request.AppInstallationID != c.appInstallationID {
		return authorizationsemantic.CompleteResponse{}, IssuedAuthorizationCredentials{}, &authorizationsemantic.Failure{Category: authorizationsemantic.FailureInvalidRequest,
			InvalidComponent: authorizationsemantic.InvalidComponentAppInstallationID}
	}
	request.AppInstallationID = c.appInstallationID
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return authorizationsemantic.CompleteResponse{}, IssuedAuthorizationCredentials{}, err
	}
	defer cancel()
	return c.authorizations.Complete(callCtx, credentials, request)
}

func (c *RuntimePlatformClient) ExchangeAuthorizationToken(ctx context.Context, credentials AuthorizationExchangeCredentials, request authorizationsemantic.ExchangeRequest) (authorizationsemantic.ExchangeResponse, IssuedAuthorizationCredentials, error) {
	if c == nil || c.authorizations == nil || c.appInstallationID == "" {
		return authorizationsemantic.ExchangeResponse{}, IssuedAuthorizationCredentials{}, sessionUnavailable()
	}
	if request.AppInstallationID != "" && request.AppInstallationID != c.appInstallationID {
		return authorizationsemantic.ExchangeResponse{}, IssuedAuthorizationCredentials{}, &authorizationsemantic.Failure{
			Category: authorizationsemantic.FailureInvalidRequest, InvalidComponent: authorizationsemantic.InvalidComponentAppInstallationID}
	}
	request.AppInstallationID = c.appInstallationID
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return authorizationsemantic.ExchangeResponse{}, IssuedAuthorizationCredentials{}, err
	}
	defer cancel()
	return c.authorizations.Exchange(callCtx, credentials, request)
}

func (c *RuntimePlatformClient) GetAppMetadataView(ctx context.Context, request catalogsemantic.GetRequest) (catalogsemantic.AppMetadataView, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return catalogsemantic.AppMetadataView{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireCatalogGetRequest(callCtx, request)
	if err != nil {
		return catalogsemantic.AppMetadataView{}, err
	}
	response, err := c.catalog.GetAppMetadataView(
		c.workloadDataContext(callCtx, catalogsemantic.AppMetadataCapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return catalogsemantic.AppMetadataView{}, mapping.FromPlatformStatusError(err, catalogsemantic.AppMetadataCapabilityName)
	}
	return mapping.FromWireGetAppMetadataViewResponse(response)
}

func (c *RuntimePlatformClient) WatchAppMetadataView(
	ctx context.Context,
	request catalogsemantic.WatchRequest,
) (*AppMetadataWatch, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return nil, err
	}
	wireRequest, err := mapping.ToWireAppMetadataWatchRequest(callCtx, request)
	if err != nil {
		cancel()
		return nil, err
	}
	stream, err := c.catalog.WatchAppMetadataView(
		c.workloadDataContext(callCtx, catalogsemantic.AppMetadataCapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		cancel()
		return nil, mapping.FromPlatformStatusError(err, catalogsemantic.AppMetadataCapabilityName)
	}
	return &AppMetadataWatch{
		streamLifecycle: streamLifecycle{cancel: cancel},
		stream:          stream,
		state:           catalogsemantic.NewAppMetadataWatchState(request),
	}, nil
}

func (watch *AppMetadataWatch) Recv() (catalogsemantic.AppMetadataView, error) {
	if watch == nil || watch.stream == nil {
		return catalogsemantic.AppMetadataView{}, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	watch.mu.Lock()
	defer watch.mu.Unlock()
	if watch.closed {
		return catalogsemantic.AppMetadataView{}, io.EOF
	}
	response, err := watch.stream.Recv()
	if errors.Is(err, io.EOF) {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataView{}, io.EOF
	}
	if err != nil {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataView{}, mapping.FromPlatformStatusError(err, catalogsemantic.AppMetadataCapabilityName)
	}
	view, err := mapping.FromWireWatchAppMetadataViewResponse(response)
	if err == nil {
		err = watch.state.Observe(view)
	}
	if err != nil {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataView{}, err
	}
	return view, nil
}

func (c *RuntimePlatformClient) GetAppMetadataViewV2(
	ctx context.Context,
	request catalogsemantic.GetRequest,
) (catalogsemantic.AppMetadataViewV2, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return catalogsemantic.AppMetadataViewV2{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireCatalogGetV2Request(callCtx, request)
	if err != nil {
		return catalogsemantic.AppMetadataViewV2{}, err
	}
	response, err := c.catalog.GetAppMetadataViewV2(
		c.workloadDataContext(
			callCtx,
			catalogsemantic.AppMetadataV2CapabilityName,
		),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return catalogsemantic.AppMetadataViewV2{},
			mapping.FromPlatformStatusError(
				err,
				catalogsemantic.AppMetadataV2CapabilityName,
			)
	}
	return mapping.FromWireGetAppMetadataViewV2Response(response)
}

func (c *RuntimePlatformClient) WatchAppMetadataViewV2(
	ctx context.Context,
	request catalogsemantic.WatchRequest,
) (*AppMetadataV2Watch, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return nil, err
	}
	wireRequest, err := mapping.ToWireAppMetadataV2WatchRequest(
		callCtx,
		request,
	)
	if err != nil {
		cancel()
		return nil, err
	}
	stream, err := c.catalog.WatchAppMetadataViewV2(
		c.workloadDataContext(
			callCtx,
			catalogsemantic.AppMetadataV2CapabilityName,
		),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		cancel()
		return nil, mapping.FromPlatformStatusError(
			err,
			catalogsemantic.AppMetadataV2CapabilityName,
		)
	}
	return &AppMetadataV2Watch{
		streamLifecycle: streamLifecycle{cancel: cancel},
		stream:          stream,
		state:           catalogsemantic.NewAppMetadataV2WatchState(request),
	}, nil
}

func (watch *AppMetadataV2Watch) Recv() (
	catalogsemantic.AppMetadataViewV2,
	error,
) {
	if watch == nil || watch.stream == nil {
		return catalogsemantic.AppMetadataViewV2{},
			&commonsemantic.Failure{
				Category: commonsemantic.FailureUnavailable,
			}
	}
	watch.mu.Lock()
	defer watch.mu.Unlock()
	if watch.closed {
		return catalogsemantic.AppMetadataViewV2{}, io.EOF
	}
	response, err := watch.stream.Recv()
	if errors.Is(err, io.EOF) {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataViewV2{}, io.EOF
	}
	if err != nil {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataViewV2{},
			mapping.FromPlatformStatusError(
				err,
				catalogsemantic.AppMetadataV2CapabilityName,
			)
	}
	view, err := mapping.FromWireWatchAppMetadataViewV2Response(response)
	if err == nil {
		err = watch.state.Observe(view)
	}
	if err != nil {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataViewV2{}, err
	}
	return view, nil
}

func (c *RuntimePlatformClient) GetAppMetadataViewV3(
	ctx context.Context,
	request catalogsemantic.GetRequest,
) (catalogsemantic.AppMetadataViewV3, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return catalogsemantic.AppMetadataViewV3{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireCatalogGetV3Request(callCtx, request)
	if err != nil {
		return catalogsemantic.AppMetadataViewV3{}, err
	}
	response, err := c.catalogV3.GetAppMetadataViewV3(
		c.workloadDataContext(callCtx, catalogsemantic.AppMetadataV3CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return catalogsemantic.AppMetadataViewV3{}, mapping.FromPlatformStatusError(
			err, catalogsemantic.AppMetadataV3CapabilityName,
		)
	}
	return mapping.FromWireGetAppMetadataViewV3Response(response)
}

func (c *RuntimePlatformClient) WatchAppMetadataViewV3(
	ctx context.Context,
	request catalogsemantic.WatchRequest,
) (*AppMetadataV3Watch, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return nil, err
	}
	wireRequest, err := mapping.ToWireAppMetadataV3WatchRequest(callCtx, request)
	if err != nil {
		cancel()
		return nil, err
	}
	stream, err := c.catalogV3.WatchAppMetadataViewV3(
		c.workloadDataContext(callCtx, catalogsemantic.AppMetadataV3CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		cancel()
		return nil, mapping.FromPlatformStatusError(err, catalogsemantic.AppMetadataV3CapabilityName)
	}
	return &AppMetadataV3Watch{
		streamLifecycle: streamLifecycle{cancel: cancel},
		stream:          stream, state: catalogsemantic.NewAppMetadataV3WatchState(request),
	}, nil
}

func (watch *AppMetadataV3Watch) Recv() (catalogsemantic.AppMetadataViewV3, error) {
	if watch == nil || watch.stream == nil {
		return catalogsemantic.AppMetadataViewV3{}, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	watch.mu.Lock()
	defer watch.mu.Unlock()
	if watch.closed {
		return catalogsemantic.AppMetadataViewV3{}, io.EOF
	}
	response, err := watch.stream.Recv()
	if errors.Is(err, io.EOF) {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataViewV3{}, io.EOF
	}
	if err != nil {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataViewV3{}, mapping.FromPlatformStatusError(err, catalogsemantic.AppMetadataV3CapabilityName)
	}
	view, err := mapping.FromWireWatchAppMetadataViewV3Response(response)
	if err == nil {
		err = watch.state.Observe(view)
	}
	if err != nil {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.AppMetadataViewV3{}, err
	}
	return view, nil
}

func (c *RuntimePlatformClient) GetIntegrationBindingView(ctx context.Context, request catalogsemantic.GetRequest) (catalogsemantic.IntegrationBindingView, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return catalogsemantic.IntegrationBindingView{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireIntegrationBindingGetRequest(callCtx, request)
	if err != nil {
		return catalogsemantic.IntegrationBindingView{}, err
	}
	response, err := c.catalog.GetIntegrationBindingView(
		c.workloadDataContext(callCtx, catalogsemantic.IntegrationBindingCapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return catalogsemantic.IntegrationBindingView{}, mapping.FromPlatformStatusError(err, catalogsemantic.IntegrationBindingCapabilityName)
	}
	return mapping.FromWireGetIntegrationBindingViewResponse(response)
}

func (c *RuntimePlatformClient) WatchIntegrationBindingView(
	ctx context.Context,
	request catalogsemantic.WatchRequest,
) (*IntegrationBindingWatch, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return nil, err
	}
	wireRequest, err := mapping.ToWireIntegrationBindingWatchRequest(callCtx, request)
	if err != nil {
		cancel()
		return nil, err
	}
	stream, err := c.catalog.WatchIntegrationBindingView(
		c.workloadDataContext(callCtx, catalogsemantic.IntegrationBindingCapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		cancel()
		return nil, mapping.FromPlatformStatusError(err, catalogsemantic.IntegrationBindingCapabilityName)
	}
	return &IntegrationBindingWatch{
		streamLifecycle: streamLifecycle{cancel: cancel},
		stream:          stream,
		state:           catalogsemantic.NewIntegrationBindingWatchState(request),
	}, nil
}

func (watch *IntegrationBindingWatch) Recv() (catalogsemantic.IntegrationBindingView, error) {
	if watch == nil || watch.stream == nil {
		return catalogsemantic.IntegrationBindingView{}, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	watch.mu.Lock()
	defer watch.mu.Unlock()
	if watch.closed {
		return catalogsemantic.IntegrationBindingView{}, io.EOF
	}
	response, err := watch.stream.Recv()
	if errors.Is(err, io.EOF) {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.IntegrationBindingView{}, io.EOF
	}
	if err != nil {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.IntegrationBindingView{}, mapping.FromPlatformStatusError(err, catalogsemantic.IntegrationBindingCapabilityName)
	}
	view, err := mapping.FromWireWatchIntegrationBindingViewResponse(response)
	if err == nil {
		err = watch.state.Observe(view)
	}
	if err != nil {
		watch.closed = true
		watch.Cancel()
		return catalogsemantic.IntegrationBindingView{}, err
	}
	return view, nil
}

func (c *RuntimePlatformClient) Search(ctx context.Context, bearer string, request searchsemantic.Request) (searchsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, searchsemantic.CapabilityName)
	if err != nil {
		return searchsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireSearchRequest(callCtx, request)
	if err != nil {
		return searchsemantic.Response{}, err
	}
	response, err := c.search.SearchRecords(
		c.dataContext(callCtx, searchsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return searchsemantic.Response{}, mapping.FromPlatformStatusError(err, searchsemantic.CapabilityName)
	}
	return mapping.FromWireSearchResponse(request, response)
}

func (c *RuntimePlatformClient) ReadPrivateListViews(ctx context.Context, bearer string, request listviewsemantic.ReadRequest) (listviewsemantic.ReadResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, listviewsemantic.CapabilityName)
	if err != nil {
		return listviewsemantic.ReadResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadPrivateListViewsRequest(callCtx, request)
	if err != nil {
		return listviewsemantic.ReadResponse{}, err
	}
	response, err := c.listViews.ReadPrivateListViews(
		c.dataContext(callCtx, listviewsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return listviewsemantic.ReadResponse{}, mapping.FromPlatformStatusError(err, listviewsemantic.CapabilityName)
	}
	return mapping.FromWireReadPrivateListViewsResponse(request, response)
}

func (c *RuntimePlatformClient) MutatePrivateListView(ctx context.Context, bearer string, request listviewsemantic.MutateRequest) (listviewsemantic.MutateResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, listviewsemantic.CapabilityName)
	if err != nil {
		return listviewsemantic.MutateResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireMutatePrivateListViewRequest(callCtx, request)
	if err != nil {
		return listviewsemantic.MutateResponse{}, err
	}
	response, err := c.listViews.MutatePrivateListView(
		c.dataContext(callCtx, listviewsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return listviewsemantic.MutateResponse{}, mapping.FromPlatformStatusError(err, listviewsemantic.CapabilityName)
	}
	return mapping.FromWireMutatePrivateListViewResponse(request, response)
}

// ReadObjectAdminIndex returns one bounded stored-metadata administration
// index. Product route and DTO projection remain outside the transport host.
func (c *RuntimePlatformClient) ReadObjectAdminIndex(
	ctx context.Context,
	bearer string,
	request metadataadminsemantic.ObjectAdminIndexRequest,
) (metadataadminsemantic.ObjectAdminIndexResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, metadataadminsemantic.CapabilityName)
	if err != nil {
		return metadataadminsemantic.ObjectAdminIndexResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadObjectAdminIndexRequest(callCtx, request)
	if err != nil {
		return metadataadminsemantic.ObjectAdminIndexResponse{}, err
	}
	response, err := c.metadataAdminReads.ReadObjectAdminIndex(
		c.dataContext(callCtx, metadataadminsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return metadataadminsemantic.ObjectAdminIndexResponse{}, mapping.FromPlatformStatusError(err, metadataadminsemantic.CapabilityName)
	}
	return mapping.FromWireReadObjectAdminIndexResponse(request, response)
}

// ReadLayoutAdminWorkspace returns the stored-layout index and assignment
// routing rows for one object in a single coarse Runtime call.
func (c *RuntimePlatformClient) ReadLayoutAdminWorkspace(
	ctx context.Context,
	bearer string,
	request metadataadminsemantic.LayoutAdminWorkspaceRequest,
) (metadataadminsemantic.LayoutAdminWorkspaceResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, metadataadminsemantic.CapabilityName)
	if err != nil {
		return metadataadminsemantic.LayoutAdminWorkspaceResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadLayoutAdminWorkspaceRequest(callCtx, request)
	if err != nil {
		return metadataadminsemantic.LayoutAdminWorkspaceResponse{}, err
	}
	response, err := c.metadataAdminReads.ReadLayoutAdminWorkspace(
		c.dataContext(callCtx, metadataadminsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return metadataadminsemantic.LayoutAdminWorkspaceResponse{}, mapping.FromPlatformStatusError(err, metadataadminsemantic.CapabilityName)
	}
	return mapping.FromWireReadLayoutAdminWorkspaceResponse(request, response)
}

// ReadStoredLayout returns the exact stored authoring document. It is not an
// effective presentation-layout query and performs no product projection.
func (c *RuntimePlatformClient) ReadStoredLayout(
	ctx context.Context,
	bearer string,
	request metadataadminsemantic.StoredLayoutRequest,
) (metadataadminsemantic.StoredLayoutResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, metadataadminsemantic.CapabilityName)
	if err != nil {
		return metadataadminsemantic.StoredLayoutResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadStoredLayoutRequest(callCtx, request)
	if err != nil {
		return metadataadminsemantic.StoredLayoutResponse{}, err
	}
	response, err := c.metadataAdminReads.ReadStoredLayout(
		c.dataContext(callCtx, metadataadminsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return metadataadminsemantic.StoredLayoutResponse{}, mapping.FromPlatformStatusError(err, metadataadminsemantic.CapabilityName)
	}
	return mapping.FromWireReadStoredLayoutResponse(request, response)
}

// ReadValidationRuleAdminIndex returns the bounded stored validation-rule facts
// for one object. Product query grammar and response projection remain outside
// the transport host.
func (c *RuntimePlatformClient) ReadValidationRuleAdminIndex(
	ctx context.Context,
	bearer string,
	request metadataadminsemantic.ValidationRuleAdminIndexRequest,
) (metadataadminsemantic.ValidationRuleAdminIndexResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, metadataadminsemantic.CapabilityName)
	if err != nil {
		return metadataadminsemantic.ValidationRuleAdminIndexResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadValidationRuleAdminIndexRequest(callCtx, request)
	if err != nil {
		return metadataadminsemantic.ValidationRuleAdminIndexResponse{}, err
	}
	response, err := c.metadataAdminReads.ReadValidationRuleAdminIndex(
		c.dataContext(callCtx, metadataadminsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return metadataadminsemantic.ValidationRuleAdminIndexResponse{}, mapping.FromPlatformStatusError(err, metadataadminsemantic.CapabilityName)
	}
	return mapping.FromWireReadValidationRuleAdminIndexResponse(request, response)
}

// ReadApprovalNotificationFlows returns the bounded descriptor catalog that
// Runtime has already proven eligible for approval notifications. Flow
// definitions and product response projection remain outside the host.
func (c *RuntimePlatformClient) ReadApprovalNotificationFlows(
	ctx context.Context,
	bearer string,
	request approvalnotificationsemantic.Request,
) (approvalnotificationsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, approvalnotificationsemantic.CapabilityName)
	if err != nil {
		return approvalnotificationsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadApprovalNotificationFlowsRequest(callCtx, request)
	if err != nil {
		return approvalnotificationsemantic.Response{}, err
	}
	response, err := c.approvalFlowReads.ReadApprovalNotificationFlows(
		c.dataContext(callCtx, approvalnotificationsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return approvalnotificationsemantic.Response{}, mapping.FromPlatformStatusError(
			err,
			approvalnotificationsemantic.CapabilityName,
		)
	}
	return mapping.FromWireReadApprovalNotificationFlowsResponse(request, response)
}

// ResolvePageLayout returns the one caller-effective neutral PageLayout. The
// bearer is exchanged for a delegated Runtime identity; Profile and Role never
// enter the request payload.
func (c *RuntimePlatformClient) ResolvePageLayout(
	ctx context.Context,
	bearer string,
	request pagelayoutsemantic.Request,
) (pagelayoutsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, pagelayoutsemantic.CapabilityName)
	if err != nil {
		return pagelayoutsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireResolvePageLayoutRequest(callCtx, request)
	if err != nil {
		return pagelayoutsemantic.Response{}, err
	}
	response, err := c.pageLayouts.ResolvePageLayout(
		c.dataContext(callCtx, pagelayoutsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return pagelayoutsemantic.Response{}, mapping.FromPlatformStatusError(
			err,
			pagelayoutsemantic.CapabilityName,
		)
	}
	return mapping.FromWireResolvePageLayoutResponse(request, response)
}

// ReadObjectListFields returns the current tenant-owned ordered ListFields for
// a bounded object set. It shares PageLayout serving admission and does not
// read or refresh Catalog metadata.
func (c *RuntimePlatformClient) ReadObjectListFields(
	ctx context.Context,
	bearer string,
	request pagelayoutsemantic.ObjectListFieldsRequest,
) (pagelayoutsemantic.ObjectListFieldsResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, pagelayoutsemantic.CapabilityName)
	if err != nil {
		return pagelayoutsemantic.ObjectListFieldsResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadObjectListFieldsRequest(callCtx, request)
	if err != nil {
		return pagelayoutsemantic.ObjectListFieldsResponse{}, err
	}
	response, err := c.pageLayouts.ReadObjectListFields(
		c.dataContext(callCtx, pagelayoutsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return pagelayoutsemantic.ObjectListFieldsResponse{}, mapping.FromPlatformStatusError(
			err,
			pagelayoutsemantic.CapabilityName,
		)
	}
	return mapping.FromWireReadObjectListFieldsResponse(request, response)
}

func (c *RuntimePlatformClient) ReadSearchScopeOrder(
	ctx context.Context,
	bearer string,
	request searchsemantic.ScopeOrderRequest,
) (searchsemantic.ScopeOrderResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(
		ctx, bearer, searchsemantic.CapabilityName,
	)
	if err != nil {
		return searchsemantic.ScopeOrderResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireSearchScopeOrderRequest(callCtx, request)
	if err != nil {
		return searchsemantic.ScopeOrderResponse{}, err
	}
	response, err := c.search.ReadSearchScopeOrder(
		c.dataContext(callCtx, searchsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return searchsemantic.ScopeOrderResponse{}, mapping.FromPlatformStatusError(
			err, searchsemantic.CapabilityName,
		)
	}
	return mapping.FromWireSearchScopeOrderResponse(request, response)
}

func (c *RuntimePlatformClient) ExecuteFlow(ctx context.Context, bearer string, request flowsemantic.Request) (flowsemantic.Response, error) {
	return c.executeFlowWithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV2CapabilityName,
	)
}

// ExecuteFlowWithAppMetadataV3 preserves ExecuteFlow's N-1 V2 authority while
// allowing consumers that explicitly require the complete V3 Catalog view to
// select that capability. Both methods invoke the same neutral Runtime RPC.
func (c *RuntimePlatformClient) ExecuteFlowWithAppMetadataV3(ctx context.Context, bearer string, request flowsemantic.Request) (flowsemantic.Response, error) {
	return c.executeFlowWithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV3CapabilityName,
	)
}

// ExecuteFlowV2 returns the exclusive success-or-caller-visible-rejection
// result. Infrastructure, authorization, and non-presentable Runtime failures
// remain errors. Existing ExecuteFlow methods retain their success-only
// response contract for source compatibility.
func (c *RuntimePlatformClient) ExecuteFlowV2(
	ctx context.Context,
	bearer string,
	request flowsemantic.Request,
) (flowsemantic.ResponseV2, error) {
	return c.executeFlowV2WithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV2CapabilityName,
	)
}

// ExecuteFlowV2WithAppMetadataV3 is ExecuteFlowV2 with the complete V3 Catalog
// view selected for the request-scoped Runtime authority union.
func (c *RuntimePlatformClient) ExecuteFlowV2WithAppMetadataV3(
	ctx context.Context,
	bearer string,
	request flowsemantic.Request,
) (flowsemantic.ResponseV2, error) {
	return c.executeFlowV2WithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV3CapabilityName,
	)
}

func (c *RuntimePlatformClient) executeFlowV2WithMetadataCapability(
	ctx context.Context,
	bearer string,
	request flowsemantic.Request,
	metadataCapability string,
) (flowsemantic.ResponseV2, error) {
	callCtx, cancel, err := c.authorizedFlowAttempt(ctx, bearer, metadataCapability)
	if err != nil {
		return flowsemantic.ResponseV2{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireExecuteFlowRequest(callCtx, request)
	if err != nil {
		return flowsemantic.ResponseV2{}, err
	}
	response, err := c.flow.ExecuteFlow(
		c.dataContext(callCtx, flowsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return flowsemantic.ResponseV2{}, mapping.FromPlatformStatusError(err, flowsemantic.CapabilityName)
	}
	return mapping.FromWireExecuteFlowResponseV2(response)
}

func (c *RuntimePlatformClient) executeFlowWithMetadataCapability(ctx context.Context, bearer string, request flowsemantic.Request, metadataCapability string) (flowsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedFlowAttempt(ctx, bearer, metadataCapability)
	if err != nil {
		return flowsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireExecuteFlowRequest(callCtx, request)
	if err != nil {
		return flowsemantic.Response{}, err
	}
	response, err := c.flow.ExecuteFlow(
		c.dataContext(callCtx, flowsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return flowsemantic.Response{}, mapping.FromPlatformStatusError(err, flowsemantic.CapabilityName)
	}
	return mapping.FromWireExecuteFlowResponse(response)
}

// ExecuteCatalogAction invokes the Catalog-selected action profile on the
// existing ExecuteFlow RPC. The caller supplies only immutable Catalog action
// identity; Runtime derives the exact Flow identity from that revision.
func (c *RuntimePlatformClient) ExecuteCatalogAction(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionRequest,
) (flowsemantic.Response, error) {
	return c.executeCatalogActionWithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV2CapabilityName,
	)
}

func (c *RuntimePlatformClient) ExecuteCatalogActionWithAppMetadataV3(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionRequest,
) (flowsemantic.Response, error) {
	return c.executeCatalogActionWithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV3CapabilityName,
	)
}

// ExecuteCatalogActionV2 returns the exclusive success-or-caller-visible-
// rejection result for a Catalog-selected action. Existing success-only
// methods remain unchanged for source compatibility.
func (c *RuntimePlatformClient) ExecuteCatalogActionV2(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionRequest,
) (flowsemantic.ResponseV2, error) {
	return c.executeCatalogActionV2WithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV2CapabilityName,
	)
}

// ExecuteCatalogActionV2WithAppMetadataV3 is ExecuteCatalogActionV2 with the
// complete V3 Catalog view selected for the request-scoped Runtime authority
// union.
func (c *RuntimePlatformClient) ExecuteCatalogActionV2WithAppMetadataV3(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionRequest,
) (flowsemantic.ResponseV2, error) {
	return c.executeCatalogActionV2WithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV3CapabilityName,
	)
}

func (c *RuntimePlatformClient) executeCatalogActionV2WithMetadataCapability(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionRequest,
	metadataCapability string,
) (flowsemantic.ResponseV2, error) {
	callCtx, cancel, err := c.authorizedFlowAttempt(ctx, bearer, metadataCapability)
	if err != nil {
		return flowsemantic.ResponseV2{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireExecuteCatalogActionRequest(callCtx, request)
	if err != nil {
		return flowsemantic.ResponseV2{}, err
	}
	response, err := c.flow.ExecuteFlow(
		c.dataContext(callCtx, flowsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return flowsemantic.ResponseV2{}, mapping.FromPlatformStatusError(err, flowsemantic.CapabilityName)
	}
	return mapping.FromWireExecuteFlowResponseV2(response)
}

func (c *RuntimePlatformClient) executeCatalogActionWithMetadataCapability(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionRequest,
	metadataCapability string,
) (flowsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedFlowAttempt(ctx, bearer, metadataCapability)
	if err != nil {
		return flowsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireExecuteCatalogActionRequest(callCtx, request)
	if err != nil {
		return flowsemantic.Response{}, err
	}
	response, err := c.flow.ExecuteFlow(
		c.dataContext(callCtx, flowsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return flowsemantic.Response{}, mapping.FromPlatformStatusError(err, flowsemantic.CapabilityName)
	}
	return mapping.FromWireExecuteFlowResponse(response)
}

// PreviewCatalogAction evaluates one immutable Catalog-selected action through
// Runtime's existing no-effect Flow preview profiles.
func (c *RuntimePlatformClient) PreviewCatalogAction(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionPreviewRequest,
) (flowsemantic.CatalogActionPreviewResponse, error) {
	return c.previewCatalogActionWithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV2CapabilityName,
	)
}

func (c *RuntimePlatformClient) PreviewCatalogActionWithAppMetadataV3(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionPreviewRequest,
) (flowsemantic.CatalogActionPreviewResponse, error) {
	return c.previewCatalogActionWithMetadataCapability(
		ctx, bearer, request, catalogsemantic.AppMetadataV3CapabilityName,
	)
}

func (c *RuntimePlatformClient) previewCatalogActionWithMetadataCapability(
	ctx context.Context,
	bearer string,
	request flowsemantic.CatalogActionPreviewRequest,
	metadataCapability string,
) (flowsemantic.CatalogActionPreviewResponse, error) {
	callCtx, cancel, err := c.authorizedFlowAttempt(ctx, bearer, metadataCapability)
	if err != nil {
		return flowsemantic.CatalogActionPreviewResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWirePreviewCatalogActionRequest(callCtx, request)
	if err != nil {
		return flowsemantic.CatalogActionPreviewResponse{}, err
	}
	response, err := c.flow.PreviewCatalogAction(
		c.dataContext(callCtx, flowsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return flowsemantic.CatalogActionPreviewResponse{}, mapping.FromPlatformStatusError(
			err, flowsemantic.CapabilityName,
		)
	}
	return mapping.FromWirePreviewCatalogActionResponse(request, response)
}

func (c *RuntimePlatformClient) ReadReport(ctx context.Context, bearer string, request reportsemantic.Request) (reportsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, reportsemantic.CapabilityName)
	if err != nil {
		return reportsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadReportRequest(callCtx, request)
	if err != nil {
		return reportsemantic.Response{}, err
	}
	response, err := c.report.ReadReport(
		c.dataContext(callCtx, reportsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return reportsemantic.Response{}, mapping.FromPlatformStatusError(err, reportsemantic.CapabilityName)
	}
	return mapping.FromWireReadReportResponse(response)
}

// ReadAuditLog reads one bounded privileged page through the delegated-user
// transport. Product route grammar and response projection remain L1-owned.
func (c *RuntimePlatformClient) ReadAuditLog(
	ctx context.Context,
	bearer string,
	request auditsemantic.Request,
) (auditsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, auditsemantic.CapabilityName)
	if err != nil {
		return auditsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadAuditLogRequest(callCtx, request)
	if err != nil {
		return auditsemantic.Response{}, err
	}
	response, err := c.auditLog.ReadAuditLog(
		c.dataContext(callCtx, auditsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return auditsemantic.Response{}, mapping.FromPlatformStatusError(err, auditsemantic.CapabilityName)
	}
	return mapping.FromWireReadAuditLogResponse(request, response)
}

// ExecuteApproval invokes the existing L0 approval engine through the neutral
// lifecycle capability on this client's one private Runtime target.
func (c *RuntimePlatformClient) ExecuteApproval(
	ctx context.Context,
	bearer string,
	request approvalsemantic.ExecuteRequest,
) (approvalsemantic.ExecuteResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(
		ctx, bearer, approvalsemantic.ExecuteCapabilityName,
	)
	if err != nil {
		return approvalsemantic.ExecuteResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireExecuteApprovalRequest(callCtx, request)
	if err != nil {
		return approvalsemantic.ExecuteResponse{}, err
	}
	response, err := c.approvals.ExecuteApproval(
		c.dataContext(callCtx, approvalsemantic.ExecuteCapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return approvalsemantic.ExecuteResponse{}, mapping.FromPlatformStatusError(
			err, approvalsemantic.ExecuteCapabilityName,
		)
	}
	return mapping.FromWireExecuteApprovalResponse(request, response)
}

// ReadApproval reads the caller-scoped approval lifecycle projection from the
// same private Runtime target and preserves its revision/generation receipts.
func (c *RuntimePlatformClient) ReadApproval(
	ctx context.Context,
	bearer string,
	request approvalsemantic.ReadRequest,
) (approvalsemantic.ReadResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(
		ctx, bearer, approvalsemantic.ReadCapabilityName,
	)
	if err != nil {
		return approvalsemantic.ReadResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadApprovalRequest(callCtx, request)
	if err != nil {
		return approvalsemantic.ReadResponse{}, err
	}
	response, err := c.approvals.ReadApproval(
		c.dataContext(callCtx, approvalsemantic.ReadCapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return approvalsemantic.ReadResponse{}, mapping.FromPlatformStatusError(
			err, approvalsemantic.ReadCapabilityName,
		)
	}
	return mapping.FromWireReadApprovalResponse(request, response)
}

func (c *RuntimePlatformClient) BeginCreateFile(
	ctx context.Context,
	bearer string,
	header filessemantic.CreateHeader,
) (*RuntimeFileUpload, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, filessemantic.CapabilityName)
	if err != nil {
		return nil, err
	}
	stream, err := c.files.CreateFile(
		c.dataContext(callCtx, filessemantic.CapabilityName),
		platformCallOptions()...,
	)
	if err != nil {
		cancel()
		return nil, mapping.FromPlatformStatusError(err, filessemantic.CapabilityName)
	}
	state, err := filessemantic.NewCreateStreamState(callCtx)
	if err != nil {
		cancel()
		return nil, err
	}
	firstChunk := filessemantic.CreateChunk{Header: &header}
	if err := state.Observe(firstChunk); err != nil {
		cancel()
		return nil, err
	}
	first, err := mapping.ToWireCreateFileChunk(firstChunk)
	if err != nil {
		cancel()
		return nil, err
	}
	if err := stream.Send(first); err != nil {
		err = uploadSendFailure(err, stream.CloseAndRecv)
		cancel()
		return nil, mapping.FromPlatformStatusError(err, filessemantic.CapabilityName)
	}
	return &RuntimeFileUpload{
		streamLifecycle: streamLifecycle{cancel: cancel},
		stream:          stream,
		state:           state,
	}, nil
}

func (upload *RuntimeFileUpload) Send(data []byte) error {
	if upload == nil || upload.stream == nil || upload.state == nil {
		return &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	upload.mu.Lock()
	defer upload.mu.Unlock()
	if upload.closed {
		return errors.New("runtime Platform client: file upload is closed")
	}
	chunk := filessemantic.CreateChunk{Data: append([]byte(nil), data...)}
	if err := upload.state.Observe(chunk); err != nil {
		upload.closed = true
		upload.Cancel()
		return err
	}
	wireChunk, err := mapping.ToWireCreateFileChunk(chunk)
	if err != nil {
		upload.closed = true
		upload.Cancel()
		return err
	}
	if err := upload.stream.Send(wireChunk); err != nil {
		err = uploadSendFailure(err, upload.stream.CloseAndRecv)
		upload.closed = true
		upload.Cancel()
		return mapping.FromPlatformStatusError(err, filessemantic.CapabilityName)
	}
	return nil
}

func (upload *RuntimeFileUpload) CloseAndRecv() (filessemantic.CreateResponse, error) {
	if upload == nil || upload.stream == nil || upload.state == nil {
		return filessemantic.CreateResponse{}, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	upload.mu.Lock()
	defer upload.mu.Unlock()
	if upload.closed {
		return filessemantic.CreateResponse{}, errors.New("runtime Platform client: file upload is closed")
	}
	if err := upload.state.Complete(); err != nil {
		upload.closed = true
		upload.Cancel()
		return filessemantic.CreateResponse{}, err
	}
	upload.closed = true
	response, err := upload.stream.CloseAndRecv()
	upload.Cancel()
	if err != nil {
		return filessemantic.CreateResponse{}, mapping.FromPlatformStatusError(err, filessemantic.CapabilityName)
	}
	return mapping.FromWireCreateFileResponse(response)
}

func (c *RuntimePlatformClient) OpenFile(
	ctx context.Context,
	bearer string,
	request filessemantic.OpenRequest,
) (*RuntimeFileDownload, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, filessemantic.CapabilityName)
	if err != nil {
		return nil, err
	}
	wireRequest, err := mapping.ToWireOpenFileRequest(callCtx, request)
	if err != nil {
		cancel()
		return nil, err
	}
	stream, err := c.files.OpenFile(
		c.dataContext(callCtx, filessemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		cancel()
		return nil, mapping.FromPlatformStatusError(err, filessemantic.CapabilityName)
	}
	return &RuntimeFileDownload{
		streamLifecycle: streamLifecycle{cancel: cancel},
		stream:          stream,
		state:           &filessemantic.OpenStreamState{},
	}, nil
}

func (download *RuntimeFileDownload) Recv() (filessemantic.OpenChunk, error) {
	if download == nil || download.stream == nil || download.state == nil {
		return filessemantic.OpenChunk{}, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	download.mu.Lock()
	defer download.mu.Unlock()
	if download.closed {
		return filessemantic.OpenChunk{}, io.EOF
	}
	wireChunk, err := download.stream.Recv()
	if errors.Is(err, io.EOF) {
		download.closed = true
		download.Cancel()
		if err := download.state.Complete(); err != nil {
			return filessemantic.OpenChunk{}, err
		}
		return filessemantic.OpenChunk{}, io.EOF
	}
	if err != nil {
		download.closed = true
		download.Cancel()
		return filessemantic.OpenChunk{}, mapping.FromPlatformStatusError(err, filessemantic.CapabilityName)
	}
	chunk, err := mapping.FromWireOpenFileChunk(wireChunk)
	if err == nil {
		err = download.state.Observe(chunk)
	}
	if err != nil {
		download.closed = true
		download.Cancel()
		return filessemantic.OpenChunk{}, err
	}
	return chunk, nil
}

func (c *RuntimePlatformClient) DeleteFile(ctx context.Context, bearer string, request filessemantic.DeleteRequest) (filessemantic.DeleteResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, filessemantic.CapabilityName)
	if err != nil {
		return filessemantic.DeleteResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireDeleteFileRequest(callCtx, request)
	if err != nil {
		return filessemantic.DeleteResponse{}, err
	}
	response, err := c.files.DeleteFile(
		c.dataContext(callCtx, filessemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return filessemantic.DeleteResponse{}, mapping.FromPlatformStatusError(err, filessemantic.CapabilityName)
	}
	return mapping.FromWireDeleteFileResponse(response)
}

func (c *RuntimePlatformClient) CreateBulkIngestJob(ctx context.Context, bearer string, request bulkingestsemantic.CreateRequest) (bulkingestsemantic.CreateResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, bulkingestsemantic.CapabilityName)
	if err != nil {
		return bulkingestsemantic.CreateResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireCreateBulkIngestJobRequest(callCtx, request)
	if err != nil {
		return bulkingestsemantic.CreateResponse{}, err
	}
	response, err := c.bulkIngest.CreateBulkIngestJob(c.dataContext(callCtx, bulkingestsemantic.CapabilityName), wireRequest, platformCallOptions()...)
	if err != nil {
		return bulkingestsemantic.CreateResponse{}, mapping.FromPlatformStatusError(err, bulkingestsemantic.CapabilityName)
	}
	return mapping.FromWireCreateBulkIngestJobResponse(request, response)
}

func (c *RuntimePlatformClient) ReadBulkIngestJob(ctx context.Context, bearer string, request bulkingestsemantic.ReadRequest) (bulkingestsemantic.ReadResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, bulkingestsemantic.CapabilityName)
	if err != nil {
		return bulkingestsemantic.ReadResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadBulkIngestJobRequest(callCtx, request)
	if err != nil {
		return bulkingestsemantic.ReadResponse{}, err
	}
	response, err := c.bulkIngest.ReadBulkIngestJob(c.dataContext(callCtx, bulkingestsemantic.CapabilityName), wireRequest, platformCallOptions()...)
	if err != nil {
		return bulkingestsemantic.ReadResponse{}, mapping.FromPlatformStatusError(err, bulkingestsemantic.CapabilityName)
	}
	return mapping.FromWireReadBulkIngestJobResponse(request, response)
}

func (c *RuntimePlatformClient) CloseBulkIngestJob(ctx context.Context, bearer string, request bulkingestsemantic.CloseRequest) (bulkingestsemantic.CloseResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, bulkingestsemantic.CapabilityName)
	if err != nil {
		return bulkingestsemantic.CloseResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireCloseBulkIngestJobRequest(callCtx, request)
	if err != nil {
		return bulkingestsemantic.CloseResponse{}, err
	}
	response, err := c.bulkIngest.CloseBulkIngestJob(c.dataContext(callCtx, bulkingestsemantic.CapabilityName), wireRequest, platformCallOptions()...)
	if err != nil {
		return bulkingestsemantic.CloseResponse{}, mapping.FromPlatformStatusError(err, bulkingestsemantic.CapabilityName)
	}
	return mapping.FromWireCloseBulkIngestJobResponse(request, response)
}

func (c *RuntimePlatformClient) BeginBulkIngestUpload(ctx context.Context, bearer string, header bulkingestsemantic.UploadHeader) (*RuntimeBulkIngestUpload, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, bulkingestsemantic.CapabilityName)
	if err != nil {
		return nil, err
	}
	state, err := bulkingestsemantic.NewUploadStreamState(callCtx)
	if err != nil {
		cancel()
		return nil, err
	}
	first := bulkingestsemantic.UploadChunk{Header: &header}
	if err := state.Observe(first); err != nil {
		cancel()
		return nil, err
	}
	stream, err := c.bulkIngest.UploadBulkIngestData(c.dataContext(callCtx, bulkingestsemantic.CapabilityName), platformCallOptions()...)
	if err != nil {
		cancel()
		return nil, mapping.FromPlatformStatusError(err, bulkingestsemantic.CapabilityName)
	}
	wireFirst, err := mapping.ToWireUploadBulkIngestChunk(first)
	if err != nil {
		cancel()
		return nil, err
	}
	if err := stream.Send(wireFirst); err != nil {
		err = uploadSendFailure(err, stream.CloseAndRecv)
		cancel()
		return nil, mapping.FromPlatformStatusError(err, bulkingestsemantic.CapabilityName)
	}
	return &RuntimeBulkIngestUpload{streamLifecycle: streamLifecycle{cancel: cancel}, stream: stream, state: state, header: header}, nil
}

func (upload *RuntimeBulkIngestUpload) Send(data []byte) error {
	if upload == nil || upload.stream == nil || upload.state == nil {
		return &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	upload.mu.Lock()
	defer upload.mu.Unlock()
	if upload.closed {
		return &commonsemantic.Failure{Category: commonsemantic.FailureInvalidRequest}
	}
	chunk := bulkingestsemantic.UploadChunk{Data: append([]byte(nil), data...)}
	if err := upload.state.Observe(chunk); err != nil {
		upload.closed = true
		upload.Cancel()
		return err
	}
	wireChunk, err := mapping.ToWireUploadBulkIngestChunk(chunk)
	if err != nil {
		upload.closed = true
		upload.Cancel()
		return err
	}
	if err := upload.stream.Send(wireChunk); err != nil {
		err = uploadSendFailure(err, upload.stream.CloseAndRecv)
		upload.closed = true
		upload.Cancel()
		return mapping.FromPlatformStatusError(err, bulkingestsemantic.CapabilityName)
	}
	return nil
}

func (upload *RuntimeBulkIngestUpload) CloseAndRecv() (bulkingestsemantic.UploadResponse, error) {
	if upload == nil || upload.stream == nil || upload.state == nil {
		return bulkingestsemantic.UploadResponse{}, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	upload.mu.Lock()
	defer upload.mu.Unlock()
	if upload.closed {
		return bulkingestsemantic.UploadResponse{}, &commonsemantic.Failure{Category: commonsemantic.FailureInvalidRequest}
	}
	upload.closed = true
	defer upload.Cancel()
	if err := upload.state.Complete(); err != nil {
		return bulkingestsemantic.UploadResponse{}, err
	}
	response, err := upload.stream.CloseAndRecv()
	if err != nil {
		return bulkingestsemantic.UploadResponse{}, mapping.FromPlatformStatusError(err, bulkingestsemantic.CapabilityName)
	}
	return mapping.FromWireUploadBulkIngestResponse(upload.header, response)
}

func (c *RuntimePlatformClient) AcceptCommand(ctx context.Context, request commandsemantic.Request) (commandsemantic.Response, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return commandsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireAcceptCommandRequest(callCtx, request)
	if err != nil {
		return commandsemantic.Response{}, err
	}
	response, err := c.commands.AcceptCommand(
		c.workloadDataContext(callCtx, commandsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return commandsemantic.Response{}, mapping.FromPlatformStatusError(err, commandsemantic.CapabilityName)
	}
	return mapping.FromWireAcceptCommandResponse(request, response)
}

// GetApplicationResult reads only Runtime's immutable result authority for the
// exact CommandID and ExecutionRefDigest pair. A transport error is never
// converted into a terminal application disposition.
func (c *RuntimePlatformClient) GetApplicationResult(
	ctx context.Context,
	request applicationresultsemantic.GetResultRequest,
) (applicationresultsemantic.GetResultResponse, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return applicationresultsemantic.GetResultResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireGetApplicationResultRequest(callCtx, request)
	if err != nil {
		return applicationresultsemantic.GetResultResponse{}, err
	}
	response, err := c.results.GetApplicationResult(
		c.workloadDataContext(callCtx, applicationresultsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return applicationresultsemantic.GetResultResponse{}, mapping.FromPlatformStatusError(
			err,
			applicationresultsemantic.CapabilityName,
		)
	}
	return mapping.FromWireGetApplicationResultResponse(request, response)
}

// ClaimExternalEffects preserves the released N-1 client surface for callers
// connected to an N-1 Runtime. The D3 Runtime composition does not register
// this legacy service; new Integration code uses the outbound-intent methods.
// Deprecated: use ListPendingOutboundIntents and let Integration own provider
// dispatch state.
func (c *RuntimePlatformClient) ClaimExternalEffects(
	ctx context.Context,
	request externaleffectsemantic.ClaimRequest,
) (externaleffectsemantic.ClaimResponse, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return externaleffectsemantic.ClaimResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireClaimExternalEffectsRequest(callCtx, request)
	if err != nil {
		return externaleffectsemantic.ClaimResponse{}, err
	}
	response, err := c.externalEffects.ClaimExternalEffects(
		c.workloadDataContext(callCtx, externaleffectsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return externaleffectsemantic.ClaimResponse{}, mapping.FromPlatformStatusError(err, externaleffectsemantic.CapabilityName)
	}
	return mapping.FromWireClaimExternalEffectsResponse(request, response)
}

// CompleteExternalEffect preserves the released N-1 client surface. It is
// inert in the D3 candidate because that Runtime does not register the legacy
// service.
// Deprecated: use AcknowledgeOutboundIntent and CommitOutboundResult.
func (c *RuntimePlatformClient) CompleteExternalEffect(
	ctx context.Context,
	claim externaleffectsemantic.ClaimResponse,
	request externaleffectsemantic.CompleteRequest,
) (externaleffectsemantic.CompleteResponse, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return externaleffectsemantic.CompleteResponse{}, err
	}
	defer cancel()
	if err := externaleffectsemantic.ValidateCompleteRequestForClaim(callCtx, claim, request); err != nil {
		return externaleffectsemantic.CompleteResponse{}, err
	}
	wireRequest, err := mapping.ToWireCompleteExternalEffectRequest(callCtx, request)
	if err != nil {
		return externaleffectsemantic.CompleteResponse{}, err
	}
	response, err := c.externalEffects.CompleteExternalEffect(
		c.workloadDataContext(callCtx, externaleffectsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return externaleffectsemantic.CompleteResponse{}, mapping.FromPlatformStatusError(err, externaleffectsemantic.CapabilityName)
	}
	return mapping.FromWireCompleteExternalEffectResponse(request, response)
}

// ReadOutboundIntentGeneration reads only Runtime's durable scheduling cursor.
// A newer generation authorizes no work; it tells Integration to call the
// authoritative list method below.
func (c *RuntimePlatformClient) ReadOutboundIntentGeneration(
	ctx context.Context,
	request outboundintentsemantic.GenerationRequest,
) (outboundintentsemantic.GenerationResponse, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return outboundintentsemantic.GenerationResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadOutboundIntentGenerationRequest(callCtx, request)
	if err != nil {
		return outboundintentsemantic.GenerationResponse{}, err
	}
	response, err := c.outboundIntents.ReadOutboundIntentGeneration(
		c.workloadDataContext(callCtx, outboundintentsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return outboundintentsemantic.GenerationResponse{}, mapping.FromPlatformStatusError(
			err,
			outboundintentsemantic.CapabilityName,
		)
	}
	return mapping.FromWireReadOutboundIntentGenerationResponse(request, response)
}

// ListPendingOutboundIntents reads immutable provider-neutral intents. The
// Integration process must durably accept each intent before acknowledging it;
// provider dispatch state never crosses back into Runtime.
func (c *RuntimePlatformClient) ListPendingOutboundIntents(
	ctx context.Context,
	request outboundintentsemantic.ListRequest,
) (outboundintentsemantic.ListResponse, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return outboundintentsemantic.ListResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireListPendingOutboundIntentsRequest(callCtx, request)
	if err != nil {
		return outboundintentsemantic.ListResponse{}, err
	}
	response, err := c.outboundIntents.ListPendingOutboundIntents(
		c.workloadDataContext(callCtx, outboundintentsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return outboundintentsemantic.ListResponse{}, mapping.FromPlatformStatusError(err, outboundintentsemantic.CapabilityName)
	}
	return mapping.FromWireListPendingOutboundIntentsResponse(request, response)
}

func (c *RuntimePlatformClient) AcknowledgeOutboundIntent(
	ctx context.Context,
	request outboundintentsemantic.AcknowledgeRequest,
) (outboundintentsemantic.AcknowledgeResponse, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return outboundintentsemantic.AcknowledgeResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireAcknowledgeOutboundIntentRequest(callCtx, request)
	if err != nil {
		return outboundintentsemantic.AcknowledgeResponse{}, err
	}
	response, err := c.outboundIntents.AcknowledgeOutboundIntent(
		c.workloadDataContext(callCtx, outboundintentsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return outboundintentsemantic.AcknowledgeResponse{}, mapping.FromPlatformStatusError(err, outboundintentsemantic.CapabilityName)
	}
	return mapping.FromWireAcknowledgeOutboundIntentResponse(request, response)
}

// OpenOutboundMailAttachment consumes and verifies one intent-bound attachment
// stream before any provider call. The request cannot name an arbitrary file;
// Runtime resolves the index from the exact accepted intent and command.
func (c *RuntimePlatformClient) OpenOutboundMailAttachment(
	ctx context.Context,
	request outboundintentsemantic.OpenMailAttachmentRequest,
	expected outboundintentsemantic.MailAttachmentV1,
) (outboundintentsemantic.OpenedMailAttachment, error) {
	state, err := outboundintentsemantic.NewMailAttachmentStreamState(expected)
	if err != nil {
		return outboundintentsemantic.OpenedMailAttachment{}, err
	}
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return outboundintentsemantic.OpenedMailAttachment{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireOpenOutboundMailAttachmentRequest(callCtx, request)
	if err != nil {
		return outboundintentsemantic.OpenedMailAttachment{}, err
	}
	stream, err := c.outboundIntents.OpenOutboundMailAttachment(
		c.workloadDataContext(callCtx, outboundintentsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return outboundintentsemantic.OpenedMailAttachment{}, mapping.FromPlatformStatusError(err, outboundintentsemantic.CapabilityName)
	}
	var (
		result outboundintentsemantic.OpenedMailAttachment
		first  = true
		valid  bool
	)
	defer func() {
		if !valid {
			clearBytes(result.Data)
		}
	}()
	for {
		wireChunk, recvErr := stream.Recv()
		if recvErr == io.EOF {
			break
		}
		if recvErr != nil {
			return outboundintentsemantic.OpenedMailAttachment{}, mapping.FromPlatformStatusError(recvErr, outboundintentsemantic.CapabilityName)
		}
		chunk, mapErr := mapping.FromWireOpenOutboundMailAttachmentChunk(wireChunk)
		if mapErr != nil || state.Observe(chunk) != nil {
			return outboundintentsemantic.OpenedMailAttachment{}, &outboundintentsemantic.Failure{Category: commonsemantic.FailureInvalidRequest}
		}
		if first {
			if chunk.Receipts == nil {
				return outboundintentsemantic.OpenedMailAttachment{}, &outboundintentsemantic.Failure{Category: commonsemantic.FailureInvalidRequest}
			}
			result.FileName, result.ContentType = chunk.FileName, chunk.ContentType
			result.ContentLength, result.ContentDigest = chunk.ContentLength, chunk.ContentDigest
			result.Receipts = *chunk.Receipts
			result.Data = make([]byte, 0, chunk.ContentLength)
			first = false
		}
		result.Data = append(result.Data, chunk.Data...)
	}
	if err := state.Complete(); err != nil || first {
		return outboundintentsemantic.OpenedMailAttachment{}, &outboundintentsemantic.Failure{Category: commonsemantic.FailureInvalidRequest}
	}
	if err := outboundintentsemantic.ValidateOpenedMailAttachment(request, expected, result); err != nil {
		return outboundintentsemantic.OpenedMailAttachment{}, err
	}
	valid = true
	return result, nil
}

func clearBytes(data []byte) {
	for index := range data {
		data[index] = 0
	}
}

// CommitOutboundResult applies only Runtime's exact metadata-authorized local
// projection for an Integration command that has already completed provider
// I/O. Provider dispatch, retry and reconciliation remain Integration-owned.
func (c *RuntimePlatformClient) CommitOutboundResult(
	ctx context.Context,
	request outboundintentsemantic.CommitResultRequest,
) (outboundintentsemantic.CommitResultResponse, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return outboundintentsemantic.CommitResultResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireCommitOutboundResultRequest(callCtx, request)
	if err != nil {
		return outboundintentsemantic.CommitResultResponse{}, err
	}
	response, err := c.outboundIntents.CommitOutboundResult(
		c.workloadDataContext(callCtx, outboundintentsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return outboundintentsemantic.CommitResultResponse{}, mapping.FromPlatformStatusError(err, outboundintentsemantic.CapabilityName)
	}
	return mapping.FromWireCommitOutboundResultResponse(request, response)
}

// CommitOutboundNoEffect terminalizes one exact accepted Integration command
// without provider I/O or a Runtime metadata projection. Runtime admits only a
// closed reason under a trusted serving Catalog revision strictly newer than
// the immutable intent revision.
func (c *RuntimePlatformClient) CommitOutboundNoEffect(
	ctx context.Context,
	request outboundintentsemantic.CommitNoEffectRequest,
) (outboundintentsemantic.CommitNoEffectResponse, error) {
	callCtx, cancel, err := c.workloadAttempt(ctx)
	if err != nil {
		return outboundintentsemantic.CommitNoEffectResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireCommitOutboundNoEffectRequest(callCtx, request)
	if err != nil {
		return outboundintentsemantic.CommitNoEffectResponse{}, err
	}
	response, err := c.outboundNoEffect.CommitOutboundNoEffect(
		c.workloadDataContext(callCtx, outboundintentsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return outboundintentsemantic.CommitNoEffectResponse{}, mapping.FromPlatformStatusError(err, outboundintentsemantic.CapabilityName)
	}
	return mapping.FromWireCommitOutboundNoEffectResponse(request, response)
}

// ReadEffectivePermissions returns the Runtime-owned effective projection for
// the admitted principal or one Runtime-authorized target principal. The
// bearer establishes viewer authority; TargetPrincipalID never replaces it.
func (c *RuntimePlatformClient) ReadEffectivePermissions(
	ctx context.Context,
	bearer string,
	request permissionsemantic.Request,
) (permissionsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(
		ctx, bearer, permissionsemantic.CapabilityName,
	)
	if err != nil {
		return permissionsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadEffectivePermissionsRequest(callCtx, request)
	if err != nil {
		return permissionsemantic.Response{}, err
	}
	response, err := c.permissions.ReadEffectivePermissions(
		c.dataContext(callCtx, permissionsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return permissionsemantic.Response{}, mapping.FromPlatformStatusError(
			err, permissionsemantic.CapabilityName,
		)
	}
	return mapping.FromWireReadEffectivePermissionsResponseForRequest(request, response)
}

// ReadPermissionAdministration returns one bounded L0-owned permission catalog
// or PermissionSet grant family. Product route envelopes remain owned by L1.
func (c *RuntimePlatformClient) ReadPermissionAdministration(
	ctx context.Context,
	bearer string,
	request permissionadminsemantic.ReadRequest,
) (permissionadminsemantic.ReadResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, permissionadminsemantic.CapabilityName)
	if err != nil {
		return permissionadminsemantic.ReadResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadPermissionAdministrationRequest(callCtx, request)
	if err != nil {
		return permissionadminsemantic.ReadResponse{}, err
	}
	response, err := c.permissionAdmin.ReadPermissionAdministration(
		c.dataContext(callCtx, permissionadminsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return permissionadminsemantic.ReadResponse{}, mapping.FromPlatformStatusError(
			err, permissionadminsemantic.CapabilityName,
		)
	}
	return mapping.FromWireReadPermissionAdministrationResponse(request, response)
}

// MutatePermissionAdministration applies one bounded grant-family patch. The
// caller identity and administration authority come from Runtime admission,
// never from request fields.
func (c *RuntimePlatformClient) MutatePermissionAdministration(
	ctx context.Context,
	bearer string,
	request permissionadminsemantic.MutateRequest,
) (permissionadminsemantic.MutateResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, permissionadminsemantic.CapabilityName)
	if err != nil {
		return permissionadminsemantic.MutateResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireMutatePermissionAdministrationRequest(callCtx, request)
	if err != nil {
		return permissionadminsemantic.MutateResponse{}, err
	}
	response, err := c.permissionAdmin.MutatePermissionAdministration(
		c.dataContext(callCtx, permissionadminsemantic.CapabilityName),
		wireRequest,
		platformCallOptions()...,
	)
	if err != nil {
		return permissionadminsemantic.MutateResponse{}, mapping.FromPlatformStatusError(
			err, permissionadminsemantic.CapabilityName,
		)
	}
	return mapping.FromWireMutatePermissionAdministrationResponse(request, response)
}

// ReadPermissionAuthoringSnapshot returns the one coherent five-family stored
// permission image and compare token for a Profile or PermissionSet target.
// Runtime, not L1 or the transport host, resolves Profile identity and owns the
// canonical PermissionSet aggregate.
func (c *RuntimePlatformClient) ReadPermissionAuthoringSnapshot(
	ctx context.Context,
	bearer string,
	request permissionauthoringsemantic.SnapshotRequest,
) (permissionauthoringsemantic.SnapshotResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, permissionauthoringsemantic.CapabilityName)
	if err != nil {
		return permissionauthoringsemantic.SnapshotResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireReadPermissionAuthoringSnapshotRequest(callCtx, request)
	if err != nil {
		return permissionauthoringsemantic.SnapshotResponse{}, err
	}
	response, err := c.permissionAuthoring.ReadPermissionAuthoringSnapshot(
		c.dataContext(callCtx, permissionauthoringsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return permissionauthoringsemantic.SnapshotResponse{}, mapping.FromPlatformStatusError(
			err, permissionauthoringsemantic.CapabilityName,
		)
	}
	return mapping.FromWireReadPermissionAuthoringSnapshotResponse(request, response)
}

// SavePermissionAuthoring submits one atomic patch across all five permission
// families. A retry must reuse this exact request, including CommandID.
func (c *RuntimePlatformClient) SavePermissionAuthoring(
	ctx context.Context,
	bearer string,
	request permissionauthoringsemantic.Request,
) (permissionauthoringsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, permissionauthoringsemantic.CapabilityName)
	if err != nil {
		return permissionauthoringsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireSavePermissionAuthoringRequest(callCtx, request)
	if err != nil {
		return permissionauthoringsemantic.Response{}, err
	}
	response, err := c.permissionAuthoring.SavePermissionAuthoring(
		c.dataContext(callCtx, permissionauthoringsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return permissionauthoringsemantic.Response{}, mapping.FromPlatformStatusError(
			err, permissionauthoringsemantic.CapabilityName,
		)
	}
	return mapping.FromWireSavePermissionAuthoringResponse(request, response)
}

// GetPermissionAuthoringStatus reconciles an outcome-ambiguous Save against
// the original immutable request. Keeping the request here is intentional: a
// status payload that is self-consistent but belongs to another PermissionSet
// or revision must never become a successful Save result.
func (c *RuntimePlatformClient) GetPermissionAuthoringStatus(
	ctx context.Context,
	bearer string,
	request permissionauthoringsemantic.Request,
) (permissionauthoringsemantic.StatusResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, permissionauthoringsemantic.CapabilityName)
	if err != nil {
		return permissionauthoringsemantic.StatusResponse{}, err
	}
	defer cancel()
	statusRequest, err := permissionauthoringsemantic.StatusRequestFor(request)
	if err != nil {
		return permissionauthoringsemantic.StatusResponse{}, err
	}
	wireRequest, err := mapping.ToWireGetPermissionAuthoringStatusRequest(callCtx, statusRequest)
	if err != nil {
		return permissionauthoringsemantic.StatusResponse{}, err
	}
	response, err := c.permissionAuthoring.GetPermissionAuthoringStatus(
		c.dataContext(callCtx, permissionauthoringsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return permissionauthoringsemantic.StatusResponse{}, mapping.FromPlatformStatusError(
			err, permissionauthoringsemantic.CapabilityName,
		)
	}
	return mapping.FromWireGetPermissionAuthoringStatusResponseForRequest(request, response)
}

// ReadLayoutAuthoringV2Workspace reads the current database-owned workspace.
func (c *RuntimePlatformClient) ReadLayoutAuthoringV2Workspace(
	ctx context.Context,
	bearer string,
	request layoutauthoringv2semantic.WorkspaceRequest,
) (layoutauthoringv2semantic.WorkspaceResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, layoutauthoringv2semantic.CapabilityName)
	if err != nil {
		return layoutauthoringv2semantic.WorkspaceResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireLayoutAuthoringV2ReadWorkspaceRequest(callCtx, request)
	if err != nil {
		return layoutauthoringv2semantic.WorkspaceResponse{}, err
	}
	response, err := c.layoutAuthoringV2.ReadWorkspace(
		c.dataContext(callCtx, layoutauthoringv2semantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return layoutauthoringv2semantic.WorkspaceResponse{}, mapping.FromPlatformStatusError(err, layoutauthoringv2semantic.CapabilityName)
	}
	return mapping.FromWireLayoutAuthoringV2ReadWorkspaceResponse(request, response)
}

// ReadLayoutAuthoringV2StoredLayout reads one complete neutral Layout document
// and the object's ordered list fields from current database state.
func (c *RuntimePlatformClient) ReadLayoutAuthoringV2StoredLayout(
	ctx context.Context,
	bearer string,
	request layoutauthoringv2semantic.StoredLayoutRequest,
) (layoutauthoringv2semantic.StoredLayoutResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, layoutauthoringv2semantic.CapabilityName)
	if err != nil {
		return layoutauthoringv2semantic.StoredLayoutResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireLayoutAuthoringV2ReadStoredLayoutRequest(callCtx, request)
	if err != nil {
		return layoutauthoringv2semantic.StoredLayoutResponse{}, err
	}
	response, err := c.layoutAuthoringV2.ReadStoredLayout(
		c.dataContext(callCtx, layoutauthoringv2semantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return layoutauthoringv2semantic.StoredLayoutResponse{}, mapping.FromPlatformStatusError(err, layoutauthoringv2semantic.CapabilityName)
	}
	return mapping.FromWireLayoutAuthoringV2ReadStoredLayoutResponse(request, response)
}

// MutateLayoutAuthoringV2 applies one object-scoped Layout mutation in the
// Runtime transaction. A successful return means the change is committed.
func (c *RuntimePlatformClient) MutateLayoutAuthoringV2(
	ctx context.Context,
	bearer string,
	request layoutauthoringv2semantic.Request,
) (layoutauthoringv2semantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, layoutauthoringv2semantic.CapabilityName)
	if err != nil {
		return layoutauthoringv2semantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireLayoutAuthoringV2MutateRequest(callCtx, request)
	if err != nil {
		return layoutauthoringv2semantic.Response{}, err
	}
	response, err := c.layoutAuthoringV2.Mutate(
		c.dataContext(callCtx, layoutauthoringv2semantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return layoutauthoringv2semantic.Response{}, mapping.FromPlatformStatusError(err, layoutauthoringv2semantic.CapabilityName)
	}
	return mapping.FromWireLayoutAuthoringV2MutateResponse(request, response)
}

// SubmitLayoutAuthoring submits one typed durable Layout command. Transport
// ambiguity is reconciled through GetLayoutAuthoringCommand rather than by
// issuing a second mutation under a new identity.
func (c *RuntimePlatformClient) SubmitLayoutAuthoring(
	ctx context.Context,
	bearer string,
	request layoutauthoringsemantic.SubmitRequest,
) (layoutauthoringsemantic.SubmitResponse, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, layoutauthoringsemantic.CapabilityName)
	if err != nil {
		return layoutauthoringsemantic.SubmitResponse{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireLayoutAuthoringSubmitRequest(callCtx, request)
	if err != nil {
		return layoutauthoringsemantic.SubmitResponse{}, err
	}
	response, err := c.layoutAuthoring.Submit(
		c.dataContext(callCtx, layoutauthoringsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return layoutauthoringsemantic.SubmitResponse{}, mapping.FromPlatformStatusError(err, layoutauthoringsemantic.CapabilityName)
	}
	return mapping.FromWireLayoutAuthoringSubmitResponse(request, response)
}

// GetLayoutAuthoringCommand reads the durable status of one accepted Layout
// command by its immutable request identity.
func (c *RuntimePlatformClient) GetLayoutAuthoringCommand(
	ctx context.Context,
	bearer string,
	request layoutauthoringsemantic.GetCommandRequest,
) (layoutauthoringsemantic.CommandStatus, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, layoutauthoringsemantic.CapabilityName)
	if err != nil {
		return layoutauthoringsemantic.CommandStatus{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireLayoutAuthoringGetCommandRequest(callCtx, request)
	if err != nil {
		return layoutauthoringsemantic.CommandStatus{}, err
	}
	response, err := c.layoutAuthoring.GetCommand(
		c.dataContext(callCtx, layoutauthoringsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return layoutauthoringsemantic.CommandStatus{}, mapping.FromPlatformStatusError(err, layoutauthoringsemantic.CapabilityName)
	}
	return mapping.FromWireLayoutAuthoringCommandStatus(request, response)
}

// ReadLayoutAuthoringWorkspace reads one object-scoped stored Layout aggregate
// from an exact Catalog authoring view when the caller supplies a view ref.
func (c *RuntimePlatformClient) ReadLayoutAuthoringWorkspace(
	ctx context.Context,
	bearer string,
	request layoutauthoringsemantic.WorkspaceRequest,
) (layoutauthoringsemantic.Workspace, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, layoutauthoringsemantic.CapabilityName)
	if err != nil {
		return layoutauthoringsemantic.Workspace{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireLayoutAuthoringWorkspaceRequest(callCtx, request)
	if err != nil {
		return layoutauthoringsemantic.Workspace{}, err
	}
	response, err := c.layoutAuthoring.ReadWorkspace(
		c.dataContext(callCtx, layoutauthoringsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return layoutauthoringsemantic.Workspace{}, mapping.FromPlatformStatusError(err, layoutauthoringsemantic.CapabilityName)
	}
	return mapping.FromWireLayoutAuthoringWorkspace(request, response)
}

// ReadLayoutAuthoringStoredLayout reads one stored Layout without resolving it
// into caller-effective presentation behavior.
func (c *RuntimePlatformClient) ReadLayoutAuthoringStoredLayout(
	ctx context.Context,
	bearer string,
	request layoutauthoringsemantic.StoredLayoutRequest,
) (layoutauthoringsemantic.StoredLayout, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, layoutauthoringsemantic.CapabilityName)
	if err != nil {
		return layoutauthoringsemantic.StoredLayout{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireLayoutAuthoringStoredLayoutRequest(callCtx, request)
	if err != nil {
		return layoutauthoringsemantic.StoredLayout{}, err
	}
	response, err := c.layoutAuthoring.ReadStoredLayout(
		c.dataContext(callCtx, layoutauthoringsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return layoutauthoringsemantic.StoredLayout{}, mapping.FromPlatformStatusError(err, layoutauthoringsemantic.CapabilityName)
	}
	return mapping.FromWireLayoutAuthoringStoredLayout(request, response)
}

// MutateAnalyticsDefinition authors one saved report or dashboard through the
// Runtime-owned Records transaction boundary. L1 supplies only the neutral
// canonical definition and keeps all Salesforce route semantics local.
func (c *RuntimePlatformClient) MutateAnalyticsDefinition(
	ctx context.Context,
	bearer string,
	request analyticsauthoringsemantic.Request,
) (analyticsauthoringsemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, analyticsauthoringsemantic.CapabilityName)
	if err != nil {
		return analyticsauthoringsemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireMutateAnalyticsDefinitionRequest(callCtx, request)
	if err != nil {
		return analyticsauthoringsemantic.Response{}, err
	}
	response, err := c.analyticsAuthoring.MutateAnalyticsDefinition(
		c.dataContext(callCtx, analyticsauthoringsemantic.CapabilityName), wireRequest, platformCallOptions()...,
	)
	if err != nil {
		return analyticsauthoringsemantic.Response{}, mapping.FromPlatformStatusError(err, analyticsauthoringsemantic.CapabilityName)
	}
	return mapping.FromWireMutateAnalyticsDefinitionResponse(request, response)
}

func (c *RuntimePlatformClient) AccessResource(ctx context.Context, bearer string, request resourceaccesssemantic.Request) (resourceaccesssemantic.Response, error) {
	callCtx, cancel, err := c.authorizedAttempt(ctx, bearer, resourceaccesssemantic.CapabilityName)
	if err != nil {
		return resourceaccesssemantic.Response{}, err
	}
	defer cancel()
	wireRequest, err := mapping.ToWireResourceAccessRequest(callCtx, request)
	if err != nil {
		return resourceaccesssemantic.Response{}, err
	}
	response, err := c.resourceAccess.AccessResource(c.dataContext(callCtx, resourceaccesssemantic.CapabilityName), wireRequest, platformCallOptions()...)
	if err != nil {
		return resourceaccesssemantic.Response{}, mapping.FromPlatformStatusError(err, resourceaccesssemantic.CapabilityName)
	}
	return mapping.FromWireResourceAccessResponse(request, response)
}

func (c *RuntimePlatformClient) authorizedAttempt(ctx context.Context, bearer, capability string) (context.Context, context.CancelFunc, error) {
	return c.authorizedAttemptForCapabilities(ctx, bearer, []string{capability})
}

// authorizedFlowAttempt requests only the two neutral authorities Runtime
// needs to execute a revision-bound Flow. The public V2 and V3 client methods
// select their matching Catalog capability while sharing one coarse Flow RPC.
func (c *RuntimePlatformClient) authorizedFlowAttempt(ctx context.Context, bearer, metadataCapability string) (context.Context, context.CancelFunc, error) {
	return c.authorizedAttemptForCapabilities(ctx, bearer, []string{
		metadataCapability,
		flowsemantic.CapabilityName,
	})
}

func (c *RuntimePlatformClient) authorizedAttemptForCapabilities(ctx context.Context, bearer string, capabilities []string) (context.Context, context.CancelFunc, error) {
	if c == nil || c.identity == nil {
		return nil, func() {}, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	if delegation, ok := outgoingRuntimeDelegation(ctx, c.identityCoordinator, c.appInstallationID); ok {
		dataCtx, cancelData, err := c.workloadAttempt(ctx)
		if err != nil {
			return nil, func() {}, err
		}
		return withRuntimeDelegation(dataCtx, delegation), cancelData, nil
	}
	identityCtx, cancelIdentity, err := c.workloadAttempt(ctx)
	if err != nil {
		return nil, func() {}, err
	}
	request := identitysemantic.Request{
		AppInstallationID: c.appInstallationID, RequestedCapabilities: capabilities,
	}
	delegation, err := c.identityCoordinator.exchange(identityCtx, bearer, request, c.identity.Exchange)
	cancelIdentity()
	if err != nil {
		return nil, func() {}, err
	}
	dataCtx, cancelData, err := c.workloadAttempt(ctx)
	if err != nil {
		return nil, func() {}, err
	}
	return withRuntimeDelegation(dataCtx, delegation.OpaqueDelegation), cancelData, nil
}

// AuthorizeCapabilities exchanges the end-user credential once for one
// request-scoped L1 composition. The returned context carries only the opaque
// Runtime delegation; every composed Runtime method still performs its normal
// capability, SecurityEpoch, AuthEpoch and PermissionFloor admission. Callers
// must not retain the context beyond the owning request.
func (c *RuntimePlatformClient) AuthorizeCapabilities(
	ctx context.Context,
	bearer string,
	capabilities []string,
) (context.Context, error) {
	if c == nil || c.identity == nil {
		return nil, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	identityCtx, cancelIdentity, err := c.workloadAttempt(ctx)
	if err != nil {
		return nil, err
	}
	request := identitysemantic.Request{
		AppInstallationID:     c.appInstallationID,
		RequestedCapabilities: append([]string(nil), capabilities...),
	}
	delegation, err := c.identityCoordinator.exchange(identityCtx, bearer, request, c.identity.Exchange)
	cancelIdentity()
	if err != nil {
		return nil, err
	}
	return withRequestScopedRuntimeDelegation(
		ctx, delegation.OpaqueDelegation, c.identityCoordinator, c.appInstallationID,
	), nil
}

func (c *RuntimePlatformClient) workloadAttempt(ctx context.Context) (context.Context, context.CancelFunc, error) {
	if c == nil || c.connection == nil {
		return nil, func() {}, &commonsemantic.Failure{Category: commonsemantic.FailureUnavailable}
	}
	if ctx == nil {
		return nil, func() {}, &commonsemantic.Failure{
			Category: commonsemantic.FailureInvalidRequest, InvalidComponent: commonsemantic.InvalidComponentDeadline,
		}
	}
	callCtx, cancel := context.WithTimeout(ctx, c.attemptTimeout)
	return callCtx, cancel, nil
}

func (c *RuntimePlatformClient) dataContext(ctx context.Context, capability string) context.Context {
	return withClientProtocol(
		withWorkloadAuthorization(ctx, c.workloadToken),
		commonsemantic.ProtocolMajor,
		commonsemantic.ProtocolMinor,
		capability,
	)
}

func (c *RuntimePlatformClient) workloadDataContext(ctx context.Context, capability string) context.Context {
	return c.dataContext(withoutOutgoingRuntimeDelegation(withoutOutgoingEndUserAuthorization(ctx)), capability)
}

func withoutOutgoingRuntimeDelegation(ctx context.Context) context.Context {
	values, _ := metadata.FromOutgoingContext(ctx)
	values = values.Copy()
	values.Delete(envelope.RuntimeDelegationMetadataKey)
	return metadata.NewOutgoingContext(ctx, values)
}

func outgoingRuntimeDelegation(
	ctx context.Context,
	coordinator *identityExchangeCoordinator,
	appInstallationID string,
) (string, bool) {
	if ctx == nil {
		return "", false
	}
	authority, ok := ctx.Value(runtimeRequestAuthorityContextKey{}).(runtimeRequestAuthority)
	if !ok || authority.coordinator == nil || authority.coordinator != coordinator ||
		authority.appInstallationID == "" || authority.appInstallationID != appInstallationID {
		return "", false
	}
	values, ok := metadata.FromOutgoingContext(ctx)
	if !ok {
		return "", false
	}
	delegations := values.Get(envelope.RuntimeDelegationMetadataKey)
	if len(delegations) != 1 || delegations[0] == "" ||
		strings.TrimSpace(delegations[0]) != delegations[0] ||
		len(delegations[0]) > envelope.MaxRequestWireBytes {
		return "", false
	}
	return delegations[0], true
}

type runtimeRequestAuthorityContextKey struct{}

type runtimeRequestAuthority struct {
	coordinator       *identityExchangeCoordinator
	appInstallationID string
}

func withRequestScopedRuntimeDelegation(
	ctx context.Context,
	delegation string,
	coordinator *identityExchangeCoordinator,
	appInstallationID string,
) context.Context {
	return context.WithValue(
		withRuntimeDelegation(ctx, delegation),
		runtimeRequestAuthorityContextKey{},
		runtimeRequestAuthority{
			coordinator: coordinator, appInstallationID: appInstallationID,
		},
	)
}

func withoutOutgoingEndUserAuthorization(ctx context.Context) context.Context {
	values, _ := metadata.FromOutgoingContext(ctx)
	values = values.Copy()
	for _, key := range sessionSensitiveMetadataKeys() {
		values.Delete(key)
	}
	return metadata.NewOutgoingContext(ctx, values)
}

func platformCallOptions() []grpc.CallOption {
	return []grpc.CallOption{
		grpc.MaxCallSendMsgSize(envelope.MaxRequestWireBytes),
		grpc.MaxCallRecvMsgSize(envelope.MaxResponseWireBytes),
		grpc.WaitForReady(false),
	}
}

func (c *RuntimePlatformClient) Ready() bool {
	return c != nil && runtimeConnectionReady(c.connection)
}

func (c *RuntimePlatformClient) Close() error {
	if c == nil || c.connection == nil {
		return nil
	}
	return c.connection.Close()
}

// gRPC Send reports EOF for a server rejection; its typed status is available
// only on receive. Read that terminal status before cancelling the upload so
// callers and the identity cache both observe the actual rejection.
func uploadSendFailure[T any](sendErr error, closeAndRecv func() (*T, error)) error {
	if errors.Is(sendErr, io.EOF) {
		if _, terminalErr := closeAndRecv(); terminalErr != nil {
			return terminalErr
		}
	}
	return sendErr
}
